Merge branch 'hugo' into dev
This commit is contained in:
commit
40b25ec988
21 files changed
+2185
-593
No files matched your search
@@ -8,16 +8,15 @@ from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.models import Agent, ScheduleRun, ScheduleTask
|
||||
from app.services.schedule.srm_service import (
|
||||
SRM_MSDS_HEADER_LABELS,
|
||||
SRM_MSDS_SQL_ALIAS_ORDER,
|
||||
SRM_ROHS_HEADER_LABELS,
|
||||
SRM_ROHS_SQL_ALIAS_ORDER,
|
||||
run_msds_doc_check_dify_job,
|
||||
run_rohs_doc_check_dify_job,
|
||||
from app.services.schedule.sql_config import (
|
||||
get_schedule_sql_config,
|
||||
get_schedule_sql_config_by_task_id,
|
||||
get_all_schedule_sql_configs,
|
||||
upsert_schedule_task_config,
|
||||
ScheduleSqlConfig,
|
||||
)
|
||||
|
||||
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str]]
|
||||
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
|
||||
ScheduleExecutor = Callable[[ScheduleTask, ScheduleRun], ScheduleExecuteResult]
|
||||
|
||||
|
||||
@@ -74,7 +73,13 @@ def _run_common_executor(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecut
|
||||
raise RuntimeError("platform_api_path is missing")
|
||||
|
||||
base = str(current_app.config.get("INTERNAL_API_BASE_URL") or "").strip().rstrip("/")
|
||||
url = endpoint if endpoint.startswith("http://") or endpoint.startswith("https://") else (f"{base}{endpoint}" if base else endpoint)
|
||||
if endpoint.startswith("http://") or endpoint.startswith("https://"):
|
||||
url = endpoint
|
||||
elif base:
|
||||
name = endpoint.lstrip("/")
|
||||
url = f"{base}/api/internal/jobs/{name}"
|
||||
else:
|
||||
url = endpoint
|
||||
|
||||
payload = {
|
||||
"run_no": run.run_no,
|
||||
@@ -83,13 +88,21 @@ def _run_common_executor(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecut
|
||||
"dify_agent_id": task.dify_agent_id,
|
||||
}
|
||||
|
||||
step_logs: list[dict[str, Any]] = []
|
||||
|
||||
run.api_request_json = payload
|
||||
db.session.commit()
|
||||
|
||||
try:
|
||||
resp = requests.post(url, json=payload, timeout=(5, 60))
|
||||
timeout = max(5, (task.wait_seconds or 120) + 30)
|
||||
resp = requests.post(url, json=payload, timeout=(5, timeout))
|
||||
resp.raise_for_status()
|
||||
data = resp.json() if resp.content else {}
|
||||
step_logs.append({
|
||||
"step": "call_internal_api",
|
||||
"status": "success",
|
||||
"detail": {"url": url, "status_code": resp.status_code},
|
||||
})
|
||||
except requests.RequestException as e:
|
||||
data = {}
|
||||
if e.response is not None:
|
||||
@@ -99,6 +112,11 @@ def _run_common_executor(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecut
|
||||
data = {"error_text": e.response.text}
|
||||
else:
|
||||
data = {"error": str(e)}
|
||||
step_logs.append({
|
||||
"step": "call_internal_api",
|
||||
"status": "failed",
|
||||
"detail": {"url": url, "error": str(e)},
|
||||
})
|
||||
run.api_response_json = data
|
||||
db.session.commit()
|
||||
raise e
|
||||
@@ -109,56 +127,151 @@ def _run_common_executor(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecut
|
||||
summary = data.get("summary") if isinstance(data, dict) and isinstance(data.get("summary"), dict) else {}
|
||||
details = data.get("details") if isinstance(data, dict) and isinstance(data.get("details"), list) else []
|
||||
errors = data.get("errors") if isinstance(data, dict) and isinstance(data.get("errors"), list) else []
|
||||
remote_step_logs = data.get("step_logs") if isinstance(data, dict) and isinstance(data.get("step_logs"), list) else []
|
||||
|
||||
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, 0, details, [str(e) for e in errors if str(e).strip()]
|
||||
skipped = int(summary.get("skipped_count") if summary.get("skipped_count") is not None else 0)
|
||||
|
||||
if remote_step_logs:
|
||||
step_logs.extend(remote_step_logs)
|
||||
|
||||
return total, success, failed, skipped, details, [str(e) for e in errors if str(e).strip()], step_logs
|
||||
|
||||
|
||||
def _run_srm_rohs_doc_check_executor(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||
return run_rohs_doc_check_dify_job(
|
||||
conn_str=_build_srm_conn_str(),
|
||||
def _run_external_api_job(task: ScheduleTask, run: ScheduleRun, cfg: ScheduleSqlConfig) -> ScheduleExecuteResult:
|
||||
import requests as http_requests
|
||||
|
||||
ext = cfg.external_api
|
||||
if not ext.url:
|
||||
return 0, 0, 0, 0, [], ["external_api url is empty"], []
|
||||
|
||||
step_logs: list[dict[str, Any]] = []
|
||||
step_logs.append({"step": "call_external_api", "status": "started", "url": ext.url, "method": ext.method})
|
||||
|
||||
try:
|
||||
headers = dict(ext.headers) if ext.headers else {}
|
||||
body = ext.body_template or "{}"
|
||||
resp = http_requests.request(
|
||||
method=ext.method,
|
||||
url=ext.url,
|
||||
headers=headers,
|
||||
data=body,
|
||||
timeout=120,
|
||||
)
|
||||
step_logs.append({"step": "call_external_api", "status": "completed", "status_code": resp.status_code})
|
||||
if not resp.ok:
|
||||
return 0, 0, 0, 1, [], [f"external API returned {resp.status_code}: {resp.text[:500]}"], step_logs
|
||||
try:
|
||||
result_data = resp.json()
|
||||
except Exception:
|
||||
result_data = {"raw": resp.text[:2000]}
|
||||
|
||||
total = 1
|
||||
details = [result_data] if isinstance(result_data, dict) else (result_data if isinstance(result_data, list) else [{"raw": str(result_data)}])
|
||||
step_logs.append({"step": "call_external_api", "status": "success", "total": total})
|
||||
return total, total, 0, 0, details, [], step_logs
|
||||
except Exception as e:
|
||||
step_logs.append({"step": "call_external_api", "status": "error", "error": str(e)})
|
||||
return 0, 0, 1, 0, [], [str(e)], step_logs
|
||||
|
||||
|
||||
def _run_generic_check_job(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||
from app.services.schedule.srm_service import (
|
||||
_run_check_job_loop,
|
||||
_fetch_records,
|
||||
_execute_writeback,
|
||||
_build_record_text,
|
||||
)
|
||||
|
||||
cfg = get_schedule_sql_config_by_task_id(task.id)
|
||||
if not cfg:
|
||||
return 0, 0, 0, 0, [], [], []
|
||||
|
||||
if cfg.data_source_type == "external_api":
|
||||
return _run_external_api_job(task, run, cfg)
|
||||
|
||||
if not cfg.fetch_sql:
|
||||
return 0, 0, 0, 0, [], [], []
|
||||
|
||||
if cfg.data_source and not cfg.data_source.is_empty():
|
||||
conn_str = cfg.data_source.build_connection_string()
|
||||
else:
|
||||
conn_str = _build_srm_conn_str()
|
||||
agent = _resolve_dify_agent(task)
|
||||
user = _resolve_schedule_user(task)
|
||||
has_detail = bool(cfg.detail_sql)
|
||||
|
||||
def fetch_fn(cs: str):
|
||||
return _fetch_records(cs, cfg.fetch_sql)
|
||||
|
||||
def writeback_fn(cs: str, *, row_id: str, run_no: str, dify_result: str, dify_message: str):
|
||||
_execute_writeback(cs, cfg.writeback_sql, (run_no, dify_result, dify_message, str(row_id)))
|
||||
|
||||
pre_dify_fn = None
|
||||
build_record_fn = None
|
||||
|
||||
if has_detail:
|
||||
def _pre_dify(cs: str, item: dict[str, Any], row_id_value: str) -> dict[str, Any] | None:
|
||||
try:
|
||||
detail_rows = _fetch_records(cs, cfg.detail_sql, params=(str(row_id_value),))
|
||||
except Exception as detail_exc:
|
||||
return {
|
||||
"dify_result": "人工判定",
|
||||
"dify_message": f"查询成分明细失败:{detail_exc}",
|
||||
"writeback_srm": False,
|
||||
"writeback_err": str(detail_exc),
|
||||
}
|
||||
detail_summary_lines: list[str] = []
|
||||
for dr in detail_rows:
|
||||
parts = [f"{cfg.header_labels.get(dk, dk)}: {dr.get(dk, '')}" for dk in cfg.detail_alias_order]
|
||||
detail_summary_lines.append(", ".join(parts))
|
||||
item["detail_text"] = "; ".join(detail_summary_lines) if detail_summary_lines else ""
|
||||
item["_detail_rows"] = detail_rows
|
||||
return None
|
||||
pre_dify_fn = _pre_dify
|
||||
|
||||
def _build_with_detail(cs: str, item: dict[str, Any], row_id_value: str) -> tuple[str, str | None]:
|
||||
detail_rows = item.pop("_detail_rows", [])
|
||||
text = _build_record_text(item, cfg.alias_order, cfg.header_labels, detail_rows, cfg.detail_alias_order)
|
||||
return text, item.get("attachment")
|
||||
build_record_fn = _build_with_detail
|
||||
else:
|
||||
def _build_simple(cs: str, item: dict[str, Any], row_id_value: str) -> tuple[str, str | None]:
|
||||
text = _build_record_text(item, cfg.alias_order, cfg.header_labels)
|
||||
return text, item.get("attachment")
|
||||
build_record_fn = _build_simple
|
||||
|
||||
return _run_check_job_loop(
|
||||
conn_str=conn_str,
|
||||
run_no=run.run_no,
|
||||
agent=_resolve_dify_agent(task),
|
||||
user=_resolve_schedule_user(task),
|
||||
agent=agent,
|
||||
user=user,
|
||||
wait_seconds=task.wait_seconds or 120,
|
||||
run_id=run.id,
|
||||
fetch_fn=fetch_fn,
|
||||
build_record_fn=build_record_fn,
|
||||
writeback_fn=writeback_fn,
|
||||
writeback_sql=cfg.writeback_sql,
|
||||
row_id_key=cfg.row_id_key,
|
||||
log_prefix=cfg.log_prefix,
|
||||
fetch_sql=cfg.fetch_sql,
|
||||
pre_dify_fn=pre_dify_fn,
|
||||
)
|
||||
|
||||
|
||||
def _run_srm_msds_doc_check_executor(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||
return run_msds_doc_check_dify_job(
|
||||
conn_str=_build_srm_conn_str(),
|
||||
run_no=run.run_no,
|
||||
agent=_resolve_dify_agent(task),
|
||||
user=_resolve_schedule_user(task),
|
||||
wait_seconds=task.wait_seconds or 120,
|
||||
run_id=run.id,
|
||||
)
|
||||
|
||||
|
||||
_SCHEDULE_EXECUTOR_REGISTRY: dict[str, ScheduleExecutor] = {
|
||||
"default": _run_common_executor,
|
||||
"srm_rohs_doc_check": _run_srm_rohs_doc_check_executor,
|
||||
"srm_msds_doc_check": _run_srm_msds_doc_check_executor,
|
||||
}
|
||||
|
||||
|
||||
def register_schedule_executor(name: str, executor: ScheduleExecutor) -> None:
|
||||
key = str(name or "").strip().lower()
|
||||
if not key:
|
||||
raise ValueError("executor name is required")
|
||||
_SCHEDULE_EXECUTOR_REGISTRY[key] = executor
|
||||
def list_registered_api_paths() -> list[dict[str, str]]:
|
||||
from app.models import ScheduleTask
|
||||
results: list[dict[str, str]] = []
|
||||
tasks = ScheduleTask.query.filter(ScheduleTask.platform_api_path.isnot(None)).all()
|
||||
for t in tasks:
|
||||
results.append({"value": t.platform_api_path, "label": t.name or str(t.id)})
|
||||
return results
|
||||
|
||||
|
||||
def resolve_schedule_executor(task: ScheduleTask) -> ScheduleExecutor:
|
||||
path = normalize_platform_api_path(task.platform_api_path)
|
||||
if path:
|
||||
lookup_key = path.lstrip("/").lower()
|
||||
if lookup_key in _SCHEDULE_EXECUTOR_REGISTRY:
|
||||
return _SCHEDULE_EXECUTOR_REGISTRY[lookup_key]
|
||||
return _SCHEDULE_EXECUTOR_REGISTRY["default"]
|
||||
return _run_common_executor
|
||||
|
||||
|
||||
_SCHEDULE_HEADER_REGISTRY: dict[str, tuple[list[str], dict[str, str]]] = {}
|
||||
@@ -180,5 +293,23 @@ def resolve_schedule_header(platform_api_path: str | None) -> tuple[list[str] |
|
||||
return None, None
|
||||
|
||||
|
||||
register_schedule_header("srm_rohs_doc_check", SRM_ROHS_SQL_ALIAS_ORDER, SRM_ROHS_HEADER_LABELS)
|
||||
register_schedule_header("srm_msds_doc_check", SRM_MSDS_SQL_ALIAS_ORDER, SRM_MSDS_HEADER_LABELS)
|
||||
def _register_headers_from_config() -> None:
|
||||
_SCHEDULE_HEADER_REGISTRY.clear()
|
||||
for name, cfg in get_all_schedule_sql_configs().items():
|
||||
if cfg.alias_order and cfg.header_labels:
|
||||
register_schedule_header(name, cfg.alias_order, cfg.header_labels)
|
||||
|
||||
|
||||
def reload_config() -> dict[str, Any]:
|
||||
_register_headers_from_config()
|
||||
return {"reloaded": []}
|
||||
|
||||
|
||||
_HEADERS_LOADED = False
|
||||
|
||||
|
||||
def ensure_headers_loaded() -> None:
|
||||
global _HEADERS_LOADED
|
||||
if not _HEADERS_LOADED:
|
||||
_register_headers_from_config()
|
||||
_HEADERS_LOADED = True
|
||||
@@ -52,6 +52,7 @@ def serialize_run(run: ScheduleRun) -> dict:
|
||||
'api_request_json': run.api_request_json,
|
||||
'api_response_json': run.api_response_json,
|
||||
'response_summary_json': run.response_summary_json,
|
||||
'step_logs': run.step_logs,
|
||||
'error_message': run.error_message,
|
||||
'excel_file_name': run.excel_file_name,
|
||||
'excel_file_size': run.excel_file_size,
|
||||
|
||||
@@ -58,9 +58,6 @@ def create_task(
|
||||
enabled: bool,
|
||||
actor_id: int | None,
|
||||
) -> ScheduleTask:
|
||||
if not normalize_platform_api_path(platform_api_path):
|
||||
raise ValueError("platform_api_path is required for platform_app")
|
||||
|
||||
task = ScheduleTask(
|
||||
schedule_no=_generate_schedule_no(),
|
||||
name=name,
|
||||
@@ -151,11 +148,18 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
|
||||
db.session.commit()
|
||||
|
||||
start_ts = time.time()
|
||||
step_logs: list = []
|
||||
try:
|
||||
executor = resolve_schedule_executor(task)
|
||||
total_count, success_count, failed_count, skipped_count, details, errors = executor(task, run)
|
||||
total_count, success_count, failed_count, skipped_count, details, errors, step_logs = executor(task, run)
|
||||
except Exception as exc:
|
||||
total_count, success_count, failed_count, skipped_count, details, errors = 0, 0, 0, 0, [], [str(exc)]
|
||||
step_logs = [{"step": "executor_error", "status": "failed", "detail": {"error": str(exc)}}]
|
||||
|
||||
try:
|
||||
db.session.refresh(run)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if is_run_cancelled(run.id):
|
||||
run.finished_at = datetime.utcnow()
|
||||
@@ -211,6 +215,7 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
|
||||
run.success_count = success_count
|
||||
run.failed_count = failed_count
|
||||
run.skipped_count = skipped_count
|
||||
run.step_logs = step_logs if step_logs else None
|
||||
run.response_summary_json = {
|
||||
"errors": errors[:20],
|
||||
"schedule_type": task.schedule_type,
|
||||
|
||||
@@ -0,0 +1,239 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
_ENV_VAR_PATTERN = re.compile(r"\$\{(\w+)\}")
|
||||
|
||||
|
||||
def resolve_env_value(val: str) -> str:
|
||||
if not val or "${" not in val:
|
||||
return val
|
||||
|
||||
def _replacer(match: re.Match) -> str:
|
||||
env_key = match.group(1)
|
||||
return os.environ.get(env_key, match.group(0))
|
||||
|
||||
return _ENV_VAR_PATTERN.sub(_replacer, val)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DataSourceConfig:
|
||||
db_type: str = "sqlserver"
|
||||
host: str = ""
|
||||
port: str = ""
|
||||
database: str = ""
|
||||
username: str = ""
|
||||
password: str = ""
|
||||
driver: str = ""
|
||||
encrypt: str = ""
|
||||
trust_cert: str = ""
|
||||
|
||||
def is_empty(self) -> bool:
|
||||
return not self.host.strip()
|
||||
|
||||
def build_connection_string(self) -> str:
|
||||
host = resolve_env_value(self.host)
|
||||
port = resolve_env_value(self.port)
|
||||
database = resolve_env_value(self.database)
|
||||
username = resolve_env_value(self.username)
|
||||
password = resolve_env_value(self.password)
|
||||
|
||||
if not port:
|
||||
if self.db_type == "sqlserver":
|
||||
port = "1433"
|
||||
elif self.db_type == "postgresql":
|
||||
port = "5432"
|
||||
elif self.db_type == "mysql":
|
||||
port = "3306"
|
||||
|
||||
if self.db_type == "sqlserver":
|
||||
driver = resolve_env_value(self.driver) or "SQL Server"
|
||||
encrypt = resolve_env_value(self.encrypt) or "no"
|
||||
trust_cert = resolve_env_value(self.trust_cert) or "yes"
|
||||
return (
|
||||
f"DRIVER={{{driver}}};"
|
||||
f"SERVER={host},{port};"
|
||||
f"DATABASE={database};"
|
||||
f"UID={username};"
|
||||
f"PWD={password};"
|
||||
f"Encrypt={encrypt};"
|
||||
f"TrustServerCertificate={trust_cert};"
|
||||
)
|
||||
elif self.db_type == "postgresql":
|
||||
return f"postgresql://{username}:{password}@{host}:{port}/{database}"
|
||||
elif self.db_type == "mysql":
|
||||
return f"mysql+pymysql://{username}:{password}@{host}:{port}/{database}"
|
||||
raise ValueError(f"Unsupported db_type: {self.db_type}")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ExternalApiConfig:
|
||||
url: str = ""
|
||||
method: str = "POST"
|
||||
headers: dict[str, str] = field(default_factory=dict)
|
||||
body_template: str = ""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ScheduleSqlConfig:
|
||||
description: str = ""
|
||||
row_id_key: str = "id"
|
||||
log_prefix: str = ""
|
||||
fetch_sql: str = ""
|
||||
base_fetch_sql: str = ""
|
||||
fetch_where_conditions: str = ""
|
||||
fetch_order_by: str = ""
|
||||
writeback_sql: str = ""
|
||||
detail_sql: str = ""
|
||||
alias_order: list[str] = field(default_factory=list)
|
||||
detail_alias_order: list[str] = field(default_factory=list)
|
||||
header_labels: dict[str, str] = field(default_factory=dict)
|
||||
data_source: DataSourceConfig = field(default_factory=DataSourceConfig)
|
||||
external_api: ExternalApiConfig = field(default_factory=ExternalApiConfig)
|
||||
data_source_type: str = "database"
|
||||
|
||||
|
||||
def _build_fetch_sql(base: str, where_conds: str, order_by: str) -> str:
|
||||
parts = [base.strip().rstrip(";").strip()]
|
||||
if where_conds.strip():
|
||||
parts.append("where")
|
||||
parts.append(where_conds.strip())
|
||||
if order_by.strip():
|
||||
parts.append(order_by.strip())
|
||||
return "\n".join(parts)
|
||||
|
||||
|
||||
def _config_from_model(cfg_model: Any) -> ScheduleSqlConfig:
|
||||
from app import db
|
||||
from app.models import ScheduleTask
|
||||
|
||||
task_id = cfg_model.schedule_task_id
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
|
||||
base = str(cfg_model.base_fetch_sql or "")
|
||||
where_conds = str(cfg_model.fetch_where_conditions or "")
|
||||
order_by = str(cfg_model.fetch_order_by or "")
|
||||
fetch_sql = _build_fetch_sql(base, where_conds, order_by) if base else ""
|
||||
|
||||
ds = DataSourceConfig(
|
||||
db_type=str(cfg_model.ds_db_type or "sqlserver"),
|
||||
host=str(cfg_model.ds_host or ""),
|
||||
port=str(cfg_model.ds_port or ""),
|
||||
database=str(cfg_model.ds_database or ""),
|
||||
username=str(cfg_model.ds_username or ""),
|
||||
password=str(cfg_model.ds_password or ""),
|
||||
driver=str(cfg_model.ds_driver or ""),
|
||||
encrypt=str(cfg_model.ds_encrypt or ""),
|
||||
trust_cert=str(cfg_model.ds_trust_cert or ""),
|
||||
)
|
||||
|
||||
ext = ExternalApiConfig(
|
||||
url=str(cfg_model.api_url or ""),
|
||||
method=str(cfg_model.api_method or "POST"),
|
||||
headers=dict(cfg_model.api_headers or {}),
|
||||
body_template=str(cfg_model.api_body_template or ""),
|
||||
)
|
||||
|
||||
return ScheduleSqlConfig(
|
||||
description=str(task.name if task else ""),
|
||||
row_id_key=str(cfg_model.row_id_key or "id"),
|
||||
log_prefix=str(cfg_model.log_prefix or ""),
|
||||
fetch_sql=fetch_sql,
|
||||
base_fetch_sql=base,
|
||||
fetch_where_conditions=where_conds,
|
||||
fetch_order_by=order_by,
|
||||
writeback_sql=str(cfg_model.writeback_sql or ""),
|
||||
detail_sql=str(cfg_model.detail_sql or ""),
|
||||
alias_order=list(cfg_model.alias_order or []),
|
||||
detail_alias_order=list(cfg_model.detail_alias_order or []),
|
||||
header_labels=dict(cfg_model.header_labels or {}),
|
||||
data_source=ds,
|
||||
external_api=ext,
|
||||
data_source_type=str(task.data_source_type if task else "database"),
|
||||
)
|
||||
|
||||
|
||||
def get_schedule_sql_config(name: str) -> ScheduleSqlConfig | None:
|
||||
from app import db
|
||||
from app.models import ScheduleTask, ScheduleTaskConfig
|
||||
|
||||
key = name.strip().lower()
|
||||
task = None
|
||||
if key.isdigit():
|
||||
task = db.session.get(ScheduleTask, int(key))
|
||||
if not task:
|
||||
task = ScheduleTask.query.filter(
|
||||
ScheduleTask.platform_api_path.ilike(f"%{key}%")
|
||||
).first()
|
||||
if not task:
|
||||
return None
|
||||
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task.id).first()
|
||||
if not cfg_model:
|
||||
return None
|
||||
|
||||
return _config_from_model(cfg_model)
|
||||
|
||||
|
||||
def get_schedule_sql_config_by_task_id(task_id: int) -> ScheduleSqlConfig | None:
|
||||
from app import db
|
||||
from app.models import ScheduleTask, ScheduleTaskConfig
|
||||
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||
if not cfg_model:
|
||||
return None
|
||||
return _config_from_model(cfg_model)
|
||||
|
||||
|
||||
def get_all_schedule_sql_configs() -> dict[str, ScheduleSqlConfig]:
|
||||
from app.models import ScheduleTask, ScheduleTaskConfig
|
||||
|
||||
results: dict[str, ScheduleSqlConfig] = {}
|
||||
configs = ScheduleTaskConfig.query.all()
|
||||
for cfg_model in configs:
|
||||
key = str(cfg_model.schedule_task_id)
|
||||
results[key] = _config_from_model(cfg_model)
|
||||
return results
|
||||
|
||||
|
||||
def upsert_schedule_task_config(task_id: int, data: dict[str, Any]) -> ScheduleSqlConfig:
|
||||
from app import db
|
||||
from app.models import ScheduleTask, ScheduleTaskConfig
|
||||
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||
if not cfg_model:
|
||||
cfg_model = ScheduleTaskConfig(schedule_task_id=task_id)
|
||||
db.session.add(cfg_model)
|
||||
|
||||
for k, v in data.items():
|
||||
if k == "data_source" and isinstance(v, dict):
|
||||
cfg_model.ds_db_type = str(v.get("db_type", "sqlserver"))
|
||||
cfg_model.ds_host = str(v.get("host", ""))
|
||||
cfg_model.ds_port = str(v.get("port", ""))
|
||||
cfg_model.ds_database = str(v.get("database", ""))
|
||||
cfg_model.ds_username = str(v.get("username", ""))
|
||||
cfg_model.ds_password = str(v.get("password", ""))
|
||||
cfg_model.ds_driver = str(v.get("driver", "")) if v.get("driver") else None
|
||||
cfg_model.ds_encrypt = str(v.get("encrypt", "")) if v.get("encrypt") else None
|
||||
cfg_model.ds_trust_cert = str(v.get("trust_cert", "")) if v.get("trust_cert") else None
|
||||
elif k == "external_api" and isinstance(v, dict):
|
||||
cfg_model.api_url = str(v.get("url", ""))
|
||||
cfg_model.api_method = str(v.get("method", "POST"))
|
||||
cfg_model.api_headers = dict(v.get("headers", {}))
|
||||
cfg_model.api_body_template = str(v.get("body_template", ""))
|
||||
elif k in ("row_id_key", "log_prefix"):
|
||||
setattr(cfg_model, k, str(v) if v is not None else "")
|
||||
elif k in ("base_fetch_sql", "fetch_where_conditions", "fetch_order_by",
|
||||
"writeback_sql", "detail_sql"):
|
||||
setattr(cfg_model, k, str(v) if v is not None else None)
|
||||
elif k in ("alias_order", "detail_alias_order"):
|
||||
setattr(cfg_model, k, list(v) if isinstance(v, (list, tuple)) else [])
|
||||
elif k == "header_labels":
|
||||
setattr(cfg_model, k, dict(v) if isinstance(v, dict) else {})
|
||||
|
||||
db.session.commit()
|
||||
db.session.refresh(cfg_model)
|
||||
return _config_from_model(cfg_model)
|
||||
@@ -1,5 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any, Callable
|
||||
|
||||
from flask import current_app
|
||||
@@ -12,169 +13,6 @@ except Exception: # pragma: no cover
|
||||
pyodbc = None
|
||||
|
||||
|
||||
FETCHD_ROHS_SQL = """
|
||||
select
|
||||
t2.supplier_code as supplier_code,
|
||||
t2.supplier_name as supplier_name,
|
||||
t2.material_code as item_code,
|
||||
t2.material_name as item_name,
|
||||
t1.id as id,
|
||||
t1.material as material,
|
||||
t1.material_name as material_name,
|
||||
t1.third_code as third_code,
|
||||
t1.test_item as test_item,
|
||||
t1.pb as pb,
|
||||
t1.cd as cd,
|
||||
t1.hg as hg,
|
||||
t1.cr6 as cr6,
|
||||
t1.pbbs as pbbs,
|
||||
t1.pbdes as pbdes,
|
||||
t1.dbp as dbp,
|
||||
t1.bbp as bbp,
|
||||
t1.dehp as dehp,
|
||||
t1.dibp as dibp,
|
||||
t1.cl as cl,
|
||||
t1.br as br,
|
||||
COALESCE(CONVERT(VARCHAR(19), t1.test_date, 120), '1970-01-01 00:00:00') as test_date,
|
||||
'http://srm.well-trust.com:8090/hexin-boot/sys/common/static/' + COALESCE(t1.attachment, '') as attachment
|
||||
from
|
||||
control_harmful_substances t1,
|
||||
control_harmful t2
|
||||
where
|
||||
1 = 1
|
||||
and t1.control_harmful_id = t2.id
|
||||
and t1.def11 is null
|
||||
and t2.def1 = '7'
|
||||
"""
|
||||
|
||||
SRM_ROHS_SQL_ALIAS_ORDER: list[str] = [
|
||||
"id",
|
||||
"supplier_code",
|
||||
"supplier_name",
|
||||
"item_code",
|
||||
"item_name",
|
||||
"material",
|
||||
"material_name",
|
||||
"third_code",
|
||||
"test_item",
|
||||
"pb",
|
||||
"cd",
|
||||
"hg",
|
||||
"cr6",
|
||||
"pbbs",
|
||||
"pbdes",
|
||||
"dbp",
|
||||
"bbp",
|
||||
"dehp",
|
||||
"dibp",
|
||||
"cl",
|
||||
"br",
|
||||
"test_date",
|
||||
"attachment",
|
||||
]
|
||||
|
||||
SRM_ROHS_HEADER_LABELS: dict[str, str] = {
|
||||
"id": "SRM系统ID",
|
||||
"supplier_code": "供应商编码",
|
||||
"supplier_name": "供应商名称",
|
||||
"item_code": "物料编码",
|
||||
"item_name": "物料名称",
|
||||
"material": "材质",
|
||||
"material_name": "材质名称",
|
||||
"third_code": "第三方编码",
|
||||
"test_item": "检测项目",
|
||||
"pb": "铅(Pb)",
|
||||
"cd": "镉(Cd)",
|
||||
"hg": "汞(Hg)",
|
||||
"cr6": "六价铬(Cr6+)",
|
||||
"pbbs": "多溴联苯(PBBs)",
|
||||
"pbdes": "多溴二苯醚(PBDEs)",
|
||||
"dbp": "邻苯二甲酸二丁酯(DBP)",
|
||||
"bbp": "邻苯二甲酸丁苄酯(BBP)",
|
||||
"dehp": "邻苯二甲酸二(2-乙基己)酯(DEHP)",
|
||||
"dibp": "邻苯二甲酸二异丁酯(DIBP)",
|
||||
"cl": "氯(Cl)",
|
||||
"br": "溴(Br)",
|
||||
"test_date": "检测日期",
|
||||
"attachment": "附件地址",
|
||||
"dify_result": "判定结果",
|
||||
"dify_message": "判定说明",
|
||||
"writeback_srm": "回写SRM",
|
||||
"writeback_err": "回写错误",
|
||||
}
|
||||
|
||||
FETCHD_MSDS_SQL = """
|
||||
select
|
||||
cc.id as cc_id,
|
||||
cc.supplier_code as supplier_code,
|
||||
cc.supplier_name as supplier_name,
|
||||
cc.material_code as material_code,
|
||||
cc.material_name as material_name,
|
||||
ccm.id as ccm_id,
|
||||
ccm.material as material,
|
||||
ccm.attachment as attachment,
|
||||
ccm.weight as weight
|
||||
from
|
||||
chemical_composition cc
|
||||
inner join chemical_composition_management ccm on
|
||||
cc.id = ccm.chemical_composition_id
|
||||
where
|
||||
cc.def1 = '7'
|
||||
and ccm.def11 is null
|
||||
order by ccm.id
|
||||
"""
|
||||
|
||||
FETCHD_MSDS_DETAIL_SQL = """
|
||||
select
|
||||
ccmb.cas_no as cas_no,
|
||||
ccmb.component_name as component_name,
|
||||
ccmb.concentration as concentration
|
||||
from
|
||||
chemical_composition_management_b ccmb
|
||||
where
|
||||
ccmb.chemical_composition_management_id = ?
|
||||
order by ccmb.id
|
||||
"""
|
||||
|
||||
SRM_MSDS_SQL_ALIAS_ORDER: list[str] = [
|
||||
"cc_id",
|
||||
"supplier_code",
|
||||
"supplier_name",
|
||||
"material_code",
|
||||
"material_name",
|
||||
"ccm_id",
|
||||
"material",
|
||||
"attachment",
|
||||
"weight",
|
||||
]
|
||||
|
||||
SRM_MSDS_DETAIL_ALIAS_ORDER: list[str] = [
|
||||
"cas_no",
|
||||
"component_name",
|
||||
"concentration",
|
||||
]
|
||||
|
||||
SRM_MSDS_HEADER_LABELS: dict[str, str] = {
|
||||
"cc_id": "SRM系统CC_ID",
|
||||
"supplier_code": "供应商编码",
|
||||
"supplier_name": "供应商名称",
|
||||
"material_code": "物料编码",
|
||||
"material_name": "物料名称",
|
||||
"ccm_id": "SRM系统CCM_ID",
|
||||
"material": "材质",
|
||||
"attachment": "附件地址",
|
||||
"weight": "重量",
|
||||
"cas_no": "CAS号",
|
||||
"component_name": "成分名称",
|
||||
"concentration": "浓度",
|
||||
"detail_text": "成分明细",
|
||||
"dify_result": "判定结果",
|
||||
"dify_message": "判定说明",
|
||||
"writeback_srm": "回写SRM",
|
||||
"writeback_err": "回写错误",
|
||||
}
|
||||
|
||||
|
||||
def _connect(conn_str: str):
|
||||
if pyodbc is None:
|
||||
raise RuntimeError("pyodbc is not installed")
|
||||
@@ -244,6 +82,40 @@ RecordBuilder = Callable[[str, dict[str, Any], str], tuple[str, str | None]]
|
||||
WritebackFunc = Callable[..., None]
|
||||
PreDifyFunc = Callable[[str, dict[str, Any], str], dict[str, Any] | None]
|
||||
|
||||
_MAX_STEP_LOGS_PER_ROW = 200
|
||||
_MAX_DIFY_RESPONSE_LEN = 4000
|
||||
|
||||
|
||||
def _ts() -> str:
|
||||
return datetime.utcnow().isoformat()
|
||||
|
||||
|
||||
def _make_step(
|
||||
step: str,
|
||||
status: str,
|
||||
started_at: str,
|
||||
finished_at: str,
|
||||
row_id: str | None = None,
|
||||
**extra: Any,
|
||||
) -> dict[str, Any]:
|
||||
entry: dict[str, Any] = {
|
||||
"step": step,
|
||||
"status": status,
|
||||
"started_at": started_at,
|
||||
"finished_at": finished_at,
|
||||
"duration_ms": int((datetime.fromisoformat(finished_at) - datetime.fromisoformat(started_at)).total_seconds() * 1000),
|
||||
}
|
||||
if row_id:
|
||||
entry["row_id"] = row_id
|
||||
entry.update(extra)
|
||||
return entry
|
||||
|
||||
|
||||
def _truncate_str(s: str, max_len: int = _MAX_DIFY_RESPONSE_LEN) -> str:
|
||||
if len(s) <= max_len:
|
||||
return s
|
||||
return s[:max_len] + f"...[truncated, total {len(s)} chars]"
|
||||
|
||||
|
||||
def _run_check_job_loop(
|
||||
*,
|
||||
@@ -256,17 +128,41 @@ def _run_check_job_loop(
|
||||
fetch_fn: Callable[[str], list[dict[str, Any]]],
|
||||
build_record_fn: RecordBuilder,
|
||||
writeback_fn: WritebackFunc,
|
||||
writeback_sql: str = "",
|
||||
row_id_key: str,
|
||||
log_prefix: str,
|
||||
fetch_sql: str = "",
|
||||
max_rows: int = 0,
|
||||
pre_dify_fn: PreDifyFunc | None = None,
|
||||
) -> tuple[int, int, int, int, list[dict[str, Any]], list[str]]:
|
||||
) -> tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]:
|
||||
from app.services.schedule.scheduler_service import is_run_cancelled
|
||||
|
||||
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")
|
||||
|
||||
rows = fetch_fn(conn_str)
|
||||
step_logs: list[dict[str, Any]] = []
|
||||
|
||||
t0 = _ts()
|
||||
try:
|
||||
rows = fetch_fn(conn_str)
|
||||
if max_rows > 0:
|
||||
rows = rows[:max_rows]
|
||||
step_logs.append(_make_step(
|
||||
"fetch_srm",
|
||||
"success",
|
||||
t0, _ts(),
|
||||
detail={"sql": _truncate_str(fetch_sql or fetch_fn.__name__, 500), "row_count": len(rows)},
|
||||
))
|
||||
except Exception as fetch_exc:
|
||||
step_logs.append(_make_step(
|
||||
"fetch_srm",
|
||||
"failed",
|
||||
t0, _ts(),
|
||||
detail={"sql": _truncate_str(fetch_sql or fetch_fn.__name__, 500), "error": str(fetch_exc)},
|
||||
))
|
||||
raise
|
||||
|
||||
details: list[dict[str, Any]] = []
|
||||
success_count = 0
|
||||
failed_count = 0
|
||||
@@ -290,7 +186,18 @@ def _run_check_job_loop(
|
||||
row_id_value = str(row.get(row_id_key, ""))
|
||||
|
||||
if pre_dify_fn:
|
||||
pre_result = pre_dify_fn(conn_str, item, row_id_value)
|
||||
t_pre = _ts()
|
||||
try:
|
||||
pre_result = pre_dify_fn(conn_str, item, row_id_value)
|
||||
except Exception as pre_exc:
|
||||
pre_result = {
|
||||
"dify_result": "人工判定",
|
||||
"dify_message": f"pre_dify执行异常:{pre_exc}",
|
||||
"writeback_srm": False,
|
||||
"writeback_err": str(pre_exc),
|
||||
}
|
||||
step_logs.append(_make_step("pre_dify", "failed", t_pre, _ts(), row_id=row_id_value, detail={"error": str(pre_exc)}))
|
||||
|
||||
if pre_result is not None:
|
||||
item.update(pre_result)
|
||||
failed_count += 1
|
||||
@@ -306,22 +213,41 @@ def _run_check_job_loop(
|
||||
|
||||
try:
|
||||
if use_dify:
|
||||
dify_res = DifyService.run_workflow_streaming(
|
||||
agent=agent,
|
||||
inputs={
|
||||
"run_no": run_no,
|
||||
"record": record_text,
|
||||
"attachment_url": attachment_url,
|
||||
},
|
||||
user=user,
|
||||
timeout=(5, max(300, int(wait_seconds))),
|
||||
)
|
||||
dify_inputs = {
|
||||
"run_no": run_no,
|
||||
"record": record_text,
|
||||
"attachment_url": attachment_url,
|
||||
}
|
||||
t_dify = _ts()
|
||||
try:
|
||||
dify_res = DifyService.run_workflow_streaming(
|
||||
agent=agent,
|
||||
inputs=dify_inputs,
|
||||
user=user,
|
||||
timeout=(5, max(300, int(wait_seconds))),
|
||||
)
|
||||
except Exception as dify_exc:
|
||||
step_logs.append(_make_step("call_dify", "failed", t_dify, _ts(), row_id=row_id_value, detail={
|
||||
"request": {"inputs": {k: _truncate_str(str(v), 500) for k, v in dify_inputs.items()}, "agent_id": getattr(agent, "id", None)},
|
||||
"error": str(dify_exc),
|
||||
}))
|
||||
raise
|
||||
|
||||
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
|
||||
workflow_run_id = dify_res.get("workflow_run_id") 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}"
|
||||
dify_result = "人工判定"
|
||||
dify_message = f"Dify执行失败:{err_detail}"
|
||||
|
||||
step_logs.append(_make_step("call_dify", "failed", t_dify, _ts(), row_id=row_id_value, detail={
|
||||
"request": {"inputs": {k: _truncate_str(str(v), 500) for k, v in dify_inputs.items()}, "agent_id": getattr(agent, "id", None)},
|
||||
"response": _truncate_str(str(dify_res)),
|
||||
"workflow_run_id": workflow_run_id,
|
||||
}))
|
||||
|
||||
item.update({
|
||||
"dify_result": dify_result,
|
||||
"dify_message": dify_message,
|
||||
@@ -343,13 +269,30 @@ def _run_check_job_loop(
|
||||
)
|
||||
dify_result, dify_message = _derive_dify_result_and_message(outputs if isinstance(outputs, dict) else {})
|
||||
dify_ok = True
|
||||
|
||||
step_logs.append(_make_step("call_dify", "success", t_dify, _ts(), row_id=row_id_value, detail={
|
||||
"request": {"inputs": {k: _truncate_str(str(v), 500) for k, v in dify_inputs.items()}, "agent_id": getattr(agent, "id", None)},
|
||||
"response": {
|
||||
"status": dify_status,
|
||||
"dify_result": dify_result,
|
||||
"dify_message": _truncate_str(dify_message),
|
||||
"workflow_run_id": workflow_run_id,
|
||||
},
|
||||
}))
|
||||
else:
|
||||
dify_result = "人工判定"
|
||||
dify_message = "未配置 Agent ID,跳过 Dify"
|
||||
dify_ok = True
|
||||
|
||||
wb_sql = writeback_sql
|
||||
wb_params = (run_no, dify_result, dify_message, str(row_id_value))
|
||||
t_wb = _ts()
|
||||
try:
|
||||
writeback_fn(conn_str, row_id=row_id_value, run_no=run_no, dify_result=dify_result, dify_message=dify_message)
|
||||
step_logs.append(_make_step("writeback_srm", "success", t_wb, _ts(), row_id=row_id_value, detail={
|
||||
"sql": _truncate_str(wb_sql, 500),
|
||||
"params": [str(p) for p in wb_params],
|
||||
}))
|
||||
item.update({
|
||||
"dify_result": dify_result,
|
||||
"dify_message": dify_message,
|
||||
@@ -361,6 +304,11 @@ def _run_check_job_loop(
|
||||
except Exception as wb_exc:
|
||||
if current_app:
|
||||
current_app.logger.error("[%s] writeback failed %s=%s error=%s", log_prefix, log_prefix, row_id_value, wb_exc)
|
||||
step_logs.append(_make_step("writeback_srm", "failed", t_wb, _ts(), row_id=row_id_value, detail={
|
||||
"sql": _truncate_str(wb_sql, 500),
|
||||
"params": [str(p) for p in wb_params],
|
||||
"error": str(wb_exc),
|
||||
}))
|
||||
item.update({
|
||||
"dify_result": dify_result,
|
||||
"dify_message": dify_message,
|
||||
@@ -381,120 +329,20 @@ def _run_check_job_loop(
|
||||
})
|
||||
failed_count += 1
|
||||
all_errors.append(str(exc))
|
||||
t_wb2 = _ts()
|
||||
try:
|
||||
writeback_fn(conn_str, row_id=row_id_value, run_no=run_no, dify_result=dify_result, dify_message=dify_message)
|
||||
step_logs.append(_make_step("writeback_srm", "success", t_wb2, _ts(), row_id=row_id_value, detail={"note": "fallback writeback after dify error"}))
|
||||
item["writeback_srm"] = True
|
||||
except Exception as wb_exc:
|
||||
step_logs.append(_make_step("writeback_srm", "failed", t_wb2, _ts(), row_id=row_id_value, detail={"error": str(wb_exc), "note": "fallback writeback also failed"}))
|
||||
item["writeback_srm"] = False
|
||||
item["writeback_err"] = f"{item.get('writeback_err', '')}; writeback failed: {wb_exc}"
|
||||
|
||||
details.append(item)
|
||||
|
||||
if len(step_logs) > _MAX_STEP_LOGS_PER_ROW:
|
||||
step_logs = step_logs[:_MAX_STEP_LOGS_PER_ROW]
|
||||
|
||||
total_count = success_count + failed_count + skipped_count
|
||||
return total_count, success_count, failed_count, skipped_count, details, all_errors
|
||||
|
||||
|
||||
def fetch_rohs_records(conn_str: str) -> list[dict[str, Any]]:
|
||||
return _fetch_records(conn_str, FETCHD_ROHS_SQL)
|
||||
|
||||
|
||||
def writeback_rohs(conn_str: str, *, row_id: str, run_no: str, dify_result: str, dify_message: str) -> None:
|
||||
_execute_writeback(
|
||||
conn_str,
|
||||
"UPDATE control_harmful_substances SET def11=?, def12=?, def13=? WHERE id=?",
|
||||
(run_no, dify_result, dify_message, str(row_id)),
|
||||
)
|
||||
|
||||
|
||||
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]]:
|
||||
def _build_record(conn_str: str, item: dict[str, Any], row_id_value: str) -> tuple[str, str | None]:
|
||||
text = _build_record_text(item, SRM_ROHS_SQL_ALIAS_ORDER, SRM_ROHS_HEADER_LABELS)
|
||||
return text, item.get("attachment")
|
||||
|
||||
return _run_check_job_loop(
|
||||
conn_str=conn_str,
|
||||
run_no=run_no,
|
||||
agent=agent,
|
||||
user=user,
|
||||
wait_seconds=wait_seconds,
|
||||
run_id=run_id,
|
||||
fetch_fn=fetch_rohs_records,
|
||||
build_record_fn=_build_record,
|
||||
writeback_fn=writeback_rohs,
|
||||
row_id_key="id",
|
||||
log_prefix="srm-rohs-dify",
|
||||
)
|
||||
|
||||
|
||||
def fetch_msds_records(conn_str: str) -> list[dict[str, Any]]:
|
||||
return _fetch_records(conn_str, FETCHD_MSDS_SQL)
|
||||
|
||||
|
||||
def fetch_msds_detail_records(conn_str: str, ccm_id: str) -> list[dict[str, Any]]:
|
||||
return _fetch_records(conn_str, FETCHD_MSDS_DETAIL_SQL, params=(str(ccm_id),))
|
||||
|
||||
|
||||
def writeback_msds(conn_str: str, *, row_id: str, run_no: str, dify_result: str, dify_message: str) -> None:
|
||||
_execute_writeback(
|
||||
conn_str,
|
||||
"UPDATE chemical_composition_management SET def11=?, def12=?, def13=? WHERE id=?",
|
||||
(run_no, dify_result, dify_message, str(row_id)),
|
||||
)
|
||||
|
||||
|
||||
def _msds_pre_dify_fn(conn_str: str, item: dict[str, Any], row_id_value: str) -> dict[str, Any] | None:
|
||||
try:
|
||||
detail_rows = fetch_msds_detail_records(conn_str, row_id_value)
|
||||
except Exception as detail_exc:
|
||||
return {
|
||||
"dify_result": "人工判定",
|
||||
"dify_message": f"查询成分明细失败:{detail_exc}",
|
||||
"writeback_srm": False,
|
||||
"writeback_err": str(detail_exc),
|
||||
}
|
||||
detail_summary_lines: list[str] = []
|
||||
for dr in detail_rows:
|
||||
parts = [f"{SRM_MSDS_HEADER_LABELS.get(dk, dk)}: {dr.get(dk, '')}" for dk in SRM_MSDS_DETAIL_ALIAS_ORDER]
|
||||
detail_summary_lines.append(", ".join(parts))
|
||||
item["detail_text"] = "; ".join(detail_summary_lines) if detail_summary_lines else ""
|
||||
item["_detail_rows"] = detail_rows
|
||||
return None
|
||||
|
||||
|
||||
def _msds_build_record(conn_str: str, item: dict[str, Any], row_id_value: str) -> tuple[str, str | None]:
|
||||
detail_rows = item.pop("_detail_rows", [])
|
||||
text = _build_record_text(item, SRM_MSDS_SQL_ALIAS_ORDER, SRM_MSDS_HEADER_LABELS, detail_rows, SRM_MSDS_DETAIL_ALIAS_ORDER)
|
||||
return text, item.get("attachment")
|
||||
|
||||
|
||||
def run_msds_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]]:
|
||||
return _run_check_job_loop(
|
||||
conn_str=conn_str,
|
||||
run_no=run_no,
|
||||
agent=agent,
|
||||
user=user,
|
||||
wait_seconds=wait_seconds,
|
||||
run_id=run_id,
|
||||
fetch_fn=fetch_msds_records,
|
||||
build_record_fn=_msds_build_record,
|
||||
writeback_fn=writeback_msds,
|
||||
row_id_key="ccm_id",
|
||||
log_prefix="srm-msds-dify",
|
||||
pre_dify_fn=_msds_pre_dify_fn,
|
||||
)
|
||||
return total_count, success_count, failed_count, skipped_count, details, all_errors, step_logs
|
||||
Reference in new issue
Block a user