feat(contract): 采购合同对比agent

Signed-off-by: sophie <sophie>

Signed-off-by: sophie <sophie>
This commit is contained in:
sophie committed 2026-07-27 14:47:09 +08:00
1 parent ffccf19ba2
commit 0503ff76a6
90 files changed
+16729 -1344

No files matched your search

+2
View File
@@ -40,6 +40,7 @@ def register_blueprints(app: Flask) -> None:
)
from app.api.tools import file_check_bp, maintenance_tool_bp, shipping_notice_bp
from app.api.files import files_bp
from app.api.procurement_contract_tools import procurement_contract_bp
app.register_blueprint(chat_bp, url_prefix='/api/chat')
app.register_blueprint(admin_bp, url_prefix='/api/admin')
@@ -62,3 +63,4 @@ def register_blueprints(app: Flask) -> None:
app.register_blueprint(speech_bp, url_prefix='/api/speech')
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')
+1
View File
@@ -19,5 +19,6 @@ import app.api.admin.permissions # noqa: F401
import app.api.admin.users # noqa: F401
import app.api.admin.wecom # noqa: F401
import app.api.admin.announcements # noqa: F401
import app.api.admin.procurement_contract # noqa: F401
__all__ = ['admin_bp']
@@ -0,0 +1,264 @@
"""
backend/app/api/admin/procurement_contract.py
Purpose: Admin APIs for procurement contract templates, risk rules, and review history.
Dependencies: admin blueprint, procurement_contract services, file asset upload, unified response envelope.
Flow: Admin manages reusable templates/rules; review history remains read-only with export endpoints.
"""
from __future__ import annotations
import io
import json
from flask import g, request, send_file
from app.api.admin.blueprint import admin_bp
from app.core.auth.jwt import get_current_user
from app.core.decorators import require_admin
from app.core.errors import UnauthorizedError, ValidationError
from app.core.response import ok
from app.services.file_assets.service import upload_file_asset
from app.services.procurement_contract import review_service, rule_service, template_service
from app.services.procurement_contract.template_service import read_template_bytes
def _admin_user():
"""Return current admin user or raise UnauthorizedError."""
user = get_current_user()
if not user:
raise UnauthorizedError()
return user
def _int_arg(name: str, default: int) -> int:
"""Parse an integer query argument with a ValidationError on bad input."""
raw = request.args.get(name)
if raw in (None, ""):
return default
try:
return int(raw)
except (TypeError, ValueError) as exc:
raise ValidationError(f"{name} must be integer") from exc
def _optional_json_form(name: str):
"""Parse an optional multipart JSON field through the unified validation error contract."""
raw = request.form.get(name)
if not raw:
return None
try:
return json.loads(raw)
except (TypeError, ValueError) as exc:
raise ValidationError(
f"{name} must be valid JSON",
code="PROCUREMENT_CONTRACT.INVALID_COMPARISON_REGION_CONFIG",
details={"field": name},
) from exc
@admin_bp.route("/procurement-contract/templates", methods=["GET"])
@require_admin
def admin_list_contract_templates():
"""List all contract templates."""
status = request.args.get("status") or None
return ok(template_service.list_templates(status=status), request_id=getattr(g, "request_id", None))
@admin_bp.route("/procurement-contract/templates", methods=["POST"])
@require_admin
def admin_create_contract_template():
"""Upload and create a reusable procurement contract template."""
user = _admin_user()
if request.content_type and "multipart/form-data" in request.content_type:
upload = request.files.get("file")
if not upload or not upload.filename:
raise ValidationError("file is required")
asset = upload_file_asset(user_id=user.id, upload=upload)
row = template_service.create_template(
user_id=user.id,
name=(request.form.get("name") or "").strip(),
version=(request.form.get("version") or "").strip(),
file_asset_no=str(asset.get("asset_no") or ""),
remark=request.form.get("remark"),
is_default=str(request.form.get("is_default") or "").lower() in ("1", "true", "yes"),
status=(request.form.get("status") or "enabled").strip(),
contract_type=(request.form.get("contract_type") or "general_procurement").strip(),
applicable_scope=request.form.get("applicable_scope"),
change_note=request.form.get("change_note"),
comparison_region_config=_optional_json_form("comparison_region_config"),
)
else:
data = request.get_json() or {}
file_asset_no = (data.get("file_asset_no") or "").strip()
file_asset_id = int(data.get("file_asset_id") or 0) or None
if not file_asset_no and not file_asset_id:
raise ValidationError("file_asset_no is required")
row = template_service.create_template(
user_id=user.id,
name=(data.get("name") or "").strip(),
version=(data.get("version") or "").strip(),
file_asset_id=file_asset_id,
file_asset_no=file_asset_no or None,
remark=data.get("remark"),
is_default=bool(data.get("is_default")),
status=(data.get("status") or "enabled").strip(),
contract_type=(data.get("contract_type") or "general_procurement").strip(),
applicable_scope=data.get("applicable_scope"),
change_note=data.get("change_note"),
comparison_region_config=data.get("comparison_region_config"),
)
return ok(row, request_id=getattr(g, "request_id", None), status=201)
@admin_bp.route("/procurement-contract/templates/<int:template_id>", methods=["PATCH"])
@require_admin
def admin_update_contract_template(template_id: int):
"""
Update template metadata, status, default flag, or validated comparison-region configuration.
Args:
template_id: ContractTemplate primary key from the Admin route.
Returns:
Unified success envelope containing the updated template row.
"""
user = _admin_user()
row = template_service.update_template(template_id, user_id=user.id, data=request.get_json() or {})
return ok(row, request_id=getattr(g, "request_id", None))
@admin_bp.route("/procurement-contract/templates/<int:template_id>/comparison-region-preview", methods=["POST"])
@require_admin
def admin_preview_contract_template_regions(template_id: int):
"""
Preview unsaved comparison-region anchors against the stored template file.
Args:
template_id: ContractTemplate primary key; the stored file is used only for recognition preview.
Returns:
Unified success envelope with matched body, signature, and attachment anchors.
"""
data = request.get_json() or {}
result = template_service.preview_comparison_regions(
template_id,
data.get("comparison_region_config"),
)
return ok(result, request_id=getattr(g, "request_id", None))
@admin_bp.route("/procurement-contract/templates/<int:template_id>", methods=["DELETE"])
@require_admin
def admin_delete_contract_template(template_id: int):
"""Delete a non-default template."""
return ok(template_service.delete_template(template_id), request_id=getattr(g, "request_id", None))
@admin_bp.route("/procurement-contract/templates/<int:template_id>/file", methods=["GET"])
@require_admin
def admin_download_contract_template(template_id: int):
"""Download template file bytes."""
tpl = template_service.get_template_or_404(template_id)
filename, data = read_template_bytes(tpl)
return send_file(io.BytesIO(data), mimetype="application/octet-stream", as_attachment=True, download_name=filename)
@admin_bp.route("/procurement-contract/rules", methods=["GET"])
@require_admin
def admin_list_contract_risk_rules():
"""List configurable procurement contract risk rules."""
rows = rule_service.list_rules(
contract_type=request.args.get("contract_type") or None,
status=request.args.get("status") or None,
clause_category=request.args.get("clause_category") or None,
)
return ok(rows, request_id=getattr(g, "request_id", None))
@admin_bp.route("/procurement-contract/rules", methods=["POST"])
@require_admin
def admin_create_contract_risk_rule():
"""Create a procurement contract risk rule."""
user = _admin_user()
row = rule_service.create_rule(user_id=user.id, data=request.get_json() or {})
return ok(row, request_id=getattr(g, "request_id", None), status=201)
@admin_bp.route("/procurement-contract/rules/<int:rule_id>", methods=["PATCH"])
@require_admin
def admin_update_contract_risk_rule(rule_id: int):
"""Update a procurement contract risk rule."""
user = _admin_user()
row = rule_service.update_rule(rule_id, user_id=user.id, data=request.get_json() or {})
return ok(row, request_id=getattr(g, "request_id", None))
@admin_bp.route("/procurement-contract/rules/<int:rule_id>", methods=["DELETE"])
@require_admin
def admin_delete_contract_risk_rule(rule_id: int):
"""Delete a procurement contract risk rule."""
return ok(rule_service.delete_rule(rule_id), request_id=getattr(g, "request_id", None))
@admin_bp.route("/procurement-contract/reviews", methods=["GET"])
@require_admin
def admin_list_contract_reviews():
"""List review history with filters."""
data = review_service.list_reviews(
review_mode=request.args.get("review_mode") or None,
template_source=request.args.get("template_source") or None,
status=request.args.get("status") or None,
keyword=request.args.get("keyword") or None,
contract_type=request.args.get("contract_type") or None,
supplier_name=request.args.get("supplier_name") or None,
risk_level=request.args.get("risk_level") or None,
date_from=request.args.get("date_from") or None,
date_to=request.args.get("date_to") or None,
limit=_int_arg("limit", 100),
offset=_int_arg("offset", 0),
)
return ok(data, request_id=getattr(g, "request_id", None))
@admin_bp.route("/procurement-contract/reviews/<int:review_id>", methods=["GET"])
@require_admin
def admin_get_contract_review(review_id: int):
"""Get review details."""
return ok(review_service.get_review(review_id=review_id), request_id=getattr(g, "request_id", None))
@admin_bp.route("/procurement-contract/reviews/<int:review_id>/report", methods=["GET"])
@require_admin
def admin_download_contract_review_report(review_id: int):
"""Download review report as txt or docx."""
if (request.args.get("format") or "").lower() == "docx":
name, data, mimetype = review_service.read_review_report_docx_bytes(review_id=review_id)
else:
name, data = review_service.read_review_report_bytes(review_id=review_id)
mimetype = "text/plain; charset=utf-8"
return send_file(io.BytesIO(data), mimetype=mimetype, as_attachment=True, download_name=name)
@admin_bp.route("/procurement-contract/reviews/<int:review_id>/contract", methods=["GET"])
@require_admin
def admin_download_contract_review_contract(review_id: int):
"""Download original contract file for a review."""
filename, data = review_service.read_review_contract_bytes(review_id=review_id)
return send_file(io.BytesIO(data), mimetype="application/octet-stream", as_attachment=True, download_name=filename)
@admin_bp.route("/procurement-contract/reviews/<int:review_id>/annotated-contract", methods=["GET"])
@require_admin
def admin_download_annotated_contract(review_id: int):
"""Download original PDF with anchored contract-review highlights."""
filename, data, mimetype = review_service.read_review_annotated_contract_bytes(review_id=review_id)
return send_file(io.BytesIO(data), mimetype=mimetype, as_attachment=True, download_name=filename)
@admin_bp.route("/procurement-contract/reviews/<int:review_id>/template-file", methods=["GET"])
@require_admin
def admin_download_contract_review_template(review_id: int):
"""Download template file used by a review."""
filename, data = review_service.read_review_template_bytes(review_id=review_id)
return send_file(io.BytesIO(data), mimetype="application/octet-stream", as_attachment=True, download_name=filename)
+73 -3
View File
@@ -86,6 +86,42 @@ def _session_title_from_text(text: str) -> str:
return value[:30] + ('...' if len(value) > 30 else '')
def _looks_like_review_auto_title(title: str) -> bool:
"""
判断会话标题是否为审查结果 headline(误用作历史标题)。
Args:
title: ChatSession.title。
Returns:
True 表示标题像「模板比对完成…」这类自动摘要,而非用户提问。
"""
value = str(title or '').strip()
return value.startswith(('模板比对完成', '单份审核完成', '采购合同审查结果'))
def _fallback_title_from_contract_review_log(log: ChatLog | None) -> str:
"""
从合同审查日志推导可读会话标题(优先 query,其次合同文件名)。
Args:
log: procurement-contract-review 类型的 ChatLog。
Returns:
截断后的标题;无法推导时返回空串。
"""
if not log:
return ''
query = str(log.query or '').strip()
if query:
return _session_title_from_text(query)
payload = log.payload if isinstance(log.payload, dict) else {}
file_name = str(payload.get('contract_file_name') or '').strip()
if file_name:
return _session_title_from_text(f'请对《{file_name}》进行审查')
return ''
def _user_facing_chat_query(text: str, *, agent_code: str | None = None) -> str:
"""
将内部 Agent 编排提示转换成业务用户可见话术。
@@ -900,6 +936,32 @@ def get_chat_sessions():
),
).order_by(desc(ChatSession.last_active_at), desc(ChatSession.id)).limit(20).all()
# 纠偏历史:审查结果卡曾把 headline 写成标题时,改用合同文件名展示
title_repaired = False
for item in session_rows:
if not _looks_like_review_auto_title(item.title or ''):
continue
review_log = (
db.session.query(ChatLog)
.filter(
ChatLog.user_id == user.id,
ChatLog.agent_id == agent.id,
ChatLog.message_type == 'procurement-contract-review',
or_(
ChatLog.session_id == item.session_id,
ChatLog.conversation_id == item.session_id,
),
)
.order_by(desc(ChatLog.created_at), desc(ChatLog.id))
.first()
)
better = _fallback_title_from_contract_review_log(review_log)
if better:
item.title = better
title_repaired = True
if title_repaired:
db.session.commit()
sessions = [_serialize_session(item) for item in session_rows]
session_ids = {item['conversation_id'] for item in sessions}
@@ -1056,7 +1118,10 @@ def get_chat_messages():
@require_agent_permission
def save_local_message():
"""
保存前端本地生成的聊天记录(如表单、确认弹窗、提交结果等)
保存前端本地生成的聊天记录(如表单、确认弹窗、合同审查结果卡等)。
核心逻辑:user 角色用 content/query 落库;纯文本 assistant 忽略 query 防重复气泡;
结构化 typed 消息(leave-form / procurement-contract-review 等)保留 query,供历史回放与会话标题。
"""
user = getattr(g, 'current_user', None)
agent = getattr(g, 'current_agent', None)
@@ -1073,8 +1138,10 @@ def save_local_message():
user_query = user_query or content
content = ''
else:
# 本地生成的助手/表单消息不能携带 query;历史回放会把 query 渲染成用户气泡。
user_query = ''
# [STEP] 纯文本助手消息忽略误传的 query,避免与已落库用户气泡重复(见回归测试)
# 结构化结果卡必须保留 query,否则刷新后用户提问与历史标题都会丢失
if not message_type or message_type == 'text':
user_query = ''
if not message_type:
raise ValidationError('type is required')
@@ -1090,6 +1157,9 @@ def save_local_message():
external_conversation_id=external_conversation_id,
)
conversation_id = session.session_id
# 纠偏:已有会话若误用审查 headline 作标题,有用户提问时改回提问摘要
if user_query and _looks_like_review_auto_title(session.title or ''):
session.title = _session_title_from_text(user_query)
# 如果 payload 里面包含 formId,且该 formId 已经被保存过,可以直接更新该记录
# 这样能保证前端表单状态(例如已确认)被持久化
@@ -0,0 +1,111 @@
"""
backend/app/api/procurement_contract_tools.py
Purpose: Chat/tool-facing procurement contract review APIs.
Dependencies: procurement_contract services, JWT current user, unified response envelope.
Flow: Authenticated users upload comparison files, start reviews, query own history, and download own reports.
"""
from __future__ import annotations
import io
from flask import Blueprint, g, request, send_file
from app.core.auth.jwt import get_current_user
from app.core.errors import UnauthorizedError, ValidationError
from app.core.response import ok
from app.services.procurement_contract import review_service, template_service
procurement_contract_bp = Blueprint("procurement_contract", __name__)
def _require_user():
"""Return current authenticated user."""
user = get_current_user()
if not user:
raise UnauthorizedError()
return user
def _optional_int(value, field: str) -> int | None:
"""Parse optional int payload fields with a ValidationError on bad input."""
if value in (None, ""):
return None
try:
return int(value)
except (TypeError, ValueError) as exc:
raise ValidationError(f"{field} must be integer") from exc
@procurement_contract_bp.route("/templates", methods=["GET"])
def list_enabled_templates():
"""List enabled templates for chat dropdown."""
_require_user()
return ok(template_service.list_enabled_for_chat(), request_id=getattr(g, "request_id", None))
@procurement_contract_bp.route("/reviews", methods=["POST"])
def start_contract_review():
"""Start a review; compare mode requires a user-uploaded original contract baseline."""
user = _require_user()
data = request.get_json() or {}
contract_asset_no = (data.get("contract_asset_no") or "").strip()
if not contract_asset_no:
raise ValidationError("contract_asset_no is required")
result = review_service.start_review(
user_id=user.id,
review_mode=str(data.get("review_mode") or "compare"),
contract_asset_no=contract_asset_no,
original_contract_asset_no=(data.get("original_contract_asset_no") or None),
contract_type=(data.get("contract_type") or None),
supplier_name=(data.get("supplier_name") or None),
agent_id=_optional_int(data.get("agent_id"), "agent_id"),
chat_log_id=_optional_int(data.get("chat_log_id"), "chat_log_id"),
)
return ok(result, request_id=getattr(g, "request_id", None), status=202)
@procurement_contract_bp.route("/reviews/<review_no>", methods=["GET"])
def get_contract_review(review_no: str):
"""Get a current user's review by review number."""
user = _require_user()
return ok(review_service.get_review_for_owner(review_no=review_no, user_id=user.id), request_id=getattr(g, "request_id", None))
@procurement_contract_bp.route("/reviews/<review_no>/report", methods=["GET"])
def download_my_contract_review_report(review_no: str):
"""Download current user's review report as txt or docx."""
user = _require_user()
review_service.get_review_for_owner(review_no=review_no, user_id=user.id)
if (request.args.get("format") or "").lower() == "docx":
name, data, mimetype = review_service.read_review_report_docx_bytes(review_no=review_no)
else:
name, data = review_service.read_review_report_bytes(review_no=review_no)
mimetype = "text/plain; charset=utf-8"
return send_file(io.BytesIO(data), mimetype=mimetype, as_attachment=True, download_name=name)
@procurement_contract_bp.route("/reviews/<review_no>/annotated-contract", methods=["GET"])
def download_my_annotated_contract(review_no: str):
"""Download current user's original PDF with anchored risk highlights."""
user = _require_user()
review_service.get_review_for_owner(review_no=review_no, user_id=user.id)
name, data, mimetype = review_service.read_review_annotated_contract_bytes(review_no=review_no)
return send_file(io.BytesIO(data), mimetype=mimetype, as_attachment=True, download_name=name)
@procurement_contract_bp.route("/reviews", methods=["GET"])
def list_my_contract_reviews():
"""List current user's recent procurement contract reviews."""
user = _require_user()
data = review_service.list_reviews(
user_id=user.id,
review_mode=request.args.get("review_mode") or None,
status=request.args.get("status") or None,
keyword=request.args.get("keyword") or None,
risk_level=request.args.get("risk_level") or None,
limit=_optional_int(request.args.get("limit"), "limit") or 20,
offset=_optional_int(request.args.get("offset"), "offset") or 0,
)
return ok(data, request_id=getattr(g, "request_id", None))
+40
View File
@@ -102,6 +102,46 @@ class Config:
DIFY_API_KEY = os.getenv('DIFY_API_KEY')
DIFY_CHAT_CONNECT_TIMEOUT_SECONDS = int(os.getenv('DIFY_CHAT_CONNECT_TIMEOUT_SECONDS', '5'))
DIFY_CHAT_READ_TIMEOUT_SECONDS = int(os.getenv('DIFY_CHAT_READ_TIMEOUT_SECONDS', '30'))
PROCUREMENT_CONTRACT_LLM_ENABLED = os.getenv('PROCUREMENT_CONTRACT_LLM_ENABLED', 'false').lower() == 'true'
# 合同审核可独立复用 Chatflow;未配置时按 Agent 的 dify_app_type 判断。
PROCUREMENT_CONTRACT_LLM_PROVIDER = os.getenv('PROCUREMENT_CONTRACT_LLM_PROVIDER', 'agent').strip().lower()
PROCUREMENT_CONTRACT_LLM_AGENT_ID = int(os.getenv('PROCUREMENT_CONTRACT_LLM_AGENT_ID') or '0')
PROCUREMENT_CONTRACT_LLM_DIFY_APP_ID = os.getenv('PROCUREMENT_CONTRACT_LLM_DIFY_APP_ID', '').strip()
PROCUREMENT_CONTRACT_LLM_DIFY_API_KEY = os.getenv('PROCUREMENT_CONTRACT_LLM_DIFY_API_KEY', '').strip()
PROCUREMENT_CONTRACT_LLM_DIFY_BASE = os.getenv('PROCUREMENT_CONTRACT_LLM_DIFY_BASE', '').strip()
PROCUREMENT_CONTRACT_LLM_CONNECT_TIMEOUT_SECONDS = int(
os.getenv('PROCUREMENT_CONTRACT_LLM_CONNECT_TIMEOUT_SECONDS') or '5'
)
PROCUREMENT_CONTRACT_LLM_READ_TIMEOUT_SECONDS = int(
os.getenv('PROCUREMENT_CONTRACT_LLM_READ_TIMEOUT_SECONDS') or '120'
)
# 合同审核清洗产物与异步任务配置;目录仅供 HXOPS 读写,不直接暴露给 Dify。
PROCUREMENT_CONTRACT_STORAGE_ROOT = _data_path('PROCUREMENT_CONTRACT_STORAGE_ROOT', 'procurement_contract')
PROCUREMENT_CONTRACT_JOB_TIMEOUT_SECONDS = float(
os.getenv('PROCUREMENT_CONTRACT_JOB_TIMEOUT_SECONDS') or '600'
)
PROCUREMENT_CONTRACT_LLM_MAX_TEXT_CHARS = int(
os.getenv('PROCUREMENT_CONTRACT_LLM_MAX_TEXT_CHARS') or '120000'
)
PROCUREMENT_CONTRACT_LLM_MAX_CLAUSES = int(
os.getenv('PROCUREMENT_CONTRACT_LLM_MAX_CLAUSES') or '160'
)
# MinerU 仅在显式配置服务地址后接管 PDF 解析;Word 与服务故障仍复用现有清洗链路。
PROCUREMENT_CONTRACT_MINERU_API_URL = os.getenv('PROCUREMENT_CONTRACT_MINERU_API_URL', '').strip().rstrip('/')
PROCUREMENT_CONTRACT_MINERU_BACKEND = os.getenv('PROCUREMENT_CONTRACT_MINERU_BACKEND', 'pipeline').strip()
PROCUREMENT_CONTRACT_MINERU_PARSE_METHOD = os.getenv('PROCUREMENT_CONTRACT_MINERU_PARSE_METHOD', 'auto').strip()
PROCUREMENT_CONTRACT_MINERU_CONNECT_TIMEOUT_SECONDS = int(
os.getenv('PROCUREMENT_CONTRACT_MINERU_CONNECT_TIMEOUT_SECONDS') or '5'
)
PROCUREMENT_CONTRACT_MINERU_READ_TIMEOUT_SECONDS = int(
os.getenv('PROCUREMENT_CONTRACT_MINERU_READ_TIMEOUT_SECONDS') or '300'
)
# 合同产物归档到独立私有 MinIO 桶;本地目录仅作为审核过程和按需恢复缓存。
PROCUREMENT_CONTRACT_ARCHIVE_ENABLED = os.getenv('PROCUREMENT_CONTRACT_ARCHIVE_ENABLED', 'true').lower() == 'true'
PROCUREMENT_CONTRACT_ARCHIVE_BUCKET = os.getenv('PROCUREMENT_CONTRACT_ARCHIVE_BUCKET', 'procurement-contract').strip()
PROCUREMENT_CONTRACT_ARCHIVE_CLEANUP_LOCAL = (
os.getenv('PROCUREMENT_CONTRACT_ARCHIVE_CLEANUP_LOCAL', 'true').lower() == 'true'
)
# Redis 连接配置,默认使用本地 Redis + 密码
REDIS_URL = os.getenv('REDIS_URL')
FEEDBACK_ENABLED = os.getenv('FEEDBACK_ENABLED', 'true').lower() == 'true'
+1 -1
View File
@@ -5,4 +5,4 @@ backend/app/jobs/handlers/__init__.py
逻辑:Wave 2 起在 worker 启动前 import 本包。
"""
from app.jobs.handlers import file_check_run, kb_clean, kb_dify_sync, schedule_run, shipping_notice_parse, shipping_notice_run, wecom_directory_sync # noqa: F401
from app.jobs.handlers import file_check_run, kb_clean, kb_dify_sync, procurement_contract_review, schedule_run, shipping_notice_parse, shipping_notice_run, wecom_directory_sync # noqa: F401
@@ -0,0 +1,48 @@
"""
backend/app/jobs/handlers/procurement_contract_review.py
用途:采购合同清洗、确定性分析与 Dify 全面审核的异步任务处理器。
依赖:jobs.registry、models.Job、procurement_contract.review_service。
逻辑:contract 队列领取任务后按 review_no 执行审核;仅在重试次数耗尽时把业务审核标记为 failed。
"""
from __future__ import annotations
from app import db
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.models import Job
from app.services.procurement_contract import review_service
@register_handler(JobType.PROCUREMENT_CONTRACT_REVIEW)
def run_procurement_contract_review(ctx: JobContext, payload: dict) -> None:
"""
执行一份采购合同后台审核。
Args:
ctx: Worker 上下文,用于记录运行日志。
payload: 必须包含 review_no;job_id 由通用队列注入。
Raises:
RuntimeError: 审核失败时抛出,由通用队列决定重试或终态失败。
"""
review_no = str(payload.get("review_no") or "").strip()
job_id = int(payload.get("job_id") or 0)
if not review_no or not job_id:
raise RuntimeError("review_no and job_id are required")
try:
result = review_service.execute_review_job(review_no=review_no, job_id=job_id)
finish_job(job_id, result={"review_no": review_no, "status": "success"}, message="合同审核完成")
ctx.logger.info("contract review completed review_no=%s job_id=%s", review_no, job_id)
except Exception as exc:
db.session.rollback()
job = db.session.get(Job, job_id)
if job and int(job.attempts or 0) >= int(job.max_attempts or 1):
review_service.mark_review_failed(review_no=review_no, error=str(exc))
else:
review_service.mark_review_retrying(review_no=review_no, error=str(exc))
ctx.logger.exception("contract review failed review_no=%s job_id=%s", review_no, job_id)
raise
+21 -1
View File
@@ -3,7 +3,7 @@ backend/app/jobs/store.py
用途:Job 认领与状态读写(Wave 2:KbJob 双轨 adapter,无新表)。
依赖:KbJob、各域 queue_service 的 claim/recover 逻辑。
逻辑:runner 通过 claim_next 获取待执行任务;返回归一化 dict 供 handler 分发。
逻辑:runner 通过 claim_next 获取 kb / shipping / contract 待执行任务;返回归一化 dict 供 handler 分发。
"""
from __future__ import annotations
@@ -79,6 +79,17 @@ def claim_next(*, queues: list[str] | None = None) -> dict[str, Any] | None:
from app.services.shipping_notice.queue_service import recover_stale_shipping_notice_jobs
recover_stale_shipping_notice_jobs()
if JobType.PROCUREMENT_CONTRACT_REVIEW.value in allowed_types:
from app.jobs.queue import recover_stale_jobs
from flask import current_app
from app.services.procurement_contract.review_service import sync_review_after_job_recovery
recover_stale_jobs(
domain="procurement_contract",
timeout_seconds=float(current_app.config.get("PROCUREMENT_CONTRACT_JOB_TIMEOUT_SECONDS", 600)),
job_type=JobType.PROCUREMENT_CONTRACT_REVIEW,
on_recovered=sync_review_after_job_recovery,
)
# [STEP 2] 按队列优先级 claim
for name in queue_names:
@@ -94,6 +105,15 @@ def claim_next(*, queues: list[str] | None = None) -> dict[str, Any] | None:
job = claim_next_shipping_notice_job()
if job:
return _normalize_generic_job(job)
elif name == 'contract':
from app.jobs.queue import claim_next_job
job = claim_next_job(
domain="procurement_contract",
job_types=[JobType.PROCUREMENT_CONTRACT_REVIEW],
)
if job:
return _normalize_generic_job(job)
return None
+2
View File
@@ -19,6 +19,7 @@ class JobType(StrEnum):
SCHEDULE_RUN = 'schedule_run'
FILE_CHECK_RUN = 'file_check_run'
WECOM_DIRECTORY_SYNC = 'wecom_directory_sync'
PROCUREMENT_CONTRACT_REVIEW = 'procurement_contract_review'
class JobStatus(StrEnum):
@@ -50,6 +51,7 @@ _HANDLER_TO_KB_JOB_TYPE: dict[JobType, str] = {
QUEUE_KB_JOB_TYPES: dict[str, frozenset[str]] = {
'kb': frozenset({'clean', 'path_upload', 'sync_dify'}),
'shipping': frozenset({'shipping_notice_run', 'shipping_notice_parse'}),
'contract': frozenset({'procurement_contract_review'}),
}
+4
View File
@@ -17,6 +17,7 @@ from app.models.maintenance import MaintenanceAuditLog, MaintenanceDevice, Maint
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.shipping import (
ShippingBatch,
ShippingInventoryFile,
@@ -74,6 +75,9 @@ __all__ = [
'ShippingNoticeDocument',
'ShippingNoticeCandidate',
'FileAsset',
'ContractTemplate',
'ContractReview',
'ContractRiskRule',
'AgentGuide',
'AgentDirectoryMember',
'TrainingRecord',
+119
View File
@@ -0,0 +1,119 @@
"""
backend/app/models/contract.py
用途:采购合同审查域模型——标准模板库与单次审查记录。
依赖:models.base.Base、users / agents / file_assets FK。
逻辑:Admin 模板库与历史页、Chat/Tool 发起审查均读写本表;不绑定 ScheduleRun。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import JSON, Boolean, DateTime, ForeignKey, Integer, String, Text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
class ContractTemplate(Base):
"""管理员维护的标准采购合同模板。"""
__tablename__ = "contract_templates"
__table_args__ = (
UniqueConstraint("name", "version", name="uq_contract_templates_name_version"),
)
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String(128), nullable=False)
version: Mapped[str] = mapped_column(String(32), nullable=False)
file_asset_id: Mapped[Optional[int]] = mapped_column(ForeignKey("file_assets.id"), nullable=True)
file_name: Mapped[str] = mapped_column(String(255), nullable=False)
contract_type: Mapped[str] = mapped_column(String(64), default="general_procurement", nullable=False, index=True)
applicable_scope: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
change_note: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
comparison_region_config: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
status: Mapped[str] = mapped_column(String(16), default="enabled", nullable=False, index=True)
is_default: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
updated_by: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), 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 ContractReview(Base):
"""一次单合同审查记录(模板比对或单份审核)。"""
__tablename__ = "contract_reviews"
id: Mapped[int] = mapped_column(primary_key=True)
review_no: Mapped[str] = mapped_column(String(64), unique=True, nullable=False, index=True)
agent_id: Mapped[Optional[int]] = mapped_column(ForeignKey("agents.id"), nullable=True, index=True)
user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False, index=True)
chat_log_id: Mapped[Optional[int]] = mapped_column(ForeignKey("chat_logs.id"), nullable=True)
review_mode: Mapped[str] = mapped_column(String(16), nullable=False, index=True) # compare | solo
status: Mapped[str] = mapped_column(String(16), default="pending", nullable=False, index=True)
contract_asset_id: Mapped[Optional[int]] = mapped_column(ForeignKey("file_assets.id"), nullable=True)
contract_file_name: Mapped[str] = mapped_column(String(255), nullable=False)
supplier_name: Mapped[Optional[str]] = mapped_column(String(128), nullable=True, index=True)
# 从对方合同正文抽取的业务合同编号(非审查编号 review_no)
contract_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True, index=True)
contract_type: Mapped[str] = mapped_column(String(64), default="general_procurement", nullable=False, index=True)
template_id: Mapped[Optional[int]] = mapped_column(ForeignKey("contract_templates.id"), nullable=True)
template_source: Mapped[str] = mapped_column(String(16), nullable=False, default="none")
# library | user_upload | none
template_asset_id: Mapped[Optional[int]] = mapped_column(ForeignKey("file_assets.id"), nullable=True)
template_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
total_change_count: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
high_risk_count: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
medium_risk_count: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
low_risk_count: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
summary_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
clauses_json: Mapped[Optional[list[Any]]] = mapped_column(JSON, nullable=True)
report_text: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False, index=True)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False
)
class ContractRiskRule(Base):
"""Configurable procurement contract risk rule used by solo and compare review."""
__tablename__ = "contract_risk_rules"
__table_args__ = (
UniqueConstraint("code", name="uq_contract_risk_rules_code"),
)
id: Mapped[int] = mapped_column(primary_key=True)
code: Mapped[str] = mapped_column(String(64), nullable=False)
contract_type: Mapped[str] = mapped_column(String(64), default="general_procurement", nullable=False, index=True)
clause_category: Mapped[str] = mapped_column(String(64), nullable=False, index=True)
title: Mapped[str] = mapped_column(String(128), nullable=False)
keywords: Mapped[list[Any]] = mapped_column(JSON, nullable=False, default=list)
trigger_type: Mapped[str] = mapped_column(String(32), default="keyword_missing", nullable=False)
risk_level: Mapped[str] = mapped_column(String(16), nullable=False, index=True)
risk_hint: Mapped[str] = mapped_column(Text, nullable=False)
suggestion: Mapped[str] = mapped_column(Text, nullable=False)
negotiation_text: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
status: Mapped[str] = mapped_column(String(16), default="enabled", nullable=False, index=True)
sort_order: Mapped[int] = mapped_column(Integer, default=100, nullable=False)
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
updated_by: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), 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
)
@@ -116,3 +116,17 @@ agent_types:
lock_input_when_running:
type: boolean
default: true
procurement_contract_review:
label: 采购合同审查
conversation_mode_default: task_chat
runtime_provider_default: dify
models:
- ContractTemplate
- ContractReview
required_fields: []
default_capabilities:
file_upload: true
forced_capabilities:
file_upload: true
human_confirm: false
handler_config_schema: {}
+98
View File
@@ -1166,6 +1166,104 @@ class DifyService:
error_msg = json.dumps({'event': 'error', 'message': message})
yield f"data: {error_msg}\n\n"
@staticmethod
def run_chatflow_once(
*,
agent,
query: str,
inputs: dict[str, Any] | None = None,
user: str = "system",
timeout: tuple[int, int] = (5, 120),
) -> dict[str, Any]:
"""
以单次、无持久会话方式调用 Dify Chatflow 并收集最终回答。
核心逻辑:复用 Chatflow 的 `/v1/chat-messages` 和 SSE 协议,但不写 chat_logs、
不传 conversation_id;适用于合同审核等后台结构化任务,返回 message_end 的 answer。
Args:
agent: 含 Dify API Key 的 Chatflow Agent。
query: 传给 Chatflow 的一次性任务提示。
inputs: Dify Start 节点声明的变量。
user: Dify 用户标识,不应使用真实业务用户 ID。
timeout: `(connect_seconds, read_seconds)`。
Returns:
包含 `answer`、`conversation_id`、`message_id` 的字典。
Raises:
RuntimeError: Dify 返回错误事件或未产出最终回答。
requests.RequestException: HTTP 连接、超时或状态码错误。
"""
base_url = agent.api_base_url if getattr(agent, "api_base_url", None) else Config.DIFY_API_BASE
url = DifyService._build_chat_messages_url(base_url)
headers = {
"Authorization": f"Bearer {agent.dify_api_key}",
"Content-Type": "application/json",
}
payload = {
"inputs": DifyService._stringify_inputs(inputs),
"query": str(query or "").strip(),
"response_mode": "streaming",
"user": str(user or "system"),
}
if current_app:
current_app.logger.info(
"[chatflow-once] start agent_id=%s url=%s query_len=%s",
getattr(agent, "id", None),
url,
len(payload["query"]),
)
answer_parts: list[str] = []
final_data: dict[str, Any] = {}
with requests.post(url, headers=headers, json=payload, stream=True, timeout=timeout) as response:
if not response.ok and current_app:
current_app.logger.error(
"[chatflow-once] bad response status=%s url=%s body=%s",
response.status_code,
url,
response.text[:2000],
)
response.raise_for_status()
for line in response.iter_lines():
if not line:
continue
decoded = line.decode("utf-8", errors="replace")
if not decoded.startswith("data: "):
continue
try:
data = json.loads(decoded[6:])
except json.JSONDecodeError:
continue
event = str(data.get("event") or "")
if event == "error":
raise RuntimeError(str(data.get("message") or data))
if event == "message" and data.get("answer"):
answer_parts.append(str(data["answer"]))
if event in {"message_end", "workflow_finished"}:
final_data = data
workflow_data = data.get("data") if isinstance(data.get("data"), dict) else {}
if event == "workflow_finished" and workflow_data.get("status") == "failed":
# Chatflow also emits workflow events; expose the canvas-node error to the review task.
error_text = str(workflow_data.get("error") or "Dify Chatflow workflow failed")
raise RuntimeError(error_text)
final_answer = str(data.get("answer") or "").strip()
if final_answer:
answer_parts = [final_answer]
if event == "message_end":
break
answer = "".join(answer_parts).strip()
if not answer:
raise RuntimeError("Dify Chatflow returned no final answer")
return {
"answer": answer,
"conversation_id": final_data.get("conversation_id"),
"message_id": final_data.get("message_id") or final_data.get("id"),
"event": final_data.get("event") or "message_end",
}
@staticmethod
def _log_chat(
user_id,
@@ -0,0 +1,7 @@
"""
backend/app/services/procurement_contract/__init__.py
用途:采购合同审查域服务包入口。
依赖:template_service、review_service。
逻辑:API / Tool 层从此包导入业务函数。
"""
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,211 @@
"""
backend/app/services/procurement_contract/artifact_archive.py
用途:将采购合同审核的本地运行产物归档至私有 MinIO,并在本地缓存缺失时按需恢复。
依赖:Flask current_app、minio、procurement_contract.preprocessing 的审查目录约定。
逻辑:审核完成后先上传所有文件,再上传 manifest;manifest 成功后本地目录可安全清理,
后续标注合同或 OCR 页码定位通过 manifest 从 MinIO 恢复所需文件。
"""
from __future__ import annotations
import hashlib
import io
import json
import logging
import mimetypes
import shutil
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
from flask import current_app
from minio import Minio
_LOGGER = logging.getLogger(__name__)
_MANIFEST_NAME = "_manifest.json"
def _archive_enabled() -> bool:
"""读取归档开关,关闭时调用方保持本地缓存行为。"""
return bool(current_app.config.get("PROCUREMENT_CONTRACT_ARCHIVE_ENABLED", True))
def _archive_bucket() -> str:
"""获取合同专用私有桶名,拒绝空配置避免误写默认桶。"""
bucket = str(current_app.config.get("PROCUREMENT_CONTRACT_ARCHIVE_BUCKET") or "").strip()
if not bucket:
raise RuntimeError("PROCUREMENT_CONTRACT_ARCHIVE_BUCKET is required")
return bucket
def _archive_client() -> Minio:
"""构造 MinIO 客户端;合同归档不设置 public-read policy。"""
endpoint = str(current_app.config.get("MINIO_ENDPOINT") or "").strip()
if not endpoint:
raise RuntimeError("MINIO_ENDPOINT is required")
return Minio(
endpoint,
access_key=str(current_app.config.get("MINIO_ACCESS_KEY") or ""),
secret_key=str(current_app.config.get("MINIO_SECRET_KEY") or ""),
secure=bool(current_app.config.get("MINIO_SECURE", False)),
)
def _review_root(review_no: str) -> Path:
"""将审查编号限制在存储根目录内,和预处理阶段保持同一目录规则。"""
root = Path(str(current_app.config["PROCUREMENT_CONTRACT_STORAGE_ROOT"])).resolve()
candidate = (root / str(review_no or "").strip()).resolve()
if candidate.parent != root:
raise RuntimeError("invalid review_no")
return candidate
def _object_key(review_no: str, relative_path: Path) -> str:
"""生成稳定对象键,保留审查目录内的相对层级。"""
return f"reviews/{review_no}/{relative_path.as_posix()}"
def _ensure_bucket(client: Minio, bucket: str) -> None:
"""确保私有合同桶存在;禁止继承公开资料桶策略。"""
if not client.bucket_exists(bucket):
client.make_bucket(bucket)
def _file_entry(path: Path, *, root: Path) -> dict[str, Any]:
"""生成可校验的归档清单条目,供恢复时限定允许路径。"""
data = path.read_bytes()
relative = path.relative_to(root)
return {
"path": relative.as_posix(),
"size": len(data),
"sha256": hashlib.sha256(data).hexdigest(),
"content_type": mimetypes.guess_type(path.name)[0] or "application/octet-stream",
}
def archive_review_artifacts(review_no: str) -> dict[str, Any]:
"""
上传一份审核的所有本地产物,并最后写入 manifest 作为完整归档提交标记。
Args:
review_no: 已完成审核编号。
Returns:
归档状态、bucket、对象前缀和文件数量;开关关闭时返回 disabled。
Raises:
RuntimeError: 本地目录不存在或 MinIO 上传失败;调用方必须保留本地目录。
"""
if not _archive_enabled():
return {"status": "disabled"}
root = _review_root(review_no)
if not root.is_dir():
raise RuntimeError(f"review artifact directory not found: {review_no}")
files = sorted(
(path for path in root.rglob("*") if path.is_file() and path.name != _MANIFEST_NAME),
key=lambda path: path.relative_to(root).as_posix(),
)
if not files:
raise RuntimeError(f"review artifact directory is empty: {review_no}")
client = _archive_client()
bucket = _archive_bucket()
_ensure_bucket(client, bucket)
entries: list[dict[str, Any]] = []
for path in files:
entry = _file_entry(path, root=root)
data = path.read_bytes()
client.put_object(
bucket,
_object_key(review_no, Path(entry["path"])),
io.BytesIO(data),
len(data),
content_type=entry["content_type"],
)
entries.append(entry)
manifest = {
"review_no": review_no,
"archived_at": datetime.now(timezone.utc).isoformat(),
"files": entries,
}
manifest_data = json.dumps(manifest, ensure_ascii=False, indent=2).encode("utf-8")
client.put_object(
bucket,
_object_key(review_no, Path(_MANIFEST_NAME)),
io.BytesIO(manifest_data),
len(manifest_data),
content_type="application/json",
)
return {
"status": "archived",
"bucket": bucket,
"prefix": f"reviews/{review_no}/",
"manifest_key": _object_key(review_no, Path(_MANIFEST_NAME)),
"file_count": len(entries),
}
def restore_review_artifact(review_no: str, relative_path: str) -> Path | None:
"""
本地缓存缺失时,从已提交 manifest 的私有归档恢复单个文件。
Args:
review_no: 审查编号。
relative_path: 审查目录下的相对文件路径,不允许绝对路径或父级跳转。
Returns:
已存在或恢复后的本地路径;归档关闭或 manifest 未包含该文件时返回 None。
"""
root = _review_root(review_no)
relative = Path(relative_path)
target = (root / relative).resolve()
if target.parent != root and root not in target.parents:
raise RuntimeError("invalid artifact relative path")
if target.is_file():
return target
if not _archive_enabled():
return None
client = _archive_client()
bucket = _archive_bucket()
try:
response = client.get_object(bucket, _object_key(review_no, Path(_MANIFEST_NAME)))
try:
manifest = json.loads(response.read().decode("utf-8"))
finally:
response.close()
response.release_conn()
allowed = {str(item.get("path")): item for item in manifest.get("files") or [] if isinstance(item, dict)}
entry = allowed.get(relative.as_posix())
if not entry:
return None
response = client.get_object(bucket, _object_key(review_no, relative))
try:
data = response.read()
finally:
response.close()
response.release_conn()
except Exception as exc:
_LOGGER.warning("[contract-review] artifact restore failed review_no=%s path=%s err=%s", review_no, relative, exc)
return None
if hashlib.sha256(data).hexdigest() != str(entry.get("sha256") or ""):
_LOGGER.warning("[contract-review] artifact checksum mismatch review_no=%s path=%s", review_no, relative)
return None
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(data)
return target
def cleanup_local_review_artifacts(review_no: str) -> bool:
"""仅在归档成功后删除本地运行缓存;由环境开关控制,删除失败不影响归档结果。"""
if not bool(current_app.config.get("PROCUREMENT_CONTRACT_ARCHIVE_CLEANUP_LOCAL", True)):
return False
root = _review_root(review_no)
if not root.is_dir():
return False
shutil.rmtree(root)
return True
@@ -0,0 +1,388 @@
"""
backend/app/services/procurement_contract/comparison_regions.py
Purpose: Validate template comparison-region rules and split uploaded contracts into metadata,
body, signature, and attachment scopes.
Dependencies: Standard-library regex/dataclasses only; review_service invokes this before analyze_compare.
Flow: Admin saves validated JSON; compare reviews partition both user-uploaded files and pass only body text
to the existing diff engine while returning metadata and attachment summaries separately.
"""
from __future__ import annotations
import copy
import re
from dataclasses import dataclass
from typing import Any
from app.core.errors import ValidationError
ALLOWED_METADATA_FIELDS = {"title", "version", "contract_no", "buyer", "seller"}
ALLOWED_ATTACHMENT_POLICIES = {"page_count_only"}
CONFIG_ARRAY_FIELDS = (
"metadata_fields",
"body_start_anchors",
"body_end_anchors",
"signature_terms",
"attachment_start_anchors",
)
DEFAULT_COMPARISON_REGION_CONFIG: dict[str, Any] = {
"metadata_fields": ["contract_no", "buyer", "seller", "version"],
"body_start_anchors": ["兹因甲方向乙方购买设备"],
"body_end_anchors": ["本合同一式两份", "以下无正文", "本页以下无正文"],
"signature_terms": ["甲方", "乙方", "盖章", "签署日期", "合同专用章"],
"attachment_start_anchors": ["附件", "性能需求表", "技术协议", "设备配置清单"],
"attachment_policy": "page_count_only",
}
_FIELD_PATTERNS = {
"version": re.compile(r"(?:版本|版次)\s*[::]\s*([^\n;;]{1,40})", re.I),
"contract_no": re.compile(r"(?:合同(?:编号|号)|编号)\s*[::]\s*([^\n;;]{2,128})", re.I),
"buyer": re.compile(r"(?:买方|甲方)\s*[::]\s*([^\n;;((]{2,128})", re.I),
"seller": re.compile(r"(?:卖方|乙方|供应商)\s*[::]\s*([^\n;;((]{2,128})", re.I),
}
@dataclass(frozen=True)
class RegionPartition:
"""Recognized comparison scopes for one uploaded contract."""
metadata: dict[str, str | None]
body: str
signature: str
attachment_pages: int
body_start_anchor: str
body_end_anchor: str
attachment_anchor: str | None
signature_terms_found: list[str]
def default_comparison_region_config() -> dict[str, Any]:
"""Return an isolated V4 default config so callers cannot mutate the shared constant."""
return copy.deepcopy(DEFAULT_COMPARISON_REGION_CONFIG)
def validate_comparison_region_config(value: Any) -> dict[str, Any]:
"""
Validate and normalize a comparison-region JSON object received from Admin.
Args:
value: Dict containing known array fields and attachment_policy.
Returns:
Normalized JSON-safe config with trimmed, deduplicated string arrays.
Raises:
ValidationError: The shape, anchors, metadata field, or policy is unsupported.
"""
if not isinstance(value, dict):
raise ValidationError(
"comparison_region_config must be an object",
code="PROCUREMENT_CONTRACT.INVALID_COMPARISON_REGION_CONFIG",
)
normalized: dict[str, Any] = {}
for field in CONFIG_ARRAY_FIELDS:
raw_items = value.get(field)
if not isinstance(raw_items, list) or not raw_items:
raise ValidationError(
f"{field} must be a non-empty array",
code="PROCUREMENT_CONTRACT.INVALID_COMPARISON_REGION_CONFIG",
details={"field": field},
)
if len(raw_items) > 20:
raise ValidationError(
f"{field} supports at most 20 items",
code="PROCUREMENT_CONTRACT.INVALID_COMPARISON_REGION_CONFIG",
details={"field": field},
)
items: list[str] = []
for raw_item in raw_items:
item = str(raw_item).strip() if isinstance(raw_item, str) else ""
if not item or len(item) > 120:
raise ValidationError(
f"{field} contains an invalid item",
code="PROCUREMENT_CONTRACT.INVALID_COMPARISON_REGION_CONFIG",
details={"field": field},
)
if item not in items:
items.append(item)
normalized[field] = items
unknown_fields = set(normalized["metadata_fields"]) - ALLOWED_METADATA_FIELDS
if unknown_fields:
raise ValidationError(
"metadata_fields contains unsupported fields",
code="PROCUREMENT_CONTRACT.INVALID_COMPARISON_REGION_CONFIG",
details={"field": "metadata_fields", "unknown": sorted(unknown_fields)},
)
policy = str(value.get("attachment_policy") or "").strip()
if policy not in ALLOWED_ATTACHMENT_POLICIES:
raise ValidationError(
"unsupported attachment_policy",
code="PROCUREMENT_CONTRACT.INVALID_COMPARISON_REGION_CONFIG",
details={"field": "attachment_policy", "value": policy},
)
normalized["attachment_policy"] = policy
return normalized
def _compact_with_positions(text: str) -> tuple[str, list[int]]:
"""Build punctuation-insensitive text plus source indexes for robust OCR anchor matching."""
compact: list[str] = []
positions: list[int] = []
for index, char in enumerate(text or ""):
if not char.isalnum():
continue
compact.append(char.lower())
positions.append(index)
return "".join(compact), positions
def _find_anchor(text: str, anchors: list[str], *, start: int = 0) -> tuple[int, int, str] | None:
"""Locate the earliest configured anchor while tolerating OCR whitespace and punctuation noise."""
compact_text, positions = _compact_with_positions(text)
if not compact_text or not positions:
return None
compact_start = next((i for i, source_index in enumerate(positions) if source_index >= start), len(positions))
matches: list[tuple[int, int, str]] = []
for anchor in anchors:
compact_anchor, _ = _compact_with_positions(anchor)
if not compact_anchor:
continue
compact_index = compact_text.find(compact_anchor, compact_start)
if compact_index < 0:
continue
source_start = positions[compact_index]
source_end = positions[min(compact_index + len(compact_anchor) - 1, len(positions) - 1)] + 1
matches.append((source_start, source_end, anchor))
return min(matches, key=lambda item: item[0]) if matches else None
def _body_end_index(text: str, match: tuple[int, int, str]) -> int:
"""Keep the last substantive clause but exclude explicit no-body markers and following signatures."""
start, end, anchor = match
if "无正文" in anchor:
return start
tail = text[end : end + 300]
sentence_end = re.search(r"[。;;\n]", tail)
return end + sentence_end.end() if sentence_end else end
def _extract_metadata(header_text: str, fields: list[str]) -> dict[str, str | None]:
"""Extract configured header fields from text preceding the body start anchor."""
metadata: dict[str, str | None] = {}
for field in fields:
if field == "title":
title = next(
(line.strip() for line in header_text.splitlines() if "合同" in line and len(line.strip()) <= 80),
None,
)
metadata[field] = title
continue
pattern = _FIELD_PATTERNS.get(field)
match = pattern.search(header_text) if pattern else None
metadata[field] = re.sub(r"\s+", "", match.group(1)).strip("::;;。 ")[:128] if match else None
return metadata
def _page_index_for_anchor(page_texts: list[str], anchors: list[str]) -> int | None:
"""Return the page containing a configured body anchor."""
for page_index, page_text in enumerate(page_texts):
if _find_anchor(page_text, anchors):
return page_index
return None
def _attachment_boundary(
page_texts: list[str],
anchors: list[str],
*,
minimum_page_index: int,
) -> tuple[int, str] | None:
"""Find an attachment heading near the start of a page after the body/signature boundary."""
for page_index in range(max(0, minimum_page_index), len(page_texts)):
page_text = page_texts[page_index]
compact_page, _ = _compact_with_positions(page_text)
for anchor in anchors:
match = _find_anchor(page_text, [anchor])
if not match:
continue
compact_prefix, _ = _compact_with_positions(page_text[: match[0]])
# Generic "attachment" wording frequently appears inside body clauses; only accept page headings.
prefix_limit = 45 if anchor in {"附件", "附录"} else 140
if len(compact_prefix) <= prefix_limit and len(compact_page) > len(anchor):
return page_index, anchor
return None
def diagnose_partition(
text: str,
page_texts: list[str],
config: dict[str, Any],
) -> dict[str, Any]:
"""
Report why one uploaded contract can or cannot use comparison-region partitioning.
Args:
text: Cleaned full-document text used by the deterministic comparison.
page_texts: Extracted text for each physical page, including blank pages.
config: Already validated comparison-region config.
Returns:
JSON-safe recognition facts for audit records and Worker warning logs. It does not expose
contract text, only anchor/section availability and the resulting fallback reason.
"""
start_match = _find_anchor(text, config["body_start_anchors"])
end_match = _find_anchor(text, config["body_end_anchors"], start=start_match[1] if start_match else 0)
body_end = _body_end_index(text, end_match) if end_match else None
signature_text = text[body_end:] if body_end is not None else ""
signature_terms_found = [
term for term in config["signature_terms"] if _find_anchor(signature_text, [term])
]
page_text_available = bool(page_texts and any(page.strip() for page in page_texts))
body_start_page = _page_index_for_anchor(page_texts, config["body_start_anchors"]) if page_text_available else None
body_end_page = _page_index_for_anchor(page_texts, config["body_end_anchors"]) if page_text_available else None
attachment = (
_attachment_boundary(
page_texts,
config["attachment_start_anchors"],
minimum_page_index=body_end_page,
)
if body_end_page is not None
else None
)
if not text.strip():
fallback_reason = "clean_text_unavailable"
elif not page_text_available:
fallback_reason = "page_text_unavailable"
elif not start_match:
fallback_reason = "body_start_anchor_missing"
elif not end_match or body_end is None or body_end <= start_match[0]:
fallback_reason = "body_end_anchor_missing"
elif body_start_page is None or body_end_page is None or body_end_page < body_start_page:
fallback_reason = "anchor_page_unavailable"
elif not signature_terms_found:
fallback_reason = "signature_term_missing"
else:
fallback_reason = None
return {
"page_text_available": page_text_available,
"page_count": len(page_texts),
"body_start_anchor": start_match[2] if start_match else None,
"body_end_anchor": end_match[2] if end_match else None,
"body_start_page": body_start_page + 1 if body_start_page is not None else None,
"body_end_page": body_end_page + 1 if body_end_page is not None else None,
"signature_terms_found": signature_terms_found,
"attachment_anchor": attachment[1] if attachment else None,
"attachment_page": attachment[0] + 1 if attachment else None,
"fallback_reason": fallback_reason,
}
def partition_document(
text: str,
page_texts: list[str],
config: dict[str, Any],
) -> RegionPartition | None:
"""
Partition one contract; return None unless required body anchors and reliable pages are available.
Args:
text: Existing cleaned contract text used by analyze_compare.
page_texts: Text extracted page-by-page from the original PDF or converted Word PDF.
config: Already validated comparison-region config.
Returns:
RegionPartition when safe to apply, otherwise None to force legacy full-document comparison.
"""
if not text.strip() or not page_texts or not any(page.strip() for page in page_texts):
return None
start_match = _find_anchor(text, config["body_start_anchors"])
if not start_match:
return None
end_match = _find_anchor(text, config["body_end_anchors"], start=start_match[1])
if not end_match:
return None
body_end = _body_end_index(text, end_match)
if body_end <= start_match[0]:
return None
body_start_page = _page_index_for_anchor(page_texts, config["body_start_anchors"])
body_end_page = _page_index_for_anchor(page_texts, config["body_end_anchors"])
if body_start_page is None or body_end_page is None or body_end_page < body_start_page:
return None
attachment = _attachment_boundary(
page_texts,
config["attachment_start_anchors"],
minimum_page_index=body_end_page,
)
attachment_page = attachment[0] if attachment else len(page_texts)
attachment_pages = max(0, len(page_texts) - attachment_page)
signature_text = text[body_end:]
signature_terms_found = [
term for term in config["signature_terms"] if _find_anchor(signature_text, [term])
]
if not signature_terms_found:
return None
return RegionPartition(
metadata=_extract_metadata(text[: start_match[0]], config["metadata_fields"]),
body=text[start_match[0] : body_end].strip(),
signature=signature_text.strip(),
attachment_pages=attachment_pages,
body_start_anchor=start_match[2],
body_end_anchor=end_match[2],
attachment_anchor=attachment[1] if attachment else None,
signature_terms_found=signature_terms_found,
)
def build_metadata_comparison(
original: dict[str, str | None],
returned: dict[str, str | None],
) -> dict[str, dict[str, str | None]]:
"""Build stable field-by-field statuses without adding metadata changes to clause counts."""
result: dict[str, dict[str, str | None]] = {}
for field in original.keys() | returned.keys():
before = original.get(field)
after = returned.get(field)
if before == after:
status = "unchanged"
elif not before and after:
status = "filled"
elif before and not after:
status = "removed"
else:
status = "changed"
result[field] = {"original": before, "returned": after, "status": status}
return result
def build_attachment_comparison(original_pages: int, returned_pages: int) -> dict[str, Any]:
"""Summarize attachment page deltas without exposing attachment content."""
added = max(0, returned_pages - original_pages)
removed = max(0, original_pages - returned_pages)
status = "added" if added else "removed" if removed else "unchanged"
return {
"status": status,
"original_pages": original_pages,
"returned_pages": returned_pages,
"added_pages": added,
"removed_pages": removed,
}
def preview_anchor_recognition(text: str, config: dict[str, Any]) -> dict[str, Any]:
"""Preview which configured anchors can be recognized in an Admin template file."""
start = _find_anchor(text, config["body_start_anchors"])
end = _find_anchor(text, config["body_end_anchors"], start=start[1] if start else 0)
attachment = _find_anchor(text, config["attachment_start_anchors"], start=end[1] if end else 0)
signature_terms = [term for term in config["signature_terms"] if _find_anchor(text, [term])]
return {
"status": "recognized" if start and end else "incomplete",
"body_start_anchor": start[2] if start else None,
"body_end_anchor": end[2] if end else None,
"signature_terms_found": signature_terms,
"attachment_anchor": attachment[2] if attachment else None,
"warning": None if start and end else "Body start or end anchor was not recognized",
}
@@ -0,0 +1,512 @@
"""
backend/app/services/procurement_contract/llm_enhancer.py
Purpose: Dify Chatflow/Workflow-based comprehensive legal review for cleaned procurement contracts.
Dependencies: Config, DifyService, Agent model.
Flow: review_service passes cleaned text, structured clauses and deterministic findings; Dify Chatflow or Workflow enhances existing findings
and independently returns new legal risks, then this module validates and merges them without lowering deterministic risk.
"""
from __future__ import annotations
import json
import re
from typing import Any
from flask import current_app
from app import db
from app.core.config.settings import Config
from app.models import Agent
from app.services.dify import DifyService
MAX_FINDINGS = 20
MAX_TEXT_CHARS = 900
VALID_RISK_LEVELS = {"high", "medium", "low", "ok"}
RISK_RANK = {"ok": 0, "low": 1, "medium": 2, "high": 3}
def is_enabled() -> bool:
"""Return whether procurement-contract LLM enhancement is enabled by configuration."""
return bool(getattr(Config, "PROCUREMENT_CONTRACT_LLM_ENABLED", False))
def enhance_review_result(
result: dict[str, Any],
*,
review_no: str,
review_mode: str,
contract_type: str | None,
template_name: str | None = None,
clean_text: str = "",
structured_clauses: list[dict[str, Any]] | None = None,
) -> dict[str, Any]:
"""
Ask Dify to enhance deterministic findings and independently scan the cleaned contract.
AI trigger timing: call after HXOPS has cleaned and structured the contract and completed Diff/rule checks.
The LLM must return JSON only; it may add risks and may challenge deterministic findings only with verified evidence.
Args:
result: HXOPS deterministic review result.
review_no/review_mode/contract_type/template_name: Review context passed to Dify.
clean_text: Cleaned contract Markdown text; never pass a server-local path.
structured_clauses: Full ordered clause list generated by HXOPS.
Returns:
Result with enhanced existing findings, validated new_items and Dify audit metadata.
"""
if not is_enabled():
return result
clauses = result.get("clauses_json") if isinstance(result.get("clauses_json"), list) else []
clean_text = str(clean_text or "").strip()
structured_clauses = structured_clauses or []
if not clean_text or not structured_clauses:
return _with_llm_meta(result, enabled=True, status="skipped", message="cleaned contract is unavailable")
agent = _resolve_agent()
if not agent:
return _with_llm_meta(result, enabled=True, status="skipped", message="LLM agent is not configured")
findings = _build_findings_payload(clauses)
max_text_chars = max(int(getattr(Config, "PROCUREMENT_CONTRACT_LLM_MAX_TEXT_CHARS", 120000) or 120000), 10000)
max_clauses = max(int(getattr(Config, "PROCUREMENT_CONTRACT_LLM_MAX_CLAUSES", 160) or 160), 20)
sent_text = clean_text[:max_text_chars]
sent_clauses = structured_clauses[:max_clauses]
input_truncated = len(clean_text) > len(sent_text) or len(structured_clauses) > len(sent_clauses)
inputs = {
"review_no": review_no,
"review_mode": review_mode,
"contract_type": contract_type or "general_procurement",
"template_name": template_name or "",
"findings_json": json.dumps(findings, ensure_ascii=False),
"clauses_json": json.dumps(sent_clauses, ensure_ascii=False),
"clean_text": sent_text,
"scan_enabled": "true",
"scan_scope": "bounded_contract" if input_truncated else "full_contract",
"instruction": _review_instruction(),
}
try:
timeout = (
int(getattr(Config, "PROCUREMENT_CONTRACT_LLM_CONNECT_TIMEOUT_SECONDS", 5) or 5),
int(getattr(Config, "PROCUREMENT_CONTRACT_LLM_READ_TIMEOUT_SECONDS", 120) or 120),
)
provider = _review_provider(agent)
if provider == "chatflow":
response = DifyService.run_chatflow_once(
agent=agent,
query=_chatflow_review_query(),
inputs=inputs,
user=f"contract-review:{review_no}",
timeout=timeout,
)
enhancements, new_items = _extract_review_output({"answer": response.get("answer")})
workflow_run_id = str(response.get("message_id") or "") or None
else:
response = DifyService.run_workflow_streaming(
agent=agent,
inputs=inputs,
user=f"contract-review:{review_no}",
timeout=timeout,
)
enhancements, new_items = _extract_review_output(response)
workflow_run_id = _workflow_run_id(response)
except Exception as exc: # noqa: BLE001 - enhancement must not fail deterministic review
if current_app:
current_app.logger.warning("[contract-llm] enhance failed review_no=%s err=%s", review_no, exc)
return _with_llm_meta(result, enabled=True, status="failed", message=str(exc)[:500])
if not enhancements and not new_items:
return _with_llm_meta(result, enabled=True, status="empty", message="LLM returned no usable review items")
merged = _merge_review_output(
result,
enhancements,
new_items,
clean_text=clean_text,
structured_clauses=structured_clauses,
)
summary = merged.get("summary_json") if isinstance(merged.get("summary_json"), dict) else {}
summary["llm_input"] = {
"text_characters": len(clean_text),
"sent_text_characters": len(sent_text),
"clause_count": len(structured_clauses),
"sent_clause_count": len(sent_clauses),
"truncated": input_truncated,
}
merged["summary_json"] = summary
return _with_llm_meta(
merged,
enabled=True,
status="success",
message="Dify comprehensive review applied",
provider=provider,
workflow_run_id=workflow_run_id,
)
def _resolve_agent() -> Agent | None:
"""Resolve the configured Dify Chatflow or Workflow agent used for contract review."""
agent_id = int(getattr(Config, "PROCUREMENT_CONTRACT_LLM_AGENT_ID", 0) or 0)
if agent_id:
row = db.session.get(Agent, agent_id)
if row and row.is_active and row.dify_api_key:
return row
app_id = str(getattr(Config, "PROCUREMENT_CONTRACT_LLM_DIFY_APP_ID", "") or "").strip()
if app_id:
row = db.session.query(Agent).filter(Agent.dify_app_id == app_id, Agent.is_active.is_(True)).first()
if row and row.dify_api_key:
return row
api_key = str(getattr(Config, "PROCUREMENT_CONTRACT_LLM_DIFY_API_KEY", "") or "").strip()
if api_key:
return Agent(
id=0,
name="Procurement Contract LLM Enhancer",
dify_api_key=api_key,
api_base_url=str(getattr(Config, "PROCUREMENT_CONTRACT_LLM_DIFY_BASE", "") or "").strip() or Config.DIFY_API_BASE,
dify_app_type="workflow",
)
return None
def _review_provider(agent: Agent) -> str:
"""Return the configured Dify provider; env override supports reusing a Chatflow during rollout."""
configured = str(getattr(Config, "PROCUREMENT_CONTRACT_LLM_PROVIDER", "agent") or "agent").strip().lower()
if configured in {"chatflow", "workflow"}:
return configured
app_type = str(getattr(agent, "dify_app_type", "") or "").strip().lower()
return "chatflow" if app_type == "chatflow" else "workflow"
def _chatflow_review_query() -> str:
"""
提供给 Chatflow 的一次性任务提示;正式合同内容均通过 Start inputs 传入。
Chatflow 可以沿用普通会话应用,但必须在画布中识别该指令并只输出 JSON,
否则后端会把非 JSON 回答标为无可用审核项。
"""
return "执行合同全面审核任务。请严格根据 Start 输入变量返回 instruction 要求的 JSON,不要输出解释性文字。"
def _build_findings_payload(clauses: list[Any]) -> list[dict[str, Any]]:
"""Build compact findings for LLM consumption without sending the whole contract."""
findings: list[dict[str, Any]] = []
for idx, raw in enumerate(clauses[:MAX_FINDINGS], start=1):
if not isinstance(raw, dict):
continue
findings.append(
{
"id": str(raw.get("clause_no") or idx),
"title": str(raw.get("title") or raw.get("clause_category") or f"finding-{idx}")[:120],
"change_type": str(raw.get("change_type") or ""),
"rule_risk_level": str(raw.get("risk_level") or ""),
"category": str(raw.get("clause_category") or ""),
"rule_detail": _clip(raw.get("detail")),
"rule_risk_hint": _clip(raw.get("risk_hint")),
"rule_suggestion": _clip(raw.get("suggestion")),
"template_excerpt": _clip(raw.get("old_text"), 450),
"contract_excerpt": _clip(raw.get("new_text"), 450),
}
)
return findings
def _review_instruction() -> str:
"""Build the versioned instruction consumed by the Chatflow review branch's LLM node."""
# [PROMPT_UPDATE] 2026-07-21: 增加带原文证据和置信度门槛的 confirm/reject/uncertain 纠错协议。
return (
"你是企业采购方合同审核助手。输入包含 clean_text、clauses_json、findings_json。"
"必须逐条覆盖 clauses_json,并结合全文检查付款、交付、验收、质保、违约赔偿、免责、"
"责任上限、知识产权、保密数据、解除续期、不可抗力、争议解决以及跨条款冲突。"
"items 用于增强 findings_json 已有项;new_items 用于返回后端未发现的新风险。"
"每个 new_item 必须引用真实 clause_id/clause_no,并给出合同原文 evidence;禁止编造法条编号。"
"返回严格 JSON:{\"items\":[{\"id\":\"1\",\"decision\":\"confirm|reject|uncertain\",\"evidence\":\"合同原文\",\"professional_reason\":\"...\","
"\"professional_suggestion\":\"...\",\"negotiation_text\":\"...\","
"\"model_risk_level\":\"high|medium|low|ok\",\"confidence\":0.0}],"
"\"new_items\":[{\"id\":\"llm-1\",\"clause_id\":\"clause-0001\","
"\"clause_no\":\"第八条\",\"title\":\"...\",\"clause_category\":\"liability\","
"\"risk_level\":\"high|medium|low\",\"professional_reason\":\"...\","
"\"business_impact\":\"...\",\"professional_suggestion\":\"...\","
"\"negotiation_text\":\"...\",\"evidence\":\"合同原文\",\"confidence\":0.0}]}."
"已有项若规则结论正确返回 confirm;若原文明确证明规则误报可返回 reject;OCR 无法确认返回 uncertain。"
"reject 必须引用能直接反驳规则结论的真实合同原文,且 confidence 不低于0.8;confidence 必须为 0 到 1。"
)
def _clip(value: Any, limit: int = MAX_TEXT_CHARS) -> str:
"""Normalize and clip text sent to or returned from the LLM."""
text = re.sub(r"\s+", " ", str(value or "")).strip()
if len(text) <= limit:
return text
return text[:limit] + "..."
def _extract_review_output(
workflow_result: dict[str, Any] | None,
) -> tuple[dict[str, dict[str, Any]], list[dict[str, Any]]]:
"""Parse Dify outputs into existing-finding enhancements and independent new risks."""
data = workflow_result if isinstance(workflow_result, dict) else {}
outputs = data.get("outputs") if isinstance(data.get("outputs"), dict) else {}
direct_output = None
if outputs.get("items") is not None or outputs.get("new_items") is not None:
direct_output = {
"items": _parse_json_candidate(outputs.get("items")) or outputs.get("items") or [],
"new_items": _parse_json_candidate(outputs.get("new_items")) or outputs.get("new_items") or [],
}
candidates = [
direct_output,
outputs.get("items"),
outputs.get("enhancements"),
outputs.get("result"),
outputs.get("text"),
outputs.get("output"),
data.get("answer"),
]
parsed: Any = None
for candidate in candidates:
parsed = _parse_json_candidate(candidate)
if parsed:
break
raw_new_items: list[Any] = []
if isinstance(parsed, dict):
raw_items = parsed.get("items") or parsed.get("enhancements") or []
raw_new_items = parsed.get("new_items") or parsed.get("newItems") or []
elif isinstance(parsed, list):
raw_items = parsed
else:
raw_items = []
out: dict[str, dict[str, Any]] = {}
for item in raw_items:
if not isinstance(item, dict):
continue
item_id = str(item.get("id") or item.get("clause_no") or "").strip()
if not item_id:
continue
confidence = _normalize_confidence(item.get("confidence"))
level = str(item.get("model_risk_level") or item.get("risk_level") or "").strip().lower()
if level not in VALID_RISK_LEVELS:
level = ""
decision = str(item.get("decision") or "confirm").strip().lower()
if decision not in {"confirm", "reject", "uncertain"}:
decision = "confirm"
out[item_id] = {
"llm_reason": _clip(item.get("professional_reason") or item.get("reason") or item.get("detail")),
"llm_suggestion": _clip(item.get("professional_suggestion") or item.get("suggestion")),
"llm_negotiation_text": _clip(item.get("negotiation_text")),
"llm_model_risk_level": level,
"llm_confidence": confidence,
"llm_decision": decision,
"llm_evidence": _clip(item.get("evidence"), 1200),
}
new_items = [item for item in raw_new_items if isinstance(item, dict)]
return out, new_items
def _parse_json_candidate(value: Any) -> Any:
"""Parse a Dify output value that may already be JSON or may be JSON text."""
if isinstance(value, (dict, list)):
return value
if not isinstance(value, str) or not value.strip():
return None
text = value.strip()
try:
return json.loads(text)
except json.JSONDecodeError:
pass
match = re.search(r"```(?:json)?\s*(.*?)```", text, flags=re.S)
if match:
try:
return json.loads(match.group(1).strip())
except json.JSONDecodeError:
return None
start = min([i for i in [text.find("{"), text.find("[")] if i >= 0], default=-1)
end = max(text.rfind("}"), text.rfind("]"))
if start >= 0 and end > start:
try:
return json.loads(text[start : end + 1])
except json.JSONDecodeError:
return None
return None
def _normalize_confidence(value: Any) -> float | None:
"""Normalize confidence to 0..1."""
try:
num = float(value)
except (TypeError, ValueError):
return None
if num > 1:
num = num / 100
return max(0.0, min(1.0, round(num, 2)))
def _normalize_evidence(value: Any) -> str:
"""归一化证据文本,供原文包含校验和结果展示。"""
return re.sub(r"\s+", "", str(value or "")).strip()
def _merge_review_output(
result: dict[str, Any],
enhancements: dict[str, dict[str, Any]],
new_items: list[dict[str, Any]],
*,
clean_text: str,
structured_clauses: list[dict[str, Any]],
) -> dict[str, Any]:
"""
合并 Dify 对已有发现的增强及其独立发现,并执行证据、去重和风险等级治理。
Args:
result: HXOPS 确定性结果。
enhancements: finding id 对应的解释增强。
new_items: Dify 独立发现的候选风险。
clean_text/structured_clauses: 用于验证 clause_id 与 evidence 是否真实存在。
Returns:
合并后的结果;证据不足项保留但标记 needs_review,便于采购人员识别不确定结论。
"""
clauses = result.get("clauses_json") if isinstance(result.get("clauses_json"), list) else []
for idx, clause in enumerate(clauses, start=1):
if not isinstance(clause, dict):
continue
item_id = str(clause.get("clause_no") or idx)
extra = enhancements.get(item_id)
if not extra:
continue
clause["llm_enabled"] = True
clause.update({k: v for k, v in extra.items() if v not in ("", None)})
if extra.get("llm_reason"):
clause["detail"] = extra["llm_reason"]
if extra.get("llm_suggestion"):
clause["suggestion"] = extra["llm_suggestion"]
if extra.get("llm_negotiation_text"):
clause["negotiation_text"] = extra["llm_negotiation_text"]
deterministic_level = str(clause.get("risk_level") or "ok").lower()
model_level = str(extra.get("llm_model_risk_level") or "").lower()
decision = str(extra.get("llm_decision") or "confirm")
evidence = str(extra.get("llm_evidence") or "").strip()
evidence_valid = bool(_normalize_evidence(evidence) and _normalize_evidence(evidence) in _normalize_evidence(clean_text))
confidence = extra.get("llm_confidence")
if decision == "reject" and evidence_valid and isinstance(confidence, float) and confidence >= 0.8:
clause["risk_level"] = "ok"
clause["change_type"] = "pass"
clause["validation_status"] = "confirmed"
clause["evidence"] = evidence
clause["detail"] = extra.get("llm_reason") or "原文证据表明该确定性风险未命中。"
elif decision == "uncertain":
clause["validation_status"] = "needs_review"
if evidence_valid:
clause["evidence"] = evidence
elif RISK_RANK.get(model_level, -1) > RISK_RANK.get(deterministic_level, 0):
clause["risk_level"] = model_level
clause_map = {
str(item.get("clause_id") or ""): item
for item in structured_clauses
if isinstance(item, dict) and item.get("clause_id")
}
clause_no_map = {
str(item.get("clause_no") or "").strip(): item
for item in structured_clauses
if isinstance(item, dict) and str(item.get("clause_no") or "").strip()
}
normalized_contract = _normalize_evidence(clean_text)
fingerprints = {
_normalize_evidence(
f"{item.get('clause_no') or ''}|{item.get('title') or ''}|{item.get('detail') or ''}"
)[:240]
for item in clauses
if isinstance(item, dict)
}
accepted = 0
needs_review = 0
for idx, raw in enumerate(new_items, start=1):
clause_id = str(raw.get("clause_id") or "").strip()
requested_clause_no = str(raw.get("clause_no") or "").strip()
linked_clause = clause_map.get(clause_id) or clause_no_map.get(requested_clause_no)
evidence = _clip(raw.get("evidence"), 1200)
evidence_key = _normalize_evidence(evidence)
evidence_valid = bool(evidence_key and evidence_key in normalized_contract)
clause_valid = bool(linked_clause)
title = _clip(raw.get("title") or "AI 新发现风险", 120)
reason = _clip(raw.get("professional_reason") or raw.get("legal_reason") or raw.get("reason"))
fingerprint = _normalize_evidence(
f"{raw.get('clause_no') or (linked_clause or {}).get('clause_no') or ''}|{title}|{reason}"
)[:240]
if not fingerprint or fingerprint in fingerprints:
continue
level = str(raw.get("risk_level") or raw.get("model_risk_level") or "medium").lower()
if level not in {"high", "medium", "low"}:
level = "medium"
confidence = _normalize_confidence(raw.get("confidence"))
validation_status = "confirmed" if clause_valid and evidence_valid else "needs_review"
item = {
"clause_no": str(
requested_clause_no or (linked_clause or {}).get("clause_no") or f"AI-{idx}"
),
"clause_id": clause_id or None,
"title": title,
"clause_category": str(
raw.get("clause_category") or raw.get("category") or (linked_clause or {}).get("category") or "other"
),
"change_type": "llm_scan",
"risk_level": level,
"detail": reason or "大模型识别到潜在合同风险。",
"risk_hint": reason,
"business_impact": _clip(raw.get("business_impact")),
"suggestion": _clip(raw.get("professional_suggestion") or raw.get("suggestion")),
"negotiation_text": _clip(raw.get("negotiation_text")),
"evidence": evidence,
"source": "llm",
"llm_enabled": True,
"llm_confidence": confidence,
"llm_reason": reason,
"llm_model_risk_level": level,
"validation_status": validation_status,
}
clauses.append(item)
fingerprints.add(fingerprint)
accepted += 1
if validation_status == "needs_review":
needs_review += 1
result["clauses_json"] = clauses
summary = result.get("summary_json") if isinstance(result.get("summary_json"), dict) else {}
summary["llm_new_findings"] = {"accepted": accepted, "needs_review": needs_review}
result["summary_json"] = summary
return result
def _with_llm_meta(
result: dict[str, Any],
*,
enabled: bool,
status: str,
message: str,
provider: str | None = None,
workflow_run_id: str | None = None,
) -> dict[str, Any]:
"""Attach LLM enhancement metadata to summary_json."""
summary = result.get("summary_json") if isinstance(result.get("summary_json"), dict) else {}
summary["llm_enhancement"] = {
"enabled": enabled,
"status": status,
"message": message,
"provider": provider,
"workflow_run_id": workflow_run_id,
}
result["summary_json"] = summary
return result
def _workflow_run_id(workflow_result: dict[str, Any] | None) -> str | None:
"""Read Dify workflow run id from gateway metadata."""
if not isinstance(workflow_result, dict):
return None
value = workflow_result.get("workflow_run_id") or workflow_result.get("id")
return str(value) if value else None
@@ -0,0 +1,381 @@
"""
backend/app/services/procurement_contract/pdf_annotation.py
用途:把合同审核发现锚定到原 PDF 页码/坐标,并生成带标准高亮批注的合同副本。
依赖:pypdfium2 提取逐字坐标;pypdf 写入 Highlight annotation。
逻辑:审核结果合并后调用 enrich_result_with_pdf_anchors → 条款写入 evidence_anchor;
下载时文本型 PDF 复用坐标绘制高亮,扫描 PDF 按 OCR 分页正文定位原页并添加批注意见。
"""
from __future__ import annotations
import difflib
import io
import re
import unicodedata
from typing import Any
MAX_ANCHOR_CANDIDATES = 6
MAX_ANCHOR_CHARS = 180
MIN_FUZZY_ANCHOR_CHARS = 10
MIN_FUZZY_SCORE = 0.82
PAGE_IMAGE_MARKER_RE = re.compile(r"!\[page-image-(\d+)\]", re.IGNORECASE)
def _compact_text(value: Any) -> str:
"""归一化空白和全半角,保留字符顺序供 PDF 搜索。"""
text = unicodedata.normalize("NFKC", str(value or ""))
return re.sub(r"\s+", "", text).strip()
def _candidate_texts(item: dict[str, Any]) -> list[str]:
"""
按证据可靠性生成 PDF 锚定候选文本。
比对模式优先合同侧 new_text;单份审核优先 evidence。建议、原因和谈判话术不是合同原文,
禁止作为锚点候选,避免把模型生成内容标进 PDF。
"""
raw_values = [item.get("new_text"), item.get("evidence")]
candidates: list[str] = []
seen: set[str] = set()
for raw in raw_values:
text = re.sub(r"\s+", " ", str(raw or "")).strip()
if not text:
continue
fragments = [
part.strip(" ,,。;;::()()[]【】")
for part in re.split(r"\n+|(?<=[。!?;;])", text)
if part.strip()
]
for fragment in sorted(fragments or [text], key=len, reverse=True):
compact = _compact_text(fragment)
if len(compact) < 4 or compact in seen:
continue
seen.add(compact)
candidates.append(fragment[:MAX_ANCHOR_CHARS])
if len(candidates) >= MAX_ANCHOR_CANDIDATES:
return candidates
return candidates
def _ocr_pages(clean_text: str) -> list[tuple[int, str]]:
"""按清洗 Markdown 的 page-image 标记拆分 OCR 扫描件页文本。"""
matches = list(PAGE_IMAGE_MARKER_RE.finditer(str(clean_text or "")))
pages: list[tuple[int, str]] = []
for index, match in enumerate(matches):
start = match.end()
end = matches[index + 1].start() if index + 1 < len(matches) else len(clean_text)
pages.append((int(match.group(1)), clean_text[start:end]))
return pages
def locate_ocr_evidence_page(clean_text: str, item: dict[str, Any]) -> dict[str, Any] | None:
"""
扫描 PDF 无文本坐标时,用 OCR 分页正文可靠定位证据所在页。
Returns:
命中时返回 page_no/source_text/confidence/method,不生成伪造矩形坐标。
"""
pages = _ocr_pages(clean_text)
candidates = _candidate_texts(item)
if not pages or not candidates:
return None
best: dict[str, Any] | None = None
for page_no, page_text in pages:
page_key = _compact_text(page_text)
if not page_key:
continue
for candidate in candidates:
candidate_key = _compact_text(candidate)
if len(candidate_key) < 4:
continue
if candidate_key in page_key:
return {
"page_no": page_no,
"rects": [],
"matched_text": candidate,
"source_text": candidate,
"confidence": 1.0,
"method": "ocr_page",
}
window_size = min(len(candidate_key), 80)
if window_size < MIN_FUZZY_ANCHOR_CHARS or len(page_key) < window_size:
continue
candidate_window = candidate_key[:window_size]
step = max(1, window_size // 12)
score = max(
difflib.SequenceMatcher(
a=candidate_window,
b=page_key[start : start + window_size],
autojunk=False,
).ratio()
for start in range(0, len(page_key) - window_size + 1, step)
)
if score >= MIN_FUZZY_SCORE and (best is None or score > best["confidence"]):
best = {
"page_no": page_no,
"rects": [],
"matched_text": candidate,
"source_text": candidate,
"confidence": round(score, 3),
"method": "ocr_page",
}
return best
def _merge_char_rects(rects: list[tuple[float, float, float, float]]) -> list[list[float]]:
"""把同一文本行的逐字坐标合并成适合高亮显示的矩形。"""
if not rects:
return []
ordered = sorted(rects, key=lambda rect: (-rect[3], rect[0]))
lines: list[list[float]] = []
for left, bottom, right, top in ordered:
if not lines:
lines.append([left, bottom, right, top])
continue
current = lines[-1]
vertical_overlap = min(current[3], top) - max(current[1], bottom)
min_height = max(1.0, min(current[3] - current[1], top - bottom))
if vertical_overlap / min_height >= 0.45:
current[0] = min(current[0], left)
current[1] = min(current[1], bottom)
current[2] = max(current[2], right)
current[3] = max(current[3], top)
else:
lines.append([left, bottom, right, top])
return [[round(value, 2) for value in rect] for rect in lines]
def _exact_anchor(textpage: Any, candidate: str) -> dict[str, Any] | None:
"""使用 PDFium 原生搜索返回首个精确文本命中的坐标。"""
query = re.sub(r"\s+", "", candidate)
if len(query) < 4:
return None
searcher = textpage.search(query, match_case=False)
occurrence = searcher.get_next()
if not occurrence:
return None
index, count = occurrence
rects = [textpage.get_charbox(char_index) for char_index in range(index, index + count)]
return {
"char_index": int(index),
"char_count": int(count),
"rects": _merge_char_rects(rects),
"matched_text": textpage.get_text_range(index, count),
"confidence": 1.0,
"method": "exact",
}
def _fuzzy_anchor(page_text: str, textpage: Any, candidate: str) -> dict[str, Any] | None:
"""精确搜索失败时,在去空白页文本上做受限滑窗匹配并映射回原字符坐标。"""
compact_page_chars: list[str] = []
compact_to_raw: list[int] = []
for raw_index, char in enumerate(page_text):
normalized = _compact_text(char)
if not normalized:
continue
compact_page_chars.append(normalized)
compact_to_raw.append(raw_index)
page_key = "".join(compact_page_chars)
candidate_key = _compact_text(candidate)
if len(candidate_key) < MIN_FUZZY_ANCHOR_CHARS or len(page_key) < len(candidate_key):
return None
window_size = min(len(candidate_key), 80)
candidate_window = candidate_key[:window_size]
best_score = 0.0
best_start = -1
exact_start = page_key.find(candidate_window)
if exact_start >= 0:
best_score = 1.0
best_start = exact_start
step = max(1, window_size // 12)
for start in range(0, len(page_key) - window_size + 1, step):
if best_score == 1.0:
break
window = page_key[start : start + window_size]
score = difflib.SequenceMatcher(a=candidate_window, b=window, autojunk=False).ratio()
if score > best_score:
best_score = score
best_start = start
if best_start < 0 or best_score < MIN_FUZZY_SCORE:
return None
raw_start = compact_to_raw[best_start]
raw_end_index = min(best_start + window_size - 1, len(compact_to_raw) - 1)
raw_end = compact_to_raw[raw_end_index]
count = max(1, raw_end - raw_start + 1)
rects = [textpage.get_charbox(char_index) for char_index in range(raw_start, raw_start + count)]
return {
"char_index": int(raw_start),
"char_count": int(count),
"rects": _merge_char_rects(rects),
"matched_text": textpage.get_text_range(raw_start, count),
"confidence": round(best_score, 3),
"method": "fuzzy",
}
def locate_pdf_evidence(pdf_bytes: bytes, item: dict[str, Any]) -> dict[str, Any] | None:
"""
在 PDF 中定位一个审核发现的合同原文证据。
Args:
pdf_bytes: 原合同 PDF 字节。
item: 审核发现项,仅使用 new_text/evidence 字段。
Returns:
成功时返回 page_no、rects、matched_text、confidence;无法可靠定位时返回 None。
"""
import pypdfium2 as pdfium
candidates = _candidate_texts(item)
if not candidates:
return None
document = pdfium.PdfDocument(pdf_bytes)
try:
best: dict[str, Any] | None = None
for page_index in range(len(document)):
page = document[page_index]
textpage = page.get_textpage()
page_text = textpage.get_text_range()
for candidate in candidates:
located = _exact_anchor(textpage, candidate)
if located is None:
located = _fuzzy_anchor(page_text, textpage, candidate)
if located is None:
continue
located["page_no"] = page_index + 1
located["source_text"] = candidate
if located["method"] == "exact":
return located
if best is None or located["confidence"] > best["confidence"]:
best = located
return best
finally:
document.close()
def enrich_result_with_pdf_anchors(
result: dict[str, Any],
*,
filename: str,
pdf_bytes: bytes,
) -> dict[str, Any]:
"""
给审核结果逐项写入 PDF 证据锚点和定位统计;失败不会中断审核主流程。
Args:
result: 已完成规则和 LLM 合并的审核结果。
filename: 原合同文件名;非 PDF 时直接标记 unsupported。
pdf_bytes: 原合同字节。
Returns:
原 result 的更新版本。
"""
clauses = result.get("clauses_json") if isinstance(result.get("clauses_json"), list) else []
summary = result.get("summary_json") if isinstance(result.get("summary_json"), dict) else {}
if not str(filename or "").lower().endswith(".pdf"):
summary["evidence_anchoring"] = {"status": "unsupported", "anchored": 0, "unanchored": len(clauses)}
result["summary_json"] = summary
return result
anchored = 0
attempted = 0
for item in clauses:
if not isinstance(item, dict) or item.get("risk_level") == "ok":
continue
attempted += 1
anchor = locate_pdf_evidence(pdf_bytes, item)
if anchor:
item["evidence_anchor"] = anchor
item["anchor_status"] = "anchored"
anchored += 1
else:
item["anchor_status"] = "unanchored"
summary["evidence_anchoring"] = {
"status": "complete",
"anchored": anchored,
"unanchored": max(0, attempted - anchored),
}
result["summary_json"] = summary
return result
def _annotation_color(risk_level: str) -> str:
"""映射风险等级到 PDF 高亮颜色。"""
if risk_level == "high":
return "ff6b6b"
if risk_level == "medium":
return "ffb84d"
return "ffe066"
def build_annotated_pdf_bytes(
pdf_bytes: bytes,
clauses: list[dict[str, Any]],
*,
clean_text: str = "",
) -> bytes:
"""
按 evidence_anchor 在原 PDF 副本上写入可打印的标准高亮批注。
Args:
pdf_bytes: 原合同 PDF 字节。
clauses: 审核发现列表;优先使用 evidence_anchor,扫描件可回退 OCR 页码定位。
clean_text: 包含 page-image 标记的清洗正文,仅用于扫描 PDF 页级批注。
Returns:
带高亮批注的 PDF 字节;没有可定位发现时返回原合同副本。
"""
from pypdf import PdfReader, PdfWriter
from pypdf.annotations import Highlight, Text
from pypdf.generic import ArrayObject, FloatObject, NameObject, TextStringObject
reader = PdfReader(io.BytesIO(pdf_bytes))
writer = PdfWriter()
writer.clone_document_from_reader(reader)
annotation_count = 0
for item in clauses:
anchor = item.get("evidence_anchor") if isinstance(item, dict) else None
if not isinstance(anchor, dict) and isinstance(item, dict):
anchor = locate_ocr_evidence_page(clean_text, item)
if not isinstance(anchor, dict):
continue
page_index = int(anchor.get("page_no") or 0) - 1
if page_index < 0 or page_index >= len(writer.pages):
continue
rects = anchor.get("rects") or []
for raw_rect in rects:
if not isinstance(raw_rect, list) or len(raw_rect) != 4:
continue
left, bottom, right, top = [float(value) for value in raw_rect]
quad_points = ArrayObject(
[
FloatObject(left), FloatObject(top), FloatObject(right), FloatObject(top),
FloatObject(left), FloatObject(bottom), FloatObject(right), FloatObject(bottom),
]
)
annotation = Highlight(
rect=(left, bottom, right, top),
quad_points=quad_points,
highlight_color=_annotation_color(str(item.get("risk_level") or "low")),
printing=True,
)
annotation[NameObject("/Contents")] = TextStringObject(
f"{item.get('title') or '合同审核提示'}: {item.get('detail') or ''}"
)
writer.add_annotation(page_number=page_index, annotation=annotation)
annotation_count += 1
if not rects:
page = writer.pages[page_index]
top = float(page.mediabox.top)
note = Text(
rect=(18, max(18, top - 42), 38, max(38, top - 22)),
text=f"{item.get('title') or '合同审核提示'}: {item.get('detail') or ''}",
open=False,
)
writer.add_annotation(page_number=page_index, annotation=note)
annotation_count += 1
output = io.BytesIO()
writer.write(output)
return output.getvalue()
@@ -0,0 +1,346 @@
"""
backend/app/services/procurement_contract/preprocessing.py
用途:复用知识库 edkb_system 清洗能力,为单次合同审核生成 Markdown 和结构化条款产物。
依赖:knowledge_cleaning.edkb_adapter、file_assets、procurement_contract.analyze。
逻辑:合同 Worker 读取 FileAsset 字节 → 写入审查专属目录 → 清洗为 Markdown → 合同去噪与条款切分;
不创建 KbDocument,也不把一次性合同同步到企业正式 Dataset。
"""
from __future__ import annotations
import json
import mimetypes
import re
import shutil
from pathlib import Path
from typing import Any
import requests
from flask import current_app
from app.core.errors import ValidationError
from app.models import FileAsset
from app.services.file_assets.service import read_asset_bytes
from app.services.knowledge_cleaning.edkb_adapter import build_clean_result
from app.services.procurement_contract import analyze, artifact_archive
from edkb_system.skills.soffice_util import convert_with_soffice, find_soffice
def _extract_pdf_page_texts(pdf_path: Path) -> list[str]:
"""
Extract searchable text per PDF page while preserving the source pagination.
Args:
pdf_path: Existing PDF path produced by upload or LibreOffice conversion.
Returns:
One string per physical page; blank strings are retained so page counts remain exact.
"""
import pypdfium2 as pdfium
document = pdfium.PdfDocument(str(pdf_path))
try:
pages: list[str] = []
for page_index in range(len(document)):
page = document[page_index]
text_page = page.get_textpage()
try:
pages.append(text_page.get_text_range() or "")
finally:
text_page.close()
page.close()
return pages
finally:
document.close()
def _ocr_marker_page_texts(raw_text: str) -> list[str]:
"""Recover page-aligned OCR text from existing `page-image-N` markers for scanned PDFs."""
matches = list(re.finditer(r"!\[page-image-(\d+)\]", raw_text or "", flags=re.I))
if not matches:
return []
pages: list[str] = []
for index, match in enumerate(matches):
end = matches[index + 1].start() if index + 1 < len(matches) else len(raw_text)
pages.append(raw_text[match.end() : end].strip())
return pages
def _extract_page_texts(source_path: Path, target_dir: Path, raw_text: str) -> tuple[list[str], str | None]:
"""
Produce physical-page text for PDF and Word files without inventing page boundaries.
Word files are converted to PDF through the existing LibreOffice utility. If conversion or PDF
parsing fails, callers receive no pages and comparison-region logic safely falls back to full diff.
When MinerU supplies readable full-document OCR but a PDF has no native text layer, use one logical
page for body-boundary recognition. Logical pagination deliberately does not claim physical page counts.
"""
suffix = source_path.suffix.lower()
pdf_path = source_path
warning: str | None = None
if suffix in {".doc", ".docx"}:
soffice = find_soffice()
if not soffice:
return [], "LibreOffice is unavailable; comparison regions were not applied"
page_dir = target_dir / "page_source"
page_dir.mkdir(parents=True, exist_ok=True)
completed = convert_with_soffice(
soffice,
convert_to="pdf",
source_path=source_path,
out_dir=page_dir,
)
pdf_path = page_dir / f"{source_path.stem}.pdf"
if completed.returncode != 0 or not pdf_path.is_file():
shutil.rmtree(page_dir, ignore_errors=True)
return [], "LibreOffice conversion failed; comparison regions were not applied"
elif suffix != ".pdf":
return [], "File format has no reliable pagination; comparison regions were not applied"
try:
pages = _extract_pdf_page_texts(pdf_path)
marker_pages = _ocr_marker_page_texts(raw_text)
if marker_pages and len(marker_pages) >= len(pages):
pages = marker_pages
elif not any(page.strip() for page in pages) and raw_text.strip():
# MinerU's current response exposes only md_content. Keep its readable OCR available for
# body anchors instead of rejecting the region config solely because the source PDF lacks text.
pages = [raw_text]
warning = "PDF native page text unavailable; used MinerU logical page for body boundaries"
return [analyze.clean_contract_text(page) for page in pages], warning
except Exception as exc: # noqa: BLE001 - page extraction is optional and has an explicit fallback
marker_pages = _ocr_marker_page_texts(raw_text)
if marker_pages:
return [analyze.clean_contract_text(page) for page in marker_pages], str(exc)[:500]
return [], str(exc)[:500]
def _mineru_parse_pdf(source_path: Path, target_dir: Path) -> tuple[str, dict[str, Any]]:
"""
调用部署在内网的 MinerU API 解析 PDF,并保存完整返回供合同审核审计追溯。
核心逻辑:以同步 `/file_parse` 接口上传单份 PDF,读取对应文件的 `md_content`;MinerU
服务地址为空、接口失败或未返回 Markdown 时抛出异常,调用方再回退现有清洗器。
Args:
source_path: 审查目录内的 PDF 文件。
target_dir: 当前合同角色的清洗产物目录。
Returns:
MinerU Markdown 正文和不含绝对路径的解析元数据。
Raises:
RuntimeError: MinerU 未配置、请求失败或响应缺少当前文件的 Markdown。
"""
api_url = str(current_app.config.get("PROCUREMENT_CONTRACT_MINERU_API_URL") or "").strip().rstrip("/")
if not api_url:
raise RuntimeError("MinerU API is not configured")
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"
content_type = mimetypes.guess_type(source_path.name)[0] or "application/pdf"
payload = {
"lang_list": "ch",
"backend": backend,
"parse_method": parse_method,
"formula_enable": "false",
}
try:
with source_path.open("rb") as handle:
response = requests.post(
f"{api_url}/file_parse",
data=payload,
files=[("files", (source_path.name, handle, content_type))],
timeout=(connect_timeout, read_timeout),
)
response.raise_for_status()
result = response.json()
except (OSError, ValueError, requests.RequestException) as exc:
raise RuntimeError(f"MinerU parse failed: {exc}") from exc
if str(result.get("status") or "").lower() != "completed":
detail = str(result.get("error") or result.get("status") or "unknown status")
raise RuntimeError(f"MinerU parse did not complete: {detail}")
results = result.get("results")
if not isinstance(results, dict) or not results:
raise RuntimeError("MinerU response has no file results")
# API 以去扩展名文件名为 key;单文件请求直接取唯一结果,避免依赖服务端命名规则。
parsed = next((value for value in results.values() if isinstance(value, dict)), None)
markdown = str((parsed or {}).get("md_content") or "").strip()
if not markdown:
raise RuntimeError("MinerU response has no md_content")
(target_dir / "mineru_result.json").write_text(
json.dumps(result, ensure_ascii=False, indent=2),
encoding="utf-8",
)
(target_dir / "mineru_document.md").write_text(markdown, encoding="utf-8")
return markdown, {
"provider": "mineru",
"backend": str(result.get("backend") or backend),
"version": str(result.get("version") or ""),
"parse_method": parse_method,
"result_artifact": "mineru_result.json",
}
def _review_root(review_no: str) -> Path:
"""解析并创建审查专属存储目录,拒绝把审查编号解释为路径。"""
safe_no = re.sub(r"[^A-Za-z0-9_-]+", "_", str(review_no or "").strip())[:80]
if not safe_no:
raise ValidationError("review_no is required")
root = Path(str(current_app.config["PROCUREMENT_CONTRACT_STORAGE_ROOT"])).resolve() / safe_no
root.mkdir(parents=True, exist_ok=True)
return root
def _safe_source_name(filename: str, role: str) -> str:
"""生成保留扩展名的本地文件名,避免原文件名穿越审查目录。"""
suffix = Path(str(filename or "")).suffix.lower()[:16]
return f"{role}{suffix or '.bin'}"
def clean_review_asset(
*,
review_no: str,
role: str,
asset: FileAsset,
) -> dict[str, Any]:
"""
清洗一份合同或模板并产出合同审核结构。
核心逻辑:优先使用知识库 edkb_system 生成 Markdown;失败时回退到合同域本地抽取器,
随后执行合同专用去噪和条款切分,并保存 `document.md` / `clauses.json`。
Args:
review_no: 合同审查编号,只用于隔离产物目录。
role: 仅允许 contract 或 template。
asset: 已校验可读的 FileAsset ORM 对象。
Returns:
包含 clean_text、clauses 和不暴露绝对路径的 extraction_meta。
Raises:
ValidationError: 文件无法产生可审核正文。
"""
normalized_role = str(role or "").strip().lower()
if normalized_role not in {"contract", "template"}:
raise ValidationError("role must be contract or template")
review_root = _review_root(review_no)
source_dir = review_root / "source"
target_dir = review_root / "cleaned" / normalized_role
source_dir.mkdir(parents=True, exist_ok=True)
target_dir.mkdir(parents=True, exist_ok=True)
data = read_asset_bytes(asset)
source_path = source_dir / _safe_source_name(asset.original_filename, normalized_role)
source_path.write_bytes(data)
mode = "edkb_system"
warning: str | None = None
mineru_meta: dict[str, Any] = {}
# [STEP 1] PDF 优先交给 MinerU 恢复版面、表格与阅读顺序;未配置或服务异常时保持旧链路可用。
if source_path.suffix.lower() == ".pdf" and current_app.config.get("PROCUREMENT_CONTRACT_MINERU_API_URL"):
try:
raw_text, mineru_meta = _mineru_parse_pdf(source_path, target_dir)
mode = "mineru"
except Exception as exc: # noqa: BLE001 - MinerU is an optional parser with explicit fallback
warning = str(exc)[:500]
if mode != "mineru":
try:
clean_result = build_clean_result(source_path, target_dir)
cleaned_path = Path(str(clean_result.get("cleaned_file_path") or ""))
raw_text = cleaned_path.read_text(encoding="utf-8", errors="ignore") if cleaned_path.is_file() else ""
mode = str(clean_result.get("mode") or mode)
except Exception as exc: # noqa: BLE001 - local extractor is the intended degradation path
warning = f"{warning}; {exc}".strip("; ")[:500]
mode = "local_fallback"
raw_text = analyze.extract_text_from_bytes(asset.original_filename, data)
# 保留清洗器原始分页/OCR文本供扫描 PDF 批注定位;审核正文会继续移除页码和图片标记。
(target_dir / "ocr_document.md").write_text(raw_text, encoding="utf-8")
clean_text = analyze.clean_contract_text(raw_text)
if not clean_text or clean_text.startswith("[binary:"):
raise ValidationError("合同正文无法解析,请上传 Word 或可检索文本的 PDF")
clauses = analyze.structure_contract_clauses(clean_text)
if not clauses:
raise ValidationError("合同正文未识别到可审核条款")
document_path = target_dir / "document.md"
clauses_path = target_dir / "clauses.json"
document_path.write_text(clean_text, encoding="utf-8")
clauses_path.write_text(json.dumps(clauses, ensure_ascii=False, indent=2), encoding="utf-8")
quality = analyze.extraction_quality(clean_text)
page_texts, page_warning = _extract_page_texts(source_path, target_dir, raw_text)
return {
"clean_text": clean_text,
"clauses": clauses,
"page_texts": page_texts,
"page_count": len(page_texts),
"extraction_meta": {
"role": normalized_role,
"mode": mode,
"character_count": len(clean_text),
"clause_count": len(clauses),
"quality": quality,
"warning": warning or page_warning or quality.get("warning"),
"document_artifact": f"cleaned/{normalized_role}/document.md",
"clauses_artifact": f"cleaned/{normalized_role}/clauses.json",
"mineru": mineru_meta or None,
},
}
def persist_review_result_artifact(review_no: str, result: dict[str, Any]) -> None:
"""
保存最终结构化结果副本,供问题排查和审计回溯。
Args:
review_no: 合同审查编号。
result: 已完成后端校验和合并的结果字典。
"""
result_dir = _review_root(review_no) / "result"
result_dir.mkdir(parents=True, exist_ok=True)
(result_dir / "merged_result.json").write_text(
json.dumps(result, ensure_ascii=False, indent=2, default=str),
encoding="utf-8",
)
def read_review_clean_text(review_no: str, *, role: str = "contract") -> str:
"""
读取审查任务已保存的清洗正文,供扫描 PDF 下载时按 OCR 分页补充批注定位。
Args:
review_no: 合同审查编号。
role: 仅允许 contract 或 template;下载标注合同默认读取 contract。
Returns:
清洗后的 Markdown 正文;产物不存在时返回空字符串。
"""
normalized_role = str(role or "").strip().lower()
if normalized_role not in {"contract", "template"}:
raise ValidationError("role must be contract or template")
role_root = _review_root(review_no) / "cleaned" / normalized_role
ocr_document_path = role_root / "ocr_document.md"
if not ocr_document_path.is_file():
artifact_archive.restore_review_artifact(
review_no,
f"cleaned/{normalized_role}/ocr_document.md",
)
if ocr_document_path.is_file():
return ocr_document_path.read_text(encoding="utf-8", errors="ignore")
document_path = role_root / "document.md"
if not document_path.is_file():
artifact_archive.restore_review_artifact(
review_no,
f"cleaned/{normalized_role}/document.md",
)
if not document_path.is_file():
return ""
return document_path.read_text(encoding="utf-8", errors="ignore")
@@ -0,0 +1,795 @@
"""
backend/app/services/procurement_contract/review_service.py
用途:创建、异步执行、查询与导出采购合同审查记录。
依赖:ContractReview/FileAsset/Job、知识库清洗适配器、rule/analyze/llm_enhancer/pdf_annotation。
逻辑:Chat/Admin API 创建 queued 审查 → Worker 清洗 → 改稿 Diff/五灯或单份五问 →
(仅 solo 可选)LLM 增强 → 页锚落库。比对模式默认不做 Dify 全面扫描。
"""
from __future__ import annotations
import secrets
from datetime import datetime, timedelta
from typing import Any
from flask import current_app
from sqlalchemy import or_
from app import db
from app.core.config.settings import Config
from app.core.errors import ForbiddenError, NotFoundError, ValidationError
from app.core.response import utc_iso
from app.models import ContractReview, FileAsset, Job, User
from app.services.file_assets.service import mark_asset_referenced, read_asset_bytes
from app.services.procurement_contract import (
analyze,
artifact_archive,
comparison_regions,
llm_enhancer,
pdf_annotation,
preprocessing,
rule_service,
template_service,
)
DEFAULT_CONTRACT_TYPE = "general_procurement"
def _gen_review_no() -> str:
"""Generate review number like CR-YYYYMMDD-AB12."""
day = datetime.utcnow().strftime("%Y%m%d")
return f"CR-{day}-{secrets.token_hex(2).upper()}"
def serialize_review(row: ContractReview, *, include_detail: bool = False) -> dict[str, Any]:
"""Convert a review ORM row into API response data."""
user = db.session.get(User, row.user_id) if row.user_id else None
data: dict[str, Any] = {
"id": row.id,
"review_no": row.review_no,
"review_mode": row.review_mode,
"status": row.status,
"contract_file_name": row.contract_file_name,
"supplier_name": row.supplier_name,
"contract_no": row.contract_no,
"contract_type": row.contract_type,
"template_id": row.template_id,
"template_source": row.template_source,
"template_name": row.template_name,
"total_change_count": row.total_change_count,
"high_risk_count": row.high_risk_count,
"medium_risk_count": row.medium_risk_count,
"low_risk_count": row.low_risk_count,
"user_id": row.user_id,
"user_name": (user.real_name or user.username) if user else None,
"error_message": row.error_message,
"started_at": utc_iso(row.started_at),
"finished_at": utc_iso(row.finished_at),
"created_at": utc_iso(row.created_at),
}
processing = row.summary_json.get("processing") if isinstance(row.summary_json, dict) else None
if isinstance(processing, dict):
data["progress"] = int(processing.get("progress") or 0)
data["processing_stage"] = processing.get("stage")
data["processing_message"] = processing.get("message")
else:
data["progress"] = 100 if row.status in {"success", "failed"} else 0
data["processing_stage"] = row.status
data["processing_message"] = None
if include_detail:
data["summary_json"] = row.summary_json
data["clauses_json"] = row.clauses_json
data["report_text"] = row.report_text
data["contract_asset_id"] = row.contract_asset_id
data["template_asset_id"] = row.template_asset_id
data["agent_id"] = row.agent_id
data["chat_log_id"] = row.chat_log_id
return data
def _parse_date(value: str | None, *, end_of_day: bool = False) -> datetime | None:
"""Parse YYYY-MM-DD or ISO datetime filter values."""
raw = str(value or "").strip()
if not raw:
return None
try:
if len(raw) == 10:
dt = datetime.strptime(raw, "%Y-%m-%d")
return dt + timedelta(days=1) if end_of_day else dt
return datetime.fromisoformat(raw.replace("Z", "+00:00")).replace(tzinfo=None)
except ValueError as exc:
raise ValidationError("invalid date filter") from exc
def list_reviews(
*,
review_mode: str | None = None,
template_source: str | None = None,
status: str | None = None,
keyword: str | None = None,
user_id: int | None = None,
contract_type: str | None = None,
supplier_name: str | None = None,
risk_level: str | None = None,
date_from: str | None = None,
date_to: str | None = None,
limit: int = 100,
offset: int = 0,
) -> dict[str, Any]:
"""List review history with filters used by admin and chat pages."""
q = db.session.query(ContractReview)
if review_mode:
q = q.filter(ContractReview.review_mode == review_mode)
if template_source:
q = q.filter(ContractReview.template_source == template_source)
if status:
q = q.filter(ContractReview.status == status)
if user_id is not None:
q = q.filter(ContractReview.user_id == user_id)
if contract_type:
q = q.filter(ContractReview.contract_type == contract_type)
if supplier_name:
q = q.filter(ContractReview.supplier_name.ilike(f"%{supplier_name.strip()}%"))
if risk_level == "high":
q = q.filter(ContractReview.high_risk_count > 0)
elif risk_level == "medium":
q = q.filter(ContractReview.high_risk_count == 0, ContractReview.medium_risk_count > 0)
elif risk_level == "low":
q = q.filter(
ContractReview.high_risk_count == 0,
ContractReview.medium_risk_count == 0,
ContractReview.low_risk_count > 0,
)
start = _parse_date(date_from)
end = _parse_date(date_to, end_of_day=True)
if start:
q = q.filter(ContractReview.created_at >= start)
if end:
q = q.filter(ContractReview.created_at < end)
if keyword:
like = f"%{keyword.strip()}%"
q = q.filter(
or_(
ContractReview.review_no.ilike(like),
ContractReview.contract_file_name.ilike(like),
ContractReview.template_name.ilike(like),
ContractReview.supplier_name.ilike(like),
ContractReview.contract_no.ilike(like),
)
)
total = q.count()
rows = (
q.order_by(ContractReview.created_at.desc())
.offset(max(0, int(offset or 0)))
.limit(min(max(int(limit or 100), 1), 200))
.all()
)
return {"total": total, "items": [serialize_review(r) for r in rows]}
def _load_review_row(*, review_id: int | None = None, review_no: str | None = None) -> ContractReview:
"""Load a review row by id or review_no."""
row = None
if review_id is not None:
row = db.session.get(ContractReview, review_id)
elif review_no:
row = db.session.query(ContractReview).filter(ContractReview.review_no == review_no).first()
if not row:
raise NotFoundError("review not found")
return row
def get_review(review_id: int | None = None, review_no: str | None = None) -> dict[str, Any]:
"""Get review details by id or review_no."""
return serialize_review(_load_review_row(review_id=review_id, review_no=review_no), include_detail=True)
def get_review_for_owner(*, review_no: str, user_id: int) -> dict[str, Any]:
"""
Get a user's review, recovering a stale background job before serializing it.
A browser reload must not leave a card permanently at its last persisted progress when the
contract worker has exited mid-task. Only an already-stale running job is recovered here;
normal task claiming remains the worker's responsibility.
"""
row = _load_review_row(review_no=review_no)
if row.user_id != user_id:
raise ForbiddenError("not your review")
_recover_stale_review_if_needed(row)
db.session.refresh(row)
return serialize_review(row, include_detail=True)
def _recover_stale_review_if_needed(row: ContractReview) -> None:
"""Recover timed-out contract jobs when a user polls a still-running review card."""
if row.status != "running" or not row.started_at:
return
timeout_seconds = max(int(getattr(Config, "PROCUREMENT_CONTRACT_JOB_TIMEOUT_SECONDS", 600) or 600), 60)
if row.started_at >= datetime.utcnow() - timedelta(seconds=timeout_seconds):
return
from app.jobs.queue import recover_stale_jobs
from app.jobs.types import JobType
recover_stale_jobs(
domain="procurement_contract",
timeout_seconds=timeout_seconds,
job_type=JobType.PROCUREMENT_CONTRACT_REVIEW,
on_recovered=sync_review_after_job_recovery,
)
def read_review_report_bytes(*, review_id: int | None = None, review_no: str | None = None) -> tuple[str, bytes]:
"""
读取纯文本审查报告字节。
核心逻辑:正文前拼接审查编号、业务合同编号与供应商(乙方/卖方)。
"""
row = _load_review_row(review_id=review_id, review_no=review_no)
body = row.report_text or ""
if not body and isinstance(row.summary_json, dict):
body = str(row.summary_json.get("headline") or "")
header = "\n".join(
[
f"审查编号:{row.review_no}",
f"待审合同:{row.contract_file_name}",
f"合同编号:{row.contract_no or '-'}",
f"供应商(乙方/卖方):{row.supplier_name or '-'}",
"",
body,
]
)
return f"{row.review_no}_report.txt", header.encode("utf-8")
def read_review_report_docx_bytes(*, review_id: int | None = None, review_no: str | None = None) -> tuple[str, bytes, str]:
"""
Create a docx report when python-docx is available.
Returns filename, bytes and mimetype; falls back to plain text without failing export.
"""
row = _load_review_row(review_id=review_id, review_no=review_no)
try:
import io
from docx import Document
doc = Document()
doc.add_heading("合同差异对比报告" if row.review_mode == "compare" else "采购合同风险审核报告", level=1)
doc.add_paragraph(f"审查编号:{row.review_no}")
doc.add_paragraph(f"待审合同:{row.contract_file_name}")
doc.add_paragraph(f"合同编号:{row.contract_no or '-'}")
doc.add_paragraph(f"供应商(乙方/卖方):{row.supplier_name or '-'}")
doc.add_paragraph(f"审查模式:{row.review_mode}")
if row.review_mode == "compare":
doc.add_paragraph(
f"差异统计:共 {row.total_change_count} 项;风险参考:高 {row.high_risk_count} / "
f"中 {row.medium_risk_count} / 低 {row.low_risk_count}"
)
else:
doc.add_paragraph(f"风险统计:高 {row.high_risk_count} / 中 {row.medium_risk_count} / 低 {row.low_risk_count}")
doc.add_paragraph("说明:本报告为采购风险提示,不作为法律意见。")
doc.add_paragraph(row.report_text or "")
buffer = io.BytesIO()
doc.save(buffer)
return (
f"{row.review_no}_report.docx",
buffer.getvalue(),
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
)
except Exception:
name, data = read_review_report_bytes(review_id=review_id, review_no=review_no)
return name, data, "text/plain; charset=utf-8"
def read_review_contract_bytes(*, review_id: int | None = None, review_no: str | None = None) -> tuple[str, bytes]:
"""Read original contract bytes for a review."""
row = _load_review_row(review_id=review_id, review_no=review_no)
asset = db.session.get(FileAsset, row.contract_asset_id) if row.contract_asset_id else None
if not asset or asset.deleted_at is not None:
raise NotFoundError("contract file not found")
return asset.original_filename or row.contract_file_name or "contract.bin", read_asset_bytes(asset)
def read_review_template_bytes(*, review_id: int | None = None, review_no: str | None = None) -> tuple[str, bytes]:
"""Read the comparison baseline file used for a review (legacy field name: template)."""
row = _load_review_row(review_id=review_id, review_no=review_no)
asset = db.session.get(FileAsset, row.template_asset_id) if row.template_asset_id else None
if not asset or asset.deleted_at is not None:
raise NotFoundError("comparison baseline file not found")
return asset.original_filename or "original-contract.bin", read_asset_bytes(asset)
def read_review_annotated_contract_bytes(
*,
review_id: int | None = None,
review_no: str | None = None,
) -> tuple[str, bytes, str]:
"""
生成并读取带审核高亮批注的合同 PDF。
核心逻辑:文本型 PDF 使用 evidence_anchor 写入 Highlight;扫描 PDF 使用已保存 OCR 分页正文定位页面并写入批注意见。
原始 FileAsset 永不修改。没有任何可定位证据时仍返回原合同副本,避免下载入口报错。
"""
row = _load_review_row(review_id=review_id, review_no=review_no)
asset = db.session.get(FileAsset, row.contract_asset_id) if row.contract_asset_id else None
if not asset or asset.deleted_at is not None:
raise NotFoundError("contract file not found")
filename = asset.original_filename or row.contract_file_name or "contract.pdf"
if not filename.lower().endswith(".pdf"):
raise ValidationError("annotated contract is only available for PDF files")
clauses = row.clauses_json if isinstance(row.clauses_json, list) else []
data = pdf_annotation.build_annotated_pdf_bytes(
read_asset_bytes(asset),
clauses,
clean_text=preprocessing.read_review_clean_text(row.review_no),
)
stem = filename.rsplit(".", 1)[0]
return f"{stem}_{row.review_no}_annotated.pdf", data, "application/pdf"
def start_review(
*,
user_id: int,
review_mode: str,
contract_asset_id: int | None = None,
contract_asset_no: str | None = None,
original_contract_asset_id: int | None = None,
original_contract_asset_no: str | None = None,
contract_type: str | None = None,
supplier_name: str | None = None,
agent_id: int | None = None,
chat_log_id: int | None = None,
) -> dict[str, Any]:
"""
创建采购合同审核记录并投递异步任务。
核心逻辑:比对模式校验我方原合同和卖方回传合同,单份模式仅校验待审合同;随后同事务写入 queued 审查与通用 Job。
文件清洗、Dify 调用和报告生成均由 Worker 执行,避免 Web 请求超时。
"""
mode = (review_mode or "").strip()
if mode not in ("compare", "solo"):
raise ValidationError("review_mode must be compare or solo")
if mode == "compare" and not (original_contract_asset_id or original_contract_asset_no):
raise ValidationError("original_contract_asset_no is required for compare mode")
contract_asset = _resolve_asset_for_user(
user_id=user_id,
asset_id=contract_asset_id,
asset_no=contract_asset_no,
label="contract",
)
normalized_contract_type = (contract_type or DEFAULT_CONTRACT_TYPE).strip() or DEFAULT_CONTRACT_TYPE
template_source = "none"
template_name = None
template_asset_id = None
template_id = None
if mode == "compare":
original_asset = _resolve_asset_for_user(
user_id=user_id,
asset_id=original_contract_asset_id,
asset_no=original_contract_asset_no,
label="original contract",
)
template_source = "user_upload"
template_asset_id = original_asset.id
template_name = original_asset.original_filename
row = ContractReview(
review_no=_gen_review_no(),
agent_id=agent_id,
user_id=user_id,
chat_log_id=chat_log_id,
review_mode=mode,
status="queued",
contract_asset_id=contract_asset.id,
contract_file_name=contract_asset.original_filename,
supplier_name=(supplier_name or "").strip() or None,
contract_type=normalized_contract_type,
template_id=template_id,
template_source=template_source,
template_asset_id=template_asset_id,
template_name=template_name,
total_change_count=0,
high_risk_count=0,
medium_risk_count=0,
low_risk_count=0,
summary_json={
"mode": mode,
"processing": {"stage": "queued", "progress": 0, "message": "等待后台审核"},
"review_note": "本结果为采购风险提示,不作为法律意见。",
},
)
db.session.add(row)
db.session.flush()
mark_asset_referenced(contract_asset)
if template_source == "user_upload" and template_asset_id:
original_asset = db.session.get(FileAsset, template_asset_id)
if original_asset:
mark_asset_referenced(original_asset)
from app.jobs import enqueue
from app.jobs.types import JobType
enqueue(
JobType.PROCUREMENT_CONTRACT_REVIEW,
{"review_no": row.review_no},
domain="procurement_contract",
business_ref=row.review_no,
created_by_id=user_id,
max_attempts=2,
message="等待合同清洗与审核",
commit=False,
)
db.session.commit()
return serialize_review(row, include_detail=True)
def _resolve_asset_for_user(*, user_id: int, asset_id: int | None, asset_no: str | None, label: str) -> FileAsset:
"""Resolve an uploaded file asset and enforce ownership for asset_no path."""
asset: FileAsset | None = None
if asset_id:
asset = db.session.get(FileAsset, asset_id)
elif asset_no:
from app.services.file_assets.service import get_asset_for_user
asset = get_asset_for_user(asset_no, user_id)
if not asset or asset.deleted_at is not None:
raise ValidationError(f"{label} file asset not found")
if asset.upload_status != "ready":
raise ValidationError(f"{label} file asset is not ready")
return asset
def _set_processing(
row: ContractReview,
*,
stage: str,
progress: int,
message: str,
job_id: int | None = None,
) -> None:
"""
同步更新业务审核记录和通用 Job 的阶段进度。
Args:
row: 当前 ContractReview。
stage/progress/message: 前端轮询展示的稳定阶段协议。
job_id: 可选通用 Job 主键;Worker 调用时同时更新队列监控信息。
"""
summary = dict(row.summary_json or {})
summary["processing"] = {
"stage": stage,
"progress": max(0, min(100, int(progress))),
"message": message,
}
row.summary_json = summary
row.status = "running" if stage not in {"success", "failed"} else stage
if job_id:
job = db.session.get(Job, int(job_id))
if job:
job.progress = max(0, min(100, int(progress)))
job.message = message[:500]
db.session.commit()
def execute_review_job(*, review_no: str, job_id: int | None = None) -> dict[str, Any]:
"""
在后台 Worker 中执行一份采购合同的完整审核。
核心逻辑:[STEP 1] 复用知识库清洗器;[STEP 2] 合同结构化;[STEP 3] Diff 与整份红线;
[STEP 4] Dify 全面法律扫描;[STEP 5] 后端重算、持久化和报告生成。
Args:
review_no: 已创建的审查编号。
job_id: 通用 Job 主键,用于同步进度。
Returns:
已落库的完整审核详情。
"""
row = _load_review_row(review_no=review_no)
row.started_at = row.started_at or datetime.utcnow()
row.finished_at = None
row.error_message = None
_set_processing(row, stage="extracting", progress=10, message="正在提取并清洗合同", job_id=job_id)
contract_asset = db.session.get(FileAsset, row.contract_asset_id)
if not contract_asset:
raise ValidationError("contract asset missing")
contract_doc = preprocessing.clean_review_asset(
review_no=row.review_no,
role="contract",
asset=contract_asset,
)
contract_text = str(contract_doc["clean_text"])
contract_clauses = list(contract_doc["clauses"])
party = analyze.extract_party_fields(contract_text)
if not row.supplier_name and party.get("supplier_name"):
row.supplier_name = str(party["supplier_name"])
if party.get("contract_no"):
row.contract_no = str(party["contract_no"])
_set_processing(row, stage="structuring", progress=30, message="正在识别合同条款结构", job_id=job_id)
rules = rule_service.get_enabled_rules(row.contract_type)
template_meta: dict[str, Any] | None = None
_set_processing(
row,
stage="deterministic_review",
progress=45,
message="正在执行模板比对与公司红线检查",
job_id=job_id,
)
if row.review_mode == "solo":
result = analyze.analyze_solo(contract_text, rules=rules)
else:
if not row.template_asset_id:
raise ValidationError("original contract asset missing for compare mode")
template_asset = db.session.get(FileAsset, row.template_asset_id)
if not template_asset:
raise ValidationError("original contract asset missing")
template_doc = preprocessing.clean_review_asset(
review_no=row.review_no,
role="template",
asset=template_asset,
)
template_meta = dict(template_doc["extraction_meta"])
# [STEP 1] 比对模式只做改稿红线 + 五灯,不再叠加整份 solo 扫描(避免噪声淹没采购)。
original_text = str(template_doc["clean_text"])
returned_text = contract_text
comparison_scope: dict[str, Any] = {
"status": "fallback",
"template_id": None,
"template_name": None,
"warning": "No enabled default template comparison-region config was available",
}
metadata_comparison: dict[str, Any] = {}
attachment_comparison: dict[str, Any] = {"status": "unavailable"}
default_template = template_service.get_default_enabled_template()
if default_template and isinstance(default_template.comparison_region_config, dict):
comparison_scope.update({
"template_id": default_template.id,
"template_name": default_template.name,
"warning": "Comparison-region anchors could not be recognized in both uploaded files",
})
try:
region_config = comparison_regions.validate_comparison_region_config(
default_template.comparison_region_config
)
original_diagnostic = comparison_regions.diagnose_partition(
original_text,
list(template_doc.get("page_texts") or []),
region_config,
)
returned_diagnostic = comparison_regions.diagnose_partition(
returned_text,
list(contract_doc.get("page_texts") or []),
region_config,
)
comparison_scope["diagnostics"] = {
"original_contract": original_diagnostic,
"returned_contract": returned_diagnostic,
}
original_partition = comparison_regions.partition_document(
original_text,
list(template_doc.get("page_texts") or []),
region_config,
)
returned_partition = comparison_regions.partition_document(
returned_text,
list(contract_doc.get("page_texts") or []),
region_config,
)
if original_partition and returned_partition:
original_text = original_partition.body
returned_text = returned_partition.body
metadata_comparison = comparison_regions.build_metadata_comparison(
original_partition.metadata,
returned_partition.metadata,
)
attachment_comparison = comparison_regions.build_attachment_comparison(
original_partition.attachment_pages,
returned_partition.attachment_pages,
)
comparison_scope = {
"status": "applied",
"template_id": default_template.id,
"template_name": default_template.name,
"body_start_found": True,
"body_end_found": True,
"signature_excluded": True,
"attachment_policy": region_config["attachment_policy"],
"diagnostics": {
"original_contract": original_diagnostic,
"returned_contract": returned_diagnostic,
},
"warning": None,
}
except ValidationError as exc:
comparison_scope["warning"] = exc.message
elif default_template:
comparison_scope.update({
"template_id": default_template.id,
"template_name": default_template.name,
"warning": "The enabled default template has no comparison-region config",
})
if comparison_scope["status"] == "fallback":
current_app.logger.warning(
"[contract-review] comparison region fallback review_no=%s template_id=%s "
"warning=%s diagnostics=%s",
row.review_no,
comparison_scope.get("template_id"),
comparison_scope.get("warning"),
comparison_scope.get("diagnostics"),
)
# [STEP 1] Uploaded original remains the baseline; Admin contributes only reusable region rules.
result = analyze.analyze_compare(original_text, returned_text, rules=rules)
region_summary = result.get("summary_json") if isinstance(result.get("summary_json"), dict) else {}
region_summary["comparison_scope"] = comparison_scope
region_summary["metadata_comparison"] = metadata_comparison
region_summary["attachment_comparison"] = attachment_comparison
result["summary_json"] = region_summary
summary = result.get("summary_json") if isinstance(result.get("summary_json"), dict) else {}
summary["extraction"] = {
"contract": contract_doc["extraction_meta"],
"template": template_meta,
}
summary["structured_clause_count"] = len(contract_clauses)
result["summary_json"] = summary
# [STEP 2] 比对模式关闭 Dify 全面审核;仅单份卖方合同可选 LLM 解释增强。
if row.review_mode == "solo":
_set_processing(row, stage="llm_reviewing", progress=60, message="正在补充 AI 风险说明", job_id=job_id)
result = llm_enhancer.enhance_review_result(
result,
review_no=row.review_no,
review_mode=row.review_mode,
contract_type=row.contract_type,
template_name=row.template_name,
clean_text=contract_text,
structured_clauses=contract_clauses,
)
else:
_set_processing(row, stage="validating", progress=70, message="正在整理比对结果", job_id=job_id)
summary = result.get("summary_json") if isinstance(result.get("summary_json"), dict) else {}
summary["llm_enhancement"] = {
"enabled": False,
"status": "skipped",
"message": "compare mode uses redline + focus lights only",
}
result["summary_json"] = summary
_set_processing(row, stage="validating", progress=88, message="正在校验并合并审核结果", job_id=job_id)
try:
result = pdf_annotation.enrich_result_with_pdf_anchors(
result,
filename=contract_asset.original_filename or row.contract_file_name,
pdf_bytes=read_asset_bytes(contract_asset),
)
except Exception as exc: # noqa: BLE001 - evidence anchoring is a non-blocking report enhancement
current_app.logger.warning(
"[contract-review] evidence anchoring failed review_no=%s err=%s",
row.review_no,
exc,
)
summary = result.get("summary_json") if isinstance(result.get("summary_json"), dict) else {}
summary["evidence_anchoring"] = {"status": "failed", "anchored": 0, "unanchored": 0}
result["summary_json"] = summary
result = analyze.rebuild_result(result)
summary = result["summary_json"]
summary["processing"] = {"stage": "success", "progress": 100, "message": "审核完成"}
result["summary_json"] = summary
row.status = "success"
row.total_change_count = int(result.get("total_change_count") or 0)
row.high_risk_count = int(result.get("high_risk_count") or 0)
row.medium_risk_count = int(result.get("medium_risk_count") or 0)
row.low_risk_count = int(result.get("low_risk_count") or 0)
row.summary_json = result["summary_json"]
row.clauses_json = result["clauses_json"]
row.report_text = result["report_text"]
row.error_message = None
row.finished_at = datetime.utcnow()
db.session.commit()
try:
preprocessing.persist_review_result_artifact(row.review_no, result)
except Exception as exc: # noqa: BLE001 - audit copy failure must not invalidate persisted review
current_app.logger.warning("[contract-review] result artifact failed review_no=%s err=%s", row.review_no, exc)
try:
archive_meta = artifact_archive.archive_review_artifacts(row.review_no)
summary = dict(row.summary_json or {})
summary["artifact_archive"] = archive_meta
row.summary_json = summary
db.session.commit()
if archive_meta.get("status") == "archived":
artifact_archive.cleanup_local_review_artifacts(row.review_no)
except Exception as exc: # noqa: BLE001 - MinIO archiving must not turn a completed review into failure
current_app.logger.warning("[contract-review] artifact archive failed review_no=%s err=%s", row.review_no, exc)
summary = dict(row.summary_json or {})
summary["artifact_archive"] = {"status": "failed", "message": str(exc)[:500]}
row.summary_json = summary
db.session.commit()
return serialize_review(row, include_detail=True)
def mark_review_failed(*, review_no: str, error: str) -> None:
"""在后台任务最终失败时将审核记录收口为 failed,避免前端永久轮询。"""
row = _load_review_row(review_no=review_no)
summary = dict(row.summary_json or {})
summary["processing"] = {"stage": "failed", "progress": 100, "message": "审核失败"}
row.summary_json = summary
row.status = "failed"
row.error_message = str(error or "contract review failed")[:2000]
row.finished_at = datetime.utcnow()
db.session.commit()
def mark_review_retrying(*, review_no: str, error: str) -> None:
"""普通执行异常仍可重试时将业务审核状态恢复为 queued。"""
row = _load_review_row(review_no=review_no)
summary = dict(row.summary_json or {})
summary["processing"] = {"stage": "queued", "progress": 0, "message": "审核失败,等待后台重试"}
row.summary_json = summary
row.status = "queued"
row.error_message = str(error or "contract review retrying")[:2000]
row.finished_at = None
db.session.commit()
def sync_review_after_job_recovery(job: Job) -> None:
"""
通用队列回收超时合同任务时同步业务审核状态。
核心逻辑:任务仍可重试时把进度重置为 queued;重试耗尽时收口 failed。
本函数由 recover_stale_jobs 在同一事务内调用,不自行 commit。
Args:
job: 已被队列更新为 queued 或 failed 的通用 Job。
"""
review_no = str(job.business_ref or (job.payload_json or {}).get("review_no") or "").strip()
if not review_no:
return
row = db.session.query(ContractReview).filter(ContractReview.review_no == review_no).first()
if not row:
return
summary = dict(row.summary_json or {})
if job.status == "queued":
summary["processing"] = {"stage": "queued", "progress": 0, "message": "任务超时,等待后台重试"}
row.status = "queued"
row.finished_at = None
elif job.status == "failed":
summary["processing"] = {"stage": "failed", "progress": 100, "message": "审核任务执行超时"}
row.status = "failed"
row.error_message = str(job.error_message or "合同审核任务执行超时")[:2000]
row.finished_at = datetime.utcnow()
row.summary_json = summary
def _run_analysis(row: ContractReview) -> dict[str, Any]:
"""
兼容旧测试和内部调用的同步确定性分析入口。
核心逻辑:提取文本 → 解析供应商/合同编号 → Diff 或红线规则 → 把当事人字段写入报告头。
"""
contract_asset = db.session.get(FileAsset, row.contract_asset_id)
if not contract_asset:
raise ValidationError("contract asset missing")
contract_bytes = read_asset_bytes(contract_asset)
contract_text = analyze.extract_text_from_bytes(contract_asset.original_filename, contract_bytes)
party = analyze.extract_party_fields(contract_text)
rules = rule_service.get_enabled_rules(row.contract_type)
if row.review_mode == "solo":
result = analyze.analyze_solo(contract_text, rules=rules)
else:
if not row.template_asset_id:
raise ValidationError("original contract asset missing for compare mode")
tpl_asset = db.session.get(FileAsset, row.template_asset_id)
if not tpl_asset:
raise ValidationError("original contract asset missing")
tpl_bytes = read_asset_bytes(tpl_asset)
tpl_text = analyze.extract_text_from_bytes(tpl_asset.original_filename, tpl_bytes)
result = analyze.analyze_compare(tpl_text, contract_text, rules=rules)
result["extracted_supplier_name"] = party.get("supplier_name")
result["extracted_contract_no"] = party.get("contract_no")
return result
@@ -0,0 +1,289 @@
"""
backend/app/services/procurement_contract/rule_service.py
Purpose: Manage procurement contract risk rules used by compare and solo review.
Dependencies: ContractRiskRule model, SQLAlchemy session, unified AppError classes.
Flow: Admin CRUD persists configurable red-line rules; review_service loads enabled rules for analysis.
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from uuid import uuid4
from app import db
from app.core.errors import NotFoundError, ValidationError
from app.core.response import utc_iso
from app.models import ContractRiskRule
DEFAULT_CONTRACT_TYPE = "general_procurement"
VALID_RISK_LEVELS = {"high", "medium", "low"}
VALID_STATUS = {"enabled", "disabled"}
VALID_TRIGGER_TYPES = {"keyword_missing", "keyword_present"}
# Keep categories stable because they drive result grouping, de-duplication and policy replacement.
VALID_CLAUSE_CATEGORIES = {
"payment",
"delivery",
"acceptance",
"warranty",
"liability",
"jurisdiction",
"dispute",
"ip",
"other",
}
BUILTIN_RULE_CODES = {
"payment_acceptance_required",
"acceptance_process_required",
"liability_required",
"jurisdiction_required",
"warranty_required",
}
def serialize_rule(row: ContractRiskRule) -> dict[str, Any]:
"""Convert a risk rule ORM row into API response data."""
return {
"id": row.id,
"code": row.code,
"rule_kind": "builtin" if row.code in BUILTIN_RULE_CODES else "custom",
"contract_type": row.contract_type,
"clause_category": row.clause_category,
"title": row.title,
"keywords": row.keywords or [],
"trigger_type": row.trigger_type,
"risk_level": row.risk_level,
"risk_hint": row.risk_hint,
"suggestion": row.suggestion,
"negotiation_text": row.negotiation_text,
"status": row.status,
"sort_order": row.sort_order,
"created_at": utc_iso(row.created_at),
"updated_at": utc_iso(row.updated_at),
}
def _normalize_keywords(raw: Any) -> list[str]:
"""Normalize JSON/list/string keywords into a unique non-empty string list."""
if isinstance(raw, str):
items = [p.strip() for p in raw.replace(",", ",").split(",")]
elif isinstance(raw, list):
items = [str(p).strip() for p in raw]
else:
items = []
seen: set[str] = set()
result: list[str] = []
for item in items:
if item and item not in seen:
seen.add(item)
result.append(item)
return result
def _validate_clause_category(category: str) -> str:
"""
Validate and normalize a rule category used by the contract analyzer.
Args:
category: Stable category code selected in the admin form; free-form labels are not supported.
Returns:
A validated category code.
Raises:
ValidationError: If the category cannot participate in result grouping safely.
"""
normalized = category.strip().lower()
if normalized not in VALID_CLAUSE_CATEGORIES:
raise ValidationError("invalid clause_category")
return normalized
def _generate_custom_rule_code(category: str) -> str:
"""
Generate an opaque code for a custom keyword rule.
The code is an internal identifier only. Generating it server-side prevents administrators from
accidentally using a built-in code that carries compound business logic.
Args:
category: Validated clause category used to make the generated code traceable.
Returns:
Globally unique custom rule code.
"""
return f"custom_{category}_{uuid4().hex[:12]}"
def list_rules(
*,
contract_type: str | None = None,
status: str | None = None,
clause_category: str | None = None,
) -> list[dict[str, Any]]:
"""List risk rules with optional filters."""
q = db.session.query(ContractRiskRule)
if contract_type:
q = q.filter(ContractRiskRule.contract_type == contract_type)
if status:
q = q.filter(ContractRiskRule.status == status)
if clause_category:
q = q.filter(ContractRiskRule.clause_category == clause_category)
rows = q.order_by(ContractRiskRule.sort_order.asc(), ContractRiskRule.id.asc()).all()
return [serialize_rule(r) for r in rows]
def get_enabled_rules(contract_type: str | None = None) -> list[dict[str, Any]]:
"""
Load enabled rules for analysis.
Rules for the requested contract type are used first; general procurement rules are included as fallback.
"""
normalized = (contract_type or DEFAULT_CONTRACT_TYPE).strip() or DEFAULT_CONTRACT_TYPE
q = db.session.query(ContractRiskRule).filter(ContractRiskRule.status == "enabled")
if normalized != DEFAULT_CONTRACT_TYPE:
q = q.filter(ContractRiskRule.contract_type.in_([normalized, DEFAULT_CONTRACT_TYPE]))
else:
q = q.filter(ContractRiskRule.contract_type == DEFAULT_CONTRACT_TYPE)
rows = q.order_by(ContractRiskRule.sort_order.asc(), ContractRiskRule.id.asc()).all()
return [serialize_rule(r) for r in rows]
def create_rule(*, user_id: int, data: dict[str, Any]) -> dict[str, Any]:
"""
Create a custom keyword-based contract risk rule.
Built-in codes are reserved for compound procurement checks. Custom rules receive an internal
generated code so their keywords cannot accidentally change a built-in rule's semantics.
Args:
user_id: Administrator creating the rule.
data: Rule display fields, category, keywords and trigger configuration; code is optional.
Returns:
Serialized newly created rule.
Raises:
ValidationError: If category, keywords or enum fields are invalid, or a built-in code is supplied.
"""
code = str(data.get("code") or "").strip()
title = str(data.get("title") or "").strip()
category = _validate_clause_category(str(data.get("clause_category") or ""))
risk_level = str(data.get("risk_level") or "").strip()
risk_hint = str(data.get("risk_hint") or "").strip()
suggestion = str(data.get("suggestion") or "").strip()
keywords = _normalize_keywords(data.get("keywords"))
trigger_type = str(data.get("trigger_type") or "keyword_missing").strip()
status = str(data.get("status") or "enabled").strip()
if not title:
raise ValidationError("title is required")
if not keywords:
raise ValidationError("keywords are required")
if risk_level not in VALID_RISK_LEVELS:
raise ValidationError("invalid risk_level")
if trigger_type not in VALID_TRIGGER_TYPES:
raise ValidationError("invalid trigger_type")
if status not in VALID_STATUS:
raise ValidationError("invalid status")
if code:
if code in BUILTIN_RULE_CODES:
raise ValidationError("built-in rule code is reserved")
raise ValidationError("custom rule code is generated by server")
code = _generate_custom_rule_code(category)
exists = db.session.query(ContractRiskRule).filter(ContractRiskRule.code == code).first()
if exists:
raise ValidationError("rule code already exists")
row = ContractRiskRule(
code=code,
contract_type=str(data.get("contract_type") or DEFAULT_CONTRACT_TYPE).strip() or DEFAULT_CONTRACT_TYPE,
clause_category=category,
title=title,
keywords=keywords,
trigger_type=trigger_type,
risk_level=risk_level,
risk_hint=risk_hint,
suggestion=suggestion,
negotiation_text=(str(data.get("negotiation_text") or "").strip() or None),
status=status,
sort_order=int(data.get("sort_order") or 100),
created_by=user_id,
updated_by=user_id,
)
db.session.add(row)
db.session.commit()
return serialize_rule(row)
def update_rule(rule_id: int, *, user_id: int, data: dict[str, Any]) -> dict[str, Any]:
"""
Update an existing risk rule without changing its detection semantics.
Built-in rules may keep editable display and risk guidance fields, but their category, keywords and
trigger remain fixed because those fields are coupled to compound analyzer logic.
Args:
rule_id: Existing rule primary key.
user_id: Administrator making the change.
data: Partial editable rule payload.
Returns:
Serialized updated rule.
Raises:
NotFoundError: If the rule does not exist.
ValidationError: If enum values are invalid or a built-in detection definition is changed.
"""
row = db.session.get(ContractRiskRule, rule_id)
if not row:
raise NotFoundError("risk rule not found")
if row.code in BUILTIN_RULE_CODES:
if "clause_category" in data and _validate_clause_category(str(data.get("clause_category") or "")) != row.clause_category:
raise ValidationError("built-in rule definition is read-only")
if "keywords" in data and _normalize_keywords(data.get("keywords")) != list(row.keywords or []):
raise ValidationError("built-in rule definition is read-only")
if "trigger_type" in data and str(data.get("trigger_type") or "").strip() != row.trigger_type:
raise ValidationError("built-in rule definition is read-only")
for key in ("contract_type", "clause_category", "title", "risk_hint", "suggestion", "negotiation_text"):
if key in data:
value = str(data.get(key) or "").strip()
if key != "negotiation_text" and not value:
raise ValidationError(f"{key} is required")
if key == "clause_category":
value = _validate_clause_category(value)
setattr(row, key, value or None)
if "keywords" in data:
keywords = _normalize_keywords(data.get("keywords"))
if not keywords:
raise ValidationError("keywords are required")
row.keywords = keywords
if "trigger_type" in data:
trigger_type = str(data.get("trigger_type") or "").strip()
if trigger_type not in VALID_TRIGGER_TYPES:
raise ValidationError("invalid trigger_type")
row.trigger_type = trigger_type
if "risk_level" in data:
risk_level = str(data.get("risk_level") or "").strip()
if risk_level not in VALID_RISK_LEVELS:
raise ValidationError("invalid risk_level")
row.risk_level = risk_level
if "status" in data:
status = str(data.get("status") or "").strip()
if status not in VALID_STATUS:
raise ValidationError("invalid status")
row.status = status
if "sort_order" in data:
row.sort_order = int(data.get("sort_order") or 100)
row.updated_by = user_id
row.updated_at = datetime.utcnow()
db.session.commit()
return serialize_rule(row)
def delete_rule(rule_id: int) -> dict[str, Any]:
"""Delete a risk rule."""
row = db.session.get(ContractRiskRule, rule_id)
if not row:
raise NotFoundError("risk rule not found")
db.session.delete(row)
db.session.commit()
return {"deleted": True, "id": rule_id}
@@ -0,0 +1,293 @@
"""
backend/app/services/procurement_contract/template_service.py
用途:采购合同标准模板库 CRUD、设默认、列表。
依赖:models.ContractTemplate、file_assets、db、errors。
逻辑:Admin API 调用;Chat 下拉读 enabled 列表。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from app import db
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.core.response import utc_iso
from app.models import ContractReview, ContractTemplate, FileAsset, User
from app.services.file_assets.service import (
get_asset_for_user,
mark_asset_referenced,
read_asset_bytes,
release_asset_reference,
)
from app.services.procurement_contract import analyze
from app.services.procurement_contract.comparison_regions import (
preview_anchor_recognition,
validate_comparison_region_config,
)
def serialize_template(row: ContractTemplate) -> dict[str, Any]:
"""ORM → API dict。"""
return {
"id": row.id,
"name": row.name,
"version": row.version,
"file_name": row.file_name,
"file_asset_id": row.file_asset_id,
"contract_type": row.contract_type,
"applicable_scope": row.applicable_scope,
"change_note": row.change_note,
"comparison_region_config": row.comparison_region_config,
"status": row.status,
"is_default": bool(row.is_default),
"remark": row.remark,
"created_by": row.created_by,
"updated_by": row.updated_by,
"updated_by_name": _user_name(row.updated_by),
"created_at": utc_iso(row.created_at),
"updated_at": utc_iso(row.updated_at),
}
def list_templates(*, status: str | None = None) -> list[dict[str, Any]]:
"""列出模板;可按 status 过滤。"""
q = db.session.query(ContractTemplate)
if status:
q = q.filter(ContractTemplate.status == status)
rows = q.order_by(ContractTemplate.is_default.desc(), ContractTemplate.updated_at.desc()).all()
return [serialize_template(r) for r in rows]
def _user_name(user_id: int | None) -> str | None:
"""Resolve a user's display name for template metadata."""
if not user_id:
return None
user = db.session.get(User, user_id)
if not user:
return None
return user.real_name or user.username
def list_enabled_for_chat() -> list[dict[str, Any]]:
"""会话下拉:仅启用中的模板。"""
return list_templates(status="enabled")
def get_default_enabled_template() -> ContractTemplate | None:
"""Return the single enabled default template whose config controls compare-region partitioning."""
return (
db.session.query(ContractTemplate)
.filter(
ContractTemplate.status == "enabled",
ContractTemplate.is_default.is_(True),
)
.order_by(ContractTemplate.updated_at.desc())
.first()
)
def create_template(
*,
user_id: int,
name: str,
version: str,
file_asset_id: int | None = None,
file_asset_no: str | None = None,
remark: str | None = None,
is_default: bool = False,
status: str = "enabled",
contract_type: str = "general_procurement",
applicable_scope: str | None = None,
change_note: str | None = None,
comparison_region_config: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""
创建模板并可选设为默认。
Raises:
ValidationError: 参数非法或资产不可用。
"""
name = (name or "").strip()
version = (version or "").strip()
if not name or not version:
raise ValidationError("name and version are required")
if status not in ("enabled", "disabled"):
raise ValidationError("invalid status")
asset: FileAsset | None = None
if file_asset_id:
asset = db.session.get(FileAsset, file_asset_id)
elif file_asset_no:
asset = get_asset_for_user(file_asset_no, user_id)
if not asset or asset.deleted_at is not None:
raise ValidationError("file asset not found")
exists = (
db.session.query(ContractTemplate)
.filter(ContractTemplate.name == name, ContractTemplate.version == version)
.first()
)
if exists:
raise ValidationError("template name+version already exists")
if is_default and status == "enabled":
_clear_defaults()
row = ContractTemplate(
name=name,
version=version,
file_asset_id=asset.id,
file_name=asset.original_filename,
contract_type=(contract_type or "general_procurement").strip() or "general_procurement",
applicable_scope=(applicable_scope or "").strip() or None,
change_note=(change_note or "").strip() or None,
comparison_region_config=(
validate_comparison_region_config(comparison_region_config)
if comparison_region_config is not None
else None
),
status=status,
is_default=bool(is_default and status == "enabled"),
remark=(remark or "").strip() or None,
created_by=user_id,
updated_by=user_id,
)
db.session.add(row)
mark_asset_referenced(asset)
db.session.commit()
return serialize_template(row)
def update_template(template_id: int, *, user_id: int, data: dict[str, Any]) -> dict[str, Any]:
"""更新模板元数据 / 启停 / 设默认。"""
row = db.session.get(ContractTemplate, template_id)
if not row:
raise NotFoundError("template not found")
if "name" in data and data["name"] is not None:
row.name = str(data["name"]).strip() or row.name
if "version" in data and data["version"] is not None:
row.version = str(data["version"]).strip() or row.version
if "remark" in data:
row.remark = (str(data["remark"]).strip() or None) if data["remark"] is not None else None
if "contract_type" in data and data["contract_type"] is not None:
row.contract_type = str(data["contract_type"]).strip() or row.contract_type
if "applicable_scope" in data:
row.applicable_scope = (str(data["applicable_scope"]).strip() or None) if data["applicable_scope"] is not None else None
if "change_note" in data:
row.change_note = (str(data["change_note"]).strip() or None) if data["change_note"] is not None else None
if "comparison_region_config" in data:
row.comparison_region_config = (
validate_comparison_region_config(data["comparison_region_config"])
if data["comparison_region_config"] is not None
else None
)
if "status" in data and data["status"] is not None:
status = str(data["status"])
if status not in ("enabled", "disabled"):
raise ValidationError("invalid status")
if status == "disabled" and row.is_default:
raise ValidationError("cannot disable default template; set another default first")
row.status = status
if data.get("is_default") is True:
if row.status != "enabled":
raise ValidationError("only enabled template can be default")
_clear_defaults()
row.is_default = True
elif data.get("is_default") is False:
row.is_default = False
row.updated_by = user_id
row.updated_at = datetime.utcnow()
db.session.commit()
return serialize_template(row)
def delete_template(template_id: int) -> dict[str, Any]:
"""
Delete a non-default template that is not referenced by review history.
Historical reviews retain their template relationship for audit and file download,
so referenced templates must be disabled rather than deleted.
Raises:
NotFoundError: The template does not exist.
ValidationError: The template is currently the default template.
ConflictError: One or more review history records reference the template.
"""
row = db.session.get(ContractTemplate, template_id)
if not row:
raise NotFoundError("template not found")
if row.is_default:
raise ValidationError("cannot delete default template")
review_count = (
db.session.query(ContractReview.id)
.filter(ContractReview.template_id == template_id)
.count()
)
if review_count:
raise ConflictError(
code="PROCUREMENT_CONTRACT.TEMPLATE_REFERENCED",
message="模板已被审查历史引用,无法删除;请停用该模板",
details={"template_id": template_id, "review_count": review_count},
)
asset = db.session.get(FileAsset, row.file_asset_id) if row.file_asset_id else None
db.session.delete(row)
if asset:
release_asset_reference(asset)
db.session.commit()
return {"deleted": True, "id": template_id}
def get_template_or_404(template_id: int) -> ContractTemplate:
"""取模板实体。"""
row = db.session.get(ContractTemplate, template_id)
if not row:
raise NotFoundError("template not found")
return row
def read_template_bytes(template: ContractTemplate) -> tuple[str, bytes]:
"""读取模板文件字节。"""
if not template.file_asset_id:
raise ValidationError("template has no file")
asset = db.session.get(FileAsset, template.file_asset_id)
if not asset:
raise NotFoundError("template file not found")
return asset.original_filename, read_asset_bytes(asset)
def preview_comparison_regions(template_id: int, config: Any) -> dict[str, Any]:
"""
Preview configured anchors against the stored Admin template without changing review baselines.
Args:
template_id: Admin template primary key.
config: Unsaved comparison-region config from the edit dialog.
Returns:
Recognition status for body, signature, and attachment anchors.
"""
template = get_template_or_404(template_id)
normalized = validate_comparison_region_config(config)
filename, data = read_template_bytes(template)
raw_text = analyze.extract_text_from_bytes(filename, data)
clean_text = analyze.clean_contract_text(raw_text)
if not clean_text or clean_text.startswith("[binary:"):
raise ValidationError(
"template text cannot be extracted for comparison-region preview",
code="PROCUREMENT_CONTRACT.COMPARISON_REGION_PREVIEW_FAILED",
)
result = preview_anchor_recognition(clean_text, normalized)
result["template_id"] = template.id
result["template_name"] = template.name
return result
def _clear_defaults() -> None:
"""清除所有默认标记。"""
db.session.query(ContractTemplate).filter(ContractTemplate.is_default.is_(True)).update(
{"is_default": False},
synchronize_session=False,
)
@@ -0,0 +1,103 @@
"""Add contract_templates and contract_reviews tables.
Purpose:
Persist procurement contract review templates and per-contract review history.
Dependencies:
Alembic revision c8d9e0f1a2b3; file_assets / users / agents / chat_logs exist.
Flow:
Admin manages templates; chat/tool creates contract_reviews rows.
Revision ID: a1c2d3e4f5b6
Revises: c8d9e0f1a2b3
Create Date: 2026-07-15 09:30:00.000000
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision = "a1c2d3e4f5b6"
down_revision = "c8d9e0f1a2b3"
branch_labels = None
depends_on = None
def upgrade():
"""Create contract_templates and contract_reviews."""
op.create_table(
"contract_templates",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("name", sa.String(length=128), nullable=False),
sa.Column("version", sa.String(length=32), nullable=False),
sa.Column("file_asset_id", sa.Integer(), nullable=True),
sa.Column("file_name", sa.String(length=255), nullable=False),
sa.Column("status", sa.String(length=16), nullable=False),
sa.Column("is_default", sa.Boolean(), nullable=False),
sa.Column("remark", sa.Text(), nullable=True),
sa.Column("created_by", sa.Integer(), nullable=True),
sa.Column("updated_by", sa.Integer(), nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.Column("updated_at", sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(["created_by"], ["users.id"]),
sa.ForeignKeyConstraint(["file_asset_id"], ["file_assets.id"]),
sa.ForeignKeyConstraint(["updated_by"], ["users.id"]),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint("name", "version", name="uq_contract_templates_name_version"),
)
op.create_index("ix_contract_templates_status", "contract_templates", ["status"], unique=False)
op.create_table(
"contract_reviews",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("review_no", sa.String(length=64), nullable=False),
sa.Column("agent_id", sa.Integer(), nullable=True),
sa.Column("user_id", sa.Integer(), nullable=False),
sa.Column("chat_log_id", sa.Integer(), nullable=True),
sa.Column("review_mode", sa.String(length=16), nullable=False),
sa.Column("status", sa.String(length=16), nullable=False),
sa.Column("contract_asset_id", sa.Integer(), nullable=True),
sa.Column("contract_file_name", sa.String(length=255), nullable=False),
sa.Column("template_id", sa.Integer(), nullable=True),
sa.Column("template_source", sa.String(length=16), nullable=False),
sa.Column("template_asset_id", sa.Integer(), nullable=True),
sa.Column("template_name", sa.String(length=255), nullable=True),
sa.Column("high_risk_count", sa.Integer(), nullable=False),
sa.Column("medium_risk_count", sa.Integer(), nullable=False),
sa.Column("low_risk_count", sa.Integer(), nullable=False),
sa.Column("summary_json", sa.JSON(), nullable=True),
sa.Column("clauses_json", sa.JSON(), nullable=True),
sa.Column("report_text", sa.Text(), nullable=True),
sa.Column("error_message", sa.Text(), nullable=True),
sa.Column("started_at", sa.DateTime(), nullable=True),
sa.Column("finished_at", sa.DateTime(), nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.Column("updated_at", sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(["agent_id"], ["agents.id"]),
sa.ForeignKeyConstraint(["chat_log_id"], ["chat_logs.id"]),
sa.ForeignKeyConstraint(["contract_asset_id"], ["file_assets.id"]),
sa.ForeignKeyConstraint(["template_asset_id"], ["file_assets.id"]),
sa.ForeignKeyConstraint(["template_id"], ["contract_templates.id"]),
sa.ForeignKeyConstraint(["user_id"], ["users.id"]),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint("review_no"),
)
op.create_index("ix_contract_reviews_review_no", "contract_reviews", ["review_no"], unique=False)
op.create_index("ix_contract_reviews_agent_id", "contract_reviews", ["agent_id"], unique=False)
op.create_index("ix_contract_reviews_user_id", "contract_reviews", ["user_id"], unique=False)
op.create_index("ix_contract_reviews_review_mode", "contract_reviews", ["review_mode"], unique=False)
op.create_index("ix_contract_reviews_status", "contract_reviews", ["status"], unique=False)
op.create_index("ix_contract_reviews_created_at", "contract_reviews", ["created_at"], unique=False)
def downgrade():
"""Drop contract review tables."""
op.drop_index("ix_contract_reviews_created_at", table_name="contract_reviews")
op.drop_index("ix_contract_reviews_status", table_name="contract_reviews")
op.drop_index("ix_contract_reviews_review_mode", table_name="contract_reviews")
op.drop_index("ix_contract_reviews_user_id", table_name="contract_reviews")
op.drop_index("ix_contract_reviews_agent_id", table_name="contract_reviews")
op.drop_index("ix_contract_reviews_review_no", table_name="contract_reviews")
op.drop_table("contract_reviews")
op.drop_index("ix_contract_templates_status", table_name="contract_templates")
op.drop_table("contract_templates")
@@ -0,0 +1,185 @@
"""Extend procurement contract review rules and metadata.
Purpose:
Add configurable risk rules, richer template metadata, and review search fields.
Dependencies:
Alembic revision a1c2d3e4f5b6 creates procurement contract base tables.
Flow:
Admin maintains risk rules; review service stores richer counts and metadata.
Revision ID: b2c4d6e8f0a1
Revises: a1c2d3e4f5b6
Create Date: 2026-07-15 11:20:00.000000
"""
from __future__ import annotations
import json
import sqlalchemy as sa
from alembic import op
revision = "b2c4d6e8f0a1"
down_revision = "a1c2d3e4f5b6"
branch_labels = None
depends_on = None
def upgrade():
"""Add rule table and richer procurement contract metadata."""
op.add_column(
"contract_templates",
sa.Column("contract_type", sa.String(length=64), nullable=False, server_default="general_procurement"),
)
op.add_column("contract_templates", sa.Column("applicable_scope", sa.Text(), nullable=True))
op.add_column("contract_templates", sa.Column("change_note", sa.Text(), nullable=True))
op.create_index("ix_contract_templates_contract_type", "contract_templates", ["contract_type"], unique=False)
op.add_column("contract_reviews", sa.Column("supplier_name", sa.String(length=128), nullable=True))
op.add_column(
"contract_reviews",
sa.Column("contract_type", sa.String(length=64), nullable=False, server_default="general_procurement"),
)
op.add_column("contract_reviews", sa.Column("total_change_count", sa.Integer(), nullable=False, server_default="0"))
op.create_index("ix_contract_reviews_supplier_name", "contract_reviews", ["supplier_name"], unique=False)
op.create_index("ix_contract_reviews_contract_type", "contract_reviews", ["contract_type"], unique=False)
op.create_table(
"contract_risk_rules",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("code", sa.String(length=64), nullable=False),
sa.Column("contract_type", sa.String(length=64), nullable=False),
sa.Column("clause_category", sa.String(length=64), nullable=False),
sa.Column("title", sa.String(length=128), nullable=False),
sa.Column("keywords", sa.JSON(), nullable=False),
sa.Column("trigger_type", sa.String(length=32), nullable=False),
sa.Column("risk_level", sa.String(length=16), nullable=False),
sa.Column("risk_hint", sa.Text(), nullable=False),
sa.Column("suggestion", sa.Text(), nullable=False),
sa.Column("negotiation_text", sa.Text(), nullable=True),
sa.Column("status", sa.String(length=16), nullable=False),
sa.Column("sort_order", sa.Integer(), nullable=False),
sa.Column("created_by", sa.Integer(), nullable=True),
sa.Column("updated_by", sa.Integer(), nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=False, server_default=sa.func.now()),
sa.Column("updated_at", sa.DateTime(), nullable=False, server_default=sa.func.now()),
sa.ForeignKeyConstraint(["created_by"], ["users.id"]),
sa.ForeignKeyConstraint(["updated_by"], ["users.id"]),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint("code", name="uq_contract_risk_rules_code"),
)
op.create_index("ix_contract_risk_rules_contract_type", "contract_risk_rules", ["contract_type"], unique=False)
op.create_index("ix_contract_risk_rules_clause_category", "contract_risk_rules", ["clause_category"], unique=False)
op.create_index("ix_contract_risk_rules_risk_level", "contract_risk_rules", ["risk_level"], unique=False)
op.create_index("ix_contract_risk_rules_status", "contract_risk_rules", ["status"], unique=False)
rule_table = sa.table(
"contract_risk_rules",
sa.column("code", sa.String),
sa.column("contract_type", sa.String),
sa.column("clause_category", sa.String),
sa.column("title", sa.String),
sa.column("keywords", sa.JSON),
sa.column("trigger_type", sa.String),
sa.column("risk_level", sa.String),
sa.column("risk_hint", sa.Text),
sa.column("suggestion", sa.Text),
sa.column("negotiation_text", sa.Text),
sa.column("status", sa.String),
sa.column("sort_order", sa.Integer),
)
op.bulk_insert(
rule_table,
[
{
"code": "payment_acceptance_required",
"contract_type": "general_procurement",
"clause_category": "payment",
"title": "付款需绑定验收与发票",
"keywords": ["付款", "支付", "结算", "账期", "验收", "发票"],
"trigger_type": "keyword_missing",
"risk_level": "high",
"risk_hint": "付款条款缺少验收或发票前提,可能导致未验收即付款。",
"suggestion": "建议恢复或补充“验收合格并收到合规发票后付款”。",
"negotiation_text": "我方付款需以交付、验收合格和收到合规发票为前提,请恢复我司模板条款。",
"status": "enabled",
"sort_order": 10,
},
{
"code": "acceptance_process_required",
"contract_type": "general_procurement",
"clause_category": "acceptance",
"title": "验收标准与不合格处理",
"keywords": ["验收", "合格", "不合格", "整改", "退货", "更换"],
"trigger_type": "keyword_missing",
"risk_level": "high",
"risk_hint": "合同缺少验收标准或不合格处理,后续质量争议难以认定。",
"suggestion": "建议补充验收流程、验收标准和不合格整改/退换货处理。",
"negotiation_text": "验收条款是确认交付质量的基础,请补充明确验收标准和不合格处理方式。",
"status": "enabled",
"sort_order": 20,
},
{
"code": "liability_required",
"contract_type": "general_procurement",
"clause_category": "liability",
"title": "违约责任不可缺失",
"keywords": ["违约", "赔偿", "违约金", "逾期", "延迟交付"],
"trigger_type": "keyword_missing",
"risk_level": "high",
"risk_hint": "合同缺少违约责任,供应商逾期或质量问题的约束不足。",
"suggestion": "建议补回逾期交付、质量不合格、保密违约等责任。",
"negotiation_text": "违约责任属于基本履约保障,建议保留逾期交付和质量不合格赔偿条款。",
"status": "enabled",
"sort_order": 30,
},
{
"code": "jurisdiction_required",
"contract_type": "general_procurement",
"clause_category": "jurisdiction",
"title": "争议解决与管辖",
"keywords": ["管辖", "仲裁", "人民法院", "争议解决"],
"trigger_type": "keyword_missing",
"risk_level": "medium",
"risk_hint": "合同缺少争议解决约定,发生纠纷时维权成本和不确定性增加。",
"suggestion": "建议明确采购方所在地法院或双方认可的仲裁机构。",
"negotiation_text": "为便于双方处理争议,请保留我司模板中的争议解决条款。",
"status": "enabled",
"sort_order": 40,
},
{
"code": "warranty_required",
"contract_type": "general_procurement",
"clause_category": "warranty",
"title": "质保与售后期限",
"keywords": ["质保", "保修", "售后", "维修", "更换"],
"trigger_type": "keyword_missing",
"risk_level": "medium",
"risk_hint": "合同缺少质保或售后约定,后续维修更换缺少依据。",
"suggestion": "建议明确质保期限、起算点、维修响应和更换责任。",
"negotiation_text": "请补充质保期限及售后响应要求,确保交付后质量保障可执行。",
"status": "enabled",
"sort_order": 50,
},
],
)
def downgrade():
"""Remove rule table and added procurement contract metadata."""
op.drop_index("ix_contract_risk_rules_status", table_name="contract_risk_rules")
op.drop_index("ix_contract_risk_rules_risk_level", table_name="contract_risk_rules")
op.drop_index("ix_contract_risk_rules_clause_category", table_name="contract_risk_rules")
op.drop_index("ix_contract_risk_rules_contract_type", table_name="contract_risk_rules")
op.drop_table("contract_risk_rules")
op.drop_index("ix_contract_reviews_contract_type", table_name="contract_reviews")
op.drop_index("ix_contract_reviews_supplier_name", table_name="contract_reviews")
op.drop_column("contract_reviews", "total_change_count")
op.drop_column("contract_reviews", "contract_type")
op.drop_column("contract_reviews", "supplier_name")
op.drop_index("ix_contract_templates_contract_type", table_name="contract_templates")
op.drop_column("contract_templates", "change_note")
op.drop_column("contract_templates", "applicable_scope")
op.drop_column("contract_templates", "contract_type")
@@ -0,0 +1,35 @@
"""Add contract_no to contract_reviews for extracted business contract number.
Purpose:
Persist the counterparty contract number extracted from uploaded contract text.
Dependencies:
Alembic revision b2c4d6e8f0a1 adds procurement contract review metadata.
Flow:
Review analysis fills contract_no; Admin history and report export display it.
Revision ID: c3d5e7f9a1b2
Revises: b2c4d6e8f0a1
Create Date: 2026-07-17 10:40:00.000000
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision = "c3d5e7f9a1b2"
down_revision = "b2c4d6e8f0a1"
branch_labels = None
depends_on = None
def upgrade():
"""Add contract_no column for extracted 合同编号."""
op.add_column("contract_reviews", sa.Column("contract_no", sa.String(length=128), nullable=True))
op.create_index("ix_contract_reviews_contract_no", "contract_reviews", ["contract_no"], unique=False)
def downgrade():
"""Remove contract_no column."""
op.drop_index("ix_contract_reviews_contract_no", table_name="contract_reviews")
op.drop_column("contract_reviews", "contract_no")
@@ -0,0 +1,29 @@
"""Add comparison-region config to procurement contract templates.
Revision ID: d4e6f8a0b2c3
Revises: c3d5e7f9a1b2
Create Date: 2026-07-24 10:00:00.000000
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision = "d4e6f8a0b2c3"
down_revision = "c3d5e7f9a1b2"
branch_labels = None
depends_on = None
def upgrade():
"""Add nullable JSON config so existing templates keep legacy comparison behavior."""
op.add_column(
"contract_templates",
sa.Column("comparison_region_config", sa.JSON(), nullable=True),
)
def downgrade():
"""Remove the comparison-region config column."""
op.drop_column("contract_templates", "comparison_region_config")
@@ -0,0 +1,737 @@
"""
tests/services/procurement_contract/test_analyze.py
用途:采购合同清洗、条款结构化、规则叠加、可读性校验与比对结果字段断言。
依赖:procurement_contract.analyze。
逻辑:保证缺字占位/乱码不会写入 old_text/new_text;条款 title 供前端展示。
"""
from app.core.errors import ValidationError
from app.services.procurement_contract import analyze, rule_service
def test_readable_text_rejects_pdf_missing_glyph_placeholders():
"""缺字占位主导的抽取结果必须判定为不可读。"""
assert not analyze._is_readable_extracted_text("□□□□□合同条款□□□□□")
def test_compare_uses_difference_title_instead_of_rule_title():
"""对比项标题应描述实际差异类别,不得套用单份审核规则标题。"""
result = analyze.analyze_compare(
"付款:验收后30日内支付。",
"付款:验收后90日内支付。",
rules=[
{
"title": "付款条款",
"clause_category": "payment",
"keywords": ["付款"],
"risk_level": "high",
"risk_hint": "付款期限延长",
"suggestion": "恢复原付款期限",
}
],
)
# 断言:规则仅提供风险参考;标题和报告围绕真实付款差异。
clause = result["clauses_json"][0]
assert clause["title"] == "付款条件变更"
assert clause["old_text"] == "付款:验收后30日内支付。"
assert clause["new_text"] == "付款:验收后90日内支付。"
assert clause["comparison_readable"] is True
assert clause["suggestion"] == ""
assert clause["negotiation_text"] == ""
def test_compare_classifies_equipment_schedule_as_commercial_without_legal_risk():
"""合同号、主体和设备清单变化应保留为商业待确认,不计入法律风险。"""
result = analyze.analyze_compare(
"采购合同\n合同编号:TMP-001\n设备名称:冲切机\n型号:A1\n数量:1台\n单价:100元",
"采购合同\n合同编号:VENDOR-889\n设备名称:冲切机\n型号:B2\n数量:2台\n单价:200元",
rules=[],
)
# 断言:交易基础信息变化供业务确认,不污染高中低风险统计。
assert result["clauses_json"][0]["change_class"] in {"metadata", "commercial"}
assert result["high_risk_count"] == 0
assert result["medium_risk_count"] == 0
assert result["low_risk_count"] == 0
def test_compare_ignores_truncated_equipment_table_header_without_values():
"""同一设备表仅因 OCR 漏取后半段表头时,不得产生合同内容变更。"""
result = analyze.analyze_compare(
"序号|设备名称|品牌|型号|数量|单价|总价",
"序号|设备名称|品牌",
rules=[],
)
# 断言:纯表头没有业务值,短表头又是长表头的有序子集,应计为 OCR 噪声。
assert result["clauses_json"] == []
assert result["total_change_count"] == 0
assert result["summary_json"]["comparison_quality"]["ignored_ocr_noise"] == 1
def test_compare_keeps_equipment_table_value_change_when_header_matches():
"""设备表金额、数量等字段值变化必须保留,不能被表头容错规则吞掉。"""
result = analyze.analyze_compare(
"序号|设备名称|品牌|型号|数量|单价|总价\n1|贴标设备|煜英|非标定制|1|24000|24000",
"序号|设备名称|品牌|型号|数量|单价|总价\n1|贴标设备|煜英|非标定制|2|24000|48000",
rules=[],
)
# 断言:数量和总价均为业务事实,仍需显示为商业信息变更。
assert result["total_change_count"] == 1
assert result["clauses_json"][0]["change_class"] == "commercial"
def test_compare_ignores_split_total_row_when_amounts_match_in_both_contracts():
"""同一合计行仅因表格列拆分不一致时,不得误报为金额修改。"""
result = analyze.analyze_compare(
"设备数量:2\n设备总价:¥44,000\n合计|2|¥44,000",
"设备数量:2\n设备总价:¥44,000\n合计",
rules=[],
)
# 断言:金额事实在双方全文一致,只有合计行列拆分不同,应计为抽取噪声。
assert result["clauses_json"] == []
assert result["total_change_count"] == 0
assert result["summary_json"]["comparison_quality"]["ignored_ocr_noise"] == 1
def test_compare_keeps_split_total_row_when_amount_differs():
"""合计金额未在双方全文一致出现时,不能按表格拆列噪声过滤。"""
result = analyze.analyze_compare(
"设备数量:2\n设备总价:¥44,000\n合计|2|¥44,000",
"设备数量:2\n设备总价:¥45,000\n合计",
rules=[],
)
# 断言:44,000 与 45,000 不一致,必须保留真实金额差异。
assert result["total_change_count"] >= 1
def test_compare_ignores_nonsemantic_markdown_and_ocr_fragments():
"""Markdown 标记和单字符 OCR 残片不能成为合同新增项。"""
for fragment in ("##", "人>", "乙", "v"):
result = analyze.analyze_compare("第一条 合同正文", f"第一条 合同正文\n{fragment}", rules=[])
# 断言:残片不含独立字段、金额或义务,必须完全排除在差异清单外。
assert result["clauses_json"] == []
assert result["total_change_count"] == 0
def test_compare_ignores_truncated_duplicate_supplier_name_fragment():
"""签章区新增的 OCR 截断供应商名不应被误报为合同新增内容。"""
supplier = "如玖军棱科技苏州有限公司"
result = analyze.analyze_compare(
f"乙方:{supplier}\n第一条 合同正文",
f"乙方:{supplier}\n第一条 合同正文\n如兮军棱科技(苏",
rules=[],
)
# 断言:共同供应商名只多出一个错字截断片段,应计为 OCR 噪声。
assert result["clauses_json"] == []
assert result["total_change_count"] == 0
assert result["summary_json"]["comparison_quality"]["ignored_ocr_noise"] == 1
def test_supplier_fragment_filter_does_not_hide_actual_supplier_change():
"""原回传合同的供应商主体不一致时,即使有短片段也不得作为重复名称过滤。"""
assert not analyze._is_truncated_duplicate_supplier_fragment_change(
"",
"新供应商科技(苏",
"乙方:原供应商科技苏州有限公司",
"乙方:新供应商科技苏州有限公司\n新供应商科技(苏",
)
def test_compare_keeps_distinct_payment_fragments():
"""同一付款主题下不同句子的账期变化应分别保留,避免漏报。"""
result = analyze.analyze_compare(
"付款:验收后30日支付。\n发票:收到专票后付款。",
"付款:验收后90日支付。\n发票:收到专票后60日付款。",
rules=[
{
"title": "付款需绑定验收与发票",
"clause_category": "payment",
"keywords": ["付款", "验收", "发票"],
"risk_level": "high",
"risk_hint": "付款条件被放宽",
"suggestion": "恢复模板付款条件",
}
],
)
assert len(result["clauses_json"]) == 2
assert all(row["title"] == "付款条件变更" for row in result["clauses_json"])
def test_compare_classifies_equivalent_clause_numbering_as_format_without_risk():
"""中文/阿拉伯数字等价的编号变化只能算格式,不得触发付款高风险规则。"""
result = analyze.analyze_compare(
"3、付款方式:验收后30日支付。",
"三、付款方式:验收后30日支付。",
rules=[
{
"title": "付款需绑定验收与发票",
"clause_category": "payment",
"keywords": ["付款"],
"risk_level": "high",
"risk_hint": "付款条件变更",
"suggestion": "恢复模板付款条件",
}
],
)
# 断言:风险评估建立在语义变化上,而不是原始字符 Diff。
assert result["clauses_json"] == []
assert result["high_risk_count"] == 0
def test_compare_classifies_price_schedule_as_commercial_without_legal_risk():
"""数量和单价修改应归入商业待确认,不默认为法律高风险。"""
result = analyze.analyze_compare(
"设备名称:空压机。数量:1台。单价:100元。",
"设备名称:空压机。数量:2台。单价:200元。",
rules=[],
)
assert result["clauses_json"][0]["change_class"] == "commercial"
assert result["clauses_json"][0]["risk_level"] == "ok"
def test_compare_keeps_payment_term_change_as_obligation_risk():
"""付款账期放宽改变采购方权利义务,仍应进入风险判断。"""
result = analyze.analyze_compare(
"付款方式:验收后30日支付。",
"付款方式:验收后90日支付。",
rules=[
{
"title": "付款需绑定验收与发票",
"clause_category": "payment",
"keywords": ["付款"],
"risk_level": "high",
"risk_hint": "付款条件放宽",
"suggestion": "恢复模板付款期限",
}
],
)
assert result["clauses_json"][0]["change_class"] == "obligation"
assert result["clauses_json"][0]["risk_level"] == "high"
def test_compare_classifies_warranty_period_change_by_changed_field():
"""同句包含质保款和支付时,质保期限数字变化仍必须归类为质保差异。"""
original = "质保款(总价款的0%)¥0.00元,从验收合格日起算6个月质保期满后,乙方无违约行为后支付。"
returned = "质保款(总价款的0%)¥0.00元,从验收合格日起算12个月质保期满后,乙方无违约行为后支付。"
result = analyze.analyze_compare(
original,
returned,
rules=[
{
"title": "付款需绑定验收与发票",
"clause_category": "payment",
"risk_level": "high",
"risk_hint": "付款条件不足",
"suggestion": "恢复付款条件",
"negotiation_text": "恢复我司付款条款",
},
{
"title": "质保期限要求",
"clause_category": "warranty",
"risk_level": "medium",
},
],
)
# 断言:页面和报告只陈述质保差异,不出现无关付款建议或沟通话术。
assert len(result["clauses_json"]) == 1
clause = result["clauses_json"][0]
assert clause["clause_category"] == "warranty"
assert clause["title"] == "质保与售后变更"
assert clause["suggestion"] == ""
assert clause["negotiation_text"] == ""
assert "差异项清单" in result["report_text"]
assert "我方原文" in result["report_text"]
assert "回传内容" in result["report_text"]
assert "6个月" in result["report_text"]
assert "12个月" in result["report_text"]
assert "付款需绑定验收与发票" not in result["report_text"]
assert "沟通话术" not in result["report_text"]
def test_compare_ignores_cleaner_role_markers_and_spacing_only_changes():
"""清洗器的模板/合同标记、空白与排版差异不得生成任何变更记录。"""
result = analyze.analyze_compare(
"template\n2. 本合同之任何增修应以书面为之,并以双方盖公章的方式签订。",
"contract\n2.本合同之任何增修应以书面为之,并以双方盖公章的方式签订。",
rules=[],
)
# 断言:以语义归一键比对后,仅表达差异不进入结果列表。
assert result["clauses_json"] == []
def test_compare_ignores_standalone_numbering_fragment_insert():
"""A detached table or clause serial number must not become a contract-change record."""
result = analyze.analyze_compare(
"第一条 付款方式:验收后30日内支付。",
"第一条 付款方式:验收后30日内支付。\n1",
rules=[],
)
# The isolated `1` has no field, amount, unit, or obligation and is counted only as OCR noise.
assert result["clauses_json"] == []
assert result["total_change_count"] == 0
assert result["summary_json"]["comparison_quality"]["ignored_ocr_noise"] == 1
def test_compare_ignores_renumbered_clause_when_body_is_unchanged():
"""供应商插入条款540e的重新编号不应使后续所有条款错位成为修改。"""
result = analyze.analyze_compare(
"11、 违约责任\n乙方违约应承担赔偿责任。",
"一、违约责任\n乙方违约应承担赔偿责任。",
rules=[],
)
assert result["clauses_json"] == []
def test_safe_comparison_text_clears_unreadable_blobs():
"""缺字占位 / 私用区主导的片段不得写入对照列。"""
assert analyze._safe_comparison_text("□" * 40) == ""
assert analyze._safe_comparison_text("\ue000" * 40) == ""
assert analyze._safe_comparison_text("付款:验收后30日内支付。") == "付款:验收后30日内支付。"
def test_extract_party_fields_reads_seller_and_contract_no():
"""乙方(卖方)与合同编号须从合同抬头抽取为供应商与业务合同号。"""
text = (
"甲方(买方):苏州和信精密科技有限公司\n"
"乙方(卖方):邢台恒阔机械制造有限公司\n"
"合同编号:HX-PO-20260709-0002\n"
"第一条 甲方向乙方所购买的……"
)
party = analyze.extract_party_fields(text)
# 断言:卖方公司名与合同编号被正确识别
assert party["supplier_name"] == "邢台恒阔机械制造有限公司"
assert party["contract_no"] == "HX-PO-20260709-0002"
def test_compare_short_circuits_binary_placeholder_text():
"""任一侧为 [binary:] 占位时不应产出虚假变更行。"""
result = analyze.analyze_compare(
"[binary:a.pdf] PDF 文本编码不兼容或未能提取正文;请上传 Word 或可检索文本的 PDF。",
"付款:验收后30日内支付。",
rules=[],
)
assert result["clauses_json"] == []
assert result["summary_json"]["text_extraction_warning"] == "pdf_unreadable"
def test_split_paragraphs_breaks_single_line_pdf_page_into_clause_units():
"""单行 PDF 页须按句拆分,避免一整页落入一个 Diff 单元格。"""
parts = analyze._split_paragraphs(
"□□□□设备买卖合同。付款:验收后30日内支付。质保期12个月。"
)
# 缺字占位已清洗,各句独立成段。
assert parts == ["设备买卖合同。", "付款:验收后30日内支付。", "质保期12个月。"]
def test_clean_contract_text_removes_repeated_header_and_page_number():
"""重复页眉和独立页码应删除,正式条款内容必须保留。"""
raw = (
"采购合同(内部)\n第1页\n第一条 交付期限为30日。\n"
"采购合同(内部)\n第2页\n第二条 验收期为10日。\n"
"采购合同(内部)\n第3页\n第三条 质保期为12个月。"
)
cleaned = analyze.clean_contract_text(raw)
# 关键断言:重复短页眉被识别为噪音,条款编号及业务数值未被改写。
assert "采购合同(内部)" not in cleaned
assert "第一条 交付期限为30日。" in cleaned
assert "第三条 质保期为12个月。" in cleaned
def test_clean_contract_text_removes_inline_page_number_and_page_image_marker():
"""扫描清洗器的分页图片标记及粘在正文中的页码不得进入 Diff。"""
cleaned = analyze.clean_contract_text(
"![page-image-1]\n付款条款。 第 1页 共 6页 交货条款。"
)
assert "page-image" not in cleaned
assert "第 1页 共 6页" not in cleaned
assert "付款条款" in cleaned
def test_clean_contract_text_normalizes_mineru_html_table_without_tag_attributes():
"""MinerU 表格应只保留单元格内容,rowspan/colspan 不得进入合同改动对照。"""
cleaned = analyze.clean_contract_text(
"<table><tr><td rowspan=1 colspan=2>设备名称</td><td colspan=1>数量</td></tr>"
"<tr><td rowspan=1 colspan=2>切割机</td><td colspan=1>2</td></tr></table>"
)
# 关键断言:可比文本保留表格业务值,不携带 MinerU HTML 布局属性。
assert cleaned == "设备名称 | 数量\n切割机 | 2"
assert "rowspan" not in cleaned
assert "<td" not in cleaned
def test_clean_contract_text_removes_duplicate_mineru_signature_party_line():
"""签章区乙方名称已在抬头出现时不应形成伪删除条款。"""
cleaned = analyze.clean_contract_text(
"卖方:宏博气体设备(苏州)有限公司(以下简称乙方)\n"
"签署日期:2026年7月1日\n乙方:宏博气体设备(苏州)有限公司"
)
# 关键断言:卖方抬头保留,签章区重复主体行被剥离。
assert cleaned.count("宏博气体设备(苏州)有限公司") == 1
def test_structure_contract_clauses_preserves_order_and_category():
"""结构化条款必须保留原顺序、编号,并按领域关键词标注类别。"""
clauses = analyze.structure_contract_clauses(
"第一条 付款\n甲方验收后30日内支付。\n第二条 验收\n甲方应书面确认验收结果。"
)
# 断言:Dify 可通过稳定 clause_id 遍历全部条款并引用证据。
assert [item["clause_id"] for item in clauses] == ["clause-0001", "clause-0002"]
assert clauses[0]["clause_no"] == "第一条"
assert clauses[0]["category"] == "payment"
assert clauses[1]["category"] == "acceptance"
def test_compare_adds_full_contract_rule_scan_without_inflating_change_count():
"""模板无差异时仍应追加缺项红线,但模板变更数保持为零。"""
text = "第一条 货物应在30日内交付。"
rules = [
{
"code": "IP_REQUIRED",
"title": "知识产权保障",
"clause_category": "ip",
"keywords": ["知识产权"],
"trigger_type": "keyword_missing",
"risk_level": "high",
"risk_hint": "缺少知识产权保障条款",
"suggestion": "补充供应商侵权赔偿责任",
}
]
result = analyze.analyze_compare(text, text, rules=rules)
result = analyze.append_solo_rule_findings(result, text, rules=rules)
# 断言:规则风险被补齐,但不能把规则风险数误当模板变更数。
assert result["total_change_count"] == 0
assert result["high_risk_count"] >= 1
ip_findings = [item for item in result["clauses_json"] if item["clause_no"] == "IP_REQUIRED"]
assert len(ip_findings) == 1
assert ip_findings[0]["change_type"] == "rule_scan"
def test_extraction_quality_flags_ocr_noise_without_rejecting_readable_chinese():
"""正文可读但数字含圈号/希腊字母时应降级质量,不能当作高可信文本。"""
quality = analyze.extraction_quality("付款:¥108,OO0 元,交货期为 2026 年 ⑧ 月 ⑳ 日。")
assert quality["level"] in {"medium", "low"}
assert quality["warning"] in {"ocr_noise_detected", "text_quality_low"}
def test_compare_ignores_high_similarity_ocr_character_noise():
"""标点和单个 OCR 错字且关键数值一致时不应报告为合同修改。"""
result = analyze.analyze_compare(
"第八条 质保。维修价格需符合市场行情。",
"第八条 质保,维修价格需符合市场行情c",
rules=[],
)
assert result["clauses_json"] == []
assert result["summary_json"]["comparison_quality"]["ignored_ocr_noise"] == 1
def test_compare_keeps_explicit_numeric_change_despite_high_text_similarity():
"""付款期限等明确数字变化不能被 OCR 容错吞掉。"""
result = analyze.analyze_compare(
"付款方式:验收合格后30日内支付。",
"付款方式:验收合格后90日内支付。",
rules=[],
)
assert len(result["clauses_json"]) == 1
assert result["clauses_json"][0]["change_class"] == "obligation"
def test_compare_ignores_ocr_corrupted_list_number():
"""列表编号 4) 被 OCR 为 0 时不应认定履约义务发生变化。"""
result = analyze.analyze_compare(
"4) 买方发出的任何合理的延期交货指示;",
"0 买方发出的任何合理的延期交货指示;",
rules=[],
)
assert result["clauses_json"] == []
def test_compare_marks_corrupted_percentage_as_needing_confirmation():
"""比例数字被识别为普通汉字时不进结果卡,只记入手动复核建议统计。"""
result = analyze.analyze_compare(
"质保款(总价款的0%)¥0.00元,质保期12个月。",
"质保款(总价款的维%)¥0.OO元,质保期12个月。",
rules=[],
)
assert all(row.get("change_type") != "ocr_uncertain" for row in result["clauses_json"])
assert result["total_change_count"] == 0
quality = result["summary_json"]["comparison_quality"]
assert quality["needs_confirmation"] == 0
assert quality["confirmation_fragments"] >= 1 or quality["ignored_ocr_noise"] >= 1
def test_compare_ignores_ocr_corrupted_metadata_in_noisy_contract():
"""合同号和主体名称的 OCR 乱码不应逐条要求采购确认。"""
filler = "设备采购合同约定双方应共同遵守。" * 40
result = analyze.analyze_compare(
f"合同号:5203-2607090002\n买方:苏州和信精密科技有限公司\n{filler}",
f"合同号:羽Os刁GO⒛90002\n买方:苏州和信精密科技有限公司\n{filler}",
rules=[],
)
# 断言:抬头 OCR 噪声被统计但不进入待确认或正式改动。
quality = result["summary_json"]["comparison_quality"]
assert quality["needs_confirmation"] == 0
assert quality["ignored_ocr_noise"] >= 1
assert result["total_change_count"] == 0
def test_compare_keeps_readable_contract_number_change_in_noisy_contract():
"""清晰可读的合同编号变化仍应作为基础信息改动保留。"""
filler = "扫描版本α。设备采购合同约定双方应共同遵守。" * 40
result = analyze.analyze_compare(
f"合同号:5203-2607090002\n{filler}",
f"合同号:5203-2607090003\n{filler}",
rules=[],
)
# 断言:只有含 OCR 可疑字形的抬头差异才忽略,明确数字变化不能被吞掉。
changes = [row for row in result["clauses_json"] if row.get("change_type") == "modify"]
assert len(changes) == 1
assert changes[0].get("validation_status") != "needs_review"
assert result["total_change_count"] == 1
def test_compare_groups_multiple_payment_ocr_fragments_into_one_confirmation():
"""同一付款主题的多个 OCR 数字异常不进结果卡,只累计确认片段数。"""
filler = "扫描版本α。本合同经双方签署后生效并共同遵守。" * 40
result = analyze.analyze_compare(
f"{filler}\n预付款为总价款的30%。\n验收款于验收后30日内支付。",
f"{filler}\n预付款为总价款的3哪%。\n验收款于验收后卫日内支付。",
rules=[],
)
pending = [row for row in result["clauses_json"] if row["change_type"] == "ocr_uncertain"]
assert pending == []
assert result["summary_json"]["comparison_quality"]["confirmation_fragments"] >= 1
assert result["summary_json"]["comparison_quality"]["needs_confirmation"] == 0
def test_compare_ignores_noncritical_ocr_typo_in_noisy_contract():
"""非关键普通错字在长篇扫描合同中不应生成待确认项。"""
filler = "扫描版本α。设备采购合同约定双方应共同遵守。" * 40
result = analyze.analyze_compare(
f"{filler}\n包装材料应符合正常运输要求。",
f"{filler}\n包装材科应符合正常运输要求。",
rules=[],
)
quality = result["summary_json"]["comparison_quality"]
assert quality["needs_confirmation"] == 0
assert quality["ignored_ocr_noise"] >= 1
def test_compare_ignores_short_mixed_ocr_garbage_insert():
"""正文表格附近的印章/字体乱码不得作为供应商新增条款展示。"""
result = analyze.analyze_compare(
"专用控制平台 I5 工控 1 套 专用电脑",
"专用控制平台 I5 工控 1 套 专用电脑\n1 惠 C 市 WW n3",
rules=[],
)
# 断言:短乱码只计入已忽略噪声,不进入改动项或风险统计。
assert result["clauses_json"] == []
assert result["total_change_count"] == 0
assert result["summary_json"]["comparison_quality"]["ignored_ocr_noise"] == 1
def test_compare_keeps_short_commercial_values_and_contract_terms():
"""型号、数量、金额、期限等合法短文本不能被短乱码门禁误删。"""
cases = (
"型号:BD-BLC1313",
"1 台 ABC 3000W",
"金额100元",
"验收后30天支付",
"质保期2年",
)
for added_text in cases:
result = analyze.analyze_compare("设备配置如下", f"设备配置如下\n{added_text}", rules=[])
# 断言:每种具有明确业务语义的短新增值均保留一条差异。
assert len(result["clauses_json"]) == 1, added_text
assert result["clauses_json"][0]["change_type"] == "insert", added_text
def test_compare_ignores_document_end_marker_fragment():
"""“以下无正文”等签章页结束语抽取不完整时不应计为合同修改。"""
result = analyze.analyze_compare("(以下无正文)", "(以下", rules=[])
assert result["clauses_json"] == []
def test_compare_ignores_signature_block_alignment_noise():
"""签章页的主体名称和签署日期错位不应计为条款修改。"""
result = analyze.analyze_compare("乙方:供应商有限公司", "签署日期:", rules=[])
assert result["clauses_json"] == []
def test_compare_ignores_duplicate_party_name_from_signature_section():
"""乙方名称已在抬头出现时,签章区重复行的删除不应成为合同改动。"""
template = "卖方:宏博气体设备(苏州)有限公司\n签署日期:2026年7月1日\n乙方:宏博气体设备(苏州)有限公司"
contract = "卖方:宏博气体设备(苏州)有限公司\n签署日期:2026年7月1日"
result = analyze.analyze_compare(template, contract, rules=[])
# 关键断言:主体信息重复仅属签章版式,不进入采购改动项。
assert result["clauses_json"] == []
def test_compare_ignores_end_signature_misaligned_to_existing_warranty_summary():
"""签署日期与正文已出现的保固摘要错配时,不得伪造质保修改。"""
template = "保固售服:整机保修1年,碳分子筛质保3年。\n签署日期:年月日"
contract = "保固售服:整机保修1年,碳分子筛质保3年。\n签署日期:年月日\n保固售服:整机保修1年,碳分子筛质保3年。"
result = analyze.analyze_compare(template, contract, rules=[])
# 关键断言:同一摘要已在正文存在,尾部抽取错位不应产生中风险。
assert result["clauses_json"] == []
def test_compare_keeps_liability_change_despite_payment_prefix_and_signature():
"""同段付款未变但违约金改写、或同行含签署日期时,必须检出实质变更。"""
# 断言:focused 截断不得吞掉同段违约金改动。
result = analyze.analyze_compare(
"付款:验收后30日支付。\n迟延交货违约金按每日合同价款的千分之五计。",
"付款:验收后30日支付。\n迟延交货违约金按每日合同价款的千分之一计。",
rules=[],
)
assert len(result["clauses_json"]) >= 1
assert any("千分" in f"{row.get('old_text')}{row.get('new_text')}" for row in result["clauses_json"])
lights = {item["key"]: item for item in result["summary_json"]["focus_lights"]}
assert lights["liability"]["status"] == "changed"
# 断言:签章词不得吞掉同段违约金改动。
signed = analyze.analyze_compare(
"迟延交货违约金按每日合同价款的千分之五计。签署日期:2026年1月1日",
"迟延交货违约金按每日合同价款的千分之一计。签署日期:2026年1月1日",
rules=[],
)
assert len(signed["clauses_json"]) >= 1
assert signed["clauses_json"][0]["risk_level"] in {"high", "medium"}
def test_compare_detects_chinese_per_mille_change():
"""中文「千分之五→千分之一」必须识别为实质数字变更。"""
result = analyze.analyze_compare(
"乙方逾期交付的,每逾期一日按合同总价千分之五支付违约金。",
"乙方逾期交付的,每逾期一日按合同总价千分之一支付违约金。",
rules=[],
)
assert len(result["clauses_json"]) == 1
assert result["clauses_json"][0]["change_class"] == "obligation"
assert result["clauses_json"][0]["risk_level"] in {"high", "medium"}
def test_compare_jurisdiction_change_is_at_least_medium():
"""管辖地由甲方改为乙方时,即使无管理端规则也应达到中高风险。"""
result = analyze.analyze_compare(
"因本合同而生的争议,双方同意以甲方所在地人民法院作为第一审管辖法院。",
"因本合同而生的争议,双方同意以乙方所在地人民法院作为第一审管辖法院。",
rules=[],
)
assert len(result["clauses_json"]) == 1
assert result["clauses_json"][0]["change_class"] == "obligation"
assert result["clauses_json"][0]["risk_level"] in {"high", "medium"}
lights = {item["key"]: item for item in result["summary_json"]["focus_lights"]}
assert lights["dispute"]["status"] == "changed"
def test_structure_contract_clauses_recognizes_chinese_list_heading():
"""一、二、形式的主条款必须独立切分,不能与合同抬头粘在同一段。"""
clauses = analyze.structure_contract_clauses(
"设备买卖合同\n一、付款方式\n验收合格后付款。\n二、交货期限\n签约后30日交货。"
)
numbered = [item for item in clauses if item["clause_no"] in {"一、", "二、"}]
assert [item["clause_no"] for item in numbered] == ["一、", "二、"]
def test_solo_policy_flags_missing_procurement_focus_terms():
"""卖方自有合同缺少采购五项重点保障时应给出确定性风险项。"""
result = analyze.analyze_solo("设备名称:方管矫直机。总价:28000元。", rules=[])
codes = {item["clause_no"] for item in result["clauses_json"]}
assert {
"POLICY_PAYMENT_CONDITIONS",
"POLICY_DELIVERY_DEADLINE",
"POLICY_WARRANTY_TERM",
"POLICY_JURISDICTION",
"POLICY_DELAY_PENALTY",
}.issubset(codes)
def test_solo_policy_accepts_clear_five_per_mille_delay_penalty():
"""每日合同总价千分之五的逾期交付违约金达到采购基线,不应新增该项风险。"""
text = (
"付款:设备到货并验收合格,收到发票后支付。\n"
"交货期限:签约后30个工作日。\n"
"质保期:验收合格后12个月。\n"
"争议由甲方所在地人民法院管辖。\n"
"乙方逾期交付的,每逾期一日按合同总价5‰支付违约金。"
)
result = analyze.analyze_solo(text, rules=[])
codes = {item["clause_no"] for item in result["clauses_json"]}
assert "POLICY_DELAY_PENALTY" not in codes
def test_solo_policy_accepts_chinese_five_per_mille_delay_penalty():
"""“每延迟一日按千分之五”应识别为达到采购基线。"""
text = "乙方迟延履行交货义务时,每延迟一日按设备总价款千分之五支付违约金。"
result = analyze.analyze_solo(text, rules=[])
codes = {item["clause_no"] for item in result["clauses_json"]}
assert "POLICY_DELAY_PENALTY" not in codes
def test_solo_policy_marks_ocr_delivery_date_for_confirmation_not_high_risk():
"""交期数字受 OCR 污染时应进入待确认,不能计入高风险。"""
text = "交货期限:乙方应于2026年⊥月⒛日前交货。"
result = analyze.analyze_solo(text, rules=[])
item = next(row for row in result["clauses_json"] if row["clause_no"] == "POLICY_DELIVERY_DEADLINE")
assert item["validation_status"] == "needs_review"
assert result["high_risk_count"] == 3
def test_compound_payment_rule_requires_acceptance_and_invoice():
"""付款组合规则不能因仅出现“付款”一词就判定通过。"""
rule = {
"code": "payment_acceptance_required",
"title": "付款需绑定验收与发票",
"clause_category": "payment",
"keywords": ["付款", "验收", "发票"],
"trigger_type": "keyword_missing",
"risk_level": "high",
}
assert analyze._triggered(rule, "合同约定签约后立即付款。") is True
assert analyze._triggered(rule, "货到并验收合格,收到发票后付款。") is False
def test_custom_rule_categories_are_limited_to_supported_result_groups():
"""自定义规则只能使用受支持分类,避免自由文本破坏风险聚合和策略去重。"""
# 关键断言:标准分类可通过;未知分类必须在保存前被拒绝。
assert rule_service._validate_clause_category("PAYMENT") == "payment"
try:
rule_service._validate_clause_category("free_text_category")
except ValidationError:
pass
else:
raise AssertionError("未知条款分类必须被拒绝")
def test_builtin_rule_codes_are_reserved_for_compound_procurement_checks():
"""内置编码不能被自定义规则复用,避免关键词配置意外改写付款等组合判断。"""
# 关键断言:前端不传 code 创建自定义规则;若旧客户端传入内置编码,服务端必须拒绝。
assert "payment_acceptance_required" in rule_service.BUILTIN_RULE_CODES
def test_structure_contract_clauses_uses_heading_and_parent_category():
"""交货和保固子条款应继承父级主题,不被正文中的付款或验收词抢占。"""
clauses = analyze.structure_contract_clauses(
"四、交货\n1.交货期限为30日,买方未付款时顺延。\n九、保固\n1.整机保固从验收合格日起12个月。"
)
delivery = next(row for row in clauses if "交货期限" in row["text"])
warranty = next(row for row in clauses if "整机保固" in row["text"])
assert delivery["category"] == "delivery"
assert warranty["category"] == "warranty"
def test_compare_keeps_multiple_distinct_payment_changes():
"""同一付款类别的预付款比例和付款期限变化必须分别保留。"""
result = analyze.analyze_compare(
"付款期限:验收后30日支付。\n预付款:签约后支付30%。",
"付款期限:验收后90日支付。\n预付款:签约后支付50%。",
rules=[],
)
assert result["total_change_count"] == 2
@@ -0,0 +1,100 @@
"""
backend/tests/services/procurement_contract/test_artifact_archive.py
用途:验证采购合同审核产物的 MinIO 私有归档、manifest 提交和按需恢复。
依赖:procurement_contract.artifact_archive、Flask 最小应用。
逻辑:以内存 MinIO 替身覆盖上传和下载,确保只有完整 manifest 才能恢复文件,归档后本地可安全清理。
"""
import io
from pathlib import Path
from types import SimpleNamespace
from flask import Flask
from app.services.procurement_contract import artifact_archive
class _MemoryResponse:
"""模拟 MinIO 读取响应,兼容 close/release_conn 生命周期。"""
def __init__(self, data: bytes):
self._stream = io.BytesIO(data)
def read(self) -> bytes:
return self._stream.read()
def close(self) -> None:
self._stream.close()
def release_conn(self) -> None:
return None
class _MemoryMinio:
"""最小私有对象存储替身,记录 bucket、对象与最终 manifest 写入顺序。"""
def __init__(self):
self.buckets: set[str] = set()
self.objects: dict[tuple[str, str], bytes] = {}
self.put_keys: list[str] = []
def bucket_exists(self, bucket: str) -> bool:
return bucket in self.buckets
def make_bucket(self, bucket: str) -> None:
self.buckets.add(bucket)
def put_object(self, bucket, key, stream, length, content_type):
self.objects[(bucket, key)] = stream.read(length)
self.put_keys.append(key)
def get_object(self, bucket: str, key: str) -> _MemoryResponse:
return _MemoryResponse(self.objects[(bucket, key)])
def _archive_app() -> Flask:
"""提供合同归档开关和独立存储目录。"""
app = Flask(__name__)
app.config.update(
PROCUREMENT_CONTRACT_STORAGE_ROOT="unused-in-unit-test",
PROCUREMENT_CONTRACT_ARCHIVE_ENABLED=True,
PROCUREMENT_CONTRACT_ARCHIVE_BUCKET="procurement-contract",
PROCUREMENT_CONTRACT_ARCHIVE_CLEANUP_LOCAL=True,
MINIO_ENDPOINT="minio:9000",
MINIO_ACCESS_KEY="test",
MINIO_SECRET_KEY="test",
MINIO_SECURE=False,
)
return app
def test_archive_uploads_all_files_then_manifest_and_restores_missing_file(monkeypatch):
"""归档必须先上传文件后提交 manifest,恢复时校验 checksum。"""
review_no = "CR-TEST-ARCHIVE"
document_data = "付款条件:验收后30日付款。".encode("utf-8")
result_data = b'{"total_change_count": 0}'
document = SimpleNamespace(
relative_to=lambda _root: Path("cleaned/contract/document.md"),
read_bytes=lambda: document_data,
is_file=lambda: True,
name="document.md",
)
result = SimpleNamespace(
relative_to=lambda _root: Path("result/merged_result.json"),
read_bytes=lambda: result_data,
is_file=lambda: True,
name="merged_result.json",
)
root = SimpleNamespace(is_dir=lambda: True, rglob=lambda _pattern: [document, result])
storage = _MemoryMinio()
monkeypatch.setattr(artifact_archive, "_archive_client", lambda: storage)
monkeypatch.setattr(artifact_archive, "_review_root", lambda _review_no: root)
with _archive_app().app_context():
meta = artifact_archive.archive_review_artifacts(review_no)
# 关键断言:manifest 最后写入,只有它代表完整可恢复归档。
assert storage.put_keys[-1].endswith("/_manifest.json")
assert meta["status"] == "archived"
assert storage.objects[("procurement-contract", f"reviews/{review_no}/cleaned/contract/document.md")] == document_data
@@ -0,0 +1,126 @@
"""
backend/tests/services/procurement_contract/test_comparison_regions.py
Purpose: Verify comparison-region validation, partitioning, metadata extraction, and attachment summaries.
Dependencies: procurement_contract.comparison_regions pure helpers.
Flow: Tests model the V4 body/signature/attachment sequence without database or external converters.
"""
import pytest
from app.core.errors import ValidationError
from app.services.procurement_contract import comparison_regions
def _config():
"""Return an isolated V4 config for mutation-safe tests."""
return comparison_regions.default_comparison_region_config()
def test_validate_rejects_unknown_attachment_policy():
"""An unknown attachment policy must use the unified validation error contract."""
config = _config()
config["attachment_policy"] = "content_diff"
with pytest.raises(ValidationError) as exc_info:
comparison_regions.validate_comparison_region_config(config)
# The assertion protects the stable business error code exposed by Admin API.
assert exc_info.value.code == "PROCUREMENT_CONTRACT.INVALID_COMPARISON_REGION_CONFIG"
def test_partition_excludes_header_signature_and_attachment_content():
"""Only substantive body text remains after a successful V4 partition."""
pages = [
"设备买卖合同\n版本:04\n合同号:A-001\n买方:和信公司\n卖方:供应商甲\n兹因甲方向乙方购买设备\n第一条 价格不变。",
"第二条 交货期为30日。\n本合同一式两份,由双方各持一份。",
"甲方:和信公司 乙方:供应商甲\n盖章\n签署日期:2026年7月24日",
"性能需求表\n设备配置内容不参与审核",
]
text = "\n".join(pages)
partition = comparison_regions.partition_document(text, pages, _config())
# Body changes remain reviewable, while seal and attachment text are outside the body scope.
assert partition is not None
assert "交货期为30日" in partition.body
assert "盖章" not in partition.body
assert "设备配置内容" not in partition.body
assert partition.attachment_pages == 1
assert partition.metadata["contract_no"] == "A-001"
assert partition.metadata["seller"] == "供应商甲"
def test_partition_requires_both_body_anchors_for_safe_fallback():
"""Missing end anchors must return None rather than silently truncating clauses."""
pages = ["合同号:A-001\n兹因甲方向乙方购买设备\n第一条 价格不变。"]
partition = comparison_regions.partition_document(pages[0], pages, _config())
# None is the explicit signal for review_service to call the legacy full-document diff.
assert partition is None
def test_diagnose_partition_reports_missing_page_text_for_scanned_contract():
"""A scan with OCR body text but no page text must identify the pagination prerequisite."""
text = (
"合同号:A-001\n兹因甲方向乙方购买设备\n第一条 价格不变。\n"
"本合同一式两份。\n甲方:和信公司\n盖章"
)
diagnostic = comparison_regions.diagnose_partition(text, ["", ""], _config())
# The reason distinguishes scan pagination loss from a configuration or anchor mismatch.
assert diagnostic["page_text_available"] is False
assert diagnostic["body_start_anchor"] == "兹因甲方向乙方购买设备"
assert diagnostic["body_end_anchor"] == "本合同一式两份"
assert diagnostic["fallback_reason"] == "page_text_unavailable"
def test_attachment_comparison_reports_pages_only():
"""Attachment summaries contain counts and never expose attachment content."""
result = comparison_regions.build_attachment_comparison(0, 2)
# Added pages are informational and do not have any clause/evidence payload.
assert result == {
"status": "added",
"original_pages": 0,
"returned_pages": 2,
"added_pages": 2,
"removed_pages": 0,
}
def test_same_attachment_page_count_ignores_content_changes():
"""Different attachment text is intentionally irrelevant when physical page counts match."""
result = comparison_regions.build_attachment_comparison(1, 1)
# No content field exists and equal page counts produce an unchanged informational summary.
assert result["status"] == "unchanged"
assert result["added_pages"] == 0
assert result["removed_pages"] == 0
def test_missing_signature_terms_forces_safe_fallback():
"""A body-end phrase alone cannot justify dropping all following text without a signature signal."""
pages = [
"合同号:A-001\n买方:和信公司\n卖方:供应商甲\n兹因甲方向乙方购买设备\n第一条 价格不变。",
"第二条 交货期为30日。\n本合同一式两份,由双方各持一份。\n补充履约条款仍应审核。",
]
partition = comparison_regions.partition_document("\n".join(pages), pages, _config())
# None ensures the supplemental substantive clause remains in the legacy full-document comparison.
assert partition is None
def test_metadata_comparison_is_structured_not_clause_diff():
"""Header changes receive field statuses outside the clause schema."""
result = comparison_regions.build_metadata_comparison(
{"contract_no": "A-001", "seller": "供应商甲"},
{"contract_no": "A-002", "seller": "供应商甲"},
)
# Only the changed contract number is marked changed; unchanged parties stay visible for reference.
assert result["contract_no"]["status"] == "changed"
assert result["seller"]["status"] == "unchanged"
@@ -0,0 +1,181 @@
"""
tests/services/procurement_contract/test_llm_enhancer.py
用途:采购合同 Dify 新风险结果的证据校验、风险升级和待确认状态断言。
依赖:procurement_contract.llm_enhancer。
逻辑:直接测试纯合并函数,不访问数据库或真实 Dify,锁住结果治理契约。
"""
from app.services.procurement_contract import llm_enhancer
def _base_result() -> dict:
"""构造一个已有中风险规则发现的最小确定性结果。"""
return {
"summary_json": {"mode": "solo"},
"clauses_json": [
{
"clause_no": "RULE-1",
"title": "付款期限",
"risk_level": "medium",
"detail": "付款条件需要确认",
}
],
}
def test_merge_review_output_validates_evidence_and_escalates_existing_risk():
"""有效原文证据应成为 confirmed,新模型等级可提高但不能降低已有风险。"""
result = llm_enhancer._merge_review_output(
_base_result(),
{
"RULE-1": {
"llm_reason": "付款前置条件不足",
"llm_model_risk_level": "high",
"llm_confidence": 0.9,
}
},
[
{
"clause_id": "clause-0001",
"clause_no": "第八条",
"title": "默示验收",
"risk_level": "high",
"professional_reason": "沉默被视为验收合格",
"evidence": "三日内未提出异议视为验收合格",
"confidence": 0.88,
}
],
clean_text="第八条 三日内未提出异议视为验收合格。",
structured_clauses=[
{
"clause_id": "clause-0001",
"clause_no": "第八条",
"category": "acceptance",
"text": "第八条 三日内未提出异议视为验收合格。",
}
],
)
# 断言:已有规则风险只升不降;新风险证据和条款均有效。
assert result["clauses_json"][0]["risk_level"] == "high"
assert result["clauses_json"][1]["validation_status"] == "confirmed"
def test_merge_review_output_marks_missing_evidence_for_review():
"""模型引用不存在的证据时不得标成已确认结论。"""
result = llm_enhancer._merge_review_output(
_base_result(),
{},
[
{
"clause_no": "第八条",
"title": "不存在的免责内容",
"risk_level": "high",
"professional_reason": "模型候选风险",
"evidence": "供应商不承担任何责任",
}
],
clean_text="第八条 双方应按约履行。",
structured_clauses=[
{
"clause_id": "clause-0001",
"clause_no": "第八条",
"category": "liability",
"text": "第八条 双方应按约履行。",
}
],
)
# 断言:条款编号存在但证据不在原文中,必须进入待确认状态。
assert result["clauses_json"][1]["validation_status"] == "needs_review"
assert result["summary_json"]["llm_new_findings"]["needs_review"] == 1
def test_needs_review_llm_finding_is_excluded_from_risk_counts():
"""证据未验证的模型候选项只能进入待确认,不得污染高中低风险统计。"""
from app.services.procurement_contract import analyze
result = llm_enhancer._merge_review_output(
{"summary_json": {"mode": "solo"}, "clauses_json": []},
{},
[{
"clause_id": "clause-0001",
"title": "待确认风险",
"risk_level": "high",
"evidence": "不存在的原文",
}],
clean_text="第一条 双方应按约履行。",
structured_clauses=[{
"clause_id": "clause-0001",
"clause_no": "第一条",
"category": "other",
"text": "第一条 双方应按约履行。",
}],
)
rebuilt = analyze.rebuild_result(result)
assert rebuilt["clauses_json"][0]["validation_status"] == "needs_review"
assert rebuilt["high_risk_count"] == 0
def test_llm_can_reject_deterministic_false_positive_with_verified_evidence():
"""模型仅在真实原文和高置信度同时满足时,才可撤销确定性误报。"""
result = llm_enhancer._merge_review_output(
_base_result(),
{
"RULE-1": {
"llm_decision": "reject",
"llm_evidence": "验收合格并收到发票后90日付款",
"llm_reason": "原文已明确付款前置条件",
"llm_confidence": 0.92,
"llm_model_risk_level": "ok",
}
},
[],
clean_text="付款条款:验收合格并收到发票后90日付款。",
structured_clauses=[],
)
assert result["clauses_json"][0]["risk_level"] == "ok"
assert result["clauses_json"][0]["validation_status"] == "confirmed"
def test_llm_cannot_reject_finding_without_verified_evidence():
"""证据不在合同原文时,reject 不能降低已有确定性风险。"""
result = llm_enhancer._merge_review_output(
_base_result(),
{
"RULE-1": {
"llm_decision": "reject",
"llm_evidence": "不存在的付款原文",
"llm_confidence": 0.99,
"llm_model_risk_level": "ok",
}
},
[],
clean_text="付款条款需要双方确认。",
structured_clauses=[],
)
assert result["clauses_json"][0]["risk_level"] == "medium"
def test_chatflow_provider_override_takes_priority_over_agent_app_type(monkeypatch):
"""复用Chatflow时环境变量应覆盖HXOPS Agent页面的Workflow类型。"""
class FakeAgent:
dify_app_type = "workflow"
monkeypatch.setattr(llm_enhancer.Config, "PROCUREMENT_CONTRACT_LLM_PROVIDER", "chatflow")
# 断言:无需把原会话Chatflow改为Workflow,合同后台调用也会走chat-messages。
assert llm_enhancer._review_provider(FakeAgent()) == "chatflow"
def test_chatflow_answer_json_uses_same_review_output_contract():
"""Chatflow最终Answer中的JSON应被解析成已有项增强和独立风险。"""
enhancements, new_items = llm_enhancer._extract_review_output(
{
"answer": (
'{"items":[{"id":"RULE-1","professional_reason":"付款风险"}],'
'"new_items":[{"id":"llm-1","title":"免责条款"}]}'
)
}
)
# 断言:Chatflow与Workflow只在传输层不同,最终结构化审核协议保持一致。
assert enhancements["RULE-1"]["llm_reason"] == "付款风险"
assert new_items[0]["title"] == "免责条款"
@@ -0,0 +1,121 @@
"""
tests/services/procurement_contract/test_pdf_annotation.py
用途:验证采购合同 PDF 证据锚定、坐标字段和高亮批注输出。
依赖:procurement_contract.pdf_annotation、pypdfium2、pypdf。
逻辑:覆盖文本型 PDF 精确高亮,以及扫描 PDF 按 OCR 分页正文添加页级批注意见。
"""
from __future__ import annotations
import io
from pypdf import PdfReader, PdfWriter
from pypdf.generic import DictionaryObject, DecodedStreamObject, NameObject
from app.services.procurement_contract import pdf_annotation
def _sample_pdf_bytes() -> bytes:
"""用 PDF 标准 Helvetica 字体生成带可搜索文本层的单页测试 PDF。"""
writer = PdfWriter()
page = writer.add_blank_page(width=595, height=842)
font = DictionaryObject(
{
NameObject("/Type"): NameObject("/Font"),
NameObject("/Subtype"): NameObject("/Type1"),
NameObject("/BaseFont"): NameObject("/Helvetica"),
}
)
font_ref = writer._add_object(font)
page[NameObject("/Resources")] = DictionaryObject(
{NameObject("/Font"): DictionaryObject({NameObject("/F1"): font_ref})}
)
stream = DecodedStreamObject()
stream.set_data(b"BT /F1 14 Tf 72 720 Td (Seller delay penalty is 5 per mille per day.) Tj ET")
page[NameObject("/Contents")] = writer._add_object(stream)
buffer = io.BytesIO()
writer.write(buffer)
return buffer.getvalue()
def test_anchor_and_annotate_pdf_contract_evidence():
"""锚定命中后必须返回第一页坐标,并生成至少一个标准 PDF 高亮批注。"""
pdf_bytes = _sample_pdf_bytes()
item = {
"title": "Delay penalty",
"risk_level": "high",
"detail": "Penalty is below policy baseline.",
"evidence": "Seller delay penalty is 5 per mille per day.",
}
anchor = pdf_annotation.locate_pdf_evidence(pdf_bytes, item)
# 断言:原文证据被定位到第一页,且坐标可以直接供 PDF Highlight 使用。
assert anchor is not None
assert anchor["page_no"] == 1
assert anchor["rects"]
assert anchor["confidence"] >= 0.82
item["evidence_anchor"] = anchor
annotated = pdf_annotation.build_annotated_pdf_bytes(pdf_bytes, [item])
reader = PdfReader(io.BytesIO(annotated))
assert len(reader.pages[0].get("/Annots", [])) >= 1
def test_enrich_result_marks_non_pdf_as_unsupported():
"""Word 合同不支持 PDF 坐标时只写状态,不影响审核结果。"""
result = {"summary_json": {}, "clauses_json": [{"risk_level": "high", "evidence": "sample"}]}
enriched = pdf_annotation.enrich_result_with_pdf_anchors(
result,
filename="contract.docx",
pdf_bytes=b"not-a-pdf",
)
assert enriched["summary_json"]["evidence_anchoring"]["status"] == "unsupported"
def test_annotate_scanned_pdf_from_ocr_page_text():
"""扫描 PDF 无文本坐标时,应按 page-image OCR 文本命中页码并添加页级批注。"""
pdf_bytes = _sample_pdf_bytes()
item = {
"title": "Delivery deadline",
"risk_level": "high",
"detail": "Deadline needs confirmation.",
"evidence": "Seller shall deliver before 2026-08-20.",
}
clean_text = (
"![page-image-1]\nOther clauses.\n"
"![page-image-2]\nSeller shall deliver before 2026-08-20.\n"
)
anchor = pdf_annotation.locate_ocr_evidence_page(clean_text, item)
assert anchor is not None
assert anchor["page_no"] == 2
assert anchor["rects"] == []
assert anchor["method"] == "ocr_page"
writer = PdfWriter()
writer.add_blank_page(width=595, height=842)
writer.add_blank_page(width=595, height=842)
buffer = io.BytesIO()
writer.write(buffer)
annotated = pdf_annotation.build_annotated_pdf_bytes(
buffer.getvalue(),
[item],
clean_text=clean_text,
)
reader = PdfReader(io.BytesIO(annotated))
assert not reader.pages[0].get("/Annots", [])
assert len(reader.pages[1].get("/Annots", [])) >= 1
def test_annotate_returns_original_pdf_when_no_finding_can_be_anchored():
"""没有可定位证据时下载仍应成功,返回未加批注的合同副本。"""
pdf_bytes = _sample_pdf_bytes()
annotated = pdf_annotation.build_annotated_pdf_bytes(
pdf_bytes,
[{"title": "Unanchored", "risk_level": "medium", "new_text": "合同中不存在的文字"}],
)
reader = PdfReader(io.BytesIO(annotated))
# 关键断言:原页保留,且没有凭空生成批注。
assert len(reader.pages) == 1
assert not reader.pages[0].get("/Annots", [])
@@ -0,0 +1,146 @@
"""
backend/tests/services/procurement_contract/test_preprocessing.py
用途:验证采购合同调用 MinerU 的请求协议、Markdown 读取与故障回退前提。
依赖:procurement_contract.preprocessing、Flask 最小应用上下文。
逻辑:模拟测试环境 MinerU 的 `/file_parse` 返回,确保 PDF 解析产物可审计且不依赖服务端文件名。
"""
from io import BytesIO
from pathlib import Path
import pytest
from flask import Flask
from app.services.procurement_contract import preprocessing
class _MineruResponse:
"""模拟 requests.Response,仅暴露 MinerU 客户端需要的状态和 JSON 接口。"""
def __init__(self, payload: dict):
self.payload = payload
def raise_for_status(self) -> None:
return None
def json(self) -> dict:
return self.payload
class _SourcePdf:
"""模拟待上传的 PDF,避免测试依赖受限的本机临时目录。"""
name = "seller.pdf"
def open(self, mode: str):
assert mode == "rb"
class _Handle(BytesIO):
def __enter__(self):
return self
def __exit__(self, exc_type, exc, tb):
self.close()
return False
return _Handle(b"%PDF-1.4 test")
class _Artifact:
"""保存 MinerU 审计产物的内存替身。"""
def __init__(self, store: dict[str, str], name: str):
self.store = store
self.name = name
def write_text(self, content: str, *, encoding: str) -> None:
assert encoding == "utf-8"
self.store[self.name] = content
class _OutputDir:
"""模拟清洗目录,仅记录 MinerU 产生的 JSON 与 Markdown。"""
def __init__(self):
self.files: dict[str, str] = {}
def __truediv__(self, name: str) -> _Artifact:
return _Artifact(self.files, name)
def _mineru_app() -> Flask:
"""构造最小配置,隔离 MinerU 单元测试的文件输出目录。"""
app = Flask(__name__)
app.config.update(
PROCUREMENT_CONTRACT_MINERU_API_URL="http://host.docker.internal:8100",
PROCUREMENT_CONTRACT_MINERU_BACKEND="pipeline",
PROCUREMENT_CONTRACT_MINERU_PARSE_METHOD="auto",
PROCUREMENT_CONTRACT_MINERU_CONNECT_TIMEOUT_SECONDS=5,
PROCUREMENT_CONTRACT_MINERU_READ_TIMEOUT_SECONDS=300,
)
return app
def test_mineru_parse_pdf_reads_markdown_and_persists_response(monkeypatch):
"""MinerU 成功时必须使用 files 字段,并保存原始响应供问题追溯。"""
seen: dict = {}
def fake_post(url, *, data, files, timeout):
seen.update({"url": url, "data": data, "files": files, "timeout": timeout})
return _MineruResponse(
{
"status": "completed",
"backend": "pipeline",
"version": "3.1.14",
"results": {"seller": {"md_content": "## 三、付款方式\n\n预付款为30%。"}},
}
)
monkeypatch.setattr(preprocessing.requests, "post", fake_post)
source = _SourcePdf()
output = _OutputDir()
with _mineru_app().app_context():
markdown, meta = preprocessing._mineru_parse_pdf(source, output)
# 关键断言:协议与测试环境 OpenAPI 一致,单文件结果不依赖 results 的文件名键。
assert markdown == "## 三、付款方式\n\n预付款为30%。"
assert seen["url"] == "http://host.docker.internal:8100/file_parse"
assert seen["data"]["lang_list"] == "ch"
assert seen["data"]["backend"] == "pipeline"
assert seen["files"][0][0] == "files"
assert meta == {
"provider": "mineru",
"backend": "pipeline",
"version": "3.1.14",
"parse_method": "auto",
"result_artifact": "mineru_result.json",
}
assert output.files["mineru_document.md"] == markdown
assert '"status": "completed"' in output.files["mineru_result.json"]
def test_mineru_parse_pdf_rejects_incomplete_task_result(monkeypatch):
"""MinerU 未完成或未返回 Markdown 时必须抛错,调用方才能安全回退旧解析器。"""
monkeypatch.setattr(
preprocessing.requests,
"post",
lambda *args, **kwargs: _MineruResponse({"status": "failed", "error": "model unavailable"}),
)
with _mineru_app().app_context(), pytest.raises(RuntimeError, match="did not complete"):
preprocessing._mineru_parse_pdf(_SourcePdf(), _OutputDir())
def test_extract_page_texts_uses_mineru_logical_page_when_pdf_has_no_text_layer(monkeypatch):
"""Readable MinerU OCR must still let comparison regions find body anchors on scanned PDFs."""
monkeypatch.setattr(preprocessing, "_extract_pdf_page_texts", lambda _path: ["", ""])
pages, warning = preprocessing._extract_page_texts(
Path("seller.pdf"),
_OutputDir(),
"兹因甲方向乙方购买设备\n第一条 价格不变。\n本合同一式两份。\n甲方:和信公司",
)
# The logical page is only an anchor fallback; physical attachment page counts remain unavailable.
assert pages == ["兹因甲方向乙方购买设备\n第一条 价格不变。\n本合同一式两份。\n甲方:和信公司"]
assert warning == "PDF native page text unavailable; used MinerU logical page for body boundaries"
@@ -0,0 +1,22 @@
"""
tests/services/procurement_contract/test_review_service.py
用途:验证采购合同审核创建阶段的文件输入门禁。
依赖:review_service、ValidationError。
逻辑:在访问文件资产或数据库前,确保比对模式必须显式提供我方原合同,禁止回退默认模板。
"""
import pytest
from app.core.errors import ValidationError
from app.services.procurement_contract import review_service
def test_compare_review_requires_uploaded_original_contract():
"""比对模式缺少我方原合同时应立即拒绝,防止静默使用库内默认模板。"""
with pytest.raises(ValidationError, match="original_contract_asset_no is required"):
review_service.start_review(
user_id=1,
review_mode="compare",
contract_asset_no="FA-SELLER-RETURN",
)
@@ -118,6 +118,51 @@ def test_local_assistant_message_query_does_not_duplicate_user_bubble(client):
assert msgs[-1]['content'] == '已确认,进入下一步。'
def test_local_typed_assistant_message_keeps_query_for_user_bubble_and_title(client):
"""结构化结果卡须保留 query:刷新后回放用户提问,会话标题用提问而非 headline。"""
headers = get_headers(client)
user_question = '请对《邦达激光合同.pdf》进行模板比对'
headline = '模板比对完成:高 1 / 中 0 / 低 0,共 1 处变更'
save_res = client.post('/api/chat/messages/local?agent_id=1', headers=headers, json={
'conversation_id': 'conv-contract-review',
'role': 'assistant',
'type': 'procurement-contract-review',
'content': headline,
'query': user_question,
'payload': {
'review_no': 'CR-TEST-001',
'contract_file_name': '邦达激光合同.pdf',
'high_risk_count': 1,
'medium_risk_count': 0,
'low_risk_count': 0,
},
})
assert save_res.status_code == 200
# 断言:历史回放含用户气泡 + 结果卡
msg_res = client.get(
'/api/chat/messages?conversation_id=conv-contract-review&agent_id=1',
headers=headers,
)
assert msg_res.status_code == 200
msgs = msg_res.get_json()
assert len(msgs) >= 2
assert msgs[0]['role'] == 'user'
assert msgs[0]['content'] == user_question
assert msgs[-1]['role'] == 'assistant'
assert msgs[-1]['type'] == 'procurement-contract-review'
# 断言:侧栏标题取用户提问,而非审查 headline
sessions_res = client.get('/api/chat/sessions?agent_id=1', headers=headers)
assert sessions_res.status_code == 200
sessions = sessions_res.get_json()
target = next((s for s in sessions if s['conversation_id'] == 'conv-contract-review'), None)
assert target is not None
assert target['title'].startswith('请对《邦达激光合同.pdf》')
assert '模板比对完成' not in target['title']
def test_chat_sessions_keep_latest_non_empty_query_as_title(client):
headers = get_headers(client)
+2 -2
View File
@@ -3,7 +3,7 @@ backend/worker.py
用途:统一后台 worker 入口(方案 D)。
依赖:app.create_app、app.jobs.runner、app.jobs.handlers。
逻辑:--queues kb,shipping;Wave 2 经 jobs.runner 统一 poll → dispatch。
逻辑:--queues kb,shipping,contract;经 jobs.runner 统一 poll → dispatch。
"""
from __future__ import annotations
@@ -80,7 +80,7 @@ def main(*, queues: list[str] | None = None, config_name: str | None = None) ->
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='HXOPS unified background worker')
parser.add_argument('--queues', default='kb', help='Comma-separated queue names (kb, shipping)')
parser.add_argument('--queues', default='kb', help='Comma-separated queue names (kb, shipping, contract)')
parser.add_argument('--config', default=None, dest='config_name', help='Flask config name (optional)')
args = parser.parse_args()
queue_list = [q.strip() for q in args.queues.split(',') if q.strip()]
+5 -3
View File
@@ -2,7 +2,7 @@
backend/worker_kb.py
用途:知识库 worker 部署兼容入口(Compose / Supervisor 沿用此路径)。
逻辑:Wave 2 转调 worker.py,默认 --queues kb;保留多进程并发配置。
逻辑:转调 worker.py;第一个进程消费 kb+contract,其余进程仅消费 kb,避免合同 Word 清洗并发争用。
"""
from __future__ import annotations
@@ -14,9 +14,11 @@ from worker import _configure_logging, _resolve_config_name, main
def _worker_loop(worker_index: int) -> None:
"""启动一个兼容 Worker;仅首进程额外消费合同审核任务。"""
log = _configure_logging(str(worker_index))
log.info('kb-worker process started index=%s', worker_index)
main(queues=['kb'], config_name=_resolve_config_name())
queues = ['kb', 'contract'] if worker_index == 1 else ['kb']
main(queues=queues, config_name=_resolve_config_name())
def main_kb() -> None:
@@ -25,7 +27,7 @@ def main_kb() -> None:
concurrency = max(int(bootstrap_app.config.get('KB_WORKER_CONCURRENCY', 1) or 1), 1)
if concurrency == 1:
main(queues=['kb'], config_name=_resolve_config_name())
main(queues=['kb', 'contract'], config_name=_resolve_config_name())
return
log = _configure_logging('master')