149 lines
5.2 KiB
Python
149 lines
5.2 KiB
Python
from __future__ import annotations
|
|
|
|
from typing import Any
|
|
|
|
from flask import current_app
|
|
from app.services.dify import DifyService
|
|
|
|
try:
|
|
import pyodbc # type: ignore
|
|
except Exception: # pragma: no cover
|
|
pyodbc = None
|
|
|
|
|
|
FIXED_ROHS_SQL = """
|
|
select
|
|
TOP(100)
|
|
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'
|
|
"""
|
|
|
|
|
|
def _connect(conn_str: str):
|
|
if pyodbc is None:
|
|
raise RuntimeError('pyodbc is not installed')
|
|
return pyodbc.connect(conn_str, timeout=15)
|
|
|
|
|
|
def fetch_rohs_records(conn_str: str) -> list[dict[str, Any]]:
|
|
conn = _connect(conn_str)
|
|
try:
|
|
cur = conn.cursor()
|
|
cur.execute(FIXED_ROHS_SQL)
|
|
cols = [c[0] for c in cur.description]
|
|
rows = cur.fetchall()
|
|
return [{cols[i]: row[i] for i in range(len(cols))} for row in rows]
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
def writeback_rohs(conn_str: str, *, row_id: str, run_no: str, judgement: str, reason: str) -> None:
|
|
conn = _connect(conn_str)
|
|
try:
|
|
cur = conn.cursor()
|
|
cur.execute(
|
|
"UPDATE control_harmful_substances SET def11=?, def12=?, def13=? WHERE id=?",
|
|
(run_no, judgement, reason, str(row_id)),
|
|
)
|
|
conn.commit()
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
def _derive_judgement_and_reason(data: dict[str, Any]) -> tuple[str, str]:
|
|
judgement = str(data.get("judgement") or data.get("result") or "人工判定").strip()
|
|
reason = str(data.get("reason") or "").strip()
|
|
if judgement not in {"合格", "不合格", "人工判定"}:
|
|
reason = (reason + " | 返回值异常:" + judgement).strip(" |")
|
|
judgement = "人工判定"
|
|
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]]:
|
|
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_rohs_records(conn_str)
|
|
total_count = len(rows)
|
|
details: list[dict[str, Any]] = []
|
|
success_count = 0
|
|
failed_count = 0
|
|
errors: list[str] = []
|
|
|
|
for row in rows:
|
|
item = dict(row)
|
|
try:
|
|
if use_dify:
|
|
dify_res = DifyService.run_workflow_streaming(
|
|
agent=agent,
|
|
inputs={"inputs": {"run_no": run_no, "records": item}},
|
|
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 {}
|
|
else:
|
|
judgement = "人工判定"
|
|
reason = "未配置 Agent ID,跳过 Dify"
|
|
|
|
try:
|
|
writeback_rohs(
|
|
conn_str,
|
|
row_id=str(row.get("id")),
|
|
run_no=run_no,
|
|
judgement=judgement,
|
|
reason=reason,
|
|
)
|
|
item.update({"judgement": judgement, "reason": reason, "writeback_ok": True, "error": None})
|
|
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
|
|
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)})
|
|
failed_count += 1
|
|
errors.append(str(exc))
|
|
details.append(item)
|
|
|
|
return total_count, success_count, failed_count, details, errors
|