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}
|
||||
|
||||
Binary file not shown.
@@ -1,4 +0,0 @@
|
||||
source_file=su_schedule_4.xlsx
|
||||
source_size=5980
|
||||
clean_status=placeholder_success
|
||||
fallback_reason=No module named 'pydantic'
|
||||
@@ -1,5 +0,0 @@
|
||||
su_schedule_5
|
||||
## Sheet: result
|
||||
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=PC6842;材质名称=标签;第三方编码=SHAEC25020186401;检测项目=RoHS十项+卤素;铅(Pb)=N.D;镉(Cd)=N.D;汞(Hg)=N.D;六价铬(Cr6+)=N.D;多溴联苯(PBBs)=N.D;多溴二苯醚(PBDEs)=N.D;邻苯二甲酸二丁酯(DBP)=N.D;邻苯二甲酸丁苄酯(BBP)=N.D;邻苯二甲酸二(2-乙基己)酯(DEHP)=N.D;邻苯二甲酸二异丁酯(DIBP)=N.D;氯(Cl)=N.D;溴(Br)=N.D;检测日期=2025-08-14 00:00:00;报告有效截止日期=2026-08-14 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/本色磨砂PC-有害物质报告-20250814-英文_1779086818095.pdf;chm_id=17790867106401639770;检核结果=人工判定;检核说明=返回值异常:空;回写SRM=True;回写错误=。
|
||||
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=Black ink;材质名称=标签;第三方编码=A2260184574101008E;检测项目=卤素;铅(Pb)=NA;镉(Cd)=NA;汞(Hg)=NA;六价铬(Cr6+)=NA;多溴联苯(PBBs)=NA;多溴二苯醚(PBDEs)=NA;邻苯二甲酸二丁酯(DBP)=NA;邻苯二甲酸丁苄酯(BBP)=NA;邻苯二甲酸二(2-乙基己)酯(DEHP)=NA;邻苯二甲酸二异丁酯(DIBP)=NA;氯(Cl)=N.D;溴(Br)=N.D;检测日期=2026-03-18 00:00:00;报告有效截止日期=2027-03-18 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/2026-黑色HF_1774832573760.pdf;chm_id=17790869056412507491;检核结果=合格;检核说明=;回写SRM=True;回写错误=。
|
||||
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=Black ink;材质名称=标签;第三方编码=A2260184574101001E;检测项目=RoHS十项;铅(Pb)=N.D;镉(Cd)=N.D;汞(Hg)=N.D;六价铬(Cr6+)=N.D;多溴联苯(PBBs)=N.D;多溴二苯醚(PBDEs)=N.D;邻苯二甲酸二丁酯(DBP)=N.D;邻苯二甲酸丁苄酯(BBP)=N.D;邻苯二甲酸二(2-乙基己)酯(DEHP)=N.D;邻苯二甲酸二异丁酯(DIBP)=N.D;氯(Cl)=NA;溴(Br)=NA;检测日期=2026-03-18 00:00:00;报告有效截止日期=2027-03-18 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/2026-黑色ROHS_1774832608199.pdf;chm_id=17790870063173449273;检核结果=人工判定;检核说明=返回值异常:空;回写SRM=True;回写错误=。
|
||||
@@ -1,5 +0,0 @@
|
||||
su_schedule_5
|
||||
## Sheet: result
|
||||
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=PC6842;材质名称=标签;第三方编码=SHAEC25020186401;检测项目=RoHS十项+卤素;铅(Pb)=N.D;镉(Cd)=N.D;汞(Hg)=N.D;六价铬(Cr6+)=N.D;多溴联苯(PBBs)=N.D;多溴二苯醚(PBDEs)=N.D;邻苯二甲酸二丁酯(DBP)=N.D;邻苯二甲酸丁苄酯(BBP)=N.D;邻苯二甲酸二(2-乙基己)酯(DEHP)=N.D;邻苯二甲酸二异丁酯(DIBP)=N.D;氯(Cl)=N.D;溴(Br)=N.D;检测日期=2025-08-14 00:00:00;报告有效截止日期=2026-08-14 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/本色磨砂PC-有害物质报告-20250814-英文_1779086818095.pdf;chm_id=17790867106401639770;检核结果=人工判定;检核说明=返回值异常:空;回写SRM=True;回写错误=。
|
||||
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=Black ink;材质名称=标签;第三方编码=A2260184574101008E;检测项目=卤素;铅(Pb)=NA;镉(Cd)=NA;汞(Hg)=NA;六价铬(Cr6+)=NA;多溴联苯(PBBs)=NA;多溴二苯醚(PBDEs)=NA;邻苯二甲酸二丁酯(DBP)=NA;邻苯二甲酸丁苄酯(BBP)=NA;邻苯二甲酸二(2-乙基己)酯(DEHP)=NA;邻苯二甲酸二异丁酯(DIBP)=NA;氯(Cl)=N.D;溴(Br)=N.D;检测日期=2026-03-18 00:00:00;报告有效截止日期=2027-03-18 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/2026-黑色HF_1774832573760.pdf;chm_id=17790869056412507491;检核结果=合格;检核说明=;回写SRM=True;回写错误=。
|
||||
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=Black ink;材质名称=标签;第三方编码=A2260184574101001E;检测项目=RoHS十项;铅(Pb)=N.D;镉(Cd)=N.D;汞(Hg)=N.D;六价铬(Cr6+)=N.D;多溴联苯(PBBs)=N.D;多溴二苯醚(PBDEs)=N.D;邻苯二甲酸二丁酯(DBP)=N.D;邻苯二甲酸丁苄酯(BBP)=N.D;邻苯二甲酸二(2-乙基己)酯(DEHP)=N.D;邻苯二甲酸二异丁酯(DIBP)=N.D;氯(Cl)=NA;溴(Br)=NA;检测日期=2026-03-18 00:00:00;报告有效截止日期=2027-03-18 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/2026-黑色ROHS_1774832608199.pdf;chm_id=17790870063173449273;检核结果=人工判定;检核说明=返回值异常:空;回写SRM=True;回写错误=。
|
||||
Binary file not shown.
@@ -1,4 +0,0 @@
|
||||
source_file=su_schedule_5.xlsx
|
||||
source_size=5980
|
||||
clean_status=placeholder_success
|
||||
fallback_reason=[Errno 1] Operation not permitted
|
||||
@@ -1,5 +0,0 @@
|
||||
su_schedule_5
|
||||
## Sheet: result
|
||||
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=PC6842;材质名称=标签;第三方编码=SHAEC25020186401;检测项目=RoHS十项+卤素;铅(Pb)=N.D;镉(Cd)=N.D;汞(Hg)=N.D;六价铬(Cr6+)=N.D;多溴联苯(PBBs)=N.D;多溴二苯醚(PBDEs)=N.D;邻苯二甲酸二丁酯(DBP)=N.D;邻苯二甲酸丁苄酯(BBP)=N.D;邻苯二甲酸二(2-乙基己)酯(DEHP)=N.D;邻苯二甲酸二异丁酯(DIBP)=N.D;氯(Cl)=N.D;溴(Br)=N.D;检测日期=2025-08-14 00:00:00;报告有效截止日期=2026-08-14 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/本色磨砂PC-有害物质报告-20250814-英文_1779086818095.pdf;chm_id=17790867106401639770;检核结果=人工判定;检核说明=返回值异常:空;回写SRM=True;回写错误=。
|
||||
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=Black ink;材质名称=标签;第三方编码=A2260184574101008E;检测项目=卤素;铅(Pb)=NA;镉(Cd)=NA;汞(Hg)=NA;六价铬(Cr6+)=NA;多溴联苯(PBBs)=NA;多溴二苯醚(PBDEs)=NA;邻苯二甲酸二丁酯(DBP)=NA;邻苯二甲酸丁苄酯(BBP)=NA;邻苯二甲酸二(2-乙基己)酯(DEHP)=NA;邻苯二甲酸二异丁酯(DIBP)=NA;氯(Cl)=N.D;溴(Br)=N.D;检测日期=2026-03-18 00:00:00;报告有效截止日期=2027-03-18 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/2026-黑色HF_1774832573760.pdf;chm_id=17790869056412507491;检核结果=合格;检核说明=;回写SRM=True;回写错误=。
|
||||
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=Black ink;材质名称=标签;第三方编码=A2260184574101001E;检测项目=RoHS十项;铅(Pb)=N.D;镉(Cd)=N.D;汞(Hg)=N.D;六价铬(Cr6+)=N.D;多溴联苯(PBBs)=N.D;多溴二苯醚(PBDEs)=N.D;邻苯二甲酸二丁酯(DBP)=N.D;邻苯二甲酸丁苄酯(BBP)=N.D;邻苯二甲酸二(2-乙基己)酯(DEHP)=N.D;邻苯二甲酸二异丁酯(DIBP)=N.D;氯(Cl)=NA;溴(Br)=NA;检测日期=2026-03-18 00:00:00;报告有效截止日期=2027-03-18 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/2026-黑色ROHS_1774832608199.pdf;chm_id=17790870063173449273;检核结果=人工判定;检核说明=返回值异常:空;回写SRM=True;回写错误=。
|
||||
@@ -1,5 +0,0 @@
|
||||
su_schedule_5
|
||||
## Sheet: result
|
||||
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=PC6842;材质名称=标签;第三方编码=SHAEC25020186401;检测项目=RoHS十项+卤素;铅(Pb)=N.D;镉(Cd)=N.D;汞(Hg)=N.D;六价铬(Cr6+)=N.D;多溴联苯(PBBs)=N.D;多溴二苯醚(PBDEs)=N.D;邻苯二甲酸二丁酯(DBP)=N.D;邻苯二甲酸丁苄酯(BBP)=N.D;邻苯二甲酸二(2-乙基己)酯(DEHP)=N.D;邻苯二甲酸二异丁酯(DIBP)=N.D;氯(Cl)=N.D;溴(Br)=N.D;检测日期=2025-08-14 00:00:00;报告有效截止日期=2026-08-14 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/本色磨砂PC-有害物质报告-20250814-英文_1779086818095.pdf;chm_id=17790867106401639770;检核结果=人工判定;检核说明=返回值异常:空;回写SRM=True;回写错误=。
|
||||
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=Black ink;材质名称=标签;第三方编码=A2260184574101008E;检测项目=卤素;铅(Pb)=NA;镉(Cd)=NA;汞(Hg)=NA;六价铬(Cr6+)=NA;多溴联苯(PBBs)=NA;多溴二苯醚(PBDEs)=NA;邻苯二甲酸二丁酯(DBP)=NA;邻苯二甲酸丁苄酯(BBP)=NA;邻苯二甲酸二(2-乙基己)酯(DEHP)=NA;邻苯二甲酸二异丁酯(DIBP)=NA;氯(Cl)=N.D;溴(Br)=N.D;检测日期=2026-03-18 00:00:00;报告有效截止日期=2027-03-18 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/2026-黑色HF_1774832573760.pdf;chm_id=17790869056412507491;检核结果=合格;检核说明=;回写SRM=True;回写错误=。
|
||||
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=Black ink;材质名称=标签;第三方编码=A2260184574101001E;检测项目=RoHS十项;铅(Pb)=N.D;镉(Cd)=N.D;汞(Hg)=N.D;六价铬(Cr6+)=N.D;多溴联苯(PBBs)=N.D;多溴二苯醚(PBDEs)=N.D;邻苯二甲酸二丁酯(DBP)=N.D;邻苯二甲酸丁苄酯(BBP)=N.D;邻苯二甲酸二(2-乙基己)酯(DEHP)=N.D;邻苯二甲酸二异丁酯(DIBP)=N.D;氯(Cl)=NA;溴(Br)=NA;检测日期=2026-03-18 00:00:00;报告有效截止日期=2027-03-18 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/2026-黑色ROHS_1774832608199.pdf;chm_id=17790870063173449273;检核结果=人工判定;检核说明=返回值异常:空;回写SRM=True;回写错误=。
|
||||
@@ -1,5 +0,0 @@
|
||||
su_schedule_5
|
||||
## Sheet: result
|
||||
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=PC6842;材质名称=标签;第三方编码=SHAEC25020186401;检测项目=RoHS十项+卤素;铅(Pb)=N.D;镉(Cd)=N.D;汞(Hg)=N.D;六价铬(Cr6+)=N.D;多溴联苯(PBBs)=N.D;多溴二苯醚(PBDEs)=N.D;邻苯二甲酸二丁酯(DBP)=N.D;邻苯二甲酸丁苄酯(BBP)=N.D;邻苯二甲酸二(2-乙基己)酯(DEHP)=N.D;邻苯二甲酸二异丁酯(DIBP)=N.D;氯(Cl)=N.D;溴(Br)=N.D;检测日期=2025-08-14 00:00:00;报告有效截止日期=2026-08-14 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/本色磨砂PC-有害物质报告-20250814-英文_1779086818095.pdf;chm_id=17790867106401639770;检核结果=人工判定;检核说明=返回值异常:空;回写SRM=True;回写错误=。
|
||||
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=Black ink;材质名称=标签;第三方编码=A2260184574101008E;检测项目=卤素;铅(Pb)=NA;镉(Cd)=NA;汞(Hg)=NA;六价铬(Cr6+)=NA;多溴联苯(PBBs)=NA;多溴二苯醚(PBDEs)=NA;邻苯二甲酸二丁酯(DBP)=NA;邻苯二甲酸丁苄酯(BBP)=NA;邻苯二甲酸二(2-乙基己)酯(DEHP)=NA;邻苯二甲酸二异丁酯(DIBP)=NA;氯(Cl)=N.D;溴(Br)=N.D;检测日期=2026-03-18 00:00:00;报告有效截止日期=2027-03-18 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/2026-黑色HF_1774832573760.pdf;chm_id=17790869056412507491;检核结果=合格;检核说明=;回写SRM=True;回写错误=。
|
||||
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=Black ink;材质名称=标签;第三方编码=A2260184574101001E;检测项目=RoHS十项;铅(Pb)=N.D;镉(Cd)=N.D;汞(Hg)=N.D;六价铬(Cr6+)=N.D;多溴联苯(PBBs)=N.D;多溴二苯醚(PBDEs)=N.D;邻苯二甲酸二丁酯(DBP)=N.D;邻苯二甲酸丁苄酯(BBP)=N.D;邻苯二甲酸二(2-乙基己)酯(DEHP)=N.D;邻苯二甲酸二异丁酯(DIBP)=N.D;氯(Cl)=NA;溴(Br)=NA;检测日期=2026-03-18 00:00:00;报告有效截止日期=2027-03-18 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/2026-黑色ROHS_1774832608199.pdf;chm_id=17790870063173449273;检核结果=人工判定;检核说明=返回值异常:空;回写SRM=True;回写错误=。
|
||||
@@ -1,5 +0,0 @@
|
||||
su_schedule_6
|
||||
## Sheet: result
|
||||
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=PC6842;材质名称=标签;第三方编码=SHAEC25020186401;检测项目=RoHS十项+卤素;铅(Pb)=N.D;镉(Cd)=N.D;汞(Hg)=N.D;六价铬(Cr6+)=N.D;多溴联苯(PBBs)=N.D;多溴二苯醚(PBDEs)=N.D;邻苯二甲酸二丁酯(DBP)=N.D;邻苯二甲酸丁苄酯(BBP)=N.D;邻苯二甲酸二(2-乙基己)酯(DEHP)=N.D;邻苯二甲酸二异丁酯(DIBP)=N.D;氯(Cl)=N.D;溴(Br)=N.D;检测日期=2025-08-14 00:00:00;报告有效截止日期=2026-08-14 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/本色磨砂PC-有害物质报告-20250814-英文_1779086818095.pdf;chm_id=17790867106401639770;检核结果=人工判定;检核说明=返回值异常:空;回写SRM=True;回写错误=。
|
||||
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=Black ink;材质名称=标签;第三方编码=A2260184574101008E;检测项目=卤素;铅(Pb)=NA;镉(Cd)=NA;汞(Hg)=NA;六价铬(Cr6+)=NA;多溴联苯(PBBs)=NA;多溴二苯醚(PBDEs)=NA;邻苯二甲酸二丁酯(DBP)=NA;邻苯二甲酸丁苄酯(BBP)=NA;邻苯二甲酸二(2-乙基己)酯(DEHP)=NA;邻苯二甲酸二异丁酯(DIBP)=NA;氯(Cl)=N.D;溴(Br)=N.D;检测日期=2026-03-18 00:00:00;报告有效截止日期=2027-03-18 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/2026-黑色HF_1774832573760.pdf;chm_id=17790869056412507491;检核结果=合格;检核说明=;回写SRM=True;回写错误=。
|
||||
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=Black ink;材质名称=标签;第三方编码=A2260184574101001E;检测项目=RoHS十项;铅(Pb)=N.D;镉(Cd)=N.D;汞(Hg)=N.D;六价铬(Cr6+)=N.D;多溴联苯(PBBs)=N.D;多溴二苯醚(PBDEs)=N.D;邻苯二甲酸二丁酯(DBP)=N.D;邻苯二甲酸丁苄酯(BBP)=N.D;邻苯二甲酸二(2-乙基己)酯(DEHP)=N.D;邻苯二甲酸二异丁酯(DIBP)=N.D;氯(Cl)=NA;溴(Br)=NA;检测日期=2026-03-18 00:00:00;报告有效截止日期=2027-03-18 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/2026-黑色ROHS_1774832608199.pdf;chm_id=17790870063173449273;检核结果=人工判定;检核说明=返回值异常:空;回写SRM=True;回写错误=。
|
||||
Binary file not shown.
@@ -1,5 +0,0 @@
|
||||
su_schedule_7
|
||||
## Sheet: result
|
||||
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=PC6842;材质名称=标签;第三方编码=SHAEC25020186401;检测项目=RoHS十项+卤素;铅(Pb)=N.D;镉(Cd)=N.D;汞(Hg)=N.D;六价铬(Cr6+)=N.D;多溴联苯(PBBs)=N.D;多溴二苯醚(PBDEs)=N.D;邻苯二甲酸二丁酯(DBP)=N.D;邻苯二甲酸丁苄酯(BBP)=N.D;邻苯二甲酸二(2-乙基己)酯(DEHP)=N.D;邻苯二甲酸二异丁酯(DIBP)=N.D;氯(Cl)=N.D;溴(Br)=N.D;检测日期=2025-08-14 00:00:00;报告有效截止日期=2026-08-14 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/本色磨砂PC-有害物质报告-20250814-英文_1779086818095.pdf;chm_id=17790867106401639770;检核结果=人工判定;检核说明=返回值异常:空;回写SRM=True;回写错误=。
|
||||
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=Black ink;材质名称=标签;第三方编码=A2260184574101008E;检测项目=卤素;铅(Pb)=NA;镉(Cd)=NA;汞(Hg)=NA;六价铬(Cr6+)=NA;多溴联苯(PBBs)=NA;多溴二苯醚(PBDEs)=NA;邻苯二甲酸二丁酯(DBP)=NA;邻苯二甲酸丁苄酯(BBP)=NA;邻苯二甲酸二(2-乙基己)酯(DEHP)=NA;邻苯二甲酸二异丁酯(DIBP)=NA;氯(Cl)=N.D;溴(Br)=N.D;检测日期=2026-03-18 00:00:00;报告有效截止日期=2027-03-18 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/2026-黑色HF_1774832573760.pdf;chm_id=17790869056412507491;检核结果=合格;检核说明=;回写SRM=True;回写错误=。
|
||||
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=Black ink;材质名称=标签;第三方编码=A2260184574101001E;检测项目=RoHS十项;铅(Pb)=N.D;镉(Cd)=N.D;汞(Hg)=N.D;六价铬(Cr6+)=N.D;多溴联苯(PBBs)=N.D;多溴二苯醚(PBDEs)=N.D;邻苯二甲酸二丁酯(DBP)=N.D;邻苯二甲酸丁苄酯(BBP)=N.D;邻苯二甲酸二(2-乙基己)酯(DEHP)=N.D;邻苯二甲酸二异丁酯(DIBP)=N.D;氯(Cl)=NA;溴(Br)=NA;检测日期=2026-03-18 00:00:00;报告有效截止日期=2027-03-18 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/2026-黑色ROHS_1774832608199.pdf;chm_id=17790870063173449273;检核结果=人工判定;检核说明=返回值异常:空;回写SRM=True;回写错误=。
|
||||
Binary file not shown.
@@ -1 +0,0 @@
|
||||
integration smoke text
|
||||
@@ -27,34 +27,44 @@ depends_on = None
|
||||
|
||||
def _drop_fk_if_exists(table: str, fk_name: str) -> None:
|
||||
"""尽力删除外键;不存在则忽略(兼容 SQLite/PG 与历史库差异)。"""
|
||||
try:
|
||||
op.drop_constraint(fk_name, table, type_='foreignkey')
|
||||
except Exception:
|
||||
pass
|
||||
inspector = sa.inspect(op.get_bind())
|
||||
if table not in inspector.get_table_names():
|
||||
return
|
||||
if not any(fk.get('name') == fk_name for fk in inspector.get_foreign_keys(table)):
|
||||
return
|
||||
op.drop_constraint(fk_name, table, type_='foreignkey')
|
||||
|
||||
|
||||
def _drop_constraint_if_exists(table: str, name: str, type_: str = 'unique') -> None:
|
||||
"""尽力删除约束。"""
|
||||
try:
|
||||
inspector = sa.inspect(op.get_bind())
|
||||
if table not in inspector.get_table_names():
|
||||
return
|
||||
if type_ == 'unique':
|
||||
exists = any(item.get('name') == name for item in inspector.get_unique_constraints(table))
|
||||
elif type_ == 'foreignkey':
|
||||
exists = any(item.get('name') == name for item in inspector.get_foreign_keys(table))
|
||||
else:
|
||||
exists = any(item.get('name') == name for item in inspector.get_check_constraints(table))
|
||||
if exists:
|
||||
op.drop_constraint(name, table, type_=type_)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _drop_column_if_exists(table: str, column: str) -> None:
|
||||
"""尽力删除列。"""
|
||||
try:
|
||||
op.drop_column(table, column)
|
||||
except Exception:
|
||||
pass
|
||||
inspector = sa.inspect(op.get_bind())
|
||||
if table not in inspector.get_table_names():
|
||||
return
|
||||
if not any(item.get('name') == column for item in inspector.get_columns(table)):
|
||||
return
|
||||
op.drop_column(table, column)
|
||||
|
||||
|
||||
def _drop_table_if_exists(table: str) -> None:
|
||||
"""尽力删除表。"""
|
||||
try:
|
||||
inspector = sa.inspect(op.get_bind())
|
||||
if table in inspector.get_table_names():
|
||||
op.drop_table(table)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
"""add contract payment warning tables
|
||||
|
||||
Revision ID: g0a1b2c3d4e5
|
||||
Revises: ('a0b1c2d3e4f5', '9a2d6b4e8c1f')
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = "g0a1b2c3d4e5"
|
||||
down_revision = ("a0b1c2d3e4f5", "9a2d6b4e8c1f")
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.create_table(
|
||||
"contract_payment_contracts",
|
||||
sa.Column("id", sa.Integer(), nullable=False),
|
||||
sa.Column("contract_no", sa.String(length=128), nullable=True),
|
||||
sa.Column("purchase_order_no", sa.String(length=128), nullable=True),
|
||||
sa.Column("supplier_name", sa.String(length=255), nullable=True),
|
||||
sa.Column("total_amount", sa.Numeric(precision=18, scale=2), nullable=True),
|
||||
sa.Column("currency", sa.String(length=16), nullable=True),
|
||||
sa.Column("effective_date", sa.Date(), nullable=True),
|
||||
sa.Column("delivery_due_date", sa.Date(), nullable=True),
|
||||
sa.Column("warranty_period_days", sa.Integer(), nullable=True),
|
||||
sa.Column("owner_user_id", sa.Integer(), nullable=True),
|
||||
sa.Column("oa_record_id", sa.String(length=128), nullable=True),
|
||||
sa.Column("oa_archive_at", sa.DateTime(), nullable=True),
|
||||
sa.Column("status", sa.String(length=32), nullable=False, server_default="active"),
|
||||
sa.Column("parse_status", sa.String(length=32), nullable=False, server_default="pending"),
|
||||
sa.Column("plan_status", sa.String(length=32), nullable=False, server_default="pending"),
|
||||
sa.Column("source_payload_json", sa.JSON(), nullable=True),
|
||||
sa.Column("parse_result_json", sa.JSON(), nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||
sa.Column("updated_at", sa.DateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(["owner_user_id"], ["users.id"]),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
sa.UniqueConstraint("contract_no", name="uq_contract_payment_contracts_contract_no"),
|
||||
)
|
||||
op.create_index("ix_contract_payment_contracts_purchase_order_no", "contract_payment_contracts", ["purchase_order_no"])
|
||||
op.create_index("ix_contract_payment_contracts_status", "contract_payment_contracts", ["status"])
|
||||
op.create_index("ix_contract_payment_contracts_owner_user_id", "contract_payment_contracts", ["owner_user_id"])
|
||||
op.create_index("ix_contract_payment_contracts_oa_record_id", "contract_payment_contracts", ["oa_record_id"])
|
||||
op.create_index("ix_contract_payment_contracts_parse_status", "contract_payment_contracts", ["parse_status"])
|
||||
op.create_index("ix_contract_payment_contracts_plan_status", "contract_payment_contracts", ["plan_status"])
|
||||
|
||||
op.create_table(
|
||||
"contract_payment_attachments",
|
||||
sa.Column("id", sa.Integer(), nullable=False),
|
||||
sa.Column("contract_id", sa.Integer(), nullable=False),
|
||||
sa.Column("source", sa.String(length=32), nullable=False),
|
||||
sa.Column("source_key", sa.String(length=512), nullable=False),
|
||||
sa.Column("file_name", sa.String(length=255), nullable=False),
|
||||
sa.Column("mime_type", sa.String(length=128), nullable=True),
|
||||
sa.Column("file_asset_id", sa.Integer(), nullable=True),
|
||||
sa.Column("dms_path", sa.String(length=1024), nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=True),
|
||||
sa.Column("metadata_json", sa.JSON(), nullable=True),
|
||||
sa.Column("status", sa.String(length=32), nullable=False, server_default="discovered"),
|
||||
sa.Column("created_record_at", sa.DateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(["contract_id"], ["contract_payment_contracts.id"], ondelete="CASCADE"),
|
||||
sa.ForeignKeyConstraint(["file_asset_id"], ["file_assets.id"]),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
sa.UniqueConstraint("contract_id", "source", "source_key", name="uq_contract_payment_attachments_source"),
|
||||
)
|
||||
op.create_index("ix_contract_payment_attachments_contract", "contract_payment_attachments", ["contract_id"])
|
||||
|
||||
op.create_table(
|
||||
"contract_payment_nodes",
|
||||
sa.Column("id", sa.Integer(), nullable=False),
|
||||
sa.Column("contract_id", sa.Integer(), nullable=False),
|
||||
sa.Column("node_code", sa.String(length=64), nullable=False),
|
||||
sa.Column("node_type", sa.String(length=32), nullable=False),
|
||||
sa.Column("amount", sa.Numeric(precision=18, scale=2), nullable=True),
|
||||
sa.Column("percentage", sa.Numeric(precision=8, scale=4), nullable=True),
|
||||
sa.Column("anchor_type", sa.String(length=32), nullable=True),
|
||||
sa.Column("anchor_date", sa.Date(), nullable=True),
|
||||
sa.Column("offset_days", sa.Integer(), nullable=False, server_default="0"),
|
||||
sa.Column("due_date", sa.Date(), nullable=True),
|
||||
sa.Column("reminder_days", sa.Integer(), nullable=False, server_default="14"),
|
||||
sa.Column("status", sa.String(length=32), nullable=False, server_default="pending"),
|
||||
sa.Column("evidence_json", sa.JSON(), nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||
sa.Column("updated_at", sa.DateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(["contract_id"], ["contract_payment_contracts.id"], ondelete="CASCADE"),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
sa.UniqueConstraint("contract_id", "node_code", name="uq_contract_payment_nodes_code"),
|
||||
)
|
||||
op.create_index("ix_contract_payment_nodes_due_date", "contract_payment_nodes", ["due_date", "status"])
|
||||
op.create_index("ix_contract_payment_nodes_contract_id", "contract_payment_nodes", ["contract_id"])
|
||||
|
||||
op.create_table(
|
||||
"contract_payment_events",
|
||||
sa.Column("id", sa.Integer(), nullable=False),
|
||||
sa.Column("contract_id", sa.Integer(), nullable=False),
|
||||
sa.Column("event_type", sa.String(length=32), nullable=False),
|
||||
sa.Column("event_date", sa.Date(), nullable=False),
|
||||
sa.Column("source_event_id", sa.String(length=128), nullable=False),
|
||||
sa.Column("payload_json", sa.JSON(), nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(["contract_id"], ["contract_payment_contracts.id"], ondelete="CASCADE"),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
sa.UniqueConstraint("event_type", "source_event_id", name="uq_contract_payment_events_source"),
|
||||
)
|
||||
op.create_index("ix_contract_payment_events_contract_type", "contract_payment_events", ["contract_id", "event_type"])
|
||||
|
||||
op.create_table(
|
||||
"contract_payment_alerts",
|
||||
sa.Column("id", sa.Integer(), nullable=False),
|
||||
sa.Column("contract_id", sa.Integer(), nullable=False),
|
||||
sa.Column("node_id", sa.Integer(), nullable=False),
|
||||
sa.Column("trigger_key", sa.String(length=64), nullable=False),
|
||||
sa.Column("scheduled_at", sa.DateTime(), nullable=True),
|
||||
sa.Column("sent_at", sa.DateTime(), nullable=True),
|
||||
sa.Column("recipient_user_id", sa.Integer(), nullable=True),
|
||||
sa.Column("status", sa.String(length=32), nullable=False, server_default="pending"),
|
||||
sa.Column("message_json", sa.JSON(), nullable=True),
|
||||
sa.Column("error_message", sa.Text(), nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(["contract_id"], ["contract_payment_contracts.id"], ondelete="CASCADE"),
|
||||
sa.ForeignKeyConstraint(["node_id"], ["contract_payment_nodes.id"], ondelete="CASCADE"),
|
||||
sa.ForeignKeyConstraint(["recipient_user_id"], ["users.id"]),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
sa.UniqueConstraint("node_id", "trigger_key", name="uq_contract_payment_alerts_trigger"),
|
||||
)
|
||||
op.create_index("ix_contract_payment_alerts_status_scheduled", "contract_payment_alerts", ["status", "scheduled_at"])
|
||||
op.create_index("ix_contract_payment_alerts_contract_id", "contract_payment_alerts", ["contract_id"])
|
||||
op.create_index("ix_contract_payment_alerts_node_id", "contract_payment_alerts", ["node_id"])
|
||||
op.create_index("ix_contract_payment_alerts_recipient_user_id", "contract_payment_alerts", ["recipient_user_id"])
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_table("contract_payment_alerts")
|
||||
op.drop_table("contract_payment_events")
|
||||
op.drop_table("contract_payment_nodes")
|
||||
op.drop_table("contract_payment_attachments")
|
||||
op.drop_table("contract_payment_contracts")
|
||||
@@ -0,0 +1,51 @@
|
||||
"""add workflow number and allow contract number pending PDF parsing"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = "h1b2c3d4e5f6"
|
||||
down_revision = "g0a1b2c3d4e5"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.alter_column(
|
||||
"contract_payment_contracts",
|
||||
"contract_no",
|
||||
existing_type=sa.String(length=128),
|
||||
nullable=True,
|
||||
)
|
||||
op.add_column(
|
||||
"contract_payment_contracts",
|
||||
sa.Column("workflow_no", sa.String(length=128), nullable=True),
|
||||
)
|
||||
op.create_index(
|
||||
"ix_contract_payment_contracts_workflow_no",
|
||||
"contract_payment_contracts",
|
||||
["workflow_no"],
|
||||
)
|
||||
# 已同步的首批数据把 OA“流程编号”误写进合同编号;仅迁移明确的 HT 流程号,
|
||||
# 真正合同号将由已保存的附件在下一次解析时回填。
|
||||
op.execute(
|
||||
"UPDATE contract_payment_contracts "
|
||||
"SET workflow_no = contract_no, contract_no = NULL "
|
||||
"WHERE contract_no LIKE 'HT-%'"
|
||||
)
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.execute(
|
||||
"UPDATE contract_payment_contracts "
|
||||
"SET contract_no = COALESCE(workflow_no, oa_record_id, CAST(id AS VARCHAR(128))) "
|
||||
"WHERE contract_no IS NULL"
|
||||
)
|
||||
op.drop_index("ix_contract_payment_contracts_workflow_no", table_name="contract_payment_contracts")
|
||||
op.drop_column("contract_payment_contracts", "workflow_no")
|
||||
op.alter_column(
|
||||
"contract_payment_contracts",
|
||||
"contract_no",
|
||||
existing_type=sa.String(length=128),
|
||||
nullable=False,
|
||||
)
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
"""extend contract payment three round alerts
|
||||
|
||||
Revision ID: h2c3d4e5f6a7
|
||||
Revises: h1b2c3d4e5f6
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = "h2c3d4e5f6a7"
|
||||
down_revision = "h1b2c3d4e5f6"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
"""
|
||||
增加厂商预付款请款作业事实表,并将预警幂等键扩展到收件人维度。
|
||||
|
||||
核心逻辑:同一提醒轮次允许发送给不同岗位收件人;OA 请款记录独立保存,
|
||||
使预付款、出货款可以按真实请款事实停止后续升级。
|
||||
"""
|
||||
op.create_table(
|
||||
"contract_payment_vendor_requests",
|
||||
sa.Column("id", sa.Integer(), nullable=False),
|
||||
sa.Column("contract_id", sa.Integer(), nullable=False),
|
||||
sa.Column("source_request_id", sa.String(length=128), nullable=False),
|
||||
sa.Column("request_no", sa.String(length=128), nullable=True),
|
||||
sa.Column("payment_stage", sa.String(length=32), nullable=False),
|
||||
sa.Column("request_status", sa.String(length=64), nullable=True),
|
||||
sa.Column("requested_at", sa.DateTime(), nullable=True),
|
||||
sa.Column("payload_json", sa.JSON(), nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||
sa.Column("updated_at", sa.DateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(["contract_id"], ["contract_payment_contracts.id"], ondelete="CASCADE"),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
sa.UniqueConstraint("source_request_id", name="uq_contract_payment_vendor_requests_source"),
|
||||
)
|
||||
op.create_index(
|
||||
"ix_contract_payment_vendor_requests_contract_stage",
|
||||
"contract_payment_vendor_requests",
|
||||
["contract_id", "payment_stage"],
|
||||
)
|
||||
op.add_column(
|
||||
"contract_payment_alerts",
|
||||
sa.Column("alert_round", sa.Integer(), nullable=False, server_default="1"),
|
||||
)
|
||||
op.drop_constraint("uq_contract_payment_alerts_trigger", "contract_payment_alerts", type_="unique")
|
||||
op.create_unique_constraint(
|
||||
"uq_contract_payment_alerts_trigger",
|
||||
"contract_payment_alerts",
|
||||
["node_id", "trigger_key", "recipient_user_id"],
|
||||
)
|
||||
|
||||
|
||||
def downgrade():
|
||||
"""回滚请款事实表和三轮预警收件人幂等字段。"""
|
||||
op.drop_constraint("uq_contract_payment_alerts_trigger", "contract_payment_alerts", type_="unique")
|
||||
op.create_unique_constraint(
|
||||
"uq_contract_payment_alerts_trigger",
|
||||
"contract_payment_alerts",
|
||||
["node_id", "trigger_key"],
|
||||
)
|
||||
op.drop_column("contract_payment_alerts", "alert_round")
|
||||
op.drop_table("contract_payment_vendor_requests")
|
||||
@@ -0,0 +1,25 @@
|
||||
"""merge contract payment warning migration head
|
||||
|
||||
Revision ID: i3d4e5f6a7b8
|
||||
Revises: 58915a6f02ff, h2c3d4e5f6a7
|
||||
|
||||
用途:合并既有数据库演进线与合同付款预警表演进线,确保部署只有一个 Alembic head。
|
||||
依赖:既有 58915a6f02ff head、合同付款预警 h2c3d4e5f6a7 head。
|
||||
逻辑:不变更任何表或数据;仅声明两条已完成迁移线在此收敛。
|
||||
"""
|
||||
|
||||
from alembic import op # noqa: F401 - Alembic migration module contract
|
||||
|
||||
|
||||
revision = "i3d4e5f6a7b8"
|
||||
down_revision = ("58915a6f02ff", "h2c3d4e5f6a7")
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""合并历史迁移头与合同付款预警迁移头,不执行数据库结构变更。"""
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""回退时由 Alembic 分别沿两条父迁移链继续处理。"""
|
||||
@@ -0,0 +1,205 @@
|
||||
"""create contract payment warning domain
|
||||
|
||||
Revision ID: j4e5f6a7b8c9
|
||||
Revises: 58915a6f02ff
|
||||
|
||||
用途:一次性创建合同付款预警域的合同、付款节点、OA 请款、逐笔预警和周汇总批次表。
|
||||
依赖:项目现有主迁移头 58915a6f02ff。
|
||||
逻辑:将此前拆分的基础表、流程编号、三轮收件人和周汇总演进合并为单一迁移,
|
||||
新部署只执行一次;合同编号允许先为空,OA 流程编号和申请人独立保存。
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy import inspect
|
||||
|
||||
|
||||
revision = "j4e5f6a7b8c9"
|
||||
down_revision = "58915a6f02ff"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""创建合同付款域全部业务表、索引和约束。"""
|
||||
# 历史部署曾通过 i3d4e5f6a7b8 及其父迁移创建过同名合同付款表。
|
||||
# 这些数据库只需要收敛版本图,不能再次执行整套 CREATE TABLE。
|
||||
if inspect(op.get_bind()).has_table("contract_payment_contracts"):
|
||||
return
|
||||
op.create_table(
|
||||
"contract_payment_contracts",
|
||||
sa.Column("id", sa.Integer(), nullable=False),
|
||||
sa.Column("contract_no", sa.String(length=128), nullable=True),
|
||||
sa.Column("purchase_order_no", sa.String(length=128), nullable=True),
|
||||
sa.Column("supplier_name", sa.String(length=255), nullable=True),
|
||||
sa.Column("applicant_name", sa.String(length=128), nullable=True),
|
||||
sa.Column("total_amount", sa.Numeric(precision=18, scale=2), nullable=True),
|
||||
sa.Column("currency", sa.String(length=16), nullable=True),
|
||||
sa.Column("effective_date", sa.Date(), nullable=True),
|
||||
sa.Column("delivery_due_date", sa.Date(), nullable=True),
|
||||
sa.Column("warranty_period_days", sa.Integer(), nullable=True),
|
||||
sa.Column("owner_user_id", sa.Integer(), nullable=True),
|
||||
sa.Column("oa_record_id", sa.String(length=128), nullable=True),
|
||||
sa.Column("workflow_no", sa.String(length=128), nullable=True),
|
||||
sa.Column("oa_archive_at", sa.DateTime(), nullable=True),
|
||||
sa.Column("status", sa.String(length=32), nullable=False, server_default="active"),
|
||||
sa.Column("parse_status", sa.String(length=32), nullable=False, server_default="pending"),
|
||||
sa.Column("plan_status", sa.String(length=32), nullable=False, server_default="pending"),
|
||||
sa.Column("source_payload_json", sa.JSON(), nullable=True),
|
||||
sa.Column("parse_result_json", sa.JSON(), nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||
sa.Column("updated_at", sa.DateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(["owner_user_id"], ["users.id"]),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
sa.UniqueConstraint("contract_no", name="uq_contract_payment_contracts_contract_no"),
|
||||
)
|
||||
op.create_index("ix_contract_payment_contracts_purchase_order_no", "contract_payment_contracts", ["purchase_order_no"])
|
||||
op.create_index("ix_contract_payment_contracts_status", "contract_payment_contracts", ["status"])
|
||||
op.create_index("ix_contract_payment_contracts_owner_user_id", "contract_payment_contracts", ["owner_user_id"])
|
||||
op.create_index("ix_contract_payment_contracts_oa_record_id", "contract_payment_contracts", ["oa_record_id"])
|
||||
op.create_index("ix_contract_payment_contracts_workflow_no", "contract_payment_contracts", ["workflow_no"])
|
||||
op.create_index("ix_contract_payment_contracts_parse_status", "contract_payment_contracts", ["parse_status"])
|
||||
op.create_index("ix_contract_payment_contracts_plan_status", "contract_payment_contracts", ["plan_status"])
|
||||
|
||||
op.create_table(
|
||||
"contract_payment_attachments",
|
||||
sa.Column("id", sa.Integer(), nullable=False),
|
||||
sa.Column("contract_id", sa.Integer(), nullable=False),
|
||||
sa.Column("source", sa.String(length=32), nullable=False),
|
||||
sa.Column("source_key", sa.String(length=512), nullable=False),
|
||||
sa.Column("file_name", sa.String(length=255), nullable=False),
|
||||
sa.Column("mime_type", sa.String(length=128), nullable=True),
|
||||
sa.Column("file_asset_id", sa.Integer(), nullable=True),
|
||||
sa.Column("dms_path", sa.String(length=1024), nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=True),
|
||||
sa.Column("metadata_json", sa.JSON(), nullable=True),
|
||||
sa.Column("status", sa.String(length=32), nullable=False, server_default="discovered"),
|
||||
sa.Column("created_record_at", sa.DateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(["contract_id"], ["contract_payment_contracts.id"], ondelete="CASCADE"),
|
||||
sa.ForeignKeyConstraint(["file_asset_id"], ["file_assets.id"]),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
sa.UniqueConstraint("contract_id", "source", "source_key", name="uq_contract_payment_attachments_source"),
|
||||
)
|
||||
op.create_index("ix_contract_payment_attachments_contract", "contract_payment_attachments", ["contract_id"])
|
||||
|
||||
op.create_table(
|
||||
"contract_payment_nodes",
|
||||
sa.Column("id", sa.Integer(), nullable=False),
|
||||
sa.Column("contract_id", sa.Integer(), nullable=False),
|
||||
sa.Column("node_code", sa.String(length=64), nullable=False),
|
||||
sa.Column("node_type", sa.String(length=32), nullable=False),
|
||||
sa.Column("amount", sa.Numeric(precision=18, scale=2), nullable=True),
|
||||
sa.Column("percentage", sa.Numeric(precision=8, scale=4), nullable=True),
|
||||
sa.Column("anchor_type", sa.String(length=32), nullable=True),
|
||||
sa.Column("anchor_date", sa.Date(), nullable=True),
|
||||
sa.Column("offset_days", sa.Integer(), nullable=False, server_default="0"),
|
||||
sa.Column("due_date", sa.Date(), nullable=True),
|
||||
sa.Column("reminder_days", sa.Integer(), nullable=False, server_default="14"),
|
||||
sa.Column("status", sa.String(length=32), nullable=False, server_default="pending"),
|
||||
sa.Column("evidence_json", sa.JSON(), nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||
sa.Column("updated_at", sa.DateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(["contract_id"], ["contract_payment_contracts.id"], ondelete="CASCADE"),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
sa.UniqueConstraint("contract_id", "node_code", name="uq_contract_payment_nodes_code"),
|
||||
)
|
||||
op.create_index("ix_contract_payment_nodes_due_date", "contract_payment_nodes", ["due_date", "status"])
|
||||
op.create_index("ix_contract_payment_nodes_contract_id", "contract_payment_nodes", ["contract_id"])
|
||||
|
||||
op.create_table(
|
||||
"contract_payment_events",
|
||||
sa.Column("id", sa.Integer(), nullable=False),
|
||||
sa.Column("contract_id", sa.Integer(), nullable=False),
|
||||
sa.Column("event_type", sa.String(length=32), nullable=False),
|
||||
sa.Column("event_date", sa.Date(), nullable=False),
|
||||
sa.Column("source_event_id", sa.String(length=128), nullable=False),
|
||||
sa.Column("payload_json", sa.JSON(), nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(["contract_id"], ["contract_payment_contracts.id"], ondelete="CASCADE"),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
sa.UniqueConstraint("event_type", "source_event_id", name="uq_contract_payment_events_source"),
|
||||
)
|
||||
op.create_index("ix_contract_payment_events_contract_type", "contract_payment_events", ["contract_id", "event_type"])
|
||||
|
||||
op.create_table(
|
||||
"contract_payment_vendor_requests",
|
||||
sa.Column("id", sa.Integer(), nullable=False),
|
||||
sa.Column("contract_id", sa.Integer(), nullable=False),
|
||||
sa.Column("source_request_id", sa.String(length=128), nullable=False),
|
||||
sa.Column("request_no", sa.String(length=128), nullable=True),
|
||||
sa.Column("payment_stage", sa.String(length=32), nullable=False),
|
||||
sa.Column("request_status", sa.String(length=64), nullable=True),
|
||||
sa.Column("requested_at", sa.DateTime(), nullable=True),
|
||||
sa.Column("payload_json", sa.JSON(), nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||
sa.Column("updated_at", sa.DateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(["contract_id"], ["contract_payment_contracts.id"], ondelete="CASCADE"),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
sa.UniqueConstraint("source_request_id", name="uq_contract_payment_vendor_requests_source"),
|
||||
)
|
||||
op.create_index("ix_contract_payment_vendor_requests_contract_stage", "contract_payment_vendor_requests", ["contract_id", "payment_stage"])
|
||||
|
||||
op.create_table(
|
||||
"contract_payment_alerts",
|
||||
sa.Column("id", sa.Integer(), nullable=False),
|
||||
sa.Column("contract_id", sa.Integer(), nullable=False),
|
||||
sa.Column("node_id", sa.Integer(), nullable=False),
|
||||
sa.Column("trigger_key", sa.String(length=64), nullable=False),
|
||||
sa.Column("scheduled_at", sa.DateTime(), nullable=True),
|
||||
sa.Column("sent_at", sa.DateTime(), nullable=True),
|
||||
sa.Column("recipient_user_id", sa.Integer(), nullable=True),
|
||||
sa.Column("alert_round", sa.Integer(), nullable=False, server_default="1"),
|
||||
sa.Column("status", sa.String(length=32), nullable=False, server_default="pending"),
|
||||
sa.Column("message_json", sa.JSON(), nullable=True),
|
||||
sa.Column("error_message", sa.Text(), nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(["contract_id"], ["contract_payment_contracts.id"], ondelete="CASCADE"),
|
||||
sa.ForeignKeyConstraint(["node_id"], ["contract_payment_nodes.id"], ondelete="CASCADE"),
|
||||
sa.ForeignKeyConstraint(["recipient_user_id"], ["users.id"]),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
sa.UniqueConstraint("node_id", "trigger_key", "recipient_user_id", name="uq_contract_payment_alerts_trigger"),
|
||||
)
|
||||
op.create_index("ix_contract_payment_alerts_status_scheduled", "contract_payment_alerts", ["status", "scheduled_at"])
|
||||
op.create_index("ix_contract_payment_alerts_contract_id", "contract_payment_alerts", ["contract_id"])
|
||||
op.create_index("ix_contract_payment_alerts_node_id", "contract_payment_alerts", ["node_id"])
|
||||
op.create_index("ix_contract_payment_alerts_recipient_user_id", "contract_payment_alerts", ["recipient_user_id"])
|
||||
|
||||
op.create_table(
|
||||
"contract_payment_alert_batches",
|
||||
sa.Column("id", sa.Integer(), nullable=False),
|
||||
sa.Column("batch_no", sa.String(length=64), nullable=False),
|
||||
sa.Column("week_key", sa.String(length=16), nullable=False),
|
||||
sa.Column("recipient_user_id", sa.Integer(), nullable=False),
|
||||
sa.Column("status", sa.String(length=32), nullable=False, server_default="pending"),
|
||||
sa.Column("summary_json", sa.JSON(), nullable=True),
|
||||
sa.Column("excel_file_name", sa.String(length=255), nullable=True),
|
||||
sa.Column("excel_file_data", sa.LargeBinary(), nullable=True),
|
||||
sa.Column("excel_file_size", sa.Integer(), nullable=True),
|
||||
sa.Column("sent_at", sa.DateTime(), nullable=True),
|
||||
sa.Column("wecom_trace_json", sa.JSON(), nullable=True),
|
||||
sa.Column("error_message", sa.Text(), nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(["recipient_user_id"], ["users.id"]),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
sa.UniqueConstraint("batch_no"),
|
||||
sa.UniqueConstraint("week_key", "recipient_user_id", name="uq_contract_payment_alert_batches_week_recipient"),
|
||||
)
|
||||
op.create_index("ix_contract_payment_alert_batches_status_created", "contract_payment_alert_batches", ["status", "created_at"])
|
||||
|
||||
# 历史首批数据曾将明确的 HT 流程号写入合同编号,合并迁移时一并纠正。
|
||||
op.execute(
|
||||
"UPDATE contract_payment_contracts "
|
||||
"SET workflow_no = contract_no, contract_no = NULL "
|
||||
"WHERE contract_no LIKE 'HT-%'"
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""按依赖逆序删除合同付款域全部表。"""
|
||||
op.drop_table("contract_payment_alert_batches")
|
||||
op.drop_table("contract_payment_alerts")
|
||||
op.drop_table("contract_payment_vendor_requests")
|
||||
op.drop_table("contract_payment_events")
|
||||
op.drop_table("contract_payment_nodes")
|
||||
op.drop_table("contract_payment_attachments")
|
||||
op.drop_table("contract_payment_contracts")
|
||||
@@ -0,0 +1,26 @@
|
||||
"""合并当前 Alembic 多头迁移。
|
||||
|
||||
用途:将历史修复、发货复核流和合同付款域三条并行迁移链收敛为单一 head,
|
||||
使 ``flask db upgrade`` 不再因 ``head`` 歧义而中止。
|
||||
依赖:``i3d4e5f6a7b8`` 和当前合同付款域迁移 ``j4e5f6a7b8c9``。
|
||||
逻辑:本迁移不修改业务表,仅建立 Alembic 图上的合并节点;三条父链的升级内容
|
||||
仍分别由各自迁移执行。
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = "k5f6a7b8c9d0"
|
||||
down_revision = ("i3d4e5f6a7b8", "hk5l6m7n8o9p", "j4e5f6a7b8c9")
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""合并迁移分支;不执行额外数据库 DDL。"""
|
||||
pass
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""撤销合并节点;不会回滚三个父分支的业务变更。"""
|
||||
pass
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
"""补齐历史合同付款库缺失的预警汇总批次表。
|
||||
|
||||
用途:修复旧版合同付款迁移已创建基础表、但因兼容路径跳过
|
||||
``contract_payment_alert_batches`` 的数据库。
|
||||
依赖:当前合并迁移头 ``k5f6a7b8c9d0``。
|
||||
逻辑:仅在目标表不存在时创建表和索引,保留已有合同付款数据;
|
||||
页面读取周预警汇总批次时不再触发 PostgreSQL UndefinedTable。
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy import inspect
|
||||
|
||||
|
||||
revision = "l6a7b8c9d0e1"
|
||||
down_revision = "k5f6a7b8c9d0"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""为历史库补建预警汇总批次表及其必要索引。"""
|
||||
if inspect(op.get_bind()).has_table("contract_payment_alert_batches"):
|
||||
return
|
||||
|
||||
op.create_table(
|
||||
"contract_payment_alert_batches",
|
||||
sa.Column("id", sa.Integer(), nullable=False),
|
||||
sa.Column("batch_no", sa.String(length=64), nullable=False),
|
||||
sa.Column("week_key", sa.String(length=16), nullable=False),
|
||||
sa.Column("recipient_user_id", sa.Integer(), nullable=False),
|
||||
sa.Column("status", sa.String(length=32), nullable=False, server_default="pending"),
|
||||
sa.Column("summary_json", sa.JSON(), nullable=True),
|
||||
sa.Column("excel_file_name", sa.String(length=255), nullable=True),
|
||||
sa.Column("excel_file_data", sa.LargeBinary(), nullable=True),
|
||||
sa.Column("excel_file_size", sa.Integer(), nullable=True),
|
||||
sa.Column("sent_at", sa.DateTime(), nullable=True),
|
||||
sa.Column("wecom_trace_json", sa.JSON(), nullable=True),
|
||||
sa.Column("error_message", sa.Text(), nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(["recipient_user_id"], ["users.id"]),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
sa.UniqueConstraint("batch_no"),
|
||||
sa.UniqueConstraint(
|
||||
"week_key",
|
||||
"recipient_user_id",
|
||||
name="uq_contract_payment_alert_batches_week_recipient",
|
||||
),
|
||||
)
|
||||
op.create_index(
|
||||
"ix_contract_payment_alert_batches_status_created",
|
||||
"contract_payment_alert_batches",
|
||||
["status", "created_at"],
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""仅删除由本迁移补建的预警汇总批次表。"""
|
||||
if inspect(op.get_bind()).has_table("contract_payment_alert_batches"):
|
||||
op.drop_table("contract_payment_alert_batches")
|
||||
@@ -0,0 +1,43 @@
|
||||
"""新增合同付款 OA 增量同步断点表。
|
||||
|
||||
用途:记录合同付款预警 OA 通知同步上次成功位置,作为时间窗口增量拉取的游标,
|
||||
避免每次全量重扫待办/已办列表;同一 state_key 只存一行,由唯一约束保证。
|
||||
依赖:当前合并迁移头 ``l6a7b8c9d0e1``。
|
||||
逻辑:仅在目标表不存在时创建;业务代码以 state_key 读写断点,供 sync_service 计算增量窗口。
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy import inspect
|
||||
|
||||
|
||||
revision = "m7e8f9a0b1c2"
|
||||
down_revision = "l6a7b8c9d0e1"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""为 OA 增量同步补建断点表,并保证 state_key 唯一。"""
|
||||
if inspect(op.get_bind()).has_table("contract_payment_sync_states"):
|
||||
return
|
||||
|
||||
op.create_table(
|
||||
"contract_payment_sync_states",
|
||||
sa.Column("id", sa.Integer(), nullable=False),
|
||||
sa.Column("state_key", sa.String(length=64), nullable=False),
|
||||
sa.Column("last_successful_sync_at", sa.DateTime(), nullable=True),
|
||||
sa.Column("last_archive_seen_at", sa.DateTime(), nullable=True),
|
||||
sa.Column("last_run_at", sa.DateTime(), nullable=True),
|
||||
sa.Column("synced_contract_count", sa.Integer(), nullable=False, server_default="0"),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||
sa.Column("updated_at", sa.DateTime(), nullable=False),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
sa.UniqueConstraint("state_key", name="uq_contract_payment_sync_states_state_key"),
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""删除 OA 增量同步断点表。"""
|
||||
if inspect(op.get_bind()).has_table("contract_payment_sync_states"):
|
||||
op.drop_table("contract_payment_sync_states")
|
||||
@@ -0,0 +1,26 @@
|
||||
"""合并合同付款与发货通知两条 Alembic 头。
|
||||
|
||||
用途:将 ``dev`` 上的发货通知 head 与 ``contract-payment`` 的增量同步 head 收成一条链,
|
||||
避免 ``flask db upgrade`` 因 Multiple head revisions 失败。
|
||||
依赖:``hw6x7y8z9a0b``(shipping_task_events.source 扩宽)、
|
||||
``m7e8f9a0b1c2``(contract_payment_sync_states)。
|
||||
逻辑:不修改业务表,只声明两条已完成迁移线在此收敛。
|
||||
"""
|
||||
|
||||
from alembic import op # noqa: F401 - Alembic migration module contract
|
||||
|
||||
|
||||
revision = "n8f9a0b1c2d3"
|
||||
down_revision = ("hw6x7y8z9a0b", "m7e8f9a0b1c2")
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""合并发货通知 head 与合同付款同步断点 head,不执行数据库结构变更。"""
|
||||
pass
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""撤销合并节点;不会回滚两个父分支的业务变更。"""
|
||||
pass
|
||||
@@ -0,0 +1,142 @@
|
||||
"""
|
||||
backend/scripts/reparse_contract_payment_contracts.py
|
||||
|
||||
用途:对存量采购合同付款预警台账重新执行合同解析,回填缺失/错误的金额、付款节点与解析状态。
|
||||
依赖:Flask create_app、contract_payment 模型、sync_service.build_payment_plan_from_bytes、file_assets.read_asset_bytes。
|
||||
逻辑:以「盖章完成合同上传」附件为权威来源(其次为第一个非辅助合同附件),读取已落库附件字节重跑解析;
|
||||
dry-run 只打印计划;单条失败不影响其他合同;本脚本不触发任何网络/OA 调用。
|
||||
|
||||
用法:
|
||||
cd backend
|
||||
python scripts/reparse_contract_payment_contracts.py --dry-run
|
||||
python scripts/reparse_contract_payment_contracts.py --contract-no 5203-2607310001
|
||||
python scripts/reparse_contract_payment_contracts.py --all --limit 200
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
_BACKEND_ROOT = Path(__file__).resolve().parents[1]
|
||||
_REPO_ROOT = _BACKEND_ROOT.parent
|
||||
if str(_BACKEND_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(_BACKEND_ROOT))
|
||||
|
||||
# 合同附件里可能混入的辅助文件关键字,不作为合同正文解析来源。
|
||||
_AUXILIARY_TOKENS = ("方案", "清单", "明细", "报价", "规格", "配置", "一览", "附件清单", "送货单", "报价单", "排产", "交期")
|
||||
|
||||
|
||||
def _prepare_env() -> None:
|
||||
"""导入 app 前固定 ENV_NAME=dev,并允许 .env.local 覆盖 DATABASE_URL。"""
|
||||
os.environ.setdefault("ENV_NAME", "dev")
|
||||
try:
|
||||
from dotenv import dotenv_values
|
||||
except ImportError:
|
||||
return
|
||||
local_file = _REPO_ROOT / ".env.local"
|
||||
if not local_file.exists():
|
||||
return
|
||||
values = {k: v for k, v in dotenv_values(local_file).items() if v is not None}
|
||||
if values.get("DATABASE_URL"):
|
||||
os.environ["DATABASE_URL"] = str(values["DATABASE_URL"])
|
||||
|
||||
|
||||
def _parse_args() -> argparse.Namespace:
|
||||
"""解析命令行:目标过滤、dry-run 与条数上限。"""
|
||||
parser = argparse.ArgumentParser(description="Re-parse stale/missing contract payment plans")
|
||||
parser.add_argument("--contract-no", action="append", default=[], help="仅处理指定合同编号(可重复)")
|
||||
parser.add_argument("--all", action="store_true", help="处理全部合同;缺省仅处理待复核或金额缺失的合同")
|
||||
parser.add_argument("--dry-run", action="store_true", help="只打印计划,不写库")
|
||||
parser.add_argument("--limit", type=int, default=0, help="最多处理条数;0 表示不限制")
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def _is_auxiliary(file_name: str) -> bool:
|
||||
"""按文件名判断是否为辅助文件(清单/方案/报价单等)。"""
|
||||
name = str(file_name or "").lower()
|
||||
return any(token in name for token in _AUXILIARY_TOKENS)
|
||||
|
||||
|
||||
def _pick_attachment(attachments: list) -> object:
|
||||
"""挑选解析所用附件:优先「盖章完成合同上传」,其次第一个非辅助合同附件。"""
|
||||
for attachment in attachments:
|
||||
if (attachment.metadata_json or {}).get("label") == "盖章完成合同上传":
|
||||
return attachment
|
||||
for attachment in attachments:
|
||||
if not _is_auxiliary(attachment.file_name):
|
||||
return attachment
|
||||
return attachments[0] if attachments else None
|
||||
|
||||
|
||||
def main() -> int:
|
||||
"""按范围重跑合同解析;返回 0 成功、1 有失败。"""
|
||||
_prepare_env()
|
||||
args = _parse_args()
|
||||
|
||||
from sqlalchemy import or_
|
||||
|
||||
from app import create_app, db
|
||||
from app.models import ContractPaymentAttachment, ContractPaymentContract, FileAsset
|
||||
from app.services.contract_payment.sync_service import build_payment_plan_from_bytes
|
||||
from app.services.file_assets.service import read_asset_bytes
|
||||
|
||||
app = create_app(os.environ.get("ENV_NAME", "dev"))
|
||||
failed = 0
|
||||
with app.app_context():
|
||||
query = db.session.query(ContractPaymentContract)
|
||||
if args.contract_no:
|
||||
query = query.filter(ContractPaymentContract.contract_no.in_(args.contract_no))
|
||||
elif not args.all:
|
||||
# 缺省只处理存量待复核/金额缺失的合同,避免无谓重跑已成功解析的合同。
|
||||
query = query.filter(
|
||||
or_(
|
||||
ContractPaymentContract.parse_status == "needs_review",
|
||||
ContractPaymentContract.total_amount.is_(None),
|
||||
)
|
||||
)
|
||||
query = query.order_by(ContractPaymentContract.id.asc())
|
||||
contracts = query.limit(args.limit).all() if args.limit else query.all()
|
||||
|
||||
print(f"待处理合同数:{len(contracts)}(dry-run={args.dry_run})")
|
||||
for contract in contracts:
|
||||
attachments = (
|
||||
db.session.query(ContractPaymentAttachment)
|
||||
.filter_by(contract_id=contract.id, source="oa", status="stored")
|
||||
.order_by(ContractPaymentAttachment.created_record_at.asc())
|
||||
.all()
|
||||
)
|
||||
if not attachments:
|
||||
print(f"[{contract.id}] {contract.contract_no or ''} 跳过:无已落库 OA 附件")
|
||||
continue
|
||||
target = _pick_attachment(attachments)
|
||||
if target is None or not target.file_asset_id:
|
||||
print(f"[{contract.id}] {contract.contract_no or ''} 跳过:附件未关联文件资产")
|
||||
continue
|
||||
asset = db.session.get(FileAsset, target.file_asset_id)
|
||||
if asset is None:
|
||||
print(f"[{contract.id}] {contract.contract_no or ''} 跳过:文件资产缺失")
|
||||
continue
|
||||
if args.dry_run:
|
||||
print(f"[{contract.id}] {contract.contract_no or ''} 计划:{target.file_name}")
|
||||
continue
|
||||
try:
|
||||
result = build_payment_plan_from_bytes(
|
||||
contract,
|
||||
filename=target.file_name,
|
||||
data=read_asset_bytes(asset),
|
||||
)
|
||||
db.session.commit()
|
||||
print(f"[{contract.id}] {contract.contract_no or ''} 成功 -> {result.get('status')}({target.file_name})")
|
||||
except Exception as exc: # noqa: BLE001
|
||||
db.session.rollback()
|
||||
failed += 1
|
||||
print(f"[{contract.id}] {contract.contract_no or ''} 失败:{exc}")
|
||||
|
||||
return 1 if failed else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -2,7 +2,11 @@
|
||||
tests/jobs/test_store.py
|
||||
|
||||
用途:验证 store.claim_next 归一化与空队列行为。
|
||||
依赖:通用 Job 队列、各 Worker 队列路由。
|
||||
逻辑:覆盖空队列、发货回收、合同付款超时回收和 Job 载荷归一化。
|
||||
"""
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from app.jobs.store import _normalize_generic_job, _normalize_kb_job
|
||||
from app.jobs.types import JobType
|
||||
from app.models import Job, KbJob
|
||||
@@ -78,6 +82,44 @@ def test_claim_next_shipping_claims_inventory_callback_process_job(app):
|
||||
assert claimed['job_type'] == JobType.SHIPPING_INVENTORY_CALLBACK_PROCESS
|
||||
|
||||
|
||||
def test_claim_next_contract_recovers_stale_contract_payment_sync_job(app):
|
||||
"""
|
||||
合同付款同步 Worker 在领取前应回收超时 Job,避免异常退出后任务永久停在 running。
|
||||
|
||||
核心逻辑:构造已超过合同付款超时阈值的 running Job;`claim_next` 先将其恢复为
|
||||
queued,再在同一轮领取为新的执行代次。
|
||||
"""
|
||||
from app import db
|
||||
from app.jobs import store
|
||||
|
||||
with app.app_context():
|
||||
app.config['CONTRACT_PAYMENT_JOB_TIMEOUT_SECONDS'] = 60
|
||||
stale_at = datetime.utcnow() - timedelta(seconds=61)
|
||||
job = Job(
|
||||
domain='procurement_contract',
|
||||
job_type=JobType.CONTRACT_PAYMENT_SYNC.value,
|
||||
status='running',
|
||||
attempts=1,
|
||||
max_attempts=3,
|
||||
started_at=stale_at,
|
||||
locked_at=stale_at,
|
||||
locked_by='stopped-worker',
|
||||
payload_json={},
|
||||
)
|
||||
db.session.add(job)
|
||||
db.session.commit()
|
||||
|
||||
claimed = store.claim_next(queues=['contract'])
|
||||
db.session.refresh(job)
|
||||
|
||||
# 关键断言:旧 running 任务被回收并以第二次执行代次重新领取,而非永久卡死。
|
||||
assert claimed is not None
|
||||
assert claimed['id'] == job.id
|
||||
assert job.status == 'running'
|
||||
assert job.attempts == 2
|
||||
assert job.locked_by != 'stopped-worker'
|
||||
|
||||
|
||||
def test_find_shipping_notice_job_id_matches_task_no(app):
|
||||
from app import db
|
||||
from app.jobs.queue import _find_shipping_notice_job_id
|
||||
|
||||
@@ -0,0 +1,311 @@
|
||||
"""
|
||||
backend/tests/test_contract_payment_acceptance_archive.py
|
||||
|
||||
用途:验证合同付款验收归档从 OA SQL 读取、按采购单号落库,以及事件先于节点时仍能回放日期。
|
||||
依赖:acceptance_oa_service、sync_service、ContractPayment* 模型。
|
||||
逻辑:SQL 与 OA 连接一律 mock,不访问真实 ecology 库;覆盖 JOIN/currentnodetype=3/cgdh、幂等、无合同跳过、节点后生成回放。
|
||||
"""
|
||||
|
||||
from datetime import date, datetime
|
||||
from decimal import Decimal
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ContractPaymentContract,
|
||||
ContractPaymentEvent,
|
||||
ContractPaymentNode,
|
||||
)
|
||||
from app.services.contract_payment.acceptance_oa_service import (
|
||||
build_archived_acceptance_sql,
|
||||
fetch_archived_acceptances,
|
||||
parse_oa_archive_at,
|
||||
source_event_id,
|
||||
)
|
||||
from app.services.contract_payment.sync_service import (
|
||||
ingest_acceptance_archives,
|
||||
refresh_acceptance_nodes_from_events,
|
||||
_persist_payment_plan,
|
||||
sync_notifications,
|
||||
)
|
||||
|
||||
|
||||
class _FakeCursor:
|
||||
"""记录 SQL 参数并返回预设行,模拟 pyodbc cursor。"""
|
||||
|
||||
def __init__(self, rows):
|
||||
self.rows = rows
|
||||
self.sql = ""
|
||||
self.params = None
|
||||
|
||||
def execute(self, sql, params=None):
|
||||
self.sql = sql
|
||||
self.params = list(params or [])
|
||||
|
||||
def fetchall(self):
|
||||
return self.rows
|
||||
|
||||
|
||||
class _FakeConnection:
|
||||
def __init__(self, cursor):
|
||||
self._cursor = cursor
|
||||
self.closed = False
|
||||
|
||||
def cursor(self):
|
||||
return self._cursor
|
||||
|
||||
def close(self):
|
||||
self.closed = True
|
||||
|
||||
|
||||
def test_acceptance_sql_joins_form_and_archived_nodetype():
|
||||
"""关键断言:查询 JOIN 验收主表与流程主表,并以 currentnodetype=3、非空 cgdh 过滤。"""
|
||||
sql, params = build_archived_acceptance_sql(
|
||||
table="formtable_main_324",
|
||||
po_field="cgdh",
|
||||
request_id_field="requestId",
|
||||
node_type="3",
|
||||
since=datetime(2026, 8, 1, 12, 0, 0),
|
||||
purchase_order_nos=["PO-1"],
|
||||
)
|
||||
|
||||
assert "[formtable_main_324]" in sql
|
||||
assert "[workflow_requestbase]" in sql
|
||||
assert "w.[requestid] = f.[requestId]" in sql
|
||||
assert "w.[currentnodetype]" in sql
|
||||
assert "w.[status]" not in sql
|
||||
assert "f.[cgdh]" in sql
|
||||
assert "IN (?)" in sql
|
||||
assert params[0] == "3"
|
||||
assert "2026-08-01" in params
|
||||
assert "PO-1" in params
|
||||
|
||||
|
||||
def test_parse_oa_archive_at_combines_ecology_date_time():
|
||||
"""关键断言:归档日使用 lastoperatedate+lastoperatetime,兼容无分隔日期。"""
|
||||
assert parse_oa_archive_at("2026-08-01", "16:32:01") == datetime(2026, 8, 1, 16, 32, 1)
|
||||
assert parse_oa_archive_at("20260801", "163201") == datetime(2026, 8, 1, 16, 32, 1)
|
||||
assert parse_oa_archive_at("2026/08/01", None) == datetime(2026, 8, 1, 0, 0, 0)
|
||||
|
||||
|
||||
def test_fetch_archived_acceptances_maps_cgdh_and_request_id(app, monkeypatch):
|
||||
"""关键断言:游标行映射为 request_id + 采购单号 + 归档时间,并关闭连接。"""
|
||||
cursor = _FakeCursor([
|
||||
(32401, " PO-ACC-1 ", "3", "2026-08-01", "10:00:00", "2026-07-01", "09:00:00"),
|
||||
(None, "PO-SKIP", "3", "2026-08-02", "10:00:00", None, None),
|
||||
])
|
||||
conn = _FakeConnection(cursor)
|
||||
|
||||
with app.app_context():
|
||||
monkeypatch.setattr(
|
||||
"app.services.contract_payment.acceptance_oa_service.OASQLServerService._connect",
|
||||
lambda *args, **kwargs: conn,
|
||||
)
|
||||
events, ok = fetch_archived_acceptances(since=None)
|
||||
|
||||
assert ok is True
|
||||
assert conn.closed is True
|
||||
assert len(events) == 1
|
||||
assert events[0]["request_id"] == "32401"
|
||||
assert events[0]["purchase_order_no"] == "PO-ACC-1"
|
||||
assert events[0]["currentnodetype"] == "3"
|
||||
assert events[0]["archive_at"] == "2026-08-01 10:00:00"
|
||||
assert "formtable_main_324" in cursor.sql
|
||||
assert "currentnodetype" in cursor.sql
|
||||
assert cursor.params == ["3"]
|
||||
|
||||
|
||||
def test_ingest_acceptance_matches_purchase_order_and_is_idempotent(app):
|
||||
"""关键断言:按 cgdh=采购单号落库;无合同跳过;同一 requestId 重复同步不新增事件。"""
|
||||
with app.app_context():
|
||||
contract = ContractPaymentContract(
|
||||
contract_no="HT-ACC-1",
|
||||
purchase_order_no="PO-ACC-1",
|
||||
)
|
||||
db.session.add(contract)
|
||||
db.session.flush()
|
||||
|
||||
items = [
|
||||
{
|
||||
"request_id": "32401",
|
||||
"purchase_order_no": "PO-ACC-1",
|
||||
"archive_at": "2026-08-01 10:00:00",
|
||||
"currentnodetype": "3",
|
||||
},
|
||||
{
|
||||
"request_id": "32402",
|
||||
"purchase_order_no": "PO-MISSING",
|
||||
"archive_at": "2026-08-02 10:00:00",
|
||||
"currentnodetype": "3",
|
||||
},
|
||||
]
|
||||
created, skipped = ingest_acceptance_archives(items)
|
||||
created_again, skipped_again = ingest_acceptance_archives(items)
|
||||
events = db.session.query(ContractPaymentEvent).filter_by(contract_id=contract.id).all()
|
||||
|
||||
assert created == 1
|
||||
assert skipped == 1
|
||||
assert created_again == 0
|
||||
assert skipped_again == 1
|
||||
assert len(events) == 1
|
||||
assert events[0].event_type == "acceptance_archive"
|
||||
assert events[0].event_date == date(2026, 8, 1)
|
||||
assert events[0].source_event_id == source_event_id("32401", contract.id)
|
||||
|
||||
|
||||
def test_persist_plan_replays_existing_acceptance_event(app):
|
||||
"""关键断言:验收事件先入库、节点后解析时,验收款/质保款仍能用归档日计算。"""
|
||||
with app.app_context():
|
||||
contract = ContractPaymentContract(
|
||||
contract_no="HT-ACC-REPLAY",
|
||||
purchase_order_no="PO-ACC-REPLAY",
|
||||
)
|
||||
db.session.add(contract)
|
||||
db.session.flush()
|
||||
db.session.add(ContractPaymentEvent(
|
||||
contract_id=contract.id,
|
||||
event_type="acceptance_archive",
|
||||
event_date=date(2026, 8, 1),
|
||||
source_event_id=source_event_id("9001", contract.id),
|
||||
payload_json={"purchase_order_no": "PO-ACC-REPLAY"},
|
||||
))
|
||||
db.session.flush()
|
||||
|
||||
_persist_payment_plan(contract, result={
|
||||
"status": "parsed",
|
||||
"fields": {"warranty_period_days": 365},
|
||||
"nodes": [
|
||||
{
|
||||
"node_code": "acceptance",
|
||||
"node_type": "acceptance",
|
||||
"amount": "100.00",
|
||||
"percentage": "20",
|
||||
"anchor_type": "acceptance_archive",
|
||||
"due_date": None,
|
||||
"evidence": {},
|
||||
},
|
||||
{
|
||||
"node_code": "warranty",
|
||||
"node_type": "warranty",
|
||||
"amount": "50.00",
|
||||
"percentage": "10",
|
||||
"anchor_type": "acceptance_archive",
|
||||
"due_date": None,
|
||||
"evidence": {},
|
||||
},
|
||||
],
|
||||
"issues": [],
|
||||
})
|
||||
acceptance = db.session.query(ContractPaymentNode).filter_by(
|
||||
contract_id=contract.id, node_type="acceptance"
|
||||
).one()
|
||||
warranty = db.session.query(ContractPaymentNode).filter_by(
|
||||
contract_id=contract.id, node_type="warranty"
|
||||
).one()
|
||||
|
||||
assert acceptance.anchor_date == date(2026, 8, 1)
|
||||
assert acceptance.due_date == date(2026, 8, 1)
|
||||
assert warranty.anchor_date == date(2026, 8, 1)
|
||||
assert warranty.due_date == date(2027, 8, 1)
|
||||
|
||||
|
||||
def test_refresh_keeps_earliest_archive_date(app):
|
||||
"""关键断言:多张验收单取最早归档日,后到事件不得把锚点推后。"""
|
||||
with app.app_context():
|
||||
contract = ContractPaymentContract(
|
||||
contract_no="HT-ACC-MIN",
|
||||
purchase_order_no="PO-ACC-MIN",
|
||||
warranty_period_days=30,
|
||||
)
|
||||
db.session.add(contract)
|
||||
db.session.flush()
|
||||
db.session.add(ContractPaymentNode(
|
||||
contract_id=contract.id,
|
||||
node_code="acceptance",
|
||||
node_type="acceptance",
|
||||
amount=Decimal("100.00"),
|
||||
percentage=Decimal("20"),
|
||||
anchor_date=date(2026, 7, 1),
|
||||
due_date=date(2026, 7, 1),
|
||||
status="active",
|
||||
))
|
||||
db.session.add(ContractPaymentEvent(
|
||||
contract_id=contract.id,
|
||||
event_type="acceptance_archive",
|
||||
event_date=date(2026, 8, 15),
|
||||
source_event_id="later",
|
||||
))
|
||||
db.session.add(ContractPaymentEvent(
|
||||
contract_id=contract.id,
|
||||
event_type="acceptance_archive",
|
||||
event_date=date(2026, 7, 1),
|
||||
source_event_id="earlier",
|
||||
))
|
||||
refresh_acceptance_nodes_from_events(contract)
|
||||
node = db.session.query(ContractPaymentNode).filter_by(
|
||||
contract_id=contract.id, node_type="acceptance"
|
||||
).one()
|
||||
|
||||
assert node.anchor_date == date(2026, 7, 1)
|
||||
|
||||
|
||||
def test_sync_notifications_ingests_sql_acceptance(app, monkeypatch):
|
||||
"""关键断言:合同 HTTP 同步后按采购单号吞入 OA SQL 验收归档,并推进独立断点。"""
|
||||
with app.app_context():
|
||||
contract = ContractPaymentContract(
|
||||
contract_no="HT-ACC-SYNC",
|
||||
purchase_order_no="PO-ACC-SYNC",
|
||||
)
|
||||
db.session.add(contract)
|
||||
db.session.flush()
|
||||
db.session.add(ContractPaymentNode(
|
||||
contract_id=contract.id,
|
||||
node_code="acceptance",
|
||||
node_type="acceptance",
|
||||
amount=Decimal("10.00"),
|
||||
percentage=Decimal("20"),
|
||||
status="active",
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
class FakeClient:
|
||||
def configuration_status(self):
|
||||
return {
|
||||
"configured": True,
|
||||
"list_configured": True,
|
||||
"missing": [],
|
||||
"attachment_template_configured": False,
|
||||
}
|
||||
|
||||
def fetch_notifications(self, *, since=None):
|
||||
return [], False
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.contract_payment.sync_service.fetch_archived_acceptances",
|
||||
lambda **_kwargs: (
|
||||
[{
|
||||
"request_id": "551",
|
||||
"purchase_order_no": "PO-ACC-SYNC",
|
||||
"archive_at": "2026-08-01 08:00:00",
|
||||
"currentnodetype": "3",
|
||||
}],
|
||||
True,
|
||||
),
|
||||
)
|
||||
result = sync_notifications(client=FakeClient())
|
||||
event = db.session.query(ContractPaymentEvent).filter_by(
|
||||
event_type="acceptance_archive"
|
||||
).one()
|
||||
node = db.session.query(ContractPaymentNode).filter_by(
|
||||
contract_id=contract.id, node_type="acceptance"
|
||||
).one()
|
||||
from app.models import ContractPaymentSyncState
|
||||
acc_state = db.session.query(ContractPaymentSyncState).filter_by(
|
||||
state_key="oa-acceptance-archive"
|
||||
).one()
|
||||
|
||||
assert result["acceptance_found"] == 1
|
||||
assert result["acceptance_saved"] == 1
|
||||
assert result["acceptance_error"] is False
|
||||
assert event.source_event_id == source_event_id("551", contract.id)
|
||||
assert node.anchor_date == date(2026, 8, 1)
|
||||
assert acc_state.last_successful_sync_at is not None
|
||||
@@ -0,0 +1,578 @@
|
||||
"""
|
||||
backend/tests/test_contract_payment_parse.py
|
||||
|
||||
用途:验证合同付款预警解析器、三轮预警升级、ERP 金额匹配及周汇总摘要。
|
||||
依赖:contract_payment.parse_service、alert_service、erp_payment_service、supervisor_oa_service(三轮测试 mock)。
|
||||
逻辑:覆盖确定性解析边界、pending 计数与下一次周五 18:00;三轮升级 mock OA 矩阵,不调用外部 OA、文档库或企业微信。
|
||||
"""
|
||||
|
||||
from datetime import date, datetime
|
||||
from decimal import Decimal
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ContractPaymentContract,
|
||||
ContractPaymentAttachment,
|
||||
ContractPaymentAlert,
|
||||
ContractPaymentNode,
|
||||
User,
|
||||
)
|
||||
from app.services.contract_payment.alert_service import (
|
||||
bind_contract_owner_from_applicant,
|
||||
build_weekly_alert_summary,
|
||||
generate_alerts,
|
||||
)
|
||||
from app.services.contract_payment import parse_service
|
||||
from app.services.contract_payment.parse_service import parse_contract_bytes, parse_contract_text
|
||||
from app.services.contract_payment.dms_client import ContractDmsClient
|
||||
from app.services.contract_payment.oa_client import ContractOaClient
|
||||
from app.services.contract_payment.erp_payment_service import resolve_paid_node_ids
|
||||
from app.services.contract_payment.sync_service import _overwrite_oa_fields, _with_force_sync_audit
|
||||
from app.services.contract_payment.sync_service import _persist_payment_plan, save_oa_attachments
|
||||
|
||||
|
||||
def test_force_oa_sync_overwrites_only_non_empty_values_and_keeps_audit():
|
||||
"""关键断言:强制同步只覆盖 OA 明确返回字段,且最新原始载荷不会丢失金额变更审计。"""
|
||||
contract = ContractPaymentContract(
|
||||
purchase_order_no="PO-OLD",
|
||||
supplier_name="旧供应商",
|
||||
total_amount=Decimal("100.00"),
|
||||
currency="人民币",
|
||||
source_payload_json={"source_event_id": "old-event"},
|
||||
)
|
||||
|
||||
changed = _overwrite_oa_fields(contract, {
|
||||
"purchase_order_no": "PO-NEW",
|
||||
"supplier_name": "",
|
||||
"total_amount": Decimal("200.00"),
|
||||
"currency": None,
|
||||
}, operator_id=42)
|
||||
payload = _with_force_sync_audit({"source_event_id": "new-event"}, contract.source_payload_json)
|
||||
|
||||
# 非空 OA 值覆盖,空值不清空原合同事实。
|
||||
assert changed == 2
|
||||
assert contract.purchase_order_no == "PO-NEW"
|
||||
assert contract.supplier_name == "旧供应商"
|
||||
assert contract.currency == "人民币"
|
||||
assert payload["source_event_id"] == "new-event"
|
||||
assert payload["force_sync_audit"][0]["operator_id"] == 42
|
||||
assert payload["force_sync_audit"][0]["changed_fields"]["total_amount"] == {
|
||||
"before": "100.00", "after": "200.00",
|
||||
}
|
||||
|
||||
|
||||
def test_payment_plan_requires_purchase_order_for_automatic_alerts(app):
|
||||
"""关键断言:采购单号缺失时,解析结果不能进入自动付款预警台账。"""
|
||||
with app.app_context():
|
||||
contract = ContractPaymentContract(contract_no="HT-PO-MISSING")
|
||||
db.session.add(contract)
|
||||
db.session.flush()
|
||||
|
||||
result = _persist_payment_plan(contract, result={
|
||||
"status": "parsed",
|
||||
"fields": {},
|
||||
"nodes": [],
|
||||
"issues": [],
|
||||
})
|
||||
|
||||
# persist 会 commit;断言须在 app_context 内读取 ORM 字段。
|
||||
assert result["status"] == "needs_review"
|
||||
assert "采购单号无法识别" in result["issues"]
|
||||
assert contract.parse_status == "needs_review"
|
||||
assert contract.plan_status == "needs_review"
|
||||
|
||||
|
||||
def test_normal_oa_sync_does_not_overwrite_a_single_contract_reparse(app, monkeypatch):
|
||||
"""关键断言:已归档附件在普通 OA 同步中不再重解析,避免覆盖单合同重解析结果。"""
|
||||
with app.app_context():
|
||||
contract = ContractPaymentContract(
|
||||
contract_no="HT-SINGLE-REPARSE",
|
||||
owner_user_id=1,
|
||||
parse_status="parsed",
|
||||
plan_status="active",
|
||||
)
|
||||
db.session.add(contract)
|
||||
db.session.flush()
|
||||
db.session.add(ContractPaymentAttachment(
|
||||
contract_id=contract.id,
|
||||
source="oa",
|
||||
source_key="oa:sealed-1",
|
||||
file_name="盖章合同.pdf",
|
||||
file_asset_id=1,
|
||||
status="stored",
|
||||
))
|
||||
db.session.flush()
|
||||
monkeypatch.setattr(
|
||||
'app.services.contract_payment.sync_service.build_payment_plan_from_bytes',
|
||||
lambda *_args, **_kwargs: (_ for _ in ()).throw(AssertionError("普通 OA 同步不应重新解析已归档附件")),
|
||||
)
|
||||
|
||||
result = save_oa_attachments(
|
||||
contract,
|
||||
item={"attachments": [{"attachment_id": "sealed-1", "file_name": "盖章合同.pdf", "priority": 0}]},
|
||||
client=object(),
|
||||
)
|
||||
|
||||
assert result == {"found": 1, "saved": 0}
|
||||
assert contract.parse_status == "parsed"
|
||||
|
||||
|
||||
def test_parse_standard_payment_plan():
|
||||
"""关键断言:预付款纳入节点,出货款到期锚点为交货期限,金额按比例计算。"""
|
||||
result = parse_contract_text(
|
||||
"设备采购合同;合同编号:HT-2026-0001;设备总价款(含税):100,000元;"
|
||||
"预付款10%;出货款在2026年8月20日前支付50%;验收款20%;质保款20%;质保期12个月。"
|
||||
)
|
||||
assert result["status"] == "parsed"
|
||||
assert result["fields"]["delivery_due_date"] == "2026-08-20"
|
||||
shipment = next(item for item in result["nodes"] if item["node_type"] == "shipment")
|
||||
assert shipment["amount"] == "50000.00"
|
||||
assert shipment["due_date"] == "2026-08-20"
|
||||
assert shipment["anchor_type"] == "erp_payment"
|
||||
|
||||
|
||||
def test_scanned_pdf_prefers_mineru_markdown_for_payment_plan(app, monkeypatch):
|
||||
"""关键断言:扫描 PDF 配置 MinerU 后直接使用 Markdown,不再调用旧文字层或 OCR。"""
|
||||
class MinerUResponse:
|
||||
def raise_for_status(self):
|
||||
return None
|
||||
|
||||
def json(self):
|
||||
return {
|
||||
"status": "completed",
|
||||
"results": {"sealed-contract": {"md_content": (
|
||||
"# 设备采购合同\n合同号:HT-2026-009;合同总价:100,000元;"
|
||||
"预付款10%;出货款40%;验收款40%;质保款10%;交货期:2026年09月01日。"
|
||||
)}},
|
||||
}
|
||||
|
||||
with app.app_context():
|
||||
app.config.update(PROCUREMENT_CONTRACT_MINERU_API_URL="http://mineru.example")
|
||||
monkeypatch.setattr(parse_service, "extract_text_from_bytes", lambda *_: "[binary:pdf]")
|
||||
monkeypatch.setattr(parse_service, "_extract_ocr_text", lambda *_: (_ for _ in ()).throw(AssertionError("不应调用旧 OCR")))
|
||||
monkeypatch.setattr(parse_service.requests, "post", lambda *args, **kwargs: MinerUResponse())
|
||||
result = parse_contract_bytes("盖章合同.pdf", b"scanned-pdf")
|
||||
|
||||
assert result["status"] == "parsed"
|
||||
assert result["evidence"]["document_extractor"] == "mineru"
|
||||
|
||||
|
||||
def test_parse_missing_delivery_is_review():
|
||||
"""关键断言:无法确认交货期限时不能生成正式出货款提醒。"""
|
||||
result = parse_contract_text("合同总价:100,000元;出货款50%;验收款20%。")
|
||||
assert result["status"] == "needs_review"
|
||||
assert "合同交货期限无法识别" in result["issues"]
|
||||
|
||||
|
||||
def test_parse_pdf_contract_clause_extracts_contract_no_and_payment_terms():
|
||||
"""关键断言:合同号来自正文,金额、四段付款比例与付款质保期均能识别。"""
|
||||
result = parse_contract_text(
|
||||
"设备采购合同\n合同号:20260729\n"
|
||||
"设备总价款(含税):¥264,800 元整\n"
|
||||
"预付款:¥79,440 元整(总价款的 30%)\n"
|
||||
"出货款:¥79,440 元整(总价款的 30 %)\n"
|
||||
"验收款(总价款的 30 %)¥79,440 元整\n"
|
||||
"质保款(总价款的 10%)¥26,480 元整\n"
|
||||
"交货期限:乙方应于 2026 年 09 月 11 日前将设备送达交货地点。\n"
|
||||
"从验收合格日起算 12 个月质保期满后支付。\n"
|
||||
"保固 贰 年"
|
||||
)
|
||||
assert result["status"] == "parsed"
|
||||
assert result["fields"]["contract_no"] == "20260729"
|
||||
assert result["fields"]["total_amount"] == "264800"
|
||||
assert result["fields"]["warranty_period_days"] == 360
|
||||
assert {node["node_type"]: node["percentage"] for node in result["nodes"]} == {
|
||||
"prepayment": "30",
|
||||
"shipment": "30",
|
||||
"acceptance": "30",
|
||||
"warranty": "10",
|
||||
}
|
||||
|
||||
|
||||
def test_payment_plan_requires_all_payment_ratios_to_total_one_hundred():
|
||||
"""关键断言:无论合同措辞如何,四阶段比例仍必须完整且合计为 100%。"""
|
||||
result = parse_contract_text(
|
||||
"设备采购合同\n合同编号:HT-2026-001\n设备总价款(含税):100,000元\n"
|
||||
"预付款30%;出货款35%;验收款35%;质保款5%;交货期限:2026年09月01日。"
|
||||
)
|
||||
|
||||
assert result["status"] == "needs_review"
|
||||
assert "四阶段付款比例合计不等于100%" in result["issues"]
|
||||
|
||||
|
||||
def test_non_template_contract_can_be_parsed_when_required_facts_are_complete():
|
||||
"""关键断言:不再以 V4 固定模板作为准入条件,完整四阶段条款可正常进入台账。"""
|
||||
result = parse_contract_text(
|
||||
"采购协议 合同号:HT-2026-002;合同总价:100,000元;"
|
||||
"预付款10%;出货款40%;验收款40%;尾款10%;交货期:2026年09月01日。"
|
||||
)
|
||||
|
||||
assert result["status"] == "parsed"
|
||||
|
||||
|
||||
def test_missing_payment_stages_do_not_report_removed_template_match_rule():
|
||||
"""关键断言:付款阶段缺失只报告真实条款问题,不再报告固定模板不匹配。"""
|
||||
result = parse_contract_text("采购协议 合同号:HT-2026-003;合同总价:100,000元;预付款100%;交货期:2026年09月01日。")
|
||||
|
||||
assert result["status"] == "needs_review"
|
||||
assert "付款阶段比例无法识别:出货款、验收款、质保款" in result["issues"]
|
||||
assert not any("固定模板" in issue for issue in result["issues"])
|
||||
|
||||
|
||||
def test_repeated_same_shipment_percentage_is_not_reported_six_times():
|
||||
"""关键断言:MinerU 把出货款同一比例抽到多次时,只保留一条事实,不连写「比例重复」。"""
|
||||
repeated = ";".join(["出货款30%"] * 7)
|
||||
result = parse_contract_text(
|
||||
f"采购协议 合同号:HT-2026-004;合同总价:100,000元;{repeated};交货期:2026年09月01日。"
|
||||
)
|
||||
|
||||
duplicate_issues = [issue for issue in result["issues"] if "出货款付款比例重复" in issue]
|
||||
assert duplicate_issues == []
|
||||
shipment = next(item for item in result["nodes"] if item["node_type"] == "shipment")
|
||||
assert shipment["percentage"] == "30"
|
||||
|
||||
|
||||
def test_conflicting_shipment_percentages_report_duplicate_once():
|
||||
"""关键断言:出货款出现 30% 与 40% 两种比例时,只报一条重复原因。"""
|
||||
result = parse_contract_text(
|
||||
"采购协议 合同号:HT-2026-005;合同总价:100,000元;"
|
||||
"出货款30%;出货款40%;出货款30%;交货期:2026年09月01日。"
|
||||
)
|
||||
|
||||
duplicate_issues = [issue for issue in result["issues"] if issue == "出货款付款比例重复,需人工确认"]
|
||||
assert duplicate_issues == ["出货款付款比例重复,需人工确认"]
|
||||
assert not any(node["node_type"] == "shipment" for node in result["nodes"])
|
||||
|
||||
|
||||
def test_dms_resolve_year_folder_uses_configured_root(app, monkeypatch):
|
||||
"""关键断言:DMS 先用根 FolderID 查年份目录,并返回目录记录 ID。"""
|
||||
app.config.update(
|
||||
CONTRACT_DMS_BASE_URL="http://dms.example",
|
||||
CONTRACT_DMS_USERNAME="contract-user",
|
||||
CONTRACT_DMS_PASSWORD="secret",
|
||||
CONTRACT_DMS_LIBRARY_ID="library-1",
|
||||
CONTRACT_DMS_ROOT_FOLDER_ID="root-1",
|
||||
CONTRACT_DMS_YEAR_FOLDER_NAME_TEMPLATE="{year}年设备合同书",
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
ContractDmsClient,
|
||||
"_page",
|
||||
classmethod(lambda cls, **kwargs: [{"IsFolder": True, "LeafName": "2026年设备合同书", "ID": "year-2026"}]),
|
||||
)
|
||||
from datetime import date
|
||||
|
||||
assert ContractDmsClient.resolve_folder(archive_date=date(2026, 8, 1)) == "year-2026"
|
||||
|
||||
|
||||
def test_dms_search_filters_created_date_window(app, monkeypatch):
|
||||
"""关键断言:同合同编号文件按 OA 归档日期窗口筛选,过期文件不返回。"""
|
||||
app.config.update(
|
||||
CONTRACT_DMS_BASE_URL="http://dms.example",
|
||||
CONTRACT_DMS_USERNAME="contract-user",
|
||||
CONTRACT_DMS_PASSWORD="secret",
|
||||
CONTRACT_DMS_LIBRARY_ID="library-1",
|
||||
CONTRACT_DMS_ROOT_FOLDER_ID="root-1",
|
||||
CONTRACT_DMS_LOOKUP_WINDOW_DAYS=3,
|
||||
)
|
||||
monkeypatch.setattr(ContractDmsClient, "resolve_folder", classmethod(lambda cls, **kwargs: "year-1"))
|
||||
monkeypatch.setattr(
|
||||
ContractDmsClient,
|
||||
"_page",
|
||||
classmethod(
|
||||
lambda cls, **kwargs: [
|
||||
{"IsFolder": False, "LeafName": "合同-A.pdf", "CreatedDate": "2026-08-01T10:00:00", "ID": "new"},
|
||||
{"IsFolder": False, "LeafName": "合同-A.pdf", "CreatedDate": "2025-01-01T10:00:00", "ID": "old"},
|
||||
]
|
||||
if kwargs.get("parent_folder_id") == "year-1"
|
||||
else [{"IsFolder": True, "LeafName": "暂存", "ID": "temp-1"}],
|
||||
),
|
||||
)
|
||||
from datetime import date
|
||||
|
||||
rows = ContractDmsClient.search(contract_no="合同-A", archive_date=date(2026, 8, 1))
|
||||
assert [row["ID"] for row in rows] == ["new"]
|
||||
|
||||
|
||||
def test_oa_contract_detail_parses_fields_and_prefers_sealed_attachment(app):
|
||||
"""关键断言:盖章上传字段优先,即使普通附件文件名更像合同正文。"""
|
||||
app.config.update(
|
||||
CONTRACT_PAYMENT_OA_BASE_URL="http://oa.example",
|
||||
CONTRACT_PAYMENT_OA_ATTACHMENT_URL_TEMPLATE="/workflow/download?attachmentid={attachment_id}",
|
||||
)
|
||||
page = """
|
||||
<html><body>
|
||||
<h1>流程处理 - 合同申请单 - 归档 HT-20260806-30062-0</h1>
|
||||
<table>
|
||||
<tr><td>合同单位</td><td>测试供应商有限公司</td><td>采购单号</td><td>PO-001</td><td>申请人</td><td>张三</td></tr>
|
||||
<tr><td>合同金额</td><td>221,000.00</td><td>合同书币别</td><td>人民币</td></tr>
|
||||
<tr><td>合同生效日期</td><td>2026-08-06</td><td>约定到货日期</td><td>2026-09-01</td></tr>
|
||||
<tr><td>合同附件</td><td><a onclick=\"downloadFile('normal-1')\">采购合同正文.pdf</a></td></tr>
|
||||
<tr><td>盖章完成合同上传</td><td><a onclick=\"downloadFile('sealed-1')\">双泵压缩机方案.pdf</a></td></tr>
|
||||
</table>
|
||||
</body></html>
|
||||
"""
|
||||
with app.app_context():
|
||||
result = ContractOaClient()._parse_detail_html(page, base_url="http://oa.example/workflow/detail")
|
||||
|
||||
# 流程编号来自 OA 表单;真实合同编号只能由附件正文解析得到。
|
||||
assert result["contract_no"] == ""
|
||||
assert result["workflow_no"] == "HT-20260806-30062-0"
|
||||
assert result["purchase_order_no"] == "PO-001"
|
||||
assert result["applicant_name"] == "张三"
|
||||
assert result["total_amount"] == "221000.00"
|
||||
# 关键断言:生产 OA 的“合同书币别”标签应映射到合同台账币别。
|
||||
assert result["currency"] == "人民币"
|
||||
assert result["delivery_due_date"] == "2026-09-01"
|
||||
# 字段语义高于文件名关键词:盖章上传文件必须是第一个下载候选。
|
||||
assert [item["attachment_id"] for item in result["attachments"]] == ["sealed-1", "normal-1"]
|
||||
|
||||
|
||||
def test_oa_contract_event_uses_process_id_as_idempotency_key():
|
||||
"""关键断言:待办被查看并转入已办时,流程 ID 不变,因此生成相同的幂等事件键。"""
|
||||
event = ContractOaClient._build_contract_event(
|
||||
{"bucket": "todo", "process_id": "30062", "archive_at": "2026-08-06 10:00:00"},
|
||||
{"workflow_name": "合同申请单", "status": "归档", "contract_no": None, "workflow_no": "HT-20260806-30062-0", "attachments": []},
|
||||
)
|
||||
assert event is not None
|
||||
assert event["source_event_id"] == "oa-contract-archive:30062"
|
||||
|
||||
|
||||
def test_oa_contract_detail_uses_workflow_download_control(app):
|
||||
"""关键断言:泛微附件的 downloads(imageFileId) 必须生成可下载的 FileDownload URL。"""
|
||||
app.config.update(
|
||||
CONTRACT_PAYMENT_OA_BASE_URL="http://oa.example",
|
||||
CONTRACT_PAYMENT_OA_BELONGTO_USER_ID="22238",
|
||||
CONTRACT_PAYMENT_OA_ATTACHMENT_URL_TEMPLATE=(
|
||||
"/weaver/weaver.file.FileDownload?fileid={attachment_id}&requestid={request_id}&download=1"
|
||||
),
|
||||
)
|
||||
page = """
|
||||
<table><tr><td>盖章完成合同上传</td><td>
|
||||
<table class="annexblocktblclass"><tr><td>
|
||||
<a onclick="openDocExt('document-1','version-1','image-1',1)" title="盖章合同.pdf">盖章合同.pdf</a>
|
||||
<a onclick="downloads('image-1')" title="下载"></a>
|
||||
</td></tr></table>
|
||||
<a href="/hrm/company/HrmDepartmentDsp.jsp?id=513">供应链部</a>
|
||||
</td></tr></table>
|
||||
"""
|
||||
with app.app_context():
|
||||
result = ContractOaClient()._parse_detail_html(page, base_url="http://oa.example/workflow/detail", process_id="30062")
|
||||
|
||||
assert result["attachments"] == [{
|
||||
"attachment_id": "image-1",
|
||||
"file_name": "盖章合同.pdf",
|
||||
"download_url": "http://oa.example/weaver/weaver.file.FileDownload?fileid=image-1&requestid=30062&download=1",
|
||||
"label": "盖章完成合同上传",
|
||||
"priority": 0,
|
||||
}]
|
||||
|
||||
|
||||
def test_three_round_prepayment_alerts_follow_recipient_escalation(app, monkeypatch):
|
||||
"""关键断言:预付款在归档后第 7/14/21 天分别通知申请人、OA 矩阵第二轮 zz 与第三轮 jfl。"""
|
||||
from app.services.contract_payment.supervisor_oa_service import SupervisorMatrix, SupervisorMatrixCache
|
||||
|
||||
with app.app_context():
|
||||
owner = User(username="buyer", email="buyer@example.com", status="active", real_name="李采购")
|
||||
head = User(
|
||||
username="head", email="head@example.com", status="active",
|
||||
real_name="王主管", wecom_userid="27100",
|
||||
)
|
||||
leader = User(
|
||||
username="leader", email="leader@example.com", status="active",
|
||||
real_name="赵分管", wecom_userid="63",
|
||||
)
|
||||
ignored = User(
|
||||
username="ignored-global", email="ignored-global@example.com", status="active",
|
||||
real_name="全局岗位",
|
||||
)
|
||||
db.session.add_all([owner, head, leader, ignored])
|
||||
db.session.flush()
|
||||
app.config.update(
|
||||
CONTRACT_PAYMENT_DEPARTMENT_HEAD_USER_IDS=str(ignored.id),
|
||||
CONTRACT_PAYMENT_PROCUREMENT_LEADER_USER_IDS=str(ignored.id),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
SupervisorMatrixCache,
|
||||
"get",
|
||||
lambda self, name: SupervisorMatrix(
|
||||
applicant_oa_id=18654,
|
||||
department_id=513,
|
||||
round2_oa_id=27100,
|
||||
round3_oa_id=63,
|
||||
round2_name="王主管",
|
||||
round3_name="赵分管",
|
||||
ok=True,
|
||||
),
|
||||
)
|
||||
contract = ContractPaymentContract(
|
||||
contract_no="HT-001",
|
||||
applicant_name="李采购",
|
||||
owner_user_id=None,
|
||||
oa_archive_at=datetime(2026, 8, 1, 9, 0),
|
||||
status="active",
|
||||
)
|
||||
db.session.add(contract)
|
||||
db.session.flush()
|
||||
db.session.add(ContractPaymentNode(
|
||||
contract_id=contract.id,
|
||||
node_code="prepayment",
|
||||
node_type="prepayment",
|
||||
anchor_type="erp_payment",
|
||||
status="active",
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
result = generate_alerts(today=date(2026, 8, 22), send=False)
|
||||
rows = db.session.query(ContractPaymentAlert).order_by(ContractPaymentAlert.alert_round).all()
|
||||
owner_id, head_id, leader_id = owner.id, head.id, leader.id
|
||||
bound_owner_id = db.session.get(ContractPaymentContract, contract.id).owner_user_id
|
||||
|
||||
assert result["created"] == 3
|
||||
assert [(row.alert_round, row.recipient_user_id) for row in rows] == [
|
||||
(1, owner_id), (2, head_id), (3, leader_id),
|
||||
]
|
||||
assert bound_owner_id == owner_id
|
||||
|
||||
|
||||
def test_round_one_recipient_ignores_stale_default_owner(app):
|
||||
"""关键断言:第一轮按申请人真实姓名匹配,忽略历史上写入的默认管理员 owner_user_id。"""
|
||||
with app.app_context():
|
||||
stale = User(username="cp-stale-admin", email="cp-stale-admin@example.com", status="active", real_name="系统管理员")
|
||||
buyer = User(username="cp-real-buyer", email="cp-real-buyer@example.com", status="active", real_name="陈申请人")
|
||||
db.session.add_all([stale, buyer])
|
||||
db.session.flush()
|
||||
contract = ContractPaymentContract(
|
||||
contract_no="HT-OWNER-STALE",
|
||||
applicant_name="陈申请人",
|
||||
owner_user_id=stale.id,
|
||||
oa_archive_at=datetime(2026, 8, 1, 9, 0),
|
||||
status="active",
|
||||
)
|
||||
db.session.add(contract)
|
||||
db.session.flush()
|
||||
db.session.add(ContractPaymentNode(
|
||||
contract_id=contract.id, node_code="prepayment", node_type="prepayment", status="active",
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
result = generate_alerts(today=date(2026, 8, 8), send=False)
|
||||
rows = db.session.query(ContractPaymentAlert).filter_by(contract_id=contract.id).all()
|
||||
buyer_id = buyer.id
|
||||
bound_owner_id = db.session.get(ContractPaymentContract, contract.id).owner_user_id
|
||||
|
||||
assert result["created"] == 1
|
||||
assert [row.recipient_user_id for row in rows] == [buyer_id]
|
||||
assert bound_owner_id == buyer_id
|
||||
|
||||
|
||||
def test_round_one_skips_when_applicant_name_is_ambiguous_or_missing(app):
|
||||
"""关键断言:申请人为空、系统无对应用户或真实姓名重名时,第一轮不发送、不兜底。"""
|
||||
with app.app_context():
|
||||
first = User(username="cp-dup-a", email="cp-dup-a@example.com", status="active", real_name="同名采购")
|
||||
second = User(username="cp-dup-b", email="cp-dup-b@example.com", status="active", real_name="同名采购")
|
||||
db.session.add_all([first, second])
|
||||
db.session.flush()
|
||||
missing = ContractPaymentContract(
|
||||
contract_no="HT-OWNER-MISS",
|
||||
applicant_name="不存在的人",
|
||||
oa_archive_at=datetime(2026, 8, 1, 9, 0),
|
||||
status="active",
|
||||
)
|
||||
dup = ContractPaymentContract(
|
||||
contract_no="HT-OWNER-DUP",
|
||||
applicant_name="同名采购",
|
||||
oa_archive_at=datetime(2026, 8, 1, 9, 0),
|
||||
status="active",
|
||||
)
|
||||
empty = ContractPaymentContract(
|
||||
contract_no="HT-OWNER-EMPTY",
|
||||
applicant_name=None,
|
||||
owner_user_id=first.id,
|
||||
oa_archive_at=datetime(2026, 8, 1, 9, 0),
|
||||
status="active",
|
||||
)
|
||||
db.session.add_all([missing, dup, empty])
|
||||
db.session.flush()
|
||||
for row in (missing, dup, empty):
|
||||
db.session.add(ContractPaymentNode(
|
||||
contract_id=row.id, node_code="prepayment", node_type="prepayment", status="active",
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
result = generate_alerts(today=date(2026, 8, 8), send=False)
|
||||
alerts = db.session.query(ContractPaymentAlert).filter(
|
||||
ContractPaymentAlert.contract_id.in_([missing.id, dup.id, empty.id])
|
||||
).all()
|
||||
empty_bound = bind_contract_owner_from_applicant(db.session.get(ContractPaymentContract, empty.id))
|
||||
|
||||
assert result["created"] == 0
|
||||
assert alerts == []
|
||||
assert empty_bound is None
|
||||
|
||||
|
||||
def test_weekly_alert_summary_counts_pending_and_next_friday(app):
|
||||
"""关键断言:待发送只计 active 合同的 pending;下次发送为上海时区下周五 18:00。"""
|
||||
with app.app_context():
|
||||
owner = User(username="summary-owner", email="summary-owner@example.com", status="active")
|
||||
db.session.add(owner)
|
||||
db.session.flush()
|
||||
active = ContractPaymentContract(contract_no="HT-SUMMARY-1", owner_user_id=owner.id, status="active")
|
||||
inactive = ContractPaymentContract(contract_no="HT-SUMMARY-2", owner_user_id=owner.id, status="archived")
|
||||
db.session.add_all([active, inactive])
|
||||
db.session.flush()
|
||||
active_node = ContractPaymentNode(contract_id=active.id, node_code="prepayment", node_type="prepayment", status="active")
|
||||
inactive_node = ContractPaymentNode(contract_id=inactive.id, node_code="prepayment", node_type="prepayment", status="active")
|
||||
db.session.add_all([active_node, inactive_node])
|
||||
db.session.flush()
|
||||
db.session.add_all([
|
||||
ContractPaymentAlert(
|
||||
contract_id=active.id, node_id=active_node.id, trigger_key="round:1:date:2026-09-01",
|
||||
recipient_user_id=owner.id, alert_round=1, status="pending",
|
||||
),
|
||||
ContractPaymentAlert(
|
||||
contract_id=active.id, node_id=active_node.id, trigger_key="round:2:date:2026-09-01",
|
||||
recipient_user_id=owner.id, alert_round=2, status="sent",
|
||||
),
|
||||
ContractPaymentAlert(
|
||||
contract_id=inactive.id, node_id=inactive_node.id, trigger_key="round:1:date:2026-09-01",
|
||||
recipient_user_id=owner.id, alert_round=1, status="pending",
|
||||
),
|
||||
])
|
||||
db.session.commit()
|
||||
|
||||
before_friday = build_weekly_alert_summary(now=datetime(2026, 9, 3, 1, 0))
|
||||
at_send_time = build_weekly_alert_summary(now=datetime(2026, 9, 4, 10, 0))
|
||||
|
||||
assert before_friday["pending_count"] == 1
|
||||
assert before_friday["timezone"] == "Asia/Shanghai"
|
||||
assert before_friday["next_send_at"] == "2026-09-04T10:00:00Z"
|
||||
assert at_send_time["next_send_at"] == "2026-09-11T10:00:00Z"
|
||||
|
||||
|
||||
def test_erp_payment_amount_matches_the_corresponding_stage():
|
||||
"""关键断言:不同金额的 ERP 付款必须分别匹配同金额付款阶段。"""
|
||||
paid_node_ids = resolve_paid_node_ids(
|
||||
[(1, "prepayment", Decimal("20000")), (2, "shipment", Decimal("30000"))],
|
||||
[Decimal("30000")],
|
||||
)
|
||||
|
||||
assert paid_node_ids == {2}
|
||||
|
||||
|
||||
def test_erp_equal_payment_amounts_follow_prepayment_then_shipment_order():
|
||||
"""关键断言:预付款、出货款同金额时,付款记录按预付款优先的业务顺序占用节点。"""
|
||||
nodes = [(1, "prepayment", Decimal("30000")), (2, "shipment", Decimal("30000"))]
|
||||
|
||||
assert resolve_paid_node_ids(nodes, [Decimal("30000")]) == {1}
|
||||
assert resolve_paid_node_ids(nodes, [Decimal("30000"), Decimal("30000")]) == {1, 2}
|
||||
|
||||
|
||||
def test_erp_combined_payment_marks_prepayment_and_shipment_paid():
|
||||
"""关键断言:预付款、出货款在同一笔请款中一并请款时,单笔付款(金额=两者之和)应同时命中两个节点。"""
|
||||
nodes = [(1, "prepayment", Decimal("21600")), (2, "shipment", Decimal("21600"))]
|
||||
|
||||
# 分开请款:各自一份仍按节点金额分别命中。
|
||||
assert resolve_paid_node_ids(nodes, [Decimal("21600")]) == {1}
|
||||
assert resolve_paid_node_ids(nodes, [Decimal("43200")]) == {1, 2}
|
||||
# 一笔请款同时预付款+出货款:金额等于两者之和,一次性标记两者为已付。
|
||||
assert resolve_paid_node_ids(nodes, [Decimal("43200")]) == {1, 2}
|
||||
@@ -0,0 +1,130 @@
|
||||
"""
|
||||
backend/tests/test_contract_payment_permissions.py
|
||||
|
||||
用途:验收合同付款预警专项权限 `contract_payment.access` 的角色默认值、显式覆盖与 API 拦截。
|
||||
依赖:User 功能权限、Flask test client、contract_payment 蓝图。
|
||||
逻辑:admin 默认可访问;普通用户默认 403;显式授予后可查询台账;关闭 admin 覆盖后同样 403。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import User
|
||||
|
||||
|
||||
def _make_memory_user(*, role: str, overrides: dict | None = None) -> User:
|
||||
"""构造带功能权限覆盖的内存用户(不落库,仅测 has_feature_permission)。"""
|
||||
user = User(username=f'cp-{role}', role=role)
|
||||
if overrides is not None:
|
||||
user.feature_permissions = overrides
|
||||
return user
|
||||
|
||||
|
||||
def _create_user(
|
||||
*,
|
||||
username: str,
|
||||
role: str = 'user',
|
||||
feature_permissions: dict | None = None,
|
||||
) -> User:
|
||||
"""创建落库用户,供 contract-payment API 走 legacy header 认证。"""
|
||||
user = User(
|
||||
username=username,
|
||||
email=f'{username}@example.com',
|
||||
role=role,
|
||||
status='active',
|
||||
real_name=f'{username}-实名',
|
||||
employee_id=f'{username.upper()}-EMP',
|
||||
department='采购部',
|
||||
)
|
||||
user.set_feature_permissions(feature_permissions)
|
||||
user.set_password('password123')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
db.session.refresh(user)
|
||||
db.session.expunge(user)
|
||||
return user
|
||||
|
||||
|
||||
def _auth_headers(user: User) -> dict[str, str]:
|
||||
"""生成测试鉴权头,显式携带 user_id 以稳定命中 legacy 用户解析。"""
|
||||
return {
|
||||
'X-User-Id': str(user.id),
|
||||
'X-Username': user.username,
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
|
||||
|
||||
def _json_error(response) -> dict:
|
||||
"""读取标准 envelope 的 error 对象。"""
|
||||
body = response.get_json()
|
||||
assert body.get('success') is False
|
||||
assert isinstance(body.get('error'), dict)
|
||||
return body['error']
|
||||
|
||||
|
||||
def test_admin_default_has_contract_payment_access(app):
|
||||
"""admin 角色默认具备 contract_payment.access;普通用户默认无。"""
|
||||
with app.app_context():
|
||||
admin = _make_memory_user(role='admin')
|
||||
user = _make_memory_user(role='user')
|
||||
# 关键断言:不新建角色,仅功能键裁剪工作台访问。
|
||||
assert admin.can_access_contract_payment() is True
|
||||
assert user.can_access_contract_payment() is False
|
||||
|
||||
|
||||
def test_explicit_grant_and_revoke_contract_payment_access(app):
|
||||
"""普通用户可被显式授予;admin 可被显式关闭。"""
|
||||
with app.app_context():
|
||||
granted = _make_memory_user(role='user', overrides={'contract_payment.access': True})
|
||||
revoked_admin = _make_memory_user(role='admin', overrides={'contract_payment.access': False})
|
||||
# 关键断言:显式覆盖优先于角色默认。
|
||||
assert granted.can_access_contract_payment() is True
|
||||
assert revoked_admin.can_access_contract_payment() is False
|
||||
|
||||
|
||||
def test_set_feature_permissions_persists_contract_payment_override(app):
|
||||
"""用户表单保存时只持久化与角色默认值不同的 contract_payment.access。"""
|
||||
with app.app_context():
|
||||
user = User(username='cp-override', role='user')
|
||||
user.set_feature_permissions({'contract_payment.access': True})
|
||||
# 关键断言:未知键被忽略,已知覆盖项写入 JSON。
|
||||
assert user.feature_permissions == {'contract_payment.access': True}
|
||||
assert user.can_access_contract_payment() is True
|
||||
|
||||
admin = User(username='cp-admin-override', role='admin')
|
||||
admin.set_feature_permissions({'contract_payment.access': False})
|
||||
assert admin.feature_permissions == {'contract_payment.access': False}
|
||||
assert admin.can_access_contract_payment() is False
|
||||
|
||||
|
||||
def test_contract_payment_api_forbids_user_without_access(client, app):
|
||||
"""无权限用户查询台账或触发同步均返回 CONTRACT_PAYMENT.FORBIDDEN。"""
|
||||
with app.app_context():
|
||||
ordinary = _create_user(username='cp_api_denied')
|
||||
|
||||
headers = _auth_headers(ordinary)
|
||||
list_res = client.get('/api/contract-payment/contracts', headers=headers)
|
||||
# 关键断言:登录不足够,专项权限缺失必须 403。
|
||||
assert list_res.status_code == 403
|
||||
assert _json_error(list_res)['code'] == 'CONTRACT_PAYMENT.FORBIDDEN'
|
||||
|
||||
sync_res = client.post('/api/contract-payment/sync', headers=headers, json={})
|
||||
assert sync_res.status_code == 403
|
||||
assert _json_error(sync_res)['code'] == 'CONTRACT_PAYMENT.FORBIDDEN'
|
||||
|
||||
|
||||
def test_contract_payment_api_allows_granted_user(client, app):
|
||||
"""显式授予后普通用户可以查询台账。"""
|
||||
with app.app_context():
|
||||
granted = _create_user(
|
||||
username='cp_api_granted',
|
||||
feature_permissions={'contract_payment.access': True},
|
||||
)
|
||||
|
||||
headers = _auth_headers(granted)
|
||||
list_res = client.get('/api/contract-payment/contracts', headers=headers)
|
||||
# 关键断言:授予后不再 403,返回标准成功 envelope。
|
||||
assert list_res.status_code == 200
|
||||
body = list_res.get_json()
|
||||
assert body.get('success') is True
|
||||
assert 'items' in (body.get('data') or {})
|
||||
@@ -0,0 +1,215 @@
|
||||
"""
|
||||
backend/tests/test_contract_payment_supervisor_oa.py
|
||||
|
||||
用途:验证合同付款第二、三轮收件人从 OA HrmResource + Matrixtable_3 解析,且不向第一轮兜底。
|
||||
依赖:supervisor_oa_service、alert_service、ContractPayment* 模型。
|
||||
逻辑:SQL 与 OA 连接一律 mock,不访问真实 ecology 库。
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ContractPaymentAlert,
|
||||
ContractPaymentContract,
|
||||
ContractPaymentNode,
|
||||
User,
|
||||
)
|
||||
from app.services.contract_payment.alert_service import generate_alerts
|
||||
from app.services.contract_payment.supervisor_oa_service import (
|
||||
SupervisorMatrix,
|
||||
build_hrm_lookup_sql,
|
||||
build_matrix_lookup_sql,
|
||||
fetch_supervisor_matrix,
|
||||
)
|
||||
from datetime import date
|
||||
|
||||
|
||||
class _ScriptedCursor:
|
||||
"""按调用顺序返回预设结果集,记录 SQL 与参数。"""
|
||||
|
||||
def __init__(self, responses):
|
||||
self.responses = list(responses)
|
||||
self.sqls = []
|
||||
self.params_list = []
|
||||
self._current = []
|
||||
|
||||
def execute(self, sql, params=None):
|
||||
self.sqls.append(sql)
|
||||
self.params_list.append(list(params or []))
|
||||
self._current = self.responses.pop(0) if self.responses else []
|
||||
|
||||
def fetchall(self):
|
||||
return self._current
|
||||
|
||||
def fetchone(self):
|
||||
return self._current[0] if self._current else None
|
||||
|
||||
|
||||
class _FakeConnection:
|
||||
def __init__(self, cursor):
|
||||
self._cursor = cursor
|
||||
self.closed = False
|
||||
|
||||
def cursor(self):
|
||||
return self._cursor
|
||||
|
||||
def close(self):
|
||||
self.closed = True
|
||||
|
||||
|
||||
def test_hrm_sql_matches_trimmed_lastname():
|
||||
"""关键断言:人员查询按去空白 lastname 精确匹配,并选出 id 与 departmentid。"""
|
||||
sql, params = build_hrm_lookup_sql(
|
||||
table="HrmResource",
|
||||
name_field="lastname",
|
||||
dept_field="departmentid",
|
||||
applicant_name="柴晓红",
|
||||
)
|
||||
assert "[HrmResource]" in sql
|
||||
assert "[lastname]" in sql
|
||||
assert "[departmentid]" in sql
|
||||
assert "LTRIM(RTRIM(" in sql
|
||||
assert params == ["柴晓红"]
|
||||
|
||||
|
||||
def test_matrix_sql_joins_department_to_zz_and_jfl():
|
||||
"""关键断言:矩阵按 bm=部门 ID 过滤,选出 zz(第二轮)与 jfl(第三轮)。"""
|
||||
sql, params = build_matrix_lookup_sql(
|
||||
table="Matrixtable_3",
|
||||
dept_field="bm",
|
||||
round2_field="zz",
|
||||
round3_field="jfl",
|
||||
department_id=513,
|
||||
)
|
||||
assert "[Matrixtable_3]" in sql
|
||||
assert "[bm]" in sql
|
||||
assert "[zz]" in sql
|
||||
assert "[jfl]" in sql
|
||||
assert params == [513]
|
||||
|
||||
|
||||
def test_fetch_supervisor_matrix_maps_unique_applicant(app, monkeypatch):
|
||||
"""关键断言:唯一姓名 + 唯一部门矩阵行映射出 zz/jfl,并关闭连接。"""
|
||||
cursor = _ScriptedCursor([
|
||||
[(18654, "柴晓红", 513)],
|
||||
[(513, 27100, 63)],
|
||||
[("王主管",)],
|
||||
[("赵分管",)],
|
||||
])
|
||||
conn = _FakeConnection(cursor)
|
||||
|
||||
with app.app_context():
|
||||
monkeypatch.setattr(
|
||||
"app.services.contract_payment.supervisor_oa_service.OASQLServerService._connect",
|
||||
lambda *args, **kwargs: conn,
|
||||
)
|
||||
matrix = fetch_supervisor_matrix("柴晓红")
|
||||
|
||||
assert conn.closed is True
|
||||
assert matrix is not None
|
||||
assert matrix.ok is True
|
||||
assert matrix.applicant_oa_id == 18654
|
||||
assert matrix.department_id == 513
|
||||
assert matrix.round2_oa_id == 27100
|
||||
assert matrix.round3_oa_id == 63
|
||||
assert matrix.round2_name == "王主管"
|
||||
assert matrix.round3_name == "赵分管"
|
||||
assert cursor.params_list[0] == ["柴晓红"]
|
||||
assert cursor.params_list[1] == [513]
|
||||
|
||||
|
||||
def test_fetch_supervisor_matrix_skips_duplicate_lastname(app, monkeypatch):
|
||||
"""关键断言:HrmResource 姓名重名时不猜测部门,返回 None。"""
|
||||
cursor = _ScriptedCursor([
|
||||
[(11, "同名采购", 100), (22, "同名采购", 200)],
|
||||
])
|
||||
conn = _FakeConnection(cursor)
|
||||
|
||||
with app.app_context():
|
||||
monkeypatch.setattr(
|
||||
"app.services.contract_payment.supervisor_oa_service.OASQLServerService._connect",
|
||||
lambda *args, **kwargs: conn,
|
||||
)
|
||||
matrix = fetch_supervisor_matrix("同名采购")
|
||||
|
||||
assert matrix is None
|
||||
assert conn.closed is True
|
||||
assert len(cursor.sqls) == 1
|
||||
|
||||
|
||||
def test_round_two_and_three_skip_without_falling_back_to_owner(app, monkeypatch):
|
||||
"""关键断言:OA 矩阵缺失时第二、三轮不发送,也不改发给第一轮申请人。"""
|
||||
from app.services.contract_payment.supervisor_oa_service import SupervisorMatrixCache
|
||||
|
||||
with app.app_context():
|
||||
owner = User(username="cp-oa-owner", email="cp-oa-owner@example.com", status="active", real_name="刘申请人")
|
||||
db.session.add(owner)
|
||||
db.session.flush()
|
||||
monkeypatch.setattr(SupervisorMatrixCache, "get", lambda self, name: None)
|
||||
contract = ContractPaymentContract(
|
||||
contract_no="HT-OA-SKIP",
|
||||
applicant_name="刘申请人",
|
||||
oa_archive_at=datetime(2026, 8, 1, 9, 0),
|
||||
status="active",
|
||||
)
|
||||
db.session.add(contract)
|
||||
db.session.flush()
|
||||
db.session.add(ContractPaymentNode(
|
||||
contract_id=contract.id, node_code="prepayment", node_type="prepayment", status="active",
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
result = generate_alerts(today=date(2026, 8, 22), send=False)
|
||||
rows = db.session.query(ContractPaymentAlert).filter_by(contract_id=contract.id).all()
|
||||
owner_id = owner.id
|
||||
|
||||
assert result["created"] == 1
|
||||
assert [row.alert_round for row in rows] == [1]
|
||||
assert rows[0].recipient_user_id == owner_id
|
||||
|
||||
|
||||
def test_round_two_maps_user_by_real_name_when_wecom_unbound(app, monkeypatch):
|
||||
"""关键断言:主管未绑定 wecom_userid 时,仍可用 OA lastname 唯一匹配系统用户,并记下 OA 企微 id。"""
|
||||
from app.services.contract_payment.supervisor_oa_service import SupervisorMatrixCache
|
||||
|
||||
with app.app_context():
|
||||
owner = User(username="cp-oa-buyer", email="cp-oa-buyer@example.com", status="active", real_name="钱采购")
|
||||
head = User(username="cp-oa-head", email="cp-oa-head@example.com", status="active", real_name="孙主管")
|
||||
db.session.add_all([owner, head])
|
||||
db.session.flush()
|
||||
monkeypatch.setattr(
|
||||
SupervisorMatrixCache,
|
||||
"get",
|
||||
lambda self, name: SupervisorMatrix(
|
||||
applicant_oa_id=1,
|
||||
department_id=513,
|
||||
round2_oa_id=27100,
|
||||
round3_oa_id=None,
|
||||
round2_name="孙主管",
|
||||
round3_name=None,
|
||||
ok=True,
|
||||
),
|
||||
)
|
||||
contract = ContractPaymentContract(
|
||||
contract_no="HT-OA-NAME",
|
||||
applicant_name="钱采购",
|
||||
oa_archive_at=datetime(2026, 8, 1, 9, 0),
|
||||
status="active",
|
||||
)
|
||||
db.session.add(contract)
|
||||
db.session.flush()
|
||||
db.session.add(ContractPaymentNode(
|
||||
contract_id=contract.id, node_code="prepayment", node_type="prepayment", status="active",
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
result = generate_alerts(today=date(2026, 8, 15), send=False)
|
||||
rows = db.session.query(ContractPaymentAlert).filter_by(contract_id=contract.id).order_by(
|
||||
ContractPaymentAlert.alert_round
|
||||
).all()
|
||||
owner_id, head_id = owner.id, head.id
|
||||
|
||||
assert result["created"] == 2
|
||||
assert [(row.alert_round, row.recipient_user_id) for row in rows] == [(1, owner_id), (2, head_id)]
|
||||
assert rows[1].message_json["oa_wecom_userid"] == "27100"
|
||||
@@ -0,0 +1,251 @@
|
||||
"""
|
||||
backend/tests/test_contract_payment_sync_incremental.py
|
||||
|
||||
用途:验证合同付款 OA 增量同步的时间窗口、翻页与持久化断点逻辑。
|
||||
依赖:contract_payment.oa_client、contract_payment.sync_service、ContractPaymentSyncState 模型。
|
||||
逻辑:只覆盖确定性边界(断点计算、窗口过滤、翻页停止、断点单调推进),不调用外部 OA、ERP、文件服务或企业微信。
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from app import db
|
||||
from app.models import ContractPaymentSyncState
|
||||
from app.services.contract_payment.oa_client import ContractOaClient
|
||||
from app.services.contract_payment.sync_service import (
|
||||
_advance_oa_sync_state,
|
||||
compute_oa_sync_since,
|
||||
)
|
||||
|
||||
|
||||
def test_oa_incremental_full_scan_when_no_watermark(app):
|
||||
"""关键断言:无断点(首次运行)返回全量(since=None),保证历史归档合同完整入库。"""
|
||||
with app.app_context():
|
||||
since, state = compute_oa_sync_since(now=datetime(2026, 9, 1, 12, 0, 0))
|
||||
|
||||
assert since is None
|
||||
assert state is None
|
||||
|
||||
|
||||
def test_oa_incremental_since_is_watermark_minus_overlap(app):
|
||||
"""关键断言:有断点后 since = last_successful_sync_at - overlap,否则会漏掉上轮结尾的迟到/越序记录。"""
|
||||
with app.app_context():
|
||||
app.config.update(CONTRACT_PAYMENT_OA_SYNC_OVERLAP_SECONDS=3600)
|
||||
state = ContractPaymentSyncState(
|
||||
state_key="oa-contract-archive",
|
||||
last_successful_sync_at=datetime(2026, 8, 30, 12, 0, 0),
|
||||
)
|
||||
db.session.add(state)
|
||||
db.session.flush()
|
||||
|
||||
since, row = compute_oa_sync_since(now=datetime(2026, 9, 1, 12, 0, 0))
|
||||
|
||||
assert row is state
|
||||
assert since == datetime(2026, 8, 30, 11, 0, 0)
|
||||
|
||||
|
||||
def test_advance_oa_sync_state_creates_and_is_monotonic(app):
|
||||
"""关键断言:断点新建并推进成功时间;archive_seen_at 只允许向未来前进,不因旧归档倒灌回退。"""
|
||||
with app.app_context():
|
||||
first = _advance_oa_sync_state(
|
||||
None,
|
||||
max_archive_at=datetime(2026, 8, 6, 10, 0, 0),
|
||||
processed=2,
|
||||
now=datetime(2026, 9, 1, 9, 0, 0),
|
||||
)
|
||||
db.session.flush()
|
||||
|
||||
assert first.state_key == "oa-contract-archive"
|
||||
assert first.last_successful_sync_at == datetime(2026, 9, 1, 9, 0, 0)
|
||||
assert first.last_archive_seen_at == datetime(2026, 8, 6, 10, 0, 0)
|
||||
assert first.synced_contract_count == 2
|
||||
|
||||
# 再处理一条归档时间更旧的事件:seen 时间戳不得回退。
|
||||
again = _advance_oa_sync_state(
|
||||
first,
|
||||
max_archive_at=datetime(2026, 8, 1, 0, 0, 0),
|
||||
processed=1,
|
||||
now=datetime(2026, 9, 1, 9, 5, 0),
|
||||
)
|
||||
db.session.flush()
|
||||
|
||||
assert again is first
|
||||
assert first.last_archive_seen_at == datetime(2026, 8, 6, 10, 0, 0)
|
||||
assert first.synced_contract_count == 3
|
||||
|
||||
|
||||
def test_oa_archive_at_datetime_parses_common_formats():
|
||||
"""关键断言:兼容 yyyy-mm-dd、yyyy-mm-dd HH:mm:ss;无法解析或为空时返回 None 以保守保留。"""
|
||||
assert ContractOaClient._archive_at_datetime({"archive_at": "2026-08-06"}) == datetime(2026, 8, 6)
|
||||
assert ContractOaClient._archive_at_datetime({"archive_at": "2026-08-06 10:00:00"}) == datetime(2026, 8, 6, 10, 0, 0)
|
||||
assert ContractOaClient._archive_at_datetime({"archive_at": "not-a-date"}) is None
|
||||
assert ContractOaClient._archive_at_datetime({"archive_at": ""}) is None
|
||||
|
||||
|
||||
def test_oa_below_since_keeps_recent_and_undated_but_drops_old(app):
|
||||
"""关键断言:早于窗口下界的候选丢弃;无归档时间保守保留(靠幂等去重,不误删)。"""
|
||||
since = datetime(2026, 8, 1)
|
||||
rows = [
|
||||
{"process_id": "new", "archive_at": "2026-08-06 10:00:00"},
|
||||
{"process_id": "old", "archive_at": "2026-07-01"},
|
||||
{"process_id": "nodate", "archive_at": ""},
|
||||
]
|
||||
|
||||
kept = [row["process_id"] for row in rows if not ContractOaClient._below_since(row, since)]
|
||||
|
||||
assert kept == ["new", "nodate"]
|
||||
|
||||
|
||||
def test_weaver_page_id_reads_html_and_falls_back_by_bucket():
|
||||
"""关键断言:待办不得复用已办 pageId,否则 SplitPage 会把待办翻成已办第一页。"""
|
||||
assert ContractOaClient._weaver_page_id('var pageId = "Wf:waitingWork";', bucket="todo") == "Wf:waitingWork"
|
||||
assert ContractOaClient._weaver_page_id("", bucket="todo") == "Wf:doingWork"
|
||||
assert ContractOaClient._weaver_page_id("", bucket="done") == "Wf:handledMatters"
|
||||
"""关键断言:OA 实际 10 条/页、配置页大小 20 时,不得把首页 10 条误判为已经到底。"""
|
||||
app.config.update(CONTRACT_PAYMENT_OA_SYNC_MAX_PAGES=5, CONTRACT_PAYMENT_OA_SYNC_PAGE_SIZE=20)
|
||||
client = ContractOaClient()
|
||||
|
||||
def fake(session, *, bucket, page=1):
|
||||
if bucket != "done":
|
||||
return []
|
||||
if page == 1:
|
||||
return [{"process_id": f"d{i}"} for i in range(1, 11)]
|
||||
if page == 2:
|
||||
return [{"process_id": "d11"}, {"process_id": "d12"}, {"process_id": "d13"}]
|
||||
return []
|
||||
|
||||
monkeypatch.setattr(client, "_fetch_worklist", fake)
|
||||
|
||||
rows, truncated = client._fetch_worklist_paginated(object(), bucket="done", since=None)
|
||||
|
||||
assert [row["process_id"] for row in rows] == [f"d{i}" for i in range(1, 14)]
|
||||
assert truncated is False
|
||||
|
||||
|
||||
def test_oa_worklist_paginated_stops_on_short_page(app, monkeypatch):
|
||||
"""关键断言:首页满页继续翻页,短页(少于首页实际行数)即到底停止。"""
|
||||
app.config.update(CONTRACT_PAYMENT_OA_SYNC_MAX_PAGES=5, CONTRACT_PAYMENT_OA_SYNC_PAGE_SIZE=2)
|
||||
client = ContractOaClient()
|
||||
|
||||
def fake(session, *, bucket, page=1):
|
||||
if bucket != "todo":
|
||||
return []
|
||||
if page == 1:
|
||||
return [{"process_id": "p1"}, {"process_id": "p2"}]
|
||||
if page == 2:
|
||||
return [{"process_id": "p3"}]
|
||||
return []
|
||||
|
||||
monkeypatch.setattr(client, "_fetch_worklist", fake)
|
||||
|
||||
rows, truncated = client._fetch_worklist_paginated(object(), bucket="todo", since=datetime(2026, 8, 1))
|
||||
|
||||
assert [row["process_id"] for row in rows] == ["p1", "p2", "p3"]
|
||||
assert truncated is False
|
||||
|
||||
|
||||
def test_oa_worklist_paginated_respects_forward_window_across_pages(app, monkeypatch):
|
||||
"""关键断言:跨页收集时仍按增量下限过滤,旧记录不进入待打开详情列表。"""
|
||||
app.config.update(CONTRACT_PAYMENT_OA_SYNC_MAX_PAGES=3, CONTRACT_PAYMENT_OA_SYNC_PAGE_SIZE=1)
|
||||
client = ContractOaClient()
|
||||
|
||||
def fake(session, *, bucket, page=1):
|
||||
if bucket != "todo":
|
||||
return []
|
||||
if page == 1:
|
||||
return [{"process_id": "a", "archive_at": "2026-08-10"}]
|
||||
if page == 2:
|
||||
return [{"process_id": "b", "archive_at": "2026-07-10"}]
|
||||
return []
|
||||
|
||||
monkeypatch.setattr(client, "_fetch_worklist", fake)
|
||||
|
||||
rows, truncated = client._fetch_worklist_paginated(object(), bucket="todo", since=datetime(2026, 8, 1))
|
||||
|
||||
assert [row["process_id"] for row in rows] == ["a"]
|
||||
assert truncated is False
|
||||
|
||||
|
||||
def test_oa_full_scan_ignores_max_pages_until_short_page(app, monkeypatch):
|
||||
"""关键断言:首次全量不受 MAX_PAGES=2 截断,避免存量合同静默漏入库。"""
|
||||
app.config.update(CONTRACT_PAYMENT_OA_SYNC_MAX_PAGES=2, CONTRACT_PAYMENT_OA_SYNC_PAGE_SIZE=2)
|
||||
client = ContractOaClient()
|
||||
|
||||
def fake(session, *, bucket, page=1):
|
||||
if bucket != "todo":
|
||||
return []
|
||||
pages = {
|
||||
1: [{"process_id": "p1"}, {"process_id": "p2"}],
|
||||
2: [{"process_id": "p3"}, {"process_id": "p4"}],
|
||||
3: [{"process_id": "p5"}],
|
||||
}
|
||||
return pages.get(page, [])
|
||||
|
||||
monkeypatch.setattr(client, "_fetch_worklist", fake)
|
||||
|
||||
rows, truncated = client._fetch_worklist_paginated(object(), bucket="todo", since=None)
|
||||
|
||||
assert [row["process_id"] for row in rows] == ["p1", "p2", "p3", "p4", "p5"]
|
||||
assert truncated is False
|
||||
|
||||
|
||||
def test_oa_incremental_max_pages_marks_truncated(app, monkeypatch):
|
||||
"""关键断言:增量窗口触顶且末页仍满页时标记 truncated,供同步层不推进断点。"""
|
||||
app.config.update(CONTRACT_PAYMENT_OA_SYNC_MAX_PAGES=2, CONTRACT_PAYMENT_OA_SYNC_PAGE_SIZE=2)
|
||||
client = ContractOaClient()
|
||||
fetched_pages: list[int] = []
|
||||
|
||||
def fake(session, *, bucket, page=1):
|
||||
if bucket != "todo":
|
||||
return []
|
||||
fetched_pages.append(page)
|
||||
pages = {
|
||||
1: [{"process_id": "p1"}, {"process_id": "p2"}],
|
||||
2: [{"process_id": "p3"}, {"process_id": "p4"}],
|
||||
3: [{"process_id": "p5"}],
|
||||
}
|
||||
return pages.get(page, [])
|
||||
|
||||
monkeypatch.setattr(client, "_fetch_worklist", fake)
|
||||
|
||||
rows, truncated = client._fetch_worklist_paginated(object(), bucket="todo", since=datetime(2026, 8, 1))
|
||||
|
||||
assert [row["process_id"] for row in rows] == ["p1", "p2", "p3", "p4"]
|
||||
assert truncated is True
|
||||
assert fetched_pages == [1, 2]
|
||||
|
||||
|
||||
def test_truncated_worklist_does_not_advance_watermark(app, monkeypatch):
|
||||
"""关键断言:列表翻页截断时保留已有断点,避免漏扫页被当成同步成功。"""
|
||||
from app.services.contract_payment.sync_service import sync_notifications
|
||||
|
||||
with app.app_context():
|
||||
state = ContractPaymentSyncState(
|
||||
state_key="oa-contract-archive",
|
||||
last_successful_sync_at=datetime(2026, 8, 30, 12, 0, 0),
|
||||
last_run_at=datetime(2026, 8, 30, 12, 0, 0),
|
||||
)
|
||||
db.session.add(state)
|
||||
db.session.commit()
|
||||
|
||||
class FakeClient:
|
||||
def configuration_status(self):
|
||||
return {
|
||||
"configured": True,
|
||||
"list_configured": True,
|
||||
"missing": [],
|
||||
"attachment_template_configured": False,
|
||||
}
|
||||
|
||||
def fetch_notifications(self, *, since=None):
|
||||
return [], True
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.contract_payment.sync_service.fetch_archived_acceptances",
|
||||
lambda **_kwargs: ([], True),
|
||||
)
|
||||
result = sync_notifications(client=FakeClient())
|
||||
db.session.refresh(state)
|
||||
|
||||
assert result["oa_worklist_truncated"] is True
|
||||
assert state.last_successful_sync_at == datetime(2026, 8, 30, 12, 0, 0)
|
||||
assert state.last_run_at == datetime(2026, 8, 30, 12, 0, 0)
|
||||
@@ -75,6 +75,17 @@ def main(
|
||||
app = create_app(resolved_config)
|
||||
queue_names = queues or ['kb']
|
||||
|
||||
# 启动期诊断:确认合同付款 ERP 回查的运行时配置状态(只标记是否就绪,不输出密码)。
|
||||
_erp_dsn = str(app.config.get("CONTRACT_PAYMENT_ERP_DSN") or "").strip()
|
||||
_erp_user = str(app.config.get("CONTRACT_PAYMENT_ERP_USERNAME") or "").strip()
|
||||
_erp_pwd = str(app.config.get("CONTRACT_PAYMENT_ERP_PASSWORD") or "")
|
||||
logger.info(
|
||||
"合同付款预警 ERP 回查配置: dsn=%s 用户名=%s 密码=%s",
|
||||
"✓就绪" if _erp_dsn else "✗缺失",
|
||||
"✓就绪" if _erp_user else "✗缺失",
|
||||
"✓就绪" if _erp_pwd else "✗缺失",
|
||||
)
|
||||
|
||||
if queue_names == ['schedule'] and not bool(app.config.get('SCHEDULE_WORKER_ENABLED', True)):
|
||||
logger.info('Schedule worker disabled by SCHEDULE_WORKER_ENABLED=false')
|
||||
return
|
||||
|
||||
Reference in new issue
Block a user