Merge branch 'dev' into hugo-shipping-notice
This commit is contained in:
commit
472b530be3
397 files changed
+46450
-34171
No files matched your search
@@ -21,11 +21,13 @@ def register_blueprints(app: Flask) -> None:
|
||||
from app.api.chat import chat_bp
|
||||
from app.api.admin import admin_bp
|
||||
from app.api.agents import agents_bp
|
||||
from app.api.user import user_bp
|
||||
from app.api.user import auth_bp, user_bp
|
||||
from app.api.integration import integration_bp
|
||||
from app.api.internal_jobs import internal_jobs_bp
|
||||
from app.api.maintenance import maintenance_bp
|
||||
from app.api.speech import speech_bp
|
||||
from app.api.sso import sso_bp, sso_well_known_bp
|
||||
from app.api.linked_services import linked_services_bp
|
||||
from app.api.training import training_admin_bp, training_user_bp
|
||||
from app.api.agent_runtime_context_tools import agent_runtime_context_bp
|
||||
|
||||
@@ -37,14 +39,17 @@ def register_blueprints(app: Flask) -> None:
|
||||
workspace_file_check_bp,
|
||||
workspace_schedule_bp,
|
||||
workspace_shipping_notice_bp,
|
||||
workspace_voucher_check_bp,
|
||||
)
|
||||
from app.api.tools import file_check_bp, maintenance_tool_bp, shipping_notice_bp
|
||||
from app.api.tools import file_check_bp, maintenance_tool_bp, shipping_notice_bp, voucher_check_tools_bp
|
||||
from app.api.files import files_bp
|
||||
from app.api.procurement_contract_tools import procurement_contract_bp
|
||||
|
||||
app.register_blueprint(chat_bp, url_prefix='/api/chat')
|
||||
app.register_blueprint(admin_bp, url_prefix='/api/admin')
|
||||
app.register_blueprint(agents_bp, url_prefix='/api/agents')
|
||||
app.register_blueprint(user_bp, url_prefix='/api/user')
|
||||
app.register_blueprint(auth_bp, url_prefix='/api/user')
|
||||
app.register_blueprint(training_user_bp, url_prefix='/api/user')
|
||||
app.register_blueprint(knowledge_base_bp, url_prefix='/api/kb')
|
||||
app.register_blueprint(integration_bp, url_prefix='/api/integration')
|
||||
@@ -53,12 +58,18 @@ def register_blueprints(app: Flask) -> None:
|
||||
app.register_blueprint(workspace_announcements_bp, url_prefix='/api/workspace')
|
||||
app.register_blueprint(workspace_shipping_notice_bp, url_prefix='/api/workspace')
|
||||
app.register_blueprint(workspace_file_check_bp, url_prefix='/api/workspace')
|
||||
app.register_blueprint(workspace_voucher_check_bp, url_prefix='/api/workspace')
|
||||
app.register_blueprint(internal_jobs_bp, url_prefix='/api/internal/jobs')
|
||||
app.register_blueprint(maintenance_bp, url_prefix='/api/maintenance')
|
||||
app.register_blueprint(shipping_notice_bp, url_prefix='/api/shipping-notice')
|
||||
app.register_blueprint(file_check_bp, url_prefix='/api/file-check')
|
||||
app.register_blueprint(voucher_check_tools_bp, url_prefix='/api/accounting-voucher-check')
|
||||
app.register_blueprint(agent_runtime_context_bp, url_prefix='/api/agent-runtime-context')
|
||||
app.register_blueprint(maintenance_tool_bp, url_prefix='/api/maintenance')
|
||||
app.register_blueprint(speech_bp, url_prefix='/api/speech')
|
||||
app.register_blueprint(sso_bp, url_prefix='/api/sso')
|
||||
app.register_blueprint(linked_services_bp, url_prefix='/api')
|
||||
app.register_blueprint(sso_well_known_bp)
|
||||
app.register_blueprint(training_admin_bp, url_prefix='/api/admin')
|
||||
app.register_blueprint(files_bp, url_prefix='/api/files')
|
||||
app.register_blueprint(procurement_contract_bp, url_prefix='/api/procurement-contract')
|
||||
@@ -18,16 +18,8 @@ import app.api.admin.database # noqa: F401
|
||||
import app.api.admin.permissions # noqa: F401
|
||||
import app.api.admin.users # noqa: F401
|
||||
import app.api.admin.wecom # noqa: F401
|
||||
import app.api.admin.shipping_order_extraction # noqa: F401
|
||||
import app.api.admin.announcements # noqa: F401
|
||||
import app.api.admin.shipping_customers # noqa: F401
|
||||
import app.api.admin.shipping_identity_rules # noqa: F401
|
||||
import app.api.admin.shipping_inventory # noqa: F401
|
||||
import app.api.admin.shipping_order_schema # noqa: F401
|
||||
import app.api.admin.shipping_field_assets # noqa: F401
|
||||
import app.api.admin.shipping_order_document_profiles # noqa: F401
|
||||
import app.api.admin.shipping_document_layouts # noqa: F401
|
||||
import app.api.admin.shipping_process_gate # noqa: F401
|
||||
import app.api.admin.shipping_legacy_stp_jobs # noqa: F401
|
||||
import app.api.admin.linked_services # noqa: F401
|
||||
import app.api.admin.procurement_contract # noqa: F401
|
||||
|
||||
__all__ = ['admin_bp']
|
||||
@@ -0,0 +1,44 @@
|
||||
"""
|
||||
backend/app/api/admin/linked_services.py
|
||||
|
||||
用途:管理后台关联服务 CRUD API(薄路由层)。
|
||||
依赖:admin.blueprint、services/admin/linked_service_service。
|
||||
逻辑:/linked-services* 路由;侧栏只读见 api/linked_services.py。
|
||||
"""
|
||||
|
||||
from flask import jsonify, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.services.admin import linked_service_service
|
||||
|
||||
|
||||
@admin_bp.route('/linked-services', methods=['GET'])
|
||||
@require_admin
|
||||
def list_linked_services():
|
||||
"""列出全部关联服务(含停用)。"""
|
||||
return jsonify(linked_service_service.list_linked_services())
|
||||
|
||||
|
||||
@admin_bp.route('/linked-services', methods=['POST'])
|
||||
@require_admin
|
||||
def create_linked_service():
|
||||
"""创建关联服务。"""
|
||||
data = request.get_json() or {}
|
||||
payload = linked_service_service.create_linked_service(data)
|
||||
return jsonify(payload), 201
|
||||
|
||||
|
||||
@admin_bp.route('/linked-services/<int:id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_linked_service(id: int):
|
||||
"""更新关联服务。"""
|
||||
data = request.get_json() or {}
|
||||
return jsonify(linked_service_service.update_linked_service(id, data))
|
||||
|
||||
|
||||
@admin_bp.route('/linked-services/<int:id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_linked_service(id: int):
|
||||
"""删除关联服务。"""
|
||||
return jsonify(linked_service_service.delete_linked_service(id))
|
||||
@@ -0,0 +1,264 @@
|
||||
"""
|
||||
backend/app/api/admin/procurement_contract.py
|
||||
|
||||
Purpose: Admin APIs for procurement contract templates, risk rules, and review history.
|
||||
Dependencies: admin blueprint, procurement_contract services, file asset upload, unified response envelope.
|
||||
Flow: Admin manages reusable templates/rules; review history remains read-only with export endpoints.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import json
|
||||
|
||||
from flask import g, request, send_file
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.errors import UnauthorizedError, ValidationError
|
||||
from app.core.response import ok
|
||||
from app.services.file_assets.service import upload_file_asset
|
||||
from app.services.procurement_contract import review_service, rule_service, template_service
|
||||
from app.services.procurement_contract.template_service import read_template_bytes
|
||||
|
||||
|
||||
def _admin_user():
|
||||
"""Return current admin user or raise UnauthorizedError."""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
|
||||
def _int_arg(name: str, default: int) -> int:
|
||||
"""Parse an integer query argument with a ValidationError on bad input."""
|
||||
raw = request.args.get(name)
|
||||
if raw in (None, ""):
|
||||
return default
|
||||
try:
|
||||
return int(raw)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError(f"{name} must be integer") from exc
|
||||
|
||||
|
||||
def _optional_json_form(name: str):
|
||||
"""Parse an optional multipart JSON field through the unified validation error contract."""
|
||||
raw = request.form.get(name)
|
||||
if not raw:
|
||||
return None
|
||||
try:
|
||||
return json.loads(raw)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError(
|
||||
f"{name} must be valid JSON",
|
||||
code="PROCUREMENT_CONTRACT.INVALID_COMPARISON_REGION_CONFIG",
|
||||
details={"field": name},
|
||||
) from exc
|
||||
|
||||
|
||||
@admin_bp.route("/procurement-contract/templates", methods=["GET"])
|
||||
@require_admin
|
||||
def admin_list_contract_templates():
|
||||
"""List all contract templates."""
|
||||
status = request.args.get("status") or None
|
||||
return ok(template_service.list_templates(status=status), request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@admin_bp.route("/procurement-contract/templates", methods=["POST"])
|
||||
@require_admin
|
||||
def admin_create_contract_template():
|
||||
"""Upload and create a reusable procurement contract template."""
|
||||
user = _admin_user()
|
||||
if request.content_type and "multipart/form-data" in request.content_type:
|
||||
upload = request.files.get("file")
|
||||
if not upload or not upload.filename:
|
||||
raise ValidationError("file is required")
|
||||
asset = upload_file_asset(user_id=user.id, upload=upload)
|
||||
row = template_service.create_template(
|
||||
user_id=user.id,
|
||||
name=(request.form.get("name") or "").strip(),
|
||||
version=(request.form.get("version") or "").strip(),
|
||||
file_asset_no=str(asset.get("asset_no") or ""),
|
||||
remark=request.form.get("remark"),
|
||||
is_default=str(request.form.get("is_default") or "").lower() in ("1", "true", "yes"),
|
||||
status=(request.form.get("status") or "enabled").strip(),
|
||||
contract_type=(request.form.get("contract_type") or "general_procurement").strip(),
|
||||
applicable_scope=request.form.get("applicable_scope"),
|
||||
change_note=request.form.get("change_note"),
|
||||
comparison_region_config=_optional_json_form("comparison_region_config"),
|
||||
)
|
||||
else:
|
||||
data = request.get_json() or {}
|
||||
file_asset_no = (data.get("file_asset_no") or "").strip()
|
||||
file_asset_id = int(data.get("file_asset_id") or 0) or None
|
||||
if not file_asset_no and not file_asset_id:
|
||||
raise ValidationError("file_asset_no is required")
|
||||
row = template_service.create_template(
|
||||
user_id=user.id,
|
||||
name=(data.get("name") or "").strip(),
|
||||
version=(data.get("version") or "").strip(),
|
||||
file_asset_id=file_asset_id,
|
||||
file_asset_no=file_asset_no or None,
|
||||
remark=data.get("remark"),
|
||||
is_default=bool(data.get("is_default")),
|
||||
status=(data.get("status") or "enabled").strip(),
|
||||
contract_type=(data.get("contract_type") or "general_procurement").strip(),
|
||||
applicable_scope=data.get("applicable_scope"),
|
||||
change_note=data.get("change_note"),
|
||||
comparison_region_config=data.get("comparison_region_config"),
|
||||
)
|
||||
return ok(row, request_id=getattr(g, "request_id", None), status=201)
|
||||
|
||||
|
||||
@admin_bp.route("/procurement-contract/templates/<int:template_id>", methods=["PATCH"])
|
||||
@require_admin
|
||||
def admin_update_contract_template(template_id: int):
|
||||
"""
|
||||
Update template metadata, status, default flag, or validated comparison-region configuration.
|
||||
|
||||
Args:
|
||||
template_id: ContractTemplate primary key from the Admin route.
|
||||
|
||||
Returns:
|
||||
Unified success envelope containing the updated template row.
|
||||
"""
|
||||
user = _admin_user()
|
||||
row = template_service.update_template(template_id, user_id=user.id, data=request.get_json() or {})
|
||||
return ok(row, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@admin_bp.route("/procurement-contract/templates/<int:template_id>/comparison-region-preview", methods=["POST"])
|
||||
@require_admin
|
||||
def admin_preview_contract_template_regions(template_id: int):
|
||||
"""
|
||||
Preview unsaved comparison-region anchors against the stored template file.
|
||||
|
||||
Args:
|
||||
template_id: ContractTemplate primary key; the stored file is used only for recognition preview.
|
||||
|
||||
Returns:
|
||||
Unified success envelope with matched body, signature, and attachment anchors.
|
||||
"""
|
||||
data = request.get_json() or {}
|
||||
result = template_service.preview_comparison_regions(
|
||||
template_id,
|
||||
data.get("comparison_region_config"),
|
||||
)
|
||||
return ok(result, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@admin_bp.route("/procurement-contract/templates/<int:template_id>", methods=["DELETE"])
|
||||
@require_admin
|
||||
def admin_delete_contract_template(template_id: int):
|
||||
"""Delete a non-default template."""
|
||||
return ok(template_service.delete_template(template_id), request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@admin_bp.route("/procurement-contract/templates/<int:template_id>/file", methods=["GET"])
|
||||
@require_admin
|
||||
def admin_download_contract_template(template_id: int):
|
||||
"""Download template file bytes."""
|
||||
tpl = template_service.get_template_or_404(template_id)
|
||||
filename, data = read_template_bytes(tpl)
|
||||
return send_file(io.BytesIO(data), mimetype="application/octet-stream", as_attachment=True, download_name=filename)
|
||||
|
||||
|
||||
@admin_bp.route("/procurement-contract/rules", methods=["GET"])
|
||||
@require_admin
|
||||
def admin_list_contract_risk_rules():
|
||||
"""List configurable procurement contract risk rules."""
|
||||
rows = rule_service.list_rules(
|
||||
contract_type=request.args.get("contract_type") or None,
|
||||
status=request.args.get("status") or None,
|
||||
clause_category=request.args.get("clause_category") or None,
|
||||
)
|
||||
return ok(rows, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@admin_bp.route("/procurement-contract/rules", methods=["POST"])
|
||||
@require_admin
|
||||
def admin_create_contract_risk_rule():
|
||||
"""Create a procurement contract risk rule."""
|
||||
user = _admin_user()
|
||||
row = rule_service.create_rule(user_id=user.id, data=request.get_json() or {})
|
||||
return ok(row, request_id=getattr(g, "request_id", None), status=201)
|
||||
|
||||
|
||||
@admin_bp.route("/procurement-contract/rules/<int:rule_id>", methods=["PATCH"])
|
||||
@require_admin
|
||||
def admin_update_contract_risk_rule(rule_id: int):
|
||||
"""Update a procurement contract risk rule."""
|
||||
user = _admin_user()
|
||||
row = rule_service.update_rule(rule_id, user_id=user.id, data=request.get_json() or {})
|
||||
return ok(row, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@admin_bp.route("/procurement-contract/rules/<int:rule_id>", methods=["DELETE"])
|
||||
@require_admin
|
||||
def admin_delete_contract_risk_rule(rule_id: int):
|
||||
"""Delete a procurement contract risk rule."""
|
||||
return ok(rule_service.delete_rule(rule_id), request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@admin_bp.route("/procurement-contract/reviews", methods=["GET"])
|
||||
@require_admin
|
||||
def admin_list_contract_reviews():
|
||||
"""List review history with filters."""
|
||||
data = review_service.list_reviews(
|
||||
review_mode=request.args.get("review_mode") or None,
|
||||
template_source=request.args.get("template_source") or None,
|
||||
status=request.args.get("status") or None,
|
||||
keyword=request.args.get("keyword") or None,
|
||||
contract_type=request.args.get("contract_type") or None,
|
||||
supplier_name=request.args.get("supplier_name") or None,
|
||||
risk_level=request.args.get("risk_level") or None,
|
||||
date_from=request.args.get("date_from") or None,
|
||||
date_to=request.args.get("date_to") or None,
|
||||
limit=_int_arg("limit", 100),
|
||||
offset=_int_arg("offset", 0),
|
||||
)
|
||||
return ok(data, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@admin_bp.route("/procurement-contract/reviews/<int:review_id>", methods=["GET"])
|
||||
@require_admin
|
||||
def admin_get_contract_review(review_id: int):
|
||||
"""Get review details."""
|
||||
return ok(review_service.get_review(review_id=review_id), request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@admin_bp.route("/procurement-contract/reviews/<int:review_id>/report", methods=["GET"])
|
||||
@require_admin
|
||||
def admin_download_contract_review_report(review_id: int):
|
||||
"""Download review report as txt or docx."""
|
||||
if (request.args.get("format") or "").lower() == "docx":
|
||||
name, data, mimetype = review_service.read_review_report_docx_bytes(review_id=review_id)
|
||||
else:
|
||||
name, data = review_service.read_review_report_bytes(review_id=review_id)
|
||||
mimetype = "text/plain; charset=utf-8"
|
||||
return send_file(io.BytesIO(data), mimetype=mimetype, as_attachment=True, download_name=name)
|
||||
|
||||
|
||||
@admin_bp.route("/procurement-contract/reviews/<int:review_id>/contract", methods=["GET"])
|
||||
@require_admin
|
||||
def admin_download_contract_review_contract(review_id: int):
|
||||
"""Download original contract file for a review."""
|
||||
filename, data = review_service.read_review_contract_bytes(review_id=review_id)
|
||||
return send_file(io.BytesIO(data), mimetype="application/octet-stream", as_attachment=True, download_name=filename)
|
||||
|
||||
|
||||
@admin_bp.route("/procurement-contract/reviews/<int:review_id>/annotated-contract", methods=["GET"])
|
||||
@require_admin
|
||||
def admin_download_annotated_contract(review_id: int):
|
||||
"""Download original PDF with anchored contract-review highlights."""
|
||||
filename, data, mimetype = review_service.read_review_annotated_contract_bytes(review_id=review_id)
|
||||
return send_file(io.BytesIO(data), mimetype=mimetype, as_attachment=True, download_name=filename)
|
||||
|
||||
|
||||
@admin_bp.route("/procurement-contract/reviews/<int:review_id>/template-file", methods=["GET"])
|
||||
@require_admin
|
||||
def admin_download_contract_review_template(review_id: int):
|
||||
"""Download template file used by a review."""
|
||||
filename, data = review_service.read_review_template_bytes(review_id=review_id)
|
||||
return send_file(io.BytesIO(data), mimetype="application/octet-stream", as_attachment=True, download_name=filename)
|
||||
+240
-22
@@ -422,6 +422,7 @@ def _is_allowed_preview_url(target_url: str) -> bool:
|
||||
def _fetch_preview_source_bytes(file_url: str, max_size: int | None=15 * 1024 * 1024):
|
||||
"""
|
||||
从上游文件 URL 拉取二进制内容(供预览接口复用)。
|
||||
核心逻辑:共享盘直读 / 固资图 / HTTP 拉取;integration kind=source 404 时回退 md → Dify 原文件 → 分段文本。
|
||||
如果 file_url 是内部 integration API 下载链接且包含过期 token,则尝试重新获取最新链接。
|
||||
返回: (content_bytes, content_type, error_tuple)
|
||||
其中 error_tuple = (message, status_code);成功时为 None。
|
||||
@@ -596,6 +597,10 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None=15 * 1024 *
|
||||
file_url = refreshed_url
|
||||
current_app.logger.warning(f"[file-preview] upstream returned status {upstream.status_code} for {file_url}")
|
||||
if upstream.status_code == 404:
|
||||
# [STEP] 源文件 404:先试 integration kind=md,再试 Dify 原文件/分段文本
|
||||
fallback = _fetch_preview_bytes_after_source_404(file_url, max_size=max_size)
|
||||
if fallback[0] is not None or fallback[2] is not None:
|
||||
return fallback
|
||||
return None, None, ('source file not found', 404)
|
||||
return None, None, (f'upstream returned status {upstream.status_code}', 502)
|
||||
|
||||
@@ -609,6 +614,174 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None=15 * 1024 *
|
||||
return (None, None, ('upstream returned invalid preview payload', 502))
|
||||
return (content, content_type, None)
|
||||
|
||||
|
||||
def _rewrite_integration_download_kind(file_url: str, kind: str) -> str:
|
||||
"""
|
||||
将 integration download URL 的 kind 查询参数改写为目标值。
|
||||
@param file_url: 原始下载 URL
|
||||
@param kind: 目标 kind(如 md)
|
||||
@returns 改写后的 URL;无法识别时原样返回
|
||||
"""
|
||||
from urllib.parse import parse_qs, urlencode, urlunparse
|
||||
|
||||
raw = str(file_url or '').strip()
|
||||
if not raw or '/api/integration/files/' not in raw:
|
||||
return raw
|
||||
parsed = urlparse(raw)
|
||||
qs = parse_qs(parsed.query, keep_blank_values=True)
|
||||
qs['kind'] = [str(kind)]
|
||||
flat: dict = {}
|
||||
for key, values in qs.items():
|
||||
flat[key] = values[0] if len(values) == 1 else values
|
||||
new_query = urlencode(flat, doseq=True)
|
||||
return urlunparse((parsed.scheme, parsed.netloc, parsed.path, parsed.params, new_query, parsed.fragment))
|
||||
|
||||
|
||||
def _extract_integration_token_ids(file_url: str) -> tuple[str, str]:
|
||||
"""
|
||||
从 integration 下载 URL 的 JWT token 中解析 dataset_id / remote_document_id。
|
||||
@returns (dataset_id, remote_document_id),失败时为空字符串
|
||||
"""
|
||||
import base64
|
||||
from urllib.parse import parse_qs
|
||||
|
||||
try:
|
||||
parsed = urlparse(str(file_url or ''))
|
||||
qs = parse_qs(parsed.query)
|
||||
token = (qs.get('token') or [''])[0]
|
||||
if not token:
|
||||
return ('', '')
|
||||
parts = token.split('.')
|
||||
if len(parts) < 2:
|
||||
return ('', '')
|
||||
payload_b64 = parts[1] + '=' * (-len(parts[1]) % 4)
|
||||
payload_data = json.loads(base64.urlsafe_b64decode(payload_b64).decode('utf-8'))
|
||||
dataset_id = str(payload_data.get('dataset_id') or '').strip()
|
||||
remote_document_id = str(payload_data.get('remote_document_id') or '').strip()
|
||||
return (dataset_id, remote_document_id)
|
||||
except Exception:
|
||||
return ('', '')
|
||||
|
||||
|
||||
def _fetch_dify_source_bytes(dataset_id: str, remote_document_id: str, max_size: int | None):
|
||||
"""
|
||||
从 Dify 拉取文档原始二进制(签名下载 URL)。
|
||||
【AI 触发时机】本地 source 文件丢失、integration 404 时作为预览兜底。
|
||||
@returns (content, content_type, error_tuple) 与 _fetch_preview_source_bytes 一致
|
||||
"""
|
||||
if not dataset_id or not remote_document_id:
|
||||
return (None, None, None)
|
||||
try:
|
||||
info = IntegrationApiService._lookup_from_dify_document_api(dataset_id, remote_document_id)
|
||||
source_url = str((info or {}).get('source_download_url') or '').strip()
|
||||
if not source_url:
|
||||
return (None, None, None)
|
||||
upstream = requests.get(source_url, timeout=(5, 30))
|
||||
if upstream.status_code != 200:
|
||||
current_app.logger.warning(
|
||||
'[file-preview] dify source download status=%s dataset=%s doc=%s',
|
||||
upstream.status_code,
|
||||
dataset_id,
|
||||
remote_document_id,
|
||||
)
|
||||
return (None, None, None)
|
||||
content = upstream.content or b''
|
||||
if max_size is not None and len(content) > max_size:
|
||||
return (None, None, ('file too large for online preview', 413))
|
||||
content_type = (upstream.headers.get('content-type') or '').split(';')[0].strip().lower()
|
||||
return (content, content_type or None, None)
|
||||
except Exception as exc:
|
||||
current_app.logger.warning(
|
||||
'[file-preview] dify source download failed dataset=%s doc=%s err=%s',
|
||||
dataset_id,
|
||||
remote_document_id,
|
||||
exc,
|
||||
)
|
||||
return (None, None, None)
|
||||
|
||||
|
||||
def _looks_like_text_document(content: bytes) -> bool:
|
||||
"""
|
||||
判断内容是否可按文本/Markdown 预览,避免把 OLE/PDF 等二进制当文本导致乱码。
|
||||
核心逻辑:识别常见二进制魔数;抽样解码后要求可打印字符占比足够高。
|
||||
"""
|
||||
if not content:
|
||||
return False
|
||||
# [STEP 1] 排除 PDF / ZIP(OOXML) / OLE(旧版 Office)
|
||||
if content.startswith((b'%PDF-', b'PK\x03\x04', b'\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1')):
|
||||
return False
|
||||
sample = content[:4096]
|
||||
if b'\x00' in sample:
|
||||
return False
|
||||
text = None
|
||||
for enc in ('utf-8', 'utf-8-sig', 'gb18030'):
|
||||
try:
|
||||
text = sample.decode(enc)
|
||||
break
|
||||
except UnicodeDecodeError:
|
||||
continue
|
||||
if text is None:
|
||||
return False
|
||||
printable = sum(1 for ch in text if ch.isprintable() or ch in '\r\n\t')
|
||||
return (printable / max(len(text), 1)) >= 0.85
|
||||
|
||||
|
||||
def _fetch_preview_bytes_after_source_404(file_url: str, max_size: int | None):
|
||||
"""
|
||||
源文件 404 后的预览兜底链:integration md → Dify 原文件 → Dify 分段文本。
|
||||
"""
|
||||
# [STEP 1] kind=source → kind=md(清洗稿,必须是可读文本)
|
||||
if 'kind=source' in str(file_url or '') and '/api/integration/files/' in str(file_url or ''):
|
||||
md_url = _rewrite_integration_download_kind(file_url, 'md')
|
||||
if md_url and md_url != file_url:
|
||||
try:
|
||||
api_key = IntegrationApiService.get_api_key()
|
||||
headers = {'X-Integration-Key': api_key} if api_key else {}
|
||||
upstream = requests.get(md_url, headers=headers, timeout=(5, 20))
|
||||
if upstream.status_code == 200:
|
||||
content = upstream.content or b''
|
||||
if max_size is not None and len(content) > max_size:
|
||||
return (None, None, ('file too large for online preview', 413))
|
||||
content_type = (upstream.headers.get('content-type') or '').split(';')[0].strip().lower()
|
||||
if content_type == 'application/json':
|
||||
current_app.logger.warning('[file-preview] md fallback returned json url=%s', md_url)
|
||||
elif not _looks_like_text_document(content):
|
||||
current_app.logger.warning(
|
||||
'[file-preview] md fallback ignored binary payload url=%s',
|
||||
md_url,
|
||||
)
|
||||
else:
|
||||
current_app.logger.info('[file-preview] source 404 fallback to markdown url=%s', md_url)
|
||||
return (content, content_type or 'text/markdown', None)
|
||||
except requests.RequestException as exc:
|
||||
current_app.logger.warning('[file-preview] markdown fallback failed: %s', exc)
|
||||
|
||||
dataset_id, remote_document_id = _extract_integration_token_ids(file_url)
|
||||
|
||||
# [STEP 2] Dify 原始文件下载
|
||||
dify_bytes = _fetch_dify_source_bytes(dataset_id, remote_document_id, max_size)
|
||||
if dify_bytes[0] is not None:
|
||||
current_app.logger.info(
|
||||
'[file-preview] source 404 fallback to dify binary dataset=%s doc=%s',
|
||||
dataset_id,
|
||||
remote_document_id,
|
||||
)
|
||||
return dify_bytes
|
||||
if dify_bytes[2] is not None:
|
||||
return dify_bytes
|
||||
|
||||
# [STEP 3] Dify 分段文本(任意文档形态)
|
||||
text = _fetch_dify_document_segments_text(dataset_id, remote_document_id)
|
||||
if text:
|
||||
current_app.logger.info(
|
||||
'[file-preview] source 404 fallback to dify segments dataset=%s doc=%s',
|
||||
dataset_id,
|
||||
remote_document_id,
|
||||
)
|
||||
return (text.encode('utf-8'), 'text/plain; charset=utf-8', None)
|
||||
return (None, None, None)
|
||||
|
||||
|
||||
def _extract_placeholder_text(content: bytes) -> str:
|
||||
sample = content[:2048]
|
||||
for enc in ('utf-16le', 'utf-8', 'utf-8-sig', 'gb18030', 'latin-1'):
|
||||
@@ -627,6 +800,46 @@ def _extract_placeholder_text(content: bytes) -> str:
|
||||
return ''
|
||||
|
||||
|
||||
|
||||
def _fetch_dify_document_segments_text(dataset_id: str, remote_document_id: str) -> str | None:
|
||||
"""
|
||||
拼接 Dify 文档全部分段文本,不限制 doc_form(供源文件丢失时的预览兜底)。
|
||||
"""
|
||||
if not dataset_id or not remote_document_id:
|
||||
return None
|
||||
try:
|
||||
from app.services.knowledge_cleaning.dify_sync_service import KbDifySyncService
|
||||
service = KbDifySyncService()
|
||||
segments_payload = service._request(
|
||||
'GET',
|
||||
f'/datasets/{dataset_id}/documents/{remote_document_id}/segments?limit=1000',
|
||||
)
|
||||
rows = []
|
||||
if isinstance(segments_payload, dict):
|
||||
rows = segments_payload.get('data') or []
|
||||
elif isinstance(segments_payload, list):
|
||||
rows = segments_payload
|
||||
if not isinstance(rows, list) or not rows:
|
||||
return None
|
||||
ordered_rows = sorted(
|
||||
[row for row in rows if isinstance(row, dict)],
|
||||
key=lambda row: (int(row.get('position') or 0), str(row.get('id') or '')),
|
||||
)
|
||||
parts: list[str] = []
|
||||
for row in ordered_rows:
|
||||
text_part = str(row.get('content') or '').strip()
|
||||
if text_part:
|
||||
parts.append(text_part)
|
||||
return '\n\n'.join(parts).strip() or None
|
||||
except Exception as e:
|
||||
current_app.logger.warning(
|
||||
'[source-file-text] failed to fetch dify segments dataset=%s doc=%s err=%s',
|
||||
dataset_id,
|
||||
remote_document_id,
|
||||
e,
|
||||
)
|
||||
return None
|
||||
|
||||
def _fetch_dify_text_document(dataset_id: str, remote_document_id: str) -> str | None:
|
||||
"""
|
||||
对于 Dify 中以 text_model / txt 形式存储的文档,
|
||||
@@ -660,28 +873,7 @@ def _fetch_dify_text_document(dataset_id: str, remote_document_id: str) -> str |
|
||||
if not is_text_doc:
|
||||
return None
|
||||
|
||||
segments_payload = service._request(
|
||||
'GET',
|
||||
f'/datasets/{dataset_id}/documents/{remote_document_id}/segments?limit=1000',
|
||||
)
|
||||
rows = []
|
||||
if isinstance(segments_payload, dict):
|
||||
rows = segments_payload.get('data') or []
|
||||
elif isinstance(segments_payload, list):
|
||||
rows = segments_payload
|
||||
if not isinstance(rows, list) or not rows:
|
||||
return None
|
||||
|
||||
ordered_rows = sorted(
|
||||
[row for row in rows if isinstance(row, dict)],
|
||||
key=lambda row: (int(row.get('position') or 0), str(row.get('id') or '')),
|
||||
)
|
||||
parts: list[str] = []
|
||||
for row in ordered_rows:
|
||||
text = str(row.get('content') or '').strip()
|
||||
if text:
|
||||
parts.append(text)
|
||||
return '\n\n'.join(parts).strip() or None
|
||||
return _fetch_dify_document_segments_text(dataset_id, remote_document_id)
|
||||
except Exception as e:
|
||||
current_app.logger.warning(
|
||||
'[source-file-text] failed to fetch dify text document dataset=%s doc=%s err=%s',
|
||||
@@ -2210,6 +2402,20 @@ def preview_file_raw():
|
||||
|
||||
# 根据文件二进制头部纠正扩展名,防止文件本身是 docx 却被命名为 doc,导致转换或下载后乱码
|
||||
real_ext = _guess_ext_from_content(content, ext)
|
||||
# 仅当内容确实是文本时,才允许按 content_type 切到 md/txt(避免 .doc OLE 被当文本渲染乱码)
|
||||
normalized_ct = (content_type or '').split(';')[0].strip().lower()
|
||||
if _looks_like_text_document(content):
|
||||
if 'markdown' in normalized_ct:
|
||||
real_ext = 'md'
|
||||
elif normalized_ct.startswith('text/') and original_ext in (
|
||||
'pdf', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx',
|
||||
):
|
||||
real_ext = 'txt'
|
||||
elif real_ext in ('md', 'markdown', 'txt') and original_ext in (
|
||||
'pdf', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx',
|
||||
):
|
||||
# content_type/文件名声称是文本,但载荷是 Office 二进制:以魔数扩展名为准
|
||||
real_ext = _guess_ext_from_content(content, original_ext or ext)
|
||||
if real_ext != ext:
|
||||
current_app.logger.info(f"[file-preview] corrected extension from {ext} to {real_ext}")
|
||||
ext = real_ext
|
||||
@@ -2217,6 +2423,18 @@ def preview_file_raw():
|
||||
name = f"{name.rsplit('.', 1)[0]}.{ext}"
|
||||
elif name:
|
||||
name = f"{name}.{ext}"
|
||||
# 回退文本预览时,避免仍带二进制 Content-Type 导致前端按 PDF 渲染
|
||||
if ext in ('md', 'markdown', 'txt') and _looks_like_text_document(content):
|
||||
if not str(content_type or '').lower().startswith('text/'):
|
||||
content_type = {
|
||||
'md': 'text/markdown; charset=utf-8',
|
||||
'markdown': 'text/markdown; charset=utf-8',
|
||||
'txt': 'text/plain; charset=utf-8',
|
||||
}.get(ext)
|
||||
elif ext in ('md', 'markdown', 'txt') and not _looks_like_text_document(content):
|
||||
# 拒绝把二进制伪装成文本扩展名
|
||||
ext = _guess_ext_from_content(content, original_ext or 'bin') or (original_ext or 'bin')
|
||||
content_type = None
|
||||
|
||||
# 仅当文件真实格式仍然是旧版 Office/PPT 时才转 PDF。
|
||||
# 如果原始文件名是 .doc 但内容实际是 .docx,则交给前端 Office 组件渲染,
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
"""
|
||||
api/chat/__init__.py
|
||||
|
||||
用途:聊天域 Blueprint 的统一入口。
|
||||
依赖:chat 各职责路由模块、app.api.chat_turns。
|
||||
逻辑:创建唯一的 chat_bp,导入子模块完成路由注册,并挂载 Chat Turn 流式接口。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import Blueprint
|
||||
|
||||
chat_bp = Blueprint('chat', __name__)
|
||||
|
||||
# 子模块导入时在同一 Blueprint 上注册原有 URL。
|
||||
from . import assets, completions, directory, feedback, previews, sessions, uploads # noqa: E402, F401
|
||||
from app.api.chat_turns import register_chat_turn_routes # noqa: E402
|
||||
|
||||
register_chat_turn_routes(chat_bp)
|
||||
|
||||
__all__ = ['chat_bp']
|
||||
@@ -0,0 +1,129 @@
|
||||
"""
|
||||
api/chat/assets.py
|
||||
|
||||
用途:提供查询结果预览和固定资产文件、图片解析接口。
|
||||
依赖:chat.shared、Text2SQLService、FixedAssetHistoryService、FixedAssetImageService。
|
||||
逻辑:校验当前用户与 Agent 上下文后调用领域服务,返回分页数据或安全的预览元数据。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from .shared import * # noqa: F403
|
||||
from . import chat_bp
|
||||
|
||||
|
||||
@chat_bp.route('/query-preview/<int:chat_log_id>', methods=['GET'])
|
||||
@require_agent_permission
|
||||
def get_chat_query_preview(chat_log_id: int):
|
||||
page = request.args.get('page', type=int) or 1
|
||||
page_size = request.args.get('page_size', type=int) or 100
|
||||
page = max(1, page)
|
||||
page_size = max(1, min(200, page_size))
|
||||
|
||||
log = db.session.query(ChatLog).filter(
|
||||
ChatLog.id == chat_log_id,
|
||||
ChatLog.user_id == getattr(g.current_user, 'id', 0),
|
||||
ChatLog.agent_id == getattr(g.current_agent, 'id', 0),
|
||||
).first()
|
||||
if not log:
|
||||
raise NotFoundError('query preview not found')
|
||||
|
||||
payload = log.payload if isinstance(log.payload, dict) else {}
|
||||
if payload.get('kind') != 'text2sql_result_preview':
|
||||
raise ValidationError('current message does not support query preview')
|
||||
|
||||
sql = str(payload.get('sql') or '').strip()
|
||||
query = str(payload.get('query') or log.query or '').strip()
|
||||
if not sql:
|
||||
raise ValidationError('query preview sql is missing')
|
||||
|
||||
from app.services.text2sql import Text2SQLService
|
||||
total_count = payload.get('total_count')
|
||||
try:
|
||||
total_count = int(total_count) if total_count is not None else None
|
||||
except (TypeError, ValueError):
|
||||
total_count = None
|
||||
|
||||
columns, rows, resolved_total = Text2SQLService.get_preview_page(
|
||||
sql=sql,
|
||||
query=query,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
agent=g.current_agent,
|
||||
total_count=total_count,
|
||||
user_context=Text2SQLService._normalize_user_context(g.current_user),
|
||||
)
|
||||
if columns == ["Error"]:
|
||||
raise AppError(code='CHAT.QUERY_PREVIEW_FAILED', message=str(rows[0][0] if rows and rows[0] else 'query preview failed'), http_status=500)
|
||||
|
||||
total = resolved_total if resolved_total is not None else len(rows)
|
||||
return jsonify({
|
||||
'columns': columns,
|
||||
'rows': [list(row) for row in rows],
|
||||
'page': page,
|
||||
'page_size': page_size,
|
||||
'total': total,
|
||||
'has_more': page * page_size < total,
|
||||
'query': query,
|
||||
})
|
||||
|
||||
@chat_bp.route('/asset-history/search', methods=['GET'])
|
||||
@require_agent_permission
|
||||
def search_asset_history_files():
|
||||
"""
|
||||
检索固定资产履历文件。
|
||||
|
||||
用途:聊天结果表格点击“资产编号”时,返回共享盘中的候选履历文件列表。
|
||||
约束:至少提供资产编号或资产名称之一;不直接返回文件内容,只返回预览所需路径元数据。
|
||||
"""
|
||||
asset_id = (request.args.get('asset_id') or '').strip()
|
||||
asset_name = (request.args.get('asset_name') or '').strip()
|
||||
limit = request.args.get('limit', type=int) or 20
|
||||
limit = max(1, min(limit, 50))
|
||||
|
||||
if not asset_id and not asset_name:
|
||||
raise ValidationError('asset_id or asset_name is required')
|
||||
|
||||
from app.services.fixed_asset_history import FixedAssetHistoryService
|
||||
|
||||
if not FixedAssetHistoryService.is_enabled():
|
||||
raise ServiceUnavailableError('asset history share is not configured')
|
||||
|
||||
items = FixedAssetHistoryService.search_history_files(
|
||||
asset_id=asset_id,
|
||||
asset_name=asset_name,
|
||||
limit=limit,
|
||||
)
|
||||
return jsonify({
|
||||
'asset_id': asset_id,
|
||||
'asset_name': asset_name,
|
||||
'total': len(items),
|
||||
'items': items,
|
||||
})
|
||||
|
||||
@chat_bp.route('/asset-image/resolve', methods=['GET'])
|
||||
@require_agent_permission
|
||||
def resolve_asset_image_preview():
|
||||
"""
|
||||
解析固定资产图片预览链接。
|
||||
|
||||
用途:聊天结果表格点击“图片 -> 查看”时,后端自动登录外部文档库并返回最佳图片的可预览元数据。
|
||||
约束:至少提供资产编号或资产名称之一;只返回当前最佳命中的单张图片,不向前端暴露文档库登录态。
|
||||
"""
|
||||
asset_id = (request.args.get('asset_id') or '').strip()
|
||||
asset_name = (request.args.get('asset_name') or '').strip()
|
||||
if not asset_id and not asset_name:
|
||||
raise ValidationError('asset_id or asset_name is required')
|
||||
|
||||
from app.services.fixed_asset_image import FixedAssetImageService
|
||||
|
||||
result = FixedAssetImageService.resolve_images(
|
||||
asset_id=asset_id,
|
||||
asset_name=asset_name,
|
||||
)
|
||||
return jsonify({
|
||||
'asset_id': asset_id,
|
||||
'asset_name': asset_name,
|
||||
'item': result.get('item'),
|
||||
'items': result.get('items', []),
|
||||
'total': result.get('total', 0),
|
||||
})
|
||||
@@ -0,0 +1,331 @@
|
||||
"""
|
||||
api/chat/completions.py
|
||||
|
||||
用途:处理聊天 SSE completions 请求与上游事件转发。
|
||||
依赖:chat.shared、chat.core、services.chat.router、DifyService。
|
||||
逻辑:解析 HTTP 请求并建立本地会话,按 Chat Router 分流后保持原 SSE 契约输出。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from .shared import * # noqa: F403
|
||||
from . import chat_bp
|
||||
from .core import (
|
||||
_build_chat_adapter_hints,
|
||||
_ensure_chat_session,
|
||||
_get_chat_session,
|
||||
_should_reset_provider_conversation_for_asset_query,
|
||||
_update_chat_session,
|
||||
)
|
||||
|
||||
|
||||
@chat_bp.route('/completions', methods=['POST'])
|
||||
@require_agent_permission
|
||||
def chat_completions():
|
||||
"""
|
||||
SSE 流式聊天接口
|
||||
用途:接收前端问题,调用 DifyService.stream_chat,并以 text/event-stream 形式返回
|
||||
核心逻辑:
|
||||
1. 从请求体中读取 query / agent_id / conversation_id
|
||||
2. 通过装饰器已完成权限校验,并在 g 中注入 current_user / current_agent
|
||||
3. 使用 Flask 的 stream_with_context 包裹生成器,实现流式推送
|
||||
传入参数:
|
||||
无(从 request.json 读取)
|
||||
返回值:
|
||||
Flask Response 对象,mimetype=text/event-stream
|
||||
"""
|
||||
data = request.get_json() or {}
|
||||
query = data.get('query')
|
||||
display_query = str(data.get('display_query') or query or '').strip()
|
||||
# 前端传入的 conversation_id 在 B2 里代表本地 session_id
|
||||
conversation_id = data.get('conversation_id')
|
||||
shipping_task_id = str(data.get('task_id') or '').strip()
|
||||
shipping_batch_no = str(data.get('batch_no') or '').strip()
|
||||
kb_type = data.get('kb_type', '企业知识库')
|
||||
files = data.get('files')
|
||||
request_id = uuid.uuid4().hex[:12]
|
||||
user = getattr(g, 'current_user', None)
|
||||
agent = getattr(g, 'current_agent', None)
|
||||
current_app.logger.info('[chat-api] /completions request_id=%s user_id=%s agent_id=%s query_len=%s conversation_id=%s kb_type=%s', request_id, getattr(user, 'id', None), getattr(agent, 'id', None), len(query or ''), conversation_id, kb_type)
|
||||
if user is None or agent is None:
|
||||
current_app.logger.error("[chat-api] missing user/agent context user=%s agent=%s", bool(user), bool(agent))
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing user or agent context', http_status=500)
|
||||
|
||||
from app.services.agent_registry.resolver import resolve_runtime_provider
|
||||
|
||||
if resolve_runtime_provider(agent) == 'iframe':
|
||||
raise ValidationError('Embedded iframe agents do not support chat completions')
|
||||
|
||||
user_id = getattr(user, 'id', None)
|
||||
agent_id = getattr(agent, 'id', None)
|
||||
|
||||
from types import SimpleNamespace
|
||||
from app.services.agent_directory import serialize_directory_members
|
||||
|
||||
is_aggregate = bool(getattr(agent, 'is_aggregate', False))
|
||||
directory_members = serialize_directory_members(agent_id, active_only=True) if is_aggregate else []
|
||||
agent_proxy = SimpleNamespace(
|
||||
id=agent_id,
|
||||
name=getattr(agent, 'name', None),
|
||||
type=getattr(agent, 'type', None),
|
||||
dify_api_key=getattr(agent, 'dify_api_key', None),
|
||||
api_base_url=getattr(agent, 'api_base_url', None),
|
||||
extra_config=getattr(agent, 'extra_config', None) or {},
|
||||
agent_code=getattr(agent, 'agent_code', None),
|
||||
runtime_provider=getattr(agent, 'runtime_provider', None),
|
||||
conversation_mode=getattr(agent, 'conversation_mode', None),
|
||||
dify_app_type=getattr(agent, 'dify_app_type', None),
|
||||
capabilities=getattr(agent, 'capabilities', None),
|
||||
bound_schedule_task_id=getattr(agent, 'bound_schedule_task_id', None),
|
||||
handler_config=getattr(agent, 'handler_config', None),
|
||||
is_aggregate=is_aggregate,
|
||||
directory_members=directory_members,
|
||||
)
|
||||
user_proxy = SimpleNamespace(
|
||||
id=user_id,
|
||||
username=getattr(user, 'username', None),
|
||||
employee_id=getattr(user, 'employee_id', None),
|
||||
real_name=getattr(user, 'real_name', None),
|
||||
role=getattr(user, 'role', None),
|
||||
)
|
||||
|
||||
from app.services.dify import DifyService
|
||||
|
||||
external_conversation_id = None
|
||||
if conversation_id:
|
||||
existing_session = _get_chat_session(user_id, agent_id, conversation_id)
|
||||
if existing_session:
|
||||
session = _ensure_chat_session(
|
||||
user_id,
|
||||
agent_id,
|
||||
existing_session.session_id,
|
||||
title=display_query,
|
||||
status='running',
|
||||
)
|
||||
external_conversation_id = session.external_conversation_id
|
||||
if external_conversation_id and _should_reset_provider_conversation_for_asset_query(query, agent_proxy):
|
||||
current_app.logger.info(
|
||||
'[chat-api] reset provider conversation for asset query request_id=%s session_id=%s old_provider_conversation_id=%s query=%s',
|
||||
request_id,
|
||||
session.session_id,
|
||||
external_conversation_id,
|
||||
query,
|
||||
)
|
||||
session.external_conversation_id = None
|
||||
session.updated_at = datetime.utcnow()
|
||||
session.last_active_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
external_conversation_id = None
|
||||
else:
|
||||
session = _ensure_chat_session(
|
||||
user_id,
|
||||
agent_id,
|
||||
conversation_id,
|
||||
title=display_query,
|
||||
status='running',
|
||||
external_conversation_id=conversation_id,
|
||||
)
|
||||
external_conversation_id = session.external_conversation_id
|
||||
else:
|
||||
session = _ensure_chat_session(user_id, agent_id, None, title=display_query, status='running')
|
||||
|
||||
normalized_files: list[dict] | None = None
|
||||
if files is not None:
|
||||
if not isinstance(files, list):
|
||||
raise ValidationError('files must be a list')
|
||||
normalized_files = []
|
||||
for item in files:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
transfer_method = str(item.get('transfer_method') or '').strip()
|
||||
ftype = str(item.get('type') or '').strip()
|
||||
if transfer_method not in ('local_file', 'remote_url'):
|
||||
continue
|
||||
if ftype not in ('image', 'document', 'audio', 'video', 'custom'):
|
||||
continue
|
||||
if transfer_method == 'local_file':
|
||||
upload_file_id = str(item.get('upload_file_id') or '').strip()
|
||||
if not upload_file_id:
|
||||
continue
|
||||
normalized_files.append({'type': ftype, 'transfer_method': 'local_file', 'upload_file_id': upload_file_id})
|
||||
else:
|
||||
url = str(item.get('url') or '').strip()
|
||||
if not url:
|
||||
continue
|
||||
normalized_files.append({'type': ftype, 'transfer_method': 'remote_url', 'url': url})
|
||||
if not normalized_files:
|
||||
normalized_files = None
|
||||
|
||||
from app.services.agent_registry.handlers.base import ChatStreamContext
|
||||
|
||||
relay_stream_ctx = ChatStreamContext(
|
||||
query=query,
|
||||
display_query=display_query,
|
||||
user=user_proxy,
|
||||
agent=agent_proxy,
|
||||
session=session,
|
||||
external_conversation_id=external_conversation_id,
|
||||
request_id=request_id,
|
||||
normalized_files=normalized_files,
|
||||
adapter_hints=_build_chat_adapter_hints(
|
||||
shipping_task_id=shipping_task_id,
|
||||
shipping_batch_no=shipping_batch_no,
|
||||
),
|
||||
shipping_task_id=shipping_task_id,
|
||||
shipping_batch_no=shipping_batch_no,
|
||||
kb_type=kb_type,
|
||||
)
|
||||
|
||||
from app.services.hr_leave_sqlserver import HRLeaveSQLServerService
|
||||
from app.services.chat.router import try_fast_route
|
||||
|
||||
leave_supported = HRLeaveSQLServerService.supports(query)
|
||||
|
||||
fast_route = try_fast_route(
|
||||
user=user_proxy,
|
||||
agent=agent_proxy,
|
||||
query=query,
|
||||
agent_id=agent_id,
|
||||
session_id=session.session_id,
|
||||
external_conversation_id=external_conversation_id,
|
||||
normalized_files=normalized_files,
|
||||
kb_type=kb_type,
|
||||
leave_supported=leave_supported,
|
||||
)
|
||||
if fast_route is not None:
|
||||
generator = fast_route.generator
|
||||
elif leave_supported:
|
||||
generator = DifyService.stream_chat(
|
||||
query,
|
||||
user_proxy.id,
|
||||
agent_proxy,
|
||||
external_conversation_id,
|
||||
request_id=request_id,
|
||||
session_id=session.session_id,
|
||||
files=normalized_files,
|
||||
inputs=build_chat_dify_inputs(
|
||||
agent_proxy,
|
||||
session_id=session.session_id,
|
||||
request_id=request_id,
|
||||
trigger_source="frontend_chat",
|
||||
user_role=user_proxy.role,
|
||||
adapter_hints=_build_chat_adapter_hints(
|
||||
shipping_task_id=shipping_task_id,
|
||||
shipping_batch_no=shipping_batch_no,
|
||||
),
|
||||
),
|
||||
)
|
||||
else:
|
||||
from app.services.chat.executors import stream_chat_via_executor
|
||||
|
||||
generator = stream_chat_via_executor(relay_stream_ctx)
|
||||
|
||||
def relay_stream():
|
||||
from app.services.chat_perf import chat_perf_enabled
|
||||
|
||||
relay_started = time.perf_counter()
|
||||
relay_first_chunk_at: float | None = None
|
||||
created_event = {
|
||||
'event': 'session_created',
|
||||
'conversation_id': session.session_id,
|
||||
'provider_conversation_id': session.external_conversation_id,
|
||||
'session_status': session.status,
|
||||
}
|
||||
yield f"data: {json.dumps(created_event, ensure_ascii=False)}\n\n"
|
||||
|
||||
known_provider_conversation_id = session.external_conversation_id
|
||||
known_status = session.status
|
||||
emitted_handler_state_keys: set[str] = set()
|
||||
|
||||
from app.services.chat.stream_relay import (
|
||||
iter_handler_preface_sse,
|
||||
iter_handler_terminal_sse,
|
||||
)
|
||||
|
||||
for preface_line in iter_handler_preface_sse(relay_stream_ctx, emitted_keys=emitted_handler_state_keys):
|
||||
yield preface_line
|
||||
|
||||
try:
|
||||
for chunk in generator:
|
||||
if relay_first_chunk_at is None:
|
||||
relay_first_chunk_at = time.perf_counter()
|
||||
if not isinstance(chunk, str) or not chunk.startswith('data: '):
|
||||
yield chunk
|
||||
continue
|
||||
|
||||
raw_payload = chunk[6:].strip()
|
||||
try:
|
||||
event_data = json.loads(raw_payload)
|
||||
except Exception:
|
||||
yield chunk
|
||||
continue
|
||||
|
||||
provider_conversation_id = str(event_data.get('conversation_id') or known_provider_conversation_id or '').strip() or None
|
||||
event_name = event_data.get('event')
|
||||
should_touch = False
|
||||
if provider_conversation_id and provider_conversation_id != known_provider_conversation_id:
|
||||
known_provider_conversation_id = provider_conversation_id
|
||||
should_touch = True
|
||||
if event_name in ('message_end', 'workflow_finished'):
|
||||
known_status = 'done'
|
||||
should_touch = True
|
||||
elif event_name == 'error':
|
||||
known_status = 'error'
|
||||
should_touch = True
|
||||
|
||||
if should_touch:
|
||||
updated_session = _update_chat_session(
|
||||
user_id,
|
||||
agent_id,
|
||||
session.session_id,
|
||||
status=known_status,
|
||||
external_conversation_id=known_provider_conversation_id,
|
||||
touch=True,
|
||||
)
|
||||
if updated_session:
|
||||
known_status = updated_session.status
|
||||
|
||||
event_data['provider_conversation_id'] = provider_conversation_id
|
||||
event_data['conversation_id'] = session.session_id
|
||||
event_data['session_status'] = known_status
|
||||
if chat_perf_enabled() and event_name in ('message_end', 'workflow_finished'):
|
||||
relay_first_ms = int((relay_first_chunk_at - relay_started) * 1000) if relay_first_chunk_at else None
|
||||
relay_total_ms = int((time.perf_counter() - relay_started) * 1000)
|
||||
current_app.logger.info(
|
||||
'[chat-perf] relay request_id=%s session_id=%s first_chunk_ms=%s total_relay_ms=%s event=%s',
|
||||
request_id,
|
||||
session.session_id,
|
||||
relay_first_ms,
|
||||
relay_total_ms,
|
||||
event_name,
|
||||
)
|
||||
event_data['hxops_relay'] = {
|
||||
'first_chunk_ms': relay_first_ms,
|
||||
'total_relay_ms': relay_total_ms,
|
||||
}
|
||||
yield f"data: {json.dumps(event_data, ensure_ascii=False)}\n\n"
|
||||
if event_name in ('message_end', 'workflow_finished'):
|
||||
for terminal_line in iter_handler_terminal_sse(
|
||||
relay_stream_ctx,
|
||||
event_data,
|
||||
emitted_keys=emitted_handler_state_keys,
|
||||
):
|
||||
yield terminal_line
|
||||
except Exception as exc:
|
||||
current_app.logger.exception("[chat-api] relay stream failed request_id=%s session_id=%s", request_id, session.session_id)
|
||||
payload = {'event': 'error', 'message': str(exc), 'conversation_id': session.session_id, 'session_status': 'error'}
|
||||
yield f"data: {json.dumps(payload, ensure_ascii=False)}\n\n"
|
||||
|
||||
# 返回 SSE 响应,mimetype 设为 text/event-stream
|
||||
return Response(
|
||||
stream_with_context(
|
||||
relay_stream()
|
||||
),
|
||||
mimetype='text/event-stream',
|
||||
headers={
|
||||
'Cache-Control': 'no-cache',
|
||||
'Content-Type': 'text/event-stream; charset=utf-8',
|
||||
'Connection': 'keep-alive',
|
||||
# 对于 Nginx 反向代理,需要关闭缓冲以支持实时流式传输
|
||||
'X-Accel-Buffering': 'no'
|
||||
}
|
||||
)
|
||||
@@ -0,0 +1,218 @@
|
||||
"""
|
||||
api/chat/core.py
|
||||
|
||||
用途:提供聊天 API 内部共享的会话、标题和日志辅助操作。
|
||||
依赖:chat.shared、ChatSession、ChatLog、services.chat.session_service。
|
||||
逻辑:供 completions 与 sessions 路由复用,集中维护本地会话和上游 conversation_id 的映射。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from .shared import * # noqa: F403
|
||||
|
||||
|
||||
def _build_chat_adapter_hints(*, shipping_task_id: str | None = None, shipping_batch_no: str | None = None) -> dict | None:
|
||||
"""
|
||||
构建聊天入口分发给领域 adapter 的提示字典。
|
||||
|
||||
核心逻辑:平台入口只暴露通用参数;像发货通知这类业务专用 task/batch 提示,
|
||||
统一收敛到 adapter_hints 这个不透明容器里,避免平台函数签名泄漏领域字段。
|
||||
"""
|
||||
task_id = str(shipping_task_id or '').strip()
|
||||
batch_no = str(shipping_batch_no or '').strip()
|
||||
if not task_id and not batch_no:
|
||||
return None
|
||||
return {
|
||||
'shipping_notice': {
|
||||
'task_id': task_id or None,
|
||||
'batch_no': batch_no or None,
|
||||
}
|
||||
}
|
||||
|
||||
def _should_reset_provider_conversation_for_asset_query(query: str, agent_proxy) -> bool:
|
||||
"""
|
||||
判断固资管理里的当前问题是否应当切断上游 Dify 会话上下文。
|
||||
|
||||
核心逻辑:
|
||||
- 仅对“固资管理”Agent 生效;
|
||||
- 仅当用户本轮问题可脱离上一轮上下文独立完成时触发;
|
||||
- 这样可以保留本地同一历史会话,又避免把上一轮超大结果继续带给上游模型,导致 context length 爆掉。
|
||||
"""
|
||||
from app.services.text2sql import Text2SQLService
|
||||
|
||||
return Text2SQLService._should_reset_provider_conversation(query, agent_proxy)
|
||||
|
||||
def _session_title_from_text(text: str) -> str:
|
||||
value = str(text or '').strip()
|
||||
if not value:
|
||||
return ''
|
||||
return value[:30] + ('...' if len(value) > 30 else '')
|
||||
|
||||
def _looks_like_review_auto_title(title: str) -> bool:
|
||||
"""
|
||||
判断会话标题是否为审查结果 headline(误用作历史标题)。
|
||||
|
||||
Args:
|
||||
title: ChatSession.title。
|
||||
|
||||
Returns:
|
||||
True 表示标题像「模板比对完成…」这类自动摘要,而非用户提问。
|
||||
"""
|
||||
value = str(title or '').strip()
|
||||
return value.startswith(('模板比对完成', '单份审核完成', '采购合同审查结果'))
|
||||
|
||||
def _fallback_title_from_contract_review_log(log: ChatLog | None) -> str:
|
||||
"""
|
||||
从合同审查日志推导可读会话标题(优先 query,其次合同文件名)。
|
||||
|
||||
Args:
|
||||
log: procurement-contract-review 类型的 ChatLog。
|
||||
|
||||
Returns:
|
||||
截断后的标题;无法推导时返回空串。
|
||||
"""
|
||||
if not log:
|
||||
return ''
|
||||
query = str(log.query or '').strip()
|
||||
if query:
|
||||
return _session_title_from_text(query)
|
||||
payload = log.payload if isinstance(log.payload, dict) else {}
|
||||
file_name = str(payload.get('contract_file_name') or '').strip()
|
||||
if file_name:
|
||||
return _session_title_from_text(f'请对《{file_name}》进行审查')
|
||||
return ''
|
||||
|
||||
def _user_facing_chat_query(text: str, *, agent_code: str | None = None) -> str:
|
||||
"""
|
||||
将内部 Agent 编排提示转换成业务用户可见话术。
|
||||
|
||||
Args:
|
||||
text: chat_logs.query 中保存的用户侧文本。
|
||||
agent_code: 当前 Agent 应用类型;仅 shipping_notice 做工具名净化。
|
||||
Returns:
|
||||
可直接展示在聊天历史里的用户问题。
|
||||
"""
|
||||
value = str(text or '').strip()
|
||||
if not value or str(agent_code or '').strip() != SHIPPING_NOTICE_AGENT_CODE:
|
||||
return value
|
||||
import re
|
||||
|
||||
task_match = re.search(r'(SN-\d{8}-[A-Z0-9]+)', value, re.I)
|
||||
task_no = task_match.group(1).upper() if task_match else ''
|
||||
if 'create_task' in value or 'get_task_status' in value or 'parse_notice' in value:
|
||||
return f'继续处理当前发货任务 {task_no}'.strip()
|
||||
return value
|
||||
|
||||
def _serialize_session(session: ChatSession) -> dict:
|
||||
last_active = session.last_active_at or session.created_at
|
||||
return {
|
||||
'id': session.id,
|
||||
'conversation_id': session.session_id,
|
||||
'title': session.title or '',
|
||||
'created_at': last_active.isoformat() if last_active else '',
|
||||
'status': session.status,
|
||||
}
|
||||
|
||||
def _get_chat_session(user_id: int, agent_id: int, session_id: str | None):
|
||||
session_key = str(session_id or '').strip()
|
||||
if not session_key:
|
||||
return None
|
||||
return db.session.query(ChatSession).filter_by(
|
||||
user_id=user_id,
|
||||
agent_id=agent_id,
|
||||
session_id=session_key,
|
||||
).first()
|
||||
|
||||
def _chat_logs_for_session(user_id: int, agent_id: int, session: ChatSession):
|
||||
match_ids = {session.session_id}
|
||||
external_id = str(session.external_conversation_id or '').strip()
|
||||
if external_id:
|
||||
match_ids.add(external_id)
|
||||
return db.session.query(ChatLog).filter(
|
||||
ChatLog.user_id == user_id,
|
||||
ChatLog.agent_id == agent_id,
|
||||
or_(
|
||||
ChatLog.session_id.in_(match_ids),
|
||||
ChatLog.conversation_id.in_(match_ids),
|
||||
),
|
||||
).order_by(ChatLog.created_at.asc()).all()
|
||||
|
||||
def _ensure_chat_session(
|
||||
user_id: int,
|
||||
agent_id: int,
|
||||
session_id: str | None,
|
||||
title: str = '',
|
||||
status: str = 'running',
|
||||
external_conversation_id: str | None = None,
|
||||
):
|
||||
session_key = str(session_id or '').strip()
|
||||
external_id = str(external_conversation_id or '').strip() or None
|
||||
session = _get_chat_session(user_id, agent_id, session_key)
|
||||
changed = False
|
||||
if not session:
|
||||
session = ChatSession(
|
||||
session_id=session_key or uuid.uuid4().hex,
|
||||
user_id=user_id,
|
||||
agent_id=agent_id,
|
||||
title=_session_title_from_text(title),
|
||||
status=status,
|
||||
external_conversation_id=external_id,
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
last_active_at=datetime.utcnow(),
|
||||
)
|
||||
db.session.add(session)
|
||||
db.session.commit()
|
||||
return session
|
||||
|
||||
if not session.title and title:
|
||||
session.title = _session_title_from_text(title)
|
||||
changed = True
|
||||
if status and session.status != status:
|
||||
session.status = status
|
||||
changed = True
|
||||
if external_id and session.external_conversation_id != external_id:
|
||||
session.external_conversation_id = external_id
|
||||
changed = True
|
||||
session.last_active_at = datetime.utcnow()
|
||||
session.updated_at = datetime.utcnow()
|
||||
changed = True
|
||||
if changed:
|
||||
db.session.commit()
|
||||
return session
|
||||
|
||||
def _update_chat_session(
|
||||
user_id: int,
|
||||
agent_id: int,
|
||||
session_id: str,
|
||||
*,
|
||||
status: str | None = None,
|
||||
external_conversation_id: str | None = None,
|
||||
title: str | None = None,
|
||||
touch: bool = False,
|
||||
):
|
||||
session = _get_chat_session(user_id, agent_id, session_id)
|
||||
if not session:
|
||||
return None
|
||||
|
||||
changed = False
|
||||
if title and not session.title:
|
||||
session.title = _session_title_from_text(title)
|
||||
changed = True
|
||||
|
||||
external_id = str(external_conversation_id or '').strip() or None
|
||||
if external_id and session.external_conversation_id != external_id:
|
||||
session.external_conversation_id = external_id
|
||||
changed = True
|
||||
|
||||
if status and session.status != status:
|
||||
session.status = status
|
||||
changed = True
|
||||
|
||||
if touch or changed:
|
||||
session.last_active_at = datetime.utcnow()
|
||||
session.updated_at = datetime.utcnow()
|
||||
changed = True
|
||||
|
||||
if changed:
|
||||
db.session.commit()
|
||||
return session
|
||||
@@ -0,0 +1,55 @@
|
||||
"""
|
||||
api/chat/directory.py
|
||||
|
||||
用途:提供聊天表单所需的 OA 员工、部门和分部名称查询接口。
|
||||
依赖:chat.shared、OASQLServerService、chat_bp。
|
||||
逻辑:解析分页或 ID 参数后调用 OA 集成服务,并保持原 `/api/chat/oa/*` 响应格式。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from .shared import * # noqa: F403
|
||||
from . import chat_bp
|
||||
|
||||
|
||||
@chat_bp.route('/oa/employees', methods=['GET'])
|
||||
@require_agent_permission
|
||||
def get_oa_employees():
|
||||
"""
|
||||
获取 OA 系统中的员工列表(分页/搜索)
|
||||
"""
|
||||
keyword = request.args.get('keyword', '').strip()
|
||||
try:
|
||||
page = int(request.args.get('page', 1))
|
||||
page_size = int(request.args.get('page_size', 20))
|
||||
except ValueError:
|
||||
page = 1
|
||||
page_size = 20
|
||||
try:
|
||||
from app.services.oa_sqlserver import OASQLServerService
|
||||
result = OASQLServerService.search_employees(keyword, page, page_size)
|
||||
return jsonify(result)
|
||||
except Exception as e:
|
||||
current_app.logger.error(f'[OA-Employees] Query failed: {e}')
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=str(e), http_status=500)
|
||||
|
||||
@chat_bp.route('/oa/resolve-names', methods=['GET'])
|
||||
@require_agent_permission
|
||||
def resolve_oa_names():
|
||||
dept_ids = request.args.get('department_ids', '').strip()
|
||||
sub_ids = request.args.get('subcompany_ids', '').strip()
|
||||
result = {}
|
||||
try:
|
||||
from app.services.oa_sqlserver import OASQLServerService
|
||||
if dept_ids:
|
||||
for did in dept_ids.split(','):
|
||||
did = did.strip()
|
||||
if did:
|
||||
result[f'dept_{did}'] = OASQLServerService.get_department_name(did)
|
||||
if sub_ids:
|
||||
for sid in sub_ids.split(','):
|
||||
sid = sid.strip()
|
||||
if sid:
|
||||
result[f'sub_{sid}'] = OASQLServerService.get_subcompany_name(sid)
|
||||
except Exception as e:
|
||||
current_app.logger.error(f'[OA-ResolveNames] Query failed: {e}')
|
||||
return jsonify(result)
|
||||
@@ -0,0 +1,60 @@
|
||||
"""
|
||||
api/chat/feedback.py
|
||||
|
||||
用途:处理用户对聊天回答的评分与文字反馈。
|
||||
依赖:chat.shared、ChatLog、Feedback、chat_bp。
|
||||
逻辑:定位当前用户和 Agent 的最近一条会话日志,创建或更新对应反馈记录。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from .shared import * # noqa: F403
|
||||
from . import chat_bp
|
||||
|
||||
|
||||
@chat_bp.route('/feedback', methods=['POST'])
|
||||
@require_agent_permission
|
||||
def submit_feedback():
|
||||
"""
|
||||
提交对回答的评分与评论
|
||||
用途:在对话结束后,由前端发送评分(1~5)和文字意见
|
||||
核心逻辑:
|
||||
1. 从请求体中读取 score/comment/conversation_id
|
||||
2. 根据当前 user/agent 与 conversation_id 查找最近一条 ChatLog
|
||||
3. 为该 ChatLog 创建或更新 Feedback 记录
|
||||
"""
|
||||
data = request.get_json() or {}
|
||||
score = data.get('score')
|
||||
comment = data.get('comment') or ''
|
||||
conversation_id = data.get('conversation_id')
|
||||
if not current_app.config.get('FEEDBACK_ENABLED', True):
|
||||
raise ForbiddenError('feedback is disabled')
|
||||
if score is None:
|
||||
raise ValidationError('score is required')
|
||||
try:
|
||||
score_value = int(score)
|
||||
except (TypeError, ValueError):
|
||||
raise ValidationError('score must be an integer')
|
||||
if score_value < 1 or score_value > 5:
|
||||
raise ValidationError('score must be between 1 and 5')
|
||||
user = getattr(g, 'current_user', None)
|
||||
agent = getattr(g, 'current_agent', None)
|
||||
if user is None or agent is None:
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing user or agent context', http_status=500)
|
||||
chat_logs_query = db.session.query(ChatLog).filter_by(user_id=user.id, agent_id=agent.id)
|
||||
if conversation_id:
|
||||
chat_logs_query = chat_logs_query.filter(
|
||||
or_(ChatLog.session_id == conversation_id, ChatLog.conversation_id == conversation_id)
|
||||
)
|
||||
|
||||
# 取最新一条对话日志
|
||||
chat_log = chat_logs_query.order_by(ChatLog.created_at.desc()).first()
|
||||
if not chat_log:
|
||||
raise NotFoundError('ChatLog not found')
|
||||
if chat_log.feedback:
|
||||
chat_log.feedback.score = score_value
|
||||
chat_log.feedback.comment = comment
|
||||
else:
|
||||
fb = Feedback(chat_log_id=chat_log.id, score=score_value, comment=comment)
|
||||
db.session.add(fb)
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
@@ -0,0 +1,611 @@
|
||||
"""
|
||||
api/chat/preview_support.py
|
||||
|
||||
用途:提供聊天文件预览所需的来源校验、文件获取和格式转换操作。
|
||||
依赖:chat.shared、requests、LibreOffice、openpyxl、共享盘配置。
|
||||
逻辑:由 previews 路由调用,限制可访问路径与 URL,并将 Office/Excel 内容转换为可预览格式。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from .shared import * # noqa: F403
|
||||
|
||||
|
||||
def _normalize_allowed_share_path(path_value: str) -> tuple[str, str]:
|
||||
"""
|
||||
统一归一化 Windows UNC / Windows 本地盘符 / Linux 挂载目录路径。
|
||||
|
||||
Returns:
|
||||
(path_kind, normalized_path)
|
||||
- path_kind: 'windows' | 'posix' | ''
|
||||
- normalized_path: 归一化后的绝对路径文本
|
||||
"""
|
||||
raw_value = str(path_value or '').strip().strip('"')
|
||||
if not raw_value:
|
||||
return ('', '')
|
||||
if raw_value.startswith('\\\\'):
|
||||
normalized = raw_value.replace('/', '\\')
|
||||
normalized = '\\\\' + normalized[2:].rstrip('\\')
|
||||
return ('windows', normalized)
|
||||
if len(raw_value) >= 3 and raw_value[1] == ':' and raw_value[2] in ('\\', '/'):
|
||||
normalized = ntpath.normpath(raw_value.replace('/', '\\')).rstrip('\\')
|
||||
return ('windows', normalized)
|
||||
if raw_value.startswith('/'):
|
||||
normalized = posixpath.normpath(raw_value.replace('\\', '/'))
|
||||
return ('posix', normalized.rstrip('/'))
|
||||
return ('', '')
|
||||
|
||||
def _is_path_within_allowed_root(target_path: str, root_path: str) -> bool:
|
||||
target_kind, normalized_target = _normalize_allowed_share_path(target_path)
|
||||
root_kind, normalized_root = _normalize_allowed_share_path(root_path)
|
||||
if not normalized_target or not normalized_root or target_kind != root_kind:
|
||||
return False
|
||||
if target_kind == 'windows':
|
||||
target_lower = normalized_target.lower()
|
||||
root_lower = normalized_root.lower()
|
||||
return target_lower == root_lower or target_lower.startswith(root_lower.rstrip('\\') + '\\')
|
||||
return normalized_target == normalized_root or normalized_target.startswith(normalized_root.rstrip('/') + '/')
|
||||
|
||||
def _is_allowed_share_path(target_url: str) -> bool:
|
||||
target_kind, normalized_target = _normalize_allowed_share_path(target_url)
|
||||
if not normalized_target:
|
||||
return False
|
||||
history_share_root = ''
|
||||
history_local_root = ''
|
||||
if has_request_context():
|
||||
history_share_root = str(current_app.config.get('FIXED_ASSET_HISTORY_SHARE_ROOT') or '').strip()
|
||||
history_local_root = str(current_app.config.get('FIXED_ASSET_HISTORY_LOCAL_ROOT') or '').strip()
|
||||
if not history_share_root:
|
||||
history_share_root = str(Config.FIXED_ASSET_HISTORY_SHARE_ROOT or '').strip()
|
||||
if not history_local_root:
|
||||
history_local_root = str(Config.FIXED_ASSET_HISTORY_LOCAL_ROOT or '').strip()
|
||||
roots = [
|
||||
PLM_PREVIEW_SHARE_ROOT,
|
||||
history_share_root,
|
||||
history_local_root,
|
||||
]
|
||||
return any(root and _is_path_within_allowed_root(normalized_target, root) for root in roots)
|
||||
|
||||
def _is_allowed_preview_url(target_url: str) -> bool:
|
||||
"""
|
||||
预览代理 URL 白名单校验。
|
||||
仅允许:
|
||||
1) 配置中的集成服务主机;
|
||||
2) 本机地址;
|
||||
3) 私网 IP 或常见内网域名(.local/.lan)。
|
||||
"""
|
||||
try:
|
||||
if _is_allowed_share_path(target_url):
|
||||
return True
|
||||
parsed = urlparse(target_url)
|
||||
if parsed.scheme not in ('http', 'https'):
|
||||
return False
|
||||
host = (parsed.hostname or '').strip().lower()
|
||||
if not host:
|
||||
return False
|
||||
integration_base = (IntegrationApiService.get_base_url() or '').strip()
|
||||
if integration_base:
|
||||
integration_host = (urlparse(integration_base).hostname or '').strip().lower()
|
||||
if integration_host and host == integration_host:
|
||||
return True
|
||||
|
||||
# 放行当前请求的 Host (前端能够访问本接口说明 Host 是受信任的自身域名/IP)
|
||||
if has_request_context():
|
||||
req_host = (request.host.split(':')[0] or "").strip().lower()
|
||||
if host == req_host:
|
||||
return True
|
||||
|
||||
if host in ("localhost", "127.0.0.1", "::1"):
|
||||
return True
|
||||
try:
|
||||
ip = ipaddress.ip_address(host)
|
||||
return ip.is_private or ip.is_loopback
|
||||
except ValueError:
|
||||
# 非 IP 主机:仅放行内网风格本地域名。
|
||||
return host.endswith(".local") or host.endswith(".lan") or host.endswith(".well-trust.com")
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def _fetch_preview_source_bytes(file_url: str, max_size: int | None=15 * 1024 * 1024):
|
||||
"""
|
||||
从上游文件 URL 拉取二进制内容(供预览接口复用)。
|
||||
如果 file_url 是内部 integration API 下载链接且包含过期 token,则尝试重新获取最新链接。
|
||||
返回: (content_bytes, content_type, error_tuple)
|
||||
其中 error_tuple = (message, status_code);成功时为 None。
|
||||
"""
|
||||
import base64
|
||||
import json
|
||||
import time
|
||||
import sqlalchemy as sa
|
||||
from urllib.parse import parse_qs
|
||||
if _is_allowed_share_path(file_url):
|
||||
_path_kind, normalized_path = _normalize_allowed_share_path(file_url)
|
||||
try:
|
||||
if not os.path.isfile(normalized_path):
|
||||
return (None, None, ('source file not found', 404))
|
||||
file_size = os.path.getsize(normalized_path)
|
||||
if max_size is not None and file_size > max_size:
|
||||
return (None, None, ('file too large for online preview', 413))
|
||||
with open(normalized_path, 'rb') as fh:
|
||||
content = fh.read()
|
||||
except OSError as exc:
|
||||
current_app.logger.warning('[file-preview] failed to read share path %s: %s', normalized_path, exc)
|
||||
return (None, None, ('failed to read source file', 502))
|
||||
guessed_type = (mimetypes.guess_type(normalized_path)[0] or '').strip().lower()
|
||||
if _extract_placeholder_text(content):
|
||||
guessed_type = 'text/plain; charset=utf-8'
|
||||
return (content, guessed_type, None)
|
||||
try:
|
||||
from app.services.fixed_asset_image import FixedAssetImageService
|
||||
content, content_type, asset_image_err = FixedAssetImageService.fetch_preview_bytes(
|
||||
file_url,
|
||||
max_size=max_size,
|
||||
)
|
||||
if content is not None or asset_image_err is not None:
|
||||
return (content, content_type, asset_image_err)
|
||||
except Exception as exc:
|
||||
current_app.logger.warning('[file-preview] fixed asset image fetch failed url=%s err=%s', file_url, exc)
|
||||
headers = {}
|
||||
base_url = IntegrationApiService.get_base_url()
|
||||
api_key = IntegrationApiService.get_api_key()
|
||||
|
||||
def _resolve_latest_integration_url(raw_url: str):
|
||||
dataset_id = ''
|
||||
remote_document_id = ''
|
||||
try:
|
||||
parsed = urlparse(raw_url)
|
||||
qs = parse_qs(parsed.query)
|
||||
token = (qs.get('token') or [''])[0]
|
||||
if token:
|
||||
parts = token.split('.')
|
||||
if len(parts) >= 2:
|
||||
payload_b64 = parts[1]
|
||||
payload_b64 += '=' * (-len(payload_b64) % 4)
|
||||
payload_data = json.loads(base64.urlsafe_b64decode(payload_b64).decode('utf-8'))
|
||||
dataset_id = str(payload_data.get('dataset_id') or '').strip()
|
||||
remote_document_id = str(payload_data.get('remote_document_id') or '').strip()
|
||||
except Exception:
|
||||
pass
|
||||
if not dataset_id or not remote_document_id:
|
||||
try:
|
||||
stmt = sa.text('CAST(retriever_resources AS TEXT) LIKE :url')
|
||||
log = db.session.query(ChatLog).filter(stmt).params(url=f'%{raw_url}%').order_by(ChatLog.created_at.desc()).first()
|
||||
if log and log.retriever_resources:
|
||||
for r in log.retriever_resources:
|
||||
if not isinstance(r, dict):
|
||||
continue
|
||||
source_url = str(r.get('source_download_url') or '')
|
||||
if source_url == raw_url or (source_url and source_url.split('&token=')[0] == raw_url.split('&token=')[0]):
|
||||
resolved_dataset_id, resolved_remote_document_id = DifyService._extract_dify_ids(r)
|
||||
dataset_id = dataset_id or str(resolved_dataset_id or '').strip()
|
||||
remote_document_id = remote_document_id or str(resolved_remote_document_id or '').strip()
|
||||
if dataset_id and remote_document_id:
|
||||
break
|
||||
except Exception as e:
|
||||
current_app.logger.warning('[file-preview] failed to find IDs in ChatLog: %s', e)
|
||||
if dataset_id and remote_document_id:
|
||||
new_info = IntegrationApiService.lookup_file_by_dify(dataset_id, remote_document_id)
|
||||
if new_info and new_info.get('source_download_url'):
|
||||
current_app.logger.info('[file-preview] refreshed integration url for dataset=%s doc=%s', dataset_id, remote_document_id)
|
||||
return new_info['source_download_url']
|
||||
return raw_url
|
||||
|
||||
def _build_headers(raw_url: str):
|
||||
next_headers = {}
|
||||
|
||||
is_trusted = False
|
||||
if base_url and raw_url.startswith(base_url):
|
||||
is_trusted = True
|
||||
elif _is_allowed_preview_url(raw_url):
|
||||
is_trusted = True
|
||||
else:
|
||||
try:
|
||||
parsed = urlparse(raw_url)
|
||||
host = (parsed.hostname or "").strip().lower()
|
||||
if has_request_context():
|
||||
req_host = (request.host.split(':')[0] or "").strip().lower()
|
||||
if host == req_host:
|
||||
is_trusted = True
|
||||
if host in ("localhost", "127.0.0.1", "::1"):
|
||||
is_trusted = True
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
current_app.logger.info(f"[_build_headers] raw_url={raw_url}, is_trusted={is_trusted}")
|
||||
if is_trusted:
|
||||
if api_key:
|
||||
next_headers['X-Integration-Key'] = api_key
|
||||
if has_request_context():
|
||||
auth_header = (request.headers.get('Authorization') or '').strip()
|
||||
cookie_header = (request.headers.get('Cookie') or '').strip()
|
||||
if auth_header:
|
||||
next_headers['Authorization'] = auth_header
|
||||
if cookie_header:
|
||||
next_headers['Cookie'] = cookie_header
|
||||
|
||||
return next_headers
|
||||
|
||||
def _should_refresh_from_response(resp) -> bool:
|
||||
ctype = (resp.headers.get('content-type') or '').split(';')[0].strip().lower()
|
||||
if resp.status_code == 401:
|
||||
return True
|
||||
if resp.status_code in (403, 404) and 'token=' in file_url:
|
||||
return True
|
||||
if ctype == 'application/json':
|
||||
body = (resp.content or b'')[:512].decode('utf-8', errors='ignore').lower()
|
||||
if 'unauthorized' in body or '"error"' in body:
|
||||
return True
|
||||
return False
|
||||
|
||||
def _retry_with_refreshed_url(raw_url: str):
|
||||
refreshed_url = _resolve_latest_integration_url(raw_url)
|
||||
if not refreshed_url or refreshed_url == raw_url:
|
||||
return None, raw_url
|
||||
retry_headers = _build_headers(refreshed_url)
|
||||
try:
|
||||
return requests.get(refreshed_url, headers=retry_headers, timeout=(5, 20)), refreshed_url
|
||||
except requests.RequestException as e:
|
||||
current_app.logger.warning('[file-preview] refreshed upstream request failed: %s', e)
|
||||
return None, refreshed_url
|
||||
|
||||
if 'token=' in file_url:
|
||||
try:
|
||||
parsed = urlparse(file_url)
|
||||
qs = parse_qs(parsed.query)
|
||||
token = (qs.get('token') or [''])[0]
|
||||
if token:
|
||||
parts = token.split('.')
|
||||
if len(parts) >= 2:
|
||||
payload_b64 = parts[1]
|
||||
payload_b64 += '=' * (-len(payload_b64) % 4)
|
||||
payload_data = json.loads(base64.urlsafe_b64decode(payload_b64).decode('utf-8'))
|
||||
exp = payload_data.get('exp', 0)
|
||||
if exp and exp < time.time() + 300:
|
||||
file_url = _resolve_latest_integration_url(file_url)
|
||||
except Exception as e:
|
||||
current_app.logger.warning('[file-preview] failed to refresh expired integration token: %s', e)
|
||||
headers = _build_headers(file_url)
|
||||
try:
|
||||
upstream = requests.get(file_url, headers=headers, timeout=(5, 20))
|
||||
except requests.RequestException as e:
|
||||
current_app.logger.warning('[file-preview] upstream request failed: %s', e)
|
||||
return (None, None, ('failed to fetch source file', 502))
|
||||
if 'token=' in file_url and _should_refresh_from_response(upstream):
|
||||
refreshed_upstream, refreshed_url = _retry_with_refreshed_url(file_url)
|
||||
if refreshed_upstream is not None:
|
||||
upstream = refreshed_upstream
|
||||
file_url = refreshed_url
|
||||
if upstream.status_code != 200:
|
||||
if 'token=' in file_url:
|
||||
refreshed_upstream, refreshed_url = _retry_with_refreshed_url(file_url)
|
||||
if refreshed_upstream is not None:
|
||||
upstream = refreshed_upstream
|
||||
file_url = refreshed_url
|
||||
current_app.logger.warning(f"[file-preview] upstream returned status {upstream.status_code} for {file_url}")
|
||||
if upstream.status_code == 404:
|
||||
return None, None, ('source file not found', 404)
|
||||
return None, None, (f'upstream returned status {upstream.status_code}', 502)
|
||||
|
||||
content = upstream.content or b''
|
||||
if max_size is not None and len(content) > max_size:
|
||||
return (None, None, ('file too large for online preview', 413))
|
||||
content_type = (upstream.headers.get('content-type') or '').split(';')[0].strip().lower()
|
||||
if content_type == 'application/json':
|
||||
body = content[:512].decode('utf-8', errors='ignore')
|
||||
current_app.logger.warning('[file-preview] upstream returned json instead of binary url=%s body=%s', file_url, body)
|
||||
return (None, None, ('upstream returned invalid preview payload', 502))
|
||||
return (content, content_type, None)
|
||||
|
||||
def _extract_placeholder_text(content: bytes) -> str:
|
||||
sample = content[:2048]
|
||||
for enc in ('utf-16le', 'utf-8', 'utf-8-sig', 'gb18030', 'latin-1'):
|
||||
try:
|
||||
text = sample.decode(enc).replace('\x00', '').strip()
|
||||
except Exception:
|
||||
continue
|
||||
if not text:
|
||||
continue
|
||||
lines = [line.strip() for line in text.splitlines() if line.strip()]
|
||||
if not lines:
|
||||
continue
|
||||
first_line = lines[0][:160]
|
||||
if any((token in first_line for token in ('该文件', '机密文件', '未经允许', '法律风险', '禁止', '保密'))):
|
||||
return first_line
|
||||
return ''
|
||||
|
||||
def _fetch_dify_text_document(dataset_id: str, remote_document_id: str) -> str | None:
|
||||
"""
|
||||
对于 Dify 中以 text_model / txt 形式存储的文档,
|
||||
直接拼接 segments 内容,避免依赖可能失效的 file-preview 签名链接。
|
||||
"""
|
||||
if not dataset_id or not remote_document_id:
|
||||
return None
|
||||
try:
|
||||
from app.services.knowledge_cleaning.dify_sync_service import KbDifySyncService
|
||||
service = KbDifySyncService()
|
||||
document_payload = service.get_document(
|
||||
dataset_id=str(dataset_id),
|
||||
document_id=str(remote_document_id),
|
||||
)
|
||||
if not isinstance(document_payload, dict):
|
||||
return None
|
||||
|
||||
upload_info = (
|
||||
((document_payload.get('data_source_info') or {}).get('upload_file'))
|
||||
if isinstance(document_payload.get('data_source_info'), dict)
|
||||
else {}
|
||||
) or {}
|
||||
source_ext = str(upload_info.get('extension') or '').strip().lower()
|
||||
doc_form = str(document_payload.get('doc_form') or '').strip().lower()
|
||||
mime_type = str(upload_info.get('mime_type') or '').strip().lower()
|
||||
is_text_doc = (
|
||||
source_ext in ('txt', 'md', 'markdown', 'csv', 'html', 'htm', 'properties', 'vtt')
|
||||
or doc_form == 'text_model'
|
||||
or mime_type.startswith('text/')
|
||||
)
|
||||
if not is_text_doc:
|
||||
return None
|
||||
|
||||
segments_payload = service._request(
|
||||
'GET',
|
||||
f'/datasets/{dataset_id}/documents/{remote_document_id}/segments?limit=1000',
|
||||
)
|
||||
rows = []
|
||||
if isinstance(segments_payload, dict):
|
||||
rows = segments_payload.get('data') or []
|
||||
elif isinstance(segments_payload, list):
|
||||
rows = segments_payload
|
||||
if not isinstance(rows, list) or not rows:
|
||||
return None
|
||||
|
||||
ordered_rows = sorted(
|
||||
[row for row in rows if isinstance(row, dict)],
|
||||
key=lambda row: (int(row.get('position') or 0), str(row.get('id') or '')),
|
||||
)
|
||||
parts: list[str] = []
|
||||
for row in ordered_rows:
|
||||
text = str(row.get('content') or '').strip()
|
||||
if text:
|
||||
parts.append(text)
|
||||
return '\n\n'.join(parts).strip() or None
|
||||
except Exception as e:
|
||||
current_app.logger.warning(
|
||||
'[source-file-text] failed to fetch dify text document dataset=%s doc=%s err=%s',
|
||||
dataset_id,
|
||||
remote_document_id,
|
||||
e,
|
||||
)
|
||||
return None
|
||||
|
||||
def _convert_office_to_pdf(content: bytes, ext: str) -> bytes:
|
||||
"""
|
||||
使用 LibreOffice 或 WPS/MS Office 将 office 文件转为 PDF
|
||||
"""
|
||||
import shutil
|
||||
temp_dir = tempfile.mkdtemp()
|
||||
try:
|
||||
input_path = os.path.join(temp_dir, f"input.{ext}")
|
||||
with open(input_path, 'wb') as f:
|
||||
f.write(content)
|
||||
commands = ['soffice', 'libreoffice', 'C:\\Program Files\\LibreOffice\\program\\soffice.exe', 'C:\\Program Files (x86)\\LibreOffice\\program\\soffice.exe']
|
||||
success = False
|
||||
for cmd in commands:
|
||||
try:
|
||||
process = subprocess.run([cmd, '--headless', '--convert-to', 'pdf', '--outdir', temp_dir, input_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=60)
|
||||
if process.returncode == 0:
|
||||
success = True
|
||||
break
|
||||
else:
|
||||
current_app.logger.warning(f"LibreOffice command {cmd} failed: {process.stderr.decode('utf-8', errors='ignore')}")
|
||||
except (FileNotFoundError, subprocess.TimeoutExpired):
|
||||
continue
|
||||
if not success and os.name == 'nt':
|
||||
app = None
|
||||
doc_obj = None
|
||||
pythoncom = None
|
||||
try:
|
||||
import win32com.client
|
||||
import pythoncom
|
||||
pythoncom.CoInitialize()
|
||||
output_path = os.path.join(temp_dir, 'input.pdf')
|
||||
if ext in ('doc', 'docx'):
|
||||
try:
|
||||
from pathlib import Path
|
||||
from edkb_system.skills.word_bridge import convert_with_word
|
||||
|
||||
convert_with_word(Path(input_path), Path(output_path), 17)
|
||||
success = True
|
||||
except Exception as word_bridge_exc:
|
||||
current_app.logger.warning("Word bridge conversion failed: %s", word_bridge_exc)
|
||||
|
||||
if not success and ext in ('doc', 'docx'):
|
||||
try:
|
||||
# 对旧版 .doc,MS Word 的 PDF 导出兼容性通常优于 WPS
|
||||
app = win32com.client.Dispatch("Word.Application")
|
||||
except Exception:
|
||||
app = win32com.client.Dispatch("KWPS.Application")
|
||||
app.Visible = False
|
||||
app.DisplayAlerts = False
|
||||
input_abs = os.path.abspath(input_path)
|
||||
output_abs = os.path.abspath(output_path)
|
||||
try:
|
||||
doc_obj = app.Documents.Open(
|
||||
FileName=input_abs,
|
||||
ConfirmConversions=False,
|
||||
ReadOnly=True,
|
||||
AddToRecentFiles=False,
|
||||
Visible=False,
|
||||
NoEncodingDialog=True,
|
||||
OpenAndRepair=True,
|
||||
)
|
||||
except TypeError:
|
||||
doc_obj = app.Documents.Open(input_abs, ReadOnly=True)
|
||||
|
||||
try:
|
||||
# 旧版 WPS/Word 对 ExportAsFixedFormat 的兼容通常优于 SaveAs(FileFormat=17)
|
||||
doc_obj.ExportAsFixedFormat(output_abs, 17) # 17 = wdExportFormatPDF
|
||||
except Exception:
|
||||
doc_obj.SaveAs(output_abs, 17) # 17 = wdFormatPDF
|
||||
success = True
|
||||
elif ext in ('ppt', 'pptx'):
|
||||
try:
|
||||
app = win32com.client.Dispatch('KWPP.Application')
|
||||
except Exception:
|
||||
app = win32com.client.Dispatch('PowerPoint.Application')
|
||||
app.Visible = False
|
||||
try:
|
||||
app.DisplayAlerts = False
|
||||
except Exception:
|
||||
pass
|
||||
doc_obj = app.Presentations.Open(os.path.abspath(input_path), ReadOnly=True, WithWindow=False)
|
||||
doc_obj.SaveAs(os.path.abspath(output_path), 32) # 32 = ppSaveAsPDF
|
||||
success = True
|
||||
elif ext in ('xls', 'xlsx'):
|
||||
try:
|
||||
app = win32com.client.Dispatch('KET.Application')
|
||||
except Exception:
|
||||
app = win32com.client.Dispatch('Excel.Application')
|
||||
app.Visible = False
|
||||
app.DisplayAlerts = False
|
||||
doc_obj = app.Workbooks.Open(os.path.abspath(input_path), ReadOnly=True)
|
||||
doc_obj.ExportAsFixedFormat(0, os.path.abspath(output_path)) # 0 = xlTypePDF
|
||||
success = True
|
||||
except ImportError:
|
||||
current_app.logger.warning('pywin32 not installed, cannot fallback to WPS/MS Office COM API.')
|
||||
except Exception as e:
|
||||
current_app.logger.warning(f"WPS/MS Office COM conversion failed: {e}")
|
||||
finally:
|
||||
if doc_obj is not None:
|
||||
try:
|
||||
doc_obj.Close(False)
|
||||
except Exception:
|
||||
pass
|
||||
if app is not None:
|
||||
try:
|
||||
app.Quit()
|
||||
except Exception:
|
||||
pass
|
||||
if pythoncom is not None:
|
||||
try:
|
||||
pythoncom.CoUninitialize()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not success:
|
||||
raise Exception('Failed to convert document to PDF using LibreOffice or WPS/MS Office')
|
||||
output_path = os.path.join(temp_dir, 'input.pdf')
|
||||
if os.path.exists(output_path):
|
||||
with open(output_path, 'rb') as f:
|
||||
return f.read()
|
||||
else:
|
||||
raise Exception("PDF output not found after conversion")
|
||||
finally:
|
||||
shutil.rmtree(temp_dir, ignore_errors=True)
|
||||
|
||||
def _convert_excel_to_xlsx(content: bytes, ext: str) -> bytes:
|
||||
"""
|
||||
使用 LibreOffice 将老式 `.xls` 转为 `.xlsx`,供在线预览解析。
|
||||
"""
|
||||
normalized_ext = (ext or '').strip().lower()
|
||||
if normalized_ext != 'xls':
|
||||
return content
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
input_path = os.path.join(temp_dir, 'input.xls')
|
||||
output_path = os.path.join(temp_dir, 'input.xlsx')
|
||||
with open(input_path, 'wb') as f:
|
||||
f.write(content)
|
||||
commands = ['soffice', 'libreoffice', 'C:\\Program Files\\LibreOffice\\program\\soffice.exe', 'C:\\Program Files (x86)\\LibreOffice\\program\\soffice.exe']
|
||||
errors = []
|
||||
for cmd in commands:
|
||||
try:
|
||||
process = subprocess.run([cmd, '--headless', '--convert-to', 'xlsx', '--outdir', temp_dir, input_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=60)
|
||||
except (FileNotFoundError, subprocess.TimeoutExpired) as e:
|
||||
errors.append(f'{cmd}: {e}')
|
||||
continue
|
||||
if process.returncode == 0 and os.path.exists(output_path):
|
||||
with open(output_path, 'rb') as f:
|
||||
return f.read()
|
||||
stderr = process.stderr.decode('utf-8', errors='ignore').strip()
|
||||
errors.append(f"{cmd}: {stderr or f'code={process.returncode}'}")
|
||||
|
||||
allow_windows_excel_preview = (
|
||||
os.getenv('ENABLE_WINDOWS_EXCEL_PREVIEW_CONVERSION', '').strip().lower() in ('1', 'true', 'yes', 'on')
|
||||
)
|
||||
if allow_windows_excel_preview:
|
||||
if _convert_excel_via_windows_office(input_path, output_path):
|
||||
with open(output_path, 'rb') as f:
|
||||
return f.read()
|
||||
errors.append("windows-office: failed to convert xls via WPS/MS Excel")
|
||||
else:
|
||||
errors.append("windows-office: disabled for preview to avoid interactive Office dialogs")
|
||||
|
||||
joined = "; ".join(errors) if errors else "no converter attempted"
|
||||
raise RuntimeError(f"failed to convert xls to xlsx: {joined}")
|
||||
|
||||
def _convert_excel_via_windows_office(input_path: str, output_path: str) -> bool:
|
||||
"""
|
||||
在 Windows 环境下使用 WPS/MS Excel 将 `.xls` 转为 `.xlsx`。
|
||||
LibreOffice 不存在时,给在线预览提供兜底转换能力。
|
||||
"""
|
||||
if os.name != 'nt':
|
||||
return False
|
||||
try:
|
||||
import pythoncom
|
||||
import win32com.client
|
||||
except ImportError:
|
||||
current_app.logger.warning('pywin32 not installed, cannot fallback to WPS/MS Excel for xls preview.')
|
||||
return False
|
||||
app = None
|
||||
workbook = None
|
||||
pythoncom.CoInitialize()
|
||||
try:
|
||||
try:
|
||||
app = win32com.client.Dispatch('KET.Application')
|
||||
except Exception:
|
||||
app = win32com.client.Dispatch('Excel.Application')
|
||||
app.Visible = False
|
||||
app.DisplayAlerts = False
|
||||
workbook = app.Workbooks.Open(os.path.abspath(input_path))
|
||||
workbook.SaveAs(os.path.abspath(output_path), FileFormat=51)
|
||||
workbook.Close(False)
|
||||
workbook = None
|
||||
app.Quit()
|
||||
app = None
|
||||
return os.path.exists(output_path)
|
||||
except Exception as exc:
|
||||
current_app.logger.warning('WPS/MS Excel conversion failed for xls preview: %s', exc)
|
||||
return False
|
||||
finally:
|
||||
try:
|
||||
if workbook is not None:
|
||||
workbook.Close(False)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
if app is not None:
|
||||
app.Quit()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
pythoncom.CoUninitialize()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _detect_excel_format(content: bytes, ext: str) -> str:
|
||||
"""
|
||||
根据文件头兜底判断 Excel 实际格式,避免只依赖 URL/文件名扩展名。
|
||||
- OLE 复合文档头: 老式 `.xls`
|
||||
- ZIP 头: `.xlsx`
|
||||
"""
|
||||
normalized_ext = (ext or '').strip().lower()
|
||||
head = content[:8] if content else b''
|
||||
if head.startswith(b'PK\x03\x04'):
|
||||
return 'xlsx'
|
||||
if head.startswith(b'\xd0\xcf\x11\xe0'):
|
||||
return 'xls'
|
||||
return normalized_ext
|
||||
|
||||
def _load_excel_workbook(content: bytes, ext: str):
|
||||
normalized_ext = _detect_excel_format(content, ext)
|
||||
if normalized_ext == 'xls':
|
||||
content = _convert_excel_to_xlsx(content, 'xls')
|
||||
return load_workbook(filename=io.BytesIO(content), data_only=True, read_only=True)
|
||||
@@ -0,0 +1,330 @@
|
||||
"""
|
||||
api/chat/previews.py
|
||||
|
||||
用途:处理聊天来源文件、Excel、文本及原始文件预览路由。
|
||||
依赖:chat.shared、chat.preview_support、Dify 与共享盘数据源。
|
||||
逻辑:校验预览来源后获取文件内容,按格式转换并返回安全的预览响应。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from .shared import * # noqa: F403
|
||||
from . import chat_bp
|
||||
from .preview_support import (
|
||||
_convert_office_to_pdf,
|
||||
_detect_excel_format,
|
||||
_extract_placeholder_text,
|
||||
_fetch_dify_text_document,
|
||||
_fetch_preview_source_bytes,
|
||||
_is_allowed_preview_url,
|
||||
_load_excel_workbook,
|
||||
)
|
||||
|
||||
|
||||
@chat_bp.route('/source-file', methods=['GET'])
|
||||
@require_agent_permission
|
||||
def resolve_source_file():
|
||||
"""
|
||||
Resolve original source download URL by Dify dataset/document IDs.
|
||||
"""
|
||||
dataset_id = (request.args.get('dataset_id') or '').strip()
|
||||
remote_document_id = (request.args.get('remote_document_id') or '').strip()
|
||||
if not dataset_id or not remote_document_id:
|
||||
current_app.logger.warning('[source-file] missing required params: dataset_id=%r remote_document_id_present=%s remote_document_id_preview=%r query_args=%s', dataset_id, bool(remote_document_id), remote_document_id[:8] + '...' if remote_document_id else '', dict(request.args))
|
||||
raise ValidationError('dataset_id and remote_document_id are required')
|
||||
payload = IntegrationApiService.lookup_file_by_dify(dataset_id, remote_document_id)
|
||||
if not payload:
|
||||
raise NotFoundError('source file mapping not found')
|
||||
|
||||
source_ext = str(payload.get('source_ext') or '').strip().lower()
|
||||
source_download_url = payload.get('source_download_url')
|
||||
|
||||
return jsonify({
|
||||
'dataset_id': dataset_id,
|
||||
'remote_document_id': remote_document_id,
|
||||
'source_filename': payload.get('source_filename'),
|
||||
'source_ext': source_ext,
|
||||
'source_download_url': source_download_url,
|
||||
'download_url_expires_at': payload.get('download_url_expires_at'),
|
||||
})
|
||||
|
||||
@chat_bp.route('/source-file-text', methods=['GET'])
|
||||
@require_agent_permission
|
||||
def source_file_text():
|
||||
dataset_id = (request.args.get('dataset_id') or '').strip()
|
||||
remote_document_id = (request.args.get('remote_document_id') or '').strip()
|
||||
if not dataset_id or not remote_document_id:
|
||||
raise ValidationError('dataset_id and remote_document_id are required')
|
||||
|
||||
text = _fetch_dify_text_document(dataset_id, remote_document_id)
|
||||
if not text:
|
||||
raise NotFoundError('failed to resolve text source file')
|
||||
|
||||
filename = f'{remote_document_id}.txt'
|
||||
return Response(
|
||||
text,
|
||||
status=200,
|
||||
mimetype='text/plain; charset=utf-8',
|
||||
headers={
|
||||
'Content-Disposition': f'inline; filename="{filename}"',
|
||||
'Cache-Control': 'no-store',
|
||||
},
|
||||
)
|
||||
|
||||
@chat_bp.route('/preview-excel', methods=['GET'])
|
||||
@require_agent_permission
|
||||
def preview_excel():
|
||||
"""
|
||||
内网 Excel 预览接口(简版可上线)。
|
||||
说明:
|
||||
- xlsx 直接解析;
|
||||
- xls 先转为 xlsx 后再解析。
|
||||
"""
|
||||
file_url = (request.args.get('url') or '').strip()
|
||||
if not file_url:
|
||||
raise ValidationError('url is required')
|
||||
if not _is_allowed_preview_url(file_url):
|
||||
raise ForbiddenError('url is not allowed for preview')
|
||||
parsed = urlparse(file_url)
|
||||
url_path_ext = ((parsed.path or '').split('.')[-1] if '.' in (parsed.path or '') else '').lower()
|
||||
name = (request.args.get('name') or '').strip()
|
||||
name_ext = (name.split('.')[-1] if '.' in name else '').lower()
|
||||
ext = url_path_ext or name_ext
|
||||
if ext and ext not in ('xlsx', 'xls'):
|
||||
raise_for_status(f'unsupported file extension: {ext}', 415)
|
||||
try:
|
||||
limit = int(request.args.get('limit', 100))
|
||||
except ValueError:
|
||||
limit = 100
|
||||
limit = max(1, min(limit, 300))
|
||||
content, _, err = _fetch_preview_source_bytes(file_url, max_size=50 * 1024 * 1024)
|
||||
if err:
|
||||
msg, code = err
|
||||
raise_for_status(msg, code)
|
||||
|
||||
detected_ext = _detect_excel_format(content or b'', ext)
|
||||
if detected_ext not in ('xlsx', 'xls'):
|
||||
raise_for_status(f'unsupported file extension: {ext or detected_ext or "unknown"}', 415)
|
||||
|
||||
try:
|
||||
wb = _load_excel_workbook(content, detected_ext)
|
||||
except Exception as e:
|
||||
current_app.logger.warning(
|
||||
"[excel-preview] parse workbook failed ext=%s detected_ext=%s size=%s name=%s url=%s err=%r",
|
||||
ext,
|
||||
detected_ext,
|
||||
len(content or b''),
|
||||
name,
|
||||
file_url,
|
||||
e,
|
||||
)
|
||||
details: dict = {}
|
||||
if current_app.config.get('DEBUG') or os.getenv('ENV_NAME', 'dev').strip().lower() == 'dev':
|
||||
details = {'detail': str(e), 'ext': ext, 'detected_ext': detected_ext, 'size': len(content or b'')}
|
||||
raise AppError(code='VALIDATION.UNPROCESSABLE', message='failed to parse excel file', http_status=422, details=details)
|
||||
if not wb.sheetnames:
|
||||
raise_for_status('workbook has no sheets', 422)
|
||||
requested_sheet = (request.args.get('sheet') or '').strip()
|
||||
sheet_name = requested_sheet if requested_sheet in wb.sheetnames else wb.sheetnames[0]
|
||||
ws = wb[sheet_name]
|
||||
rows = []
|
||||
for row in ws.iter_rows(values_only=True):
|
||||
normalized = []
|
||||
for cell in row:
|
||||
if cell is None:
|
||||
normalized.append('')
|
||||
elif isinstance(cell, (int, float, bool)):
|
||||
normalized.append(cell)
|
||||
else:
|
||||
normalized.append(str(cell))
|
||||
rows.append(normalized)
|
||||
if len(rows) >= limit:
|
||||
break
|
||||
max_cols = max((len(r) for r in rows), default=0)
|
||||
for r in rows:
|
||||
if len(r) < max_cols:
|
||||
r.extend([''] * (max_cols - len(r)))
|
||||
columns = [f'COL_{i + 1}' for i in range(max_cols)]
|
||||
return jsonify({'sheet_name': sheet_name, 'sheets': wb.sheetnames, 'columns': columns, 'rows': rows, 'limit': limit, 'truncated': len(rows) >= limit})
|
||||
|
||||
@chat_bp.route('/preview-text', methods=['GET'])
|
||||
@require_agent_permission
|
||||
def preview_text():
|
||||
"""
|
||||
文本类文件预览接口(内网代理)。
|
||||
支持:md/markdown/txt/csv/vtt/properties/html/htm
|
||||
"""
|
||||
file_url = (request.args.get('url') or '').strip()
|
||||
if not file_url:
|
||||
raise ValidationError('url is required')
|
||||
if not _is_allowed_preview_url(file_url):
|
||||
raise ForbiddenError('url is not allowed for preview')
|
||||
parsed = urlparse(file_url)
|
||||
url_path_ext = ((parsed.path or '').split('.')[-1] if '.' in (parsed.path or '') else '').lower()
|
||||
name = (request.args.get('name') or '').strip()
|
||||
name_ext = (name.split('.')[-1] if '.' in name else '').lower()
|
||||
explicit_ext = (request.args.get('ext') or '').strip().lower()
|
||||
ext = explicit_ext or url_path_ext or name_ext
|
||||
allowed = {'md', 'markdown', 'txt', 'csv', 'vtt', 'properties', 'html', 'htm'}
|
||||
if ext and ext not in allowed:
|
||||
raise_for_status(f'unsupported text extension: {ext}', 415)
|
||||
max_size = 100 * 1024 * 1024 if request.args.get('download') == '1' else 15 * 1024 * 1024
|
||||
content, content_type, err = _fetch_preview_source_bytes(file_url, max_size=max_size)
|
||||
if err:
|
||||
msg, code = err
|
||||
raise_for_status(msg, code)
|
||||
text = None
|
||||
for enc in ('utf-8', 'utf-8-sig', 'gb18030', 'latin-1'):
|
||||
try:
|
||||
text = content.decode(enc)
|
||||
break
|
||||
except Exception:
|
||||
continue
|
||||
if text is None:
|
||||
raise_for_status('failed to decode text file', 422)
|
||||
return jsonify({'content': text, 'content_type': content_type or 'text/plain', 'ext': ext})
|
||||
|
||||
def _guess_ext_from_content(content: bytes, default_ext: str) -> str:
|
||||
"""
|
||||
根据文件内容(Magic Bytes)纠正可能的错误扩展名
|
||||
"""
|
||||
import io
|
||||
import zipfile
|
||||
|
||||
if not content:
|
||||
return default_ext
|
||||
if content.startswith(b'%PDF-'):
|
||||
return 'pdf'
|
||||
if content.startswith(b'PK\x03\x04'):
|
||||
# ZIP 归档,进一步检查内部目录判断是 docx/xlsx/pptx。
|
||||
try:
|
||||
with zipfile.ZipFile(io.BytesIO(content)) as zf:
|
||||
names = {name.lower() for name in zf.namelist()}
|
||||
if any(name.startswith('word/') for name in names):
|
||||
return 'docx'
|
||||
if any(name.startswith('xl/') for name in names):
|
||||
return 'xlsx'
|
||||
if any(name.startswith('ppt/') for name in names):
|
||||
return 'pptx'
|
||||
except Exception:
|
||||
pass
|
||||
if default_ext == 'doc':
|
||||
return 'docx'
|
||||
if default_ext == 'xls':
|
||||
return 'xlsx'
|
||||
if default_ext == 'ppt':
|
||||
return 'pptx'
|
||||
if default_ext in ('docx', 'xlsx', 'pptx'):
|
||||
return default_ext
|
||||
return 'docx'
|
||||
if content.startswith(b'\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1'):
|
||||
# OLE 复合文件,通常是 doc, xls, ppt 等。
|
||||
if default_ext == 'docx': return 'doc'
|
||||
if default_ext == 'xlsx': return 'xls'
|
||||
if default_ext == 'pptx': return 'ppt'
|
||||
if default_ext in ('doc', 'xls', 'ppt'): return default_ext
|
||||
return 'doc'
|
||||
return default_ext
|
||||
|
||||
@chat_bp.route('/preview-file-raw', methods=['GET'])
|
||||
@require_agent_permission
|
||||
def preview_file_raw():
|
||||
"""
|
||||
二进制文件内网代理预览接口。
|
||||
用途:
|
||||
- 为 pdf/doc/docx 生成可被前端 iframe 访问的同源地址;
|
||||
- 尽量使用 inline 响应头,避免强制下载。
|
||||
"""
|
||||
file_url = (request.args.get('url') or '').strip()
|
||||
if not file_url:
|
||||
raise ValidationError('url is required')
|
||||
if not _is_allowed_preview_url(file_url):
|
||||
raise ForbiddenError('url is not allowed for preview')
|
||||
parsed = urlparse(file_url)
|
||||
url_path_ext = ((parsed.path or '').split('.')[-1] if '.' in (parsed.path or '') else '').lower()
|
||||
name = (request.args.get('name') or '').strip()
|
||||
name_ext = (name.split('.')[-1] if '.' in name else '').lower()
|
||||
original_ext = url_path_ext or name_ext
|
||||
ext = original_ext
|
||||
is_download = request.args.get('download') == '1'
|
||||
max_size = None if is_download else 15 * 1024 * 1024
|
||||
content, content_type, err = _fetch_preview_source_bytes(file_url, max_size=max_size)
|
||||
if err:
|
||||
msg, code = err
|
||||
raise_for_status(msg, code)
|
||||
|
||||
# 根据文件二进制头部纠正扩展名,防止文件本身是 docx 却被命名为 doc,导致转换或下载后乱码
|
||||
real_ext = _guess_ext_from_content(content, ext)
|
||||
if real_ext != ext:
|
||||
current_app.logger.info(f"[file-preview] corrected extension from {ext} to {real_ext}")
|
||||
ext = real_ext
|
||||
if name and '.' in name:
|
||||
name = f"{name.rsplit('.', 1)[0]}.{ext}"
|
||||
elif name:
|
||||
name = f"{name}.{ext}"
|
||||
|
||||
# 仅当文件真实格式仍然是旧版 Office/PPT 时才转 PDF。
|
||||
# 如果原始文件名是 .doc 但内容实际是 .docx,则交给前端 Office 组件渲染,
|
||||
# 避免在服务端走旧版转换链路导致长时间卡住。
|
||||
needs_pdf_conversion = (
|
||||
request.args.get('download') != '1'
|
||||
and ext in ('doc', 'ppt', 'pptx')
|
||||
)
|
||||
if needs_pdf_conversion:
|
||||
try:
|
||||
content = _convert_office_to_pdf(content, ext)
|
||||
ext = 'pdf'
|
||||
content_type = 'application/pdf'
|
||||
if name and '.' in name:
|
||||
name = f"{name.rsplit('.', 1)[0]}.pdf"
|
||||
elif name:
|
||||
name = f"{name}.pdf"
|
||||
except Exception as e:
|
||||
current_app.logger.error("[file-preview] LibreOffice conversion failed: %s", e)
|
||||
placeholder_text = _extract_placeholder_text(content)
|
||||
if placeholder_text:
|
||||
content = placeholder_text.encode('utf-8')
|
||||
ext = 'txt'
|
||||
content_type = 'text/plain; charset=utf-8'
|
||||
if name and '.' in name:
|
||||
name = f"{name.rsplit('.', 1)[0]}.txt"
|
||||
elif name:
|
||||
name = f"{name}.txt"
|
||||
current_app.logger.info('[file-preview] office preview degraded to text placeholder for %s', file_url)
|
||||
else:
|
||||
raise AppError(
|
||||
code='VALIDATION.UNPROCESSABLE',
|
||||
message='failed to convert office file for preview',
|
||||
http_status=422,
|
||||
)
|
||||
|
||||
fallback_types = {
|
||||
'pdf': 'application/pdf',
|
||||
'doc': 'application/msword',
|
||||
'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'xls': 'application/vnd.ms-excel',
|
||||
'csv': 'text/csv',
|
||||
'txt': 'text/plain',
|
||||
'md': 'text/markdown',
|
||||
'markdown': 'text/markdown',
|
||||
'html': 'text/html',
|
||||
'htm': 'text/html',
|
||||
}
|
||||
if ext == 'pdf' and not content.startswith(b'%PDF-'):
|
||||
placeholder_text = _extract_placeholder_text(content)
|
||||
if placeholder_text:
|
||||
content = placeholder_text.encode('utf-8')
|
||||
content_type = 'text/plain; charset=utf-8'
|
||||
current_app.logger.info('[file-preview] pdf preview degraded to text placeholder for %s', file_url)
|
||||
mime = content_type or fallback_types.get(ext) or 'application/octet-stream'
|
||||
from urllib.parse import quote
|
||||
filename = (request.args.get('name') or '').strip() or f"preview.{ext or 'bin'}"
|
||||
encoded_filename = quote(filename)
|
||||
ascii_filename = filename.encode('ascii', 'ignore').decode('ascii') or f"preview.{ext or 'bin'}"
|
||||
disposition_type = 'attachment' if is_download else 'inline'
|
||||
resp = Response(content, status=200, mimetype=mime)
|
||||
resp.headers['Content-Disposition'] = f"""{disposition_type}; filename="{ascii_filename}"; filename*=UTF-8''{encoded_filename}"""
|
||||
resp.headers['Cache-Control'] = 'no-store'
|
||||
resp.headers['X-Preview-Actual-Ext'] = ext or ''
|
||||
resp.headers['X-Preview-Original-Ext'] = original_ext or ''
|
||||
return resp
|
||||
@@ -0,0 +1,315 @@
|
||||
"""
|
||||
api/chat/sessions.py
|
||||
|
||||
用途:处理聊天会话、历史消息与本地结构化消息路由。
|
||||
依赖:chat.shared、chat.core、ChatSession、ChatLog。
|
||||
逻辑:校验当前用户和 Agent 后读写会话及日志,保持历史数据兼容查询。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from .shared import * # noqa: F403
|
||||
from . import chat_bp
|
||||
from .core import (
|
||||
_chat_logs_for_session,
|
||||
_ensure_chat_session,
|
||||
_fallback_title_from_contract_review_log,
|
||||
_get_chat_session,
|
||||
_looks_like_review_auto_title,
|
||||
_serialize_session,
|
||||
_session_title_from_text,
|
||||
_user_facing_chat_query,
|
||||
)
|
||||
|
||||
|
||||
@chat_bp.route('/sessions', methods=['GET'])
|
||||
@require_agent_permission
|
||||
def get_chat_sessions():
|
||||
"""
|
||||
获取当前用户与当前 Agent 的历史会话列表
|
||||
"""
|
||||
user = getattr(g, 'current_user', None)
|
||||
agent = getattr(g, 'current_agent', None)
|
||||
if user is None or agent is None:
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing context', http_status=500)
|
||||
|
||||
session_rows = db.session.query(ChatSession).filter(
|
||||
ChatSession.user_id == user.id,
|
||||
ChatSession.agent_id == agent.id,
|
||||
or_(
|
||||
ChatSession.status == 'running',
|
||||
exists().where(
|
||||
and_(
|
||||
ChatLog.session_id == ChatSession.session_id,
|
||||
ChatLog.user_id == user.id,
|
||||
ChatLog.agent_id == agent.id,
|
||||
)
|
||||
),
|
||||
),
|
||||
).order_by(desc(ChatSession.last_active_at), desc(ChatSession.id)).limit(20).all()
|
||||
|
||||
# 纠偏历史:审查结果卡曾把 headline 写成标题时,改用合同文件名展示
|
||||
title_repaired = False
|
||||
for item in session_rows:
|
||||
if not _looks_like_review_auto_title(item.title or ''):
|
||||
continue
|
||||
review_log = (
|
||||
db.session.query(ChatLog)
|
||||
.filter(
|
||||
ChatLog.user_id == user.id,
|
||||
ChatLog.agent_id == agent.id,
|
||||
ChatLog.message_type == 'procurement-contract-review',
|
||||
or_(
|
||||
ChatLog.session_id == item.session_id,
|
||||
ChatLog.conversation_id == item.session_id,
|
||||
),
|
||||
)
|
||||
.order_by(desc(ChatLog.created_at), desc(ChatLog.id))
|
||||
.first()
|
||||
)
|
||||
better = _fallback_title_from_contract_review_log(review_log)
|
||||
if better:
|
||||
item.title = better
|
||||
title_repaired = True
|
||||
if title_repaired:
|
||||
db.session.commit()
|
||||
|
||||
sessions = [_serialize_session(item) for item in session_rows]
|
||||
session_ids = {item['conversation_id'] for item in sessions}
|
||||
|
||||
# 兼容旧数据:未迁移到 chat_sessions 的历史记录继续从 chat_logs 聚合出来。
|
||||
subquery = db.session.query(
|
||||
ChatLog.conversation_id,
|
||||
func.max(ChatLog.created_at).label('last_active')
|
||||
).filter(
|
||||
ChatLog.user_id == user.id,
|
||||
ChatLog.agent_id == agent.id,
|
||||
ChatLog.session_id.is_(None),
|
||||
ChatLog.conversation_id.isnot(None),
|
||||
ChatLog.conversation_id != '',
|
||||
).group_by(ChatLog.conversation_id).subquery()
|
||||
|
||||
legacy_rows = db.session.query(
|
||||
subquery.c.conversation_id,
|
||||
subquery.c.last_active,
|
||||
).order_by(desc(subquery.c.last_active)).limit(20).all()
|
||||
|
||||
for row in legacy_rows:
|
||||
if not row.conversation_id or row.conversation_id in session_ids:
|
||||
continue
|
||||
latest_query_row = db.session.query(ChatLog.query).filter(ChatLog.user_id == user.id, ChatLog.agent_id == agent.id, ChatLog.conversation_id == row.conversation_id, ChatLog.query.isnot(None), ChatLog.query != '').order_by(desc(ChatLog.created_at), desc(ChatLog.id)).first()
|
||||
title = (latest_query_row[0] if latest_query_row and latest_query_row[0] else '').strip()
|
||||
sessions.append({
|
||||
'id': 0,
|
||||
'conversation_id': row.conversation_id,
|
||||
'title': title[:30] + ('...' if len(title) > 30 else '') if title else '',
|
||||
'created_at': row.last_active.isoformat(),
|
||||
'status': 'done',
|
||||
})
|
||||
|
||||
sessions.sort(key=lambda item: item.get('created_at') or '', reverse=True)
|
||||
return jsonify(sessions[:20])
|
||||
|
||||
@chat_bp.route('/sessions', methods=['DELETE'])
|
||||
@require_agent_permission
|
||||
def delete_all_chat_sessions():
|
||||
"""
|
||||
删除当前用户与当前 Agent 的所有历史会话
|
||||
"""
|
||||
user = getattr(g, 'current_user', None)
|
||||
agent = getattr(g, 'current_agent', None)
|
||||
if user is None or agent is None:
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing context', http_status=500)
|
||||
chat_logs = db.session.query(ChatLog).filter_by(user_id=user.id, agent_id=agent.id).all()
|
||||
chat_log_ids = [log.id for log in chat_logs]
|
||||
if chat_log_ids:
|
||||
from app.models import GeneralFeedback
|
||||
db.session.query(Feedback).filter(Feedback.chat_log_id.in_(chat_log_ids)).delete(synchronize_session=False)
|
||||
db.session.query(GeneralFeedback).filter(GeneralFeedback.chat_log_id.in_(chat_log_ids)).delete(synchronize_session=False)
|
||||
db.session.query(ChatLog).filter(ChatLog.id.in_(chat_log_ids)).delete(synchronize_session=False)
|
||||
db.session.query(ChatSession).filter_by(user_id=user.id, agent_id=agent.id).delete(synchronize_session=False)
|
||||
db.session.commit()
|
||||
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
@chat_bp.route('/sessions/<conversation_id>', methods=['DELETE'])
|
||||
@require_agent_permission
|
||||
def delete_chat_session(conversation_id):
|
||||
"""
|
||||
删除指定的会话记录
|
||||
"""
|
||||
user = getattr(g, 'current_user', None)
|
||||
agent = getattr(g, 'current_agent', None)
|
||||
if user is None or agent is None:
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing context', http_status=500)
|
||||
|
||||
session = _get_chat_session(user.id, agent.id, conversation_id)
|
||||
if session:
|
||||
chat_logs = db.session.query(ChatLog).filter(
|
||||
ChatLog.user_id == user.id,
|
||||
ChatLog.agent_id == agent.id,
|
||||
or_(
|
||||
ChatLog.session_id == session.session_id,
|
||||
ChatLog.conversation_id == session.external_conversation_id,
|
||||
)
|
||||
).all()
|
||||
else:
|
||||
chat_logs = db.session.query(ChatLog).filter_by(
|
||||
user_id=user.id,
|
||||
agent_id=agent.id,
|
||||
conversation_id=conversation_id
|
||||
).all()
|
||||
|
||||
chat_log_ids = [log.id for log in chat_logs]
|
||||
if chat_log_ids:
|
||||
from app.models import GeneralFeedback
|
||||
db.session.query(Feedback).filter(Feedback.chat_log_id.in_(chat_log_ids)).delete(synchronize_session=False)
|
||||
db.session.query(GeneralFeedback).filter(GeneralFeedback.chat_log_id.in_(chat_log_ids)).delete(synchronize_session=False)
|
||||
db.session.query(ChatLog).filter(ChatLog.id.in_(chat_log_ids)).delete(synchronize_session=False)
|
||||
if session:
|
||||
db.session.delete(session)
|
||||
db.session.commit()
|
||||
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
@chat_bp.route('/messages', methods=['GET'])
|
||||
@require_agent_permission
|
||||
def get_chat_messages():
|
||||
"""
|
||||
获取指定会话的消息记录
|
||||
"""
|
||||
conversation_id = request.args.get('conversation_id')
|
||||
if not conversation_id:
|
||||
return jsonify([])
|
||||
|
||||
session = _get_chat_session(getattr(g.current_user, 'id', 0), getattr(g.current_agent, 'id', 0), conversation_id)
|
||||
if session:
|
||||
logs = _chat_logs_for_session(g.current_user.id, g.current_agent.id, session)
|
||||
else:
|
||||
logs = db.session.query(ChatLog).filter(
|
||||
ChatLog.user_id == g.current_user.id,
|
||||
ChatLog.agent_id == g.current_agent.id,
|
||||
ChatLog.conversation_id == conversation_id,
|
||||
).order_by(ChatLog.created_at.asc()).all()
|
||||
|
||||
messages = []
|
||||
agent_code = str(getattr(g.current_agent, 'agent_code', '') or '').strip() or 'generic'
|
||||
for log in logs:
|
||||
if log.query:
|
||||
messages.append({'role': 'user', 'content': _user_facing_chat_query(log.query, agent_code=agent_code)})
|
||||
if (
|
||||
not log.answer
|
||||
and not log.message_type
|
||||
and not log.payload
|
||||
):
|
||||
continue
|
||||
if (
|
||||
log.query
|
||||
and log.answer == log.query
|
||||
and (not log.message_type or log.message_type == 'text')
|
||||
and not log.payload
|
||||
):
|
||||
continue
|
||||
assistant_msg = {
|
||||
'role': 'assistant',
|
||||
'content': DifyService._dedupe_exact_doubled_text(log.answer or ''),
|
||||
'chat_log_id': log.id,
|
||||
'retriever_resources': log.retriever_resources or [],
|
||||
'attribution_parts': log.attribution_parts or [],
|
||||
}
|
||||
if log.run_id:
|
||||
assistant_msg['run_id'] = log.run_id
|
||||
if log.message_type:
|
||||
assistant_msg['type'] = log.message_type
|
||||
if log.payload:
|
||||
assistant_msg['payload'] = log.payload
|
||||
messages.append(assistant_msg)
|
||||
return jsonify(messages)
|
||||
|
||||
@chat_bp.route('/messages/local', methods=['POST'])
|
||||
@require_agent_permission
|
||||
def save_local_message():
|
||||
"""
|
||||
保存前端本地生成的聊天记录(如表单、确认弹窗、合同审查结果卡等)。
|
||||
|
||||
核心逻辑:user 角色用 content/query 落库;纯文本 assistant 忽略 query 防重复气泡;
|
||||
结构化 typed 消息(leave-form / procurement-contract-review 等)保留 query,供历史回放与会话标题。
|
||||
"""
|
||||
user = getattr(g, 'current_user', None)
|
||||
agent = getattr(g, 'current_agent', None)
|
||||
if user is None or agent is None:
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing context', http_status=500)
|
||||
data = request.get_json() or {}
|
||||
conversation_id = (data.get('conversation_id') or '').strip()
|
||||
role = (data.get('role') or 'assistant').strip()
|
||||
message_type = data.get('type')
|
||||
content = data.get('content', '')
|
||||
payload = data.get('payload')
|
||||
user_query = data.get('query', '')
|
||||
if role == 'user':
|
||||
user_query = user_query or content
|
||||
content = ''
|
||||
else:
|
||||
# [STEP] 纯文本助手消息忽略误传的 query,避免与已落库用户气泡重复(见回归测试)
|
||||
# 结构化结果卡必须保留 query,否则刷新后用户提问与历史标题都会丢失
|
||||
if not message_type or message_type == 'text':
|
||||
user_query = ''
|
||||
|
||||
if not message_type:
|
||||
raise ValidationError('type is required')
|
||||
|
||||
title = user_query or content
|
||||
external_conversation_id = conversation_id if conversation_id and _get_chat_session(user.id, agent.id, conversation_id) is None else None
|
||||
session = _ensure_chat_session(
|
||||
user.id,
|
||||
agent.id,
|
||||
conversation_id or None,
|
||||
title=title,
|
||||
status='done',
|
||||
external_conversation_id=external_conversation_id,
|
||||
)
|
||||
conversation_id = session.session_id
|
||||
# 纠偏:已有会话若误用审查 headline 作标题,有用户提问时改回提问摘要
|
||||
if user_query and _looks_like_review_auto_title(session.title or ''):
|
||||
session.title = _session_title_from_text(user_query)
|
||||
|
||||
# 如果 payload 里面包含 formId,且该 formId 已经被保存过,可以直接更新该记录
|
||||
# 这样能保证前端表单状态(例如已确认)被持久化
|
||||
local_id = payload.get('formId') if payload and isinstance(payload, dict) else None
|
||||
chat_log = None
|
||||
if local_id:
|
||||
# 在 payload 中查找是否已存在相同 formId 的同类型消息
|
||||
# SQLite / Postgres 对 JSON 过滤有差异,为了简单,我们可以取出当前会话的所有该类型消息并在内存中匹配
|
||||
logs = db.session.query(ChatLog).filter_by(
|
||||
user_id=user.id,
|
||||
agent_id=agent.id,
|
||||
session_id=conversation_id,
|
||||
message_type=message_type
|
||||
).order_by(ChatLog.created_at.desc()).limit(20).all()
|
||||
|
||||
for log in logs:
|
||||
if log.payload and isinstance(log.payload, dict) and (log.payload.get('formId') == local_id):
|
||||
chat_log = log
|
||||
break
|
||||
if chat_log:
|
||||
chat_log.content = content
|
||||
chat_log.answer = content
|
||||
chat_log.payload = payload
|
||||
if user_query and (not chat_log.query):
|
||||
chat_log.query = user_query
|
||||
else:
|
||||
chat_log = ChatLog(
|
||||
user_id=user.id,
|
||||
agent_id=agent.id,
|
||||
conversation_id=session.external_conversation_id or conversation_id,
|
||||
session_id=conversation_id,
|
||||
query=user_query,
|
||||
answer=content,
|
||||
message_type=message_type,
|
||||
payload=payload
|
||||
)
|
||||
db.session.add(chat_log)
|
||||
session.status = 'done'
|
||||
session.last_active_at = datetime.utcnow()
|
||||
session.updated_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok', 'chat_log_id': chat_log.id, 'conversation_id': conversation_id})
|
||||
@@ -0,0 +1,47 @@
|
||||
"""
|
||||
api/chat/shared.py
|
||||
|
||||
用途:汇总聊天 API 子模块共同使用的框架对象、模型、服务和常量。
|
||||
依赖:Flask、SQLAlchemy、DifyService、IntegrationApiService、聊天数据模型。
|
||||
逻辑:各 chat 路由模块从本文件复用基础依赖;Blueprint 仅由 api/chat/__init__.py 创建,避免重复注册。
|
||||
"""
|
||||
import io
|
||||
import ipaddress
|
||||
import mimetypes
|
||||
import ntpath
|
||||
import posixpath
|
||||
import tempfile
|
||||
import os
|
||||
import subprocess
|
||||
import uuid
|
||||
import json
|
||||
import time
|
||||
from datetime import datetime
|
||||
from urllib.parse import urlparse
|
||||
import requests
|
||||
from flask import Blueprint, request, Response, stream_with_context, jsonify, g, current_app, has_request_context
|
||||
from sqlalchemy import func, desc, or_, exists, and_
|
||||
from openpyxl import load_workbook
|
||||
from app.services.agent_runtime_context.dify_inputs import build_chat_dify_inputs
|
||||
from app.services.dify import DifyService
|
||||
from app.core.config.settings import Config
|
||||
from app.services.integration_api import IntegrationApiService
|
||||
from app.core.decorators import require_agent_permission
|
||||
from app.models import Agent, ChatLog, ChatSession, Feedback
|
||||
from app import db
|
||||
from app.core.errors import (
|
||||
AppError,
|
||||
ConflictError,
|
||||
ForbiddenError,
|
||||
NotFoundError,
|
||||
ServiceUnavailableError,
|
||||
UnauthorizedError,
|
||||
ValidationError,
|
||||
raise_for_status,
|
||||
)
|
||||
SHIPPING_NOTICE_AGENT_CODE = 'shipping_notice'
|
||||
|
||||
|
||||
PLM_PREVIEW_SHARE_ROOT = (os.getenv('PLM_PREVIEW_SHARE_ROOT') or '\\\\192.168.0.11\\dss\\dssroot\\').strip()
|
||||
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
"""
|
||||
api/chat/uploads.py
|
||||
|
||||
用途:处理聊天附件上传并转发至当前 Agent 对应的 Dify 应用。
|
||||
依赖:chat.shared、DifyService、Config、requests、chat_bp。
|
||||
逻辑:校验文件类型、上传方式和大小限制后调用 Dify 文件接口,返回标准化文件元数据。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from .shared import * # noqa: F403
|
||||
from . import chat_bp
|
||||
|
||||
|
||||
@chat_bp.route('/files/upload', methods=['POST'])
|
||||
@require_agent_permission
|
||||
def upload_chat_file():
|
||||
user = getattr(g, 'current_user', None)
|
||||
agent = getattr(g, 'current_agent', None)
|
||||
if user is None or agent is None:
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing user or agent context', http_status=500)
|
||||
if str(getattr(agent, 'type', '') or '').strip().lower() != 'api':
|
||||
raise ValidationError('This agent does not support file upload')
|
||||
if not getattr(agent, 'dify_api_key', None):
|
||||
raise ValidationError('This agent does not support file upload')
|
||||
|
||||
upload = request.files.get('file')
|
||||
if not upload:
|
||||
raise ValidationError('file is required')
|
||||
|
||||
from app.services.dify import DifyService
|
||||
from app.core.config.settings import Config
|
||||
|
||||
params = DifyService.get_app_parameters(agent, force_refresh=True)
|
||||
file_upload_cfg = (params or {}).get('file_upload') if isinstance(params, dict) else {}
|
||||
system_params = (params or {}).get('system_parameters') if isinstance(params, dict) else {}
|
||||
|
||||
filename = str(getattr(upload, 'filename', '') or '').strip()
|
||||
mimetype = str(getattr(upload, 'mimetype', '') or '').lower().strip()
|
||||
detected_type, ext = DifyService.detect_file_type(filename, mimetype)
|
||||
file_type = None
|
||||
normalized_allowed_types = None
|
||||
normalized_allowed_methods = None
|
||||
normalized_allowed_exts = None
|
||||
is_new_schema = False
|
||||
if isinstance(file_upload_cfg, dict) and file_upload_cfg.get('enabled') is True and isinstance(file_upload_cfg.get('allowed_file_types'), list):
|
||||
is_new_schema = True
|
||||
normalized_allowed_types = set(
|
||||
(
|
||||
str(v or '').strip().lower()
|
||||
for v in (file_upload_cfg.get('allowed_file_types') or [])
|
||||
if str(v or '').strip()
|
||||
)
|
||||
)
|
||||
normalized_allowed_methods = set(
|
||||
(
|
||||
str(v or '').strip().lower()
|
||||
for v in (file_upload_cfg.get('allowed_file_upload_methods') or [])
|
||||
if str(v or '').strip()
|
||||
)
|
||||
)
|
||||
exts = []
|
||||
for v in (file_upload_cfg.get('allowed_file_extensions') or []):
|
||||
s = str(v or '').strip()
|
||||
if not s:
|
||||
continue
|
||||
if s.startswith('.'):
|
||||
s = s[1:]
|
||||
s = s.lower().strip()
|
||||
if s:
|
||||
exts.append(s)
|
||||
normalized_allowed_exts = set(exts) if exts else None
|
||||
|
||||
if detected_type:
|
||||
file_type = detected_type
|
||||
else:
|
||||
if is_new_schema and normalized_allowed_types and 'custom' in normalized_allowed_types and (not DifyService.is_known_file_extension(ext)):
|
||||
file_type = 'custom'
|
||||
else:
|
||||
custom_cfg = file_upload_cfg.get('custom') if isinstance(file_upload_cfg, dict) else None
|
||||
if isinstance(custom_cfg, dict) and custom_cfg.get('enabled') and (not DifyService.is_known_file_extension(ext)):
|
||||
file_type = 'custom'
|
||||
else:
|
||||
raise ValidationError(f'Unsupported file type (ext={ext or ""}, mime={mimetype or ""})')
|
||||
|
||||
def _effective_type_methods(target_type: str) -> set[str]:
|
||||
if not isinstance(file_upload_cfg, dict):
|
||||
return set(normalized_allowed_methods or set())
|
||||
cfg = file_upload_cfg.get(target_type)
|
||||
transfer_methods = []
|
||||
if isinstance(cfg, dict):
|
||||
transfer_methods = cfg.get('transfer_methods') or cfg.get('transfer_methods'.replace('_', '-')) or []
|
||||
if isinstance(transfer_methods, str):
|
||||
transfer_methods = [transfer_methods]
|
||||
if isinstance(transfer_methods, list) and len(transfer_methods) > 0:
|
||||
return set(str(m or '').strip().lower() for m in transfer_methods if str(m or '').strip())
|
||||
return set(normalized_allowed_methods or set())
|
||||
|
||||
def _is_type_enabled_in_new_schema(target_type: str) -> bool:
|
||||
if not (is_new_schema and normalized_allowed_types):
|
||||
return False
|
||||
if not isinstance(file_upload_cfg, dict):
|
||||
return target_type in normalized_allowed_types
|
||||
cfg = file_upload_cfg.get(target_type)
|
||||
if isinstance(cfg, dict) and isinstance(cfg.get('enabled'), bool):
|
||||
if cfg.get('enabled') is False:
|
||||
return False
|
||||
if cfg.get('enabled') is True:
|
||||
return True
|
||||
return target_type in normalized_allowed_types
|
||||
|
||||
if is_new_schema and normalized_allowed_types:
|
||||
if not _is_type_enabled_in_new_schema(file_type):
|
||||
raise ValidationError(f'File type not enabled: {file_type}')
|
||||
type_methods = _effective_type_methods(file_type)
|
||||
if 'local_file' not in type_methods:
|
||||
raise ValidationError('local_file upload is not enabled')
|
||||
if normalized_allowed_exts:
|
||||
allowed_for_type = set()
|
||||
for e in normalized_allowed_exts:
|
||||
t, _ = DifyService.detect_file_type(f'file.{e}', None)
|
||||
if t is None:
|
||||
if _is_type_enabled_in_new_schema('custom') and (not DifyService.is_known_file_extension(e)):
|
||||
allowed_for_type.add(e)
|
||||
continue
|
||||
if t == file_type:
|
||||
allowed_for_type.add(e)
|
||||
if allowed_for_type and (not ext or ext not in allowed_for_type):
|
||||
raise ValidationError(f'Unsupported file extension: .{ext or ""}')
|
||||
else:
|
||||
# legacy schema checks
|
||||
type_cfg = file_upload_cfg.get(file_type) if isinstance(file_upload_cfg, dict) else None
|
||||
if not isinstance(type_cfg, dict) or not type_cfg.get('enabled'):
|
||||
raise ValidationError(f'File type not enabled: {file_type}')
|
||||
transfer_methods = type_cfg.get('transfer_methods') or type_cfg.get('transfer_methods'.replace('_', '-')) or []
|
||||
if isinstance(transfer_methods, str):
|
||||
transfer_methods = [transfer_methods]
|
||||
if 'local_file' not in set((str(m).strip() for m in transfer_methods if m is not None)):
|
||||
raise ValidationError('local_file upload is not enabled')
|
||||
|
||||
def _mb_limit_for_type() -> float | None:
|
||||
merged = {}
|
||||
if isinstance(system_params, dict):
|
||||
merged.update(system_params)
|
||||
if isinstance(file_upload_cfg, dict) and isinstance(file_upload_cfg.get('fileUploadConfig'), dict):
|
||||
merged.update(file_upload_cfg.get('fileUploadConfig') or {})
|
||||
if file_type == 'image':
|
||||
return merged.get('image_file_size_limit') or merged.get('file_size_limit')
|
||||
if file_type == 'audio':
|
||||
return merged.get('audio_file_size_limit') or merged.get('file_size_limit')
|
||||
if file_type == 'video':
|
||||
return merged.get('video_file_size_limit') or merged.get('file_size_limit')
|
||||
return merged.get('file_size_limit')
|
||||
|
||||
size_limit_mb = _mb_limit_for_type()
|
||||
if size_limit_mb is not None:
|
||||
try:
|
||||
import os
|
||||
stream = getattr(upload, 'stream', None)
|
||||
if stream and hasattr(stream, 'tell') and hasattr(stream, 'seek'):
|
||||
cur = stream.tell()
|
||||
stream.seek(0, os.SEEK_END)
|
||||
size_bytes = stream.tell()
|
||||
stream.seek(cur)
|
||||
limit_bytes = int(float(size_limit_mb) * 1024 * 1024)
|
||||
if size_bytes > limit_bytes:
|
||||
raise ValidationError(f'File too large (limit {size_limit_mb}MB)')
|
||||
except ValidationError:
|
||||
raise
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
base_url = agent.api_base_url if getattr(agent, 'api_base_url', None) else Config.DIFY_API_BASE
|
||||
dify_url = DifyService._build_files_upload_url(base_url)
|
||||
headers = {'Authorization': f'Bearer {agent.dify_api_key}'}
|
||||
|
||||
try:
|
||||
try:
|
||||
upload.stream.seek(0)
|
||||
except Exception:
|
||||
pass
|
||||
resp = requests.post(
|
||||
dify_url,
|
||||
headers=headers,
|
||||
files={'file': (filename or 'upload', upload.stream, mimetype or 'application/octet-stream')},
|
||||
data={'user': str(getattr(user, 'id', 'system'))},
|
||||
timeout=(5, 300),
|
||||
)
|
||||
except requests.RequestException as exc:
|
||||
raise ServiceUnavailableError(f'Upload failed: {exc}')
|
||||
|
||||
if not resp.ok:
|
||||
body = (resp.text or '')[:1500]
|
||||
header_snapshot = {}
|
||||
try:
|
||||
for k in ('x-request-id', 'x-requestid', 'request-id', 'trace-id', 'cf-ray', 'server', 'date'):
|
||||
v = resp.headers.get(k) or resp.headers.get(k.title())
|
||||
if v:
|
||||
header_snapshot[k] = v
|
||||
except Exception:
|
||||
header_snapshot = {}
|
||||
current_app.logger.warning(
|
||||
'[chat-upload] dify upload failed status=%s url=%s headers=%s body=%s',
|
||||
resp.status_code,
|
||||
dify_url,
|
||||
header_snapshot,
|
||||
body,
|
||||
)
|
||||
raise AppError(
|
||||
code='DIFY.UPLOAD_FAILED',
|
||||
message='Upload failed',
|
||||
http_status=502,
|
||||
details={'status': resp.status_code, 'body': body, 'url': dify_url, 'headers': header_snapshot},
|
||||
)
|
||||
|
||||
data = resp.json() if resp.content else {}
|
||||
return jsonify({
|
||||
'id': data.get('id'),
|
||||
'name': data.get('name') or filename,
|
||||
'size': data.get('size'),
|
||||
'extension': data.get('extension') or ext,
|
||||
'mime_type': data.get('mime_type') or mimetype,
|
||||
'type': file_type,
|
||||
})
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/app/api/file_check_tools.py
|
||||
|
||||
用途:文件检核 Chatflow 显式 HTTP Tool API。
|
||||
用途:文件检核 / 立账凭证检核 Chatflow 显式 HTTP Tool API(启动检核复用本蓝图)。
|
||||
依赖:workspace_file_check、file_check_tools、schedule.scheduler_service。
|
||||
逻辑:Dify Chatflow 调用本蓝图发起检核、查询批次、下载 Excel。
|
||||
逻辑:发起检核时可透传顶层 mode/invoice_no(或嵌套 run_options)写入 ScheduleRun.api_request_json。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -74,7 +74,7 @@ def _require_tool_auth() -> None:
|
||||
"""
|
||||
校验 Tool API 访问权限。
|
||||
|
||||
核心逻辑:Excel 下载仅校验 query token(浏览器场景);其余端点校验 Dify/RPA 的 Tool API Key。
|
||||
核心逻辑:Excel 下载仅校验 query token(浏览器场景);其余端点走共用 integration_tool_auth。
|
||||
"""
|
||||
# [STEP 1] 浏览器 Excel 下载:JWT token 独立于 Tool API Key
|
||||
if request.path.endswith("/excel"):
|
||||
@@ -84,26 +84,10 @@ def _require_tool_auth() -> None:
|
||||
return
|
||||
raise UnauthorizedError("invalid_auth")
|
||||
|
||||
# [STEP 2] Dify / RPA 服务端调用
|
||||
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",
|
||||
)
|
||||
# [STEP 2] Dify / RPA 服务端调用(与立账凭证检核等 Tool 共用密钥)
|
||||
from app.services.integration_tool_auth import require_integration_tool_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")
|
||||
require_integration_tool_auth()
|
||||
|
||||
|
||||
def _tool_error_code(exc: AppError) -> str:
|
||||
@@ -382,7 +366,17 @@ def _precheck_no_data(task: ScheduleTask) -> dict | None:
|
||||
|
||||
@file_check_bp.route("/tools/tasks/run", methods=["POST"])
|
||||
def run_file_check():
|
||||
"""立即执行检核;任务 enabled 仅控制 cron,不限制人工或 Chatflow 触发。"""
|
||||
"""
|
||||
立即执行检核;任务 enabled 仅控制 cron,不限制人工或 Chatflow 触发。
|
||||
|
||||
核心逻辑:解析 task → 防并发锁 → 可选透传 mode/invoice_no(或 run_options)到
|
||||
ScheduleRun.api_request_json → 异步启动平台 Job。Dify 推荐填顶层 mode/invoice_no。
|
||||
|
||||
Body 关键字段(立账凭证检核):
|
||||
mode: incremental | force_all | single
|
||||
invoice_no: mode=single 时发票号
|
||||
run_options: 可选嵌套对象,与顶层字段合并(顶层优先)
|
||||
"""
|
||||
perf_started = time.perf_counter()
|
||||
data = _prepare_bind_payload(request.get_json(silent=True) or {})
|
||||
task = _resolve_check_task(data)
|
||||
@@ -428,16 +422,33 @@ def run_file_check():
|
||||
)
|
||||
return jsonify(no_data_response)
|
||||
|
||||
# [STEP] 解析运行选项:优先顶层 mode/invoice_no(Dify Tool 表单对嵌套 object 常不展示),
|
||||
# 再与 run_options 对象合并;立账凭证检核读取,普通文件检核忽略。
|
||||
raw_options = data.get("run_options") if isinstance(data.get("run_options"), dict) else {}
|
||||
run_options = {}
|
||||
mode = str(data.get("mode") or raw_options.get("mode") or "").strip().lower()
|
||||
if mode in {"incremental", "force_all", "single"}:
|
||||
run_options["mode"] = mode
|
||||
invoice_no = data.get("invoice_no")
|
||||
if invoice_no is None or not str(invoice_no).strip():
|
||||
invoice_no = raw_options.get("invoice_no")
|
||||
if invoice_no is not None and str(invoice_no).strip():
|
||||
run_options["invoice_no"] = str(invoice_no).strip()
|
||||
|
||||
api_request_json = {
|
||||
"trigger_source": data.get("trigger_source") or "dify_chatflow",
|
||||
"conversation_id": data.get("conversation_id"),
|
||||
}
|
||||
if run_options:
|
||||
api_request_json["run_options"] = run_options
|
||||
|
||||
run = ScheduleRun(
|
||||
run_no=_generate_run_no(),
|
||||
schedule_task_id=task.id,
|
||||
trigger_type="dify_chatflow",
|
||||
started_at=datetime.utcnow(),
|
||||
status="running",
|
||||
api_request_json={
|
||||
"trigger_source": data.get("trigger_source") or "dify_chatflow",
|
||||
"conversation_id": data.get("conversation_id"),
|
||||
},
|
||||
api_request_json=api_request_json,
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
|
||||
+110
-11
@@ -1,6 +1,9 @@
|
||||
"""
|
||||
backend/app/api/integration.py
|
||||
文件用途:知识库外部集成查询接口
|
||||
|
||||
用途:知识库外部集成查询/下载接口(供 Dify Tool 与聊天源文件预览解析)。
|
||||
依赖:Flask Blueprint、SQLAlchemy、IntegrationApiService、Kb* 模型。
|
||||
逻辑:聊天预览经 /api/chat/preview-* 代理到本模块 download;dify-file 供 IntegrationApiService 反查本地映射。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
from pathlib import Path
|
||||
@@ -144,6 +147,12 @@ def _kb_storage_root() -> Path:
|
||||
return root
|
||||
|
||||
def _resolve_storage_path(path_value: str | None) -> Path | None:
|
||||
"""
|
||||
解析知识库存储相对/绝对路径,并校验落在 KB_STORAGE_ROOT 内。
|
||||
核心逻辑:相对路径拼到存储根;绝对路径直接 resolve 后做越界校验。
|
||||
@param path_value: 数据库中的路径字符串
|
||||
@returns 合法绝对 Path,越界或空则 None
|
||||
"""
|
||||
if not path_value:
|
||||
return None
|
||||
raw_path = Path(str(path_value))
|
||||
@@ -155,6 +164,45 @@ def _resolve_storage_path(path_value: str | None) -> Path | None:
|
||||
return None
|
||||
return candidate
|
||||
|
||||
|
||||
def _existing_storage_path(path_value: str | None) -> Path | None:
|
||||
"""
|
||||
解析存储路径且要求文件真实存在。
|
||||
核心逻辑:先 _resolve_storage_path,再校验 is_file。
|
||||
@returns 存在的 Path,否则 None
|
||||
"""
|
||||
path = _resolve_storage_path(path_value)
|
||||
if path is None or not path.exists() or not path.is_file():
|
||||
return None
|
||||
return path
|
||||
|
||||
|
||||
def _markdown_storage_path(version: KbDocumentVersion) -> Path | None:
|
||||
"""
|
||||
取版本可用的清洗 Markdown 文件路径(优先 cleaned_file,其次 preview)。
|
||||
核心逻辑:路径存在且内容像文本时才返回,避免误把 OLE 二进制当 md。
|
||||
"""
|
||||
for path_value in (version.cleaned_file_path, version.cleaned_preview_path):
|
||||
path = _existing_storage_path(path_value)
|
||||
if path is None:
|
||||
continue
|
||||
try:
|
||||
head = path.read_bytes()[:4096]
|
||||
except OSError:
|
||||
continue
|
||||
if head.startswith((b'%PDF-', b'PK\x03\x04', b'\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1')):
|
||||
current_app.logger.warning(
|
||||
'[integration] skip binary cleaned path version_id=%s path=%s',
|
||||
version.id,
|
||||
path,
|
||||
)
|
||||
continue
|
||||
if b'\x00' in head:
|
||||
continue
|
||||
return path
|
||||
return None
|
||||
|
||||
|
||||
def _current_version(document: KbDocument) -> KbDocumentVersion | None:
|
||||
versions = list(getattr(document, 'versions', []) or [])
|
||||
if not versions:
|
||||
@@ -165,13 +213,40 @@ def _document_query():
|
||||
return db.session.query(KbDocument).options(joinedload(KbDocument.group), joinedload(KbDocument.versions).joinedload(KbDocumentVersion.sync_records)).filter(KbDocument.is_deleted.is_(False))
|
||||
|
||||
def _serialize_integration_document(document: KbDocument, *, version: KbDocumentVersion | None=None, sync_record: KbDifySyncRecord | None=None):
|
||||
"""
|
||||
序列化集成侧文档元数据与可下载 URL。
|
||||
核心逻辑:源文件在磁盘存在时返回 kind=source;否则回退到清洗 Markdown(kind=md),
|
||||
避免聊天预览拿到“库有映射、盘无文件”的死链。
|
||||
"""
|
||||
version = version or _current_version(document)
|
||||
if not version:
|
||||
abort(404, description='No current version found.')
|
||||
sync_record = sync_record or (next((item for item in getattr(version, 'sync_records', []) if item.status == 'synced'), None) or (version.sync_records[0] if getattr(version, 'sync_records', None) else None))
|
||||
source_download_url = _build_download_url(document.id, kind='source', version_id=version.id)
|
||||
markdown_download_url = _build_download_url(document.id, kind='md', version_id=version.id) if version.cleaned_file_path or version.cleaned_preview_path else None
|
||||
return {'document_id': document.id, 'knowledge_base': {'id': document.group.id if document.group else None, 'name': document.group.name if document.group else None, 'department_id': document.group.department_id if document.group else None, 'dify_dataset_id': document.group.dify_dataset_id if document.group else None}, 'title': document.title, 'source_filename': version.source_file_name, 'source_ext': version.source_file_ext, 'file_name': version.source_file_name, 'version_id': version.id, 'version_no': version.version_no, 'convert_status': version.status, 'sync_status': sync_record.status if sync_record else None, 'uploaded_at': version.created_at.isoformat() if version.created_at else None, 'converted_at': version.converted_at.isoformat() if version.converted_at else None, 'download_url_expires_at': None, 'source_download_url': source_download_url, 'markdown_download_url': markdown_download_url, 'markdown_download_url_expires_at': None, 'markdown_public_url': markdown_download_url, 'dify': {'dataset_id': sync_record.dataset_id if sync_record else document.group.dify_dataset_id if document.group else None, 'remote_document_id': sync_record.remote_document_id if sync_record else None, 'status': sync_record.status if sync_record else None, 'last_synced_at': sync_record.synced_at.isoformat() if sync_record and sync_record.synced_at else None}}
|
||||
source_path = _existing_storage_path(version.source_file_path)
|
||||
markdown_path = _markdown_storage_path(version)
|
||||
markdown_download_url = (
|
||||
_build_download_url(document.id, kind='md', version_id=version.id) if markdown_path else None
|
||||
)
|
||||
if source_path is not None:
|
||||
source_download_url = _build_download_url(document.id, kind='source', version_id=version.id)
|
||||
source_filename = version.source_file_name
|
||||
source_ext = version.source_file_ext
|
||||
elif markdown_path is not None:
|
||||
# [STEP] 源文件缺失时用清洗稿顶替预览入口,扩展名改为 md 以便前端走文本预览
|
||||
source_download_url = markdown_download_url
|
||||
stem = Path(str(version.source_file_name or document.title or f'document-{document.id}')).stem
|
||||
source_filename = f'{stem}.md'
|
||||
source_ext = 'md'
|
||||
current_app.logger.info(
|
||||
'[integration] source missing, serialize fallback to markdown document_id=%s version_id=%s',
|
||||
document.id,
|
||||
version.id,
|
||||
)
|
||||
else:
|
||||
source_download_url = _build_download_url(document.id, kind='source', version_id=version.id)
|
||||
source_filename = version.source_file_name
|
||||
source_ext = version.source_file_ext
|
||||
return {'document_id': document.id, 'knowledge_base': {'id': document.group.id if document.group else None, 'name': document.group.name if document.group else None, 'department_id': document.group.department_id if document.group else None, 'dify_dataset_id': document.group.dify_dataset_id if document.group else None}, 'title': document.title, 'source_filename': source_filename, 'source_ext': source_ext, 'file_name': source_filename, 'version_id': version.id, 'version_no': version.version_no, 'convert_status': version.status, 'sync_status': sync_record.status if sync_record else None, 'uploaded_at': version.created_at.isoformat() if version.created_at else None, 'converted_at': version.converted_at.isoformat() if version.converted_at else None, 'download_url_expires_at': None, 'source_download_url': source_download_url, 'markdown_download_url': markdown_download_url, 'markdown_download_url_expires_at': None, 'markdown_public_url': markdown_download_url, 'dify': {'dataset_id': sync_record.dataset_id if sync_record else document.group.dify_dataset_id if document.group else None, 'remote_document_id': sync_record.remote_document_id if sync_record else None, 'status': sync_record.status if sync_record else None, 'last_synced_at': sync_record.synced_at.isoformat() if sync_record and sync_record.synced_at else None}}
|
||||
|
||||
def _serialize_knowledge_base(group: KbGroup, *, document_count: int) -> dict:
|
||||
return {'id': group.id, 'knowledge_base_id': group.id, 'name': group.name, 'description': group.description, 'department_id': group.department_id, 'dify_dataset_id': group.dify_dataset_id, 'document_count': int(document_count or 0), 'created_at': group.created_at.isoformat() if group.created_at else None, 'updated_at': group.updated_at.isoformat() if group.updated_at else None}
|
||||
@@ -196,13 +271,31 @@ def _list_files_payload(*, knowledge_base_id: int | None=None, department_id: in
|
||||
return payload
|
||||
|
||||
def _resolve_download_path(version: KbDocumentVersion, kind: str) -> tuple[Path, str]:
|
||||
"""
|
||||
解析下载目标路径与文件名。
|
||||
核心逻辑:kind=source 优先原始文件;缺失时回退清洗 Markdown,避免预览 404。
|
||||
@param version: 文档版本
|
||||
@param kind: source | md
|
||||
@returns (绝对路径, 下载文件名)
|
||||
@raises NotFoundError: 源文件与清洗稿均不存在
|
||||
"""
|
||||
if kind == 'source':
|
||||
path = _resolve_storage_path(version.source_file_path)
|
||||
if path is None:
|
||||
raise NotFoundError('File not found on disk.')
|
||||
filename = version.source_file_name or f'document-{version.document_id}'
|
||||
return (path, filename)
|
||||
preferred = _resolve_storage_path(version.cleaned_file_path) or _resolve_storage_path(version.cleaned_preview_path)
|
||||
path = _existing_storage_path(version.source_file_path)
|
||||
if path is not None:
|
||||
filename = version.source_file_name or f'document-{version.document_id}'
|
||||
return (path, filename)
|
||||
preferred = _markdown_storage_path(version)
|
||||
if preferred is not None:
|
||||
current_app.logger.warning(
|
||||
'[integration] source file missing, fallback to markdown document_id=%s version_id=%s path=%s',
|
||||
version.document_id,
|
||||
version.id,
|
||||
preferred,
|
||||
)
|
||||
filename = f'document-{version.document_id}-v{version.version_no}.md'
|
||||
return (preferred, filename)
|
||||
raise NotFoundError('File not found on disk.')
|
||||
preferred = _markdown_storage_path(version)
|
||||
if not preferred:
|
||||
abort(409, description='Markdown not ready.')
|
||||
filename = f'document-{version.document_id}-v{version.version_no}.md'
|
||||
@@ -248,6 +341,10 @@ def list_files_for_knowledge_base(knowledge_base_id: int):
|
||||
|
||||
@integration_bp.route('/dify-file', methods=['GET'])
|
||||
def get_file_detail_by_dify():
|
||||
"""
|
||||
按 Dify dataset/document 反查本地知识库文件元数据。
|
||||
核心逻辑:查 KbDifySyncRecord;若源文件与清洗稿均不在磁盘,返回 404 以便上层改走 Dify 下载。
|
||||
"""
|
||||
remote_document_id = str(request.args.get('remote_document_id') or '').strip()
|
||||
dataset_id = str(request.args.get('dataset_id') or '').strip() or None
|
||||
if not remote_document_id:
|
||||
@@ -258,8 +355,10 @@ def get_file_detail_by_dify():
|
||||
record = record_query.first()
|
||||
version = record.document_version if record else None
|
||||
document = version.document if version else None
|
||||
if not document:
|
||||
if not document or not version:
|
||||
raise NotFoundError('No local file mapping found for the given Dify document.')
|
||||
if _existing_storage_path(version.source_file_path) is None and _markdown_storage_path(version) is None:
|
||||
raise NotFoundError('No readable local file for the given Dify document.')
|
||||
return jsonify(_serialize_integration_document(document, version=version, sync_record=record))
|
||||
|
||||
@integration_bp.route('/dify-files/resolve', methods=['POST'])
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
"""
|
||||
backend/app/api/linked_services.py
|
||||
|
||||
用途:已登录用户读取启用中的关联服务,供 Chat/工作台侧栏入口展示。
|
||||
依赖:JWT current-user、linked_service_service。
|
||||
逻辑:仅返回 is_enabled=true;目录失败时由前端静默隐藏入口。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import Blueprint, jsonify, request
|
||||
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import AppError, UnauthorizedError
|
||||
from app.services.admin import linked_service_service
|
||||
|
||||
|
||||
linked_services_bp = Blueprint('linked_services', __name__)
|
||||
|
||||
|
||||
def _require_active_user():
|
||||
"""解析 Bearer 登录用户;未登录或停用账号时拒绝。"""
|
||||
authorization = str(request.headers.get('Authorization') or '').strip()
|
||||
scheme, _, token = authorization.partition(' ')
|
||||
if scheme.lower() != 'bearer' or not token.strip():
|
||||
raise UnauthorizedError('Bearer token is required')
|
||||
user = get_current_user()
|
||||
if user is None:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
if user.status != 'active':
|
||||
raise AppError(code='AUTH.ACCOUNT_DISABLED', message='Account is disabled', http_status=403)
|
||||
return user
|
||||
|
||||
|
||||
@linked_services_bp.route('/linked-services', methods=['GET'])
|
||||
def list_enabled_linked_services():
|
||||
"""返回当前用户可见的已启用关联服务。"""
|
||||
_require_active_user()
|
||||
return jsonify({'items': linked_service_service.list_enabled_linked_services()})
|
||||
@@ -0,0 +1,111 @@
|
||||
"""
|
||||
backend/app/api/procurement_contract_tools.py
|
||||
|
||||
Purpose: Chat/tool-facing procurement contract review APIs.
|
||||
Dependencies: procurement_contract services, JWT current user, unified response envelope.
|
||||
Flow: Authenticated users upload comparison files, start reviews, query own history, and download own reports.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
|
||||
from flask import Blueprint, g, request, send_file
|
||||
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import UnauthorizedError, ValidationError
|
||||
from app.core.response import ok
|
||||
from app.services.procurement_contract import review_service, template_service
|
||||
|
||||
procurement_contract_bp = Blueprint("procurement_contract", __name__)
|
||||
|
||||
|
||||
def _require_user():
|
||||
"""Return current authenticated user."""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
|
||||
def _optional_int(value, field: str) -> int | None:
|
||||
"""Parse optional int payload fields with a ValidationError on bad input."""
|
||||
if value in (None, ""):
|
||||
return None
|
||||
try:
|
||||
return int(value)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError(f"{field} must be integer") from exc
|
||||
|
||||
|
||||
@procurement_contract_bp.route("/templates", methods=["GET"])
|
||||
def list_enabled_templates():
|
||||
"""List enabled templates for chat dropdown."""
|
||||
_require_user()
|
||||
return ok(template_service.list_enabled_for_chat(), request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@procurement_contract_bp.route("/reviews", methods=["POST"])
|
||||
def start_contract_review():
|
||||
"""Start a review; compare mode requires a user-uploaded original contract baseline."""
|
||||
user = _require_user()
|
||||
data = request.get_json() or {}
|
||||
contract_asset_no = (data.get("contract_asset_no") or "").strip()
|
||||
if not contract_asset_no:
|
||||
raise ValidationError("contract_asset_no is required")
|
||||
result = review_service.start_review(
|
||||
user_id=user.id,
|
||||
review_mode=str(data.get("review_mode") or "compare"),
|
||||
contract_asset_no=contract_asset_no,
|
||||
original_contract_asset_no=(data.get("original_contract_asset_no") or None),
|
||||
contract_type=(data.get("contract_type") or None),
|
||||
supplier_name=(data.get("supplier_name") or None),
|
||||
agent_id=_optional_int(data.get("agent_id"), "agent_id"),
|
||||
chat_log_id=_optional_int(data.get("chat_log_id"), "chat_log_id"),
|
||||
)
|
||||
return ok(result, request_id=getattr(g, "request_id", None), status=202)
|
||||
|
||||
|
||||
@procurement_contract_bp.route("/reviews/<review_no>", methods=["GET"])
|
||||
def get_contract_review(review_no: str):
|
||||
"""Get a current user's review by review number."""
|
||||
user = _require_user()
|
||||
return ok(review_service.get_review_for_owner(review_no=review_no, user_id=user.id), request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@procurement_contract_bp.route("/reviews/<review_no>/report", methods=["GET"])
|
||||
def download_my_contract_review_report(review_no: str):
|
||||
"""Download current user's review report as txt or docx."""
|
||||
user = _require_user()
|
||||
review_service.get_review_for_owner(review_no=review_no, user_id=user.id)
|
||||
if (request.args.get("format") or "").lower() == "docx":
|
||||
name, data, mimetype = review_service.read_review_report_docx_bytes(review_no=review_no)
|
||||
else:
|
||||
name, data = review_service.read_review_report_bytes(review_no=review_no)
|
||||
mimetype = "text/plain; charset=utf-8"
|
||||
return send_file(io.BytesIO(data), mimetype=mimetype, as_attachment=True, download_name=name)
|
||||
|
||||
|
||||
@procurement_contract_bp.route("/reviews/<review_no>/annotated-contract", methods=["GET"])
|
||||
def download_my_annotated_contract(review_no: str):
|
||||
"""Download current user's original PDF with anchored risk highlights."""
|
||||
user = _require_user()
|
||||
review_service.get_review_for_owner(review_no=review_no, user_id=user.id)
|
||||
name, data, mimetype = review_service.read_review_annotated_contract_bytes(review_no=review_no)
|
||||
return send_file(io.BytesIO(data), mimetype=mimetype, as_attachment=True, download_name=name)
|
||||
|
||||
|
||||
@procurement_contract_bp.route("/reviews", methods=["GET"])
|
||||
def list_my_contract_reviews():
|
||||
"""List current user's recent procurement contract reviews."""
|
||||
user = _require_user()
|
||||
data = review_service.list_reviews(
|
||||
user_id=user.id,
|
||||
review_mode=request.args.get("review_mode") or None,
|
||||
status=request.args.get("status") or None,
|
||||
keyword=request.args.get("keyword") or None,
|
||||
risk_level=request.args.get("risk_level") or None,
|
||||
limit=_optional_int(request.args.get("limit"), "limit") or 20,
|
||||
offset=_optional_int(request.args.get("offset"), "offset") or 0,
|
||||
)
|
||||
return ok(data, request_id=getattr(g, "request_id", None))
|
||||
@@ -2,16 +2,15 @@
|
||||
backend/app/api/schedule/runs.py
|
||||
|
||||
用途:排程运行触发与运行记录查询 API。
|
||||
依赖:schedule.blueprint、services/schedule/query_service、scheduler_service。
|
||||
逻辑:/schedules/<id>/run、/schedules/<id>/runs、/schedule-runs/* 路由。
|
||||
依赖:schedule.blueprint、services/schedule/query_service、queue_service。
|
||||
逻辑:手动执行仅创建 queued run/job;独立 schedule worker 承担实际运行。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
from datetime import datetime
|
||||
from io import BytesIO
|
||||
|
||||
from flask import current_app, jsonify, request, send_file
|
||||
from flask import jsonify, request, send_file
|
||||
|
||||
from app import db
|
||||
from app.api.schedule.blueprint import schedule_admin_bp
|
||||
@@ -20,66 +19,28 @@ from app.core.decorators import require_admin
|
||||
from app.core.errors import ConflictError, NotFoundError
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.schedule.query_service import get_run, list_runs, serialize_run
|
||||
from app.services.schedule.scheduler_service import _generate_run_no, run_task_now
|
||||
from app.services.schedule.queue_service import enqueue_manual_schedule_run
|
||||
from app.services.schedule.shipping_inventory_rpa_archive import resolve_inventory_raw_zip_download
|
||||
from app.services.schedule.shipping_inventory_rpa_finalize import recover_stale_awaiting_rpa_schedule_runs
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/run', methods=['POST'])
|
||||
@require_admin
|
||||
def run_schedule(task_id: int):
|
||||
"""
|
||||
手动触发排程后台执行。
|
||||
核心逻辑:创建 running ScheduleRun → 守护线程内 run_task_now。
|
||||
手动触发排程并立即返回 queued 运行记录。
|
||||
核心逻辑:queue_service 同事务创建 ScheduleRun + Job;独立 worker 后台执行。
|
||||
"""
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
recover_stale_awaiting_rpa_schedule_runs(task)
|
||||
user = get_current_user()
|
||||
existing = (
|
||||
db.session.query(ScheduleRun)
|
||||
.filter(ScheduleRun.schedule_task_id == task.id, ScheduleRun.status == 'running')
|
||||
.first()
|
||||
)
|
||||
if existing:
|
||||
raise ConflictError('该排程正在执行中,请等待完成后再试', details={'run_id': existing.id})
|
||||
run = ScheduleRun(
|
||||
run_no=_generate_run_no(),
|
||||
schedule_task_id=task.id,
|
||||
trigger_type='manual',
|
||||
run, _job_id, created = enqueue_manual_schedule_run(
|
||||
task.id,
|
||||
triggered_by_user_id=getattr(user, 'id', None),
|
||||
started_at=datetime.utcnow(),
|
||||
status='running',
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
app = current_app._get_current_object()
|
||||
run_id = run.id
|
||||
|
||||
def _background():
|
||||
with app.app_context():
|
||||
t = db.session.get(ScheduleTask, task_id)
|
||||
r = db.session.get(ScheduleRun, run_id)
|
||||
if not t or not r:
|
||||
return
|
||||
try:
|
||||
run_task_now(t, trigger_type='manual', triggered_by_user_id=r.triggered_by_user_id, run=r)
|
||||
except Exception as exc:
|
||||
try:
|
||||
r = db.session.get(ScheduleRun, run_id)
|
||||
if r and r.status == 'running':
|
||||
r.status = 'failed'
|
||||
r.error_message = str(exc)
|
||||
r.finished_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
current_app.logger.error('[schedule-run] run_id=%s failed: %s', run_id, exc, exc_info=True)
|
||||
|
||||
t = threading.Thread(target=_background, daemon=True, name=f'schedule-run-{run_id}')
|
||||
t.start()
|
||||
fresh = db.session.get(ScheduleRun, run_id)
|
||||
if not created:
|
||||
raise ConflictError('该排程正在等待或执行中,请等待完成后再试', details={'run_id': run.id})
|
||||
fresh = db.session.get(ScheduleRun, run.id)
|
||||
return jsonify(serialize_run(fresh))
|
||||
|
||||
|
||||
|
||||
@@ -231,17 +231,17 @@ def delete_schedule(task_id: int):
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.schedule.scheduler_service import request_cancel_run
|
||||
|
||||
running_runs = (
|
||||
active_runs = (
|
||||
db.session.query(ScheduleRun)
|
||||
.filter(ScheduleRun.schedule_task_id == task_id, ScheduleRun.status == 'running')
|
||||
.filter(ScheduleRun.schedule_task_id == task_id, ScheduleRun.status.in_(('queued', 'running')))
|
||||
.all()
|
||||
)
|
||||
for rr in running_runs:
|
||||
for rr in active_runs:
|
||||
request_cancel_run(rr.id)
|
||||
rr.status = 'failed'
|
||||
rr.error_message = '排程已被删除,执行中断'
|
||||
rr.finished_at = datetime.utcnow()
|
||||
if running_runs:
|
||||
if active_runs:
|
||||
db.session.commit()
|
||||
db.session.query(ScheduleRun).filter(ScheduleRun.schedule_task_id == task_id).delete(synchronize_session=False)
|
||||
db.session.delete(task)
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
"""
|
||||
backend/app/api/sso.py
|
||||
|
||||
Purpose: Expose peer-service discovery, short-lived assertion issuance, and public JWKS APIs.
|
||||
Dependencies: JWT current-user resolver, SSO services, and Flask Blueprint.
|
||||
Flow: Authenticated browsers request audience-bound assertions; peer-service backends verify them using JWKS.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import Blueprint, g, jsonify, request
|
||||
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import AppError, UnauthorizedError, ValidationError
|
||||
from app.services.auth.sso import build_jwks, issue_assertion, list_applications
|
||||
|
||||
|
||||
sso_bp = Blueprint('sso', __name__)
|
||||
sso_well_known_bp = Blueprint('sso_well_known', __name__)
|
||||
|
||||
|
||||
def _require_active_user():
|
||||
"""Resolve an active Bearer-authenticated user and retain verified JWT claims."""
|
||||
authorization = str(request.headers.get('Authorization') or '').strip()
|
||||
scheme, _, token = authorization.partition(' ')
|
||||
if scheme.lower() != 'bearer' or not token.strip():
|
||||
raise UnauthorizedError('Bearer token is required')
|
||||
user = get_current_user()
|
||||
if user is None:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
claims = dict(getattr(g, 'jwt_claims', None) or {})
|
||||
if not claims:
|
||||
raise UnauthorizedError('Verified Bearer token is required')
|
||||
if user.status != 'active':
|
||||
raise AppError(code='AUTH.ACCOUNT_DISABLED', message='Account is disabled', http_status=403)
|
||||
return user, claims
|
||||
|
||||
|
||||
@sso_bp.route('/apps', methods=['GET'])
|
||||
def list_sso_apps():
|
||||
"""Return enabled application navigation metadata to authenticated HXOPS users."""
|
||||
_require_active_user()
|
||||
return jsonify({'items': [application.public_payload() for application in list_applications()]})
|
||||
|
||||
|
||||
@sso_bp.route('/apps/<string:app_key>/assertions', methods=['POST'])
|
||||
def create_sso_assertion(app_key: str):
|
||||
"""Issue a short-lived RS256 assertion and return the registered peer callback URL."""
|
||||
user, claims = _require_active_user()
|
||||
data = request.get_json(silent=True) or {}
|
||||
if not isinstance(data, dict):
|
||||
raise ValidationError('JSON body is required')
|
||||
return jsonify(issue_assertion(
|
||||
app_key=app_key,
|
||||
user=user,
|
||||
claims=claims,
|
||||
state=data.get('state'),
|
||||
))
|
||||
|
||||
|
||||
@sso_well_known_bp.route('/.well-known/jwks.json', methods=['GET'])
|
||||
def sso_jwks():
|
||||
"""Publish active and rotation-window product SSO public keys for offline peer verification."""
|
||||
response = jsonify(build_jwks())
|
||||
response.headers['Cache-Control'] = 'public, max-age=300'
|
||||
return response
|
||||
@@ -2,10 +2,11 @@
|
||||
backend/app/api/tools/__init__.py
|
||||
|
||||
用途:Dify HTTP Tool API Blueprint 聚合。
|
||||
逻辑:Wave 1 前 re-export shipping_notice_tools、file_check_tools。
|
||||
逻辑:re-export shipping_notice、file_check、maintenance、voucher_check tools。
|
||||
"""
|
||||
from app.api.tools.shipping_notice import shipping_notice_bp # noqa: F401
|
||||
from app.api.tools.file_check import file_check_bp # noqa: F401
|
||||
from app.api.tools.maintenance import maintenance_tool_bp # noqa: F401
|
||||
from app.api.tools.voucher_check import voucher_check_tools_bp # noqa: F401
|
||||
|
||||
__all__ = ['shipping_notice_bp', 'file_check_bp']
|
||||
__all__ = ['shipping_notice_bp', 'file_check_bp', 'maintenance_tool_bp', 'voucher_check_tools_bp']
|
||||
@@ -0,0 +1,105 @@
|
||||
"""
|
||||
backend/app/api/tools/voucher_check.py
|
||||
|
||||
用途:立账凭证检核 Dify Tool API(缺资料/批次明细/单票最新状态查询 + OpenAPI)。
|
||||
依赖:voucher_check.query_service、openapi_spec、integration_tool_auth;启动检核复用 file-check。
|
||||
逻辑:非 envelope 契约(ok/error_code);与 file-check 共用 Tool API Key;register_blueprints 挂到 /api/accounting-voucher-check。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import Blueprint, jsonify, request
|
||||
|
||||
from app.core.errors import AppError
|
||||
from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE
|
||||
from app.services.integration_tool_auth import require_integration_tool_auth
|
||||
from app.services.voucher_check import query_service
|
||||
from app.services.voucher_check.openapi_spec import build_voucher_check_openapi_spec
|
||||
|
||||
voucher_check_tools_bp = Blueprint("voucher_check_tools", __name__)
|
||||
|
||||
|
||||
@voucher_check_tools_bp.before_request
|
||||
def _verify_tool_access():
|
||||
"""openapi.json 免鉴权,其余端点校验 Tool API Key。"""
|
||||
if request.path.endswith("/openapi.json"):
|
||||
return None
|
||||
require_integration_tool_auth()
|
||||
return None
|
||||
|
||||
|
||||
def _tool_error(exc: AppError):
|
||||
"""将 AppError 映射为 Tool 非 envelope 错误体。"""
|
||||
code = str(exc.code or "").lower().replace(".", "_")
|
||||
message = str(exc.message or "").strip()
|
||||
# 与 file-check 对齐:鉴权类错误码用 message 短码,便于 Dify 分支
|
||||
if message in {"missing_auth", "invalid_auth"}:
|
||||
code = message
|
||||
return jsonify({
|
||||
"ok": False,
|
||||
"error_code": code,
|
||||
"message": message or code,
|
||||
"details": exc.details or {},
|
||||
}), exc.http_status
|
||||
|
||||
|
||||
@voucher_check_tools_bp.route("/tools/openapi.json", methods=["GET"])
|
||||
def voucher_check_openapi_spec():
|
||||
"""
|
||||
返回 Dify 可 URL 导入的 OpenAPI(无需鉴权)。
|
||||
【AI 触发时机】:不由对话调用;运维/Dify 导入工具时访问。
|
||||
"""
|
||||
return jsonify(build_voucher_check_openapi_spec(resolve_HXOPS_TOOLS_API_BASE()))
|
||||
|
||||
|
||||
@voucher_check_tools_bp.route("/tools/tasks/<int:task_id>/missing", methods=["GET"])
|
||||
def tool_list_missing(task_id: int):
|
||||
"""
|
||||
查询当前月或指定月缺资料票。
|
||||
【AI 触发时机】:用户说「查询缺资料发票」时调用。
|
||||
"""
|
||||
try:
|
||||
data = query_service.list_missing_states(
|
||||
task_id=task_id,
|
||||
scope_code=str(request.args.get("scope_code") or "HXJM"),
|
||||
period=request.args.get("period"),
|
||||
limit=request.args.get("limit", default=200, type=int) or 200,
|
||||
)
|
||||
return jsonify({"ok": True, **data})
|
||||
except AppError as exc:
|
||||
return _tool_error(exc)
|
||||
|
||||
|
||||
@voucher_check_tools_bp.route("/tools/runs/<int:run_id>/items", methods=["GET"])
|
||||
def tool_list_run_items(run_id: int):
|
||||
"""
|
||||
查询批次明细,可按 result 过滤。
|
||||
【AI 触发时机】:用户查询某批次结果明细时调用。
|
||||
"""
|
||||
try:
|
||||
data = query_service.list_run_items(
|
||||
run_id=run_id,
|
||||
result=request.args.get("result"),
|
||||
page=request.args.get("page", default=1, type=int) or 1,
|
||||
page_size=request.args.get("page_size", default=50, type=int) or 50,
|
||||
)
|
||||
return jsonify({"ok": True, **data})
|
||||
except AppError as exc:
|
||||
return _tool_error(exc)
|
||||
|
||||
|
||||
@voucher_check_tools_bp.route("/tools/invoices/<path:invoice_no>/latest", methods=["GET"])
|
||||
def tool_invoice_latest(invoice_no: str):
|
||||
"""
|
||||
查询指定发票最新状态。
|
||||
【AI 触发时机】:用户询问某张发票检核结论时调用。
|
||||
"""
|
||||
try:
|
||||
data = query_service.get_invoice_latest(
|
||||
invoice_no=invoice_no,
|
||||
scope_code=str(request.args.get("scope_code") or "HXJM"),
|
||||
period=request.args.get("period"),
|
||||
)
|
||||
return jsonify({"ok": True, **data})
|
||||
except AppError as exc:
|
||||
return _tool_error(exc)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,46 @@
|
||||
"""
|
||||
api/user/__init__.py
|
||||
|
||||
用途:导出用户域与认证域 Blueprint,并维护历史测试替身兼容入口。
|
||||
依赖:handlers、auth 及其共享认证操作。
|
||||
逻辑:register_blueprints 将两个 Blueprint 挂载到 `/api/user`;兼容代理确保迁包前的替身点仍然生效。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from types import ModuleType
|
||||
|
||||
from . import handlers
|
||||
from . import auth
|
||||
from .auth import auth_bp
|
||||
|
||||
|
||||
user_bp = handlers.user_bp
|
||||
|
||||
# The documented Wave 3 compatibility export supports existing tests and callers.
|
||||
_get_current_user = handlers._get_current_user
|
||||
|
||||
|
||||
class _UserApiCompatModule(ModuleType):
|
||||
"""Forward historic private test replacement points to the canonical handlers."""
|
||||
|
||||
def __setattr__(self, name: str, value: object) -> None:
|
||||
super().__setattr__(name, value)
|
||||
if hasattr(handlers, name):
|
||||
setattr(handlers, name, value)
|
||||
if hasattr(auth, name):
|
||||
setattr(auth, name, value)
|
||||
|
||||
|
||||
sys.modules[__name__].__class__ = _UserApiCompatModule
|
||||
|
||||
|
||||
def __getattr__(name: str):
|
||||
"""Expose historic test symbols from their formal auth or user module."""
|
||||
if hasattr(auth, name):
|
||||
return getattr(auth, name)
|
||||
return getattr(handlers, name)
|
||||
|
||||
|
||||
__all__ = ['auth_bp', 'user_bp']
|
||||
@@ -0,0 +1,40 @@
|
||||
"""
|
||||
api/user/auth.py
|
||||
|
||||
用途:用户认证 Blueprint 的兼容门面与路由装配入口。
|
||||
依赖:auth_local、auth_casdoor、auth_wecom、auth_password_reset、auth_support。
|
||||
逻辑:api/user/__init__.py 从此模块导出 auth_bp;各职责路由在独立模块注册,历史测试仍可替换本模块私有符号。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from types import ModuleType
|
||||
|
||||
from flask import Blueprint
|
||||
|
||||
from . import auth_support as _support
|
||||
|
||||
auth_bp = Blueprint('user_auth', __name__)
|
||||
|
||||
|
||||
class _AuthCompatModule(ModuleType):
|
||||
"""将历史 monkeypatch 同步到共享认证操作,保持测试替身入口稳定。"""
|
||||
|
||||
def __setattr__(self, name: str, value: object) -> None:
|
||||
super().__setattr__(name, value)
|
||||
if hasattr(_support, name):
|
||||
setattr(_support, name, value)
|
||||
|
||||
|
||||
sys.modules[__name__].__class__ = _AuthCompatModule
|
||||
|
||||
|
||||
def __getattr__(name: str):
|
||||
"""兼容导出共享认证操作与历史测试替身点。"""
|
||||
return getattr(_support, name)
|
||||
|
||||
|
||||
# Importing modules registers their narrow route groups on the shared Blueprint.
|
||||
from . import auth_casdoor, auth_local, auth_password_reset, auth_wecom # noqa: E402, F401
|
||||
|
||||
__all__ = ['auth_bp']
|
||||
@@ -0,0 +1,125 @@
|
||||
"""
|
||||
api/user/auth_casdoor.py
|
||||
|
||||
用途:Casdoor 密码、授权码与刷新令牌认证路由。
|
||||
依赖:auth.auth_bp、auth_support 兼容操作、services/auth/hxops。
|
||||
逻辑:HTTP 参数与公开 URL 在本模块分组;登录编排仍复用已有 Casdoor 服务适配器。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import current_app, jsonify, request
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, UnauthorizedError, ValidationError
|
||||
from app.services.auth.hxops.casdoor_authorize import CasdoorAuthorizeOptions
|
||||
|
||||
from . import auth as _compat
|
||||
from .auth import auth_bp
|
||||
|
||||
|
||||
@auth_bp.post('/casdoor/password-login', endpoint='casdoor_password_login')
|
||||
def password_login():
|
||||
"""使用 Casdoor password grant 登录,并返回 HXOPS 本地 API 会话。"""
|
||||
if (current_app.config.get('AUTH_LOGIN_MODE') or 'casdoor').lower() != 'casdoor':
|
||||
raise AppError(
|
||||
code='AUTH.CASDOOR_PASSWORD_LOGIN_DISABLED',
|
||||
message='Casdoor password login is disabled by AUTH_LOGIN_MODE',
|
||||
http_status=403,
|
||||
)
|
||||
data = request.get_json() or {}
|
||||
username = _compat._clean_str(data.get('username'))
|
||||
password = data.get('password') or ''
|
||||
if not username or not password:
|
||||
raise ValidationError('Username and password are required')
|
||||
try:
|
||||
result = _compat._hxops_login_service().password(username, password)
|
||||
db.session.commit()
|
||||
return jsonify(result.login_payload())
|
||||
except _compat.WeComLoginError:
|
||||
db.session.rollback()
|
||||
raise
|
||||
except AppError:
|
||||
db.session.rollback()
|
||||
raise
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
_compat._raise_casdoor_auth_error(exc, context='password')
|
||||
|
||||
|
||||
@auth_bp.get('/casdoor/authorize-url', endpoint='casdoor_authorize_url')
|
||||
def authorize_url():
|
||||
"""生成包含状态参数的 Casdoor 授权码登录地址。"""
|
||||
try:
|
||||
options = CasdoorAuthorizeOptions(
|
||||
redirect_uri=request.args.get('redirect_uri'),
|
||||
provider_hint=request.args.get('provider_hint'),
|
||||
default_provider=request.args.get('default_provider'),
|
||||
silent_signin=request.args.get('silent_signin'),
|
||||
)
|
||||
return jsonify(_compat._build_casdoor_authorize_payload(options))
|
||||
except Exception as exc:
|
||||
raise AppError(
|
||||
code='SYSTEM.INTERNAL_ERROR',
|
||||
message=f'Failed to build Casdoor authorize url: {exc}',
|
||||
http_status=500,
|
||||
) from exc
|
||||
|
||||
|
||||
@auth_bp.post('/casdoor/login', endpoint='casdoor_login')
|
||||
def authorization_code_login():
|
||||
"""交换授权码、映射本地用户并签发 HXOPS API 会话。"""
|
||||
data = request.get_json() or {}
|
||||
code = _compat._clean_str(data.get('code'))
|
||||
state = _compat._clean_str(data.get('state'))
|
||||
if not code:
|
||||
raise ValidationError('code is required')
|
||||
current_app.logger.info('[casdoor_login] start code_len=%s state=%s', len(code), state[:24] if state else '')
|
||||
redirect_uri = _compat._consume_casdoor_state(state)
|
||||
if not redirect_uri:
|
||||
current_app.logger.warning('[casdoor_login] invalid_state state=%s', state[:24] if state else '')
|
||||
raise ValidationError('Invalid or expired Casdoor state')
|
||||
try:
|
||||
result = _compat._hxops_login_service().authorization_code(code, redirect_uri)
|
||||
current_app.logger.info('[casdoor_login] user_resolved username=%s id=%s', result.user.username, result.user.id)
|
||||
db.session.commit()
|
||||
return jsonify(result.login_payload())
|
||||
except _compat.WeComLoginError:
|
||||
db.session.rollback()
|
||||
current_app.logger.warning('[casdoor_login] business_reject')
|
||||
raise
|
||||
except AppError:
|
||||
db.session.rollback()
|
||||
raise
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
current_app.logger.exception('[casdoor_login] failed state=%s redirect_uri=%s', state[:24] if state else '', redirect_uri)
|
||||
_compat._raise_casdoor_auth_error(exc, context='code')
|
||||
|
||||
|
||||
@auth_bp.post('/casdoor/refresh', endpoint='casdoor_refresh')
|
||||
def refresh():
|
||||
"""以 Casdoor refresh token 换取新的 HXOPS API 会话。"""
|
||||
data = request.get_json() or {}
|
||||
refresh_token = _compat._clean_str(data.get('refresh_token'))
|
||||
if not refresh_token:
|
||||
raise ValidationError('refresh_token is required')
|
||||
current_app.logger.info('[casdoor_refresh] start refresh=%s', _compat._token_brief(refresh_token))
|
||||
try:
|
||||
result = _compat._hxops_login_service().refresh(refresh_token)
|
||||
current_app.logger.info(
|
||||
'[casdoor_refresh] token_refresh_ok next_refresh=%s user_id=%s',
|
||||
_compat._token_brief(result.refresh_token), result.user.id,
|
||||
)
|
||||
return jsonify(result.refresh_payload())
|
||||
except AppError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
message = str(exc)
|
||||
if 'unsupported_grant_type' in message or 'refresh_token is not supported' in message:
|
||||
raise AppError(
|
||||
code='AUTH.CASDOOR_REFRESH_UNSUPPORTED',
|
||||
message='Casdoor refresh token is not supported by current application config',
|
||||
http_status=400,
|
||||
) from exc
|
||||
current_app.logger.exception('[casdoor_refresh] failed refresh=%s', _compat._token_brief(refresh_token))
|
||||
raise UnauthorizedError(f'Casdoor refresh failed: {exc}') from exc
|
||||
@@ -0,0 +1,128 @@
|
||||
"""
|
||||
api/user/auth_local.py
|
||||
|
||||
用途:注册、传统密码登录与改密 HTTP 路由。
|
||||
依赖:auth.auth_bp、auth_support 的共享认证操作。
|
||||
逻辑:本模块仅装配本地密码职责;业务处理暂由兼容实现承接,后续迁移不改变公开 URL。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import current_app, jsonify, request
|
||||
from sqlalchemy.exc import DatabaseError, OperationalError
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, ServiceUnavailableError, UnauthorizedError, ValidationError
|
||||
|
||||
from . import auth as _compat
|
||||
from .auth import auth_bp
|
||||
|
||||
|
||||
@auth_bp.post('/register', endpoint='register')
|
||||
def register():
|
||||
"""校验必填和唯一字段后创建本地用户,保持原有注册响应。"""
|
||||
data = request.get_json() or {}
|
||||
required_fields = ['username', 'password', 'email', 'real_name', 'employee_id', 'phone_number']
|
||||
for field in required_fields:
|
||||
if not data.get(field):
|
||||
raise ValidationError(f'{field} is required')
|
||||
if db.session.query(_compat.User).filter_by(username=data['username']).first():
|
||||
raise ValidationError('Username already exists')
|
||||
if db.session.query(_compat.User).filter_by(email=data['email']).first():
|
||||
raise ValidationError('Email already exists')
|
||||
if db.session.query(_compat.User).filter_by(employee_id=data['employee_id']).first():
|
||||
raise ValidationError('Employee ID already exists')
|
||||
try:
|
||||
user = _compat.User(
|
||||
username=data['username'], email=data['email'], real_name=data['real_name'],
|
||||
employee_id=data['employee_id'], phone_number=data['phone_number'],
|
||||
department=data.get('department'), role='user', status='active',
|
||||
)
|
||||
user.set_password(data['password'])
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
return jsonify({'message': 'Registration successful', 'id': user.id}), 201
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=str(exc), http_status=500) from exc
|
||||
|
||||
|
||||
@auth_bp.post('/login', endpoint='login')
|
||||
def login():
|
||||
"""处理兼容的本地用户名密码登录;委托原有审计与重试逻辑。"""
|
||||
if not bool(current_app.config.get('AUTH_ALLOW_LOCAL_PASSWORD_LOGIN', True)):
|
||||
raise AppError(
|
||||
code='AUTH.PASSWORD_LOGIN_DISABLED',
|
||||
message='Password login is disabled. Please use Casdoor login.',
|
||||
http_status=403,
|
||||
)
|
||||
|
||||
def attempt_login():
|
||||
"""校验本地密码并写入登录审计;用于可恢复数据库失败的一次重试。"""
|
||||
data = request.get_json() or {}
|
||||
username = data.get('username')
|
||||
password = data.get('password')
|
||||
if not username or not password:
|
||||
_compat._write_login_audit('password', 'failed', username=username, reason='missing_credentials')
|
||||
raise ValidationError('Username and password are required')
|
||||
user = db.session.query(_compat.User).filter_by(username=username).first()
|
||||
if not user:
|
||||
_compat._write_login_audit('password', 'failed', username=username, reason='user_not_found')
|
||||
db.session.commit()
|
||||
raise AppError(code='AUTH.USER_NOT_FOUND', message='User not found', http_status=404)
|
||||
if not user.check_password(password):
|
||||
_compat._write_login_audit('password', 'failed', user=user, reason='incorrect_password')
|
||||
db.session.commit()
|
||||
raise AppError(code='AUTH.INCORRECT_PASSWORD', message='Incorrect password', http_status=401)
|
||||
if user.status != 'active':
|
||||
_compat._write_login_audit('password', 'failed', user=user, reason='account_disabled')
|
||||
db.session.commit()
|
||||
raise AppError(code='AUTH.ACCOUNT_DISABLED', message='Account is disabled', http_status=403)
|
||||
_compat._write_login_audit('password', 'success', user=user)
|
||||
db.session.commit()
|
||||
return jsonify(_compat._build_login_payload(user, 'password'))
|
||||
|
||||
try:
|
||||
return attempt_login()
|
||||
except (OperationalError, DatabaseError):
|
||||
db.session.rollback()
|
||||
db.session.remove()
|
||||
try:
|
||||
return attempt_login()
|
||||
except (OperationalError, DatabaseError) as retry_exc:
|
||||
current_app.logger.warning('Password login retry failed: %s', retry_exc)
|
||||
raise ServiceUnavailableError('Database connection failed') from retry_exc
|
||||
except AppError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
current_app.logger.exception('Login error: %s', exc)
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Internal server error', http_status=500) from exc
|
||||
|
||||
|
||||
@auth_bp.post('/change-password', endpoint='change_password')
|
||||
def change_password():
|
||||
"""校验当前身份并同步更新本地与 Casdoor 密码。"""
|
||||
user = _compat._get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
data = request.get_json() or {}
|
||||
current_password = data.get('current_password')
|
||||
new_password = data.get('new_password')
|
||||
if not current_password or not new_password:
|
||||
raise ValidationError('Current and new password are required')
|
||||
try:
|
||||
_compat._verify_current_password_for_change(user, current_password)
|
||||
_compat._sync_casdoor_password(user.username, current_password, new_password)
|
||||
user.set_password(new_password)
|
||||
db.session.commit()
|
||||
return jsonify({'message': 'Password changed successfully'})
|
||||
except AppError:
|
||||
raise
|
||||
except RuntimeError as exc:
|
||||
db.session.rollback()
|
||||
if _compat._is_casdoor_password_error(str(exc)):
|
||||
_compat._raise_incorrect_current_password()
|
||||
_compat._raise_casdoor_set_password_error(exc)
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=str(exc), http_status=500) from exc
|
||||
@@ -0,0 +1,147 @@
|
||||
"""
|
||||
api/user/auth_password_reset.py
|
||||
|
||||
用途:密码找回与确认重置 HTTP 路由。
|
||||
依赖:auth.auth_bp、auth_support 的企微配置与 Casdoor 密码同步操作。
|
||||
逻辑:密码重置从常规登录路由分离;保留原有 URL、通用提示语和令牌有效期语义。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
import uuid
|
||||
|
||||
from flask import current_app, jsonify, request
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, ValidationError
|
||||
from app.services.wecom_notify import send_wecom_event_message
|
||||
|
||||
from . import auth as _compat
|
||||
from .auth import auth_bp
|
||||
|
||||
_RATE_CACHE: dict[str, datetime] = {}
|
||||
_GENERIC_MESSAGE = 'If the account exists and WeCom is bound, a reset link has been sent to your WeCom.'
|
||||
|
||||
|
||||
def _base_url() -> str:
|
||||
"""读取密码重置的公网基地址,避免将内部服务地址发给企业微信用户。"""
|
||||
for key in ('WECOM_PUBLIC_BASE_URL', 'PUBLIC_BASE_URL', 'WECOM_NOTIFY_BASE_URL'):
|
||||
base = _compat._clean_str(current_app.config.get(key))
|
||||
if base:
|
||||
return base.rstrip('/')
|
||||
return ''
|
||||
|
||||
|
||||
def _rate_limit(employee_id: str, *, window_seconds: int = 300) -> tuple[bool, int]:
|
||||
"""按工号和来源 IP 限制找回请求,返回是否允许及剩余等待秒数。"""
|
||||
client_ip = request.headers.get('X-Forwarded-For', request.remote_addr) or 'unknown'
|
||||
key = f'{employee_id}:{client_ip}'
|
||||
now = datetime.utcnow()
|
||||
last = _RATE_CACHE.get(key)
|
||||
if last:
|
||||
elapsed = (now - last).total_seconds()
|
||||
if elapsed < window_seconds:
|
||||
return False, max(1, int(window_seconds - elapsed))
|
||||
_RATE_CACHE[key] = now
|
||||
return True, 0
|
||||
|
||||
|
||||
def _sync_casdoor_password(user, new_password: str) -> None:
|
||||
"""令牌重置无需旧密码;Casdoor 启用时仍须同步 IdP 密码。"""
|
||||
if not _compat._is_casdoor_configured():
|
||||
return
|
||||
try:
|
||||
_compat._casdoor_set_password(_compat._casdoor_user_owner(), user.username, '', new_password)
|
||||
except RuntimeError as exc:
|
||||
if _compat._is_casdoor_user_missing_error(str(exc)):
|
||||
_compat._raise_casdoor_user_not_in_idp(exc)
|
||||
_compat._raise_casdoor_set_password_error(exc)
|
||||
|
||||
|
||||
@auth_bp.post('/reset-password-by-wecom', endpoint='reset_password_by_wecom')
|
||||
def request_by_wecom():
|
||||
"""向已绑定企业微信的用户发送限时重置链接。"""
|
||||
if not _compat._is_wecom_configured():
|
||||
raise AppError(code='WECOM.RESET_NOT_CONFIGURED', message='WeCom password reset is not configured', http_status=503, details={'missing': _compat._get_wecom_config_missing_fields()})
|
||||
if not bool(current_app.config.get('WECOM_NOTIFY_ENABLED', True)):
|
||||
raise AppError(code='WECOM.NOTIFY_DISABLED', message='WeCom notification is disabled', http_status=503)
|
||||
base_url = _base_url()
|
||||
if not base_url:
|
||||
raise AppError(code='WECOM.RESET_URL_NOT_CONFIGURED', message='Password reset public base URL is not configured', http_status=503)
|
||||
data = request.get_json() or {}
|
||||
employee_id = _compat._clean_str(data.get('employee_id'))
|
||||
username = _compat._clean_str(data.get('username'))
|
||||
if not employee_id:
|
||||
raise ValidationError('Employee ID is required')
|
||||
if not username:
|
||||
raise ValidationError('Username is required')
|
||||
allowed, retry_after_seconds = _rate_limit(employee_id)
|
||||
if not allowed:
|
||||
raise AppError(code='AUTH.PASSWORD_RESET_RATE_LIMITED', message='Password reset requests are too frequent', http_status=429, details={'retry_after_seconds': retry_after_seconds, 'retry_after_minutes': max(1, (retry_after_seconds + 59) // 60)}, retryable=True)
|
||||
user = db.session.query(_compat.User).filter(_compat.User.employee_id == employee_id).first()
|
||||
if not user or user.username != username or user.status != 'active' or not user.wecom_userid:
|
||||
return jsonify({'message': _GENERIC_MESSAGE})
|
||||
token = str(uuid.uuid4())
|
||||
user.reset_token = token
|
||||
user.reset_token_expiry = datetime.utcnow() + timedelta(hours=1)
|
||||
db.session.flush()
|
||||
try:
|
||||
result = send_wecom_event_message(event_type='password_reset', user=user, title='和信AI智能工作台 密码重置', content='您发起了和信AI智能工作台密码重置请求。\n请在 1 小时内点击下方按钮设置新密码。\n如非本人操作,请忽略本消息。', jump_url=f'{base_url}/reset-password?token={token}')
|
||||
if not result.get('ok'):
|
||||
db.session.rollback()
|
||||
return jsonify({'message': _GENERIC_MESSAGE})
|
||||
db.session.commit()
|
||||
return jsonify({'message': _GENERIC_MESSAGE})
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
current_app.logger.exception('[password_reset] unexpected failure user_id=%s: %s', user.id, exc)
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Failed to request password reset', http_status=500) from exc
|
||||
|
||||
|
||||
@auth_bp.post('/reset-password-by-email', endpoint='reset_password_request')
|
||||
def request_by_email():
|
||||
"""保留邮件找回兼容接口及其既有响应格式。"""
|
||||
data = request.get_json() or {}
|
||||
email = data.get('email')
|
||||
if not email:
|
||||
raise ValidationError('Email is required')
|
||||
user = db.session.query(_compat.User).filter_by(email=email).first()
|
||||
if not user:
|
||||
return jsonify({'message': 'If the email exists, a reset link has been sent.'})
|
||||
user.reset_token = str(uuid.uuid4())
|
||||
user.reset_token_expiry = datetime.utcnow() + timedelta(hours=1)
|
||||
db.session.commit()
|
||||
# Legacy development contract: the email channel is mocked by logging its reset link.
|
||||
reset_link = f'http://localhost:5173/reset-password?token={user.reset_token}'
|
||||
print('============================================')
|
||||
print(f'MOCK EMAIL TO: {email}')
|
||||
print('SUBJECT: Password Reset Request')
|
||||
print(f'LINK: {reset_link}')
|
||||
print('============================================')
|
||||
return jsonify({'message': 'If the email exists, a reset link has been sent.'})
|
||||
|
||||
|
||||
@auth_bp.post('/reset-password-confirm', endpoint='reset_password_confirm')
|
||||
def confirm():
|
||||
"""校验重置令牌后同步更新本地与 Casdoor 密码。"""
|
||||
data = request.get_json() or {}
|
||||
token = _compat._clean_str(data.get('token'))
|
||||
new_password = data.get('new_password')
|
||||
if not token or not new_password:
|
||||
raise ValidationError('Token and new password are required')
|
||||
user = db.session.query(_compat.User).filter_by(reset_token=token).first()
|
||||
if not user or not user.reset_token_expiry or user.reset_token_expiry < datetime.utcnow():
|
||||
raise AppError(code='AUTH.RESET_TOKEN_INVALID', message='Invalid or expired token', http_status=400)
|
||||
try:
|
||||
_sync_casdoor_password(user, new_password)
|
||||
user.set_password(new_password)
|
||||
user.reset_token = None
|
||||
user.reset_token_expiry = None
|
||||
db.session.commit()
|
||||
return jsonify({'message': 'Password has been reset successfully'})
|
||||
except AppError:
|
||||
db.session.rollback()
|
||||
raise
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=str(exc), http_status=500) from exc
|
||||
@@ -0,0 +1,628 @@
|
||||
"""
|
||||
api/user/auth_support.py
|
||||
|
||||
用途:承载用户认证域的共享操作,包括 Casdoor 兼容适配、企微身份匹配、登录审计和短时状态。
|
||||
依赖:services/auth、services/wecom_auth_service、models.User/LoginAudit/WecomCallbackAudit。
|
||||
逻辑:auth_* 路由模块调用本文件完成领域协作;auth.py 兼容门面转发历史测试替身,不再保留路由实现。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import request, jsonify, current_app
|
||||
from app import db
|
||||
from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaultAgent, UserHomepageConfig, LoginAudit, WecomCallbackAudit, GeneralFeedback, ChatLog
|
||||
from app.services.feedback_notify import send_feedback_group_notification
|
||||
from app.services.agent_category import serialize_agent_list_item, sort_agent_rows
|
||||
from app.services.agent_registry.serialization import serialize_registry_fields
|
||||
from app.services.wecom_notify import mark_wecom_message_opened, send_wecom_event_message
|
||||
from app.services.wecom_crypto import sha1_hex, decrypt_wecom_aes, extract_encrypt_field
|
||||
from app.core.auth.jwt import get_current_user as _auth_current_user
|
||||
from sqlalchemy.exc import DatabaseError, IntegrityError, OperationalError
|
||||
from sqlalchemy import and_, or_, inspect, insert
|
||||
from datetime import datetime, timedelta
|
||||
import uuid
|
||||
import requests
|
||||
from urllib.parse import quote
|
||||
import re
|
||||
import ast
|
||||
from app.core.errors import (
|
||||
AppError,
|
||||
ConflictError,
|
||||
ForbiddenError,
|
||||
NotFoundError,
|
||||
ServiceUnavailableError,
|
||||
UnauthorizedError,
|
||||
ValidationError,
|
||||
raise_for_status,
|
||||
)
|
||||
from app.services.auth import casdoor_service as _casdoor_svc
|
||||
from app.services.auth.hxops.casdoor_authorize import CasdoorAuthorizeOptions
|
||||
from app.services.auth.hxops.login_service import HxopsLoginService
|
||||
from app.services.auth.hxops import casdoor_route_adapter as _casdoor_route_adapter
|
||||
from app.services.auth import wecom_auth_service as _wecom_svc
|
||||
_WECOM_ACCESS_TOKEN_CACHE = _wecom_svc.ACCESS_TOKEN_CACHE
|
||||
_WECOM_STATE_CACHE = _wecom_svc.STATE_CACHE
|
||||
_WECOM_BIND_SESSION_CACHE = _wecom_svc.BIND_SESSION_CACHE
|
||||
_PASSWORD_RESET_RATE_CACHE = {}
|
||||
_PASSWORD_RESET_GENERIC_MESSAGE = 'If the account exists and WeCom is bound, a reset link has been sent to your WeCom.'
|
||||
_ALLOWED_WECOM_MATCH_FIELDS = {'employee_id', 'mobile', 'email'}
|
||||
_LOGIN_AUDIT_COLUMNS_CACHE = None
|
||||
|
||||
|
||||
def _token_brief(token: str) -> str:
|
||||
if not token:
|
||||
return 'empty'
|
||||
text = str(token)
|
||||
if len(text) <= 16:
|
||||
return f'len={len(text)}:{text}'
|
||||
return f'len={len(text)}:{text[:8]}...{text[-8:]}'
|
||||
|
||||
def _is_users_pk_sequence_error(exc: Exception) -> bool:
|
||||
message = str(exc)
|
||||
return 'null value in column "id"' in message and 'relation "users"' in message
|
||||
|
||||
class WeComLoginError(AppError):
|
||||
def __init__(self, error: str, error_code: str, status_code: int, reason: str = None, extra: dict = None):
|
||||
details = dict(extra or {})
|
||||
if reason:
|
||||
details['reason'] = reason
|
||||
super().__init__(code=error_code, message=error, http_status=status_code, details=details)
|
||||
self.error = error
|
||||
self.error_code = error_code
|
||||
self.status_code = status_code
|
||||
self.reason = reason
|
||||
self.extra = extra or {}
|
||||
|
||||
def _write_login_audit(source: str, status: str, user: User=None, username: str=None, reason: str=None, wecom_userid: str=None, error_code: str=None, match_rules: list=None, match_operator: str=None, match_result: str=None):
|
||||
payload = {'user_id': user.id if user else None, 'username': username or (user.username if user else None), 'source': source, 'status': status, 'reason': reason, 'error_code': error_code, 'match_rules': ','.join(match_rules) if isinstance(match_rules, list) else match_rules, 'match_operator': match_operator, 'match_result': match_result, 'wecom_userid': wecom_userid, 'ip': request.headers.get('X-Forwarded-For', request.remote_addr), 'user_agent': (request.user_agent.string or '')[:255], 'created_at': datetime.utcnow()}
|
||||
try:
|
||||
supported_columns = _get_login_audit_supported_columns()
|
||||
if not supported_columns:
|
||||
return
|
||||
filtered_payload = {key: value for key, value in payload.items() if key in supported_columns}
|
||||
if not filtered_payload:
|
||||
return
|
||||
_execute_login_audit_insert(filtered_payload)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _get_login_audit_supported_columns():
|
||||
global _LOGIN_AUDIT_COLUMNS_CACHE
|
||||
if _LOGIN_AUDIT_COLUMNS_CACHE is not None:
|
||||
return _LOGIN_AUDIT_COLUMNS_CACHE
|
||||
try:
|
||||
columns = {column['name'] for column in inspect(db.engine).get_columns(LoginAudit.__tablename__)}
|
||||
except Exception:
|
||||
columns = set()
|
||||
_LOGIN_AUDIT_COLUMNS_CACHE = columns
|
||||
return columns
|
||||
|
||||
def _execute_login_audit_insert(payload: dict):
|
||||
nested = db.session.begin_nested()
|
||||
try:
|
||||
db.session.execute(insert(LoginAudit.__table__).values(**payload))
|
||||
db.session.flush()
|
||||
nested.commit()
|
||||
except Exception:
|
||||
nested.rollback()
|
||||
raise
|
||||
|
||||
def _get_current_user():
|
||||
"""
|
||||
Resolve current authenticated user for API handlers.
|
||||
|
||||
Behavior:
|
||||
1) Prefer JWT Bearer token validation (Casdoor JWKS).
|
||||
2) Optional legacy header fallback depends on AUTH_LEGACY_HEADER_ENABLED.
|
||||
3) Returns None when authentication cannot be established.
|
||||
"""
|
||||
return _auth_current_user()
|
||||
|
||||
def _run_db_with_retry(operation, *, label: str):
|
||||
try:
|
||||
return operation()
|
||||
except (OperationalError, DatabaseError) as exc:
|
||||
current_app.logger.warning('%s failed on first attempt: %s', label, exc)
|
||||
db.session.rollback()
|
||||
db.session.remove()
|
||||
try:
|
||||
db.engine.dispose()
|
||||
except Exception as dispose_exc:
|
||||
current_app.logger.warning('%s dispose engine failed: %s', label, dispose_exc)
|
||||
return operation()
|
||||
|
||||
def _get_wecom_config_missing_fields() -> list[str]:
|
||||
return _wecom_svc.get_config_missing_fields()
|
||||
|
||||
|
||||
def _is_wecom_configured() -> bool:
|
||||
return _wecom_svc.is_configured()
|
||||
|
||||
def _issue_casdoor_state(redirect_uri: str):
|
||||
"""兼容旧调用点:签发格式不变的 Casdoor state。"""
|
||||
return _casdoor_route_adapter.issue_casdoor_state(redirect_uri)
|
||||
|
||||
def _consume_casdoor_state(state: str):
|
||||
"""兼容旧调用点:校验 Casdoor state 并恢复签名绑定的 redirect_uri。"""
|
||||
return _casdoor_route_adapter.consume_casdoor_state(state)
|
||||
|
||||
def _get_casdoor_oidc_metadata():
|
||||
"""兼容旧调用点:委托公共 CasdoorClient 获取 discovery 文档。"""
|
||||
return _casdoor_route_adapter.get_oidc_metadata()
|
||||
|
||||
|
||||
def _build_casdoor_authorize_payload(options: CasdoorAuthorizeOptions) -> dict[str, str]:
|
||||
"""兼容入口:使用旧 discovery/state 替换点构造 Casdoor 授权响应。"""
|
||||
return _casdoor_route_adapter.build_authorize_payload(
|
||||
options,
|
||||
oidc_metadata=_get_casdoor_oidc_metadata,
|
||||
issue_state=_issue_casdoor_state,
|
||||
)
|
||||
|
||||
def _resolve_user_from_casdoor_claims(claims: dict):
|
||||
"""兼容旧调用点:通过公共身份对象映射 HXOPS 用户。"""
|
||||
from app.services.auth.casdoor.identity import identity_from_claims
|
||||
from app.services.auth.common import IdentityValidationError
|
||||
from app.services.auth.hxops.user_resolver import HxopsIdentityMappingError, resolve_hxops_user
|
||||
|
||||
try:
|
||||
identity = identity_from_claims(
|
||||
claims,
|
||||
expected_issuer=str(current_app.config.get('AUTH_JWT_ISSUER') or ''),
|
||||
)
|
||||
return resolve_hxops_user(identity)
|
||||
except IdentityValidationError as exc:
|
||||
raise AppError(
|
||||
code='AUTH.CASDOOR_IDENTITY_INVALID',
|
||||
message='Casdoor identity is missing issuer or subject',
|
||||
http_status=401,
|
||||
) from exc
|
||||
except HxopsIdentityMappingError as exc:
|
||||
raise WeComLoginError(error=str(exc), error_code=exc.code, status_code=exc.status) from exc
|
||||
|
||||
|
||||
def _issue_casdoor_api_token(user: User, claims: dict) -> str:
|
||||
"""
|
||||
为已通过 Casdoor 认证的用户签发 HXOPS API 会话 JWT。
|
||||
|
||||
Args:
|
||||
user: 已映射成功的 HXOPS 本地用户。
|
||||
claims: Casdoor ID token 或 userinfo 返回的可信身份声明。
|
||||
|
||||
Returns:
|
||||
HXOPS 本地签名 JWT,其中保留 Casdoor issuer/subject 供跨系统 SSO 使用。
|
||||
|
||||
Raises:
|
||||
AppError: Casdoor 未返回稳定 subject,不能建立可复用身份。
|
||||
"""
|
||||
from app.services.auth.casdoor.identity import identity_from_claims
|
||||
from app.services.auth.common import IdentityValidationError
|
||||
from app.services.auth.hxops.session_token import issue_hxops_access_token
|
||||
|
||||
try:
|
||||
identity = identity_from_claims(
|
||||
claims,
|
||||
expected_issuer=str(current_app.config.get('AUTH_JWT_ISSUER') or claims.get('iss') or ''),
|
||||
)
|
||||
except IdentityValidationError as exc:
|
||||
raise AppError(
|
||||
code='AUTH.CASDOOR_IDENTITY_INVALID',
|
||||
message='Casdoor identity is missing issuer or subject',
|
||||
http_status=401,
|
||||
) from exc
|
||||
return issue_hxops_access_token(user, identity)
|
||||
|
||||
def _casdoor_exchange_code(code: str, redirect_uri: str):
|
||||
"""兼容旧测试替换点:委托公共客户端执行 authorization code grant。"""
|
||||
return _casdoor_route_adapter.authorization_code_login(code, redirect_uri)
|
||||
|
||||
def _casdoor_refresh_token(refresh_token: str):
|
||||
"""兼容旧测试替换点:委托公共客户端执行 refresh grant。"""
|
||||
return _casdoor_route_adapter.refresh_token(refresh_token)
|
||||
|
||||
def _casdoor_userinfo(access_token: str):
|
||||
"""兼容旧测试替换点:委托公共客户端读取 userinfo。"""
|
||||
return _casdoor_route_adapter.userinfo(access_token)
|
||||
|
||||
def _casdoor_password_login(username: str, password: str):
|
||||
"""
|
||||
Resource-owner password login against Casdoor token endpoint.
|
||||
Requires the Casdoor application to enable password grant.
|
||||
"""
|
||||
return _casdoor_route_adapter.password_login(username, password)
|
||||
|
||||
|
||||
def _hxops_login_service() -> HxopsLoginService:
|
||||
"""创建使用当前兼容代理的登录服务,使既有 monkeypatch 测试和调用方式保持有效。"""
|
||||
return _casdoor_route_adapter.create_login_service(
|
||||
write_login_audit=_write_login_audit,
|
||||
password_operation=_casdoor_password_login,
|
||||
code_operation=_casdoor_exchange_code,
|
||||
refresh_operation=_casdoor_refresh_token,
|
||||
userinfo_operation=_casdoor_userinfo,
|
||||
)
|
||||
|
||||
def _is_casdoor_login_mode() -> bool:
|
||||
return (current_app.config.get('AUTH_LOGIN_MODE') or 'casdoor').lower() == 'casdoor'
|
||||
|
||||
def _is_casdoor_configured() -> bool:
|
||||
return _casdoor_svc.is_casdoor_configured()
|
||||
|
||||
def _casdoor_user_owner() -> str:
|
||||
return _casdoor_svc.casdoor_user_owner()
|
||||
|
||||
def _verify_casdoor_password(username: str, password: str):
|
||||
_casdoor_password_login(username, password)
|
||||
|
||||
def _casdoor_set_password(user_owner: str, user_name: str, old_password: str, new_password: str):
|
||||
return _casdoor_svc.casdoor_set_password(user_owner, user_name, old_password, new_password)
|
||||
|
||||
def _is_casdoor_user_exists_error(message: str) -> bool:
|
||||
return _casdoor_svc.is_user_exists_error(message)
|
||||
|
||||
def _raise_casdoor_add_user_error(source) -> None:
|
||||
_casdoor_svc.raise_add_user_error(source)
|
||||
|
||||
def _casdoor_add_user(user_payload: dict):
|
||||
return _casdoor_svc.casdoor_add_user(user_payload)
|
||||
|
||||
def _sync_casdoor_create_user(*, username: str, password: str, email: str, employee_id: str | None = None, real_name=None, phone_number=None, status='active', department=None):
|
||||
"""兼容入口:同步创建 Casdoor 用户,并传递认证主映射工号。"""
|
||||
return _casdoor_svc.sync_create_user(username=username, password=password, employee_id=employee_id, email=email, real_name=real_name, phone_number=phone_number, status=status, department=department)
|
||||
|
||||
def _raise_casdoor_update_user_error(source) -> None:
|
||||
_casdoor_svc.raise_update_user_error(source)
|
||||
|
||||
def _casdoor_update_user(user_payload: dict):
|
||||
return _casdoor_svc.casdoor_update_user(user_payload)
|
||||
|
||||
def _sync_casdoor_admin_set_password(user: User, new_password: str):
|
||||
return _casdoor_svc.sync_admin_set_password(user, new_password)
|
||||
|
||||
def _sync_casdoor_update_user(user: User, *, new_password: str | None = None):
|
||||
return _casdoor_svc.sync_update_user(user, new_password=new_password)
|
||||
|
||||
def _is_casdoor_password_error(message: str) -> bool:
|
||||
return _casdoor_svc.is_password_error(message)
|
||||
|
||||
def _is_casdoor_user_missing_error(message: str) -> bool:
|
||||
return _casdoor_svc.is_user_missing_error(message)
|
||||
|
||||
def _raise_casdoor_user_not_in_idp(source=None) -> None:
|
||||
_casdoor_svc.raise_user_not_in_idp(source)
|
||||
|
||||
def _extract_casdoor_error_payload(source) -> dict:
|
||||
return _casdoor_svc.extract_error_payload(source)
|
||||
|
||||
def _raise_casdoor_auth_error(source, *, context: str, status_code: int = 401) -> None:
|
||||
_casdoor_svc.raise_auth_error(source, context=context, status_code=status_code)
|
||||
|
||||
def _raise_casdoor_set_password_error(source) -> None:
|
||||
_casdoor_svc.raise_set_password_error(source)
|
||||
|
||||
def _raise_incorrect_current_password():
|
||||
raise AppError(
|
||||
code='AUTH.INCORRECT_CURRENT_PASSWORD',
|
||||
message='Incorrect current password',
|
||||
http_status=403,
|
||||
)
|
||||
|
||||
def _verify_current_password_for_change(user, current_password: str):
|
||||
if user.check_password(current_password):
|
||||
return
|
||||
if not _is_casdoor_configured():
|
||||
_raise_incorrect_current_password()
|
||||
try:
|
||||
_verify_casdoor_password(user.username, current_password)
|
||||
except AppError as e:
|
||||
if e.code == 'CASDOOR_INVALID_CREDENTIALS':
|
||||
_raise_incorrect_current_password()
|
||||
raise
|
||||
except RuntimeError as e:
|
||||
if _is_casdoor_password_error(str(e)):
|
||||
_raise_incorrect_current_password()
|
||||
raise
|
||||
|
||||
def _sync_casdoor_password(username: str, current_password: str, new_password: str):
|
||||
if not _is_casdoor_configured():
|
||||
return
|
||||
user_owner = _casdoor_user_owner()
|
||||
try:
|
||||
_casdoor_set_password(user_owner, username, current_password, new_password)
|
||||
except AppError as first_error:
|
||||
if first_error.code in ('CASDOOR_INVALID_CREDENTIALS', 'AUTH.INCORRECT_CURRENT_PASSWORD'):
|
||||
_raise_incorrect_current_password()
|
||||
raise
|
||||
except RuntimeError as first_error:
|
||||
if _is_casdoor_user_missing_error(str(first_error)):
|
||||
_raise_casdoor_user_not_in_idp(first_error)
|
||||
if _is_casdoor_password_error(str(first_error)):
|
||||
_raise_incorrect_current_password()
|
||||
try:
|
||||
_casdoor_set_password(user_owner, username, '', new_password)
|
||||
except RuntimeError:
|
||||
raise first_error
|
||||
|
||||
def _cleanup_wecom_state_cache():
|
||||
now = datetime.utcnow()
|
||||
expired = [k for k, v in _WECOM_STATE_CACHE.items() if not v or v < now]
|
||||
for k in expired:
|
||||
_WECOM_STATE_CACHE.pop(k, None)
|
||||
|
||||
def _issue_wecom_state():
|
||||
_cleanup_wecom_state_cache()
|
||||
state = f'hxops_wecom_{uuid.uuid4().hex}'
|
||||
_WECOM_STATE_CACHE[state] = datetime.utcnow() + timedelta(minutes=10)
|
||||
return state
|
||||
|
||||
def _consume_wecom_state(state: str):
|
||||
if not state:
|
||||
return False
|
||||
_cleanup_wecom_state_cache()
|
||||
exp = _WECOM_STATE_CACHE.pop(state, None)
|
||||
return bool(exp and exp > datetime.utcnow())
|
||||
|
||||
def _cleanup_wecom_bind_session_cache():
|
||||
now = datetime.utcnow()
|
||||
expired = [key for key, item in _WECOM_BIND_SESSION_CACHE.items() if not isinstance(item, dict) or not item.get('expires_at') or item['expires_at'] < now]
|
||||
for key in expired:
|
||||
_WECOM_BIND_SESSION_CACHE.pop(key, None)
|
||||
|
||||
def _issue_wecom_bind_session(identity: dict):
|
||||
_cleanup_wecom_bind_session_cache()
|
||||
token = f'hxops_wecom_bind_{uuid.uuid4().hex}'
|
||||
_WECOM_BIND_SESSION_CACHE[token] = {'expires_at': datetime.utcnow() + timedelta(minutes=10), 'identity': dict(identity or {})}
|
||||
return token
|
||||
|
||||
def _get_wecom_bind_session(token: str):
|
||||
if not token:
|
||||
return None
|
||||
_cleanup_wecom_bind_session_cache()
|
||||
item = _WECOM_BIND_SESSION_CACHE.get(token)
|
||||
if not isinstance(item, dict):
|
||||
return None
|
||||
expires_at = item.get('expires_at')
|
||||
if not expires_at or expires_at < datetime.utcnow():
|
||||
_WECOM_BIND_SESSION_CACHE.pop(token, None)
|
||||
return None
|
||||
identity = item.get('identity')
|
||||
return identity if isinstance(identity, dict) else None
|
||||
|
||||
def _consume_wecom_bind_session(token: str):
|
||||
identity = _get_wecom_bind_session(token)
|
||||
if identity is None:
|
||||
return None
|
||||
_WECOM_BIND_SESSION_CACHE.pop(token, None)
|
||||
return identity
|
||||
|
||||
def _parse_wecom_field_list(raw_value, default_fields: list[str]):
|
||||
return _wecom_svc.parse_field_list(raw_value, default_fields)
|
||||
|
||||
def _verify_wecom_msg_signature(msg_signature: str, token: str, timestamp: str, nonce: str, encrypt: str) -> bool:
|
||||
if not msg_signature or not token or (not encrypt):
|
||||
return False
|
||||
expected = sha1_hex([token, str(timestamp or ''), str(nonce or ''), encrypt])
|
||||
return expected == msg_signature
|
||||
|
||||
def _extract_xml_field(xml_text: str, tag: str):
|
||||
if not xml_text:
|
||||
return None
|
||||
m = re.search(f'<{tag}><!\\[CDATA\\[(.*?)\\]\\]></{tag}>', xml_text, re.DOTALL)
|
||||
if m:
|
||||
return m.group(1).strip()
|
||||
m2 = re.search(f'<{tag}>(.*?)</{tag}>', xml_text, re.DOTALL)
|
||||
if m2:
|
||||
return m2.group(1).strip()
|
||||
return None
|
||||
|
||||
def _persist_wecom_callback_audit(*, msg_signature, timestamp, nonce, encrypt_raw, decrypted_xml=None, msg_type=None, event=None, from_user=None, agent_id=None, msg_id=None, error_message=None):
|
||||
try:
|
||||
row = WecomCallbackAudit(msg_signature=msg_signature, timestamp=timestamp, nonce=nonce, encrypt_raw=encrypt_raw, decrypted_xml=decrypted_xml, msg_type=msg_type, event=event, from_user=from_user, agent_id=agent_id, msg_id=msg_id, error_message=error_message)
|
||||
db.session.add(row)
|
||||
db.session.commit()
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
|
||||
def _get_wecom_access_token():
|
||||
return _wecom_svc.get_access_token()
|
||||
|
||||
def _build_login_payload(user: User, source: str='password', bind_status: str=None):
|
||||
payload = {
|
||||
'id': user.id,
|
||||
'username': user.username,
|
||||
'role': user.role,
|
||||
'default_agent_id': user.default_agent_id,
|
||||
'feature_permissions': user.get_feature_permissions(),
|
||||
'source': source,
|
||||
'access_token': issue_local_access_token(user),
|
||||
'token_type': 'Bearer',
|
||||
}
|
||||
if bind_status:
|
||||
payload['bind_status'] = bind_status
|
||||
return payload
|
||||
|
||||
def _clean_str(value):
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, str):
|
||||
value = value.strip()
|
||||
return value or None
|
||||
return str(value).strip() or None
|
||||
|
||||
def _parse_leave_int_flag(value, field_label: str):
|
||||
if value in (0, 1):
|
||||
return int(value)
|
||||
text = _clean_str(value)
|
||||
if text in ('0', '1'):
|
||||
return int(text)
|
||||
raise OALeaveWorkflowError(f'{field_label} 取值无效,应为 0 或 1。')
|
||||
|
||||
def _normalize_mobile(mobile: str):
|
||||
mobile = _clean_str(mobile)
|
||||
if not mobile:
|
||||
return None
|
||||
digits = re.sub('\\D', '', mobile)
|
||||
if not digits:
|
||||
return mobile
|
||||
if digits.startswith('0086'):
|
||||
digits = digits[4:]
|
||||
elif digits.startswith('86') and len(digits) > 11:
|
||||
digits = digits[2:]
|
||||
return digits
|
||||
|
||||
def _extract_wecom_extattr_value(wecom_user: dict, key: str):
|
||||
extattr = wecom_user.get('extattr') or {}
|
||||
attrs = extattr.get('attrs') if isinstance(extattr, dict) else None
|
||||
if not isinstance(attrs, list):
|
||||
return None
|
||||
for attr in attrs:
|
||||
if not isinstance(attr, dict):
|
||||
continue
|
||||
if _clean_str(attr.get('name')) != key:
|
||||
continue
|
||||
raw = attr.get('value')
|
||||
if isinstance(raw, dict):
|
||||
raw = raw.get('text') or raw.get('web') or raw.get('value')
|
||||
return _clean_str(raw)
|
||||
return None
|
||||
|
||||
def _get_wecom_match_config():
|
||||
return _wecom_svc.get_match_config()
|
||||
|
||||
def _get_wecom_first_login_bind_mode():
|
||||
return _wecom_svc.get_first_login_bind_mode()
|
||||
|
||||
def _get_wecom_first_login_input_fields():
|
||||
return _wecom_svc.get_first_login_input_fields()
|
||||
|
||||
def _extract_wecom_identity(wecom_user: dict):
|
||||
return _wecom_svc.extract_identity(wecom_user)
|
||||
|
||||
def _mobile_candidates(identity: dict):
|
||||
values = []
|
||||
for item in [identity.get('mobile'), identity.get('mobile_raw')]:
|
||||
item = _clean_str(item)
|
||||
if item and item not in values:
|
||||
values.append(item)
|
||||
return values
|
||||
|
||||
def _find_users_by_input_field(field: str, value):
|
||||
field = _clean_str(field)
|
||||
if field not in _ALLOWED_WECOM_MATCH_FIELDS:
|
||||
return ([], 'invalid_field')
|
||||
if field == 'employee_id':
|
||||
needle = _clean_str(value)
|
||||
if not needle:
|
||||
return ([], 'employee_id')
|
||||
return (db.session.query(User).filter(User.employee_id == needle).all(), None)
|
||||
if field == 'email':
|
||||
needle = _clean_str(value)
|
||||
if not needle:
|
||||
return ([], 'email')
|
||||
return (db.session.query(User).filter(User.email == needle).all(), None)
|
||||
if field == 'mobile':
|
||||
raw_mobile = _clean_str(value)
|
||||
normalized_mobile = _normalize_mobile(raw_mobile)
|
||||
candidates = []
|
||||
for item in [normalized_mobile, raw_mobile]:
|
||||
item = _clean_str(item)
|
||||
if item and item not in candidates:
|
||||
candidates.append(item)
|
||||
if not candidates:
|
||||
return ([], 'mobile')
|
||||
return (db.session.query(User).filter(User.phone_number.in_(candidates)).all(), None)
|
||||
return ([], 'invalid_field')
|
||||
|
||||
def _find_users_by_match_rules(identity: dict, rules: list, operator: str):
|
||||
return _wecom_svc.find_users_by_match_rules(identity, rules, operator)
|
||||
|
||||
def _assert_wecom_binding_not_occupied(user: User, identity: dict):
|
||||
wecom_userid = identity.get('wecom_userid')
|
||||
wecom_unionid = identity.get('wecom_unionid')
|
||||
if wecom_userid:
|
||||
dup = db.session.query(User).filter(User.wecom_userid == wecom_userid, User.id != user.id).first()
|
||||
if dup:
|
||||
raise WeComLoginError(error=f'Current WeCom account has been bound to user: {dup.username}', error_code='WECOM_BIND_CONFLICT', status_code=409, reason='bind_conflict')
|
||||
if wecom_unionid:
|
||||
dup_union = db.session.query(User).filter(User.wecom_unionid == wecom_unionid, User.id != user.id).first()
|
||||
if dup_union:
|
||||
raise WeComLoginError(error=f'Current WeCom unionid has been bound to user: {dup_union.username}', error_code='WECOM_BIND_CONFLICT', status_code=409, reason='bind_conflict')
|
||||
|
||||
def _sync_user_from_wecom_identity(user: User, identity: dict):
|
||||
_assert_wecom_binding_not_occupied(user, identity)
|
||||
if identity.get('wecom_userid'):
|
||||
user.wecom_userid = identity['wecom_userid']
|
||||
if identity.get('wecom_unionid') and (not user.wecom_unionid):
|
||||
user.wecom_unionid = identity['wecom_unionid']
|
||||
if identity.get('name') and (not user.real_name):
|
||||
user.real_name = identity['name']
|
||||
if identity.get('email') and (not user.email):
|
||||
dup_email = db.session.query(User).filter(User.email == identity['email'], User.id != user.id).first()
|
||||
if not dup_email:
|
||||
user.email = identity['email']
|
||||
if identity.get('mobile') and (not user.phone_number):
|
||||
candidates = _mobile_candidates(identity)
|
||||
dup_mobile = db.session.query(User).filter(User.phone_number.in_(candidates), User.id != user.id).first()
|
||||
if not dup_mobile:
|
||||
user.phone_number = identity['mobile']
|
||||
if identity.get('employee_id') and (not user.employee_id):
|
||||
dup_employee = db.session.query(User).filter(User.employee_id == identity['employee_id'], User.id != user.id).first()
|
||||
if not dup_employee:
|
||||
user.employee_id = identity['employee_id']
|
||||
|
||||
def _create_user_from_wecom_identity(identity: dict) -> User:
|
||||
base_username = (identity.get('wecom_userid') or identity.get('email') or identity.get('mobile') or f'wecom_{uuid.uuid4().hex[:8]}').replace('@', '_')
|
||||
candidate = base_username
|
||||
suffix = 1
|
||||
while db.session.query(User).filter_by(username=candidate).first():
|
||||
candidate = f'{base_username}_{suffix}'
|
||||
suffix += 1
|
||||
safe_email = identity.get('email') or f'{candidate}@wecom.local'
|
||||
if db.session.query(User).filter_by(email=safe_email).first():
|
||||
safe_email = f'{candidate}_{uuid.uuid4().hex[:6]}@wecom.local'
|
||||
employee_id = identity.get('employee_id')
|
||||
if employee_id and db.session.query(User).filter_by(employee_id=employee_id).first():
|
||||
employee_id = None
|
||||
phone_number = identity.get('mobile')
|
||||
if phone_number:
|
||||
candidates = _mobile_candidates(identity)
|
||||
dup_mobile = db.session.query(User).filter(User.phone_number.in_(candidates)).first()
|
||||
if dup_mobile:
|
||||
phone_number = None
|
||||
user = User(username=candidate, email=safe_email, role='user', status='active', real_name=identity.get('name'), employee_id=employee_id, phone_number=phone_number, wecom_userid=identity.get('wecom_userid'), wecom_unionid=identity.get('wecom_unionid'))
|
||||
user.set_password(uuid.uuid4().hex)
|
||||
db.session.add(user)
|
||||
return user
|
||||
|
||||
def _issue_wecom_input_bind_prompt(identity: dict):
|
||||
allowed_fields = _get_wecom_first_login_input_fields()
|
||||
binding_token = _issue_wecom_bind_session(identity)
|
||||
raise WeComLoginError(error='First WeCom login requires verification input to bind a local account.', error_code='WECOM_BIND_INPUT_REQUIRED', status_code=409, reason='input_bind_required', extra={'binding_token': binding_token, 'allowed_fields': allowed_fields, 'wecom_name': identity.get('name'), 'wecom_userid': identity.get('wecom_userid')})
|
||||
|
||||
def _sync_or_create_user_from_wecom(wecom_user: dict):
|
||||
identity = _extract_wecom_identity(wecom_user)
|
||||
rules, operator = _get_wecom_match_config()
|
||||
rule_info = {'operator': operator, 'fields': rules}
|
||||
bind_mode = _get_wecom_first_login_bind_mode()
|
||||
user = None
|
||||
if identity.get('wecom_userid'):
|
||||
user = db.session.query(User).filter_by(wecom_userid=identity['wecom_userid']).first()
|
||||
if user:
|
||||
_sync_user_from_wecom_identity(user, identity)
|
||||
return (user, 'already_bound', rule_info)
|
||||
if bind_mode == 'input_verify':
|
||||
_issue_wecom_input_bind_prompt(identity)
|
||||
matched_users, missing_fields = _find_users_by_match_rules(identity, rules, operator)
|
||||
if missing_fields:
|
||||
missing_field = missing_fields[0]
|
||||
raise WeComLoginError(error=f'Required match attribute missing: {missing_field}', error_code='WECOM_MATCH_ATTR_MISSING', status_code=422, reason=f'missing_attr:{missing_field}', extra={'missing_field': missing_field, 'match_rules': rule_info})
|
||||
if len(matched_users) == 1:
|
||||
user = matched_users[0]
|
||||
_sync_user_from_wecom_identity(user, identity)
|
||||
return (user, 'matched_and_bound', rule_info)
|
||||
if len(matched_users) > 1:
|
||||
raise WeComLoginError(error='Multiple local users matched', error_code='WECOM_MATCH_AMBIGUOUS', status_code=409, reason='ambiguous_match', extra={'candidate_count': len(matched_users), 'match_rules': rule_info})
|
||||
if not current_app.config.get('WECOM_AUTO_CREATE_USER', True):
|
||||
raise WeComLoginError(error='No linked account found. Contact admin to bind WeCom account.', error_code='WECOM_BIND_REQUIRED', status_code=403, reason='bind_required', extra={'match_rules': rule_info})
|
||||
user = _create_user_from_wecom_identity(identity)
|
||||
return (user, 'auto_created', rule_info)
|
||||
@@ -0,0 +1,196 @@
|
||||
"""
|
||||
api/user/auth_wecom.py
|
||||
|
||||
用途:企业微信 OAuth、绑定与回调 HTTP 路由。
|
||||
依赖:auth.auth_bp、auth_support 的企微签名、身份匹配和审计操作。
|
||||
逻辑:将企微认证入口同本地/Casdoor 路由隔离,保持企业微信回调 URL 不变。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from urllib.parse import quote
|
||||
|
||||
import requests
|
||||
from flask import current_app, jsonify, request
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, ConflictError, ForbiddenError, UnauthorizedError, ValidationError
|
||||
from app.services.wecom_crypto import decrypt_wecom_aes, extract_encrypt_field
|
||||
|
||||
from . import auth as _compat
|
||||
from .auth import auth_bp
|
||||
|
||||
|
||||
@auth_bp.get('/wecom/authorize-url', endpoint='wecom_authorize_url')
|
||||
def authorize_url():
|
||||
"""生成企业微信 OAuth 授权地址。"""
|
||||
if not _compat._is_wecom_configured():
|
||||
raise ValidationError('WeCom login is not configured')
|
||||
redirect_uri = request.args.get('redirect_uri') or current_app.config.get('WECOM_REDIRECT_URI')
|
||||
if not redirect_uri:
|
||||
raise ValidationError('redirect_uri is required')
|
||||
state = _compat._issue_wecom_state()
|
||||
corp_id = current_app.config.get('WECOM_CORP_ID')
|
||||
agent_id = current_app.config.get('WECOM_AGENT_ID')
|
||||
url = f"https://open.weixin.qq.com/connect/oauth2/authorize?appid={corp_id}&redirect_uri={quote(redirect_uri, safe='')}&response_type=code&scope=snsapi_base&state={quote(state, safe='')}&agentid={agent_id}#wechat_redirect"
|
||||
return jsonify({'url': url, 'state': state})
|
||||
|
||||
|
||||
@auth_bp.post('/wecom/login', endpoint='wecom_login')
|
||||
def login():
|
||||
"""完成企业微信 OAuth 登录并映射或绑定本地用户。"""
|
||||
if not _compat._is_wecom_configured():
|
||||
raise ValidationError('WeCom login is not configured')
|
||||
data = request.get_json() or {}
|
||||
code, state = data.get('code'), data.get('state')
|
||||
if not code:
|
||||
_compat._write_login_audit('wecom', 'failed', reason='missing_code')
|
||||
db.session.commit()
|
||||
raise ValidationError('code is required')
|
||||
if not _compat._consume_wecom_state(state):
|
||||
_compat._write_login_audit('wecom', 'failed', reason='invalid_state')
|
||||
db.session.commit()
|
||||
raise ValidationError('Invalid or expired WeCom state')
|
||||
wecom_userid = None
|
||||
try:
|
||||
access_token = _compat._get_wecom_access_token()
|
||||
info = requests.get('https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo', params={'access_token': access_token, 'code': code}, timeout=8).json()
|
||||
wecom_userid = info.get('userid') or info.get('UserId')
|
||||
if info.get('errcode') != 0:
|
||||
raise UnauthorizedError(f"WeCom auth failed: {info.get('errmsg', 'unknown error')}")
|
||||
if not wecom_userid:
|
||||
raise AppError(code='WECOM_NOT_IN_AGENT_SCOPE', message='当前企业微信账号未授权登录该应用:账号不在自建应用的可见范围内,或不是本企业成员。请管理员到「企业微信后台 → 应用管理 → 该应用 → 可见范围」中加入该成员所在的部门或个人。', http_status=401)
|
||||
wecom_user = requests.get('https://qyapi.weixin.qq.com/cgi-bin/user/get', params={'access_token': access_token, 'userid': wecom_userid}, timeout=8).json()
|
||||
if wecom_user.get('errcode') != 0:
|
||||
raise UnauthorizedError(f"WeCom user fetch failed: {wecom_user.get('errmsg', 'unknown error')}")
|
||||
user, bind_status, rule_info = _compat._sync_or_create_user_from_wecom(wecom_user)
|
||||
if user.status != 'active':
|
||||
raise ForbiddenError('Account is disabled')
|
||||
_compat._write_login_audit('wecom', 'success', user=user, wecom_userid=wecom_userid, match_rules=rule_info.get('fields'), match_operator=rule_info.get('operator'), match_result=bind_status)
|
||||
db.session.commit()
|
||||
return jsonify(_compat._build_login_payload(user, 'wecom', bind_status=bind_status))
|
||||
except _compat.WeComLoginError as exc:
|
||||
db.session.rollback()
|
||||
_compat._write_login_audit('wecom', 'failed', reason=exc.reason or 'wecom_login_error', wecom_userid=wecom_userid, error_code=exc.error_code)
|
||||
db.session.commit()
|
||||
raise
|
||||
except AppError as exc:
|
||||
db.session.rollback()
|
||||
_compat._write_login_audit('wecom', 'failed', reason=str(exc)[:160], wecom_userid=wecom_userid, error_code=exc.code)
|
||||
db.session.commit()
|
||||
raise
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
if _compat._is_users_pk_sequence_error(exc):
|
||||
_compat._write_login_audit('wecom', 'failed', reason='db_sequence_misconfig', wecom_userid=wecom_userid, error_code='DB_SEQUENCE_MISCONFIG')
|
||||
db.session.commit()
|
||||
raise AppError(code='SYSTEM.DB_SEQUENCE_MISCONFIG', message='数据库主键自增配置异常,当前环境缺少 users.id 的自动序列。请执行数据库迁移后重试。', http_status=500) from exc
|
||||
_compat._write_login_audit('wecom', 'failed', reason=f'exception:{str(exc)[:160]}', wecom_userid=wecom_userid)
|
||||
db.session.commit()
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=f'WeCom login failed: {exc}', http_status=500) from exc
|
||||
|
||||
|
||||
@auth_bp.post('/wecom/complete-bind', endpoint='wecom_complete_bind')
|
||||
def complete_bind():
|
||||
"""提交首登人工绑定信息并完成企业微信账号绑定。"""
|
||||
if not _compat._is_wecom_configured():
|
||||
raise ValidationError('WeCom login is not configured')
|
||||
data = request.get_json() or {}
|
||||
token, field, value = _compat._clean_str(data.get('binding_token')), _compat._clean_str(data.get('field')), data.get('value')
|
||||
identity = _compat._get_wecom_bind_session(token)
|
||||
if not identity:
|
||||
raise AppError(code='WECOM_BIND_SESSION_EXPIRED', message='WeCom binding session expired. Please restart WeCom login.', http_status=400)
|
||||
allowed_fields = _compat._get_wecom_first_login_input_fields()
|
||||
if field not in allowed_fields:
|
||||
raise AppError(code='WECOM_BIND_FIELD_NOT_ALLOWED', message='Selected bind field is not allowed', http_status=400, details={'allowed_fields': allowed_fields})
|
||||
matched_users, missing_field = _compat._find_users_by_input_field(field, value)
|
||||
if missing_field:
|
||||
raise AppError(code='WECOM_BIND_INPUT_VALUE_REQUIRED', message=f'{field} is required', http_status=400, details={'field': field})
|
||||
if not matched_users:
|
||||
raise AppError(code='WECOM_BIND_INPUT_NOT_FOUND', message='No local account matched the verification value.', http_status=404, details={'field': field})
|
||||
if len(matched_users) > 1:
|
||||
raise ConflictError('Multiple local accounts matched the verification value.', code='WECOM_BIND_INPUT_AMBIGUOUS', details={'field': field, 'candidate_count': len(matched_users)})
|
||||
user = matched_users[0]
|
||||
if user.status != 'active':
|
||||
raise ForbiddenError('Account is disabled')
|
||||
try:
|
||||
_compat._sync_user_from_wecom_identity(user, identity)
|
||||
_compat._write_login_audit('wecom', 'success', user=user, wecom_userid=identity.get('wecom_userid'), match_rules=[field], match_operator='AND', match_result='input_verified_and_bound')
|
||||
db.session.commit()
|
||||
_compat._WECOM_BIND_SESSION_CACHE.pop(token, None)
|
||||
return jsonify(_compat._build_login_payload(user, 'wecom', bind_status='input_verified_and_bound'))
|
||||
except _compat.WeComLoginError as exc:
|
||||
db.session.rollback()
|
||||
_compat._write_login_audit('wecom', 'failed', user=user, reason=exc.reason or 'wecom_input_bind_error', wecom_userid=identity.get('wecom_userid'), error_code=exc.error_code, match_rules=[field], match_operator='AND')
|
||||
db.session.commit()
|
||||
raise
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
_compat._write_login_audit('wecom', 'failed', user=user, reason=f'exception:{str(exc)[:160]}', wecom_userid=identity.get('wecom_userid'), error_code='WECOM_BIND_INPUT_EXCEPTION', match_rules=[field], match_operator='AND')
|
||||
db.session.commit()
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=f'WeCom bind failed: {exc}', http_status=500) from exc
|
||||
|
||||
|
||||
@auth_bp.route('/wecom/callback', methods=['GET', 'POST'], endpoint='wecom_callback')
|
||||
def callback():
|
||||
"""处理企业微信 URL 验证及加密事件回调。"""
|
||||
signature = request.args.get('msg_signature') or request.args.get('signature')
|
||||
timestamp, nonce = request.args.get('timestamp', ''), request.args.get('nonce', '')
|
||||
token = current_app.config.get('WECOM_CALLBACK_TOKEN') or ''
|
||||
aes_key, corp_id = current_app.config.get('WECOM_ENCODING_AES_KEY') or '', current_app.config.get('WECOM_CORP_ID') or ''
|
||||
if not token:
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='callback token not configured', http_status=500)
|
||||
if request.method == 'GET':
|
||||
echostr = request.args.get('echostr', '') or ''
|
||||
if not _compat._verify_wecom_msg_signature(signature, token, timestamp, nonce, echostr):
|
||||
raise ForbiddenError('invalid callback signature')
|
||||
try:
|
||||
plain = decrypt_wecom_aes(echostr, aes_key, corp_id) if aes_key else echostr
|
||||
except Exception as exc:
|
||||
_compat._persist_wecom_callback_audit(msg_signature=signature, timestamp=timestamp, nonce=nonce, encrypt_raw=echostr, error_message=f'decrypt_failed:{str(exc)[:200]}')
|
||||
raise ValidationError('decrypt failed') from exc
|
||||
_compat._persist_wecom_callback_audit(msg_signature=signature, timestamp=timestamp, nonce=nonce, encrypt_raw=echostr, decrypted_xml=plain, msg_type='url_verify' if aes_key else 'url_verify_plain')
|
||||
return plain, 200, {'Content-Type': 'text/plain; charset=utf-8'}
|
||||
payload = request.get_data(as_text=True) or ''
|
||||
encrypt_field = extract_encrypt_field(payload) or ''
|
||||
if not encrypt_field:
|
||||
raise ValidationError('missing Encrypt field')
|
||||
if not _compat._verify_wecom_msg_signature(signature, token, timestamp, nonce, encrypt_field):
|
||||
_compat._persist_wecom_callback_audit(msg_signature=signature, timestamp=timestamp, nonce=nonce, encrypt_raw=encrypt_field, error_message='invalid_msg_signature')
|
||||
raise ForbiddenError('invalid callback signature')
|
||||
decrypted = None
|
||||
if aes_key:
|
||||
try:
|
||||
decrypted = decrypt_wecom_aes(encrypt_field, aes_key, corp_id)
|
||||
except Exception as exc:
|
||||
_compat._persist_wecom_callback_audit(msg_signature=signature, timestamp=timestamp, nonce=nonce, encrypt_raw=encrypt_field, error_message=f'decrypt_failed:{str(exc)[:200]}')
|
||||
raise ValidationError('decrypt failed') from exc
|
||||
_compat._persist_wecom_callback_audit(
|
||||
msg_signature=signature, timestamp=timestamp, nonce=nonce, encrypt_raw=encrypt_field,
|
||||
decrypted_xml=decrypted, msg_type=_compat._extract_xml_field(decrypted, 'MsgType') if decrypted else None,
|
||||
event=_compat._extract_xml_field(decrypted, 'Event') if decrypted else None,
|
||||
from_user=_compat._extract_xml_field(decrypted, 'FromUserName') if decrypted else None,
|
||||
agent_id=_compat._extract_xml_field(decrypted, 'AgentID') if decrypted else None,
|
||||
msg_id=_compat._extract_xml_field(decrypted, 'MsgId') if decrypted else None,
|
||||
)
|
||||
return 'success', 200, {'Content-Type': 'text/plain; charset=utf-8'}
|
||||
|
||||
|
||||
@auth_bp.get('/wecom/binding', endpoint='get_wecom_binding')
|
||||
def binding():
|
||||
"""返回当前用户的企业微信绑定状态。"""
|
||||
user = _compat._get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
return jsonify({'bound': bool(user.wecom_userid), 'wecom_userid': user.wecom_userid, 'wecom_unionid': user.wecom_unionid})
|
||||
|
||||
|
||||
@auth_bp.post('/wecom/unbind', endpoint='unbind_wecom_self')
|
||||
def unbind():
|
||||
"""解除当前用户与企业微信账号的绑定。"""
|
||||
user = _compat._get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
user.wecom_userid = None
|
||||
user.wecom_unionid = None
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok', 'message': 'WeCom account unbound'})
|
||||
@@ -0,0 +1,383 @@
|
||||
"""
|
||||
backend/app/api/user/handlers.py
|
||||
|
||||
用途:当前用户域 API(Casdoor 登录、企微 OAuth、首页、FAQ、反馈等)。
|
||||
依赖:sqlalchemy(and_/or_、exc)、app.core.errors、models、wecom/dify 相关 services。
|
||||
逻辑:薄路由层鉴权与参数校验;Casdoor/企微 OAuth 委托 services/auth/*。
|
||||
"""
|
||||
from flask import Blueprint, request, jsonify, current_app
|
||||
from sqlalchemy import and_, or_
|
||||
from sqlalchemy.exc import DatabaseError, OperationalError
|
||||
from app import db
|
||||
from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaultAgent, UserHomepageConfig, GeneralFeedback, ChatLog
|
||||
from app.services.feedback_notify import send_feedback_group_notification
|
||||
from app.services.agent_category import serialize_agent_list_item, sort_agent_rows
|
||||
from app.services.agent_registry.serialization import serialize_registry_fields
|
||||
from app.services.wecom_notify import mark_wecom_message_opened, send_wecom_event_message
|
||||
import re
|
||||
import ast
|
||||
from app.core.errors import (
|
||||
AppError,
|
||||
ForbiddenError,
|
||||
NotFoundError,
|
||||
ServiceUnavailableError,
|
||||
UnauthorizedError,
|
||||
ValidationError,
|
||||
)
|
||||
from .auth import (
|
||||
_clean_str,
|
||||
_get_current_user,
|
||||
_parse_leave_int_flag,
|
||||
_run_db_with_retry,
|
||||
)
|
||||
user_bp = Blueprint('user', __name__)
|
||||
|
||||
@user_bp.route('/wecom/deeplink-opened', methods=['POST'])
|
||||
def mark_wecom_deeplink_opened():
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
data = request.get_json() or {}
|
||||
trace_id = _clean_str(data.get('trace_id'))
|
||||
if not trace_id:
|
||||
raise ValidationError('trace_id is required')
|
||||
ok = mark_wecom_message_opened(trace_id)
|
||||
if not ok:
|
||||
raise NotFoundError('trace_id not found')
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
@user_bp.route('/wecom/task-complete', methods=['POST'])
|
||||
def wecom_task_complete():
|
||||
"""
|
||||
Lightweight endpoint for sending task completion WeCom message.
|
||||
Can be called by frontend after long-running task is done.
|
||||
"""
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
data = request.get_json() or {}
|
||||
title = _clean_str(data.get('title')) or 'AI 任务已完成'
|
||||
content = _clean_str(data.get('content')) or '你发起的 AI 任务已完成,点击查看详情。'
|
||||
agent_id = data.get('agent_id')
|
||||
jump_path = '/workspace'
|
||||
jump_params = {}
|
||||
if agent_id:
|
||||
jump_path = f'/chat/{int(agent_id)}'
|
||||
result = send_wecom_event_message(event_type='task_completed', user=user, title=title, content=content, jump_path=jump_path, jump_params=jump_params)
|
||||
db.session.commit()
|
||||
return (jsonify(result), 200 if result.get('ok') else 202)
|
||||
|
||||
@user_bp.route('/leave-balance', methods=['GET'])
|
||||
def get_leave_balance():
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
leave_type_code = _clean_str(request.args.get('leave_type'))
|
||||
if leave_type_code not in ('010', '408'):
|
||||
raise ValidationError('仅支持查询年假(010)和育儿假(408)的余额')
|
||||
try:
|
||||
from app.services.hr_leave_sqlserver import HRLeaveSQLServerService
|
||||
employee_code = HRLeaveSQLServerService._get_employee_code(user)
|
||||
now_year = datetime.now().year
|
||||
if leave_type_code == '010':
|
||||
_, record = HRLeaveSQLServerService._query_one(view_name='VIEW_D044', year_column='D044001', total_column='D044005', used_column='D044006', remaining_column='D044007', employee_code=employee_code, year=now_year)
|
||||
label = '年假'
|
||||
else:
|
||||
_, record = HRLeaveSQLServerService._query_one(view_name='VIEW_D072', year_column='d072001', total_column='d072002', used_column='d072003', remaining_column='d072004', employee_code=employee_code, year=now_year)
|
||||
label = '育儿假'
|
||||
remaining = record.get('remaining_hours') if record else None
|
||||
try:
|
||||
has_balance = remaining is not None and float(remaining) > 0
|
||||
except (TypeError, ValueError):
|
||||
has_balance = False
|
||||
return jsonify({'leave_type_code': leave_type_code, 'leave_type_label': label, 'year': record.get('leave_year', now_year) if record else now_year, 'total_hours': record.get('total_hours') if record else None, 'used_hours': record.get('used_hours') if record else None, 'remaining_hours': remaining, 'has_balance': has_balance})
|
||||
except Exception as exc:
|
||||
current_app.logger.exception('[leave-balance] query failed user_id=%s', getattr(user, 'id', None))
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=f'假期余额查询失败:{exc}', http_status=500)
|
||||
|
||||
@user_bp.route('/leave-workflow/submit', methods=['POST'])
|
||||
def submit_leave_workflow():
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
data = request.get_json() or {}
|
||||
form_data = {'applicantName': _clean_str(data.get('applicantName')) or _clean_str(getattr(user, 'real_name', None)) or _clean_str(getattr(user, 'username', None)), 'employeeId': _clean_str(data.get('employeeId')) or _clean_str(getattr(user, 'employee_id', None)) or _clean_str(getattr(user, 'username', None)), 'applicantJobTitle': _clean_str(data.get('applicantJobTitle')), 'applicantDepartmentId': _clean_str(data.get('applicantDepartmentId')), 'applicantSubCompanyId1': _clean_str(data.get('applicantSubCompanyId1')), 'applyTime': _clean_str(data.get('applyTime')), 'fillerName': _clean_str(data.get('fillerName')) or _clean_str(getattr(user, 'real_name', None)) or _clean_str(getattr(user, 'username', None)), 'agentUid': _clean_str(data.get('agentUid')), 'agentEmployeeId': _clean_str(data.get('agentEmployeeId')), 'agentName': _clean_str(data.get('agentName')), 'agentJobTitle': _clean_str(data.get('agentJobTitle')), 'agentDepartmentId': _clean_str(data.get('agentDepartmentId')), 'agentSubCompanyId1': _clean_str(data.get('agentSubCompanyId1')), 'leaveType': _clean_str(data.get('leaveType')), 'startTime': _clean_str(data.get('startTime')), 'endTime': _clean_str(data.get('endTime')), 'durationHours': data.get('durationHours'), 'isOutOfOffice': _parse_leave_int_flag(data.get('isOutOfOffice'), '是否外出'), 'isWorkInjury': _parse_leave_int_flag(data.get('isWorkInjury'), '是否为工伤'), 'remark': _clean_str(data.get('remark')) or ''}
|
||||
required_fields = {'applicantName': '请假人', 'employeeId': '工号', 'fillerName': '填单人', 'agentUid': '代理人UID', 'agentEmployeeId': '代理人工号', 'agentName': '代理人姓名', 'leaveType': '假别', 'startTime': '开始时间', 'endTime': '结束时间'}
|
||||
for key, label in required_fields.items():
|
||||
if not form_data.get(key):
|
||||
raise ValidationError(f'{label}不能为空。')
|
||||
try:
|
||||
from app.services.oa_leave_workflow import OALeaveWorkflowService, OALeaveWorkflowError
|
||||
result = OALeaveWorkflowService.submit_leave_request(form_data, user)
|
||||
except OALeaveWorkflowError as exc:
|
||||
current_app.logger.warning('[oa-leave] submit failed user_id=%s employee_id=%s err=%s', getattr(user, 'id', None), form_data.get('employeeId'), exc)
|
||||
raise ValidationError(str(exc))
|
||||
except Exception as exc:
|
||||
current_app.logger.exception('[oa-leave] unexpected submit failure user_id=%s', getattr(user, 'id', None))
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=f'OA 请假提交失败:{exc}', http_status=500)
|
||||
current_app.logger.info('[oa-leave] submit success user_id=%s employee_id=%s request_id=%s workflow_id=%s', getattr(user, 'id', None), form_data.get('employeeId'), result.get('request_id'), result.get('workflow_id'))
|
||||
return jsonify(result)
|
||||
|
||||
@user_bp.route('/feedback', methods=['POST'])
|
||||
def submit_general_feedback():
|
||||
"""
|
||||
通用意见反馈接口(与 /api/chat/feedback 的对话评分接口不同
|
||||
"""
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
data = request.get_json() or {}
|
||||
feedback_type = _clean_str(data.get('feedback_type'))
|
||||
feedback_module = _clean_str(data.get('feedback_module'))
|
||||
content = _clean_str(data.get('content'))
|
||||
source_page = _clean_str(data.get('source_page'))
|
||||
raw_chat_log_id = data.get('chat_log_id')
|
||||
chat_log_id = None
|
||||
if raw_chat_log_id not in (None, ''):
|
||||
try:
|
||||
chat_log_id = int(raw_chat_log_id)
|
||||
except (TypeError, ValueError):
|
||||
raise ValidationError('chat_log_id must be an integer')
|
||||
if chat_log_id <= 0:
|
||||
raise ValidationError('chat_log_id must be a positive integer')
|
||||
if not feedback_type:
|
||||
raise ValidationError('feedback_type is required')
|
||||
if not feedback_module:
|
||||
raise ValidationError('feedback_module is required')
|
||||
if len(feedback_type) > 32:
|
||||
raise ValidationError('feedback_type is too long')
|
||||
if len(feedback_module) > 32:
|
||||
raise ValidationError('feedback_module is too long')
|
||||
if not content:
|
||||
raise ValidationError('content is required')
|
||||
if len(content) > 2000:
|
||||
raise ValidationError('content is too long')
|
||||
if source_page != 'chat':
|
||||
chat_log_id = None
|
||||
if chat_log_id is not None:
|
||||
chat_log = db.session.get(ChatLog, chat_log_id)
|
||||
if not chat_log:
|
||||
raise ValidationError('chat_log_id not found')
|
||||
if chat_log.user_id != user.id:
|
||||
raise ForbiddenError('chat_log_id is not owned by current user')
|
||||
row = GeneralFeedback(user_id=user.id, username=user.username, feedback_type=feedback_type, feedback_module=feedback_module, content=content, source_page=source_page, chat_log_id=chat_log_id)
|
||||
db.session.add(row)
|
||||
db.session.commit()
|
||||
notify_result = send_feedback_group_notification(row, user)
|
||||
if notify_result.get('ok'):
|
||||
current_app.logger.info('[feedback] group notification sent feedback_id=%s', row.id)
|
||||
elif not notify_result.get('skipped'):
|
||||
current_app.logger.warning(
|
||||
'[feedback] group notification failed feedback_id=%s reason=%s',
|
||||
row.id,
|
||||
notify_result.get('reason'),
|
||||
)
|
||||
return jsonify({'status': 'ok', 'id': row.id})
|
||||
|
||||
@user_bp.route('/home', methods=['GET'])
|
||||
def home():
|
||||
"""
|
||||
Get user homepage data
|
||||
"""
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
|
||||
def _load_home_payload():
|
||||
if user.role == 'admin':
|
||||
agent_rows = Agent.query.filter(Agent.is_active.is_(True)).all()
|
||||
else:
|
||||
agent_rows = [agent for agent in user.agents if agent.is_active]
|
||||
agent_rows = sort_agent_rows(agent_rows)
|
||||
favorites = db.session.query(UserFavoriteAgent).filter_by(user_id=user.id).all()
|
||||
favorite_ids = [f.agent_id for f in favorites]
|
||||
qqs = db.session.query(QuickQuestion).filter(
|
||||
or_(
|
||||
QuickQuestion.user_id == user.id,
|
||||
and_(QuickQuestion.user_id.is_(None), QuickQuestion.is_enabled.is_(True)),
|
||||
)
|
||||
).all()
|
||||
layout_config = db.session.query(UserHomepageConfig).filter_by(user_id=user.id).first()
|
||||
layout = layout_config.layout if layout_config else {}
|
||||
embedded_rel = db.session.query(UserDefaultAgent).filter_by(user_id=user.id).order_by(UserDefaultAgent.sort_order).all()
|
||||
embedded_agents = []
|
||||
for rel in embedded_rel:
|
||||
agent = db.session.get(Agent, rel.agent_id)
|
||||
if agent:
|
||||
registry = serialize_registry_fields(agent)
|
||||
embedded_agents.append({
|
||||
'id': agent.id,
|
||||
'name': agent.name,
|
||||
'iframe_url': registry.get('iframe_url'),
|
||||
'runtime_provider': registry.get('runtime_provider'),
|
||||
'conversation_mode': registry.get('conversation_mode'),
|
||||
})
|
||||
return jsonify({'user': {'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'feature_permissions': user.get_feature_permissions(), 'language': user.language, 'theme_preference': user.theme_preference or 'system'}, 'agents': [serialize_agent_list_item(a) for a in agent_rows], 'favorite_agent_ids': favorite_ids, 'quick_questions': [{'id': q.id, 'title': q.title, 'question': q.question, 'agent_id': q.agent_id} for q in qqs], 'embedded_agents': embedded_agents, 'layout': layout})
|
||||
try:
|
||||
return _run_db_with_retry(_load_home_payload, label='user.home')
|
||||
except (OperationalError, DatabaseError) as exc:
|
||||
current_app.logger.warning('user.home retry failed: %s', exc)
|
||||
raise ServiceUnavailableError('Database connection failed')
|
||||
|
||||
@user_bp.route('/favorites/<int:agent_id>', methods=['POST', 'DELETE'])
|
||||
def toggle_favorite(agent_id: int):
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
if request.method == 'POST':
|
||||
exists = db.session.query(UserFavoriteAgent).filter_by(user_id=user.id, agent_id=agent_id).first()
|
||||
if not exists:
|
||||
fav = UserFavoriteAgent(user_id=user.id, agent_id=agent_id)
|
||||
db.session.add(fav)
|
||||
else:
|
||||
db.session.query(UserFavoriteAgent).filter_by(user_id=user.id, agent_id=agent_id).delete()
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
@user_bp.route('/quick-questions', methods=['POST'])
|
||||
def add_quick_question():
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
data = request.get_json() or {}
|
||||
if not data.get('title') or not data.get('question') or (not data.get('agent_id')):
|
||||
raise ValidationError('Missing fields')
|
||||
qq = QuickQuestion(user_id=user.id, title=data['title'], question=data['question'], agent_id=data['agent_id'])
|
||||
db.session.add(qq)
|
||||
db.session.commit()
|
||||
return (jsonify({'message': 'Added', 'id': qq.id}), 201)
|
||||
|
||||
@user_bp.route('/quick-questions/<int:qq_id>', methods=['PUT', 'DELETE'])
|
||||
def update_quick_question(qq_id: int):
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
qq = db.session.query(QuickQuestion).filter_by(id=qq_id, user_id=user.id).first()
|
||||
if not qq:
|
||||
raise NotFoundError('QuickQuestion not found or permission denied')
|
||||
if request.method == 'DELETE':
|
||||
db.session.delete(qq)
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
data = request.get_json() or {}
|
||||
if 'title' in data:
|
||||
qq.title = data['title']
|
||||
if 'question' in data:
|
||||
qq.question = data['question']
|
||||
if 'agent_id' in data:
|
||||
qq.agent_id = data['agent_id']
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
@user_bp.route('/homepage-layout', methods=['PUT'])
|
||||
def update_layout():
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
data = request.get_json() or {}
|
||||
layout = data.get('layout', {})
|
||||
config = db.session.query(UserHomepageConfig).filter_by(user_id=user.id).first()
|
||||
if not config:
|
||||
config = UserHomepageConfig(user_id=user.id, layout=layout)
|
||||
db.session.add(config)
|
||||
else:
|
||||
config.layout = layout
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
@user_bp.route('/profile', methods=['GET', 'PUT'])
|
||||
def user_profile():
|
||||
"""
|
||||
User profile management
|
||||
GET: Get details
|
||||
PUT: Update basic info
|
||||
"""
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
if request.method == 'GET':
|
||||
return jsonify({'id': user.id, 'username': user.username, 'real_name': user.real_name, 'email': user.email, 'phone_number': user.phone_number, 'employee_id': user.employee_id, 'department': user.department, 'role': user.role, 'feature_permissions': user.get_feature_permissions(), 'language': user.language, 'theme_preference': user.theme_preference or 'system'})
|
||||
data = request.get_json() or {}
|
||||
|
||||
def _update_profile():
|
||||
if 'real_name' in data:
|
||||
user.real_name = data['real_name']
|
||||
if 'phone_number' in data:
|
||||
user.phone_number = data['phone_number']
|
||||
if 'language' in data:
|
||||
user.language = data['language']
|
||||
if 'theme_preference' in data:
|
||||
if data['theme_preference'] not in ['light', 'dark', 'system']:
|
||||
raise ValidationError('Invalid theme preference')
|
||||
user.theme_preference = data['theme_preference']
|
||||
if 'email' in data:
|
||||
if data['email']:
|
||||
existing = db.session.query(User).filter_by(email=data['email']).first()
|
||||
if existing and existing.id != user.id:
|
||||
raise ValidationError('Email already exists')
|
||||
user.email = data['email']
|
||||
if 'employee_id' in data:
|
||||
if data['employee_id']:
|
||||
existing = db.session.query(User).filter_by(employee_id=data['employee_id']).first()
|
||||
if existing and existing.id != user.id:
|
||||
raise ValidationError('Employee ID already exists')
|
||||
user.employee_id = data['employee_id']
|
||||
if 'department' in data:
|
||||
user.department = data['department']
|
||||
db.session.commit()
|
||||
return jsonify({'message': 'Profile updated successfully'})
|
||||
try:
|
||||
return _run_db_with_retry(_update_profile, label='user.profile.update')
|
||||
except (OperationalError, DatabaseError) as exc:
|
||||
db.session.rollback()
|
||||
current_app.logger.warning('user.profile.update retry failed: %s', exc)
|
||||
raise ServiceUnavailableError('Database connection failed')
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=str(e), http_status=500)
|
||||
|
||||
@user_bp.route('/agents/<int:id>', methods=['GET'])
|
||||
def get_agent_details(id):
|
||||
"""
|
||||
Get agent details with permission check
|
||||
"""
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
agent = db.session.get(Agent, id)
|
||||
if not agent:
|
||||
raise NotFoundError('Not found')
|
||||
if user.role != 'admin':
|
||||
has_permission = agent in user.agents
|
||||
if not has_permission:
|
||||
raise ForbiddenError('Access denied')
|
||||
|
||||
from app.services.agent_registry.resolver import resolve_runtime_provider
|
||||
from app.services.agent_registry.serialization import serialize_agent_for_user_detail
|
||||
|
||||
dify_parameters = None
|
||||
if resolve_runtime_provider(agent) in {'dify', 'hybrid'} and getattr(agent, 'dify_api_key', None):
|
||||
from app.services.dify import DifyService
|
||||
|
||||
try:
|
||||
params = DifyService.get_app_parameters(agent)
|
||||
if isinstance(params, dict):
|
||||
dify_parameters = {
|
||||
'file_upload': params.get('file_upload') if isinstance(params.get('file_upload'), dict) else {},
|
||||
'system_parameters': params.get('system_parameters') if isinstance(params.get('system_parameters'), dict) else {},
|
||||
}
|
||||
except Exception as exc:
|
||||
current_app.logger.warning('[user.agents] dify parameters fetch failed agent_id=%s err=%s', id, exc)
|
||||
|
||||
return jsonify(serialize_agent_for_user_detail(
|
||||
agent,
|
||||
dify_parameters=dify_parameters,
|
||||
))
|
||||
|
||||
@user_bp.route('/db', methods=['GET'])
|
||||
def get_db():
|
||||
from app.models import User
|
||||
from app import db
|
||||
u = db.session.query(User).filter_by(username='26040006').first()
|
||||
return jsonify({'db': current_app.config.get('SQLALCHEMY_DATABASE_URI'), 'user': u.username if u else None})
|
||||
@@ -1,21 +1,20 @@
|
||||
"""
|
||||
backend/app/api/workspace/__init__.py
|
||||
|
||||
用途:工作台域 Blueprint 聚合(schedule、shipping_notice、file_check、announcements、process_gate 路由)。
|
||||
用途:工作台域 Blueprint 聚合(schedule、shipping_notice、file_check、voucher_check、announcements)。
|
||||
依赖:workspace 各子模块 blueprint。
|
||||
逻辑:import 子模块注册路由;register_blueprints 从本包导入各 bp;process_gate 路由挂载于 workspace_shipping_notice_bp。
|
||||
逻辑:import 子模块注册路由;register_blueprints 从本包导入各 bp。
|
||||
"""
|
||||
from app.api.workspace.announcements import workspace_announcements_bp
|
||||
from app.api.workspace.file_check import workspace_file_check_bp
|
||||
from app.api.workspace.schedule import workspace_schedule_bp
|
||||
from app.api.workspace.shipping_notice import workspace_shipping_notice_bp
|
||||
|
||||
import app.api.workspace.shipping_process_gate # noqa: F401
|
||||
import app.api.workspace.shipping_inventory_candidates # noqa: F401
|
||||
from app.api.workspace.voucher_check import workspace_voucher_check_bp
|
||||
|
||||
__all__ = [
|
||||
'workspace_announcements_bp',
|
||||
'workspace_file_check_bp',
|
||||
'workspace_schedule_bp',
|
||||
'workspace_shipping_notice_bp',
|
||||
'workspace_voucher_check_bp',
|
||||
]
|
||||
@@ -57,6 +57,31 @@ def serialize_current_step(payload: dict) -> dict | None:
|
||||
return None
|
||||
return {'step': str(current_step.get('step') or ''), 'label': str(current_step.get('label') or current_step.get('step') or ''), 'row_id': current_step.get('row_id'), 'started_at': current_step.get('started_at'), 'processed_count': int(current_step.get('processed_count') or 0), 'success_count': int(current_step.get('success_count') or 0), 'failed_count': int(current_step.get('failed_count') or 0), 'skipped_count': int(current_step.get('skipped_count') or 0)}
|
||||
|
||||
def serialize_progress_metrics(payload: dict) -> list[dict] | None:
|
||||
"""
|
||||
序列化领域自定义进度指标(如立账凭证检核的齐全/缺资料)。
|
||||
核心逻辑:读取 response_summary_json.progress_metrics;非法则返回 None 以回退旧八格。
|
||||
"""
|
||||
response_summary = payload.get('response_summary_json') if isinstance(payload.get('response_summary_json'), dict) else {}
|
||||
metrics = response_summary.get('progress_metrics')
|
||||
if not isinstance(metrics, list) or not metrics:
|
||||
return None
|
||||
out: list[dict] = []
|
||||
for item in metrics:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
key = str(item.get('key') or '').strip()
|
||||
if not key:
|
||||
continue
|
||||
out.append({
|
||||
'key': key,
|
||||
'label_key': str(item.get('label_key') or ''),
|
||||
'label': str(item.get('label') or ''),
|
||||
'value': int(item.get('value') or 0),
|
||||
})
|
||||
return out or None
|
||||
|
||||
|
||||
def _serialize_progress_run(run: ScheduleRun) -> dict:
|
||||
payload = serialize_run(run)
|
||||
total = int(payload.get('total_count') or 0)
|
||||
@@ -66,7 +91,39 @@ def _serialize_progress_run(run: ScheduleRun) -> dict:
|
||||
processed = success + failed + skipped
|
||||
percent = int(round(processed / total * 100)) if total > 0 else 0
|
||||
percent = max(0, min(percent, 100))
|
||||
return {'run_id': payload['id'], 'run_no': payload['run_no'], 'task_id': payload['schedule_task_id'], 'title': payload.get('schedule_name') or '', 'status': payload['status'], 'total_count': total, 'processed_count': processed, 'success_count': success, 'failed_count': failed, 'skipped_count': skipped, 'judgement': serialize_file_judgement(payload), 'current_step': serialize_current_step(payload), 'progress_percent': percent, 'started_at': payload.get('started_at'), 'finished_at': payload.get('finished_at'), 'duration_ms': payload.get('duration_ms'), 'error_message': payload.get('error_message'), 'excel': {'file_name': payload.get('excel_file_name'), 'file_size': payload.get('excel_file_size'), 'download_url': f'/api/workspace/file-check/runs/{run.id}/excel' if payload.get('excel_file_name') else None}, 'knowledge_base': {'sync_status': payload.get('kb_sync_status'), 'group_id': payload.get('kb_group_id'), 'document_id': payload.get('kb_document_id'), 'document_version_id': payload.get('kb_document_version_id'), 'sync_job_id': payload.get('kb_sync_job_id'), 'error_message': payload.get('kb_sync_error')}}
|
||||
return {
|
||||
'run_id': payload['id'],
|
||||
'run_no': payload['run_no'],
|
||||
'task_id': payload['schedule_task_id'],
|
||||
'title': payload.get('schedule_name') or '',
|
||||
'status': payload['status'],
|
||||
'total_count': total,
|
||||
'processed_count': processed,
|
||||
'success_count': success,
|
||||
'failed_count': failed,
|
||||
'skipped_count': skipped,
|
||||
'judgement': serialize_file_judgement(payload),
|
||||
'progress_metrics': serialize_progress_metrics(payload),
|
||||
'current_step': serialize_current_step(payload),
|
||||
'progress_percent': percent,
|
||||
'started_at': payload.get('started_at'),
|
||||
'finished_at': payload.get('finished_at'),
|
||||
'duration_ms': payload.get('duration_ms'),
|
||||
'error_message': payload.get('error_message'),
|
||||
'excel': {
|
||||
'file_name': payload.get('excel_file_name'),
|
||||
'file_size': payload.get('excel_file_size'),
|
||||
'download_url': f'/api/workspace/file-check/runs/{run.id}/excel' if payload.get('excel_file_name') else None,
|
||||
},
|
||||
'knowledge_base': {
|
||||
'sync_status': payload.get('kb_sync_status'),
|
||||
'group_id': payload.get('kb_group_id'),
|
||||
'document_id': payload.get('kb_document_id'),
|
||||
'document_version_id': payload.get('kb_document_version_id'),
|
||||
'sync_job_id': payload.get('kb_sync_job_id'),
|
||||
'error_message': payload.get('kb_sync_error'),
|
||||
},
|
||||
}
|
||||
|
||||
@workspace_file_check_bp.route('/file-check/runs/for-log', methods=['GET'])
|
||||
def workspace_file_check_run_for_log():
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
"""
|
||||
backend/app/api/workspace/voucher_check.py
|
||||
|
||||
用途:工作台立账凭证检核记录查询 API(批次明细 / 最新状态)。
|
||||
依赖:auth.jwt、response_utils envelope、voucher_check.query_service。
|
||||
逻辑:对话与检核记录页共用;标准 {success,data|error,request_id} envelope。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import Blueprint, request
|
||||
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import UnauthorizedError
|
||||
from app.core.response import ok
|
||||
from app.services.voucher_check import query_service
|
||||
|
||||
workspace_voucher_check_bp = Blueprint("workspace_voucher_check", __name__)
|
||||
|
||||
|
||||
def _require_user():
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
|
||||
@workspace_voucher_check_bp.route("/accounting-voucher-check/runs/<int:run_id>/items", methods=["GET"])
|
||||
def workspace_voucher_run_items(run_id: int):
|
||||
"""
|
||||
分页查看批次明细。
|
||||
核心逻辑:委托 query_service.list_run_items,可按 result 过滤。
|
||||
"""
|
||||
_require_user()
|
||||
data = query_service.list_run_items(
|
||||
run_id=run_id,
|
||||
result=request.args.get("result"),
|
||||
page=request.args.get("page", default=1, type=int) or 1,
|
||||
page_size=request.args.get("page_size", default=50, type=int) or 50,
|
||||
)
|
||||
return ok(data)
|
||||
|
||||
|
||||
@workspace_voucher_check_bp.route("/accounting-voucher-check/states", methods=["GET"])
|
||||
def workspace_voucher_states():
|
||||
"""
|
||||
按月份、状态、发票号筛选最新状态。
|
||||
"""
|
||||
_require_user()
|
||||
data = query_service.list_states(
|
||||
scope_code=str(request.args.get("scope_code") or "HXJM"),
|
||||
period=request.args.get("period"),
|
||||
status=request.args.get("status"),
|
||||
invoice_no=request.args.get("invoice_no"),
|
||||
page=request.args.get("page", default=1, type=int) or 1,
|
||||
page_size=request.args.get("page_size", default=50, type=int) or 50,
|
||||
)
|
||||
return ok(data)
|
||||
|
||||
|
||||
@workspace_voucher_check_bp.route("/accounting-voucher-check/states/<path:invoice_no>", methods=["GET"])
|
||||
def workspace_voucher_state_detail(invoice_no: str):
|
||||
"""查看单票最近状态和历史批次快照。"""
|
||||
_require_user()
|
||||
data = query_service.get_invoice_latest(
|
||||
invoice_no=invoice_no,
|
||||
scope_code=str(request.args.get("scope_code") or "HXJM"),
|
||||
period=request.args.get("period"),
|
||||
)
|
||||
return ok(data)
|
||||
Reference in new issue
Block a user