File size: 17,905 Bytes
d50bd61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
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 <strong>${items.length}</strong> kết quả${qText} (CSDL Quốc gia liên thông)`;
  }

  if (!items || items.length === 0) {
    listEl.innerHTML = `
      <div style="padding: 40px 20px; text-align: center; color: var(--text-dim, #666);">
        <div style="font-size: 32px; margin-bottom: 8px;">🔍</div>
        <div style="font-weight: 600; margin-bottom: 4px;">Không tìm thấy kết quả phù hợp với từ khóa "${escapeHtml(query)}"</div>
        <div style="font-size: 13px;">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ế...</div>
      </div>
    `;
    return;
  }

  const esc = escapeHtml;

  if (type === "tthc") {
    listEl.innerHTML = items.map((it, idx) => `
      <div class="kb-item-card" data-idx="${idx}">
        <div class="kb-item-header">
          <div class="kb-item-title">${esc(it.title || "Thủ tục hành chính")}</div>
          <div class="kb-badges-group">
            ${it.doc_id ? `<span class="pill proc" style="font-size:11px;font-weight:700">Mã: ${esc(it.doc_id)}</span>` : ""}
            <span class="pill success" style="font-size:11px">● Đang hiệu lực</span>
          </div>
        </div>
        <div class="kb-item-meta">
          <span>🏛️ ${esc(it.co_quan_ban_hanh || "Bộ Tư pháp")}</span>
          ${it.section ? `<span>📋 Phần: ${esc(it.section)}</span>` : ""}
        </div>
        <div class="kb-item-snippet">${esc(it.snippet || it.full_text || "")}</div>
        <div class="kb-item-actions">
          <button type="button" class="kb-apply-btn" onclick="applyTTHCToComplaint('${esc(it.title)}', '${esc(it.doc_id||"")}')">
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 5v14M5 12h14"/></svg>
            <span>Nạp vào phản ánh mới</span>
          </button>
          <a href="https://dichvucong.gov.vn/p/home/dvc-tra-cuu-thu-tuc-hanh-chinh.html" target="_blank" rel="noopener" class="kb-external-link">
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M18 13v6a2 2 0 01-2 2H5a2 2 0 01-2-2V8a2 2 0 012-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>
            <span>Xem trên Dịch vụ công Quốc gia</span>
          </a>
        </div>
      </div>
    `).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 = `<div><strong>Cơ quan ban hành:</strong> ${esc(top.co_quan_ban_hanh || "Bộ Tư pháp")}</div><div style="margin-top:4px;"><strong>Quy định:</strong> Theo chuẩn hóa Nghị định 30/2020/NĐ-CP và Quyết định 45/2016/QĐ-TTg.</div>`;
      if (procEl) procEl.innerHTML = `<div><strong>${esc(top.title)}</strong></div><div style="font-size:12px;margin-top:4px;color:var(--text-dim,#666)">Mã thủ tục: ${esc(top.doc_id || "Chưa cấp")}</div>`;
      if (paknEl) paknEl.innerHTML = `<div>Đã ghi nhận <strong>128</strong> 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.</div>`;
      if (nextEl) nextEl.innerHTML = `<ol style="padding-left:18px;margin:0;font-size:12px"><li>Kiểm tra giấy tờ theo mục Thành phần hồ sơ.</li><li>Nộp hồ sơ trực tuyến hoặc tại Trung tâm Phục vụ HCC.</li><li>Theo dõi mã tra cứu trên Cổng DVC.</li></ol>`;
    }
  } else {
    // VBPL
    listEl.innerHTML = items.map((it, idx) => `
      <div class="kb-item-card" data-idx="${idx}">
        <div class="kb-item-header">
          <div class="kb-item-title">${esc(it.title || "Văn bản quy phạm pháp luật")}</div>
          <div class="kb-badges-group">
            ${it.so_hieu ? `<span class="pill law" style="font-size:11px;font-weight:700">${esc(it.so_hieu)}</span>` : ""}
            <span class="pill success" style="font-size:11px">● Còn hiệu lực</span>
          </div>
        </div>
        <div class="kb-item-meta">
          <span>🏛️ ${esc(it.co_quan_ban_hanh || "Cơ quan nhà nước")}</span>
          ${it.section ? `<span>📜 ${esc(it.section)}</span>` : ""}
          ${it.ngay_hieu_luc ? `<span>📅 Hiệu lực: ${esc(it.ngay_hieu_luc)}</span>` : ""}
        </div>
        <div class="kb-item-snippet" style="border-left-color: #2e7d32">${esc(it.snippet || it.full_text || "")}</div>
        <div class="kb-item-actions">
          <button type="button" class="kb-apply-btn" style="color:#2e7d32;background:rgba(46,125,50,0.08);border-color:rgba(46,125,50,0.3)" onclick="quoteVBPLToComplaint('${esc(it.so_hieu||it.title)}', '${esc(it.section||"")}', '${esc(it.title||"")}')">
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></svg>
            <span>Trích dẫn vào phản ánh</span>
          </button>
          ${it.url ? `<a href="${esc(it.url)}" target="_blank" rel="noopener" class="kb-external-link">
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M18 13v6a2 2 0 01-2 2H5a2 2 0 01-2-2V8a2 2 0 012-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>
            <span>Xem trên vbpl.vn</span>
          </a>` : ""}
        </div>
      </div>
    `).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 = `<div><strong>${esc(top.title)}</strong></div><div style="margin-top:4px;font-size:12px;color:var(--text-dim,#666)">Số hiệu: ${esc(top.so_hieu || "N/A")} | Cơ quan: ${esc(top.co_quan_ban_hanh || "Quốc hội")}</div>`;
      if (scopeEl) scopeEl.innerHTML = `<div>Á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.</div>`;
      if (appliedEl) appliedEl.innerHTML = `<div>Á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.</div>`;
      if (updatesEl) updatesEl.innerHTML = `<div>Trạng thái: <strong>Còn hiệu lực thi hành</strong></div>`;
    }
  }
}

// Á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</script>\n</body>\n</html>\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 </script> before </body>
        cut_idx = content.rfind("</script>")
    
    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"<script>(.*?)</script>", 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!")