Merge branch 'dev' into hugo-shipping-notice

This commit is contained in:
hugo committed 2026-08-11 14:33:56 +08:00
commit 472b530be3
397 files changed
+46450 -34171

No files matched your search

+2
View File
@@ -12,6 +12,7 @@ from . import (
department_service,
faq_service,
guide_service,
linked_service_service,
permission_service,
report_service,
shipping_customer_import_service,
@@ -30,6 +31,7 @@ __all__ = [
'department_service',
'faq_service',
'guide_service',
'linked_service_service',
'permission_service',
'report_service',
'shipping_customer_import_service',
@@ -0,0 +1,130 @@
"""
backend/app/services/admin/linked_service_service.py
用途:关联服务 CRUD 与侧栏只读列表。
依赖:models.LinkedService、app.core.errors。
逻辑:api/admin/linked_services.py 管理 CRUD;api/linked_services.py 返回已启用项。
"""
from __future__ import annotations
from typing import Any
from urllib.parse import urlparse
from app import db
from app.core.errors import NotFoundError, ValidationError
from app.models import LinkedService
def _normalize_name(value: Any) -> str:
"""校验并规范化显示名称。"""
name = str(value or '').strip()
if not name:
raise ValidationError('Name is required')
if len(name) > 100:
raise ValidationError('Name is too long')
return name
def _normalize_url(value: Any) -> str:
"""
校验并规范化访问地址。
核心逻辑:仅允许 http/https,且必须含主机;内网 IP 可用 http。
"""
url = str(value or '').strip()
if not url:
raise ValidationError('URL is required')
if len(url) > 500:
raise ValidationError('URL is too long')
parsed = urlparse(url)
if parsed.scheme not in {'http', 'https'} or not parsed.netloc:
raise ValidationError('URL must be an absolute http(s) address')
return url
def serialize_linked_service(row: LinkedService, *, include_admin_fields: bool = False) -> dict:
"""LinkedService ORM → API dict。"""
payload = {
'id': row.id,
'name': row.name,
'url': row.url,
}
if include_admin_fields:
payload.update({
'is_enabled': bool(row.is_enabled),
'sort_order': int(row.sort_order or 0),
'created_at': row.created_at.isoformat() if row.created_at else None,
'updated_at': row.updated_at.isoformat() if row.updated_at else None,
})
return payload
def list_enabled_linked_services() -> list[dict]:
"""返回已启用关联服务,供 Chat/工作台侧栏入口使用。"""
rows = (
db.session.query(LinkedService)
.filter(LinkedService.is_enabled.is_(True))
.order_by(LinkedService.sort_order.asc(), LinkedService.id.asc())
.all()
)
return [serialize_linked_service(row) for row in rows]
def list_linked_services() -> list[dict]:
"""管理端列表:含停用项与排序字段。"""
rows = (
db.session.query(LinkedService)
.order_by(LinkedService.sort_order.asc(), LinkedService.id.asc())
.all()
)
return [serialize_linked_service(row, include_admin_fields=True) for row in rows]
def create_linked_service(data: dict[str, Any]) -> dict:
"""
创建关联服务。
Args:
data: 含 name、url;可选 is_enabled、sort_order。
Returns:
{ id, message }
"""
row = LinkedService(
name=_normalize_name(data.get('name')),
url=_normalize_url(data.get('url')),
is_enabled=bool(data.get('is_enabled', True)),
sort_order=int(data.get('sort_order') or 0),
)
db.session.add(row)
db.session.commit()
return {'message': 'Created', 'id': row.id}
def update_linked_service(service_id: int, data: dict[str, Any]) -> dict:
"""
更新关联服务。
Raises:
NotFoundError: 记录不存在。
"""
row = db.session.get(LinkedService, service_id)
if not row:
raise NotFoundError('Not found')
row.name = _normalize_name(data.get('name'))
row.url = _normalize_url(data.get('url'))
if 'is_enabled' in data:
row.is_enabled = bool(data.get('is_enabled'))
if 'sort_order' in data:
row.sort_order = int(data.get('sort_order') or 0)
db.session.commit()
return {'message': 'Updated'}
def delete_linked_service(service_id: int) -> dict:
"""删除关联服务(不存在时静默成功)。"""
row = db.session.get(LinkedService, service_id)
if row:
db.session.delete(row)
db.session.commit()
return {'message': 'Deleted'}
@@ -214,6 +214,7 @@ def create_user(data: dict[str, Any]) -> dict:
casdoor_service.sync_create_user(
username=user.username,
password=data['password'],
employee_id=user.employee_id,
email=email,
real_name=user.real_name,
phone_number=user.phone_number,
@@ -115,3 +115,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: {}
@@ -0,0 +1,20 @@
"""
backend/app/services/auth/casdoor/__init__.py
用途:导出不依赖 HXOPS User 模型的 Casdoor 认证公共能力。
依赖:config、client、identity、errors。
逻辑:HXOPS 与平级服务可复制本目录,并用各自配置适配器创建 CasdoorClient。
"""
from .client import CasdoorClient, CasdoorTokenResult, get_casdoor_client
from .config import CasdoorConfig, casdoor_config_from_flask
from .identity import identity_from_claims
__all__ = [
'CasdoorClient',
'CasdoorConfig',
'CasdoorTokenResult',
'casdoor_config_from_flask',
'get_casdoor_client',
'identity_from_claims',
]
+170
View File
@@ -0,0 +1,170 @@
"""
backend/app/services/auth/casdoor/client.py
用途:封装 Casdoor OAuth/OIDC HTTP 通信,供 HXOPS 与平级服务复制复用。
依赖:requests、CasdoorConfig、Casdoor 错误映射。
逻辑:所有 grant 和 userinfo 请求集中在此;模块不依赖 HXOPS User、数据库或业务权限。
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from threading import Lock
from typing import Any
import requests
from .config import CasdoorConfig, casdoor_config_from_flask
from .errors import raise_auth_error
_CLIENT_CACHE_LOCK = Lock()
_CLIENT_CACHE_CONFIG: CasdoorConfig | None = None
_CLIENT_CACHE_VALUE: CasdoorClient | None = None
@dataclass(frozen=True)
class CasdoorTokenResult:
"""Casdoor token endpoint 返回的标准字段和原始扩展字段。"""
access_token: str
refresh_token: str | None
id_token: str | None
token_type: str
expires_in: int
raw: dict[str, Any]
def as_dict(self) -> dict[str, Any]:
"""返回兼容现有 HXOPS 路由和测试的 token 字典。"""
return dict(self.raw)
class CasdoorClient:
"""无业务模型依赖的 Casdoor OAuth/OIDC 客户端。"""
def __init__(self, config: CasdoorConfig, *, http_session=requests):
"""
创建客户端并注入配置和 HTTP 实现。
Args:
config: 当前服务自己的 Casdoor Application 配置。
http_session: 兼容 requests 的 HTTP 对象,测试可注入替身。
"""
self.config = config
self._http = http_session
self._metadata: dict[str, Any] | None = None
self._metadata_expires_at: datetime | None = None
self._metadata_lock = Lock()
def oidc_metadata(self) -> dict[str, Any]:
"""读取并缓存 OIDC discovery 文档 10 分钟。"""
now = datetime.now(timezone.utc)
if self._metadata and self._metadata_expires_at and self._metadata_expires_at > now:
return dict(self._metadata)
with self._metadata_lock:
now = datetime.now(timezone.utc)
if self._metadata and self._metadata_expires_at and self._metadata_expires_at > now:
return dict(self._metadata)
response = self._http.get(
f'{self.config.base_url}/.well-known/openid-configuration',
timeout=self.config.timeout_seconds,
)
response.raise_for_status()
data = response.json() or {}
if not isinstance(data, dict):
raise RuntimeError('Casdoor OIDC metadata is invalid')
self._metadata = data
self._metadata_expires_at = now + timedelta(minutes=10)
return dict(data)
def _token_endpoint(self) -> str:
"""从 discovery 文档读取 token endpoint,缺失时安全失败。"""
endpoint = str(self.oidc_metadata().get('token_endpoint') or '').strip()
if not endpoint:
raise RuntimeError('Casdoor token endpoint missing')
return endpoint
def _token_request(self, payload: dict[str, Any], *, context: str) -> CasdoorTokenResult:
"""执行 token endpoint 请求并统一解析成功或失败结果。"""
response = self._http.post(
self._token_endpoint(),
data=payload,
timeout=self.config.timeout_seconds,
)
try:
data = response.json() or {}
except ValueError as exc:
raise RuntimeError(f'Casdoor token request failed: HTTP {response.status_code}') from exc
if not response.ok or not data.get('access_token'):
raise_auth_error(data, context=context)
return CasdoorTokenResult(
access_token=str(data['access_token']),
refresh_token=str(data['refresh_token']) if data.get('refresh_token') else None,
id_token=str(data['id_token']) if data.get('id_token') else None,
token_type=str(data.get('token_type') or 'Bearer'),
expires_in=int(data.get('expires_in') or 3600),
raw=dict(data),
)
def password_login(self, username: str, password: str) -> CasdoorTokenResult:
"""使用当前服务自己的 Casdoor Application 执行 password grant。"""
return self._token_request({
'grant_type': 'password',
'username': username,
'password': password,
'client_id': self.config.client_id,
'client_secret': self.config.client_secret,
'scope': self.config.scope,
}, context='password')
def authorization_code_login(self, code: str, redirect_uri: str) -> CasdoorTokenResult:
"""将浏览器返回的 authorization code 兑换为 Casdoor token。"""
return self._token_request({
'grant_type': 'authorization_code',
'code': code,
'client_id': self.config.client_id,
'client_secret': self.config.client_secret,
'redirect_uri': redirect_uri,
}, context='code')
def refresh(self, refresh_token: str) -> CasdoorTokenResult:
"""使用 Casdoor refresh token 获取新 token 集合。"""
return self._token_request({
'grant_type': 'refresh_token',
'refresh_token': refresh_token,
'client_id': self.config.client_id,
'client_secret': self.config.client_secret,
}, context='refresh')
def userinfo(self, access_token: str) -> dict[str, Any]:
"""使用 Casdoor access token 获取可信用户声明。"""
endpoint = str(self.oidc_metadata().get('userinfo_endpoint') or '').strip()
if not endpoint:
raise RuntimeError('Casdoor userinfo endpoint missing')
response = self._http.get(
endpoint,
headers={'Authorization': f'Bearer {access_token}'},
timeout=self.config.timeout_seconds,
)
try:
data = response.json() or {}
except ValueError as exc:
raise RuntimeError(f'Casdoor userinfo failed: HTTP {response.status_code}') from exc
if not response.ok or not isinstance(data, dict):
raise RuntimeError(f'Casdoor userinfo failed: HTTP {response.status_code}')
return data
def get_casdoor_client() -> CasdoorClient:
"""复用当前配置对应的进程内客户端,配置变化时自动替换缓存实例。"""
global _CLIENT_CACHE_CONFIG, _CLIENT_CACHE_VALUE
config = casdoor_config_from_flask()
if _CLIENT_CACHE_VALUE is not None and _CLIENT_CACHE_CONFIG == config:
return _CLIENT_CACHE_VALUE
with _CLIENT_CACHE_LOCK:
if _CLIENT_CACHE_VALUE is None or _CLIENT_CACHE_CONFIG != config:
_CLIENT_CACHE_CONFIG = config
_CLIENT_CACHE_VALUE = CasdoorClient(config)
return _CLIENT_CACHE_VALUE
@@ -0,0 +1,68 @@
"""
backend/app/services/auth/casdoor/config.py
用途:定义纯 Casdoor 客户端配置及 HXOPS Flask 配置适配器。
依赖:dataclasses、flask.current_app、app.core.errors。
逻辑:公共客户端只接收 CasdoorConfig;不同服务只需替换配置适配器。
"""
from __future__ import annotations
from dataclasses import dataclass
from flask import current_app
from app.core.errors import AppError
@dataclass(frozen=True)
class CasdoorConfig:
"""Casdoor OAuth/OIDC 客户端运行参数,secret 不参与 repr。"""
base_url: str
client_id: str
client_secret: str
issuer: str
scope: str = 'openid profile email'
timeout_seconds: int = 8
def __repr__(self) -> str:
"""输出可诊断但不包含 client_secret 的配置摘要。"""
return (
'CasdoorConfig('
f'base_url={self.base_url!r}, client_id={self.client_id!r}, '
f'issuer={self.issuer!r}, scope={self.scope!r}, '
f'timeout_seconds={self.timeout_seconds!r})'
)
def casdoor_config_from_flask() -> CasdoorConfig:
"""
从当前 Flask 应用读取并校验 Casdoor 客户端配置。
Returns:
可交给 CasdoorClient 的不可变配置。
Raises:
AppError: 基础地址、客户端凭据或 issuer 未配置。
"""
base_url = str(current_app.config.get('CASDOOR_BASE_URL') or '').strip().rstrip('/')
client_id = str(current_app.config.get('CASDOOR_CLIENT_ID') or '').strip()
client_secret = str(current_app.config.get('CASDOOR_CLIENT_SECRET') or '')
issuer = str(current_app.config.get('AUTH_JWT_ISSUER') or '').strip().rstrip('/')
scope = str(current_app.config.get('CASDOOR_SCOPE') or 'openid profile email').strip()
timeout_seconds = int(current_app.config.get('CASDOOR_HTTP_TIMEOUT_SECONDS') or 8)
if not base_url or not client_id or not client_secret or not issuer:
raise AppError(
code='CASDOOR_CONFIG_ERROR',
message='Authentication service is not configured. Please contact the administrator.',
http_status=503,
)
return CasdoorConfig(
base_url=base_url,
client_id=client_id,
client_secret=client_secret,
issuer=issuer,
scope=scope or 'openid profile email',
timeout_seconds=max(1, timeout_seconds),
)
+106
View File
@@ -0,0 +1,106 @@
"""
backend/app/services/auth/casdoor/errors.py
用途:把 Casdoor OAuth/OIDC 失败转换为稳定业务错误码。
依赖:标准库解析工具、flask.current_app、app.core.errors。
逻辑:CasdoorClient 将失败响应交给本模块,API 层只处理统一 AppError。
"""
from __future__ import annotations
import ast
import json
import re
from flask import current_app
from app.core.errors import AppError, ValidationError
def clean_str(value) -> str | None:
"""去除字符串首尾空白,空值统一返回 None。"""
if value is None:
return None
return str(value).strip() or None
def extract_error_payload(source) -> dict:
"""从 Casdoor 响应字典或异常文本中提取可识别错误字段。"""
if isinstance(source, dict):
return source
text = str(source or '')
match = re.search(r'\{.*\}', text, re.DOTALL)
if match:
try:
parsed = ast.literal_eval(match.group(0))
if isinstance(parsed, dict):
return parsed
except (SyntaxError, ValueError):
pass
try:
parsed = json.loads(text)
return parsed if isinstance(parsed, dict) else {}
except (json.JSONDecodeError, TypeError):
return {}
def is_password_error(message: str) -> bool:
"""判断 Casdoor 错误是否表示用户名或密码无效。"""
lowered = (message or '').lower()
return 'invalid_grant' in lowered or 'password login failed' in lowered or 'incorrect password' in lowered
def raise_auth_error(source, *, context: str, status_code: int = 401) -> None:
"""
将 Casdoor 登录、授权码和刷新失败映射为稳定错误。
Args:
source: Casdoor JSON 错误体或捕获的异常。
context: ``password``、``code``、``refresh`` 或 ``verify``。
status_code: 未识别错误的默认 HTTP 状态码。
Raises:
AppError: 所有失败均转换为统一认证错误,不返回原始 token 或 secret。
"""
data = extract_error_payload(source)
raw = str(source or '')
oauth_error = (clean_str(data.get('error')) or '').lower()
if not oauth_error and 'invalid_grant' in raw.lower():
oauth_error = 'invalid_grant'
if not oauth_error and 'invalid_client' in raw.lower():
oauth_error = 'invalid_client'
if oauth_error == 'invalid_grant' or is_password_error(raw):
if context in {'password', 'verify'}:
raise AppError(code='CASDOOR_INVALID_CREDENTIALS', message='Incorrect username or password', http_status=401)
raise AppError(code='CASDOOR_CODE_EXPIRED', message='Login session expired, please sign in again', http_status=401)
if oauth_error in {'invalid_client', 'unauthorized_client'}:
raise AppError(
code='CASDOOR_CONFIG_ERROR',
message='Authentication service is misconfigured. Please contact the administrator.',
http_status=503,
details={'casdoor_error': oauth_error},
)
if oauth_error == 'access_denied':
raise AppError(code='CASDOOR_ACCESS_DENIED', message='Login was cancelled or denied', http_status=403)
if oauth_error == 'unsupported_grant_type':
raise AppError(
code='AUTH.CASDOOR_REFRESH_UNSUPPORTED',
message='Casdoor refresh token is not supported by current application config',
http_status=400,
)
lowered_raw = raw.lower()
if 'token endpoint missing' in lowered_raw or 'casdoor_base_url is not configured' in lowered_raw:
raise AppError(
code='CASDOOR_CONFIG_ERROR',
message='Authentication service is not configured. Please contact the administrator.',
http_status=503,
)
if 'invalid or expired casdoor state' in lowered_raw:
raise ValidationError('Invalid or expired Casdoor state')
current_app.logger.warning('[casdoor] unmapped auth error context=%s payload=%s', context, data)
raise AppError(
code='CASDOOR_AUTH_FAILED',
message='Authentication failed, please try again',
http_status=status_code,
details={'casdoor_error': oauth_error or None},
)
@@ -0,0 +1,70 @@
"""
backend/app/services/auth/casdoor/identity.py
用途:将 Casdoor ID token/userinfo claims 转换为统一 AuthIdentity。
依赖:hmac、typing、services.auth.common.identity。
逻辑:严格绑定预期 issuer,提取稳定 subject 与可变用户资料,不访问业务数据库。
"""
from __future__ import annotations
import hmac
from collections.abc import Mapping
from typing import Any
from app.services.auth.common import AuthIdentity, IdentityValidationError, require_stable_identity
def _claim_text(claims: Mapping[str, Any], *keys: str) -> str | None:
"""按优先级读取第一个非空 claim 并转换为去空白字符串。"""
for key in keys:
value = claims.get(key)
if value is not None and str(value).strip():
return str(value).strip()
return None
def _claim_or_property_text(claims: Mapping[str, Any], *keys: str) -> str | None:
"""优先读取顶层 claim,再兼容 Casdoor properties 中同名的用户自定义属性。"""
value = _claim_text(claims, *keys)
if value:
return value
properties = claims.get('properties')
if isinstance(properties, Mapping):
return _claim_text(properties, *keys)
return None
def identity_from_claims(
claims: Mapping[str, Any],
*,
expected_issuer: str,
) -> AuthIdentity:
"""
将可信 Casdoor claims 转换为跨服务统一身份。
Args:
claims: 已验证 ID token 或通过 HTTPS 从 userinfo 获取的声明。
expected_issuer: 当前服务配置的可信 Casdoor issuer。
Returns:
不包含角色和业务权限的 AuthIdentity。
Raises:
IdentityValidationError: issuer 不匹配或缺少稳定 subject/username。
"""
trusted_issuer = str(expected_issuer or '').strip().rstrip('/')
claim_issuer = str(claims.get('iss') or trusted_issuer).strip().rstrip('/')
if not trusted_issuer or not claim_issuer or not hmac.compare_digest(claim_issuer, trusted_issuer):
raise IdentityValidationError('Casdoor identity issuer does not match the trusted issuer')
identity = AuthIdentity(
issuer=trusted_issuer,
subject=_claim_text(claims, 'sub') or '',
username=_claim_text(claims, 'preferred_username', 'name') or '',
display_name=_claim_text(claims, 'display_name', 'displayName', 'real_name', 'realName', 'name'),
email=_claim_text(claims, 'email'),
phone_number=_claim_text(claims, 'phone_number', 'phone'),
employee_id=_claim_or_property_text(claims, 'employee_id', 'employeeId'),
department=_claim_text(claims, 'department', 'affiliation'),
)
return require_stable_identity(identity)
+53 -321
View File
@@ -1,373 +1,105 @@
"""
backend/app/services/auth/casdoor_service.py
用途:Casdoor IdP 用户同步与 OAuth 错误映射(管理端创建/改密、用户域登录共用)。
依赖:flask.current_app、requests、app.core.errors。
逻辑:由 services/admin/user_service、api/user 登录路由调用。
用途:为历史调用点保留 Casdoor 错误与 HXOPS 用户同步兼容门面。
依赖:公共 casdoor.errors、HXOPS casdoor_user_sync。
逻辑:新代码按职责导入分层模块;旧路由、管理端和测试可继续替换本文件函数。
"""
from __future__ import annotations
import ast
import json
import re
from typing import Any
import requests
from flask import current_app
from app.core.errors import AppError, ConflictError, ValidationError
from app.models import User
def clean_str(value) -> str | None:
"""Trim 字符串;空串返回 None。"""
if value is None:
return None
if isinstance(value, str):
value = value.strip()
return value or None
return str(value).strip() or None
from app.services.auth.casdoor.errors import (
clean_str,
extract_error_payload,
is_password_error,
raise_auth_error,
)
from app.services.auth.hxops import casdoor_user_sync as _sync
def is_casdoor_configured() -> bool:
"""Casdoor 基础配置是否齐全。"""
if not clean_str(current_app.config.get('CASDOOR_ORGANIZATION')):
return False
base = (current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/')
client_id = current_app.config.get('CASDOOR_CLIENT_ID') or ''
client_secret = current_app.config.get('CASDOOR_CLIENT_SECRET') or ''
return bool(base and client_id and client_secret)
"""兼容入口:检查 Casdoor 用户同步配置。"""
return _sync.is_casdoor_configured()
def casdoor_user_owner() -> str:
"""返回 Casdoor organization owner。"""
owner = clean_str(current_app.config.get('CASDOOR_ORGANIZATION'))
if not owner:
raise RuntimeError('CASDOOR_ORGANIZATION is not configured')
return owner
def extract_error_payload(source) -> dict:
"""从 Casdoor 响应或异常文本解析 JSON 错误体。"""
if isinstance(source, dict):
return source
text = str(source or '')
match = re.search(r'\{.*\}', text, re.DOTALL)
if match:
try:
parsed = ast.literal_eval(match.group(0))
if isinstance(parsed, dict):
return parsed
except (SyntaxError, ValueError):
pass
try:
parsed = json.loads(text)
if isinstance(parsed, dict):
return parsed
except (json.JSONDecodeError, TypeError):
pass
return {}
"""兼容入口:返回 Casdoor organization owner。"""
return _sync.casdoor_user_owner()
def is_user_exists_error(message: str) -> bool:
lowered = (message or '').lower()
return 'already exist' in lowered or 'duplicate' in lowered or 'has existed' in lowered
def is_password_error(message: str) -> bool:
lowered = (message or '').lower()
return 'invalid_grant' in lowered or 'password login failed' in lowered or 'incorrect password' in lowered
"""兼容入口:判断 IdP 用户已存在错误。"""
return _sync.is_user_exists_error(message)
def is_user_missing_error(message: str) -> bool:
lowered = (message or '').lower()
return (
"doesn't exist" in lowered
or 'does not exist' in lowered
or 'user not found' in lowered
or 'no such user' in lowered
)
"""兼容入口:判断 IdP 用户不存在错误。"""
return _sync.is_user_missing_error(message)
def raise_user_not_in_idp(source=None) -> None:
data = extract_error_payload(source)
msg_text = clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
raise AppError(
code='CASDOOR_USER_NOT_IN_IDP',
message='Your account has not been registered in the authentication system. Please contact the administrator.',
http_status=409,
details={'technical': msg_text or str(source or '')[:300]},
)
"""兼容入口:抛出 IdP 缺失用户业务错误。"""
_sync.raise_user_not_in_idp(source)
def raise_add_user_error(source) -> None:
"""将 Casdoor add-user 失败映射为稳定业务错误码。"""
data = extract_error_payload(source)
msg_text = clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
lowered = (msg_text or str(source or '')).lower()
if is_user_exists_error(lowered):
raise ConflictError(
'Username already exists in Casdoor',
code='USER.USERNAME_EXISTS',
details={'field': 'username', 'technical': msg_text},
)
if any(token in lowered for token in ('too short', 'too weak', 'password policy', 'at least')):
raise AppError(code='CASDOOR_PASSWORD_POLICY', message='Password does not meet security requirements', http_status=400)
raise AppError(
code='CASDOOR_ADD_USER_FAILED',
message='Failed to create user in authentication system. Please try again or contact the administrator.',
http_status=502,
details={'technical': msg_text or str(source or '')[:300]},
)
"""兼容入口:映射 Casdoor 新增用户错误。"""
_sync.raise_add_user_error(source)
def raise_update_user_error(source) -> None:
"""将 Casdoor update-user 失败映射为稳定业务错误码。"""
data = extract_error_payload(source)
msg_text = clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
lowered = (msg_text or str(source or '')).lower()
if is_user_missing_error(lowered):
raise_user_not_in_idp(source)
if is_user_exists_error(lowered) or ('email' in lowered and 'already' in lowered):
raise ConflictError(
'Email already exists in Casdoor',
code='USER.EMAIL_EXISTS',
details={'field': 'email', 'technical': msg_text},
)
raise AppError(
code='CASDOOR_UPDATE_USER_FAILED',
message='Failed to update user in authentication system. Please try again or contact the administrator.',
http_status=502,
details={'technical': msg_text or str(source or '')[:300]},
)
"""兼容入口:映射 Casdoor 更新用户错误。"""
_sync.raise_update_user_error(source)
def raise_set_password_error(source) -> None:
"""将 Casdoor set-password 失败映射为稳定业务错误码。"""
data = extract_error_payload(source)
msg_text = clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
lowered = (msg_text or str(source or '')).lower()
if is_password_error(lowered) or 'old password' in lowered or 'current password' in lowered:
raise AppError(code='CASDOOR_INVALID_CREDENTIALS', message='Incorrect current password', http_status=401)
if any(token in lowered for token in ('too short', 'too weak', 'password policy', 'at least')):
raise AppError(code='CASDOOR_PASSWORD_POLICY', message='New password does not meet security requirements', http_status=400)
if is_user_missing_error(lowered):
raise_user_not_in_idp(source)
raise AppError(
code='CASDOOR_SET_PASSWORD_FAILED',
message='Failed to change password. Please try again or contact the administrator.',
http_status=502,
details={'technical': msg_text or str(source)[:300]},
)
"""兼容入口:映射 Casdoor 修改密码错误。"""
_sync.raise_set_password_error(source)
def raise_auth_error(source, *, context: str, status_code: int = 401) -> None:
"""Map Casdoor OAuth/API failures to stable business error codes."""
data = extract_error_payload(source)
raw = str(source or '')
oauth_error = clean_str(data.get('error')).lower()
if not oauth_error and 'invalid_grant' in raw.lower():
oauth_error = 'invalid_grant'
if not oauth_error and 'invalid_client' in raw.lower():
oauth_error = 'invalid_client'
if oauth_error == 'invalid_grant' or is_password_error(raw):
if context in ('password', 'verify'):
raise AppError(code='CASDOOR_INVALID_CREDENTIALS', message='Incorrect username or password', http_status=401)
raise AppError(code='CASDOOR_CODE_EXPIRED', message='Login session expired, please sign in again', http_status=401)
if oauth_error in ('invalid_client', 'unauthorized_client'):
raise AppError(
code='CASDOOR_CONFIG_ERROR',
message='Authentication service is misconfigured. Please contact the administrator.',
http_status=503,
details={'casdoor_error': oauth_error},
)
if oauth_error == 'access_denied':
raise AppError(code='CASDOOR_ACCESS_DENIED', message='Login was cancelled or denied', http_status=403)
if 'token endpoint missing' in raw.lower() or 'casdoor_base_url is not configured' in raw.lower() or 'casdoor is not configured' in raw.lower():
raise AppError(
code='CASDOOR_CONFIG_ERROR',
message='Authentication service is not configured. Please contact the administrator.',
http_status=503,
)
if 'invalid or expired casdoor state' in raw.lower():
raise ValidationError('Invalid or expired Casdoor state')
current_app.logger.warning('[casdoor] unmapped auth error context=%s payload=%s raw=%s', context, data, raw[:500])
raise AppError(
code='CASDOOR_AUTH_FAILED',
message='Authentication failed, please try again',
http_status=status_code,
details={'casdoor_error': oauth_error or None, 'technical': raw[:300]},
)
def build_user_profile_payload(**kwargs) -> dict[str, Any]:
"""兼容入口:构造不含密码的 Casdoor 用户资料。"""
return _sync.build_user_profile_payload(**kwargs)
def build_user_profile_payload(
*,
username: str,
email: str,
real_name=None,
phone_number=None,
status='active',
department=None,
) -> dict:
"""组装 Casdoor 用户资料字段(不含 password)。"""
display_name = clean_str(real_name) or username
payload = {
'owner': casdoor_user_owner(),
'name': username,
'email': email or '',
'displayName': display_name,
'realName': clean_str(real_name) or '',
'phone': clean_str(phone_number) or '',
'isForbidden': clean_str(status) not in (None, 'active'),
}
department_value = clean_str(department)
if department_value:
payload['affiliation'] = department_value
return payload
def build_user_payload(**kwargs) -> dict[str, Any]:
"""兼容入口:构造 Casdoor 创建用户请求体。"""
return _sync.build_user_payload(**kwargs)
def build_user_payload(
*,
username: str,
password: str,
email: str,
real_name=None,
phone_number=None,
status='active',
department=None,
) -> dict:
"""组装 Casdoor add-user 请求体。"""
payload = build_user_profile_payload(
username=username,
email=email,
real_name=real_name,
phone_number=phone_number,
status=status,
department=department,
)
payload['password'] = password
return payload
def casdoor_add_user(user_payload: dict[str, Any]) -> None:
"""兼容入口:调用 Casdoor 创建用户。"""
_sync.casdoor_add_user(user_payload)
def casdoor_add_user(user_payload: dict) -> None:
"""调用 Casdoor /api/add-user 创建 IdP 用户。"""
base = (current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/')
client_id = current_app.config.get('CASDOOR_CLIENT_ID') or ''
client_secret = current_app.config.get('CASDOOR_CLIENT_SECRET') or ''
if not base or not client_id or not client_secret:
raise RuntimeError('Casdoor is not configured')
url = f'{base}/api/add-user'
resp = requests.post(url, json=user_payload, auth=(client_id, client_secret), timeout=8)
try:
data = resp.json() or {}
except ValueError:
raise RuntimeError(f'Casdoor add-user failed: HTTP {resp.status_code} {resp.text[:200]}')
if data.get('status') != 'ok':
raise_add_user_error(data)
def casdoor_update_user(user_payload: dict) -> None:
"""调用 Casdoor /api/update-user 更新 IdP 用户资料。"""
base = (current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/')
client_id = current_app.config.get('CASDOOR_CLIENT_ID') or ''
client_secret = current_app.config.get('CASDOOR_CLIENT_SECRET') or ''
if not base or not client_id or not client_secret:
raise RuntimeError('Casdoor is not configured')
url = f'{base}/api/update-user'
resp = requests.post(url, json=user_payload, auth=(client_id, client_secret), timeout=8)
try:
data = resp.json() or {}
except ValueError:
raise RuntimeError(f'Casdoor update-user failed: HTTP {resp.status_code} {resp.text[:200]}')
if data.get('status') != 'ok':
raise_update_user_error(data)
def casdoor_update_user(user_payload: dict[str, Any]) -> None:
"""兼容入口:调用 Casdoor 更新用户。"""
_sync.casdoor_update_user(user_payload)
def casdoor_set_password(user_owner: str, user_name: str, old_password: str, new_password: str) -> None:
"""调用 Casdoor /api/set-password。"""
base = (current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/')
client_id = current_app.config.get('CASDOOR_CLIENT_ID') or ''
client_secret = current_app.config.get('CASDOOR_CLIENT_SECRET') or ''
if not base or not client_id or not client_secret:
raise RuntimeError('Casdoor is not configured')
url = f'{base}/api/set-password'
resp = requests.post(
url,
files={
'userOwner': (None, user_owner),
'userName': (None, user_name),
'oldPassword': (None, old_password),
'newPassword': (None, new_password),
},
auth=(client_id, client_secret),
timeout=8,
)
try:
data = resp.json() or {}
except ValueError:
raise RuntimeError(f'Casdoor set-password failed: HTTP {resp.status_code} {resp.text[:200]}')
if data.get('status') != 'ok':
raise_set_password_error(data)
"""兼容入口:调用 Casdoor 修改密码。"""
_sync.casdoor_set_password(user_owner, user_name, old_password, new_password)
def sync_create_user(
*,
username: str,
password: str,
email: str,
real_name=None,
phone_number=None,
status='active',
department=None,
) -> None:
"""管理端创建用户时同步至 Casdoor。"""
if not is_casdoor_configured():
return
payload = build_user_payload(
username=username,
password=password,
email=email,
real_name=real_name,
phone_number=phone_number,
status=status,
department=department,
)
casdoor_add_user(payload)
def sync_create_user(**kwargs) -> None:
"""兼容入口:同步创建用户,并保留旧模块 monkeypatch 替换点。"""
_sync.sync_create_user(**kwargs, add_user=casdoor_add_user)
def sync_admin_set_password(user: User, new_password: str) -> None:
"""管理端重设密码时同步 Casdoor(无旧密码)。"""
if not is_casdoor_configured():
return
user_owner = casdoor_user_owner()
try:
casdoor_set_password(user_owner, user.username, '', new_password)
except RuntimeError as exc:
if is_user_missing_error(str(exc)):
raise_user_not_in_idp(exc)
raise_set_password_error(exc)
"""兼容入口:同步管理员改密,并保留旧模块 monkeypatch 替换点。"""
_sync.sync_admin_set_password(user, new_password, set_password=casdoor_set_password)
def sync_update_user(user: User, *, new_password: str | None = None) -> None:
"""管理端编辑用户时同步 Casdoor:仅改密;IdP 无账号则 add-user 补建。"""
if not is_casdoor_configured() or not new_password:
return
def _provision_missing_user_in_casdoor():
sync_create_user(
username=user.username,
password=new_password,
email=user.email,
real_name=user.real_name,
phone_number=user.phone_number,
status=user.status,
department=user.department,
)
try:
sync_admin_set_password(user, new_password)
except AppError as exc:
if exc.code == 'CASDOOR_USER_NOT_IN_IDP':
_provision_missing_user_in_casdoor()
return
raise
"""兼容入口:同步用户改密或补建 IdP 账号,并保留测试替换点。"""
_sync.sync_update_user(
user,
new_password=new_password,
set_password=casdoor_set_password,
add_user=casdoor_add_user,
)
@@ -0,0 +1,16 @@
"""
backend/app/services/auth/common/__init__.py
用途:导出不依赖 HXOPS 数据模型的认证公共类型。
依赖:common.identity。
逻辑:Casdoor 客户端、HXOPS 登录和 SSO 模块通过本入口共享统一身份对象。
"""
from .identity import AuthIdentity, IdentityValidationError, identity_key, require_stable_identity
__all__ = [
'AuthIdentity',
'IdentityValidationError',
'identity_key',
'require_stable_identity',
]
@@ -0,0 +1,69 @@
"""
backend/app/services/auth/common/identity.py
用途:定义跨认证来源通用、可复制的稳定身份对象。
依赖:Python dataclasses;不依赖 Flask、SQLAlchemy 或 HXOPS User。
逻辑:Casdoor claims 先转换为 AuthIdentity,业务系统再按 issuer + subject 映射自己的用户。
"""
from __future__ import annotations
from dataclasses import dataclass
class IdentityValidationError(ValueError):
"""身份缺少跨服务稳定键时抛出,调用方负责映射为自身错误契约。"""
@dataclass(frozen=True)
class AuthIdentity:
"""认证系统返回的稳定身份和可变展示资料,不包含任何业务权限。"""
issuer: str
subject: str
username: str
display_name: str | None = None
email: str | None = None
phone_number: str | None = None
employee_id: str | None = None
department: str | None = None
def require_stable_identity(identity: AuthIdentity) -> AuthIdentity:
"""
校验跨服务身份必须具备 issuer、subject 和 username。
Args:
identity: 待校验的认证身份。
Returns:
去除稳定键首尾空白后的不可变身份对象。
Raises:
IdentityValidationError: 缺少稳定身份键或用户名。
"""
issuer = str(identity.issuer or '').strip()
subject = str(identity.subject or '').strip()
username = str(identity.username or '').strip()
if not issuer or not subject:
raise IdentityValidationError('Identity issuer and subject are required')
if not username:
raise IdentityValidationError('Identity username is required')
if issuer == identity.issuer and subject == identity.subject and username == identity.username:
return identity
return AuthIdentity(
issuer=issuer,
subject=subject,
username=username,
display_name=identity.display_name,
email=identity.email,
phone_number=identity.phone_number,
employee_id=identity.employee_id,
department=identity.department,
)
def identity_key(identity: AuthIdentity) -> tuple[str, str]:
"""返回业务系统建立外部身份映射时使用的唯一键 ``(issuer, subject)``。"""
stable = require_stable_identity(identity)
return stable.issuer, stable.subject
@@ -0,0 +1,28 @@
"""
backend/app/services/auth/hxops/__init__.py
用途:导出依赖 HXOPS User、数据库和会话契约的认证编排能力。
依赖:user_resolver、session_token、login_service、casdoor_route_adapter、casdoor_authorize、casdoor_state、casdoor_user_sync。
逻辑:API 路由调用本包;平级服务不复制本目录。
"""
from .login_service import HxopsLoginService, LoginResult
from .casdoor_authorize import CasdoorAuthorizeOptions, build_casdoor_authorize_payload
from . import casdoor_route_adapter
from .casdoor_state import consume_casdoor_state, issue_casdoor_state
from . import casdoor_user_sync
from .session_token import issue_hxops_access_token
from .user_resolver import resolve_hxops_user
__all__ = [
'HxopsLoginService',
'LoginResult',
'casdoor_user_sync',
'CasdoorAuthorizeOptions',
'build_casdoor_authorize_payload',
'casdoor_route_adapter',
'consume_casdoor_state',
'issue_hxops_access_token',
'issue_casdoor_state',
'resolve_hxops_user',
]
@@ -0,0 +1,105 @@
"""
backend/app/services/auth/hxops/casdoor_authorize.py
用途:组装 HXOPS 跳转 Casdoor 的 OAuth 授权地址及其 state 响应。
依赖:Flask 配置、Casdoor OIDC discovery、Casdoor state 服务。
逻辑:路由传入可选参数,本模块选择默认值、处理企微 provider 规则并返回原有响应字段。
"""
from __future__ import annotations
from collections.abc import Callable, Mapping
from dataclasses import dataclass
from typing import Any
from urllib.parse import quote
from flask import current_app
from app.core.errors import AppError
from .casdoor_state import issue_casdoor_state
MetadataOperation = Callable[[], Mapping[str, Any]]
StateOperation = Callable[[str], str]
@dataclass(frozen=True)
class CasdoorAuthorizeOptions:
"""授权地址构造所需的浏览器可选参数,不包含任何 client_secret。"""
redirect_uri: str | None = None
provider_hint: str | None = None
default_provider: str | None = None
silent_signin: str | None = None
def _clean_text(value: object) -> str | None:
"""将 query/config 值归一为去空白字符串,空值统一为 None。"""
text = str(value or '').strip()
return text or None
def _is_truthy(value: object) -> bool:
"""识别现有接口支持的 1/true/yes 静默登录显式开关。"""
return (_clean_text(value) or '').lower() in {'1', 'true', 'yes'}
def build_casdoor_authorize_payload(
options: CasdoorAuthorizeOptions,
*,
oidc_metadata: MetadataOperation | None = None,
issue_state: StateOperation = issue_casdoor_state,
) -> dict[str, str]:
"""
依据 Casdoor discovery 与 HXOPS 配置构造授权地址,保持现有 response 字段和参数规则。
Args:
options: redirect_uri、provider_hint、default_provider 与 silent_signin 的可选浏览器输入。
oidc_metadata: 可选 discovery 读取函数,路由和测试可注入既有兼容代理。
issue_state: 可选 state 签发函数,供路由兼容 monkeypatch 与单元测试注入。
Returns:
包含 ``url``、``state`` 与 ``redirect_uri`` 的原有扁平响应 payload。
Raises:
AppError: Casdoor 授权端点或 client/redirect 配置缺失时保持既有 500 错误契约。
"""
metadata = (oidc_metadata or _flask_oidc_metadata)()
authorize_endpoint = _clean_text(metadata.get('authorization_endpoint'))
if not authorize_endpoint:
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Casdoor authorization endpoint missing', http_status=500)
client_id = _clean_text(current_app.config.get('CASDOOR_CLIENT_ID'))
redirect_uri = _clean_text(options.redirect_uri) or _clean_text(current_app.config.get('CASDOOR_REDIRECT_URI'))
scope = _clean_text(current_app.config.get('CASDOOR_SCOPE')) or 'openid profile email'
if not client_id or not redirect_uri:
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Casdoor client config is incomplete', http_status=500)
default_provider = (_clean_text(options.default_provider) or '').lower()
provider_hint = _clean_text(options.provider_hint)
if not provider_hint and default_provider == 'wecom':
provider_hint = _clean_text(current_app.config.get('CASDOOR_WECOM_PROVIDER_HINT'))
silent_signin = _is_truthy(options.silent_signin)
if not silent_signin and default_provider == 'wecom':
silent_signin = bool(current_app.config.get('CASDOOR_WECOM_SILENT_SIGNIN'))
state = issue_state(redirect_uri)
url = (
f'{authorize_endpoint}?client_id={quote(client_id, safe="")}'
f'&response_type=code&redirect_uri={quote(redirect_uri, safe="")}'
f'&scope={quote(scope, safe="")}&state={quote(state, safe="")}'
)
if provider_hint:
url += f'&provider_hint={quote(provider_hint, safe="")}'
if silent_signin:
url += '&silentSignin=1'
return {'url': url, 'state': state, 'redirect_uri': redirect_uri}
def _flask_oidc_metadata() -> Mapping[str, Any]:
"""读取当前 Flask 配置对应的 Casdoor discovery 文档,供默认服务调用。"""
from app.services.auth.casdoor import get_casdoor_client
return get_casdoor_client().oidc_metadata()
@@ -0,0 +1,92 @@
"""
backend/app/services/auth/hxops/casdoor_route_adapter.py
用途:集中 HXOPS Casdoor 路由所需的默认操作与登录服务装配。
依赖:CasdoorClient、授权地址/state 服务、HxopsLoginService。
逻辑:api/user 保留历史私有替换点,本模块提供其默认实现及可注入的登录编排工厂。
"""
from __future__ import annotations
from collections.abc import Callable, Mapping
from typing import Any
from app.services.auth.casdoor import get_casdoor_client
from .casdoor_authorize import CasdoorAuthorizeOptions, build_casdoor_authorize_payload
from .casdoor_state import consume_casdoor_state, issue_casdoor_state
from .login_service import HxopsLoginService, TokenOperation, UserinfoOperation
AuditOperation = Callable[..., None]
MetadataOperation = Callable[[], Mapping[str, Any]]
StateOperation = Callable[[str], str]
def get_oidc_metadata() -> dict[str, Any]:
"""读取当前 HXOPS Casdoor Application 对应的 OIDC discovery 文档。"""
return get_casdoor_client().oidc_metadata()
def password_login(username: str, password: str) -> dict[str, Any]:
"""以 HXOPS 自己的 Casdoor Application 执行 password grant。"""
return get_casdoor_client().password_login(username, password).as_dict()
def authorization_code_login(code: str, redirect_uri: str) -> dict[str, Any]:
"""以 HXOPS 自己的 Casdoor Application 兑换 authorization code。"""
return get_casdoor_client().authorization_code_login(code, redirect_uri).as_dict()
def refresh_token(refresh_token_value: str) -> dict[str, Any]:
"""使用 Casdoor refresh token 获取新的 Casdoor token 集合。"""
return get_casdoor_client().refresh(refresh_token_value).as_dict()
def userinfo(access_token: str) -> dict[str, Any]:
"""读取 Casdoor userinfo,供登录编排在缺少可信 ID token 时回退。"""
return get_casdoor_client().userinfo(access_token)
def build_authorize_payload(
options: CasdoorAuthorizeOptions,
*,
oidc_metadata: MetadataOperation | None = None,
issue_state: StateOperation | None = None,
) -> dict[str, str]:
"""构造原有 Casdoor authorize-url 响应,并允许路由兼容层注入测试替身。"""
return build_casdoor_authorize_payload(
options,
oidc_metadata=oidc_metadata or get_oidc_metadata,
issue_state=issue_state or issue_casdoor_state,
)
def create_login_service(
*,
write_login_audit: AuditOperation | None,
password_operation: TokenOperation | None = None,
code_operation: TokenOperation | None = None,
refresh_operation: TokenOperation | None = None,
userinfo_operation: UserinfoOperation | None = None,
) -> HxopsLoginService:
"""
组装 HXOPS 登录服务;路由可注入旧私有替换点以维持测试和渐进迁移兼容。
Args:
write_login_audit: HXOPS 登录审计写入函数。
password_operation: 可选 password grant 实现,默认使用本模块操作。
code_operation: 可选 authorization code grant 实现,默认使用本模块操作。
refresh_operation: 可选 refresh grant 实现,默认使用本模块操作。
userinfo_operation: 可选 userinfo 实现,默认使用本模块操作。
Returns:
已配置 Casdoor 操作和审计回调的 HxopsLoginService。
"""
return HxopsLoginService(
password_login=password_operation or password_login,
authorization_code_login=code_operation or authorization_code_login,
refresh_token=refresh_operation or refresh_token,
userinfo=userinfo_operation or userinfo,
write_login_audit=write_login_audit,
)
@@ -0,0 +1,103 @@
"""
backend/app/services/auth/hxops/casdoor_state.py
用途:签发和校验 Casdoor 授权码登录的无状态 HMAC state。
依赖:标准库、Flask 配置;不依赖数据库和 HXOPS User。
逻辑:授权地址签发固定格式 state,回调校验签名和有效期后恢复已绑定的 redirect_uri。
"""
from __future__ import annotations
import base64
import hashlib
import hmac
import json
import time
import uuid
from typing import Callable
from flask import current_app
_STATE_PREFIX = 'hxops_casdoor_v1'
_STATE_TTL_SECONDS = 600
def issue_casdoor_state(
redirect_uri: str,
*,
secret: str | None = None,
now_timestamp: int | None = None,
nonce_factory: Callable[[], str] | None = None,
) -> str:
"""
签发绑定 callback redirect_uri 的短时 HMAC state,保持现有 state 格式不变。
Args:
redirect_uri: 已由调用方选择的 Casdoor 回调地址,原样写入签名 payload。
secret: 可选 HMAC 密钥,仅供测试或非 Flask 调用注入;默认使用 SECRET_KEY。
now_timestamp: 可选当前 Unix 秒数,用于确定性测试;默认读取系统时钟。
nonce_factory: 可选随机 nonce 生成器;默认生成 UUID4 hex。
Returns:
格式为 ``hxops_casdoor_v1.<payload>.<signature>`` 的 URL-safe state。
"""
now = int(time.time()) if now_timestamp is None else int(now_timestamp)
payload = {
'v': 1,
'exp': now + _STATE_TTL_SECONDS,
'nonce': (nonce_factory or (lambda: uuid.uuid4().hex))(),
'redirect_uri': redirect_uri,
}
payload_json = json.dumps(payload, separators=(',', ':'))
payload_b64 = base64.urlsafe_b64encode(payload_json.encode('utf-8')).decode('ascii').rstrip('=')
signing_secret = str(secret if secret is not None else current_app.config.get('SECRET_KEY') or '')
signature = hmac.new(signing_secret.encode('utf-8'), payload_b64.encode('ascii'), hashlib.sha256).digest()
signature_b64 = base64.urlsafe_b64encode(signature).decode('ascii').rstrip('=')
return f'{_STATE_PREFIX}.{payload_b64}.{signature_b64}'
def consume_casdoor_state(
state: str | None,
*,
secret: str | None = None,
now_timestamp: int | None = None,
) -> str | None:
"""
校验 Casdoor state 的版本、HMAC 签名和有效期,成功时返回其绑定的 redirect_uri。
Args:
state: Casdoor 回调带回的 state。
secret: 可选 HMAC 密钥,仅供测试或非 Flask 调用注入;默认使用 SECRET_KEY。
now_timestamp: 可选当前 Unix 秒数,用于确定性测试;默认读取系统时钟。
Returns:
已签名且未过期的 redirect_uri;任一校验失败时返回 None,调用方映射为既有验证错误。
"""
if not state:
return None
try:
prefix, payload_b64, signature_b64 = state.split('.')
if prefix != _STATE_PREFIX:
return None
signing_secret = str(secret if secret is not None else current_app.config.get('SECRET_KEY') or '')
expected_signature = hmac.new(
signing_secret.encode('utf-8'),
payload_b64.encode('ascii'),
hashlib.sha256,
).digest()
expected_b64 = base64.urlsafe_b64encode(expected_signature).decode('ascii').rstrip('=')
if not hmac.compare_digest(expected_b64, signature_b64):
return None
padded_payload = payload_b64 + '=' * (-len(payload_b64) % 4)
payload = json.loads(base64.urlsafe_b64decode(padded_payload.encode('ascii')).decode('utf-8'))
if not isinstance(payload, dict) or payload.get('v') != 1:
return None
expires_at = int(payload.get('exp') or 0)
except (TypeError, ValueError, UnicodeDecodeError, json.JSONDecodeError):
return None
now = int(time.time()) if now_timestamp is None else int(now_timestamp)
if expires_at <= now:
return None
redirect_uri = payload.get('redirect_uri')
return str(redirect_uri).strip() or None
@@ -0,0 +1,325 @@
"""
backend/app/services/auth/hxops/casdoor_user_sync.py
用途:集中实现 HXOPS 用户创建和改密到 Casdoor 的管理端同步。
依赖:Flask 配置、requests、HXOPS User 模型、公共 Casdoor 错误解析。
逻辑:管理端事务调用本模块;HTTP 失败映射为稳定 AppError,由上层决定回滚。
"""
from __future__ import annotations
from typing import Any, Callable
import requests
from flask import current_app
from app.core.errors import AppError, ConflictError
from app.models import User
from app.services.auth.casdoor.errors import clean_str, extract_error_payload, is_password_error
AddUserOperation = Callable[[dict[str, Any]], None]
SetPasswordOperation = Callable[[str, str, str, str], None]
def is_casdoor_configured() -> bool:
"""检查用户同步所需的 organization、地址和客户端凭据是否齐全。"""
if not clean_str(current_app.config.get('CASDOOR_ORGANIZATION')):
return False
base = str(current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/')
client_id = current_app.config.get('CASDOOR_CLIENT_ID') or ''
client_secret = current_app.config.get('CASDOOR_CLIENT_SECRET') or ''
return bool(base and client_id and client_secret)
def casdoor_user_owner() -> str:
"""返回 Casdoor organization owner,缺失时阻止构造无效用户请求。"""
owner = clean_str(current_app.config.get('CASDOOR_ORGANIZATION'))
if not owner:
raise RuntimeError('CASDOOR_ORGANIZATION is not configured')
return owner
def is_user_exists_error(message: str) -> bool:
"""判断 Casdoor 错误文本是否表示用户名或用户记录已存在。"""
lowered = (message or '').lower()
return 'already exist' in lowered or 'duplicate' in lowered or 'has existed' in lowered
def is_user_missing_error(message: str) -> bool:
"""判断 Casdoor 错误文本是否表示 IdP 中不存在目标用户。"""
lowered = (message or '').lower()
return (
"doesn't exist" in lowered
or 'does not exist' in lowered
or 'user not found' in lowered
or 'no such user' in lowered
)
def raise_user_not_in_idp(source=None) -> None:
"""将 IdP 缺失用户转换为稳定业务错误,避免上层解析供应商文本。"""
data = extract_error_payload(source)
msg_text = clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
raise AppError(
code='CASDOOR_USER_NOT_IN_IDP',
message='Your account has not been registered in the authentication system. Please contact the administrator.',
http_status=409,
details={'technical': msg_text or str(source or '')[:300]},
)
def raise_add_user_error(source) -> None:
"""将 Casdoor add-user 失败映射为稳定业务错误码。"""
data = extract_error_payload(source)
msg_text = clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
lowered = (msg_text or str(source or '')).lower()
if is_user_exists_error(lowered):
raise ConflictError(
'Username already exists in Casdoor',
code='USER.USERNAME_EXISTS',
details={'field': 'username', 'technical': msg_text},
)
if any(token in lowered for token in ('too short', 'too weak', 'password policy', 'at least')):
raise AppError(code='CASDOOR_PASSWORD_POLICY', message='Password does not meet security requirements', http_status=400)
raise AppError(
code='CASDOOR_ADD_USER_FAILED',
message='Failed to create user in authentication system. Please try again or contact the administrator.',
http_status=502,
details={'technical': msg_text or str(source or '')[:300]},
)
def raise_update_user_error(source) -> None:
"""将 Casdoor update-user 失败映射为稳定业务错误码。"""
data = extract_error_payload(source)
msg_text = clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
lowered = (msg_text or str(source or '')).lower()
if is_user_missing_error(lowered):
raise_user_not_in_idp(source)
if is_user_exists_error(lowered) or ('email' in lowered and 'already' in lowered):
raise ConflictError(
'Email already exists in Casdoor',
code='USER.EMAIL_EXISTS',
details={'field': 'email', 'technical': msg_text},
)
raise AppError(
code='CASDOOR_UPDATE_USER_FAILED',
message='Failed to update user in authentication system. Please try again or contact the administrator.',
http_status=502,
details={'technical': msg_text or str(source or '')[:300]},
)
def raise_set_password_error(source) -> None:
"""将 Casdoor set-password 失败映射为稳定业务错误码。"""
data = extract_error_payload(source)
msg_text = clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
lowered = (msg_text or str(source or '')).lower()
if is_password_error(lowered) or 'old password' in lowered or 'current password' in lowered:
raise AppError(code='CASDOOR_INVALID_CREDENTIALS', message='Incorrect current password', http_status=401)
if any(token in lowered for token in ('too short', 'too weak', 'password policy', 'at least')):
raise AppError(code='CASDOOR_PASSWORD_POLICY', message='New password does not meet security requirements', http_status=400)
if is_user_missing_error(lowered):
raise_user_not_in_idp(source)
raise AppError(
code='CASDOOR_SET_PASSWORD_FAILED',
message='Failed to change password. Please try again or contact the administrator.',
http_status=502,
details={'technical': msg_text or str(source)[:300]},
)
def build_user_profile_payload(
*,
username: str,
email: str,
employee_id: str | None = None,
real_name=None,
phone_number=None,
status='active',
department=None,
) -> dict[str, Any]:
"""组装 Casdoor 用户资料字段,并将 HXOPS 工号写入 Casdoor 自定义属性。"""
payload: dict[str, Any] = {
'owner': casdoor_user_owner(),
'name': username,
'email': email or '',
'displayName': clean_str(real_name) or username,
'realName': clean_str(real_name) or '',
'phone': clean_str(phone_number) or '',
'isForbidden': clean_str(status) not in (None, 'active'),
}
department_value = clean_str(department)
if department_value:
payload['affiliation'] = department_value
employee_id_value = clean_str(employee_id)
if employee_id_value:
# Casdoor 将扩展资料放入 properties;应用需将 employee_id 配置为 userinfo/ID token 可见。
payload['properties'] = {'employee_id': employee_id_value}
return payload
def build_user_payload(
*,
username: str,
password: str,
email: str,
employee_id: str | None = None,
real_name=None,
phone_number=None,
status='active',
department=None,
) -> dict[str, Any]:
"""组装 Casdoor add-user 请求体,并只在创建场景附加明文密码。"""
payload = build_user_profile_payload(
username=username,
employee_id=employee_id,
email=email,
real_name=real_name,
phone_number=phone_number,
status=status,
department=department,
)
payload['password'] = password
return payload
def _management_config() -> tuple[str, str, str, int]:
"""读取 Casdoor 管理 API 配置,返回地址、凭据和 HTTP 超时。"""
base = str(current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/')
client_id = str(current_app.config.get('CASDOOR_CLIENT_ID') or '')
client_secret = str(current_app.config.get('CASDOOR_CLIENT_SECRET') or '')
timeout = max(1, int(current_app.config.get('CASDOOR_HTTP_TIMEOUT_SECONDS') or 8))
if not base or not client_id or not client_secret:
raise RuntimeError('Casdoor is not configured')
return base, client_id, client_secret, timeout
def casdoor_add_user(user_payload: dict[str, Any]) -> None:
"""调用 Casdoor `/api/add-user` 创建 IdP 用户。"""
base, client_id, client_secret, timeout = _management_config()
response = requests.post(
f'{base}/api/add-user',
json=user_payload,
auth=(client_id, client_secret),
timeout=timeout,
)
try:
data = response.json() or {}
except ValueError as exc:
raise RuntimeError(f'Casdoor add-user failed: HTTP {response.status_code} {response.text[:200]}') from exc
if data.get('status') != 'ok':
raise_add_user_error(data)
def casdoor_update_user(user_payload: dict[str, Any]) -> None:
"""调用 Casdoor `/api/update-user` 更新 IdP 用户资料。"""
base, client_id, client_secret, timeout = _management_config()
response = requests.post(
f'{base}/api/update-user',
json=user_payload,
auth=(client_id, client_secret),
timeout=timeout,
)
try:
data = response.json() or {}
except ValueError as exc:
raise RuntimeError(f'Casdoor update-user failed: HTTP {response.status_code} {response.text[:200]}') from exc
if data.get('status') != 'ok':
raise_update_user_error(data)
def casdoor_set_password(user_owner: str, user_name: str, old_password: str, new_password: str) -> None:
"""调用 Casdoor `/api/set-password` 修改或由管理员覆盖用户密码。"""
base, client_id, client_secret, timeout = _management_config()
response = requests.post(
f'{base}/api/set-password',
files={
'userOwner': (None, user_owner),
'userName': (None, user_name),
'oldPassword': (None, old_password),
'newPassword': (None, new_password),
},
auth=(client_id, client_secret),
timeout=timeout,
)
try:
data = response.json() or {}
except ValueError as exc:
raise RuntimeError(f'Casdoor set-password failed: HTTP {response.status_code} {response.text[:200]}') from exc
if data.get('status') != 'ok':
raise_set_password_error(data)
def sync_create_user(
*,
username: str,
password: str,
email: str,
employee_id: str | None = None,
real_name=None,
phone_number=None,
status='active',
department=None,
add_user: AddUserOperation | None = None,
) -> None:
"""管理端创建 HXOPS 用户时同步 Casdoor;未配置 IdP 时保持原有跳过行为。"""
if not is_casdoor_configured():
return
payload = build_user_payload(
username=username,
password=password,
employee_id=employee_id,
email=email,
real_name=real_name,
phone_number=phone_number,
status=status,
department=department,
)
(add_user or casdoor_add_user)(payload)
def sync_admin_set_password(
user: User,
new_password: str,
*,
set_password: SetPasswordOperation | None = None,
) -> None:
"""管理端无旧密码重设 Casdoor 密码,并将缺失用户转换为稳定错误。"""
if not is_casdoor_configured():
return
try:
(set_password or casdoor_set_password)(casdoor_user_owner(), user.username, '', new_password)
except RuntimeError as exc:
if is_user_missing_error(str(exc)):
raise_user_not_in_idp(exc)
raise_set_password_error(exc)
def sync_update_user(
user: User,
*,
new_password: str | None = None,
set_password: SetPasswordOperation | None = None,
add_user: AddUserOperation | None = None,
) -> None:
"""同步管理端改密;IdP 缺失账号时用新密码补建,资料编辑仍不主动同步。"""
if not is_casdoor_configured() or not new_password:
return
try:
sync_admin_set_password(user, new_password, set_password=set_password)
except AppError as exc:
if exc.code != 'CASDOOR_USER_NOT_IN_IDP':
raise
sync_create_user(
username=user.username,
password=new_password,
employee_id=user.employee_id,
email=user.email,
real_name=user.real_name,
phone_number=user.phone_number,
status=user.status,
department=user.department,
add_user=add_user,
)
@@ -0,0 +1,196 @@
"""
backend/app/services/auth/hxops/login_service.py
用途:统一编排 HXOPS 的 Casdoor 密码登录、授权码登录和刷新流程。
依赖:Casdoor token/identity 公共模块、HXOPS 用户映射、HXOPS API Token。
逻辑:Casdoor token -> claims -> AuthIdentity -> HXOPS User -> 本地 API JWT;路由仅负责参数和事务边界。
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Callable
from flask import current_app
from app.core.auth.jwt import _decode_jwt
from app.core.errors import AppError
from app.models import User
from app.services.auth.casdoor.client import CasdoorTokenResult
from app.services.auth.casdoor.identity import identity_from_claims
from app.services.auth.common import AuthIdentity, IdentityValidationError
from .session_token import issue_hxops_access_token
from .user_resolver import HxopsIdentityMappingError, resolve_hxops_user
TokenOperation = Callable[..., CasdoorTokenResult | dict[str, Any]]
UserinfoOperation = Callable[[str], dict[str, Any]]
AuditOperation = Callable[..., None]
@dataclass(frozen=True)
class LoginResult:
"""HXOPS 登录接口所需的用户、Token 和原响应有效期数据。"""
user: User
identity: AuthIdentity
access_token: str
refresh_token: str | None
id_token: str | None
token_type: str
expires_in: int
def login_payload(self) -> dict[str, Any]:
"""生成与现有 password/code 登录接口完全一致的扁平响应。"""
return {
'id': self.user.id,
'username': self.user.username,
'role': self.user.role,
'default_agent_id': self.user.default_agent_id,
'feature_permissions': self.user.get_feature_permissions(),
'source': 'casdoor',
'access_token': self.access_token,
'refresh_token': self.refresh_token,
'id_token': self.id_token,
'token_type': self.token_type,
'expires_in': self.expires_in,
}
def refresh_payload(self) -> dict[str, Any]:
"""生成与现有 refresh 接口完全一致的 Token 响应。"""
return {
'access_token': self.access_token,
'refresh_token': self.refresh_token,
'id_token': self.id_token,
'token_type': self.token_type,
'expires_in': self.expires_in,
}
def _normalize_token_result(source: CasdoorTokenResult | dict[str, Any]) -> CasdoorTokenResult:
"""兼容重构期间旧字典替身和新的 CasdoorTokenResult。"""
if isinstance(source, CasdoorTokenResult):
return source
data = dict(source or {})
access_token = str(data.get('access_token') or '')
if not access_token:
raise AppError(code='CASDOOR_AUTH_FAILED', message='Authentication failed, please try again', http_status=401)
return CasdoorTokenResult(
access_token=access_token,
refresh_token=str(data['refresh_token']) if data.get('refresh_token') else None,
id_token=str(data['id_token']) if data.get('id_token') else None,
token_type=str(data.get('token_type') or 'Bearer'),
expires_in=int(data.get('expires_in') or 3600),
raw=data,
)
class HxopsLoginService:
"""把公共 Casdoor 能力与 HXOPS 用户、审计和 API JWT 组合起来。"""
def __init__(
self,
*,
password_login: TokenOperation,
authorization_code_login: TokenOperation,
refresh_token: TokenOperation,
userinfo: UserinfoOperation,
write_login_audit: AuditOperation | None = None,
decode_id_token: Callable[[str], dict[str, Any]] = _decode_jwt,
):
"""
注入 Casdoor 操作和可选审计函数,便于路由兼容与单元测试。
Args:
password_login: 执行 password grant 的函数。
authorization_code_login: 执行 code grant 的函数。
refresh_token: 执行 refresh grant 的函数。
userinfo: 读取 Casdoor userinfo 的函数。
write_login_audit: HXOPS 登录审计函数;公共模块不感知请求对象。
decode_id_token: 现有 Casdoor JWKS 验证函数。
"""
self._password_login = password_login
self._authorization_code_login = authorization_code_login
self._refresh_token = refresh_token
self._userinfo = userinfo
self._write_login_audit = write_login_audit
self._decode_id_token = decode_id_token
def _identity_from_token(self, token: CasdoorTokenResult, *, prefer_id_token: bool) -> AuthIdentity:
"""优先验证 ID token,失败或缺失时回退 HTTPS userinfo。"""
claims: dict[str, Any] | None = None
if prefer_id_token and token.id_token:
try:
claims = self._decode_id_token(token.id_token)
except Exception:
claims = None
if claims is None:
claims = self._userinfo(token.access_token)
try:
return identity_from_claims(
claims,
expected_issuer=str(current_app.config.get('AUTH_JWT_ISSUER') or ''),
)
except IdentityValidationError as exc:
current_app.logger.warning(
'[casdoor_login] invalid stable identity reason=%s claim_keys=%s',
str(exc),
sorted(str(key) for key in claims.keys()),
)
raise AppError(
code='AUTH.CASDOOR_IDENTITY_INVALID',
message='Casdoor identity is missing issuer or subject',
http_status=401,
) from exc
def _complete_login(
self,
token_source: CasdoorTokenResult | dict[str, Any],
*,
prefer_id_token: bool,
fallback_refresh_token: str | None = None,
audit_success: bool = False,
) -> LoginResult:
"""完成身份解析、本地用户映射和 HXOPS API Token 签发。"""
token = _normalize_token_result(token_source)
identity = self._identity_from_token(token, prefer_id_token=prefer_id_token)
try:
user = resolve_hxops_user(identity)
except HxopsIdentityMappingError as exc:
raise AppError(code=exc.code, message=str(exc), http_status=exc.status) from exc
if audit_success and self._write_login_audit:
self._write_login_audit('casdoor', 'success', user=user)
return LoginResult(
user=user,
identity=identity,
access_token=issue_hxops_access_token(user, identity),
refresh_token=token.refresh_token or fallback_refresh_token,
id_token=token.id_token,
token_type=token.token_type,
expires_in=token.expires_in,
)
def password(self, username: str, password: str) -> LoginResult:
"""通过 Casdoor password grant 登录 HXOPS。"""
return self._complete_login(
self._password_login(username, password),
prefer_id_token=True,
audit_success=True,
)
def authorization_code(self, code: str, redirect_uri: str) -> LoginResult:
"""通过 Casdoor authorization code 登录 HXOPS。"""
return self._complete_login(
self._authorization_code_login(code, redirect_uri),
prefer_id_token=True,
audit_success=True,
)
def refresh(self, refresh_token: str) -> LoginResult:
"""刷新 Casdoor token 后重新确认身份并签发 HXOPS API JWT。"""
return self._complete_login(
self._refresh_token(refresh_token),
prefer_id_token=False,
fallback_refresh_token=refresh_token,
)
@@ -0,0 +1,31 @@
"""
backend/app/services/auth/hxops/session_token.py
用途:为 HXOPS 本地 API 签发包含 Casdoor 稳定身份引用的会话 JWT。
依赖:User、AuthIdentity、app.core.auth.jwt 现有签发函数。
逻辑:保留现有 HS256 claims 和有效期;只调整调用边界,不改变 Token 契约。
"""
from __future__ import annotations
from app.core.auth.jwt import issue_local_access_token
from app.models import User
from app.services.auth.common import AuthIdentity
def issue_hxops_access_token(user: User, identity: AuthIdentity | None = None) -> str:
"""
签发 HXOPS API 会话 JWT,保持重构前 claims 完全兼容。
Args:
user: 已映射并检查 active 的 HXOPS 用户。
identity: 可选 Casdoor 稳定身份;存在时写入 casdoor_iss/casdoor_sub。
Returns:
由 HXOPS SECRET_KEY 签名的本站 Bearer Token。
"""
return issue_local_access_token(
user,
casdoor_issuer=identity.issuer if identity else None,
casdoor_subject=identity.subject if identity else None,
)
@@ -0,0 +1,84 @@
"""
backend/app/services/auth/hxops/user_resolver.py
用途:将统一 AuthIdentity 按工号映射为 HXOPS 本地 User。
依赖:Flask 日志、SQLAlchemy session、User、AuthIdentity。
逻辑:Casdoor 工号优先;用户名作为当前“用户名即工号”的过渡兼容,不使用邮箱或手机号。
"""
from __future__ import annotations
from flask import current_app
from app.extensions import db
from app.models import User
from app.services.auth.common import AuthIdentity
class HxopsIdentityMappingError(Exception):
"""HXOPS 本地用户无法映射或状态不允许登录。"""
def __init__(self, message: str, *, code: str, status: int):
super().__init__(message)
self.code = code
self.status = status
def resolve_hxops_user(identity: AuthIdentity) -> User:
"""
按工号优先规则将认证身份映射到 HXOPS 用户。
核心逻辑:优先使用 Casdoor employee_id;若其缺失,则将当前用户名作为工号
查找本地 employee_id,最后才按 username 兼容历史数据。邮箱和手机号不参与认证
匹配。若工号与用户名分别命中不同用户,拒绝登录以防错误账号关联。
Args:
identity: 已验证 Casdoor issuer/subject 的统一身份;employee_id 是首选匹配键。
Returns:
状态为 active 的 HXOPS User。
Raises:
HxopsIdentityMappingError: 用户未同步、身份字段冲突或账号已禁用。
"""
current_app.logger.info(
'[casdoor_login] identity employee_id=%s username=%s subject=%s',
identity.employee_id,
identity.username,
identity.subject,
)
# [STEP 1] 工号是当前产品用户的主映射键;Casdoor 未提供时用户名即工号。
employee_id = str(identity.employee_id or identity.username or '').strip()
employee_user = None
if employee_id:
employee_user = db.session.query(User).filter_by(employee_id=employee_id).first()
# [STEP 2] username 仅保留给尚未补齐 employee_id 的历史本地账号。
username_user = db.session.query(User).filter_by(username=identity.username).first()
if employee_user is not None and username_user is not None and employee_user.id != username_user.id:
current_app.logger.warning(
'[casdoor_login] identity_mapping_conflict employee_id=%s employee_user_id=%s '
'username=%s username_user_id=%s subject=%s',
employee_id,
employee_user.id,
identity.username,
username_user.id,
identity.subject,
)
raise HxopsIdentityMappingError(
'Casdoor employee ID and username map to different local accounts. Please contact admin.',
code='CASDOOR_IDENTITY_CONFLICT',
status=403,
)
user = employee_user or username_user
if user is None:
raise HxopsIdentityMappingError(
'No local user matched Casdoor identity. Please contact admin to provision account.',
code='CASDOOR_USER_NOT_FOUND',
status=403,
)
if user.status != 'active':
raise HxopsIdentityMappingError('Account is disabled', code='ACCOUNT_DISABLED', status=403)
return user
+18
View File
@@ -0,0 +1,18 @@
"""
backend/app/services/auth/sso/__init__.py
Purpose: Export the reusable HXOPS-to-peer-service SSO signing surface.
Dependencies: application registry and assertion signing modules.
Flow: API routes import this package; peer services consume the documented assertion/JWKS contract.
"""
from .application_registry import SsoApplication, get_application, list_applications
from .assertion_service import build_jwks, issue_assertion
__all__ = [
'SsoApplication',
'build_jwks',
'get_application',
'issue_assertion',
'list_applications',
]
@@ -0,0 +1,149 @@
"""
backend/app/services/auth/sso/application_registry.py
Purpose: Parse and validate peer services allowed to receive HXOPS SSO assertions.
Dependencies: Flask configuration, JSON, URL parsing, and AppError.
Flow: Assertion routes resolve app metadata here so browser-provided callback URLs are never trusted.
"""
from __future__ import annotations
import json
import re
from dataclasses import dataclass
from urllib.parse import urlparse
from flask import current_app
from app.core.errors import AppError, NotFoundError
_APP_KEY_RE = re.compile(r'^[a-z0-9][a-z0-9_-]{1,63}$')
@dataclass(frozen=True)
class SsoApplication:
"""Registered peer-service metadata safe for server-controlled SSO routing."""
key: str
display_name: str
login_url: str
callback_url: str
audience: str
enabled: bool = True
def public_payload(self) -> dict[str, str]:
"""Return fields safe for authenticated HXOPS navigation components."""
return {
'key': self.key,
'display_name': self.display_name,
'login_url': self.login_url,
}
def _validate_http_url(value: str, *, field: str) -> str:
"""
Validate an application URL from server configuration.
Args:
value: Absolute browser or callback URL.
field: Configuration field name used in diagnostics.
Returns:
Normalized URL without surrounding whitespace.
Raises:
AppError: URL is missing, malformed, or uses HTTP outside development/testing.
"""
normalized = str(value or '').strip()
parsed = urlparse(normalized)
if parsed.scheme not in {'http', 'https'} or not parsed.netloc:
raise AppError(
code='AUTH.SSO_CONFIG_ERROR',
message=f'Invalid SSO application {field}',
http_status=503,
)
env_name = str(current_app.config.get('ENV_NAME') or current_app.config.get('FLASK_ENV') or '').lower()
if parsed.scheme != 'https' and env_name not in {'dev', 'development', 'test', 'testing'}:
raise AppError(
code='AUTH.SSO_CONFIG_ERROR',
message=f'SSO application {field} must use HTTPS',
http_status=503,
)
return normalized
def list_applications() -> list[SsoApplication]:
"""
Parse the enabled SSO application registry from ``SSO_APPS_JSON``.
Returns:
Valid enabled application definitions.
Raises:
AppError: Configuration is invalid. Fail closed to avoid open redirects.
"""
if not bool(current_app.config.get('SSO_ENABLED', False)):
return []
raw = current_app.config.get('SSO_APPS_JSON') or '[]'
try:
items = json.loads(raw) if isinstance(raw, str) else raw
except (TypeError, ValueError) as exc:
raise AppError(
code='AUTH.SSO_CONFIG_ERROR',
message='SSO application registry is invalid',
http_status=503,
) from exc
if not isinstance(items, list):
raise AppError(
code='AUTH.SSO_CONFIG_ERROR',
message='SSO application registry must be a JSON array',
http_status=503,
)
applications: list[SsoApplication] = []
seen_keys: set[str] = set()
seen_audiences: set[str] = set()
for item in items:
if not isinstance(item, dict) or not bool(item.get('enabled', True)):
continue
key = str(item.get('key') or '').strip().lower()
audience = str(item.get('audience') or key).strip()
display_name = str(item.get('display_name') or key).strip()
if (
not _APP_KEY_RE.fullmatch(key)
or not _APP_KEY_RE.fullmatch(audience.lower())
or audience != audience.lower()
or not display_name
):
raise AppError(
code='AUTH.SSO_CONFIG_ERROR',
message='SSO application identity configuration is incomplete',
http_status=503,
)
if key in seen_keys or audience in seen_audiences:
raise AppError(
code='AUTH.SSO_CONFIG_ERROR',
message='SSO application keys and audiences must be unique',
http_status=503,
)
applications.append(SsoApplication(
key=key,
display_name=display_name,
login_url=_validate_http_url(item.get('login_url'), field='login_url'),
callback_url=_validate_http_url(item.get('callback_url'), field='callback_url'),
audience=audience,
enabled=True,
))
seen_keys.add(key)
seen_audiences.add(audience)
return applications
def get_application(app_key: str) -> SsoApplication:
"""Resolve one enabled application by its server-controlled key."""
normalized = str(app_key or '').strip().lower()
for application in list_applications():
if application.key == normalized:
return application
raise NotFoundError('SSO application not found', code='AUTH.SSO_APP_NOT_FOUND')
@@ -0,0 +1,265 @@
"""
backend/app/services/auth/sso/assertion_service.py
Purpose: Sign peer-service-specific short-lived login assertions and publish their verification key.
Dependencies: application registry, PyJWT, cryptography, Flask configuration, and User.
Flow: The SSO API authenticates an HXOPS user, this module signs an audience-bound JWT, and peers verify it through JWKS.
"""
from __future__ import annotations
import base64
import json
import secrets
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any
from urllib.parse import urlparse
import jwt
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from flask import current_app
from app.core.errors import AppError, ValidationError
from app.models import User
from app.services.auth.casdoor.identity import identity_from_claims
from app.services.auth.common import IdentityValidationError
from .application_registry import get_application
def _config_error(message: str) -> AppError:
"""Build a fail-closed SSO configuration error without leaking key material."""
return AppError(code='AUTH.SSO_CONFIG_ERROR', message=message, http_status=503)
def _read_signing_key() -> rsa.RSAPrivateKey:
"""
Load the configured RSA private key used only for product SSO assertions.
Returns:
Parsed RSA private key.
Raises:
AppError: The path is absent, unreadable, invalid, or not an RSA private key.
"""
raw_path = str(current_app.config.get('SSO_PRIVATE_KEY_PATH') or '').strip()
if not raw_path:
raise _config_error('SSO signing private key is not configured')
try:
key_bytes = Path(raw_path).read_bytes()
private_key = serialization.load_pem_private_key(key_bytes, password=None)
except (OSError, ValueError, TypeError) as exc:
raise _config_error('SSO signing private key cannot be loaded') from exc
if not isinstance(private_key, rsa.RSAPrivateKey):
raise _config_error('SSO signing key must be an RSA private key')
return private_key
def _issuer() -> str:
"""Return the configured absolute SSO issuer after environment-aware URL validation."""
issuer = str(current_app.config.get('SSO_ISSUER') or '').strip().rstrip('/')
parsed = urlparse(issuer)
if parsed.scheme not in {'http', 'https'} or not parsed.netloc:
raise _config_error('SSO issuer must be an absolute URL')
env_name = str(current_app.config.get('ENV_NAME') or current_app.config.get('FLASK_ENV') or '').lower()
if parsed.scheme != 'https' and env_name not in {'dev', 'development', 'test', 'testing'}:
raise _config_error('SSO issuer must use HTTPS')
return issuer
def _ttl_seconds() -> int:
"""Validate the short assertion lifetime; values outside 10-60 seconds fail closed."""
try:
ttl_seconds = int(current_app.config.get('SSO_ASSERTION_TTL_SECONDS') or 60)
except (TypeError, ValueError) as exc:
raise _config_error('SSO assertion TTL is invalid') from exc
if ttl_seconds < 10 or ttl_seconds > 60:
raise _config_error('SSO assertion TTL must be between 10 and 60 seconds')
return ttl_seconds
def _algorithm() -> str:
"""Enforce the single supported asymmetric signing algorithm and reject downgrade configuration."""
algorithm = str(current_app.config.get('SSO_SIGNING_ALGORITHM') or 'RS256').strip().upper()
if algorithm != 'RS256':
raise _config_error('SSO signing algorithm must be RS256')
return algorithm
def _key_id() -> str:
"""Return the stable public key identifier embedded in JWT and JWKS metadata."""
key_id = str(current_app.config.get('SSO_SIGNING_KEY_ID') or '').strip()
if not key_id or len(key_id) > 128:
raise _config_error('SSO signing key ID is not configured')
return key_id
def _identity_claims(user: User, claims: dict[str, Any]) -> dict[str, Any]:
"""
Build the portable Casdoor identity claims without HXOPS business permissions.
Args:
user: Active HXOPS user mapped from the authenticated Casdoor identity.
claims: Verified HXOPS API JWT claims containing ``casdoor_iss/casdoor_sub``.
Returns:
Stable identity plus mutable display attributes safe for peer-service user mapping.
"""
expected_issuer = str(current_app.config.get('AUTH_JWT_ISSUER') or '').strip()
try:
identity = identity_from_claims({
'iss': claims.get('casdoor_iss'),
'sub': claims.get('casdoor_sub'),
'preferred_username': user.username,
'name': user.real_name or user.username,
'email': user.email,
'phone_number': user.phone_number,
'employee_id': user.employee_id,
'department': user.department,
}, expected_issuer=expected_issuer)
except IdentityValidationError as exc:
raise AppError(
code='AUTH.SSO_IDENTITY_UNSUPPORTED',
message='Current login is not backed by a Casdoor identity',
http_status=403,
) from exc
return {
'sub': identity.subject,
'identity_issuer': identity.issuer,
'preferred_username': identity.username,
'name': identity.display_name,
'email': identity.email,
'phone_number': identity.phone_number,
'employee_id': identity.employee_id,
'department': identity.department,
}
def issue_assertion(*, app_key: str, user: User, claims: dict[str, Any], state: Any) -> dict[str, Any]:
"""
Sign a peer-service-specific login assertion for an active HXOPS user.
Args:
app_key: Server-registered target service key.
user: Current active HXOPS user.
claims: Verified HXOPS API JWT claims with Casdoor identity references.
state: Opaque signed state created by the peer service and returned unchanged.
Returns:
Registered callback URL, RS256 assertion, original state, and expiry seconds.
"""
if user.status != 'active':
raise AppError(code='AUTH.ACCOUNT_DISABLED', message='Account is disabled', http_status=403)
normalized_state = str(state or '').strip()
if not normalized_state or len(normalized_state) > 4096:
raise ValidationError('state is required and must not exceed 4096 characters')
application = get_application(app_key)
ttl_seconds = _ttl_seconds()
now = datetime.now(timezone.utc)
payload = {
'iss': _issuer(),
'aud': application.audience,
**_identity_claims(user, claims),
'iat': int(now.timestamp()),
'nbf': int((now - timedelta(seconds=5)).timestamp()),
'exp': int((now + timedelta(seconds=ttl_seconds)).timestamp()),
'jti': secrets.token_urlsafe(24),
}
try:
assertion = jwt.encode(
payload,
_read_signing_key(),
algorithm=_algorithm(),
headers={'kid': _key_id(), 'typ': 'JWT'},
)
except AppError:
raise
except Exception as exc:
current_app.logger.exception('[sso] failed to sign assertion app=%s', application.key)
raise AppError(
code='AUTH.SSO_ASSERTION_ISSUE_FAILED',
message='Failed to issue an SSO assertion',
http_status=503,
retryable=True,
) from exc
current_app.logger.info(
'[sso] assertion issued app=%s user_id=%s subject=%s ttl=%s',
application.key,
user.id,
payload['sub'],
ttl_seconds,
)
return {
'post_url': application.callback_url,
'assertion': assertion,
'state': normalized_state,
'expires_in': ttl_seconds,
}
def _base64url_uint(value: int) -> str:
"""Encode an RSA integer using the unpadded base64url form required by JWK."""
raw = value.to_bytes(max(1, (value.bit_length() + 7) // 8), 'big')
return base64.urlsafe_b64encode(raw).rstrip(b'=').decode('ascii')
def _public_jwk(public_key: rsa.RSAPublicKey, *, key_id: str) -> dict[str, str]:
"""Convert one trusted RSA public key to the minimal signing JWK contract."""
numbers = public_key.public_numbers()
return {
'kty': 'RSA',
'kid': key_id,
'use': 'sig',
'alg': _algorithm(),
'n': _base64url_uint(numbers.n),
'e': _base64url_uint(numbers.e),
}
def _additional_public_jwks(active_key_id: str) -> list[dict[str, str]]:
"""
Load verification-only public keys retained during a signing-key rotation window.
Returns:
Additional JWK entries configured as ``[{"kid", "public_key_path"}]``.
Raises:
AppError: JSON, key IDs, paths, or public key material are invalid.
"""
raw = current_app.config.get('SSO_ADDITIONAL_PUBLIC_KEYS_JSON') or '[]'
try:
items = json.loads(raw) if isinstance(raw, str) else raw
except (TypeError, ValueError) as exc:
raise _config_error('Additional SSO public keys configuration is invalid') from exc
if not isinstance(items, list):
raise _config_error('Additional SSO public keys must be a JSON array')
jwks: list[dict[str, str]] = []
seen_key_ids = {active_key_id}
for item in items:
if not isinstance(item, dict):
raise _config_error('Additional SSO public key entry is invalid')
key_id = str(item.get('kid') or '').strip()
path = str(item.get('public_key_path') or '').strip()
if not key_id or len(key_id) > 128 or not path or key_id in seen_key_ids:
raise _config_error('Additional SSO public key identity is invalid or duplicated')
try:
public_key = serialization.load_pem_public_key(Path(path).read_bytes())
except (OSError, ValueError, TypeError) as exc:
raise _config_error('Additional SSO public key cannot be loaded') from exc
if not isinstance(public_key, rsa.RSAPublicKey):
raise _config_error('Additional SSO public key must be RSA')
jwks.append(_public_jwk(public_key, key_id=key_id))
seen_key_ids.add(key_id)
return jwks
def build_jwks() -> dict[str, list[dict[str, str]]]:
"""Build JWKS with the active signing key plus verification-only rotation keys."""
active_key_id = _key_id()
active_jwk = _public_jwk(_read_signing_key().public_key(), key_id=active_key_id)
return {'keys': [active_jwk, *_additional_public_jwks(active_key_id)]}
@@ -560,12 +560,40 @@
"type": "string",
"nullable": true,
"description": "HXOPS 会话 ID;可与 sys.conversation_id 二选一,优先显式传入"
},
"mode": {
"type": "string",
"nullable": true,
"enum": ["incremental", "force_all", "single"],
"description": "【Dify 推荐】运行模式(立账凭证检核读取;文件检核忽略)。incremental=增量 / force_all=全量 / single=单发票;单发票时须同时填 invoice_no"
},
"invoice_no": {
"type": "string",
"nullable": true,
"description": "【Dify 推荐】mode=single 时必填的发票号;来自意图识别.invoice_no"
},
"run_options": {
"type": "object",
"nullable": true,
"description": "可选嵌套写法(部分 Dify 版本不展示对象字段;优先用顶层 mode/invoice_no)。mode=incremental|force_all|single;single 时须带 invoice_no",
"properties": {
"mode": {
"type": "string",
"enum": ["incremental", "force_all", "single"],
"default": "incremental"
},
"invoice_no": {
"type": "string",
"nullable": true,
"description": "mode=single 时必填的发票号"
}
}
}
},
"required": [
"task_id"
],
"description": "Chatflow Tool 节点绑定 task_id(Integer,来源 解析运行态上下文.task_id_int)、hxops_turn_id(经 agent_runtime_context 解析后传入);user_message 用于展示与兼容兜底"
"description": "Chatflow Tool 节点绑定 task_id(Integer,来源 解析运行态上下文.task_id_int)、hxops_turn_id(经 agent_runtime_context 解析后传入);立账凭证检核用顶层 mode/invoice_no(Dify 友好)或嵌套 run_options"
},
"RunCheckSuccessResponse": {
"type": "object",
+15 -6
View File
@@ -59,7 +59,7 @@ class HRLeaveSQLServerService:
_PERSON_NAME_PATTERNS = (
r"(?:查询|查下|查一下|帮我查|帮忙查|看看|核对|想知道|统计).{0,4}(?P<name>[\u4e00-\u9fa5]{2,4})(?:的)?(?:年假|育儿假|假期|休假)",
r"(?P<name>[\u4e00-\u9fa5]{2,4})(?:的)?(?:年假|育儿假|假期|休假).{0,8}(?:还剩|还有|剩余|可休|已休|未休|多少|情况|记录|明细|查询)",
r"(?P<name>[\u4e00-\u9fa5]{2,4}).{0,6}(?:还剩|还有|剩余|可休|已休|未休|多少).{0,6}(?:年假|育儿假|假期|休假)",
r"(?P<name>[\u4e00-\u9fa5]{2,4}?).{0,6}(?:还剩|还有|剩余|可休|已休|未休|多少).{0,6}(?:年假|育儿假|假期|休假)",
)
_PERSON_NAME_STOPWORDS = {
"我的",
@@ -92,6 +92,10 @@ class HRLeaveSQLServerService:
"部门",
}
_OTHER_PERSON_QUERY_MESSAGE = "暂时不支持查询其他人假期"
_SALARY_CONSULTATION_PATTERN = re.compile(
r"(?:请假|休假|年假|事假|病假).{0,12}(?:薪资|工资|薪酬|扣薪|扣钱|扣款|扣除|多少钱|福利|计算|公式)"
r"|(?:薪资|工资|薪酬|扣薪|扣钱|扣款|扣除|多少钱|福利|计算公式).{0,12}(?:请假|休假|年假|事假|病假)"
)
@classmethod
def supports(cls, query: str) -> bool:
@@ -104,6 +108,10 @@ class HRLeaveSQLServerService:
text = (query or "").strip()
if not text:
return False
# [STEP 1] 薪资/扣款是制度计算问答,必须交给 FAQ/Dify,不能进入个人假期余额 SQL。
# [PROMPT_UPDATE] 公式、适用条件和计薪口径由知识库原文负责,后端只做路由保护。
if cls._SALARY_CONSULTATION_PATTERN.search(text):
return False
if not any(keyword in text for keyword in cls._LEAVE_KEYWORDS):
return False
if any(keyword in text for keyword in cls._PROCESS_KEYWORDS):
@@ -129,10 +137,10 @@ class HRLeaveSQLServerService:
text = (query or "").strip()
if not text:
return False
if any(keyword in text for keyword in cls._SELF_KEYWORDS):
return False
if any(re.search(pattern, text) for pattern in cls._OTHER_PERSON_PRONOUN_PATTERNS):
return True
if any(keyword in text for keyword in cls._SELF_KEYWORDS):
return False
return bool(cls._extract_candidate_person_names(text))
@classmethod
@@ -170,10 +178,10 @@ class HRLeaveSQLServerService:
text = (query or "").strip()
if not text:
return False
if any(keyword in text for keyword in cls._SELF_KEYWORDS):
return False
if any(re.search(pattern, text) for pattern in cls._OTHER_PERSON_PRONOUN_PATTERNS):
return True
if any(keyword in text for keyword in cls._SELF_KEYWORDS):
return False
self_identifiers = {
str(getattr(user, "real_name", None) or "").strip(),
str(getattr(user, "username", None) or "").strip(),
@@ -181,7 +189,8 @@ class HRLeaveSQLServerService:
}
self_identifiers = {value for value in self_identifiers if value}
for candidate in cls._extract_candidate_person_names(text):
if candidate not in self_identifiers:
normalized_candidate = candidate.rstrip("的")
if normalized_candidate not in self_identifiers:
return True
return False
+48 -4
View File
@@ -1,5 +1,9 @@
"""
Integration API client for resolving original source-file download links.
backend/app/services/integration_api.py
用途:解析 Dify dataset/document 对应的源文件下载链接(本地 KB 映射 + Dify 签名 URL 兜底)。
依赖:Flask request/current_app、requests、Kb* 模型。
逻辑:chat.resolve_source_file / 预览代理调用本服务;本地无可读文件时回退 Dify download。
"""
from datetime import datetime, timedelta, timezone
from typing import Any, Dict, List, Optional, Tuple
@@ -223,8 +227,14 @@ class IntegrationApiService:
@staticmethod
def _lookup_local_db(dataset_id: str, remote_document_id: str) -> Optional[Dict[str, Any]]:
"""
从本地 KbDifySyncRecord 反查可预览下载链接。
核心逻辑:优先返回磁盘上存在的源文件;缺失时回退清洗 Markdown;
两者皆无则返回 None,让上层继续走 Dify 签名下载兜底。
"""
if not has_app_context():
return None
from pathlib import Path
from app import db
from app.models import KbDifySyncRecord, KbDocumentVersion, KbDocument
@@ -251,6 +261,30 @@ class IntegrationApiService:
version = record.document_version
document = version.document
def _existing(path_value: str | None):
if not path_value:
return None
raw = Path(str(path_value))
root = Path(current_app.config.get('KB_STORAGE_ROOT')).resolve()
candidate = (raw if raw.is_absolute() else (root / raw)).resolve()
try:
candidate.relative_to(root)
except ValueError:
return None
if candidate.exists() and candidate.is_file():
return candidate
return None
source_path = _existing(version.source_file_path)
markdown_path = _existing(version.cleaned_file_path) or _existing(version.cleaned_preview_path)
if source_path is None and markdown_path is None:
current_app.logger.info(
'[integration-lookup] local mapping found but no readable file document_id=%s version_id=%s',
document.id,
version.id,
)
return None
base_url = IntegrationApiService._request_origin_url()
if not base_url:
explicit = str(current_app.config.get('WECOM_PUBLIC_BASE_URL') or '').strip().rstrip('/')
@@ -276,15 +310,25 @@ class IntegrationApiService:
}
token = jwt.encode(payload, secret, algorithm='HS256')
if source_path is not None:
kind = 'source'
source_filename = version.source_file_name
source_ext = version.source_file_ext
else:
kind = 'md'
stem = Path(str(version.source_file_name or document.title or f'document-{document.id}')).stem
source_filename = f'{stem}.md'
source_ext = 'md'
source_download_url = (
f'{base_url}/api/integration/files/{document.id}/download'
f'?kind=source&version_id={version.id}&token={token}'
f'?kind={kind}&version_id={version.id}&token={token}'
)
return {
"source_download_url": source_download_url,
"source_filename": version.source_file_name,
"source_ext": version.source_file_ext,
"source_filename": source_filename,
"source_ext": source_ext,
"download_url_expires_at": None,
"version_id": version.id,
"document_id": document.id,
@@ -0,0 +1,44 @@
"""
backend/app/services/integration_tool_auth.py
用途:Dify / 集成方 HTTP Tool API 共用鉴权(Bearer 或 X-Integration-Key)。
依赖:Flask current_app、core.errors。
逻辑:file-check / accounting-voucher-check 等 Tool Blueprint before_request 调用;
密钥优先 FILE_CHECK_TOOL_API_KEY,回退 INTEGRATION_API_KEY。
"""
from __future__ import annotations
from flask import current_app, request
from app.core.errors import ServiceUnavailableError, UnauthorizedError
def require_integration_tool_auth() -> None:
"""
校验 Tool API 访问权限。
核心逻辑:Authorization Bearer 与 X-Integration-Key 二选一,值须与配置密钥完全一致。
Raises:
ServiceUnavailableError: 服务端未配置密钥。
UnauthorizedError: 缺少或错误的凭证。
"""
configured = str(
current_app.config.get("FILE_CHECK_TOOL_API_KEY")
or current_app.config.get("INTEGRATION_API_KEY")
or ""
).strip()
if not configured:
raise ServiceUnavailableError(
"FILE_CHECK_TOOL_API_KEY or INTEGRATION_API_KEY is not configured",
code="missing_auth",
)
bearer = str(request.headers.get("Authorization") or "").strip()
api_token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
integration_key = str(request.headers.get("X-Integration-Key") or "").strip()
if configured in {api_token, integration_key}:
return
if not api_token and not integration_key:
raise UnauthorizedError("missing_auth")
raise UnauthorizedError("invalid_auth")
@@ -7,6 +7,7 @@ from __future__ import annotations
from datetime import datetime
import hashlib
import re
import time
from pathlib import Path
import requests
@@ -19,6 +20,8 @@ from app.services.knowledge_cleaning.settings_service import get_kb_dify_setting
_EXCEL_SOURCE_EXTENSIONS = frozenset({'xlsx', 'xls', 'csv'})
_DIFY_INDEXING_SUCCEEDED = frozenset({'completed', 'completed_successfully', 'succeeded', 'success'})
_DIFY_INDEXING_FAILED = frozenset({'error', 'failed', 'failure'})
def _decode_separator(value: str) -> str:
@@ -65,6 +68,9 @@ class KbDifySyncService:
self.segment_chunk_overlap = int(str(settings.get('KB_DIFY_SEGMENT_CHUNK_OVERLAP') or '50'))
self.remove_urls_emails = _as_bool_setting(settings.get('KB_DIFY_REMOVE_URLS'))
self.timeout = 60
# Dify create/update 仅表示已接收文本,索引仍在后台异步执行。
self.indexing_wait_seconds = 60
self.indexing_poll_seconds = 2
def _build_process_rule(self, source_ext: str | None = None) -> dict:
ext = str(source_ext or '').strip().lower().lstrip('.')
@@ -137,9 +143,9 @@ class KbDifySyncService:
'retrieval_model': {
'search_method': self.search_method,
'reranking_enable': False,
'top_k': 3,
'score_threshold_enabled': False,
'score_threshold': None,
'top_k': 5,
'score_threshold_enabled': True,
'score_threshold': 0.25,
},
}
return self._request('POST', '/datasets', json=payload)
@@ -243,6 +249,54 @@ class KbDifySyncService:
def get_document(self, *, dataset_id: str, document_id: str) -> dict:
return self._request('GET', f'/datasets/{dataset_id}/documents/{document_id}')
def wait_for_document_indexing(
self,
*,
dataset_id: str,
document_id: str,
initial_payload: dict | None = None,
) -> dict:
"""
确认 Dify 异步索引的最终结果,禁止把“已受理”当作“已可检索”。
核心逻辑:读取创建/更新响应或文档详情中的 indexing_status,直到 completed 或 error。
超时也按失败处理,避免工作台把仍未可检索的文件标为同步成功。
Args:
dataset_id: Dify Dataset ID,不能为空。
document_id: Dify 文档 ID,不能为空。
initial_payload: create/update 接口的原始响应,可减少一次详情请求。
Returns:
含 indexing_status 和 Dify 文档详情的字典。
Raises:
KbDifySyncError: Dify 索引失败、状态缺失或在限定时间内未完成。
"""
if not dataset_id or not document_id:
raise KbDifySyncError('Dify 文档索引校验缺少 dataset_id 或 document_id')
payload = initial_payload or {}
deadline = time.monotonic() + self.indexing_wait_seconds
last_status = ''
while True:
document = payload.get('document') if isinstance(payload, dict) else None
document = document if isinstance(document, dict) else payload
document = document if isinstance(document, dict) else {}
status = str(document.get('indexing_status') or '').strip().lower()
error = str(document.get('error') or document.get('error_message') or '').strip()
last_status = status or last_status
if status in _DIFY_INDEXING_SUCCEEDED:
return {'indexing_status': status, 'document': document}
if status in _DIFY_INDEXING_FAILED:
raise KbDifySyncError(error or f'Dify 文档索引失败(状态:{status})')
if time.monotonic() >= deadline:
raise KbDifySyncError(
f'Dify 文档索引未在 {self.indexing_wait_seconds} 秒内完成(当前状态:{last_status or "unknown"}),请在 Dify 查看文档错误后重试'
)
time.sleep(self.indexing_poll_seconds)
payload = self.get_document(dataset_id=dataset_id, document_id=document_id)
def delete_document(self, *, dataset_id: str, document_id: str) -> None:
self._request(
'DELETE',
@@ -274,9 +328,30 @@ def _load_sync_text(version: KbDocumentVersion) -> tuple[str, str]:
def _is_remote_document_missing(error_text: str) -> bool:
"""
判断同步记录指向的 Dify 远端文档是否已失效。
Dify 在不同版本中会对已删除或不可访问的文档返回 404/not_found,
也可能返回 400 invalid_param 和 ``Document is not available``。两种结果都表示
不能继续 update-by-text,调用方必须新建远端文档并刷新本地映射。
Args:
error_text: Dify HTTP 异常转换后的完整错误文本。
Returns:
远端文档已失效时返回 True;其他 API 错误返回 False,避免掩盖配置或网络问题。
"""
normalized_error = str(error_text or '').lower()
return (
'404' in error_text
and ('Document not found' in error_text or '"code":"not_found"' in error_text)
('404' in normalized_error and (
'document not found' in normalized_error
or '"code":"not_found"' in normalized_error
))
or (
'400' in normalized_error
and '"code":"invalid_param"' in normalized_error
and 'document is not available' in normalized_error
)
)
@@ -290,7 +365,90 @@ def _resolve_upload_name(version: KbDocumentVersion) -> str:
return f'文档-{version.document_id}'
def _save_sync_record(
*,
version: KbDocumentVersion,
dataset_id: str,
dataset_name: str,
remote_document_id: str,
remote_document_name: str | None,
sync_hash: str,
synced_by_id: int | None,
status: str,
error_message: str | None,
) -> KbDifySyncRecord:
"""
持久化本地到 Dify 的映射及最终索引结果。
核心逻辑:同一版本和远端文档复用记录;成功与失败均保存,
让工作台能展示 Dify 的真实索引状态和原因。
Args:
version: 已上传且归属有效分组的文档版本。
dataset_id: Dify Dataset ID。
remote_document_id: Dify 文档 ID。
status: 本地同步状态,仅传 synced 或 failed。
error_message: Dify 索引失败详情;成功时传 None。
Returns:
已 flush 的 KbDifySyncRecord。
"""
document = version.document
group = document.group
record = (
db.session.query(KbDifySyncRecord)
.filter(
KbDifySyncRecord.document_version_id == version.id,
KbDifySyncRecord.remote_document_id == remote_document_id,
)
.first()
)
if not record:
record = KbDifySyncRecord(
group_id=group.id,
document_id=document.id,
document_version_id=version.id,
dataset_id=dataset_id,
dataset_name=dataset_name,
remote_document_id=remote_document_id,
remote_document_name=remote_document_name,
status=status,
sync_hash=sync_hash,
error_message=error_message,
synced_by_id=synced_by_id,
synced_at=datetime.utcnow(),
)
add_and_flush_with_sequence_retry(record, 'kb_dify_sync_records')
return record
record.dataset_id = dataset_id
record.dataset_name = dataset_name
record.remote_document_name = remote_document_name
record.status = status
record.sync_hash = sync_hash
record.error_message = error_message
record.synced_by_id = synced_by_id
record.synced_at = datetime.utcnow()
return record
def sync_document_version_to_dify(document_version_id: int, synced_by_id: int | None = None) -> dict:
"""
同步清洗后的知识库版本,并以 Dify 最终索引结果作为成功标准。
核心逻辑:上传/更新文本后轮询 Dify 的 indexing_status;仅 completed 写入 synced,
error 时持久化失败原因并抛错,由调用任务将工作台同步步骤标红。
Args:
document_version_id: 当前待同步的 KbDocumentVersion 主键。
synced_by_id: 发起同步的用户 ID,可为空(自动任务)。
Returns:
含 Dify 映射与 indexing_status 的同步结果。
Raises:
KbDifySyncError: 本地文本、Dify API 或 Dify 索引失败。
"""
version = db.session.get(KbDocumentVersion, document_version_id)
if not version or not version.document or not version.document.group:
raise KbDifySyncError('文档版本或关联分组不存在')
@@ -318,7 +476,13 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int |
remote_document_id = None
remote_document_name = None
upload_name = _resolve_upload_name(version)
if existing_record and existing_record.dataset_id == dataset_id and existing_record.sync_hash == sync_hash:
indexing_payload: dict | None = None
if (
existing_record
and existing_record.dataset_id == dataset_id
and existing_record.sync_hash == sync_hash
and existing_record.status == 'synced'
):
try:
payload = service.get_document(
dataset_id=dataset_id,
@@ -326,6 +490,7 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int |
)
remote_document_id = payload.get('id') or existing_record.remote_document_id
remote_document_name = payload.get('name') or existing_record.remote_document_name or upload_name
indexing_payload = payload
except KbDifySyncError as exc:
if not _is_remote_document_missing(str(exc)):
raise
@@ -337,6 +502,7 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int |
)
remote_document_id = payload.get('document', {}).get('id') or payload.get('id')
remote_document_name = payload.get('document', {}).get('name') or upload_name
indexing_payload = payload
elif existing_record and existing_record.dataset_id == dataset_id:
try:
payload = service.update_document_by_text(
@@ -357,6 +523,7 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int |
)
remote_document_id = payload.get('document', {}).get('id') or payload.get('id') or existing_record.remote_document_id
remote_document_name = payload.get('document', {}).get('name') or upload_name
indexing_payload = payload
else:
payload = service.create_document_by_text(
dataset_id=dataset_id,
@@ -366,42 +533,43 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int |
)
remote_document_id = payload.get('document', {}).get('id') or payload.get('id')
remote_document_name = payload.get('document', {}).get('name') or upload_name
indexing_payload = payload
if not remote_document_id:
raise KbDifySyncError('Dify 未返回远端文档 ID')
record = (
db.session.query(KbDifySyncRecord)
.filter(
KbDifySyncRecord.document_version_id == version.id,
KbDifySyncRecord.remote_document_id == remote_document_id,
try:
indexing_result = service.wait_for_document_indexing(
dataset_id=dataset_id,
document_id=remote_document_id,
initial_payload=indexing_payload,
)
.first()
)
if not record:
record = KbDifySyncRecord(
group_id=group.id,
document_id=document.id,
document_version_id=version.id,
except KbDifySyncError as exc:
_save_sync_record(
version=version,
dataset_id=dataset_id,
dataset_name=dataset_name,
remote_document_id=remote_document_id,
remote_document_name=remote_document_name,
status='synced',
sync_hash=sync_hash,
synced_by_id=synced_by_id,
status='failed',
error_message=str(exc),
)
add_and_flush_with_sequence_retry(record, "kb_dify_sync_records")
else:
record.dataset_id = dataset_id
record.dataset_name = dataset_name
record.remote_document_name = remote_document_name
record.status = 'synced'
record.sync_hash = sync_hash
record.error_message = None
record.synced_by_id = synced_by_id
db.session.commit()
raise
record.synced_at = datetime.utcnow()
_save_sync_record(
version=version,
dataset_id=dataset_id,
dataset_name=dataset_name,
remote_document_id=remote_document_id,
remote_document_name=remote_document_name,
sync_hash=sync_hash,
synced_by_id=synced_by_id,
status='synced',
error_message=None,
)
db.session.commit()
content_changed = previous_sync_hash != sync_hash
@@ -438,6 +606,7 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int |
'remote_document_id': remote_document_id,
'remote_document_name': remote_document_name,
'sync_hash': sync_hash,
'indexing_status': indexing_result['indexing_status'],
'source_path': source_path,
}
@@ -1,6 +1,9 @@
"""
backend/app/services/knowledge_cleaning/edkb_adapter.py
文件用途:edkb_system 轻量适配层
用途:把 edkb_system 的清洗产物适配为业务服务可直接使用的文件路径和统计信息。
依赖:edkb_system.controller、文件系统临时目录和导出产物约定。
逻辑:复制源文件到隔离目录执行清洗,再把 Markdown、分块和原始布局等必要产物持久化到目标目录。
"""
from __future__ import annotations
@@ -60,6 +63,15 @@ def _find_generated_chunks_jsonl(output_root: Path) -> Path | None:
return candidates[0]
def _find_generated_raw_layout(output_root: Path) -> Path | None:
"""定位包含 OCR Block 元数据的原始布局产物,供下游复用检测框。"""
candidates = [path for path in output_root.rglob('01_raw_layout.json') if path.is_file()]
if not candidates:
return None
candidates.sort(key=lambda item: len(item.parts))
return candidates[0]
def _count_jsonl_lines(path: Path) -> int:
count = 0
with path.open(encoding='utf-8', errors='ignore') as handle:
@@ -178,6 +190,12 @@ def build_clean_result(source_path: Path, target_dir: Path) -> dict:
_rewrite_preview_markdown_if_needed(preview_path, target_dir)
content = cleaned_path.read_text(encoding='utf-8', errors='ignore')
chunks_file_path, chunks_count = _persist_debug_chunks(output_dir, target_dir)
raw_layout_source = _find_generated_raw_layout(output_dir)
raw_layout_path = None
if raw_layout_source:
raw_layout_target = target_dir / '01_raw_layout.json'
shutil.copy2(raw_layout_source, raw_layout_target)
raw_layout_path = str(raw_layout_target)
return {
'mode': 'edkb_system',
@@ -186,4 +204,5 @@ def build_clean_result(source_path: Path, target_dir: Path) -> dict:
'word_count': len(content.split()),
'chunks_file_path': chunks_file_path,
'chunks_count': chunks_count,
'raw_layout_path': raw_layout_path,
}
@@ -18,14 +18,16 @@ SETTING_DEFAULTS = {
'DIFY_API_KEY': '',
'KB_DIFY_PERMISSION': 'only_me',
'KB_DIFY_INDEXING_TECHNIQUE': 'high_quality',
'KB_DIFY_SEARCH_METHOD': 'semantic_search',
# 混合检索同时利用关键词与向量相似度,适合“水型灭火器/A 类火灾”等实体明确问法。
'KB_DIFY_SEARCH_METHOD': 'hybrid_search',
'KB_DIFY_DOC_FORM': 'text_model',
'KB_DIFY_PROCESS_MODE': 'automatic',
# 普通制度文档也按空行保留完整知识单元,避免标题、适用范围和禁用条件被拆散。
'KB_DIFY_PROCESS_MODE': 'custom',
'KB_DIFY_PROCESS_MODE_EXCEL': 'custom',
'KB_DIFY_SEGMENT_SEPARATOR': '\\n\\n',
'KB_DIFY_SEGMENT_SEPARATOR_EXCEL': '\\n\\n',
'KB_DIFY_SEGMENT_MAX_TOKENS': '800',
'KB_DIFY_SEGMENT_CHUNK_OVERLAP': '50',
'KB_DIFY_SEGMENT_MAX_TOKENS': '600',
'KB_DIFY_SEGMENT_CHUNK_OVERLAP': '100',
'KB_DIFY_REMOVE_URLS': 'false',
}
@@ -622,6 +622,7 @@ def run_sync_job(job_id: int) -> tuple[bool, str]:
result = sync_document_version_to_dify(version.id, synced_by_id=job.created_by_id)
except KbDifySyncError as exc:
version.status = 'ready'
version.error_message = str(exc)
job.status = 'failed'
job.progress = 100
job.error_message = str(exc)
@@ -632,6 +633,7 @@ def run_sync_job(job_id: int) -> tuple[bool, str]:
return False, str(exc)
except Exception as exc:
version.status = 'ready'
version.error_message = f'同步到 Dify 时发生未预期错误:{exc}'
job.status = 'failed'
job.progress = 100
job.error_message = f'同步到 Dify 时发生未预期错误:{exc}'
@@ -642,6 +644,7 @@ def run_sync_job(job_id: int) -> tuple[bool, str]:
return False, str(exc)
version.status = 'synced'
version.error_message = None
job.status = 'success'
job.progress = 100
job.message = '已同步到 Dify'
@@ -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,223 @@
"""
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
from minio.error import S3Error
_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 S3Error as exc:
if exc.code == "NoSuchKey":
# [STEP 1] 审核执行中可选 OCR 坐标不存在时,归档尚未提交属于预期状态,不刷告警。
_LOGGER.debug(
"[contract-review] artifact manifest not ready review_no=%s path=%s",
review_no,
relative,
)
return None
_LOGGER.warning("[contract-review] artifact restore failed review_no=%s path=%s err=%s", review_no, relative, exc)
return None
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,513 @@
"""
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
# OCR 可能只错一个值,完整句无法命中时仍可用稳定字段名定位同一行。
stable_values = [item.get("new_text")]
if str(item.get("change_type") or "") == "modify":
stable_values.append(item.get("old_text"))
for raw in stable_values:
text = re.sub(r"^\s*\d+(?:[.、.])?\s*", "", str(raw or "")).strip()
label = re.split(r"[::]", text, maxsplit=1)[0].strip(" ,。;;::")
compact = _compact_text(label)
if 4 <= len(compact) <= 30 and compact not in seen:
seen.add(compact)
candidates.append(label)
if len(candidates) >= MAX_ANCHOR_CANDIDATES:
break
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 _ocr_layout_pages(ocr_layout: dict[str, Any] | None) -> list[dict[str, Any]]:
"""校验并返回 OCR 坐标产物中的页面列表。"""
if not isinstance(ocr_layout, dict):
return []
pages = ocr_layout.get("pages")
return [page for page in pages if isinstance(page, dict)] if isinstance(pages, list) else []
def _layout_match(
page: dict[str, Any],
candidate: str,
) -> tuple[list[dict[str, Any]], float] | None:
"""在单页 OCR 行序列中匹配候选文本,并返回覆盖该文本的行框。"""
lines = [line for line in page.get("lines") or [] if isinstance(line, dict)]
compact_chars: list[str] = []
char_line_indexes: list[int] = []
for line_index, line in enumerate(lines):
for char in _compact_text(line.get("text")):
compact_chars.append(char)
char_line_indexes.append(line_index)
page_key = "".join(compact_chars)
candidate_key = _compact_text(candidate)
if len(candidate_key) < 4 or len(page_key) < len(candidate_key):
return None
window_size = min(len(candidate_key), 80)
candidate_window = candidate_key[:window_size]
best_start = page_key.find(candidate_window)
best_score = 1.0 if best_start >= 0 else 0.0
if best_start < 0 and window_size >= MIN_FUZZY_ANCHOR_CHARS:
step = max(1, window_size // 12)
for start in range(0, len(page_key) - window_size + 1, step):
score = difflib.SequenceMatcher(
a=candidate_window,
b=page_key[start : start + window_size],
autojunk=False,
).ratio()
if score > best_score:
best_start = start
best_score = score
if best_start < 0 or best_score < MIN_FUZZY_SCORE:
return None
end = min(best_start + window_size, len(char_line_indexes))
matched_indexes = sorted(set(char_line_indexes[best_start:end]))
matched_lines = [lines[index] for index in matched_indexes if lines[index].get("polygon")]
if not matched_lines:
return None
return matched_lines, best_score
def locate_ocr_layout_evidence(
ocr_layout: dict[str, Any] | None,
item: dict[str, Any],
) -> dict[str, Any] | None:
"""
在纯图片 PDF 的持久化 OCR 行框中定位证据。
Returns:
命中时返回页码、归一化多边形和置信度;坐标转换延迟到写 PDF 批注阶段完成。
"""
candidates = _candidate_texts(item)
if not candidates:
return None
best: dict[str, Any] | None = None
for page in _ocr_layout_pages(ocr_layout):
page_no = int(page.get("page_no") or 0)
if page_no <= 0:
continue
for candidate in candidates:
matched = _layout_match(page, candidate)
if not matched:
continue
lines, score = matched
anchor = {
"page_no": page_no,
"rects": [],
"ocr_polygons": [line["polygon"] for line in lines],
"matched_text": "\n".join(str(line.get("text") or "") for line in lines),
"source_text": candidate,
"confidence": round(score, 3),
"method": "ocr_bbox_exact" if score == 1.0 else "ocr_bbox_fuzzy",
}
if score == 1.0:
return anchor
if best is None or score > float(best.get("confidence") or 0):
best = anchor
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,
ocr_layout: dict[str, Any] | None = None,
) -> 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):
continue
is_compare_change = str(item.get("change_type") or "") in {"insert", "delete", "modify"}
if item.get("risk_level") == "ok" and not is_compare_change:
continue
attempted += 1
anchor = locate_pdf_evidence(pdf_bytes, item)
if anchor is None:
anchor = locate_ocr_layout_evidence(ocr_layout, 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 = "",
ocr_layout: dict[str, Any] | None = None,
) -> 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_layout_evidence(ocr_layout, item)
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 []
if not rects and anchor.get("ocr_polygons"):
page = writer.pages[page_index]
width = float(page.mediabox.width)
height = float(page.mediabox.height)
page_left = float(page.mediabox.left)
page_bottom = float(page.mediabox.bottom)
for polygon in anchor.get("ocr_polygons") or []:
if not isinstance(polygon, list) or len(polygon) < 4:
continue
try:
xs = [float(point[0]) for point in polygon]
ys = [float(point[1]) for point in polygon]
except (TypeError, ValueError, IndexError):
continue
rects.append([
page_left + min(xs) * width,
page_bottom + (1.0 - max(ys)) * height,
page_left + max(xs) * width,
page_bottom + (1.0 - min(ys)) * height,
])
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,468 @@
"""
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
OCR_LAYOUT_ARTIFACT = "ocr_layout.json"
_OCR_RENDER_SCALE = 1.25
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 _ocr_layout_from_edkb(raw_layout_path: Path | None) -> list[dict[str, Any]]:
"""从 edkb 原始布局中提取 PDF 整页 OCR 行框,避免重复执行 OCR。"""
if not raw_layout_path or not raw_layout_path.is_file():
return []
try:
blocks = json.loads(raw_layout_path.read_text(encoding="utf-8"))
except (OSError, ValueError):
return []
pages: dict[int, list[dict[str, Any]]] = {}
for block in blocks if isinstance(blocks, list) else []:
if not isinstance(block, dict) or block.get("type") != "ocr_text":
continue
meta = block.get("meta") if isinstance(block.get("meta"), dict) else {}
if not meta.get("page_image") or not isinstance(meta.get("ocr_lines"), list):
continue
page_no = int(block.get("page") or 0)
if page_no <= 0:
continue
lines = [item for item in meta["ocr_lines"] if isinstance(item, dict) and item.get("polygon")]
if lines:
pages.setdefault(page_no, []).extend(lines)
return [{"page_no": page_no, "lines": pages[page_no]} for page_no in sorted(pages)]
def _ocr_layout_from_pdf(pdf_path: Path) -> list[dict[str, Any]]:
"""
为无文本层 PDF 生成行级 OCR 坐标;RapidOCR 不可用或单页失败时安全返回其余页面。
坐标保存为左上角原点的归一化多边形,下载标注时再按实际 PDF 页面尺寸换算。
"""
try:
import numpy as np
import pypdfium2 as pdfium
from edkb_system.skills.ocr import recognize_image_lines
except Exception:
return []
try:
document = pdfium.PdfDocument(str(pdf_path))
except Exception:
return []
pages: list[dict[str, Any]] = []
try:
for page_index in range(len(document)):
page = document[page_index]
try:
text_page = page.get_textpage()
try:
if (text_page.get_text_range() or "").strip():
continue
finally:
text_page.close()
bitmap = page.render(scale=_OCR_RENDER_SCALE)
image = np.asarray(bitmap.to_pil().convert("RGB"))
lines = recognize_image_lines(image, pdf_page_image=True)
if lines:
pages.append({"page_no": page_index + 1, "lines": lines})
except Exception:
continue
finally:
page.close()
finally:
document.close()
return pages
def _persist_pdf_ocr_layout(
source_path: Path,
target_dir: Path,
*,
raw_layout_path: Path | None = None,
) -> dict[str, Any] | None:
"""复用或生成纯图片 PDF 行坐标,并保存为合同审查可归档产物。"""
if source_path.suffix.lower() != ".pdf":
return None
pages = _ocr_layout_from_edkb(raw_layout_path)
source = "edkb"
if not pages:
pages = _ocr_layout_from_pdf(source_path)
source = "rapidocr_fallback"
if not pages:
return None
payload = {"version": 1, "coordinate_space": "normalized_top_left", "pages": pages}
artifact_path = target_dir / OCR_LAYOUT_ARTIFACT
artifact_path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
return {
"source": source,
"page_count": len(pages),
"line_count": sum(len(page.get("lines") or []) for page in 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] = {}
raw_layout_path: Path | None = None
# [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)
raw_layout_value = str(clean_result.get("raw_layout_path") or "").strip()
raw_layout_path = Path(raw_layout_value) if raw_layout_value else None
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)
ocr_layout = _persist_pdf_ocr_layout(source_path, target_dir, raw_layout_path=raw_layout_path)
if ocr_layout:
ocr_layout["artifact"] = f"cleaned/{normalized_role}/{OCR_LAYOUT_ARTIFACT}"
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,
"ocr_layout": ocr_layout,
},
}
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")
def read_review_ocr_layout(review_no: str, *, role: str = "contract") -> dict[str, Any]:
"""读取或从 MinIO 恢复纯图片 PDF 的行级 OCR 坐标产物。"""
normalized_role = str(role or "").strip().lower()
if normalized_role not in {"contract", "template"}:
raise ValidationError("role must be contract or template")
relative_path = f"cleaned/{normalized_role}/{OCR_LAYOUT_ARTIFACT}"
layout_path = _review_root(review_no) / relative_path
if not layout_path.is_file():
artifact_archive.restore_review_artifact(review_no, relative_path)
if not layout_path.is_file():
return {}
try:
payload = json.loads(layout_path.read_text(encoding="utf-8"))
except (OSError, ValueError):
return {}
return payload if isinstance(payload, dict) else {}
@@ -0,0 +1,838 @@
"""
backend/app/services/procurement_contract/review_service.py
用途:创建、异步执行、查询与导出采购合同审查记录。
依赖:ContractReview/FileAsset/Job、知识库清洗适配器、rule/analyze/llm_enhancer/pdf_annotation/visual_ocr_validation。
逻辑: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,
visual_ocr_validation,
)
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 行框,
无行框时再按 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),
ocr_layout=preprocessing.read_review_ocr_layout(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 与双边视觉 OCR 复核;
[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)
# [STEP 2] 混合提取产生的地点类差异再做双边同源 OCR;只有视觉结果一致才移除。
try:
result = visual_ocr_validation.suppress_mixed_extraction_ocr_noise(
result,
review_no=row.review_no,
original_filename=template_asset.original_filename or row.template_name or "template.pdf",
original_pdf_bytes=read_asset_bytes(template_asset),
original_extraction_meta=template_meta,
original_ocr_layout=preprocessing.read_review_ocr_layout(row.review_no, role="template"),
returned_filename=contract_asset.original_filename or row.contract_file_name,
returned_pdf_bytes=read_asset_bytes(contract_asset),
returned_extraction_meta=dict(contract_doc["extraction_meta"]),
returned_ocr_layout=preprocessing.read_review_ocr_layout(row.review_no, role="contract"),
)
except Exception as exc: # noqa: BLE001 - OCR复核失败时必须保留原始差异并继续审核
current_app.logger.warning(
"[contract-review] visual OCR validation failed review_no=%s err=%s",
row.review_no,
exc,
)
validation_summary = (
result.get("summary_json") if isinstance(result.get("summary_json"), dict) else {}
)
comparison_quality = (
validation_summary.get("comparison_quality")
if isinstance(validation_summary.get("comparison_quality"), dict)
else {}
)
comparison_quality["visual_ocr_rechecks"] = {
"status": "failed",
"mixed_extraction": None,
"checked": 0,
"ignored": 0,
"kept": 0,
"reason": str(exc)[:500],
"items": [],
}
validation_summary["comparison_quality"] = comparison_quality
result["summary_json"] = validation_summary
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),
ocr_layout=preprocessing.read_review_ocr_layout(row.review_no),
)
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,935 @@
"""
backend/app/services/procurement_contract/visual_ocr_validation.py
用途:对“原生文本 vs 扫描 OCR”产生的地点字段及设备清单疑似差异执行双边同源 OCR 复核。
依赖:pypdfium2 页面渲染、RapidOCR 行识别、pdf_annotation 页面证据定位。
逻辑:review_service 完成确定性 Diff 后调用本模块;地点字段按行复核,设备清单按视觉坐标
重建表头与数据行;双方同源 OCR 业务值一致时移除噪声差异,并保留结构化诊断与日志。
"""
from __future__ import annotations
import logging
import re
import unicodedata
from difflib import SequenceMatcher
from typing import Any
from app.services.procurement_contract import pdf_annotation
_LOGGER = logging.getLogger(__name__)
_OCR_RENDER_SCALE = 1.25
_MAX_DIAGNOSTIC_ITEMS = 50
_EQUIPMENT_TABLE_HEADER_TERMS = ("序号", "设备名称", "品牌", "型号", "数量", "单价", "总价")
_EQUIPMENT_TABLE_END_TERMS = ("合计", "备注", "总计")
_EQUIPMENT_DIFF_HINTS = (
"设备名称",
"品牌",
"型号",
"数量",
"单价",
"总价",
"合计",
"总计",
"交易条件",
"清单信息",
)
_LOCATION_FIELD_LABELS = frozenset({
"设备使用地",
"设备安装地",
"交货地点",
"交付地点",
"安装地点",
"使用地点",
})
_CRITICAL_VALUE_HINTS = (
"金额", "价款", "价税", "单价", "总价", "付款", "支付", "比例", "%",
"日期", "期限", "交货期", "交付期", "数量", "型号", "规格", "税率",
)
_CRITICAL_VALUE_PATTERNS = (
r"\d{4}[年/-]\d{1,2}[月/-]\d{1,2}",
r"\d+(?:\.\d+)?\s*[%%]",
r"(?:人民币|RMB|CNY|USD|¥|¥)\s*\d",
r"\d[\d,]*(?:\.\d{1,2})?\s*(?:元|万元|万元整)",
r"\d+\s*(?:套|台|件|个|只|箱|批|吨|千克|KG|kg|台)",
r"(?=[A-Za-z0-9-]{5,})(?=[A-Za-z0-9-]*[A-Za-z])(?=[A-Za-z0-9-]*\d)[A-Za-z0-9-]+",
)
_MATERIAL_DIRECTION_TERMS = (
"不得", "无须", "无需", "不承担", "无权", "有权", "免除", "免责", "赔偿", "解除", "终止",
)
def _compact_text(value: Any) -> str:
"""统一全半角并只保留中英文和数字,供 OCR 字段行稳定比较。"""
normalized = unicodedata.normalize("NFKC", str(value or ""))
return re.sub(r"[^\u4e00-\u9fffA-Za-z0-9]+", "", normalized)
def _field_label(value: Any) -> str:
"""从差异文本中提取冒号前的稳定字段名,并移除条款编号。"""
text = str(value or "").strip().splitlines()[0] if str(value or "").strip() else ""
text = re.sub(r"^\s*(?:第[一二三四五六七八九十百千万\d]+条|[一二三四五六七八九十百千万\d]+[.、.))])\s*", "", text)
return re.split(r"[::]", text, maxsplit=1)[0].strip(" ,,。;;::")
def _eligible_location_field(item: dict[str, Any]) -> str | None:
"""仅允许双方字段名一致的地点类 modify 项进入自动复核。"""
if str(item.get("change_type") or "") != "modify":
return None
old_text = str(item.get("old_text") or "").strip()
new_text = str(item.get("new_text") or "").strip()
if not old_text or not new_text:
return None
old_label = _field_label(old_text)
new_label = _field_label(new_text)
if old_label != new_label or old_label not in _LOCATION_FIELD_LABELS:
return None
return old_label
def _eligible_high_similarity_field(item: dict[str, Any]) -> bool:
"""
判断无稳定字段标签的条款 modify 是否可进入双边同源 OCR 复核。
核心逻辑:混合 PDF 的初始文本可能来自“原生文字层 vs 扫描 OCR”,因此付款、交期、
质保等关键条款也允许进入候选;但只有双方已抽取的数字、型号及权利义务方向完全一致时
才执行视觉复核。最终仍须两份 PDF 命中页使用同一 OCR 后文本完全一致,才会忽略差异。
Args:
item: analyze_compare 生成的单条 modify 差异。
Returns:
True 表示该条款可进行命中页双边 OCR;关键业务事实已变化时返回 False。
"""
if str(item.get("change_type") or "") != "modify":
return False
old_text = str(item.get("old_text") or "")
new_text = str(item.get("new_text") or "")
old_key = _compact_text(old_text)
new_key = _compact_text(new_text)
if min(len(old_key), len(new_key)) < 8 or old_key == new_key:
return False
# [STEP 1] 数字、比例、日期、型号任一变化都保留原 Diff,不以 OCR 复核自动撤销。
if _critical_fact_tokens(old_text) != _critical_fact_tokens(new_text):
return False
# [STEP 2] 否定、免责、赔偿和解除等方向变化属于实质权利义务变化。
old_directions = {term for term in _MATERIAL_DIRECTION_TERMS if term in old_text}
new_directions = {term for term in _MATERIAL_DIRECTION_TERMS if term in new_text}
if old_directions != new_directions:
return False
# [STEP 3] 候选门槛只用于控制 OCR 成本;是否忽略仍由双边视觉文本完全一致决定。
similarity = SequenceMatcher(None, old_key, new_key).ratio()
return similarity >= (0.55 if min(len(old_key), len(new_key)) >= 24 else 0.78)
def _critical_fact_tokens(value: str) -> dict[str, tuple[str, ...]]:
"""
提取不能被视觉 OCR 自动忽略的合同业务事实。
核心逻辑:统一全半角并移除开头条款序号,分别收集数字、百分比/千分比和字母数字型号;
比较候选资格时要求两侧 token 完全一致,避免把 24 小时改成 48 小时等真实变化吞掉。
Args:
value: 单侧差异原文。
Returns:
按 numbers、rates、models 分类并排序的不可变 token 字典。
"""
normalized = unicodedata.normalize("NFKC", str(value or ""))
normalized = re.sub(r"^\s*(?:第\s*)?[一二三四五六七八九十百千万\d]+(?:条|款|项)?[.、::))\s]+", "", normalized)
number_matches = tuple(re.findall(r"\d+(?:[,.]\d+)*", normalized))
rates = tuple(re.findall(r"\d+(?:\.\d+)?\s*(?:%|‰)|(?:百分之|千分之)[零〇一二两三四五六七八九十百千万点\d.]+", normalized))
models = tuple(
token.lower()
for token in re.findall(r"(?=[A-Za-z0-9-]{4,})(?=[A-Za-z0-9-]*[A-Za-z])(?=[A-Za-z0-9-]*\d)[A-Za-z0-9-]+", normalized)
)
critical_context = any(
hint in normalized
for hint in _CRITICAL_VALUE_HINTS + ("天", "日", "个月", "月", "年", "小时", "工作日", "期限")
)
numbers = number_matches if critical_context or rates else ()
return {"numbers": numbers, "rates": rates, "models": models}
def _pdf_text_profile(pdf_bytes: bytes) -> dict[str, int] | None:
"""
检查 PDF 是否含可搜索文字层,用于确认双方是否属于混合提取模式。
Args:
pdf_bytes: 完整 PDF 字节。
Returns:
page_count/native_text_pages;PDF 无法打开时返回 None。
"""
try:
import pypdfium2 as pdfium
document = pdfium.PdfDocument(pdf_bytes)
except Exception:
return None
native_text_pages = 0
try:
for page_index in range(len(document)):
page = document[page_index]
try:
text_page = page.get_textpage()
try:
if (text_page.get_text_range() or "").strip():
native_text_pages += 1
finally:
text_page.close()
finally:
page.close()
return {"page_count": len(document), "native_text_pages": native_text_pages}
finally:
document.close()
def _evidence_item(text: str) -> dict[str, Any]:
"""把单侧字段文本包装成 pdf_annotation 可识别的定位项。"""
return {"change_type": "modify", "old_text": text, "new_text": text}
def _locate_page(
*,
pdf_bytes: bytes,
ocr_layout: dict[str, Any] | None,
text: str,
scanned_side: bool,
) -> int | None:
"""按页面类型定位字段:扫描侧优先 OCR 行框,文本侧优先 PDF 字符坐标。"""
item = _evidence_item(text)
anchor = (
pdf_annotation.locate_ocr_layout_evidence(ocr_layout, item)
if scanned_side
else pdf_annotation.locate_pdf_evidence(pdf_bytes, item)
)
if anchor is None and not scanned_side:
anchor = pdf_annotation.locate_ocr_layout_evidence(ocr_layout, item)
page_no = int((anchor or {}).get("page_no") or 0)
return page_no if page_no > 0 else None
def _ocr_pdf_pages(pdf_bytes: bytes, page_numbers: set[int]) -> dict[int, list[dict[str, Any]]]:
"""
用相同渲染比例和 RapidOCR 参数强制识别指定 PDF 页面。
Args:
pdf_bytes: 完整 PDF 字节,不修改原文件。
page_numbers: 1-based 页面集合;只渲染已由证据定位命中的页面。
Returns:
page_no 到 OCR 行记录的映射;单页失败时保留其他页面结果。
"""
if not page_numbers:
return {}
import numpy as np
import pypdfium2 as pdfium
from edkb_system.skills.ocr import recognize_image_lines
document = pdfium.PdfDocument(pdf_bytes)
output: dict[int, list[dict[str, Any]]] = {}
try:
for page_no in sorted(page_numbers):
if page_no <= 0 or page_no > len(document):
continue
page = document[page_no - 1]
try:
bitmap = page.render(scale=_OCR_RENDER_SCALE)
image = np.asarray(bitmap.to_pil().convert("RGB"))
output[page_no] = recognize_image_lines(
image,
pdf_page_image=True,
retain_short_tokens=True,
)
except Exception as exc: # noqa: BLE001 - one OCR page must not block the contract review
_LOGGER.warning("[contract-review] visual OCR page failed page_no=%s err=%s", page_no, exc)
finally:
page.close()
finally:
document.close()
return output
def _matching_field_line(lines: list[dict[str, Any]], field_label: str) -> str:
"""从 OCR 阅读顺序中选出包含稳定字段名的单行或相邻行窗口。"""
label_key = _compact_text(field_label)
texts = [str(line.get("text") or "").strip() for line in lines if isinstance(line, dict)]
for window_size in (1, 2, 3):
for start in range(0, max(0, len(texts) - window_size + 1)):
candidate = "".join(texts[start : start + window_size])
if label_key and label_key in _compact_text(candidate):
return candidate[:500]
return ""
def _shared_clause_anchor(old_text: str, new_text: str) -> str:
"""
提取差异两侧共同的稳定条款前缀,供双边 OCR 从同一业务位置开始重建。
核心逻辑:从去标点文本的最长公共前缀中截取最多 48 个字符;若差异发生得过早,
则回退到双方开头的高相似短锚点。锚点仅用于定位,不参与最终“视觉文本完全一致”判定。
Args:
old_text: 原合同抽取条款。
new_text: 回传合同抽取条款,可能包含 OCR 乱码或截断。
Returns:
至少 8 个字符的共同条款锚点;无法可靠提取时返回空字符串。
"""
old_key = _compact_text(old_text)
new_key = _compact_text(new_text)
common_length = 0
for old_char, new_char in zip(old_key, new_key):
if old_char != new_char:
break
common_length += 1
if common_length >= 8:
return old_key[: min(common_length, 48)]
# [STEP 1] 差异若紧邻条款开头,仍允许使用短窗口定位,但必须保证双方前缀高度相似。
max_probe = min(32, len(old_key), len(new_key))
for probe_length in range(max_probe, 7, -1):
if SequenceMatcher(None, old_key[:probe_length], new_key[:probe_length]).ratio() >= 0.9:
return old_key[:probe_length]
return ""
def _matching_similar_line(
lines: list[dict[str, Any]],
expected_text: str,
*,
shared_anchor: str = "",
target_length: int | None = None,
) -> str:
"""
从 OCR 行及相邻行窗口中选出最接近原始差异文本的视觉条款。
核心逻辑:优先用差异两侧共同锚点定位同一条款起始行,再向后拼接至双方统一目标长度;
无共同锚点时才回退相似窗口。候选排序同时考虑相似度和长度覆盖,避免短前缀因乱码侧
expected_text 较短而胜过完整条款。
Args:
lines: 同一 PDF 页面按阅读顺序排列的 OCR 行。
expected_text: 初始 Diff 中该侧的条款文本。
shared_anchor: 双方抽取文本共同前缀;存在时要求候选窗口覆盖该锚点。
target_length: 双方统一的去标点目标长度,避免回传侧乱码截断导致窗口过短。
Returns:
最接近的 OCR 行窗口;无可靠候选时返回空字符串。
"""
expected_key = _compact_text(expected_text)
texts = [str(line.get("text") or "").strip() for line in lines if isinstance(line, dict)]
if not expected_key or not texts:
return ""
desired_length = max(int(target_length or 0), len(expected_key))
anchor_key = _compact_text(shared_anchor)
max_window = min(8, max(3, desired_length // 22 + 2))
# [STEP 1] 从双方共同锚点命中的行开始重建,达到目标长度后停止,避免吞入下一条款。
if len(anchor_key) >= 8:
anchored_candidates: list[tuple[float, float, int, str]] = []
for start in range(len(texts)):
candidate = ""
for end in range(start, min(len(texts), start + max_window)):
candidate += texts[end]
candidate_key = _compact_text(candidate)
anchor_score = SequenceMatcher(
None,
anchor_key,
candidate_key[: max(len(anchor_key), min(len(candidate_key), len(anchor_key) + 8))],
).ratio()
if anchor_key not in candidate_key and anchor_score < 0.82:
continue
coverage = min(len(candidate_key), desired_length) / max(1, desired_length)
similarity = SequenceMatcher(None, expected_key, candidate_key).ratio()
anchored_candidates.append((coverage, similarity, -abs(len(candidate_key) - desired_length), candidate))
if len(candidate_key) >= desired_length:
break
if anchored_candidates:
coverage, similarity, _length_delta, candidate = max(anchored_candidates)
if coverage >= 0.72 and similarity >= 0.5:
return candidate[:500]
# [STEP 2] 无可靠共同锚点时回退全页窗口;长度覆盖优先于微小的相似度优势。
best_text = ""
best_rank = (0.0, 0.0, -10**9)
for window_size in range(1, max_window + 1):
for start in range(0, max(0, len(texts) - window_size + 1)):
candidate = "".join(texts[start : start + window_size])
candidate_key = _compact_text(candidate)
score = SequenceMatcher(None, expected_key, candidate_key).ratio()
coverage = min(len(candidate_key), desired_length) / max(1, desired_length)
rank = (score, coverage, -abs(len(candidate_key) - desired_length))
if score >= 0.55 and coverage >= 0.55 and rank > best_rank:
best_text, best_rank = candidate, rank
return best_text[:500]
def _line_bounds(line: dict[str, Any]) -> tuple[float, float, float, float] | None:
"""读取 OCR 行像素框;旧版行记录没有 pixel_polygon 时回退到归一化框。"""
raw_polygon = line.get("pixel_polygon") or line.get("polygon")
if not isinstance(raw_polygon, list):
return None
points: list[tuple[float, float]] = []
for point in raw_polygon:
if not isinstance(point, (list, tuple)) or len(point) < 2:
continue
try:
points.append((float(point[0]), float(point[1])))
except (TypeError, ValueError):
continue
if len(points) < 4:
return None
xs = [point[0] for point in points]
ys = [point[1] for point in points]
return min(xs), min(ys), max(xs), max(ys)
def _line_center(line: dict[str, Any]) -> tuple[float, float] | None:
"""返回 OCR 行框中心点,用于按视觉行和列组织设备表。"""
bounds = _line_bounds(line)
if bounds is None:
return None
left, top, right, bottom = bounds
return (left + right) / 2.0, (top + bottom) / 2.0
def _group_visual_rows(lines: list[dict[str, Any]]) -> list[list[dict[str, Any]]]:
"""根据行框纵向重叠将 OCR 片段聚成视觉行,再按横坐标排序。"""
positioned = [line for line in lines if isinstance(line, dict) and _line_bounds(line)]
positioned.sort(key=lambda line: (_line_center(line) or (0.0, 0.0))[1])
rows: list[dict[str, Any]] = []
for line in positioned:
bounds = _line_bounds(line)
if bounds is None:
continue
_, top, _, bottom = bounds
center_y = (top + bottom) / 2.0
height = max(0.001, bottom - top)
matched: dict[str, Any] | None = None
for row in reversed(rows[-3:]):
tolerance = max(float(row["height"]), height) * 0.7
if abs(center_y - float(row["center_y"])) <= tolerance:
matched = row
break
if matched is None:
rows.append({"center_y": center_y, "height": height, "lines": [line]})
else:
matched_lines = matched["lines"]
matched_lines.append(line)
matched["center_y"] = sum((_line_center(item) or (0.0, 0.0))[1] for item in matched_lines) / len(
matched_lines
)
matched["height"] = max(float(matched["height"]), height)
output: list[list[dict[str, Any]]] = []
for row in rows:
output.append(sorted(row["lines"], key=lambda line: (_line_center(line) or (0.0, 0.0))[0]))
return output
def _table_header_row(rows: list[list[dict[str, Any]]]) -> tuple[int, list[dict[str, Any]]] | None:
"""定位同时包含至少五个标准列名的设备清单表头。"""
best: tuple[int, list[dict[str, Any]], int] | None = None
for row_index, row in enumerate(rows):
text = "".join(str(line.get("text") or "") for line in row)
hits = sum(1 for term in _EQUIPMENT_TABLE_HEADER_TERMS if term in text)
if hits >= 5 and (best is None or hits > best[2]):
best = row_index, row, hits
return (best[0], best[1]) if best else None
def _header_columns(header_row: list[dict[str, Any]]) -> list[tuple[str, float]]:
"""把表头 OCR 片段映射为标准字段及其横向中心,兼容一个片段含多个列名。"""
columns: list[tuple[str, float]] = []
for line in header_row:
text = str(line.get("text") or "")
bounds = _line_bounds(line)
if bounds is None:
continue
left, _, right, _ = bounds
matched_terms = [term for term in _EQUIPMENT_TABLE_HEADER_TERMS if term in text]
if not matched_terms:
continue
width = max(0.001, right - left)
for term in matched_terms:
position = text.find(term)
ratio = (position + len(term) / 2.0) / max(1, len(text))
columns.append((term, left + width * ratio))
deduplicated: dict[str, float] = {}
for term, center_x in columns:
deduplicated.setdefault(term, center_x)
return sorted(deduplicated.items(), key=lambda item: item[1])
def _column_boundaries(columns: list[tuple[str, float]]) -> list[tuple[str, float, float]]:
"""根据相邻表头中心中点生成每列左右边界。"""
boundaries: list[tuple[str, float, float]] = []
for index, (term, center_x) in enumerate(columns):
left = float("-inf") if index == 0 else (columns[index - 1][1] + center_x) / 2.0
right = float("inf") if index == len(columns) - 1 else (center_x + columns[index + 1][1]) / 2.0
boundaries.append((term, left, right))
return boundaries
def _equipment_table_rows(lines: list[dict[str, Any]]) -> dict[str, Any] | None:
"""
从整页 OCR 行框中重建设备清单业务行,空品牌列不会引起后续字段左移。
Returns:
包含 rows/key/page_text 的表格;找不到标准表头或业务行时返回 None。
"""
visual_rows = _group_visual_rows(lines)
located_header = _table_header_row(visual_rows)
if located_header is None:
return None
header_index, header_row = located_header
columns = _header_columns(header_row)
required_columns = {"设备名称", "型号", "数量", "单价", "总价"}
if not required_columns.issubset({term for term, _ in columns}):
return None
boundaries = _column_boundaries(columns)
table_rows: list[dict[str, str]] = []
for row in visual_rows[header_index + 1:]:
row_text = "".join(str(line.get("text") or "") for line in row)
if any(term in row_text for term in _EQUIPMENT_TABLE_END_TERMS):
if table_rows:
break
continue
values = {term: "" for term, _ in columns}
for line in row:
center = _line_center(line)
if center is None:
continue
center_x, _ = center
for term, left, right in boundaries:
if left <= center_x < right:
values[term] += str(line.get("text") or "").strip()
break
if not values.get("设备名称"):
continue
if not any(values.get(term) for term in ("型号", "数量", "单价", "总价")):
continue
table_rows.append(values)
if not table_rows:
return None
comparable_fields = ("设备名称", "品牌", "型号", "数量", "单价", "总价")
normalized_rows = [
{field: _compact_text(row.get(field)) for field in comparable_fields}
for row in table_rows
]
key = "||".join("|".join(row[field] for field in comparable_fields) for row in normalized_rows)
return {"rows": table_rows, "normalized_rows": normalized_rows, "key": key}
def _looks_like_equipment_table_diff(item: dict[str, Any]) -> bool:
"""判断差异项是否可能来自设备清单列错位,避免表格复核影响普通条款。"""
if str(item.get("change_class") or "") != "commercial":
return False
blob = "\n".join(
str(item.get(field) or "")
for field in ("title", "old_text", "new_text")
)
if any(term in blob for term in _EQUIPMENT_DIFF_HINTS[:7]):
return True
has_model = bool(re.search(r"(?=[A-Za-z0-9-]{5,})(?=[A-Za-z0-9-]*[A-Za-z])(?=[A-Za-z0-9-]*\d)", blob))
has_amount = bool(re.search(r"\d[\d,.]{2,}", blob))
return has_model and has_amount
def _is_empty_commercial_companion(item: dict[str, Any]) -> bool:
"""识别同一表格错位产生的无原文商业占位项;有任何对照文本时都必须保留。"""
if str(item.get("change_class") or "") != "commercial":
return False
if str(item.get("old_text") or "").strip() or str(item.get("new_text") or "").strip():
return False
detail = str(item.get("detail") or "")
return any(term in detail for term in ("交易条件", "清单信息"))
def _table_candidate_pages(
*,
pdf_bytes: bytes,
ocr_layout: dict[str, Any] | None,
scanned_side: bool,
) -> set[int]:
"""用标准表头定位设备清单页;定位失败时只回退第一页,不扫描整份合同。"""
item = _evidence_item("序号 设备名称 品牌 型号 数量 单价 总价")
anchor = (
pdf_annotation.locate_ocr_layout_evidence(ocr_layout, item)
if scanned_side
else pdf_annotation.locate_pdf_evidence(pdf_bytes, item)
)
page_no = int((anchor or {}).get("page_no") or 0)
return {page_no} if page_no > 0 else {1}
def _write_diagnostics(
result: dict[str, Any],
*,
status: str,
mixed_extraction: bool,
checked: int,
ignored: int,
kept: int,
items: list[dict[str, Any]],
reason: str | None = None,
) -> None:
"""把复核统计写入 comparison_quality,确保结果归档后仍可追溯。"""
summary = result.get("summary_json") if isinstance(result.get("summary_json"), dict) else {}
quality = summary.get("comparison_quality") if isinstance(summary.get("comparison_quality"), dict) else {}
quality["visual_ocr_rechecks"] = {
"status": status,
"mixed_extraction": mixed_extraction,
"checked": checked,
"ignored": ignored,
"kept": kept,
"reason": reason,
"items": items[:_MAX_DIAGNOSTIC_ITEMS],
}
if ignored:
quality["ignored_ocr_noise"] = int(quality.get("ignored_ocr_noise") or 0) + ignored
summary["comparison_quality"] = quality
result["summary_json"] = summary
def _refresh_focus_lights(result: dict[str, Any]) -> None:
"""差异被移除后同步五盏灯的改动计数,避免摘要仍显示已变化。"""
summary = result.get("summary_json") if isinstance(result.get("summary_json"), dict) else {}
lights = summary.get("focus_lights") if isinstance(summary.get("focus_lights"), list) else []
clauses = result.get("clauses_json") if isinstance(result.get("clauses_json"), list) else []
risk_rank = {"ok": 0, "low": 1, "medium": 2, "high": 3}
for light in lights:
if not isinstance(light, dict):
continue
category = str(light.get("key") or "")
changes = [
item
for item in clauses
if isinstance(item, dict)
and str(item.get("clause_category") or "") == category
and str(item.get("change_type") or "") in {"insert", "delete", "modify"}
]
if changes:
light["change_count"] = len(changes)
light["risk_level"] = max(
(str(item.get("risk_level") or "ok") for item in changes),
key=lambda level: risk_rank.get(level, 0),
)
light["status"] = "changed"
elif light.get("status") == "changed":
light.update({"status": "unchanged", "risk_level": "ok", "change_count": 0})
summary["focus_lights"] = lights
result["summary_json"] = summary
def _log_diagnostic(review_no: str, diagnostic: dict[str, Any]) -> None:
"""输出单项双边视觉 OCR 复核日志,包含定位失败和保留分支。"""
_LOGGER.info(
"[contract-review] visual OCR recheck review_no=%s type=%s field=%s original_mode=%s "
"returned_mode=%s original_page=%s returned_page=%s old=%r new=%r original_ocr=%r "
"returned_ocr=%r decision=%s reason=%s",
review_no,
diagnostic.get("validation_type"),
diagnostic.get("field_label"),
diagnostic["original_extraction_mode"],
diagnostic["returned_extraction_mode"],
diagnostic["original_page_no"],
diagnostic["returned_page_no"],
diagnostic["old_text"],
diagnostic["new_text"],
diagnostic.get("original_visual_ocr"),
diagnostic.get("returned_visual_ocr"),
diagnostic["decision"],
diagnostic["reason"],
)
def suppress_mixed_extraction_ocr_noise(
result: dict[str, Any],
*,
review_no: str,
original_filename: str,
original_pdf_bytes: bytes,
original_extraction_meta: dict[str, Any] | None,
original_ocr_layout: dict[str, Any] | None,
returned_filename: str,
returned_pdf_bytes: bytes,
returned_extraction_meta: dict[str, Any] | None,
returned_ocr_layout: dict[str, Any] | None,
) -> dict[str, Any]:
"""
移除混合提取模式中经双边同源 OCR 证明一致的地点字段、高相似非关键文本和设备清单噪声差异。
核心逻辑:[STEP 1] 确认一侧为文本 PDF、一侧为扫描 PDF;[STEP 2] 地点字段按稳定标签
定位命中页;[STEP 3] 设备清单按标准表头定位并用坐标重建列;[STEP 4] 双边视觉业务值
完全一致才移除关联差异。设备数量、金额、型号真实变化会使表格键不同并保留差异。
Args:
result: analyze_compare 生成的审核结果,函数原位更新并返回。
review_no: 审查编号,写入结构化日志。
original_filename: 我方原合同文件名,仅 PDF 执行。
original_pdf_bytes: 我方原合同 PDF 字节。
original_extraction_meta: 我方原合同提取元数据。
original_ocr_layout: 我方原合同持久化 OCR 行框。
returned_filename: 供应商回传合同文件名,仅 PDF 执行。
returned_pdf_bytes: 供应商回传合同 PDF 字节。
returned_extraction_meta: 回传合同提取元数据。
returned_ocr_layout: 回传合同持久化 OCR 行框。
Returns:
已更新 clauses_json 和 comparison_quality 诊断的同一结果字典。
"""
if not original_filename.lower().endswith(".pdf") or not returned_filename.lower().endswith(".pdf"):
_write_diagnostics(
result,
status="skipped",
mixed_extraction=False,
checked=0,
ignored=0,
kept=0,
items=[],
reason="non_pdf_input",
)
return result
# [STEP 1] 直接检查 PDF 文字层,避免把 MinerU/edkb 的提供商名称误当成提取方式。
original_profile = _pdf_text_profile(original_pdf_bytes)
returned_profile = _pdf_text_profile(returned_pdf_bytes)
if original_profile is None or returned_profile is None:
_write_diagnostics(
result,
status="skipped",
mixed_extraction=False,
checked=0,
ignored=0,
kept=0,
items=[],
reason="pdf_profile_unavailable",
)
return result
original_scanned = original_profile["native_text_pages"] == 0
returned_scanned = returned_profile["native_text_pages"] == 0
mixed_extraction = original_scanned != returned_scanned
if not mixed_extraction:
_write_diagnostics(
result,
status="skipped",
mixed_extraction=False,
checked=0,
ignored=0,
kept=0,
items=[],
reason="same_extraction_type",
)
return result
# [STEP 2] 定位地点项与高相似非关键文本,并识别设备清单列错位候选项。
clauses = result.get("clauses_json") if isinstance(result.get("clauses_json"), list) else []
pending_text_candidates: list[dict[str, Any]] = []
diagnostic_items: list[dict[str, Any]] = []
candidate_item_ids: set[int] = set()
original_pages: set[int] = set()
returned_pages: set[int] = set()
for item in clauses:
if not isinstance(item, dict):
continue
field_label = _eligible_location_field(item)
validation_type = "location_field" if field_label else "high_similarity_text"
if not field_label and not _eligible_high_similarity_field(item):
continue
candidate_item_ids.add(id(item))
original_page = _locate_page(
pdf_bytes=original_pdf_bytes,
ocr_layout=original_ocr_layout,
text=str(item.get("old_text") or ""),
scanned_side=original_scanned,
)
returned_page = _locate_page(
pdf_bytes=returned_pdf_bytes,
ocr_layout=returned_ocr_layout,
text=str(item.get("new_text") or ""),
scanned_side=returned_scanned,
)
diagnostic = {
"clause_no": item.get("clause_no"),
"title": str(item.get("title") or "")[:200],
"validation_type": validation_type,
"field_label": field_label or "同源 OCR 条款复核",
"original_extraction_mode": str((original_extraction_meta or {}).get("mode") or ""),
"returned_extraction_mode": str((returned_extraction_meta or {}).get("mode") or ""),
"original_page_no": original_page,
"returned_page_no": returned_page,
"old_text": str(item.get("old_text") or "")[:500],
"new_text": str(item.get("new_text") or "")[:500],
}
diagnostic_items.append(diagnostic)
if not original_page or not returned_page:
diagnostic.update({"decision": "kept", "reason": "page_not_located"})
_log_diagnostic(review_no, diagnostic)
continue
pending_text_candidates.append({
"item": item,
"field_label": field_label,
"validation_type": validation_type,
"original_page": original_page,
"returned_page": returned_page,
"diagnostic": diagnostic,
})
original_pages.add(original_page)
returned_pages.add(returned_page)
equipment_items = [item for item in clauses if isinstance(item, dict) and _looks_like_equipment_table_diff(item)]
if equipment_items:
candidate_item_ids.update(id(item) for item in equipment_items)
candidate_item_ids.update(id(item) for item in clauses if _is_empty_commercial_companion(item))
original_pages.update(
_table_candidate_pages(
pdf_bytes=original_pdf_bytes,
ocr_layout=original_ocr_layout,
scanned_side=original_scanned,
)
)
returned_pages.update(
_table_candidate_pages(
pdf_bytes=returned_pdf_bytes,
ocr_layout=returned_ocr_layout,
scanned_side=returned_scanned,
)
)
if not diagnostic_items and not equipment_items:
_write_diagnostics(
result,
status="complete",
mixed_extraction=True,
checked=0,
ignored=0,
kept=0,
items=[],
reason="no_eligible_visual_recheck",
)
return result
original_page_ocr = _ocr_pdf_pages(original_pdf_bytes, original_pages) if original_pages else {}
returned_page_ocr = _ocr_pdf_pages(returned_pdf_bytes, returned_pages) if returned_pages else {}
ignored_item_ids: set[int] = set()
# [STEP 3] 字段行或高相似文本只有双方视觉 OCR 完全一致时,才判为 OCR 噪声。
for candidate in pending_text_candidates:
if candidate["validation_type"] == "location_field":
original_visual = _matching_field_line(
original_page_ocr.get(candidate["original_page"], []), candidate["field_label"]
)
returned_visual = _matching_field_line(
returned_page_ocr.get(candidate["returned_page"], []), candidate["field_label"]
)
else:
shared_anchor = _shared_clause_anchor(
str(candidate["item"].get("old_text") or ""),
str(candidate["item"].get("new_text") or ""),
)
target_length = max(
len(_compact_text(candidate["item"].get("old_text"))),
len(_compact_text(candidate["item"].get("new_text"))),
)
original_visual = _matching_similar_line(
original_page_ocr.get(candidate["original_page"], []),
candidate["item"].get("old_text") or "",
shared_anchor=shared_anchor,
target_length=target_length,
)
returned_visual = _matching_similar_line(
returned_page_ocr.get(candidate["returned_page"], []),
candidate["item"].get("new_text") or "",
shared_anchor=shared_anchor,
target_length=target_length,
)
diagnostic = candidate["diagnostic"]
diagnostic["original_visual_ocr"] = original_visual
diagnostic["returned_visual_ocr"] = returned_visual
if original_visual and returned_visual and _compact_text(original_visual) == _compact_text(returned_visual):
diagnostic.update({"decision": "ignored", "reason": "same_visual_ocr"})
ignored_item_ids.add(id(candidate["item"]))
else:
reason = "field_line_not_recognized" if not original_visual or not returned_visual else "visual_ocr_differs"
diagnostic.update({"decision": "kept", "reason": reason})
_log_diagnostic(review_no, diagnostic)
# [STEP 4] 设备表按视觉列重建;空品牌列保留为空,型号/金额不会因线性文本错位而丢失。
if equipment_items:
original_tables = [
(page_no, table)
for page_no in sorted(original_pages)
for table in [_equipment_table_rows(original_page_ocr.get(page_no, []))]
if table
]
returned_tables = [
(page_no, table)
for page_no in sorted(returned_pages)
for table in [_equipment_table_rows(returned_page_ocr.get(page_no, []))]
if table
]
table_match: tuple[int, dict[str, Any], int, dict[str, Any]] | None = None
for original_page, original_table in original_tables:
for returned_page, returned_table in returned_tables:
if original_table["key"] and original_table["key"] == returned_table["key"]:
table_match = original_page, original_table, returned_page, returned_table
break
if table_match:
break
table_diagnostic = {
"clause_no": None,
"title": "设备清单视觉复核",
"validation_type": "equipment_table",
"field_label": "设备清单",
"original_extraction_mode": str((original_extraction_meta or {}).get("mode") or ""),
"returned_extraction_mode": str((returned_extraction_meta or {}).get("mode") or ""),
"original_page_no": table_match[0] if table_match else (original_tables[0][0] if original_tables else None),
"returned_page_no": table_match[2] if table_match else (returned_tables[0][0] if returned_tables else None),
"old_text": "\n".join(str(item.get("old_text") or "") for item in equipment_items)[:500],
"new_text": "\n".join(str(item.get("new_text") or "") for item in equipment_items)[:500],
"original_visual_ocr": (table_match[1]["rows"] if table_match else original_tables[0][1]["rows"])
if original_tables
else None,
"returned_visual_ocr": (table_match[3]["rows"] if table_match else returned_tables[0][1]["rows"])
if returned_tables
else None,
}
diagnostic_items.append(table_diagnostic)
if table_match:
table_diagnostic.update({"decision": "ignored", "reason": "same_visual_equipment_table"})
ignored_item_ids.update(id(item) for item in equipment_items)
ignored_item_ids.update(id(item) for item in clauses if _is_empty_commercial_companion(item))
else:
reason = (
"equipment_table_not_recognized"
if not original_tables or not returned_tables
else "visual_table_differs"
)
table_diagnostic.update({"decision": "kept", "reason": reason})
_log_diagnostic(review_no, table_diagnostic)
if ignored_item_ids:
result["clauses_json"] = [item for item in clauses if id(item) not in ignored_item_ids]
_refresh_focus_lights(result)
ignored = len(ignored_item_ids)
kept = len(candidate_item_ids - ignored_item_ids)
_write_diagnostics(
result,
status="complete",
mixed_extraction=True,
checked=len(pending_text_candidates) + (1 if equipment_items else 0),
ignored=ignored,
kept=kept,
items=diagnostic_items,
)
return result
@@ -81,7 +81,10 @@ def _run_platform_job_in_process(task: ScheduleTask, run: ScheduleRun) -> Schedu
from app.services.schedule.job_registry import run_platform_job
key = normalize_platform_api_path(task.platform_api_path)
# [STEP 1] 合并而非覆盖:保留会话触发写入的 run_options 等字段
existing = run.api_request_json if isinstance(run.api_request_json, dict) else {}
payload = {
**existing,
"run_no": run.run_no,
"schedule_task_id": task.id,
"schedule_name": task.name,
@@ -0,0 +1,346 @@
"""
backend/app/services/schedule/queue_service.py
用途:把手动与 Cron 排程统一写入通用 Job 队列,并维护 ScheduleRun 业务状态。
依赖:models.ScheduleTask/ScheduleRun、jobs.queue、schedule timezone 与 RPA 收口服务。
逻辑:API 只创建 queued run;独立 schedule worker 扫描到期任务、领取 Job 后执行 scheduler_service。
"""
from __future__ import annotations
from datetime import datetime
from flask import current_app
from app import db
from app.jobs.queue import enqueue, fail_job, finish_job, recover_stale_jobs
from app.jobs.types import JobType
from app.models import Job, ScheduleRun, ScheduleTask
from app.services.schedule.shipping_inventory_rpa_finalize import (
recover_all_stale_awaiting_rpa_schedule_runs,
recover_stale_awaiting_rpa_schedule_runs,
)
from app.services.schedule.timezone_util import compute_next_run_at, utc_now_naive
_worker_initialized = False
def _active_run(task_id: int) -> ScheduleRun | None:
"""返回同一排程当前 queued/running 的运行记录,防止并发重复执行。"""
return (
db.session.query(ScheduleRun)
.filter(
ScheduleRun.schedule_task_id == int(task_id),
ScheduleRun.status.in_(("queued", "running")),
)
.order_by(ScheduleRun.id.asc())
.first()
)
def _advance_next_run(task: ScheduleTask) -> None:
"""Cron 触发入队后立即推进下次执行时间;无后续时间时停用任务。"""
if task.cron_expr:
task.next_run_at = compute_next_run_at(
task.cron_expr,
timezone_name=getattr(task, "schedule_timezone", None),
)
if task.next_run_at is None:
task.enabled = False
else:
task.next_run_at = None
def _create_queued_run(
task: ScheduleTask,
*,
trigger_type: str,
triggered_by_user_id: int | None,
) -> tuple[ScheduleRun, int]:
"""
在当前事务创建 ScheduleRun 与对应通用 Job。
Args:
task: 已由调用方锁定的排程任务。
trigger_type: `manual` 或 `cron`,禁止传入未知触发类型。
triggered_by_user_id: 手动触发用户 ID;Cron 为 None。
Returns:
`(ScheduleRun, job_id)`;调用方负责提交事务。
"""
normalized_trigger = str(trigger_type or "").strip().lower()
if normalized_trigger not in {"manual", "cron"}:
raise ValueError(f"unsupported schedule trigger_type={trigger_type!r}")
from app.services.schedule.scheduler_service import _generate_run_no
run = ScheduleRun(
run_no=_generate_run_no(),
schedule_task_id=task.id,
trigger_type=normalized_trigger,
triggered_by_user_id=triggered_by_user_id,
started_at=None,
status="queued",
)
db.session.add(run)
db.session.flush()
job_id = enqueue(
JobType.SCHEDULE_RUN,
{
"schedule_task_id": task.id,
"schedule_run_id": run.id,
"trigger_type": normalized_trigger,
"triggered_by_user_id": triggered_by_user_id,
},
domain="schedule",
business_ref=f"schedule_run:{run.id}",
created_by_id=triggered_by_user_id,
max_attempts=3,
message="排程等待后台执行",
dedupe_active=False,
commit=False,
)
return run, job_id
def enqueue_manual_schedule_run(
task_id: int,
*,
triggered_by_user_id: int | None,
) -> tuple[ScheduleRun, int, bool]:
"""
手动触发排程并写入 schedule 队列。
核心逻辑:锁定 ScheduleTask 后复检 queued/running;已有活动记录时直接返回,
否则同事务创建 ScheduleRun 与 Job,避免接口线程承担长耗时执行。
Returns:
`(run, job_id, created)`;created=False 表示已有活动 run。
"""
task = (
db.session.query(ScheduleTask)
.filter(ScheduleTask.id == int(task_id))
.with_for_update()
.first()
)
if task is None:
raise LookupError(f"schedule task {task_id} not found")
recover_stale_awaiting_rpa_schedule_runs(task)
active = _active_run(task.id)
if active is not None:
job = (
db.session.query(Job)
.filter(
Job.domain == "schedule",
Job.job_type == JobType.SCHEDULE_RUN.value,
Job.status.in_(("queued", "running")),
Job.business_ref == f"schedule_run:{active.id}",
)
.order_by(Job.id.asc())
.first()
)
return active, int(job.id) if job else 0, False
run, job_id = _create_queued_run(
task,
trigger_type="manual",
triggered_by_user_id=triggered_by_user_id,
)
db.session.commit()
return run, job_id, True
def enqueue_due_schedule_runs(*, limit: int = 5) -> int:
"""
扫描到期排程并入队,供独立 schedule worker 每轮轮询调用。
核心逻辑:`FOR UPDATE SKIP LOCKED` 保证多 worker 不会重复调度;同任务已有
queued/running 时保留原到期时间,待该 run 完成后立即补跑;无活动 run 时同事务
创建 run/job 并推进时间。
Returns:
本轮新建的 schedule Job 数量。
"""
now = utc_now_naive()
tasks = (
db.session.query(ScheduleTask)
.filter(
ScheduleTask.enabled.is_(True),
ScheduleTask.next_run_at.isnot(None),
ScheduleTask.next_run_at <= now,
)
.order_by(ScheduleTask.next_run_at.asc(), ScheduleTask.id.asc())
.limit(max(1, int(limit or 1)))
.with_for_update(skip_locked=True)
.all()
)
if not tasks:
db.session.rollback()
return 0
created = 0
for task in tasks:
if _active_run(task.id) is None:
_create_queued_run(task, trigger_type="cron", triggered_by_user_id=None)
_advance_next_run(task)
created += 1
db.session.commit()
return created
def _sync_run_after_stale_job(job: Job) -> None:
"""通用 Job 超时回收后同步 ScheduleRun,避免业务状态永久停留在 running。"""
payload = job.payload_json if isinstance(job.payload_json, dict) else {}
run_id = int(payload.get("schedule_run_id") or 0)
run = db.session.get(ScheduleRun, run_id) if run_id else None
if run is None or run.status not in {"queued", "running"}:
return
if job.status == "queued":
run.status = "queued"
run.started_at = None
run.error_message = "后台执行超时,等待重试"
elif job.status in {"failed", "dead", "cancelled"}:
run.status = "failed"
run.finished_at = datetime.utcnow()
run.error_message = job.error_message or "后台执行超时"
def prepare_schedule_queue() -> int:
"""
执行 schedule worker 的恢复维护、到期扫描和超时 Job 回收。
Returns:
本轮新入队的到期排程数量。
"""
global _worker_initialized
timeout_seconds = float(current_app.config.get("SCHEDULE_JOB_RUNNING_TIMEOUT_SECONDS", 7200))
recover_stale_jobs(
domain="schedule",
timeout_seconds=timeout_seconds,
job_type=JobType.SCHEDULE_RUN,
on_recovered=_sync_run_after_stale_job,
)
if not _worker_initialized:
# [STEP 1] 兼容升级前由 Web 线程留下的 running 记录;无活动 Job 承接时标记中断。
from app.services.schedule.shipping_inventory_rpa_finalize import is_awaiting_rpa_schedule_run
legacy_running = db.session.query(ScheduleRun).filter(ScheduleRun.status == "running").all()
interrupted = 0
for run in legacy_running:
if is_awaiting_rpa_schedule_run(run):
continue
active_job = (
db.session.query(Job.id)
.filter(
Job.domain == "schedule",
Job.job_type == JobType.SCHEDULE_RUN.value,
Job.business_ref == f"schedule_run:{run.id}",
Job.status.in_(("queued", "running")),
)
.first()
)
if active_job is None:
run.status = "failed"
run.finished_at = datetime.utcnow()
run.error_message = "排程 worker 升级重启,旧执行已中断"
interrupted += 1
if interrupted:
db.session.commit()
current_app.logger.warning("[schedule-worker] closed %d legacy running schedule runs", interrupted)
# [STEP 2] 恢复等待 RPA 的运行与回调清理任务。
recovered = recover_all_stale_awaiting_rpa_schedule_runs()
if recovered:
current_app.logger.info("[schedule-worker] recovered %d stale awaiting RPA runs", recovered)
from app.services.shipping_notice.inventory_rpa_callback_cleanup import (
recover_pending_rpa_callback_cleanup_jobs,
)
cleanup_count, cleanup_warnings = recover_pending_rpa_callback_cleanup_jobs()
if cleanup_count:
current_app.logger.info("[schedule-worker] processed %d RPA cleanup jobs", cleanup_count)
if cleanup_warnings:
current_app.logger.warning("[schedule-worker] RPA cleanup warnings: %s", "; ".join(cleanup_warnings[:5]))
_worker_initialized = True
try:
from app.services.shipping_notice.rpa_worker_heartbeat_alert import maybe_alert_rpa_worker_status
maybe_alert_rpa_worker_status(force=False)
except Exception as exc:
db.session.rollback()
current_app.logger.warning("[schedule-worker] RPA heartbeat alert check failed: %s", exc)
return enqueue_due_schedule_runs()
def execute_schedule_job(*, job_id: int, run_id: int, logger) -> ScheduleRun | None:
"""
执行已领取的排程 Job,并同步 Job 与 ScheduleRun 终态。
Args:
job_id: 通用 Job 主键。
run_id: ScheduleRun 主键。
logger: worker logger。
Returns:
已执行的 ScheduleRun;业务记录已被删除时返回 None 并将 Job 正常收口。
"""
run = db.session.get(ScheduleRun, int(run_id))
if run is None:
finish_job(job_id, result={"schedule_run_id": run_id, "status": "deleted"}, message="排程已删除")
return None
task = db.session.get(ScheduleTask, run.schedule_task_id)
if task is None:
finish_job(job_id, result={"schedule_run_id": run_id, "status": "task_deleted"}, message="排程已删除")
return None
if run.status in {"success", "failed", "partial_failed"}:
finish_job(
job_id,
result={"schedule_run_id": run.id, "status": run.status},
message="排程已处于终态",
)
return run
from app.services.schedule.scheduler_service import run_task_now
try:
run.status = "running"
run.started_at = run.started_at or datetime.utcnow()
run.error_message = None
db.session.commit()
result_run = run_task_now(
task,
trigger_type=run.trigger_type,
triggered_by_user_id=run.triggered_by_user_id,
run=run,
)
finish_job(
job_id,
result={"schedule_run_id": result_run.id, "status": result_run.status},
message="排程执行完成",
)
return result_run
except Exception as exc:
db.session.rollback()
job = db.session.get(Job, int(job_id))
run = db.session.get(ScheduleRun, int(run_id))
retrying = bool(job and int(job.attempts or 0) < int(job.max_attempts or 1))
if run and run.status in {"queued", "running"} and not (
run.status == "running" and isinstance(run.response_summary_json, dict) and run.response_summary_json.get("awaiting_rpa")
):
run.status = "queued" if retrying else "failed"
run.started_at = None if retrying else run.started_at
run.finished_at = None if retrying else datetime.utcnow()
run.error_message = str(exc)[:1000]
db.session.commit()
owned_attempt = int(job.attempts or 0) if job is not None else None
fail_job(
job_id,
error=str(exc),
retryable=True,
owned_attempt=owned_attempt,
)
logger.exception("schedule run failed run_id=%s job_id=%s", run_id, job_id)
return run
@@ -1,15 +1,14 @@
"""
backend/app/services/schedule/scheduler_service.py
用途:排程任务生命周期(创建/更新/立即执行)与后台调度 worker。
用途:排程任务生命周期(创建/更新)与单次运行执行器。
依赖:schedule_contract、job_params、cron_util、timezone_util、excel_service、wecom_notify、kb_sync。
逻辑:api/schedule/tasks.py 与 import_service 调用 create_task/update_task/enable_task;
job_params 在本层经 normalize_job_params_for_contract 唯一归一化(含切换 platform_api_path
未传参时重置默认值);run_task_now 经 resolve_schedule_executor 分发 handler。
未传参时重置默认值);schedule worker 调用 run_task_now 并经 resolve_schedule_executor 分发 handler。
"""
from __future__ import annotations
import threading
import time
import uuid
from datetime import datetime
@@ -26,33 +25,54 @@ from app.services.schedule import resolve_schedule_executor, resolve_schedule_he
from app.services.schedule.shipping_inventory_rpa_finalize import (
apply_deferred_schedule_run_state,
is_awaiting_rpa_schedule_run,
recover_all_stale_awaiting_rpa_schedule_runs,
recover_stale_awaiting_rpa_schedule_runs,
should_defer_schedule_run_finalization,
)
from app.services.schedule.job_params import normalize_job_params_for_contract
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id
from app.services.schedule.timezone_util import compute_next_run_at, normalize_schedule_timezone, utc_now_naive
_worker_started = False
_worker_lock = threading.Lock()
_cancelled_runs: set[int] = set()
_cancel_lock = threading.Lock()
from app.services.schedule.timezone_util import compute_next_run_at, normalize_schedule_timezone
def request_cancel_run(run_id: int) -> None:
with _cancel_lock:
_cancelled_runs.add(run_id)
"""
持久化取消指定排程运行,供 Web 与独立 worker 跨进程协作。
核心逻辑:将对应 queued/running 通用 Job 标记为 cancelled;执行器通过
ScheduleRun 状态/存在性复检停止可中断的长循环。
"""
from app.jobs.types import JobType
from app.models import Job
now = datetime.utcnow()
jobs = (
db.session.query(Job)
.filter(
Job.domain == "schedule",
Job.job_type == JobType.SCHEDULE_RUN.value,
Job.business_ref == f"schedule_run:{int(run_id)}",
Job.status.in_(("queued", "running")),
)
.all()
)
for job in jobs:
job.status = "cancelled"
job.message = "排程已取消"
job.error_message = "排程已删除,执行中断"
job.locked_by = None
job.locked_at = None
job.finished_at = now
job.updated_at = now
def is_run_cancelled(run_id: int) -> bool:
with _cancel_lock:
return run_id in _cancelled_runs
"""通过数据库业务状态判断运行是否已被跨进程取消或删除。"""
run = db.session.get(ScheduleRun, int(run_id))
return run is None or str(run.status or "") not in {"queued", "running"}
def clear_cancelled_run(run_id: int) -> None:
with _cancel_lock:
_cancelled_runs.discard(run_id)
"""兼容旧调用;取消状态已持久化,无需清理进程内内存。"""
return None
def _generate_schedule_no() -> str:
@@ -122,6 +142,11 @@ def _build_schedule_run_wecom_description(run: ScheduleRun) -> str:
def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
"""
排程完成后的通用企微通知。
核心逻辑:若 response_summary_json.domain_notification_managed=true(如立账凭证检核),
则跳过以免与领域缺件/失败告警重复。
"""
from app.services.wecom_notify import (
upload_wecom_temp_media,
send_wecom_file_message,
@@ -131,6 +156,12 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
_get_enabled_events,
)
# 领域自行管理通知时跳过通用完成通知,避免重复刷屏
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
if summary.get('domain_notification_managed'):
run.wecom_notify_error = 'domain_notification_managed'
return
if not current_app.config.get('WECOM_NOTIFY_ENABLED', True):
run.wecom_notify_error = 'WECOM_NOTIFY_ENABLED=false'
return
@@ -610,129 +641,3 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
current_app.logger.error("[schedule-run] wecom notify failed: %s", wecom_exc)
return run
def start_scheduler(app):
global _worker_started
with _worker_lock:
if _worker_started:
return
_worker_started = True
if not bool(app.config.get("SCHEDULE_WORKER_ENABLED", True)):
return
import os
if os.environ.get('WERKZEUG_RUN_MAIN') == 'true' or not app.debug:
pass
else:
_worker_started = False
return
def _loop():
with app.app_context():
stale = db.session.query(ScheduleTask).filter(
ScheduleTask.enabled.is_(True),
ScheduleTask.next_run_at.isnot(None),
ScheduleTask.next_run_at <= utc_now_naive(),
).all()
for t in stale:
if t.cron_expr:
t.next_run_at = compute_next_run_at(t.cron_expr, timezone_name=getattr(t, "schedule_timezone", None))
if t.next_run_at is None:
t.enabled = False
else:
t.next_run_at = None
if stale:
db.session.commit()
current_app.logger.info("[schedule-worker] reset %d stale next_run_at on startup", len(stale))
stuck = db.session.query(ScheduleRun).filter(
ScheduleRun.status == "running",
).all()
cleaned = 0
for r in stuck:
if is_awaiting_rpa_schedule_run(r):
continue
r.status = "failed"
r.error_message = "服务重启,执行中断"
r.finished_at = datetime.utcnow()
cleaned += 1
if cleaned:
db.session.commit()
current_app.logger.info(
"[schedule-worker] cleaned %d stuck running runs on startup (skipped awaiting RPA)",
cleaned,
)
recovered_awaiting = recover_all_stale_awaiting_rpa_schedule_runs()
if recovered_awaiting:
current_app.logger.info(
"[schedule-worker] recovered %d stale awaiting RPA runs on startup",
recovered_awaiting,
)
from app.services.shipping_notice.inventory_rpa_callback_cleanup import (
recover_pending_rpa_callback_cleanup_jobs,
)
cleanup_count, cleanup_warnings = recover_pending_rpa_callback_cleanup_jobs()
if cleanup_count:
current_app.logger.info(
"[schedule-worker] processed %d RPA callback cleanup job(s) on startup",
cleanup_count,
)
if cleanup_warnings:
current_app.logger.warning(
"[schedule-worker] RPA callback cleanup warnings: %s",
"; ".join(cleanup_warnings[:5]),
)
from app.services.shipping_notice.rpa_worker_heartbeat_alert import maybe_alert_rpa_worker_status
maybe_alert_rpa_worker_status(force=True)
while True:
try:
from app.services.shipping_notice.rpa_worker_heartbeat_alert import (
maybe_alert_rpa_worker_status,
)
maybe_alert_rpa_worker_status()
now = utc_now_naive()
due_tasks = db.session.query(ScheduleTask).filter(
ScheduleTask.enabled.is_(True),
ScheduleTask.next_run_at.isnot(None),
ScheduleTask.next_run_at <= now,
).limit(5).with_for_update(skip_locked=True).all()
for task in due_tasks:
recover_stale_awaiting_rpa_schedule_runs(task)
has_running = db.session.query(ScheduleRun).filter(
ScheduleRun.schedule_task_id == task.id,
ScheduleRun.status == "running",
).first()
if has_running:
if task.cron_expr:
task.next_run_at = compute_next_run_at(task.cron_expr, timezone_name=getattr(task, "schedule_timezone", None))
db.session.commit()
continue
try:
run_task_now(task, trigger_type="cron", triggered_by_user_id=None)
except Exception as e:
current_app.logger.error("[schedule-worker] task_id=%s run failed: %s", task.id, e, exc_info=True)
db.session.rollback()
if task.cron_expr:
task.next_run_at = compute_next_run_at(task.cron_expr, timezone_name=getattr(task, "schedule_timezone", None))
if task.next_run_at is None:
task.enabled = False
else:
task.next_run_at = None
db.session.commit()
except Exception:
db.session.rollback()
time.sleep(30)
t = threading.Thread(target=_loop, daemon=True, name="schedule-worker")
t.start()
@@ -0,0 +1,44 @@
"""
backend/app/services/schedule/voucher_check_job.py
用途:立账凭证检核 platform_job 薄封装。
依赖:voucher_check.runner、excel_rows 表头注册。
逻辑:job_registry 注册 accounting-voucher-check 后由 schedule worker / 会话触发调用。
"""
from __future__ import annotations
from typing import Any
from app.models import ScheduleRun, ScheduleTask
from app.services.schedule import register_schedule_header
from app.services.voucher_check.excel_rows import (
VOUCHER_CHECK_HEADER_LABELS,
VOUCHER_CHECK_HEADER_ORDER,
)
from app.services.voucher_check.runner import run_voucher_check_batch
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
_HEADERS_REGISTERED = False
def _ensure_headers() -> None:
global _HEADERS_REGISTERED
if _HEADERS_REGISTERED:
return
register_schedule_header(
"accounting-voucher-check",
VOUCHER_CHECK_HEADER_ORDER,
VOUCHER_CHECK_HEADER_LABELS,
)
_HEADERS_REGISTERED = True
def run_voucher_check_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
"""
执行立账凭证检核排程。
核心逻辑:注册 Excel 表头后委托 runner;日批默认 incremental。
"""
_ensure_headers()
return run_voucher_check_batch(task, run)
+21 -4
View File
@@ -1,3 +1,11 @@
"""
services/text2sql.py
Purpose: Translate natural-language ERP asset queries into safe Oracle SQL and format results.
Dependencies: Oracle client, LLM client, and docs/integrations/erp/text2sql_schema.md.
Flow: The chat fast route calls this service; this service loads the ERP schema to build SQL prompts.
"""
import json
import os
import re
@@ -424,17 +432,26 @@ class Text2SQLService:
@classmethod
def get_schema(cls):
"""
Load the ERP schema document used as context for Text2SQL generation.
The environment override is checked first, followed by the packaged and source-tree
locations, so the same schema is available in containers and local development.
Returns:
str: UTF-8 schema text, or a diagnostic string when no schema document is available.
"""
if cls._schema_text is None:
schema_filename = '(表+字段).md'
schema_relative_path = os.path.join('integrations', 'erp', 'text2sql_schema.md')
env_path = (os.getenv("TEXT2SQL_SCHEMA_PATH") or "").strip()
candidate_paths = []
if env_path:
candidate_paths.append(env_path)
candidate_paths.extend([
os.path.join(cls._backend_dir(), 'docs', schema_filename),
os.path.join(cls._project_root(), 'docs', schema_filename),
os.path.join(os.getcwd(), 'docs', schema_filename),
os.path.join(cls._backend_dir(), 'docs', schema_relative_path),
os.path.join(cls._project_root(), 'docs', schema_relative_path),
os.path.join(os.getcwd(), 'docs', schema_relative_path),
])
unique_paths = []
@@ -0,0 +1,11 @@
"""
backend/app/services/voucher_check/__init__.py
用途:立账凭证检核领域服务包入口。
依赖:config / runner / query_service 等子模块。
逻辑:platform Job 与 Tool/工作台 API 从此包调用 runner 与查询能力。
"""
from app.services.voucher_check.runner import run_voucher_check_batch
__all__ = ["run_voucher_check_batch"]
@@ -0,0 +1,262 @@
"""
backend/app/services/voucher_check/config.py
用途:解析立账凭证检核环境变量与 ScheduleTask.job_params,校验目录模板与文件名规则。
依赖:Flask current_app.config、core.errors.ValidationError。
逻辑:runner / share_scanner / erp_repository 启动前调用;非法配置抛 VOUCHER_CHECK.CONFIG_INVALID。
"""
from __future__ import annotations
import json
import os
import re
from dataclasses import dataclass
from typing import Any
from flask import has_app_context, current_app
from app.core.errors import ValidationError
_ALLOWED_TEMPLATE_KEYS = {"root", "YYYY", "MM", "invoice_no"}
_TEMPLATE_TOKEN_RE = re.compile(r"\{([^{}]+)\}")
_UNSAFE_FILENAME_RE = re.compile(r"[/\\\x00]|(\.\.)")
DEFAULT_REQUIRED_FILES: list[dict[str, Any]] = [
{
"code": "price_check_sheet",
"name": "核价单",
"required": True,
"accepted_filenames": ["核价单.pdf"],
},
{
"code": "purchase_order",
"name": "采购单",
"required": True,
"accepted_filenames": ["采购单.pdf"],
},
]
DEFAULT_JOB_PARAMS: dict[str, Any] = {
"scope_code": "HXJM",
"directory_template": "{root}/{YYYY}/{MM}/{invoice_no}",
"required_files": DEFAULT_REQUIRED_FILES,
"filename_case_sensitive": True,
"notify_missing_enabled": True,
"notify_failure_enabled": True,
"same_day_dedup_enabled": True,
}
@dataclass(frozen=True)
class RequiredFileRule:
"""单条必检材料规则。"""
code: str
name: str
required: bool
accepted_filenames: tuple[str, ...]
@dataclass(frozen=True)
class VoucherCheckConfig:
"""运行期检核配置快照。"""
scope_code: str
directory_template: str
required_files: tuple[RequiredFileRule, ...]
filename_case_sensitive: bool
notify_missing_enabled: bool
notify_failure_enabled: bool
same_day_dedup_enabled: bool
local_root: str
share_unc: str
healthcheck_relative_path: str
erp_dsn: str
erp_username: str
erp_password: str
erp_timeout_seconds: int = 30
def _config_invalid(message: str, *, details: dict[str, Any] | None = None) -> ValidationError:
return ValidationError(
message,
code="VOUCHER_CHECK.CONFIG_INVALID",
details=details or {},
)
def _as_bool(value: Any, default: bool) -> bool:
if value is None:
return default
if isinstance(value, bool):
return value
text = str(value).strip().lower()
if text in {"1", "true", "yes", "on"}:
return True
if text in {"0", "false", "no", "off"}:
return False
return default
def _parse_required_files(raw: Any) -> list[RequiredFileRule]:
if raw is None:
raw = DEFAULT_REQUIRED_FILES
if isinstance(raw, str):
try:
raw = json.loads(raw)
except json.JSONDecodeError as exc:
raise _config_invalid("required_files JSON 非法", details={"error": str(exc)}) from exc
if not isinstance(raw, list) or not raw:
raise _config_invalid("required_files 至少包含一个必检项")
rules: list[RequiredFileRule] = []
for idx, item in enumerate(raw):
if not isinstance(item, dict):
raise _config_invalid(f"required_files[{idx}] 必须为对象")
code = str(item.get("code") or "").strip()
name = str(item.get("name") or code).strip()
accepted = item.get("accepted_filenames") or []
if not code:
raise _config_invalid(f"required_files[{idx}].code 不能为空")
if not isinstance(accepted, list) or not accepted:
raise _config_invalid(f"required_files[{idx}].accepted_filenames 不能为空")
filenames: list[str] = []
for fname in accepted:
text = str(fname or "").strip()
if not text:
raise _config_invalid(f"required_files[{idx}] 存在空文件名")
if "*" in text or "?" in text or _UNSAFE_FILENAME_RE.search(text):
raise _config_invalid(
f"required_files[{idx}] 文件名禁止通配/路径字符: {text}",
)
filenames.append(text)
rules.append(
RequiredFileRule(
code=code,
name=name or code,
required=_as_bool(item.get("required"), True),
accepted_filenames=tuple(filenames),
)
)
if not any(r.required for r in rules):
raise _config_invalid("required_files 至少包含一个 required=true 项")
return rules
def validate_directory_template(template: str) -> str:
"""
校验目录模板占位符。
核心逻辑:仅允许 {root}/{YYYY}/{MM}/{invoice_no} 四类占位符,且四者皆须出现。
"""
text = str(template or "").strip().replace("\\", "/")
if not text:
raise _config_invalid("directory_template 不能为空")
tokens = _TEMPLATE_TOKEN_RE.findall(text)
unknown = sorted({t for t in tokens if t not in _ALLOWED_TEMPLATE_KEYS})
if unknown:
raise _config_invalid(
"directory_template 含非法占位符",
details={"unknown": unknown},
)
missing = sorted(_ALLOWED_TEMPLATE_KEYS - set(tokens))
if missing:
raise _config_invalid(
"directory_template 缺少必要占位符",
details={"missing": missing},
)
return text
def load_voucher_check_config(job_params: dict[str, Any] | None = None) -> VoucherCheckConfig:
"""
合并 env 与 job_params,返回校验后的检核配置。
核心逻辑:敏感凭据只读环境变量;业务规则以 job_params 为准,缺省用 DEFAULT_JOB_PARAMS。
"""
params = dict(DEFAULT_JOB_PARAMS)
if isinstance(job_params, dict):
params.update({k: v for k, v in job_params.items() if v is not None})
scope_code = str(params.get("scope_code") or "HXJM").strip().upper() or "HXJM"
if scope_code != "HXJM":
raise _config_invalid("一期仅支持 scope_code=HXJM", details={"scope_code": scope_code})
template = validate_directory_template(
str(params.get("directory_template") or DEFAULT_JOB_PARAMS["directory_template"])
)
required_files = _parse_required_files(params.get("required_files"))
cfg = current_app.config if has_app_context() else {}
local_root = str(
cfg.get("VOUCHER_CHECK_LOCAL_ROOT")
or os.getenv("VOUCHER_CHECK_LOCAL_ROOT")
or ""
).strip()
share_unc = str(
cfg.get("VOUCHER_CHECK_SHARE_UNC")
or os.getenv("VOUCHER_CHECK_SHARE_UNC")
or ""
).strip()
healthcheck = str(
cfg.get("VOUCHER_CHECK_SHARE_HEALTHCHECK_RELATIVE_PATH")
or os.getenv("VOUCHER_CHECK_SHARE_HEALTHCHECK_RELATIVE_PATH")
or ".hxops-share-ready"
).strip() or ".hxops-share-ready"
# 开发机可临时用 UNC;Linux/容器必须 LOCAL_ROOT
if not local_root and not share_unc:
raise _config_invalid("未配置 VOUCHER_CHECK_LOCAL_ROOT 或 VOUCHER_CHECK_SHARE_UNC")
erp_dsn = str(
cfg.get("VOUCHER_CHECK_ERP_DSN")
or os.getenv("VOUCHER_CHECK_ERP_DSN")
or cfg.get("ERP_DB_DSN")
or os.getenv("ERP_DB_DSN")
or ""
).strip()
erp_username = str(
cfg.get("VOUCHER_CHECK_ERP_USERNAME")
or os.getenv("VOUCHER_CHECK_ERP_USERNAME")
or ""
).strip()
erp_password = str(
cfg.get("VOUCHER_CHECK_ERP_PASSWORD")
or os.getenv("VOUCHER_CHECK_ERP_PASSWORD")
or ""
)
if not erp_dsn or not erp_username:
raise _config_invalid("未配置 VOUCHER_CHECK_ERP_DSN / VOUCHER_CHECK_ERP_USERNAME")
timeout = int(
cfg.get("VOUCHER_CHECK_ERP_TIMEOUT_SECONDS")
or os.getenv("VOUCHER_CHECK_ERP_TIMEOUT_SECONDS")
or 30
)
return VoucherCheckConfig(
scope_code=scope_code,
directory_template=template,
required_files=tuple(required_files),
filename_case_sensitive=_as_bool(params.get("filename_case_sensitive"), True),
notify_missing_enabled=_as_bool(params.get("notify_missing_enabled"), True),
notify_failure_enabled=_as_bool(params.get("notify_failure_enabled"), True),
same_day_dedup_enabled=_as_bool(params.get("same_day_dedup_enabled"), True),
local_root=local_root,
share_unc=share_unc,
healthcheck_relative_path=healthcheck,
erp_dsn=erp_dsn,
erp_username=erp_username,
erp_password=erp_password,
erp_timeout_seconds=max(1, timeout),
)
def resolve_share_root(config: VoucherCheckConfig) -> str:
"""
解析实际扫描根路径。
核心逻辑:优先 LOCAL_ROOT(容器/Linux);无则回退 share_unc(开发机)。
"""
root = (config.local_root or config.share_unc or "").strip()
if not root:
raise _config_invalid("共享盘根路径为空")
return root
@@ -0,0 +1,146 @@
"""
backend/app/services/voucher_check/erp_repository.py
用途:从 Oracle HXJM 套账 apa_file 查询当前自然月发票号集合。
依赖:oracledb、Text2SQLService._init_oracle_client、voucher_check.config。
逻辑:runner 阶段 A 调用;仅只读 SELECT;失败映射为 VOUCHER_CHECK.ERP_UNAVAILABLE。
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import date, datetime
from zoneinfo import ZoneInfo
from app.core.errors import ServiceUnavailableError
from app.services.voucher_check.config import VoucherCheckConfig
_TZ = ZoneInfo("Asia/Shanghai")
_INVOICE_SQL = """
SELECT DISTINCT
TRIM(apa08) AS invoice_no,
TRUNC(apa09) AS invoice_date
FROM apa_file
WHERE apa09 >= :period_start
AND apa09 < :next_period_start
AND TRIM(apa08) IS NOT NULL
ORDER BY TRUNC(apa09), TRIM(apa08)
"""
@dataclass(frozen=True)
class ErpInvoiceRow:
"""ERP 当月发票行。"""
invoice_no: str
invoice_date: date | None
def current_period_bounds(now: datetime | None = None) -> tuple[date, date, datetime, datetime]:
"""
按 Asia/Shanghai 计算当前自然月起止。
核心逻辑:不用 Oracle SYSDATE,保证手动触发与日批口径一致。
Returns:
(period_month_first, next_month_first, period_start_dt, next_period_start_dt)
"""
base = now.astimezone(_TZ) if now and now.tzinfo else (now or datetime.now(_TZ))
if base.tzinfo is None:
base = base.replace(tzinfo=_TZ)
else:
base = base.astimezone(_TZ)
period_month = date(base.year, base.month, 1)
if base.month == 12:
next_month = date(base.year + 1, 1, 1)
else:
next_month = date(base.year, base.month + 1, 1)
period_start = datetime(period_month.year, period_month.month, 1, 0, 0, 0, tzinfo=_TZ)
next_start = datetime(next_month.year, next_month.month, 1, 0, 0, 0, tzinfo=_TZ)
return period_month, next_month, period_start, next_start
def fetch_month_invoices(
config: VoucherCheckConfig,
*,
now: datetime | None = None,
) -> tuple[date, list[ErpInvoiceRow]]:
"""
查询当前自然月发票清单。
Args:
config: 含 Oracle DSN/账号的检核配置。
now: 可选时钟(测试注入)。
Returns:
(period_month, invoices)
Raises:
ServiceUnavailableError: Oracle 不可用。
"""
period_month, _next_month, period_start, next_start = current_period_bounds(now)
try:
import oracledb
except ImportError as exc:
raise ServiceUnavailableError(
"Oracle 驱动不可用",
code="VOUCHER_CHECK.ERP_UNAVAILABLE",
) from exc
from flask import current_app
from app.services.text2sql import Text2SQLService
connection = None
try:
Text2SQLService._init_oracle_client(oracledb)
connection = oracledb.connect(
user=config.erp_username,
password=config.erp_password,
dsn=config.erp_dsn,
)
connection.call_timeout = max(1, int(config.erp_timeout_seconds)) * 1000
cursor = connection.cursor()
cursor.execute(
_INVOICE_SQL,
{
"period_start": period_start.replace(tzinfo=None),
"next_period_start": next_start.replace(tzinfo=None),
},
)
rows: list[ErpInvoiceRow] = []
seen: set[str] = set()
for raw_no, raw_date in cursor:
invoice_no = str(raw_no or "").strip()
if not invoice_no or invoice_no in seen:
continue
seen.add(invoice_no)
invoice_date: date | None = None
if raw_date is not None:
if isinstance(raw_date, datetime):
invoice_date = raw_date.date()
elif isinstance(raw_date, date):
invoice_date = raw_date
rows.append(ErpInvoiceRow(invoice_no=invoice_no, invoice_date=invoice_date))
return period_month, rows
except ServiceUnavailableError:
raise
except Exception as exc:
try:
current_app.logger.error(
"[voucher-check] ERP query failed dsn=%s error_type=%s",
config.erp_dsn,
type(exc).__name__,
)
except Exception:
pass
raise ServiceUnavailableError(
"Oracle 查询失败",
code="VOUCHER_CHECK.ERP_UNAVAILABLE",
details={"error_type": type(exc).__name__},
) from exc
finally:
if connection is not None:
try:
connection.close()
except Exception:
pass
@@ -0,0 +1,93 @@
"""
backend/app/services/voucher_check/excel_rows.py
用途:把批次明细转换为通用 Excel 导出行与表头。
依赖:无。
逻辑:runner 返回 details;schedule excel_service / register_schedule_header 使用本模块表头。
"""
from __future__ import annotations
from typing import Any
VOUCHER_CHECK_HEADER_ORDER = [
"period",
"scope_code",
"invoice_no",
"invoice_date",
"result",
"folder_exists",
"folder_path",
"matched_files",
"missing_materials",
"material_fingerprint",
"checked_at",
"error_code",
"error_message",
]
VOUCHER_CHECK_HEADER_LABELS = {
"period": "检核月份",
"scope_code": "账套",
"invoice_no": "发票号",
"invoice_date": "发票日期",
"result": "结论",
"folder_exists": "发票目录是否存在",
"folder_path": "共享盘相对路径",
"matched_files": "已找到材料",
"missing_materials": "缺失材料",
"material_fingerprint": "目录元数据指纹",
"checked_at": "实际检核时间",
"error_code": "技术错误码",
"error_message": "技术错误摘要",
}
_RESULT_LABELS = {
"complete": "齐全",
"missing": "缺资料",
"skipped": "跳过",
"technical_error": "技术异常",
}
def _fmt_matched(matched: dict[str, Any] | None) -> str:
if not matched:
return ""
return "; ".join(f"{k}={v}" for k, v in matched.items())
def _fmt_missing(missing: list[dict[str, Any]] | None) -> str:
if not missing:
return ""
parts = []
for item in missing:
name = item.get("name") or item.get("code") or ""
code = item.get("code") or ""
parts.append(f"{name}({code})" if code and name != code else str(name or code))
return "; ".join(parts)
def to_excel_detail_row(item: dict[str, Any], *, period: str, scope_code: str) -> dict[str, Any]:
"""
将内存结果行转为 Excel details 行。
"""
result = str(item.get("result") or "")
checked_at = item.get("checked_at")
invoice_date = item.get("invoice_date")
return {
"period": period,
"scope_code": scope_code,
"invoice_no": item.get("invoice_no"),
"invoice_date": invoice_date.isoformat() if hasattr(invoice_date, "isoformat") else invoice_date,
"result": _RESULT_LABELS.get(result, result),
"folder_exists": "是" if item.get("folder_exists") else "否",
"folder_path": item.get("folder_path") or "",
"matched_files": _fmt_matched(item.get("matched_files")),
"missing_materials": _fmt_missing(item.get("missing_materials")),
"material_fingerprint": item.get("material_fingerprint") or "",
"checked_at": checked_at.isoformat(sep=" ", timespec="seconds")
if hasattr(checked_at, "isoformat")
else (checked_at or ""),
"error_code": item.get("error_code") or "",
"error_message": item.get("error_message") or "",
}
@@ -0,0 +1,34 @@
"""
backend/app/services/voucher_check/fingerprint.py
用途:根据共享盘目录直接子文件的元数据生成稳定 SHA-256 指纹。
依赖:标准库 hashlib / json。
逻辑:share_scanner 枚举文件后调用;runner 用指纹判断齐全票是否可跳过。
"""
from __future__ import annotations
import hashlib
import json
from typing import Iterable, Sequence
def build_material_fingerprint(
entries: Sequence[tuple[str, int, int]] | Iterable[tuple[str, int, int]],
) -> str:
"""
对直接子文件元数据生成 SHA-256。
核心逻辑:按文件名排序后序列化为 UTF-8 JSON,再哈希;不读取文件内容。
Args:
entries: (filename, size, mtime_ns) 列表。
Returns:
64 位十六进制 SHA-256;无文件时对空数组哈希。
"""
normalized = sorted(
[(str(name), int(size), int(mtime_ns)) for name, size, mtime_ns in entries],
key=lambda item: item[0],
)
payload = json.dumps(normalized, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
return hashlib.sha256(payload).hexdigest()
@@ -0,0 +1,205 @@
"""
backend/app/services/voucher_check/notification.py
用途:立账凭证检核缺资料企微 textcard 与批次失败告警。
依赖:wecom_notify、ScheduleTask.notify_user_ids_json、persistence.mark_missing_notified。
逻辑:runner 落库后调用;同票同日节流;设置 domain_notification_managed 避免通用排程重复通知。
"""
from __future__ import annotations
import uuid
from datetime import date, datetime
from typing import Any
from zoneinfo import ZoneInfo
from flask import current_app
from app import db
from app.models import ScheduleRun, ScheduleTask, User
from app.services.voucher_check.persistence import mark_missing_notified
_TZ = ZoneInfo("Asia/Shanghai")
def _recipient_users(task: ScheduleTask) -> list[User]:
user_ids = task.notify_user_ids_json or []
if not user_ids:
return []
users = db.session.query(User).filter(User.id.in_(user_ids)).all()
return [u for u in users if u.wecom_userid]
def _today_shanghai(now: datetime | None = None) -> date:
base = now or datetime.now(_TZ)
if base.tzinfo is None:
base = base.replace(tzinfo=_TZ)
else:
base = base.astimezone(_TZ)
return base.date()
def send_missing_notifications(
*,
task: ScheduleTask,
run: ScheduleRun,
scope_code: str,
period_month: date,
missing_items: list[dict[str, Any]],
same_day_dedup: bool,
enabled: bool,
) -> int:
"""
合并发送缺资料 textcard。
核心逻辑:过滤同日已通知票;成功后才写 last_missing_notified_on。
Returns:
本次实际通知的发票数。
"""
if not enabled or not missing_items:
return 0
if not current_app.config.get("WECOM_NOTIFY_ENABLED", True):
return 0
from app.models.voucher_check import VoucherCheckInvoiceState
from app.services.wecom_notify import (
_build_jump_url,
_create_audit,
send_wecom_textcard_message,
)
today = _today_shanghai()
invoice_nos = [str(i["invoice_no"]).strip() for i in missing_items]
states = (
db.session.query(VoucherCheckInvoiceState)
.filter(
VoucherCheckInvoiceState.scope_code == scope_code,
VoucherCheckInvoiceState.period_month == period_month,
VoucherCheckInvoiceState.invoice_no.in_(invoice_nos),
)
.all()
)
state_map = {s.invoice_no: s for s in states}
to_notify: list[dict[str, Any]] = []
for item in missing_items:
inv = str(item["invoice_no"]).strip()
state = state_map.get(inv)
if same_day_dedup and state and state.last_missing_notified_on == today:
continue
to_notify.append(item)
if not to_notify:
return 0
users = _recipient_users(task)
if not users:
current_app.logger.warning(
"[voucher-check] missing notify skipped: no wecom recipients run_id=%s",
run.id,
)
return 0
sample = "、".join(i["invoice_no"] for i in to_notify[:8])
if len(to_notify) > 8:
sample += "…"
period = period_month.strftime("%Y-%m")
title = f"立账凭证缺资料: {task.name}"
description = (
f"批次 {run.run_no}\n"
f"检核月份 {period}\n"
f"缺资料 {len(to_notify)} 张\n"
f"示例:{sample}\n"
f"完整清单请查看工作台检核记录或 Excel。"
)
ok_any = False
for user in users:
trace_id = uuid.uuid4().hex
jump_url = _build_jump_url(
"/workspace/accounting-voucher-check",
trace_id,
{"task_id": task.id, "run_id": run.id},
)
try:
audit = _create_audit("voucher_check_missing", user, title, description, trace_id)
audit.jump_url = jump_url
data = send_wecom_textcard_message(user.wecom_userid, title, description, jump_url)
if data.get("errcode") == 0:
audit.status = "sent"
ok_any = True
else:
audit.error_code = str(data.get("errcode"))
audit.error_message = str(data.get("errmsg", "unknown"))[:255]
except Exception as exc:
current_app.logger.warning(
"[voucher-check] missing notify failed user=%s err=%s",
user.id,
exc,
)
if ok_any:
mark_missing_notified(
scope_code=scope_code,
period_month=period_month,
invoice_nos=[str(i["invoice_no"]).strip() for i in to_notify],
notified_on=today,
)
db.session.commit()
return len(to_notify)
return 0
def send_failure_alert(
*,
task: ScheduleTask,
run: ScheduleRun,
stage: str,
error_code: str,
error_message: str,
enabled: bool,
) -> None:
"""批次级失败告警(共享盘/Oracle/业务配置异常)。"""
if not enabled:
return
if not current_app.config.get("WECOM_NOTIFY_ENABLED", True):
return
from app.services.wecom_notify import (
_build_jump_url,
_create_audit,
send_wecom_textcard_message,
)
users = _recipient_users(task)
if not users:
return
title = f"立账凭证检核失败: {task.name}"
description = (
f"批次 {run.run_no}\n"
f"失败阶段:{stage}\n"
f"错误码:{error_code}\n"
f"摘要:{(error_message or '')[:200]}\n"
f"run_id={run.id}\n"
f"请检查 Oracle 连接与共享盘挂载/健康标记。"
)
for user in users:
trace_id = uuid.uuid4().hex
jump_url = _build_jump_url(
"/admin/schedules",
trace_id,
{"task_id": task.id, "run_id": run.id},
)
try:
audit = _create_audit("voucher_check_failure", user, title, description, trace_id)
audit.jump_url = jump_url
data = send_wecom_textcard_message(user.wecom_userid, title, description, jump_url)
if data.get("errcode") == 0:
audit.status = "sent"
else:
audit.error_code = str(data.get("errcode"))
audit.error_message = str(data.get("errmsg", "unknown"))[:255]
except Exception as exc:
current_app.logger.warning(
"[voucher-check] failure alert failed user=%s err=%s",
user.id,
exc,
)
db.session.commit()
@@ -0,0 +1,316 @@
{
"openapi": "3.0.3",
"info": {
"title": "HXOPS Accounting Voucher Check Tool API",
"description": "立账凭证检核查询 Tool API:缺资料清单、批次明细、单票最新状态。启动检核请复用 File Check 的 run_file_check(可传 run_options)。鉴权:Authorization Bearer 或 X-Integration-Key(与 FILE_CHECK_TOOL_API_KEY / INTEGRATION_API_KEY 相同)。",
"version": "1.0.0"
},
"servers": [
{
"url": "http://127.0.0.1:5052",
"description": "HXOPS_TOOLS_API_BASE"
}
],
"security": [
{
"BearerAuth": []
},
{
"IntegrationKey": []
}
],
"paths": {
"/api/accounting-voucher-check/tools/tasks/{task_id}/missing": {
"get": {
"operationId": "list_voucher_missing",
"summary": "查询缺资料发票(最新状态)",
"description": "按账套与月份查询 status=missing 的发票;默认当前自然月。",
"tags": ["Accounting Voucher Check"],
"parameters": [
{
"name": "task_id",
"in": "path",
"required": true,
"schema": { "type": "integer", "example": 12 },
"description": "排程任务 ID(Agent 绑定的 schedule_task_id,用于回显)"
},
{
"name": "period",
"in": "query",
"required": false,
"schema": { "type": "string", "example": "2026-08" },
"description": "检核月份 YYYY-MM;缺省为当前自然月"
},
{
"name": "scope_code",
"in": "query",
"required": false,
"schema": { "type": "string", "default": "HXJM", "example": "HXJM" }
},
{
"name": "limit",
"in": "query",
"required": false,
"schema": { "type": "integer", "default": 200, "minimum": 1, "maximum": 1000 }
}
],
"responses": {
"200": {
"description": "成功",
"content": {
"application/json": {
"schema": { "$ref": "#/components/schemas/MissingListResponse" }
}
}
},
"400": { "$ref": "#/components/responses/BadRequest" },
"401": { "$ref": "#/components/responses/Unauthorized" },
"503": { "$ref": "#/components/responses/MissingAuth" }
}
}
},
"/api/accounting-voucher-check/tools/runs/{run_id}/items": {
"get": {
"operationId": "list_voucher_run_items",
"summary": "查询批次发票明细",
"description": "分页返回某 ScheduleRun 的单票结论;可按 result 过滤。",
"tags": ["Accounting Voucher Check"],
"parameters": [
{
"name": "run_id",
"in": "path",
"required": true,
"schema": { "type": "integer", "example": 1001 }
},
{
"name": "result",
"in": "query",
"required": false,
"schema": {
"type": "string",
"enum": ["complete", "missing", "skipped", "technical_error"],
"example": "missing"
}
},
{
"name": "page",
"in": "query",
"required": false,
"schema": { "type": "integer", "default": 1, "minimum": 1 }
},
{
"name": "page_size",
"in": "query",
"required": false,
"schema": { "type": "integer", "default": 50, "minimum": 1, "maximum": 200 }
}
],
"responses": {
"200": {
"description": "成功",
"content": {
"application/json": {
"schema": { "$ref": "#/components/schemas/RunItemsResponse" }
}
}
},
"401": { "$ref": "#/components/responses/Unauthorized" },
"404": { "$ref": "#/components/responses/NotFound" },
"503": { "$ref": "#/components/responses/MissingAuth" }
}
}
},
"/api/accounting-voucher-check/tools/invoices/{invoice_no}/latest": {
"get": {
"operationId": "get_voucher_invoice_latest",
"summary": "查询指定发票最新检核状态",
"description": "返回单票最新状态及近期批次快照;invoice_no 保持业务原值(仅 trim)。",
"tags": ["Accounting Voucher Check"],
"parameters": [
{
"name": "invoice_no",
"in": "path",
"required": true,
"schema": { "type": "string", "example": "INV-20260803001" },
"description": "发票号(apa08 原值)"
},
{
"name": "period",
"in": "query",
"required": false,
"schema": { "type": "string", "example": "2026-08" }
},
{
"name": "scope_code",
"in": "query",
"required": false,
"schema": { "type": "string", "default": "HXJM" }
}
],
"responses": {
"200": {
"description": "成功",
"content": {
"application/json": {
"schema": { "$ref": "#/components/schemas/InvoiceLatestResponse" }
}
}
},
"400": { "$ref": "#/components/responses/BadRequest" },
"401": { "$ref": "#/components/responses/Unauthorized" },
"404": { "$ref": "#/components/responses/NotFound" },
"503": { "$ref": "#/components/responses/MissingAuth" }
}
}
}
},
"components": {
"securitySchemes": {
"BearerAuth": {
"type": "http",
"scheme": "bearer",
"description": "Authorization: Bearer <FILE_CHECK_TOOL_API_KEY 或 INTEGRATION_API_KEY>"
},
"IntegrationKey": {
"type": "apiKey",
"in": "header",
"name": "X-Integration-Key",
"description": "与 Bearer 二选一"
}
},
"schemas": {
"MissingMaterial": {
"type": "object",
"properties": {
"code": { "type": "string", "example": "price_check_sheet" },
"name": { "type": "string", "example": "核价单" }
}
},
"InvoiceState": {
"type": "object",
"properties": {
"id": { "type": "integer" },
"scope_code": { "type": "string" },
"period_month": { "type": "string", "nullable": true },
"invoice_no": { "type": "string" },
"invoice_date": { "type": "string", "nullable": true },
"status": { "type": "string", "enum": ["complete", "missing"] },
"folder_path": { "type": "string", "nullable": true },
"folder_exists": { "type": "boolean" },
"matched_files": { "type": "object", "additionalProperties": { "type": "string" } },
"missing_materials": {
"type": "array",
"items": { "$ref": "#/components/schemas/MissingMaterial" }
},
"last_checked_at": { "type": "string", "nullable": true }
}
},
"MissingListResponse": {
"type": "object",
"required": ["ok", "items", "count"],
"properties": {
"ok": { "type": "boolean", "example": true },
"task_id": { "type": "integer", "nullable": true },
"scope_code": { "type": "string" },
"period": { "type": "string", "example": "2026-08" },
"count": { "type": "integer" },
"items": {
"type": "array",
"items": { "$ref": "#/components/schemas/InvoiceState" }
}
}
},
"RunItem": {
"type": "object",
"properties": {
"id": { "type": "integer" },
"schedule_run_id": { "type": "integer" },
"invoice_no": { "type": "string" },
"result": {
"type": "string",
"enum": ["complete", "missing", "skipped", "technical_error"]
},
"folder_path": { "type": "string", "nullable": true },
"matched_files": { "type": "object", "additionalProperties": { "type": "string" } },
"missing_materials": {
"type": "array",
"items": { "$ref": "#/components/schemas/MissingMaterial" }
},
"error_code": { "type": "string", "nullable": true },
"error_message": { "type": "string", "nullable": true }
}
},
"RunItemsResponse": {
"type": "object",
"required": ["ok", "items", "total"],
"properties": {
"ok": { "type": "boolean" },
"run_id": { "type": "integer" },
"run_no": { "type": "string" },
"page": { "type": "integer" },
"page_size": { "type": "integer" },
"total": { "type": "integer" },
"items": {
"type": "array",
"items": { "$ref": "#/components/schemas/RunItem" }
}
}
},
"InvoiceLatestResponse": {
"type": "object",
"required": ["ok", "state"],
"properties": {
"ok": { "type": "boolean" },
"state": { "$ref": "#/components/schemas/InvoiceState" },
"recent_run_items": {
"type": "array",
"items": { "$ref": "#/components/schemas/RunItem" }
}
}
},
"ToolError": {
"type": "object",
"properties": {
"ok": { "type": "boolean", "example": false },
"error_code": { "type": "string" },
"message": { "type": "string" },
"details": { "type": "object" }
}
}
},
"responses": {
"BadRequest": {
"description": "参数错误",
"content": {
"application/json": {
"schema": { "$ref": "#/components/schemas/ToolError" }
}
}
},
"Unauthorized": {
"description": "鉴权失败",
"content": {
"application/json": {
"schema": { "$ref": "#/components/schemas/ToolError" }
}
}
},
"NotFound": {
"description": "资源不存在",
"content": {
"application/json": {
"schema": { "$ref": "#/components/schemas/ToolError" }
}
}
},
"MissingAuth": {
"description": "服务端未配置 Tool API Key",
"content": {
"application/json": {
"schema": { "$ref": "#/components/schemas/ToolError" }
}
}
}
}
}
}
@@ -0,0 +1,35 @@
"""
backend/app/services/voucher_check/openapi_spec.py
用途:构建立账凭证检核 Chatflow 查询 Tool 的 OpenAPI 3.0 规范。
依赖:openapi_base.json。
逻辑:GET /api/accounting-voucher-check/tools/openapi.json 调用本模块;Dify URL 导入。
"""
from __future__ import annotations
import copy
import json
from pathlib import Path
from typing import Any
_BASE_SPEC_PATH = Path(__file__).with_name("openapi_base.json")
def _load_base_spec() -> dict[str, Any]:
with _BASE_SPEC_PATH.open("r", encoding="utf-8") as fp:
return json.load(fp)
def build_voucher_check_openapi_spec(base_url: str) -> dict[str, Any]:
"""
构建立账凭证检核 Tool OpenAPI。
核心逻辑:深拷贝静态规格,并将 servers[0].url 替换为当前 HXOPS_TOOLS_API_BASE。
"""
spec = copy.deepcopy(_load_base_spec())
base = str(base_url or "").strip().rstrip("/")
servers = spec.get("servers")
if base and isinstance(servers, list) and servers:
servers[0]["url"] = base
servers[0]["description"] = "HXOPS_TOOLS_API_BASE"
return spec
@@ -0,0 +1,126 @@
"""
backend/app/services/voucher_check/persistence.py
用途:立账凭证检核单票状态与批次明细的事务写入。
依赖:models.voucher_check、ScheduleRun、SQLAlchemy session。
逻辑:runner 阶段 B 调用;skipped 只更新 last_seen_erp_at;批次级失败不进入本模块。
"""
from __future__ import annotations
from datetime import date, datetime
from typing import Any
from app import db
from app.models.voucher_check import VoucherCheckInvoiceState, VoucherCheckRunItem
def persist_batch_results(
*,
schedule_run_id: int,
scope_code: str,
period_month: date,
items: list[dict[str, Any]],
now: datetime | None = None,
) -> None:
"""
单事务写入批次明细并 upsert 最新状态。
核心逻辑:先写 run_items;非 skipped/technical_error 再 upsert states;
skipped 仅刷新 last_seen_erp_at。
Args:
schedule_run_id: ScheduleRun.id
scope_code: 账套
period_month: 当月首日
items: 内存中的结果行(含 result / fingerprint / missing 等)
now: 可选时钟
"""
ts = now or datetime.utcnow()
for item in items:
invoice_no = str(item["invoice_no"]).strip()
result = str(item["result"])
run_item = VoucherCheckRunItem(
schedule_run_id=schedule_run_id,
scope_code=scope_code,
period_month=period_month,
invoice_no=invoice_no,
invoice_date=item.get("invoice_date"),
result=result,
folder_path=item.get("folder_path"),
folder_exists=bool(item.get("folder_exists")),
material_fingerprint=item.get("material_fingerprint"),
matched_files_json=item.get("matched_files") or {},
missing_materials_json=item.get("missing_materials") or [],
error_code=item.get("error_code"),
error_message=item.get("error_message"),
checked_at=item.get("checked_at"),
created_at=ts,
)
db.session.add(run_item)
state = (
db.session.query(VoucherCheckInvoiceState)
.filter_by(
scope_code=scope_code,
period_month=period_month,
invoice_no=invoice_no,
)
.one_or_none()
)
if state is None:
state = VoucherCheckInvoiceState(
scope_code=scope_code,
period_month=period_month,
invoice_no=invoice_no,
created_at=ts,
)
db.session.add(state)
state.last_seen_erp_at = ts
state.invoice_date = item.get("invoice_date") or state.invoice_date
state.updated_at = ts
if result == "skipped":
# 跳过:不改写齐全结论与实际扫描时间
continue
if result == "technical_error":
continue
state.status = "complete" if result == "complete" else "missing"
state.folder_path = item.get("folder_path")
state.folder_exists = bool(item.get("folder_exists"))
state.material_fingerprint = item.get("material_fingerprint")
state.matched_files_json = item.get("matched_files") or {}
state.missing_materials_json = item.get("missing_materials") or []
state.last_actual_run_id = schedule_run_id
state.last_checked_at = item.get("checked_at") or ts
db.session.flush()
run_item.invoice_state_id = state.id
db.session.flush()
def mark_missing_notified(
*,
scope_code: str,
period_month: date,
invoice_nos: list[str],
notified_on: date,
) -> None:
"""发送缺资料通知成功后更新同票同日节流字段。"""
if not invoice_nos:
return
states = (
db.session.query(VoucherCheckInvoiceState)
.filter(
VoucherCheckInvoiceState.scope_code == scope_code,
VoucherCheckInvoiceState.period_month == period_month,
VoucherCheckInvoiceState.invoice_no.in_(invoice_nos),
)
.all()
)
for state in states:
state.last_missing_notified_on = notified_on
state.updated_at = datetime.utcnow()
db.session.flush()
@@ -0,0 +1,220 @@
"""
backend/app/services/voucher_check/query_service.py
用途:查询批次明细、当月缺资料与单票最新状态。
依赖:models.voucher_check、ScheduleRun。
逻辑:Tool API 与工作台 API 调用;不触发扫描。
"""
from __future__ import annotations
from datetime import date, datetime
from typing import Any
from app.core.errors import NotFoundError, ValidationError
from app.models import ScheduleRun
from app.models.voucher_check import VoucherCheckInvoiceState, VoucherCheckRunItem
from app.services.voucher_check.erp_repository import current_period_bounds
def _serialize_state(state: VoucherCheckInvoiceState) -> dict[str, Any]:
return {
"id": state.id,
"scope_code": state.scope_code,
"period_month": state.period_month.isoformat() if state.period_month else None,
"invoice_no": state.invoice_no,
"invoice_date": state.invoice_date.isoformat() if state.invoice_date else None,
"status": state.status,
"folder_path": state.folder_path,
"folder_exists": state.folder_exists,
"material_fingerprint": state.material_fingerprint,
"matched_files": state.matched_files_json or {},
"missing_materials": state.missing_materials_json or [],
"last_actual_run_id": state.last_actual_run_id,
"last_checked_at": state.last_checked_at.isoformat() if state.last_checked_at else None,
"last_seen_erp_at": state.last_seen_erp_at.isoformat() if state.last_seen_erp_at else None,
"last_missing_notified_on": (
state.last_missing_notified_on.isoformat() if state.last_missing_notified_on else None
),
"updated_at": state.updated_at.isoformat() if state.updated_at else None,
}
def _serialize_run_item(item: VoucherCheckRunItem) -> dict[str, Any]:
return {
"id": item.id,
"schedule_run_id": item.schedule_run_id,
"invoice_state_id": item.invoice_state_id,
"scope_code": item.scope_code,
"period_month": item.period_month.isoformat() if item.period_month else None,
"invoice_no": item.invoice_no,
"invoice_date": item.invoice_date.isoformat() if item.invoice_date else None,
"result": item.result,
"folder_path": item.folder_path,
"folder_exists": item.folder_exists,
"material_fingerprint": item.material_fingerprint,
"matched_files": item.matched_files_json or {},
"missing_materials": item.missing_materials_json or [],
"error_code": item.error_code,
"error_message": item.error_message,
"checked_at": item.checked_at.isoformat() if item.checked_at else None,
"created_at": item.created_at.isoformat() if item.created_at else None,
}
def parse_period_month(raw: str | None) -> date:
"""解析 YYYY-MM 或 YYYY-MM-DD 为当月首日;空则取当前自然月。"""
if not raw:
period_month, *_ = current_period_bounds()
return period_month
text = str(raw).strip()
try:
if len(text) == 7:
dt = datetime.strptime(text, "%Y-%m")
else:
dt = datetime.strptime(text[:10], "%Y-%m-%d")
return date(dt.year, dt.month, 1)
except ValueError as exc:
raise ValidationError(
"period 格式须为 YYYY-MM",
code="VOUCHER_CHECK.CONFIG_INVALID",
) from exc
def list_missing_states(
*,
task_id: int | None = None,
scope_code: str = "HXJM",
period: str | None = None,
limit: int = 200,
) -> dict[str, Any]:
"""
查询指定月份缺资料票(最新状态表)。
task_id 预留与排程绑定校验,本期仅用于响应回显。
"""
period_month = parse_period_month(period)
limit = max(1, min(int(limit or 200), 1000))
q = (
VoucherCheckInvoiceState.query.filter_by(
scope_code=scope_code,
period_month=period_month,
status="missing",
)
.order_by(VoucherCheckInvoiceState.invoice_no.asc())
.limit(limit)
)
items = [_serialize_state(s) for s in q.all()]
return {
"task_id": task_id,
"scope_code": scope_code,
"period": period_month.strftime("%Y-%m"),
"count": len(items),
"items": items,
}
def list_run_items(
*,
run_id: int,
result: str | None = None,
page: int = 1,
page_size: int = 50,
) -> dict[str, Any]:
"""分页查询批次明细。"""
run = ScheduleRun.query.get(run_id)
if not run:
raise NotFoundError("批次不存在", code="VOUCHER_CHECK.RUN_NOT_FOUND")
page = max(1, int(page or 1))
page_size = max(1, min(int(page_size or 50), 200))
q = VoucherCheckRunItem.query.filter_by(schedule_run_id=run_id)
if result:
q = q.filter(VoucherCheckRunItem.result == str(result).strip())
total = q.count()
rows = (
q.order_by(VoucherCheckRunItem.invoice_no.asc())
.offset((page - 1) * page_size)
.limit(page_size)
.all()
)
return {
"run_id": run_id,
"run_no": run.run_no,
"page": page,
"page_size": page_size,
"total": total,
"items": [_serialize_run_item(r) for r in rows],
}
def get_invoice_latest(
*,
invoice_no: str,
scope_code: str = "HXJM",
period: str | None = None,
) -> dict[str, Any]:
"""查询单票最新状态及近期批次快照。"""
inv = str(invoice_no or "").strip()
if not inv:
raise ValidationError("invoice_no 必填", code="VOUCHER_CHECK.INVOICE_REQUIRED")
period_month = parse_period_month(period)
state = (
VoucherCheckInvoiceState.query.filter_by(
scope_code=scope_code,
period_month=period_month,
invoice_no=inv,
).one_or_none()
)
if not state:
raise NotFoundError("发票状态不存在", code="VOUCHER_CHECK.RUN_NOT_FOUND")
history = (
VoucherCheckRunItem.query.filter_by(
scope_code=scope_code,
period_month=period_month,
invoice_no=inv,
)
.order_by(VoucherCheckRunItem.id.desc())
.limit(20)
.all()
)
return {
"state": _serialize_state(state),
"recent_run_items": [_serialize_run_item(h) for h in history],
}
def list_states(
*,
scope_code: str = "HXJM",
period: str | None = None,
status: str | None = None,
invoice_no: str | None = None,
page: int = 1,
page_size: int = 50,
) -> dict[str, Any]:
"""工作台:按月/状态/发票号筛选最新状态。"""
period_month = parse_period_month(period)
page = max(1, int(page or 1))
page_size = max(1, min(int(page_size or 50), 200))
q = VoucherCheckInvoiceState.query.filter_by(
scope_code=scope_code,
period_month=period_month,
)
if status:
q = q.filter(VoucherCheckInvoiceState.status == str(status).strip())
if invoice_no:
q = q.filter(VoucherCheckInvoiceState.invoice_no.ilike(f"%{str(invoice_no).strip()}%"))
total = q.count()
rows = (
q.order_by(VoucherCheckInvoiceState.invoice_no.asc())
.offset((page - 1) * page_size)
.limit(page_size)
.all()
)
return {
"scope_code": scope_code,
"period": period_month.strftime("%Y-%m"),
"page": page,
"page_size": page_size,
"total": total,
"items": [_serialize_state(r) for r in rows],
}
@@ -0,0 +1,366 @@
"""
backend/app/services/voucher_check/runner.py
用途:立账凭证检核批次编排(预检、增量、扫描、落库、进度摘要、通知)。
依赖:config、erp_repository、share_scanner、persistence、excel_rows、notification。
逻辑:platform Job 与会话触发共用;两阶段执行保证共享盘失败不污染单票状态。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from flask import current_app
from app import db
from app.core.errors import AppError, NotFoundError, ServiceUnavailableError, ValidationError
from app.models import ScheduleRun, ScheduleTask
from app.models.voucher_check import VoucherCheckInvoiceState
from app.services.voucher_check.config import load_voucher_check_config
from app.services.voucher_check.erp_repository import fetch_month_invoices
from app.services.voucher_check.excel_rows import to_excel_detail_row
from app.services.voucher_check.notification import send_failure_alert, send_missing_notifications
from app.services.voucher_check.persistence import persist_batch_results
from app.services.voucher_check.share_scanner import ensure_share_healthy, scan_invoice_folder
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
def _extract_run_options(run: ScheduleRun) -> dict[str, Any]:
payload = run.api_request_json if isinstance(run.api_request_json, dict) else {}
options = payload.get("run_options")
if not isinstance(options, dict):
options = {}
mode = str(options.get("mode") or "incremental").strip().lower()
if mode not in {"incremental", "force_all", "single"}:
mode = "incremental"
invoice_no = options.get("invoice_no")
invoice_no = str(invoice_no).strip() if invoice_no else None
return {"mode": mode, "invoice_no": invoice_no}
def _update_progress(
run: ScheduleRun,
*,
step: str,
label: str,
processed: int = 0,
voucher_summary: dict[str, Any] | None = None,
) -> None:
summary = dict(run.response_summary_json or {})
summary["current_step"] = {
"step": step,
"label": label,
"processed_count": processed,
}
if voucher_summary:
summary["voucher_check"] = voucher_summary
summary["file_judgement"] = {
"qualified_count": int(voucher_summary.get("complete_count") or 0),
"unqualified_count": int(voucher_summary.get("missing_count") or 0),
"manual_count": 0,
"system_error_count": int(voucher_summary.get("technical_error_count") or 0),
}
summary["progress_metrics"] = [
{"key": "total", "label_key": "chat.voucherCheck.total", "value": int(voucher_summary.get("total_count") or 0)},
{"key": "scan", "label_key": "chat.voucherCheck.scanned", "value": int(voucher_summary.get("scan_count") or 0)},
{"key": "skip", "label_key": "chat.voucherCheck.skipped", "value": int(voucher_summary.get("skipped_count") or 0)},
{"key": "complete", "label_key": "chat.voucherCheck.complete", "value": int(voucher_summary.get("complete_count") or 0)},
{"key": "missing", "label_key": "chat.voucherCheck.missing", "value": int(voucher_summary.get("missing_count") or 0)},
]
summary["domain_notification_managed"] = True
run.response_summary_json = summary
db.session.commit()
def run_voucher_check_batch(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
"""
执行立账凭证检核批次。
核心逻辑:阶段 A 只读预检与扫描;阶段 B 事务落库;缺资料不计入 failed_count。
Returns:
ScheduleExecuteResult:(total, success, failed, skipped, details, errors, step_logs)
"""
step_logs: list[dict[str, Any]] = []
errors: list[str] = []
options = _extract_run_options(run)
mode = options["mode"]
single_invoice = options["invoice_no"]
try:
config = load_voucher_check_config(task.job_params if isinstance(task.job_params, dict) else {})
except AppError as exc:
send_failure_alert(
task=task,
run=run,
stage="config",
error_code=exc.code,
error_message=exc.message,
enabled=True,
)
raise
# [STEP 1] 拉取 ERP 当月发票清单
_update_progress(run, step="fetch_erp", label="拉取 ERP 当月立账凭证")
try:
period_month, invoices = fetch_month_invoices(config)
except ServiceUnavailableError as exc:
send_failure_alert(
task=task,
run=run,
stage="fetch_erp",
error_code=exc.code,
error_message=exc.message,
enabled=config.notify_failure_enabled,
)
raise
step_logs.append(
{
"step": "fetch_erp",
"status": "success",
"detail": {"count": len(invoices), "period": period_month.strftime("%Y-%m")},
}
)
if mode == "single":
if not single_invoice:
raise ValidationError(
"single 模式必须提供 invoice_no",
code="VOUCHER_CHECK.INVOICE_REQUIRED",
)
invoices = [row for row in invoices if row.invoice_no == single_invoice]
if not invoices:
raise NotFoundError(
"指定发票不在当前月 ERP 集合",
code="VOUCHER_CHECK.INVOICE_NOT_IN_PERIOD",
)
# [STEP 2] 共享盘健康检查(失败则整批失败,不写单票 missing)
_update_progress(run, step="share_health", label="检查共享盘可用性")
try:
root = ensure_share_healthy(config)
except ServiceUnavailableError as exc:
send_failure_alert(
task=task,
run=run,
stage="share_health",
error_code=exc.code,
error_message=exc.message,
enabled=config.notify_failure_enabled,
)
raise
step_logs.append({"step": "share_health", "status": "success", "detail": {"root_ok": True}})
# [STEP 3] 读取历史状态,供增量判定
existing_states = (
db.session.query(VoucherCheckInvoiceState)
.filter_by(scope_code=config.scope_code, period_month=period_month)
.all()
)
state_map = {s.invoice_no: s for s in existing_states}
results: list[dict[str, Any]] = []
complete_count = 0
missing_count = 0
skipped_count = 0
technical_error_count = 0
now = datetime.utcnow()
force = mode in {"force_all", "single"}
# [STEP 4] 逐票扫描 / 指纹比对
_update_progress(
run,
step="scan_share",
label="扫描共享盘文件名",
processed=0,
voucher_summary={
"scope_code": config.scope_code,
"period": period_month.strftime("%Y-%m"),
"mode": mode,
"total_count": len(invoices),
"complete_count": 0,
"missing_count": 0,
"scan_count": 0,
"skipped_count": 0,
"technical_error_count": 0,
},
)
for idx, row in enumerate(invoices, start=1):
hist = state_map.get(row.invoice_no)
scan = scan_invoice_folder(
config,
root=root,
period_month=period_month,
invoice_no=row.invoice_no,
)
# 增量:齐全且指纹未变 → skipped(仍访问共享盘取指纹)
can_skip = (
not force
and hist is not None
and hist.status == "complete"
and hist.material_fingerprint
and scan.result == "complete"
and scan.material_fingerprint == hist.material_fingerprint
)
if can_skip:
item = {
"invoice_no": row.invoice_no,
"invoice_date": row.invoice_date,
"result": "skipped",
"folder_path": scan.folder_path,
"folder_exists": scan.folder_exists,
"material_fingerprint": scan.material_fingerprint,
"matched_files": scan.matched_files,
"missing_materials": [],
"checked_at": None,
}
skipped_count += 1
elif scan.result == "technical_error":
item = {
"invoice_no": row.invoice_no,
"invoice_date": row.invoice_date,
"result": "technical_error",
"folder_path": scan.folder_path,
"folder_exists": False,
"material_fingerprint": None,
"matched_files": {},
"missing_materials": [],
"error_code": scan.error_code,
"error_message": scan.error_message,
"checked_at": now,
}
technical_error_count += 1
else:
item = {
"invoice_no": row.invoice_no,
"invoice_date": row.invoice_date,
"result": scan.result,
"folder_path": scan.folder_path,
"folder_exists": scan.folder_exists,
"material_fingerprint": scan.material_fingerprint,
"matched_files": scan.matched_files,
"missing_materials": scan.missing_materials,
"checked_at": now,
}
if scan.result == "complete":
complete_count += 1
else:
missing_count += 1
results.append(item)
if idx % 20 == 0 or idx == len(invoices):
scan_count = complete_count + missing_count + technical_error_count
_update_progress(
run,
step="scan_share",
label="扫描共享盘文件名",
processed=idx,
voucher_summary={
"scope_code": config.scope_code,
"period": period_month.strftime("%Y-%m"),
"mode": mode,
"total_count": len(invoices),
"complete_count": complete_count,
"missing_count": missing_count,
"scan_count": scan_count,
"skipped_count": skipped_count,
"technical_error_count": technical_error_count,
},
)
step_logs.append(
{
"step": "scan_share",
"status": "success",
"detail": {
"complete": complete_count,
"missing": missing_count,
"skipped": skipped_count,
"technical_error": technical_error_count,
},
}
)
# [STEP 5] 事务落库
_update_progress(run, step="persist", label="写入检核记录")
try:
persist_batch_results(
schedule_run_id=run.id,
scope_code=config.scope_code,
period_month=period_month,
items=results,
now=now,
)
db.session.commit()
except Exception as exc:
db.session.rollback()
current_app.logger.error("[voucher-check] persist failed run_id=%s: %s", run.id, exc, exc_info=True)
send_failure_alert(
task=task,
run=run,
stage="persist",
error_code="VOUCHER_CHECK.PERSIST_FAILED",
error_message=str(exc),
enabled=config.notify_failure_enabled,
)
raise
# [STEP 6] 缺资料通知
missing_items = [r for r in results if r["result"] == "missing"]
notified = send_missing_notifications(
task=task,
run=run,
scope_code=config.scope_code,
period_month=period_month,
missing_items=missing_items,
same_day_dedup=config.same_day_dedup_enabled,
enabled=config.notify_missing_enabled,
)
step_logs.append(
{
"step": "notify",
"status": "success",
"detail": {"missing": len(missing_items), "notified": notified},
}
)
period = period_month.strftime("%Y-%m")
scan_count = complete_count + missing_count + technical_error_count
voucher_summary = {
"scope_code": config.scope_code,
"period": period,
"mode": mode,
"total_count": len(invoices),
"complete_count": complete_count,
"missing_count": missing_count,
"scan_count": scan_count,
"skipped_count": skipped_count,
"technical_error_count": technical_error_count,
"missing_notification_count": notified,
}
_update_progress(
run,
step="done",
label="检核完成",
processed=len(invoices),
voucher_summary=voucher_summary,
)
details = [
to_excel_detail_row(item, period=period, scope_code=config.scope_code) for item in results
]
# success_count = complete + missing(业务成功);failed_count 仅技术异常
success_count = complete_count + missing_count
total_count = len(invoices)
return (
total_count,
success_count,
technical_error_count,
skipped_count,
details,
errors,
step_logs,
)
@@ -0,0 +1,149 @@
"""
backend/app/services/voucher_check/schedule_seed.py
用途:确保 accounting-voucher-check 默认日批 ScheduleTask 存在(06:00 Asia/Shanghai)。
依赖:ScheduleTask/User、timezone_util、voucher_check.config.DEFAULT_JOB_PARAMS。
逻辑:迁移种子 + create_app / User after_commit 幂等补建。
"""
from __future__ import annotations
import logging
from datetime import datetime
from typing import Any
from sqlalchemy import event
from sqlalchemy.orm import Session
from app import db
from app.models import ScheduleTask, User
from app.services.schedule.timezone_util import compute_next_run_at
from app.services.voucher_check.config import DEFAULT_JOB_PARAMS
_LOGGER = logging.getLogger(__name__)
DEFAULT_VOUCHER_CHECK_SCHEDULE_NO = "SCH-ACCOUNTING-VOUCHER-CHECK"
DEFAULT_VOUCHER_CHECK_PLATFORM_PATH = "accounting-voucher-check"
DEFAULT_VOUCHER_CHECK_CRON = "0 6 * * *"
DEFAULT_VOUCHER_CHECK_NAME = "立账凭证检核(日批)"
_HOOKS_REGISTERED = False
_SESSION_INFO_KEY = "_seed_voucher_check_schedule"
def ensure_default_voucher_check_schedule(
*,
commit: bool = True,
session: Any | None = None,
) -> ScheduleTask | None:
"""
幂等确保默认立账凭证检核日批排程存在。
Args:
commit: 是否立即提交。
session: 可选独立 Session。
Returns:
新建或已存在的 ScheduleTask;尚无用户时返回 None。
"""
sess = session if session is not None else db.session
existing = (
sess.query(ScheduleTask)
.filter(
(ScheduleTask.schedule_no == DEFAULT_VOUCHER_CHECK_SCHEDULE_NO)
| (ScheduleTask.platform_api_path == DEFAULT_VOUCHER_CHECK_PLATFORM_PATH)
)
.first()
)
if existing is not None:
return existing
owner = (
sess.query(User)
.filter(User.role == "admin")
.order_by(User.id.asc())
.first()
)
if owner is None:
owner = sess.query(User).order_by(User.id.asc()).first()
if owner is None:
_LOGGER.info("skip seed accounting-voucher-check schedule: no users yet")
return None
now = datetime.utcnow()
next_run = compute_next_run_at(
DEFAULT_VOUCHER_CHECK_CRON,
timezone_name="Asia/Shanghai",
) or now
task = ScheduleTask(
schedule_no=DEFAULT_VOUCHER_CHECK_SCHEDULE_NO,
name=DEFAULT_VOUCHER_CHECK_NAME,
schedule_type="platform_job",
owner_user_id=int(owner.id),
cron_expr=DEFAULT_VOUCHER_CHECK_CRON,
schedule_timezone="Asia/Shanghai",
wait_seconds=0,
platform_api_path=DEFAULT_VOUCHER_CHECK_PLATFORM_PATH,
job_params=dict(DEFAULT_JOB_PARAMS),
kb_sync_enabled=False,
notify_user_ids_json=[],
notify_enabled=True,
enabled=True,
next_run_at=next_run,
created_by=int(owner.id),
updated_by=int(owner.id),
created_at=now,
updated_at=now,
)
sess.add(task)
if commit:
try:
sess.commit()
except Exception:
sess.rollback()
existing = (
sess.query(ScheduleTask)
.filter(
(ScheduleTask.schedule_no == DEFAULT_VOUCHER_CHECK_SCHEDULE_NO)
| (ScheduleTask.platform_api_path == DEFAULT_VOUCHER_CHECK_PLATFORM_PATH)
)
.first()
)
if existing is not None:
return existing
raise
else:
sess.flush()
_LOGGER.info("seeded accounting-voucher-check schedule id=%s", task.id)
return task
def register_voucher_check_schedule_hooks() -> None:
"""注册 User after_commit 补建钩子(幂等)。"""
global _HOOKS_REGISTERED
if _HOOKS_REGISTERED:
return
@event.listens_for(Session, "after_commit")
def _after_commit(session: Session) -> None:
if not session.info.get(_SESSION_INFO_KEY):
return
session.info[_SESSION_INFO_KEY] = False
try:
from sqlalchemy.orm import sessionmaker
bind = session.get_bind()
factory = sessionmaker(bind=bind)
with factory() as new_sess:
ensure_default_voucher_check_schedule(commit=True, session=new_sess)
except Exception:
_LOGGER.exception("voucher-check schedule seed after_commit failed")
@event.listens_for(User, "after_insert")
def _user_after_insert(mapper, connection, target) -> None: # noqa: ARG001
sess = Session.object_session(target)
if sess is not None:
sess.info[_SESSION_INFO_KEY] = True
_HOOKS_REGISTERED = True
@@ -0,0 +1,273 @@
"""
backend/app/services/voucher_check/share_scanner.py
用途:共享盘健康检查、路径构造、目录枚举与精确文件名匹配。
依赖:config、fingerprint、core.errors.ServiceUnavailableError / ValidationError。
逻辑:runner 阶段 A 调用;健康失败整批失败;单票目录缺失记业务缺资料。
"""
from __future__ import annotations
import os
from dataclasses import dataclass, field
from datetime import date
from pathlib import Path
from app.core.errors import ServiceUnavailableError, ValidationError
from app.services.voucher_check.config import (
RequiredFileRule,
VoucherCheckConfig,
resolve_share_root,
)
from app.services.voucher_check.fingerprint import build_material_fingerprint
@dataclass
class FileMeta:
"""直接子文件元数据。"""
name: str
size: int
mtime_ns: int
@dataclass
class InvoiceScanResult:
"""单票扫描结果。"""
invoice_no: str
folder_path: str
absolute_path: str
folder_exists: bool
material_fingerprint: str | None
matched_files: dict[str, str] = field(default_factory=dict)
missing_materials: list[dict[str, str]] = field(default_factory=list)
result: str = "missing" # complete / missing / technical_error
error_code: str | None = None
error_message: str | None = None
def ensure_share_healthy(config: VoucherCheckConfig) -> str:
"""
校验共享盘根目录可用。
核心逻辑:根存在、可 scandir、健康标记文件存在;失败抛 SHARE_UNAVAILABLE。
Returns:
解析后的绝对根路径。
"""
root = resolve_share_root(config)
root_path = Path(root)
try:
if not root_path.exists() or not root_path.is_dir():
raise ServiceUnavailableError(
"共享盘根目录不可用",
code="VOUCHER_CHECK.SHARE_UNAVAILABLE",
)
# [STEP 1] 轻量枚举证明 I/O 可用
with os.scandir(root_path) as it:
_ = next(it, None)
root_path.stat()
# [STEP 2] 健康标记:避免挂载丢失后空目录被误判为业务缺件
marker = (root_path / config.healthcheck_relative_path).resolve()
if not str(marker).startswith(str(root_path.resolve())):
raise ServiceUnavailableError(
"共享盘健康标记路径非法",
code="VOUCHER_CHECK.SHARE_UNAVAILABLE",
)
if not marker.is_file():
raise ServiceUnavailableError(
"共享盘健康标记文件缺失",
code="VOUCHER_CHECK.SHARE_UNAVAILABLE",
)
except ServiceUnavailableError:
raise
except OSError as exc:
raise ServiceUnavailableError(
"共享盘健康检查失败",
code="VOUCHER_CHECK.SHARE_UNAVAILABLE",
details={"error_type": type(exc).__name__},
) from exc
return str(root_path)
def _render_invoice_relative_path(
template: str,
*,
year: str,
month: str,
invoice_no: str,
) -> str:
"""渲染相对业务路径(不含 root 实际值,报告用)。"""
rendered = (
template.replace("{root}", "vouche")
.replace("{YYYY}", year)
.replace("{MM}", month)
.replace("{invoice_no}", invoice_no)
)
return rendered.strip("/").replace("\\", "/")
def build_invoice_absolute_path(
config: VoucherCheckConfig,
*,
root: str,
period_month: date,
invoice_no: str,
) -> tuple[str, str]:
"""
构造单票绝对路径与相对业务路径。
核心逻辑:invoice_no 仅 trim;含路径分隔符则视为非法(调用方记 technical_error)。
"""
year = f"{period_month.year:04d}"
month = f"{period_month.month:02d}"
invoice = str(invoice_no or "").strip()
if not invoice or "/" in invoice or "\\" in invoice or "\x00" in invoice or ".." in invoice:
raise ValidationError(
"发票号含非法路径字符",
code="VOUCHER_CHECK.INVOICE_PATH_INVALID",
details={"invoice_no": invoice_no},
)
relative = _render_invoice_relative_path(
config.directory_template,
year=year,
month=month,
invoice_no=invoice,
)
# 实际落盘:用真实 root 替换模板中的 {root}
absolute_template = (
config.directory_template.replace("{root}", root.rstrip("/\\"))
.replace("{YYYY}", year)
.replace("{MM}", month)
.replace("{invoice_no}", invoice)
)
absolute = str(Path(absolute_template))
resolved_root = Path(root).resolve()
resolved_abs = Path(absolute).resolve()
try:
resolved_abs.relative_to(resolved_root)
except ValueError as exc:
raise ValidationError(
"发票目录逃逸共享根",
code="VOUCHER_CHECK.INVOICE_PATH_INVALID",
details={"invoice_no": invoice},
) from exc
return absolute, relative
def list_direct_files(folder: Path) -> list[FileMeta]:
"""枚举发票目录直接子文件(忽略子目录与非普通文件)。"""
files: list[FileMeta] = []
if not folder.is_dir():
return files
with os.scandir(folder) as it:
for entry in it:
try:
if not entry.is_file(follow_symlinks=False):
continue
stat = entry.stat(follow_symlinks=False)
files.append(
FileMeta(
name=entry.name,
size=int(stat.st_size),
mtime_ns=int(getattr(stat, "st_mtime_ns", int(stat.st_mtime * 1_000_000_000))),
)
)
except OSError:
continue
return files
def match_required_files(
files: list[FileMeta],
rules: tuple[RequiredFileRule, ...],
*,
case_sensitive: bool,
) -> tuple[dict[str, str], list[dict[str, str]]]:
"""
按完整文件名精确匹配必检材料。
核心逻辑:任一候选命中即算该材料存在;不支持模糊/前缀匹配。
"""
if case_sensitive:
available = {f.name: f.name for f in files}
else:
available = {f.name.lower(): f.name for f in files}
matched: dict[str, str] = {}
missing: list[dict[str, str]] = []
for rule in rules:
if not rule.required:
continue
hit: str | None = None
for candidate in rule.accepted_filenames:
key = candidate if case_sensitive else candidate.lower()
if key in available:
hit = available[key]
break
if hit:
matched[rule.code] = hit
else:
missing.append({"code": rule.code, "name": rule.name})
return matched, missing
def scan_invoice_folder(
config: VoucherCheckConfig,
*,
root: str,
period_month: date,
invoice_no: str,
) -> InvoiceScanResult:
"""
扫描单票目录并判定齐全/缺资料。
核心逻辑:目录不存在→missing;存在则精确匹配必检文件名并生成指纹。
"""
try:
absolute, relative = build_invoice_absolute_path(
config,
root=root,
period_month=period_month,
invoice_no=invoice_no,
)
except ValidationError as exc:
return InvoiceScanResult(
invoice_no=str(invoice_no or "").strip(),
folder_path="",
absolute_path="",
folder_exists=False,
material_fingerprint=None,
result="technical_error",
error_code=exc.code,
error_message=exc.message,
)
folder = Path(absolute)
if not folder.exists() or not folder.is_dir():
missing = [{"code": r.code, "name": r.name} for r in config.required_files if r.required]
return InvoiceScanResult(
invoice_no=str(invoice_no).strip(),
folder_path=relative,
absolute_path=absolute,
folder_exists=False,
material_fingerprint=None,
missing_materials=missing,
result="missing",
)
files = list_direct_files(folder)
fingerprint = build_material_fingerprint([(f.name, f.size, f.mtime_ns) for f in files])
matched, missing = match_required_files(
files,
config.required_files,
case_sensitive=config.filename_case_sensitive,
)
return InvoiceScanResult(
invoice_no=str(invoice_no).strip(),
folder_path=relative,
absolute_path=absolute,
folder_exists=True,
material_fingerprint=fingerprint,
matched_files=matched,
missing_materials=missing,
result="complete" if not missing else "missing",
)