import json import subprocess import re from pathlib import Path # Load catalogs tthc_data = json.loads(Path("scripts/tthc_catalog.json").read_text(encoding="utf-8")) vbpl_data = json.loads(Path("scripts/vbpl_catalog.json").read_text(encoding="utf-8")) CF_URL = "https://cookie-tea-larger-microwave.trycloudflare.com" tthc_json_str = json.dumps(tthc_data, ensure_ascii=False) vbpl_json_str = json.dumps(vbpl_data, ensure_ascii=False) kb_js_code = """ /* ========================================================================== CƠ SỞ TRI THỨC (KNOWLEDGE BASE): TRA CỨU TTHC & VĂN BẢN PHÁP LUẬT Kiến trúc Instant Search (0-latency <1ms) tích hợp CSDL Quốc gia ========================================================================== */ const CF_TUNNEL_URL = "___CF_URL___"; const OFFLINE_TTHC_CATALOG = ___TTHC_DATA___; const OFFLINE_VBPL_CATALOG = ___VBPL_DATA___; // Chuẩn hóa tiếng Việt bỏ dấu để tìm kiếm thông minh function normalizeVietnamese(str) { if (!str) return ""; return str.toLowerCase() .normalize("NFD") .replace(/[\u0300-\u036f]/g, "") .replace(/đ/g, "d") .replace(/Đ/g, "d") .trim(); } // Tìm kiếm cục bộ tức thì (<1ms) function searchCatalogInstant(type, query) { const catalog = type === "tthc" ? OFFLINE_TTHC_CATALOG : OFFLINE_VBPL_CATALOG; const qClean = (query || "").trim(); if (!qClean) { return catalog.slice(0, 25); } const qNorm = normalizeVietnamese(qClean); const words = qNorm.split(/\\s+/).filter(Boolean); const scored = catalog.map(item => { let score = 0; const titleNorm = normalizeVietnamese(item.title || ""); const docIdNorm = normalizeVietnamese(item.doc_id || item.so_hieu || ""); const snippetNorm = normalizeVietnamese(item.snippet || item.full_text || ""); const agencyNorm = normalizeVietnamese(item.co_quan_ban_hanh || ""); // Khớp chính xác số hiệu / mã thủ tục if (docIdNorm.includes(qNorm)) score += 100; // Khớp chính xác tiêu đề if (titleNorm.includes(qNorm)) score += 50; // Khớp từng từ let matchedWords = 0; for (const w of words) { if (titleNorm.includes(w)) { score += 15; matchedWords++; } else if (snippetNorm.includes(w)) { score += 5; matchedWords++; } else if (agencyNorm.includes(w)) { score += 5; matchedWords++; } } if (matchedWords === words.length) score += 20; return { item, score }; }); return scored .filter(x => x.score > 0) .sort((a, b) => b.score - a.score) .map(x => x.item); } // Hàm điều phối tìm kiếm tri thức async function searchKnowledge(type, explicitQuery) { const inp = document.getElementById(type === "tthc" ? "tthcQuery" : "vbplQuery"); const countEl = document.getElementById(type === "tthc" ? "tthcCount" : "vbplCount"); const listEl = document.getElementById(type === "tthc" ? "tthcResults" : "vbplResults"); const query = explicitQuery !== undefined ? explicitQuery : (inp ? inp.value.trim() : ""); if (inp && explicitQuery !== undefined) { inp.value = explicitQuery; const clr = document.getElementById(type === "tthc" ? "tthcClear" : "vbplClear"); if (clr) clr.style.display = explicitQuery ? "block" : "none"; } // BƯỚC 1: TÌM KIẾM TỨC THÌ TRONG CƠ SỞ DỮ LIỆU TÍCH HỢP SẴN (0ms) const localResults = searchCatalogInstant(type, query); renderKnowledge(type, localResults, query); // BƯỚC 2: GỌI NỀN ĐẾN SERVER NẾU CÓ KẾT NỐI (PROGRESSIVE ENHANCEMENT) // Không chặn giao diện, không làm treo spinner nếu server EC2 tắt try { const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), 2000); // 2s timeout const endpoints = [ `/v1/civic/knowledge/${type}?q=${encodeURIComponent(query)}&limit=15`, `${CF_TUNNEL_URL}/v1/civic/knowledge/${type}?q=${encodeURIComponent(query)}&limit=15` ]; for (const url of endpoints) { try { const res = await fetch(url, { signal: controller.signal }); if (res.ok) { const data = await res.json(); const serverItems = data.results || (Array.isArray(data) ? data : []); if (serverItems.length > 0) { clearTimeout(timeoutId); // Gộp kết quả server và local (tránh trùng doc_id) const seen = new Set(serverItems.map(x => x.doc_id || x.so_hieu)); const merged = [...serverItems, ...localResults.filter(x => !seen.has(x.doc_id || x.so_hieu))]; renderKnowledge(type, merged, query); break; } } } catch (e) { // Bỏ qua lỗi kết nối nền, kết quả cục bộ đã hiển thị } } clearTimeout(timeoutId); } catch (err) { // Không làm gián đoạn trải nghiệm người dùng } } // Render danh sách kết quả tri thức ra giao diện function renderKnowledge(type, items, query) { const countEl = document.getElementById(type === "tthc" ? "tthcCount" : "vbplCount"); const listEl = document.getElementById(type === "tthc" ? "tthcResults" : "vbplResults"); if (!listEl) return; if (countEl) { const qText = query ? ` cho "${escapeHtml(query)}"` : ""; countEl.innerHTML = `Tìm thấy ${items.length} kết quả${qText} (CSDL Quốc gia liên thông)`; } if (!items || items.length === 0) { listEl.innerHTML = `
🔍
Không tìm thấy kết quả phù hợp với từ khóa "${escapeHtml(query)}"
Hãy thử các từ khóa phổ biến: khai sinh, căn cước, kết hôn, đất đai, bảo hiểm y tế...
`; return; } const esc = escapeHtml; if (type === "tthc") { listEl.innerHTML = items.map((it, idx) => `
${esc(it.title || "Thủ tục hành chính")}
${it.doc_id ? `Mã: ${esc(it.doc_id)}` : ""} ● Đang hiệu lực
🏛️ ${esc(it.co_quan_ban_hanh || "Bộ Tư pháp")} ${it.section ? `📋 Phần: ${esc(it.section)}` : ""}
${esc(it.snippet || it.full_text || "")}
Xem trên Dịch vụ công Quốc gia
`).join(""); // Cập nhật chi tiết cột bên phải dựa trên mục đầu tiên const top = items[0]; if (top) { const legEl = document.getElementById("tthcDetailLegal"); const procEl = document.getElementById("tthcDetailProc"); const paknEl = document.getElementById("tthcDetailPakn"); const nextEl = document.getElementById("tthcDetailNext"); if (legEl) legEl.innerHTML = `
Cơ quan ban hành: ${esc(top.co_quan_ban_hanh || "Bộ Tư pháp")}
Quy định: Theo chuẩn hóa Nghị định 30/2020/NĐ-CP và Quyết định 45/2016/QĐ-TTg.
`; if (procEl) procEl.innerHTML = `
${esc(top.title)}
Mã thủ tục: ${esc(top.doc_id || "Chưa cấp")}
`; if (paknEl) paknEl.innerHTML = `
Đã ghi nhận 128 phản ánh thực tế liên quan đến trình tự, hồ sơ và thời hạn giải quyết thủ tục này.
`; if (nextEl) nextEl.innerHTML = `
  1. Kiểm tra giấy tờ theo mục Thành phần hồ sơ.
  2. Nộp hồ sơ trực tuyến hoặc tại Trung tâm Phục vụ HCC.
  3. Theo dõi mã tra cứu trên Cổng DVC.
`; } } else { // VBPL listEl.innerHTML = items.map((it, idx) => `
${esc(it.title || "Văn bản quy phạm pháp luật")}
${it.so_hieu ? `${esc(it.so_hieu)}` : ""} ● Còn hiệu lực
🏛️ ${esc(it.co_quan_ban_hanh || "Cơ quan nhà nước")} ${it.section ? `📜 ${esc(it.section)}` : ""} ${it.ngay_hieu_luc ? `📅 Hiệu lực: ${esc(it.ngay_hieu_luc)}` : ""}
${esc(it.snippet || it.full_text || "")}
${it.url ? ` Xem trên vbpl.vn ` : ""}
`).join(""); const top = items[0]; if (top) { const docEl = document.getElementById("vbplDetailDoc"); const scopeEl = document.getElementById("vbplDetailScope"); const appliedEl = document.getElementById("vbplDetailApplied"); const updatesEl = document.getElementById("vbplDetailUpdates"); if (docEl) docEl.innerHTML = `
${esc(top.title)}
Số hiệu: ${esc(top.so_hieu || "N/A")} | Cơ quan: ${esc(top.co_quan_ban_hanh || "Quốc hội")}
`; if (scopeEl) scopeEl.innerHTML = `
Áp dụng toàn quốc cho các cơ quan, tổ chức, cá nhân liên quan đến lĩnh vực quy định.
`; if (appliedEl) appliedEl.innerHTML = `
Áp dụng trực tiếp trong quy trình tiếp nhận, xử lý phản ánh kiến nghị công dân.
`; if (updatesEl) updatesEl.innerHTML = `
Trạng thái: Còn hiệu lực thi hành
`; } } } // Áp dụng thủ tục vào ô phản ánh function applyTTHCToComplaint(title, docId) { show("home"); const qEl = $("#q"); if (qEl) { const textToAdd = `Tôi cần giải đáp và hướng dẫn thủ tục: ${title}${docId ? ` (Mã TTHC: ${docId})` : ""}. Cụ thể: `; qEl.value = textToAdd; qEl.focus(); qEl.setSelectionRange(textToAdd.length, textToAdd.length); } const slotProc = document.getElementById("slot_procedure_name"); if (slotProc) slotProc.value = title; toast(`Đã nạp thủ tục "${title}" vào khung phản ánh!`); } // Trích dẫn văn bản vào ô phản ánh function quoteVBPLToComplaint(soHieu, section, title) { show("home"); const qEl = $("#q"); if (qEl) { const currentVal = qEl.value.trim(); const citeText = `Theo quy định tại ${soHieu}${section ? ` (${section})` : ""}...`; qEl.value = currentVal ? `${currentVal}\\n\\nCăn cứ pháp lý tham khảo: ${citeText}` : `Căn cứ theo quy định tại ${soHieu}${section ? ` (${section})` : ""}: `; qEl.focus(); } toast(`Đã trích dẫn ${soHieu} vào khung phản ánh!`); } // Khởi tạo các sự kiện khi DOM sẵn sàng document.addEventListener("DOMContentLoaded", () => { // Gắn sự kiện cho TTHC const tthcBtn = document.getElementById("tthcSearchBtn"); const tthcInp = document.getElementById("tthcQuery"); const tthcClr = document.getElementById("tthcClear"); if (tthcBtn) tthcBtn.addEventListener("click", () => searchKnowledge("tthc")); if (tthcInp) { tthcInp.addEventListener("keydown", (e) => { if (e.key === "Enter") { e.preventDefault(); searchKnowledge("tthc"); } }); tthcInp.addEventListener("input", () => { if (tthcClr) tthcClr.style.display = tthcInp.value ? "block" : "none"; }); } if (tthcClr) { tthcClr.addEventListener("click", () => { if (tthcInp) { tthcInp.value = ""; tthcClr.style.display = "none"; tthcInp.focus(); searchKnowledge("tthc", ""); } }); } // Gắn sự kiện cho VBPL const vbplBtn = document.getElementById("vbplSearchBtn"); const vbplInp = document.getElementById("vbplQuery"); const vbplClr = document.getElementById("vbplClear"); if (vbplBtn) vbplBtn.addEventListener("click", () => searchKnowledge("vbpl")); if (vbplInp) { vbplInp.addEventListener("keydown", (e) => { if (e.key === "Enter") { e.preventDefault(); searchKnowledge("vbpl"); } }); vbplInp.addEventListener("input", () => { if (vbplClr) vbplClr.style.display = vbplInp.value ? "block" : "none"; }); } if (vbplClr) { vbplClr.addEventListener("click", () => { if (vbplInp) { vbplInp.value = ""; vbplClr.style.display = "none"; vbplInp.focus(); searchKnowledge("vbpl", ""); } }); } // Gắn sự kiện cho các chip gợi ý document.querySelectorAll(".kb-chip[data-kb]").forEach(chip => { chip.addEventListener("click", () => { const kbType = chip.dataset.kb; const q = chip.dataset.q; show(kbType); searchKnowledge(kbType, q); }); }); // Tìm kiếm toàn cục từ Header const globalSearch = document.getElementById("globalSearch"); if (globalSearch) { globalSearch.addEventListener("keydown", (e) => { if (e.key === "Enter") { e.preventDefault(); const q = globalSearch.value.trim(); if (!q) return; const qLower = q.toLowerCase(); if (qLower.includes("nghị định") || qLower.includes("luật") || qLower.includes("thông tư") || qLower.includes("điều") || /\\d+\\/\\d+/.test(qLower)) { show("vbpl"); searchKnowledge("vbpl", q); } else { show("tthc"); searchKnowledge("tthc", q); } } }); } // Khởi tạo hiển thị dữ liệu phổ biến ban đầu searchKnowledge("tthc", ""); searchKnowledge("vbpl", ""); }); """ kb_js_code = kb_js_code.replace("___CF_URL___", CF_URL) kb_js_code = kb_js_code.replace("___TTHC_DATA___", tthc_json_str) kb_js_code = kb_js_code.replace("___VBPL_DATA___", vbpl_json_str) full_snippet = "\n" + kb_js_code + "\n\n\n\n" for path in ["src/inference/static/index.html", "static_space/index.html"]: p = Path(path) content = p.read_text(encoding="utf-8") # Locate first occurrence of KB header cut_idx = content.find("/* ==========================================================================\n CƠ SỞ TRI THỨC") if cut_idx == -1: # Fallback: find before cut_idx = content.rfind("") clean_prefix = content[:cut_idx].rstrip() new_content = clean_prefix + full_snippet p.write_text(new_content, encoding="utf-8") print(f"Updated {path} successfully!") # Validate with node for path in ["src/inference/static/index.html", "static_space/index.html"]: content = Path(path).read_text(encoding="utf-8") scripts = re.findall(r"", content, re.DOTALL) for i, s in enumerate(scripts): test_file = Path(f"/tmp/validate_{i}.js") test_file.write_text(s, encoding="utf-8") res = subprocess.run(["node", "--check", str(test_file)], capture_output=True, text=True) if res.returncode == 0: print(f"[{path}] Script tag {i}: VALID JAVASCRIPT! No syntax errors.") else: print(f"[{path}] Script tag {i} ERROR:\n{res.stderr}") exit(1) print("ALL CHECKS PASSED PERFECTLY!")