fix: fix merge conflicts
This commit is contained in:
commit
03b9b46ebd
114 files changed
+11408
-2996
No files matched your search
+52
-23
@@ -13,6 +13,7 @@ import uuid
|
||||
from flask import Flask, jsonify, request, g
|
||||
from flask_cors import CORS
|
||||
from werkzeug.exceptions import HTTPException
|
||||
from sqlalchemy import inspect as sqlalchemy_inspect
|
||||
|
||||
from app.core.config.settings import config
|
||||
from app.core.errors import AppError
|
||||
@@ -22,6 +23,25 @@ from app.core.response import error_payload, utc_iso_now
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _is_database_table_ready(table_name: str) -> bool:
|
||||
"""判断启动期依赖的业务表是否已由 Alembic 创建。
|
||||
|
||||
[STEP 1] 使用独立连接查询表元数据,避免空库启动时触发 ORM 查询。
|
||||
[STEP 2] 表不存在或数据库暂不可用时返回 False,让迁移命令先完成结构初始化。
|
||||
|
||||
Args:
|
||||
table_name: 需要检查的 public schema 表名。
|
||||
|
||||
Returns:
|
||||
表存在且可被当前数据库连接访问时返回 True,否则返回 False。
|
||||
"""
|
||||
try:
|
||||
return bool(sqlalchemy_inspect(db.engine).has_table(table_name))
|
||||
except Exception as exc: # pragma: no cover - 启动容错
|
||||
logger.info('Skip startup table readiness check for %s: %s', table_name, exc)
|
||||
return False
|
||||
|
||||
|
||||
def _apply_persisted_settings(app: Flask) -> None:
|
||||
"""Pull the latest runtime-editable settings into ``app.config``.
|
||||
|
||||
@@ -64,29 +84,38 @@ def create_app(config_name='default'):
|
||||
load_handlers()
|
||||
from app.services.chat.intent_route_registry import ensure_intent_routes_loaded
|
||||
ensure_intent_routes_loaded()
|
||||
# 空库先迁移后建用户:启动补建 + User commit 钩子即时补建,消除无排程窗口
|
||||
try:
|
||||
from app.services.file_assets.cleanup_schedule import (
|
||||
ensure_default_file_asset_cleanup_schedule,
|
||||
register_file_asset_cleanup_schedule_hooks,
|
||||
)
|
||||
register_file_asset_cleanup_schedule_hooks()
|
||||
ensure_default_file_asset_cleanup_schedule()
|
||||
from app.services.shipping_notice.order_extraction_progress_cleanup_schedule import (
|
||||
ensure_default_order_extraction_progress_cleanup_schedule,
|
||||
)
|
||||
ensure_default_order_extraction_progress_cleanup_schedule()
|
||||
except Exception as exc: # pragma: no cover - 表未就绪时容忍
|
||||
logger.warning('Failed to ensure file-asset-cleanup schedule: %s', exc)
|
||||
try:
|
||||
from app.services.voucher_check.schedule_seed import (
|
||||
ensure_default_voucher_check_schedule,
|
||||
register_voucher_check_schedule_hooks,
|
||||
)
|
||||
register_voucher_check_schedule_hooks()
|
||||
ensure_default_voucher_check_schedule()
|
||||
except Exception as exc: # pragma: no cover - 表未就绪时容忍
|
||||
logger.warning('Failed to ensure accounting-voucher-check schedule: %s', exc)
|
||||
# 迁移命令也会创建 app;空库阶段不能执行依赖 schedule_tasks 的 ORM 初始化。
|
||||
# 迁移完成后正常启动时,此表存在,以下默认排程补建逻辑照常执行。
|
||||
if _is_database_table_ready('schedule_tasks'):
|
||||
try:
|
||||
from app.services.file_assets.cleanup_schedule import (
|
||||
ensure_default_file_asset_cleanup_schedule,
|
||||
register_file_asset_cleanup_schedule_hooks,
|
||||
)
|
||||
register_file_asset_cleanup_schedule_hooks()
|
||||
ensure_default_file_asset_cleanup_schedule()
|
||||
from app.services.shipping_notice.order_extraction_progress_cleanup_schedule import (
|
||||
ensure_default_order_extraction_progress_cleanup_schedule,
|
||||
)
|
||||
ensure_default_order_extraction_progress_cleanup_schedule()
|
||||
except Exception as exc: # pragma: no cover - 表未就绪时容忍
|
||||
logger.warning('Failed to ensure file-asset-cleanup schedule: %s', exc)
|
||||
try:
|
||||
from app.services.voucher_check.schedule_seed import (
|
||||
ensure_default_voucher_check_schedule,
|
||||
register_voucher_check_schedule_hooks,
|
||||
)
|
||||
register_voucher_check_schedule_hooks()
|
||||
ensure_default_voucher_check_schedule()
|
||||
except Exception as exc: # pragma: no cover - 表未就绪时容忍
|
||||
logger.warning('Failed to ensure accounting-voucher-check schedule: %s', exc)
|
||||
try:
|
||||
from app.services.contract_payment.schedule_seed import ensure_default_contract_payment_schedules
|
||||
ensure_default_contract_payment_schedules()
|
||||
except Exception as exc: # pragma: no cover - 表未就绪时容忍
|
||||
logger.warning('Failed to ensure contract-payment schedules: %s', exc)
|
||||
else:
|
||||
logger.info('Skip startup schedule seeding: schedule_tasks table is not ready')
|
||||
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
|
||||
FixedAssetsSnapshotService.start_worker(app)
|
||||
# AUTO_UPLOAD 显式开启时启动级校验货代上传 RPA(仅告警,不阻断启动)。
|
||||
|
||||
@@ -44,6 +44,7 @@ def register_blueprints(app: Flask) -> None:
|
||||
from app.api.tools import file_check_bp, maintenance_tool_bp, shipping_notice_bp, voucher_check_tools_bp
|
||||
from app.api.files import files_bp
|
||||
from app.api.procurement_contract_tools import procurement_contract_bp
|
||||
from app.api.contract_payment import contract_payment_bp
|
||||
|
||||
app.register_blueprint(chat_bp, url_prefix='/api/chat')
|
||||
app.register_blueprint(admin_bp, url_prefix='/api/admin')
|
||||
@@ -73,3 +74,4 @@ def register_blueprints(app: Flask) -> None:
|
||||
app.register_blueprint(training_admin_bp, url_prefix='/api/admin')
|
||||
app.register_blueprint(files_bp, url_prefix='/api/files')
|
||||
app.register_blueprint(procurement_contract_bp, url_prefix='/api/procurement-contract')
|
||||
app.register_blueprint(contract_payment_bp, url_prefix='/api/contract-payment')
|
||||
@@ -0,0 +1,438 @@
|
||||
"""
|
||||
backend/app/api/contract_payment.py
|
||||
|
||||
用途:采购合同付款预警 Agent 的合同台账、付款计划、待发送摘要和同步 API。
|
||||
依赖:JWT 当前用户、统一响应 envelope、ForbiddenError、contract_payment 服务和通用 Job 队列。
|
||||
逻辑:页面查询合同、节点与本周待发送摘要;同步和预警操作入队,避免请求线程执行外部系统和企微调用。
|
||||
合同序列化时对 parse_issues 去重,避免 MinerU 重复抽取把同一原因展示多遍。
|
||||
鉴权:所有接口要求已登录且具备 `contract_payment.access`(admin 默认开,可显式授予普通用户)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import Blueprint, g, request, send_file
|
||||
from io import BytesIO
|
||||
|
||||
from app import db
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import ForbiddenError, NotFoundError, UnauthorizedError, ValidationError
|
||||
from app.core.response import ok
|
||||
from app.jobs.queue import enqueue
|
||||
from app.jobs.types import JobType
|
||||
from app.models import (
|
||||
ContractPaymentAlert,
|
||||
ContractPaymentAlertBatch,
|
||||
ContractPaymentAttachment,
|
||||
ContractPaymentContract,
|
||||
ContractPaymentNode,
|
||||
FileAsset,
|
||||
)
|
||||
from app.services.contract_payment.alert_service import build_weekly_alert_summary
|
||||
from app.services.contract_payment.parse_service import unique_parse_issues
|
||||
from app.services.contract_payment.sync_service import build_payment_plan, build_payment_plan_from_bytes
|
||||
from app.services.file_assets.service import read_asset_bytes
|
||||
|
||||
|
||||
contract_payment_bp = Blueprint("contract_payment", __name__)
|
||||
|
||||
|
||||
def _attachment_parse_priority(attachment: ContractPaymentAttachment) -> tuple[int, int]:
|
||||
"""
|
||||
为人工重解析选择权威合同原文附件。
|
||||
|
||||
核心逻辑:与 OA 同步保持一致,优先使用字段语义标注为“盖章完成合同上传”的附件;
|
||||
只有该附件不可用时才回退已归档的其他附件,避免方案或清单抢占合同正文。
|
||||
Args:
|
||||
attachment: 当前合同的已归档附件记录。
|
||||
Returns:
|
||||
越小越优先的排序键。
|
||||
"""
|
||||
label = str((attachment.metadata_json or {}).get("label") or "").strip()
|
||||
return (0 if label == "盖章完成合同上传" else 1, attachment.id)
|
||||
|
||||
|
||||
def _require_user():
|
||||
"""
|
||||
返回当前登录用户。
|
||||
|
||||
Args:
|
||||
无。当前请求身份由 JWT 上下文提供。
|
||||
Returns:
|
||||
已认证用户。
|
||||
Raises:
|
||||
UnauthorizedError: 请求没有有效登录身份。
|
||||
"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
|
||||
def _require_contract_payment_access():
|
||||
"""
|
||||
确保当前用户已登录且具备合同付款预警访问权限。
|
||||
|
||||
核心逻辑:登录校验之后读取 `contract_payment.access`;admin 角色默认具备,
|
||||
其他角色需在用户管理中显式授予。无权限时返回业务 403,而不是静默空数据。
|
||||
|
||||
Args:
|
||||
无。当前请求身份由 JWT 上下文提供。
|
||||
Returns:
|
||||
已认证且具备合同付款预警访问权限的用户。
|
||||
Raises:
|
||||
UnauthorizedError: 请求没有有效登录身份。
|
||||
ForbiddenError: 已登录但没有 `contract_payment.access`。
|
||||
"""
|
||||
user = _require_user()
|
||||
if not user.can_access_contract_payment():
|
||||
raise ForbiddenError(
|
||||
'Contract payment access required',
|
||||
code='CONTRACT_PAYMENT.FORBIDDEN',
|
||||
)
|
||||
return user
|
||||
|
||||
|
||||
def _serialize_contract(row: ContractPaymentContract) -> dict:
|
||||
"""
|
||||
序列化合同台账、付款节点及预警记录,供列表和详情共用。
|
||||
|
||||
Args:
|
||||
row: 已查询的合同主记录。
|
||||
Returns:
|
||||
不含附件原文和敏感 OA 配置的 API 数据结构。
|
||||
"""
|
||||
nodes = db.session.query(ContractPaymentNode).filter_by(contract_id=row.id).order_by(ContractPaymentNode.due_date.asc()).all()
|
||||
attachments = db.session.query(ContractPaymentAttachment).filter_by(contract_id=row.id).order_by(ContractPaymentAttachment.created_record_at.asc()).all()
|
||||
alerts = db.session.query(ContractPaymentAlert).filter_by(contract_id=row.id).order_by(ContractPaymentAlert.scheduled_at.asc()).all()
|
||||
return {
|
||||
"id": row.id,
|
||||
"contract_no": row.contract_no,
|
||||
"workflow_no": row.workflow_no,
|
||||
"purchase_order_no": row.purchase_order_no,
|
||||
"supplier_name": row.supplier_name,
|
||||
"total_amount": str(row.total_amount) if row.total_amount is not None else None,
|
||||
"currency": row.currency,
|
||||
"effective_date": row.effective_date.isoformat() if row.effective_date else None,
|
||||
"delivery_due_date": row.delivery_due_date.isoformat() if row.delivery_due_date else None,
|
||||
"oa_record_id": row.oa_record_id,
|
||||
"oa_archive_at": row.oa_archive_at.isoformat() if row.oa_archive_at else None,
|
||||
"status": row.status,
|
||||
"applicant_name": row.applicant_name,
|
||||
"parse_status": row.parse_status,
|
||||
"plan_status": row.plan_status,
|
||||
# 解析器在 needs_review 时写入的待确认问题(如“合同金额无法识别”),供人工复核定位。
|
||||
# 已落库的 issues 可能因正文重复抽取而含相同文案,展示前按出现顺序去重。
|
||||
"parse_issues": unique_parse_issues((row.parse_result_json or {}).get("issues")),
|
||||
# 本次解析使用的正文抽取器:mineru / native_text / legacy_ocr,便于判断是否走了 OCR。
|
||||
"parse_extractor": ((row.parse_result_json or {}).get("evidence") or {}).get("document_extractor"),
|
||||
"attachments": [{
|
||||
"id": attachment.id,
|
||||
"source": attachment.source,
|
||||
"file_name": attachment.file_name,
|
||||
"mime_type": attachment.mime_type,
|
||||
"file_asset_id": attachment.file_asset_id,
|
||||
"asset_no": (
|
||||
db.session.get(FileAsset, attachment.file_asset_id).asset_no
|
||||
if attachment.file_asset_id and db.session.get(FileAsset, attachment.file_asset_id)
|
||||
else None
|
||||
),
|
||||
"dms_path": attachment.dms_path,
|
||||
"created_at": attachment.created_at.isoformat() if attachment.created_at else None,
|
||||
"status": attachment.status,
|
||||
} for attachment in attachments],
|
||||
"nodes": [{
|
||||
"id": node.id,
|
||||
"node_code": node.node_code,
|
||||
"node_type": node.node_type,
|
||||
"amount": str(node.amount) if node.amount is not None else None,
|
||||
"percentage": str(node.percentage) if node.percentage is not None else None,
|
||||
"anchor_type": node.anchor_type,
|
||||
"anchor_date": node.anchor_date.isoformat() if node.anchor_date else None,
|
||||
"due_date": node.due_date.isoformat() if node.due_date else None,
|
||||
# ERP apa_file 付款日期;已付款时展示,未付为空。
|
||||
"paid_at": (node.evidence_json or {}).get("paid_at"),
|
||||
"status": node.status,
|
||||
} for node in nodes],
|
||||
"alerts": [{
|
||||
"id": alert.id,
|
||||
"node_id": alert.node_id,
|
||||
"alert_round": alert.alert_round,
|
||||
"scheduled_at": alert.scheduled_at.isoformat() if alert.scheduled_at else None,
|
||||
"sent_at": alert.sent_at.isoformat() if alert.sent_at else None,
|
||||
"recipient_user_id": alert.recipient_user_id,
|
||||
"status": alert.status,
|
||||
} for alert in alerts],
|
||||
}
|
||||
|
||||
|
||||
@contract_payment_bp.route("/contracts", methods=["GET"])
|
||||
def list_contracts():
|
||||
"""
|
||||
查询合同台账。
|
||||
|
||||
核心逻辑:支持合同编号、流程编号、采购单号和解析状态筛选,并按 offset 分页返回台账,避免工作台一次加载全部合同。
|
||||
Args:
|
||||
无。筛选条件从 query string 读取。
|
||||
Returns:
|
||||
标准成功 envelope,data 包含 total、page、page_size、pages 和 items。
|
||||
"""
|
||||
_require_contract_payment_access()
|
||||
query = db.session.query(ContractPaymentContract)
|
||||
keyword = str(request.args.get("keyword") or "").strip()
|
||||
if keyword:
|
||||
like = f"%{keyword}%"
|
||||
query = query.filter(
|
||||
ContractPaymentContract.contract_no.ilike(like)
|
||||
| ContractPaymentContract.workflow_no.ilike(like)
|
||||
| ContractPaymentContract.purchase_order_no.ilike(like)
|
||||
)
|
||||
parse_status = str(request.args.get("parse_status") or "").strip()
|
||||
review_only = str(request.args.get("review_only") or "").strip().lower() in {"1", "true", "yes"}
|
||||
if review_only:
|
||||
query = query.filter_by(parse_status="needs_review")
|
||||
elif parse_status:
|
||||
query = query.filter_by(parse_status=parse_status)
|
||||
else:
|
||||
# 自动付款预警台账仅展示关键解析事实完整的合同;待确认合同由独立导航集中处理。
|
||||
query = query.filter_by(parse_status="parsed")
|
||||
page = max(_query_int("page", default=1), 1)
|
||||
page_size = min(max(_query_int("page_size", default=20), 1), 100)
|
||||
total = query.count()
|
||||
pages = max((total + page_size - 1) // page_size, 1)
|
||||
page = min(page, pages)
|
||||
rows = (
|
||||
query.order_by(ContractPaymentContract.oa_archive_at.desc(), ContractPaymentContract.id.desc())
|
||||
.offset((page - 1) * page_size)
|
||||
.limit(page_size)
|
||||
.all()
|
||||
)
|
||||
return ok({
|
||||
"total": total,
|
||||
"page": page,
|
||||
"page_size": page_size,
|
||||
"pages": pages,
|
||||
"items": [_serialize_contract(row) for row in rows],
|
||||
}, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
def _query_int(key: str, *, default: int) -> int:
|
||||
"""读取正整数查询参数;非法值回退默认值,防止分页接口返回 500。"""
|
||||
try:
|
||||
return int(str(request.args.get(key) or default))
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
|
||||
|
||||
@contract_payment_bp.route("/contracts/<int:contract_id>", methods=["GET"])
|
||||
def get_contract(contract_id: int):
|
||||
"""
|
||||
查看单份合同详情和付款计划。
|
||||
|
||||
Args:
|
||||
contract_id: 合同台账主键。
|
||||
Returns:
|
||||
标准成功 envelope。
|
||||
Raises:
|
||||
NotFoundError: 合同不存在。
|
||||
"""
|
||||
_require_contract_payment_access()
|
||||
row = db.session.get(ContractPaymentContract, contract_id)
|
||||
if not row:
|
||||
raise NotFoundError("合同不存在")
|
||||
return ok(_serialize_contract(row), request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@contract_payment_bp.route("/contracts/<int:contract_id>/attachments/<int:attachment_id>/download", methods=["GET"])
|
||||
def download_contract_attachment(contract_id: int, attachment_id: int):
|
||||
"""
|
||||
下载合同详情中已归档的原文附件。
|
||||
|
||||
核心逻辑:附件必须同时属于请求中的合同和本地 FileAsset,避免通过附件 ID 越权读取其他合同原文。
|
||||
|
||||
Args:
|
||||
contract_id: 合同台账主键。
|
||||
attachment_id: 合同附件主键。
|
||||
|
||||
Returns:
|
||||
受控下载的附件二进制流。
|
||||
|
||||
Raises:
|
||||
NotFoundError: 合同、附件或其保存的文件资产不存在。
|
||||
"""
|
||||
_require_contract_payment_access()
|
||||
attachment = db.session.query(ContractPaymentAttachment).filter_by(id=attachment_id, contract_id=contract_id).first()
|
||||
if not attachment or not attachment.file_asset_id:
|
||||
raise NotFoundError("合同原文附件不存在")
|
||||
asset = db.session.get(FileAsset, attachment.file_asset_id)
|
||||
if not asset:
|
||||
raise NotFoundError("合同原文附件不存在")
|
||||
return send_file(
|
||||
BytesIO(read_asset_bytes(asset)),
|
||||
mimetype=attachment.mime_type or asset.mime_type or "application/octet-stream",
|
||||
as_attachment=True,
|
||||
download_name=attachment.file_name or asset.original_filename,
|
||||
)
|
||||
|
||||
|
||||
@contract_payment_bp.route("/sync", methods=["POST"])
|
||||
def enqueue_sync():
|
||||
"""
|
||||
将 OA 合同、验收和厂商预付款请款同步任务入队。
|
||||
|
||||
Args:
|
||||
无。操作用户由 JWT 上下文读取。
|
||||
Returns:
|
||||
HTTP 202 与后台 Job ID。
|
||||
"""
|
||||
user = _require_contract_payment_access()
|
||||
data = request.get_json(silent=True) or {}
|
||||
force_value = data.get("force", False)
|
||||
if not isinstance(force_value, bool):
|
||||
raise ValidationError("force 必须是布尔值")
|
||||
force = force_value
|
||||
reparse_existing = data.get("reparse_existing", False)
|
||||
if not isinstance(reparse_existing, bool):
|
||||
raise ValidationError("reparse_existing 必须是布尔值")
|
||||
payload = {"force": force, "operator_id": user.id if force else None, "reparse_existing": reparse_existing}
|
||||
job_id = enqueue(JobType.CONTRACT_PAYMENT_SYNC, payload, domain="procurement_contract", business_ref="contract-payment-reparse-existing" if reparse_existing else "contract-payment-force-sync" if force else "contract-payment-sync", created_by_id=user.id, message="等待批量重新解析存量合同" if reparse_existing else "等待强制覆盖 OA 字段并同步合同" if force else "等待同步 OA 合同归档通知")
|
||||
return ok({"job_id": job_id}, request_id=getattr(g, "request_id", None), status=202)
|
||||
|
||||
|
||||
@contract_payment_bp.route("/alerts/run", methods=["POST"])
|
||||
def enqueue_alert_scan():
|
||||
"""
|
||||
将四阶段三轮合同付款预警扫描任务入队。
|
||||
|
||||
Args:
|
||||
无。操作用户由 JWT 上下文读取。
|
||||
Returns:
|
||||
HTTP 202 与后台 Job ID。
|
||||
"""
|
||||
user = _require_contract_payment_access()
|
||||
job_id = enqueue(JobType.CONTRACT_PAYMENT_ALERT, {}, domain="procurement_contract", business_ref="daily-alert", created_by_id=user.id, message="等待计算合同付款预警")
|
||||
return ok({"job_id": job_id}, request_id=getattr(g, "request_id", None), status=202)
|
||||
|
||||
|
||||
@contract_payment_bp.route("/alerts/summary", methods=["GET"])
|
||||
def get_alert_summary():
|
||||
"""查询本周待发送预警笔数和下一次周五 18:00 发送时间。
|
||||
|
||||
核心逻辑:委托 alert_service.build_weekly_alert_summary,与周五汇总发送使用同一 pending 过滤。
|
||||
Args:
|
||||
无。当前请求身份由 JWT 上下文提供。
|
||||
Returns:
|
||||
标准成功 envelope,含 pending_count、next_send_at、timezone。
|
||||
"""
|
||||
_require_contract_payment_access()
|
||||
return ok(build_weekly_alert_summary(), request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@contract_payment_bp.route("/alerts/weekly-run", methods=["POST"])
|
||||
def enqueue_weekly_alert_send():
|
||||
"""将合同付款预警周汇总发送任务入队。
|
||||
|
||||
Args:
|
||||
无。操作用户由 JWT 上下文读取。
|
||||
Returns:
|
||||
HTTP 202 与后台 Job ID。
|
||||
"""
|
||||
user = _require_contract_payment_access()
|
||||
job_id = enqueue(
|
||||
JobType.CONTRACT_PAYMENT_ALERT_WEEKLY,
|
||||
{},
|
||||
domain="procurement_contract",
|
||||
business_ref="weekly-alert",
|
||||
created_by_id=user.id,
|
||||
message="等待发送合同付款预警周汇总",
|
||||
)
|
||||
return ok({"job_id": job_id}, request_id=getattr(g, "request_id", None), status=202)
|
||||
|
||||
|
||||
@contract_payment_bp.route("/alert-batches", methods=["GET"])
|
||||
def list_alert_batches():
|
||||
"""查询近期合同付款预警周汇总批次。"""
|
||||
_require_contract_payment_access()
|
||||
rows = db.session.query(ContractPaymentAlertBatch).order_by(ContractPaymentAlertBatch.created_at.desc()).limit(100).all()
|
||||
return ok({"items": [{
|
||||
"id": row.id, "batch_no": row.batch_no, "week_key": row.week_key,
|
||||
"recipient_user_id": row.recipient_user_id, "status": row.status,
|
||||
"summary": row.summary_json, "excel_file_name": row.excel_file_name,
|
||||
"excel_file_size": row.excel_file_size, "sent_at": row.sent_at.isoformat() if row.sent_at else None,
|
||||
"created_at": row.created_at.isoformat(),
|
||||
} for row in rows]}, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@contract_payment_bp.route("/alert-batches/<int:batch_id>/excel", methods=["GET"])
|
||||
def download_alert_batch_excel(batch_id: int):
|
||||
"""下载已归档的合同付款预警 Excel 明细附件。"""
|
||||
_require_contract_payment_access()
|
||||
row = db.session.get(ContractPaymentAlertBatch, batch_id)
|
||||
if not row or not row.excel_file_data:
|
||||
raise NotFoundError("付款预警附件不存在")
|
||||
return send_file(
|
||||
BytesIO(row.excel_file_data),
|
||||
as_attachment=True,
|
||||
download_name=row.excel_file_name or f"contract-payment-alert-{batch_id}.xlsx",
|
||||
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
)
|
||||
|
||||
|
||||
@contract_payment_bp.route("/contracts/<int:contract_id>/parse", methods=["POST"])
|
||||
def parse_contract(contract_id: int):
|
||||
"""
|
||||
使用调用方提供的已抽取合同正文生成付款计划。
|
||||
|
||||
Args:
|
||||
contract_id: 合同台账主键。
|
||||
Returns:
|
||||
解析结果和更新后的合同详情。
|
||||
Raises:
|
||||
NotFoundError: 合同不存在。
|
||||
"""
|
||||
_require_contract_payment_access()
|
||||
row = db.session.get(ContractPaymentContract, contract_id)
|
||||
if not row:
|
||||
raise NotFoundError("合同不存在")
|
||||
data = request.get_json() or {}
|
||||
result = build_payment_plan(row, text=str(data.get("text") or ""))
|
||||
return ok({"contract": _serialize_contract(row), "parse_result": result}, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@contract_payment_bp.route("/contracts/<int:contract_id>/reparse", methods=["POST"])
|
||||
def reparse_contract_attachment(contract_id: int):
|
||||
"""
|
||||
使用已归档的合同原文附件重新生成付款解析结果。
|
||||
|
||||
核心逻辑:管理员在待确认合同中发现旧规则或附件抽取异常时触发;服务端只读取该合同
|
||||
已保存的附件,优先盖章完成合同上传,覆盖付款节点、解析状态和问题列表,不调用 OA。
|
||||
Args:
|
||||
contract_id: 合同付款台账主键。
|
||||
Returns:
|
||||
标准成功 envelope,含更新后的合同详情、解析结果及实际使用的附件名称。
|
||||
Raises:
|
||||
NotFoundError: 合同不存在。
|
||||
ValidationError: 没有可用于重解析的已归档合同附件。
|
||||
"""
|
||||
_require_contract_payment_access()
|
||||
row = db.session.get(ContractPaymentContract, contract_id)
|
||||
if not row:
|
||||
raise NotFoundError("合同不存在")
|
||||
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:
|
||||
raise ValidationError("当前合同没有已归档的原文附件,无法重新解析", code="CONTRACT_PAYMENT.ATTACHMENT_REQUIRED")
|
||||
# [STEP 1] 使用同步链路同一附件优先级,保证人工重跑与首次解析的结果可复现。
|
||||
attachment = min(attachments, key=_attachment_parse_priority)
|
||||
asset = db.session.get(FileAsset, attachment.file_asset_id)
|
||||
if not asset:
|
||||
raise ValidationError("当前合同原文附件不存在,无法重新解析", code="CONTRACT_PAYMENT.ATTACHMENT_REQUIRED")
|
||||
result = build_payment_plan_from_bytes(row, filename=attachment.file_name, data=read_asset_bytes(asset))
|
||||
return ok({
|
||||
"contract": _serialize_contract(row),
|
||||
"parse_result": result,
|
||||
"attachment_name": attachment.file_name,
|
||||
}, request_id=getattr(g, "request_id", None))
|
||||
@@ -4,7 +4,8 @@ backend/app/core/config/settings.py
|
||||
用途:Flask Config 类与环境文件加载(dev/test/prod)。
|
||||
依赖:dotenv、app.path_utils。
|
||||
逻辑:create_app 通过 config[config_name] 加载;含发货通知开关
|
||||
(如 SHIPPING_NOTICE_LINE_AUTO_FULFILL_ENABLED);旧路径 app.config 为兼容 shim。
|
||||
(如 SHIPPING_NOTICE_LINE_AUTO_FULFILL_ENABLED)与合同付款 OA 表名配置;
|
||||
旧路径 app.config 为兼容 shim。
|
||||
"""
|
||||
import os
|
||||
import warnings
|
||||
@@ -211,6 +212,22 @@ class Config:
|
||||
PROCUREMENT_CONTRACT_ARCHIVE_CLEANUP_LOCAL = (
|
||||
os.getenv('PROCUREMENT_CONTRACT_ARCHIVE_CLEANUP_LOCAL', 'true').lower() == 'true'
|
||||
)
|
||||
# 合同付款预警 ERP 只读查询:apa_file 的合格付款记录作为预付款/出货款已付款事实。
|
||||
# 统一改用通用 ERP 连接变量(ERP_DB_DSN / ERP_USERNAME / ERP_PASSWORD / ERP_TIMEOUT_SECONDS,已并入 env.shared),
|
||||
# 并保留模块级 CONTRACT_PAYMENT_ERP_* 覆盖与旧回退(VOUCHER_CHECK_ERP_*)兼容。
|
||||
CONTRACT_PAYMENT_ERP_DSN = os.getenv('CONTRACT_PAYMENT_ERP_DSN') or os.getenv('ERP_DB_DSN', '')
|
||||
CONTRACT_PAYMENT_ERP_USERNAME = os.getenv('CONTRACT_PAYMENT_ERP_USERNAME') or os.getenv('ERP_USERNAME') or os.getenv('VOUCHER_CHECK_ERP_USERNAME', '')
|
||||
CONTRACT_PAYMENT_ERP_PASSWORD = os.getenv('CONTRACT_PAYMENT_ERP_PASSWORD') or os.getenv('ERP_PASSWORD') or os.getenv('VOUCHER_CHECK_ERP_PASSWORD', '')
|
||||
CONTRACT_PAYMENT_ERP_TIMEOUT_SECONDS = int(os.getenv('CONTRACT_PAYMENT_ERP_TIMEOUT_SECONDS') or os.getenv('ERP_TIMEOUT_SECONDS', '30') or '30')
|
||||
CONTRACT_DMS_BASE_URL = os.getenv('CONTRACT_DMS_BASE_URL', '').strip().rstrip('/')
|
||||
CONTRACT_DMS_USERNAME = os.getenv('CONTRACT_DMS_USERNAME', '')
|
||||
CONTRACT_DMS_PASSWORD = os.getenv('CONTRACT_DMS_PASSWORD', '')
|
||||
CONTRACT_DMS_LIBRARY_ID = os.getenv('CONTRACT_DMS_LIBRARY_ID', '')
|
||||
CONTRACT_DMS_ROOT_FOLDER_ID = os.getenv('CONTRACT_DMS_ROOT_FOLDER_ID', '')
|
||||
CONTRACT_DMS_2026_FOLDER_ID = os.getenv('CONTRACT_DMS_2026_FOLDER_ID', '')
|
||||
CONTRACT_DMS_YEAR_FOLDER_NAME_TEMPLATE = os.getenv('CONTRACT_DMS_YEAR_FOLDER_NAME_TEMPLATE', '{year}年设备合同书')
|
||||
CONTRACT_DMS_TEMP_FOLDER_NAME = os.getenv('CONTRACT_DMS_TEMP_FOLDER_NAME', '暂存')
|
||||
CONTRACT_DMS_LOOKUP_WINDOW_DAYS = int(os.getenv('CONTRACT_DMS_LOOKUP_WINDOW_DAYS', '30') or '30')
|
||||
# Redis 连接配置,默认使用本地 Redis + 密码
|
||||
REDIS_URL = os.getenv('REDIS_URL')
|
||||
# 订单文档模板预览默认要求 Redis;仅开发单进程 run.py 可显式放开进程内一次性令牌兜底。
|
||||
@@ -227,6 +244,58 @@ class Config:
|
||||
)
|
||||
OA_LEAVE_WORKFLOW_CODE = os.getenv('OA_LEAVE_WORKFLOW_CODE', '879')
|
||||
|
||||
# 合同付款预警:OA/收件人/排程只在此处声明一份,禁止再写第二份以免改错副本。
|
||||
# 外部 OA 地址与账户由环境变量或 CI Secret 注入,禁止写入仓库。
|
||||
CONTRACT_PAYMENT_ENABLED = os.getenv('CONTRACT_PAYMENT_ENABLED', 'false').lower() == 'true'
|
||||
CONTRACT_PAYMENT_OA_BASE_URL = os.getenv('CONTRACT_PAYMENT_OA_BASE_URL', '').strip().rstrip('/')
|
||||
CONTRACT_PAYMENT_OA_USERNAME = os.getenv('CONTRACT_PAYMENT_OA_USERNAME', '').strip()
|
||||
CONTRACT_PAYMENT_OA_PASSWORD = os.getenv('CONTRACT_PAYMENT_OA_PASSWORD', '')
|
||||
CONTRACT_PAYMENT_OA_TIMEOUT_SECONDS = int(os.getenv('CONTRACT_PAYMENT_OA_TIMEOUT_SECONDS', '30') or '30')
|
||||
CONTRACT_PAYMENT_OA_LOGIN_PATH = os.getenv('CONTRACT_PAYMENT_OA_LOGIN_PATH', '/login/Login.jsp').strip()
|
||||
CONTRACT_PAYMENT_OA_LOGIN_USERNAME_FIELD = os.getenv('CONTRACT_PAYMENT_OA_LOGIN_USERNAME_FIELD', 'loginid').strip()
|
||||
CONTRACT_PAYMENT_OA_LOGIN_PASSWORD_FIELD = os.getenv('CONTRACT_PAYMENT_OA_LOGIN_PASSWORD_FIELD', 'userpassword').strip()
|
||||
CONTRACT_PAYMENT_OA_BELONGTO_USER_ID = os.getenv('CONTRACT_PAYMENT_OA_BELONGTO_USER_ID', '').strip()
|
||||
CONTRACT_PAYMENT_OA_TODO_LIST_URL = os.getenv('CONTRACT_PAYMENT_OA_TODO_LIST_URL', '').strip()
|
||||
CONTRACT_PAYMENT_OA_DONE_LIST_URL = os.getenv('CONTRACT_PAYMENT_OA_DONE_LIST_URL', '').strip()
|
||||
CONTRACT_PAYMENT_OA_VENDOR_PREPAYMENT_LIST_URL = os.getenv(
|
||||
'CONTRACT_PAYMENT_OA_VENDOR_PREPAYMENT_LIST_URL', ''
|
||||
).strip()
|
||||
CONTRACT_PAYMENT_OA_ATTACHMENT_URL_TEMPLATE = os.getenv('CONTRACT_PAYMENT_OA_ATTACHMENT_URL_TEMPLATE', '').strip()
|
||||
CONTRACT_PAYMENT_OA_ATTACHMENT_MAX_BYTES = int(os.getenv('CONTRACT_PAYMENT_OA_ATTACHMENT_MAX_BYTES', str(30 * 1024 * 1024)) or str(30 * 1024 * 1024))
|
||||
# OA 增量同步:以 last_successful_sync_at 为游标;overlap 兜住迟到/越序记录。
|
||||
# MAX_PAGES=0 表示翻到短页为止(首次全量忽略此上限);>0 仅约束增量窗口,触顶则不推进断点。
|
||||
CONTRACT_PAYMENT_OA_SYNC_OVERLAP_SECONDS = int(os.getenv('CONTRACT_PAYMENT_OA_SYNC_OVERLAP_SECONDS', '3600') or '3600')
|
||||
CONTRACT_PAYMENT_OA_SYNC_MAX_PAGES = int(os.getenv('CONTRACT_PAYMENT_OA_SYNC_MAX_PAGES', '0') or '0')
|
||||
CONTRACT_PAYMENT_OA_SYNC_PAGE_PARAM = os.getenv('CONTRACT_PAYMENT_OA_SYNC_PAGE_PARAM', 'pageIndex').strip()
|
||||
# 请求泛微 SplitPage 时的 pageSize。停翻以 OA 首页实际行数为准,不能把「首页 10 条 < 配置 20」当成已经到底。
|
||||
CONTRACT_PAYMENT_OA_SYNC_PAGE_SIZE = int(os.getenv('CONTRACT_PAYMENT_OA_SYNC_PAGE_SIZE', '20') or '20')
|
||||
# 资产验收单归档:OA SQL 表/字段。凭据复用 OA_SQLSERVER_*,不在此重复。
|
||||
# currentnodetype 为 char:0 创建 / 1 批准 / 2 提交 / 3 归档。
|
||||
# 归档日取 lastoperatedate(currentnodetype=3 时即为归档操作日)。
|
||||
CONTRACT_PAYMENT_OA_ACCEPTANCE_TABLE = os.getenv('CONTRACT_PAYMENT_OA_ACCEPTANCE_TABLE', 'formtable_main_324').strip()
|
||||
CONTRACT_PAYMENT_OA_ACCEPTANCE_PO_FIELD = os.getenv('CONTRACT_PAYMENT_OA_ACCEPTANCE_PO_FIELD', 'cgdh').strip()
|
||||
CONTRACT_PAYMENT_OA_ACCEPTANCE_REQUEST_ID_FIELD = os.getenv(
|
||||
'CONTRACT_PAYMENT_OA_ACCEPTANCE_REQUEST_ID_FIELD', 'requestId'
|
||||
).strip()
|
||||
CONTRACT_PAYMENT_OA_ACCEPTANCE_NODETYPE = os.getenv('CONTRACT_PAYMENT_OA_ACCEPTANCE_NODETYPE', '3').strip()
|
||||
# 第二、三轮上级:HrmResource.lastname=申请人 → departmentid=Matrixtable_3.bm;zz/jfl 即 OA 与企微 userid。
|
||||
CONTRACT_PAYMENT_OA_HRM_TABLE = os.getenv('CONTRACT_PAYMENT_OA_HRM_TABLE', 'HrmResource').strip()
|
||||
CONTRACT_PAYMENT_OA_HRM_NAME_FIELD = os.getenv('CONTRACT_PAYMENT_OA_HRM_NAME_FIELD', 'lastname').strip()
|
||||
CONTRACT_PAYMENT_OA_HRM_DEPT_FIELD = os.getenv('CONTRACT_PAYMENT_OA_HRM_DEPT_FIELD', 'departmentid').strip()
|
||||
CONTRACT_PAYMENT_OA_MATRIX_TABLE = os.getenv('CONTRACT_PAYMENT_OA_MATRIX_TABLE', 'Matrixtable_3').strip()
|
||||
CONTRACT_PAYMENT_OA_MATRIX_DEPT_FIELD = os.getenv('CONTRACT_PAYMENT_OA_MATRIX_DEPT_FIELD', 'bm').strip()
|
||||
CONTRACT_PAYMENT_OA_MATRIX_ROUND2_FIELD = os.getenv('CONTRACT_PAYMENT_OA_MATRIX_ROUND2_FIELD', 'zz').strip()
|
||||
CONTRACT_PAYMENT_OA_MATRIX_ROUND3_FIELD = os.getenv('CONTRACT_PAYMENT_OA_MATRIX_ROUND3_FIELD', 'jfl').strip()
|
||||
# 仅用于附件 FileAsset 所有者;第一轮预警收件人按申请人真实姓名匹配,不用此值兜底。
|
||||
CONTRACT_PAYMENT_DEFAULT_OWNER_USER_ID = os.getenv('CONTRACT_PAYMENT_DEFAULT_OWNER_USER_ID')
|
||||
CONTRACT_PAYMENT_JOB_TIMEOUT_SECONDS = float(os.getenv('CONTRACT_PAYMENT_JOB_TIMEOUT_SECONDS', '1800') or '1800')
|
||||
# 已废弃:第二、三轮改为 OA 矩阵,不再使用全局岗位用户 ID。
|
||||
CONTRACT_PAYMENT_DEPARTMENT_HEAD_USER_IDS = os.getenv('CONTRACT_PAYMENT_DEPARTMENT_HEAD_USER_IDS', '').strip()
|
||||
CONTRACT_PAYMENT_PROCUREMENT_LEADER_USER_IDS = os.getenv('CONTRACT_PAYMENT_PROCUREMENT_LEADER_USER_IDS', '').strip()
|
||||
# 每日扫描只落 pending,周五 18:00 由周汇总任务发送。
|
||||
CONTRACT_PAYMENT_ALERT_TIMEZONE = os.getenv('CONTRACT_PAYMENT_ALERT_TIMEZONE', 'Asia/Shanghai')
|
||||
CONTRACT_PAYMENT_ALERT_WEEKLY_CRON = os.getenv('CONTRACT_PAYMENT_ALERT_WEEKLY_CRON', '0 18 * * 5')
|
||||
|
||||
# External integration API (resolve original source file links by Dify IDs)
|
||||
INTEGRATION_API_MODE = os.getenv('INTEGRATION_API_MODE', 'local').strip().lower()
|
||||
INTEGRATION_API_BASE = os.getenv('INTEGRATION_API_BASE')
|
||||
@@ -461,7 +530,7 @@ class Config:
|
||||
WECOM_PUBLIC_BASE_URL = os.getenv('WECOM_PUBLIC_BASE_URL')
|
||||
WECOM_NOTIFY_ENABLED = os.getenv('WECOM_NOTIFY_ENABLED', 'true').lower() == 'true'
|
||||
WECOM_NOTIFY_BASE_URL = os.getenv('WECOM_NOTIFY_BASE_URL')
|
||||
WECOM_NOTIFY_EVENTS = os.getenv('WECOM_NOTIFY_EVENTS', 'task_completed,schedule_completed,password_reset')
|
||||
WECOM_NOTIFY_EVENTS = os.getenv('WECOM_NOTIFY_EVENTS', 'task_completed,schedule_completed,password_reset,contract_payment_warning')
|
||||
WECOM_FEEDBACK_NOTIFY_ENABLED = os.getenv('WECOM_FEEDBACK_NOTIFY_ENABLED', 'true').lower() == 'true'
|
||||
WECOM_FEEDBACK_NOTIFY_BASE_URL = os.getenv('WECOM_FEEDBACK_NOTIFY_BASE_URL')
|
||||
WECOM_FEEDBACK_BOT_WEBHOOK = os.getenv('WECOM_FEEDBACK_BOT_WEBHOOK')
|
||||
|
||||
@@ -6,6 +6,7 @@ backend/app/jobs/handlers/__init__.py
|
||||
"""
|
||||
|
||||
from app.jobs.handlers import ( # noqa: F401
|
||||
contract_payment,
|
||||
file_check_run,
|
||||
kb_clean,
|
||||
kb_dify_sync,
|
||||
@@ -23,4 +24,5 @@ from app.jobs.handlers import ( # noqa: F401
|
||||
shipping_review_revalidate_progress,
|
||||
shipping_pdf_automark,
|
||||
wecom_directory_sync,
|
||||
contract_payment,
|
||||
)
|
||||
@@ -0,0 +1,81 @@
|
||||
"""
|
||||
backend/app/jobs/handlers/contract_payment.py
|
||||
|
||||
用途:执行合同付款预警域后台任务。
|
||||
依赖:jobs.registry、contract_payment.sync_service、alert_service、jobs.queue.finish_job。
|
||||
逻辑:合同同步任务读取 OA 通知;每日任务只扫描并写入 pending,周任务按收件人汇总发送企微。
|
||||
本文件三个处理器均由 run_forever 轮询循环分发;该循环只在异常时写失败,成功必须由处理器显式
|
||||
调用 finish_job 收口为 success,否则 Job 会一直停在 running 并在超时回收后重复执行。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.queue import finish_job
|
||||
from app.jobs.registry import register_handler
|
||||
from app.jobs.types import JobType
|
||||
from app.services.contract_payment import alert_service, sync_service
|
||||
|
||||
|
||||
@register_handler(JobType.CONTRACT_PAYMENT_SYNC)
|
||||
def run_contract_payment_sync(ctx: JobContext, payload: dict) -> None:
|
||||
"""
|
||||
执行一次 OA 合同申请单 HTTP 同步与资产验收单 SQL 归档同步;付款完成状态由预警扫描查询 ERP。
|
||||
|
||||
Args:
|
||||
ctx: 后台任务上下文,用于结构化日志。
|
||||
payload: 入队载荷;`force=true` 时使用操作人 ID 强制覆盖 OA 非空字段;job_id 由通用队列注入。
|
||||
Returns:
|
||||
None;结果写入任务日志和业务表,并由 finish_job 收口 Job 为 success。
|
||||
"""
|
||||
job_id = int(payload.get("job_id") or 0)
|
||||
force = payload.get("force") is True
|
||||
if payload.get("reparse_existing") is True:
|
||||
result = sync_service.reparse_existing_contracts(limit=payload.get("limit") or 1000)
|
||||
else:
|
||||
result = sync_service.sync_notifications(force=force, operator_id=payload.get("operator_id") if force else None)
|
||||
ctx.logger.info(
|
||||
"contract payment sync result=%s oa_configured=%s oa_list_configured=%s",
|
||||
result,
|
||||
result.get("oa_configured"),
|
||||
result.get("oa_list_configured"),
|
||||
)
|
||||
# [STEP] 成功收口:run_forever 只在异常时写失败,成功必须由处理器显式 finish_job,
|
||||
# 否则 Job 停 在 running,会被超时回收重复执行。异常由 run_forever 走 mark_failed,不在此捕获。
|
||||
if job_id:
|
||||
finish_job(job_id, result=result, message="合同付款预警同步完成")
|
||||
|
||||
|
||||
@register_handler(JobType.CONTRACT_PAYMENT_ALERT)
|
||||
def run_contract_payment_alert(ctx: JobContext, payload: dict) -> None:
|
||||
"""
|
||||
执行一次四阶段三轮合同付款节点预警扫描。
|
||||
|
||||
Args:
|
||||
ctx: 后台任务上下文,用于结构化日志。
|
||||
payload: 入队载荷,当前无需业务参数;job_id 由通用队列注入。
|
||||
Returns:
|
||||
None;只写入 pending 预警审计表,不直接发送企微,并由 finish_job 收口 Job 为 success。
|
||||
"""
|
||||
job_id = int(payload.get("job_id") or 0)
|
||||
result = alert_service.generate_alerts()
|
||||
ctx.logger.info("contract payment alert result=%s", result)
|
||||
if job_id:
|
||||
finish_job(job_id, result=result, message="合同付款预警扫描完成")
|
||||
|
||||
|
||||
@register_handler(JobType.CONTRACT_PAYMENT_ALERT_WEEKLY)
|
||||
def run_contract_payment_alert_weekly(ctx: JobContext, payload: dict) -> None:
|
||||
"""执行周五合同付款预警汇总发送。
|
||||
|
||||
Args:
|
||||
ctx: 后台任务上下文,用于结构化日志。
|
||||
payload: 入队载荷,当前无需业务参数;job_id 由通用队列注入。
|
||||
Returns:
|
||||
None;企微汇总、Excel 附件和发送状态写入业务审计表,并由 finish_job 收口 Job 为 success。
|
||||
"""
|
||||
job_id = int(payload.get("job_id") or 0)
|
||||
result = alert_service.send_weekly_alerts()
|
||||
ctx.logger.info("contract payment weekly alert result=%s", result)
|
||||
if job_id:
|
||||
finish_job(job_id, result=result, message="合同付款预警周报完成")
|
||||
@@ -678,21 +678,36 @@ def recover_stale_jobs(
|
||||
)
|
||||
if on_recovered is not None:
|
||||
on_recovered(job)
|
||||
current_app.logger.warning(
|
||||
"合同任务超时回收 job_id=%s job_type=%s status=%s attempts=%s/%s timeout_seconds=%s message=%s",
|
||||
job.id, job.job_type, job.status, snap_attempts, max_attempts, int(timeout_seconds), job.message,
|
||||
)
|
||||
recovered += 1
|
||||
db.session.commit()
|
||||
if recovered:
|
||||
current_app.logger.warning("合同任务超时回收完成 domain=%s recovered=%d", domain, recovered)
|
||||
return recovered
|
||||
|
||||
|
||||
def claim_next_job(*, domain: str, job_types: list[str | JobType] | None = None, worker_id: str | None = None) -> Job | None:
|
||||
"""原子领取指定业务域下一条 queued 任务。"""
|
||||
def claim_next_job(*, domain: str | None, job_types: list[str | JobType] | None = None, worker_id: str | None = None) -> Job | None:
|
||||
"""
|
||||
原子领取指定业务域下一条 queued 任务。
|
||||
|
||||
核心逻辑:有 domain 时按业务域隔离;传入 None 时只按 job_types 领取,
|
||||
供共享的合同 worker 消费合同审查与合同付款预警子域。
|
||||
Args:
|
||||
domain: 业务域;None 表示不按域过滤。
|
||||
job_types: 可领取的任务类型。
|
||||
worker_id: 可选 worker 标识,用于领取审计。
|
||||
Returns:
|
||||
已置为 running 的任务;无可领取任务时返回 None。
|
||||
"""
|
||||
normalized_types = [_normalize_job_type(item) for item in (job_types or []) if _normalize_job_type(item)]
|
||||
now = datetime.utcnow()
|
||||
try:
|
||||
query = db.session.query(Job).filter(
|
||||
Job.domain == domain,
|
||||
Job.status == "queued",
|
||||
Job.created_at <= now,
|
||||
)
|
||||
query = db.session.query(Job).filter(Job.status == "queued", Job.created_at <= now)
|
||||
if domain is not None:
|
||||
query = query.filter(Job.domain == str(domain))
|
||||
if normalized_types:
|
||||
query = query.filter(Job.job_type.in_(normalized_types))
|
||||
job = (
|
||||
|
||||
@@ -56,7 +56,7 @@ def _normalize_kb_job(job: KbJob) -> dict[str, Any]:
|
||||
def claim_next(*, queues: list[str] | None = None) -> dict[str, Any] | None:
|
||||
"""
|
||||
认领下一条待执行 Job(SELECT FOR UPDATE SKIP LOCKED,委托各域 queue_service)。
|
||||
核心逻辑:按 queues 顺序依次尝试 kb / shipping 队列;先 recover 卡死 running 任务。
|
||||
核心逻辑:按 queues 顺序依次尝试 kb / shipping / contract 队列;先 recover 卡死 running 任务。
|
||||
Args:
|
||||
queues: worker 消费的队列名,如 ['kb'] 或 ['kb', 'shipping']。
|
||||
Returns:
|
||||
@@ -90,6 +90,25 @@ def claim_next(*, queues: list[str] | None = None) -> dict[str, Any] | None:
|
||||
job_type=JobType.PROCUREMENT_CONTRACT_REVIEW,
|
||||
on_recovered=sync_review_after_job_recovery,
|
||||
)
|
||||
contract_payment_types = (
|
||||
JobType.CONTRACT_PAYMENT_SYNC,
|
||||
JobType.CONTRACT_PAYMENT_ALERT,
|
||||
JobType.CONTRACT_PAYMENT_ALERT_WEEKLY,
|
||||
)
|
||||
if {item.value for item in contract_payment_types} & allowed_types:
|
||||
from app.jobs.queue import recover_stale_jobs
|
||||
from flask import current_app
|
||||
|
||||
# [STEP 1] 合同付款与合同审核共用 procurement_contract 域,必须按 Job 类型
|
||||
# 分别回收,不能错误使用不存在的 contract_payment 域或套用审核的较短超时。
|
||||
for job_type in contract_payment_types:
|
||||
if job_type.value not in allowed_types:
|
||||
continue
|
||||
recover_stale_jobs(
|
||||
domain="procurement_contract",
|
||||
timeout_seconds=float(current_app.config.get("CONTRACT_PAYMENT_JOB_TIMEOUT_SECONDS", 1800)),
|
||||
job_type=job_type,
|
||||
)
|
||||
|
||||
# [STEP 2] 按队列优先级 claim
|
||||
for name in queue_names:
|
||||
@@ -110,7 +129,12 @@ def claim_next(*, queues: list[str] | None = None) -> dict[str, Any] | None:
|
||||
|
||||
job = claim_next_job(
|
||||
domain="procurement_contract",
|
||||
job_types=[JobType.PROCUREMENT_CONTRACT_REVIEW],
|
||||
job_types=[
|
||||
JobType.PROCUREMENT_CONTRACT_REVIEW,
|
||||
JobType.CONTRACT_PAYMENT_SYNC,
|
||||
JobType.CONTRACT_PAYMENT_ALERT,
|
||||
JobType.CONTRACT_PAYMENT_ALERT_WEEKLY,
|
||||
],
|
||||
)
|
||||
if job:
|
||||
return _normalize_generic_job(job)
|
||||
|
||||
@@ -36,6 +36,9 @@ class JobType(StrEnum):
|
||||
FILE_CHECK_RUN = 'file_check_run'
|
||||
WECOM_DIRECTORY_SYNC = 'wecom_directory_sync'
|
||||
PROCUREMENT_CONTRACT_REVIEW = 'procurement_contract_review'
|
||||
CONTRACT_PAYMENT_SYNC = 'contract_payment_sync'
|
||||
CONTRACT_PAYMENT_ALERT = 'contract_payment_alert'
|
||||
CONTRACT_PAYMENT_ALERT_WEEKLY = 'contract_payment_alert_weekly'
|
||||
|
||||
|
||||
class JobStatus(StrEnum):
|
||||
@@ -73,7 +76,7 @@ QUEUE_KB_JOB_TYPES: dict[str, frozenset[str]] = {
|
||||
'shipping_stp_auto_create', 'shipping_line_auto_fulfill',
|
||||
'shipping_post_ot_wave_progress', 'shipping_review_revalidate_progress',
|
||||
}),
|
||||
'contract': frozenset({'procurement_contract_review'}),
|
||||
'contract': frozenset({'procurement_contract_review', 'contract_payment_sync', 'contract_payment_alert', 'contract_payment_alert_weekly'}),
|
||||
'schedule': frozenset({'schedule_run'}),
|
||||
}
|
||||
|
||||
|
||||
@@ -20,6 +20,15 @@ from app.models.schedule import ScheduleRun, ScheduleTask, ScheduleTaskConfig
|
||||
from app.models.settings import AppSetting
|
||||
from app.models.file_asset import FileAsset
|
||||
from app.models.contract import ContractReview, ContractRiskRule, ContractTemplate
|
||||
from app.models.contract_payment import (
|
||||
ContractPaymentAlert,
|
||||
ContractPaymentAttachment,
|
||||
ContractPaymentContract,
|
||||
ContractPaymentEvent,
|
||||
ContractPaymentNode,
|
||||
ContractPaymentSyncState,
|
||||
ContractPaymentVendorRequest,
|
||||
)
|
||||
from app.models.shipping import (
|
||||
ShippingInventoryFile,
|
||||
ShippingNotice,
|
||||
@@ -186,6 +195,16 @@ from app.models.shipping_inventory_mapping import ShippingInventoryMapping
|
||||
from app.models.training import TrainingRecord, TrainingConfig, TrainingConfigResource
|
||||
from app.models.user import LoginAudit, User, UserDefaultAgent, UserFavoriteAgent, UserHomepageConfig
|
||||
from app.models.voucher_check import VoucherCheckInvoiceState, VoucherCheckRunItem
|
||||
from app.models.contract_payment import (
|
||||
ContractPaymentAlert,
|
||||
ContractPaymentAlertBatch,
|
||||
ContractPaymentAttachment,
|
||||
ContractPaymentContract,
|
||||
ContractPaymentEvent,
|
||||
ContractPaymentNode,
|
||||
ContractPaymentSyncState,
|
||||
ContractPaymentVendorRequest,
|
||||
)
|
||||
from app.models.wecom import WecomCallbackAudit, WecomNotifyAudit
|
||||
|
||||
__all__ = [
|
||||
@@ -342,6 +361,12 @@ __all__ = [
|
||||
'ContractTemplate',
|
||||
'ContractReview',
|
||||
'ContractRiskRule',
|
||||
'ContractPaymentContract',
|
||||
'ContractPaymentAttachment',
|
||||
'ContractPaymentNode',
|
||||
'ContractPaymentEvent',
|
||||
'ContractPaymentVendorRequest',
|
||||
'ContractPaymentAlert',
|
||||
'AgentGuide',
|
||||
'AgentDirectoryMember',
|
||||
'TrainingRecord',
|
||||
@@ -356,4 +381,12 @@ __all__ = [
|
||||
'ShippingTaskInventoryRpaAttempt',
|
||||
'VoucherCheckInvoiceState',
|
||||
'VoucherCheckRunItem',
|
||||
'ContractPaymentContract',
|
||||
'ContractPaymentAttachment',
|
||||
'ContractPaymentNode',
|
||||
'ContractPaymentEvent',
|
||||
'ContractPaymentVendorRequest',
|
||||
'ContractPaymentAlert',
|
||||
'ContractPaymentAlertBatch',
|
||||
'ContractPaymentSyncState',
|
||||
]
|
||||
@@ -0,0 +1,208 @@
|
||||
"""
|
||||
backend/app/models/contract_payment.py
|
||||
|
||||
用途:采购合同付款预警域模型,保存 OA 合同台账、附件来源、付款节点、履约事件和企微预警幂等记录。
|
||||
依赖:models.base.Base、users、file_assets。
|
||||
逻辑:同步服务写入合同、付款请款与事件,解析服务生成付款节点,预警服务按节点状态写入提醒记录并调用企业微信。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime
|
||||
from decimal import Decimal
|
||||
from typing import Any, Optional
|
||||
|
||||
from sqlalchemy import Date, DateTime, ForeignKey, Index, JSON, LargeBinary, Numeric, String, Text, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class ContractPaymentContract(Base):
|
||||
"""OA 归档后的采购合同主记录。"""
|
||||
|
||||
__tablename__ = "contract_payment_contracts"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("contract_no", name="uq_contract_payment_contracts_contract_no"),
|
||||
Index("ix_contract_payment_contracts_purchase_order_no", "purchase_order_no"),
|
||||
Index("ix_contract_payment_contracts_status", "status"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
# 合同附件解析前可能为空;OA 表单中的流程编号不再写入此字段。
|
||||
contract_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
purchase_order_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
supplier_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
applicant_name: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
total_amount: Mapped[Optional[Decimal]] = mapped_column(Numeric(18, 2), nullable=True)
|
||||
currency: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
|
||||
effective_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
|
||||
delivery_due_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
|
||||
warranty_period_days: Mapped[Optional[int]] = mapped_column(nullable=True)
|
||||
owner_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True, index=True)
|
||||
oa_record_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True, index=True)
|
||||
workflow_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True, index=True)
|
||||
oa_archive_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
status: Mapped[str] = mapped_column(String(32), default="active", nullable=False)
|
||||
parse_status: Mapped[str] = mapped_column(String(32), default="pending", nullable=False, index=True)
|
||||
plan_status: Mapped[str] = mapped_column(String(32), default="pending", nullable=False, index=True)
|
||||
source_payload_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
parse_result_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
class ContractPaymentAttachment(Base):
|
||||
"""合同附件来源记录;OA 为主来源,文档管理系统为延迟补充。"""
|
||||
|
||||
__tablename__ = "contract_payment_attachments"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("contract_id", "source", "source_key", name="uq_contract_payment_attachments_source"),
|
||||
Index("ix_contract_payment_attachments_contract", "contract_id"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
contract_id: Mapped[int] = mapped_column(ForeignKey("contract_payment_contracts.id", ondelete="CASCADE"), nullable=False)
|
||||
source: Mapped[str] = mapped_column(String(32), nullable=False) # oa | dms
|
||||
source_key: Mapped[str] = mapped_column(String(512), nullable=False)
|
||||
file_name: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
mime_type: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
file_asset_id: Mapped[Optional[int]] = mapped_column(ForeignKey("file_assets.id"), nullable=True)
|
||||
dms_path: Mapped[Optional[str]] = mapped_column(String(1024), nullable=True)
|
||||
created_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
metadata_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
status: Mapped[str] = mapped_column(String(32), default="discovered", nullable=False)
|
||||
created_record_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
class ContractPaymentNode(Base):
|
||||
"""从合同条款编译出的付款节点。"""
|
||||
|
||||
__tablename__ = "contract_payment_nodes"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("contract_id", "node_code", name="uq_contract_payment_nodes_code"),
|
||||
Index("ix_contract_payment_nodes_due_date", "due_date", "status"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
contract_id: Mapped[int] = mapped_column(ForeignKey("contract_payment_contracts.id", ondelete="CASCADE"), nullable=False)
|
||||
node_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
node_type: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
amount: Mapped[Optional[Decimal]] = mapped_column(Numeric(18, 2), nullable=True)
|
||||
percentage: Mapped[Optional[Decimal]] = mapped_column(Numeric(8, 4), nullable=True)
|
||||
anchor_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
anchor_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
|
||||
offset_days: Mapped[int] = mapped_column(default=0, nullable=False)
|
||||
due_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
|
||||
reminder_days: Mapped[int] = mapped_column(default=14, nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(32), default="pending", nullable=False, index=True)
|
||||
evidence_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
class ContractPaymentEvent(Base):
|
||||
"""OA 验收归档及可选履约事件。"""
|
||||
|
||||
__tablename__ = "contract_payment_events"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("event_type", "source_event_id", name="uq_contract_payment_events_source"),
|
||||
Index("ix_contract_payment_events_contract_type", "contract_id", "event_type"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
contract_id: Mapped[int] = mapped_column(ForeignKey("contract_payment_contracts.id", ondelete="CASCADE"), nullable=False)
|
||||
event_type: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
event_date: Mapped[date] = mapped_column(Date, nullable=False)
|
||||
source_event_id: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
payload_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
class ContractPaymentVendorRequest(Base):
|
||||
"""OA 厂商预付款请款作业的标准化记录,用于判定预付款与出货款是否还需提醒。"""
|
||||
|
||||
__tablename__ = "contract_payment_vendor_requests"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("source_request_id", name="uq_contract_payment_vendor_requests_source"),
|
||||
Index("ix_contract_payment_vendor_requests_contract_stage", "contract_id", "payment_stage"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
contract_id: Mapped[int] = mapped_column(ForeignKey("contract_payment_contracts.id", ondelete="CASCADE"), nullable=False)
|
||||
source_request_id: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
request_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
payment_stage: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
request_status: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
requested_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
payload_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
class ContractPaymentAlert(Base):
|
||||
"""付款预警发送幂等和审计记录。"""
|
||||
|
||||
__tablename__ = "contract_payment_alerts"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("node_id", "trigger_key", "recipient_user_id", name="uq_contract_payment_alerts_trigger"),
|
||||
Index("ix_contract_payment_alerts_status_scheduled", "status", "scheduled_at"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
contract_id: Mapped[int] = mapped_column(ForeignKey("contract_payment_contracts.id", ondelete="CASCADE"), nullable=False)
|
||||
node_id: Mapped[int] = mapped_column(ForeignKey("contract_payment_nodes.id", ondelete="CASCADE"), nullable=False)
|
||||
trigger_key: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
scheduled_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
sent_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
recipient_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
|
||||
alert_round: Mapped[int] = mapped_column(default=1, nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(32), default="pending", nullable=False, index=True)
|
||||
message_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
class ContractPaymentAlertBatch(Base):
|
||||
"""按周、按收件人归并的合同付款预警发送批次。"""
|
||||
|
||||
__tablename__ = "contract_payment_alert_batches"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("week_key", "recipient_user_id", name="uq_contract_payment_alert_batches_week_recipient"),
|
||||
Index("ix_contract_payment_alert_batches_status_created", "status", "created_at"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
batch_no: Mapped[str] = mapped_column(String(64), unique=True, nullable=False)
|
||||
week_key: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
recipient_user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(32), default="pending", nullable=False)
|
||||
summary_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
excel_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
excel_file_data: Mapped[Optional[bytes]] = mapped_column(LargeBinary, nullable=True)
|
||||
excel_file_size: Mapped[Optional[int]] = mapped_column(nullable=True)
|
||||
sent_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
wecom_trace_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
class ContractPaymentSyncState(Base):
|
||||
"""合同付款域外部来源的 OA 增量同步断点(游标)。
|
||||
|
||||
用途:记录 OA 合同 HTTP 列表与验收 SQL 同步上次成功位置,供时间窗口增量拉取。
|
||||
依赖:models.base.Base。
|
||||
逻辑:同一 state_key 只保留一行;合同列表用 `oa-contract-archive`,验收归档用 `oa-acceptance-archive`。
|
||||
成功同步后更新 last_successful_sync_at,下次以它减去 overlap 作为时间下限。
|
||||
"""
|
||||
|
||||
__tablename__ = "contract_payment_sync_states"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
state_key: Mapped[str] = mapped_column(String(64), unique=True, nullable=False)
|
||||
last_successful_sync_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
last_archive_seen_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
last_run_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
synced_contract_count: Mapped[int] = mapped_column(default=0, nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
@@ -96,6 +96,8 @@ class User(Base):
|
||||
'shipping_notice.xfa_split_rule_edit': self.role == 'admin',
|
||||
'shipping_notice.xfa_split_rule_preview': self.role == 'admin',
|
||||
'shipping_notice.xfa_split_rule_publish': self.role == 'admin',
|
||||
# 合同付款预警工作台:admin 默认开;不新建角色,可给采购同事单独授予
|
||||
'contract_payment.access': self.role == 'admin',
|
||||
}
|
||||
|
||||
def get_feature_permissions(self) -> dict[str, bool]:
|
||||
@@ -103,7 +105,7 @@ class User(Base):
|
||||
返回当前用户的有效功能权限。
|
||||
|
||||
用途:统一为前端展示、登录态注入与后端业务校验提供同一份权限结果。
|
||||
核心逻辑:先按角色生成默认权限,再用用户显式配置覆盖,避免把培训类业务权限硬编码在多个模块。
|
||||
核心逻辑:先按角色生成默认权限,再用用户显式配置覆盖,避免把培训、合同付款等业务权限硬编码在多个模块。
|
||||
输出约束:仅返回布尔型权限键,缺失项自动回退到角色默认值。
|
||||
"""
|
||||
defaults = self._role_default_feature_permissions()
|
||||
@@ -143,6 +145,10 @@ class User(Base):
|
||||
"""判断当前用户是否可使用培训 HR 管理面板与接口。"""
|
||||
return self.has_feature_permission('training_hr_manage')
|
||||
|
||||
def can_access_contract_payment(self) -> bool:
|
||||
"""判断当前用户是否可查看合同付款预警工作台并触发同步/扫描。"""
|
||||
return self.has_feature_permission('contract_payment.access')
|
||||
|
||||
def set_password(self, password: str) -> None:
|
||||
"""设置密码哈希。"""
|
||||
self.password_hash = generate_password_hash(password)
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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}
|
||||
|
||||
Reference in new issue
Block a user