"""
backend/app/services/integrations/plm/oracle.py
用途:PLM Oracle 物料/SOP 查询与流式聊天快路径。
依赖:Flask current_app、Text2SQLService、ChatLog 模型。
逻辑:聊天意图路由命中 PLM 时调用;查询 Oracle 并格式化为 SSE 结果。
"""
import json
import os
import re
import time
from datetime import datetime
from html import escape
from urllib.parse import quote
from flask import current_app
from app import db
from app.models import ChatLog
from app.services.integrations.text2sql import Text2SQLService
class PLMOracleService:
_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,})",
re.IGNORECASE,
)
_RELATIONAL_SQL = """
select *
from bi_file endb
where endb.revisionguid in (
select bb.revisionguid
from (
select v.end1, b.*
from viewobject_0 v, NT_00064_0 str, NT_00016_0 cad, bi_file b
where v.name in ('ITEM-CAD2D$', 'ITEM-CAD3D$')
and str.viewfk = v.guid
and str.end2$master = cad.masterfk
and cad.latestrevision like '%m%'
and b.revisionguid = cad.guid
union
select v.end1, b.*
from viewobject_0 v, NT_00064_0 str, NT_00018_0 cad, bi_file b
where v.name in ('ITEM-CAD2D$', 'ITEM-CAD3D$')
and str.viewfk = v.guid
and str.end2$master = cad.masterfk
and cad.latestrevision like '%m%'
and b.revisionguid = cad.guid
union
select v.end1, b.*
from viewobject_0 v,
StructureObject_0 str,
document_0 doc,
bi_file b
where v.name in ('RelatedDoc')
and str.viewfk = v.guid
and str.end2$master = doc.masterfk
and doc.latestrevision like '%m%'
and b.revisionguid = doc.guid
) bb,
item_0 i
where bb.end1 = i.guid
and i.id = :item_id
and i.latestrevision like '%m%'
)
and endb.lastaccesstime is not null
"""
_FILENAME_SQL = """
select *
from bi_file
where upper(name) like :name_pattern
and lastaccesstime is not null
order by lastaccesstime desc nulls last
"""
@classmethod
def supports(cls, query: str, agent) -> bool:
_ = agent
return bool(cls.extract_material_no(query))
@classmethod
def extract_material_no(cls, query: str) -> str | None:
text = str(query or "").strip().upper()
if not text:
return None
explicit = cls._EXPLICIT_LABEL_PATTERN.search(text)
if explicit:
return explicit.group(1).strip().upper()
direct_match = cls._MATERIAL_PATTERN.fullmatch(text)
if direct_match:
return direct_match.group(0).upper()
for match in cls._MATERIAL_PATTERN.finditer(text):
candidate = match.group(0).upper()
if any(ch.isalpha() for ch in candidate) and any(ch.isdigit() for ch in candidate):
return candidate
return None
@staticmethod
def _get_connect_kwargs() -> dict:
dsn = (os.getenv("PLM_ORACLE_DSN") or "").strip()
host = (os.getenv("PLM_ORACLE_HOST") or "192.168.0.11").strip()
port = int((os.getenv("PLM_ORACLE_PORT") or "1521").strip())
service_name = (os.getenv("PLM_ORACLE_SERVICE_NAME") or "").strip()
sid = (os.getenv("PLM_ORACLE_SID") or "orcl").strip()
kwargs = {
"user": (os.getenv("PLM_ORACLE_USERNAME") or "PLM").strip(),
"password": (os.getenv("PLM_ORACLE_PASSWORD") or "PLM").strip(),
}
if dsn:
kwargs["dsn"] = dsn
return kwargs
import oracledb
if service_name:
kwargs["dsn"] = oracledb.makedsn(host, port, service_name=service_name)
else:
kwargs["dsn"] = oracledb.makedsn(host, port, sid=sid)
return kwargs
@classmethod
def _connect(cls):
try:
import oracledb
except ImportError as exc:
raise RuntimeError("oracledb 未安装,无法连接 PLM Oracle") from exc
oracle_client_dir = Text2SQLService._get_oracle_client_dir()
Text2SQLService._prepare_oracle_runtime_env(oracle_client_dir)
Text2SQLService._init_oracle_client(oracledb)
return oracledb.connect(**cls._get_connect_kwargs())
@classmethod
def _execute_query(cls, sql: str, **params) -> tuple[list[str], list[tuple]]:
connection = cls._connect()
cursor = connection.cursor()
try:
cursor.execute(sql, params)
columns = [col[0] for col in cursor.description] if cursor.description else []
rows = cursor.fetchmany(cls._MAX_RESULT_ROWS + 1)
return columns, rows
finally:
try:
cursor.close()
finally:
connection.close()
@classmethod
def _query_files(cls, material_no: str) -> tuple[list[str], list[tuple], str]:
try:
columns, rows = cls._execute_query(cls._RELATIONAL_SQL, item_id=material_no)
if rows:
return columns, rows, "relational"
except Exception as exc:
if current_app:
current_app.logger.warning("[plm-oracle] relational query failed for %s: %s", material_no, exc)
columns, rows = cls._execute_query(
cls._FILENAME_SQL,
name_pattern=f"{material_no.upper()}%",
)
return columns, rows, "filename_fallback"
@staticmethod
def _format_datetime(value) -> str:
if value is None:
return "-"
if isinstance(value, datetime):
return value.strftime("%Y-%m-%d %H:%M:%S")
return str(value)
@staticmethod
def _format_size(value) -> str:
if value in (None, ""):
return "-"
try:
size = int(value)
except (TypeError, ValueError):
return str(value)
if size < 1024:
return f"{size} B"
if size < 1024 * 1024:
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'{escape(file_name)}'
@staticmethod
def _escape_markdown_cell(value: str) -> str:
return str(value).replace("|", r"\|").replace("\r", " ").replace("\n", "
")
@staticmethod
def _escape_html_text(value) -> str:
return escape(str(value), quote=True).replace("\r", " ").replace("\n", "
")
@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(
"
| 字段 | " "值 | " "
|---|