Merge branch 'dev' into test
This commit is contained in:
commit
03366965e7
20 files changed
+737
-164
No files matched your search
@@ -32,4 +32,4 @@ CASDOOR_SCOPE=openid profile email
|
||||
CASDOOR_WECOM_PROVIDER_HINT=wecom
|
||||
|
||||
# Gunicorn配置
|
||||
GUNICORN_WORKERS=2
|
||||
GUNICORN_WORKERS=10
|
||||
@@ -32,4 +32,4 @@ CASDOOR_SCOPE=openid profile email
|
||||
CASDOOR_WECOM_PROVIDER_HINT=wecom
|
||||
|
||||
# Gunicorn配置
|
||||
GUNICORN_WORKERS=2
|
||||
GUNICORN_WORKERS=20
|
||||
+11
@@ -70,3 +70,14 @@ PLM_ORACLE_SID=orcl
|
||||
PLM_ORACLE_USERNAME=PLM
|
||||
PLM_ORACLE_PASSWORD=PLM
|
||||
ORACLE_CLIENT_LIB_DIR=oracle_client\instantclient_19_30
|
||||
|
||||
# SRM SQL Server Configuration
|
||||
SRM_SQLSERVER_HOST=192.168.55.106
|
||||
SRM_SQLSERVER_PORT=1433
|
||||
SRM_SQLSERVER_DATABASE=HX-SRM
|
||||
SRM_SQLSERVER_USERNAME=sa
|
||||
SRM_SQLSERVER_PASSWORD=sa@moreyou456
|
||||
SRM_SQLSERVER_DRIVER=SQL Server
|
||||
SRM_SQLSERVER_ENCRYPT=no
|
||||
SRM_SQLSERVER_TRUST_CERT=yes
|
||||
SRM_SQLSERVER_TIMEOUT=10
|
||||
@@ -31,4 +31,4 @@ CASDOOR_SCOPE=openid profile email
|
||||
CASDOOR_WECOM_PROVIDER_HINT=wecom
|
||||
|
||||
# Gunicorn配置
|
||||
GUNICORN_WORKERS=2
|
||||
GUNICORN_WORKERS=6
|
||||
+65
-2
@@ -7,6 +7,7 @@ backend/app/api/chat.py
|
||||
"""
|
||||
import io
|
||||
import ipaddress
|
||||
import mimetypes
|
||||
import tempfile
|
||||
import os
|
||||
import subprocess
|
||||
@@ -25,6 +26,25 @@ from app import db
|
||||
# 定义 Blueprint,用于在应用工厂中注册路由前缀 /api/chat
|
||||
chat_bp = Blueprint('chat', __name__)
|
||||
|
||||
PLM_PREVIEW_SHARE_ROOT = (os.getenv("PLM_PREVIEW_SHARE_ROOT") or "\\\\192.168.0.11\\dss\\dssroot\\").strip()
|
||||
|
||||
|
||||
def _normalize_windows_share_path(path_value: str) -> str:
|
||||
normalized = str(path_value or "").strip().strip('"').replace("/", "\\")
|
||||
if normalized.startswith("\\\\"):
|
||||
return "\\\\" + normalized[2:].rstrip("\\")
|
||||
return normalized.rstrip("\\")
|
||||
|
||||
|
||||
def _is_allowed_share_path(target_url: str) -> bool:
|
||||
normalized_target = _normalize_windows_share_path(target_url)
|
||||
normalized_root = _normalize_windows_share_path(PLM_PREVIEW_SHARE_ROOT)
|
||||
return bool(
|
||||
normalized_root
|
||||
and normalized_target.startswith("\\\\")
|
||||
and normalized_target.lower().startswith(normalized_root.lower())
|
||||
)
|
||||
|
||||
|
||||
def _is_allowed_preview_url(target_url: str) -> bool:
|
||||
"""
|
||||
@@ -35,6 +55,8 @@ def _is_allowed_preview_url(target_url: str) -> bool:
|
||||
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
|
||||
@@ -75,6 +97,25 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None = 15 * 1024
|
||||
import sqlalchemy as sa
|
||||
from urllib.parse import parse_qs
|
||||
|
||||
if _is_allowed_share_path(file_url):
|
||||
normalized_path = _normalize_windows_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
|
||||
|
||||
headers = {}
|
||||
base_url = IntegrationApiService.get_base_url()
|
||||
api_key = IntegrationApiService.get_api_key()
|
||||
@@ -188,6 +229,24 @@ 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 _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 _convert_office_to_pdf(content: bytes, ext: str) -> bytes:
|
||||
"""
|
||||
使用 LibreOffice 将 office 文件转为 PDF
|
||||
@@ -909,9 +968,13 @@ def preview_file_raw():
|
||||
'htm': 'text/html',
|
||||
}
|
||||
if ext == 'pdf' and not content.startswith(b'%PDF-'):
|
||||
return jsonify({'error': 'upstream did not return a valid pdf binary'}), 422
|
||||
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 = fallback_types.get(ext) or content_type or 'application/octet-stream'
|
||||
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"}'
|
||||
|
||||
@@ -69,6 +69,20 @@ def delete_schedule(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
return jsonify({'error': 'Not found'}), 404
|
||||
|
||||
from app.services.schedule.scheduler_service import request_cancel_run
|
||||
running_runs = db.session.query(ScheduleRun).filter(
|
||||
ScheduleRun.schedule_task_id == task_id,
|
||||
ScheduleRun.status == "running",
|
||||
).all()
|
||||
for rr in running_runs:
|
||||
request_cancel_run(rr.id)
|
||||
rr.status = "failed"
|
||||
rr.error_message = "排程已被删除,执行中断"
|
||||
rr.finished_at = datetime.utcnow()
|
||||
if running_runs:
|
||||
db.session.commit()
|
||||
|
||||
runs = db.session.query(ScheduleRun).filter(ScheduleRun.schedule_task_id == task_id).all()
|
||||
for r in runs:
|
||||
if r.excel_file_path:
|
||||
@@ -122,6 +136,13 @@ def run_schedule(task_id: int):
|
||||
return jsonify({'error': 'Not found'}), 404
|
||||
user = get_current_user()
|
||||
|
||||
existing = db.session.query(ScheduleRun).filter(
|
||||
ScheduleRun.schedule_task_id == task.id,
|
||||
ScheduleRun.status == "running",
|
||||
).first()
|
||||
if existing:
|
||||
return jsonify({'error': '该排程正在执行中,请等待完成后再试', 'run_id': existing.id}), 409
|
||||
|
||||
run = ScheduleRun(
|
||||
run_no=_generate_run_no(),
|
||||
schedule_task_id=task.id,
|
||||
|
||||
@@ -182,8 +182,9 @@ class DifyService:
|
||||
result = evt.get("data") or {}
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[workflow-streaming] finished status=%s",
|
||||
"[workflow-streaming] finished status=%s error=%s",
|
||||
result.get("status"),
|
||||
result.get("error"),
|
||||
)
|
||||
|
||||
elif event_type == "error":
|
||||
|
||||
@@ -14,6 +14,32 @@ from app.config import Config
|
||||
class IntegrationApiService:
|
||||
_cache: Dict[Tuple[str, str], Dict[str, Any]] = {}
|
||||
|
||||
@staticmethod
|
||||
def _normalize_batch_row(row: Dict[str, Any]) -> Optional[Tuple[Tuple[str, str], Dict[str, Any]]]:
|
||||
if not isinstance(row, dict):
|
||||
return None
|
||||
req = row.get("request") if isinstance(row.get("request"), dict) else {}
|
||||
dataset_id = str(req.get("dataset_id") or "").strip()
|
||||
remote_document_id = str(req.get("remote_document_id") or "").strip()
|
||||
if not dataset_id or not remote_document_id or not row.get("found"):
|
||||
return None
|
||||
|
||||
doc = row.get("document") if isinstance(row.get("document"), dict) else {}
|
||||
source_url = doc.get("source_download_url")
|
||||
if not source_url:
|
||||
return None
|
||||
|
||||
normalized = {
|
||||
"source_download_url": source_url,
|
||||
"source_filename": doc.get("source_filename"),
|
||||
"source_ext": doc.get("source_ext"),
|
||||
"download_url_expires_at": doc.get("download_url_expires_at"),
|
||||
"version_id": doc.get("version_id"),
|
||||
"document_id": doc.get("document_id"),
|
||||
}
|
||||
key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
|
||||
return key, normalized
|
||||
|
||||
@staticmethod
|
||||
def _is_loopback_url(url: str) -> bool:
|
||||
host = (urlparse(str(url or "").strip()).hostname or "").strip().lower()
|
||||
@@ -37,14 +63,13 @@ class IntegrationApiService:
|
||||
configured = str(Config.INTEGRATION_API_BASE or "").strip().rstrip("/")
|
||||
public_base = ""
|
||||
|
||||
# For server-side lookups, always prefer the explicitly configured
|
||||
# integration service endpoint when present. Falling back to the current
|
||||
# request host would incorrectly call this backend itself.
|
||||
if configured:
|
||||
return configured
|
||||
|
||||
if mode != "external":
|
||||
# For server-side lookups inside containers/workers, an explicit integration
|
||||
# endpoint is more reliable than a public loopback URL like 127.0.0.1:5002.
|
||||
if configured and (
|
||||
not has_request_context()
|
||||
or IntegrationApiService._is_loopback_url(public_base)
|
||||
):
|
||||
return configured
|
||||
if public_base:
|
||||
return public_base
|
||||
if has_request_context():
|
||||
@@ -113,16 +138,55 @@ class IntegrationApiService:
|
||||
|
||||
try:
|
||||
resp = requests.get(url, headers=headers, params=params, timeout=(4, 8))
|
||||
if resp.status_code != 200:
|
||||
return None
|
||||
payload = resp.json()
|
||||
if not isinstance(payload, dict):
|
||||
return None
|
||||
IntegrationApiService._cache[cache_key] = payload
|
||||
return payload
|
||||
if resp.status_code == 200:
|
||||
payload = resp.json()
|
||||
if isinstance(payload, dict):
|
||||
IntegrationApiService._cache[cache_key] = payload
|
||||
return payload
|
||||
elif has_app_context():
|
||||
current_app.logger.info(
|
||||
"Integration API single lookup missed, falling back to batch resolve: dataset_id=%s remote_document_id=%s status=%s",
|
||||
dataset_id,
|
||||
remote_document_id,
|
||||
resp.status_code,
|
||||
)
|
||||
except Exception as e:
|
||||
if has_app_context():
|
||||
current_app.logger.warning(f"Integration API lookup failed: {e}")
|
||||
|
||||
batch_url = f"{base_url}/api/integration/dify-files/resolve"
|
||||
batch_headers = {
|
||||
"X-Integration-Key": api_key,
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
batch_body = {
|
||||
"items": [
|
||||
{
|
||||
"dataset_id": str(dataset_id),
|
||||
"remote_document_id": str(remote_document_id),
|
||||
}
|
||||
]
|
||||
}
|
||||
try:
|
||||
resp = requests.post(batch_url, headers=batch_headers, json=batch_body, timeout=(5, 12))
|
||||
if resp.status_code != 200:
|
||||
return None
|
||||
payload = resp.json()
|
||||
data = payload.get("data") if isinstance(payload, dict) else None
|
||||
if not isinstance(data, list):
|
||||
return None
|
||||
for row in data:
|
||||
normalized_row = IntegrationApiService._normalize_batch_row(row)
|
||||
if not normalized_row:
|
||||
continue
|
||||
key, normalized = normalized_row
|
||||
IntegrationApiService._cache[key] = normalized
|
||||
if key == cache_key:
|
||||
return normalized
|
||||
return None
|
||||
except Exception as e:
|
||||
if has_app_context():
|
||||
current_app.logger.warning(f"Integration API batch fallback lookup failed: {e}")
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
@@ -199,28 +263,10 @@ class IntegrationApiService:
|
||||
for row in data:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
req = row.get("request") if isinstance(row.get("request"), dict) else {}
|
||||
dataset_id = str(req.get("dataset_id") or "").strip()
|
||||
remote_document_id = str(req.get("remote_document_id") or "").strip()
|
||||
if not dataset_id or not remote_document_id:
|
||||
normalized_row = IntegrationApiService._normalize_batch_row(row)
|
||||
if not normalized_row:
|
||||
continue
|
||||
if not row.get("found"):
|
||||
continue
|
||||
|
||||
doc = row.get("document") if isinstance(row.get("document"), dict) else {}
|
||||
source_url = doc.get("source_download_url")
|
||||
if not source_url:
|
||||
continue
|
||||
|
||||
normalized = {
|
||||
"source_download_url": source_url,
|
||||
"source_filename": doc.get("source_filename"),
|
||||
"source_ext": doc.get("source_ext"),
|
||||
"download_url_expires_at": doc.get("download_url_expires_at"),
|
||||
"version_id": doc.get("version_id"),
|
||||
"document_id": doc.get("document_id"),
|
||||
}
|
||||
key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
|
||||
key, normalized = normalized_row
|
||||
IntegrationApiService._cache[key] = normalized
|
||||
results[key] = normalized
|
||||
|
||||
|
||||
@@ -3,6 +3,8 @@ import os
|
||||
import re
|
||||
import time
|
||||
from datetime import datetime
|
||||
from html import escape
|
||||
from urllib.parse import quote
|
||||
|
||||
from flask import current_app
|
||||
|
||||
@@ -13,6 +15,8 @@ from app.services.text2sql import Text2SQLService
|
||||
class PLMOracleService:
|
||||
_ALLOWED_AGENT_NAMES = {"通用入口", "生产sop"}
|
||||
_MAX_RESULT_ROWS = 50
|
||||
_PLM_PREVIEW_SHARE_ROOT = (os.getenv("PLM_PREVIEW_SHARE_ROOT") or "\\\\192.168.0.11\\dss\\dssroot\\").strip()
|
||||
_SUMMARY_COLUMNS = ("NAME", "EXTENTIONNAME", "FILETYPE", "FILESIZE", "RELATIVEPATH", "LASTACCESSTIME")
|
||||
_MATERIAL_PATTERN = re.compile(r"\b[A-Z0-9]+(?:-[A-Z0-9]+)+\b", re.IGNORECASE)
|
||||
_EXPLICIT_LABEL_PATTERN = re.compile(
|
||||
r"(?:料号|料號|物料料号|物料料號|物料编号|物料編號|part\s*(?:no|number)?)\s*[::]?\s*([A-Z0-9][A-Z0-9._-]{5,})",
|
||||
@@ -184,6 +188,114 @@ select *
|
||||
return f"{size / 1024:.1f} KB"
|
||||
return f"{size / 1024 / 1024:.2f} MB"
|
||||
|
||||
@classmethod
|
||||
def _build_plm_share_path(cls, storage_id, file_path, file_id: str) -> str:
|
||||
parts = [cls._PLM_PREVIEW_SHARE_ROOT.rstrip("\\/")]
|
||||
for value in (storage_id, file_path, file_id):
|
||||
text = str(value or "").strip()
|
||||
if not text:
|
||||
continue
|
||||
parts.append(text.replace("/", "\\").strip("\\"))
|
||||
return "\\".join(part for part in parts if part)
|
||||
|
||||
@classmethod
|
||||
def _render_file_name(cls, row: tuple, index_map: dict[str, int]) -> str:
|
||||
def raw(column_name: str):
|
||||
idx = index_map.get(column_name.upper())
|
||||
if idx is None or idx >= len(row):
|
||||
return None
|
||||
value = row[idx]
|
||||
return None if value in (None, "") else value
|
||||
|
||||
file_name = str(raw("NAME") or "").strip()
|
||||
if not file_name:
|
||||
return "-"
|
||||
|
||||
storage_id = raw("STORAGEID")
|
||||
file_path = raw("FILEPATH")
|
||||
file_id = str(raw("ID") or "").strip()
|
||||
if not storage_id or file_path is None or not file_id:
|
||||
return escape(file_name)
|
||||
|
||||
share_path = cls._build_plm_share_path(storage_id, file_path, file_id)
|
||||
preview_href = f"#plm-preview?name={quote(file_name, safe='')}&url={quote(share_path, safe='')}"
|
||||
return f'<a href="{preview_href}">{escape(file_name)}</a>'
|
||||
|
||||
@staticmethod
|
||||
def _escape_markdown_cell(value: str) -> str:
|
||||
return str(value).replace("|", r"\|").replace("\r", " ").replace("\n", "<br>")
|
||||
|
||||
@staticmethod
|
||||
def _escape_html_text(value) -> str:
|
||||
return escape(str(value), quote=True).replace("\r", " ").replace("\n", "<br>")
|
||||
|
||||
@classmethod
|
||||
def _render_column_value(cls, row: tuple, column_name: str, index_map: dict[str, int]) -> str:
|
||||
idx = index_map.get(column_name.upper())
|
||||
if idx is None or idx >= len(row):
|
||||
return "-"
|
||||
value = row[idx]
|
||||
if value in (None, ""):
|
||||
return "-"
|
||||
upper_name = column_name.upper()
|
||||
if upper_name in {"CREATETIME", "LASTACCESSTIME"}:
|
||||
return cls._format_datetime(value)
|
||||
if upper_name == "FILESIZE":
|
||||
return cls._format_size(value)
|
||||
if upper_name == "NAME":
|
||||
return cls._render_file_name(row, index_map)
|
||||
return str(value)
|
||||
|
||||
@classmethod
|
||||
def _build_record_summary(cls, row: tuple, index_map: dict[str, int], row_no: int) -> str:
|
||||
parts = [f"记录 {row_no}"]
|
||||
for column_name in cls._SUMMARY_COLUMNS:
|
||||
if column_name.upper() not in index_map:
|
||||
continue
|
||||
rendered = cls._render_column_value(row, column_name, index_map)
|
||||
label = {
|
||||
"NAME": "文件名",
|
||||
"EXTENTIONNAME": "扩展名",
|
||||
"FILETYPE": "文件类型",
|
||||
"FILESIZE": "文件大小",
|
||||
"RELATIVEPATH": "相对路径",
|
||||
"LASTACCESSTIME": "最后访问时间",
|
||||
}.get(column_name.upper(), column_name)
|
||||
if column_name.upper() == "NAME":
|
||||
parts.append(f"{label}: {rendered}")
|
||||
else:
|
||||
parts.append(f"{label}: {cls._escape_html_text(rendered)}")
|
||||
return " | ".join(parts)
|
||||
|
||||
@classmethod
|
||||
def _build_record_detail_html(cls, row: tuple, columns: list[str], index_map: dict[str, int], row_no: int) -> str:
|
||||
rows_html = []
|
||||
for column_name in columns:
|
||||
rendered_value = cls._render_column_value(row, column_name, index_map)
|
||||
safe_value = rendered_value if column_name.upper() == "NAME" else cls._escape_html_text(rendered_value)
|
||||
rows_html.append(
|
||||
"<tr>"
|
||||
f"<th style=\"padding:6px 10px;text-align:left;border:1px solid #d1d5db;background:#f8fafc;white-space:nowrap;\">{cls._escape_html_text(column_name)}</th>"
|
||||
f"<td style=\"padding:6px 10px;border:1px solid #d1d5db;word-break:break-all;\">{safe_value}</td>"
|
||||
"</tr>"
|
||||
)
|
||||
|
||||
summary_html = cls._build_record_summary(row, index_map, row_no)
|
||||
return (
|
||||
"<details style=\"margin:12px 0;border:1px solid #e5e7eb;border-radius:8px;padding:8px 12px;background:#ffffff;\">"
|
||||
f"<summary style=\"cursor:pointer;font-weight:600;\">{summary_html}</summary>"
|
||||
"<div style=\"margin-top:10px;overflow:auto;\">"
|
||||
"<table style=\"width:100%;border-collapse:collapse;font-size:13px;\">"
|
||||
"<thead><tr>"
|
||||
"<th style=\"padding:6px 10px;text-align:left;border:1px solid #d1d5db;background:#f1f5f9;width:220px;\">字段</th>"
|
||||
"<th style=\"padding:6px 10px;text-align:left;border:1px solid #d1d5db;background:#f1f5f9;\">值</th>"
|
||||
"</tr></thead>"
|
||||
f"<tbody>{''.join(rows_html)}</tbody>"
|
||||
"</table>"
|
||||
"</div>"
|
||||
"</details>"
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def _build_answer(cls, material_no: str, columns: list[str], rows: list[tuple]) -> str:
|
||||
if not rows:
|
||||
@@ -193,29 +305,14 @@ select *
|
||||
visible_rows = rows[: cls._MAX_RESULT_ROWS]
|
||||
index_map = {name.upper(): idx for idx, name in enumerate(columns)}
|
||||
|
||||
def pick(row: tuple, column_name: str, default: str = "-") -> str:
|
||||
idx = index_map.get(column_name.upper())
|
||||
if idx is None or idx >= len(row):
|
||||
return default
|
||||
value = row[idx]
|
||||
if column_name.upper() in {"CREATETIME", "LASTACCESSTIME"}:
|
||||
return cls._format_datetime(value)
|
||||
if column_name.upper() == "FILESIZE":
|
||||
return cls._format_size(value)
|
||||
return "-" if value in (None, "") else str(value)
|
||||
|
||||
lines = [
|
||||
f"已在 PLM 中查询到料号 `{material_no}` 的相关资料,共返回 {len(visible_rows)} 条记录"
|
||||
+ ("(仅展示前 50 条)" if overflow else "。"),
|
||||
"",
|
||||
"| 序号 | 文件名 | 扩展名 | 文件类型 | 文件大小 | 相对路径 | 最后访问时间 |",
|
||||
"| --- | --- | --- | --- | --- | --- | --- |",
|
||||
"以下结果支持点击单条记录展开,展开后按数据库原始字段顺序展示完整数据:",
|
||||
]
|
||||
for idx, row in enumerate(visible_rows, start=1):
|
||||
lines.append(
|
||||
f"| {idx} | {pick(row, 'NAME')} | {pick(row, 'EXTENTIONNAME')} | {pick(row, 'FILETYPE')} | "
|
||||
f"{pick(row, 'FILESIZE')} | {pick(row, 'RELATIVEPATH')} | {pick(row, 'LASTACCESSTIME')} |"
|
||||
)
|
||||
lines.extend(["", cls._build_record_detail_html(row, columns, index_map, idx)])
|
||||
|
||||
if overflow:
|
||||
lines.extend(["", "如需查看更多结果,请进一步限定料号或资料范围。"])
|
||||
|
||||
@@ -10,7 +10,7 @@ from app import db
|
||||
from app.models import Agent, ScheduleRun, ScheduleTask
|
||||
from app.services.schedule.srm_service import run_rohs_doc_check_dify_job
|
||||
|
||||
ScheduleExecuteResult = tuple[int, int, int, list[dict[str, Any]], list[str]]
|
||||
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str]]
|
||||
ScheduleExecutor = Callable[[ScheduleTask, ScheduleRun], ScheduleExecuteResult]
|
||||
|
||||
|
||||
@@ -71,7 +71,7 @@ def _run_common_executor(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecut
|
||||
total = int(summary.get("total_count") if summary.get("total_count") is not None else (len(details) or 1))
|
||||
success = int(summary.get("success_count") if summary.get("success_count") is not None else total)
|
||||
failed = int(summary.get("failed_count") if summary.get("failed_count") is not None else max(0, total - success))
|
||||
return total, success, failed, details, [str(e) for e in errors if str(e).strip()]
|
||||
return total, success, failed, 0, details, [str(e) for e in errors if str(e).strip()]
|
||||
|
||||
|
||||
def _run_srm_rohs_doc_check_executor(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||
@@ -107,6 +107,7 @@ def _run_srm_rohs_doc_check_executor(task: ScheduleTask, run: ScheduleRun) -> Sc
|
||||
agent=agent,
|
||||
user=str(getattr(task.owner, "username", "") or task.owner_user_id or "schedule_system"),
|
||||
wait_seconds=task.wait_seconds or 120,
|
||||
run_id=run.id,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -1,11 +1,18 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from openpyxl import Workbook
|
||||
|
||||
|
||||
def _flatten_value(v: Any) -> Any:
|
||||
if isinstance(v, (dict, list)):
|
||||
return json.dumps(v, ensure_ascii=False)
|
||||
return v
|
||||
|
||||
|
||||
def export_schedule_result_excel(*, run_no: str, summary: dict, details: list[dict], root_dir: str) -> tuple[str | None, str | None, int]:
|
||||
if not details:
|
||||
return None, None, 0
|
||||
@@ -18,8 +25,8 @@ def export_schedule_result_excel(*, run_no: str, summary: dict, details: list[di
|
||||
output = row.get('dify_output')
|
||||
if not isinstance(output, dict):
|
||||
output = {}
|
||||
entry = dict(output)
|
||||
for k in ('writeback_ok', 'error'):
|
||||
entry = {k: _flatten_value(v) for k, v in output.items()}
|
||||
for k in ('writeback_ok', 'error', 'judgement', 'reason'):
|
||||
if k in row:
|
||||
entry[k] = row[k]
|
||||
rows.append(entry)
|
||||
|
||||
@@ -17,6 +17,23 @@ from app.services.schedule.mail_service import build_schedule_mail_html, send_sc
|
||||
|
||||
_worker_started = False
|
||||
_worker_lock = threading.Lock()
|
||||
_cancelled_runs: set[int] = set()
|
||||
_cancel_lock = threading.Lock()
|
||||
|
||||
|
||||
def request_cancel_run(run_id: int) -> None:
|
||||
with _cancel_lock:
|
||||
_cancelled_runs.add(run_id)
|
||||
|
||||
|
||||
def is_run_cancelled(run_id: int) -> bool:
|
||||
with _cancel_lock:
|
||||
return run_id in _cancelled_runs
|
||||
|
||||
|
||||
def clear_cancelled_run(run_id: int) -> None:
|
||||
with _cancel_lock:
|
||||
_cancelled_runs.discard(run_id)
|
||||
|
||||
|
||||
def _generate_schedule_no() -> str:
|
||||
@@ -108,6 +125,12 @@ def update_task(task: ScheduleTask, *, payload: dict[str, Any], actor_id: int |
|
||||
|
||||
def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id: int | None, run: ScheduleRun | None = None) -> ScheduleRun:
|
||||
if run is None:
|
||||
existing = db.session.query(ScheduleRun).filter(
|
||||
ScheduleRun.schedule_task_id == task.id,
|
||||
ScheduleRun.status == "running",
|
||||
).first()
|
||||
if existing:
|
||||
return existing
|
||||
run = ScheduleRun(
|
||||
run_no=_generate_run_no(),
|
||||
schedule_task_id=task.id,
|
||||
@@ -130,19 +153,36 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
|
||||
start_ts = time.time()
|
||||
try:
|
||||
executor = resolve_schedule_executor(task)
|
||||
total_count, success_count, failed_count, details, errors = executor(task, run)
|
||||
total_count, success_count, failed_count, skipped_count, details, errors = executor(task, run)
|
||||
except Exception as exc:
|
||||
total_count, success_count, failed_count, skipped_count, details, errors = 0, 0, 0, 0, [], [str(exc)]
|
||||
|
||||
duration_ms = int((time.time() - start_ts) * 1000)
|
||||
if total_count == 0 and not errors:
|
||||
status = "success"
|
||||
run.error_message = "无待处理数据"
|
||||
elif failed_count == 0:
|
||||
status = "success"
|
||||
elif success_count == 0:
|
||||
status = "failed"
|
||||
else:
|
||||
status = "partial_failed"
|
||||
if is_run_cancelled(run.id):
|
||||
run.finished_at = datetime.utcnow()
|
||||
run.duration_ms = int((time.time() - start_ts) * 1000)
|
||||
run.status = "failed"
|
||||
run.error_message = "排程已被删除,执行中断"
|
||||
db.session.commit()
|
||||
clear_cancelled_run(run.id)
|
||||
return run
|
||||
|
||||
duration_ms = int((time.time() - start_ts) * 1000)
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[schedule-run] run_no=%s total=%d success=%d failed=%d skipped=%d errors=%d",
|
||||
run.run_no, total_count, success_count, failed_count, skipped_count, len(errors),
|
||||
)
|
||||
if total_count == 0 and not errors:
|
||||
status = "success"
|
||||
run.error_message = "无待处理数据"
|
||||
elif failed_count == 0:
|
||||
status = "success"
|
||||
elif success_count == 0:
|
||||
status = "failed"
|
||||
else:
|
||||
status = "partial_failed"
|
||||
|
||||
try:
|
||||
file_path, file_name, file_size = export_schedule_result_excel(
|
||||
run_no=run.run_no,
|
||||
summary={
|
||||
@@ -155,24 +195,30 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
|
||||
details=details,
|
||||
root_dir=str(current_app.config.get("SCHEDULE_EXCEL_STORAGE_ROOT") or "").strip(),
|
||||
)
|
||||
except Exception as excel_exc:
|
||||
if current_app:
|
||||
current_app.logger.error("[schedule-run] excel export failed: %s", excel_exc)
|
||||
file_path, file_name, file_size = None, None, 0
|
||||
errors.append(f"Excel导出失败: {excel_exc}")
|
||||
|
||||
run.finished_at = datetime.utcnow()
|
||||
run.duration_ms = duration_ms
|
||||
run.status = status
|
||||
run.total_count = total_count
|
||||
run.success_count = success_count
|
||||
run.failed_count = failed_count
|
||||
run.skipped_count = 0
|
||||
run.response_summary_json = {
|
||||
"errors": errors[:20],
|
||||
"schedule_type": task.schedule_type,
|
||||
"platform_api_path": task.platform_api_path,
|
||||
}
|
||||
run.error_message = "; ".join(errors[:3]) if errors else None
|
||||
run.excel_file_path = file_path
|
||||
run.excel_file_name = file_name
|
||||
run.excel_file_size = file_size or 0
|
||||
run.finished_at = datetime.utcnow()
|
||||
run.duration_ms = duration_ms
|
||||
run.status = status
|
||||
run.total_count = total_count
|
||||
run.success_count = success_count
|
||||
run.failed_count = failed_count
|
||||
run.skipped_count = skipped_count
|
||||
run.response_summary_json = {
|
||||
"errors": errors[:20],
|
||||
"schedule_type": task.schedule_type,
|
||||
"platform_api_path": task.platform_api_path,
|
||||
}
|
||||
run.error_message = "; ".join(errors[:3]) if errors else None
|
||||
run.excel_file_path = file_path
|
||||
run.excel_file_name = file_name
|
||||
run.excel_file_size = file_size or 0
|
||||
|
||||
try:
|
||||
if task.notify_enabled:
|
||||
users = db.session.query(User).filter(User.id.in_(task.notify_user_ids_json or [])).all()
|
||||
to_addrs = [u.email for u in users if u.email]
|
||||
@@ -201,17 +247,13 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
|
||||
except Exception as mail_exc:
|
||||
run.mail_sent = False
|
||||
run.mail_error = str(mail_exc)
|
||||
except Exception as mail_exc:
|
||||
if current_app:
|
||||
current_app.logger.error("[schedule-run] mail send failed: %s", mail_exc)
|
||||
|
||||
task.last_run_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
return run
|
||||
except Exception as exc:
|
||||
run.finished_at = datetime.utcnow()
|
||||
run.duration_ms = int((time.time() - start_ts) * 1000)
|
||||
run.status = "failed"
|
||||
run.error_message = str(exc)
|
||||
db.session.commit()
|
||||
return run
|
||||
task.last_run_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
return run
|
||||
|
||||
|
||||
def start_scheduler(app):
|
||||
@@ -233,6 +275,36 @@ def start_scheduler(app):
|
||||
|
||||
def _loop():
|
||||
with app.app_context():
|
||||
stale = db.session.query(ScheduleTask).filter(
|
||||
ScheduleTask.enabled.is_(True),
|
||||
ScheduleTask.next_run_at.isnot(None),
|
||||
ScheduleTask.next_run_at <= datetime.utcnow(),
|
||||
).all()
|
||||
for t in stale:
|
||||
if t.cron_expr:
|
||||
try:
|
||||
it = croniter(t.cron_expr, datetime.utcnow())
|
||||
t.next_run_at = it.get_next(datetime)
|
||||
except Exception:
|
||||
t.next_run_at = None
|
||||
t.enabled = False
|
||||
else:
|
||||
t.next_run_at = None
|
||||
if stale:
|
||||
db.session.commit()
|
||||
current_app.logger.info("[schedule-worker] reset %d stale next_run_at on startup", len(stale))
|
||||
|
||||
stuck = db.session.query(ScheduleRun).filter(
|
||||
ScheduleRun.status == "running",
|
||||
).all()
|
||||
for r in stuck:
|
||||
r.status = "failed"
|
||||
r.error_message = "服务重启,执行中断"
|
||||
r.finished_at = datetime.utcnow()
|
||||
if stuck:
|
||||
db.session.commit()
|
||||
current_app.logger.info("[schedule-worker] cleaned %d stuck running runs on startup", len(stuck))
|
||||
|
||||
while True:
|
||||
try:
|
||||
now = datetime.utcnow()
|
||||
@@ -242,6 +314,19 @@ def start_scheduler(app):
|
||||
ScheduleTask.next_run_at <= now,
|
||||
).limit(5).with_for_update(skip_locked=True).all()
|
||||
for task in due_tasks:
|
||||
has_running = db.session.query(ScheduleRun).filter(
|
||||
ScheduleRun.schedule_task_id == task.id,
|
||||
ScheduleRun.status == "running",
|
||||
).first()
|
||||
if has_running:
|
||||
if task.cron_expr:
|
||||
try:
|
||||
iter = croniter(task.cron_expr, datetime.utcnow())
|
||||
task.next_run_at = iter.get_next(datetime)
|
||||
except Exception:
|
||||
task.next_run_at = None
|
||||
db.session.commit()
|
||||
continue
|
||||
try:
|
||||
run_task_now(task, trigger_type="cron", triggered_by_user_id=None)
|
||||
except Exception as e:
|
||||
|
||||
@@ -88,7 +88,7 @@ def _derive_judgement_and_reason(data: dict[str, Any]) -> tuple[str, str]:
|
||||
return judgement, reason
|
||||
|
||||
|
||||
def run_rohs_doc_check_dify_job(*, conn_str: str, run_no: str, agent=None, user: str = "schedule_system", wait_seconds: int = 120) -> tuple[int, int, int, list[dict[str, Any]], list[str]]:
|
||||
def run_rohs_doc_check_dify_job(*, conn_str: str, run_no: str, agent=None, user: str = "schedule_system", wait_seconds: int = 120, run_id: int | None = None) -> tuple[int, int, int, int, list[dict[str, Any]], list[str]]:
|
||||
use_dify = agent is not None
|
||||
if use_dify and not getattr(agent, "dify_api_key", None):
|
||||
raise RuntimeError("dify_agent_id is set, but Dify api key is missing")
|
||||
@@ -98,10 +98,19 @@ def run_rohs_doc_check_dify_job(*, conn_str: str, run_no: str, agent=None, user:
|
||||
details: list[dict[str, Any]] = []
|
||||
success_count = 0
|
||||
failed_count = 0
|
||||
skipped_count = 0
|
||||
errors: list[str] = []
|
||||
|
||||
for row in rows:
|
||||
from app.services.schedule.scheduler_service import is_run_cancelled
|
||||
for idx, row in enumerate(rows):
|
||||
if run_id is not None and is_run_cancelled(run_id):
|
||||
item = dict(row)
|
||||
item.update({"judgement": "人工判定", "reason": "排程已被删除,执行中断", "writeback_ok": False, "error": "排程已被删除,执行中断"})
|
||||
skipped_count += 1
|
||||
details.append(item)
|
||||
continue
|
||||
item = dict(row)
|
||||
dify_ok = False
|
||||
try:
|
||||
if use_dify:
|
||||
dify_res = DifyService.run_workflow_streaming(
|
||||
@@ -110,18 +119,30 @@ def run_rohs_doc_check_dify_job(*, conn_str: str, run_no: str, agent=None, user:
|
||||
user=user,
|
||||
timeout=(5, max(300, int(wait_seconds))),
|
||||
)
|
||||
outputs = (dify_res.get("outputs") or {}).get("output") or dify_res.get("outputs") or dify_res
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[srm-dify] judgement=%s reason=%s",
|
||||
outputs.get("judgement") if isinstance(outputs, dict) else None,
|
||||
outputs.get("reason") if isinstance(outputs, dict) else None,
|
||||
)
|
||||
judgement, reason = _derive_judgement_and_reason(outputs if isinstance(outputs, dict) else {})
|
||||
item["dify_output"] = outputs if isinstance(outputs, dict) else {}
|
||||
dify_status = dify_res.get("status") if isinstance(dify_res, dict) else None
|
||||
dify_error = dify_res.get("error") if isinstance(dify_res, dict) else None
|
||||
if dify_status == "failed" or (dify_error and not dify_res.get("outputs")):
|
||||
err_detail = str(dify_error) if dify_error else f"Dify status={dify_status}"
|
||||
judgement = "人工判定"
|
||||
reason = f"Dify执行失败:{err_detail}"
|
||||
item.update({"judgement": judgement, "reason": reason, "writeback_ok": False, "error": err_detail, "dify_output": dify_res if isinstance(dify_res, dict) else {}})
|
||||
failed_count += 1
|
||||
errors.append(f"Dify row_id={row.get('id')}: {err_detail}")
|
||||
else:
|
||||
outputs = (dify_res.get("outputs") or {}).get("output") or dify_res.get("outputs") or dify_res
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[srm-dify] judgement=%s reason=%s",
|
||||
outputs.get("judgement") if isinstance(outputs, dict) else None,
|
||||
outputs.get("reason") if isinstance(outputs, dict) else None,
|
||||
)
|
||||
judgement, reason = _derive_judgement_and_reason(outputs if isinstance(outputs, dict) else {})
|
||||
item["dify_output"] = outputs if isinstance(outputs, dict) else {}
|
||||
dify_ok = True
|
||||
else:
|
||||
judgement = "人工判定"
|
||||
reason = "未配置 Agent ID,跳过 Dify"
|
||||
dify_ok = True
|
||||
|
||||
try:
|
||||
writeback_rohs(
|
||||
@@ -131,18 +152,35 @@ def run_rohs_doc_check_dify_job(*, conn_str: str, run_no: str, agent=None, user:
|
||||
judgement=judgement,
|
||||
reason=reason,
|
||||
)
|
||||
item.update({"judgement": judgement, "reason": reason, "writeback_ok": True, "error": None})
|
||||
success_count += 1
|
||||
item.update({"judgement": judgement, "reason": reason, "writeback_ok": True, "error": item.get("error")})
|
||||
if dify_ok:
|
||||
success_count += 1
|
||||
except Exception as wb_exc:
|
||||
if current_app:
|
||||
current_app.logger.error("[srm-dify] writeback failed row_id=%s error=%s", row.get("id"), wb_exc)
|
||||
item.update({"judgement": judgement, "reason": reason, "writeback_ok": False, "error": str(wb_exc)})
|
||||
failed_count += 1
|
||||
if dify_ok:
|
||||
failed_count += 1
|
||||
errors.append(f"writeback row_id={row.get('id')}: {wb_exc}")
|
||||
except Exception as exc:
|
||||
item.update({"judgement": "人工判定", "reason": f"执行异常:{exc}", "writeback_ok": False, "error": str(exc)})
|
||||
judgement = "人工判定"
|
||||
reason = f"执行异常:{exc}"
|
||||
item.update({"judgement": judgement, "reason": reason, "writeback_ok": False, "error": str(exc)})
|
||||
failed_count += 1
|
||||
errors.append(str(exc))
|
||||
try:
|
||||
writeback_rohs(
|
||||
conn_str,
|
||||
row_id=str(row.get("id")),
|
||||
run_no=run_no,
|
||||
judgement=judgement,
|
||||
reason=reason,
|
||||
)
|
||||
item["writeback_ok"] = True
|
||||
except Exception as wb_exc:
|
||||
item["writeback_ok"] = False
|
||||
item["error"] = f"{item.get('error', '')}; writeback failed: {wb_exc}"
|
||||
details.append(item)
|
||||
|
||||
return total_count, success_count, failed_count, details, errors
|
||||
total_count = success_count + failed_count + skipped_count
|
||||
return total_count, success_count, failed_count, skipped_count, details, errors
|
||||
Vendored
+4
@@ -10,7 +10,11 @@
|
||||
<meta name="apple-mobile-web-app-title" content="AI工作台" />
|
||||
<link rel="manifest" href="/manifest.webmanifest" />
|
||||
<title>AI工作台</title>
|
||||
<<<<<<< HEAD
|
||||
<script type="module" crossorigin src="/assets/index-CSfNFoqX.js"></script>
|
||||
=======
|
||||
<script type="module" crossorigin src="/assets/index-B0LSqDmY.js"></script>
|
||||
>>>>>>> dev
|
||||
<link rel="stylesheet" crossorigin href="/assets/index-XvG2TD5m.css">
|
||||
</head>
|
||||
<body>
|
||||
|
||||
@@ -34,7 +34,7 @@ export interface ScheduleRun {
|
||||
total_count: number;
|
||||
success_count: number;
|
||||
failed_count: number;
|
||||
skipped_count: number;
|
||||
|
||||
api_request_json?: Record<string, any> | null;
|
||||
api_response_json?: Record<string, any> | null;
|
||||
response_summary_json?: Record<string, any> | null;
|
||||
|
||||
@@ -93,7 +93,9 @@ const needsOfficeFallback = computed(() => {
|
||||
* - 其余返回原始 URL,由浏览器自行处理。
|
||||
*/
|
||||
const iframeSrc = computed(() => {
|
||||
if (!props.file?.url || !props.agentId) return '';
|
||||
if (!props.file?.url) return '';
|
||||
if (officeObjectUrl.value) return officeObjectUrl.value;
|
||||
if (!props.agentId) return '';
|
||||
if (['pdf', 'doc', 'ppt', 'pptx'].includes(ext.value)) {
|
||||
// These formats must use the authenticated fetch -> blob flow only.
|
||||
// Never fallback to a protected iframe URL, otherwise it returns Unauthorized.
|
||||
@@ -102,6 +104,8 @@ const iframeSrc = computed(() => {
|
||||
return props.file.url;
|
||||
});
|
||||
|
||||
const imageSrc = computed(() => officeObjectUrl.value || props.file?.url || '');
|
||||
|
||||
const close = () => emit('update:modelValue', false);
|
||||
|
||||
const isDownloading = ref(false);
|
||||
@@ -198,19 +202,34 @@ const loadPdfContent = async () => {
|
||||
throw new Error(err?.error || `HTTP ${res.status}`);
|
||||
}
|
||||
|
||||
const buf = await res.arrayBuffer();
|
||||
// const head = new TextDecoder().decode(buf.slice(0, 5));
|
||||
// 暂时取消对 PDF header 的强校验,因为 docx 等文件也会调用该函数生成 Blob 并渲染在 iframe 或下载中
|
||||
// if (head !== '%PDF-') {
|
||||
// throw new Error('Invalid PDF binary from preview API');
|
||||
// }
|
||||
|
||||
const blob = await res.blob();
|
||||
clearOfficeObjectUrl();
|
||||
let type = 'application/octet-stream';
|
||||
if (ext.value === 'pdf' || ['doc', 'ppt', 'pptx'].includes(ext.value)) type = 'application/pdf';
|
||||
else if (ext.value === 'docx') type = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
|
||||
let fallbackType = 'application/octet-stream';
|
||||
if (ext.value === 'pdf' || ['doc', 'ppt', 'pptx'].includes(ext.value)) fallbackType = 'application/pdf';
|
||||
else if (ext.value === 'docx') fallbackType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
|
||||
const effectiveBlob = blob.type ? blob : new Blob([blob], { type: fallbackType });
|
||||
officeObjectUrl.value = URL.createObjectURL(effectiveBlob);
|
||||
};
|
||||
|
||||
const blob = new Blob([buf], { type });
|
||||
const loadBinaryContent = async () => {
|
||||
if (!props.file?.url) return;
|
||||
if (!props.agentId) throw new Error('agent_id is required for binary preview');
|
||||
|
||||
const params = new URLSearchParams({
|
||||
agent_id: String(props.agentId),
|
||||
url: props.file.url,
|
||||
name: props.file.name || '',
|
||||
});
|
||||
const res = await fetch(`/api/chat/preview-file-raw?${params.toString()}`, {
|
||||
headers: props.authHeaders || {},
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({}));
|
||||
throw new Error(err?.error || `HTTP ${res.status}`);
|
||||
}
|
||||
|
||||
const blob = await res.blob();
|
||||
clearOfficeObjectUrl();
|
||||
officeObjectUrl.value = URL.createObjectURL(blob);
|
||||
};
|
||||
|
||||
@@ -297,6 +316,20 @@ const loadContent = async () => {
|
||||
return;
|
||||
}
|
||||
|
||||
if (preferredMode.value === 'image' || (preferredMode.value === 'iframe' && !/^https?:\/\//i.test(props.file.url || ''))) {
|
||||
isLoading.value = true;
|
||||
try {
|
||||
await loadBinaryContent();
|
||||
resolvedMode.value = preferredMode.value === 'image' ? 'image' : 'iframe';
|
||||
} catch (e: any) {
|
||||
error.value = e?.message || 'Failed to load file preview';
|
||||
resolvedMode.value = preferredMode.value === 'image' ? 'image' : 'iframe';
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (preferredMode.value !== 'markdown') return;
|
||||
|
||||
isLoading.value = true;
|
||||
@@ -435,7 +468,7 @@ watch(
|
||||
/>
|
||||
</div>
|
||||
<div v-else-if="resolvedMode === 'image'" class="h-full flex items-center justify-center bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-700 rounded-lg p-2">
|
||||
<img :src="file.url" :alt="file.name" class="max-w-full max-h-full object-contain" />
|
||||
<img :src="imageSrc" :alt="file.name" class="max-w-full max-h-full object-contain" />
|
||||
</div>
|
||||
<div
|
||||
v-else-if="['pdf', 'doc', 'ppt', 'pptx'].includes(ext) && officeObjectUrl"
|
||||
|
||||
@@ -40,7 +40,7 @@ const normalizeResources = (resources: any): RetrieverResource[] => {
|
||||
return [];
|
||||
};
|
||||
|
||||
// 将检索来源资源合并到消息中,并按文档名+片段ID+内容做去重
|
||||
// 将检索来源资源合并到消息中,并按文档名+片段ID+内容做去重和更新
|
||||
const addRetrieverResources = (msg: ChatMessage, resources: any) => {
|
||||
const list = normalizeResources(resources);
|
||||
if (list.length === 0) return;
|
||||
@@ -48,11 +48,17 @@ const addRetrieverResources = (msg: ChatMessage, resources: any) => {
|
||||
for (const item of list) {
|
||||
// 使用稳定键进行去重,避免同一条来源在多事件中重复展示
|
||||
const key = `${item.document_name || ''}|${item.segment_id || ''}|${item.content || ''}`;
|
||||
const exists = msg.retriever_resources.some(
|
||||
const existingIndex = msg.retriever_resources.findIndex(
|
||||
(r) => `${r.document_name || ''}|${r.segment_id || ''}|${r.content || ''}` === key
|
||||
);
|
||||
if (!exists) {
|
||||
if (existingIndex < 0) {
|
||||
msg.retriever_resources.push(item);
|
||||
} else {
|
||||
// 存在则合并,确保后续带有 enrich 链接的字段能覆盖进去
|
||||
msg.retriever_resources[existingIndex] = {
|
||||
...msg.retriever_resources[existingIndex],
|
||||
...item
|
||||
};
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -62,12 +62,12 @@ const sidebarItems = computed(() => {
|
||||
{ id: 'users', icon: UserCog, label: t('admin.nav.users') },
|
||||
{ id: 'departments', icon: Building, label: t('admin.nav.departments') },
|
||||
{ id: 'agents', icon: Bot, label: t('admin.nav.agents') },
|
||||
{ id: 'schedules', icon: Settings2, label: '排程管理' },
|
||||
{ id: 'announcements', icon: Megaphone, label: t('admin.nav.announcements') },
|
||||
{ id: 'questions', icon: MessageCircleQuestion, label: t('admin.nav.questions') },
|
||||
{ id: 'wecom', icon: Link2, label: t('admin.nav.wecom') },
|
||||
{ id: 'permissions', icon: Users, label: t('admin.nav.permissions') },
|
||||
{ id: 'requests', icon: ShieldCheck, label: t('admin.nav.requests'), badge: permissionRequests.value.filter(r => r.status === 'pending').length },
|
||||
{ id: 'schedules', icon: Settings2, label: '排程管理' },
|
||||
];
|
||||
|
||||
return items.filter(item => {
|
||||
@@ -800,7 +800,12 @@ const backToScheduleOverview = () => {
|
||||
};
|
||||
|
||||
const runScheduleNow = async (taskId: number) => {
|
||||
await runAdminSchedule(taskId);
|
||||
const res = await runAdminSchedule(taskId);
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
showMessageDialog('error', data?.error || '手动执行失败');
|
||||
return;
|
||||
}
|
||||
await viewScheduleRuns(taskId);
|
||||
await loadSchedules();
|
||||
|
||||
@@ -4155,12 +4160,19 @@ const handlePermissionImport = async (event: Event) => {
|
||||
:class="getScheduleRunStatusBadge(r.status).cls">
|
||||
{{ getScheduleRunStatusBadge(r.status).label }}
|
||||
</span>
|
||||
<span v-if="r.error_message" class="ml-1 text-xs text-slate-400" :title="r.error_message">...</span>
|
||||
</td>
|
||||
<td class="px-4 py-3">{{ r.total_count }}</td>
|
||||
<td class="px-4 py-3">{{ r.success_count }}</td>
|
||||
<td class="px-4 py-3">{{ r.failed_count }}</td>
|
||||
<td class="px-4 py-3">
|
||||
<a v-if="r.total_count > 0" class="cursor-pointer text-brand-600 hover:text-brand-700 hover:underline" @click.prevent="downloadScheduleExcel(r.id)">
|
||||
<a
|
||||
v-if="r.total_count > 0"
|
||||
href="#"
|
||||
@click.prevent="downloadScheduleExcel(r.id)"
|
||||
class="inline-flex items-center gap-1 rounded-lg border border-slate-200 px-2 py-1 text-xs font-medium text-slate-600 transition-colors hover:bg-slate-50"
|
||||
>
|
||||
<Download class="h-3 w-3" />
|
||||
下载
|
||||
</a>
|
||||
<span v-else class="text-slate-300">-</span>
|
||||
|
||||
+175
-29
@@ -143,7 +143,9 @@ const getSourceBrief = (item: any) => {
|
||||
|
||||
interface SourceFileLink {
|
||||
name: string;
|
||||
url: string;
|
||||
url?: string;
|
||||
datasetId?: string;
|
||||
remoteDocumentId?: string;
|
||||
}
|
||||
|
||||
// 源文件展示配置(来自 config.ts)
|
||||
@@ -208,15 +210,18 @@ const isPreferredSourceLink = (url: string) => {
|
||||
return PREFERRED_SOURCE_EXTS.has(ext);
|
||||
};
|
||||
|
||||
const isNoisySourceUrl = (url: string) => {
|
||||
const isNoisySourceUrl = (_url: string) => {
|
||||
// 带签名参数的下载链接在 UI 中可读性差(如 download?version_id=...&token=...)。
|
||||
return /(?:^|\/)download\?/i.test(url) || /[?&](token|version_id|kind)=/i.test(url);
|
||||
// 暂时注释掉这段校验逻辑,保证有元数据能被展示出来
|
||||
// return /(?:^|\/)download\?/i.test(url) || /[?&](token|version_id|kind)=/i.test(url);
|
||||
return false;
|
||||
};
|
||||
|
||||
const isNoisySourceName = (name: string) => {
|
||||
const isNoisySourceName = (_name: string) => {
|
||||
// 兜底过滤:名称如果本质是查询串而不是文件名,则不展示。
|
||||
const n = (name || '').trim().toLowerCase();
|
||||
return n.startsWith('download?') || n.includes('token=') || n.includes('version_id=');
|
||||
// 注释掉,允许带参数的链接在没有文件名时也可以显示(作为退路)
|
||||
// return n.startsWith('download?') || n.includes('token=') || n.includes('version_id=');
|
||||
return false;
|
||||
};
|
||||
|
||||
const looksLikeFileName = (name: string) => {
|
||||
@@ -226,6 +231,41 @@ const looksLikeFileName = (name: string) => {
|
||||
return /\.[A-Za-z0-9]{2,8}$/.test(n);
|
||||
};
|
||||
|
||||
const findFirstByKeys = (payload: any, keyCandidates: string[]): string => {
|
||||
if (payload == null) return '';
|
||||
if (Array.isArray(payload)) {
|
||||
for (const item of payload) {
|
||||
const found = findFirstByKeys(item, keyCandidates);
|
||||
if (found) return found;
|
||||
}
|
||||
return '';
|
||||
}
|
||||
if (typeof payload !== 'object') return '';
|
||||
for (const key of keyCandidates) {
|
||||
const value = payload?.[key];
|
||||
if (value != null && String(value).trim()) {
|
||||
return String(value).trim();
|
||||
}
|
||||
}
|
||||
for (const value of Object.values(payload)) {
|
||||
const found = findFirstByKeys(value, keyCandidates);
|
||||
if (found) return found;
|
||||
}
|
||||
return '';
|
||||
};
|
||||
|
||||
const getResourceIds = (item: any) => {
|
||||
const datasetId = findFirstByKeys(item, ['dataset_id', 'dify_dataset_id', 'knowledge_base_id', 'kb_id']);
|
||||
const remoteDocumentId = findFirstByKeys(item, [
|
||||
'remote_document_id',
|
||||
'dify_document_id',
|
||||
'document_id',
|
||||
'doc_id',
|
||||
'source_document_id',
|
||||
]);
|
||||
return { datasetId, remoteDocumentId };
|
||||
};
|
||||
|
||||
const isMarkdownFileName = (name: string) => /\.(md|markdown)$/i.test((name || '').trim());
|
||||
|
||||
const isMarkdownByUrl = (url: string) => /\.(md|markdown)(?:$|\?)/i.test((url || '').toLowerCase());
|
||||
@@ -275,7 +315,21 @@ const extractUrlsFromText = (text: string) => {
|
||||
|
||||
const getSourceLinks = (resources: any[] = []): SourceFileLink[] => {
|
||||
const map = new Map<string, SourceFileLink>();
|
||||
const mergeSourceLink = (key: string, nextLink: SourceFileLink) => {
|
||||
const existing = map.get(key);
|
||||
if (!existing) {
|
||||
map.set(key, nextLink);
|
||||
return;
|
||||
}
|
||||
map.set(key, {
|
||||
...existing,
|
||||
...(nextLink.url ? { url: nextLink.url } : {}),
|
||||
...(nextLink.datasetId ? { datasetId: nextLink.datasetId } : {}),
|
||||
...(nextLink.remoteDocumentId ? { remoteDocumentId: nextLink.remoteDocumentId } : {}),
|
||||
});
|
||||
};
|
||||
for (const item of resources) {
|
||||
const { datasetId, remoteDocumentId } = getResourceIds(item);
|
||||
const directCandidates = [
|
||||
item?.source_download_url,
|
||||
item?.url,
|
||||
@@ -290,6 +344,20 @@ const getSourceLinks = (resources: any[] = []): SourceFileLink[] => {
|
||||
].filter(Boolean) as string[];
|
||||
|
||||
const content = getSourceContent(item);
|
||||
// 直接强制从对象的顶层属性里获取文件名和链接
|
||||
const forceName = item?.source_filename || item?.document_name || item?.title;
|
||||
const forceUrl = normalizeUrl(item?.source_download_url || item?.url || '');
|
||||
|
||||
if (forceName) {
|
||||
const key = forceName;
|
||||
mergeSourceLink(key, {
|
||||
name: forceName,
|
||||
...(forceUrl ? { url: forceUrl } : {}),
|
||||
...(datasetId ? { datasetId } : {}),
|
||||
...(remoteDocumentId ? { remoteDocumentId } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
const serialized = JSON.stringify(item || {});
|
||||
const discovered = [
|
||||
...directCandidates.map(normalizeUrl).filter(Boolean),
|
||||
@@ -309,23 +377,29 @@ const getSourceLinks = (resources: any[] = []): SourceFileLink[] => {
|
||||
for (const url of discovered) {
|
||||
if (isChunkLikeLink(url)) continue;
|
||||
// URL 若为噪声签名链接,且没有可用文件名元数据,则跳过。
|
||||
if (isNoisySourceUrl(url) && !item?.source_filename && !item?.document_name) continue;
|
||||
// 这里去掉 isNoisySourceUrl 判断的直接 continue,让有名的链接能过
|
||||
// if (isNoisySourceUrl(url) && !item?.source_filename && !item?.document_name) continue;
|
||||
const name = item?.source_filename || item?.document_name || item?.title || safeDecode(url.split('/').pop() || 'source-file');
|
||||
// Skip links whose display name itself is noisy.
|
||||
if (isNoisySourceName(name)) continue;
|
||||
// 根据配置决定是否显示 MD 文件
|
||||
if ( (isMarkdownFileName(name) || isMarkdownByUrl(url))) continue;
|
||||
if (isMarkdownFileName(name) || isMarkdownByUrl(url)) continue;
|
||||
|
||||
// Deduplicate by name if it looks like a filename, else by name + base URL
|
||||
const key = looksLikeFileName(name) ? name : `${name}|${url.split('?')[0]}`;
|
||||
if (!map.has(key)) {
|
||||
map.set(key, { name, url });
|
||||
}
|
||||
mergeSourceLink(key, {
|
||||
name,
|
||||
url,
|
||||
...(datasetId ? { datasetId } : {}),
|
||||
...(remoteDocumentId ? { remoteDocumentId } : {}),
|
||||
});
|
||||
}
|
||||
}
|
||||
const links = Array.from(map.values());
|
||||
const preferred = links.filter((l) => isPreferredSourceLink(l.url));
|
||||
return preferred.length > 0 ? preferred : links;
|
||||
// 暂时注释掉 isPreferredSourceLink 的过滤,让所有解析出来的气泡都能显示
|
||||
// const preferred = links.filter((l) => isPreferredSourceLink(l.url));
|
||||
// return preferred.length > 0 ? preferred : links;
|
||||
return links;
|
||||
};
|
||||
|
||||
const getMessageLinks = (msg: any): SourceFileLink[] => {
|
||||
@@ -336,19 +410,33 @@ const getMessageLinks = (msg: any): SourceFileLink[] => {
|
||||
const map = new Map<string, SourceFileLink>();
|
||||
|
||||
const merge = (links: SourceFileLink[]) => {
|
||||
const mergeMessageLink = (key: string, nextLink: SourceFileLink) => {
|
||||
const existing = map.get(key);
|
||||
if (!existing) {
|
||||
map.set(key, nextLink);
|
||||
return;
|
||||
}
|
||||
map.set(key, {
|
||||
...existing,
|
||||
...(nextLink.url ? { url: nextLink.url } : {}),
|
||||
...(nextLink.datasetId ? { datasetId: nextLink.datasetId } : {}),
|
||||
...(nextLink.remoteDocumentId ? { remoteDocumentId: nextLink.remoteDocumentId } : {}),
|
||||
});
|
||||
};
|
||||
for (const link of links) {
|
||||
if (isChunkLikeLink(link.url)) continue;
|
||||
const linkUrl = link.url || '';
|
||||
if (linkUrl && isChunkLikeLink(linkUrl)) continue;
|
||||
// 文件名有效时,保留文件按钮(即便 URL 是临时签名地址)。
|
||||
if (isNoisySourceName(link.name)) continue;
|
||||
if ( (isMarkdownFileName(link.name) || isMarkdownByUrl(link.url))) continue;
|
||||
if (isMarkdownFileName(link.name) || isMarkdownByUrl(linkUrl)) continue;
|
||||
if (isMarkdownFileName(link.name)) {
|
||||
const key = looksLikeFileName(link.name) ? link.name : `${link.name}|${link.url.split('?')[0]}`;
|
||||
if (!map.has(key)) map.set(key, link);
|
||||
const key = looksLikeFileName(link.name) ? link.name : `${link.name}|${linkUrl.split('?')[0]}`;
|
||||
mergeMessageLink(key, link);
|
||||
continue;
|
||||
}
|
||||
if (isNoisySourceUrl(link.url) && !looksLikeFileName(link.name)) continue;
|
||||
const key = looksLikeFileName(link.name) ? link.name : `${link.name}|${link.url.split('?')[0]}`;
|
||||
if (!map.has(key)) map.set(key, link);
|
||||
if (linkUrl && isNoisySourceUrl(linkUrl) && !looksLikeFileName(link.name)) continue;
|
||||
const key = looksLikeFileName(link.name) ? link.name : `${link.name}|${linkUrl.split('?')[0]}`;
|
||||
mergeMessageLink(key, link);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -359,7 +447,7 @@ const getMessageLinks = (msg: any): SourceFileLink[] => {
|
||||
}
|
||||
|
||||
const links = Array.from(map.values());
|
||||
const preferred = links.filter((l) => isPreferredSourceLink(l.url));
|
||||
const preferred = links.filter((l) => l.url && isPreferredSourceLink(l.url));
|
||||
return preferred.length > 0 ? preferred : links;
|
||||
};
|
||||
|
||||
@@ -381,7 +469,7 @@ const shouldExpandSourceDetails = (msg: any): boolean => {
|
||||
// }
|
||||
|
||||
// if (!sourceFileConfig.showMdFiles || !sourceFileConfig.expandMdByDefault) return false;
|
||||
return getMessageLinks(msg).some((link) => isMarkdownFileName(link.name) || isMarkdownByUrl(link.url));
|
||||
return getMessageLinks(msg).some((link) => isMarkdownFileName(link.name) || isMarkdownByUrl(link.url || ''));
|
||||
};
|
||||
|
||||
const shouldRenderMessage = (msg: any): boolean => {
|
||||
@@ -413,11 +501,62 @@ const shouldShowThinkingBubble = computed(() => {
|
||||
});
|
||||
|
||||
const filePreviewVisible = ref(false);
|
||||
const previewFile = ref<SourceFileLink | null>(null);
|
||||
const previewFile = ref<{ name: string; url: string } | null>(null);
|
||||
|
||||
const openPreview = (file: SourceFileLink) => {
|
||||
previewFile.value = file;
|
||||
filePreviewVisible.value = true;
|
||||
const resolveSourceLink = async (file: SourceFileLink): Promise<{ name: string; url: string }> => {
|
||||
if (file.url) {
|
||||
return {
|
||||
name: file.name,
|
||||
url: file.url,
|
||||
};
|
||||
}
|
||||
if (!file.datasetId || !file.remoteDocumentId) {
|
||||
throw new Error('当前源文件暂未返回可预览链接');
|
||||
}
|
||||
|
||||
const params = new URLSearchParams({
|
||||
agent_id: String(agentId),
|
||||
dataset_id: file.datasetId,
|
||||
remote_document_id: file.remoteDocumentId,
|
||||
});
|
||||
const response = await fetch(`/api/chat/source-file?${params.toString()}`, {
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
const data = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
throw new Error(data?.error || `HTTP ${response.status}`);
|
||||
}
|
||||
|
||||
const resolvedUrl = normalizeUrl(data?.source_download_url || '');
|
||||
if (!resolvedUrl) {
|
||||
throw new Error('未查询到源文件下载地址');
|
||||
}
|
||||
|
||||
return {
|
||||
...file,
|
||||
url: resolvedUrl,
|
||||
name: data?.source_filename || file.name,
|
||||
};
|
||||
};
|
||||
|
||||
const openPreview = async (file: SourceFileLink) => {
|
||||
try {
|
||||
const resolvedFile = await resolveSourceLink(file);
|
||||
previewFile.value = resolvedFile;
|
||||
filePreviewVisible.value = true;
|
||||
} catch (error: any) {
|
||||
showMessageDialog('warning', error?.message || '当前源文件暂时无法预览');
|
||||
}
|
||||
};
|
||||
|
||||
const parsePlmPreviewLink = (href: string): SourceFileLink | null => {
|
||||
const rawHref = (href || '').trim();
|
||||
if (!rawHref.startsWith('#plm-preview?')) return null;
|
||||
const params = new URLSearchParams(rawHref.slice('#plm-preview?'.length));
|
||||
const name = (params.get('name') || '').trim();
|
||||
const url = (params.get('url') || '').trim();
|
||||
if (!name || !url) return null;
|
||||
return { name, url };
|
||||
};
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
@@ -810,6 +949,13 @@ const startLocalLeaveFlow = async (content: string) => {
|
||||
|
||||
const handleChatMarkdownClick = (event: MouseEvent) => {
|
||||
const target = event.target as HTMLElement | null;
|
||||
const anchor = target?.closest?.('a') as HTMLAnchorElement | null;
|
||||
const previewFile = parsePlmPreviewLink(anchor?.getAttribute('href') || '');
|
||||
if (previewFile) {
|
||||
event.preventDefault();
|
||||
openPreview(previewFile);
|
||||
return;
|
||||
}
|
||||
const actionElement = target?.closest?.('[data-leave-action]') as HTMLElement | null;
|
||||
if (!actionElement) return;
|
||||
const action = actionElement.getAttribute('data-leave-action');
|
||||
@@ -1801,13 +1947,13 @@ const showChatRating = ref(false);
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if=" msg.role === 'assistant' && msg.type !== 'leave-form' && msg.type !== 'leave-confirmation' && msg.type !== 'leave-result' && ((getDisplayRetrieverResources(msg).length > 0) || (msg.attribution_parts && msg.attribution_parts.length > 0) || getMessageLinks(msg).length > 0)"
|
||||
v-if=" msg.role === 'assistant' && msg.type !== 'leave-form' && msg.type !== 'leave-confirmation' && msg.type !== 'leave-result' && ((getDisplayRetrieverResources(msg).length > 0) || (msg.attribution_parts && msg.attribution_parts.length > 0) || getSourceLinks(getDisplayRetrieverResources(msg)).length > 0)"
|
||||
class="mt-2 space-y-2"
|
||||
>
|
||||
<!-- 带有URL链接的源文件名称,支持预览 -->
|
||||
<div v-if="getMessageLinks(msg).length > 0" class="flex flex-wrap gap-2">
|
||||
<div v-if="getSourceLinks(getDisplayRetrieverResources(msg)).length > 0" class="flex flex-wrap gap-2">
|
||||
<button
|
||||
v-for="(file, linkIndex) in getMessageLinks(msg)"
|
||||
v-for="(file, linkIndex) in getSourceLinks(getDisplayRetrieverResources(msg))"
|
||||
:key="`src-link-top-${linkIndex}-${file.url}`"
|
||||
@click="openPreview(file)"
|
||||
class="break-all rounded-lg border border-brand-200 bg-brand-50 px-2.5 py-1.5 text-xs text-brand-700 transition-colors hover:bg-brand-100 dark:border-brand-500/30 dark:bg-brand-500/10 dark:text-brand-200 dark:hover:bg-brand-500/20"
|
||||
|
||||
@@ -1793,6 +1793,7 @@ onMounted(async () => {
|
||||
<th class="px-4 py-3 text-left font-semibold text-slate-600">处理笔数</th>
|
||||
<th class="px-4 py-3 text-left font-semibold text-slate-600">成功笔数</th>
|
||||
<th class="px-4 py-3 text-left font-semibold text-slate-600">失败笔数</th>
|
||||
|
||||
<th class="px-4 py-3 text-left font-semibold text-slate-600">明细</th>
|
||||
</tr>
|
||||
</thead>
|
||||
@@ -1814,6 +1815,7 @@ onMounted(async () => {
|
||||
<td class="px-4 py-3 text-slate-500">{{ r.total_count || 0 }}</td>
|
||||
<td class="px-4 py-3 text-emerald-600 font-medium">{{ r.success_count ?? 0 }}</td>
|
||||
<td class="px-4 py-3 text-rose-600 font-medium">{{ r.failed_count ?? 0 }}</td>
|
||||
|
||||
<td class="px-4 py-3">
|
||||
<a
|
||||
v-if="r.total_count > 0 && r.excel_file_name"
|
||||
|
||||
Reference in new issue
Block a user