Paul720810 commited on
Commit
ee747ec
·
verified ·
1 Parent(s): 51cf075

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +117 -92
app.py CHANGED
@@ -483,14 +483,20 @@ class TextToSQLSystem:
483
 
484
  # in class TextToSQLSystem:
485
 
486
- def _validate_and_fix_sql(self, question: str, raw_response: str) -> Tuple[Optional[str], str]:
487
  """
488
- (V17 / 最終決策版)
489
  一個全面、多層次的 SQL 驗證與生成引擎。
490
- 本函數作為第一決策者,優先匹配用戶問題與專家知識庫。
491
- 如果匹配成功,則直接使用模板覆寫;若不成功,才解析並修正 AI 的輸出。
492
- 返回一個元組 (SQL字符串或None, 狀態消息)。
493
  """
 
 
 
 
 
 
 
494
  q_lower = question.lower()
495
 
496
  # ==============================================================================
@@ -500,7 +506,7 @@ class TextToSQLSystem:
500
  # --- 預先檢測所有可能的意圖和實體 ---
501
  job_no_match = re.search(r"(?:工單|jobno)\s*'\"?([A-Z]{2,3}\d+)'\"?", question, re.IGNORECASE)
502
  entity_match_data = None
503
- ENTITY_TO_COLUMN_MAP = {'申請廠商':'sd.ApplicantName','申請方':'sd.ApplicantName','applicant':'sd.ApplicantName','付款廠商':'sd.InvoiceToName','付款方':'sd.InvoiceToName','invoiceto':'sd.InvoiceToName','代理商':'sd.AgentName','agent':'sd.AgentName','買家':'sd.BuyerName','buyer':'sd.BuyerName','客戶':'sd.BuyerName','品牌':'tsr.BuyerName'}
504
  for keyword, column in ENTITY_TO_COLUMN_MAP.items():
505
  if keyword in q_lower:
506
  match = re.search(fr"{re.escape(keyword)}[\s:;\'\"-]*([a-zA-Z0-9&.\s-]+?)(?:\s*的|\s+|為|$)", question, re.IGNORECASE)
@@ -514,32 +520,32 @@ class TextToSQLSystem:
514
  if codes: lab_group_match_data = {"codes": codes, "identifiers": lab_group_match}
515
 
516
  is_tat_query = any(k in q_lower for k in ['平均', 'average']) and any(k in q_lower for k in ['時間', '時長', '多久', '天', 'tat', 'turnaround'])
517
-
518
  # --- 判斷邏輯: 依優先級進入對應的模板 ---
519
-
520
  if job_no_match and any(kw in q_lower for kw in ['工作日', 'workday']):
521
  job_no = job_no_match.group(1).upper()
522
  self._log(f"🔄 檢測到計算【工單 {job_no}】工作日TAT的意圖,啟用模板。", "INFO")
523
- template_sql = f"WITH span AS (SELECT date(jt.JobCreation) AS d1, date(jt.ReportAuthorization) AS d2 FROM JobTimeline jt WHERE jt.JobNo = '{job_no}'), days AS (SELECT 1 FROM calendar_days, span WHERE date BETWEEN d1 AND d2 AND is_workday = 1) SELECT COUNT(*) FROM days;"
524
- return self._finalize_sql(template_sql, f"模板覆寫: {job_no} 的工作日天數")
525
 
526
- if job_no_match and any(kw in q_lower for kw in ['總處理時長', '時長', '多少天']):
527
  job_no = job_no_match.group(1).upper()
528
  self._log(f"🔄 檢測到計算【工單 {job_no}】日曆日TAT的意圖,啟用模板。", "INFO")
529
- template_sql = f"SELECT ROUND(julianday(ReportAuthorization) - julianday(JobCreation), 2) AS days FROM JobTimeline WHERE JobNo = '{job_no}';"
530
- return self._finalize_sql(template_sql, f"模板覆寫: {job_no} 的日曆日總時長")
531
 
532
- if job_no_match and any(kw in q_lower for kw in ['總金額', '金額', '業績', 'total amount']):
533
  job_no = job_no_match.group(1).upper()
534
  self._log(f"🔄 檢測到對【單一工作單 '{job_no}'】的【標準金額計算】意圖,啟用模板。", "INFO")
535
- template_sql = f"WITH JobTotalAmount AS (SELECT JobNo, SUM(LocalAmount) AS TotalAmount FROM (SELECT DISTINCT JobNo, InvoiceCreditNoteNo, LocalAmount FROM TSR53Invoice) GROUP BY JobNo) SELECT TotalAmount FROM JobTotalAmount WHERE JobNo = '{job_no}';"
536
- return self._finalize_sql(template_sql, f"模板覆寫: 工作單 {job_no} 的標準總金額 (CTE去重)")
537
 
538
- if '總金額最高' in q_lower and '工作單' in q_lower:
539
  limit_match = re.search(r'(\d+)', question)
540
  limit = limit_match.group(1) if limit_match else '10'
541
  self._log(f"🔄 檢測到查詢【Top {limit} 工作單金額】意圖,啟用模板。", "INFO")
542
- template_sql = f"""
543
  WITH JobTotalAmount AS (
544
  SELECT JobNo, SUM(LocalAmount) AS TotalAmount
545
  FROM (SELECT DISTINCT JobNo, InvoiceCreditNoteNo, LocalAmount FROM TSR53Invoice)
@@ -550,26 +556,57 @@ FROM JobTotalAmount
550
  ORDER BY TotalAmount DESC
551
  LIMIT {limit};
552
  """
553
- return self._finalize_sql(template_sql, f"模板覆寫: Top {limit} 工作單金額")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
554
 
555
- if entity_match_data and any(kw in q_lower for kw in ['業績', '營收', '金額', 'sales', 'revenue']):
 
 
 
 
 
 
 
 
 
 
 
 
 
556
  entity_type, entity_name, column_name = entity_match_data["type"], entity_match_data["name"], entity_match_data["column"]
557
  year = (re.search(r'(\d{4})\s*年?', question) or ['', datetime.now().strftime('%Y')])[1]
558
  self._log(f"🔄 檢測到查詢【{entity_type} '{entity_name}' 在 {year} 年的總業績】意圖,啟用模板。", "INFO")
559
- template_sql = f"WITH JobTotalAmount AS (SELECT JobNo, SUM(LocalAmount) AS TotalAmount FROM (SELECT DISTINCT JobNo, InvoiceCreditNoteNo, LocalAmount FROM TSR53Invoice) GROUP BY JobNo) SELECT SUM(jta.TotalAmount) AS total_revenue FROM TSR53SampleDescription AS sd JOIN JobTotalAmount AS jta ON sd.JobNo = jta.JobNo WHERE {column_name} LIKE '%{entity_name}%' AND strftime('%Y', sd.FirstReportAuthorizedDate) = '{year}';"
560
- return self._finalize_sql(template_sql, f"模板覆寫: 查詢 {entity_type}='{entity_name}' ({year}年) 的總業績")
561
-
562
- if not entity_match_data and any(kw in q_lower for kw in ['業績', '營收', '金額', 'sales', 'revenue']):
563
  year_match, month_match = re.search(r'(\d{4})\s*年?', question), re.search(r'(\d{1,2})\s*月', question)
564
  time_condition, time_log = "", "總"
565
  if year_match:
566
  year = year_match.group(1); time_condition = f"WHERE strftime('%Y', InvoiceCreditNoteDate) = '{year}'"; time_log = f"{year}年"
567
  if month_match: month = month_match.group(1).zfill(2); time_condition += f" AND strftime('%m', InvoiceCreditNoteDate) = '{month}'"; time_log += f"{month}月"
568
  self._log(f"🔄 檢測到查詢【{time_log}全局總業績】意圖,啟用模板。", "INFO")
569
- template_sql = f"SELECT SUM(LocalAmount) AS total_revenue FROM TSR53Invoice {time_condition};"
570
- return self._finalize_sql(template_sql, f"模板覆寫: {time_log}全局總業績查詢")
571
 
572
- if lab_group_match_data and any(kw in q_lower for kw in ['測試項目', 'test item']):
573
  lab_group_code = lab_group_match_data["codes"][0]
574
  target_table = f"JobTimeline_{lab_group_code}"
575
  year = (re.search(r'(\d{4})\s*年', question) or ['', datetime.now().strftime('%Y')])[1]
@@ -581,73 +618,61 @@ LIMIT {limit};
581
  time_condition += f" AND strftime('%m', end_time) = '{month}'"
582
  month_str = f"{month}月"
583
  self._log(f"🔄 檢測到查詢【{lab_group_code}組】完成的【測試項目數】意圖,啟用專屬模板。", "INFO")
584
- template_sql = f"SELECT COUNT(JobItemKey) AS test_item_count FROM {target_table} WHERE end_time IS NOT NULL AND {time_condition};"
585
- return self._finalize_sql(template_sql, f"模板覆寫: 查詢 {lab_group_code}組 在 {year}年{month_str} 完成的測試項目數")
586
-
587
- if '報告' in q_lower and any(kw in q_lower for kw in ['幾份', '多少', '數量', '總數']) and not entity_match_data and not lab_group_match_data:
588
- year_match = re.search(r'(\d{4})\s*年?', question)
589
- time_condition, time_log = "", "總"
590
- if year_match:
591
- year = year_match.group(1)
592
- time_condition = f"WHERE ReportAuthorization IS NOT NULL AND strftime('%Y', ReportAuthorization) = '{year}'"
593
- time_log = f"{year}年"
594
- else:
595
- time_condition = "WHERE ReportAuthorization IS NOT NULL"
596
- self._log(f"🔄 檢測到查詢【{time_log}全局報告總數】意圖,啟用模板。", "INFO")
597
- template_sql = f"SELECT COUNT(DISTINCT JobNo) AS report_count FROM JobTimeline {time_condition};"
598
- return self._finalize_sql(template_sql, f"模板覆寫: {time_log}全局報告總數查詢")
599
 
600
- # ==============================================================================
601
- # 第二層:常規修正流程 (Fallback Corrections)
602
- # ==============================================================================
603
- self._log("未觸發任何模板,嘗試解析並修正 AI 輸出...", "INFO")
604
-
605
- parsed_sql = parse_sql_from_response(raw_response)
606
- if not parsed_sql:
607
- self._log(f"❌ 未能從模型回應中解析出任何 SQL。原始回應: {raw_response}", "ERROR")
608
- return None, f"無法解析SQL。原始回應:\n{raw_response}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
609
 
610
- self._log(f"📊 解析出的原始 SQL: {parsed_sql}", "DEBUG")
611
-
612
- fixed_sql = " " + parsed_sql.strip() + " "
613
- fixes_applied_fallback = []
614
-
615
- dialect_corrections = {
616
- r'YEAR\s*\(([^)]+)\)': r"strftime('%Y', \1)",
617
- r"(strftime\('%Y',\s*[^)]+\))\s*=\s*(\d{4})": r"\1 = '\2'",
618
- r"EXTRACT\s*\(\s*YEAR\s+FROM\s+([^)]+)\s*\)": r"strftime('%Y', \1)"
619
- }
620
- for pattern, replacement in dialect_corrections.items():
621
- if re.search(pattern, fixed_sql, re.IGNORECASE):
622
- fixed_sql = re.sub(pattern, replacement, fixed_sql, flags=re.IGNORECASE)
623
- fixes_applied_fallback.append(f"修正方言: {pattern}")
624
-
625
- schema_corrections = {
626
- 'TSR53ReportAuthorization': 'TSR53SampleDescription', 'TSR53TestResult': 'TSR53SampleDescription',
627
- 'JobInvoice': 'TSR53Invoice', 'JobInvoiceAuthorization': 'TSR53Invoice', 'JobInvoiceCreditNote': 'TSR53Invoice',
628
- 'Customer': 'TSR53SampleDescription', 'Customers': 'TSR53SampleDescription',
629
- 'Invoice': 'TSR53Invoice', 'Invoices': 'TSR53Invoice', 'Job': 'JobTimeline', 'Jobs': 'JobsInProgress',
630
- 'Tests': 'TSR53MarsItem', 'TestsLog': 'JobItemsInProgress',
631
- 'AuthorizationDate': 'ReportAuthorization', 'ReportAuthorizationDate': 'ReportAuthorization',
632
- 'LegalAuthorization': 'OverallRating', 'LegalAuthorizationDate': 'ReportAuthorization',
633
- 'TestResult': 'OverallRating', 'Rating': 'OverallRating', 'CustomerName': 'BuyerName', 'InvoiceTo': 'InvoiceToName',
634
- 'Applicant': 'ApplicantName', 'Agent': 'AgentName', 'JobNumber': 'JobNo', 'ReportNo': 'JobNo', 'TestName': 'ItemInvoiceDescriptionJob',
635
- 'CreationDate': 'JobCreation', 'CreateDate': 'JobCreation', 'CompletedDate': 'ReportAuthorization',
636
- 'InvoiceCreditNoteAmount': 'LocalAmount',
637
- 'Amount': 'LocalAmount', 'Price': 'LocalAmount', 'Lab': 'LabGroup'
638
- }
639
- for wrong, correct in schema_corrections.items():
640
- pattern = r'\b' + re.escape(wrong) + r'\b'
641
- if re.search(pattern, fixed_sql, re.IGNORECASE):
642
- fixed_sql = re.sub(pattern, correct, fixed_sql, flags=re.IGNORECASE)
643
- fixes_applied_fallback.append(f"映射 Schema: '{wrong}' -> '{correct}'")
644
-
645
- if any(kw in q_lower for kw in ['幾份', '多少', 'how many', 'count', '數量']) and 'select ' in fixed_sql.lower() and 'count' not in fixed_sql.lower() and 'group by' not in fixed_sql.lower():
646
- fixed_sql = re.sub(r'SELECT\s+.*?FROM', 'SELECT COUNT(*) FROM', fixed_sql, count=1, flags=re.IGNORECASE)
647
- fixes_applied_fallback.append("修正邏輯: 補全 COUNT(*)")
648
-
649
- log_msg = "AI 生成並成功修正" if fixes_applied_fallback else "AI 生成且無需修正"
650
- return self._finalize_sql(fixed_sql, log_msg)
651
 
652
  def _finalize_sql(self, sql: str, log_message: str) -> Tuple[str, str]:
653
  """一個輔助函數,用於清理最終的SQL並記錄成功日誌。"""
 
483
 
484
  # in class TextToSQLSystem:
485
 
486
+ def _validate_and_fix_sql(self, sql: str, question: str) -> str:
487
  """
488
+ (V19 / 報告列表版)
489
  一個全面、多層次的 SQL 驗證與生成引擎。
490
+ 新增了對“列出報告號碼”這一意圖的識別,並調整了意圖優先級,
491
+ 確保更具體的“列表”查詢不會被寬泛的“計數”查詢錯誤攔截。
 
492
  """
493
+ if not sql or not self.schema:
494
+ self._log("SQL 修正被跳過,因輸入為空或 schema 未載入。", "WARNING")
495
+ return sql
496
+
497
+ original_sql = sql
498
+ fixed_sql = " " + sql.strip() + " "
499
+ fixes_applied = []
500
  q_lower = question.lower()
501
 
502
  # ==============================================================================
 
506
  # --- 預先檢測所有可能的意圖和實體 ---
507
  job_no_match = re.search(r"(?:工單|jobno)\s*'\"?([A-Z]{2,3}\d+)'\"?", question, re.IGNORECASE)
508
  entity_match_data = None
509
+ ENTITY_TO_COLUMN_MAP = {'申請廠商':'sd.ApplicantName','申請方':'sd.ApplicantName','applicant':'sd.ApplicantName','付款廠商':'sd.InvoiceToName','付款方':'sd.InvoiceToName','invoiceto':'sd.InvoiceToName','代理商':'sd.AgentName','agent':'sd.AgentName','買家':'sd.BuyerName','buyer':'sd.BuyerName','客戶':'sd.BuyerName', '品牌': 'tsr.BuyerName'}
510
  for keyword, column in ENTITY_TO_COLUMN_MAP.items():
511
  if keyword in q_lower:
512
  match = re.search(fr"{re.escape(keyword)}[\s:;\'\"-]*([a-zA-Z0-9&.\s-]+?)(?:\s*的|\s+|為|$)", question, re.IGNORECASE)
 
520
  if codes: lab_group_match_data = {"codes": codes, "identifiers": lab_group_match}
521
 
522
  is_tat_query = any(k in q_lower for k in ['平均', 'average']) and any(k in q_lower for k in ['時間', '時長', '多久', '天', 'tat', 'turnaround'])
523
+
524
  # --- 判斷邏輯: 依優先級進入對應的模板 ---
525
+
526
  if job_no_match and any(kw in q_lower for kw in ['工作日', 'workday']):
527
  job_no = job_no_match.group(1).upper()
528
  self._log(f"🔄 檢測到計算【工單 {job_no}】工作日TAT的意圖,啟用模板。", "INFO")
529
+ fixed_sql = f"""WITH span AS (SELECT date(jt.JobCreation) AS d1, date(jt.ReportAuthorization) AS d2 FROM JobTimeline jt WHERE jt.JobNo = '{job_no}'), days AS (SELECT 1 FROM calendar_days, span WHERE date BETWEEN d1 AND d2 AND is_workday = 1) SELECT COUNT(*) FROM days;"""
530
+ fixes_applied.append(f"模板覆寫: {job_no} 的工作日天數")
531
 
532
+ elif job_no_match and any(kw in q_lower for kw in ['總處理時長', '時長', '多少天']):
533
  job_no = job_no_match.group(1).upper()
534
  self._log(f"🔄 檢測到計算【工單 {job_no}】日曆日TAT的意圖,啟用模板。", "INFO")
535
+ fixed_sql = f"""SELECT ROUND(julianday(ReportAuthorization) - julianday(JobCreation), 2) AS days FROM JobTimeline WHERE JobNo = '{job_no}';"""
536
+ fixes_applied.append(f"模板覆寫: {job_no} 的日曆日總時長")
537
 
538
+ elif job_no_match and any(kw in q_lower for kw in ['總金額', '金額', '業績', 'total amount']):
539
  job_no = job_no_match.group(1).upper()
540
  self._log(f"🔄 檢測到對【單一工作單 '{job_no}'】的【標準金額計算】意圖,啟用模板。", "INFO")
541
+ fixed_sql = f"""WITH JobTotalAmount AS (SELECT JobNo, SUM(LocalAmount) AS TotalAmount FROM (SELECT DISTINCT JobNo, InvoiceCreditNoteNo, LocalAmount FROM TSR53Invoice) GROUP BY JobNo) SELECT TotalAmount FROM JobTotalAmount WHERE JobNo = '{job_no}';"""
542
+ fixes_applied.append(f"模板覆寫: 工作單 {job_no} 的標準總金額 (CTE去重)")
543
 
544
+ elif '總金額最高' in q_lower and '工作單' in q_lower:
545
  limit_match = re.search(r'(\d+)', question)
546
  limit = limit_match.group(1) if limit_match else '10'
547
  self._log(f"🔄 檢測到查詢【Top {limit} 工作單金額】意圖,啟用模板。", "INFO")
548
+ fixed_sql = f"""
549
  WITH JobTotalAmount AS (
550
  SELECT JobNo, SUM(LocalAmount) AS TotalAmount
551
  FROM (SELECT DISTINCT JobNo, InvoiceCreditNoteNo, LocalAmount FROM TSR53Invoice)
 
556
  ORDER BY TotalAmount DESC
557
  LIMIT {limit};
558
  """
559
+ fixes_applied.append(f"模板覆寫: Top {limit} 工作單金額")
560
+
561
+ elif any(kw in q_lower for kw in ['報告號碼', '報告清單', '列出報告', 'report number', 'list of reports']):
562
+ year_match = re.search(r'(\d{4})\s*年?', question)
563
+ month_match = re.search(r'(\d{1,2})\s*月', question)
564
+ time_condition, time_log = "WHERE ReportAuthorization IS NOT NULL", ""
565
+
566
+ if year_match:
567
+ year = year_match.group(1)
568
+ time_condition += f" AND strftime('%Y', ReportAuthorization) = '{year}'"
569
+ time_log = f"{year}年"
570
+ if month_match:
571
+ month = month_match.group(1).zfill(2)
572
+ time_condition += f" AND strftime('%m', ReportAuthorization) = '{month}'"
573
+ time_log += f"{month}月"
574
+
575
+ self._log(f"🔄 檢測到查詢【{time_log}報告列表】意圖,啟用模板。", "INFO")
576
+ fixed_sql = f"SELECT JobNo, ReportAuthorization FROM JobTimeline {time_condition} ORDER BY ReportAuthorization DESC;"
577
+ fixes_applied.append(f"模板覆寫: {time_log}報告列表查詢")
578
 
579
+ elif '報告' in q_lower and any(kw in q_lower for kw in ['幾份', '多少', '數量', '總數']) and not entity_match_data and not lab_group_match_data:
580
+ year_match = re.search(r'(\d{4})\s*年?', question)
581
+ time_condition, time_log = "", "總"
582
+ if year_match:
583
+ year = year_match.group(1)
584
+ time_condition = f"WHERE ReportAuthorization IS NOT NULL AND strftime('%Y', ReportAuthorization) = '{year}'"
585
+ time_log = f"{year}年"
586
+ else:
587
+ time_condition = "WHERE ReportAuthorization IS NOT NULL"
588
+ self._log(f"🔄 檢測到查詢【{time_log}全局報告總數】意圖,啟用模板。", "INFO")
589
+ fixed_sql = f"SELECT COUNT(DISTINCT JobNo) AS report_count FROM JobTimeline {time_condition};"
590
+ fixes_applied.append(f"模板覆寫: {time_log}全局報告總數查詢")
591
+
592
+ elif entity_match_data and any(kw in q_lower for kw in ['業績', '營收', '金額', 'sales', 'revenue']):
593
  entity_type, entity_name, column_name = entity_match_data["type"], entity_match_data["name"], entity_match_data["column"]
594
  year = (re.search(r'(\d{4})\s*年?', question) or ['', datetime.now().strftime('%Y')])[1]
595
  self._log(f"🔄 檢測到查詢【{entity_type} '{entity_name}' 在 {year} 年的總業績】意圖,啟用模板。", "INFO")
596
+ fixed_sql = f"""WITH JobTotalAmount AS (SELECT JobNo, SUM(LocalAmount) AS TotalAmount FROM (SELECT DISTINCT JobNo, InvoiceCreditNoteNo, LocalAmount FROM TSR53Invoice) GROUP BY JobNo) SELECT SUM(jta.TotalAmount) AS total_revenue FROM TSR53SampleDescription AS sd JOIN JobTotalAmount AS jta ON sd.JobNo = jta.JobNo WHERE {column_name} LIKE '%{entity_name}%' AND strftime('%Y', sd.FirstReportAuthorizedDate) = '{year}';"""
597
+ fixes_applied.append(f"模板覆寫: 查詢 {entity_type}='{entity_name}' ({year}年) 的總業績")
598
+
599
+ elif not entity_match_data and any(kw in q_lower for kw in ['業績', '營收', '金額', 'sales', 'revenue']):
600
  year_match, month_match = re.search(r'(\d{4})\s*年?', question), re.search(r'(\d{1,2})\s*月', question)
601
  time_condition, time_log = "", "總"
602
  if year_match:
603
  year = year_match.group(1); time_condition = f"WHERE strftime('%Y', InvoiceCreditNoteDate) = '{year}'"; time_log = f"{year}年"
604
  if month_match: month = month_match.group(1).zfill(2); time_condition += f" AND strftime('%m', InvoiceCreditNoteDate) = '{month}'"; time_log += f"{month}月"
605
  self._log(f"🔄 檢測到查詢【{time_log}全局總業績】意圖,啟用模板。", "INFO")
606
+ fixed_sql = f"""SELECT SUM(LocalAmount) AS total_revenue FROM TSR53Invoice {time_condition};"""
607
+ fixes_applied.append(f"模板覆寫: {time_log}全局總業績查詢")
608
 
609
+ elif lab_group_match_data and any(kw in q_lower for kw in ['測試項目', 'test item']):
610
  lab_group_code = lab_group_match_data["codes"][0]
611
  target_table = f"JobTimeline_{lab_group_code}"
612
  year = (re.search(r'(\d{4})\s*年', question) or ['', datetime.now().strftime('%Y')])[1]
 
618
  time_condition += f" AND strftime('%m', end_time) = '{month}'"
619
  month_str = f"{month}月"
620
  self._log(f"🔄 檢測到查詢【{lab_group_code}組】完成的【測試項目數】意圖,啟用專屬模板。", "INFO")
621
+ fixed_sql = f"""SELECT COUNT(JobItemKey) AS test_item_count FROM {target_table} WHERE end_time IS NOT NULL AND {time_condition};"""
622
+ fixes_applied.append(f"模板覆寫: 查詢 {lab_group_code}組 在 {year}年{month_str} 完成的測試項目數")
 
 
 
 
 
 
 
 
 
 
 
 
 
623
 
624
+ if not fixes_applied:
625
+ self._log("未觸發任何模板,執行常規修正流程...", "DEBUG")
626
+
627
+ dialect_corrections = {
628
+ r'YEAR\s*\(([^)]+)\)': r"strftime('%Y', \1)",
629
+ r"(strftime\('%Y',\s*[^)]+\))\s*=\s*(\d{4})": r"\1 = '\2'",
630
+ r"EXTRACT\s*\(\s*YEAR\s+FROM\s+([^)]+)\s*\)": r"strftime('%Y', \1)"
631
+ }
632
+ for pattern, replacement in dialect_corrections.items():
633
+ if re.search(pattern, fixed_sql, re.IGNORECASE):
634
+ fixed_sql = re.sub(pattern, replacement, fixed_sql, flags=re.IGNORECASE)
635
+ fixes_applied.append(f"修正方言: {pattern}")
636
+
637
+ schema_corrections = {
638
+ 'TSR53ReportAuthorization': 'TSR53SampleDescription', 'TSR53TestResult': 'TSR53SampleDescription',
639
+ 'JobInvoice': 'TSR53Invoice', 'JobInvoiceAuthorization': 'TSR53Invoice', 'JobInvoiceCreditNote': 'TSR53Invoice',
640
+ 'Customer': 'TSR53SampleDescription', 'Customers': 'TSR53SampleDescription',
641
+ 'Invoice': 'TSR53Invoice', 'Invoices': 'TSR53Invoice', 'Job': 'JobTimeline', 'Jobs': 'JobsInProgress',
642
+ 'Tests': 'TSR53MarsItem', 'TestsLog': 'JobItemsInProgress',
643
+ 'AuthorizationDate': 'ReportAuthorization', 'ReportAuthorizationDate': 'ReportAuthorization',
644
+ 'LegalAuthorization': 'OverallRating', 'LegalAuthorizationDate': 'ReportAuthorization',
645
+ 'TestResult': 'OverallRating', 'Rating': 'OverallRating', 'CustomerName': 'BuyerName', 'InvoiceTo': 'InvoiceToName',
646
+ 'Applicant': 'ApplicantName', 'Agent': 'AgentName', 'JobNumber': 'JobNo', 'ReportNo': 'JobNo', 'TestName': 'ItemInvoiceDescriptionJob',
647
+ 'CreationDate': 'JobCreation', 'CreateDate': 'JobCreation', 'CompletedDate': 'ReportAuthorization',
648
+ 'InvoiceCreditNoteAmount': 'LocalAmount',
649
+ 'Amount': 'LocalAmount', 'Price': 'LocalAmount', 'Lab': 'LabGroup'
650
+ }
651
+ for wrong, correct in schema_corrections.items():
652
+ pattern = r'\b' + re.escape(wrong) + r'\b'
653
+ if re.search(pattern, fixed_sql, re.IGNORECASE):
654
+ fixed_sql = re.sub(pattern, correct, fixed_sql, flags=re.IGNORECASE)
655
+ fixes_applied.append(f"映射 Schema: '{wrong}' -> '{correct}'")
656
+
657
+ if any(kw in q_lower for kw in ['幾份', '多少', 'how many', 'count', '數量']) and 'select ' in fixed_sql.lower() and 'count' not in fixed_sql.lower() and 'group by' not in fixed_sql.lower():
658
+ fixed_sql = re.sub(r'SELECT\s+.*?FROM', 'SELECT COUNT(*) FROM', fixed_sql, count=1, flags=re.IGNORECASE)
659
+ fixes_applied.append("修正邏輯: 補全 COUNT(*)")
660
+
661
+ fixed_sql = fixed_sql.strip()
662
+ if not fixed_sql.endswith(';'):
663
+ fixed_sql += ';'
664
+ fixed_sql = re.sub(r'\s+', ' ', fixed_sql).strip()
665
+
666
+ if fixes_applied:
667
+ self._log("🔄 SQL 已被自動修正:", "INFO")
668
+ self._log(f" - 原始 SQL: {original_sql}", "DEBUG")
669
+ for fix in fixes_applied:
670
+ self._log(f" - 應用規則: {fix}", "DEBUG")
671
+ self._log(f" - 修正後 SQL: {fixed_sql}", "INFO")
672
+ else:
673
+ self._log("✅ SQL 驗證通過,無需常規修正。", "INFO")
674
 
675
+ return fixed_sql
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
676
 
677
  def _finalize_sql(self, sql: str, log_message: str) -> Tuple[str, str]:
678
  """一個輔助函數,用於清理最終的SQL並記錄成功日誌。"""