feat(contract): 采购合同对比agent
Signed-off-by: sophie <sophie> Signed-off-by: sophie <sophie>
This commit is contained in:
1 parent
ffccf19ba2
commit
0503ff76a6
90 files changed
+16729
-1344
No files matched your search
@@ -41,6 +41,16 @@ DEFAULT_ADMIN_USERNAME=admin
|
||||
DEFAULT_ADMIN_PASSWORD=admin123456
|
||||
TASK_EXECUTION_MODE=sync
|
||||
|
||||
# 采购合同全面审核 Dify Chatflow:开发环境已绑定 HXOPS Agent #17。
|
||||
# Agent 内保存 API Key,勿在本文件重复写入;修改 Agent 后需重启后端和 hxops-kb-worker。
|
||||
PROCUREMENT_CONTRACT_LLM_ENABLED=true
|
||||
# 先复用现有采购合同审查 Chatflow;不受 HXOPS Agent 页面 Dify 应用类型字段影响。
|
||||
PROCUREMENT_CONTRACT_LLM_PROVIDER=chatflow
|
||||
PROCUREMENT_CONTRACT_LLM_AGENT_ID=17
|
||||
PROCUREMENT_CONTRACT_LLM_DIFY_APP_ID=
|
||||
PROCUREMENT_CONTRACT_LLM_DIFY_API_KEY=
|
||||
PROCUREMENT_CONTRACT_LLM_DIFY_BASE=http://192.168.100.192:8882/v1
|
||||
|
||||
# Gunicorn配置
|
||||
GUNICORN_WORKERS=10
|
||||
|
||||
|
||||
@@ -43,6 +43,15 @@ DEFAULT_ADMIN_USERNAME=admin
|
||||
DEFAULT_ADMIN_PASSWORD=admin123456
|
||||
TASK_EXECUTION_MODE=rq
|
||||
|
||||
# 采购合同全面审核 Dify Chatflow:正式密钥仅填在本机/Jenkins密文变量,勿写入共享文件。
|
||||
# 先在 test 验证输出质量后再把 ENABLED 改为 true。
|
||||
PROCUREMENT_CONTRACT_LLM_ENABLED=false
|
||||
PROCUREMENT_CONTRACT_LLM_PROVIDER=chatflow
|
||||
PROCUREMENT_CONTRACT_LLM_AGENT_ID=
|
||||
PROCUREMENT_CONTRACT_LLM_DIFY_APP_ID=
|
||||
PROCUREMENT_CONTRACT_LLM_DIFY_API_KEY=
|
||||
PROCUREMENT_CONTRACT_LLM_DIFY_BASE=http://192.168.100.230:8882/v1
|
||||
|
||||
# Gunicorn配置
|
||||
GUNICORN_WORKERS=20
|
||||
|
||||
|
||||
+11
@@ -34,6 +34,17 @@ EDKB_WORD_FILE_TIMEOUT_SEC=420
|
||||
# running 任务回收阈值,须大于 EDKB_SOFFICE_TIMEOUT_SEC 及整条清洗链路耗时
|
||||
KB_JOB_RUNNING_TIMEOUT_SECONDS=900
|
||||
|
||||
# 采购合同全面审核:三环境一致的异步任务与输入保护参数
|
||||
# 清洗产物目录由各环境相对 backend/ 根目录解析;容器部署可由 Compose 覆盖为 /app/data/procurement_contract
|
||||
PROCUREMENT_CONTRACT_STORAGE_ROOT=data/procurement_contract
|
||||
# 须覆盖清洗、条款结构化和一次 Dify Chatflow 调用;超时后任务可自动重试
|
||||
PROCUREMENT_CONTRACT_JOB_TIMEOUT_SECONDS=600
|
||||
PROCUREMENT_CONTRACT_LLM_CONNECT_TIMEOUT_SECONDS=5
|
||||
PROCUREMENT_CONTRACT_LLM_READ_TIMEOUT_SECONDS=120
|
||||
# 中短合同的单次全面审核上限;达到上限时后端标记 bounded_contract,不宣称全文覆盖
|
||||
PROCUREMENT_CONTRACT_LLM_MAX_TEXT_CHARS=120000
|
||||
PROCUREMENT_CONTRACT_LLM_MAX_CLAUSES=160
|
||||
|
||||
# chat回答的评分与评论
|
||||
FEEDBACK_ENABLED=true
|
||||
|
||||
|
||||
@@ -43,6 +43,24 @@ DEFAULT_ADMIN_USERNAME=admin
|
||||
DEFAULT_ADMIN_PASSWORD=admin123456
|
||||
TASK_EXECUTION_MODE=rq
|
||||
|
||||
# 采购合同全面审核 Dify Chatflow:填入测试 Agent 后再开启。
|
||||
PROCUREMENT_CONTRACT_LLM_ENABLED=false
|
||||
PROCUREMENT_CONTRACT_LLM_PROVIDER=chatflow
|
||||
PROCUREMENT_CONTRACT_LLM_AGENT_ID=
|
||||
PROCUREMENT_CONTRACT_LLM_DIFY_APP_ID=
|
||||
PROCUREMENT_CONTRACT_LLM_DIFY_API_KEY=
|
||||
PROCUREMENT_CONTRACT_LLM_DIFY_BASE=http://192.168.100.192:8882/v1
|
||||
# 测试服务器本机 MinerU API;后端和 Worker 容器经 host-gateway 访问宿主机 8100。
|
||||
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
|
||||
# 合同产物(源文件副本、MinerU 结果、清洗正文、条款和报告)归档至独立私有桶;成功后删除本地缓存。
|
||||
PROCUREMENT_CONTRACT_ARCHIVE_ENABLED=true
|
||||
PROCUREMENT_CONTRACT_ARCHIVE_BUCKET=procurement-contract
|
||||
PROCUREMENT_CONTRACT_ARCHIVE_CLEANUP_LOCAL=true
|
||||
|
||||
# Gunicorn配置
|
||||
GUNICORN_WORKERS=6
|
||||
|
||||
|
||||
@@ -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')
|
||||
@@ -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
@@ -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))
|
||||
@@ -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'
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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'}),
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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: {}
|
||||
@@ -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
@@ -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()]
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -45,6 +45,11 @@ services:
|
||||
- KB_WORKER_POLL_SECONDS=${KB_WORKER_POLL_SECONDS:-2}
|
||||
# kb-worker 自动回收长时间 running 的任务(秒)
|
||||
- KB_JOB_RUNNING_TIMEOUT_SECONDS=${KB_JOB_RUNNING_TIMEOUT_SECONDS:-900}
|
||||
# 采购合同异步审核:清洗产物与任务/模型输入保护
|
||||
- PROCUREMENT_CONTRACT_STORAGE_ROOT=${PROCUREMENT_CONTRACT_STORAGE_ROOT:-/app/data/procurement_contract}
|
||||
- PROCUREMENT_CONTRACT_JOB_TIMEOUT_SECONDS=${PROCUREMENT_CONTRACT_JOB_TIMEOUT_SECONDS:-600}
|
||||
- PROCUREMENT_CONTRACT_LLM_MAX_TEXT_CHARS=${PROCUREMENT_CONTRACT_LLM_MAX_TEXT_CHARS:-120000}
|
||||
- PROCUREMENT_CONTRACT_LLM_MAX_CLAUSES=${PROCUREMENT_CONTRACT_LLM_MAX_CLAUSES:-160}
|
||||
# LibreOffice 可执行文件路径(Linux 容器默认 /usr/bin/soffice,跳过 Windows 路径探测)
|
||||
- EDKB_SOFFICE=${EDKB_SOFFICE:-/usr/bin/soffice}
|
||||
# LibreOffice 单次格式转换超时(秒)
|
||||
@@ -102,6 +107,11 @@ services:
|
||||
- KB_WORKER_POLL_SECONDS=${KB_WORKER_POLL_SECONDS:-2}
|
||||
# kb-worker 自动回收长时间 running 的任务(秒)
|
||||
- KB_JOB_RUNNING_TIMEOUT_SECONDS=${KB_JOB_RUNNING_TIMEOUT_SECONDS:-900}
|
||||
# 采购合同异步审核:Worker 与后端必须指向同一持久化目录
|
||||
- PROCUREMENT_CONTRACT_STORAGE_ROOT=${PROCUREMENT_CONTRACT_STORAGE_ROOT:-/app/data/procurement_contract}
|
||||
- PROCUREMENT_CONTRACT_JOB_TIMEOUT_SECONDS=${PROCUREMENT_CONTRACT_JOB_TIMEOUT_SECONDS:-600}
|
||||
- PROCUREMENT_CONTRACT_LLM_MAX_TEXT_CHARS=${PROCUREMENT_CONTRACT_LLM_MAX_TEXT_CHARS:-120000}
|
||||
- PROCUREMENT_CONTRACT_LLM_MAX_CLAUSES=${PROCUREMENT_CONTRACT_LLM_MAX_CLAUSES:-160}
|
||||
# LibreOffice 可执行文件路径(Linux 容器默认 /usr/bin/soffice,跳过 Windows 路径探测)
|
||||
- EDKB_SOFFICE=${EDKB_SOFFICE:-/usr/bin/soffice}
|
||||
# LibreOffice 单次格式转换超时(秒)
|
||||
|
||||
@@ -61,3 +61,25 @@
|
||||
- 生产密钥不要放 `.env.shared`。
|
||||
- 新增变量同步更新对应 env 文件和本文档。
|
||||
- 继续清理对 `backend/.env` 的历史依赖。
|
||||
|
||||
## 7. 采购合同全面审核变量
|
||||
|
||||
采购合同审核的非敏感运行参数放在 `.env.shared`:
|
||||
|
||||
- `PROCUREMENT_CONTRACT_STORAGE_ROOT`
|
||||
- `PROCUREMENT_CONTRACT_JOB_TIMEOUT_SECONDS`
|
||||
- `PROCUREMENT_CONTRACT_LLM_CONNECT_TIMEOUT_SECONDS`
|
||||
- `PROCUREMENT_CONTRACT_LLM_READ_TIMEOUT_SECONDS`
|
||||
- `PROCUREMENT_CONTRACT_LLM_MAX_TEXT_CHARS`
|
||||
- `PROCUREMENT_CONTRACT_LLM_MAX_CLAUSES`
|
||||
|
||||
以下采购合同 Dify Chatflow 相关变量可能因环境、Agent、地址和密钥不同,必须放在 `.env.dev`、`.env.test`、`.env.prod` 或 CI/Jenkins 密文变量,禁止放入 `.env.shared`:
|
||||
|
||||
- `PROCUREMENT_CONTRACT_LLM_ENABLED`
|
||||
- `PROCUREMENT_CONTRACT_LLM_PROVIDER`
|
||||
- `PROCUREMENT_CONTRACT_LLM_AGENT_ID`
|
||||
- `PROCUREMENT_CONTRACT_LLM_DIFY_APP_ID`
|
||||
- `PROCUREMENT_CONTRACT_LLM_DIFY_API_KEY`
|
||||
- `PROCUREMENT_CONTRACT_LLM_DIFY_BASE`
|
||||
|
||||
`PROCUREMENT_CONTRACT_LLM_DIFY_API_KEY` 属于密钥;生产环境优先由 Jenkins/部署平台注入。当前优先通过 `PROCUREMENT_CONTRACT_LLM_AGENT_ID` 复用已配置的 Chatflow Agent,不在环境文件重复保存密钥。
|
||||
@@ -1,5 +1,25 @@
|
||||
# 智能HR请假管理需求
|
||||
|
||||
## 采购合同全面审核补充需求
|
||||
|
||||
> 完整可测需求(正向/异向场景、输入输出)见:[docs/features/procurement-contract/demand.md](features/procurement-contract/demand.md)。下列条目为早期补充要点,与正式需求文档一并约束。
|
||||
|
||||
- 合同比对固定上传两份文件:我方原合同与卖方回传合同;不得选择或自动回退库内默认模板。单份审核仍只上传一份待审卖方合同。
|
||||
- 模板比对须区分“已确认实质修改”和“受 OCR/表格抽取影响待确认”,空格、换行、标点、编号及高相似 OCR 噪声不得直接计为合同修改。
|
||||
- 日期、金额、比例和期限中存在圈号、错字或不确定 OCR 字形时,只能进入待确认;待确认项不得计入高中低风险统计。
|
||||
- OCR 待确认只保留会影响采购决策的关键事实,并按付款、交期、验收、质保、违约和管辖等业务主题聚合;合同抬头、普通错别字及非关键版面噪声不得逐条要求采购确认。
|
||||
- 同一条款类别下的不同事实变化必须分别保留,例如预付款比例、出货款比例和付款期限不得合并为一项。
|
||||
- 双合同对比以识别并展示真实差异为首要目标;结果卡和下载报告须逐项列出我方原文、回传内容及新增/删除/修改类型。Admin 风险规则仅提供风险等级参考,不得用单份审核规则标题、建议或沟通话术覆盖差异事实。
|
||||
- 单份卖方合同优先检查付款前置条件、明确交货期限、质保期限、采购方所在地管辖及卖方逾期交付每日合同总价 5‰ 违约金。
|
||||
- PDF 审核发现须尽量返回原文页码和坐标;文本型 PDF 下载坐标高亮副本,扫描 PDF 可依据 OCR 分页正文在对应原页添加批注意见;缺失型风险或无法定位项不得伪造文字坐标。
|
||||
- 审核结果卡顶部按“改动项、高风险、中风险、低风险”展示;正文将模板新增/删除/修改、整份合同独立风险、OCR/证据待确认项分区列出,避免把红线风险误解为卖方修改。
|
||||
- 合同审核改为后台异步任务,上传后立即返回审查编号并展示进度,避免清洗和大模型调用阻塞请求。
|
||||
- 审核进行中须始终展示完整步骤轨道(排队、提取清洗、条款识别、合同比对/风险扫描、AI 审核、结果校验、完成),后端阶段切换时同步更新当前步骤和百分比。
|
||||
- 复用知识库文件清洗能力,但待审合同不进入企业正式 Dataset;清洗正文和结构化条款由 HXOPS 传给 Dify Workflow。
|
||||
- Dify 必须独立扫描后端规则未覆盖的法律风险;HXOPS 保留模板 Diff、公司红线、证据校验、风险合并和报告落库。
|
||||
- Dify 可在引用真实合同原文且置信度达到门槛时纠正确定性误报;无有效证据时不得撤销或降低确定性风险。
|
||||
- Dify 失败时降级保留确定性结果;清洗失败时明确提示上传可解析文件。
|
||||
|
||||
## 设备维保助手补充需求
|
||||
|
||||
- 查询方式:用户通过 `设备维保助手` 会话查询设备维护/维修记录,系统支持按设备编号、设备名称、故障描述、维修说明、维修人和状态筛选记录。
|
||||
@@ -426,3 +446,10 @@
|
||||
- 聚合/非聚合由 `agents.is_aggregate` 显式配置,切回非聚合时清空成员关系。
|
||||
- 目录 Agent 本身仍配置一套聚合 Dify Chatflow;HXOPS 在发起聊天时向 Dify inputs 注入成员 Agent 元数据。
|
||||
- 本期不在 HXOPS 后端并行调用多个子 Agent,不合并多个 Dify 回答;多路召回与答案融合由聚合 Chatflow 承担。
|
||||
# 采购合同模板比对区域配置(2026-07-24)
|
||||
|
||||
- Admin 默认启用模板可维护抬头字段、正文起止锚点、签章关键词、附件起始锚点和附件页数策略。
|
||||
- Chat 合同比对仍以用户本次上传的“我方原合同”和“供应商回传合同”为实际 Diff 输入,模板库只提供区域规则。
|
||||
- 抬头字段仅用于内部区域划分和排除误报,不在 Chat 结果中展示,也不计入条款改动;正文严格比对;签章区域排除;签章后的附件仅提示新增或减少页数。
|
||||
- 附件内容不进入差异清单、改动总数或风险统计;两侧附件页数相同即不提示内容差异。
|
||||
- 无默认模板、无配置、分页提取失败或正文锚点识别失败时,安全回退全文比对并向用户展示警告。
|
||||
@@ -7,6 +7,7 @@
|
||||
| [shipping-notice](shipping-notice/README.md) | 货代发货通知 Agent | [technical.md](shipping-notice/technical.md) |
|
||||
| [file-check](file-check/README.md) | 文件检核(RoHS / MSDS 等) | [technical.md](file-check/technical.md) |
|
||||
| [fixed-assets](fixed-assets/README.md) | 固资快照同步与本地查询 | [technical.md](fixed-assets/technical.md) · [履历挂载命令](fixed-assets/history-share-mount.md) |
|
||||
| [procurement-contract](procurement-contract/README.md) | 采购合同审查 Agent(模板比对 / 单份审核) | [demand.md](procurement-contract/demand.md) · [comprehensive-review-technical.md](procurement-contract/comprehensive-review-technical.md) · [原型](../prototype/procurement-contract-review-prototype.html) |
|
||||
|
||||
**平台级**设计(跨域)见 [platform/](../platform/README.md)。
|
||||
|
||||
|
||||
@@ -1,35 +1,42 @@
|
||||
# 固资履历共享盘挂载(Linux 运维命令)
|
||||
|
||||
> 适用:Linux 宿主机 + Docker Compose 部署的 hxops-backend。
|
||||
> 已在 test 环境验证:`smbclient` 可达后,用「CIFS 挂共享根 + bind 履历子目录」方式成功。
|
||||
> **不要使用** `subdir=履历`(部分内核会报 `mount error(22): Invalid argument`)。
|
||||
> test / prod **各自**按本文在宿主机执行一次(凭据、挂载不会随代码自动同步到另一台机)。
|
||||
> 已验证方式:**CIFS 挂共享根 + `mount --bind` 履历子目录**。
|
||||
> **不要使用** `subdir=履历`(易报 `mount error(22): Invalid argument`)。
|
||||
> 首次挂载建议**不要加 `ro`**(正式环境曾出现误导性报错 `cannot mount ... read-only`)。
|
||||
|
||||
## 1. 背景
|
||||
|
||||
| 项 | 值 |
|
||||
| --- | --- |
|
||||
| Windows 源路径 | `\\192.168.100.130\设备履历记录\履历` |
|
||||
| 业务变量 | `FIXED_ASSET_HISTORY_LOCAL_ROOT`(优先于 UNC) |
|
||||
| 业务变量 | `FIXED_ASSET_HISTORY_LOCAL_ROOT`(优先于 UNC;Linux 必须配) |
|
||||
| test 本地根 | `/mnt/hxops-fixed-asset-history-test` |
|
||||
| prod 本地根 | `/mnt/hxops-fixed-asset-history-prod` |
|
||||
| 共享根挂载点 | test: `/mnt/hxops-fixed-asset-history-test-share`<br>prod: `/mnt/hxops-fixed-asset-history-prod-share` |
|
||||
| 凭据文件(每台宿主机各一份) | `/etc/smbcredentials/hxops-fixed-asset-history` |
|
||||
| 部署目录示例 | test: `~/ai/platform/hxops`<br>prod: `/data/ai-platform/hxops` |
|
||||
|
||||
挂载顺序:
|
||||
|
||||
1. CIFS 挂载共享根 `设备履历记录` → `*-share`
|
||||
2. `mount --bind` 把其中的 `履历` 挂到 `FIXED_ASSET_HISTORY_LOCAL_ROOT`
|
||||
3. 重建 `hxops-backend`,使容器内能看到该目录
|
||||
1. 在本机创建 SMB 凭据文件(`chmod 600`,属主 root)
|
||||
2. `sudo smbclient` 探测共享可达
|
||||
3. CIFS 挂载共享根 `设备履历记录` → `*-share`(先不加 `ro`)
|
||||
4. `mount --bind` 把其中的 `履历` 挂到 `FIXED_ASSET_HISTORY_LOCAL_ROOT`
|
||||
5. 重建 `hxops-backend`,并确认容器内已注入 `FIXED_ASSET_HISTORY_LOCAL_ROOT`
|
||||
|
||||
---
|
||||
|
||||
## 2. 公共准备(test / prod 各做一次即可)
|
||||
## 2. 公共准备(test / prod 每台宿主机各做一次)
|
||||
|
||||
```bash
|
||||
# 安装工具
|
||||
sudo apt update
|
||||
sudo apt install -y cifs-utils smbclient
|
||||
|
||||
# 凭据文件(密码与 .env.shared / .env.<env> 中 FIXED_ASSET_HISTORY_SHARE_* 一致)
|
||||
# 凭据文件:密码取自本机仓库 .env.shared / .env.<env>
|
||||
# grep FIXED_ASSET_HISTORY_SHARE_ .env.shared .env.prod
|
||||
sudo mkdir -p /etc/smbcredentials
|
||||
sudo tee /etc/smbcredentials/hxops-fixed-asset-history >/dev/null <<'EOF'
|
||||
username=SBLL00001
|
||||
@@ -38,25 +45,26 @@ domain=WORKGROUP
|
||||
EOF
|
||||
sudo chmod 600 /etc/smbcredentials/hxops-fixed-asset-history
|
||||
|
||||
# 连通性探测(应能列出目录)
|
||||
smbclient //192.168.100.130/设备履历记录 -A /etc/smbcredentials/hxops-fixed-asset-history -c "ls"
|
||||
# 连通性探测(凭据为 root:600,必须加 sudo,否则会 Unable to open credentials file)
|
||||
sudo smbclient //192.168.100.130/设备履历记录 \
|
||||
-A /etc/smbcredentials/hxops-fixed-asset-history -c "ls"
|
||||
```
|
||||
|
||||
`uid/gid` 默认按 `1001`;不一致时先执行 `id`,替换下面命令中的数值。
|
||||
说明:
|
||||
|
||||
若 `vers=3.0` 报 `Invalid argument`,将命令中的 `vers=3.0` 改为 `vers=2.1` 再试。
|
||||
- `uid/gid` 默认 `1001`;不一致时先执行 `id`,替换下文命令中的数值。
|
||||
- 若 `vers=3.0` 报 `Invalid argument`,改为 `vers=2.1` 再试。
|
||||
- 正式机若从未建过凭据文件,`dmesg` 常见 `STATUS_LOGON_FAILURE` / `cifs_mount failed ... -13`。
|
||||
|
||||
---
|
||||
|
||||
## 3. Test 环境命令(已验证)
|
||||
|
||||
在 hxops 仓库所在宿主机执行:
|
||||
|
||||
```bash
|
||||
# 1) 挂共享根
|
||||
# 1) 挂共享根(首次不加 ro)
|
||||
sudo mkdir -p /mnt/hxops-fixed-asset-history-test-share
|
||||
sudo mount -t cifs //192.168.100.130/设备履历记录 /mnt/hxops-fixed-asset-history-test-share \
|
||||
-o credentials=/etc/smbcredentials/hxops-fixed-asset-history,vers=3.0,iocharset=utf8,uid=1001,gid=1001,file_mode=0755,dir_mode=0755,ro
|
||||
-o credentials=/etc/smbcredentials/hxops-fixed-asset-history,vers=3.0,iocharset=utf8,uid=1001,gid=1001,file_mode=0755,dir_mode=0755
|
||||
|
||||
# 2) 确认有「履历」
|
||||
ls /mnt/hxops-fixed-asset-history-test-share
|
||||
@@ -68,23 +76,28 @@ sudo mount --bind /mnt/hxops-fixed-asset-history-test-share/履历 /mnt/hxops-fi
|
||||
# 4) 确认履历文件可见
|
||||
ls /mnt/hxops-fixed-asset-history-test | head
|
||||
|
||||
# 5) 重建后端并检查容器内路径(必须带 COMPOSE_ENV_BASENAME,否则读不到 LOCAL_ROOT)
|
||||
cd /path/to/hxops # 换成实际部署目录,例如 ~/ai/platform/hxops
|
||||
# 5) 重建后端(必须带 COMPOSE_ENV_BASENAME,否则读不到 LOCAL_ROOT,会回退 UNC 导致 503)
|
||||
cd ~/ai/platform/hxops # 按实际部署目录调整
|
||||
export COMPOSE_SHARED_ENV_BASENAME=.env.shared
|
||||
export COMPOSE_ENV_BASENAME=.env.test
|
||||
docker compose --env-file .env.test up -d hxops-backend
|
||||
docker exec hxops-backend printenv | grep FIXED_ASSET_HISTORY
|
||||
docker exec hxops-backend ls -la /mnt/hxops-fixed-asset-history-test
|
||||
docker exec hxops-backend ls -la /mnt/hxops-fixed-asset-history-test | head
|
||||
```
|
||||
|
||||
### Test 开机自动挂载(可选,写入 /etc/fstab)
|
||||
期望 `printenv` 含:
|
||||
|
||||
```text
|
||||
FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-test
|
||||
```
|
||||
|
||||
### Test 开机自动挂载(可选)
|
||||
|
||||
```bash
|
||||
echo '//192.168.100.130/设备履历记录 /mnt/hxops-fixed-asset-history-test-share cifs credentials=/etc/smbcredentials/hxops-fixed-asset-history,vers=3.0,iocharset=utf8,uid=1001,gid=1001,file_mode=0755,dir_mode=0755,ro,nofail,_netdev 0 0' | sudo tee -a /etc/fstab
|
||||
echo '//192.168.100.130/设备履历记录 /mnt/hxops-fixed-asset-history-test-share cifs credentials=/etc/smbcredentials/hxops-fixed-asset-history,vers=3.0,iocharset=utf8,uid=1001,gid=1001,file_mode=0755,dir_mode=0755,nofail,_netdev 0 0' | sudo tee -a /etc/fstab
|
||||
|
||||
echo '/mnt/hxops-fixed-asset-history-test-share/履历 /mnt/hxops-fixed-asset-history-test none bind,nofail 0 0' | sudo tee -a /etc/fstab
|
||||
|
||||
# 验证 fstab(勿在已挂载时盲目 umount 生产业务目录)
|
||||
sudo mount -a
|
||||
findmnt /mnt/hxops-fixed-asset-history-test
|
||||
```
|
||||
@@ -93,13 +106,19 @@ findmnt /mnt/hxops-fixed-asset-history-test
|
||||
|
||||
## 4. Prod 环境命令
|
||||
|
||||
与 test 相同,仅路径与 compose env 不同:
|
||||
与 test 相同,仅路径与 compose env 不同。**正式机必须单独再建一份凭据**(不会从测试机自动带过来)。
|
||||
|
||||
```bash
|
||||
# 1) 挂共享根
|
||||
# 0) 若尚未建凭据,先完成「§2 公共准备」,并用 sudo smbclient 测通
|
||||
|
||||
# 1) 挂共享根(首次不加 ro;正式机加 ro 曾报 cannot mount ... read-only)
|
||||
sudo mkdir -p /mnt/hxops-fixed-asset-history-prod-share
|
||||
sudo mount -t cifs //192.168.100.130/设备履历记录 /mnt/hxops-fixed-asset-history-prod-share \
|
||||
-o credentials=/etc/smbcredentials/hxops-fixed-asset-history,vers=3.0,iocharset=utf8,uid=1001,gid=1001,file_mode=0755,dir_mode=0755,ro
|
||||
-o credentials=/etc/smbcredentials/hxops-fixed-asset-history,vers=3.0,iocharset=utf8,uid=1001,gid=1001,file_mode=0755,dir_mode=0755
|
||||
|
||||
# 若仍失败:
|
||||
# sudo dmesg | tail -n 40
|
||||
# 再试 vers=2.1
|
||||
|
||||
# 2) 确认有「履历」
|
||||
ls /mnt/hxops-fixed-asset-history-prod-share
|
||||
@@ -111,19 +130,25 @@ sudo mount --bind /mnt/hxops-fixed-asset-history-prod-share/履历 /mnt/hxops-fi
|
||||
# 4) 确认履历文件可见
|
||||
ls /mnt/hxops-fixed-asset-history-prod | head
|
||||
|
||||
# 5) 重建后端并检查容器内路径(必须带 COMPOSE_ENV_BASENAME,否则读不到 LOCAL_ROOT)
|
||||
cd /path/to/hxops
|
||||
# 5) 重建后端
|
||||
cd /data/ai-platform/hxops # 按实际部署目录调整
|
||||
export COMPOSE_SHARED_ENV_BASENAME=.env.shared
|
||||
export COMPOSE_ENV_BASENAME=.env.prod
|
||||
docker compose --env-file .env.prod up -d hxops-backend
|
||||
docker exec hxops-backend printenv | grep FIXED_ASSET_HISTORY
|
||||
docker exec hxops-backend ls -la /mnt/hxops-fixed-asset-history-prod
|
||||
docker exec hxops-backend ls -la /mnt/hxops-fixed-asset-history-prod | head
|
||||
```
|
||||
|
||||
### Prod 开机自动挂载(可选,写入 /etc/fstab)
|
||||
期望 `printenv` 含:
|
||||
|
||||
```text
|
||||
FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-prod
|
||||
```
|
||||
|
||||
### Prod 开机自动挂载(可选)
|
||||
|
||||
```bash
|
||||
echo '//192.168.100.130/设备履历记录 /mnt/hxops-fixed-asset-history-prod-share cifs credentials=/etc/smbcredentials/hxops-fixed-asset-history,vers=3.0,iocharset=utf8,uid=1001,gid=1001,file_mode=0755,dir_mode=0755,ro,nofail,_netdev 0 0' | sudo tee -a /etc/fstab
|
||||
echo '//192.168.100.130/设备履历记录 /mnt/hxops-fixed-asset-history-prod-share cifs credentials=/etc/smbcredentials/hxops-fixed-asset-history,vers=3.0,iocharset=utf8,uid=1001,gid=1001,file_mode=0755,dir_mode=0755,nofail,_netdev 0 0' | sudo tee -a /etc/fstab
|
||||
|
||||
echo '/mnt/hxops-fixed-asset-history-prod-share/履历 /mnt/hxops-fixed-asset-history-prod none bind,nofail 0 0' | sudo tee -a /etc/fstab
|
||||
|
||||
@@ -151,42 +176,41 @@ sudo umount /mnt/hxops-fixed-asset-history-prod-share
|
||||
|
||||
## 6. 排障
|
||||
|
||||
| 现象 | 处理 |
|
||||
| 现象 | 原因 / 处理 |
|
||||
| --- | --- |
|
||||
| `asset history share is unreachable` | 宿主机 `LOCAL_ROOT` 未挂载,或容器未 recreate / compose 未 bind 该路径 |
|
||||
| `Unable to open credentials file` / `Failed to set parse authentication file` | 凭据不存在,或用普通用户读 `root:600` 文件。先建文件,探测时用 **`sudo smbclient`** |
|
||||
| `STATUS_LOGON_FAILURE` / `cifs_mount failed ... -13`(见 `dmesg`) | 账号密码错误,或凭据文件缺失/读失败。核对 `/etc/smbcredentials/hxops-fixed-asset-history` 与 `.env.*` |
|
||||
| `cannot mount ... read-only` | 多为误导文案。去掉 `ro` 再挂,并看 `dmesg \| tail -n 40` |
|
||||
| `mount error(22): Invalid argument` | 勿用 `subdir=`;或改 `vers=2.1` / `vers=2.0` |
|
||||
| `smbclient` 失败 | 查网络、账号密码、Windows 共享权限 |
|
||||
| 宿主机有文件、容器内没有 | `docker compose --env-file .env.<env> up -d hxops-backend` 重建后再 `docker exec ... ls` |
|
||||
| 容器 `ls` 正常但仍 503 `unreachable` | 应用未读到 `FIXED_ASSET_HISTORY_LOCAL_ROOT`,回退到 UNC。执行 `docker exec hxops-backend printenv \| grep FIXED_ASSET`;重建时必须带上 env:见下方「重建后端」 |
|
||||
| 目录存在但为空 | 可能 Docker 先创建了空目录;先 `umount`/清错挂,再按本文重新 mount |
|
||||
| `smbclient` 超时 / Host is down | 正式机到 `192.168.100.130` 网络未放通(需 SMB 445) |
|
||||
| `asset history share is unreachable`(API 503) | 宿主机未挂载,或容器未注入 `FIXED_ASSET_HISTORY_LOCAL_ROOT`(回退到 UNC)。按 §3/§4 重建并检查 `printenv` |
|
||||
| 容器 `ls` 正常,API 200,但提示「未找到履历文件」 | 共享盘已通,但文件名/路径未命中该资产编号或名称;属检索/归档命名问题,不是挂载问题 |
|
||||
| 宿主机有文件、容器内没有 | 挂载后 recreate backend;确认 `docker-compose.yml` 已 bind `LOCAL_ROOT` |
|
||||
| 目录存在但为空 | 可能 Docker 先创建了空目录;先正确 CIFS/bind,再 recreate 容器 |
|
||||
|
||||
### 重建后端(重要)
|
||||
|
||||
compose 默认 `env_file` 指向 `.env.dev`(无 LOCAL_ROOT)。手动重建时请显式指定:
|
||||
### 快速自检清单
|
||||
|
||||
```bash
|
||||
cd /path/to/hxops
|
||||
export COMPOSE_SHARED_ENV_BASENAME=.env.shared
|
||||
export COMPOSE_ENV_BASENAME=.env.test # prod 改成 .env.prod
|
||||
docker compose --env-file .env.test up -d hxops-backend
|
||||
# 凭据
|
||||
sudo ls -l /etc/smbcredentials/hxops-fixed-asset-history
|
||||
sudo smbclient //192.168.100.130/设备履历记录 -A /etc/smbcredentials/hxops-fixed-asset-history -c "ls"
|
||||
|
||||
# 确认容器内已注入 LOCAL_ROOT(不应为空,且不是 UNC)
|
||||
# 挂载
|
||||
findmnt /mnt/hxops-fixed-asset-history-prod-share # 或 test-share
|
||||
findmnt /mnt/hxops-fixed-asset-history-prod # 或 test
|
||||
ls /mnt/hxops-fixed-asset-history-prod | head
|
||||
|
||||
# 容器
|
||||
docker exec hxops-backend printenv | grep FIXED_ASSET_HISTORY
|
||||
docker exec hxops-backend ls /mnt/hxops-fixed-asset-history-prod | head
|
||||
```
|
||||
|
||||
期望类似:
|
||||
|
||||
```text
|
||||
FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-test
|
||||
FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历
|
||||
```
|
||||
|
||||
|
||||
相关配置:
|
||||
### 相关配置
|
||||
|
||||
- `.env.test` / `.env.prod`:`FIXED_ASSET_HISTORY_LOCAL_ROOT`
|
||||
- `docker-compose.yml`:已把 test/prod 两个 `LOCAL_ROOT` 只读挂进 `hxops-backend`
|
||||
- 可选脚本:`scripts/mount_fixed_asset_history.sh`(封装同上逻辑)
|
||||
- `.env.shared` / `.env.<env>`:`FIXED_ASSET_HISTORY_SHARE_USERNAME` / `PASSWORD`
|
||||
- `docker-compose.yml`:已把 test/prod 两个 `LOCAL_ROOT` 只读挂进 `hxops-backend`,并注入 `FIXED_ASSET_HISTORY_LOCAL_ROOT`
|
||||
- 可选脚本:`scripts/mount_fixed_asset_history.sh`(封装同上逻辑;执行用 `sudo bash scripts/...`)
|
||||
|
||||
---
|
||||
|
||||
@@ -194,4 +218,6 @@ FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历
|
||||
|
||||
1. 宿主机:`ls $LOCAL_ROOT` 能看到履历文件
|
||||
2. 容器:`docker exec hxops-backend ls $LOCAL_ROOT` 同样可见
|
||||
3. 前端:聊天页点击资产编号,不再出现 503 / `asset history share is unreachable`
|
||||
3. 容器:`FIXED_ASSET_HISTORY_LOCAL_ROOT` 已注入且指向上述本地路径(不是 UNC)
|
||||
4. 前端:点击资产编号不再出现 503 / `asset history share is unreachable`
|
||||
5. 若仍提示「未找到履历文件」:挂载已正常,需核对共享盘是否存在该资产对应文件(编号或设备名)
|
||||
@@ -0,0 +1,11 @@
|
||||
# 采购合同审查(procurement-contract)
|
||||
|
||||
| 项 | 说明 |
|
||||
| --- | --- |
|
||||
| **需求** | [demand.md](demand.md) |
|
||||
| **当前方案 / 技术** | [comprehensive-review-technical.md](comprehensive-review-technical.md) |
|
||||
| **旧版 MVP** | [technical.md](technical.md) |
|
||||
| **原型** | [../../prototype/procurement-contract-review-prototype.html](../../prototype/procurement-contract-review-prototype.html) |
|
||||
| **状态** | 全面审核基础链路已落地:异步 Job + 双模式 Chat + Admin 三 Tab;比对以改稿/红线为主 |
|
||||
|
||||
**范围摘要**:同一 Agent 双模式(合同比对:我方原合同 + 卖方回传;单份:待审卖方合同);Admin 模板库 / 风险规则 / 审查历史;结果卡与报告下载;无人审、无 ScheduleRun。
|
||||
@@ -0,0 +1,350 @@
|
||||
# 采购合同改稿对照与五问技术方案
|
||||
|
||||
| 项目 | 说明 |
|
||||
| --- | --- |
|
||||
| 文档版本 | v1.1 |
|
||||
| 状态 | Phase 1 已切换:改稿红线比对 + 采购五盏灯为主;比对模式关闭 Dify 全面扫描;单份模式保留五问硬规则 |
|
||||
| 适用范围 | 约 95% 发出稿 vs 回传稿对照;约 5% 卖方自有合同五问 |
|
||||
| 旧版说明 | 原「全面审核」叙事与同步 MVP 见 [technical.md](technical.md);以本文 v1.1 为准 |
|
||||
|
||||
## 1. 方案定位
|
||||
|
||||
合同审核改为市面对齐的双模式产品,而不是「后端 Diff 噪声门禁 + LLM 全面扫」:
|
||||
|
||||
- **改稿对照(compare)**:标出回传稿相对发出稿的实质文本差异,顶部展示付款/保固/管辖/交期/违约金五盏灯;OCR 不确定项不进结果卡主列表。
|
||||
- **卖方合同五问(solo)**:只检查付款前置、交期、质保、买方管辖、逾期违约金 ≥ 0.5‰。
|
||||
- HXOPS 复用知识库 `edkb_system` 清洗,不创建 `KbDocument`、不同步企业 Dataset。
|
||||
- **比对模式默认不调用 Dify**;单份模式可按配置做 LLM 增强。
|
||||
- 整条链路仍为异步 Job + 前端轮询。
|
||||
- Chat 比对模式固定接收「我方发出稿 + 卖方回传稿」。
|
||||
|
||||
## 2. 总体流程
|
||||
|
||||
### 2.1 系统任务编排
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
U["用户选择改稿对照或卖方五问"] --> API["POST /api/procurement-contract/reviews"]
|
||||
API --> REV["创建 ContractReview<br/>status=queued"]
|
||||
API --> JOB["创建通用 Job<br/>procurement_contract_review"]
|
||||
API --> UI["立即返回 review_no<br/>前端每 2 秒轮询"]
|
||||
JOB --> W["hxops-kb-worker<br/>contract 队列"]
|
||||
W --> C["复用知识库 build_clean_result"]
|
||||
C --> P["合同专用预处理"]
|
||||
P --> D1{"模式?"}
|
||||
D1 -->|compare| R1["实质 Diff + 五盏灯<br/>不调 Dify"]
|
||||
D1 -->|solo| R2["五问硬规则<br/>可选 Dify 增强"]
|
||||
R1 --> DONE["status=success"]
|
||||
R2 --> DONE
|
||||
DONE --> UI
|
||||
```
|
||||
|
||||
### 2.2 合同审核完整处理链路
|
||||
|
||||
OCR 属于“提取清洗”阶段;OCR 识别错误在此阶段产生,但 `OCR/抽取待确认` 项是在后续合同比对和结果校验阶段,根据差异可靠性生成。
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A["用户发起合同审核"] --> B{"选择审核模式"}
|
||||
|
||||
B -->|模板比对| C["上传我方原合同<br/>+ 卖方回传合同"]
|
||||
B -->|单份审核| D["上传卖方自有合同"]
|
||||
|
||||
C --> E["创建审核任务"]
|
||||
D --> E
|
||||
|
||||
E --> F["提取清洗<br/>两份合同分别处理"]
|
||||
F --> G{"文件能否直接提取文字"}
|
||||
|
||||
G -->|扫描 PDF / 无文本层| H["执行 OCR 识别"]
|
||||
G -->|Word / 可检索 PDF| I["直接提取文本"]
|
||||
|
||||
H --> J["保存原始分页文本<br/>ocr_document.md"]
|
||||
I --> J
|
||||
|
||||
J --> K["文本清洗<br/>移除页码、图片标记、异常空格和换行"]
|
||||
K --> L["OCR 数字归一<br/>日期、金额、百分比、千分比"]
|
||||
L --> M["生成审核正文<br/>document.md"]
|
||||
M --> N["抽取质量评分"]
|
||||
|
||||
N --> O["条款识别与结构化<br/>标题、父级条款、条款类别、条款编号"]
|
||||
O --> P{"审核模式"}
|
||||
|
||||
P -->|模板比对| Q["语义对齐两份合同<br/>忽略空格、标点、换行和格式差异"]
|
||||
Q --> R{"差异可靠性判断"}
|
||||
|
||||
R -->|明确真实修改| S["生成改动项"]
|
||||
R -->|高相似 OCR 字形差异| T["作为 OCR 噪声忽略"]
|
||||
R -->|关键数字异常或段落无法对齐| U["生成待确认项"]
|
||||
|
||||
P -->|单份审核| V["直接进入整份风险扫描"]
|
||||
Q --> V
|
||||
|
||||
V --> W["采购规则扫描<br/>付款、交期、质保、管辖地、违约责任"]
|
||||
W --> X["生成确定性风险项"]
|
||||
|
||||
S --> Y["AI 全面审核与纠错"]
|
||||
X --> Y
|
||||
U --> Y
|
||||
|
||||
Y --> Z{"AI 结论是否有<br/>可定位的原文证据"}
|
||||
Z -->|证据有效| AA["确认、补充或否决风险"]
|
||||
Z -->|证据不足| AB["保留为待确认项"]
|
||||
|
||||
AA --> AC["结果校验、去重与合并"]
|
||||
AB --> AC
|
||||
U --> AC
|
||||
|
||||
AC --> AD["证据锚定<br/>定位页码、条款和原文位置"]
|
||||
AD --> AE["生成审核结果"]
|
||||
|
||||
AE --> AF["改动项"]
|
||||
AE --> AG["风险项"]
|
||||
AE --> AH["待确认项"]
|
||||
AE --> AI["标注合同和审核报告"]
|
||||
```
|
||||
|
||||
### 2.3 OCR 待确认项产生时序
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant PDF as 卖方扫描 PDF
|
||||
participant OCR as 提取清洗
|
||||
participant DIFF as 合同比对
|
||||
participant CHECK as 结果校验
|
||||
participant UI as 结果页面
|
||||
|
||||
PDF->>OCR: 上传扫描版合同
|
||||
OCR->>OCR: OCR 识别文字、日期、金额和比例
|
||||
Note over OCR: 可能出现 30%→3哪、合同号乱码等误识别
|
||||
OCR->>OCR: 清洗页码、图片标记、空格和换行
|
||||
OCR->>DIFF: 提交清洗后的 document.md
|
||||
DIFF->>DIFF: 与我方原合同进行语义对齐
|
||||
DIFF->>DIFF: 判断真实修改、可忽略噪声或不确定差异
|
||||
DIFF->>CHECK: 提交改动项、风险项和候选待确认片段
|
||||
CHECK->>CHECK: 证据校验、去重和分类
|
||||
CHECK-->>UI: 无法可靠恢复的关键差异进入待确认项
|
||||
```
|
||||
|
||||
## 3. 异步任务与进度协议
|
||||
|
||||
`POST /reviews` 返回 HTTP `202`,不等待合同清洗或 Dify。前端通过 `GET /reviews/<review_no>` 轮询:
|
||||
|
||||
结果卡始终展示下表全部阶段,已完成阶段显示完成状态,`processing_stage` 对应阶段高亮并展示旋转状态,未开始阶段保持灰色;百分比使用后端里程碑值,不在前端虚构中间进度。
|
||||
|
||||
| 阶段 | 进度 | 说明 |
|
||||
| --- | ---: | --- |
|
||||
| `queued` | 0 | 等待 Worker |
|
||||
| `extracting` | 10 | 读取文件并复用知识库清洗器 |
|
||||
| `structuring` | 30 | 合同去噪和条款结构化 |
|
||||
| `deterministic_review` | 45 | 模板 Diff 与整份红线规则 |
|
||||
| `llm_reviewing` | 60 | Dify 全面法律审核 |
|
||||
| `validating` | 88 | 证据校验、合并和报告生成 |
|
||||
| `success` | 100 | 审核完成 |
|
||||
| `failed` | 100 | 清洗或主流程失败 |
|
||||
|
||||
通用 `jobs` 表负责领取、锁、超时回收和最多两次尝试;`ContractReview.summary_json.processing` 是前端展示的业务进度。Worker 中断时,超时回收会把审核重置为排队或最终失败。
|
||||
|
||||
## 4. 文件清洗与产物
|
||||
|
||||
清洗复用 `knowledge_cleaning.edkb_adapter.build_clean_result`。合同域不复用知识库数据模型和 Dataset 同步,只复用文件解析能力。
|
||||
|
||||
PDF 在配置 `PROCUREMENT_CONTRACT_MINERU_API_URL` 后优先调用内网 MinerU `POST /file_parse`:上传字段为 `files`,测试环境传入 `lang_list=ch`、`backend=pipeline` 和 `parse_method=auto`。HXOPS 读取同步响应 `results.*.md_content` 作为审核正文,并保存完整响应;MinerU 不可用、超时或未返回 Markdown 时自动回退知识库清洗器,再回退本地提取器。Word 等非 PDF 文件继续使用现有清洗器。
|
||||
|
||||
MinerU 的 HTML 表格在进入条款切分前转换为稳定的单元格行文本(`列 | 列`),`rowspan`、`colspan` 等版面属性不参与 Diff;签章区重复出现且已在合同抬头识别过的甲乙方名称会剥离,避免产生设备清单伪变更或乙方名称伪删除。
|
||||
|
||||
合同 Diff 会忽略两类无业务事实的解析噪声:双方全文金额一致但仅“合计/总计”行列拆分不同的表格片段,以及单边出现的 Markdown 标记、单字符 OCR 残片;任何金额、数量、型号或义务内容不一致仍保留为真实差异。
|
||||
|
||||
文末签署日期与已在正文出现的保固/售后摘要发生跨区错位时,Diff 会识别为版面噪声而非条款修改。PDF 标注下载不再因全部发现无法定位而失败:有锚点时写入高亮或页级批注,无锚点时返回原合同副本,避免前端下载入口报错。
|
||||
|
||||
```text
|
||||
backend/data/procurement_contract/CR-.../
|
||||
source/contract.docx
|
||||
source/template.docx
|
||||
cleaned/contract/document.md
|
||||
cleaned/contract/ocr_document.md
|
||||
cleaned/contract/mineru_document.md # 使用 MinerU 时保留原始 Markdown
|
||||
cleaned/contract/mineru_result.json # 使用 MinerU 时保留完整 API 响应
|
||||
cleaned/contract/clauses.json
|
||||
cleaned/template/document.md
|
||||
cleaned/template/clauses.json
|
||||
result/merged_result.json
|
||||
```
|
||||
|
||||
目录仅由 HXOPS 读写。Dify 不读取服务器路径,HXOPS 将 `clean_text` 与 `clauses_json` 作为 Chatflow Start 输入发送。
|
||||
|
||||
审核完成后,HXOPS 将整个 `CR-...` 目录上传至私有 MinIO 桶 `procurement-contract`,先上传全部文件,再写入 `_manifest.json` 作为完整归档提交标记。归档成功后按 `PROCUREMENT_CONTRACT_ARCHIVE_CLEANUP_LOCAL=true` 删除 Docker 卷中的本地目录;后续下载标注合同或 OCR 页码定位需要清洗文本时,本地缓存不存在会依据 manifest 从 MinIO 恢复所需文件并校验 SHA-256。归档失败不影响已完成的审核结论,保留本地目录并在 `summary_json.artifact_archive` 记录失败原因。
|
||||
|
||||
```json
|
||||
{
|
||||
"clause_id": "clause-0012",
|
||||
"clause_no": "第八条",
|
||||
"title": "验收",
|
||||
"category": "acceptance",
|
||||
"text": "第八条 验收……"
|
||||
}
|
||||
```
|
||||
|
||||
## 5. HXOPS 确定性审核
|
||||
|
||||
- 模板比对:当前按清洗段落使用 `difflib.SequenceMatcher` 识别新增、删除和修改。
|
||||
- 输入门禁:比对模式必须显式提供 `original_contract_asset_no`,后端不再接受缺省基准并自动选择模板库默认文件。
|
||||
- 文本质量门禁:记录模板与合同的 `score/level/suspicious_ratio`;明确数字和权利义务变化继续输出,OCR 可疑数字、列表编号、表格错位及高相似字形噪声转入 `comparison_quality.needs_confirmation`,不计入 `total_changes`。
|
||||
- 条款对齐使用 OCR 容错键,避免圈号、常见数字字形和列表编号导致后续条款整体错位;合同抬头、普通错字及非关键版面噪声计入 `ignored_ocr_noise`,不逐条展示。
|
||||
- 待确认只保留关键数字或权利义务不明确的片段,并按付款、交付、验收、质保、违约与责任、争议解决等业务主题聚合;`comparison_quality.confirmation_fragments` 保留底层受影响片段数,`needs_confirmation` 表示页面需人工确认的主题数。
|
||||
- 页码、`page-image-N` 和粘连分页噪声从审核正文剥离;原始 OCR 分页文本保存为 `ocr_document.md`,继续供扫描 PDF 批注定位使用。
|
||||
- 关键数字支持圈号、常见 OCR 字形、中文数字和“千分之五”等归一。无法可靠恢复时输出 `needs_review`,不计入高中低风险。
|
||||
- 条款分类按父级标题、当前标题、正文关键词依次加权;同一业务类别下的不同事实 Diff 全部保留,仅完全相同证据去重。
|
||||
- 整份红线:比对模式也执行单份审核规则,补足非差异段落中的实质缺项。
|
||||
- 规则支持 `keyword_missing` 与 `keyword_present`,用于公司明确红线和确定性兜底,不承担全面法律语义审核。
|
||||
- 采购重点策略:在配置规则之外确定性检查付款是否绑定交付/验收/发票、交期是否可计算、质保期限、买方所在地管辖,以及卖方逾期交付是否达到每日合同总价 `5‰`。
|
||||
- PDF 证据锚定:优先使用合同侧 `new_text` 或原文 `evidence`,通过 PDFium 精确/模糊搜索获得页码与逐字坐标;扫描 PDF 无文本层时按清洗 Markdown 的 OCR 分页标记定位页码。下载时文本型 PDF 写入风险高亮,扫描 PDF 在对应原页写入批注意见;缺失型风险没有可引用原文时保持 `unanchored`。
|
||||
- 结果展示分类:`insert/delete/modify` 仅进入合同改动项;`missing/rule_scan/policy_scan/llm_scan` 进入独立风险项;`ocr_uncertain` 或 `validation_status=needs_review` 进入待确认项。三类互斥,待确认项不计入改动数和高中低风险统计。
|
||||
- Dify 对确定性发现可返回 `confirm/reject/uncertain`;只有原文直接反证和 `confidence >= 0.8` 同时满足时,`reject` 才能撤销误报。
|
||||
|
||||
## 6. Dify Chatflow 协议
|
||||
|
||||
当前复用已有“采购合同审查”Chatflow,不需要新建 Workflow 应用。HXOPS对有附件的审核任务仍由后台 Worker 发起,
|
||||
只是调用接口从 `/v1/workflows/run` 改为 `/v1/chat-messages`;无附件时该 Chatflow 仅承担双文件上传或单份审核引导。
|
||||
|
||||
### 6.1 输入变量
|
||||
|
||||
| 变量 | 类型 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `review_no` | String | HXOPS 审核编号 |
|
||||
| `review_mode` | String | `compare` 或 `solo` |
|
||||
| `contract_type` | String | 合同类型 |
|
||||
| `template_name` | String | 模板名称,无模板为空 |
|
||||
| `findings_json` | Paragraph/String | HXOPS Diff 和规则发现 |
|
||||
| `clauses_json` | Paragraph/String | 按原文顺序排列的结构化条款 |
|
||||
| `clean_text` | Paragraph/String | 清洗后的合同全文 |
|
||||
| `scan_enabled` | String | 固定为 `true` |
|
||||
| `scan_scope` | String | 未截断为 `full_contract`;达到输入上限时为 `bounded_contract` |
|
||||
| `instruction` | Paragraph/String | HXOPS 版本化审核约束 |
|
||||
|
||||
输入保护默认最多 `120000` 字符和 `160` 条结构化条款。发生截断时写入 `summary_json.llm_input.truncated=true`,不能宣称已完整覆盖超长合同。
|
||||
|
||||
### 6.2 推荐节点
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
START["开始<br/>声明输入变量"] --> ROUTE["任务识别 LLM / 条件分支"]
|
||||
ROUTE -->|合同全面审核任务| REVIEW["LLM 节点<br/>全面合同审核"]
|
||||
ROUTE -->|普通问答| GUIDE["上传与模板使用引导"]
|
||||
REVIEW --> END["回答<br/>审核分支仅输出 JSON"]
|
||||
GUIDE --> END
|
||||
```
|
||||
|
||||
第一版只使用一次核心 LLM 调用,避免画布串行节点过多。模型必须逐条覆盖 `clauses_json`,检查付款、交付、验收、质保、违约赔偿、免责、责任上限、知识产权、保密数据、解除续期、不可抗力、争议解决和跨条款冲突。
|
||||
|
||||
已有发现放入 `items`;新风险放入 `new_items`。每个新风险必须返回真实 `clause_id` 或 `clause_no` 和合同原文 `evidence`,禁止编造法条编号。
|
||||
|
||||
节点级配置:
|
||||
|
||||
| 顺序 | 节点名称 | 类型 | 输入与配置 | 输出 / 连线 |
|
||||
| ---: | --- | --- | --- | --- |
|
||||
| 1 | `开始` | Start | 声明 §6.1 全部输入变量;`clean_text/clauses_json/findings_json/instruction` 使用 Paragraph | 连到 `识别审核任务` |
|
||||
| 2 | `识别审核任务` | LLM 或 If-Else | query含“执行合同全面审核任务”且 `scan_enabled == "true"` 时进入审核;其他消息进入会话引导 | 审核 → `全面合同审核`;普通问答 → `会话引导` |
|
||||
| 3 | `全面合同审核` | LLM | 推荐低温度 `0.1`;System使用 `instruction`;User拼接合同上下文和输出要求 | 连到 `回答` |
|
||||
| 4 | `会话引导` | LLM / Answer | 保留无附件上传、模板选择等会话能力 | 连到 `回答` |
|
||||
| 5 | `回答` | Answer | 审核分支只能输出严格JSON;普通分支可输出自然语言 | HXOPS解析审核分支回答 |
|
||||
|
||||
`全面合同审核` 的 User Prompt 建议:
|
||||
|
||||
```text
|
||||
审核编号:{{review_no}}
|
||||
审核模式:{{review_mode}}
|
||||
合同类型:{{contract_type}}
|
||||
模板名称:{{template_name}}
|
||||
|
||||
HXOPS 已发现风险:
|
||||
{{findings_json}}
|
||||
|
||||
结构化条款(必须逐条覆盖):
|
||||
{{clauses_json}}
|
||||
|
||||
清洗合同全文(用于跨条款复核和证据核对):
|
||||
{{clean_text}}
|
||||
|
||||
请严格按照 System 中的 JSON Schema 返回,不得输出 Markdown,不得省略 evidence。
|
||||
```
|
||||
|
||||
如果模型偶尔使用Markdown代码围栏,HXOPS会自动提取其中JSON;不需要在Chatflow增加结果标准化Code节点。
|
||||
|
||||
### 6.3 输出协议
|
||||
|
||||
```json
|
||||
{
|
||||
"items": [
|
||||
{
|
||||
"id": "1",
|
||||
"professional_reason": "该修改削弱了采购方验收权",
|
||||
"professional_suggestion": "删除默示验收",
|
||||
"negotiation_text": "建议恢复公司模板验收条款",
|
||||
"model_risk_level": "high",
|
||||
"confidence": 0.91
|
||||
}
|
||||
],
|
||||
"new_items": [
|
||||
{
|
||||
"id": "llm-1",
|
||||
"clause_id": "clause-0012",
|
||||
"clause_no": "第八条",
|
||||
"title": "逾期自动视为验收合格",
|
||||
"clause_category": "acceptance",
|
||||
"risk_level": "high",
|
||||
"professional_reason": "验收期过短且沉默被视为认可",
|
||||
"business_impact": "隐蔽质量问题可能无法及时主张",
|
||||
"professional_suggestion": "删除默示验收并延长验收期",
|
||||
"negotiation_text": "建议以书面验收结论作为付款前提",
|
||||
"evidence": "甲方三日内未提出异议视为验收合格",
|
||||
"confidence": 0.88
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Chatflow审核分支的最终Answer必须输出完整JSON。HXOPS兼容纯JSON或包在Markdown代码围栏中的JSON。
|
||||
|
||||
## 7. 结果治理与降级
|
||||
|
||||
```text
|
||||
最终风险 = 模板差异风险 ∪ 公司红线风险 ∪ Dify 独立发现风险
|
||||
```
|
||||
|
||||
- Dify 可以提高已有项风险等级,不能降低规则等级。
|
||||
- 新发现 `clause_id` 必须存在;`evidence` 必须能在清洗正文中找到,否则标记 `needs_review`。
|
||||
- 相同条款、标题和原因的风险去重。
|
||||
- Dify 失败时保留 Diff 和规则结果,审核仍可成功,并记录 LLM 失败状态。
|
||||
- 清洗失败或合同无可读正文时整次审核失败。
|
||||
- 合并后统一重算风险数量与报告,保证页面和下载报告一致。
|
||||
|
||||
## 8. 环境配置
|
||||
|
||||
```bash
|
||||
PROCUREMENT_CONTRACT_LLM_ENABLED=true
|
||||
PROCUREMENT_CONTRACT_LLM_AGENT_ID=123
|
||||
# 当前复用 Chatflow;`workflow` 仅为后端兼容保留值。
|
||||
PROCUREMENT_CONTRACT_LLM_PROVIDER=chatflow
|
||||
# 或直接配置Dify应用凭据
|
||||
PROCUREMENT_CONTRACT_LLM_DIFY_API_KEY=app-xxxxxxxx
|
||||
PROCUREMENT_CONTRACT_LLM_DIFY_BASE=http://dify-api:5001/v1
|
||||
|
||||
PROCUREMENT_CONTRACT_LLM_CONNECT_TIMEOUT_SECONDS=5
|
||||
PROCUREMENT_CONTRACT_LLM_READ_TIMEOUT_SECONDS=120
|
||||
PROCUREMENT_CONTRACT_JOB_TIMEOUT_SECONDS=600
|
||||
PROCUREMENT_CONTRACT_LLM_MAX_TEXT_CHARS=120000
|
||||
PROCUREMENT_CONTRACT_LLM_MAX_CLAUSES=160
|
||||
PROCUREMENT_CONTRACT_STORAGE_ROOT=backend/data/procurement_contract
|
||||
```
|
||||
|
||||
生产部署必须保证 `hxops-kb-worker` 常驻。兼容入口 `worker_kb.py` 的第一个进程消费 `kb,contract`,其余进程仅消费 `kb`。
|
||||
|
||||
## 9. 安全与后续演进
|
||||
|
||||
- 不向 Dify 发送本地路径,不把合同放进企业公共 Dataset。
|
||||
- Dify 密钥仅存在环境变量或 Agent 密钥字段。
|
||||
- 上线前确认 Dify 和模型供应商的数据留存、网络边界与跨境要求。
|
||||
- `summary_json` 保存 Dify消息ID、输入长度和截断标记。
|
||||
|
||||
后续重点:超长合同分组审核与全局复核、扫描 PDF OCR、表格/批注/修订痕迹、条款语义 Diff、条件与数值规则、受控法律知识库、刷新后恢复进度卡、失败重试入口和标准合同回归评测。
|
||||
Binary file not shown.
@@ -0,0 +1,376 @@
|
||||
# 采购合同审查 — 需求说明
|
||||
|
||||
| 项目 | 说明 |
|
||||
|------|------|
|
||||
| 文档版本 | v1.0 |
|
||||
| 状态 | 基于当前代码 / UI / 已确认产品决策整理 |
|
||||
| 关联 | [comprehensive-review-technical.md](comprehensive-review-technical.md)(实现权威)· [原型](../../prototype/procurement-contract-review-prototype.html) |
|
||||
| 读者 | 产品、测试、研发 |
|
||||
|
||||
---
|
||||
|
||||
## 1. 背景与目标
|
||||
|
||||
### 1.1 背景
|
||||
|
||||
企业采购场景下,需对「我方发出稿 vs 卖方回传稿」做改稿对照,或对「卖方自有合同」做关键条款完备性检查。能力落地在 HXOPS 工作台单一 Agent「采购合同审查」中,并配套管理端维护红线规则与查看历史。
|
||||
|
||||
### 1.2 目标
|
||||
|
||||
1. 普通用户在 Chat 中选择模式、上传合同后发起审核,获得可下载的结构化结果(改动项 / 风险项 / 可选待确认项)与报告。
|
||||
2. 审核异步执行:上传后立即拿到审查编号与进度,不因清洗或大模型阻塞整次 HTTP。
|
||||
3. 管理员可维护合同模板库、风险红线规则,并检索全站审查历史与下载产物。
|
||||
4. 结果定位为**采购风险提示**,不作为法律意见;不自动改合同、不回写 OA/SRM。
|
||||
|
||||
### 1.3 角色
|
||||
|
||||
| 角色 | 权限概要 |
|
||||
|------|----------|
|
||||
| 会话用户 | 已登录且具备「采购合同审查」Agent 访问权;仅能查看/下载本人审查 |
|
||||
| 管理员 | `require_admin` + 模块 `procurement_contract`;维护模板/规则、查看全部历史 |
|
||||
|
||||
---
|
||||
|
||||
## 2. 范围
|
||||
|
||||
### 2.1 本期范围(In Scope)
|
||||
|
||||
| 编号 | 能力 |
|
||||
|------|------|
|
||||
| R-CHAT-01 | Chat 双模式:合同比对(compare)/ 单份审核(solo) |
|
||||
| R-CHAT-02 | 比对:固定上传「我方原合同 + 卖方回传合同」;不得选用或回退库内默认模板 |
|
||||
| R-CHAT-03 | 单份:仅上传一份待审卖方合同 |
|
||||
| R-CHAT-04 | 异步审查:提交后返回审查编号;结果卡展示完整步骤轨道并轮询至终态 |
|
||||
| R-CHAT-05 | 结果卡分区展示改动项 / 独立风险项;(单份)可选待确认项;下载报告(docx);PDF 可下载标注合同 |
|
||||
| R-CHAT-06 | 无附件纯文字走 Agent 绑定 Chatflow 引导,不创建审查 |
|
||||
| R-ADM-01 | Admin 模板库:上传 / 编辑元数据 / 启停 / 设默认 / 下载 / 删除约束 |
|
||||
| R-ADM-02 | Admin 风险规则:增删改查、启停;迁移种子规则默认保留且可改 |
|
||||
| R-ADM-03 | Admin 审查历史:筛选、详情、下载报告/原合同/标注合同/比对底稿 |
|
||||
| R-ANA-01 | 比对:实质 Diff + 风险分级;空格/标点/编号等噪声不计改动 |
|
||||
| R-ANA-02 | 单份:红线规则 + 五问硬规则(付款前置、交期、质保、买方管辖、逾期违约金 ≥ 日 5‰) |
|
||||
| R-ANA-03 | 正文抽取当事人:供应商(乙方/卖方等)、业务合同编号 |
|
||||
| R-ANA-04 | 清洗复用知识库能力,待审合同不进入企业正式 Dataset |
|
||||
|
||||
### 2.2 非本期范围(Out of Scope)
|
||||
|
||||
- ScheduleTask / 批次 / cron 拉数
|
||||
- 人工确认闸门(`human_confirm`)
|
||||
- 回写 OA / SRM / 法务;自动改合同、盖章
|
||||
- Chat 企业知识库入口、库内模板下拉、口头指定模板版本(如「用 V3.1」)
|
||||
- Workspace 独立只读历史页
|
||||
- 将审查报告同步入企业知识库 Dataset(仅复用清洗器)
|
||||
- 以法律意见或合规终裁名义对外输出
|
||||
|
||||
---
|
||||
|
||||
## 3. 术语
|
||||
|
||||
| 术语 | 含义 |
|
||||
|------|------|
|
||||
| 我方原合同 / 发出稿 | 比对模式底稿,Chat 中专用上传入口 |
|
||||
| 卖方回传合同 | 比对模式对方稿;亦为单份模式的待审合同 |
|
||||
| review_no | 系统审查编号(如 `CR-YYYYMMDD-XXXX`),非业务合同编号 |
|
||||
| contract_no | 从合同正文抽取的业务合同编号 |
|
||||
| 改动项 | 相对底稿的实质 insert/delete/modify |
|
||||
| 独立风险项 | 红线/五问等规则命中,非「对方改稿」语义 |
|
||||
| 待确认项 | OCR/抽取不确定且影响采购决策的项;**不得计入**高/中/低风险统计 |
|
||||
| 五盏灯 | 付款 / 保固 / 管辖 / 交期 / 违约金 关注维度(比对分析侧产出) |
|
||||
|
||||
---
|
||||
|
||||
## 4. 功能需求与输入输出
|
||||
|
||||
### 4.1 Chat — 模式与上传
|
||||
|
||||
| ID | 用户输入 / 操作 | 系统输出 / 行为 |
|
||||
|----|-----------------|-----------------|
|
||||
| IO-C01 | 进入「采购合同审查」Agent | 输入区上方显示模式切换;**不展示**企业知识库入口 |
|
||||
| IO-C02 | 切到「合同比对」 | 提示需上传我方原合同 + 卖方回传;显示「上传我方原合同」入口 |
|
||||
| IO-C03 | 切到「单份审核」 | 隐藏我方原合同入口;提示仅上传待审卖方合同 |
|
||||
| IO-C04 | 比对模式上传我方原合同(pdf/doc/docx/txt/md) | 出现「我方原合同」chip;记录 asset |
|
||||
| IO-C05 | 清除我方原合同 chip | chip 消失,需重新上传才能发起比对 |
|
||||
| IO-C06 | 附件区选择卖方/待审合同 | 仅允许 **1** 份文档类附件;展示文件 chip |
|
||||
| IO-C07 | 点击快捷语 | 仅填充输入框文案,不自动发起审查 |
|
||||
|
||||
**允许文件类型**:`pdf, doc, docx, txt, md, markdown`。
|
||||
|
||||
### 4.2 Chat — 发起审查
|
||||
|
||||
| ID | 用户输入 / 操作 | 系统输出 / 行为 |
|
||||
|----|-----------------|-----------------|
|
||||
| IO-C10 | 比对:已上传我方原合同 + 1 份卖方回传,点击发送(可有或无文字) | 创建审查;写入用户气泡 + 结果卡;HTTP 接受后展示进度;后台异步执行 |
|
||||
| IO-C11 | 单份:已上传 1 份待审合同,点击发送 | 同上,模式为 solo |
|
||||
| IO-C12 | 发送时输入为空 | 使用默认用户文案:对《文件名》进行「合同比对/单份审核」 |
|
||||
| IO-C13 | 发送时带自定义文字 | 用户气泡展示该文字;作为历史 query 落库 |
|
||||
| IO-C14 | 审查进行中 | 结果卡展示完整步骤轨道(排队→提取清洗→条款识别→比对/风险扫描→AI→校验→完成),当前步高亮;约每 2s 轮询;前端等待上限约 10 分钟(后台任务可继续) |
|
||||
| IO-C15 | 审查成功 | 结果卡展示:review_no、文件名、可选 contract_no/供应商、底稿名与来源、改动项/风险统计、分区条款表;可下载报告(默认 docx);PDF 可下载标注合同 |
|
||||
| IO-C16 | 审查失败 | 结果卡/提示展示失败原因(如无法解析正文);状态 failed |
|
||||
| IO-C17 | 刷新或重新打开会话且审查仍进行中 | 结果卡恢复并继续轮询至终态 |
|
||||
| IO-C18 | 无附件、无「仅有我方原合同」场景下发送纯文字 | **不**创建审查;走 Dify Chatflow 引导回复 |
|
||||
|
||||
### 4.3 Chat — 结果卡内容约定
|
||||
|
||||
| 分区 | 何时出现 | 计入风险统计 |
|
||||
|------|----------|--------------|
|
||||
| 合同改动项 | 比对成功且存在 insert/delete/modify | 按项风险计入高/中/低 |
|
||||
| 独立风险项 | 规则/五问/策略扫描命中(非 ok) | 计入 |
|
||||
| 待确认项 | 单份模式可展示;比对模式结果卡**不展示** OCR 待确认主列表 | **不计入**高中低 |
|
||||
|
||||
顶部统计:改动项数量 + 高 / 中 / 低风险计数;可有高风险角标。
|
||||
免责声明:采购风险提示,不作为法律意见。
|
||||
|
||||
### 4.4 Admin — 模板库
|
||||
|
||||
| ID | 用户输入 / 操作 | 系统输出 / 行为 |
|
||||
|----|-----------------|-----------------|
|
||||
| IO-T01 | 打开「模板库」Tab | 列表:名称、版本、文件、状态、是否默认、操作 |
|
||||
| IO-T02 | 上传模板(文件 + 名称 + 版本 + 可选备注/默认/状态) | 创建成功;启用模板可供历史兼容使用(**Chat 比对不再选用库内模板**) |
|
||||
| IO-T03 | 编辑模板 | 仅元数据;不可在本弹窗换文件(需新版本上传) |
|
||||
| IO-T04 | 设为默认 | 仅启用中模板;成功后其它默认取消 |
|
||||
| IO-T05 | 停用默认模板 | 拒绝,提示先设其它默认可再停用 |
|
||||
| IO-T06 | 删除默认模板 | 拒绝 |
|
||||
| IO-T07 | 删除已被审查引用的模板 | 拒绝(冲突);可改为停用 |
|
||||
| IO-T08 | 下载模板文件 | 鉴权下载原文件 |
|
||||
|
||||
### 4.5 Admin — 风险规则
|
||||
|
||||
| ID | 用户输入 / 操作 | 系统输出 / 行为 |
|
||||
|----|-----------------|-----------------|
|
||||
| IO-R01 | 打开「风险规则」Tab | 展示种子规则 + 自定义规则;可按启用/停用筛选 |
|
||||
| IO-R02 | 新增自定义规则(标题、标准分类、关键词、触发条件、风险等级、说明、建议等) | 创建成功;系统自动生成内部编码,用户不可输入内置编码 |
|
||||
| IO-R03 | 编辑规则 | 可改标题/关键词/等级等;**编码只读** |
|
||||
| IO-R04 | 点击启用/停用 | 状态立即切换(乐观更新);失败回滚;无整表闪烁 |
|
||||
| IO-R05 | 删除规则 | 确认后删除;之后审查不再使用该条 |
|
||||
| IO-R06 | 迁移环境首次升级 | 种子规则自动入库且默认可编辑 |
|
||||
|
||||
**触发条件**
|
||||
|
||||
| 值 | 含义 |
|
||||
|----|------|
|
||||
| `keyword_missing` | 正文缺少关键词时触发风险 |
|
||||
| `keyword_present` | 正文出现关键词时触发风险 |
|
||||
|
||||
**风险等级**:`high` / `medium` / `low`。
|
||||
|
||||
**规则字段与判定边界**
|
||||
|
||||
| 字段 | 配置约束 | 对审核的影响 |
|
||||
|---|---|---|
|
||||
| 编码 | 自定义规则由系统生成;内置规则编码只读且保留 | 内置编码对应组合业务判断;自定义编码仅作唯一标识 |
|
||||
| 条款分类 | 仅可选 `payment`、`delivery`、`acceptance`、`warranty`、`liability`、`jurisdiction`、`dispute`、`ip`、`other` | 用于结果归类、聚合和策略去重 |
|
||||
| 关键词 | 逗号分隔、至少一项 | `keyword_present` 为命中任一词即触发;`keyword_missing` 为全部词均未出现才触发 |
|
||||
| 内置规则 | 付款、验收、违约、管辖、质保五类种子规则 | 使用后端组合业务判断,不能用普通关键词语义替代 |
|
||||
|
||||
### 4.6 Admin — 审查历史
|
||||
|
||||
| ID | 用户输入 / 操作 | 系统输出 / 行为 |
|
||||
|----|-----------------|-----------------|
|
||||
| IO-H01 | 打开「审查历史」 | 列表含审查编号、模式、合同文件、合同编号、供应商、模板/底稿、来源、用户、时间、状态、风险 |
|
||||
| IO-H02 | 按关键字/模式/来源/风险筛选 | 列表刷新(关键字可匹配 review_no、文件名、模板名、供应商、合同编号) |
|
||||
| IO-H03 | 打开详情 | 抽屉展示摘要与报告预览区 |
|
||||
| IO-H04 | 下载报告 / 待审合同 / 标注合同 / 比对底稿 | 鉴权下载对应产物(标注合同仅 PDF 有意义) |
|
||||
|
||||
### 4.7 分析规则(业务约束,供设计与断言)
|
||||
|
||||
**比对(compare)**
|
||||
|
||||
- 输入:我方原合同全文 + 卖方回传全文。
|
||||
- 空格、换行、标点、编号及高相似 OCR 噪声 **不得** 计为合同改动。
|
||||
- 日期/金额/比例/期限出现圈号、错字或不确定 OCR 字形 → 仅可进待确认(实现上比对主列表可不展示待确认)。
|
||||
- 同一条款类别下不同事实变化须分别保留(如预付款比例与付款期限不可合并为一项)。
|
||||
- 比对路径以 Diff + 五盏灯关注为主;**不**强制跑与单份完全相同的整份红线扫缺。
|
||||
|
||||
**单份(solo)**
|
||||
|
||||
- 优先检查:付款前置条件、明确交货期限、质保期限、采购方所在地管辖、卖方逾期交付每日合同总价 **≥ 5‰** 违约金。
|
||||
- 叠加启用中的 `contract_risk_rules`(按合同类型,可回落 `general_procurement`)。
|
||||
- 可选 LLM 增强:不得无证据撤销或降低确定性风险等级。
|
||||
|
||||
**通用**
|
||||
|
||||
- 清洗失败或正文不可解析 → 审查失败,明确提示上传可解析文件(Word / 可检索 PDF)。
|
||||
- PDF 发现尽量带页码/坐标;无法定位时不得伪造文字坐标;标注下载在无锚点时可回退原 PDF 副本。
|
||||
|
||||
---
|
||||
|
||||
## 5. 正向场景(Happy Path)
|
||||
|
||||
> 写法:前置条件 → 操作步骤 → 期望结果。可直接拆为测试用例。
|
||||
|
||||
### HP-01 比对审核成功(Word/可检索 PDF)
|
||||
|
||||
1. **前置**:用户有 Agent 权限;准备我方原合同 A、卖方回传 B(可抽取正文)。
|
||||
2. **步骤**:选「合同比对」→ 上传 A 为原合同 → 附件上传 B → 发送。
|
||||
3. **期望**:
|
||||
- 出现用户气泡与结果卡;拿到 `review_no`;
|
||||
- 进度轨道逐步推进至完成;
|
||||
- 成功态展示改动项与/或风险统计;
|
||||
- 可下载 docx 报告;若为 PDF 可尝试标注下载;
|
||||
- Admin 历史可见该条,`template_source=user_upload`。
|
||||
|
||||
### HP-02 单份审核成功
|
||||
|
||||
1. **前置**:启用至少一条风险规则或五问可命中的合同文本。
|
||||
2. **步骤**:选「单份审核」→ 上传一份待审合同 → 发送。
|
||||
3. **期望**:结果卡成功;独立风险项或通过项符合规则;可下载报告;历史 `template_source=none`。
|
||||
|
||||
### HP-03 历史还原进行中任务
|
||||
|
||||
1. **前置**:刚发起审查仍为 queued/running。
|
||||
2. **步骤**:刷新页面或切换会话再回来。
|
||||
3. **期望**:用户气泡仍在;结果卡恢复进度并继续轮询至终态。
|
||||
|
||||
### HP-04 无附件文字引导
|
||||
|
||||
1. **步骤**:不上传任何合同,输入「怎么做合同比对?」并发送。
|
||||
2. **期望**:不创建 `contract_reviews`;收到 Chatflow 引导回复。
|
||||
|
||||
### HP-05 管理员维护规则后影响单份审核
|
||||
|
||||
1. **前置**:Admin 新增/启用一条 `keyword_missing` 规则。
|
||||
2. **步骤**:用户单份上传一份故意缺该关键词的合同并审核。
|
||||
3. **期望**:结果中出现对应独立风险项。
|
||||
|
||||
### HP-06 管理员停用规则后不再命中
|
||||
|
||||
1. **前置**:将某规则停用(列表乐观更新为停用)。
|
||||
2. **步骤**:再审一份本应命中的合同。
|
||||
3. **期望**:该规则不再产生风险项。
|
||||
|
||||
### HP-07 模板库设默认与下载
|
||||
|
||||
1. **步骤**:上传启用模板 → 设为默认 → 下载文件。
|
||||
2. **期望**:仅一条默认;下载内容与上传一致。(Chat 比对不依赖此默认。)
|
||||
|
||||
### HP-08 审查历史筛选与下载
|
||||
|
||||
1. **前置**:存在多条不同模式/来源记录。
|
||||
2. **步骤**:按模式、来源、关键字筛选 → 打开详情 → 下载报告与原合同。
|
||||
3. **期望**:列表符合筛选;下载成功且需登录鉴权。
|
||||
|
||||
### HP-09 当事人字段抽取
|
||||
|
||||
1. **前置**:合同正文含「乙方/卖方」及「合同编号」。
|
||||
2. **步骤**:完成一次审核。
|
||||
3. **期望**:结果卡与历史展示抽取的供应商与 `contract_no`(请求未手填供应商时)。
|
||||
|
||||
---
|
||||
|
||||
## 6. 异向 / 异常场景(Negative Path)
|
||||
|
||||
### NP-01 比对缺文件
|
||||
|
||||
| 操作 | 期望 |
|
||||
|------|------|
|
||||
| 比对模式仅上传卖方回传、未上传我方原合同即发送 | 警告「需两份文件」类提示;**不**创建审查 |
|
||||
| 比对模式仅上传我方原合同、无卖方附件即发送 | 同上 |
|
||||
|
||||
### NP-02 多附件
|
||||
|
||||
| 操作 | 期望 |
|
||||
|------|------|
|
||||
| 附件区选择超过 1 份本地文档后发送 | 警告每次仅一份;阻止或不启动审查 |
|
||||
|
||||
### NP-03 不支持的文件类型
|
||||
|
||||
| 操作 | 期望 |
|
||||
|------|------|
|
||||
| 上传 exe/图片等非允许类型(若前端未拦截) | 上传或审查失败,有明确错误提示 |
|
||||
|
||||
### NP-04 无法解析正文
|
||||
|
||||
| 操作 | 期望 |
|
||||
|------|------|
|
||||
| 上传损坏文件、纯扫描且 OCR/清洗均失败 | 审查终态 `failed`;提示上传可解析 Word/可检索 PDF;不假装成功 |
|
||||
|
||||
### NP-05 审查超时(前端)
|
||||
|
||||
| 操作 | 期望 |
|
||||
|------|------|
|
||||
| 任务超过前端等待上限仍未终态 | 前端提示超时/仍可稍后在历史查看;后台 Job 可继续执行 |
|
||||
|
||||
### NP-06 无权限
|
||||
|
||||
| 操作 | 期望 |
|
||||
|------|------|
|
||||
| 未登录调用审查 API | 401 |
|
||||
| 普通用户访问 Admin 页/API | 拒绝 |
|
||||
| 用户 A 用 review_no 下载用户 B 的报告 | 拒绝(非本人) |
|
||||
|
||||
### NP-07 模板约束
|
||||
|
||||
| 操作 | 期望 |
|
||||
|------|------|
|
||||
| 删除默认模板 | 失败提示 |
|
||||
| 停用当前默认模板 | 失败,要求先设其他默认 |
|
||||
| 删除已被审查引用的模板 | 冲突错误,建议停用 |
|
||||
| 名称+版本重复创建 | 失败,唯一约束 |
|
||||
|
||||
### NP-08 规则校验
|
||||
|
||||
| 操作 | 期望 |
|
||||
|------|------|
|
||||
| 新建规则缺少编码/标题/分类/关键词/说明/建议 | 表单或接口校验失败 |
|
||||
| 新建重复编码 | 失败 |
|
||||
| 非法 risk_level / trigger_type / status | 失败 |
|
||||
|
||||
### NP-09 启停规则失败回滚
|
||||
|
||||
| 操作 | 期望 |
|
||||
|------|------|
|
||||
| 点击启用但接口失败 | 列表状态恢复为变更前;有错误提示;不闪整表 loading |
|
||||
|
||||
### NP-10 标注合同非 PDF
|
||||
|
||||
| 操作 | 期望 |
|
||||
|------|------|
|
||||
| 对非 PDF 审查请求标注合同下载 | 明确失败(仅 PDF 可用) |
|
||||
|
||||
### NP-11 LLM 增强失败(单份且开启)
|
||||
|
||||
| 操作 | 期望 |
|
||||
|------|------|
|
||||
| Dify/Workflow 超时或报错 | 确定性规则结果仍成功落库;不因 LLM 失败丢失主结论 |
|
||||
|
||||
### NP-12 纯噪声 Diff
|
||||
|
||||
| 操作 | 期望 |
|
||||
|------|------|
|
||||
| 两份合同仅空格/标点/换行差异 | 不产生实质改动项(或改动项为空);不误报高风险改稿 |
|
||||
|
||||
---
|
||||
|
||||
## 7. 非功能需求
|
||||
|
||||
| ID | 要求 |
|
||||
|----|------|
|
||||
| NFR-01 | 提交审查接口快速返回(接受任务),不因清洗/LLM 同步阻塞至完成 |
|
||||
| NFR-02 | 进度轮询间隔约 2s;步骤与百分比以后端为准,前端不虚构中间进度 |
|
||||
| NFR-03 | 四语言 i18n:zh-CN / zh-TW / en / th(Chat + Admin + 关键 error code) |
|
||||
| NFR-04 | 下载须带鉴权;禁止裸链无 Token 拉取 |
|
||||
| NFR-05 | 待审合同不写入企业正式知识库 Dataset |
|
||||
| NFR-06 | Job 可重试(实现侧最多有限次数);失败可追踪 |
|
||||
|
||||
---
|
||||
|
||||
## 8. 验收标准(测试可勾选)
|
||||
|
||||
- [ ] 比对必须两份文件,缺一不可发起。
|
||||
- [ ] 单份仅一份附件可发起。
|
||||
- [ ] 发起后有 review_no 与步骤进度,终态 success/failed。
|
||||
- [ ] 成功结果卡含改动/风险分区;待确认不计入风险统计;比对不展示 OCR 待确认主列表。
|
||||
- [ ] 报告 docx 可下载;PDF 标注下载行为符合「仅 PDF」。
|
||||
- [ ] 无附件文字不建审查。
|
||||
- [ ] Admin 三 Tab 可用;种子规则可编辑启停;模板删除/默认约束生效。
|
||||
- [ ] 历史可筛、可看、可下本人/管理员对应产物。
|
||||
- [ ] 不可解析文件失败提示清晰。
|
||||
- [ ] 四语言关键文案无硬编码中文遗漏(新建字符串)。
|
||||
|
||||
---
|
||||
|
||||
## 9. 修订记录
|
||||
|
||||
| 版本 | 说明 |
|
||||
|------|------|
|
||||
| v1.0 | 依据当前代码/UI、会话确认决策与既有补充需求整理;含正/异向场景与 I/O |
|
||||
| v1.1 | 去掉原「测试用例设计提示」「设计输入摘要」两节 |
|
||||
@@ -0,0 +1,450 @@
|
||||
# 采购合同审查 Agent — 技术文档
|
||||
|
||||
> 本文记录原同步 MVP。异步清洗、Dify 全面审核和结果治理的新方案见
|
||||
> [comprehensive-review-technical.md](comprehensive-review-technical.md),后续开发以新文档为准。
|
||||
|
||||
| 项目 | 说明 |
|
||||
|------|------|
|
||||
| 文档版本 | v0.4 |
|
||||
| 状态 | **已落地 MVP**(HXOPS 同步审查:规则 + Diff;可选 Dify Workflow 润色) |
|
||||
| 原型 | [docs/prototype/procurement-contract-review-prototype.html](../../prototype/procurement-contract-review-prototype.html) |
|
||||
| 读者 | 产品、研发、测试 |
|
||||
|
||||
> **主路径口径**:审查是 **Chat → HXOPS API(同步)**,不是 Chat → Dify Chatflow → Tool。Dify Chatflow 仅作无附件时的文字引导;LLM 仅作可选后处理增强。
|
||||
|
||||
> **设备表 OCR 容错**:合同对比仅在两侧都是纯设备表表头、且较短表头为较长表头的有序子集时,忽略因 OCR 截断造成的差异;设备名称、品牌、型号、数量、单价、总价等业务字段值一旦存在或变化,仍作为真实商业差异保留。
|
||||
|
||||
> **供应商名称 OCR 容错**:仅当双方抽取的供应商名称高度相似时,忽略签章区或页眉中无业务字段、且只是共同供应商名称短前缀的单边 OCR 截断片段;任一供应商主体实际变化仍保留为差异。
|
||||
|
||||
---
|
||||
|
||||
## 1. 目标与边界
|
||||
|
||||
### 1.1 目标
|
||||
|
||||
在 HXOPS 工作台提供**单一 Agent「采购合同审查」**(`agent_code=procurement_contract_review`),支持两种模式:
|
||||
|
||||
| 模式 | 用户行为 | 产出 |
|
||||
|------|----------|------|
|
||||
| **合同比对** `compare` | 上传我方原合同 + 卖方回传合同 | 段落 Diff + 风险分级 + 报告 |
|
||||
| **单份审核** `solo` | 仅上传待审合同 | 按风险规则表做完备性/缺项检查 + 报告 |
|
||||
|
||||
每次审查对应**一份合同、一条 `contract_reviews` 记录**;结果可下载;管理员维护模板库、风险红线规则并查看历史。
|
||||
|
||||
### 1.2 边界(当前不做)
|
||||
|
||||
- 不使用 `ScheduleTask` / `ScheduleRun`,不做批次/cron
|
||||
- 无人工确认闸门(`human_confirm: false`)
|
||||
- 不回写 OA / SRM / 法务;不自动改合同
|
||||
- 会话输入区**不展示企业知识库与模板库入口**;比对基准只来自本次上传的我方原合同
|
||||
- 审查不经 Dify Tool 鉴权链路;会话 API 使用用户 JWT
|
||||
|
||||
### 1.3 与现有能力关系
|
||||
|
||||
| 复用 | 不照搬 |
|
||||
|------|--------|
|
||||
| Agent Registry / Catalog、`file_upload`、通用 `FileAsset` 上传下载 | 其它业务域的状态机 / 人工确认 / ScheduleRun |
|
||||
| Admin 模块形态、错误 envelope、`requestJson`、四语言 i18n | — |
|
||||
| 可选:`DifyService.run_workflow_streaming` 做条款润色 | Chatflow 编排审查全流程 |
|
||||
|
||||
---
|
||||
|
||||
## 2. 产品交互(已实现)
|
||||
|
||||
### 2.1 会话(Chat)
|
||||
|
||||
```text
|
||||
[ 合同比对 | 单份审核 ] ← 输入框上方
|
||||
我方原合同 chip / 卖方回传合同 chip
|
||||
[🎤 📎 | 上传卖方回传合同 | 上传我方原合同 | 输入… | 发送]
|
||||
```
|
||||
|
||||
| 行为 | 实现 |
|
||||
|------|------|
|
||||
| 合同比对 | 必须上传我方原合同与卖方回传合同;不展示模板下拉,也不自动使用库内默认模板 |
|
||||
| 单份审核 | 隐藏我方原合同上传,仅按一份待审合同和启用中的 `contract_risk_rules` 检查 |
|
||||
| 发送 | 有本地附件时拦截 SSE:上传 FileAsset → `POST /api/procurement-contract/reviews` → 结果卡 |
|
||||
| 无附件文字 | 走该 Agent 绑定的 Dify Chatflow(引导用,不执行审查) |
|
||||
| 结果 | `type=procurement-contract-review` 结果卡:风险统计、条款对照、可选合同编号/供应商;下载报告默认 **docx** |
|
||||
| 多附件 | 卖方回传合同超过一份时阻止发送,要求移除多余文件 |
|
||||
| 历史 | 助手结果卡落库时带上用户 `query`,`loadHistory` 后用户气泡可还原 |
|
||||
|
||||
Chat 不支持口头指定或选择模板版本;模板库仅保留管理与历史兼容用途。
|
||||
|
||||
### 2.2 管理端
|
||||
|
||||
路由:**`/admin/procurement-contract`**(单页三 Tab)。
|
||||
|
||||
| Tab | 职责 |
|
||||
|-----|------|
|
||||
| **模板库** | 上传、编辑元数据、启停、设默认、下载文件、删除;已被审查历史引用的模板仅可停用,不可删除 |
|
||||
| **风险规则** | 列表/状态筛选;新增、编辑、启停、删除;迁移种子规则**默认保留且可改**(编辑时 `code` 只读);启停为乐观更新,避免整表闪烁 |
|
||||
| **审查历史** | 筛选(模式/来源/关键字/风险等);列含审查编号、合同编号、供应商;详情抽屉;下载报告 / 待审合同 / 所用模板 |
|
||||
|
||||
规则弹窗:`max-h-[92vh]`,标题与底栏固定,表单体内部滚动;两列表单用 `grid` + `gap`(避免与 `space-y` 叠用导致字段错位)。
|
||||
|
||||
---
|
||||
|
||||
## 3. 总体架构(当前)
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
subgraph Chat
|
||||
UI[专用 composer]
|
||||
Card[结果卡]
|
||||
Guide[Dify Chatflow · 无附件引导]
|
||||
end
|
||||
subgraph HXOPS
|
||||
FA[FileAsset API]
|
||||
API["/api/procurement-contract"]
|
||||
Admin["/api/admin/procurement-contract"]
|
||||
Svc[review_service]
|
||||
Analyze[analyze · 规则/Diff]
|
||||
Party[当事人字段抽取]
|
||||
LLM[llm_enhancer · 可选]
|
||||
Tpl[(contract_templates)]
|
||||
Rules[(contract_risk_rules)]
|
||||
Rev[(contract_reviews)]
|
||||
Store[文件存储]
|
||||
end
|
||||
UI -->|有附件| FA
|
||||
FA --> API
|
||||
API --> Svc
|
||||
Svc --> Party
|
||||
Svc --> Analyze
|
||||
Analyze --> Rules
|
||||
Svc --> LLM
|
||||
LLM -.->|PROCUREMENT_CONTRACT_LLM_*| WF[Dify Workflow]
|
||||
Svc --> Rev
|
||||
Svc --> Tpl
|
||||
FA --> Store
|
||||
Svc --> Card
|
||||
UI -->|无附件文字| Guide
|
||||
Admin --> Tpl
|
||||
Admin --> Rules
|
||||
Admin --> Rev
|
||||
```
|
||||
|
||||
**原则**:
|
||||
|
||||
1. **HXOPS 是审查记录、模板库、风险规则的真相源。**
|
||||
2. **确定性分析先跑完**(规则缺项 / 段落 Diff),再可选 LLM 润色;润色失败不影响主结果落库。
|
||||
3. LLM **不得删除规则发现项,不得把风险降到低于规则等级。**
|
||||
|
||||
---
|
||||
|
||||
## 4. 数据模型
|
||||
|
||||
迁移:
|
||||
|
||||
1. `a1c2d3e4f5b6_add_contract_review_tables`
|
||||
2. `b2c4d6e8f0a1_extend_contract_review_rules`(建规则表 + **种子红线**)
|
||||
3. `c3d5e7f9a1b2_add_contract_review_contract_no`(`contract_reviews.contract_no` 索引字段)
|
||||
|
||||
模型:`backend/app/models/contract.py`。
|
||||
|
||||
### 4.1 `contract_templates`
|
||||
|
||||
| 字段 | 说明 |
|
||||
|------|------|
|
||||
| id, name, version | `UNIQUE(name, version)` |
|
||||
| file_asset_id, file_name | 指向 `file_assets` |
|
||||
| contract_type | 默认 `general_procurement` |
|
||||
| applicable_scope, change_note, remark | 可选说明 |
|
||||
| status | `enabled` / `disabled` |
|
||||
| is_default | 启用中同时最多一个默认 |
|
||||
| created_by / updated_by / timestamps | |
|
||||
|
||||
### 4.2 `contract_reviews`
|
||||
|
||||
| 字段 | 说明 |
|
||||
|------|------|
|
||||
| review_no | 系统审查编号,如 `CR-YYYYMMDD-XXXX`(**不是**业务合同编号) |
|
||||
| agent_id, user_id, chat_log_id? | 可关联会话 |
|
||||
| review_mode | `compare` \| `solo` |
|
||||
| status | `pending` \| `running` \| `success` \| `failed` |
|
||||
| contract_asset_id, contract_file_name | 待审合同 |
|
||||
| supplier_name | 供应商;请求未传时可由正文抽取(乙方/卖方等) |
|
||||
| contract_no | **业务合同编号**;从正文抽取(合同编号/合同号/Contract No. 等) |
|
||||
| contract_type | 合同类型,默认 `general_procurement` |
|
||||
| template_id?, template_source | 历史兼容字段;新 Chat 比对固定 `template_id=null`、`template_source=user_upload` |
|
||||
| template_asset_id?, template_name? | 历史兼容字段;新 Chat 比对保存我方原合同资产与文件名 |
|
||||
| total_change_count, high/medium/low_risk_count | 摘要计数 |
|
||||
| summary_json, clauses_json | 结构化结果(含可选 LLM 字段、可读性标记等) |
|
||||
| report_text | 报告正文(下载 txt/docx 由此生成) |
|
||||
| error_message, started_at, finished_at, timestamps | |
|
||||
|
||||
**不建**:`schedule_runs` 绑定、人工确认 checkpoint。
|
||||
|
||||
### 4.3 `contract_risk_rules`
|
||||
|
||||
| 字段 | 说明 |
|
||||
|------|------|
|
||||
| code | 唯一规则编码(创建后界面编辑不可改) |
|
||||
| contract_type, clause_category, title | 分类与展示 |
|
||||
| keywords | JSON 字符串数组 |
|
||||
| trigger_type | `keyword_missing` \| `keyword_present` |
|
||||
| risk_level | `high` \| `medium` \| `low` |
|
||||
| risk_hint, suggestion, negotiation_text | 提示文案 |
|
||||
| status, sort_order | 启停与排序 |
|
||||
|
||||
迁移种子一批通用采购红线(付款/验收/违约/管辖/质保等)。
|
||||
**单份**:全量启用规则做缺项/出现检查。
|
||||
**比对**:以 Diff 段为主;规则关键词可参与 Diff 段风险抬升,**不**等同于单份整份红线扫缺。
|
||||
|
||||
### 4.4 Agent Catalog
|
||||
|
||||
`catalog_manifest.yaml` → `procurement_contract_review`:
|
||||
|
||||
| 字段 | 值 |
|
||||
|------|-----|
|
||||
| `runtime_provider_default` | `dify` |
|
||||
| `conversation_mode_default` | `task_chat` |
|
||||
| `forced_capabilities` | `file_upload: true`,`human_confirm: false` |
|
||||
| `handler_config_schema` | `{}`(无 Schedule 绑定) |
|
||||
|
||||
Admin 应用管理需绑定 **Chatflow**(引导);可选 **Workflow** 润色可与 Chatflow 使用不同 Dify 应用(见 §7)。
|
||||
|
||||
---
|
||||
|
||||
## 5. API
|
||||
|
||||
统一 envelope:`{ success, data | error, request_id }`。会话侧:用户 JWT;管理端:`require_admin`。
|
||||
|
||||
### 5.1 会话 API `/api/procurement-contract`
|
||||
|
||||
| 方法 | 路径 | 说明 |
|
||||
|------|------|------|
|
||||
| GET | `/templates` | 历史兼容的启用模板列表;当前 Chat UI 不调用 |
|
||||
| POST | `/reviews` | 发起审查(同步完成,含详情) |
|
||||
| GET | `/reviews` | 本人最近审查 |
|
||||
| GET | `/reviews/<review_no>` | 本人详情 |
|
||||
| GET | `/reviews/<review_no>/report` | 本人报告;`?format=docx`(会话默认)或 `txt` |
|
||||
|
||||
**POST `/reviews` body(主要字段)**
|
||||
|
||||
```json
|
||||
{
|
||||
"review_mode": "compare | solo",
|
||||
"contract_asset_no": "必填",
|
||||
"original_contract_asset_no": "compare 必填,solo 为空",
|
||||
"contract_type": null,
|
||||
"supplier_name": null,
|
||||
"agent_id": null,
|
||||
"chat_log_id": null
|
||||
}
|
||||
```
|
||||
|
||||
文件先经 `/api/files/assets` 上传拿到 `asset_no`。
|
||||
|
||||
### 5.2 管理 API `/api/admin/procurement-contract`
|
||||
|
||||
| 资源 | 路径 |
|
||||
|------|------|
|
||||
| 模板 | `GET/POST /templates`;`PATCH/DELETE /templates/<id>`;`GET /templates/<id>/file` |
|
||||
| 规则 | `GET/POST /rules`;`PATCH/DELETE /rules/<id>` |
|
||||
| 历史 | `GET /reviews`(mode/source/status/keyword/contract_type/supplier_name/contract_no/risk/date…);`GET /reviews/<id>` |
|
||||
| 下载 | `GET /reviews/<id>/report`(txt/docx);`.../contract`;`.../template-file` |
|
||||
|
||||
### 5.3 前端落点
|
||||
|
||||
| 模块 | 路径 |
|
||||
|------|------|
|
||||
| Chat 编排 | `frontend/src/features/chat/composables/useProcurementContractChat.ts` |
|
||||
| 结果卡 | `.../chat/components/messages/ContractReviewResultCard.vue` |
|
||||
| Admin 页 | `.../admin/modules/procurement-contract/ProcurementContractPage.vue` |
|
||||
| 风险规则面板 | `.../procurement-contract/components/ContractRiskRulesPanel.vue` |
|
||||
| API 客户端 | `.../admin/api/procurement-contract.api.ts` |
|
||||
|
||||
---
|
||||
|
||||
## 6. 审查流水线
|
||||
|
||||
实现入口:`review_service.start_review`(**同步**,请求内 `running → success|failed`)。
|
||||
|
||||
### 6.1 公共步骤
|
||||
|
||||
```text
|
||||
[STEP 1] 解析卖方回传合同 FileAsset;compare 额外解析本次上传的我方原合同
|
||||
[STEP 2] 落库 contract_reviews(status=running),标记资产已引用
|
||||
[STEP 3] extract_text_from_bytes(txt/md/docx/pdf 尽力;扫描件/旧 .doc 弱)
|
||||
[STEP 4] extract_party_fields:乙方/卖方 → supplier_name;合同编号 → contract_no
|
||||
[STEP 5] analyze_solo 或 analyze_compare(含 PDF 不可读防护)
|
||||
[STEP 6] llm_enhancer.enhance_review_result(可跳过/失败仍保留规则结果)
|
||||
[STEP 7] 写 summary/clauses/report/风险计数与当事人字段,终态
|
||||
[STEP 8] 前端结果卡;报告按需下载(Chat 默认 docx)
|
||||
```
|
||||
|
||||
### 6.2 单份 `analyze_solo`
|
||||
|
||||
- 加载启用中的 `contract_risk_rules`(按 `contract_type`,可回落通用类型)
|
||||
- `keyword_missing` / `keyword_present` → `missing` / `pass` + 风险等级与建议
|
||||
|
||||
### 6.3 比对 `analyze_compare`
|
||||
|
||||
- 双方文本按段落切分,`difflib.SequenceMatcher` 取非 equal 段
|
||||
- 变更类型:`insert` / `delete` / `modify`
|
||||
- Diff 段用规则关键词与内置敏感词抬升 `high` / `medium` / `low`
|
||||
- 正文不可读时:抑制不可靠 Diff 摘录,并在 summary 中标记(结果卡展示提示)
|
||||
- **限制**:不跑「整份合同相对规则表的全量缺项扫」;与单份覆盖不完全等价
|
||||
|
||||
### 6.4 文本抽取(MVP)
|
||||
|
||||
| 格式 | 能力 |
|
||||
|------|------|
|
||||
| txt / md / csv | UTF-8 解码 |
|
||||
| docx | python-docx 或 zip+XML 回退 |
|
||||
| pdf | 可选 pdfplumber / pypdf;乱码/占位文本有可读性校验 |
|
||||
| 其它 / .doc | 弱回退或占位提示 |
|
||||
|
||||
### 6.5 同步与超时
|
||||
|
||||
当前为同步 API。开启 LLM 润色时读超时默认 **120s**,网关/前端需留意。长合同异步进度属后续迭代。
|
||||
|
||||
---
|
||||
|
||||
## 7. Dify 相关配置
|
||||
|
||||
### 7.1 Chatflow(Agent 绑定,引导)
|
||||
|
||||
用途:用户**未上传合同**时的说明、引导。
|
||||
**不负责**发起审查、落库、出 Diff。
|
||||
|
||||
建议 Start 变量:`query`、`files`、`agent_runtime_context`(平台统一约定)。
|
||||
结果由前端结果卡渲染;Chatflow 勿编造审查编号或条款结论。
|
||||
|
||||
### 7.2 Workflow(可选润色)
|
||||
|
||||
模块:`llm_enhancer.py`。
|
||||
|
||||
| 变量 | 默认 / 说明 |
|
||||
|------|-------------|
|
||||
| `PROCUREMENT_CONTRACT_LLM_ENABLED` | `false`;`true` 才调用 |
|
||||
| `PROCUREMENT_CONTRACT_LLM_AGENT_ID` | 优先:HXOPS Agent 主键(须有 API Key) |
|
||||
| `PROCUREMENT_CONTRACT_LLM_DIFY_APP_ID` | 或按 app_id 查 Agent |
|
||||
| `PROCUREMENT_CONTRACT_LLM_DIFY_API_KEY` / `_BASE` | 或直连 Workflow(不入库 Agent;Base 可回落 `DIFY_API_BASE`) |
|
||||
| `PROCUREMENT_CONTRACT_LLM_CONNECT_TIMEOUT_SECONDS` | `5` |
|
||||
| `PROCUREMENT_CONTRACT_LLM_READ_TIMEOUT_SECONDS` | `120` |
|
||||
|
||||
输入概要:`review_no`、`review_mode`、`contract_type`、`template_name`、`findings_json`、`instruction`。
|
||||
期望输出 JSON:`items[]` 含 `professional_reason` / `professional_suggestion` / `negotiation_text` / `model_risk_level` / `confidence`;**`model_risk_level` 不得低于规则等级**。
|
||||
|
||||
默认 **关闭**;关闭时审查完全本地启发式。
|
||||
|
||||
### 7.3 尚未提供
|
||||
|
||||
- `docs/openapi/procurement_contract_tools*.json` 画布导入包
|
||||
- Dify Tool 专用鉴权(当前会话 API 仅 JWT 用户)
|
||||
|
||||
---
|
||||
|
||||
## 8. 前端范围与验收
|
||||
|
||||
| 模块 | 状态 |
|
||||
|------|------|
|
||||
| Chat 专用 composer + 结果卡 + 报告下载(docx) | ✅ |
|
||||
| Admin 模板库 + 历史 + 鉴权下载 | ✅ |
|
||||
| 风险规则 Admin UI(种子可编辑;启停乐观更新) | ✅ |
|
||||
| 当事人字段展示(合同编号 / 供应商) | ✅ |
|
||||
| i18n 四语言 | ✅ |
|
||||
| 用户气泡 + 结果卡历史还原 | ✅ |
|
||||
|
||||
**核心验收**
|
||||
|
||||
- [x] 模式切换在输入框上方;合同比对展示两个语义明确的上传入口,单份隐藏我方原合同入口
|
||||
- [x] 附件发送出结果卡;报告可下载;历史含模式/比对基准来源/合同编号/供应商
|
||||
- [x] 我方原合同不入模板库,历史兼容保存为 `template_source=user_upload`
|
||||
- [x] 规则可视化配置(种子保留可编辑)
|
||||
- [ ] 比对模式与单份红线规则对齐补全
|
||||
- [ ] OCR / 扫描 PDF 可靠抽取
|
||||
|
||||
---
|
||||
|
||||
## 9. 分期
|
||||
|
||||
### Phase 1 — MVP(当前)
|
||||
|
||||
1. ✅ 表结构:`contract_templates` / `contract_reviews` / `contract_risk_rules` / `contract_no`
|
||||
2. ✅ 模板库 Admin + 风险规则 Admin + Chat 双模式 + 同步审查 + 结果卡
|
||||
3. ✅ 历史列表/详情/下载;当事人字段抽取
|
||||
4. ✅ 可选 Dify Workflow 润色(环境开关)
|
||||
5. ✅ Catalog 注册;无人审、无 ScheduleRun、无企业 KB 入口
|
||||
|
||||
### Phase 2
|
||||
|
||||
- 比对模式叠加整份红线缺项检查;按合同类型更细的规则运营
|
||||
- 异步审查 + 进度展示;OCR 管道
|
||||
- Workspace 本人只读历史;口头指定模板版本
|
||||
- 报告入 KB / 会话追问(若产品需要)
|
||||
- OpenAPI + Tool 鉴权(若审查改由画布触发)
|
||||
|
||||
### Phase 3(另立需求)
|
||||
|
||||
- 人工审核流、系统回写、批次
|
||||
|
||||
---
|
||||
|
||||
## 10. 关键代码索引
|
||||
|
||||
| 层 | 路径 |
|
||||
|----|------|
|
||||
| 模型 | `backend/app/models/contract.py` |
|
||||
| 服务 | `backend/app/services/procurement_contract/`(`review_service` / `analyze` / `rule_service` / `template_service` / `llm_enhancer`) |
|
||||
| API | `backend/app/api/procurement_contract_tools.py`、`backend/app/api/admin/procurement_contract.py` |
|
||||
| Catalog | `backend/app/services/agent_registry/data/catalog_manifest.yaml` |
|
||||
| 配置 | `backend/app/core/config/settings.py` → `PROCUREMENT_CONTRACT_LLM_*` |
|
||||
| Chat | `useProcurementContractChat.ts`、`ContractReviewResultCard.vue` |
|
||||
| Admin | `ProcurementContractPage.vue`、`components/ContractRiskRulesPanel.vue` |
|
||||
|
||||
---
|
||||
|
||||
## 11. 决策冻结
|
||||
|
||||
| # | 决策 | 结论 |
|
||||
|---|------|------|
|
||||
| 1 | Agent 数量 | **一个**,双模式 |
|
||||
| 2 | 批次 | **不做** ScheduleRun |
|
||||
| 3 | 人审 | **不做** |
|
||||
| 4 | 模板 | Admin 库 + 会话临时上传 |
|
||||
| 5 | 会话 KB | **关闭** |
|
||||
| 6 | 审查编排 | **HXOPS 同步 API**;非 Chatflow 编排 |
|
||||
| 7 | LLM | **可选 Workflow 润色**;默认关;规则结果优先 |
|
||||
| 8 | 历史 | Admin 独立页(三 Tab),非排程 runs |
|
||||
| 9 | 红线规则 | 迁移种子入库 + Admin 可配置;种子可编辑 |
|
||||
|
||||
---
|
||||
|
||||
## 12. 文档同步
|
||||
|
||||
- 本文件为研发权威;状态摘要见 [README.md](README.md)、[docs/funclist.md](../../funclist.md)
|
||||
- 涉及需求变化时同步 `docs/demand.md`
|
||||
# 7. 默认模板比对区域(2026-07-24)
|
||||
|
||||
Admin 模板新增 `comparison_region_config`,包含 `metadata_fields`、`body_start_anchors`、
|
||||
`body_end_anchors`、`signature_terms`、`attachment_start_anchors` 和固定策略
|
||||
`attachment_policy=page_count_only`。模板文件只用于维护和识别预览,Chat 实际比对基准始终是用户本次上传的我方原合同。
|
||||
|
||||
compare Worker 对两份文件取得逐页文本后划分 `metadata/body/signature/attachments`。只有 `body`
|
||||
进入原有 `analyze_compare`;抬头可保留在 `summary_json.metadata_comparison` 供内部审计,但 Chat 不展示;签章整段排除;附件从识别到的
|
||||
标题页开始计数并写入 `summary_json.attachment_comparison`。附件页数提示不进入 `clauses_json`、
|
||||
`total_change_count` 或风险统计。
|
||||
|
||||
PDF 保留原始分页;Word 和旧 `.doc` 通过现有 LibreOffice 能力转 PDF 后提取分页。两侧任一文件的正文
|
||||
起止锚点或分页不可用时,`comparison_scope.status=fallback`,执行原全文比对并在结果卡提示区域配置未生效。
|
||||
|
||||
若 PDF 没有原生文本层但 MinerU 返回可读的完整 OCR,系统使用该 OCR 作为单个逻辑页识别正文起止与签署区,
|
||||
使正文区域规则仍可生效;逻辑页不作为物理附件页计数依据。
|
||||
|
||||
发生回退时,Worker 会以 `review_no` 输出 `comparison region fallback` warning;审查结果的
|
||||
`summary_json.comparison_scope.diagnostics` 同时保留双方文件的分页文本可用性、正文起止锚点及页码、
|
||||
签署词、附件锚点和 `fallback_reason`,便于区分扫描件 OCR 分页缺失与配置锚点不匹配。
|
||||
|
||||
正文 Diff 另设短 OCR 乱码门禁:只对单侧新增/删除的短片段生效;当片段缺少合同关键词、
|
||||
字段标签、金额期限、数量单位或完整型号,并呈现少量汉字夹杂多个短拉丁/数字碎片时,
|
||||
计入 `comparison_quality.ignored_ocr_noise`,不写入 `clauses_json`。两侧修改及可识别的金额、
|
||||
期限、型号、功率和数量仍按正常差异处理。
|
||||
|
||||
双合同对比按字符变化位置附近的业务对象重新分类,避免同句背景词抢占类别(例如“质保款”
|
||||
句中的“6 个月→12 个月质保期”归入 warranty,而非 payment)。对比结果的标题、说明和下载
|
||||
报告由确定性 Diff 生成;Admin 风险规则只提供风险等级参考,不覆盖标题,也不输出建议和
|
||||
沟通话术。下载文档使用“合同差异对比报告”,逐项列出我方原文、回传内容和变化类型。
|
||||
@@ -104,6 +104,24 @@
|
||||
| 检核报告同步知识库 | 已实现 | 检核 success / partial_failed 且生成 Excel 后同步到所选知识库分组 |
|
||||
| 多 Agent 共用 Chatflow | 已实现 | RoHS / MSDS 等 Agent 共用同一 Dify Chatflow,`task_id` 由 Agent extra_config 注入 |
|
||||
|
||||
### 采购合同审查
|
||||
|
||||
| 功能项 | 状态 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| 实现方案(双模式 Agent) | 已文档化 | [docs/features/procurement-contract/technical.md](features/procurement-contract/technical.md)(v0.4,与代码对齐) |
|
||||
| HTML 原型 | 已文档化 | [docs/prototype/procurement-contract-review-prototype.html](prototype/procurement-contract-review-prototype.html) |
|
||||
| 异步全面审核方案 | 已实现基础链路 | [全面审核技术方案](features/procurement-contract/comprehensive-review-technical.md):知识库清洗复用、通用 Job/Worker、条款结构化、Diff/整份红线、Dify 独立扫描、证据校验与结果合并 |
|
||||
| Dify Workflow 全面法律审核 | 已实现(需配置开启) | 接收 `clean_text/clauses_json/findings_json`,兼容 `items/new_items`;Dify 失败降级保留确定性结果 |
|
||||
| Admin 模板库 + 风险规则 + 审查历史 | 已实现 | `/admin/procurement-contract`(三 Tab);种子红线可界面编辑/启停/增删;启停乐观更新;历史含供应商与合同编号 |
|
||||
| OCR 噪声门禁与采购重点策略 | 已实现增强版 | 清除分页噪声和正文短乱码新增项;支持圈号数字、中文“千分之五”和常见 OCR 数字归一;保留金额、期限、型号、功率和数量等合法短文本;不确定日期/比例转待确认且不计正式风险;付款、交期、整机质保、管辖和逾期交付按事实判断 |
|
||||
| 条款层级分类与 Diff 保真 | 已实现增强版 | 子条款继承父级业务类别,标题优先于正文偶发词;同类别不同事实修改分别保留,仅对完全相同证据去重 |
|
||||
| 双合同差异专用报告 | 已实现 | 按实际变化位置分类,逐项输出我方原文、回传内容及新增/删除/修改类型;风险规则仅提供等级参考,不覆盖差异标题或生成沟通话术 |
|
||||
| LLM 证据化纠错 | 已实现 | 模型可对确定性项返回 confirm/reject/uncertain;仅真实原文证据且置信度不低于 0.8 时允许撤销误报 |
|
||||
| PDF 原文证据锚定与标注副本 | 已实现 | 文本型 PDF 保存页码、坐标并高亮;扫描 PDF 按 OCR 分页正文在对应原页添加批注意见;Chat 成功审核的 PDF 始终展示下载入口,未定位项不伪造文字坐标 |
|
||||
| 合同审查结果分区展示 | 已实现 | 顶部统计改动项与高中低风险;正文互斥拆分合同改动项、独立风险项、待确认项;风险原文与修改建议分列展示 |
|
||||
| Chat 双模式 composer + 结果卡 | 已实现 | 合同比对固定上传“我方原合同 + 卖方回传合同”;单份审核上传一份待审合同;进行中展示七步进度轨道并高亮当前阶段;结果卡展示风险统计与条款对照,OCR 待确认按关键业务主题聚合,报告默认 docx |
|
||||
| 合同当事人字段抽取 | 已实现 | 从对方合同正文识别乙方/卖方 → 供应商、合同编号 → `contract_no`,写入审查记录与下载报告 |
|
||||
|
||||
### RoHS 文件检核(实例)
|
||||
|
||||
| 功能项 | 状态 | 说明 |
|
||||
@@ -534,3 +552,10 @@
|
||||
| 目录展开/折叠与子应用点击 | 已实现 | Chat 侧边栏/移动端 Agent 切换器将目录渲染为树形节点;目录可点击,展开后成员应用也可点击并进入各自 Dify 问答。 |
|
||||
| 聚合 Chatflow 上下文注入 | 已实现 | 聊天时向 Dify inputs 注入成员应用 ID、名称、Dify App ID 与分类等元数据。 |
|
||||
| 多子 Agent 并行召回与答案融合 | 未纳入本期 | 当前由目录 Agent 对应的 Dify Chatflow 基于注入元数据完成聚合问答。 |
|
||||
# 采购合同审查功能增量(2026-07-24)
|
||||
|
||||
- [x] Admin 模板比对区域配置、V4 默认恢复与识别预览
|
||||
- [x] 默认启用模板区域规则自动应用于 Chat 双文件比对
|
||||
- [x] 抬头区域排除且不展示、正文限定比对、签章排除
|
||||
- [x] 附件仅提示页数变化且不计入差异/风险统计
|
||||
- [x] 锚点或分页失败时全文比对安全回退提示
|
||||
@@ -77,3 +77,7 @@
|
||||
4. 文件检核结果供品质人员参考,SRM 等源系统中的审核/驳回操作仍须按既有流程手工完成。
|
||||
|
||||
请各部门按本公告执行,如需新增 Agent 能力,请提交需求至平台管理员。
|
||||
|
||||
---
|
||||
|
||||
研发同事专项说明(「研发赋能知识库」及下属子库)见:[研发知识库使用说明](./rd_knowledge_base_usage.md)。
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -7,15 +7,17 @@
|
||||
|
||||
本次更新亮点:
|
||||
|
||||
1. 员工培训 Agent:新增新人入职与员工培训闭环,可在对话中进入培训/考试工作区,支持学习、答题、交卷结算;管理员与 HR 可查看培训相关统计。
|
||||
1. 研发知识库上线:新增「研发赋能」聚合入口,覆盖研发专利、研发培训、研发标准、研发流程、研发作业规范、研发知识等子 Agent,可按主题检索专利、培训、标准、流程与作业规范等研发资料。
|
||||
|
||||
2. 设备维保助手 Agent:新增设备维保智能助手,可识别维保相关意图,协助查询设备与维保信息。
|
||||
2. 员工培训 Agent:新增新人入职与员工培训闭环,可在对话中进入培训/考试工作区,支持学习、答题、交卷结算;管理员与 HR 可查看培训相关统计。
|
||||
|
||||
3. 固资管理 Agent:支持资产履历直达预览与下载,Excel 预览体验优化,连续查询更稳定。
|
||||
3. 设备维保助手 Agent:新增设备维保智能助手,可识别维保相关意图,协助查询设备与维保信息。
|
||||
|
||||
4. 货代发货 Agent:支持重新上传发货通知、批量自动处理与任务重试;新增库存快照与导出能力,批次任务跟踪更清晰。
|
||||
4. 固资管理 Agent:支持资产履历直达预览与下载,Excel 预览体验优化,连续查询更稳定。
|
||||
|
||||
5. 其它优化:开启语音输入;意见反馈可同步通知企业微信;文件检核进度展示更直观;知识库上传与 PDF(含图文 OCR)同步更可靠;页面加载与后台管理体验持续优化。
|
||||
5. 货代发货 Agent:支持重新上传发货通知、批量自动处理与任务重试;新增库存快照与导出能力,批次任务跟踪更清晰。
|
||||
|
||||
6. 其它优化:开启语音输入;意见反馈可同步通知企业微信;文件检核进度展示更直观;知识库上传与 PDF(含图文 OCR)同步更可靠;页面加载与后台管理体验持续优化。
|
||||
|
||||
————————————————————
|
||||
【面向开发者】
|
||||
@@ -23,20 +25,22 @@
|
||||
|
||||
本次更新亮点:
|
||||
|
||||
1. 员工培训:完成培训闭环与管理配置;培训工作区考试流转(交卷后再结算);角色化常见问题;透传账号角色到 Dify;HR 统计问答兜底与布局交互修复;试题 PDF 导入判断题解析修复
|
||||
1. 研发知识库:上线研发赋能聚合应用及子 Agent(研发专利、研发培训、研发标准、研发流程、研发作业规范、研发知识);支持聚合应用成员勾选与分级展示
|
||||
|
||||
2. 设备维保:新增维保助手相关能力、意图识别、上下文设备解析及 Tool Key 配置
|
||||
2. 员工培训:完成培训闭环与管理配置;培训工作区考试流转(交卷后再结算);角色化常见问题;透传账号角色到 Dify;HR 统计问答兜底与布局交互修复;试题 PDF 导入判断题解析修复
|
||||
|
||||
3. 固资管理:对接 Dify 查询;支持资产履历预览与下载权限;修复连续问答、宽泛查询空字段与首轮会话中断等问题;快照同步增加账套字段与自动清理
|
||||
3. 设备维保:新增维保助手相关能力、意图识别、上下文设备解析及 Tool Key 配置
|
||||
|
||||
4. 货代发货:批量自动处理与任务重试;重新上传发货通知;库存快照管理与 RPA 批量导出;发货消息与轻量工作台逻辑优化;排程增加库存源描述与站点 ID、平台任务参数契约与动态选项
|
||||
4. 固资管理:对接 Dify 查询;支持资产履历预览与下载权限;修复连续问答、宽泛查询空字段与首轮会话中断等问题;快照同步增加账套字段与自动清理
|
||||
|
||||
5. 文件检核:进度卡片展示合格/不合格/人工判定笔数;持久化 chat_tool_runs;统一 agent_runtime_context 注入;增强可靠性元信息与错误分类
|
||||
5. 货代发货:批量自动处理与任务重试;重新上传发货通知;库存快照管理与 RPA 批量导出;发货消息与轻量工作台逻辑优化;排程增加库存源描述与站点 ID、平台任务参数契约与动态选项
|
||||
|
||||
6. 知识库:手册/设计类 PDF 保留图片并 OCR 写入 Markdown 再同步;上传提示与页面样式优化;清洗超时与 job 队列重构;旧 KB 任务入队兼容
|
||||
6. 文件检核:进度卡片展示合格/不合格/人工判定笔数;持久化 chat_tool_runs;统一 agent_runtime_context 注入;增强可靠性元信息与错误分类
|
||||
|
||||
7. 聊天与交互:开启语音输入;源文件解析不阻塞 SSE;修复生产源文件名兜底问题;智能体支持分级显示与聚合应用配置;意见反馈通知企业微信群
|
||||
7. 知识库:手册/设计类 PDF 保留图片并 OCR 写入 Markdown 再同步;上传提示与页面样式优化;清洗超时与 job 队列重构;旧 KB 任务入队兼容
|
||||
|
||||
8. 管理后台:Admin 列表排序过滤;聊天日志与应用权限优化;知识库配置布局调整
|
||||
8. 聊天与交互:开启语音输入;源文件解析不阻塞 SSE;修复生产源文件名兜底问题;智能体支持分级显示与聚合应用配置;意见反馈通知企业微信群
|
||||
|
||||
9. 工程与基建:后端 core/基础设施迁移与 models 拆分;admin/schedule 重构;push 前校验 migration multiple head;文件检核与货代相关单测补充
|
||||
9. 管理后台:Admin 列表排序过滤;聊天日志与应用权限优化;知识库配置布局调整
|
||||
|
||||
10. 工程与基建:后端 core/基础设施迁移与 models 拆分;admin/schedule 重构;push 前校验 migration multiple head;文件检核与货代相关单测补充
|
||||
+30
@@ -1,5 +1,27 @@
|
||||
# 智能HR请假管理技术架构
|
||||
|
||||
## 采购合同全面审核架构
|
||||
|
||||
采购合同审核采用异步混合架构:HXOPS 复用知识库文件清洗能力,生成独立合同 Markdown 与条款 JSON;通用 Worker 执行模板 Diff、整份红线检查和 Dify Workflow 全面法律扫描;HXOPS 最终完成证据校验、去重、风险定级、报告生成和审计落库。一次性合同不进入企业正式 Dify Dataset。完整方案见 [采购合同全面审核技术方案](features/procurement-contract/comprehensive-review-technical.md)。
|
||||
|
||||
Chat 合同比对的基准固定为用户本次上传的“我方原合同”,目标文件固定为“卖方回传合同”;前后端均不再选择或自动回退模板库默认文件。单份审核不需要比对基准。
|
||||
|
||||
模板 Diff 在进入风险分类前执行文本质量评分和 OCR 容错判断:条款对齐键使用 OCR 容错归一,明确数字或权利义务变化保留为实质修改;普通错字、抬头乱码和非关键版面噪声直接计入已忽略噪声,只有关键数字或权利义务无法确认时才进入待确认,并按付款、交期、验收、质保、违约和管辖等主题聚合。单份审核在可配置关键词规则之外增加采购重点确定性策略,首批覆盖付款、交期、质保、管辖及逾期交付每日 5‰ 违约金基线。
|
||||
|
||||
扫描或版面复杂的采购合同 PDF 在 `PROCUREMENT_CONTRACT_MINERU_API_URL` 已配置时优先经 MinerU `POST /file_parse` 解析,使用其 Markdown 的标题、表格和阅读顺序进行条款切分;MinerU 请求失败仍降级为现有 RapidOCR/知识库清洗链路,避免单一解析服务故障阻塞审核任务。
|
||||
|
||||
采购合同审核产物采用“本地运行缓存 + MinIO 私有归档”策略:任务完成后上传 `source/cleaned/result` 全部文件及带 SHA-256 的 manifest 到独立私有桶 `procurement-contract`,上传成功才删除本地 Docker 卷缓存;读取清洗正文时本地缺失会从 MinIO 按需恢复,保证下载标注合同和扫描 PDF 页码定位可继续使用。
|
||||
|
||||
合同域会先将 MinerU HTML 表格规范为单元格文本,并滤除签章区已在抬头出现的重复甲乙方信息,确保 HTML 版面属性和签章布局不被误判为合同条款改动。
|
||||
|
||||
对于文末签署日期与正文保固摘要等跨区错配,合同 Diff 以版面噪声处理;标注合同下载在无可定位风险时返回原合同副本,不因缺少锚点而向用户报错。
|
||||
|
||||
关键事实解析支持圈号数字、中文数字及“千分之五”等表达;无法可靠恢复的日期、金额和比例不直接触发正式风险,而是以 `validation_status=needs_review` 进入待确认。风险统计和下载报告均将待确认项与正式风险分开。条款结构采用父级标题继承与标题加权分类,同类别的不同事实变化不再合并丢失。
|
||||
|
||||
Dify 对已有确定性发现可返回 `confirm/reject/uncertain`。`reject` 必须引用存在于合同正文的直接反证,且置信度不低于 `0.8`;否则后端保持原确定性等级。该协议用于纠正规则误报,不允许无证据降级。
|
||||
|
||||
PDF 证据锚定优先使用现有 `pypdfium2` 逐字文本坐标定位,并由 `pypdf` 在原文件副本中写入标准 Highlight annotation;扫描 PDF 无文本层时,依据清洗 Markdown 的 `page-image-N` OCR 分页定位原页并添加 Text annotation,不伪造文字矩形。生成过程不修改原 FileAsset,锚定失败不阻断审核任务。
|
||||
|
||||
## 1. 架构目标
|
||||
|
||||
在现有 `hxops` 项目基础上,扩展一个可落地的智能 HR 请假管理架构,实现:
|
||||
@@ -1105,3 +1127,11 @@ Dify
|
||||
|
||||
- 聚合问答由目录 Agent 自己的 Dify Chatflow 实现。
|
||||
- HXOPS 当前只负责配置、权限、会话与上下文注入,不直接编排多个子 Agent 的回答。
|
||||
# 采购合同区域化比对技术补充(2026-07-24)
|
||||
|
||||
- `contract_templates.comparison_region_config` 使用 JSON 保存唯一默认启用模板的区域规则,由 Admin API 统一校验。
|
||||
- 审核 Worker 在 compare 模式独立读取默认模板配置,不修改审查记录原有的 `template_id/template_source`,也不读取模板库文件替换用户上传基准。
|
||||
- PDF 通过 `pypdfium2` 保留物理分页;`.doc/.docx` 复用 LibreOffice 转 PDF 后提取分页,转换失败不推测页数。
|
||||
- 两份上传文件均识别成功后,仅将 `body` 传入既有 `analyze_compare`;`metadata/signature/attachments` 分别进入字段对照、排除区和页数汇总。
|
||||
- `summary_json` 扩展 `comparison_scope`、`metadata_comparison`、`attachment_comparison`;`clauses_json` 与 Chat 发起接口保持兼容。
|
||||
- 区域处理为 fail-safe:任何一侧正文锚点或可靠分页缺失时,使用旧全文比对结果并记录回退原因。
|
||||
@@ -48,6 +48,9 @@ const WecomAuditsPage = () => import("@/features/admin/modules/wecom/pages/Wecom
|
||||
const ReportsPage = () =>
|
||||
import("@/features/admin/modules/reports/ReportsPage.vue");
|
||||
|
||||
const ProcurementContractPage = () =>
|
||||
import("@/features/admin/modules/procurement-contract/ProcurementContractPage.vue");
|
||||
|
||||
export const adminRoutes: RouteRecordRaw[] = [
|
||||
{
|
||||
path: "/admin",
|
||||
@@ -196,6 +199,16 @@ export const adminRoutes: RouteRecordRaw[] = [
|
||||
title: "平台应用说明",
|
||||
},
|
||||
},
|
||||
{
|
||||
path: "procurement-contract",
|
||||
name: "AdminProcurementContract",
|
||||
component: ProcurementContractPage,
|
||||
meta: {
|
||||
requiresAdmin: true,
|
||||
adminModule: "procurement_contract",
|
||||
title: "采购合同审查",
|
||||
},
|
||||
},
|
||||
{
|
||||
path: "reports/:table?",
|
||||
name: "AdminReports",
|
||||
|
||||
@@ -63,6 +63,7 @@ export const config = {
|
||||
requests: true, // 审批权限
|
||||
reports: true, // 数据报表
|
||||
schedules: true, // 定时任务
|
||||
procurement_contract: true, // 采购合同审查(模板库 + 历史)
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,406 @@
|
||||
/**
|
||||
* features/admin/api/procurement-contract.api.ts
|
||||
* 用途:采购合同审查 Admin / 会话 API 封装(含鉴权下载)。
|
||||
* 依赖:shared/api/client requestJson、auth headers。
|
||||
* 逻辑:Templates / Reviews 页面与 Chat 控件调用;下载走 fetch+blob。
|
||||
*/
|
||||
import { requestJson } from '@/shared/api/client';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
|
||||
export type ContractMetadataField = 'title' | 'version' | 'contract_no' | 'buyer' | 'seller';
|
||||
|
||||
export interface ContractComparisonRegionConfig {
|
||||
metadata_fields: ContractMetadataField[];
|
||||
body_start_anchors: string[];
|
||||
body_end_anchors: string[];
|
||||
signature_terms: string[];
|
||||
attachment_start_anchors: string[];
|
||||
attachment_policy: 'page_count_only';
|
||||
}
|
||||
|
||||
export interface ContractComparisonRegionPreview {
|
||||
status: 'recognized' | 'incomplete' | string;
|
||||
body_start_anchor?: string | null;
|
||||
body_end_anchor?: string | null;
|
||||
signature_terms_found?: string[];
|
||||
attachment_anchor?: string | null;
|
||||
warning?: string | null;
|
||||
}
|
||||
|
||||
export interface ContractTemplateRow {
|
||||
id: number;
|
||||
name: string;
|
||||
version: string;
|
||||
file_name: string;
|
||||
file_asset_id?: number | null;
|
||||
contract_type?: string;
|
||||
applicable_scope?: string | null;
|
||||
change_note?: string | null;
|
||||
comparison_region_config?: ContractComparisonRegionConfig | null;
|
||||
status: 'enabled' | 'disabled' | string;
|
||||
is_default: boolean;
|
||||
remark?: string | null;
|
||||
updated_by_name?: string | null;
|
||||
created_at?: string | null;
|
||||
updated_at?: string | null;
|
||||
}
|
||||
|
||||
export interface ContractClauseItem {
|
||||
clause_no?: string;
|
||||
title?: string;
|
||||
change_type?: string;
|
||||
/** 后端语义分类:仅 obligation 会参与法律与履约风险统计。 */
|
||||
change_class?: 'format' | 'metadata' | 'commercial' | 'obligation' | string;
|
||||
risk_level?: string;
|
||||
clause_category?: string;
|
||||
detail?: string;
|
||||
risk_hint?: string;
|
||||
suggestion?: string;
|
||||
negotiation_text?: string;
|
||||
old_text?: string;
|
||||
new_text?: string;
|
||||
/** 后端标记:old/new 是否为可读抽取片段;false 时前端展示编码不兼容提示 */
|
||||
comparison_readable?: boolean;
|
||||
llm_enabled?: boolean;
|
||||
llm_confidence?: number | null;
|
||||
llm_reason?: string;
|
||||
llm_suggestion?: string;
|
||||
llm_negotiation_text?: string;
|
||||
llm_model_risk_level?: string;
|
||||
llm_decision?: 'confirm' | 'reject' | 'uncertain' | string;
|
||||
llm_evidence?: string;
|
||||
evidence?: string;
|
||||
source?: string;
|
||||
validation_status?: 'confirmed' | 'needs_review' | string;
|
||||
/** 同一业务主题下聚合的底层 OCR 不确定片段数。 */
|
||||
affected_fragments?: number;
|
||||
business_impact?: string;
|
||||
anchor_status?: 'anchored' | 'unanchored' | string;
|
||||
evidence_anchor?: {
|
||||
page_no?: number;
|
||||
rects?: number[][];
|
||||
matched_text?: string;
|
||||
source_text?: string;
|
||||
confidence?: number;
|
||||
method?: 'exact' | 'fuzzy' | 'ocr_page' | string;
|
||||
} | null;
|
||||
}
|
||||
|
||||
export interface ContractRiskRuleRow {
|
||||
id: number;
|
||||
code: string;
|
||||
/** 内置规则携带组合业务判断;自定义规则仅执行关键词命中判断。 */
|
||||
rule_kind?: 'builtin' | 'custom' | string;
|
||||
contract_type: string;
|
||||
clause_category: string;
|
||||
title: string;
|
||||
keywords: string[];
|
||||
trigger_type: 'keyword_missing' | 'keyword_present' | string;
|
||||
risk_level: 'high' | 'medium' | 'low' | string;
|
||||
risk_hint: string;
|
||||
suggestion: string;
|
||||
negotiation_text?: string | null;
|
||||
status: 'enabled' | 'disabled' | string;
|
||||
sort_order: number;
|
||||
created_at?: string | null;
|
||||
updated_at?: string | null;
|
||||
}
|
||||
|
||||
export interface ContractReviewRow {
|
||||
id: number;
|
||||
review_no: string;
|
||||
review_mode: 'compare' | 'solo' | string;
|
||||
status: string;
|
||||
contract_file_name: string;
|
||||
supplier_name?: string | null;
|
||||
/** 从合同正文抽取的业务合同编号(非审查编号) */
|
||||
contract_no?: string | null;
|
||||
contract_type?: string;
|
||||
template_id?: number | null;
|
||||
template_source: string;
|
||||
template_name?: string | null;
|
||||
total_change_count?: number;
|
||||
high_risk_count: number;
|
||||
medium_risk_count: number;
|
||||
low_risk_count: number;
|
||||
user_id: number;
|
||||
user_name?: string | null;
|
||||
error_message?: string | null;
|
||||
started_at?: string | null;
|
||||
finished_at?: string | null;
|
||||
created_at?: string | null;
|
||||
progress?: number;
|
||||
processing_stage?: string | null;
|
||||
processing_message?: string | null;
|
||||
summary_json?: Record<string, unknown> | null;
|
||||
clauses_json?: ContractClauseItem[] | null;
|
||||
report_text?: string | null;
|
||||
template_asset_id?: number | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 鉴权下载:fetch blob → 触发浏览器保存。
|
||||
* @param url - 需携带 JWT 的下载 URL
|
||||
* @param fallbackName - Content-Disposition 缺失时的文件名
|
||||
*/
|
||||
async function downloadAuthenticatedFile(url: string, fallbackName: string): Promise<void> {
|
||||
const res = await fetch(url, { headers: getAuthHeaders() });
|
||||
if (!res.ok) {
|
||||
const body = await res.json().catch(() => ({}));
|
||||
const err = body as { error?: { message?: string }; message?: string };
|
||||
throw new Error(err?.error?.message || err?.message || res.statusText);
|
||||
}
|
||||
const disposition = res.headers.get('content-disposition');
|
||||
const blob = await res.blob();
|
||||
const objectUrl = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = objectUrl;
|
||||
const rawName = disposition?.match(/filename\*?=(?:UTF-8'')?["']?([^;"'\n]+)/)?.[1] || fallbackName;
|
||||
try {
|
||||
a.download = decodeURIComponent(rawName);
|
||||
} catch {
|
||||
a.download = rawName;
|
||||
}
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(objectUrl);
|
||||
}
|
||||
|
||||
/** Admin:下载模板文件 */
|
||||
export function downloadAdminContractTemplate(templateId: number): Promise<void> {
|
||||
return downloadAuthenticatedFile(
|
||||
`/api/admin/procurement-contract/templates/${templateId}/file`,
|
||||
`template-${templateId}`,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Admin:下载审查报告。
|
||||
* @param reviewId - 审查主键
|
||||
* @param reviewNo - 审查编号(文件名用)
|
||||
* @param format - 默认 docx;传 txt 可下载纯文本
|
||||
*/
|
||||
export function downloadAdminContractReviewReport(
|
||||
reviewId: number,
|
||||
reviewNo?: string,
|
||||
format: 'txt' | 'docx' = 'docx',
|
||||
): Promise<void> {
|
||||
const q = format === 'docx' ? '?format=docx' : '';
|
||||
return downloadAuthenticatedFile(
|
||||
`/api/admin/procurement-contract/reviews/${reviewId}/report${q}`,
|
||||
`${reviewNo || reviewId}_report.${format === 'docx' ? 'docx' : 'txt'}`,
|
||||
);
|
||||
}
|
||||
|
||||
/** Admin:下载待审合同 */
|
||||
export function downloadAdminContractReviewContract(reviewId: number, fileName?: string): Promise<void> {
|
||||
return downloadAuthenticatedFile(
|
||||
`/api/admin/procurement-contract/reviews/${reviewId}/contract`,
|
||||
fileName || `contract-${reviewId}`,
|
||||
);
|
||||
}
|
||||
|
||||
/** Admin:下载带风险高亮批注的合同 PDF 副本 */
|
||||
export function downloadAdminAnnotatedContract(reviewId: number, reviewNo?: string): Promise<void> {
|
||||
return downloadAuthenticatedFile(
|
||||
`/api/admin/procurement-contract/reviews/${reviewId}/annotated-contract`,
|
||||
`${reviewNo || reviewId}_annotated.pdf`,
|
||||
);
|
||||
}
|
||||
|
||||
/** Admin:下载本次审查所用模板文件 */
|
||||
export function downloadAdminContractReviewTemplateFile(reviewId: number): Promise<void> {
|
||||
return downloadAuthenticatedFile(
|
||||
`/api/admin/procurement-contract/reviews/${reviewId}/template-file`,
|
||||
`template-for-review-${reviewId}`,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Chat:下载本人审查报告。
|
||||
* @param reviewNo - 审查编号
|
||||
* @param format - 默认 docx;传 txt 可下载纯文本
|
||||
*/
|
||||
export function downloadChatContractReviewReport(
|
||||
reviewNo: string,
|
||||
format: 'txt' | 'docx' = 'docx',
|
||||
): Promise<void> {
|
||||
const q = format === 'docx' ? '?format=docx' : '';
|
||||
return downloadAuthenticatedFile(
|
||||
`/api/procurement-contract/reviews/${encodeURIComponent(reviewNo)}/report${q}`,
|
||||
`${reviewNo}_report.${format === 'docx' ? 'docx' : 'txt'}`,
|
||||
);
|
||||
}
|
||||
|
||||
/** Chat:下载本人带风险高亮批注的合同 PDF */
|
||||
export function downloadChatAnnotatedContract(reviewNo: string): Promise<void> {
|
||||
return downloadAuthenticatedFile(
|
||||
`/api/procurement-contract/reviews/${encodeURIComponent(reviewNo)}/annotated-contract`,
|
||||
`${reviewNo}_annotated.pdf`,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 管理端模板列表。
|
||||
*/
|
||||
export async function listAdminContractTemplates(status?: string): Promise<ContractTemplateRow[]> {
|
||||
const q = status ? `?status=${encodeURIComponent(status)}` : '';
|
||||
return requestJson<ContractTemplateRow[]>(`/api/admin/procurement-contract/templates${q}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传并创建模板(multipart)。
|
||||
*/
|
||||
export async function createAdminContractTemplate(form: FormData): Promise<ContractTemplateRow> {
|
||||
const res = await fetch('/api/admin/procurement-contract/templates', {
|
||||
method: 'POST',
|
||||
headers: getAuthHeaders(),
|
||||
body: form,
|
||||
});
|
||||
const body = await res.json();
|
||||
if (!res.ok || body?.success === false) {
|
||||
throw new Error(body?.error?.message || body?.message || 'upload failed');
|
||||
}
|
||||
return (body?.data ?? body) as ContractTemplateRow;
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新模板。
|
||||
*/
|
||||
export async function updateAdminContractTemplate(
|
||||
id: number,
|
||||
data: Partial<Pick<ContractTemplateRow, 'name' | 'version' | 'status' | 'is_default' | 'remark' | 'contract_type' | 'applicable_scope' | 'change_note' | 'comparison_region_config'>>,
|
||||
): Promise<ContractTemplateRow> {
|
||||
return requestJson<ContractTemplateRow>(`/api/admin/procurement-contract/templates/${id}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
}
|
||||
|
||||
/** Admin: preview unsaved region anchors against the stored template file. */
|
||||
export async function previewAdminContractTemplateRegions(
|
||||
id: number,
|
||||
comparisonRegionConfig: ContractComparisonRegionConfig,
|
||||
): Promise<ContractComparisonRegionPreview> {
|
||||
return requestJson<ContractComparisonRegionPreview>(
|
||||
`/api/admin/procurement-contract/templates/${id}/comparison-region-preview`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ comparison_region_config: comparisonRegionConfig }),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除模板。
|
||||
*/
|
||||
export async function deleteAdminContractTemplate(id: number): Promise<void> {
|
||||
await requestJson(`/api/admin/procurement-contract/templates/${id}`, { method: 'DELETE' });
|
||||
}
|
||||
|
||||
/**
|
||||
* 审查历史列表。
|
||||
*/
|
||||
export async function listAdminContractReviews(params?: {
|
||||
review_mode?: string;
|
||||
template_source?: string;
|
||||
status?: string;
|
||||
keyword?: string;
|
||||
contract_type?: string;
|
||||
supplier_name?: string;
|
||||
risk_level?: string;
|
||||
date_from?: string;
|
||||
date_to?: string;
|
||||
}): Promise<{ total: number; items: ContractReviewRow[] }> {
|
||||
const sp = new URLSearchParams();
|
||||
if (params?.review_mode) sp.set('review_mode', params.review_mode);
|
||||
if (params?.template_source) sp.set('template_source', params.template_source);
|
||||
if (params?.status) sp.set('status', params.status);
|
||||
if (params?.keyword) sp.set('keyword', params.keyword);
|
||||
if (params?.contract_type) sp.set('contract_type', params.contract_type);
|
||||
if (params?.supplier_name) sp.set('supplier_name', params.supplier_name);
|
||||
if (params?.risk_level) sp.set('risk_level', params.risk_level);
|
||||
if (params?.date_from) sp.set('date_from', params.date_from);
|
||||
if (params?.date_to) sp.set('date_to', params.date_to);
|
||||
const q = sp.toString() ? `?${sp.toString()}` : '';
|
||||
return requestJson(`/api/admin/procurement-contract/reviews${q}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 审查详情。
|
||||
*/
|
||||
export async function getAdminContractReview(id: number): Promise<ContractReviewRow> {
|
||||
return requestJson(`/api/admin/procurement-contract/reviews/${id}`);
|
||||
}
|
||||
|
||||
/** Admin:风险规则列表 */
|
||||
export async function listAdminContractRiskRules(params?: {
|
||||
contract_type?: string;
|
||||
status?: string;
|
||||
clause_category?: string;
|
||||
}): Promise<ContractRiskRuleRow[]> {
|
||||
const sp = new URLSearchParams();
|
||||
if (params?.contract_type) sp.set('contract_type', params.contract_type);
|
||||
if (params?.status) sp.set('status', params.status);
|
||||
if (params?.clause_category) sp.set('clause_category', params.clause_category);
|
||||
const q = sp.toString() ? `?${sp.toString()}` : '';
|
||||
return requestJson(`/api/admin/procurement-contract/rules${q}`);
|
||||
}
|
||||
|
||||
/** Admin:创建风险规则 */
|
||||
export async function createAdminContractRiskRule(
|
||||
data: Omit<Partial<ContractRiskRuleRow>, 'id'>,
|
||||
): Promise<ContractRiskRuleRow> {
|
||||
return requestJson('/api/admin/procurement-contract/rules', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
}
|
||||
|
||||
/** Admin:更新风险规则 */
|
||||
export async function updateAdminContractRiskRule(
|
||||
id: number,
|
||||
data: Partial<ContractRiskRuleRow>,
|
||||
): Promise<ContractRiskRuleRow> {
|
||||
return requestJson(`/api/admin/procurement-contract/rules/${id}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
}
|
||||
|
||||
/** Admin:删除风险规则 */
|
||||
export async function deleteAdminContractRiskRule(id: number): Promise<void> {
|
||||
await requestJson(`/api/admin/procurement-contract/rules/${id}`, { method: 'DELETE' });
|
||||
}
|
||||
|
||||
/** 会话:启用模板列表 */
|
||||
export async function listChatContractTemplates(): Promise<ContractTemplateRow[]> {
|
||||
return requestJson('/api/procurement-contract/templates');
|
||||
}
|
||||
|
||||
/** 会话:发起审查 */
|
||||
export async function startChatContractReview(payload: {
|
||||
review_mode: 'compare' | 'solo';
|
||||
contract_asset_no: string;
|
||||
/** 模板比对时必填:用户上传的我方原合同资产编号。 */
|
||||
original_contract_asset_no?: string | null;
|
||||
contract_type?: string | null;
|
||||
supplier_name?: string | null;
|
||||
agent_id?: number | null;
|
||||
}): Promise<ContractReviewRow> {
|
||||
return requestJson('/api/procurement-contract/reviews', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
}
|
||||
|
||||
/** 会话:轮询本人合同审查详情 */
|
||||
export async function getChatContractReview(reviewNo: string): Promise<ContractReviewRow> {
|
||||
return requestJson(`/api/procurement-contract/reviews/${encodeURIComponent(reviewNo)}`);
|
||||
}
|
||||
@@ -10,7 +10,8 @@ import { useI18n } from 'vue-i18n';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import {
|
||||
LayoutDashboard, UserPlus, UserCog, Building, Bot, FileText,
|
||||
Settings2, Megaphone, MessageCircleQuestion, Link2, Users, ShieldCheck, BarChart2, AppWindow
|
||||
Settings2, Megaphone, MessageCircleQuestion, Link2, Users, ShieldCheck, BarChart2, AppWindow,
|
||||
ScrollText,
|
||||
} from 'lucide-vue-next';
|
||||
import type { Component } from 'vue';
|
||||
import { config } from '@/config';
|
||||
@@ -36,6 +37,7 @@ const iconMap: Record<AdminModuleId, Component> = {
|
||||
wecom: Link2,
|
||||
permissions: Users,
|
||||
platform_apps: AppWindow,
|
||||
procurement_contract: ScrollText,
|
||||
requests: ShieldCheck,
|
||||
reports: BarChart2,
|
||||
};
|
||||
|
||||
@@ -15,7 +15,7 @@ export interface AdminModuleMeta {
|
||||
|
||||
/** 已独立拆分的模块(全部 admin 模块均已拆分) */
|
||||
export const STANDALONE_ADMIN_MODULES = new Set<AdminModuleId>([
|
||||
'dashboard', 'agents', 'users', 'departments', 'approvals', 'announcements', 'questions', 'requests', 'permissions', 'schedules', 'knowledge_base', 'wecom', 'platform_apps', 'reports',
|
||||
'dashboard', 'agents', 'users', 'departments', 'approvals', 'announcements', 'questions', 'requests', 'permissions', 'schedules', 'knowledge_base', 'wecom', 'platform_apps', 'procurement_contract', 'reports',
|
||||
]);
|
||||
|
||||
export const ADMIN_MODULE_METAS: AdminModuleMeta[] = [
|
||||
@@ -31,6 +31,7 @@ export const ADMIN_MODULE_METAS: AdminModuleMeta[] = [
|
||||
{ id: 'wecom', routeName: 'AdminWecom', path: 'wecom', labelKey: 'admin.nav.wecom', configKey: 'wecom' },
|
||||
{ id: 'permissions', routeName: 'AdminPermissions', path: 'permissions', labelKey: 'admin.nav.permissions', configKey: 'permissions' },
|
||||
{ id: 'platform_apps', routeName: 'AdminPlatformApps', path: 'platform-apps', labelKey: 'admin.nav.platformApps', configKey: 'platform_apps' },
|
||||
{ id: 'procurement_contract', routeName: 'AdminProcurementContract', path: 'procurement-contract', labelKey: 'admin.nav.procurementContract', configKey: 'procurement_contract' },
|
||||
{ id: 'requests', routeName: 'AdminRequests', path: 'requests', labelKey: 'admin.nav.requests', configKey: 'requests' },
|
||||
];
|
||||
|
||||
|
||||
+1073
File diff suppressed because it is too large.
Load diff
+590
@@ -0,0 +1,590 @@
|
||||
/**
|
||||
* features/admin/modules/procurement-contract/components/ContractRiskRulesPanel.vue
|
||||
* 用途:采购合同风险红线规则列表与新增/编辑(含迁移种子默认规则)。
|
||||
* 依赖:procurement-contract.api、DeleteConfirmDialog、useMessage、vue-i18n。
|
||||
* 逻辑:由 ProcurementContractPage「风险规则」Tab 挂载;CRUD 走 Admin rules API。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { CircleHelp, Plus, ShieldAlert, ShieldCheck, SlidersHorizontal } from 'lucide-vue-next';
|
||||
import {
|
||||
createAdminContractRiskRule,
|
||||
deleteAdminContractRiskRule,
|
||||
listAdminContractRiskRules,
|
||||
updateAdminContractRiskRule,
|
||||
type ContractRiskRuleRow,
|
||||
} from '@/features/admin/api/procurement-contract.api';
|
||||
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
|
||||
const { t } = useI18n();
|
||||
const msg = useMessage();
|
||||
|
||||
const loading = ref(false);
|
||||
const saving = ref(false);
|
||||
const rules = ref<ContractRiskRuleRow[]>([]);
|
||||
const filterStatus = ref('');
|
||||
|
||||
const showForm = ref(false);
|
||||
const editing = ref<ContractRiskRuleRow | null>(null);
|
||||
const formTitle = ref('');
|
||||
const formCategory = ref('');
|
||||
const formKeywords = ref('');
|
||||
const formTriggerType = ref<'keyword_missing' | 'keyword_present'>('keyword_missing');
|
||||
const formRiskLevel = ref<'high' | 'medium' | 'low'>('medium');
|
||||
const formRiskHint = ref('');
|
||||
const formSuggestion = ref('');
|
||||
const formNegotiation = ref('');
|
||||
const formStatus = ref<'enabled' | 'disabled'>('enabled');
|
||||
const formSortOrder = ref(100);
|
||||
|
||||
const clauseCategories = [
|
||||
'payment',
|
||||
'delivery',
|
||||
'acceptance',
|
||||
'warranty',
|
||||
'liability',
|
||||
'jurisdiction',
|
||||
'dispute',
|
||||
'ip',
|
||||
'other',
|
||||
] as const;
|
||||
|
||||
const showDeleteConfirm = ref(false);
|
||||
const pendingDelete = ref<ContractRiskRuleRow | null>(null);
|
||||
const deleting = ref(false);
|
||||
|
||||
const isEditMode = computed(() => Boolean(editing.value));
|
||||
const formTitleText = computed(() =>
|
||||
isEditMode.value
|
||||
? t('admin.procurementContract.ruleEditTitle')
|
||||
: t('admin.procurementContract.ruleCreateTitle'),
|
||||
);
|
||||
|
||||
const isBuiltinRule = computed(() => editing.value?.rule_kind === 'builtin');
|
||||
|
||||
const keywordLogicHint = computed(() =>
|
||||
formTriggerType.value === 'keyword_present'
|
||||
? t('admin.procurementContract.keywordPresentLogicHint')
|
||||
: t('admin.procurementContract.keywordMissingLogicHint'),
|
||||
);
|
||||
const ruleStats = computed(() => ({
|
||||
total: rules.value.length,
|
||||
enabled: rules.value.filter((rule) => rule.status === 'enabled').length,
|
||||
highRisk: rules.value.filter((rule) => rule.risk_level === 'high').length,
|
||||
}));
|
||||
|
||||
/**
|
||||
* 生成风险规则统计卡片,帮助管理员先扫状态再进入列表维护。
|
||||
*/
|
||||
const ruleSummaryCards = computed(() => [
|
||||
{
|
||||
key: 'total',
|
||||
label: t('admin.procurementContract.ruleStatTotal'),
|
||||
value: ruleStats.value.total,
|
||||
icon: SlidersHorizontal,
|
||||
className: 'border-slate-200 bg-white text-slate-600',
|
||||
},
|
||||
{
|
||||
key: 'enabled',
|
||||
label: t('admin.procurementContract.ruleStatEnabled'),
|
||||
value: ruleStats.value.enabled,
|
||||
icon: ShieldCheck,
|
||||
className: 'border-emerald-100 bg-emerald-50/80 text-emerald-700',
|
||||
},
|
||||
{
|
||||
key: 'highRisk',
|
||||
label: t('admin.procurementContract.ruleStatHighRisk'),
|
||||
value: ruleStats.value.highRisk,
|
||||
icon: ShieldAlert,
|
||||
className: 'border-rose-100 bg-rose-50/80 text-rose-700',
|
||||
},
|
||||
]);
|
||||
|
||||
/**
|
||||
* 加载风险规则列表。
|
||||
* @param options.silent - 为 true 时不切换 loading,避免启停时整表闪烁
|
||||
*/
|
||||
async function loadRules(options?: { silent?: boolean }): Promise<void> {
|
||||
const silent = Boolean(options?.silent);
|
||||
if (!silent) loading.value = true;
|
||||
try {
|
||||
rules.value = await listAdminContractRiskRules({
|
||||
status: filterStatus.value || undefined,
|
||||
});
|
||||
} catch (e: unknown) {
|
||||
console.error(e);
|
||||
msg.error(e instanceof Error ? e.message : t('admin.procurementContract.loadFailed'));
|
||||
} finally {
|
||||
if (!silent) loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 响应筛选条件变更并刷新规则列表。
|
||||
*/
|
||||
async function onFilterStatusChange(): Promise<void> {
|
||||
await loadRules();
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
void loadRules();
|
||||
});
|
||||
|
||||
/**
|
||||
* 重置规则表单为新建默认值。
|
||||
*/
|
||||
function resetForm(): void {
|
||||
editing.value = null;
|
||||
formTitle.value = '';
|
||||
formCategory.value = 'payment';
|
||||
formKeywords.value = '';
|
||||
formTriggerType.value = 'keyword_missing';
|
||||
formRiskLevel.value = 'medium';
|
||||
formRiskHint.value = '';
|
||||
formSuggestion.value = '';
|
||||
formNegotiation.value = '';
|
||||
formStatus.value = 'enabled';
|
||||
formSortOrder.value = 100;
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开新建规则弹窗。
|
||||
*/
|
||||
function openCreate(): void {
|
||||
resetForm();
|
||||
showForm.value = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开编辑规则弹窗(种子规则也可改,code 只读)。
|
||||
*/
|
||||
function openEdit(row: ContractRiskRuleRow): void {
|
||||
editing.value = row;
|
||||
formTitle.value = row.title;
|
||||
formCategory.value = row.clause_category;
|
||||
formKeywords.value = (row.keywords || []).join(',');
|
||||
formTriggerType.value = row.trigger_type === 'keyword_present' ? 'keyword_present' : 'keyword_missing';
|
||||
formRiskLevel.value =
|
||||
row.risk_level === 'high' || row.risk_level === 'low' ? row.risk_level : 'medium';
|
||||
formRiskHint.value = row.risk_hint || '';
|
||||
formSuggestion.value = row.suggestion || '';
|
||||
formNegotiation.value = row.negotiation_text || '';
|
||||
formStatus.value = row.status === 'disabled' ? 'disabled' : 'enabled';
|
||||
formSortOrder.value = Number(row.sort_order) || 100;
|
||||
showForm.value = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 关闭规则表单。
|
||||
*/
|
||||
function closeForm(): void {
|
||||
showForm.value = false;
|
||||
editing.value = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交新建或更新规则。
|
||||
*/
|
||||
async function submitForm(): Promise<void> {
|
||||
if (!formTitle.value.trim() || !formCategory.value.trim()) {
|
||||
msg.error(t('admin.procurementContract.ruleRequiredFields'));
|
||||
return;
|
||||
}
|
||||
if (!formKeywords.value.trim()) {
|
||||
msg.error(t('admin.procurementContract.ruleKeywordsRequired'));
|
||||
return;
|
||||
}
|
||||
if (!formRiskHint.value.trim() || !formSuggestion.value.trim()) {
|
||||
msg.error(t('admin.procurementContract.ruleRequiredFields'));
|
||||
return;
|
||||
}
|
||||
|
||||
saving.value = true;
|
||||
try {
|
||||
// 与后端 _normalize_keywords 一致:逗号/中文逗号分隔
|
||||
const keywords = formKeywords.value
|
||||
.replace(/,/g, ',')
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean);
|
||||
const payload = {
|
||||
title: formTitle.value.trim(),
|
||||
clause_category: formCategory.value.trim(),
|
||||
// 当前采购合同审核只支持通用采购类型,保留固定值以兼容后端规则加载。
|
||||
contract_type: 'general_procurement',
|
||||
keywords,
|
||||
trigger_type: formTriggerType.value,
|
||||
risk_level: formRiskLevel.value,
|
||||
risk_hint: formRiskHint.value.trim(),
|
||||
suggestion: formSuggestion.value.trim(),
|
||||
negotiation_text: formNegotiation.value.trim() || null,
|
||||
status: formStatus.value,
|
||||
sort_order: Number(formSortOrder.value) || 100,
|
||||
};
|
||||
if (isEditMode.value && editing.value) {
|
||||
await updateAdminContractRiskRule(editing.value.id, payload);
|
||||
msg.success(t('admin.procurementContract.ruleEditOk'));
|
||||
} else {
|
||||
await createAdminContractRiskRule(payload);
|
||||
msg.success(t('admin.procurementContract.ruleCreateOk'));
|
||||
}
|
||||
closeForm();
|
||||
await loadRules({ silent: true });
|
||||
} catch (e: unknown) {
|
||||
msg.error(e instanceof Error ? e.message : t('admin.procurementContract.actionFailed'));
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 切换规则启停(种子与自定义规则均可)。
|
||||
* 核心逻辑:先乐观更新本地行,成功后再静默对齐服务端;失败则回滚。
|
||||
*/
|
||||
async function toggleStatus(row: ContractRiskRuleRow): Promise<void> {
|
||||
const prev = row.status;
|
||||
const next = prev === 'enabled' ? 'disabled' : 'enabled';
|
||||
row.status = next;
|
||||
try {
|
||||
const updated = await updateAdminContractRiskRule(row.id, { status: next });
|
||||
Object.assign(row, updated);
|
||||
// 当前筛选为「启用/停用」时,状态变更后该项应离开列表
|
||||
if (filterStatus.value && filterStatus.value !== next) {
|
||||
rules.value = rules.value.filter((r) => r.id !== row.id);
|
||||
}
|
||||
} catch (e: unknown) {
|
||||
row.status = prev;
|
||||
msg.error(e instanceof Error ? e.message : t('admin.procurementContract.actionFailed'));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开删除确认。
|
||||
*/
|
||||
function openDelete(row: ContractRiskRuleRow): void {
|
||||
pendingDelete.value = row;
|
||||
showDeleteConfirm.value = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 关闭删除确认。
|
||||
*/
|
||||
function closeDelete(): void {
|
||||
showDeleteConfirm.value = false;
|
||||
pendingDelete.value = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 确认删除规则。
|
||||
*/
|
||||
async function confirmDelete(): Promise<void> {
|
||||
const row = pendingDelete.value;
|
||||
if (!row) return;
|
||||
deleting.value = true;
|
||||
try {
|
||||
await deleteAdminContractRiskRule(row.id);
|
||||
closeDelete();
|
||||
rules.value = rules.value.filter((r) => r.id !== row.id);
|
||||
} catch (e: unknown) {
|
||||
msg.error(e instanceof Error ? e.message : t('admin.procurementContract.actionFailed'));
|
||||
} finally {
|
||||
deleting.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 风险等级文案。
|
||||
*/
|
||||
function riskLabel(level: string): string {
|
||||
if (level === 'high') return t('admin.procurementContract.riskHigh');
|
||||
if (level === 'medium') return t('admin.procurementContract.riskMedium');
|
||||
if (level === 'low') return t('admin.procurementContract.riskLow');
|
||||
return level;
|
||||
}
|
||||
|
||||
/**
|
||||
* 触发类型文案。
|
||||
*/
|
||||
function triggerLabel(type: string): string {
|
||||
if (type === 'keyword_present') return t('admin.procurementContract.triggerPresent');
|
||||
return t('admin.procurementContract.triggerMissing');
|
||||
}
|
||||
|
||||
/**
|
||||
* 状态文案。
|
||||
*/
|
||||
function statusLabel(status: string): string {
|
||||
if (status === 'enabled') return t('admin.procurementContract.enable');
|
||||
if (status === 'disabled') return t('admin.procurementContract.disable');
|
||||
return status;
|
||||
}
|
||||
|
||||
/**
|
||||
* 规则关键词展示文本。
|
||||
* @param row - 风险规则行;关键词为空时返回短横线占位,避免表格空洞。
|
||||
*/
|
||||
function keywordText(row: ContractRiskRuleRow): string {
|
||||
const keywords = row.keywords || [];
|
||||
return keywords.length ? keywords.join(',') : '-';
|
||||
}
|
||||
|
||||
/**
|
||||
* 将内部条款分类编码转换为与规则弹窗一致的可读名称。
|
||||
* 核心逻辑:规则仍保存稳定编码,列表仅负责展示本地化文案。
|
||||
* @param category - 后端返回的条款分类编码。
|
||||
* @returns 用户可读的分类名称;历史未知编码保持原样,避免丢失信息。
|
||||
*/
|
||||
function categoryLabel(category: string): string {
|
||||
const key = `admin.procurementContract.category_${category}`;
|
||||
const translated = t(key);
|
||||
return translated === key ? category : translated;
|
||||
}
|
||||
|
||||
defineExpose({ loadRules, openCreate });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="space-y-5">
|
||||
<div class="grid gap-3 md:grid-cols-3">
|
||||
<div
|
||||
v-for="card in ruleSummaryCards"
|
||||
:key="card.key"
|
||||
class="rounded-xl border px-4 py-3 shadow-sm"
|
||||
:class="card.className"
|
||||
>
|
||||
<div class="flex items-center justify-between gap-3">
|
||||
<div>
|
||||
<div class="text-xs font-medium text-muted">{{ card.label }}</div>
|
||||
<div class="mt-1 text-2xl font-semibold text-primary">{{ card.value }}</div>
|
||||
</div>
|
||||
<span class="inline-flex h-9 w-9 items-center justify-center rounded-lg bg-white/80 shadow-sm">
|
||||
<component :is="card.icon" class="h-4 w-4" />
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col gap-3 rounded-xl border border-subtle bg-white px-4 py-3 shadow-sm sm:flex-row sm:items-center sm:justify-between">
|
||||
<div class="flex items-center gap-3">
|
||||
<label class="flex shrink-0 items-center gap-2 text-sm font-medium text-secondary">
|
||||
<span>{{ t('admin.procurementContract.colStatus') }}</span>
|
||||
<select
|
||||
v-model="filterStatus"
|
||||
class="input-field h-10 w-48 min-w-48 py-0 text-sm"
|
||||
@change="onFilterStatusChange"
|
||||
>
|
||||
<option value="">{{ t('admin.procurementContract.all') }}</option>
|
||||
<option value="enabled">{{ t('admin.procurementContract.enable') }}</option>
|
||||
<option value="disabled">{{ t('admin.procurementContract.disable') }}</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<button type="button" class="btn-primary inline-flex h-10 items-center gap-2 px-4 shadow-sm" @click="openCreate">
|
||||
<Plus class="h-4 w-4" />
|
||||
{{ t('admin.procurementContract.addRule') }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="overflow-hidden rounded-xl border border-subtle bg-white shadow-sm">
|
||||
<div class="overflow-auto">
|
||||
<table class="w-full min-w-[1030px] whitespace-nowrap text-sm">
|
||||
<thead class="bg-slate-50/80 text-xs font-semibold text-muted">
|
||||
<tr>
|
||||
<th class="px-5 py-3 text-left">{{ t('admin.procurementContract.colRuleTitle') }}</th>
|
||||
<th class="px-5 py-3 text-left">{{ t('admin.procurementContract.colCategory') }}</th>
|
||||
<th class="px-5 py-3 text-left">{{ t('admin.procurementContract.colKeywords') }}</th>
|
||||
<th class="px-5 py-3 text-left">{{ t('admin.procurementContract.colTrigger') }}</th>
|
||||
<th class="px-5 py-3 text-left">{{ t('admin.procurementContract.colRisk') }}</th>
|
||||
<th class="px-5 py-3 text-left">{{ t('admin.procurementContract.colStatus') }}</th>
|
||||
<th class="px-5 py-3 text-left">{{ t('admin.procurementContract.colSort') }}</th>
|
||||
<th class="px-5 py-3 text-left">{{ t('admin.procurementContract.colActions') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-if="loading">
|
||||
<td colspan="8" class="px-4 py-8 text-center text-muted">
|
||||
{{ t('admin.procurementContract.loading') }}
|
||||
</td>
|
||||
</tr>
|
||||
<tr v-else-if="!rules.length">
|
||||
<td colspan="8" class="px-4 py-8 text-center text-muted">
|
||||
{{ t('admin.procurementContract.emptyRules') }}
|
||||
</td>
|
||||
</tr>
|
||||
<tr v-for="row in rules" :key="row.id" class="border-t border-subtle transition-colors hover:bg-slate-50/70">
|
||||
<td class="px-5 py-4 align-top">
|
||||
<div class="font-semibold text-primary">{{ row.title }}</div>
|
||||
</td>
|
||||
<td class="px-5 py-4 align-top">
|
||||
<span class="inline-flex rounded-md border border-slate-200 bg-slate-50 px-2 py-1 text-xs font-medium text-slate-700">
|
||||
{{ categoryLabel(row.clause_category) }}
|
||||
</span>
|
||||
</td>
|
||||
<td class="max-w-[260px] px-5 py-4 align-top text-xs text-muted" :title="keywordText(row)">
|
||||
<div class="line-clamp-2 whitespace-normal leading-5">{{ keywordText(row) }}</div>
|
||||
</td>
|
||||
<td class="px-5 py-4 align-top text-secondary">{{ triggerLabel(row.trigger_type) }}</td>
|
||||
<td class="px-5 py-4 align-top">
|
||||
<span
|
||||
class="inline-flex rounded-full px-2.5 py-1 text-xs font-semibold"
|
||||
:class="{
|
||||
'bg-rose-50 text-rose-700': row.risk_level === 'high',
|
||||
'bg-amber-50 text-amber-800': row.risk_level === 'medium',
|
||||
'bg-sky-50 text-sky-700': row.risk_level === 'low',
|
||||
}"
|
||||
>
|
||||
{{ riskLabel(row.risk_level) }}
|
||||
</span>
|
||||
</td>
|
||||
<td class="px-5 py-4 align-top">
|
||||
<span
|
||||
class="inline-flex rounded-full px-2.5 py-1 text-xs font-semibold"
|
||||
:class="row.status === 'enabled' ? 'bg-emerald-50 text-emerald-700' : 'bg-slate-100 text-slate-600'"
|
||||
>
|
||||
{{ statusLabel(row.status) }}
|
||||
</span>
|
||||
</td>
|
||||
<td class="px-5 py-4 align-top font-mono text-xs text-muted">{{ row.sort_order }}</td>
|
||||
<td class="px-5 py-4 align-top">
|
||||
<div class="flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex h-8 items-center rounded-lg border border-[#d8e0ec] bg-white px-3 text-xs font-semibold text-[#2f80d1] transition-colors hover:border-[#2f80d1] hover:bg-[#eaf4ff]"
|
||||
@click="openEdit(row)"
|
||||
>
|
||||
{{ t('admin.edit') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex h-8 items-center rounded-lg border border-[#d8e0ec] bg-white px-3 text-xs font-semibold text-[#172033] transition-colors hover:border-[#667792] hover:bg-slate-50"
|
||||
@click="toggleStatus(row)"
|
||||
>
|
||||
{{ row.status === 'enabled' ? t('admin.procurementContract.disable') : t('admin.procurementContract.enable') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex h-8 items-center rounded-lg border border-rose-200 bg-white px-3 text-xs font-semibold text-rose-600 transition-colors hover:border-rose-300 hover:bg-rose-50"
|
||||
@click="openDelete(row)"
|
||||
>
|
||||
{{ t('admin.delete') }}
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="showForm"
|
||||
class="admin-modal-overlay animate-fade-in"
|
||||
@click.self="closeForm"
|
||||
>
|
||||
<div class="admin-modal-panel max-w-2xl max-h-[92vh] my-auto scale-100" role="dialog" aria-modal="true">
|
||||
<div class="admin-modal-header flex items-center justify-between gap-3">
|
||||
<h3 class="section-title">{{ formTitleText }}</h3>
|
||||
<button type="button" class="btn-ghost h-9 px-3 text-sm" @click="closeForm">
|
||||
{{ t('admin.close') }}
|
||||
</button>
|
||||
</div>
|
||||
<div class="admin-modal-body min-h-0 !space-y-0 grid grid-cols-1 gap-4 sm:grid-cols-2 items-start">
|
||||
<label class="flex flex-col gap-1.5 text-sm">
|
||||
<span class="font-medium text-secondary">{{ t('admin.procurementContract.colRuleTitle') }}</span>
|
||||
<input v-model="formTitle" type="text" class="input-field w-full" />
|
||||
</label>
|
||||
<label class="flex flex-col gap-1.5 text-sm">
|
||||
<span class="font-medium text-secondary">{{ t('admin.procurementContract.colCategory') }}</span>
|
||||
<select v-model="formCategory" class="input-field w-full" :disabled="isBuiltinRule">
|
||||
<option v-for="category in clauseCategories" :key="category" :value="category">
|
||||
{{ t(`admin.procurementContract.category_${category}`) }}
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="flex flex-col gap-1.5 text-sm sm:col-span-2">
|
||||
<span class="font-medium text-secondary">{{ t('admin.procurementContract.colKeywords') }}</span>
|
||||
<input
|
||||
v-model="formKeywords"
|
||||
type="text"
|
||||
class="input-field w-full"
|
||||
:disabled="isBuiltinRule"
|
||||
:placeholder="t('admin.procurementContract.ruleKeywordsPlaceholder')"
|
||||
/>
|
||||
<span class="text-xs leading-5 text-muted">{{ keywordLogicHint }}</span>
|
||||
</label>
|
||||
<label class="flex flex-col gap-1.5 text-sm">
|
||||
<span class="font-medium text-secondary">{{ t('admin.procurementContract.colTrigger') }}</span>
|
||||
<select v-model="formTriggerType" class="input-field w-full" :disabled="isBuiltinRule">
|
||||
<option value="keyword_missing">{{ t('admin.procurementContract.triggerMissing') }}</option>
|
||||
<option value="keyword_present">{{ t('admin.procurementContract.triggerPresent') }}</option>
|
||||
</select>
|
||||
<span v-if="isBuiltinRule" class="text-xs leading-5 text-amber-700">{{ t('admin.procurementContract.builtinRuleLogicHint') }}</span>
|
||||
</label>
|
||||
<label class="flex flex-col gap-1.5 text-sm">
|
||||
<span class="font-medium text-secondary">{{ t('admin.procurementContract.colRisk') }}</span>
|
||||
<select v-model="formRiskLevel" class="input-field w-full">
|
||||
<option value="high">{{ t('admin.procurementContract.riskHigh') }}</option>
|
||||
<option value="medium">{{ t('admin.procurementContract.riskMedium') }}</option>
|
||||
<option value="low">{{ t('admin.procurementContract.riskLow') }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="flex flex-col gap-1.5 text-sm">
|
||||
<span class="font-medium text-secondary">{{ t('admin.procurementContract.colStatus') }}</span>
|
||||
<select v-model="formStatus" class="input-field w-full">
|
||||
<option value="enabled">{{ t('admin.procurementContract.enable') }}</option>
|
||||
<option value="disabled">{{ t('admin.procurementContract.disable') }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<div class="flex flex-col gap-1.5 text-sm">
|
||||
<div class="flex items-center gap-1.5">
|
||||
<label for="risk-rule-sort-order" class="font-medium text-secondary">{{ t('admin.procurementContract.colSort') }}</label>
|
||||
<span class="group relative inline-flex">
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex text-muted transition-colors hover:text-brand-600 focus:outline-none focus-visible:text-brand-600"
|
||||
:aria-label="t('admin.procurementContract.ruleSortHint')"
|
||||
>
|
||||
<CircleHelp class="h-4 w-4" />
|
||||
</button>
|
||||
<span class="pointer-events-none absolute bottom-full left-1/2 z-10 mb-2 hidden w-60 -translate-x-1/2 rounded-lg border border-subtle bg-white px-3 py-2 text-xs font-normal leading-5 text-secondary shadow-lg group-hover:block group-focus-within:block">
|
||||
{{ t('admin.procurementContract.ruleSortHint') }}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
<input id="risk-rule-sort-order" v-model.number="formSortOrder" type="number" class="input-field w-full" min="0" />
|
||||
</div>
|
||||
<label class="flex flex-col gap-1.5 text-sm sm:col-span-2">
|
||||
<span class="font-medium text-secondary">{{ t('admin.procurementContract.colRiskHint') }}</span>
|
||||
<textarea v-model="formRiskHint" rows="2" class="input-field w-full resize-y" />
|
||||
</label>
|
||||
<label class="flex flex-col gap-1.5 text-sm sm:col-span-2">
|
||||
<span class="font-medium text-secondary">{{ t('admin.procurementContract.colSuggestion') }}</span>
|
||||
<textarea v-model="formSuggestion" rows="2" class="input-field w-full resize-y" />
|
||||
</label>
|
||||
<label class="flex flex-col gap-1.5 text-sm sm:col-span-2">
|
||||
<span class="font-medium text-secondary">{{ t('admin.procurementContract.colNegotiation') }}</span>
|
||||
<textarea v-model="formNegotiation" rows="2" class="input-field w-full resize-y" />
|
||||
</label>
|
||||
</div>
|
||||
<div class="admin-modal-footer flex justify-end gap-2">
|
||||
<button type="button" class="btn-ghost h-10 px-4" @click="closeForm">
|
||||
{{ t('admin.cancel') }}
|
||||
</button>
|
||||
<button type="button" class="btn-primary h-10 px-4 disabled:opacity-70" :disabled="saving" @click="submitForm">
|
||||
{{ saving ? t('admin.procurementContract.saving') : t('admin.procurementContract.saveChanges') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DeleteConfirmDialog
|
||||
v-model="showDeleteConfirm"
|
||||
:message="t('admin.procurementContract.confirmDeleteRule', { title: pendingDelete?.title || '' })"
|
||||
:confirm-loading="deleting"
|
||||
@confirm="confirmDelete"
|
||||
@cancel="closeDelete"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
@@ -17,6 +17,7 @@ export type AdminModuleId =
|
||||
| 'permissions'
|
||||
| 'requests'
|
||||
| 'platform_apps'
|
||||
| 'procurement_contract'
|
||||
| 'reports';
|
||||
|
||||
export type AdminReportTableId =
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
/**
|
||||
* features/chat/components/ChatInputBar.vue
|
||||
* 聊天输入栏:文本框、附件、语音、知识库选择与发送按钮。
|
||||
* 逻辑:设备维保助手的管理入口(设备台账、登记维修)与语音按钮同侧排列,发送按钮独占右侧。
|
||||
* 聊天输入栏:文本框、附件、语音、知识库与采购合同双文件输入控件。
|
||||
* 逻辑:采购合同审查隐藏企业知识库;模板比对明确上传我方原合同和卖方回传合同,单份审核仅上传待审合同。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { Ref } from 'vue';
|
||||
import {
|
||||
Check,
|
||||
ChevronDown,
|
||||
Database,
|
||||
FileText,
|
||||
Link2,
|
||||
Loader2,
|
||||
Mic,
|
||||
@@ -18,8 +19,10 @@ import {
|
||||
RefreshCw,
|
||||
Send,
|
||||
Square,
|
||||
Upload,
|
||||
X,
|
||||
} from 'lucide-vue-next';
|
||||
import type { ContractReviewMode } from '../composables/useProcurementContractChat';
|
||||
import type { PendingAttachment, ShippingNoticePendingAttachment } from '../types/shipping.types';
|
||||
import {
|
||||
isBlockingWarning,
|
||||
@@ -35,6 +38,7 @@ export interface ChatInputAttachmentPolicy {
|
||||
|
||||
const inputValue = defineModel<string>({ required: true });
|
||||
const selectedKb = defineModel<string>('selectedKb', { required: true });
|
||||
const procurementReviewMode = defineModel<ContractReviewMode>('procurementReviewMode', { default: 'compare' });
|
||||
|
||||
const props = defineProps<{
|
||||
attachments: PendingAttachment[];
|
||||
@@ -47,6 +51,8 @@ const props = defineProps<{
|
||||
isUploadingAttachments: boolean;
|
||||
canSendMessage: boolean;
|
||||
isShippingNoticeAgent: boolean;
|
||||
isProcurementContractAgent?: boolean;
|
||||
procurementOriginalContractName?: string | null;
|
||||
isMaintenanceAgent?: boolean;
|
||||
canManageMaintenance?: boolean;
|
||||
shippingSuggestedPrompt: string;
|
||||
@@ -72,9 +78,12 @@ const emit = defineEmits<{
|
||||
'maintenance-ledger-config': [];
|
||||
'maintenance-create-record': [];
|
||||
'clear-shipping-focus': [];
|
||||
'procurement-original-contract-selected': [event: Event];
|
||||
'clear-procurement-original-contract': [];
|
||||
}>();
|
||||
|
||||
const filePickerRef = ref<HTMLInputElement | null>(null);
|
||||
const originalContractPickerRef = ref<HTMLInputElement | null>(null);
|
||||
const { t } = useI18n();
|
||||
const textareaRef = ref<HTMLTextAreaElement | null>(null);
|
||||
const attachmentMenuRef = ref<HTMLElement | null>(null);
|
||||
@@ -85,6 +94,35 @@ const showAttachmentUrlPanel = ref(false);
|
||||
const showKbDropdown = ref(false);
|
||||
const attachmentUrlInput = ref('');
|
||||
|
||||
const hasProcurementContractAttachment = computed(() =>
|
||||
Boolean(props.isProcurementContractAgent)
|
||||
&& props.attachments.some((item) => item.kind === 'local'),
|
||||
);
|
||||
|
||||
const procurementQuickActions = computed(() => {
|
||||
const actions = [
|
||||
{
|
||||
label: 'chat.procurementContract.quickReview',
|
||||
prompt: 'chat.procurementContract.promptReview',
|
||||
},
|
||||
{
|
||||
label: 'chat.procurementContract.quickRisk',
|
||||
prompt: 'chat.procurementContract.promptRisk',
|
||||
},
|
||||
];
|
||||
if (procurementReviewMode.value === 'compare') {
|
||||
actions.push({
|
||||
label: 'chat.procurementContract.quickDiff',
|
||||
prompt: 'chat.procurementContract.promptDiff',
|
||||
});
|
||||
}
|
||||
actions.push({
|
||||
label: 'chat.procurementContract.quickSuggestion',
|
||||
prompt: 'chat.procurementContract.promptSuggestion',
|
||||
});
|
||||
return actions;
|
||||
});
|
||||
|
||||
/**
|
||||
* 汇总 EML 附件解析进度,供输入栏徽标展示。
|
||||
* 核心逻辑:failed/empty/skipped/超限/文本预算耗尽计为问题;duplicate 单独提示,不记为失败。
|
||||
@@ -172,6 +210,15 @@ const selectAttachmentLocal = () => {
|
||||
filePickerRef.value?.click();
|
||||
};
|
||||
|
||||
/**
|
||||
* 采购合同 Agent 的主上传入口:比对模式选择卖方回传合同,单份模式选择待审合同。
|
||||
*/
|
||||
const selectProcurementContractLocal = () => {
|
||||
if (!props.attachmentPolicy.canLocal || props.isThinking || props.isUploadingAttachments) return;
|
||||
closeAttachmentMenu();
|
||||
filePickerRef.value?.click();
|
||||
};
|
||||
|
||||
const selectAttachmentUrl = async () => {
|
||||
if (!props.attachmentPolicy.canRemote) return;
|
||||
showAttachmentMenu.value = true;
|
||||
@@ -201,6 +248,16 @@ const submitRemoteUrl = () => {
|
||||
closeAttachmentMenu();
|
||||
};
|
||||
|
||||
/**
|
||||
* 上传合同后的快捷审查动作:写入审查方案并立即发送。
|
||||
*/
|
||||
const runProcurementQuickAction = async (promptKey: string) => {
|
||||
if (!hasProcurementContractAttachment.value || props.isThinking || props.isUploadingAttachments) return;
|
||||
inputValue.value = t(promptKey);
|
||||
await nextTick();
|
||||
emit('send');
|
||||
};
|
||||
|
||||
const bindShippingPickerRef = (el: unknown) => {
|
||||
props.shippingPickerRefHolder.pickerRef.value = (el as HTMLInputElement | null) ?? null;
|
||||
};
|
||||
@@ -259,6 +316,47 @@ watch(
|
||||
<template>
|
||||
<footer class="safe-bottom z-20 shrink-0 bg-transparent p-2 md:p-3">
|
||||
<div class="relative mx-auto max-w-4xl">
|
||||
<div
|
||||
v-if="isProcurementContractAgent"
|
||||
class="mb-2 flex flex-wrap items-center gap-2"
|
||||
>
|
||||
<div
|
||||
class="inline-flex items-center gap-1 rounded-full border border-[#d8e0ec] bg-[#eef2f7] p-[3px]"
|
||||
role="tablist"
|
||||
:aria-label="$t('chat.procurementContract.mode')"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
class="rounded-full px-3 py-1.5 text-xs font-bold transition-all"
|
||||
:class="procurementReviewMode === 'compare'
|
||||
? 'bg-white text-[#2f80d1] shadow-[0_1px_4px_rgba(23,32,51,0.08)]'
|
||||
: 'bg-transparent text-[#667792] hover:text-[#172033]'"
|
||||
:aria-selected="procurementReviewMode === 'compare'"
|
||||
@click="procurementReviewMode = 'compare'"
|
||||
>
|
||||
{{ $t('chat.procurementContract.modeCompare') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
class="rounded-full px-3 py-1.5 text-xs font-bold transition-all"
|
||||
:class="procurementReviewMode === 'solo'
|
||||
? 'bg-white text-[#2f80d1] shadow-[0_1px_4px_rgba(23,32,51,0.08)]'
|
||||
: 'bg-transparent text-[#667792] hover:text-[#172033]'"
|
||||
:aria-selected="procurementReviewMode === 'solo'"
|
||||
@click="procurementReviewMode = 'solo'"
|
||||
>
|
||||
{{ $t('chat.procurementContract.modeSolo') }}
|
||||
</button>
|
||||
</div>
|
||||
<span class="text-xs text-[#667792]">
|
||||
{{ $t(procurementReviewMode === 'compare'
|
||||
? 'chat.procurementContract.compareHint'
|
||||
: 'chat.procurementContract.soloHint') }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col rounded-2xl bg-surface p-1.5 shadow-[0_0_15px_rgba(0,0,0,0.05)] transition-all">
|
||||
<div
|
||||
v-if="isShippingNoticeAgent && shippingFocusTaskNo"
|
||||
@@ -307,12 +405,40 @@ watch(
|
||||
@change="emit('local-files-selected', $event)"
|
||||
/>
|
||||
|
||||
<input
|
||||
ref="originalContractPickerRef"
|
||||
type="file"
|
||||
class="hidden"
|
||||
accept=".pdf,.doc,.docx,.txt,.md"
|
||||
@change="emit('procurement-original-contract-selected', $event)"
|
||||
/>
|
||||
|
||||
<div
|
||||
v-if="isProcurementContractAgent && procurementReviewMode === 'compare' && procurementOriginalContractName"
|
||||
class="flex flex-wrap gap-2 px-3 pb-1"
|
||||
>
|
||||
<div class="flex items-center gap-2 rounded-lg border border-dashed border-[#8db8e6] bg-[#eef6ff] px-2 py-1 text-xs font-semibold text-[#1f5f99]">
|
||||
<FileText class="h-3.5 w-3.5" />
|
||||
<span class="max-w-[260px] truncate">{{ $t('chat.procurementContract.originalContractChip', { name: procurementOriginalContractName }) }}</span>
|
||||
<button type="button" class="text-[#1f5f99] hover:opacity-80" @click="emit('clear-procurement-original-contract')">
|
||||
<X class="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="attachments.length > 0" class="flex flex-wrap gap-2 px-3 pb-1">
|
||||
<div
|
||||
v-for="a in attachments"
|
||||
:key="a.id"
|
||||
class="flex items-center gap-2 rounded-lg border border-default bg-surface-soft px-2 py-1 text-xs text-secondary"
|
||||
class="flex items-center gap-2 rounded-lg border px-2 py-1 text-xs"
|
||||
:class="isProcurementContractAgent && a.kind === 'local'
|
||||
? 'border-[#9cc7f2] bg-[#eef6ff] font-semibold text-[#1f5f99]'
|
||||
: 'border-default bg-surface-soft text-secondary'"
|
||||
>
|
||||
<FileText
|
||||
v-if="isProcurementContractAgent && a.kind === 'local'"
|
||||
class="h-3.5 w-3.5 shrink-0 text-[#2f80d1]"
|
||||
/>
|
||||
<span class="max-w-[220px] truncate">
|
||||
<template v-if="a.kind === 'shipping_notice'">
|
||||
{{ a.originalFilename }}
|
||||
@@ -351,6 +477,11 @@ watch(
|
||||
<span v-else-if="a.parseStatus === 'failed'" class="text-muted"> · {{ t('chat.shippingNoticeParseFailed') }}</span>
|
||||
</template>
|
||||
<template v-else>
|
||||
<span v-if="isProcurementContractAgent" class="mr-1 text-[#2f80d1]">
|
||||
{{ $t(procurementReviewMode === 'compare'
|
||||
? 'chat.procurementContract.sellerReturnedContractLabel'
|
||||
: 'chat.procurementContract.contractToReviewLabel') }}:
|
||||
</span>
|
||||
{{ a.kind === 'local' ? a.file.name : a.url }}
|
||||
</template>
|
||||
</span>
|
||||
@@ -378,6 +509,22 @@ watch(
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="hasProcurementContractAttachment"
|
||||
class="flex flex-wrap items-center gap-2 px-3 pb-1"
|
||||
>
|
||||
<button
|
||||
v-for="action in procurementQuickActions"
|
||||
:key="action.label"
|
||||
type="button"
|
||||
class="rounded-full border border-[#d8e0ec] bg-white px-3 py-1.5 text-xs font-semibold text-[#31445f] transition-colors hover:border-[#2f80d1] hover:bg-[#eef6ff] hover:text-[#1f5f99] disabled:cursor-not-allowed disabled:opacity-50"
|
||||
:disabled="isThinking || isUploadingAttachments"
|
||||
@click="runProcurementQuickAction(action.prompt)"
|
||||
>
|
||||
{{ $t(action.label) }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="isShippingNoticeAgent && attachments.length > 0"
|
||||
class="flex flex-wrap items-center gap-2 px-3 pb-1 text-xs text-muted"
|
||||
@@ -471,7 +618,47 @@ watch(
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="!isMaintenanceAgent" ref="kbMenuRef" class="relative">
|
||||
<div v-if="isProcurementContractAgent && procurementReviewMode === 'compare'" class="flex flex-wrap items-center gap-1.5">
|
||||
<button
|
||||
type="button"
|
||||
class="flex items-center gap-1 rounded-full border border-[#8db8e6] bg-[#f8fbff] px-3 py-1.5 text-xs font-semibold text-[#1f5f99] transition-colors hover:border-[#2f80d1] hover:bg-[#eef6ff] disabled:cursor-not-allowed disabled:opacity-50"
|
||||
:disabled="isThinking || isUploadingAttachments"
|
||||
@click="originalContractPickerRef?.click()"
|
||||
>
|
||||
<Upload class="h-3.5 w-3.5" />
|
||||
{{ $t('chat.procurementContract.uploadOriginalContract') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="flex items-center gap-1 rounded-full bg-[#2f80d1] px-3 py-1.5 text-xs font-semibold text-white shadow-sm transition-colors hover:bg-[#2369ad] disabled:cursor-not-allowed disabled:opacity-50"
|
||||
:disabled="isThinking || isUploadingAttachments || !attachmentPolicy.canLocal"
|
||||
:title="$t('chat.procurementContract.uploadSellerReturnedContract')"
|
||||
@click="selectProcurementContractLocal"
|
||||
>
|
||||
<Upload class="h-3.5 w-3.5" />
|
||||
{{ $t('chat.procurementContract.uploadSellerReturnedContract') }}
|
||||
</button>
|
||||
</div>
|
||||
<div
|
||||
v-else-if="isProcurementContractAgent"
|
||||
class="flex flex-wrap items-center gap-1.5"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="flex items-center gap-1 rounded-full bg-[#2f80d1] px-3 py-1.5 text-xs font-semibold text-white shadow-sm transition-colors hover:bg-[#2369ad] disabled:cursor-not-allowed disabled:opacity-50"
|
||||
:disabled="isThinking || isUploadingAttachments || !attachmentPolicy.canLocal"
|
||||
:title="$t('chat.procurementContract.uploadContractToReview')"
|
||||
@click="selectProcurementContractLocal"
|
||||
>
|
||||
<Upload class="h-3.5 w-3.5" />
|
||||
{{ $t('chat.procurementContract.uploadContractToReview') }}
|
||||
</button>
|
||||
<span class="rounded-full border border-dashed border-[#d8e0ec] px-3 py-1.5 text-xs font-semibold text-[#667792]">
|
||||
{{ $t('chat.procurementContract.soloHint') }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div v-else-if="!isMaintenanceAgent" ref="kbMenuRef" class="relative">
|
||||
<button
|
||||
type="button"
|
||||
:disabled="kbDropdownDisabled"
|
||||
|
||||
@@ -264,6 +264,7 @@ watch(() => page.currentAgentId, () => {
|
||||
:key="`${page.currentAgentId}-${page.conversationId || 'draft'}-${page.messages.length}`"
|
||||
v-model="page.input"
|
||||
v-model:selected-kb="page.selectedKb"
|
||||
v-model:procurement-review-mode="page.procurementReviewMode"
|
||||
:attachments="page.attachments"
|
||||
:attachment-policy="page.attachmentPolicy"
|
||||
:available-kb-options="page.availableKbOptions"
|
||||
@@ -274,6 +275,8 @@ watch(() => page.currentAgentId, () => {
|
||||
:is-uploading-attachments="page.isUploadingAttachments"
|
||||
:can-send-message="page.canSendMessage"
|
||||
:is-shipping-notice-agent="page.isShippingNoticeAgent"
|
||||
:is-procurement-contract-agent="page.isProcurementContractAgent"
|
||||
:procurement-original-contract-name="page.procurementOriginalContractName"
|
||||
:is-maintenance-agent="isMaintenanceAgentPage"
|
||||
:can-manage-maintenance="canManageMaintenance"
|
||||
:shipping-suggested-prompt="page.shippingSuggestedPrompt"
|
||||
@@ -295,6 +298,8 @@ watch(() => page.currentAgentId, () => {
|
||||
@maintenance-ledger-config="maintenancePanel = 'ledger'"
|
||||
@maintenance-create-record="openBlankMaintenanceRecordCreate"
|
||||
@clear-shipping-focus="page.clearShippingFocus"
|
||||
@procurement-original-contract-selected="page.handleProcurementOriginalContractSelected"
|
||||
@clear-procurement-original-contract="page.clearProcurementOriginalContract"
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
/**
|
||||
* features/chat/components/messages/ChatMessageBubble.vue
|
||||
* 用途:渲染单条聊天消息,统一承接用户气泡、助手 Markdown、内嵌文件下载、请假/出货子组件与操作栏。
|
||||
* 依赖:Vue computed、lucide 图标、Leave/Shipping 子消息组件、chat.types 与页面级 handlers。
|
||||
* 逻辑:由 ChatMessageList 按消息逐条挂载;正文渲染与特殊交互委托 useChatPageMarkdown 等页面编排层提供的 handlers。
|
||||
* 用途:渲染单条聊天消息,统一承接用户气泡、助手 Markdown、内嵌文件下载、请假/出货/合同审查子组件与操作栏。
|
||||
* 依赖:Vue computed、lucide 图标、Leave/Shipping/ContractReview 子消息组件、chat.types 与页面级 handlers。
|
||||
* 逻辑:由 ChatMessageList 按消息逐条挂载;合同审查结果卡自带边框,外层不再套 chat-msg-assistant 气泡以免双层框。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, ref, watch } from 'vue';
|
||||
@@ -10,6 +10,7 @@ import { Check, Copy, Download, Edit2, Eye, LayoutGrid, MessageSquareText, Rotat
|
||||
import { useAuthStore } from '@/features/auth/stores/auth.store';
|
||||
import LeaveMessageBlock, { type LeaveMessageHandlers } from './LeaveMessageBlock.vue';
|
||||
import MaintenanceDeviceResultCard from './MaintenanceDeviceResultCard.vue';
|
||||
import ContractReviewResultCard from './ContractReviewResultCard.vue';
|
||||
import ShippingInventoryMappingMessage, { type ShippingMappingHandlers } from './ShippingInventoryMappingMessage.vue';
|
||||
import ShippingMatchResultCard from './ShippingMatchResultCard.vue';
|
||||
import ShippingParseReviewMessage, { type ShippingParseReviewHandlers } from './ShippingParseReviewMessage.vue';
|
||||
@@ -87,6 +88,9 @@ const authStore = useAuthStore();
|
||||
const INLINE_DOWNLOAD_ALLOWED_EMPLOYEE_ID = '17070141';
|
||||
const RESTRICTED_INLINE_DOWNLOAD_FILE_NAME = '资产明细全量导出表.csv';
|
||||
|
||||
/** 合同审查结果卡:自身已是完整卡片,外层只需透明容器。 */
|
||||
const isContractReviewMessage = computed(() => message.type === 'procurement-contract-review');
|
||||
|
||||
const isLeaveMessage = computed(() =>
|
||||
message.type === 'leave-form'
|
||||
|| message.type === 'leave-confirmation'
|
||||
@@ -626,7 +630,9 @@ function handleInlineDownload(file: InlineDownloadFile): void {
|
||||
class="text-[15px] leading-relaxed"
|
||||
:class="message.role === 'user'
|
||||
? 'rounded-2xl rounded-tr-sm bg-brand-600 px-5 py-2.5 text-white shadow-sm shadow-brand-500/15'
|
||||
: 'chat-msg-assistant'"
|
||||
: isContractReviewMessage
|
||||
? 'w-full'
|
||||
: 'chat-msg-assistant'"
|
||||
>
|
||||
<div v-if="message.role === 'user'" class="whitespace-pre-wrap">{{ message.content }}</div>
|
||||
<div v-else>
|
||||
@@ -664,6 +670,10 @@ function handleInlineDownload(file: InlineDownloadFile): void {
|
||||
@view-record-history="emit('maintenance-view-record-history', $event)"
|
||||
@create-record="emit('maintenance-create-record-for-device', $event)"
|
||||
/>
|
||||
<ContractReviewResultCard
|
||||
v-else-if="message.type === 'procurement-contract-review'"
|
||||
:message="message"
|
||||
/>
|
||||
<TrainingExamQuestionMessage
|
||||
v-else-if="isTrainingExamMessage && trainingHandlers.getQuestion()"
|
||||
:question="trainingHandlers.getQuestion()!"
|
||||
|
||||
@@ -0,0 +1,738 @@
|
||||
/**
|
||||
* features/chat/components/messages/ContractReviewResultCard.vue
|
||||
* 用途:在聊天会话中渲染采购合同审查结果卡(改动项、独立风险项 + 下载报告)。
|
||||
* 依赖:vue-i18n、procurement-contract.api、chat.types。
|
||||
* 逻辑:queued/running 展示审核步骤;成功后按来源拆分合同改动与独立风险;比对模式不展示 OCR 待确认主列表。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed, onUnmounted, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { Check, Loader2 } from 'lucide-vue-next';
|
||||
import {
|
||||
downloadChatAnnotatedContract,
|
||||
downloadChatContractReviewReport,
|
||||
getChatContractReview,
|
||||
type ContractClauseItem,
|
||||
type ContractReviewRow,
|
||||
} from '@/features/admin/api/procurement-contract.api';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import type { ChatMessage } from '../../types/chat.types';
|
||||
|
||||
const props = defineProps<{ message: ChatMessage }>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const msg = useMessage();
|
||||
const downloading = ref(false);
|
||||
const downloadingAnnotated = ref(false);
|
||||
const latestReview = ref<ContractReviewRow | null>(null);
|
||||
let refreshTimer: ReturnType<typeof window.setTimeout> | undefined;
|
||||
let refreshing = false;
|
||||
let disposed = false;
|
||||
|
||||
const review = computed<ContractReviewRow | null>(() => {
|
||||
if (latestReview.value) return latestReview.value;
|
||||
const raw = props.message.payload;
|
||||
return raw && typeof raw === 'object' ? raw as ContractReviewRow : null;
|
||||
});
|
||||
const clauses = computed<ContractClauseItem[]>(() =>
|
||||
Array.isArray(review.value?.clauses_json) ? review.value.clauses_json : [],
|
||||
);
|
||||
const isCompareMode = computed(() => review.value?.review_mode === 'compare');
|
||||
const confirmedChangeTypes = new Set(['insert', 'delete', 'modify']);
|
||||
const independentRiskTypes = new Set(['missing', 'rule_scan', 'policy_scan', 'llm_scan']);
|
||||
const changeClauses = computed(() => clauses.value.filter((clause) =>
|
||||
confirmedChangeTypes.has(clause.change_type || ''),
|
||||
));
|
||||
const independentRiskClauses = computed(() => clauses.value.filter((clause) =>
|
||||
independentRiskTypes.has(clause.change_type || '')
|
||||
&& clause.risk_level !== 'ok'
|
||||
&& clause.validation_status !== 'needs_review',
|
||||
));
|
||||
/** 比对模式不展示待确认主列表;单份模式仅保留策略 OCR 待确认。 */
|
||||
const confirmationClauses = computed(() => {
|
||||
if (isCompareMode.value) return [];
|
||||
return clauses.value.filter((clause) =>
|
||||
clause.change_type === 'ocr_uncertain' || clause.validation_status === 'needs_review',
|
||||
);
|
||||
});
|
||||
const clauseSections = computed(() => {
|
||||
const sections = [
|
||||
{ key: 'changes', title: t('chat.procurementContract.sectionChanges'), clauses: changeClauses.value },
|
||||
{ key: 'risks', title: t('chat.procurementContract.sectionIndependentRisks'), clauses: independentRiskClauses.value },
|
||||
];
|
||||
if (!isCompareMode.value) {
|
||||
sections.push({
|
||||
key: 'confirmations',
|
||||
title: t('chat.procurementContract.sectionConfirmations'),
|
||||
clauses: confirmationClauses.value,
|
||||
});
|
||||
}
|
||||
return sections.filter((section) => section.clauses.length > 0);
|
||||
});
|
||||
const changeCount = computed(() => review.value?.total_change_count ?? changeClauses.value.length);
|
||||
const comparisonQuality = computed<Record<string, unknown>>(() => {
|
||||
const raw = review.value?.summary_json?.comparison_quality;
|
||||
return raw && typeof raw === 'object' ? raw as Record<string, unknown> : {};
|
||||
});
|
||||
const comparisonScope = computed<Record<string, unknown>>(() => {
|
||||
const raw = review.value?.summary_json?.comparison_scope;
|
||||
return raw && typeof raw === 'object' ? raw as Record<string, unknown> : {};
|
||||
});
|
||||
const attachmentComparison = computed<Record<string, unknown>>(() => {
|
||||
const raw = review.value?.summary_json?.attachment_comparison;
|
||||
return raw && typeof raw === 'object' ? raw as Record<string, unknown> : {};
|
||||
});
|
||||
const attachmentNotice = computed(() => {
|
||||
const status = String(attachmentComparison.value.status || '');
|
||||
const added = Number(attachmentComparison.value.added_pages || 0);
|
||||
const removed = Number(attachmentComparison.value.removed_pages || 0);
|
||||
if (status === 'added' && added > 0) return t('chat.procurementContract.attachmentAdded', { count: added });
|
||||
if (status === 'removed' && removed > 0) return t('chat.procurementContract.attachmentRemoved', { count: removed });
|
||||
return '';
|
||||
});
|
||||
const confirmationTotal = computed(() => {
|
||||
if (isCompareMode.value) return 0;
|
||||
const raw = comparisonQuality.value.needs_confirmation;
|
||||
return typeof raw === 'number' ? raw : confirmationClauses.value.length;
|
||||
});
|
||||
const confirmationHiddenCount = computed(() => Math.max(0, confirmationTotal.value - confirmationClauses.value.length));
|
||||
const isProcessing = computed(() => ['queued', 'running'].includes(review.value?.status || ''));
|
||||
|
||||
interface ReviewProgressStep {
|
||||
stage: string;
|
||||
label: string;
|
||||
milestone: number;
|
||||
state: 'completed' | 'active' | 'pending';
|
||||
}
|
||||
|
||||
const REVIEW_PROGRESS_STAGE_ORDER = [
|
||||
'queued',
|
||||
'extracting',
|
||||
'structuring',
|
||||
'deterministic_review',
|
||||
'llm_reviewing',
|
||||
'validating',
|
||||
'success',
|
||||
];
|
||||
|
||||
/**
|
||||
* 构建完整审核步骤轨道,并根据后端 processing_stage 标记已完成、当前和未开始阶段。
|
||||
* 核心逻辑:阶段顺序由前后端稳定协议确定;比对与单份审核仅替换确定性审核步骤文案。
|
||||
* @returns 含阶段文案、里程碑进度和展示状态的七步轨道
|
||||
*/
|
||||
const reviewProgressSteps = computed<ReviewProgressStep[]>(() => {
|
||||
const currentStage = review.value?.processing_stage || 'queued';
|
||||
const currentIndex = Math.max(0, REVIEW_PROGRESS_STAGE_ORDER.indexOf(currentStage));
|
||||
const labels = [
|
||||
t('chat.procurementContract.stepQueued'),
|
||||
t('chat.procurementContract.stepExtracting'),
|
||||
t('chat.procurementContract.stepStructuring'),
|
||||
t(review.value?.review_mode === 'solo'
|
||||
? 'chat.procurementContract.stepRiskScanning'
|
||||
: 'chat.procurementContract.stepComparing'),
|
||||
t('chat.procurementContract.stepAiReviewing'),
|
||||
t('chat.procurementContract.stepValidating'),
|
||||
t('chat.procurementContract.stepCompleted'),
|
||||
];
|
||||
const milestones = [0, 10, 30, 45, 60, 88, 100];
|
||||
return REVIEW_PROGRESS_STAGE_ORDER.map((stage, index) => ({
|
||||
stage,
|
||||
label: labels[index] || stage,
|
||||
milestone: milestones[index] ?? 0,
|
||||
state: index < currentIndex ? 'completed' : index === currentIndex ? 'active' : 'pending',
|
||||
}));
|
||||
});
|
||||
const cardStatusTitle = computed(() => {
|
||||
if (isProcessing.value) return t('chat.procurementContract.reviewRunning');
|
||||
if (review.value?.status === 'failed') return t('chat.procurementContract.reviewFailed');
|
||||
return t('chat.procurementContract.completed');
|
||||
});
|
||||
const reportDownloadLabel = computed(() => t(
|
||||
isCompareMode.value
|
||||
? 'chat.procurementContract.downloadDifferenceReport'
|
||||
: 'chat.procurementContract.downloadReport',
|
||||
));
|
||||
/**
|
||||
* Refresh a persisted in-progress card after the user reloads or reopens a chat.
|
||||
* The initial send flow also polls, but this local polling prevents an old card from freezing
|
||||
* when the page was closed before its worker job reached a terminal state.
|
||||
*/
|
||||
function scheduleReviewRefresh(): void {
|
||||
if (disposed) return;
|
||||
if (refreshTimer !== undefined) {
|
||||
window.clearTimeout(refreshTimer);
|
||||
refreshTimer = undefined;
|
||||
}
|
||||
const reviewNo = review.value?.review_no;
|
||||
if (!reviewNo || !isProcessing.value) return;
|
||||
refreshTimer = window.setTimeout(async () => {
|
||||
if (refreshing) return;
|
||||
refreshing = true;
|
||||
try {
|
||||
latestReview.value = await getChatContractReview(reviewNo);
|
||||
} catch (error) {
|
||||
// A temporary network error must not turn a still-running review into a failed result.
|
||||
console.warn('Failed to refresh procurement contract review', error);
|
||||
} finally {
|
||||
refreshing = false;
|
||||
if (!disposed) scheduleReviewRefresh();
|
||||
}
|
||||
}, 2000);
|
||||
}
|
||||
|
||||
watch(
|
||||
() => [review.value?.review_no, isProcessing.value] as const,
|
||||
() => scheduleReviewRefresh(),
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
onUnmounted(() => {
|
||||
disposed = true;
|
||||
if (refreshTimer !== undefined) window.clearTimeout(refreshTimer);
|
||||
});
|
||||
|
||||
/**
|
||||
* 页头右侧风险徽标文案:有高风险时强调数量,否则提示无高风险。
|
||||
* @returns 已本地化徽标文案
|
||||
*/
|
||||
const headerRiskBadge = computed(() => {
|
||||
const high = review.value?.high_risk_count ?? 0;
|
||||
if (high > 0) {
|
||||
return t('chat.procurementContract.containsHighRisk', { count: high });
|
||||
}
|
||||
return t('chat.procurementContract.noHighRisk');
|
||||
});
|
||||
|
||||
/**
|
||||
* 比对基准来源徽标;历史库内模板显示模板库,新流程显示本次上传。
|
||||
* @returns 本地化来源文案,无则 null
|
||||
*/
|
||||
const templateSourceLabel = computed(() => {
|
||||
const source = review.value?.template_source;
|
||||
if (source === 'library') return t('chat.procurementContract.sourceLibrary');
|
||||
if (source === 'user_upload') return t('chat.procurementContract.sourceUpload');
|
||||
return null;
|
||||
});
|
||||
|
||||
/**
|
||||
* 返回表格风险列的短标签(高 / 中 / 低),对齐原型单字徽标。
|
||||
* @param level - 风险等级
|
||||
* @param isComparisonChange - 是否为合同对比中的已识别差异;无风险时避免误称“通过”
|
||||
*/
|
||||
function riskShortLabel(level?: string | null, isComparisonChange = false): string {
|
||||
if (level === 'high') return t('chat.procurementContract.riskShortHigh');
|
||||
if (level === 'medium') return t('chat.procurementContract.riskShortMedium');
|
||||
if (level === 'low') return t('chat.procurementContract.riskShortLow');
|
||||
if (level === 'ok' && isComparisonChange) return t('chat.procurementContract.riskNoFinding');
|
||||
if (level === 'ok') return t('chat.procurementContract.riskOk');
|
||||
return level || '-';
|
||||
}
|
||||
|
||||
/**
|
||||
* 风险徽标样式(高/中/低/通过)。
|
||||
* @param level - 风险等级
|
||||
*/
|
||||
function riskBadgeClass(level?: string | null): string {
|
||||
if (level === 'high') return 'border-[#fecdca] bg-[#fef3f2] text-[#b42318]';
|
||||
if (level === 'medium') return 'border-[#fedf89] bg-[#fffaeb] text-[#b54708]';
|
||||
if (level === 'low') return 'border-[#b2ddff] bg-[#eff8ff] text-[#175cd3]';
|
||||
if (level === 'ok') return 'border-[#abe6c5] bg-[#ecfdf3] text-[#067647]';
|
||||
return 'border-[#d8e0ec] bg-white text-[#667792]';
|
||||
}
|
||||
|
||||
/**
|
||||
* 变更类型本地化文案。
|
||||
* @param type - 变更类型
|
||||
*/
|
||||
function changeTypeLabel(type?: string | null): string {
|
||||
if (type === 'insert') return t('chat.procurementContract.changeInsert');
|
||||
if (type === 'delete') return t('chat.procurementContract.changeDelete');
|
||||
if (type === 'modify') return t('chat.procurementContract.changeModify');
|
||||
if (type === 'pass') return t('chat.procurementContract.changePass');
|
||||
if (type === 'missing') return t('chat.procurementContract.changeMissing');
|
||||
if (type === 'rule_scan') return t('chat.procurementContract.changeRuleScan');
|
||||
if (type === 'policy_scan') return t('chat.procurementContract.changePolicyScan');
|
||||
if (type === 'llm_scan') return t('chat.procurementContract.changeLlmScan');
|
||||
if (type === 'ocr_uncertain') return t('chat.procurementContract.changeOcrUncertain');
|
||||
return type || '-';
|
||||
}
|
||||
|
||||
/**
|
||||
* 条款列展示:优先可读标题(规则名 /「变更段 #N」),不用 Diff 序号。
|
||||
* @param clause - 条款项
|
||||
*/
|
||||
function clauseLabel(clause: ContractClauseItem): string {
|
||||
const title = (clause.title || '').trim();
|
||||
if (title) return title;
|
||||
return clause.clause_no || '-';
|
||||
}
|
||||
|
||||
/** 展示审核证据在原 PDF 中的页码;未定位时返回空串。 */
|
||||
function anchorPageLabel(clause: ContractClauseItem): string {
|
||||
const pageNo = clause.evidence_anchor?.page_no;
|
||||
return pageNo ? t('chat.procurementContract.anchorPage', { page: pageNo }) : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 清洗 PDF 缺字占位与私用区字符,避免豆腐字进入对照列。
|
||||
* @param value - 抽取文本
|
||||
*/
|
||||
function cleanExtractedText(value?: string | null): string {
|
||||
return (value || '')
|
||||
.replace(/[\u25a0-\u25ff\ufffd\ue000-\uf8ff]+/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断抽取片段是否足够可读(与后端 _is_readable_extracted_text 同口径)。
|
||||
* @param value - 待展示对照文本
|
||||
*/
|
||||
function isReadableComparisonText(value?: string | null): boolean {
|
||||
const raw = value || '';
|
||||
if (!raw.trim() || raw.startsWith('[binary:')) return false;
|
||||
const compactRaw = raw.replace(/\s+/g, '');
|
||||
if (!compactRaw) return false;
|
||||
const tofu = (compactRaw.match(/[\u25a0-\u25ff\ufffd\ue000-\uf8ff]/g) || []).length;
|
||||
if (tofu / compactRaw.length >= 0.1) return false;
|
||||
const cleaned = cleanExtractedText(raw).replace(/\s+/g, '');
|
||||
if (cleaned.length < 4) return false;
|
||||
const useful = (cleaned.match(/[\u4e00-\u9fffA-Za-z0-9]/g) || []).length;
|
||||
return useful / cleaned.length >= 0.5;
|
||||
}
|
||||
|
||||
/**
|
||||
* 截取条款摘要,优先匹配标题相关商务关键词句,控制单元格宽度。
|
||||
* @param value - 原文
|
||||
* @param title - 条款标题(用于关键词打分)
|
||||
*/
|
||||
function clauseExcerpt(value: string | null | undefined, title?: string): string {
|
||||
if (!isReadableComparisonText(value)) return '';
|
||||
const cleaned = cleanExtractedText(value);
|
||||
if (!cleaned) return '';
|
||||
const sentences = cleaned.split(/(?<=[。!?;;])\s*|\s+(?=第[一二三四五六七八九十百\d]+[条章节、..])/).filter(Boolean);
|
||||
const businessKeywords = ['付款', '支付', '验收', '发票', '交付', '质保', '保修', '违约', '赔偿', '管辖', '仲裁', '保密', '知识产权'];
|
||||
const keywords = businessKeywords.filter((keyword) => (title || '').includes(keyword));
|
||||
const matched = sentences
|
||||
.map((sentence) => ({ sentence, score: keywords.filter((keyword) => sentence.includes(keyword)).length }))
|
||||
.sort((a, b) => b.score - a.score)
|
||||
.find((item) => item.score > 0)?.sentence;
|
||||
const excerpt = matched || sentences.find((sentence) => sentence.length >= 8) || cleaned;
|
||||
return excerpt.length > 180 ? `${excerpt.slice(0, 180)}...` : excerpt;
|
||||
}
|
||||
|
||||
/**
|
||||
* 组装变更对照:可读时展示模板/合同抽取片段;否则提示编码不兼容。
|
||||
* 说明:对照列是抽取后的删改摘录,不是 PDF 像素级原文。
|
||||
* @param clause - 条款项
|
||||
*/
|
||||
function clauseComparison(clause: ContractClauseItem): {
|
||||
before: string;
|
||||
after: string;
|
||||
unreadable: boolean;
|
||||
note: string;
|
||||
} {
|
||||
const before = clauseExcerpt(clause.old_text, clause.title);
|
||||
const after = clauseExcerpt(clause.new_text, clause.title);
|
||||
if (before || after) {
|
||||
return { before, after, unreadable: false, note: '' };
|
||||
}
|
||||
const hasBinaryPlaceholder = [clause.old_text, clause.new_text]
|
||||
.some((value) => (value || '').trim().startsWith('[binary:'));
|
||||
const unreadable = clause.comparison_readable === false && hasBinaryPlaceholder;
|
||||
const evidence = cleanExtractedText(clause.evidence || clause.evidence_anchor?.matched_text || '');
|
||||
const fallback = cleanExtractedText(clause.detail || clause.risk_hint || '');
|
||||
if (unreadable) {
|
||||
return { before: '', after: '', unreadable: true, note: fallback };
|
||||
}
|
||||
return { before: '', after: evidence, unreadable: false, note: evidence ? '' : fallback };
|
||||
}
|
||||
|
||||
/** 风险项的建议独立展示,避免误标成“对方合同原文”。 */
|
||||
function clauseSuggestion(clause: ContractClauseItem): string {
|
||||
return cleanExtractedText(clause.llm_suggestion || clause.suggestion || clause.negotiation_text || '');
|
||||
}
|
||||
|
||||
type DiffPiece = { text: string; changed: boolean };
|
||||
|
||||
/**
|
||||
* Build a compact character-level diff for one template/contract excerpt.
|
||||
*
|
||||
* The backend stores only the two excerpts. Computing the visual marks here keeps old review
|
||||
* records readable too: removed template text is red and added counterparty text is green.
|
||||
*/
|
||||
function buildInlineDiff(before: string, after: string): { before: DiffPiece[]; after: DiffPiece[] } {
|
||||
if (!before || !after) {
|
||||
return {
|
||||
before: before ? [{ text: before, changed: true }] : [],
|
||||
after: after ? [{ text: after, changed: true }] : [],
|
||||
};
|
||||
}
|
||||
|
||||
let prefixLength = 0;
|
||||
const maxPrefix = Math.min(before.length, after.length);
|
||||
while (prefixLength < maxPrefix && before[prefixLength] === after[prefixLength]) prefixLength += 1;
|
||||
|
||||
let suffixLength = 0;
|
||||
const beforeRemaining = before.length - prefixLength;
|
||||
const afterRemaining = after.length - prefixLength;
|
||||
while (
|
||||
suffixLength < beforeRemaining
|
||||
&& suffixLength < afterRemaining
|
||||
&& before[before.length - 1 - suffixLength] === after[after.length - 1 - suffixLength]
|
||||
) suffixLength += 1;
|
||||
|
||||
const beforeChangedEnd = before.length - suffixLength;
|
||||
const afterChangedEnd = after.length - suffixLength;
|
||||
const prefix = before.slice(0, prefixLength);
|
||||
const suffix = suffixLength ? before.slice(beforeChangedEnd) : '';
|
||||
const beforePieces: DiffPiece[] = [];
|
||||
const afterPieces: DiffPiece[] = [];
|
||||
if (prefix) {
|
||||
beforePieces.push({ text: prefix, changed: false });
|
||||
afterPieces.push({ text: prefix, changed: false });
|
||||
}
|
||||
if (before.slice(prefixLength, beforeChangedEnd)) {
|
||||
beforePieces.push({ text: before.slice(prefixLength, beforeChangedEnd), changed: true });
|
||||
}
|
||||
if (after.slice(prefixLength, afterChangedEnd)) {
|
||||
afterPieces.push({ text: after.slice(prefixLength, afterChangedEnd), changed: true });
|
||||
}
|
||||
if (suffix) {
|
||||
beforePieces.push({ text: suffix, changed: false });
|
||||
afterPieces.push({ text: suffix, changed: false });
|
||||
}
|
||||
return { before: beforePieces, after: afterPieces };
|
||||
}
|
||||
|
||||
/**
|
||||
* 下载当前会话用户的审查报告(Word .docx)。
|
||||
*/
|
||||
async function onDownloadReport(): Promise<void> {
|
||||
const reviewNo = review.value?.review_no;
|
||||
if (!reviewNo || downloading.value) return;
|
||||
downloading.value = true;
|
||||
try {
|
||||
await downloadChatContractReviewReport(reviewNo, 'docx');
|
||||
msg.success(t('chat.procurementContract.downloadOk'));
|
||||
} catch (error: unknown) {
|
||||
msg.warning(error instanceof Error ? error.message : t('chat.procurementContract.downloadFailed'));
|
||||
} finally {
|
||||
downloading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/** 下载当前合同的 PDF 风险高亮副本。 */
|
||||
async function onDownloadAnnotated(): Promise<void> {
|
||||
const reviewNo = review.value?.review_no;
|
||||
if (!reviewNo || downloadingAnnotated.value) return;
|
||||
downloadingAnnotated.value = true;
|
||||
try {
|
||||
await downloadChatAnnotatedContract(reviewNo);
|
||||
msg.success(t('chat.procurementContract.downloadAnnotatedOk'));
|
||||
} catch (error: unknown) {
|
||||
msg.warning(error instanceof Error ? error.message : t('chat.procurementContract.downloadAnnotatedFailed'));
|
||||
} finally {
|
||||
downloadingAnnotated.value = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<article
|
||||
v-if="review"
|
||||
class="w-full max-w-[860px] overflow-hidden rounded-2xl border border-[#d8e0ec] bg-white shadow-[0_14px_36px_rgba(23,32,51,0.08)]"
|
||||
>
|
||||
<!-- 页头:审查编号 + 合同/模板元信息 + 高风险徽标 -->
|
||||
<div class="flex flex-wrap items-start justify-between gap-3 border-b border-[#d8e0ec] bg-[#fbfcfe] px-4 py-3.5 md:px-4">
|
||||
<div class="min-w-0">
|
||||
<h3 class="m-0 text-[15px] font-bold leading-snug text-[#172033]">
|
||||
{{ cardStatusTitle }} · {{ review.review_no }}
|
||||
</h3>
|
||||
<div class="mt-1 space-y-0.5 text-xs leading-5 text-[#667792]">
|
||||
<p class="m-0">
|
||||
{{ t('chat.procurementContract.counterpartyContract') }}:{{ review.contract_file_name }}
|
||||
</p>
|
||||
<p v-if="review.contract_no" class="m-0">
|
||||
{{ t('chat.procurementContract.contractNo') }}:{{ review.contract_no }}
|
||||
</p>
|
||||
<p v-if="review.supplier_name" class="m-0">
|
||||
{{ t('chat.procurementContract.supplier') }}:{{ review.supplier_name }}
|
||||
</p>
|
||||
<p v-if="review.template_name" class="m-0 flex flex-wrap items-center gap-1.5">
|
||||
<span>{{ t(review.review_mode === 'compare'
|
||||
? 'chat.procurementContract.comparisonBaseline'
|
||||
: 'chat.procurementContract.template') }}:{{ review.template_name }}</span>
|
||||
<span
|
||||
v-if="templateSourceLabel"
|
||||
class="inline-flex items-center rounded-full border border-[#9ec5ea] bg-[#eaf4ff] px-2.5 py-0.5 text-[11px] font-semibold text-[#2f80d1]"
|
||||
>
|
||||
{{ templateSourceLabel }}
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<span
|
||||
v-if="!isProcessing"
|
||||
class="inline-flex shrink-0 items-center rounded-full border px-2.5 py-1 text-xs font-semibold"
|
||||
:class="review.high_risk_count > 0
|
||||
? 'border-[#fecdca] bg-[#fef3f2] text-[#b42318]'
|
||||
: 'border-[#abe6c5] bg-[#ecfdf3] text-[#067647]'"
|
||||
>
|
||||
{{ headerRiskBadge }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div v-if="review.error_message" class="mx-4 mt-4 rounded-xl border border-[#fecdca] bg-[#fef3f2] px-3 py-2 text-sm text-[#b42318]">
|
||||
{{ review.error_message }}
|
||||
</div>
|
||||
|
||||
<div v-if="isProcessing" class="px-4 py-5">
|
||||
<div class="overflow-x-auto pb-1">
|
||||
<ol class="grid min-w-[700px] grid-cols-7">
|
||||
<li
|
||||
v-for="(step, index) in reviewProgressSteps"
|
||||
:key="step.stage"
|
||||
class="relative flex min-w-0 flex-col items-center px-1 text-center"
|
||||
>
|
||||
<div
|
||||
v-if="index > 0"
|
||||
class="absolute right-1/2 top-3 h-0.5 w-full"
|
||||
:class="step.state === 'pending' ? 'bg-[#d8e0ec]' : 'bg-[#2f80d1]'"
|
||||
/>
|
||||
<div
|
||||
class="relative z-10 flex h-6 w-6 items-center justify-center rounded-full border-2 bg-white text-[10px] font-bold transition-colors duration-300"
|
||||
:class="step.state === 'completed'
|
||||
? 'border-[#2f80d1] bg-[#2f80d1] text-white'
|
||||
: step.state === 'active'
|
||||
? 'border-[#2f80d1] text-[#2f80d1] shadow-[0_0_0_4px_rgba(47,128,209,0.13)]'
|
||||
: 'border-[#cfd8e5] text-[#98a5b7]'"
|
||||
>
|
||||
<Check v-if="step.state === 'completed'" class="h-3.5 w-3.5" />
|
||||
<Loader2 v-else-if="step.state === 'active'" class="h-3.5 w-3.5 animate-spin" />
|
||||
<span v-else>{{ index + 1 }}</span>
|
||||
</div>
|
||||
<span
|
||||
class="mt-2 block text-[11px] leading-4"
|
||||
:class="step.state === 'active'
|
||||
? 'font-bold text-[#1f5f99]'
|
||||
: step.state === 'completed'
|
||||
? 'font-medium text-[#31445f]'
|
||||
: 'text-[#98a5b7]'"
|
||||
>
|
||||
{{ step.label }}
|
||||
</span>
|
||||
<span
|
||||
class="mt-0.5 text-[10px] tabular-nums"
|
||||
:class="step.state === 'pending' ? 'text-[#b0bac8]' : 'text-[#667792]'"
|
||||
>
|
||||
{{ step.milestone }}%
|
||||
</span>
|
||||
</li>
|
||||
</ol>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else class="px-4 py-3.5">
|
||||
<!-- 风险统计看板 -->
|
||||
<div class="mb-3.5 grid grid-cols-2 gap-2.5 md:grid-cols-4">
|
||||
<div class="rounded-xl border border-[#d8e0ec] bg-[#fafbfd] px-3 py-2.5">
|
||||
<div class="text-xs text-[#667792]">{{ t('chat.procurementContract.changesCount') }}</div>
|
||||
<div class="mt-0.5 text-xl font-bold text-[#2f80d1]">{{ changeCount }}</div>
|
||||
</div>
|
||||
<div class="rounded-xl border border-[#d8e0ec] bg-[#fafbfd] px-3 py-2.5">
|
||||
<div class="text-xs text-[#667792]">{{ t('chat.procurementContract.riskHigh') }}</div>
|
||||
<div class="mt-0.5 text-xl font-bold text-[#b42318]">{{ review.high_risk_count }}</div>
|
||||
</div>
|
||||
<div class="rounded-xl border border-[#d8e0ec] bg-[#fafbfd] px-3 py-2.5">
|
||||
<div class="text-xs text-[#667792]">{{ t('chat.procurementContract.riskMedium') }}</div>
|
||||
<div class="mt-0.5 text-xl font-bold text-[#b54708]">{{ review.medium_risk_count }}</div>
|
||||
</div>
|
||||
<div class="rounded-xl border border-[#d8e0ec] bg-[#fafbfd] px-3 py-2.5">
|
||||
<div class="text-xs text-[#667792]">{{ t('chat.procurementContract.riskLow') }}</div>
|
||||
<div class="mt-0.5 text-xl font-bold text-[#175cd3]">{{ review.low_risk_count }}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 按业务语义互斥拆分:模板改动、独立风险;比对模式不展示 OCR 待确认主列表。 -->
|
||||
<div
|
||||
v-if="isCompareMode && comparisonScope.status === 'fallback'"
|
||||
class="mb-3 rounded-xl border border-[#fedf89] bg-[#fffaeb] px-3 py-2 text-sm text-[#b54708]"
|
||||
>
|
||||
{{ t('chat.procurementContract.regionFallback') }}
|
||||
</div>
|
||||
<div
|
||||
v-if="attachmentNotice"
|
||||
class="mb-3 rounded-xl border border-[#9ec5ea] bg-[#eaf4ff] px-3 py-2 text-sm font-medium text-[#1f5f99]"
|
||||
>
|
||||
{{ attachmentNotice }} · {{ t('chat.procurementContract.attachmentContentIgnored') }}
|
||||
</div>
|
||||
<div v-if="clauses.length" class="space-y-4">
|
||||
<section v-for="section in clauseSections" :key="section.key" class="overflow-x-auto">
|
||||
<h4 class="mb-2 text-sm font-semibold text-[#31445f]">{{ section.title }}</h4>
|
||||
<table class="w-full min-w-[720px] table-fixed border-collapse text-[13px]">
|
||||
<colgroup>
|
||||
<col class="w-[24%]" />
|
||||
<col class="w-[12%]" />
|
||||
<col class="w-[44%]" />
|
||||
<col class="w-[20%]" />
|
||||
</colgroup>
|
||||
<thead>
|
||||
<tr class="bg-[#f8fafc] text-left text-xs font-semibold text-[#667792]">
|
||||
<th class="border-b border-[#d8e0ec] px-2 py-2.5">{{ t('chat.procurementContract.colClause') }}</th>
|
||||
<th class="border-b border-[#d8e0ec] px-2 py-2.5">{{ t('chat.procurementContract.colChange') }}</th>
|
||||
<th class="border-b border-[#d8e0ec] px-2 py-2.5">
|
||||
{{ section.key === 'changes'
|
||||
? t('chat.procurementContract.colComparison')
|
||||
: t('chat.procurementContract.colEvidence') }}
|
||||
</th>
|
||||
<th class="border-b border-[#d8e0ec] px-2 py-2.5">
|
||||
{{ section.key === 'changes'
|
||||
? t('chat.procurementContract.colRisk')
|
||||
: t('chat.procurementContract.colSuggestion') }}
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr
|
||||
v-for="(clause, index) in section.clauses"
|
||||
:key="`${section.key}-${clause.clause_no || clause.title || index}-${index}`"
|
||||
class="align-top"
|
||||
>
|
||||
<td class="break-words border-b border-[#d8e0ec] px-2 py-2.5 font-medium leading-5 text-[#172033]">
|
||||
{{ clauseLabel(clause) }}
|
||||
<span
|
||||
v-if="section.key === 'risks'"
|
||||
class="ml-1 inline-flex items-center rounded-full border px-2 py-0.5 text-[10px] font-semibold"
|
||||
:class="riskBadgeClass(clause.risk_level)"
|
||||
>
|
||||
{{ riskShortLabel(clause.risk_level) }}
|
||||
</span>
|
||||
<span
|
||||
v-if="anchorPageLabel(clause)"
|
||||
class="mt-1 block text-[11px] font-normal text-[#2f80d1]"
|
||||
>
|
||||
{{ anchorPageLabel(clause) }}
|
||||
</span>
|
||||
<span
|
||||
v-if="clause.validation_status === 'needs_review'"
|
||||
class="ml-1 inline-flex rounded border border-[#fedf89] bg-[#fffaeb] px-1.5 py-0.5 text-[10px] font-semibold text-[#b54708]"
|
||||
>{{ t('chat.procurementContract.needsReview') }}</span>
|
||||
</td>
|
||||
<td class="border-b border-[#d8e0ec] px-2 py-2.5 text-[#667792]">
|
||||
{{ changeTypeLabel(clause.change_type) }}
|
||||
</td>
|
||||
<td class="border-b border-[#d8e0ec] px-2 py-2.5">
|
||||
<div
|
||||
v-for="cmp in [clauseComparison(clause)]"
|
||||
:key="`${clause.clause_no || clause.title || index}-cmp`"
|
||||
class="grid gap-1 break-words"
|
||||
>
|
||||
<span
|
||||
v-if="cmp.before"
|
||||
class="grid gap-1 rounded border border-[#fecdca] bg-[#fef3f2] px-2 py-1.5 text-xs leading-5 text-[#667792]"
|
||||
>
|
||||
<span class="font-semibold text-[#b42318]">{{ t('chat.procurementContract.colTemplateText') }}</span>
|
||||
<span>
|
||||
<template v-for="(piece, pieceIndex) in buildInlineDiff(cmp.before, cmp.after).before" :key="`before-${pieceIndex}`">
|
||||
<mark v-if="piece.changed" class="rounded bg-[#fecdca] px-0.5 text-[#b42318] line-through">{{ piece.text }}</mark>
|
||||
<template v-else>{{ piece.text }}</template>
|
||||
</template>
|
||||
</span>
|
||||
</span>
|
||||
<span
|
||||
v-if="cmp.after"
|
||||
class="grid gap-1 rounded border border-[#abe6c5] bg-[#ecfdf3] px-2 py-1.5 text-xs leading-5 text-[#172033]"
|
||||
>
|
||||
<span class="font-semibold text-[#067647]">
|
||||
{{ section.key === 'changes'
|
||||
? t('chat.procurementContract.colContractText')
|
||||
: t('chat.procurementContract.colEvidence') }}
|
||||
</span>
|
||||
<span>
|
||||
<template v-for="(piece, pieceIndex) in buildInlineDiff(cmp.before, cmp.after).after" :key="`after-${pieceIndex}`">
|
||||
<mark v-if="piece.changed" class="rounded bg-[#abe6c5] px-0.5 text-[#067647]">{{ piece.text }}</mark>
|
||||
<template v-else>{{ piece.text }}</template>
|
||||
</template>
|
||||
</span>
|
||||
</span>
|
||||
<span
|
||||
v-if="!cmp.before && !cmp.after && cmp.unreadable"
|
||||
class="text-xs leading-5 text-[#b54708]"
|
||||
>{{ t('chat.procurementContract.unreadableComparison') }}</span>
|
||||
<span
|
||||
v-else-if="!cmp.before && !cmp.after && !cmp.note"
|
||||
class="text-xs text-[#667792]"
|
||||
>{{ t('chat.procurementContract.noComparisonText') }}</span>
|
||||
<span
|
||||
v-if="cmp.note"
|
||||
class="text-xs leading-5 text-[#31445f]"
|
||||
>{{ cmp.note }}</span>
|
||||
</div>
|
||||
</td>
|
||||
<td class="border-b border-[#d8e0ec] px-2 py-2.5">
|
||||
<span
|
||||
v-if="section.key === 'changes'"
|
||||
class="inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold"
|
||||
:class="riskBadgeClass(clause.risk_level)"
|
||||
>
|
||||
{{ riskShortLabel(clause.risk_level, true) }}
|
||||
</span>
|
||||
<span v-else class="text-xs leading-5 text-[#31445f]">
|
||||
{{ clauseSuggestion(clause) || clause.detail || '-' }}
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<p
|
||||
v-if="section.key === 'confirmations' && confirmationHiddenCount > 0"
|
||||
class="mt-2 text-xs text-[#667792]"
|
||||
>
|
||||
{{ t('chat.procurementContract.confirmationsHidden', { count: confirmationHiddenCount }) }}
|
||||
</p>
|
||||
</section>
|
||||
<p
|
||||
v-if="confirmationTotal > 0 && confirmationClauses.length === 0"
|
||||
class="rounded-xl border border-[#fedf89] bg-[#fffaeb] px-3 py-2 text-sm text-[#b54708]"
|
||||
>
|
||||
{{ t('chat.procurementContract.confirmationsSummary', { count: confirmationTotal }) }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<p
|
||||
v-else-if="review.status === 'success' && confirmationTotal > 0"
|
||||
class="rounded-xl border border-[#fedf89] bg-[#fffaeb] px-3 py-2 text-sm text-[#b54708]"
|
||||
>
|
||||
{{ t('chat.procurementContract.confirmationsSummary', { count: confirmationTotal }) }}
|
||||
</p>
|
||||
|
||||
<p v-else-if="review.status === 'success'" class="text-sm text-[#667792]">
|
||||
{{ t('chat.procurementContract.noClauses') }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- 底部操作:PDF 审核固定提供标注副本下载,扫描件由后端按 OCR 页码添加批注意见。 -->
|
||||
<div v-if="!isProcessing" class="flex flex-wrap gap-2 px-4 pb-3.5">
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex h-9 items-center rounded-[10px] bg-[#2f80d1] px-3.5 text-sm font-semibold text-white transition-colors hover:bg-[#276fb8] disabled:cursor-not-allowed disabled:opacity-50"
|
||||
:disabled="downloading || review.status === 'failed'"
|
||||
@click="onDownloadReport"
|
||||
>
|
||||
{{ downloading ? t('chat.procurementContract.downloading') : reportDownloadLabel }}
|
||||
</button>
|
||||
<button
|
||||
v-if="review.status === 'success' && review.contract_file_name?.toLowerCase().endsWith('.pdf')"
|
||||
type="button"
|
||||
class="inline-flex h-9 items-center rounded-[10px] border border-[#9ec5ea] bg-[#eaf4ff] px-3.5 text-sm font-semibold text-[#2f80d1] transition-colors hover:bg-[#dceeff] disabled:cursor-not-allowed disabled:opacity-50"
|
||||
:disabled="downloadingAnnotated"
|
||||
@click="onDownloadAnnotated"
|
||||
>
|
||||
{{ downloadingAnnotated
|
||||
? t('chat.procurementContract.downloading')
|
||||
: t('chat.procurementContract.downloadAnnotated') }}
|
||||
</button>
|
||||
</div>
|
||||
</article>
|
||||
</template>
|
||||
@@ -6,6 +6,7 @@ import { computed, ref, type ComputedRef, type Ref } from 'vue';
|
||||
import { uploadChatFile } from '../api/chat.api';
|
||||
import type { PendingAttachment } from '../types/shipping.types';
|
||||
import type { ChatDeps } from './chat.deps';
|
||||
import { isProcurementContractAgent as resolveProcurementContractAgent } from '@/shared/utils/agent-registry.utils';
|
||||
|
||||
type ChatUploadFileType = 'image' | 'document' | 'audio' | 'video' | 'custom';
|
||||
|
||||
@@ -23,6 +24,8 @@ const DIFY_SUPPORTED_EXTS: Record<Exclude<ChatUploadFileType, 'custom'>, Set<str
|
||||
video: new Set(['mp4', 'mov', 'mpeg', 'webm']),
|
||||
};
|
||||
|
||||
const PROCUREMENT_CONTRACT_EXTS = new Set(['pdf', 'doc', 'docx', 'txt', 'md', 'markdown']);
|
||||
|
||||
const extractExt = (value: string) => {
|
||||
const text = (value || '').trim().toLowerCase();
|
||||
const withoutQuery = (text.split('?')[0] || '').split('#')[0] || '';
|
||||
@@ -76,9 +79,11 @@ export function useChatAttachments(options: UseChatAttachmentsOptions) {
|
||||
return (currentAgent.value?.dify_parameters?.system_parameters as any) || {};
|
||||
});
|
||||
|
||||
const isProcurementContractAgent = computed(() => resolveProcurementContractAgent(currentAgent.value));
|
||||
|
||||
const attachmentPolicy = computed(() => {
|
||||
const fileUploadAllowed = currentAgent.value?.capabilities?.file_upload;
|
||||
if (fileUploadAllowed === false) {
|
||||
if (fileUploadAllowed === false && !isProcurementContractAgent.value) {
|
||||
return {
|
||||
anyEnabled: false,
|
||||
enabled: {
|
||||
@@ -172,6 +177,10 @@ export function useChatAttachments(options: UseChatAttachmentsOptions) {
|
||||
}
|
||||
}
|
||||
|
||||
if (isProcurementContractAgent.value) {
|
||||
enabled.document = { local: true, remote: false, limit: 1 };
|
||||
}
|
||||
|
||||
const mergedLimits = {
|
||||
...(difySystemParameters.value || {}),
|
||||
...(raw?.fileUploadConfig || {}),
|
||||
@@ -189,6 +198,7 @@ export function useChatAttachments(options: UseChatAttachmentsOptions) {
|
||||
const canLocal = Object.values(enabled).some((v) => v.local);
|
||||
const canRemote = Object.values(enabled).some((v) => v.remote);
|
||||
const totalLimit = (() => {
|
||||
if (isProcurementContractAgent.value) return 1;
|
||||
const v1 = raw?.fileUploadConfig?.file_upload_limit;
|
||||
if (Number.isFinite(Number(v1))) return Number(v1);
|
||||
const v2 = raw?.number_limits;
|
||||
@@ -197,6 +207,7 @@ export function useChatAttachments(options: UseChatAttachmentsOptions) {
|
||||
})();
|
||||
|
||||
const effectiveAllowedExts: Set<string> | null = (() => {
|
||||
if (isProcurementContractAgent.value) return new Set(PROCUREMENT_CONTRACT_EXTS);
|
||||
if (!allowedExts) return null;
|
||||
const filtered = new Set<string>();
|
||||
for (const ext of allowedExts) {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* features/chat/composables/useChatPage.ts
|
||||
* 对话页主编排:组合 SSE、Agent、附件、请假/出货、路由同步与 page/* 子模块。
|
||||
* 对话页主编排:组合 SSE、Agent、附件、请假/出货/采购合同、路由同步与 page/* 子模块。
|
||||
*/
|
||||
import { computed, markRaw, nextTick, ref, watch } from 'vue';
|
||||
import { storeToRefs } from 'pinia';
|
||||
@@ -24,6 +24,7 @@ import { useChatRouteSync } from './useChatRouteSync';
|
||||
import { useChatScroll } from './useChatScroll';
|
||||
import { useChatSessions } from './useChatSessions';
|
||||
import { useChatShipping } from './useChatShipping';
|
||||
import { useProcurementContractChat } from './useProcurementContractChat';
|
||||
import { useChatSourceFiles } from './useChatSourceFiles';
|
||||
import { useChatAssetHistory } from './useChatAssetHistory';
|
||||
import { useChatAssetImage } from './useChatAssetImage';
|
||||
@@ -239,6 +240,8 @@ export function useChatPage() {
|
||||
const { newLocalMessageId, saveLocalMessageToBackend } = createChatPageLocalMessageApi({
|
||||
conversationId,
|
||||
currentAgentId,
|
||||
route,
|
||||
router,
|
||||
});
|
||||
|
||||
const pushLocalAssistantMessage = async (content: string) => {
|
||||
@@ -304,6 +307,27 @@ export function useChatPage() {
|
||||
});
|
||||
resetShippingConversationState = shipping.resetShippingConversationState;
|
||||
|
||||
const procurement = useProcurementContractChat({
|
||||
currentAgent: agent.currentAgent,
|
||||
currentAgentId,
|
||||
attachments: attachmentApi.attachments,
|
||||
messages,
|
||||
isThinking,
|
||||
isUploadingAttachments: attachmentApi.isUploadingAttachments,
|
||||
input,
|
||||
clearAttachments: attachmentApi.clearAttachments,
|
||||
saveLocalMessageToBackend,
|
||||
loadHistory,
|
||||
msg,
|
||||
t,
|
||||
});
|
||||
|
||||
const allowsSendWithAttachmentsOnly = computed(
|
||||
() =>
|
||||
shipping.allowsSendWithAttachmentsOnly.value
|
||||
|| procurement.allowsSendWithAttachmentsOnly.value,
|
||||
);
|
||||
|
||||
/**
|
||||
* Drawer「重试所有失败」点击:仅打开确认弹窗,不立刻发请求。
|
||||
*/
|
||||
@@ -413,7 +437,7 @@ export function useChatPage() {
|
||||
isUploadingAttachments: attachmentApi.isUploadingAttachments,
|
||||
attachmentPolicy: attachmentApi.attachmentPolicy,
|
||||
attachments: attachmentApi.attachments,
|
||||
allowsSendWithAttachmentsOnly: shipping.allowsSendWithAttachmentsOnly,
|
||||
allowsSendWithAttachmentsOnly,
|
||||
buildFileSpecsForSend: attachmentApi.buildFileSpecsForSend,
|
||||
clearAttachments: attachmentApi.clearAttachments,
|
||||
sendMessage,
|
||||
@@ -445,6 +469,7 @@ export function useChatPage() {
|
||||
tryHandleShippingAttachmentAutoFlow: shipping.tryHandleShippingAttachmentAutoFlow,
|
||||
tryHandleLeaveSend: leave.tryHandleLeaveSend,
|
||||
tryHandleShippingSend: shipping.tryHandleShippingSend,
|
||||
tryHandleProcurementContractSend: procurement.tryHandleProcurementContractSend,
|
||||
refreshToolRunProgressAfterSend: toolRun.refreshToolRunProgressAfterSend,
|
||||
prepareToolRunProgressBeforeSend: toolRun.prepareToolRunProgressBeforeSend,
|
||||
msg,
|
||||
@@ -607,6 +632,11 @@ export function useChatPage() {
|
||||
clearShippingToast: dialogs.clearShippingToast,
|
||||
showChatRating,
|
||||
isShippingNoticeAgent: shipping.isShippingNoticeAgent,
|
||||
isProcurementContractAgent: procurement.isProcurementContractAgent,
|
||||
procurementReviewMode: procurement.reviewMode,
|
||||
procurementOriginalContractName: procurement.originalContractName,
|
||||
handleProcurementOriginalContractSelected: procurement.handleOriginalContractSelected,
|
||||
clearProcurementOriginalContract: procurement.clearOriginalContract,
|
||||
showShippingProgressWorkspace: shipping.showShippingProgressWorkspace,
|
||||
shippingBatchSummary: shipping.shippingBatchSummary,
|
||||
shippingConversationWorkspace: shipping.shippingConversationWorkspace,
|
||||
|
||||
@@ -0,0 +1,264 @@
|
||||
/**
|
||||
* features/chat/composables/useProcurementContractChat.ts
|
||||
* 用途:采购合同审查 Agent 的会话态(模式、双文件输入、异步发起与进度轮询)。
|
||||
* 依赖:procurement-contract.api、file-assets.api、agent-registry.utils。
|
||||
* 逻辑:模板比对要求我方原合同与卖方回传合同;单份审核仅要求待审合同,结果卡可在刷新后回放。
|
||||
*/
|
||||
import { computed, ref, watch, type ComputedRef, type Ref } from 'vue';
|
||||
import {
|
||||
getChatContractReview,
|
||||
startChatContractReview,
|
||||
type ContractReviewRow,
|
||||
} from '@/features/admin/api/procurement-contract.api';
|
||||
import { uploadFileAsset } from '@/shared/api/file-assets.api';
|
||||
import {
|
||||
isProcurementContractAgent as resolveProcurementContractAgent,
|
||||
type AgentRegistryFields,
|
||||
} from '@/shared/utils/agent-registry.utils';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
import type { PendingAttachment } from '../types/shipping.types';
|
||||
|
||||
export type ContractReviewMode = 'compare' | 'solo';
|
||||
const REVIEW_POLL_INTERVAL_MS = 2000;
|
||||
const REVIEW_POLL_TIMEOUT_MS = 10 * 60 * 1000;
|
||||
|
||||
export interface ProcurementContractChatOptions {
|
||||
currentAgent: Ref<AgentRegistryFields | null>;
|
||||
currentAgentId: ComputedRef<number>;
|
||||
attachments: Ref<PendingAttachment[]>;
|
||||
messages: Ref<ChatMessage[]>;
|
||||
isThinking: Ref<boolean>;
|
||||
isUploadingAttachments: Ref<boolean>;
|
||||
input: Ref<string>;
|
||||
clearAttachments: () => void;
|
||||
saveLocalMessageToBackend: (msg: ChatMessage, userQuery?: string) => Promise<void>;
|
||||
loadHistory: () => Promise<void>;
|
||||
msg: { warning: (text: string) => void; success: (text: string) => void; info: (text: string) => void };
|
||||
t: (key: string, params?: Record<string, unknown>) => string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从审查 API 结果构建结果卡 payload(去掉过大的冗余后仍保留 Diff/红线数据)。
|
||||
*/
|
||||
function buildReviewResultPayload(review: ContractReviewRow): ContractReviewRow {
|
||||
return {
|
||||
id: review.id,
|
||||
review_no: review.review_no,
|
||||
review_mode: review.review_mode,
|
||||
status: review.status,
|
||||
contract_file_name: review.contract_file_name,
|
||||
supplier_name: review.supplier_name,
|
||||
contract_no: review.contract_no,
|
||||
contract_type: review.contract_type,
|
||||
template_id: review.template_id,
|
||||
template_source: review.template_source,
|
||||
template_name: review.template_name,
|
||||
total_change_count: review.total_change_count,
|
||||
high_risk_count: review.high_risk_count,
|
||||
medium_risk_count: review.medium_risk_count,
|
||||
low_risk_count: review.low_risk_count,
|
||||
user_id: review.user_id,
|
||||
user_name: review.user_name,
|
||||
error_message: review.error_message,
|
||||
started_at: review.started_at,
|
||||
finished_at: review.finished_at,
|
||||
created_at: review.created_at,
|
||||
progress: review.progress,
|
||||
processing_stage: review.processing_stage,
|
||||
processing_message: review.processing_message,
|
||||
summary_json: review.summary_json,
|
||||
clauses_json: review.clauses_json,
|
||||
report_text: review.report_text,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 轮询单次合同审核直到成功、失败或达到前端等待上限。
|
||||
* 核心逻辑:后端任务继续独立运行;前端超时只停止本页等待,不取消后台审核。
|
||||
* @param reviewNo - 后端返回的合同审查编号
|
||||
* @param onProgress - 每轮查询后更新当前消息卡
|
||||
*/
|
||||
async function pollContractReview(
|
||||
reviewNo: string,
|
||||
onProgress: (review: ContractReviewRow) => void,
|
||||
): Promise<ContractReviewRow> {
|
||||
const startedAt = Date.now();
|
||||
while (Date.now() - startedAt < REVIEW_POLL_TIMEOUT_MS) {
|
||||
const review = await getChatContractReview(reviewNo);
|
||||
onProgress(review);
|
||||
if (review.status === 'success' || review.status === 'failed') return review;
|
||||
await new Promise((resolve) => window.setTimeout(resolve, REVIEW_POLL_INTERVAL_MS));
|
||||
}
|
||||
throw new Error('contract review polling timed out');
|
||||
}
|
||||
|
||||
/**
|
||||
* 采购合同审查 Chat 编排。
|
||||
*/
|
||||
export function useProcurementContractChat(options: ProcurementContractChatOptions) {
|
||||
const isProcurementContractAgent = computed(() =>
|
||||
resolveProcurementContractAgent(options.currentAgent.value),
|
||||
);
|
||||
|
||||
const reviewMode = ref<ContractReviewMode>('compare');
|
||||
const originalContractAssetNo = ref<string | null>(null);
|
||||
const originalContractName = ref<string | null>(null);
|
||||
|
||||
const allowsSendWithAttachmentsOnly = computed(
|
||||
() => isProcurementContractAgent.value && (
|
||||
options.attachments.value.some((a) => a.kind === 'local')
|
||||
|| (reviewMode.value === 'compare' && Boolean(originalContractAssetNo.value))
|
||||
),
|
||||
);
|
||||
|
||||
watch(
|
||||
isProcurementContractAgent,
|
||||
(active) => {
|
||||
if (!active) {
|
||||
reviewMode.value = 'compare';
|
||||
originalContractAssetNo.value = null;
|
||||
originalContractName.value = null;
|
||||
}
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
/**
|
||||
* 上传合同比对所需的我方原合同,仅作为本次审核基准,不进入模板库。
|
||||
*/
|
||||
async function handleOriginalContractSelected(event: Event): Promise<void> {
|
||||
const input = event.target as HTMLInputElement;
|
||||
const file = input.files?.[0];
|
||||
input.value = '';
|
||||
if (!file) return;
|
||||
options.isUploadingAttachments.value = true;
|
||||
try {
|
||||
const asset = await uploadFileAsset(file);
|
||||
originalContractAssetNo.value = asset.asset_no;
|
||||
originalContractName.value = asset.original_filename || file.name;
|
||||
} catch (e: unknown) {
|
||||
options.msg.warning(e instanceof Error ? e.message : options.t('chat.procurementContract.uploadFailed'));
|
||||
} finally {
|
||||
options.isUploadingAttachments.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除已上传的我方原合同基准。
|
||||
*/
|
||||
function clearOriginalContract(): void {
|
||||
originalContractAssetNo.value = null;
|
||||
originalContractName.value = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 拦截带本地附件的发送:上传 FileAsset → 创建异步审查 → 轮询进度 → 写入最终结果卡。
|
||||
* @returns true 表示已消费本次发送
|
||||
*/
|
||||
async function tryHandleProcurementContractSend(
|
||||
textOrEvent: string | Event | undefined,
|
||||
_content: string,
|
||||
trimmed: string,
|
||||
): Promise<boolean> {
|
||||
if (!isProcurementContractAgent.value) return false;
|
||||
const locals = options.attachments.value.filter(
|
||||
(a): a is Extract<PendingAttachment, { kind: 'local' }> => a.kind === 'local',
|
||||
);
|
||||
if (!locals.length) {
|
||||
if (reviewMode.value === 'compare' && originalContractAssetNo.value) {
|
||||
options.msg.warning(options.t('chat.procurementContract.compareFilesRequired'));
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (options.isThinking.value || options.isUploadingAttachments.value) return true;
|
||||
|
||||
if (locals.length > 1) {
|
||||
options.msg.warning(options.t('chat.procurementContract.oneContractOnly'));
|
||||
return true;
|
||||
}
|
||||
if (reviewMode.value === 'compare' && !originalContractAssetNo.value) {
|
||||
options.msg.warning(options.t('chat.procurementContract.compareFilesRequired'));
|
||||
return true;
|
||||
}
|
||||
|
||||
const contractFile = locals[0]!.file;
|
||||
options.isUploadingAttachments.value = true;
|
||||
options.isThinking.value = true;
|
||||
try {
|
||||
// [STEP 1] 上传待审合同
|
||||
const contractAsset = await uploadFileAsset(contractFile);
|
||||
|
||||
// [STEP 2] 比对模式固定以用户上传的我方原合同作为基准,不再读取默认模板。
|
||||
const queuedReview = await startChatContractReview({
|
||||
review_mode: reviewMode.value,
|
||||
contract_asset_no: contractAsset.asset_no,
|
||||
original_contract_asset_no:
|
||||
reviewMode.value === 'compare' ? originalContractAssetNo.value : null,
|
||||
contract_type: 'general_procurement',
|
||||
agent_id: options.currentAgentId.value || null,
|
||||
});
|
||||
|
||||
// [STEP 3] 立即显示用户消息和排队进度卡
|
||||
const userText =
|
||||
trimmed
|
||||
|| options.t('chat.procurementContract.defaultUserQuery', {
|
||||
file: contractFile.name,
|
||||
mode:
|
||||
reviewMode.value === 'solo'
|
||||
? options.t('chat.procurementContract.modeSolo')
|
||||
: options.t('chat.procurementContract.modeCompare'),
|
||||
});
|
||||
const userMsg: ChatMessage = { role: 'user', content: userText, type: 'text' };
|
||||
options.messages.value.push(userMsg);
|
||||
|
||||
const assistantMsg: ChatMessage = {
|
||||
role: 'assistant',
|
||||
type: 'procurement-contract-review',
|
||||
content: options.t('chat.procurementContract.reviewQueued'),
|
||||
payload: buildReviewResultPayload(queuedReview),
|
||||
};
|
||||
options.messages.value.push(assistantMsg);
|
||||
if (typeof textOrEvent !== 'string') options.input.value = '';
|
||||
options.clearAttachments();
|
||||
clearOriginalContract();
|
||||
options.isUploadingAttachments.value = false;
|
||||
options.isThinking.value = false;
|
||||
|
||||
// [STEP 4] 后台完成后原地替换进度卡,再持久化正式结果。
|
||||
const review = await pollContractReview(queuedReview.review_no, (latest) => {
|
||||
assistantMsg.payload = buildReviewResultPayload(latest);
|
||||
assistantMsg.content = latest.processing_message || options.t('chat.procurementContract.reviewRunning');
|
||||
});
|
||||
if (review.status === 'failed') {
|
||||
throw new Error(review.error_message || options.t('chat.procurementContract.reviewFailed'));
|
||||
}
|
||||
assistantMsg.payload = buildReviewResultPayload(review);
|
||||
assistantMsg.content =
|
||||
review.summary_json && typeof review.summary_json.headline === 'string'
|
||||
? String(review.summary_json.headline)
|
||||
: options.t('chat.procurementContract.resultTitle');
|
||||
await options.saveLocalMessageToBackend(assistantMsg, userText);
|
||||
await options.loadHistory();
|
||||
} catch (e: unknown) {
|
||||
options.msg.warning(
|
||||
e instanceof Error ? e.message : options.t('chat.procurementContract.reviewFailed'),
|
||||
);
|
||||
} finally {
|
||||
options.isUploadingAttachments.value = false;
|
||||
options.isThinking.value = false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
return {
|
||||
isProcurementContractAgent,
|
||||
reviewMode,
|
||||
originalContractAssetNo,
|
||||
originalContractName,
|
||||
allowsSendWithAttachmentsOnly,
|
||||
handleOriginalContractSelected,
|
||||
clearOriginalContract,
|
||||
tryHandleProcurementContractSend,
|
||||
};
|
||||
}
|
||||
@@ -1,6 +1,10 @@
|
||||
/**
|
||||
* 对话页:本地消息落库(请假/出货等不经过 SSE 的消息)。
|
||||
* features/chat/page/useChatPageLocalMessage.ts
|
||||
* 用途:对话页本地消息落库(请假/出货/合同审查等不经 SSE 的消息)。
|
||||
* 依赖:chat.api.saveLocalChatMessage、vue Router。
|
||||
* 逻辑:落库后回写 conversationId / chat_log_id,并同步 URL 的 conversation_id 以便刷新可恢复。
|
||||
*/
|
||||
import type { RouteLocationNormalizedLoaded, Router } from 'vue-router';
|
||||
import { saveLocalChatMessage } from '../api/chat.api';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
import type { ComputedRef, Ref } from 'vue';
|
||||
@@ -8,16 +12,31 @@ import type { ComputedRef, Ref } from 'vue';
|
||||
export interface ChatPageLocalMessageContext {
|
||||
conversationId: Ref<string | null>;
|
||||
currentAgentId: ComputedRef<number>;
|
||||
route?: RouteLocationNormalizedLoaded;
|
||||
router?: Router;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建本地消息落库 API。
|
||||
* @param ctx - 会话 ID、当前 Agent,以及可选的 route/router 用于同步 URL
|
||||
*/
|
||||
export function createChatPageLocalMessageApi(ctx: ChatPageLocalMessageContext) {
|
||||
let localMessageCounter = 0;
|
||||
|
||||
/**
|
||||
* 生成前端本地消息 ID 前缀。
|
||||
* @param prefix - ID 前缀
|
||||
*/
|
||||
const newLocalMessageId = (prefix: string) => {
|
||||
localMessageCounter += 1;
|
||||
return `${prefix}-${Date.now()}-${localMessageCounter}`;
|
||||
};
|
||||
|
||||
/**
|
||||
* 将本地消息写入后端,并在首次落库时把 conversation_id 写入路由 query。
|
||||
* @param localMsg - 待保存消息
|
||||
* @param userQuery - 用户提问(结构化助手消息回放用)
|
||||
*/
|
||||
const saveLocalMessageToBackend = async (localMsg: ChatMessage, userQuery: string = '') => {
|
||||
try {
|
||||
const data = await saveLocalChatMessage({
|
||||
@@ -29,12 +48,25 @@ export function createChatPageLocalMessageApi(ctx: ChatPageLocalMessageContext)
|
||||
query: userQuery,
|
||||
agent_id: ctx.currentAgentId.value,
|
||||
});
|
||||
if (!ctx.conversationId.value && data.conversation_id) {
|
||||
ctx.conversationId.value = data.conversation_id;
|
||||
const cid = data.conversation_id ? String(data.conversation_id) : '';
|
||||
if (cid && !ctx.conversationId.value) {
|
||||
ctx.conversationId.value = cid;
|
||||
}
|
||||
if (data.chat_log_id) {
|
||||
localMsg.chat_log_id = data.chat_log_id;
|
||||
}
|
||||
// [STEP] 同步 URL,刷新后可按 conversation_id 拉回用户提问 + 结果卡
|
||||
if (cid && ctx.route && ctx.router) {
|
||||
const current = typeof ctx.route.query.conversation_id === 'string'
|
||||
? ctx.route.query.conversation_id
|
||||
: '';
|
||||
if (current !== cid) {
|
||||
await ctx.router.replace({
|
||||
path: ctx.route.path,
|
||||
query: { ...ctx.route.query, conversation_id: cid },
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to save local message', e);
|
||||
}
|
||||
|
||||
@@ -342,6 +342,7 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
|
||||
if (msgItem?.role === 'user') return true;
|
||||
if (msgItem?.type === 'shipping-parse-review') return false;
|
||||
if (msgItem?.type === 'leave-form' || msgItem?.type === 'leave-confirmation' || msgItem?.type === 'leave-result') return true;
|
||||
if (msgItem?.type === 'procurement-contract-review') return true;
|
||||
const content = (msgItem?.content || '').trim();
|
||||
if (content) return true;
|
||||
if (ctx.getMessageLinks(msgItem as unknown as Record<string, unknown>).length > 0) return true;
|
||||
@@ -361,7 +362,9 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
|
||||
|| msgItem?.type === 'leave-result'
|
||||
|| msgItem?.type === 'shipping-inventory-mapping'
|
||||
|| msgItem?.type === 'shipping-parse-review'
|
||||
|| msgItem?.type === 'shipping-match-result') {
|
||||
|| msgItem?.type === 'shipping-match-result'
|
||||
|| msgItem?.type === 'maintenance-device-result'
|
||||
|| msgItem?.type === 'procurement-contract-review') {
|
||||
return true;
|
||||
}
|
||||
return Boolean(String(msgItem?.content || '').trim());
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* 对话页:发送消息编排(出货/请假前置拦截 → Dify SSE)、复制与重新生成。
|
||||
* 对话页:发送消息编排(出货/请假/采购合同前置拦截 → Dify SSE)、复制与重新生成。
|
||||
*/
|
||||
import { computed } from 'vue';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
@@ -64,6 +64,11 @@ export interface ChatPageSendContext {
|
||||
content: string,
|
||||
trimmed: string,
|
||||
) => Promise<boolean>;
|
||||
tryHandleProcurementContractSend: (
|
||||
textOrEvent: string | Event | undefined,
|
||||
content: string,
|
||||
trimmed: string,
|
||||
) => Promise<boolean>;
|
||||
refreshToolRunProgressAfterSend: () => Promise<void>;
|
||||
prepareToolRunProgressBeforeSend: () => Promise<void>;
|
||||
msg: { warning: (text: string) => void; info: (text: string) => void };
|
||||
@@ -89,6 +94,9 @@ export function createChatPageSendApi(ctx: ChatPageSendContext) {
|
||||
if (await ctx.tryHandleShippingAttachmentAutoFlow(textOrEvent, content, trimmed)) {
|
||||
return;
|
||||
}
|
||||
if (await ctx.tryHandleProcurementContractSend(textOrEvent, content, trimmed)) {
|
||||
return;
|
||||
}
|
||||
if (!trimmed || ctx.isUploadingAttachments.value || (ctx.isThinking.value && !allowSendWhileThinking)) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ export interface RetrieverResource {
|
||||
export interface ChatMessage {
|
||||
role: 'user' | 'assistant';
|
||||
content: string;
|
||||
type?: 'text' | 'leave-form' | 'leave-confirmation' | 'leave-result' | 'shipping-inventory-mapping' | 'shipping-parse-review' | 'shipping-match-result' | 'maintenance-device-result';
|
||||
type?: 'text' | 'leave-form' | 'leave-confirmation' | 'leave-result' | 'shipping-inventory-mapping' | 'shipping-parse-review' | 'shipping-match-result' | 'maintenance-device-result' | 'procurement-contract-review';
|
||||
retriever_resources?: RetrieverResource[];
|
||||
attribution_parts?: string[];
|
||||
chat_log_id?: number;
|
||||
|
||||
@@ -26,7 +26,9 @@
|
||||
"permissions": "App Permissions",
|
||||
"requests": "Permission Requests",
|
||||
"reports": "Data Reports",
|
||||
"schedules": "Schedule Management"
|
||||
"schedules": "Schedule Management",
|
||||
"platformApps": "Platform Apps",
|
||||
"procurementContract": "Procurement Contract Review"
|
||||
},
|
||||
"platformApps": {
|
||||
"guideUsage": "Guide Usage",
|
||||
@@ -1292,5 +1294,153 @@
|
||||
"batchPermissionUpdateFailed": "Batch permission update failed",
|
||||
"enterOneField": "Please enter at least one field to update",
|
||||
"batchDeleteResult": "Deleted {count} users."
|
||||
},
|
||||
"procurementContract": {
|
||||
"title": "Procurement Contract Review",
|
||||
"subtitle": "Manage templates, risk red-line rules, and review history",
|
||||
"tabTemplates": "Templates",
|
||||
"tabRules": "Risk Rules",
|
||||
"addRule": "Add Rule",
|
||||
"rulesHint": "Built-in rules use compound procurement checks; custom rules use keyword matching only. Use standard categories.",
|
||||
"ruleStatTotal": "Rules",
|
||||
"ruleStatEnabled": "Enabled",
|
||||
"ruleStatHighRisk": "High risk",
|
||||
"emptyRules": "No risk rules yet",
|
||||
"ruleCreateTitle": "Create Risk Rule",
|
||||
"ruleEditTitle": "Edit Risk Rule",
|
||||
"ruleCreateOk": "Rule created",
|
||||
"ruleEditOk": "Rule updated",
|
||||
"ruleRequiredFields": "Please fill title, category, risk hint and suggestion",
|
||||
"ruleKeywordsRequired": "Please enter at least one keyword",
|
||||
"ruleCodePlaceholder": "Generated after saving",
|
||||
"ruleCodeGeneratedHint": "The system generates an internal code for a custom rule after saving.",
|
||||
"ruleCodeReadonlyHint": "Code is the internal rule identifier and cannot be changed.",
|
||||
"builtinRuleLogicHint": "This is a built-in procurement rule. Category, keywords, and trigger are fixed because the system evaluates compound business conditions.",
|
||||
"ruleKeywordsPlaceholder": "Comma-separated keywords, e.g. payment, acceptance, invoice",
|
||||
"keywordPresentLogicHint": "Risk is triggered when any keyword is found.",
|
||||
"keywordMissingLogicHint": "Risk is triggered only when all keywords are absent; use a built-in rule for compound conditions.",
|
||||
"category_payment": "Payment",
|
||||
"category_delivery": "Delivery",
|
||||
"category_acceptance": "Acceptance",
|
||||
"category_warranty": "Warranty / after-sales",
|
||||
"category_liability": "Breach and liability",
|
||||
"category_jurisdiction": "Jurisdiction",
|
||||
"category_dispute": "Dispute resolution",
|
||||
"category_ip": "Intellectual property",
|
||||
"category_other": "Other",
|
||||
"confirmDeleteRule": "Delete rule \"{title}\"? Reviews will stop using this red line.",
|
||||
"colRuleCode": "Code",
|
||||
"colRuleTitle": "Title",
|
||||
"colCategory": "Category",
|
||||
"colKeywords": "Keywords",
|
||||
"colTrigger": "Trigger",
|
||||
"colSort": "Sort",
|
||||
"ruleSortHint": "Lower values run first; rules for the same contract are checked in ascending order.",
|
||||
"colContractType": "Contract type",
|
||||
"colRiskHint": "Risk hint",
|
||||
"colSuggestion": "Suggestion",
|
||||
"colNegotiation": "Negotiation text",
|
||||
"triggerMissing": "Trigger when keywords are missing",
|
||||
"triggerPresent": "Trigger when keywords are present",
|
||||
"riskHigh": "High",
|
||||
"riskMedium": "Medium",
|
||||
"riskLow": "Low",
|
||||
"tabReviews": "Review History",
|
||||
"uploadTemplate": "Upload Template",
|
||||
"colName": "Name",
|
||||
"colVersion": "Version",
|
||||
"colFile": "File",
|
||||
"colStatus": "Status",
|
||||
"colDefault": "Default",
|
||||
"colActions": "Actions",
|
||||
"colMode": "Mode",
|
||||
"colSource": "Template Source",
|
||||
"colReviewNo": "Review No.",
|
||||
"colContract": "Contract",
|
||||
"colContractNo": "Contract No.",
|
||||
"colSupplier": "Supplier",
|
||||
"colTemplate": "Template",
|
||||
"colUser": "User",
|
||||
"colFinishedAt": "Completed At",
|
||||
"colRisk": "Risk",
|
||||
"keyword": "Keyword",
|
||||
"modeCompare": "Compare",
|
||||
"modeSolo": "Solo Review",
|
||||
"sourceLibrary": "Library",
|
||||
"sourceUpload": "User Upload",
|
||||
"sourceNone": "None",
|
||||
"setDefault": "Set Default",
|
||||
"setAsDefault": "Set as default template",
|
||||
"enable": "Enable",
|
||||
"disable": "Disable",
|
||||
"emptyTemplates": "No templates yet",
|
||||
"emptyReviews": "No reviews yet",
|
||||
"total": "{n} total",
|
||||
"loadFailed": "Failed to load",
|
||||
"fileRequired": "Please choose a file",
|
||||
"uploadOk": "Template uploaded",
|
||||
"uploadFailed": "Upload failed",
|
||||
"setDefaultOk": "Default template updated",
|
||||
"actionFailed": "Action failed",
|
||||
"confirmDelete": "Delete this template?",
|
||||
"downloadReport": "Download Report",
|
||||
"downloadAnnotated": "Download Annotated Contract",
|
||||
"downloadFile": "Download File",
|
||||
"downloadContract": "Download Contract",
|
||||
"downloadTemplateFile": "Download Template Used",
|
||||
"downloadFailed": "Download failed",
|
||||
"loading": "Loading…",
|
||||
"all": "All",
|
||||
"search": "Search",
|
||||
"detail": "Detail",
|
||||
"saving": "Saving…",
|
||||
"sourceAll": "All sources",
|
||||
"keywordPlaceholder": "Search review no., contract no., supplier, file…",
|
||||
"reviewNoPlaceholder": "CR-…",
|
||||
"uploadModalTitle": "Upload Contract Template",
|
||||
"uploadZonePrefix": "Drop Word / PDF here, or ",
|
||||
"uploadZoneAction": "click to choose a file",
|
||||
"uploadZoneReplace": "Click or drop to replace the file",
|
||||
"noFileSelected": "No file selected",
|
||||
"templateName": "Template name",
|
||||
"versionNo": "Version",
|
||||
"defaultNo": "No",
|
||||
"defaultYes": "Yes (default in chat)",
|
||||
"remark": "Remark",
|
||||
"remarkPlaceholder": "Use case, changes vs previous version…",
|
||||
"uploadCallout": "Once enabled, the template appears in the chat dropdown immediately.",
|
||||
"saveToLibrary": "Save to library",
|
||||
"defaultYesShort": "Yes",
|
||||
"statusSuccess": "Success",
|
||||
"statusFailed": "Failed",
|
||||
"statusRunning": "Running",
|
||||
"statusPending": "Pending",
|
||||
"confirmDeleteNamed": "Delete template \"{name} {version}\"?",
|
||||
"editModalTitle": "Edit Contract Template",
|
||||
"saveChanges": "Save changes",
|
||||
"editOk": "Template updated",
|
||||
"editFileHint": "Replacing the file is not supported in edit mode; upload a new version instead.",
|
||||
"nameVersionRequired": "Name and version are required",
|
||||
"regionConfigAction": "Comparison regions",
|
||||
"regionConfigTitle": "Comparison region configuration",
|
||||
"regionConfigHint": "Rules partition the two files uploaded for this review; they never replace the uploaded original",
|
||||
"regionMetadata": "Header metadata fields",
|
||||
"regionField_contract_no": "Contract number",
|
||||
"regionField_buyer": "Buyer",
|
||||
"regionField_seller": "Seller",
|
||||
"regionField_version": "Version",
|
||||
"regionBodyStart": "Body start anchors (one per line)",
|
||||
"regionBodyEnd": "Body end anchors (one per line)",
|
||||
"regionSignatureTerms": "Signature helper terms (one per line)",
|
||||
"regionAttachmentStart": "Attachment heading anchors (one per line)",
|
||||
"regionAttachmentPolicy": "Attachment policy",
|
||||
"regionPageCountOnly": "Only report added or removed pages; do not review attachment content",
|
||||
"regionRestoreV4": "Restore V4 defaults",
|
||||
"regionPreview": "Recognition preview",
|
||||
"regionPreviewing": "Recognizing…",
|
||||
"regionPreviewRecognized": "Body region recognized",
|
||||
"regionPreviewIncomplete": "Anchors are incomplete; reviews will safely fall back",
|
||||
"regionPreviewFailed": "Region recognition preview failed",
|
||||
"regionSaved": "Comparison region configuration saved"
|
||||
}
|
||||
}
|
||||
@@ -725,8 +725,14 @@
|
||||
"The admin view must be able to export join date, completion date, department, name, employee ID, and score."
|
||||
],
|
||||
"booleanOptions": [
|
||||
{ "id": "true", "label": "True" },
|
||||
{ "id": "false", "label": "False" }
|
||||
{
|
||||
"id": "true",
|
||||
"label": "True"
|
||||
},
|
||||
{
|
||||
"id": "false",
|
||||
"label": "False"
|
||||
}
|
||||
],
|
||||
"questionBank": [
|
||||
{
|
||||
@@ -736,10 +742,22 @@
|
||||
"answer": "c",
|
||||
"explanation": "According to the onboarding exam, salary is paid on the 15th of each month.",
|
||||
"options": [
|
||||
{ "id": "a", "label": "A. 8th" },
|
||||
{ "id": "b", "label": "B. 9th" },
|
||||
{ "id": "c", "label": "C. 15th" },
|
||||
{ "id": "d", "label": "D. 27th" }
|
||||
{
|
||||
"id": "a",
|
||||
"label": "A. 8th"
|
||||
},
|
||||
{
|
||||
"id": "b",
|
||||
"label": "B. 9th"
|
||||
},
|
||||
{
|
||||
"id": "c",
|
||||
"label": "C. 15th"
|
||||
},
|
||||
{
|
||||
"id": "d",
|
||||
"label": "D. 27th"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -749,9 +767,18 @@
|
||||
"answer": "b",
|
||||
"explanation": "The company cafeteria uses the Zhongmi meal-ordering system, not OA or ERP.",
|
||||
"options": [
|
||||
{ "id": "a", "label": "A. OA" },
|
||||
{ "id": "b", "label": "B. Zhongmi ordering system" },
|
||||
{ "id": "c", "label": "C. ERP" }
|
||||
{
|
||||
"id": "a",
|
||||
"label": "A. OA"
|
||||
},
|
||||
{
|
||||
"id": "b",
|
||||
"label": "B. Zhongmi ordering system"
|
||||
},
|
||||
{
|
||||
"id": "c",
|
||||
"label": "C. ERP"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -761,10 +788,22 @@
|
||||
"answer": "abcd",
|
||||
"explanation": "All four options listed in the exam belong to the company product scope.",
|
||||
"options": [
|
||||
{ "id": "abcd", "label": "A/B/C/D All of the above" },
|
||||
{ "id": "ab", "label": "A/B" },
|
||||
{ "id": "cd", "label": "C/D" },
|
||||
{ "id": "a", "label": "A only" }
|
||||
{
|
||||
"id": "abcd",
|
||||
"label": "A/B/C/D All of the above"
|
||||
},
|
||||
{
|
||||
"id": "ab",
|
||||
"label": "A/B"
|
||||
},
|
||||
{
|
||||
"id": "cd",
|
||||
"label": "C/D"
|
||||
},
|
||||
{
|
||||
"id": "a",
|
||||
"label": "A only"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -774,10 +813,22 @@
|
||||
"answer": "c",
|
||||
"explanation": "Leave must use the OA leave application form.",
|
||||
"options": [
|
||||
{ "id": "a", "label": "A. Overtime request" },
|
||||
{ "id": "b", "label": "B. Contact form" },
|
||||
{ "id": "c", "label": "C. Leave application" },
|
||||
{ "id": "d", "label": "D. Employee request form" }
|
||||
{
|
||||
"id": "a",
|
||||
"label": "A. Overtime request"
|
||||
},
|
||||
{
|
||||
"id": "b",
|
||||
"label": "B. Contact form"
|
||||
},
|
||||
{
|
||||
"id": "c",
|
||||
"label": "C. Leave application"
|
||||
},
|
||||
{
|
||||
"id": "d",
|
||||
"label": "D. Employee request form"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -787,9 +838,18 @@
|
||||
"answer": "a",
|
||||
"explanation": "QC080000 is the hazardous substance process management certification standard.",
|
||||
"options": [
|
||||
{ "id": "a", "label": "A. Hazardous substance process management standard" },
|
||||
{ "id": "b", "label": "B. Occupational health and safety management system" },
|
||||
{ "id": "c", "label": "C. Environmental management system" }
|
||||
{
|
||||
"id": "a",
|
||||
"label": "A. Hazardous substance process management standard"
|
||||
},
|
||||
{
|
||||
"id": "b",
|
||||
"label": "B. Occupational health and safety management system"
|
||||
},
|
||||
{
|
||||
"id": "c",
|
||||
"label": "C. Environmental management system"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -799,8 +859,14 @@
|
||||
"answer": "a",
|
||||
"explanation": "The standard 5S terms are sort, set in order, shine, standardize, and sustain.",
|
||||
"options": [
|
||||
{ "id": "a", "label": "A. Sort, set in order, shine, standardize, sustain" },
|
||||
{ "id": "b", "label": "B. Sort, set in order, clean up, standardize, sustain" }
|
||||
{
|
||||
"id": "a",
|
||||
"label": "A. Sort, set in order, shine, standardize, sustain"
|
||||
},
|
||||
{
|
||||
"id": "b",
|
||||
"label": "B. Sort, set in order, clean up, standardize, sustain"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -810,23 +876,226 @@
|
||||
"answer": "a",
|
||||
"explanation": "You should stand on the upwind side when using a fire extinguisher.",
|
||||
"options": [
|
||||
{ "id": "a", "label": "A. Upwind side" },
|
||||
{ "id": "b", "label": "B. Downwind side" }
|
||||
{
|
||||
"id": "a",
|
||||
"label": "A. Upwind side"
|
||||
},
|
||||
{
|
||||
"id": "b",
|
||||
"label": "B. Downwind side"
|
||||
}
|
||||
]
|
||||
},
|
||||
{ "id": "q8", "type": "boolean", "prompt": "Normal attendance requires clock-in, and overtime must be applied for in advance.", "answer": "true", "explanation": "Both attendance and overtime follow the company attendance policy." },
|
||||
{ "id": "q9", "type": "boolean", "prompt": "If you forget to clock in, you need an OA correction request.", "answer": "true", "explanation": "Missed punches must be corrected through the OA process." },
|
||||
{ "id": "q10", "type": "boolean", "prompt": "Monthly salary is calculated from the 21st of the previous month to the 20th of the current month.", "answer": "true", "explanation": "The exam explicitly defines this payroll calculation cycle." },
|
||||
{ "id": "q11", "type": "boolean", "prompt": "Cafeteria meals require advance booking, and face recognition can be used for dining.", "answer": "true", "explanation": "Advance booking and face-recognition dining are both supported." },
|
||||
{ "id": "q12", "type": "boolean", "prompt": "In the event of fire or explosion, you should immediately call 119.", "answer": "true", "explanation": "Calling the fire emergency number is the first step in this scenario." },
|
||||
{ "id": "q13", "type": "boolean", "prompt": "Dormitory residents must maintain fire awareness and must not install wires privately or use high-power appliances.", "answer": "true", "explanation": "This is a mandatory dormitory fire-safety rule." },
|
||||
{ "id": "q14", "type": "boolean", "prompt": "Following safety production regulations is a safety obligation of employees.", "answer": "true", "explanation": "Safety compliance is both a rule and an employee obligation." },
|
||||
{ "id": "q15", "type": "boolean", "prompt": "Employee badges may be lent to others freely.", "answer": "false", "explanation": "A badge is a personal identity credential and may not be lent out." },
|
||||
{ "id": "q16", "type": "boolean", "prompt": "RoHS mainly regulates materials and processes in electrical and electronic products to better protect human health and the environment.", "answer": "true", "explanation": "RoHS focuses on restricting hazardous substances and improving environmental protection." },
|
||||
{ "id": "q17", "type": "boolean", "prompt": "Our company's HSF policy is: green design, eco-friendly purchasing; resource conservation, green output.", "answer": "true", "explanation": "This is the HSF policy statement provided in the exam." },
|
||||
{ "id": "q18", "type": "boolean", "prompt": "EHS stands for Environment, Health, and Safety.", "answer": "true", "explanation": "EHS is the standard abbreviation for environment, health, and safety." },
|
||||
{ "id": "q19", "type": "boolean", "prompt": "External documents do not need to be controlled or managed by the organization.", "answer": "false", "explanation": "External documents also need controlled management." },
|
||||
{ "id": "q20", "type": "boolean", "prompt": "Product-related requirements should include legal and regulatory requirements as well as customer requirements.", "answer": "true", "explanation": "Product requirements must cover both regulations and customer requirements." }
|
||||
{
|
||||
"id": "q8",
|
||||
"type": "boolean",
|
||||
"prompt": "Normal attendance requires clock-in, and overtime must be applied for in advance.",
|
||||
"answer": "true",
|
||||
"explanation": "Both attendance and overtime follow the company attendance policy."
|
||||
},
|
||||
{
|
||||
"id": "q9",
|
||||
"type": "boolean",
|
||||
"prompt": "If you forget to clock in, you need an OA correction request.",
|
||||
"answer": "true",
|
||||
"explanation": "Missed punches must be corrected through the OA process."
|
||||
},
|
||||
{
|
||||
"id": "q10",
|
||||
"type": "boolean",
|
||||
"prompt": "Monthly salary is calculated from the 21st of the previous month to the 20th of the current month.",
|
||||
"answer": "true",
|
||||
"explanation": "The exam explicitly defines this payroll calculation cycle."
|
||||
},
|
||||
{
|
||||
"id": "q11",
|
||||
"type": "boolean",
|
||||
"prompt": "Cafeteria meals require advance booking, and face recognition can be used for dining.",
|
||||
"answer": "true",
|
||||
"explanation": "Advance booking and face-recognition dining are both supported."
|
||||
},
|
||||
{
|
||||
"id": "q12",
|
||||
"type": "boolean",
|
||||
"prompt": "In the event of fire or explosion, you should immediately call 119.",
|
||||
"answer": "true",
|
||||
"explanation": "Calling the fire emergency number is the first step in this scenario."
|
||||
},
|
||||
{
|
||||
"id": "q13",
|
||||
"type": "boolean",
|
||||
"prompt": "Dormitory residents must maintain fire awareness and must not install wires privately or use high-power appliances.",
|
||||
"answer": "true",
|
||||
"explanation": "This is a mandatory dormitory fire-safety rule."
|
||||
},
|
||||
{
|
||||
"id": "q14",
|
||||
"type": "boolean",
|
||||
"prompt": "Following safety production regulations is a safety obligation of employees.",
|
||||
"answer": "true",
|
||||
"explanation": "Safety compliance is both a rule and an employee obligation."
|
||||
},
|
||||
{
|
||||
"id": "q15",
|
||||
"type": "boolean",
|
||||
"prompt": "Employee badges may be lent to others freely.",
|
||||
"answer": "false",
|
||||
"explanation": "A badge is a personal identity credential and may not be lent out."
|
||||
},
|
||||
{
|
||||
"id": "q16",
|
||||
"type": "boolean",
|
||||
"prompt": "RoHS mainly regulates materials and processes in electrical and electronic products to better protect human health and the environment.",
|
||||
"answer": "true",
|
||||
"explanation": "RoHS focuses on restricting hazardous substances and improving environmental protection."
|
||||
},
|
||||
{
|
||||
"id": "q17",
|
||||
"type": "boolean",
|
||||
"prompt": "Our company's HSF policy is: green design, eco-friendly purchasing; resource conservation, green output.",
|
||||
"answer": "true",
|
||||
"explanation": "This is the HSF policy statement provided in the exam."
|
||||
},
|
||||
{
|
||||
"id": "q18",
|
||||
"type": "boolean",
|
||||
"prompt": "EHS stands for Environment, Health, and Safety.",
|
||||
"answer": "true",
|
||||
"explanation": "EHS is the standard abbreviation for environment, health, and safety."
|
||||
},
|
||||
{
|
||||
"id": "q19",
|
||||
"type": "boolean",
|
||||
"prompt": "External documents do not need to be controlled or managed by the organization.",
|
||||
"answer": "false",
|
||||
"explanation": "External documents also need controlled management."
|
||||
},
|
||||
{
|
||||
"id": "q20",
|
||||
"type": "boolean",
|
||||
"prompt": "Product-related requirements should include legal and regulatory requirements as well as customer requirements.",
|
||||
"answer": "true",
|
||||
"explanation": "Product requirements must cover both regulations and customer requirements."
|
||||
}
|
||||
]
|
||||
},
|
||||
"procurementContract": {
|
||||
"modeCompare": "Contract Compare",
|
||||
"modeSolo": "Solo Review",
|
||||
"modeHint": "Upload the contract files required by the selected mode",
|
||||
"compareHint": "Upload our original contract and the seller-returned contract",
|
||||
"selectTemplate": "Select template",
|
||||
"default": "Default",
|
||||
"uploadTempTemplate": "Upload temp template",
|
||||
"uploadContract": "Upload contract",
|
||||
"uploadOriginalContract": "Upload our original",
|
||||
"uploadSellerReturnedContract": "Upload seller return",
|
||||
"uploadContractToReview": "Upload contract to review",
|
||||
"quickReview": "Review contract",
|
||||
"quickRisk": "Risk alerts",
|
||||
"quickDiff": "Template differences",
|
||||
"quickSuggestion": "Revision suggestions",
|
||||
"promptReview": "Please review this procurement contract and summarize the main issues and conclusion by high, medium, and low risk.",
|
||||
"promptRisk": "Please focus on legal, payment, delivery, and breach-liability risks in this contract.",
|
||||
"promptDiff": "Please compare our original contract with the seller-returned contract and list key modified, deleted, and added clauses with risks.",
|
||||
"promptSuggestion": "Please provide revision suggestions that can be used directly in commercial negotiation.",
|
||||
"llmEnhanced": "AI enhanced",
|
||||
"tempTemplateChip": "Temp template: {name}",
|
||||
"originalContractChip": "Our original: {name}",
|
||||
"sellerReturnedContractLabel": "Seller-returned contract",
|
||||
"contractToReviewLabel": "Contract to review",
|
||||
"soloHint": "Solo review · no template",
|
||||
"tempTemplateUploaded": "Temporary template uploaded (session only)",
|
||||
"originalContractUploaded": "Our original contract has been uploaded",
|
||||
"uploadFailed": "Upload failed",
|
||||
"oneContractOnly": "Upload only one seller-returned contract and remove extra files",
|
||||
"compareFilesRequired": "Contract comparison requires both our original and the seller-returned contract",
|
||||
"defaultUserQuery": "Please {mode} for \"{file}\"",
|
||||
"reviewFailed": "Review failed",
|
||||
"resultTitle": "Procurement Contract Review Result",
|
||||
"completed": "Review complete",
|
||||
"counterpartyContract": "Counterparty contract",
|
||||
"contractNo": "Contract No.",
|
||||
"supplier": "Supplier",
|
||||
"riskItems": "items",
|
||||
"changesUnchanged": "Unchanged",
|
||||
"changesCount": "Changes",
|
||||
"reviewNo": "Review No.",
|
||||
"mode": "Mode",
|
||||
"status": "Status",
|
||||
"riskSummary": "Risk summary",
|
||||
"containsHighRisk": "{count} high-risk items",
|
||||
"noHighRisk": "No high risk",
|
||||
"sourceLibrary": "Template library",
|
||||
"sourceUpload": "User upload",
|
||||
"template": "Template",
|
||||
"comparisonBaseline": "Our original contract",
|
||||
"downloadReport": "Download review report",
|
||||
"downloadDifferenceReport": "Download difference report",
|
||||
"downloadAnnotated": "Download annotated contract",
|
||||
"downloadAnnotatedOk": "Annotated contract download started",
|
||||
"downloadAnnotatedFailed": "Failed to download annotated contract",
|
||||
"anchorPage": "Source page {page}",
|
||||
"downloading": "Downloading…",
|
||||
"downloadOk": "Report download started",
|
||||
"downloadFailed": "Download failed",
|
||||
"riskHigh": "High risk",
|
||||
"riskMedium": "Medium risk",
|
||||
"riskLow": "Low risk",
|
||||
"riskShortHigh": "H",
|
||||
"riskShortMedium": "M",
|
||||
"riskShortLow": "L",
|
||||
"riskOk": "OK",
|
||||
"riskNoFinding": "No risk found",
|
||||
"changeInsert": "Insert",
|
||||
"changeDelete": "Delete",
|
||||
"changeModify": "Modify",
|
||||
"changePass": "Covered",
|
||||
"changeMissing": "Missing",
|
||||
"colClause": "Clause",
|
||||
"colChange": "Type",
|
||||
"colRisk": "Risk",
|
||||
"colTemplateText": "Template text",
|
||||
"colContractText": "Contract text",
|
||||
"colDetail": "Detail",
|
||||
"colComparison": "Change comparison",
|
||||
"unreadableComparison": "The source PDF text encoding is incompatible, so the changed content cannot be displayed reliably. Upload a Word file or a searchable-text PDF.",
|
||||
"noComparisonText": "No clause comparison is available",
|
||||
"noClauses": "No clause differences or red-line gaps detected.",
|
||||
"statusSuccess": "Success",
|
||||
"statusFailed": "Failed",
|
||||
"statusRunning": "Running",
|
||||
"reviewQueued": "Review submitted and queued",
|
||||
"reviewRunning": "Contract review in progress",
|
||||
"stepQueued": "Queued",
|
||||
"stepExtracting": "Extract & clean",
|
||||
"stepStructuring": "Identify clauses",
|
||||
"stepComparing": "Compare & redlines",
|
||||
"stepRiskScanning": "Scan risk rules",
|
||||
"stepAiReviewing": "AI full review",
|
||||
"stepValidating": "Validate & merge",
|
||||
"stepCompleted": "Completed",
|
||||
"changeRuleScan": "Red-line scan",
|
||||
"changePolicyScan": "Procurement policy",
|
||||
"changeLlmScan": "AI finding",
|
||||
"changeOcrUncertain": "Needs confirmation",
|
||||
"sectionChanges": "Contract changes",
|
||||
"sectionIndependentRisks": "Independent risks",
|
||||
"sectionConfirmations": "Items to confirm",
|
||||
"colEvidence": "Source evidence",
|
||||
"colSuggestion": "Revision suggestion",
|
||||
"confirmationsHidden": "{count} additional OCR/extraction items are collapsed. Review the source or annotated contract.",
|
||||
"confirmationsSummary": "{count} items are affected by OCR/extraction noise and require source verification.",
|
||||
"sectionLegalRisk": "Legal and fulfillment risks",
|
||||
"sectionCommercial": "Commercial items to confirm",
|
||||
"sectionFormatMetadata": "Format and information changes",
|
||||
"changeClassCommercial": "Commercial change",
|
||||
"changeClassMetadata": "Information change",
|
||||
"changeClassFormat": "Format change",
|
||||
"needsReview": "Needs review",
|
||||
"regionFallback": "Comparison region rules were not applied; this review safely fell back to full-document comparison.",
|
||||
"attachmentAdded": "The returned contract adds {count} attachment page(s)",
|
||||
"attachmentRemoved": "The returned contract removes {count} attachment page(s)",
|
||||
"attachmentContentIgnored": "Attachment content is excluded from differences"
|
||||
}
|
||||
}
|
||||
@@ -45,6 +45,9 @@
|
||||
"FILE_ASSET_SIZE_EXCEEDED": "File size exceeds the limit.",
|
||||
"FILE_ASSET_EXPIRED": "File asset has expired.",
|
||||
"FILE_ASSET_ALREADY_REFERENCED": "File asset is already referenced and cannot be deleted.",
|
||||
"PROCUREMENT_CONTRACT_TEMPLATE_REFERENCED": "This template is referenced by review history and cannot be deleted. Disable it instead.",
|
||||
"PROCUREMENT_CONTRACT_INVALID_COMPARISON_REGION_CONFIG": "The comparison region configuration is invalid. Check fields, anchors, and attachment policy.",
|
||||
"PROCUREMENT_CONTRACT_COMPARISON_REGION_PREVIEW_FAILED": "Comparison regions could not be recognized from the template file.",
|
||||
"FILE_ASSET_INVALID_STATUS": "File asset status does not allow this operation.",
|
||||
"SHIPPING_NOTICE_INTAKE_NOT_FOUND": "Shipping notice intake not found.",
|
||||
"SHIPPING_NOTICE_INTAKE_PARSE_PENDING": "Shipping notice is still parsing. Please wait before confirming the batch.",
|
||||
|
||||
@@ -26,7 +26,9 @@
|
||||
"permissions": "สิทธิ์แอปพลิเคชัน",
|
||||
"requests": "คำขอสิทธิ์",
|
||||
"reports": "รายงานข้อมูล",
|
||||
"schedules": "Schedule Management"
|
||||
"schedules": "Schedule Management",
|
||||
"platformApps": "แอปแพลตฟอร์ม",
|
||||
"procurementContract": "ตรวจสอบสัญญาจัดซื้อ"
|
||||
},
|
||||
"platformApps": {
|
||||
"guideUsage": "ประเภทการใช้งานเอกสาร",
|
||||
@@ -1162,5 +1164,153 @@
|
||||
"batchPermissionUpdateFailed": "การอัปเดตสิทธิ์เป็นชุดล้มเหลว",
|
||||
"enterOneField": "กรุณากรอกข้อมูลอย่างน้อยหนึ่งช่องเพื่ออัปเดต",
|
||||
"batchDeleteResult": "ลบผู้ใช้ {count} คนแล้ว"
|
||||
},
|
||||
"procurementContract": {
|
||||
"title": "ตรวจสอบสัญญาจัดซื้อ",
|
||||
"subtitle": "จัดการเทมเพลต กฎเส้นแดงความเสี่ยง และประวัติการตรวจสอบ",
|
||||
"tabTemplates": "เทมเพลต",
|
||||
"tabRules": "กฎความเสี่ยง",
|
||||
"addRule": "เพิ่มกฎ",
|
||||
"rulesHint": "กฎในระบบใช้การตรวจสอบเงื่อนไขจัดซื้อแบบผสม ส่วนกฎที่กำหนดเองจับคู่ด้วยคำสำคัญเท่านั้น โปรดใช้หมวดมาตรฐาน",
|
||||
"ruleStatTotal": "กฎทั้งหมด",
|
||||
"ruleStatEnabled": "เปิดใช้งาน",
|
||||
"ruleStatHighRisk": "ความเสี่ยงสูง",
|
||||
"emptyRules": "ยังไม่มีกฎความเสี่ยง",
|
||||
"ruleCreateTitle": "สร้างกฎความเสี่ยง",
|
||||
"ruleEditTitle": "แก้ไขกฎความเสี่ยง",
|
||||
"ruleCreateOk": "สร้างกฎแล้ว",
|
||||
"ruleEditOk": "อัปเดตกฎแล้ว",
|
||||
"ruleRequiredFields": "กรุณากรอกชื่อ หมวด คำอธิบายความเสี่ยง และคำแนะนำ",
|
||||
"ruleKeywordsRequired": "กรุณาใส่คีย์เวิร์ดอย่างน้อยหนึ่งคำ",
|
||||
"ruleCodePlaceholder": "ระบบจะสร้างหลังบันทึก",
|
||||
"ruleCodeGeneratedHint": "ระบบจะสร้างรหัสภายในให้กฎที่กำหนดเองหลังบันทึก",
|
||||
"ruleCodeReadonlyHint": "รหัสเป็นตัวระบุกฎภายในและไม่สามารถแก้ไขได้",
|
||||
"builtinRuleLogicHint": "นี่คือกฎจัดซื้อในระบบ หมวด คำสำคัญ และเงื่อนไขทริกเกอร์ถูกกำหนดตายตัว เพราะระบบตรวจสอบเงื่อนไขธุรกิจแบบผสม",
|
||||
"ruleKeywordsPlaceholder": "คีย์เวิร์ดคั่นด้วยจุลภาค เช่น ชำระเงิน, ตรวจรับ, ใบแจ้งหนี้",
|
||||
"keywordPresentLogicHint": "พบคำสำคัญคำใดคำหนึ่งจะทริกเกอร์ความเสี่ยง",
|
||||
"keywordMissingLogicHint": "คำสำคัญทุกคำไม่ปรากฏจึงจะทริกเกอร์ความเสี่ยง ใช้กฎในระบบสำหรับเงื่อนไขแบบผสม",
|
||||
"category_payment": "การชำระเงิน",
|
||||
"category_delivery": "การส่งมอบ",
|
||||
"category_acceptance": "การตรวจรับ",
|
||||
"category_warranty": "การรับประกัน/หลังการขาย",
|
||||
"category_liability": "การผิดสัญญาและความรับผิด",
|
||||
"category_jurisdiction": "เขตอำนาจศาล",
|
||||
"category_dispute": "การระงับข้อพิพาท",
|
||||
"category_ip": "ทรัพย์สินทางปัญญา",
|
||||
"category_other": "อื่น ๆ",
|
||||
"confirmDeleteRule": "ลบกฎ \"{title}\"? การตรวจสอบจะไม่ใช้เส้นแดงนี้ต่อไป",
|
||||
"colRuleCode": "รหัส",
|
||||
"colRuleTitle": "ชื่อ",
|
||||
"colCategory": "หมวด",
|
||||
"colKeywords": "คีย์เวิร์ด",
|
||||
"colTrigger": "เงื่อนไข",
|
||||
"colSort": "เรียง",
|
||||
"ruleSortHint": "ค่ายิ่งน้อยยิ่งมีลำดับความสำคัญสูง กฎของสัญญาเดียวกันจะตรวจตามลำดับจากน้อยไปมาก",
|
||||
"colContractType": "ประเภทสัญญา",
|
||||
"colRiskHint": "คำอธิบายความเสี่ยง",
|
||||
"colSuggestion": "คำแนะนำ",
|
||||
"colNegotiation": "ข้อความเจรจา",
|
||||
"triggerMissing": "ทริกเกอร์เมื่อขาดคีย์เวิร์ด",
|
||||
"triggerPresent": "ทริกเกอร์เมื่อพบคีย์เวิร์ด",
|
||||
"riskHigh": "สูง",
|
||||
"riskMedium": "กลาง",
|
||||
"riskLow": "ต่ำ",
|
||||
"tabReviews": "ประวัติ",
|
||||
"uploadTemplate": "อัปโหลดเทมเพลต",
|
||||
"colName": "ชื่อ",
|
||||
"colVersion": "เวอร์ชัน",
|
||||
"colFile": "ไฟล์",
|
||||
"colStatus": "สถานะ",
|
||||
"colDefault": "ค่าเริ่มต้น",
|
||||
"colActions": "การดำเนินการ",
|
||||
"colMode": "โหมด",
|
||||
"colSource": "แหล่งเทมเพลต",
|
||||
"colReviewNo": "เลขที่",
|
||||
"colContract": "สัญญา",
|
||||
"colContractNo": "เลขที่สัญญา",
|
||||
"colSupplier": "ผู้ขาย",
|
||||
"colTemplate": "เทมเพลต",
|
||||
"colUser": "ผู้ใช้",
|
||||
"colFinishedAt": "เวลาที่เสร็จสิ้น",
|
||||
"colRisk": "ความเสี่ยง",
|
||||
"keyword": "คำค้น",
|
||||
"modeCompare": "เปรียบเทียบ",
|
||||
"modeSolo": "ตรวจเดี่ยว",
|
||||
"sourceLibrary": "คลัง",
|
||||
"sourceUpload": "อัปโหลดโดยผู้ใช้",
|
||||
"sourceNone": "ไม่มี",
|
||||
"setDefault": "ตั้งเป็นค่าเริ่มต้น",
|
||||
"setAsDefault": "ตั้งเป็นเทมเพลตเริ่มต้น",
|
||||
"enable": "เปิดใช้",
|
||||
"disable": "ปิดใช้",
|
||||
"emptyTemplates": "ยังไม่มีเทมเพลต",
|
||||
"emptyReviews": "ยังไม่มีประวัติ",
|
||||
"total": "ทั้งหมด {n} รายการ",
|
||||
"loadFailed": "โหลดไม่สำเร็จ",
|
||||
"fileRequired": "กรุณาเลือกไฟล์",
|
||||
"uploadOk": "อัปโหลดสำเร็จ",
|
||||
"uploadFailed": "อัปโหลดล้มเหลว",
|
||||
"setDefaultOk": "ตั้งค่าเริ่มต้นแล้ว",
|
||||
"actionFailed": "ดำเนินการล้มเหลว",
|
||||
"confirmDelete": "ลบเทมเพลตนี้?",
|
||||
"downloadReport": "ดาวน์โหลดรายงาน",
|
||||
"downloadAnnotated": "ดาวน์โหลดสัญญาที่ทำเครื่องหมาย",
|
||||
"downloadFile": "ดาวน์โหลดไฟล์",
|
||||
"downloadContract": "ดาวน์โหลดสัญญา",
|
||||
"downloadTemplateFile": "ดาวน์โหลดเทมเพลตที่ใช้",
|
||||
"downloadFailed": "ดาวน์โหลดล้มเหลว",
|
||||
"loading": "กำลังโหลด…",
|
||||
"all": "ทั้งหมด",
|
||||
"search": "ค้นหา",
|
||||
"detail": "รายละเอียด",
|
||||
"saving": "กำลังบันทึก…",
|
||||
"sourceAll": "แหล่งทั้งหมด",
|
||||
"keywordPlaceholder": "ค้นหาเลขที่ตรวจ / เลขสัญญา / ผู้ขาย / ไฟล์…",
|
||||
"reviewNoPlaceholder": "CR-…",
|
||||
"uploadModalTitle": "อัปโหลดเทมเพลตสัญญา",
|
||||
"uploadZonePrefix": "ลาก Word / PDF มาวาง หรือ ",
|
||||
"uploadZoneAction": "คลิกเพื่อเลือกไฟล์",
|
||||
"uploadZoneReplace": "คลิกหรือลากเพื่อเปลี่ยนไฟล์",
|
||||
"noFileSelected": "ยังไม่ได้เลือกไฟล์",
|
||||
"templateName": "ชื่อเทมเพลต",
|
||||
"versionNo": "เวอร์ชัน",
|
||||
"defaultNo": "ไม่",
|
||||
"defaultYes": "ใช่ (ค่าเริ่มต้นในแชท)",
|
||||
"remark": "หมายเหตุ",
|
||||
"remarkPlaceholder": "กรณีใช้งาน / สิ่งที่เปลี่ยนจากเวอร์ชันก่อน…",
|
||||
"uploadCallout": "เมื่อเปิดใช้ เทมเพลตจะปรากฏในดรอปดาวน์แชททันที",
|
||||
"saveToLibrary": "บันทึกลงคลัง",
|
||||
"defaultYesShort": "ใช่",
|
||||
"statusSuccess": "สำเร็จ",
|
||||
"statusFailed": "ล้มเหลว",
|
||||
"statusRunning": "กำลังทำ",
|
||||
"statusPending": "รอดำเนินการ",
|
||||
"confirmDeleteNamed": "ลบเทมเพลต \"{name} {version}\"?",
|
||||
"editModalTitle": "แก้ไขเทมเพลตสัญญา",
|
||||
"saveChanges": "บันทึกการแก้ไข",
|
||||
"editOk": "อัปเดตเทมเพลตแล้ว",
|
||||
"editFileHint": "โหมดแก้ไขยังไม่รองรับการเปลี่ยนไฟล์ หากต้องการไฟล์ใหม่ ให้อัปโหลดเวอร์ชันใหม่",
|
||||
"nameVersionRequired": "ต้องระบุชื่อและเวอร์ชัน",
|
||||
"regionConfigAction": "พื้นที่เปรียบเทียบ",
|
||||
"regionConfigTitle": "การตั้งค่าพื้นที่เปรียบเทียบ",
|
||||
"regionConfigHint": "กฎใช้แบ่งเอกสารสองไฟล์ที่อัปโหลดครั้งนี้เท่านั้น และไม่แทนที่สัญญาต้นฉบับ",
|
||||
"regionMetadata": "ฟิลด์ข้อมูลส่วนหัว",
|
||||
"regionField_contract_no": "เลขที่สัญญา",
|
||||
"regionField_buyer": "ผู้ซื้อ",
|
||||
"regionField_seller": "ผู้ขาย",
|
||||
"regionField_version": "เวอร์ชัน",
|
||||
"regionBodyStart": "จุดเริ่มเนื้อหา (หนึ่งรายการต่อบรรทัด)",
|
||||
"regionBodyEnd": "จุดสิ้นสุดเนื้อหา (หนึ่งรายการต่อบรรทัด)",
|
||||
"regionSignatureTerms": "คำช่วยระบุส่วนลงนาม (หนึ่งรายการต่อบรรทัด)",
|
||||
"regionAttachmentStart": "หัวข้อเริ่มภาคผนวก (หนึ่งรายการต่อบรรทัด)",
|
||||
"regionAttachmentPolicy": "นโยบายภาคผนวก",
|
||||
"regionPageCountOnly": "แจ้งเฉพาะจำนวนหน้าที่เพิ่มหรือลด และไม่ตรวจเนื้อหาภาคผนวก",
|
||||
"regionRestoreV4": "คืนค่าเริ่มต้น V4",
|
||||
"regionPreview": "แสดงตัวอย่างการระบุ",
|
||||
"regionPreviewing": "กำลังระบุ…",
|
||||
"regionPreviewRecognized": "ระบุพื้นที่เนื้อหาสำเร็จ",
|
||||
"regionPreviewIncomplete": "ระบุจุดยึดไม่ครบ ระบบจะย้อนกลับอย่างปลอดภัย",
|
||||
"regionPreviewFailed": "แสดงตัวอย่างการระบุพื้นที่ไม่สำเร็จ",
|
||||
"regionSaved": "บันทึกการตั้งค่าพื้นที่เปรียบเทียบแล้ว"
|
||||
}
|
||||
}
|
||||
@@ -725,8 +725,14 @@
|
||||
"ฝั่งจัดการต้องส่งออกวันที่เริ่มงาน วันที่เสร็จสิ้น แผนก ชื่อ รหัสพนักงาน และคะแนนได้"
|
||||
],
|
||||
"booleanOptions": [
|
||||
{ "id": "true", "label": "ถูก" },
|
||||
{ "id": "false", "label": "ผิด" }
|
||||
{
|
||||
"id": "true",
|
||||
"label": "ถูก"
|
||||
},
|
||||
{
|
||||
"id": "false",
|
||||
"label": "ผิด"
|
||||
}
|
||||
],
|
||||
"questionBank": [
|
||||
{
|
||||
@@ -736,10 +742,22 @@
|
||||
"answer": "c",
|
||||
"explanation": "ตามข้อสอบอบรมพนักงานใหม่ เงินเดือนจ่ายในวันที่ 15 ของทุกเดือน",
|
||||
"options": [
|
||||
{ "id": "a", "label": "A. วันที่ 8" },
|
||||
{ "id": "b", "label": "B. วันที่ 9" },
|
||||
{ "id": "c", "label": "C. วันที่ 15" },
|
||||
{ "id": "d", "label": "D. วันที่ 27" }
|
||||
{
|
||||
"id": "a",
|
||||
"label": "A. วันที่ 8"
|
||||
},
|
||||
{
|
||||
"id": "b",
|
||||
"label": "B. วันที่ 9"
|
||||
},
|
||||
{
|
||||
"id": "c",
|
||||
"label": "C. วันที่ 15"
|
||||
},
|
||||
{
|
||||
"id": "d",
|
||||
"label": "D. วันที่ 27"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -749,9 +767,18 @@
|
||||
"answer": "b",
|
||||
"explanation": "โรงอาหารของบริษัทใช้ระบบสั่งอาหาร Zhongmi",
|
||||
"options": [
|
||||
{ "id": "a", "label": "A. OA" },
|
||||
{ "id": "b", "label": "B. ระบบสั่งอาหาร Zhongmi" },
|
||||
{ "id": "c", "label": "C. ERP" }
|
||||
{
|
||||
"id": "a",
|
||||
"label": "A. OA"
|
||||
},
|
||||
{
|
||||
"id": "b",
|
||||
"label": "B. ระบบสั่งอาหาร Zhongmi"
|
||||
},
|
||||
{
|
||||
"id": "c",
|
||||
"label": "C. ERP"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -761,10 +788,22 @@
|
||||
"answer": "abcd",
|
||||
"explanation": "ตัวเลือกทั้งสี่ข้อเป็นกลุ่มผลิตภัณฑ์ของบริษัทตามข้อสอบ",
|
||||
"options": [
|
||||
{ "id": "abcd", "label": "A/B/C/D ทั้งหมด" },
|
||||
{ "id": "ab", "label": "A/B" },
|
||||
{ "id": "cd", "label": "C/D" },
|
||||
{ "id": "a", "label": "เฉพาะ A" }
|
||||
{
|
||||
"id": "abcd",
|
||||
"label": "A/B/C/D ทั้งหมด"
|
||||
},
|
||||
{
|
||||
"id": "ab",
|
||||
"label": "A/B"
|
||||
},
|
||||
{
|
||||
"id": "cd",
|
||||
"label": "C/D"
|
||||
},
|
||||
{
|
||||
"id": "a",
|
||||
"label": "เฉพาะ A"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -774,10 +813,22 @@
|
||||
"answer": "c",
|
||||
"explanation": "การลาต้องใช้แบบฟอร์มใบลาของ OA",
|
||||
"options": [
|
||||
{ "id": "a", "label": "A. ใบขอโอที" },
|
||||
{ "id": "b", "label": "B. ใบติดต่อ" },
|
||||
{ "id": "c", "label": "C. ใบลางาน" },
|
||||
{ "id": "d", "label": "D. ใบคำขอพนักงาน" }
|
||||
{
|
||||
"id": "a",
|
||||
"label": "A. ใบขอโอที"
|
||||
},
|
||||
{
|
||||
"id": "b",
|
||||
"label": "B. ใบติดต่อ"
|
||||
},
|
||||
{
|
||||
"id": "c",
|
||||
"label": "C. ใบลางาน"
|
||||
},
|
||||
{
|
||||
"id": "d",
|
||||
"label": "D. ใบคำขอพนักงาน"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -787,9 +838,18 @@
|
||||
"answer": "a",
|
||||
"explanation": "QC080000 คือมาตรฐานการจัดการกระบวนการสารอันตราย",
|
||||
"options": [
|
||||
{ "id": "a", "label": "A. มาตรฐานการจัดการสารอันตราย" },
|
||||
{ "id": "b", "label": "B. ระบบอาชีวอนามัยและความปลอดภัย" },
|
||||
{ "id": "c", "label": "C. ระบบการจัดการสิ่งแวดล้อม" }
|
||||
{
|
||||
"id": "a",
|
||||
"label": "A. มาตรฐานการจัดการสารอันตราย"
|
||||
},
|
||||
{
|
||||
"id": "b",
|
||||
"label": "B. ระบบอาชีวอนามัยและความปลอดภัย"
|
||||
},
|
||||
{
|
||||
"id": "c",
|
||||
"label": "C. ระบบการจัดการสิ่งแวดล้อม"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -799,8 +859,14 @@
|
||||
"answer": "a",
|
||||
"explanation": "5S หมายถึงสะสาง สะดวก สะอาด สุขลักษณะ และสร้างนิสัย",
|
||||
"options": [
|
||||
{ "id": "a", "label": "A. สะสาง สะดวก สะอาด สุขลักษณะ สร้างนิสัย" },
|
||||
{ "id": "b", "label": "B. สะสาง สะดวก ทำความสะอาด สุขลักษณะ สร้างนิสัย" }
|
||||
{
|
||||
"id": "a",
|
||||
"label": "A. สะสาง สะดวก สะอาด สุขลักษณะ สร้างนิสัย"
|
||||
},
|
||||
{
|
||||
"id": "b",
|
||||
"label": "B. สะสาง สะดวก ทำความสะอาด สุขลักษณะ สร้างนิสัย"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -810,23 +876,226 @@
|
||||
"answer": "a",
|
||||
"explanation": "ต้องยืนด้านเหนือลมเมื่อใช้ถังดับเพลิง",
|
||||
"options": [
|
||||
{ "id": "a", "label": "A. ด้านเหนือลม" },
|
||||
{ "id": "b", "label": "B. ด้านใต้ลม" }
|
||||
{
|
||||
"id": "a",
|
||||
"label": "A. ด้านเหนือลม"
|
||||
},
|
||||
{
|
||||
"id": "b",
|
||||
"label": "B. ด้านใต้ลม"
|
||||
}
|
||||
]
|
||||
},
|
||||
{ "id": "q8", "type": "boolean", "prompt": "การเข้างานปกติต้องลงเวลา และการทำโอทีต้องยื่นคำขอล่วงหน้า", "answer": "true", "explanation": "การเข้างานและโอทีต้องปฏิบัติตามกฎการลงเวลาของบริษัท" },
|
||||
{ "id": "q9", "type": "boolean", "prompt": "หากลืมลงเวลา ต้องยื่นคำขอแก้ไขผ่าน OA", "answer": "true", "explanation": "การลืมลงเวลาต้องแก้ไขผ่านกระบวนการ OA" },
|
||||
{ "id": "q10", "type": "boolean", "prompt": "เงินเดือนคำนวณตั้งแต่วันที่ 21 ของเดือนก่อนถึงวันที่ 20 ของเดือนปัจจุบัน", "answer": "true", "explanation": "ข้อสอบระบุรอบการคำนวณเงินเดือนนี้ไว้อย่างชัดเจน" },
|
||||
{ "id": "q11", "type": "boolean", "prompt": "การรับประทานอาหารในโรงอาหารต้องจองล่วงหน้า และสามารถใช้การสแกนใบหน้าได้", "answer": "true", "explanation": "โรงอาหารรองรับทั้งการจองล่วงหน้าและการสแกนใบหน้า" },
|
||||
{ "id": "q12", "type": "boolean", "prompt": "เมื่อเกิดไฟไหม้หรือระเบิด ควรโทร 119 ทันที", "answer": "true", "explanation": "การแจ้งหน่วยดับเพลิงเป็นขั้นตอนแรกที่ถูกต้อง" },
|
||||
{ "id": "q13", "type": "boolean", "prompt": "ผู้พักอาศัยในหอพักต้องระวังเรื่องไฟ และห้ามต่อสายไฟเองหรือใช้เครื่องใช้ไฟฟ้ากำลังสูง", "answer": "true", "explanation": "นี่คือข้อบังคับด้านความปลอดภัยจากอัคคีภัยในหอพัก" },
|
||||
{ "id": "q14", "type": "boolean", "prompt": "การปฏิบัติตามกฎความปลอดภัยในการผลิตเป็นหน้าที่ของพนักงาน", "answer": "true", "explanation": "การปฏิบัติตามกฎความปลอดภัยเป็นทั้งข้อกำหนดและหน้าที่ของพนักงาน" },
|
||||
{ "id": "q15", "type": "boolean", "prompt": "บัตรพนักงานสามารถให้ผู้อื่นยืมใช้ได้อย่างอิสระ", "answer": "false", "explanation": "บัตรพนักงานเป็นเอกสารยืนยันตัวตนส่วนบุคคล ห้ามให้ยืม" },
|
||||
{ "id": "q16", "type": "boolean", "prompt": "RoHS ใช้กำหนดมาตรฐานวัสดุและกระบวนการของผลิตภัณฑ์ไฟฟ้าและอิเล็กทรอนิกส์เพื่อปกป้องสุขภาพและสิ่งแวดล้อม", "answer": "true", "explanation": "เป้าหมายหลักของ RoHS คือการจำกัดสารอันตรายและลดความเสี่ยงต่อสิ่งแวดล้อม" },
|
||||
{ "id": "q17", "type": "boolean", "prompt": "นโยบาย HSF ของบริษัทคือ ออกแบบสีเขียว จัดซื้อเป็นมิตรต่อสิ่งแวดล้อม ประหยัดทรัพยากร และผลิตอย่างเป็นมิตรต่อสิ่งแวดล้อม", "answer": "true", "explanation": "นี่คือข้อความนโยบาย HSF ตามที่ระบุในข้อสอบ" },
|
||||
{ "id": "q18", "type": "boolean", "prompt": "EHS หมายถึง Environment, Health, Safety", "answer": "true", "explanation": "EHS เป็นตัวย่อมาตรฐานของสิ่งแวดล้อม สุขภาพ และความปลอดภัย" },
|
||||
{ "id": "q19", "type": "boolean", "prompt": "เอกสารจากภายนอกไม่จำเป็นต้องถูกควบคุมหรือจัดการโดยองค์กร", "answer": "false", "explanation": "เอกสารจากภายนอกก็ต้องมีการควบคุมเช่นกัน" },
|
||||
{ "id": "q20", "type": "boolean", "prompt": "ข้อกำหนดที่เกี่ยวข้องกับผลิตภัณฑ์ควรรวมถึงข้อกำหนดตามกฎหมายและข้อกำหนดของลูกค้า", "answer": "true", "explanation": "ข้อกำหนดของผลิตภัณฑ์ต้องครอบคลุมทั้งกฎหมายและความต้องการของลูกค้า" }
|
||||
{
|
||||
"id": "q8",
|
||||
"type": "boolean",
|
||||
"prompt": "การเข้างานปกติต้องลงเวลา และการทำโอทีต้องยื่นคำขอล่วงหน้า",
|
||||
"answer": "true",
|
||||
"explanation": "การเข้างานและโอทีต้องปฏิบัติตามกฎการลงเวลาของบริษัท"
|
||||
},
|
||||
{
|
||||
"id": "q9",
|
||||
"type": "boolean",
|
||||
"prompt": "หากลืมลงเวลา ต้องยื่นคำขอแก้ไขผ่าน OA",
|
||||
"answer": "true",
|
||||
"explanation": "การลืมลงเวลาต้องแก้ไขผ่านกระบวนการ OA"
|
||||
},
|
||||
{
|
||||
"id": "q10",
|
||||
"type": "boolean",
|
||||
"prompt": "เงินเดือนคำนวณตั้งแต่วันที่ 21 ของเดือนก่อนถึงวันที่ 20 ของเดือนปัจจุบัน",
|
||||
"answer": "true",
|
||||
"explanation": "ข้อสอบระบุรอบการคำนวณเงินเดือนนี้ไว้อย่างชัดเจน"
|
||||
},
|
||||
{
|
||||
"id": "q11",
|
||||
"type": "boolean",
|
||||
"prompt": "การรับประทานอาหารในโรงอาหารต้องจองล่วงหน้า และสามารถใช้การสแกนใบหน้าได้",
|
||||
"answer": "true",
|
||||
"explanation": "โรงอาหารรองรับทั้งการจองล่วงหน้าและการสแกนใบหน้า"
|
||||
},
|
||||
{
|
||||
"id": "q12",
|
||||
"type": "boolean",
|
||||
"prompt": "เมื่อเกิดไฟไหม้หรือระเบิด ควรโทร 119 ทันที",
|
||||
"answer": "true",
|
||||
"explanation": "การแจ้งหน่วยดับเพลิงเป็นขั้นตอนแรกที่ถูกต้อง"
|
||||
},
|
||||
{
|
||||
"id": "q13",
|
||||
"type": "boolean",
|
||||
"prompt": "ผู้พักอาศัยในหอพักต้องระวังเรื่องไฟ และห้ามต่อสายไฟเองหรือใช้เครื่องใช้ไฟฟ้ากำลังสูง",
|
||||
"answer": "true",
|
||||
"explanation": "นี่คือข้อบังคับด้านความปลอดภัยจากอัคคีภัยในหอพัก"
|
||||
},
|
||||
{
|
||||
"id": "q14",
|
||||
"type": "boolean",
|
||||
"prompt": "การปฏิบัติตามกฎความปลอดภัยในการผลิตเป็นหน้าที่ของพนักงาน",
|
||||
"answer": "true",
|
||||
"explanation": "การปฏิบัติตามกฎความปลอดภัยเป็นทั้งข้อกำหนดและหน้าที่ของพนักงาน"
|
||||
},
|
||||
{
|
||||
"id": "q15",
|
||||
"type": "boolean",
|
||||
"prompt": "บัตรพนักงานสามารถให้ผู้อื่นยืมใช้ได้อย่างอิสระ",
|
||||
"answer": "false",
|
||||
"explanation": "บัตรพนักงานเป็นเอกสารยืนยันตัวตนส่วนบุคคล ห้ามให้ยืม"
|
||||
},
|
||||
{
|
||||
"id": "q16",
|
||||
"type": "boolean",
|
||||
"prompt": "RoHS ใช้กำหนดมาตรฐานวัสดุและกระบวนการของผลิตภัณฑ์ไฟฟ้าและอิเล็กทรอนิกส์เพื่อปกป้องสุขภาพและสิ่งแวดล้อม",
|
||||
"answer": "true",
|
||||
"explanation": "เป้าหมายหลักของ RoHS คือการจำกัดสารอันตรายและลดความเสี่ยงต่อสิ่งแวดล้อม"
|
||||
},
|
||||
{
|
||||
"id": "q17",
|
||||
"type": "boolean",
|
||||
"prompt": "นโยบาย HSF ของบริษัทคือ ออกแบบสีเขียว จัดซื้อเป็นมิตรต่อสิ่งแวดล้อม ประหยัดทรัพยากร และผลิตอย่างเป็นมิตรต่อสิ่งแวดล้อม",
|
||||
"answer": "true",
|
||||
"explanation": "นี่คือข้อความนโยบาย HSF ตามที่ระบุในข้อสอบ"
|
||||
},
|
||||
{
|
||||
"id": "q18",
|
||||
"type": "boolean",
|
||||
"prompt": "EHS หมายถึง Environment, Health, Safety",
|
||||
"answer": "true",
|
||||
"explanation": "EHS เป็นตัวย่อมาตรฐานของสิ่งแวดล้อม สุขภาพ และความปลอดภัย"
|
||||
},
|
||||
{
|
||||
"id": "q19",
|
||||
"type": "boolean",
|
||||
"prompt": "เอกสารจากภายนอกไม่จำเป็นต้องถูกควบคุมหรือจัดการโดยองค์กร",
|
||||
"answer": "false",
|
||||
"explanation": "เอกสารจากภายนอกก็ต้องมีการควบคุมเช่นกัน"
|
||||
},
|
||||
{
|
||||
"id": "q20",
|
||||
"type": "boolean",
|
||||
"prompt": "ข้อกำหนดที่เกี่ยวข้องกับผลิตภัณฑ์ควรรวมถึงข้อกำหนดตามกฎหมายและข้อกำหนดของลูกค้า",
|
||||
"answer": "true",
|
||||
"explanation": "ข้อกำหนดของผลิตภัณฑ์ต้องครอบคลุมทั้งกฎหมายและความต้องการของลูกค้า"
|
||||
}
|
||||
]
|
||||
},
|
||||
"procurementContract": {
|
||||
"modeCompare": "เปรียบเทียบสัญญา",
|
||||
"modeSolo": "ตรวจเดี่ยว",
|
||||
"modeHint": "อัปโหลดไฟล์สัญญาตามโหมดที่เลือก",
|
||||
"compareHint": "อัปโหลดสัญญาต้นฉบับของเราและสัญญาที่ผู้ขายส่งกลับ",
|
||||
"selectTemplate": "เลือกเทมเพลต",
|
||||
"default": "ค่าเริ่มต้น",
|
||||
"uploadTempTemplate": "อัปโหลดเทมเพลตชั่วคราว",
|
||||
"uploadContract": "อัปโหลดสัญญา",
|
||||
"uploadOriginalContract": "อัปโหลดสัญญาต้นฉบับของเรา",
|
||||
"uploadSellerReturnedContract": "อัปโหลดสัญญาที่ผู้ขายส่งกลับ",
|
||||
"uploadContractToReview": "อัปโหลดสัญญาที่จะตรวจ",
|
||||
"quickReview": "ตรวจสัญญา",
|
||||
"quickRisk": "แจ้งเตือนความเสี่ยง",
|
||||
"quickDiff": "ความต่างจากเทมเพลต",
|
||||
"quickSuggestion": "คำแนะนำแก้ไข",
|
||||
"promptReview": "กรุณาตรวจสัญญาจัดซื้อฉบับนี้ และสรุปประเด็นหลักกับข้อสรุปตามระดับความเสี่ยงสูง กลาง และต่ำ",
|
||||
"promptRisk": "กรุณาเน้นระบุความเสี่ยงด้านกฎหมาย การชำระเงิน การส่งมอบ และความรับผิดจากการผิดสัญญา",
|
||||
"promptDiff": "กรุณาเปรียบเทียบสัญญาต้นฉบับของเรากับสัญญาที่ผู้ขายส่งกลับ และระบุข้อกำหนดสำคัญที่ถูกแก้ไข ลบ หรือเพิ่ม พร้อมความเสี่ยงที่เกี่ยวข้อง",
|
||||
"promptSuggestion": "กรุณาให้คำแนะนำการแก้ไขที่สามารถนำไปใช้ในการเจรจาทางธุรกิจได้โดยตรง",
|
||||
"llmEnhanced": "เสริมด้วย AI",
|
||||
"tempTemplateChip": "เทมเพลตชั่วคราว: {name}",
|
||||
"originalContractChip": "สัญญาต้นฉบับของเรา: {name}",
|
||||
"sellerReturnedContractLabel": "สัญญาที่ผู้ขายส่งกลับ",
|
||||
"contractToReviewLabel": "สัญญาที่จะตรวจ",
|
||||
"soloHint": "ตรวจเดี่ยว · ไม่ใช้เทมเพลต",
|
||||
"tempTemplateUploaded": "อัปโหลดเทมเพลตชั่วคราวแล้ว (ใช้เฉพาะเซสชันนี้)",
|
||||
"originalContractUploaded": "อัปโหลดสัญญาต้นฉบับของเราแล้ว",
|
||||
"uploadFailed": "อัปโหลดล้มเหลว",
|
||||
"oneContractOnly": "อัปโหลดสัญญาที่ผู้ขายส่งกลับเพียงหนึ่งไฟล์และลบไฟล์ส่วนเกิน",
|
||||
"compareFilesRequired": "การเปรียบเทียบต้องมีทั้งสัญญาต้นฉบับของเราและสัญญาที่ผู้ขายส่งกลับ",
|
||||
"defaultUserQuery": "กรุณา{mode} สำหรับ \"{file}\"",
|
||||
"reviewFailed": "ตรวจสอบล้มเหลว",
|
||||
"resultTitle": "ผลการตรวจสอบสัญญาจัดซื้อ",
|
||||
"completed": "ตรวจสอบเสร็จสิ้น",
|
||||
"counterpartyContract": "สัญญาคู่สัญญา",
|
||||
"contractNo": "เลขที่สัญญา",
|
||||
"supplier": "ผู้ขาย",
|
||||
"riskItems": "รายการ",
|
||||
"changesUnchanged": "ไม่มีการเปลี่ยนแปลง",
|
||||
"changesCount": "รายการแก้ไข",
|
||||
"reviewNo": "เลขที่",
|
||||
"mode": "โหมด",
|
||||
"status": "สถานะ",
|
||||
"riskSummary": "สรุปความเสี่ยง",
|
||||
"containsHighRisk": "ความเสี่ยงสูง {count} รายการ",
|
||||
"noHighRisk": "ไม่มีความเสี่ยงสูง",
|
||||
"sourceLibrary": "คลังเทมเพลต",
|
||||
"sourceUpload": "อัปโหลดโดยผู้ใช้",
|
||||
"template": "เทมเพลต",
|
||||
"comparisonBaseline": "สัญญาต้นฉบับของเรา",
|
||||
"downloadReport": "ดาวน์โหลดรายงานตรวจสอบ",
|
||||
"downloadDifferenceReport": "ดาวน์โหลดรายงานความแตกต่าง",
|
||||
"downloadAnnotated": "ดาวน์โหลดสัญญาที่ทำเครื่องหมาย",
|
||||
"downloadAnnotatedOk": "เริ่มดาวน์โหลดสัญญาที่ทำเครื่องหมายแล้ว",
|
||||
"downloadAnnotatedFailed": "ดาวน์โหลดสัญญาที่ทำเครื่องหมายไม่สำเร็จ",
|
||||
"anchorPage": "หน้าต้นฉบับ {page}",
|
||||
"downloading": "กำลังดาวน์โหลด…",
|
||||
"downloadOk": "เริ่มดาวน์โหลดรายงานแล้ว",
|
||||
"downloadFailed": "ดาวน์โหลดล้มเหลว",
|
||||
"riskHigh": "ความเสี่ยงสูง",
|
||||
"riskMedium": "ความเสี่ยงกลาง",
|
||||
"riskLow": "ความเสี่ยงต่ำ",
|
||||
"riskShortHigh": "สูง",
|
||||
"riskShortMedium": "กลาง",
|
||||
"riskShortLow": "ต่ำ",
|
||||
"riskOk": "ผ่าน",
|
||||
"riskNoFinding": "ไม่พบความเสี่ยง",
|
||||
"changeInsert": "เพิ่ม",
|
||||
"changeDelete": "ลบ",
|
||||
"changeModify": "แก้ไข",
|
||||
"changePass": "ครบ",
|
||||
"changeMissing": "ขาด",
|
||||
"colClause": "ข้อ",
|
||||
"colChange": "ประเภท",
|
||||
"colRisk": "ความเสี่ยง",
|
||||
"colTemplateText": "ข้อความเทมเพลต",
|
||||
"colContractText": "ข้อความสัญญา",
|
||||
"colDetail": "รายละเอียด",
|
||||
"colComparison": "เปรียบเทียบการเปลี่ยนแปลง",
|
||||
"unreadableComparison": "รหัสข้อความใน PDF ต้นฉบับไม่รองรับ จึงไม่สามารถแสดงเนื้อหาที่เปลี่ยนแปลงได้อย่างถูกต้อง โปรดอัปโหลดไฟล์ Word หรือ PDF ที่ค้นหาข้อความได้",
|
||||
"noComparisonText": "ไม่มีข้อมูลเปรียบเทียบข้อสัญญาที่แสดงได้",
|
||||
"noClauses": "ไม่พบความแตกต่างของข้อหรือช่องว่างในบัญชีแดง",
|
||||
"statusSuccess": "สำเร็จ",
|
||||
"statusFailed": "ล้มเหลว",
|
||||
"statusRunning": "กำลังดำเนินการ",
|
||||
"reviewQueued": "ส่งงานตรวจสอบแล้วและกำลังรอคิว",
|
||||
"reviewRunning": "กำลังตรวจสอบสัญญา",
|
||||
"stepQueued": "รอตรวจสอบ",
|
||||
"stepExtracting": "แยกและทำความสะอาด",
|
||||
"stepStructuring": "ระบุข้อสัญญา",
|
||||
"stepComparing": "เปรียบเทียบและตรวจเส้นแดง",
|
||||
"stepRiskScanning": "สแกนกฎความเสี่ยง",
|
||||
"stepAiReviewing": "AI ตรวจสอบทั้งหมด",
|
||||
"stepValidating": "ตรวจสอบและรวมผล",
|
||||
"stepCompleted": "ตรวจสอบเสร็จสิ้น",
|
||||
"changeRuleScan": "ตรวจสอบเงื่อนไขห้าม",
|
||||
"changePolicyScan": "นโยบายจัดซื้อ",
|
||||
"changeLlmScan": "AI ตรวจพบ",
|
||||
"changeOcrUncertain": "ต้องยืนยัน",
|
||||
"sectionChanges": "รายการแก้ไขสัญญา",
|
||||
"sectionIndependentRisks": "รายการความเสี่ยงอิสระ",
|
||||
"sectionConfirmations": "รายการที่ต้องยืนยัน",
|
||||
"colEvidence": "ข้อความต้นฉบับที่พบ",
|
||||
"colSuggestion": "ข้อเสนอแก้ไข",
|
||||
"confirmationsHidden": "มีรายการ OCR/การแยกข้อความอีก {count} รายการที่ไม่ได้แสดง โปรดตรวจสอบต้นฉบับหรือสัญญาที่ทำเครื่องหมาย",
|
||||
"confirmationsSummary": "มี {count} รายการที่ได้รับผลกระทบจาก OCR/การแยกข้อความและต้องตรวจสอบต้นฉบับ",
|
||||
"sectionLegalRisk": "ความเสี่ยงด้านกฎหมายและการปฏิบัติตามสัญญา",
|
||||
"sectionCommercial": "รายการทางธุรกิจที่ต้องยืนยัน",
|
||||
"sectionFormatMetadata": "การเปลี่ยนแปลงรูปแบบและข้อมูล",
|
||||
"changeClassCommercial": "การเปลี่ยนแปลงทางธุรกิจ",
|
||||
"changeClassMetadata": "การเปลี่ยนแปลงข้อมูล",
|
||||
"changeClassFormat": "การเปลี่ยนแปลงรูปแบบ",
|
||||
"needsReview": "ต้องยืนยัน",
|
||||
"regionFallback": "ไม่ได้ใช้กฎพื้นที่เปรียบเทียบ การตรวจครั้งนี้จึงย้อนกลับไปเปรียบเทียบทั้งเอกสารอย่างปลอดภัย",
|
||||
"attachmentAdded": "สัญญาที่ส่งกลับเพิ่มภาคผนวก {count} หน้า",
|
||||
"attachmentRemoved": "สัญญาที่ส่งกลับลดภาคผนวก {count} หน้า",
|
||||
"attachmentContentIgnored": "เนื้อหาภาคผนวกไม่รวมอยู่ในรายการความแตกต่าง"
|
||||
}
|
||||
}
|
||||
@@ -45,6 +45,9 @@
|
||||
"FILE_ASSET_SIZE_EXCEEDED": "ขนาดไฟล์เกินขีดจำกัด",
|
||||
"FILE_ASSET_EXPIRED": "ไฟล์หมดอายุแล้ว",
|
||||
"FILE_ASSET_ALREADY_REFERENCED": "ไฟล์ถูกอ้างอิงโดยธุรกิจแล้ว ไม่สามารถลบได้",
|
||||
"PROCUREMENT_CONTRACT_TEMPLATE_REFERENCED": "เทมเพลตนี้ถูกอ้างอิงโดยประวัติการตรวจสอบและไม่สามารถลบได้ โปรดปิดใช้งานแทน",
|
||||
"PROCUREMENT_CONTRACT_INVALID_COMPARISON_REGION_CONFIG": "การตั้งค่าพื้นที่เปรียบเทียบไม่ถูกต้อง โปรดตรวจสอบฟิลด์ จุดยึด และนโยบายภาคผนวก",
|
||||
"PROCUREMENT_CONTRACT_COMPARISON_REGION_PREVIEW_FAILED": "ไม่สามารถระบุพื้นที่เปรียบเทียบจากไฟล์เทมเพลตได้",
|
||||
"FILE_ASSET_INVALID_STATUS": "สถานะไฟล์ไม่อนุญาตการดำเนินการนี้",
|
||||
"SHIPPING_NOTICE_INTAKE_NOT_FOUND": "ไม่พบบันทึก intake ของใบแจ้งจัดส่ง",
|
||||
"SHIPPING_NOTICE_INTAKE_PARSE_PENDING": "ใบแจ้งจัดส่งยังกำลังแยกข้อความ โปรดรอก่อนยืนยันสร้างชุดงาน",
|
||||
|
||||
@@ -27,7 +27,8 @@
|
||||
"platformApps": "平台应用说明",
|
||||
"requests": "权限审批",
|
||||
"reports": "数据报表",
|
||||
"schedules": "排程管理"
|
||||
"schedules": "排程管理",
|
||||
"procurementContract": "采购合同审查"
|
||||
},
|
||||
"platformApps": {
|
||||
"guideUsage": "资料用途",
|
||||
@@ -1272,5 +1273,153 @@
|
||||
"batchPermissionUpdateFailed": "批量权限更新失败",
|
||||
"enterOneField": "请至少输入一个要更新的字段",
|
||||
"batchDeleteResult": "已删除 {count} 位用户。"
|
||||
},
|
||||
"procurementContract": {
|
||||
"title": "采购合同审查",
|
||||
"subtitle": "维护标准合同模板、风险红线规则并查看审查历史",
|
||||
"tabTemplates": "模板库",
|
||||
"tabRules": "风险规则",
|
||||
"tabReviews": "审查历史",
|
||||
"addRule": "新增规则",
|
||||
"rulesHint": "内置规则采用采购组合判断;自定义规则只按关键词匹配。请使用标准条款分类。",
|
||||
"ruleStatTotal": "当前规则",
|
||||
"ruleStatEnabled": "已启用",
|
||||
"ruleStatHighRisk": "高风险",
|
||||
"emptyRules": "暂无风险规则",
|
||||
"ruleCreateTitle": "新增风险规则",
|
||||
"ruleEditTitle": "编辑风险规则",
|
||||
"ruleCreateOk": "规则已创建",
|
||||
"ruleEditOk": "规则已更新",
|
||||
"ruleRequiredFields": "请填写标题、分类、风险说明与建议",
|
||||
"ruleKeywordsRequired": "请填写至少一个关键词",
|
||||
"ruleCodePlaceholder": "保存后由系统生成",
|
||||
"ruleCodeGeneratedHint": "自定义规则保存后由系统生成内部编码。",
|
||||
"ruleCodeReadonlyHint": "编码是规则的内部标识,不能修改。",
|
||||
"builtinRuleLogicHint": "这是内置采购规则,系统按组合业务条件判断;分类、关键词和触发条件固定,不按普通关键词规则判断。",
|
||||
"ruleKeywordsPlaceholder": "多个关键词用逗号分隔,如:付款,验收,发票",
|
||||
"keywordPresentLogicHint": "命中任意一个关键词即触发风险。",
|
||||
"keywordMissingLogicHint": "所有关键词均未出现时才触发风险;如需检查组合条件,请使用内置规则。",
|
||||
"category_payment": "付款",
|
||||
"category_delivery": "交付/交期",
|
||||
"category_acceptance": "验收",
|
||||
"category_warranty": "质保/售后",
|
||||
"category_liability": "违约与责任",
|
||||
"category_jurisdiction": "管辖地",
|
||||
"category_dispute": "争议解决",
|
||||
"category_ip": "知识产权",
|
||||
"category_other": "其他",
|
||||
"confirmDeleteRule": "确认删除规则「{title}」?删除后审查将不再使用该条红线。",
|
||||
"colRuleCode": "编码",
|
||||
"colRuleTitle": "标题",
|
||||
"colCategory": "条款分类",
|
||||
"colKeywords": "关键词",
|
||||
"colTrigger": "触发条件",
|
||||
"colSort": "排序",
|
||||
"ruleSortHint": "数值越小,规则执行优先级越高;同一份合同按排序从小到大依次检查。",
|
||||
"colContractType": "合同类型",
|
||||
"colRiskHint": "风险说明",
|
||||
"colSuggestion": "修改建议",
|
||||
"colNegotiation": "谈判话术",
|
||||
"triggerMissing": "关键词缺失时触发",
|
||||
"triggerPresent": "关键词出现时触发",
|
||||
"riskHigh": "高风险",
|
||||
"riskMedium": "中风险",
|
||||
"riskLow": "低风险",
|
||||
"uploadTemplate": "上传模板",
|
||||
"colName": "名称",
|
||||
"colVersion": "版本",
|
||||
"colFile": "文件",
|
||||
"colStatus": "状态",
|
||||
"colDefault": "默认",
|
||||
"colActions": "操作",
|
||||
"colMode": "模式",
|
||||
"colSource": "模板来源",
|
||||
"colReviewNo": "审查编号",
|
||||
"colContract": "待审合同",
|
||||
"colContractNo": "合同编号",
|
||||
"colSupplier": "供应商",
|
||||
"colTemplate": "比对模板",
|
||||
"colUser": "发起人",
|
||||
"colFinishedAt": "完成时间",
|
||||
"colRisk": "风险",
|
||||
"keyword": "关键词",
|
||||
"modeCompare": "模板比对",
|
||||
"modeSolo": "单份审核",
|
||||
"sourceLibrary": "模板库",
|
||||
"sourceUpload": "用户上传",
|
||||
"sourceNone": "无",
|
||||
"setDefault": "设为默认",
|
||||
"setAsDefault": "设为默认模板",
|
||||
"enable": "启用",
|
||||
"disable": "停用",
|
||||
"emptyTemplates": "暂无模板,请先上传",
|
||||
"emptyReviews": "暂无审查记录",
|
||||
"total": "共 {n} 条",
|
||||
"loadFailed": "加载失败",
|
||||
"fileRequired": "请选择文件",
|
||||
"uploadOk": "模板上传成功",
|
||||
"uploadFailed": "模板上传失败",
|
||||
"setDefaultOk": "已设为默认模板",
|
||||
"actionFailed": "操作失败",
|
||||
"confirmDelete": "确认删除该模板?",
|
||||
"downloadReport": "下载报告",
|
||||
"downloadAnnotated": "下载标注合同",
|
||||
"downloadFile": "下载文件",
|
||||
"downloadContract": "下载待审合同",
|
||||
"downloadTemplateFile": "下载比对模板",
|
||||
"downloadFailed": "下载失败",
|
||||
"loading": "加载中…",
|
||||
"all": "全部",
|
||||
"search": "搜索",
|
||||
"detail": "详情",
|
||||
"saving": "保存中…",
|
||||
"sourceAll": "全部来源",
|
||||
"keywordPlaceholder": "搜索审查编号、合同编号、供应商、合同名…",
|
||||
"reviewNoPlaceholder": "CR-…",
|
||||
"uploadModalTitle": "上传合同模板",
|
||||
"uploadZonePrefix": "拖拽 Word / PDF 到此处,或 ",
|
||||
"uploadZoneAction": "点击选择文件",
|
||||
"uploadZoneReplace": "点击或拖拽可更换文件",
|
||||
"noFileSelected": "未选择文件",
|
||||
"templateName": "模板名称",
|
||||
"versionNo": "版本号",
|
||||
"defaultNo": "否",
|
||||
"defaultYes": "是(会话默认选中)",
|
||||
"remark": "备注",
|
||||
"remarkPlaceholder": "适用场景、相对上一版变更说明…",
|
||||
"uploadCallout": "上传后会话下拉与「从库中挑选」即时可见(启用状态)。",
|
||||
"saveToLibrary": "保存到模板库",
|
||||
"defaultYesShort": "是",
|
||||
"statusSuccess": "成功",
|
||||
"statusFailed": "失败",
|
||||
"statusRunning": "进行中",
|
||||
"statusPending": "待处理",
|
||||
"confirmDeleteNamed": "确认删除模板「{name} {version}」?",
|
||||
"editModalTitle": "修改合同模板",
|
||||
"saveChanges": "保存修改",
|
||||
"editOk": "模板已更新",
|
||||
"editFileHint": "当前版本不支持在编辑时更换文件;如需换稿请重新上传新版本。",
|
||||
"nameVersionRequired": "请填写模板名称和版本号",
|
||||
"regionConfigAction": "比对区域",
|
||||
"regionConfigTitle": "比对区域配置",
|
||||
"regionConfigHint": "配置只用于划分本次上传的两份合同,不替换我方原合同",
|
||||
"regionMetadata": "抬头基础字段",
|
||||
"regionField_contract_no": "合同号",
|
||||
"regionField_buyer": "买方",
|
||||
"regionField_seller": "卖方",
|
||||
"regionField_version": "版本",
|
||||
"regionBodyStart": "正文起点锚点(每行一个)",
|
||||
"regionBodyEnd": "正文结束锚点(每行一个)",
|
||||
"regionSignatureTerms": "签章辅助关键词(每行一个)",
|
||||
"regionAttachmentStart": "附件标题锚点(每行一个)",
|
||||
"regionAttachmentPolicy": "附件处理策略",
|
||||
"regionPageCountOnly": "仅提示新增或减少页数,不审核附件内容",
|
||||
"regionRestoreV4": "恢复 V4 默认配置",
|
||||
"regionPreview": "识别预览",
|
||||
"regionPreviewing": "识别中…",
|
||||
"regionPreviewRecognized": "正文区域识别成功",
|
||||
"regionPreviewIncomplete": "锚点识别不完整,实际比对将安全回退",
|
||||
"regionPreviewFailed": "区域识别预览失败",
|
||||
"regionSaved": "比对区域配置已保存"
|
||||
}
|
||||
}
|
||||
@@ -725,8 +725,14 @@
|
||||
"管理端需要能导出入职日期、完成日期、部门、姓名、工号和分数。"
|
||||
],
|
||||
"booleanOptions": [
|
||||
{ "id": "true", "label": "正确" },
|
||||
{ "id": "false", "label": "错误" }
|
||||
{
|
||||
"id": "true",
|
||||
"label": "正确"
|
||||
},
|
||||
{
|
||||
"id": "false",
|
||||
"label": "错误"
|
||||
}
|
||||
],
|
||||
"questionBank": [
|
||||
{
|
||||
@@ -736,10 +742,22 @@
|
||||
"answer": "c",
|
||||
"explanation": "根据新人培训试卷答案,工资固定在每月 15 号发放。",
|
||||
"options": [
|
||||
{ "id": "a", "label": "A. 8号" },
|
||||
{ "id": "b", "label": "B. 9号" },
|
||||
{ "id": "c", "label": "C. 15号" },
|
||||
{ "id": "d", "label": "D. 27号" }
|
||||
{
|
||||
"id": "a",
|
||||
"label": "A. 8号"
|
||||
},
|
||||
{
|
||||
"id": "b",
|
||||
"label": "B. 9号"
|
||||
},
|
||||
{
|
||||
"id": "c",
|
||||
"label": "C. 15号"
|
||||
},
|
||||
{
|
||||
"id": "d",
|
||||
"label": "D. 27号"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -749,9 +767,18 @@
|
||||
"answer": "b",
|
||||
"explanation": "公司餐厅订餐使用中米新订餐系统,不是 OA 或 ERP。",
|
||||
"options": [
|
||||
{ "id": "a", "label": "A. OA" },
|
||||
{ "id": "b", "label": "B. 中米新订餐系统" },
|
||||
{ "id": "c", "label": "C. ERP" }
|
||||
{
|
||||
"id": "a",
|
||||
"label": "A. OA"
|
||||
},
|
||||
{
|
||||
"id": "b",
|
||||
"label": "B. 中米新订餐系统"
|
||||
},
|
||||
{
|
||||
"id": "c",
|
||||
"label": "C. ERP"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -761,10 +788,22 @@
|
||||
"answer": "abcd",
|
||||
"explanation": "试卷给出的四个选项都是公司产品范畴,前端以组合选项形式展示为全选。",
|
||||
"options": [
|
||||
{ "id": "abcd", "label": "A/B/C/D 全部都是" },
|
||||
{ "id": "ab", "label": "A/B" },
|
||||
{ "id": "cd", "label": "C/D" },
|
||||
{ "id": "a", "label": "仅 A" }
|
||||
{
|
||||
"id": "abcd",
|
||||
"label": "A/B/C/D 全部都是"
|
||||
},
|
||||
{
|
||||
"id": "ab",
|
||||
"label": "A/B"
|
||||
},
|
||||
{
|
||||
"id": "cd",
|
||||
"label": "C/D"
|
||||
},
|
||||
{
|
||||
"id": "a",
|
||||
"label": "仅 A"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -774,10 +813,22 @@
|
||||
"answer": "c",
|
||||
"explanation": "请假必须发起 OA 请假申请单,不能使用加班申请单或联络单。",
|
||||
"options": [
|
||||
{ "id": "a", "label": "A. 加班申请单" },
|
||||
{ "id": "b", "label": "B. 联络单" },
|
||||
{ "id": "c", "label": "C. 请假申请单" },
|
||||
{ "id": "d", "label": "D. 员工需求单" }
|
||||
{
|
||||
"id": "a",
|
||||
"label": "A. 加班申请单"
|
||||
},
|
||||
{
|
||||
"id": "b",
|
||||
"label": "B. 联络单"
|
||||
},
|
||||
{
|
||||
"id": "c",
|
||||
"label": "C. 请假申请单"
|
||||
},
|
||||
{
|
||||
"id": "d",
|
||||
"label": "D. 员工需求单"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -787,9 +838,18 @@
|
||||
"answer": "a",
|
||||
"explanation": "QC080000 对应有害物质过程管理体系认证标准。",
|
||||
"options": [
|
||||
{ "id": "a", "label": "A. 有害物质过程管理体系认证标准" },
|
||||
{ "id": "b", "label": "B. 职业健康安全管理体系" },
|
||||
{ "id": "c", "label": "C. 环境管理体系" }
|
||||
{
|
||||
"id": "a",
|
||||
"label": "A. 有害物质过程管理体系认证标准"
|
||||
},
|
||||
{
|
||||
"id": "b",
|
||||
"label": "B. 职业健康安全管理体系"
|
||||
},
|
||||
{
|
||||
"id": "c",
|
||||
"label": "C. 环境管理体系"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -799,8 +859,14 @@
|
||||
"answer": "a",
|
||||
"explanation": "5S 标准表述为整理、整顿、清扫、清洁和素养。",
|
||||
"options": [
|
||||
{ "id": "a", "label": "A. 整理、整顿、清扫、清洁和素养" },
|
||||
{ "id": "b", "label": "B. 整理、整顿、打扫、清洁和素养" }
|
||||
{
|
||||
"id": "a",
|
||||
"label": "A. 整理、整顿、清扫、清洁和素养"
|
||||
},
|
||||
{
|
||||
"id": "b",
|
||||
"label": "B. 整理、整顿、打扫、清洁和素养"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -810,8 +876,14 @@
|
||||
"answer": "a",
|
||||
"explanation": "使用灭火器要站在上风口,避免烟雾和火势倒灌。",
|
||||
"options": [
|
||||
{ "id": "a", "label": "A. 上风口" },
|
||||
{ "id": "b", "label": "B. 下风口" }
|
||||
{
|
||||
"id": "a",
|
||||
"label": "A. 上风口"
|
||||
},
|
||||
{
|
||||
"id": "b",
|
||||
"label": "B. 下风口"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -906,5 +978,124 @@
|
||||
"explanation": "产品要求必须同时覆盖法规和客户要求,这是质量体系基础。"
|
||||
}
|
||||
]
|
||||
},
|
||||
"procurementContract": {
|
||||
"modeCompare": "合同比对",
|
||||
"modeSolo": "单份审核",
|
||||
"modeHint": "按当前模式上传合同后发送即可开始审查",
|
||||
"compareHint": "请分别上传我方原合同和卖方回传合同",
|
||||
"selectTemplate": "选择模板",
|
||||
"default": "默认",
|
||||
"uploadTempTemplate": "上传临时模板",
|
||||
"uploadContract": "上传合同",
|
||||
"uploadOriginalContract": "上传我方原合同",
|
||||
"uploadSellerReturnedContract": "上传卖方回传合同",
|
||||
"uploadContractToReview": "上传待审合同",
|
||||
"quickReview": "合同审核",
|
||||
"quickRisk": "风险提示",
|
||||
"quickDiff": "模板差异",
|
||||
"quickSuggestion": "修改建议",
|
||||
"promptReview": "请审核这份采购合同,按高、中、低风险输出主要问题和结论。",
|
||||
"promptRisk": "请重点识别这份合同中的法律风险、付款风险、交付风险和违约责任风险。",
|
||||
"promptDiff": "请对比我方原合同与卖方回传合同,列出修改、删除、新增的关键条款和对应风险。",
|
||||
"promptSuggestion": "请基于审查结果给出可直接用于商务谈判的修改建议。",
|
||||
"llmEnhanced": "AI 增强",
|
||||
"tempTemplateChip": "临时模板:{name}",
|
||||
"originalContractChip": "我方原合同:{name}",
|
||||
"sellerReturnedContractLabel": "卖方回传合同",
|
||||
"contractToReviewLabel": "待审合同",
|
||||
"soloHint": "单份审核 · 无模板",
|
||||
"tempTemplateUploaded": "临时模板已上传(仅本会话有效)",
|
||||
"originalContractUploaded": "我方原合同已上传",
|
||||
"uploadFailed": "上传失败",
|
||||
"oneContractOnly": "卖方回传合同每次只能上传一份,请移除多余文件",
|
||||
"compareFilesRequired": "合同比对需要同时上传我方原合同和卖方回传合同",
|
||||
"defaultUserQuery": "请对《{file}》进行{mode}",
|
||||
"reviewFailed": "审查失败",
|
||||
"resultTitle": "采购合同审查结果",
|
||||
"completed": "审查完成",
|
||||
"counterpartyContract": "对方合同",
|
||||
"contractNo": "合同编号",
|
||||
"supplier": "供应商",
|
||||
"riskItems": "项",
|
||||
"changesUnchanged": "未改动",
|
||||
"changesCount": "改动项",
|
||||
"reviewNo": "审查编号",
|
||||
"mode": "模式",
|
||||
"status": "状态",
|
||||
"riskSummary": "风险摘要",
|
||||
"containsHighRisk": "含高风险 {count} 项",
|
||||
"noHighRisk": "无高风险",
|
||||
"sourceLibrary": "模板库",
|
||||
"sourceUpload": "用户上传",
|
||||
"template": "模板",
|
||||
"comparisonBaseline": "我方原合同",
|
||||
"downloadReport": "下载审查报告",
|
||||
"downloadDifferenceReport": "下载差异报告",
|
||||
"downloadAnnotated": "下载标注合同",
|
||||
"downloadAnnotatedOk": "标注合同已开始下载",
|
||||
"downloadAnnotatedFailed": "标注合同下载失败",
|
||||
"anchorPage": "原文第 {page} 页",
|
||||
"downloading": "下载中…",
|
||||
"downloadOk": "报告已开始下载",
|
||||
"downloadFailed": "下载失败",
|
||||
"riskHigh": "高风险",
|
||||
"riskMedium": "中风险",
|
||||
"riskLow": "低风险",
|
||||
"riskShortHigh": "高",
|
||||
"riskShortMedium": "中",
|
||||
"riskShortLow": "低",
|
||||
"riskOk": "通过",
|
||||
"riskNoFinding": "未发现风险",
|
||||
"changeInsert": "新增",
|
||||
"changeDelete": "删除",
|
||||
"changeModify": "修改",
|
||||
"changePass": "已覆盖",
|
||||
"changeMissing": "缺失",
|
||||
"colClause": "条款",
|
||||
"colChange": "类型",
|
||||
"colRisk": "风险",
|
||||
"colTemplateText": "模板原文",
|
||||
"colContractText": "对方合同",
|
||||
"colDetail": "说明",
|
||||
"colComparison": "变更对照",
|
||||
"unreadableComparison": "原始 PDF 文本编码不兼容,无法可靠显示变更内容;请上传 Word 文件或可检索文本的 PDF。",
|
||||
"noComparisonText": "暂无可展示的条款对照",
|
||||
"noClauses": "未检测到条款差异或红线缺项。",
|
||||
"statusSuccess": "成功",
|
||||
"statusFailed": "失败",
|
||||
"statusRunning": "进行中",
|
||||
"reviewQueued": "审核任务已提交,正在排队",
|
||||
"reviewRunning": "合同审核进行中",
|
||||
"stepQueued": "等待审核",
|
||||
"stepExtracting": "提取清洗",
|
||||
"stepStructuring": "条款识别",
|
||||
"stepComparing": "合同比对与红线",
|
||||
"stepRiskScanning": "风险规则扫描",
|
||||
"stepAiReviewing": "AI 全面审核",
|
||||
"stepValidating": "结果校验合并",
|
||||
"stepCompleted": "审核完成",
|
||||
"changeRuleScan": "红线扫描",
|
||||
"changePolicyScan": "采购红线",
|
||||
"changeLlmScan": "AI发现",
|
||||
"changeOcrUncertain": "待确认",
|
||||
"sectionChanges": "合同改动项",
|
||||
"sectionIndependentRisks": "独立风险项",
|
||||
"sectionConfirmations": "待确认项",
|
||||
"colEvidence": "命中原文",
|
||||
"colSuggestion": "修改建议",
|
||||
"confirmationsHidden": "另有 {count} 条 OCR/抽取待确认项未展开,请查看原文或标注合同。",
|
||||
"confirmationsSummary": "有 {count} 条内容受 OCR/抽取噪声影响,需要查看原文确认。",
|
||||
"sectionLegalRisk": "法律与履约风险",
|
||||
"sectionCommercial": "商业待确认",
|
||||
"sectionFormatMetadata": "格式与信息变化",
|
||||
"changeClassCommercial": "商业变化",
|
||||
"changeClassMetadata": "信息变化",
|
||||
"changeClassFormat": "格式变化",
|
||||
"needsReview": "待确认",
|
||||
"regionFallback": "比对区域配置未生效,本次已安全回退为全文比对。",
|
||||
"attachmentAdded": "回传合同新增附件 {count} 页",
|
||||
"attachmentRemoved": "回传合同减少附件 {count} 页",
|
||||
"attachmentContentIgnored": "附件内容未列入差异"
|
||||
}
|
||||
}
|
||||
@@ -45,6 +45,9 @@
|
||||
"FILE_ASSET_SIZE_EXCEEDED": "文件大小超过限制。",
|
||||
"FILE_ASSET_EXPIRED": "文件资产已过期。",
|
||||
"FILE_ASSET_ALREADY_REFERENCED": "文件已被业务引用,无法删除。",
|
||||
"PROCUREMENT_CONTRACT_TEMPLATE_REFERENCED": "模板已被审查历史引用,无法删除;请停用该模板。",
|
||||
"PROCUREMENT_CONTRACT_INVALID_COMPARISON_REGION_CONFIG": "比对区域配置无效,请检查字段、锚点和附件策略。",
|
||||
"PROCUREMENT_CONTRACT_COMPARISON_REGION_PREVIEW_FAILED": "无法从模板文件中识别比对区域。",
|
||||
"FILE_ASSET_INVALID_STATUS": "文件状态不允许该操作。",
|
||||
"SHIPPING_NOTICE_INTAKE_NOT_FOUND": "发货通知接入记录不存在。",
|
||||
"SHIPPING_NOTICE_INTAKE_PARSE_PENDING": "发货通知仍在解析中,请稍后再确认建单。",
|
||||
|
||||
@@ -26,7 +26,9 @@
|
||||
"permissions": "應用權限",
|
||||
"requests": "權限審批",
|
||||
"reports": "數據報表",
|
||||
"schedules": "排程管理"
|
||||
"schedules": "排程管理",
|
||||
"platformApps": "平台應用說明",
|
||||
"procurementContract": "採購合同審查"
|
||||
},
|
||||
"platformApps": {
|
||||
"guideUsage": "資料用途",
|
||||
@@ -1162,5 +1164,153 @@
|
||||
"batchPermissionUpdateFailed": "批量權限更新失敗",
|
||||
"enterOneField": "請至少輸入一個要更新的字段",
|
||||
"batchDeleteResult": "已刪除 {count} 位用戶。"
|
||||
},
|
||||
"procurementContract": {
|
||||
"title": "採購合同審查",
|
||||
"subtitle": "維護標準合同模板、風險紅線規則並查看審查歷史",
|
||||
"tabTemplates": "模板庫",
|
||||
"tabRules": "風險規則",
|
||||
"tabReviews": "審查歷史",
|
||||
"addRule": "新增規則",
|
||||
"rulesHint": "內建規則採購組合判斷;自訂規則僅按關鍵詞比對。請使用標準條款分類。",
|
||||
"ruleStatTotal": "目前規則",
|
||||
"ruleStatEnabled": "已啟用",
|
||||
"ruleStatHighRisk": "高風險",
|
||||
"emptyRules": "暫無風險規則",
|
||||
"ruleCreateTitle": "新增風險規則",
|
||||
"ruleEditTitle": "編輯風險規則",
|
||||
"ruleCreateOk": "規則已建立",
|
||||
"ruleEditOk": "規則已更新",
|
||||
"ruleRequiredFields": "請填寫標題、分類、風險說明與建議",
|
||||
"ruleKeywordsRequired": "請填寫至少一個關鍵詞",
|
||||
"ruleCodePlaceholder": "儲存後由系統產生",
|
||||
"ruleCodeGeneratedHint": "自訂規則儲存後由系統產生內部編碼。",
|
||||
"ruleCodeReadonlyHint": "編碼是規則的內部識別,無法修改。",
|
||||
"builtinRuleLogicHint": "這是內建採購規則,系統依組合業務條件判斷;分類、關鍵詞和觸發條件固定,不依一般關鍵詞規則判斷。",
|
||||
"ruleKeywordsPlaceholder": "多個關鍵詞用逗號分隔,如:付款,驗收,發票",
|
||||
"keywordPresentLogicHint": "符合任一關鍵詞即觸發風險。",
|
||||
"keywordMissingLogicHint": "所有關鍵詞均未出現時才觸發風險;組合條件請使用內建規則。",
|
||||
"category_payment": "付款",
|
||||
"category_delivery": "交付/交期",
|
||||
"category_acceptance": "驗收",
|
||||
"category_warranty": "保固/售後",
|
||||
"category_liability": "違約與責任",
|
||||
"category_jurisdiction": "管轄地",
|
||||
"category_dispute": "爭議解決",
|
||||
"category_ip": "智慧財產權",
|
||||
"category_other": "其他",
|
||||
"confirmDeleteRule": "確認刪除規則「{title}」?刪除後審查將不再使用該條紅線。",
|
||||
"colRuleCode": "編碼",
|
||||
"colRuleTitle": "標題",
|
||||
"colCategory": "條款分類",
|
||||
"colKeywords": "關鍵詞",
|
||||
"colTrigger": "觸發條件",
|
||||
"colSort": "排序",
|
||||
"ruleSortHint": "數值越小,規則執行優先級越高;同一份合約依排序由小到大依序檢查。",
|
||||
"colContractType": "合同類型",
|
||||
"colRiskHint": "風險說明",
|
||||
"colSuggestion": "修改建議",
|
||||
"colNegotiation": "談判話術",
|
||||
"triggerMissing": "關鍵詞缺失時觸發",
|
||||
"triggerPresent": "關鍵詞出現時觸發",
|
||||
"riskHigh": "高風險",
|
||||
"riskMedium": "中風險",
|
||||
"riskLow": "低風險",
|
||||
"uploadTemplate": "上傳模板",
|
||||
"colName": "名稱",
|
||||
"colVersion": "版本",
|
||||
"colFile": "檔案",
|
||||
"colStatus": "狀態",
|
||||
"colDefault": "預設",
|
||||
"colActions": "操作",
|
||||
"colMode": "模式",
|
||||
"colSource": "模板來源",
|
||||
"colReviewNo": "審查編號",
|
||||
"colContract": "待審合同",
|
||||
"colContractNo": "合同編號",
|
||||
"colSupplier": "供應商",
|
||||
"colTemplate": "比對模板",
|
||||
"colUser": "發起人",
|
||||
"colFinishedAt": "完成時間",
|
||||
"colRisk": "風險",
|
||||
"keyword": "關鍵詞",
|
||||
"modeCompare": "模板比對",
|
||||
"modeSolo": "單份審核",
|
||||
"sourceLibrary": "模板庫",
|
||||
"sourceUpload": "用戶上傳",
|
||||
"sourceNone": "無",
|
||||
"setDefault": "設為預設",
|
||||
"setAsDefault": "設為預設模板",
|
||||
"enable": "啟用",
|
||||
"disable": "停用",
|
||||
"emptyTemplates": "暫無模板,請先上傳",
|
||||
"emptyReviews": "暫無審查記錄",
|
||||
"total": "共 {n} 條",
|
||||
"loadFailed": "載入失敗",
|
||||
"fileRequired": "請選擇檔案",
|
||||
"uploadOk": "模板上傳成功",
|
||||
"uploadFailed": "模板上傳失敗",
|
||||
"setDefaultOk": "已設為預設模板",
|
||||
"actionFailed": "操作失敗",
|
||||
"confirmDelete": "確認刪除該模板?",
|
||||
"downloadReport": "下載報告",
|
||||
"downloadAnnotated": "下載標註合同",
|
||||
"downloadFile": "下載檔案",
|
||||
"downloadContract": "下載待審合同",
|
||||
"downloadTemplateFile": "下載比對模板",
|
||||
"downloadFailed": "下載失敗",
|
||||
"loading": "載入中…",
|
||||
"all": "全部",
|
||||
"search": "搜尋",
|
||||
"detail": "詳情",
|
||||
"saving": "儲存中…",
|
||||
"sourceAll": "全部來源",
|
||||
"keywordPlaceholder": "搜尋審查編號、合同編號、供應商、合同名…",
|
||||
"reviewNoPlaceholder": "CR-…",
|
||||
"uploadModalTitle": "上傳合同模板",
|
||||
"uploadZonePrefix": "拖曳 Word / PDF 到此處,或 ",
|
||||
"uploadZoneAction": "點擊選擇檔案",
|
||||
"uploadZoneReplace": "點擊或拖曳可更換檔案",
|
||||
"noFileSelected": "未選擇檔案",
|
||||
"templateName": "模板名稱",
|
||||
"versionNo": "版本號",
|
||||
"defaultNo": "否",
|
||||
"defaultYes": "是(會話預設選中)",
|
||||
"remark": "備註",
|
||||
"remarkPlaceholder": "適用場景、相對上一版變更說明…",
|
||||
"uploadCallout": "上傳後會話下拉與「從庫中挑選」即時可見(啟用狀態)。",
|
||||
"saveToLibrary": "儲存到模板庫",
|
||||
"defaultYesShort": "是",
|
||||
"statusSuccess": "成功",
|
||||
"statusFailed": "失敗",
|
||||
"statusRunning": "進行中",
|
||||
"statusPending": "待處理",
|
||||
"confirmDeleteNamed": "確認刪除模板「{name} {version}」?",
|
||||
"editModalTitle": "修改合同模板",
|
||||
"saveChanges": "儲存修改",
|
||||
"editOk": "模板已更新",
|
||||
"editFileHint": "目前版本不支援在編輯時更換檔案;如需換稿請重新上傳新版本。",
|
||||
"nameVersionRequired": "請填寫模板名稱和版本號",
|
||||
"regionConfigAction": "比對區域",
|
||||
"regionConfigTitle": "比對區域設定",
|
||||
"regionConfigHint": "設定只用於劃分本次上傳的兩份合約,不替換我方原合約",
|
||||
"regionMetadata": "抬頭基礎欄位",
|
||||
"regionField_contract_no": "合約號",
|
||||
"regionField_buyer": "買方",
|
||||
"regionField_seller": "賣方",
|
||||
"regionField_version": "版本",
|
||||
"regionBodyStart": "正文起點錨點(每行一個)",
|
||||
"regionBodyEnd": "正文結束錨點(每行一個)",
|
||||
"regionSignatureTerms": "簽章輔助關鍵字(每行一個)",
|
||||
"regionAttachmentStart": "附件標題錨點(每行一個)",
|
||||
"regionAttachmentPolicy": "附件處理策略",
|
||||
"regionPageCountOnly": "僅提示新增或減少頁數,不審核附件內容",
|
||||
"regionRestoreV4": "恢復 V4 預設設定",
|
||||
"regionPreview": "識別預覽",
|
||||
"regionPreviewing": "識別中…",
|
||||
"regionPreviewRecognized": "正文區域識別成功",
|
||||
"regionPreviewIncomplete": "錨點識別不完整,實際比對將安全回退",
|
||||
"regionPreviewFailed": "區域識別預覽失敗",
|
||||
"regionSaved": "比對區域設定已儲存"
|
||||
}
|
||||
}
|
||||
@@ -725,8 +725,14 @@
|
||||
"管理端需要能匯出入職日期、完成日期、部門、姓名、工號和分數。"
|
||||
],
|
||||
"booleanOptions": [
|
||||
{ "id": "true", "label": "正確" },
|
||||
{ "id": "false", "label": "錯誤" }
|
||||
{
|
||||
"id": "true",
|
||||
"label": "正確"
|
||||
},
|
||||
{
|
||||
"id": "false",
|
||||
"label": "錯誤"
|
||||
}
|
||||
],
|
||||
"questionBank": [
|
||||
{
|
||||
@@ -736,10 +742,22 @@
|
||||
"answer": "c",
|
||||
"explanation": "根據新人培訓試卷,工資固定在每月 15 號發放。",
|
||||
"options": [
|
||||
{ "id": "a", "label": "A. 8號" },
|
||||
{ "id": "b", "label": "B. 9號" },
|
||||
{ "id": "c", "label": "C. 15號" },
|
||||
{ "id": "d", "label": "D. 27號" }
|
||||
{
|
||||
"id": "a",
|
||||
"label": "A. 8號"
|
||||
},
|
||||
{
|
||||
"id": "b",
|
||||
"label": "B. 9號"
|
||||
},
|
||||
{
|
||||
"id": "c",
|
||||
"label": "C. 15號"
|
||||
},
|
||||
{
|
||||
"id": "d",
|
||||
"label": "D. 27號"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -749,9 +767,18 @@
|
||||
"answer": "b",
|
||||
"explanation": "公司餐廳訂餐使用中米新訂餐系統,不是 OA 或 ERP。",
|
||||
"options": [
|
||||
{ "id": "a", "label": "A. OA" },
|
||||
{ "id": "b", "label": "B. 中米新訂餐系統" },
|
||||
{ "id": "c", "label": "C. ERP" }
|
||||
{
|
||||
"id": "a",
|
||||
"label": "A. OA"
|
||||
},
|
||||
{
|
||||
"id": "b",
|
||||
"label": "B. 中米新訂餐系統"
|
||||
},
|
||||
{
|
||||
"id": "c",
|
||||
"label": "C. ERP"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -761,10 +788,22 @@
|
||||
"answer": "abcd",
|
||||
"explanation": "試卷給出的四個選項都屬於公司產品範疇,前端以組合選項呈現為全選。",
|
||||
"options": [
|
||||
{ "id": "abcd", "label": "A/B/C/D 全部都是" },
|
||||
{ "id": "ab", "label": "A/B" },
|
||||
{ "id": "cd", "label": "C/D" },
|
||||
{ "id": "a", "label": "僅 A" }
|
||||
{
|
||||
"id": "abcd",
|
||||
"label": "A/B/C/D 全部都是"
|
||||
},
|
||||
{
|
||||
"id": "ab",
|
||||
"label": "A/B"
|
||||
},
|
||||
{
|
||||
"id": "cd",
|
||||
"label": "C/D"
|
||||
},
|
||||
{
|
||||
"id": "a",
|
||||
"label": "僅 A"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -774,10 +813,22 @@
|
||||
"answer": "c",
|
||||
"explanation": "請假必須發起 OA 請假申請單,不能使用加班申請單或聯絡單。",
|
||||
"options": [
|
||||
{ "id": "a", "label": "A. 加班申請單" },
|
||||
{ "id": "b", "label": "B. 聯絡單" },
|
||||
{ "id": "c", "label": "C. 請假申請單" },
|
||||
{ "id": "d", "label": "D. 員工需求單" }
|
||||
{
|
||||
"id": "a",
|
||||
"label": "A. 加班申請單"
|
||||
},
|
||||
{
|
||||
"id": "b",
|
||||
"label": "B. 聯絡單"
|
||||
},
|
||||
{
|
||||
"id": "c",
|
||||
"label": "C. 請假申請單"
|
||||
},
|
||||
{
|
||||
"id": "d",
|
||||
"label": "D. 員工需求單"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -787,9 +838,18 @@
|
||||
"answer": "a",
|
||||
"explanation": "QC080000 對應有害物質過程管理體系認證標準。",
|
||||
"options": [
|
||||
{ "id": "a", "label": "A. 有害物質過程管理體系認證標準" },
|
||||
{ "id": "b", "label": "B. 職業健康安全管理體系" },
|
||||
{ "id": "c", "label": "C. 環境管理體系" }
|
||||
{
|
||||
"id": "a",
|
||||
"label": "A. 有害物質過程管理體系認證標準"
|
||||
},
|
||||
{
|
||||
"id": "b",
|
||||
"label": "B. 職業健康安全管理體系"
|
||||
},
|
||||
{
|
||||
"id": "c",
|
||||
"label": "C. 環境管理體系"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -799,8 +859,14 @@
|
||||
"answer": "a",
|
||||
"explanation": "5S 標準表述為整理、整頓、清掃、清潔和素養。",
|
||||
"options": [
|
||||
{ "id": "a", "label": "A. 整理、整頓、清掃、清潔和素養" },
|
||||
{ "id": "b", "label": "B. 整理、整頓、打掃、清潔和素養" }
|
||||
{
|
||||
"id": "a",
|
||||
"label": "A. 整理、整頓、清掃、清潔和素養"
|
||||
},
|
||||
{
|
||||
"id": "b",
|
||||
"label": "B. 整理、整頓、打掃、清潔和素養"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -810,23 +876,226 @@
|
||||
"answer": "a",
|
||||
"explanation": "使用滅火器要站在上風口,避免煙霧與火勢倒灌。",
|
||||
"options": [
|
||||
{ "id": "a", "label": "A. 上風口" },
|
||||
{ "id": "b", "label": "B. 下風口" }
|
||||
{
|
||||
"id": "a",
|
||||
"label": "A. 上風口"
|
||||
},
|
||||
{
|
||||
"id": "b",
|
||||
"label": "B. 下風口"
|
||||
}
|
||||
]
|
||||
},
|
||||
{ "id": "q8", "type": "boolean", "prompt": "正常出勤必須打卡,加班需要提前申請提報。", "answer": "true", "explanation": "出勤與加班都需要遵循公司考勤制度。" },
|
||||
{ "id": "q9", "type": "boolean", "prompt": "忘記刷卡需要 OA 開補刷卡單。", "answer": "true", "explanation": "漏打卡需要透過 OA 補刷卡流程修正考勤記錄。" },
|
||||
{ "id": "q10", "type": "boolean", "prompt": "每月工資從上月 21 日至本月 20 日為止計算。", "answer": "true", "explanation": "試卷中明確了工資核算週期的起止時間。" },
|
||||
{ "id": "q11", "type": "boolean", "prompt": "餐廳用餐需提前預定,可以直接刷臉用餐。", "answer": "true", "explanation": "公司餐廳支援提前預定並刷臉用餐。" },
|
||||
{ "id": "q12", "type": "boolean", "prompt": "發生火災、爆炸事故時,應立即撥打 119。", "answer": "true", "explanation": "火災事故首先要聯絡消防,119 是基本應急要求。" },
|
||||
{ "id": "q13", "type": "boolean", "prompt": "住宿人員應保持高度防火意識,不准私拉亂接電線和使用高功率電器。", "answer": "true", "explanation": "宿舍防火是紅線要求,私拉電線和使用大功率電器都被禁止。" },
|
||||
{ "id": "q14", "type": "boolean", "prompt": "遵守安全生產規章制度是從業人員應履行的安全生產義務。", "answer": "true", "explanation": "安全制度不僅是要求,也是員工必須履行的義務。" },
|
||||
{ "id": "q15", "type": "boolean", "prompt": "工牌可以隨意借由他人使用。", "answer": "false", "explanation": "工牌屬於個人身份憑證,嚴禁外借。" },
|
||||
{ "id": "q16", "type": "boolean", "prompt": "RoHS 主要用於規範電子電氣產品的材料及工藝標準,使之更加有利於人體健康及環境保護。", "answer": "true", "explanation": "RoHS 的核心目標就是限制有害物質、降低環境與人體風險。" },
|
||||
{ "id": "q17", "type": "boolean", "prompt": "我們公司的 HSF 方針是:綠色設計,環保採購;節約資源,綠色產出。", "answer": "true", "explanation": "這是試卷給出的公司 HSF 方針原文。" },
|
||||
{ "id": "q18", "type": "boolean", "prompt": "EHS(Environment、Health、Safety)指環境健康安全。", "answer": "true", "explanation": "EHS 是環境、健康、安全三個維度的統一簡稱。" },
|
||||
{ "id": "q19", "type": "boolean", "prompt": "對於外來文件,組織不需對其進行控制與管理。", "answer": "false", "explanation": "外來文件同樣需要受控管理,確保版本與使用正確。" },
|
||||
{ "id": "q20", "type": "boolean", "prompt": "與產品有關的要求應包括有關法律法規規定的要求及顧客的要求等。", "answer": "true", "explanation": "產品要求必須同時覆蓋法規和客戶要求,這是品質體系基礎。" }
|
||||
{
|
||||
"id": "q8",
|
||||
"type": "boolean",
|
||||
"prompt": "正常出勤必須打卡,加班需要提前申請提報。",
|
||||
"answer": "true",
|
||||
"explanation": "出勤與加班都需要遵循公司考勤制度。"
|
||||
},
|
||||
{
|
||||
"id": "q9",
|
||||
"type": "boolean",
|
||||
"prompt": "忘記刷卡需要 OA 開補刷卡單。",
|
||||
"answer": "true",
|
||||
"explanation": "漏打卡需要透過 OA 補刷卡流程修正考勤記錄。"
|
||||
},
|
||||
{
|
||||
"id": "q10",
|
||||
"type": "boolean",
|
||||
"prompt": "每月工資從上月 21 日至本月 20 日為止計算。",
|
||||
"answer": "true",
|
||||
"explanation": "試卷中明確了工資核算週期的起止時間。"
|
||||
},
|
||||
{
|
||||
"id": "q11",
|
||||
"type": "boolean",
|
||||
"prompt": "餐廳用餐需提前預定,可以直接刷臉用餐。",
|
||||
"answer": "true",
|
||||
"explanation": "公司餐廳支援提前預定並刷臉用餐。"
|
||||
},
|
||||
{
|
||||
"id": "q12",
|
||||
"type": "boolean",
|
||||
"prompt": "發生火災、爆炸事故時,應立即撥打 119。",
|
||||
"answer": "true",
|
||||
"explanation": "火災事故首先要聯絡消防,119 是基本應急要求。"
|
||||
},
|
||||
{
|
||||
"id": "q13",
|
||||
"type": "boolean",
|
||||
"prompt": "住宿人員應保持高度防火意識,不准私拉亂接電線和使用高功率電器。",
|
||||
"answer": "true",
|
||||
"explanation": "宿舍防火是紅線要求,私拉電線和使用大功率電器都被禁止。"
|
||||
},
|
||||
{
|
||||
"id": "q14",
|
||||
"type": "boolean",
|
||||
"prompt": "遵守安全生產規章制度是從業人員應履行的安全生產義務。",
|
||||
"answer": "true",
|
||||
"explanation": "安全制度不僅是要求,也是員工必須履行的義務。"
|
||||
},
|
||||
{
|
||||
"id": "q15",
|
||||
"type": "boolean",
|
||||
"prompt": "工牌可以隨意借由他人使用。",
|
||||
"answer": "false",
|
||||
"explanation": "工牌屬於個人身份憑證,嚴禁外借。"
|
||||
},
|
||||
{
|
||||
"id": "q16",
|
||||
"type": "boolean",
|
||||
"prompt": "RoHS 主要用於規範電子電氣產品的材料及工藝標準,使之更加有利於人體健康及環境保護。",
|
||||
"answer": "true",
|
||||
"explanation": "RoHS 的核心目標就是限制有害物質、降低環境與人體風險。"
|
||||
},
|
||||
{
|
||||
"id": "q17",
|
||||
"type": "boolean",
|
||||
"prompt": "我們公司的 HSF 方針是:綠色設計,環保採購;節約資源,綠色產出。",
|
||||
"answer": "true",
|
||||
"explanation": "這是試卷給出的公司 HSF 方針原文。"
|
||||
},
|
||||
{
|
||||
"id": "q18",
|
||||
"type": "boolean",
|
||||
"prompt": "EHS(Environment、Health、Safety)指環境健康安全。",
|
||||
"answer": "true",
|
||||
"explanation": "EHS 是環境、健康、安全三個維度的統一簡稱。"
|
||||
},
|
||||
{
|
||||
"id": "q19",
|
||||
"type": "boolean",
|
||||
"prompt": "對於外來文件,組織不需對其進行控制與管理。",
|
||||
"answer": "false",
|
||||
"explanation": "外來文件同樣需要受控管理,確保版本與使用正確。"
|
||||
},
|
||||
{
|
||||
"id": "q20",
|
||||
"type": "boolean",
|
||||
"prompt": "與產品有關的要求應包括有關法律法規規定的要求及顧客的要求等。",
|
||||
"answer": "true",
|
||||
"explanation": "產品要求必須同時覆蓋法規和客戶要求,這是品質體系基礎。"
|
||||
}
|
||||
]
|
||||
},
|
||||
"procurementContract": {
|
||||
"modeCompare": "合同比對",
|
||||
"modeSolo": "單份審核",
|
||||
"modeHint": "按目前模式上傳合同後發送即可開始審查",
|
||||
"compareHint": "請分別上傳我方原合同和賣方回傳合同",
|
||||
"selectTemplate": "選擇模板",
|
||||
"default": "預設",
|
||||
"uploadTempTemplate": "上傳臨時模板",
|
||||
"uploadContract": "上傳合約",
|
||||
"uploadOriginalContract": "上傳我方原合同",
|
||||
"uploadSellerReturnedContract": "上傳賣方回傳合同",
|
||||
"uploadContractToReview": "上傳待審合同",
|
||||
"quickReview": "合約審核",
|
||||
"quickRisk": "風險提示",
|
||||
"quickDiff": "模板差異",
|
||||
"quickSuggestion": "修改建議",
|
||||
"promptReview": "請審核這份採購合約,按高、中、低風險輸出主要問題和結論。",
|
||||
"promptRisk": "請重點識別這份合約中的法律風險、付款風險、交付風險和違約責任風險。",
|
||||
"promptDiff": "請對比我方原合同與賣方回傳合同,列出修改、刪除、新增的關鍵條款和對應風險。",
|
||||
"promptSuggestion": "請基於審查結果給出可直接用於商務談判的修改建議。",
|
||||
"llmEnhanced": "AI 增強",
|
||||
"tempTemplateChip": "臨時模板:{name}",
|
||||
"originalContractChip": "我方原合同:{name}",
|
||||
"sellerReturnedContractLabel": "賣方回傳合同",
|
||||
"contractToReviewLabel": "待審合同",
|
||||
"soloHint": "單份審核 · 無模板",
|
||||
"tempTemplateUploaded": "臨時模板已上傳(僅本會話有效)",
|
||||
"originalContractUploaded": "我方原合同已上傳",
|
||||
"uploadFailed": "上傳失敗",
|
||||
"oneContractOnly": "賣方回傳合同每次只能上傳一份,請移除多餘文件",
|
||||
"compareFilesRequired": "合同比對需要同時上傳我方原合同和賣方回傳合同",
|
||||
"defaultUserQuery": "請對《{file}》進行{mode}",
|
||||
"reviewFailed": "審查失敗",
|
||||
"resultTitle": "採購合同審查結果",
|
||||
"completed": "審查完成",
|
||||
"counterpartyContract": "對方合同",
|
||||
"contractNo": "合同編號",
|
||||
"supplier": "供應商",
|
||||
"riskItems": "項",
|
||||
"changesUnchanged": "未改動",
|
||||
"changesCount": "改動項",
|
||||
"reviewNo": "審查編號",
|
||||
"mode": "模式",
|
||||
"status": "狀態",
|
||||
"riskSummary": "風險摘要",
|
||||
"containsHighRisk": "含高風險 {count} 項",
|
||||
"noHighRisk": "無高風險",
|
||||
"sourceLibrary": "模板庫",
|
||||
"sourceUpload": "使用者上傳",
|
||||
"template": "模板",
|
||||
"comparisonBaseline": "我方原合同",
|
||||
"downloadReport": "下載審查報告",
|
||||
"downloadDifferenceReport": "下載差異報告",
|
||||
"downloadAnnotated": "下載標註合同",
|
||||
"downloadAnnotatedOk": "標註合同已開始下載",
|
||||
"downloadAnnotatedFailed": "標註合同下載失敗",
|
||||
"anchorPage": "原文第 {page} 頁",
|
||||
"downloading": "下載中…",
|
||||
"downloadOk": "報告已開始下載",
|
||||
"downloadFailed": "下載失敗",
|
||||
"riskHigh": "高風險",
|
||||
"riskMedium": "中風險",
|
||||
"riskLow": "低風險",
|
||||
"riskShortHigh": "高",
|
||||
"riskShortMedium": "中",
|
||||
"riskShortLow": "低",
|
||||
"riskOk": "通過",
|
||||
"riskNoFinding": "未發現風險",
|
||||
"changeInsert": "新增",
|
||||
"changeDelete": "刪除",
|
||||
"changeModify": "修改",
|
||||
"changePass": "已覆蓋",
|
||||
"changeMissing": "缺失",
|
||||
"colClause": "條款",
|
||||
"colChange": "類型",
|
||||
"colRisk": "風險",
|
||||
"colTemplateText": "模板原文",
|
||||
"colContractText": "對方合同",
|
||||
"colDetail": "說明",
|
||||
"colComparison": "變更對照",
|
||||
"unreadableComparison": "原始 PDF 文字編碼不相容,無法可靠顯示變更內容;請上傳 Word 檔或可搜尋文字的 PDF。",
|
||||
"noComparisonText": "暫無可顯示的條款對照",
|
||||
"noClauses": "未檢測到條款差異或紅線缺項。",
|
||||
"statusSuccess": "成功",
|
||||
"statusFailed": "失敗",
|
||||
"statusRunning": "進行中",
|
||||
"reviewQueued": "審核任務已提交,正在排隊",
|
||||
"reviewRunning": "合約審核進行中",
|
||||
"stepQueued": "等待審核",
|
||||
"stepExtracting": "提取清洗",
|
||||
"stepStructuring": "條款識別",
|
||||
"stepComparing": "合同比對與紅線",
|
||||
"stepRiskScanning": "風險規則掃描",
|
||||
"stepAiReviewing": "AI 全面審核",
|
||||
"stepValidating": "結果校驗合併",
|
||||
"stepCompleted": "審核完成",
|
||||
"changeRuleScan": "紅線掃描",
|
||||
"changePolicyScan": "採購紅線",
|
||||
"changeLlmScan": "AI發現",
|
||||
"changeOcrUncertain": "待確認",
|
||||
"sectionChanges": "合同改動項",
|
||||
"sectionIndependentRisks": "獨立風險項",
|
||||
"sectionConfirmations": "待確認項",
|
||||
"colEvidence": "命中原文",
|
||||
"colSuggestion": "修改建議",
|
||||
"confirmationsHidden": "另有 {count} 條 OCR/抽取待確認項未展開,請查看原文或標註合同。",
|
||||
"confirmationsSummary": "有 {count} 條內容受 OCR/抽取雜訊影響,需要查看原文確認。",
|
||||
"sectionLegalRisk": "法律與履約風險",
|
||||
"sectionCommercial": "商業待確認",
|
||||
"sectionFormatMetadata": "格式與資訊變化",
|
||||
"changeClassCommercial": "商業變化",
|
||||
"changeClassMetadata": "資訊變化",
|
||||
"changeClassFormat": "格式變化",
|
||||
"needsReview": "待確認",
|
||||
"regionFallback": "比對區域設定未生效,本次已安全回退為全文比對。",
|
||||
"attachmentAdded": "回傳合約新增附件 {count} 頁",
|
||||
"attachmentRemoved": "回傳合約減少附件 {count} 頁",
|
||||
"attachmentContentIgnored": "附件內容未列入差異"
|
||||
}
|
||||
}
|
||||
@@ -45,6 +45,9 @@
|
||||
"FILE_ASSET_SIZE_EXCEEDED": "檔案大小超過限制。",
|
||||
"FILE_ASSET_EXPIRED": "檔案資產已過期。",
|
||||
"FILE_ASSET_ALREADY_REFERENCED": "檔案已被業務引用,無法刪除。",
|
||||
"PROCUREMENT_CONTRACT_TEMPLATE_REFERENCED": "範本已被審查歷史引用,無法刪除;請停用該範本。",
|
||||
"PROCUREMENT_CONTRACT_INVALID_COMPARISON_REGION_CONFIG": "比對區域設定無效,請檢查欄位、錨點與附件策略。",
|
||||
"PROCUREMENT_CONTRACT_COMPARISON_REGION_PREVIEW_FAILED": "無法從範本檔案識別比對區域。",
|
||||
"FILE_ASSET_INVALID_STATUS": "檔案狀態不允許此操作。",
|
||||
"SHIPPING_NOTICE_INTAKE_NOT_FOUND": "發貨通知接入記錄不存在。",
|
||||
"SHIPPING_NOTICE_INTAKE_PARSE_PENDING": "發貨通知仍在解析中,請稍後再確認建單。",
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
export const AGENT_CODE_GENERIC = 'generic';
|
||||
export const AGENT_CODE_SHIPPING_NOTICE = 'shipping_notice';
|
||||
export const AGENT_CODE_FILE_CHECK = 'file_check';
|
||||
export const AGENT_CODE_PROCUREMENT_CONTRACT_REVIEW = 'procurement_contract_review';
|
||||
|
||||
export interface AgentRegistryCapabilities {
|
||||
streaming?: boolean;
|
||||
@@ -230,6 +231,11 @@ export function isShippingNoticeAgent(agent: AgentLike): boolean {
|
||||
return resolveAgentCode(agent) === AGENT_CODE_SHIPPING_NOTICE;
|
||||
}
|
||||
|
||||
/** 是否为采购合同审查 Agent(agent_code=procurement_contract_review)。 */
|
||||
export function isProcurementContractAgent(agent: AgentLike): boolean {
|
||||
return resolveAgentCode(agent) === AGENT_CODE_PROCUREMENT_CONTRACT_REVIEW;
|
||||
}
|
||||
|
||||
/** 是否启用本地请假表单(后端 leave_feature_enabled)。 */
|
||||
export function canUseLeaveFeature(agent: AgentLike): boolean {
|
||||
return Boolean(agent?.leave_feature_enabled);
|
||||
|
||||
Reference in new issue
Block a user