fix: fix merge conflicts
This commit is contained in:
commit
03b9b46ebd
114 files changed
+11408
-2996
No files matched your search
@@ -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))
|
||||
Reference in new issue
Block a user