/* Static demonstration catalog: no server or EC2 lookup. */ (function () { "use strict"; const state = { tthc: {sequence: 0, controller: null, items: [], selected: null}, vbpl: {sequence: 0, controller: null, items: [], selected: null} }; const el = id => document.getElementById(id); const esc = value => String(value ?? "").replace(/[&<>"']/g, c => ({"&": "&", "<": "<", ">": ">", '"': """, "'": "'"}[c])); const normalized = value => String(value || "").toLowerCase().normalize("NFD") .replace(/[\u0300-\u036f]/g, "").replace(/đ/g, "d").trim(); function externalURL(value) { try { const url = new URL(value); return ["https:", "http:"].includes(url.protocol) ? url.href : ""; } catch (_) { return ""; } } function clearDetails() { for (const [id, text] of Object.entries({ lawBox: "Chưa chọn văn bản hoặc chưa có căn cứ pháp lý được tra cứu.", tthcBox: "Chưa chọn thủ tục hành chính.", precBox: "Chưa tra cứu tiền lệ phản ánh cho nội dung này.", nextBox: "Chọn kết quả tra cứu để xem thông tin hoặc gửi câu hỏi cho trợ lý." })) { if (el(id)) el(id).innerHTML = `
${text}
`; } for (const id of ["cntAll", "cntTthc", "cntVbpl", "cntPakn"]) { if (el(id)) el(id).textContent = "0"; } window.filterEvidenceTab?.("all"); } function statusLabel(item) { return "Dữ liệu mẫu · Chưa xác minh hiệu lực hiện tại"; if (item.con_hieu_luc === false) return "Đã hết hiệu lực"; if (item.con_hieu_luc === true) return "Còn hiệu lực theo dữ liệu tra cứu"; return "Chưa có thông tin hiệu lực"; } function showDetails(type, item) { clearDetails(); if (!item) return; const info = `
Dữ liệu mẫu lưu sẵn · Chưa đồng bộ hoặc đối soát bằng EC2
${esc(item.title)}
Cơ quan: ${esc(item.co_quan_ban_hanh || "Chưa có thông tin")}
${type === "tthc" ? "Mã thủ tục" : "Số hiệu"}: ${esc(type === "tthc" ? item.doc_id : item.so_hieu)}
`; if (type === "tthc") { if (el("tthcBox")) el("tthcBox").innerHTML = info; if (el("lawBox")) el("lawBox").innerHTML = /căn cứ pháp lý/i.test(item.section || "") ? `
${esc(item.full_text || item.snippet)}
` : '
Đây là dữ liệu thủ tục mẫu. Bạn có thể hỏi Gemini để nhận nguồn tham khảo; nguồn chưa được đối soát bằng EC2.
'; } else { if (el("lawBox")) el("lawBox").innerHTML = `${info}
${esc(statusLabel(item))}
${item.ngay_hieu_luc ? `
Ngày hiệu lực: ${esc(item.ngay_hieu_luc)}
` : ""}`; } if (el("nextBox")) el("nextBox").innerHTML = '
Xem nội dung bản mẫu trong kết quả, hoặc chọn “Nạp vào phản ánh mới” / “Trích dẫn vào phản ánh” để hỏi trợ lý.
'; if (el("cntAll")) el("cntAll").textContent = "1"; if (el(type === "tthc" ? "cntTthc" : "cntVbpl")) el(type === "tthc" ? "cntTthc" : "cntVbpl").textContent = "1"; } function relevantItems(items, query, type) { const q = normalized(query); const words = q.match(/[\p{L}\p{N}]+/gu) || []; if (!words.length) return []; const legalNumber = type === "vbpl" ? q.match(/\d+\s*\/\s*\d+(?:\s*\/\s*[\p{L}\p{N}-]+)?/u)?.[0] : null; const seen = new Set(); return items.filter(item => { // A document merely citing a number must not appear as that document itself. if (legalNumber && !normalized(item.so_hieu).replace(/\s/g, "") .includes(legalNumber.replace(/\s/g, ""))) return false; // Exclude zero-match candidates; BM25 can otherwise fill its top-k with unrelated rows. const text = normalized([item.title, item.doc_id, item.so_hieu, item.full_text, item.snippet, item.co_quan_ban_hanh, item.keywords].join(" ")); const tokens = new Set(text.match(/[\p{L}\p{N}]+/gu) || []); if (!words.every(word => tokens.has(word))) return false; const key = item.doc_id || item.so_hieu || item.title; if (seen.has(key)) return false; seen.add(key); return true; }); } function notice(type, text, error = false) { if (el(type + "CountBar")) el(type + "CountBar").style.display = "none"; if (el(type + "Results")) el(type + "Results").innerHTML = `
${esc(text)}
`; } function renderKnowledge(type, items, query) { const list = el(type + "Results"); if (!list) return; if (el(type + "CountBar")) el(type + "CountBar").style.display = "flex"; if (el(type + "TotalText")) el(type + "TotalText").textContent = `Hiển thị ${items.length} kết quả mẫu${query ? ` cho “${query}”` : " lưu sẵn"}`; list.innerHTML = items.length ? items.map((item, index) => { const url = externalURL(item.url); const identifier = type === "tthc" ? item.doc_id : item.so_hieu; return `
${esc(item.title || "Chưa có tiêu đề")}
${identifier ? `${esc(identifier)}` : ""}Dữ liệu mẫu ${type === "vbpl" ? `${esc(statusLabel(item))}` : ""}
🏛️ ${esc(item.co_quan_ban_hanh || "Chưa có thông tin cơ quan")} ${item.section ? `Phần: ${esc(item.section)}` : ""} ${item.ngay_hieu_luc ? `Ngày hiệu lực: ${esc(item.ngay_hieu_luc)}` : ""}
${esc(item.snippet || item.full_text || "")}
${item.full_text ? `
Xem nội dung bản mẫu
${esc(item.full_text)}
` : ""}
${url ? `Xem nguồn dữ liệu` : ""}
`; }).join("") : `
Không tìm thấy kết quả phù hợp. Hãy thử tên thủ tục, số hiệu văn bản hoặc từ khóa khác.
`; list.querySelectorAll(".kb-item-card").forEach(card => { const item = items[Number(card.dataset.idx)]; card.querySelector('[data-action="details"]').addEventListener("click", () => { state[type].selected = item; showDetails(type, item); }); card.querySelector('[data-action="apply"]').addEventListener("click", () => { if (type === "tthc") applyTTHCToComplaint(item.title, item.doc_id); else quoteVBPLToComplaint(item.so_hieu || item.title, item.section); }); }); } let catalogPromise; async function catalog() { if(!catalogPromise)catalogPromise=fetch(new URL("demo-catalog.json",document.baseURI)).then(async r=>{if(!r.ok)throw new Error("Không tải được bộ dữ liệu mẫu.");return r.json();}).catch(e=>{catalogPromise=null;throw e;}); return catalogPromise; } async function initCatalog() { const data=await catalog(); for(const type of ["tthc","vbpl"]) { const view=el("view-"+type), row=view?.querySelector(".kb-chips-row"); if(row) {row.innerHTML='Từ khóa có sẵn:'; for(const topic of data.topics[type]) {const b=document.createElement("button");b.type="button";b.className="kb-chip";b.dataset.kb=type;b.dataset.q=topic.query;b.textContent=topic.label;b.addEventListener("click",()=>searchKnowledge(type,topic.query));row.append(b);} } const badge=view?.querySelector(".aws-card-header .pill");if(badge)badge.textContent=data[type].length+" kết quả mẫu lưu sẵn"; const nav=document.querySelector(`[data-view="${type}"] .pill`);if(nav)nav.textContent=data[type].length+" mẫu"; } await searchKnowledge("tthc", "");await searchKnowledge("vbpl", ""); } async function searchKnowledge(type, explicitQuery) { if (!state[type]) return; const current = state[type]; const sequence = ++current.sequence; current.controller?.abort(); const controller = new AbortController(); current.controller = controller; const input = el(type + "Input"); if (explicitQuery !== undefined && input) input.value = explicitQuery; const query = (explicitQuery ?? input?.value ?? "").trim(); if (el(type + "Clear")) el(type + "Clear").style.display = query ? "block" : "none"; current.items = []; current.selected = null; if (!el("view-" + type)?.hidden) clearDetails(); notice(type, `Đang tra cứu “${query}”…`); try { const data = await catalog(); if(sequence !== current.sequence)return; current.items = query ? relevantItems(data[type],query,type).slice(0,20) : data[type].slice(0,20); current.selected = current.items[0] || null; renderKnowledge(type, current.items, query); if (!el("view-" + type)?.hidden) showDetails(type, current.selected); } catch (error) { if (controller.signal.aborted || sequence !== current.sequence) return; notice(type, error.message || "Không tra cứu được dữ liệu. Vui lòng thử lại.", true); } } function clearKBSearch(type) { searchKnowledge(type, ""); el(type + "Input")?.focus(); } function applyTTHCToComplaint(title, docId) { window.show?.("home"); const input = el("q"); if (input) { input.value = `Tôi cần hướng dẫn thủ tục: ${title}${docId ? ` (Mã TTHC: ${docId})` : ""}. Cụ thể: `; input.focus(); } if (el("f_procedure_name")) { el("f_procedure_name").value = title; el("f_procedure_name").dispatchEvent(new Event("input", {bubbles: true})); } } function quoteVBPLToComplaint(identifier, section) { window.show?.("home"); const input = el("q"); if (input) { const citation = `${identifier}${section ? ` (${section})` : ""}`; input.value = input.value.trim() ? `${input.value.trim()}\n\nCăn cứ pháp lý tham khảo: ${citation}` : `Tôi muốn hỏi về quy định tại ${citation}: `; input.focus(); } } Object.assign(window, {searchKnowledge, clearKBSearch, applyTTHCToComplaint, quoteVBPLToComplaint}); window.CivicKnowledge = {clearDetails, restore: type => showDetails(type, state[type]?.selected)}; el("globalSearch")?.addEventListener("keydown", event => { if (event.key !== "Enter") return; const query = event.target.value.trim(); if (!query) return; event.preventDefault(); const type = /nghị\s+định|luật|thông\s+tư|quyết\s+định|pháp\s+lệnh|\d+\s*\/\s*\d+/i.test(query) ? "vbpl" : "tthc"; window.show?.(type); searchKnowledge(type, query); }); initCatalog().catch(error=>{notice("tthc",error.message,true);notice("vbpl",error.message,true);}); })();