Merge branch 'dev' into test
This commit is contained in:
commit
3612e89f37
5 files changed
+529
-115
No files matched your search
+1
-1
@@ -77,7 +77,7 @@ SRM_SQLSERVER_PORT=1433
|
|||||||
SRM_SQLSERVER_DATABASE=HX-SRM
|
SRM_SQLSERVER_DATABASE=HX-SRM
|
||||||
SRM_SQLSERVER_USERNAME=sa
|
SRM_SQLSERVER_USERNAME=sa
|
||||||
SRM_SQLSERVER_PASSWORD=sa@moreyou456
|
SRM_SQLSERVER_PASSWORD=sa@moreyou456
|
||||||
SRM_SQLSERVER_DRIVER=SQL Server
|
SRM_SQLSERVER_DRIVER=ODBC Driver 18 for SQL Server
|
||||||
SRM_SQLSERVER_ENCRYPT=no
|
SRM_SQLSERVER_ENCRYPT=no
|
||||||
SRM_SQLSERVER_TRUST_CERT=yes
|
SRM_SQLSERVER_TRUST_CERT=yes
|
||||||
SRM_SQLSERVER_TIMEOUT=10
|
SRM_SQLSERVER_TIMEOUT=10
|
||||||
@@ -8,7 +8,14 @@ from flask import current_app
|
|||||||
|
|
||||||
from app import db
|
from app import db
|
||||||
from app.models import Agent, ScheduleRun, ScheduleTask
|
from app.models import Agent, ScheduleRun, ScheduleTask
|
||||||
from app.services.schedule.srm_service import run_rohs_doc_check_dify_job
|
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,
|
||||||
|
)
|
||||||
|
|
||||||
ScheduleExecuteResult = tuple[int, 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]
|
ScheduleExecutor = Callable[[ScheduleTask, ScheduleRun], ScheduleExecuteResult]
|
||||||
@@ -26,6 +33,41 @@ def normalize_platform_api_path(path: str | None) -> str:
|
|||||||
return value
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def _build_srm_conn_str() -> str:
|
||||||
|
host = str(current_app.config.get("SRM_SQLSERVER_HOST") or "").strip()
|
||||||
|
if not host:
|
||||||
|
raise RuntimeError("SRM_SQLSERVER_HOST is not configured")
|
||||||
|
|
||||||
|
port = str(current_app.config.get("SRM_SQLSERVER_PORT") or "1433").strip()
|
||||||
|
database = str(current_app.config.get("SRM_SQLSERVER_DATABASE") or "").strip()
|
||||||
|
username = str(current_app.config.get("SRM_SQLSERVER_USERNAME") or "").strip()
|
||||||
|
password = str(current_app.config.get("SRM_SQLSERVER_PASSWORD") or "").strip()
|
||||||
|
driver = str(current_app.config.get("SRM_SQLSERVER_DRIVER") or "SQL Server").strip()
|
||||||
|
encrypt = str(current_app.config.get("SRM_SQLSERVER_ENCRYPT") or "no").strip().lower()
|
||||||
|
trust_cert = str(current_app.config.get("SRM_SQLSERVER_TRUST_CERT") or "yes").strip().lower()
|
||||||
|
|
||||||
|
return (
|
||||||
|
f"DRIVER={{{driver}}};"
|
||||||
|
f"SERVER={host},{port};"
|
||||||
|
f"DATABASE={database};"
|
||||||
|
f"UID={username};"
|
||||||
|
f"PWD={password};"
|
||||||
|
f"Encrypt={encrypt};"
|
||||||
|
f"TrustServerCertificate={trust_cert};"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_dify_agent(task: ScheduleTask):
|
||||||
|
agent = db.session.get(Agent, task.dify_agent_id) if task.dify_agent_id else None
|
||||||
|
if task.dify_agent_id and (not agent or not agent.dify_api_key):
|
||||||
|
raise RuntimeError("dify_agent_id is invalid or key is missing")
|
||||||
|
return agent
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_schedule_user(task: ScheduleTask) -> str:
|
||||||
|
return str(getattr(task.owner, "username", "") or task.owner_user_id or "schedule_system")
|
||||||
|
|
||||||
|
|
||||||
def _run_common_executor(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
def _run_common_executor(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||||
endpoint = normalize_platform_api_path(task.platform_api_path)
|
endpoint = normalize_platform_api_path(task.platform_api_path)
|
||||||
if not endpoint:
|
if not endpoint:
|
||||||
@@ -75,37 +117,22 @@ def _run_common_executor(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecut
|
|||||||
|
|
||||||
|
|
||||||
def _run_srm_rohs_doc_check_executor(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
def _run_srm_rohs_doc_check_executor(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||||
agent = db.session.get(Agent, task.dify_agent_id) if task.dify_agent_id else None
|
return run_rohs_doc_check_dify_job(
|
||||||
if task.dify_agent_id and (not agent or not agent.dify_api_key):
|
conn_str=_build_srm_conn_str(),
|
||||||
raise RuntimeError("dify_agent_id is invalid or key is missing")
|
run_no=run.run_no,
|
||||||
|
agent=_resolve_dify_agent(task),
|
||||||
host = str(current_app.config.get("SRM_SQLSERVER_HOST") or "").strip()
|
user=_resolve_schedule_user(task),
|
||||||
if not host:
|
wait_seconds=task.wait_seconds or 120,
|
||||||
raise RuntimeError("SRM_SQLSERVER_HOST is not configured")
|
run_id=run.id,
|
||||||
|
|
||||||
port = str(current_app.config.get("SRM_SQLSERVER_PORT") or "1433").strip()
|
|
||||||
database = str(current_app.config.get("SRM_SQLSERVER_DATABASE") or "").strip()
|
|
||||||
username = str(current_app.config.get("SRM_SQLSERVER_USERNAME") or "").strip()
|
|
||||||
password = str(current_app.config.get("SRM_SQLSERVER_PASSWORD") or "").strip()
|
|
||||||
driver = str(current_app.config.get("SRM_SQLSERVER_DRIVER") or "SQL Server").strip()
|
|
||||||
encrypt = str(current_app.config.get("SRM_SQLSERVER_ENCRYPT") or "no").strip().lower()
|
|
||||||
trust_cert = str(current_app.config.get("SRM_SQLSERVER_TRUST_CERT") or "yes").strip().lower()
|
|
||||||
|
|
||||||
conn_str = (
|
|
||||||
f"DRIVER={{{driver}}};"
|
|
||||||
f"SERVER={host},{port};"
|
|
||||||
f"DATABASE={database};"
|
|
||||||
f"UID={username};"
|
|
||||||
f"PWD={password};"
|
|
||||||
f"Encrypt={encrypt};"
|
|
||||||
f"TrustServerCertificate={trust_cert};"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
return run_rohs_doc_check_dify_job(
|
|
||||||
conn_str=conn_str,
|
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,
|
run_no=run.run_no,
|
||||||
agent=agent,
|
agent=_resolve_dify_agent(task),
|
||||||
user=str(getattr(task.owner, "username", "") or task.owner_user_id or "schedule_system"),
|
user=_resolve_schedule_user(task),
|
||||||
wait_seconds=task.wait_seconds or 120,
|
wait_seconds=task.wait_seconds or 120,
|
||||||
run_id=run.id,
|
run_id=run.id,
|
||||||
)
|
)
|
||||||
@@ -114,6 +141,7 @@ def _run_srm_rohs_doc_check_executor(task: ScheduleTask, run: ScheduleRun) -> Sc
|
|||||||
_SCHEDULE_EXECUTOR_REGISTRY: dict[str, ScheduleExecutor] = {
|
_SCHEDULE_EXECUTOR_REGISTRY: dict[str, ScheduleExecutor] = {
|
||||||
"default": _run_common_executor,
|
"default": _run_common_executor,
|
||||||
"srm_rohs_doc_check": _run_srm_rohs_doc_check_executor,
|
"srm_rohs_doc_check": _run_srm_rohs_doc_check_executor,
|
||||||
|
"srm_msds_doc_check": _run_srm_msds_doc_check_executor,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -131,3 +159,26 @@ def resolve_schedule_executor(task: ScheduleTask) -> ScheduleExecutor:
|
|||||||
if lookup_key in _SCHEDULE_EXECUTOR_REGISTRY:
|
if lookup_key in _SCHEDULE_EXECUTOR_REGISTRY:
|
||||||
return _SCHEDULE_EXECUTOR_REGISTRY[lookup_key]
|
return _SCHEDULE_EXECUTOR_REGISTRY[lookup_key]
|
||||||
return _SCHEDULE_EXECUTOR_REGISTRY["default"]
|
return _SCHEDULE_EXECUTOR_REGISTRY["default"]
|
||||||
|
|
||||||
|
|
||||||
|
_SCHEDULE_HEADER_REGISTRY: dict[str, tuple[list[str], dict[str, str]]] = {}
|
||||||
|
|
||||||
|
|
||||||
|
def register_schedule_header(name: str, header_order: list[str], header_labels: dict[str, str]) -> None:
|
||||||
|
key = str(name or "").strip().lower()
|
||||||
|
if not key:
|
||||||
|
raise ValueError("header name is required")
|
||||||
|
_SCHEDULE_HEADER_REGISTRY[key] = (header_order, header_labels)
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_schedule_header(platform_api_path: str | None) -> tuple[list[str] | None, dict[str, str] | None]:
|
||||||
|
path = normalize_platform_api_path(platform_api_path)
|
||||||
|
if path:
|
||||||
|
key = path.lstrip("/").lower()
|
||||||
|
if key in _SCHEDULE_HEADER_REGISTRY:
|
||||||
|
return _SCHEDULE_HEADER_REGISTRY[key]
|
||||||
|
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)
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import json
|
import json
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
@@ -13,40 +13,86 @@ def _flatten_value(v: Any) -> Any:
|
|||||||
return v
|
return v
|
||||||
|
|
||||||
|
|
||||||
def export_schedule_result_excel(*, run_no: str, summary: dict, details: list[dict], root_dir: str) -> tuple[str | None, str | None, int]:
|
def export_schedule_result_excel(
|
||||||
|
*,
|
||||||
|
run_no: str,
|
||||||
|
summary: dict,
|
||||||
|
details: list[dict],
|
||||||
|
root_dir: str,
|
||||||
|
header_order: list[str] | None = None,
|
||||||
|
header_labels: dict[str, str] | None = None,
|
||||||
|
) -> tuple[str | None, str | None, int]:
|
||||||
if not details:
|
if not details:
|
||||||
return None, None, 0
|
return None, None, 0
|
||||||
|
|
||||||
out_root = Path(root_dir)
|
out_root = Path(root_dir)
|
||||||
out_root.mkdir(parents=True, exist_ok=True)
|
out_root.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
rows: list[dict[str, Any]] = []
|
header_order = header_order or []
|
||||||
for row in details:
|
header_labels = header_labels or {}
|
||||||
output = row.get('dify_output')
|
|
||||||
if not isinstance(output, dict):
|
|
||||||
output = {}
|
|
||||||
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)
|
|
||||||
|
|
||||||
headers: list[str] = []
|
rows: list[dict[str, Any]] = []
|
||||||
for row in rows:
|
sql_headers: list[str] = []
|
||||||
for k in row:
|
json_headers: list[str] = []
|
||||||
if k not in headers:
|
exec_result_headers: list[str] = []
|
||||||
headers.append(k)
|
exec_result_order = ["dify_result", "dify_message", "writeback_srm", "writeback_err"]
|
||||||
|
|
||||||
|
def _append_unique(target: list[str], key: str) -> None:
|
||||||
|
if key not in target:
|
||||||
|
target.append(key)
|
||||||
|
|
||||||
|
def _collect_json_headers(obj: Any) -> None:
|
||||||
|
if isinstance(obj, dict):
|
||||||
|
for k in obj.keys():
|
||||||
|
_append_unique(json_headers, str(k))
|
||||||
|
|
||||||
|
for row in details:
|
||||||
|
if not isinstance(row, dict):
|
||||||
|
continue
|
||||||
|
|
||||||
|
flat_row: dict[str, Any] = {}
|
||||||
|
for k, v in row.items():
|
||||||
|
key = str(k)
|
||||||
|
if key in {"dify_output", "json_output", "output"}:
|
||||||
|
_collect_json_headers(v)
|
||||||
|
if isinstance(v, dict):
|
||||||
|
for json_key, json_val in v.items():
|
||||||
|
flat_row[str(json_key)] = _flatten_value(json_val)
|
||||||
|
continue
|
||||||
|
flat_row[key] = _flatten_value(v)
|
||||||
|
if key in exec_result_order:
|
||||||
|
_append_unique(exec_result_headers, key)
|
||||||
|
else:
|
||||||
|
_append_unique(sql_headers, key)
|
||||||
|
|
||||||
|
rows.append(flat_row)
|
||||||
|
|
||||||
|
if not rows:
|
||||||
|
return None, None, 0
|
||||||
|
|
||||||
|
ordered_exec_headers = [k for k in exec_result_order if k in exec_result_headers]
|
||||||
|
other_exec_headers = [k for k in exec_result_headers if k not in exec_result_order]
|
||||||
|
ordered_sql_headers = [k for k in header_order if k in sql_headers]
|
||||||
|
other_sql_headers = [k for k in sql_headers if k not in header_order]
|
||||||
|
headers = (
|
||||||
|
ordered_sql_headers
|
||||||
|
+ other_sql_headers
|
||||||
|
+ [k for k in json_headers if k not in sql_headers and k not in exec_result_headers]
|
||||||
|
+ ordered_exec_headers
|
||||||
|
+ other_exec_headers
|
||||||
|
)
|
||||||
|
|
||||||
wb = Workbook()
|
wb = Workbook()
|
||||||
ws = wb.active
|
ws = wb.active
|
||||||
ws.title = 'result'
|
ws.title = "result"
|
||||||
ws.append(headers)
|
ws.append([header_labels.get(k, k) for k in headers])
|
||||||
|
|
||||||
for row in rows:
|
for row in rows:
|
||||||
ws.append([row.get(k, '') for k in headers])
|
ws.append([row.get(k, "") for k in headers])
|
||||||
|
|
||||||
file_name = f'schedule_{run_no}.xlsx'
|
file_name = f"schedule_{run_no}.xlsx"
|
||||||
file_path = out_root / file_name
|
file_path = out_root / file_name
|
||||||
wb.save(file_path)
|
wb.save(file_path)
|
||||||
size = file_path.stat().st_size
|
size = file_path.stat().st_size
|
||||||
return str(file_path), file_name, int(size)
|
return str(file_path), file_name, int(size)
|
||||||
|
|
||||||
@@ -11,7 +11,7 @@ from flask import current_app
|
|||||||
|
|
||||||
from app import db
|
from app import db
|
||||||
from app.models import ScheduleRun, ScheduleTask, User
|
from app.models import ScheduleRun, ScheduleTask, User
|
||||||
from app.services.schedule import normalize_platform_api_path, resolve_schedule_executor
|
from app.services.schedule import normalize_platform_api_path, resolve_schedule_executor, resolve_schedule_header
|
||||||
from app.services.schedule.excel_service import export_schedule_result_excel
|
from app.services.schedule.excel_service import export_schedule_result_excel
|
||||||
from app.services.schedule.mail_service import build_schedule_mail_html, send_schedule_mail
|
from app.services.schedule.mail_service import build_schedule_mail_html, send_schedule_mail
|
||||||
|
|
||||||
@@ -183,6 +183,7 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
|
|||||||
status = "partial_failed"
|
status = "partial_failed"
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
header_order, header_labels = resolve_schedule_header(task.platform_api_path)
|
||||||
file_path, file_name, file_size = export_schedule_result_excel(
|
file_path, file_name, file_size = export_schedule_result_excel(
|
||||||
run_no=run.run_no,
|
run_no=run.run_no,
|
||||||
summary={
|
summary={
|
||||||
@@ -194,6 +195,8 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
|
|||||||
},
|
},
|
||||||
details=details,
|
details=details,
|
||||||
root_dir=str(current_app.config.get("SCHEDULE_EXCEL_STORAGE_ROOT") or "").strip(),
|
root_dir=str(current_app.config.get("SCHEDULE_EXCEL_STORAGE_ROOT") or "").strip(),
|
||||||
|
header_order=header_order,
|
||||||
|
header_labels=header_labels,
|
||||||
)
|
)
|
||||||
except Exception as excel_exc:
|
except Exception as excel_exc:
|
||||||
if current_app:
|
if current_app:
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from typing import Any
|
from typing import Any, Callable
|
||||||
|
|
||||||
from flask import current_app
|
from flask import current_app
|
||||||
|
|
||||||
from app.services.dify import DifyService
|
from app.services.dify import DifyService
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -11,9 +12,8 @@ except Exception: # pragma: no cover
|
|||||||
pyodbc = None
|
pyodbc = None
|
||||||
|
|
||||||
|
|
||||||
FIXED_ROHS_SQL = """
|
FETCHD_ROHS_SQL = """
|
||||||
select
|
select
|
||||||
TOP(100)
|
|
||||||
t2.supplier_code as supplier_code,
|
t2.supplier_code as supplier_code,
|
||||||
t2.supplier_name as supplier_name,
|
t2.supplier_name as supplier_name,
|
||||||
t2.material_code as item_code,
|
t2.material_code as item_code,
|
||||||
@@ -47,18 +47,148 @@ where
|
|||||||
and t2.def1 = '7'
|
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):
|
def _connect(conn_str: str):
|
||||||
if pyodbc is None:
|
if pyodbc is None:
|
||||||
raise RuntimeError('pyodbc is not installed')
|
raise RuntimeError("pyodbc is not installed")
|
||||||
return pyodbc.connect(conn_str, timeout=15)
|
return pyodbc.connect(conn_str, timeout=15)
|
||||||
|
|
||||||
|
|
||||||
def fetch_rohs_records(conn_str: str) -> list[dict[str, Any]]:
|
def _fetch_records(conn_str: str, sql: str, params: tuple | None = None) -> list[dict[str, Any]]:
|
||||||
conn = _connect(conn_str)
|
conn = _connect(conn_str)
|
||||||
try:
|
try:
|
||||||
cur = conn.cursor()
|
cur = conn.cursor()
|
||||||
cur.execute(FIXED_ROHS_SQL)
|
if params:
|
||||||
|
cur.execute(sql, params)
|
||||||
|
else:
|
||||||
|
cur.execute(sql)
|
||||||
cols = [c[0] for c in cur.description]
|
cols = [c[0] for c in cur.description]
|
||||||
rows = cur.fetchall()
|
rows = cur.fetchall()
|
||||||
return [{cols[i]: row[i] for i in range(len(cols))} for row in rows]
|
return [{cols[i]: row[i] for i in range(len(cols))} for row in rows]
|
||||||
@@ -66,56 +196,123 @@ def fetch_rohs_records(conn_str: str) -> list[dict[str, Any]]:
|
|||||||
conn.close()
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
def writeback_rohs(conn_str: str, *, row_id: str, run_no: str, judgement: str, reason: str) -> None:
|
def _execute_writeback(conn_str: str, sql: str, params: tuple) -> None:
|
||||||
conn = _connect(conn_str)
|
conn = _connect(conn_str)
|
||||||
try:
|
try:
|
||||||
cur = conn.cursor()
|
cur = conn.cursor()
|
||||||
cur.execute(
|
cur.execute(sql, params)
|
||||||
"UPDATE control_harmful_substances SET def11=?, def12=?, def13=? WHERE id=?",
|
|
||||||
(run_no, judgement, reason, str(row_id)),
|
|
||||||
)
|
|
||||||
conn.commit()
|
conn.commit()
|
||||||
finally:
|
finally:
|
||||||
conn.close()
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
def _derive_judgement_and_reason(data: dict[str, Any]) -> tuple[str, str]:
|
def _derive_dify_result_and_message(data: dict[str, Any]) -> tuple[str, str]:
|
||||||
judgement = str(data.get("judgement") or data.get("result") or "人工判定").strip()
|
dify_result = str(data.get("dify_result") or data.get("result") or "人工判定").strip()
|
||||||
reason = str(data.get("reason") or "").strip()
|
dify_message = str(data.get("dify_message") or data.get("message") or data.get("messge") or "").strip()
|
||||||
if judgement not in {"合格", "不合格", "人工判定"}:
|
if dify_result not in {"合格", "不合格", "人工判定"}:
|
||||||
reason = (reason + " | 返回值异常:" + judgement).strip(" |")
|
dify_message = (dify_message + " | 返回值异常:" + dify_result).strip(" |")
|
||||||
judgement = "人工判定"
|
dify_result = "人工判定"
|
||||||
return judgement, reason
|
return dify_result, dify_message
|
||||||
|
|
||||||
|
|
||||||
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_text(
|
||||||
|
item: dict[str, Any],
|
||||||
|
alias_order: list[str],
|
||||||
|
header_labels: dict[str, str],
|
||||||
|
detail_rows: list[dict[str, Any]] | None = None,
|
||||||
|
detail_alias_order: list[str] | None = None,
|
||||||
|
) -> str:
|
||||||
|
lines: list[str] = []
|
||||||
|
for key in alias_order:
|
||||||
|
label = header_labels.get(key, key)
|
||||||
|
value = item.get(key)
|
||||||
|
text = "" if value is None else str(value)
|
||||||
|
lines.append(f"{label}: {text}")
|
||||||
|
if detail_rows and detail_alias_order:
|
||||||
|
lines.append("成分明细:")
|
||||||
|
for idx, dr in enumerate(detail_rows, 1):
|
||||||
|
detail_parts: list[str] = []
|
||||||
|
for dk in detail_alias_order:
|
||||||
|
dl = header_labels.get(dk, dk)
|
||||||
|
dv = dr.get(dk)
|
||||||
|
detail_parts.append(f"{dl}: {'' if dv is None else str(dv)}")
|
||||||
|
lines.append(f" [{idx}] " + ", ".join(detail_parts))
|
||||||
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
|
||||||
|
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]
|
||||||
|
|
||||||
|
|
||||||
|
def _run_check_job_loop(
|
||||||
|
*,
|
||||||
|
conn_str: str,
|
||||||
|
run_no: str,
|
||||||
|
agent,
|
||||||
|
user: str,
|
||||||
|
wait_seconds: int,
|
||||||
|
run_id: int | None,
|
||||||
|
fetch_fn: Callable[[str], list[dict[str, Any]]],
|
||||||
|
build_record_fn: RecordBuilder,
|
||||||
|
writeback_fn: WritebackFunc,
|
||||||
|
row_id_key: str,
|
||||||
|
log_prefix: str,
|
||||||
|
pre_dify_fn: PreDifyFunc | None = None,
|
||||||
|
) -> tuple[int, int, int, int, list[dict[str, Any]], list[str]]:
|
||||||
|
from app.services.schedule.scheduler_service import is_run_cancelled
|
||||||
|
|
||||||
use_dify = agent is not None
|
use_dify = agent is not None
|
||||||
if use_dify and not getattr(agent, "dify_api_key", 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")
|
raise RuntimeError("dify_agent_id is set, but Dify api key is missing")
|
||||||
|
|
||||||
rows = fetch_rohs_records(conn_str)
|
rows = fetch_fn(conn_str)
|
||||||
total_count = len(rows)
|
|
||||||
details: list[dict[str, Any]] = []
|
details: list[dict[str, Any]] = []
|
||||||
success_count = 0
|
success_count = 0
|
||||||
failed_count = 0
|
failed_count = 0
|
||||||
skipped_count = 0
|
skipped_count = 0
|
||||||
errors: list[str] = []
|
all_errors: list[str] = []
|
||||||
|
|
||||||
from app.services.schedule.scheduler_service import is_run_cancelled
|
for row in rows:
|
||||||
for idx, row in enumerate(rows):
|
|
||||||
if run_id is not None and is_run_cancelled(run_id):
|
if run_id is not None and is_run_cancelled(run_id):
|
||||||
item = dict(row)
|
item = dict(row)
|
||||||
item.update({"judgement": "人工判定", "reason": "排程已被删除,执行中断", "writeback_ok": False, "error": "排程已被删除,执行中断"})
|
item.update({
|
||||||
|
"dify_result": "人工判定",
|
||||||
|
"dify_message": "排程已被删除,执行中断",
|
||||||
|
"writeback_srm": False,
|
||||||
|
"writeback_err": "排程已被删除,执行中断",
|
||||||
|
})
|
||||||
skipped_count += 1
|
skipped_count += 1
|
||||||
details.append(item)
|
details.append(item)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
item = dict(row)
|
item = dict(row)
|
||||||
|
row_id_value = str(row.get(row_id_key, ""))
|
||||||
|
|
||||||
|
if pre_dify_fn:
|
||||||
|
pre_result = pre_dify_fn(conn_str, item, row_id_value)
|
||||||
|
if pre_result is not None:
|
||||||
|
item.update(pre_result)
|
||||||
|
failed_count += 1
|
||||||
|
all_errors.append(pre_result.get("writeback_err", ""))
|
||||||
|
details.append(item)
|
||||||
|
continue
|
||||||
|
|
||||||
|
record_text, attachment_url = build_record_fn(conn_str, item, row_id_value)
|
||||||
|
|
||||||
dify_ok = False
|
dify_ok = False
|
||||||
|
dify_result = "人工判定"
|
||||||
|
dify_message = ""
|
||||||
|
|
||||||
try:
|
try:
|
||||||
if use_dify:
|
if use_dify:
|
||||||
dify_res = DifyService.run_workflow_streaming(
|
dify_res = DifyService.run_workflow_streaming(
|
||||||
agent=agent,
|
agent=agent,
|
||||||
inputs={"inputs": {"run_no": run_no, "records": item}},
|
inputs={
|
||||||
|
"run_no": run_no,
|
||||||
|
"record": record_text,
|
||||||
|
"attachment_url": attachment_url,
|
||||||
|
},
|
||||||
user=user,
|
user=user,
|
||||||
timeout=(5, max(300, int(wait_seconds))),
|
timeout=(5, max(300, int(wait_seconds))),
|
||||||
)
|
)
|
||||||
@@ -123,64 +320,181 @@ def run_rohs_doc_check_dify_job(*, conn_str: str, run_no: str, agent=None, user:
|
|||||||
dify_error = dify_res.get("error") 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")):
|
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}"
|
err_detail = str(dify_error) if dify_error else f"Dify status={dify_status}"
|
||||||
judgement = "人工判定"
|
dify_result = "人工判定"
|
||||||
reason = f"Dify执行失败:{err_detail}"
|
dify_message = 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 {}})
|
item.update({
|
||||||
|
"dify_result": dify_result,
|
||||||
|
"dify_message": dify_message,
|
||||||
|
"writeback_srm": False,
|
||||||
|
"writeback_err": err_detail,
|
||||||
|
})
|
||||||
failed_count += 1
|
failed_count += 1
|
||||||
errors.append(f"Dify row_id={row.get('id')}: {err_detail}")
|
all_errors.append(f"Dify {log_prefix}={row_id_value}: {err_detail}")
|
||||||
|
details.append(item)
|
||||||
|
continue
|
||||||
else:
|
else:
|
||||||
outputs = (dify_res.get("outputs") or {}).get("output") or dify_res.get("outputs") or dify_res
|
outputs = (dify_res.get("outputs") or {}).get("output") or dify_res.get("outputs") or dify_res
|
||||||
if current_app:
|
if current_app:
|
||||||
current_app.logger.info(
|
current_app.logger.info(
|
||||||
"[srm-dify] judgement=%s reason=%s",
|
"[%s] %s=%s dify_result=%s dify_message=%s",
|
||||||
outputs.get("judgement") if isinstance(outputs, dict) else None,
|
log_prefix, log_prefix, row_id_value,
|
||||||
outputs.get("reason") if isinstance(outputs, dict) else None,
|
(outputs.get("dify_result") or outputs.get("result")) if isinstance(outputs, dict) else None,
|
||||||
|
(outputs.get("dify_message") or outputs.get("message")) if isinstance(outputs, dict) else None,
|
||||||
)
|
)
|
||||||
judgement, reason = _derive_judgement_and_reason(outputs if isinstance(outputs, dict) else {})
|
dify_result, dify_message = _derive_dify_result_and_message(outputs if isinstance(outputs, dict) else {})
|
||||||
item["dify_output"] = outputs if isinstance(outputs, dict) else {}
|
|
||||||
dify_ok = True
|
dify_ok = True
|
||||||
else:
|
else:
|
||||||
judgement = "人工判定"
|
dify_result = "人工判定"
|
||||||
reason = "未配置 Agent ID,跳过 Dify"
|
dify_message = "未配置 Agent ID,跳过 Dify"
|
||||||
dify_ok = True
|
dify_ok = True
|
||||||
|
|
||||||
try:
|
try:
|
||||||
writeback_rohs(
|
writeback_fn(conn_str, row_id=row_id_value, run_no=run_no, dify_result=dify_result, dify_message=dify_message)
|
||||||
conn_str,
|
item.update({
|
||||||
row_id=str(row.get("id")),
|
"dify_result": dify_result,
|
||||||
run_no=run_no,
|
"dify_message": dify_message,
|
||||||
judgement=judgement,
|
"writeback_srm": True,
|
||||||
reason=reason,
|
"writeback_err": item.get("writeback_err"),
|
||||||
)
|
})
|
||||||
item.update({"judgement": judgement, "reason": reason, "writeback_ok": True, "error": item.get("error")})
|
|
||||||
if dify_ok:
|
if dify_ok:
|
||||||
success_count += 1
|
success_count += 1
|
||||||
except Exception as wb_exc:
|
except Exception as wb_exc:
|
||||||
if current_app:
|
if current_app:
|
||||||
current_app.logger.error("[srm-dify] writeback failed row_id=%s error=%s", row.get("id"), wb_exc)
|
current_app.logger.error("[%s] writeback failed %s=%s error=%s", log_prefix, log_prefix, row_id_value, wb_exc)
|
||||||
item.update({"judgement": judgement, "reason": reason, "writeback_ok": False, "error": str(wb_exc)})
|
item.update({
|
||||||
|
"dify_result": dify_result,
|
||||||
|
"dify_message": dify_message,
|
||||||
|
"writeback_srm": False,
|
||||||
|
"writeback_err": str(wb_exc),
|
||||||
|
})
|
||||||
if dify_ok:
|
if dify_ok:
|
||||||
failed_count += 1
|
failed_count += 1
|
||||||
errors.append(f"writeback row_id={row.get('id')}: {wb_exc}")
|
all_errors.append(f"writeback {log_prefix}={row_id_value}: {wb_exc}")
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
judgement = "人工判定"
|
dify_result = "人工判定"
|
||||||
reason = f"执行异常:{exc}"
|
dify_message = f"执行异常:{exc}"
|
||||||
item.update({"judgement": judgement, "reason": reason, "writeback_ok": False, "error": str(exc)})
|
item.update({
|
||||||
|
"dify_result": dify_result,
|
||||||
|
"dify_message": dify_message,
|
||||||
|
"writeback_srm": False,
|
||||||
|
"writeback_err": str(exc),
|
||||||
|
})
|
||||||
failed_count += 1
|
failed_count += 1
|
||||||
errors.append(str(exc))
|
all_errors.append(str(exc))
|
||||||
try:
|
try:
|
||||||
writeback_rohs(
|
writeback_fn(conn_str, row_id=row_id_value, run_no=run_no, dify_result=dify_result, dify_message=dify_message)
|
||||||
conn_str,
|
item["writeback_srm"] = True
|
||||||
row_id=str(row.get("id")),
|
|
||||||
run_no=run_no,
|
|
||||||
judgement=judgement,
|
|
||||||
reason=reason,
|
|
||||||
)
|
|
||||||
item["writeback_ok"] = True
|
|
||||||
except Exception as wb_exc:
|
except Exception as wb_exc:
|
||||||
item["writeback_ok"] = False
|
item["writeback_srm"] = False
|
||||||
item["error"] = f"{item.get('error', '')}; writeback failed: {wb_exc}"
|
item["writeback_err"] = f"{item.get('writeback_err', '')}; writeback failed: {wb_exc}"
|
||||||
|
|
||||||
details.append(item)
|
details.append(item)
|
||||||
|
|
||||||
total_count = success_count + failed_count + skipped_count
|
total_count = success_count + failed_count + skipped_count
|
||||||
return total_count, success_count, failed_count, skipped_count, details, errors
|
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,
|
||||||
|
)
|
||||||
Reference in new issue
Block a user