Merge branch 'dev' into hugo
This commit is contained in:
commit
3264ed1e07
3 files changed
+513
-71
No files matched your search
@@ -22,7 +22,7 @@ class Text2SQLService:
|
||||
"ERP_FAF_FILE_V",
|
||||
)
|
||||
_ASSET_COLUMN_LABELS = {
|
||||
"ASSET_NO": "财产编号",
|
||||
"ASSET_NO": "资产编号",
|
||||
"ASSET_NAME": "资产名称",
|
||||
"SPECIFICATION": "规格型号",
|
||||
"UNIT_PRICE": "本币单价",
|
||||
@@ -34,17 +34,17 @@ class Text2SQLService:
|
||||
"ASSET_TYPE": "资产类型",
|
||||
"ASSET_SUBTYPE": "资产次类型",
|
||||
"ASSET_SUB_TYPE": "资产次类型",
|
||||
"CUSTODIAN": "保管人",
|
||||
"CUSTODIAN": "保管人姓名",
|
||||
"CUSTODIAN_ID": "保管人工号",
|
||||
"CUSTODIAN_NAME": "保管人",
|
||||
"DEPARTMENT": "保管部门",
|
||||
"DEPARTMENT_NAME": "保管部门",
|
||||
"LOCATION": "存放位置",
|
||||
"LOCATION_NAME": "存放位置",
|
||||
"CUSTODIAN_NAME": "保管人姓名",
|
||||
"DEPARTMENT": "保管部门名称",
|
||||
"DEPARTMENT_NAME": "保管部门名称",
|
||||
"LOCATION": "存放位置名称",
|
||||
"LOCATION_NAME": "存放位置名称",
|
||||
"SITE": "营运中心代码",
|
||||
"SITE_DESC": "营运中心名称",
|
||||
"FAJ01": "序号",
|
||||
"FAJ02": "财产编号",
|
||||
"FAJ02": "资产编号",
|
||||
"FAJ021": "类型",
|
||||
"FAJ022": "附号",
|
||||
"FAJ03": "取得方式",
|
||||
@@ -60,9 +60,9 @@ class Text2SQLService:
|
||||
"FAJ14": "本币成本",
|
||||
"FAJ17": "数量",
|
||||
"FAJ18": "计量单位",
|
||||
"FAJ19": "保管人",
|
||||
"FAJ20": "保管部门",
|
||||
"FAJ21": "存放位置",
|
||||
"FAJ19": "保管人姓名",
|
||||
"FAJ20": "保管部门名称",
|
||||
"FAJ21": "存放位置名称",
|
||||
"FAJ22": "存放营运中心",
|
||||
"FAJ25": "取得日期",
|
||||
"FAJ26": "入账日期",
|
||||
@@ -124,7 +124,11 @@ class Text2SQLService:
|
||||
"当前登录用户",
|
||||
"登录用户",
|
||||
)
|
||||
_ASSET_RESULT_CODE_COLUMNS = {"财产编号", "资产编码", "ASSET_NO", "FAJ02"}
|
||||
_ASSET_CODE_HINT_PATTERN = re.compile(
|
||||
r"(?:资产编号|财产编号|资产编码|设备编号|编号|设备|资产|固资|固定资产)\s*(?:为|是|=|:|:)?\s*([A-Za-z][A-Za-z0-9_-]{4,30})",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
_ASSET_RESULT_CODE_COLUMNS = {"资产编号", "财产编号", "资产编码", "ASSET_NO", "FAJ02"}
|
||||
_ASSET_RESULT_STATUS_COLUMNS = {"资产状态", "ASSET_STATUS", "FAJ43"}
|
||||
_ASSET_STATUS_SORT_ORDER = {
|
||||
"0": 0,
|
||||
@@ -459,7 +463,8 @@ class Text2SQLService:
|
||||
query_text = str(query or "")
|
||||
sql_text = str(sql or "")
|
||||
return (
|
||||
any(keyword in query_text for keyword in ("固定资产", "固资"))
|
||||
any(keyword in query_text for keyword in ("固定资产", "固资", "资产编号", "财产编号", "资产编码"))
|
||||
or bool(cls._extract_asset_code(query_text))
|
||||
or any(marker.lower() in sql_text.lower() for marker in cls._ASSET_TABLE_MARKERS)
|
||||
)
|
||||
|
||||
@@ -483,10 +488,36 @@ class Text2SQLService:
|
||||
@staticmethod
|
||||
def _clean_asset_scope_value(value: str | None) -> str:
|
||||
text = str(value or "").strip()
|
||||
text = re.sub(r"^(请问|帮我|看下|查下|查询|统计|核对|看看|我想知道)", "", text)
|
||||
text = re.sub(r"(有哪些|有多少|多少|名下|的资产|的固定资产|固定资产|固资|资产)$", "", text)
|
||||
text = re.sub(r"^(请问|帮我|看下|查下|查询|统计|核对|看看|我想知道|在)", "", text)
|
||||
text = re.sub(r"(?:的|下)?(?:有哪些|有多少|多少|名下|资产|固定资产|固资|列表|明细|电脑|设备|机|工装|模具|车辆).*$", "", text)
|
||||
return text.strip(" ::,,。.??")
|
||||
|
||||
@classmethod
|
||||
def _extract_advanced_asset_conditions(cls, query: str) -> dict[str, str]:
|
||||
conds = {}
|
||||
|
||||
m = re.search(r"(?:规格型号|规格|型号)(?:为|是|叫|=|:|:)?\s*([A-Za-z0-9\u4e00-\u9fff_*-]+)", query)
|
||||
if m:
|
||||
val = cls._clean_asset_scope_value(m.group(1))
|
||||
if val: conds["spec"] = val
|
||||
|
||||
m = re.search(r"(?:资产类型|类型)(?:为|是|叫|=|:|:)?\s*([A-Za-z0-9\u4e00-\u9fff_*-]+)", query)
|
||||
if m:
|
||||
val = cls._clean_asset_scope_value(m.group(1))
|
||||
if val: conds["type"] = val
|
||||
|
||||
m = re.search(r"(?:资产状态|状态)(?:为|是|叫|=|:|:)?\s*([A-Za-z0-9\u4e00-\u9fff_*-]+)", query)
|
||||
if m:
|
||||
val = cls._clean_asset_scope_value(m.group(1))
|
||||
if val: conds["status"] = val
|
||||
|
||||
m = re.search(r"(?:存放位置|位置)(?:在|为|是|叫|=|:|:)?\s*([A-Za-z0-9\u4e00-\u9fff_*-]+)", query)
|
||||
if m:
|
||||
val = cls._clean_asset_scope_value(m.group(1))
|
||||
if val: conds["location"] = val
|
||||
|
||||
return conds
|
||||
|
||||
@staticmethod
|
||||
def _strip_asset_query_prefix(text: str) -> str:
|
||||
return re.sub(r"^\s*(?:请问|帮我|看下|查下|查询|统计|核对|看看|我想知道)\s*", "", str(text or "").strip())
|
||||
@@ -518,14 +549,17 @@ class Text2SQLService:
|
||||
return candidate
|
||||
|
||||
direct_patterns = [
|
||||
r"^\s*([A-Za-z0-9\u4e00-\u9fff_-]{2,20}?)(?:名下(?:的)?)?(?:固定资产|固资|资产)\s*$",
|
||||
r"^\s*([A-Za-z0-9\u4e00-\u9fff_-]{2,20}?)(?:名下(?:的)?)?(?:有哪些|有多少|多少)(?:固定资产|固资|资产)\s*$",
|
||||
r"^\s*([A-Za-z0-9\u4e00-\u9fff_-]{2,20}?)(?:名下)(?:的)?(?:固定资产|固资|资产)\s*$",
|
||||
r"^\s*([A-Za-z0-9\u4e00-\u9fff_-]{2,20}?)(?:名下)(?:的)?(?:有哪些|有多少|多少)(?:固定资产|固资|资产)\s*$",
|
||||
]
|
||||
for pattern in direct_patterns:
|
||||
match = re.search(pattern, text)
|
||||
if not match:
|
||||
continue
|
||||
candidate = cls._clean_asset_scope_value(match.group(1))
|
||||
|
||||
raw_candidate = match.group(1)
|
||||
|
||||
candidate = cls._clean_asset_scope_value(raw_candidate)
|
||||
if not candidate:
|
||||
continue
|
||||
if candidate in {*cls._ASSET_SELF_QUERY_MARKERS, "公司"}:
|
||||
@@ -534,6 +568,7 @@ class Text2SQLService:
|
||||
continue
|
||||
if cls._ASSET_SUFFIX_DEPARTMENT_PATTERN.fullmatch(candidate):
|
||||
continue
|
||||
|
||||
return candidate
|
||||
return ""
|
||||
|
||||
@@ -578,10 +613,16 @@ class Text2SQLService:
|
||||
text = cls._strip_asset_query_prefix(query)
|
||||
if not text:
|
||||
return ""
|
||||
if cls._extract_asset_code(text):
|
||||
return ""
|
||||
if cls._extract_advanced_asset_conditions(query):
|
||||
return ""
|
||||
if cls._is_self_asset_query(text):
|
||||
return ""
|
||||
if cls._extract_explicit_asset_department(text):
|
||||
return ""
|
||||
if cls._extract_explicit_asset_person(text):
|
||||
return ""
|
||||
|
||||
patterns = [
|
||||
r"^\s*(?P<keyword>[A-Za-z0-9\u4e00-\u9fff()()\-_]{2,40}?)(?:有多少|多少|有哪些|有什么)(?:固定资产|固资|资产)\s*$",
|
||||
@@ -603,6 +644,56 @@ class Text2SQLService:
|
||||
if cls._looks_like_person_name(keyword):
|
||||
continue
|
||||
return keyword
|
||||
|
||||
if re.fullmatch(r"^\s*[A-Za-z0-9\u4e00-\u9fff()()\-_]{2,40}\s*$", text):
|
||||
cleaned = cls._clean_asset_scope_value(text)
|
||||
if cleaned and cleaned not in {"公司", "全部", "所有", "当前", "目前", "你好", "在吗", "是谁", "是什么", "固定资产", "固资", "资产", "设备"}:
|
||||
if not cls._looks_like_person_name(cleaned) and not cls._ASSET_SUFFIX_DEPARTMENT_PATTERN.fullmatch(cleaned):
|
||||
return cleaned
|
||||
# 如果看起来像人名或部门,我们也把它当做泛关键字处理
|
||||
return cleaned
|
||||
|
||||
return ""
|
||||
|
||||
@staticmethod
|
||||
def _looks_like_asset_code_token(token: str) -> bool:
|
||||
"""判断候选 token 是否像资产编号。
|
||||
|
||||
AI 触发时机:当用户问题里夹带 `A0827011` 这类编号时,优先把它识别成财产编号,
|
||||
避免被误当成资产名称关键词,导致 LLM 生成模糊搜索 SQL。
|
||||
"""
|
||||
value = str(token or "").strip()
|
||||
if not re.fullmatch(r"[A-Za-z0-9_-]{5,30}", value):
|
||||
return False
|
||||
has_letter = any(char.isalpha() for char in value)
|
||||
has_digit = any(char.isdigit() for char in value)
|
||||
return has_letter and has_digit
|
||||
|
||||
@classmethod
|
||||
def _extract_asset_code(cls, query: str) -> str:
|
||||
"""从固资问句里抽取资产编号/财产编号。
|
||||
|
||||
AI 触发时机:用户直接问“查询设备A0827011”“查询资产编号为A0827011”时,
|
||||
必须走精确编号查询,而不是模糊名称查询。
|
||||
"""
|
||||
text = cls._strip_asset_query_prefix(query)
|
||||
if not text:
|
||||
return ""
|
||||
|
||||
if cls._looks_like_asset_code_token(text):
|
||||
return text.upper()
|
||||
|
||||
match = cls._ASSET_CODE_HINT_PATTERN.search(text)
|
||||
if match:
|
||||
candidate = str(match.group(1) or "").strip()
|
||||
if cls._looks_like_asset_code_token(candidate):
|
||||
return candidate.upper()
|
||||
|
||||
if any(marker in text for marker in ("资产", "设备", "固资", "固定资产", "编号")):
|
||||
candidates = re.findall(r"[A-Za-z][A-Za-z0-9_-]{4,30}", text)
|
||||
exact_matches = [candidate.upper() for candidate in candidates if cls._looks_like_asset_code_token(candidate)]
|
||||
if len(exact_matches) == 1:
|
||||
return exact_matches[0]
|
||||
return ""
|
||||
|
||||
@classmethod
|
||||
@@ -696,15 +787,24 @@ class Text2SQLService:
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def _build_asset_name_detail_sql(cls, keyword: str, query: str = "") -> str:
|
||||
literal = cls._escape_sql_literal(keyword)
|
||||
def _build_asset_code_condition(cls, base_alias: str, query: str) -> str:
|
||||
"""为财产编号构造精确过滤条件。"""
|
||||
asset_code = cls._extract_asset_code(query)
|
||||
if not asset_code:
|
||||
return ""
|
||||
literal = cls._escape_sql_literal(asset_code)
|
||||
return f"UPPER(TRIM(NVL({base_alias}.faj02, ''))) LIKE '%' || UPPER('{literal}') || '%'"
|
||||
|
||||
@classmethod
|
||||
def _build_asset_code_detail_sql(cls, asset_code: str, query: str = "") -> str:
|
||||
"""直接按财产编号构造固资明细 SQL。"""
|
||||
literal = cls._escape_sql_literal(asset_code)
|
||||
nature_condition = cls._build_asset_nature_condition("faj", query)
|
||||
nature_sql = f"\n AND {nature_condition}" if nature_condition else ""
|
||||
return f"""
|
||||
SELECT DISTINCT
|
||||
faj.faj02 AS "财产编号",
|
||||
faj.faj06 AS "中文名称",
|
||||
faj.faj061 AS "中文名称2",
|
||||
faj.faj02 AS "资产编号",
|
||||
faj.faj06 AS "资产名称",
|
||||
faj.faj08 AS "规格型号",
|
||||
faj.faj09 AS "资产性质",
|
||||
faj.faj13 AS "本币单价",
|
||||
@@ -714,7 +814,8 @@ SELECT DISTINCT
|
||||
TO_CHAR(faj.faj26, 'YYYY-MM-DD HH24:MI:SS') AS "入账日期",
|
||||
gen.gen02 AS "保管人姓名",
|
||||
gem.gem02 AS "保管部门名称",
|
||||
faf.faf02 AS "存放位置名称"
|
||||
faf.faf02 AS "存放位置名称",
|
||||
faj.faj43 AS "资产状态"
|
||||
FROM ERP_VIEW_USER.ERP_FAJ_FILE_V faj
|
||||
LEFT JOIN ERP_VIEW_USER.ERP_GEN_FILE_V gen
|
||||
ON gen.gen01 = faj.faj19
|
||||
@@ -725,9 +826,52 @@ LEFT JOIN ERP_VIEW_USER.ERP_GEM_FILE_V gem
|
||||
LEFT JOIN ERP_VIEW_USER.ERP_FAF_FILE_V faf
|
||||
ON faf.faf01 = faj.faj21
|
||||
AND faf.site = faj.site
|
||||
WHERE UPPER(TRIM(NVL(faj.faj02, ''))) LIKE '%' || UPPER('{literal}') || '%'
|
||||
{nature_sql}
|
||||
ORDER BY faj.faj02
|
||||
""".strip()
|
||||
|
||||
@classmethod
|
||||
def _build_asset_name_detail_sql(cls, keyword: str, query: str = "") -> str:
|
||||
literal = cls._escape_sql_literal(keyword)
|
||||
nature_condition = cls._build_asset_nature_condition("faj", query)
|
||||
nature_sql = f"\n AND {nature_condition}" if nature_condition else ""
|
||||
return f"""
|
||||
SELECT DISTINCT
|
||||
faj.faj02 AS "资产编号",
|
||||
faj.faj06 AS "资产名称",
|
||||
faj.faj08 AS "规格型号",
|
||||
faj.faj09 AS "资产性质",
|
||||
faj.faj13 AS "本币单价",
|
||||
faj.faj17 AS "数量",
|
||||
faj.faj18 AS "计量单位",
|
||||
TO_CHAR(faj.faj25, 'YYYY-MM-DD HH24:MI:SS') AS "取得日期",
|
||||
TO_CHAR(faj.faj26, 'YYYY-MM-DD HH24:MI:SS') AS "入账日期",
|
||||
gen.gen02 AS "保管人姓名",
|
||||
gem.gem02 AS "保管部门名称",
|
||||
faf.faf02 AS "存放位置名称",
|
||||
faj.faj43 AS "资产状态"
|
||||
FROM ERP_VIEW_USER.ERP_FAJ_FILE_V faj
|
||||
LEFT JOIN ERP_VIEW_USER.ERP_GEN_FILE_V gen
|
||||
ON gen.gen01 = faj.faj19
|
||||
AND gen.site = faj.site
|
||||
LEFT JOIN ERP_VIEW_USER.ERP_GEM_FILE_V gem
|
||||
ON gem.gem01 = faj.faj20
|
||||
AND gem.site = faj.site
|
||||
LEFT JOIN ERP_VIEW_USER.ERP_FAF_FILE_V faf
|
||||
ON faf.faf01 = faj.faj21
|
||||
AND faf.site = faj.site
|
||||
LEFT JOIN ERP_VIEW_USER.ERP_FAB_FILE_V fab
|
||||
ON fab.fab01 = faj.faj04
|
||||
AND fab.site = faj.site
|
||||
WHERE (
|
||||
UPPER(NVL(faj.faj06, ' ')) LIKE '%' || UPPER('{literal}') || '%'
|
||||
OR UPPER(NVL(faj.faj061, ' ')) LIKE '%' || UPPER('{literal}') || '%'
|
||||
OR UPPER(NVL(faj.faj08, ' ')) LIKE '%' || UPPER('{literal}') || '%'
|
||||
OR UPPER(NVL(gen.gen02, ' ')) LIKE '%' || UPPER('{literal}') || '%'
|
||||
OR UPPER(NVL(gem.gem02, ' ')) LIKE '%' || UPPER('{literal}') || '%'
|
||||
OR UPPER(NVL(faf.faf02, ' ')) LIKE '%' || UPPER('{literal}') || '%'
|
||||
OR UPPER(NVL(fab.fab02, ' ')) LIKE '%' || UPPER('{literal}') || '%'
|
||||
)
|
||||
{nature_sql}
|
||||
ORDER BY faj.faj02
|
||||
@@ -750,21 +894,19 @@ ORDER BY faj.faj02
|
||||
nature_sql = f"WHERE {nature_condition}\n" if nature_condition else ""
|
||||
return f"""
|
||||
SELECT DISTINCT
|
||||
faj.faj02 AS "财产编号",
|
||||
faj.faj06 AS "中文名称",
|
||||
faj.faj061 AS "中文名称2",
|
||||
faj.faj02 AS "资产编号",
|
||||
faj.faj06 AS "资产名称",
|
||||
faj.faj08 AS "规格型号",
|
||||
faj.faj09 AS "资产性质",
|
||||
faj.faj13 AS "本币单价",
|
||||
faj.faj14 AS "本币成本",
|
||||
faj.faj17 AS "数量",
|
||||
faj.faj18 AS "计量单位",
|
||||
TO_CHAR(faj.faj25, 'YYYY-MM-DD HH24:MI:SS') AS "取得日期",
|
||||
TO_CHAR(faj.faj26, 'YYYY-MM-DD HH24:MI:SS') AS "入账日期",
|
||||
faj.faj43 AS "资产状态",
|
||||
gen.gen02 AS "保管人姓名",
|
||||
gem.gem02 AS "保管部门名称",
|
||||
faf.faf02 AS "存放位置名称"
|
||||
faf.faf02 AS "存放位置名称",
|
||||
faj.faj43 AS "资产状态"
|
||||
FROM ERP_VIEW_USER.ERP_FAJ_FILE_V faj
|
||||
LEFT JOIN ERP_VIEW_USER.ERP_GEN_FILE_V gen
|
||||
ON gen.gen01 = faj.faj19
|
||||
@@ -777,6 +919,76 @@ LEFT JOIN ERP_VIEW_USER.ERP_FAF_FILE_V faf
|
||||
AND faf.site = faj.site
|
||||
{nature_sql}\
|
||||
ORDER BY faj.faj02
|
||||
""".strip()
|
||||
|
||||
@classmethod
|
||||
def _translate_status_to_code(cls, status_text: str) -> str | None:
|
||||
mappings = cls._ASSET_VALUE_MAPPINGS.get("资产状态", {})
|
||||
for code, name in mappings.items():
|
||||
if status_text in name or name in status_text:
|
||||
return code
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def _build_advanced_asset_detail_sql(cls, conds: dict[str, str], query: str = "") -> str:
|
||||
nature_condition = cls._build_asset_nature_condition("faj", query)
|
||||
nature_sql = f"\n AND {nature_condition}" if nature_condition else ""
|
||||
|
||||
where_clauses = []
|
||||
if "spec" in conds:
|
||||
literal = cls._escape_sql_literal(conds["spec"])
|
||||
where_clauses.append(f"UPPER(NVL(faj.faj08, ' ')) LIKE '%' || UPPER('{literal}') || '%'")
|
||||
if "type" in conds:
|
||||
literal = cls._escape_sql_literal(conds["type"])
|
||||
where_clauses.append(f"UPPER(NVL(fab.fab02, ' ')) LIKE '%' || UPPER('{literal}') || '%'")
|
||||
if "location" in conds:
|
||||
literal = cls._escape_sql_literal(conds["location"])
|
||||
where_clauses.append(f"UPPER(NVL(faf.faf02, ' ')) LIKE '%' || UPPER('{literal}') || '%'")
|
||||
if "status" in conds:
|
||||
status_code = cls._translate_status_to_code(conds["status"])
|
||||
if status_code:
|
||||
where_clauses.append(f"TRIM(NVL(faj.faj43, ' ')) = '{status_code}'")
|
||||
else:
|
||||
literal = cls._escape_sql_literal(conds["status"])
|
||||
where_clauses.append(f"UPPER(NVL(faj.faj43, ' ')) LIKE '%' || UPPER('{literal}') || '%'")
|
||||
|
||||
where_sql = " AND ".join(where_clauses)
|
||||
if where_sql:
|
||||
where_sql = f"WHERE {where_sql}"
|
||||
else:
|
||||
where_sql = "WHERE 1=1"
|
||||
|
||||
return f"""
|
||||
SELECT DISTINCT
|
||||
faj.faj02 AS "资产编号",
|
||||
faj.faj06 AS "资产名称",
|
||||
faj.faj08 AS "规格型号",
|
||||
faj.faj09 AS "资产性质",
|
||||
faj.faj13 AS "本币单价",
|
||||
faj.faj17 AS "数量",
|
||||
faj.faj18 AS "计量单位",
|
||||
TO_CHAR(faj.faj25, 'YYYY-MM-DD HH24:MI:SS') AS "取得日期",
|
||||
TO_CHAR(faj.faj26, 'YYYY-MM-DD HH24:MI:SS') AS "入账日期",
|
||||
gen.gen02 AS "保管人姓名",
|
||||
gem.gem02 AS "保管部门名称",
|
||||
faf.faf02 AS "存放位置名称",
|
||||
faj.faj43 AS "资产状态"
|
||||
FROM ERP_VIEW_USER.ERP_FAJ_FILE_V faj
|
||||
LEFT JOIN ERP_VIEW_USER.ERP_GEN_FILE_V gen
|
||||
ON gen.gen01 = faj.faj19
|
||||
AND gen.site = faj.site
|
||||
LEFT JOIN ERP_VIEW_USER.ERP_GEM_FILE_V gem
|
||||
ON gem.gem01 = faj.faj20
|
||||
AND gem.site = faj.site
|
||||
LEFT JOIN ERP_VIEW_USER.ERP_FAF_FILE_V faf
|
||||
ON faf.faf01 = faj.faj21
|
||||
AND faf.site = faj.site
|
||||
LEFT JOIN ERP_VIEW_USER.ERP_FAB_FILE_V fab
|
||||
ON fab.fab01 = faj.faj04
|
||||
AND fab.site = faj.site
|
||||
{where_sql}
|
||||
{nature_sql}
|
||||
ORDER BY faj.faj02
|
||||
""".strip()
|
||||
|
||||
@classmethod
|
||||
@@ -785,6 +997,15 @@ ORDER BY faj.faj02
|
||||
return None
|
||||
if cls._is_company_asset_detail_query(query):
|
||||
return cls._build_company_asset_detail_sql(query)
|
||||
|
||||
advanced_conds = cls._extract_advanced_asset_conditions(query)
|
||||
if advanced_conds:
|
||||
return cls._build_advanced_asset_detail_sql(advanced_conds, query)
|
||||
|
||||
asset_code = cls._extract_asset_code(query)
|
||||
if asset_code:
|
||||
return cls._build_asset_code_detail_sql(asset_code, query)
|
||||
|
||||
keyword = cls._extract_asset_name_keyword(query)
|
||||
if not keyword:
|
||||
return None
|
||||
@@ -837,7 +1058,7 @@ ORDER BY faj.faj02
|
||||
"- 固资相关联表必须同时补齐 `site` 条件,例如 `gen.site = faj.site`、`gem.site = faj.site`、`faf.site = faj.site`、`fab.site = faj.site`,避免同编码跨营运中心造成重复记录。",
|
||||
"- 固资数据只允许保留 `faj22`(存放营运中心)属于 `HXJM`、`HTT`、`HTE` 的记录;生成 SQL 时必须显式加上 `UPPER(TRIM(NVL(faj.faj22, ''))) IN ('HXJM', 'HTT', 'HTE')` 过滤。",
|
||||
"- 查询固定资产明细列表时优先使用 `SELECT DISTINCT`;如果是统计资产数量,优先使用 `COUNT(DISTINCT faj.faj02)`。",
|
||||
"- 返回结果所有列必须使用中文别名,例如 `faj.faj02 AS \"财产编号\"`、`faj.faj06 AS \"资产名称\"`、`faj.faj08 AS \"规格型号\"`。",
|
||||
"- 当查询固定资产明细时,返回结果必须且只能包含以下列并使用严格对应的中文别名:faj.faj02 AS \"资产编号\"、faj.faj06 AS \"资产名称\"、faj.faj08 AS \"规格型号\"、faj.faj09 AS \"资产性质\"、faj.faj13 AS \"本币单价\"、faj.faj17 AS \"数量\"、faj.faj18 AS \"计量单位\"、TO_CHAR(faj.faj25, YYYY-MM-DD HH24:MI:SS) AS \"取得日期\"、TO_CHAR(faj.faj26, YYYY-MM-DD HH24:MI:SS) AS \"入账日期\"、gen.gen02 AS \"保管人姓名\"、gem.gem02 AS \"保管部门名称\"、faf.faf02 AS \"存放位置名称\"、faj.faj43 AS \"资产状态\"。",
|
||||
"- 日期时间字段展示时不要去掉时分秒;若使用 TO_CHAR 格式化,必须保留为 `YYYY-MM-DD HH24:MI:SS`,不能只输出日期。",
|
||||
*filters,
|
||||
]
|
||||
@@ -1141,6 +1362,9 @@ ORDER BY faj.faj02
|
||||
|
||||
@classmethod
|
||||
def _ensure_asset_scope_filter(cls, sql: str, base_alias: str, query: str, user_context: dict | None = None) -> str:
|
||||
asset_code_predicate = cls._build_asset_code_condition(base_alias, query)
|
||||
if asset_code_predicate and asset_code_predicate not in sql:
|
||||
return cls._append_sql_predicate(sql, asset_code_predicate)
|
||||
department_predicate = cls._build_asset_department_condition(base_alias, query)
|
||||
if department_predicate:
|
||||
return cls._append_sql_predicate(sql, department_predicate)
|
||||
|
||||
@@ -7,52 +7,251 @@ backend/edkb_system/skills/excel_bridge.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import ctypes
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def convert_with_excel(path: Path, output: Path) -> Path:
|
||||
"""
|
||||
使用 Microsoft Excel COM 将源表格另存为 .xlsx。
|
||||
|
||||
核心逻辑:启动 Excel.Application → Open → SaveAs(xlsx) → Quit。
|
||||
|
||||
Args:
|
||||
path: 源 .xls 文件路径。
|
||||
output: 目标 .xlsx 路径。
|
||||
|
||||
Returns:
|
||||
成功写入的 output 路径。
|
||||
|
||||
Raises:
|
||||
RuntimeError: 非 Windows、缺少 pywin32/Excel,或转换未产出目标文件。
|
||||
"""
|
||||
import os
|
||||
|
||||
def _list_excel_pids() -> set[int]:
|
||||
if os.name != "nt":
|
||||
raise RuntimeError("Excel COM conversion is only available on Windows")
|
||||
|
||||
return set()
|
||||
try:
|
||||
import win32com.client
|
||||
except ImportError as exc:
|
||||
raise RuntimeError("Excel COM conversion requires pywin32 on Windows") from exc
|
||||
proc = subprocess.run(
|
||||
["tasklist", "/FO", "CSV", "/NH", "/FI", "IMAGENAME eq EXCEL.EXE"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
except Exception:
|
||||
return set()
|
||||
|
||||
source = str(path.resolve())
|
||||
target = str(output.resolve())
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
out: set[int] = set()
|
||||
for line in (proc.stdout or "").splitlines():
|
||||
line = line.strip()
|
||||
if not line or line.startswith("INFO:"):
|
||||
continue
|
||||
cols = [part.strip().strip('"') for part in line.split('","')]
|
||||
if len(cols) < 2:
|
||||
cols = [part.strip().strip('"') for part in line.split(",")]
|
||||
if len(cols) < 2:
|
||||
continue
|
||||
try:
|
||||
out.add(int(cols[1]))
|
||||
except ValueError:
|
||||
continue
|
||||
return out
|
||||
|
||||
excel = win32com.client.Dispatch("Excel.Application")
|
||||
excel.Visible = False
|
||||
excel.DisplayAlerts = False
|
||||
workbook = None
|
||||
|
||||
def _kill_excel_pids(pids: set[int]) -> None:
|
||||
if os.name != "nt":
|
||||
return
|
||||
for pid in sorted(pids):
|
||||
try:
|
||||
subprocess.run(
|
||||
["taskkill", "/PID", str(pid), "/F"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
|
||||
def _excel_timeout_sec() -> int:
|
||||
raw = str(os.environ.get("EDKB_EXCEL_TIMEOUT_SEC", "120")).strip()
|
||||
try:
|
||||
workbook = excel.Workbooks.Open(source)
|
||||
# 51 = xlOpenXMLWorkbook (.xlsx)
|
||||
workbook.SaveAs(target, FileFormat=51)
|
||||
finally:
|
||||
if workbook is not None:
|
||||
workbook.Close(SaveChanges=False)
|
||||
excel.Quit()
|
||||
value = int(raw)
|
||||
except ValueError:
|
||||
value = 120
|
||||
return max(value, 10)
|
||||
|
||||
if not output.exists():
|
||||
raise RuntimeError(f"Excel COM did not produce output file: {output}")
|
||||
|
||||
def _should_accept_excel_dialog(
|
||||
window_title: str, child_texts: list[str], button_texts: list[str]
|
||||
) -> bool:
|
||||
text_blob = "\n".join(x.strip().lower() for x in child_texts if x.strip())
|
||||
if not text_blob:
|
||||
return False
|
||||
|
||||
has_repair_prompt = any(
|
||||
token in text_blob
|
||||
for token in [
|
||||
"损坏",
|
||||
"是否仍要打开",
|
||||
"corrupted",
|
||||
"do you still want to open",
|
||||
"repair",
|
||||
"修复",
|
||||
]
|
||||
)
|
||||
if not has_repair_prompt:
|
||||
return False
|
||||
|
||||
return any(
|
||||
text.strip().lower().startswith(("是", "yes")) or "&y" in text.lower()
|
||||
for text in button_texts
|
||||
)
|
||||
|
||||
|
||||
def _start_excel_dialog_watcher() -> tuple[threading.Event, threading.Thread | None]:
|
||||
stop_event = threading.Event()
|
||||
if os.name != "nt":
|
||||
return stop_event, None
|
||||
|
||||
def _window_text(user32, hwnd: int) -> str:
|
||||
length = user32.GetWindowTextLengthW(hwnd)
|
||||
if length <= 0:
|
||||
return ""
|
||||
buf = ctypes.create_unicode_buffer(length + 1)
|
||||
user32.GetWindowTextW(hwnd, buf, length + 1)
|
||||
return buf.value
|
||||
|
||||
def _class_name(user32, hwnd: int) -> str:
|
||||
buf = ctypes.create_unicode_buffer(256)
|
||||
user32.GetClassNameW(hwnd, buf, 255)
|
||||
return buf.value
|
||||
|
||||
def _click_yes_if_needed() -> None:
|
||||
user32 = ctypes.windll.user32
|
||||
bm_click = 0x00F5
|
||||
vk_return = 0x0D
|
||||
wm_keydown = 0x0100
|
||||
wm_keyup = 0x0101
|
||||
|
||||
while not stop_event.is_set():
|
||||
windows: list[int] = []
|
||||
|
||||
@ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_void_p)
|
||||
def enum_windows(hwnd, lparam):
|
||||
windows.append(int(hwnd))
|
||||
return True
|
||||
|
||||
user32.EnumWindows(enum_windows, 0)
|
||||
for hwnd in windows:
|
||||
title = _window_text(user32, hwnd)
|
||||
cls = _class_name(user32, hwnd).lower()
|
||||
if "Microsoft Excel" not in title and cls != "#32770":
|
||||
continue
|
||||
|
||||
child_hwnds: list[int] = []
|
||||
|
||||
@ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_void_p)
|
||||
def enum_children(child_hwnd, lparam):
|
||||
child_hwnds.append(int(child_hwnd))
|
||||
return True
|
||||
|
||||
user32.EnumChildWindows(hwnd, enum_children, 0)
|
||||
child_texts = [_window_text(user32, child) for child in child_hwnds]
|
||||
button_hwnds = [
|
||||
child
|
||||
for child in child_hwnds
|
||||
if _class_name(user32, child).lower() == "button"
|
||||
]
|
||||
button_texts = [_window_text(user32, child) for child in button_hwnds]
|
||||
if not _should_accept_excel_dialog(title, child_texts, button_texts):
|
||||
continue
|
||||
user32.SetForegroundWindow(hwnd)
|
||||
for child, text in zip(button_hwnds, button_texts):
|
||||
normalized = text.strip().lower()
|
||||
if normalized.startswith(("是", "yes")) or "&y" in normalized:
|
||||
user32.SendMessageW(child, bm_click, 0, 0)
|
||||
break
|
||||
else:
|
||||
user32.PostMessageW(hwnd, wm_keydown, vk_return, 0)
|
||||
user32.PostMessageW(hwnd, wm_keyup, vk_return, 0)
|
||||
stop_event.wait(0.5)
|
||||
|
||||
thread = threading.Thread(target=_click_yes_if_needed, daemon=True)
|
||||
thread.start()
|
||||
return stop_event, thread
|
||||
|
||||
|
||||
def convert_with_excel(path: Path, output: Path, file_format: int = 51) -> Path:
|
||||
"""
|
||||
Excel COM conversion. 51 = xlOpenXMLWorkbook (.xlsx)
|
||||
"""
|
||||
timeout = _excel_timeout_sec()
|
||||
before_pids = _list_excel_pids()
|
||||
cmd = [
|
||||
sys.executable,
|
||||
"-m",
|
||||
"edkb_system.skills.excel_bridge",
|
||||
str(path),
|
||||
str(output),
|
||||
str(file_format),
|
||||
]
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
cmd,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=timeout,
|
||||
check=False,
|
||||
)
|
||||
except subprocess.TimeoutExpired as exc:
|
||||
after_pids = _list_excel_pids()
|
||||
_kill_excel_pids(after_pids - before_pids)
|
||||
raise RuntimeError(
|
||||
f"Excel conversion timed out after {timeout}s: {path.name}"
|
||||
) from exc
|
||||
|
||||
if proc.returncode != 0:
|
||||
err = (proc.stderr or proc.stdout or "unknown error").strip()
|
||||
raise RuntimeError(f"Excel conversion failed: {err}")
|
||||
|
||||
if not output.exists() or output.stat().st_size <= 0:
|
||||
raise RuntimeError(f"Excel conversion produced no output: {output}")
|
||||
return output
|
||||
|
||||
|
||||
def _child_main(argv: list[str]) -> int:
|
||||
if len(argv) != 4:
|
||||
print("usage: excel_bridge <input> <output> <file_format>", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
src = Path(argv[1]).resolve()
|
||||
out = Path(argv[2]).resolve()
|
||||
file_format = int(argv[3])
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
stop_event, watcher = _start_excel_dialog_watcher()
|
||||
|
||||
excel = None
|
||||
wb = None
|
||||
try:
|
||||
from win32com.client import DispatchEx
|
||||
|
||||
excel = DispatchEx("Excel.Application")
|
||||
excel.Visible = False
|
||||
excel.DisplayAlerts = 0
|
||||
|
||||
wb = excel.Workbooks.Open(
|
||||
Filename=str(src),
|
||||
ReadOnly=True,
|
||||
UpdateLinks=0,
|
||||
IgnoreReadOnlyRecommended=True,
|
||||
)
|
||||
# xlOpenXMLWorkbook = 51
|
||||
wb.SaveAs(str(out), FileFormat=file_format)
|
||||
finally:
|
||||
stop_event.set()
|
||||
if watcher is not None:
|
||||
watcher.join(timeout=1)
|
||||
if wb is not None:
|
||||
try:
|
||||
wb.Close(False)
|
||||
except Exception:
|
||||
pass
|
||||
if excel is not None:
|
||||
try:
|
||||
excel.Quit()
|
||||
except Exception:
|
||||
pass
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(_child_main(sys.argv))
|
||||
@@ -1,4 +1,4 @@
|
||||
/**
|
||||
/**
|
||||
* features/chat/composables/useChat.ts
|
||||
* SSE 流式对话核心:消息列表、runs、发送与接收。
|
||||
*/
|
||||
@@ -71,8 +71,27 @@ const addAttributionParts = (msg: ChatMessage, value: unknown) => {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 把 SSE 事件附带的元数据同步到当前消息对象。
|
||||
*
|
||||
* 说明:
|
||||
* - Text2SQL 在 `message_end` 才会返回 `payload/chat_log_id`,若这里不合并,
|
||||
* 当前页不会立刻出现“查看全部预览”按钮,只能刷新后从历史消息里重新读到。
|
||||
*/
|
||||
const applyEventMetadata = (msg: ChatMessage, data: Record<string, unknown>) => {
|
||||
const metadata = (data?.metadata || {}) as Record<string, unknown>;
|
||||
if (Number.isInteger(data.chat_log_id)) {
|
||||
msg.chat_log_id = Number(data.chat_log_id);
|
||||
}
|
||||
if (typeof data.type === 'string' && data.type.trim()) {
|
||||
msg.type = data.type as ChatMessage['type'];
|
||||
}
|
||||
if (data.payload && typeof data.payload === 'object') {
|
||||
msg.payload = {
|
||||
...(msg.payload && typeof msg.payload === 'object' ? msg.payload as Record<string, unknown> : {}),
|
||||
...(data.payload as Record<string, unknown>),
|
||||
};
|
||||
}
|
||||
addRetrieverResources(msg, data?.retriever_resources);
|
||||
addRetrieverResources(msg, metadata?.retriever_resources);
|
||||
addRetrieverResources(msg, metadata?.retrieverResources);
|
||||
|
||||
Reference in new issue
Block a user