function login() {
const u = document.getElementById("username")?.value || "";
const p = document.getElementById("password")?.value || "";
if (u === "admin" && p === "1234") {
document.getElementById("login").style.display = "none";
document.getElementById("dashboard").style.display = "block";
enableSubmenuClick();
hideAllSections();
showSection("Nl");
document.getElementById("Nl")?.scrollIntoView({ behavior: "smooth" });
} else {
alert("Sai tên đăng nhập hoặc mật khẩu!");
}
}
const BACKEND_URL = "https://doluong6-qlht.hf.space";
// ===== Helpers ẩn/hiện section + init chatbot (AN TOÀN) =====
function hideAllSections() {
document.querySelectorAll('#appMain .fade-in').forEach(el => { el.style.display = 'none'; });
}
function showSection(id, display = 'block') {
const el = document.getElementById(id);
if (el) el.style.display = display;
}
// Gắn event cho chatbot chỉ 1 lần, và chỉ khi phần tử tồn tại
function initChatbot() {
const sendBtn = document.getElementById('chatSend');
const input = document.getElementById('chatInput');
const win = document.getElementById('chatWindow');
if (!sendBtn || !input || !win) {
console.warn('[Chatbot] Thiếu phần tử UI (#chatSend | #chatInput | #chatWindow)');
return;
}
if (!sendBtn.dataset.bound) {
sendBtn.dataset.bound = '1';
sendBtn.addEventListener('click', sendChatSmart);
}
if (!input.dataset.bound) {
input.dataset.bound = '1';
input.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
e.preventDefault();
sendChatSmart();
}
});
}
}
// ==== Hiển thị nội dung theo mục được chọn ====
function chonMuc(muc) {
// Ẩn tất cả phần tử có class .fade-in
document.querySelectorAll('#appMain .fade-in').forEach(el => el.style.display = 'none');
// Hiển thị mục 'Chờ xử lý'
if (muc === "pycload") {
const stat = document.getElementById("pycload");
if (stat) stat.style.display = "flex";
hienThiDanhSachPYC();
}
// Hiển thị mục 'Đã hoàn thành'
if (muc === "pycend") {
const stat = document.getElementById("pycend");
if (stat) stat.style.display = "flex";
hienThiSoPYCHoanThanh();
}
if (muc === "pycdt") {
const stat = document.getElementById("pycdt");
if (stat) stat.style.display = "flex";
hienThiDoanhThuPYC();
}
if (muc === "pyc") {
const section = document.getElementById("pyc");
if (section) section.style.display = "block";
hienThiDanhSachPYCChuaHoanThanh();
}
if (muc === "dttong") {
const stat = document.getElementById("dttong");
if (stat) stat.style.display = "flex";
hienThiDoanhThuTong(); // <--- Hàm này phải được định nghĩa
}
if (muc === "dtthang") {
const stat = document.getElementById("dtthang");
if (stat) stat.style.display = "block";
hienThiDoanhThuTheoThang();
}
if (muc === "Nl") {
const section = document.getElementById("Nl");
if (section) section.style.display = "block";
}
if (muc === "dtdichvu") {
document.getElementById("dtdichvu").style.display = "block";
hienThiDoanhThuDichVu(); // Gọi API để hiển thị bảng
}
if (muc === "dtnoibo") {
document.getElementById("dtnoibo").style.display = "block";
hienThiDoanhThuNoiBo();
}
if (muc === "tailieu") {
const section = document.getElementById("tailieu");
if (section) {
section.style.display = "block";
taiDanhSachPDF();
hienThiPDF();// ✅ Gọi API lấy danh sách PDF
}
}
if (muc === "qt") {
const section = document.getElementById("qt");
if (section) {
section.style.display = "block";
taiDanhSachQuyTrinh();
hienThiQT();
}
}
if (muc === "dm") {
const section = document.getElementById("dm");
if (section) section.style.display = "block"; // ✅ hiện vùng hiển thị
fetch(`${BACKEND_URL}/danh_muc_thiet_bi`)
.then(res => {
if (!res.ok) throw new Error("Lỗi từ server: " + res.status);
return res.json();
})
.then(data => {
const table = $('#bangDanhMucThietBi');
table.empty();
if (!Array.isArray(data) || data.length === 0) {
table.html("
Không có dữ liệu để hiển thị.
");
return;
}
if (!$.fn.DataTable.isDataTable('#bangDanhMucThietBi')) {
table.DataTable({
data: data,
columns: Object.keys(data[0] || {}).map(key => ({ title: key, data: key })),
paging: true,
searching: true,
scrollX: true,
responsive: true,
autoWidth: false
});
} else {
const dt = table.DataTable();
dt.clear().rows.add(data).draw();
}
})
.catch(err => {
console.error("Lỗi khi tải danh mục thiết bị:", err);
$('#bangDanhMucThietBi').html("Không thể tải dữ liệu.
");
});
}
if (muc === "qlhc") {
const section = document.getElementById("qlhc");
if (section) {
section.style.display = "block";
hienThiHoaChat();
}
}
if (muc === "hsl") {
const section = document.getElementById("hsl");
if (section) section.style.display = "block";
hienThiHSKH();
}
if (muc === "taipyc") {
const section = document.getElementById("taipyc");
if (section) section.style.display = "block";
}
if (muc === "taobaogia") {
const section = document.getElementById("taobaogia");
if (section) section.style.display = "block";
}
if (muc === "banggia6") {
const section = document.getElementById("banggia6");
if (section) section.style.display = "block";
hienThiBangGia6();
}
if (muc === "banggia2") {
const section = document.getElementById("banggia2");
if (section) section.style.display = "block";
hienThiBangGia2();
}
if (muc === "banggia4") {
const section = document.getElementById("banggia4");
if (section) section.style.display = "block";
hienThiBangGia4();
}
if (muc === "banggia3") {
const section = document.getElementById("banggia3");
if (section) section.style.display = "block";
hienThiBangGia3();
}
if (muc === "banggia5") {
const section = document.getElementById("banggia5");
if (section) section.style.display = "block";
hienThiBangGia5();
}
if (muc === "taikemtheo") {
document.getElementById("taikemtheo").style.display = "block";
taiDanhSachThuMuc();
}
if (muc === 'chatbot') {
console.log("chonMuc('chatbot') được gọi");
showSection('chatbot'); // dùng helper
initChatbot(); // bảo đảm event đã gắn
document.getElementById('appMain')?.scrollIntoView({ behavior: 'smooth', block: 'start' });
return;
}
if (muc === "pycinc") {
const section = document.getElementById("pycinc");
if (section) section.style.display = "block";
refreshAndLoadPYCInc(); // gọi cập nhật và tải thống kê
}
}
async function hienThiDanhSachPYC() {
try {
const res = await fetch("/dem_pyc_tat_ca");
const data = await res.json();
console.log("DATA ĐẾM PYC:", data);
if (data.tong_so_pyc !== undefined) {
document.getElementById("pycCount").textContent = `${data.tong_so_pyc} phiếu`;
} else {
document.getElementById("pycCount").textContent = "Không xác định";
}
} catch (err) {
console.error("Lỗi khi gọi API PYC:", err);
document.getElementById("pycCount").textContent = "Lỗi";
}
}
async function hienThiSoPYCHoanThanh() {
try {
const res = await fetch(`${BACKEND_URL}/dem_pyc_hoan_thanh`);
const data = await res.json();
if (res.ok && data.tong_so_hoan_thanh !== undefined) {
document.getElementById("completedRequests").textContent = data.tong_so_hoan_thanh + " phiếu";
} else {
document.getElementById("completedRequests").textContent = "Không tải được";
}
} catch (err) {
console.error("Lỗi khi gọi API hoàn thành:", err);
document.getElementById("completedRequests").textContent = "Lỗi";
}
}
async function hienThiDoanhThuPYC() {
try {
const res = await fetch(`${BACKEND_URL}/tong_doanh_thu_pyc`);
const data = await res.json();
console.log("DATA DOANH THU:", data); // ✅ Debug console
if (res.ok && data.tong_doanh_thu !== undefined) {
const formatted = Number(data.tong_doanh_thu).toLocaleString("vi-VN") + " VND";
document.getElementById("requestRevenue").textContent = formatted;
} else {
document.getElementById("requestRevenue").textContent = "Không tải được";
}
} catch (err) {
console.error("Lỗi khi gọi API doanh thu:", err);
document.getElementById("requestRevenue").textContent = "Lỗi";
}
}
function enableSubmenuClick() {
document.querySelectorAll(".menu-item.has-sub").forEach(item => {
item.addEventListener("click", () => {
const id = item.getAttribute("data-submenu");
const submenu = document.getElementById(id);
const arrow = document.getElementById("arrow-" + id);
if (submenu.style.display === "block") {
submenu.style.display = "none";
arrow.innerHTML = "►";
} else {
submenu.style.display = "block";
arrow.innerHTML = "▼";
}
});
});
}
async function hienThiDanhSachPYCChuaHoanThanh() {
const container = document.getElementById("pycIncompleteList");
container.innerHTML = "Đang tải dữ liệu...";
try {
const res = await fetch(`${BACKEND_URL}/pyc_chua_hoan_thanh`);
const data = await res.json();
if (!Array.isArray(data) || data.length === 0) {
container.innerHTML = "Không có dữ liệu.";
return;
}
let html = "";
for (let key in data[0]) {
html += `${key} `;
}
html += " ";
for (let row of data) {
html += "";
for (let key in row) {
html += `${row[key]} `;
}
html += " ";
}
html += "
";
container.innerHTML = html;
$(document).ready(function () {
$('#tablePYCIncomplete').DataTable();
});
} catch (err) {
console.error("Lỗi khi tải bảng phiếu chưa hoàn thành:", err);
container.innerHTML = "Lỗi khi tải dữ liệu.";
}
}
async function hienThiDoanhThuTong() {
try {
const res = await fetch(`${BACKEND_URL}/doanh_thu_tong`);
const data = await res.json();
if (res.ok && data.tong_doanh_thu !== undefined) {
const formatted = Number(data.tong_doanh_thu).toLocaleString("vi-VN") + " VND";
document.getElementById("tongDoanhThu").textContent = formatted;
} else {
document.getElementById("tongDoanhThu").textContent = "Không tải được";
}
} catch (err) {
console.error("Lỗi khi gọi API doanh thu tổng:", err);
document.getElementById("tongDoanhThu").textContent = "Lỗi";
}
}
async function hienThiDoanhThuTheoThang() {
const ctx = document.getElementById("chartDoanhThuThang").getContext("2d");
try {
const res = await fetch(`${BACKEND_URL}/doanh_thu_theo_thang`);
const data = await res.json();
if (!res.ok || !data || !Array.isArray(data.thang) || !Array.isArray(data.doanh_thu)) {
throw new Error("Dữ liệu không hợp lệ");
}
// Xóa biểu đồ cũ nếu đã có
if (window.doanhThuChart) {
window.doanhThuChart.destroy();
}
// Vẽ biểu đồ cột
window.doanhThuChart = new Chart(ctx, {
type: "bar",
data: {
labels: data.thang,
datasets: [{
label: "Doanh thu (VND)",
data: data.doanh_thu,
backgroundColor: "rgba(54, 162, 235, 0.6)",
borderColor: "rgba(54, 162, 235, 1)",
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true,
ticks: {
callback: function(value) {
return value.toLocaleString("vi-VN") + " VND";
}
}
}
},
plugins: {
legend: {
display: false
},
tooltip: {
callbacks: {
label: function(context) {
return context.raw.toLocaleString("vi-VN") + " VND";
}
}
}
}
}
});
} catch (err) {
console.error("Lỗi khi gọi API doanh thu theo tháng:", err);
document.getElementById("chartDoanhThuThang").outerHTML = "Lỗi khi tải biểu đồ.
";
}
}
async function hienThiDoanhThuDichVu() {
try {
const res = await fetch("/doanh_thu_dich_vu");
const result = await res.json();
console.log("📊 Kết quả từ API doanh_thu_dich_vu:", result);
if (!result || result.error) {
document.querySelector("#anhDoanhThuDichVu").alt = "Lỗi khi tải biểu đồ.";
$('#bangDoanhThuDichVu').html("Không thể tải dữ liệu.
");
return;
}
const data = result.data || [];
const imageBase64 = result.image_base64;
// Hiển thị ảnh biểu đồ
const imgElement = document.querySelector("#anhDoanhThuDichVu");
if (imageBase64) {
imgElement.src = `data:image/png;base64,${imageBase64}`;
imgElement.alt = "Biểu đồ doanh thu dịch vụ";
} else {
imgElement.alt = "Không có ảnh biểu đồ.";
}
// Hiển thị bảng dữ liệu
const table = $('#bangDoanhThuDichVu');
if ($.fn.dataTable.isDataTable('#bangDoanhThuDichVu')) {
table.DataTable().clear().rows.add(data).draw();
} else {
table.DataTable({
data: data,
columns: [
{ title: "Dịch vụ", data: "Dịch vụ" },
{ title: "Số lượng", data: "Số lượng" },
{ title: "Tỷ lệ (%)", data: "Tỷ lệ (%)" },
{
title: "Tổng doanh thu",
data: "Tổng doanh thu",
render: function (data, type, row) {
if (type === 'display' && typeof data === 'number') {
return data.toLocaleString('vi-VN') + " ₫";
}
return data;
}
}
],
paging: false,
searching: false,
info: false
});
}
} catch (error) {
console.error("❌ Lỗi khi tải dữ liệu doanh thu dịch vụ:", error);
document.querySelector("#anhDoanhThuDichVu").alt = "Lỗi kết nối tới API.";
$('#bangDoanhThuDichVu').html("Lỗi kết nối tới máy chủ.
");
}
}
async function hienThiDoanhThuNoiBo() {
try {
const res = await fetch(`${BACKEND_URL}/doanh_thu_noi_bo`);
const result = await res.json();
console.log("📊 Kết quả doanh thu nội bộ:", result);
const data = result.data || [];
const tong = result.tong || {};
// Hiển thị bảng
const table = $('#bangDoanhThuNoiBo');
if ($.fn.dataTable.isDataTable('#bangDoanhThuNoiBo')) {
table.DataTable().clear().rows.add(data).draw();
} else {
table.DataTable({
data: data,
columns: [
{ title: "Phòng", data: "Phòng" },
{
title: "Chuyển đến",
data: "Chuyển đến",
render: function (data) {
return typeof data === 'number' ? data.toLocaleString('vi-VN') + " ₫" : "-";
}
},
{
title: "Chuyển đi",
data: "Chuyển đi",
render: function (data) {
return typeof data === 'number' ? data.toLocaleString('vi-VN') + " ₫" : "-";
}
}
],
paging: false,
searching: false,
info: false
});
}
// Hiển thị tổng
const cdStr = typeof tong["Tổng chuyển đến"] === 'number' ? tong["Tổng chuyển đến"].toLocaleString('vi-VN') + " ₫" : "-";
const diStr = typeof tong["Tổng chuyển đi"] === 'number' ? tong["Tổng chuyển đi"].toLocaleString('vi-VN') + " ₫" : "-";
document.getElementById("tongDoanhThuNoiBo").innerHTML = `
Tổng chuyển đến: ${cdStr}
Tổng chuyển đi: ${diStr}
`;
} catch (error) {
console.error("❌ Lỗi khi tải doanh thu nội bộ:", error);
document.getElementById("tongDoanhThuNoiBo").innerHTML = "Không thể tải dữ liệu nội bộ.
";
}
}
// Gọi API lấy danh sách PDF từ backend
async function taiDanhSachPDF() {
try {
const res = await fetch(`${BACKEND_URL}/danh_sach_pdf`);
const data = await res.json();
const select = document.getElementById("selectPdf");
select.innerHTML = '-- Chọn tài liệu để xem -- ';
data.pdfs.forEach(file => {
const option = document.createElement("option");
option.value = file;
option.textContent = file;
select.appendChild(option);
});
} catch (err) {
console.error("Không thể tải danh sách PDF:", err);
}
}
// Xử lý hiển thị PDF khi chọn trong dropdown
function hienThiPDF() {
const select = document.getElementById("selectPdf");
const fileName = select.value;
const viewer = document.getElementById("pdfViewer");
const iframe = document.getElementById("pdfFrame");
const download = document.getElementById("pdfDownload");
if (!fileName) {
viewer.style.display = "none";
return;
}
const pdfUrl = `${BACKEND_URL}/xem_pdf?file_name=${encodeURIComponent(fileName)}`;
iframe.src = pdfUrl;
download.href = pdfUrl;
viewer.style.display = "block";
}
async function taiDanhSachQuyTrinh() {
try {
const res = await fetch(`${BACKEND_URL}/quy_trinh`);
const data = await res.json();
const select = document.getElementById("selectQT");
select.innerHTML = `-- Chọn tài liệu -- `;
data.pdfs.forEach(item => {
let fileName, filePath;
if (typeof item === "string") {
fileName = item;
filePath = `Quy_trinh/${item}`;
} else {
fileName = item.name;
filePath = item.path;
}
const option = document.createElement("option");
option.value = filePath;
option.textContent = fileName;
select.appendChild(option);
});
} catch (error) {
console.error("Lỗi khi tải danh sách quy trình:", error);
alert("Không thể tải danh sách quy trình.");
}
}
function hienThiQT() {
const file = document.getElementById("selectQT").value;
const iframe = document.getElementById("qtFrame");
const viewer = document.getElementById("qtViewer");
const download = document.getElementById("qtDownload");
if (file) {
const ext = file.toLowerCase().split('.').pop();
const url = `${BACKEND_URL}/xem_pdf?file=${encodeURIComponent(file)}`;
if (ext === "pdf") {
iframe.src = url;
iframe.style.display = "block";
} else {
iframe.src = "";
iframe.style.display = "none";
alert("Không hỗ trợ xem trực tiếp định dạng này. Vui lòng tải về.");
}
download.href = url + "&download=true";
viewer.style.display = "block";
} else {
viewer.style.display = "none";
}
}
function parseNgayVN(ngayStr) {
if (!ngayStr || typeof ngayStr !== 'string') return null;
ngayStr = ngayStr.trim().split(" ")[0];
if (/^\d{4}-\d{2}-\d{2}$/.test(ngayStr)) return new Date(ngayStr);
const parts = ngayStr.split(/\/|-/);
if (parts.length === 3) {
let [d, m, y] = parts;
if (y.length === 2) y = '20' + y;
return new Date(`${y}-${m.padStart(2, '0')}-${d.padStart(2, '0')}`);
}
return null;
}
async function hienThiHoaChat() {
try {
const res = await fetch("/quan_ly_hoa_chat");
if (!res.ok) throw new Error("Không thể tải dữ liệu hóa chất");
const data = await res.json();
const columns = data.columns;
const rows = data.rows;
const idxHanSD = columns.findIndex(c => c.toUpperCase().includes("HẠN"));
const idxTinhTrang = columns.findIndex(c => c.toUpperCase().includes("TÌNH TRẠNG"));
const table = document.getElementById("bangHoaChat");
table.innerHTML = "";
const thead = table.createTHead();
const headerRow = thead.insertRow();
columns.forEach(col => {
const th = document.createElement("th");
th.textContent = col;
th.style.background = "#f2f2f2";
th.style.padding = "8px";
th.style.border = "1px solid #ccc";
headerRow.appendChild(th);
});
const tbody = table.createTBody();
rows.forEach(row => {
const tr = tbody.insertRow();
let backgroundColor = "";
row.forEach((cell, colIndex) => {
const td = tr.insertCell();
const input = document.createElement("input");
input.type = "text";
input.value = cell;
input.classList.add("input-cell");
input.style.width = "100%";
if (colIndex === idxTinhTrang) {
input.readOnly = true;
input.style.fontWeight = "bold";
const hanSD = parseNgayVN(row[idxHanSD]);
let color = "black";
if (cell && cell.toString().startsWith("CÒN")) {
const match = cell.match(/(\d+)/);
if (match) {
const days = parseInt(match[1]);
if (days < 0) {
backgroundColor = "#f8d7da"; input.style.color = "red";
} else if (days <= 160) {
backgroundColor = "#fff3cd"; input.style.color = "orange";
} else {
backgroundColor = "#d4edda"; input.style.color = "green";
}
}
} else {
if (hanSD instanceof Date && !isNaN(hanSD)) {
const today = new Date();
const diffDays = Math.ceil((hanSD - today) / (1000 * 3600 * 24));
if (diffDays < 0) {
input.value = "HẾT HẠN"; input.style.color = "red"; backgroundColor = "#f8d7da";
} else if (diffDays <= 160) {
input.value = `CÒN: ${diffDays} ngày`; input.style.color = "orange"; backgroundColor = "#fff3cd";
} else {
input.value = `CÒN: ${diffDays} ngày`; input.style.color = "green"; backgroundColor = "#d4edda";
}
}
}
}
td.appendChild(input);
});
if (backgroundColor) tr.style.backgroundColor = backgroundColor;
});
document.getElementById("nutLuuHoaChat").style.display = "block";
const btnExport = document.getElementById("nutTrichXuat160");
btnExport.style.display = "inline-block";
// === ✅ Trích xuất XLSX có màu
btnExport.onclick = function () {
const wb = XLSX.utils.book_new();
const wsData = [columns];
const wsStyles = [];
let soDongCanhBao = 0;
rows.forEach(row => {
const hanSD = parseNgayVN(row[idxHanSD]);
const tinhTrang = row[idxTinhTrang] || "";
if (
hanSD instanceof Date &&
!isNaN(hanSD) &&
!tinhTrang.toString().startsWith("CÒN")
) {
const today = new Date();
const diffDays = Math.ceil((hanSD - today) / (1000 * 3600 * 24));
if (diffDays <= 160) {
const rowData = row.map(cell => (cell || "").toString().replace(/[\n\r]+/g, " ").trim());
wsData.push(rowData);
soDongCanhBao++;
let fillColor = diffDays < 0 ? 'FFFFCCCC' : 'FFFFFF99';
wsStyles.push({ fillColor });
}
}
});
if (soDongCanhBao === 0) {
alert("✅ Không có hóa chất nào cần cảnh báo mới (≤160 ngày và chưa cảnh báo).");
return;
}
const ws = XLSX.utils.aoa_to_sheet(wsData);
wsStyles.forEach((style, i) => {
const rowIndex = i + 1;
columns.forEach((_, colIndex) => {
const addr = XLSX.utils.encode_cell({ r: rowIndex, c: colIndex });
if (!ws[addr]) return;
ws[addr].s = {
fill: {
patternType: "solid",
fgColor: { rgb: style.fillColor }
}
};
});
});
XLSX.utils.book_append_sheet(wb, ws, "Cảnh báo hóa chất");
const now = new Date();
const fileName = `hoa_chat_canh_bao_${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()}.xlsx`;
XLSX.writeFile(wb, fileName);
};
} catch (err) {
console.error("Lỗi khi tải danh mục hóa chất:", err);
alert("❌ Không thể tải dữ liệu hóa chất.");
}
}
// ==== Lưu dữ liệu đã chỉnh sửa ====
async function luuHoaChat() {
const table = document.getElementById("bangHoaChat");
if (!table) return;
const headers = Array.from(table.querySelectorAll("thead th")).map(th => th.textContent.trim());
const data = [];
table.querySelectorAll("tbody tr").forEach(tr => {
const row = Array.from(tr.querySelectorAll("td input")).map(input => input.value.trim());
if (row.length === headers.length) {
data.push(row);
}
});
console.log("🧪 Gửi:", { columns: headers, data: data });
try {
const res = await fetch(`${BACKEND_URL}/cap_nhat_hoa_chat`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ columns: headers, data: data })
});
const result = await res.json();
alert(result.message || "✅ Đã lưu dữ liệu thành công!");
} catch (err) {
console.error("❌ Lỗi khi lưu hóa chất:", err);
alert("❌ Không thể lưu dữ liệu.");
}
}
// Gọi API hiển thị HSKH
async function hienThiHSKH() {
try {
const response = await fetch(`${BACKEND_URL}/hien_thi_hskh`);
const data = await response.json();
if (!data || !data.rows || data.rows.length === 0) {
console.warn("Không có dữ liệu HSKH.");
return;
}
const fullIndex = data.columns.indexOf("Full");
const danhSachNguoiTiepNhan = [
"Lê Danh Huy",
"Trần Văn Dương",
"Nguyễn Mạnh Cường",
"Nguyễn Ngọc Vinh",
"Lê Thu Thảo"
];
const danhSachPhongYeuCau = ["ĐL1", "ĐL2", "ĐL3", "ĐL4", "ĐL5", "QA"];
if ($.fn.DataTable.isDataTable("#bangHSKH")) {
$('#bangHSKH').DataTable().clear().destroy();
}
let tbodyHtml = "";
data.rows.forEach((row, index) => {
const isFullChecked = (row[fullIndex] || "").toLowerCase() === "x";
const rowClass = isFullChecked ? "full-row" : "not-full-row";
tbodyHtml += ``;
// ✅ TT = index + 1
tbodyHtml += `${index + 1} `;
// ✅ Số PYC = 25/ĐL6/ + (index + 1).padStart(4, '0')
const soPYC = `25/ĐL6/${(index + 1).toString().padStart(4, "0")}`;
tbodyHtml += `${soPYC} `;
for (let j = 2; j < data.columns.length; j++) { // bắt đầu từ cột 3
const col = data.columns[j];
const cell = (row[j] != null) ? row[j] : "";
if (["Full", "PYC", "BB", "GCN"].includes(col)) {
const checked = cell.toString().toLowerCase() === "x" ? "checked" : "";
let className = "";
if (col === "Full") className = "checkbox-full";
if (col === "PYC") className = "checkbox-pyc";
if (col === "BB") className = "checkbox-bb";
if (col === "GCN") className = "checkbox-gcn";
tbodyHtml += ` `;
} else if (col === "Tên Khách hàng" || col === "Tên Cơ sở sử dụng") {
tbodyHtml += ` `;
} else if (col === "Người tiếp nhận") {
tbodyHtml += ``;
tbodyHtml += `--chọn-- `;
danhSachNguoiTiepNhan.forEach(name => {
const selected = name === cell ? "selected" : "";
tbodyHtml += `${name} `;
});
tbodyHtml += ` `;
} else if (col === "Phòng yêu cầu") {
tbodyHtml += ``;
tbodyHtml += `--chọn-- `;
danhSachPhongYeuCau.forEach(phong => {
const selected = phong === cell ? "selected" : "";
tbodyHtml += `${phong} `;
});
tbodyHtml += ` `;
} else {
tbodyHtml += ` `;
}
}
tbodyHtml += ` `;
});
$("#bangHSKH tbody").html(tbodyHtml);
$("#bangHSKH").DataTable({
scrollX: true,
autoWidth: false,
pageLength: data.rows.length,
lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "Tất cả"]],
ordering: false,
language: {
search: "🔍 Tìm kiếm:",
lengthMenu: "Hiển thị _MENU_ dòng",
info: "Đang hiển thị _START_ đến _END_ của _TOTAL_ dòng",
paginate: {
previous: "←",
next: "→"
},
emptyTable: "Không có dữ liệu"
},
columnDefs: [
{ targets: "_all", className: "dt-center" }
]
});
$("#bangHSKH tbody").on("input", "input, textarea, select", function () {
const lastRow = $("#bangHSKH tbody tr:visible").last();
let isEmpty = true;
lastRow.find("input[type='text'], textarea, select").each(function () {
const val = $(this).val();
if (val && val.trim() !== "" && val !== "--chọn--") {
isEmpty = false;
}
});
if (!isEmpty) {
const newRow = lastRow.clone();
const nextTT = $("#bangHSKH tbody tr").length + 1;
const newPYC = `25/ĐL6/${nextTT.toString().padStart(4, "0")}`;
newRow.find("td").eq(0).text(nextTT);
newRow.find("td").eq(1).text(newPYC);
newRow.find("input[type='text'], textarea").val("");
newRow.find("select").val("");
newRow.find("input[type='checkbox']").prop("checked", false);
newRow.removeClass("full-row not-full-row");
$("#bangHSKH tbody").append(newRow);
}
});
function capNhatMauDong() {
$("#bangHSKH tbody tr").each(function () {
const checkbox = $(this).find("input.checkbox-full");
if (checkbox.prop("checked")) {
$(this).removeClass("not-full-row").addClass("full-row");
} else {
$(this).removeClass("full-row").addClass("not-full-row");
}
});
}
capNhatMauDong();
$('#bangHSKH').on('draw.dt', function () {
$('#bangHSKH').css('table-layout', 'auto');
$("#bangHSKH").off("change", "input.checkbox-full")
.on("change", "input.checkbox-full", function () {
const row = $(this).closest("tr");
const isChecked = $(this).is(":checked");
row.find(".checkbox-pyc").prop("checked", isChecked);
row.find(".checkbox-bb").prop("checked", isChecked);
row.find(".checkbox-gcn").prop("checked", isChecked);
capNhatMauDong();
});
});
$("#bangHSKH").off("change", "input.checkbox-full")
.on("change", "input.checkbox-full", function () {
const row = $(this).closest("tr");
const isChecked = $(this).is(":checked");
row.find(".checkbox-pyc").prop("checked", isChecked);
row.find(".checkbox-bb").prop("checked", isChecked);
row.find(".checkbox-gcn").prop("checked", isChecked);
capNhatMauDong();
});
document.getElementById("nutLuuHSKH").style.display = "inline-block";
} catch (error) {
console.error("Lỗi khi tải dữ liệu HSKH:", error);
alert("Không thể tải dữ liệu hồ sơ lưu.");
}
}
async function luuHSKH() {
try {
const headers = [];
$("#bangHSKH thead tr:last-child th").each(function () {
headers.push($(this).text().trim());
});
const topHeaders = $("#bangHSKH thead tr:first-child th[rowspan='2']");
topHeaders.each(function (index) {
headers.splice(index, 0, $(this).text().trim());
});
const rows = [];
$("#bangHSKH tbody tr").each(function () {
const row = [];
let isEmptyRow = true;
$(this).find("td").each(function () {
const input = $(this).find("input, textarea, select");
if (input.length > 0) {
if (input.attr("type") === "checkbox") {
const checked = input.prop("checked") ? "x" : "";
row.push(checked);
if (checked !== "") isEmptyRow = false;
} else {
const val = input.val()?.trim() || "";
row.push(val);
if (val !== "") isEmptyRow = false;
}
} else {
const text = $(this).text().trim();
row.push(text);
if (text !== "") isEmptyRow = false;
}
});
if (!isEmptyRow) {
rows.push(row); // ✅ Chỉ thêm nếu dòng này có nội dung
}
});
// ✅ Kiểm tra có dữ liệu để lưu không
if (rows.length === 0) {
alert("⚠️ Không có dữ liệu hợp lệ để lưu!");
return;
}
// ✅ Gửi dữ liệu
const response = await fetch(`${BACKEND_URL}/cap_nhat_hskh`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
columns: headers,
rows: rows
})
});
if (response.ok) {
alert("✅ Dữ liệu đã được lưu thành công!");
} else {
const err = await response.json();
alert("❌ Lỗi khi lưu: " + err.detail);
}
} catch (error) {
console.error("Lỗi khi gửi dữ liệu:", error);
alert("❌ Không thể gửi dữ liệu để lưu.");
}
}
// ==== Xử lý sự kiện tải phiếu yêu cầu ====
document.getElementById("formUploadPYC").addEventListener("submit", async function(e) {
e.preventDefault();
const fileInput = document.getElementById("filePYC");
const file = fileInput.files[0];
if (!file) return alert("Vui lòng chọn file PYC");
const formData = new FormData();
formData.append("file", file);
try {
const res = await fetch(`${BACKEND_URL}/upload_pyc`, {
method: "POST",
body: formData
});
const data = await res.json();
document.getElementById("uploadStatus").innerText = data.message || "Tải thành công!";
} catch (err) {
document.getElementById("uploadStatus").innerText = "Tải lên thất bại!";
console.error(err);
}
});
document.getElementById("formBaoGia").addEventListener("submit", async function (e) {
e.preventDefault();
const tenKhachHang = document.getElementById("tenKhachHang").value;
const bangGia = document.getElementById("nhomBangGia").value;
const thietBiText = document.getElementById("dsThietBi").value;
const ds = thietBiText.split("\n").map(d => {
const parts = d.split(" - ");
return {
Ten_thiet_bi: parts[0]?.trim(),
So_luong: parseFloat(parts[1] || 1),
Don_gia: parseFloat(parts[2] || 0)
};
}).filter(d => d.Ten_thiet_bi && !isNaN(d.So_luong) && !isNaN(d.Don_gia));
if (ds.length === 0) {
alert("Không có thiết bị hợp lệ.");
return;
}
try {
const res = await fetch(`${BACKEND_URL}/tao_baogia_tu_banggia`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
ten_khach: tenKhachHang,
bang_gia_filename: bangGia,
ds_thiet_bi: ds
})
});
const data = await res.json();
document.getElementById("baoGiaStatus").innerText = data.message || "Tạo báo giá thành công!";
} catch (err) {
document.getElementById("baoGiaStatus").innerText = "Lỗi tạo báo giá!";
console.error(err);
}
});
async function hienThiBangGia6() {
try {
const response = await fetch(`${BACKEND_URL}/bang_gia_hoaly`);
const data = await response.json();
if (!data || !data.rows || data.rows.length === 0) {
$("#tableBangGia6 tbody").html("Không có dữ liệu ");
return;
}
// Hiển thị tiêu đề
let theadHtml = "";
data.columns.forEach(col => {
theadHtml += `${col} `;
});
theadHtml += " ";
$("#tableBangGia6 thead").html(theadHtml);
// Hiển thị dữ liệu
let tbodyHtml = "";
data.rows.forEach(row => {
tbodyHtml += "";
row.forEach(cell => {
// Nếu là số, định dạng theo nhóm 3 số
if (!isNaN(cell) && cell !== "") {
const formatted = Number(cell).toLocaleString("vi-VN");
tbodyHtml += `${formatted} `;
} else {
tbodyHtml += `${cell} `;
}
});
tbodyHtml += " ";
});
$("#tableBangGia6 tbody").html(tbodyHtml);
// Tạo bảng DataTable
const table = $("#tableBangGia6").DataTable({
destroy: true,
scrollX: true,
autoWidth: false,
pageLength: 25,
deferRender: true, // ✅ Tăng hiệu năng
scrollCollapse: true, // ✅ Đảm bảo co chiều cao đúng
language: {
search: "🔍 Tìm kiếm:",
lengthMenu: "Hiển thị _MENU_ dòng",
info: "Đang hiển thị _START_ đến _END_ của _TOTAL_ dòng",
paginate: { previous: "←", next: "→" },
emptyTable: "Không có dữ liệu"
}
});
// ✅ Căn chỉnh lại cột sau khi vẽ xong
setTimeout(() => {
table.columns.adjust().draw(false);
}, 100);
// Ẩn các mục khác, chỉ hiện mục này
$(".fade-in").hide();
$("#banggia6").show();
} catch (err) {
console.error("Lỗi khi tải bảng giá hóa lý:", err);
alert("Không thể tải bảng giá hóa lý.");
}
}
async function hienThiBangGia2() {
try {
const response = await fetch(`${BACKEND_URL}/bang_gia_dien`);
const data = await response.json();
if (!data || !data.rows || data.rows.length === 0) {
$("#tableBangGia2 tbody").html("Không có dữ liệu ");
return;
}
// Tạo tiêu đề
let theadHtml = "";
data.columns.forEach(col => {
theadHtml += `${col} `;
});
theadHtml += " ";
$("#tableBangGia2 thead").html(theadHtml);
// Tạo dữ liệu
let tbodyHtml = "";
data.rows.forEach(row => {
tbodyHtml += "";
row.forEach((cell, i) => {
const columnName = data.columns[i];
if (columnName.toLowerCase().includes("đơn giá") && !isNaN(cell)) {
tbodyHtml += `${Number(cell).toLocaleString("vi-VN")} `;
} else if (columnName.toLowerCase().includes("tên thiết bị")) {
tbodyHtml += `${cell} `;
} else {
tbodyHtml += `${cell} `;
}
});
tbodyHtml += " ";
});
$("#tableBangGia2 tbody").html(tbodyHtml);
const table = $("#tableBangGia2").DataTable({
destroy: true,
scrollX: true,
autoWidth: false,
pageLength: 25,
language: {
search: "🔍 Tìm kiếm:",
lengthMenu: "Hiển thị _MENU_ dòng",
info: "Đang hiển thị _START_ đến _END_ của _TOTAL_ dòng",
paginate: { previous: "←", next: "→" },
emptyTable: "Không có dữ liệu"
}
});
setTimeout(() => {
table.columns.adjust().draw(false);
}, 100);
$(".fade-in").hide();
$("#banggia2").show();
} catch (err) {
console.error("Lỗi khi tải bảng giá điện:", err);
alert("Không thể tải bảng giá điện.");
}
}
async function hienThiBangGia4() {
try {
const response = await fetch(`${BACKEND_URL}/bang_gia_nhiet_yte`);
const data = await response.json();
if (!data || !data.rows || data.rows.length === 0) {
$("#tableBangGia4 tbody").html("Không có dữ liệu ");
return;
}
let theadHtml = "";
data.columns.forEach(col => {
theadHtml += `${col} `;
});
theadHtml += " ";
$("#tableBangGia4 thead").html(theadHtml);
let tbodyHtml = "";
data.rows.forEach(row => {
tbodyHtml += "";
row.forEach((cell, i) => {
const columnName = data.columns[i];
if (columnName.toLowerCase().includes("giá") && !isNaN(cell)) {
tbodyHtml += `${Number(cell).toLocaleString("vi-VN")} `;
} else if (columnName.toLowerCase().includes("tên") || columnName.toLowerCase().includes("thiết bị")) {
tbodyHtml += `${cell} `;
} else {
tbodyHtml += `${cell} `;
}
});
tbodyHtml += " ";
});
$("#tableBangGia4 tbody").html(tbodyHtml);
const table = $("#tableBangGia4").DataTable({
destroy: true,
scrollX: true,
autoWidth: false,
pageLength: 25,
language: {
search: "🔍 Tìm kiếm:",
lengthMenu: "Hiển thị _MENU_ dòng",
info: "Đang hiển thị _START_ đến _END_ của _TOTAL_ dòng",
paginate: { previous: "←", next: "→" },
emptyTable: "Không có dữ liệu"
}
});
setTimeout(() => {
table.columns.adjust().draw(false);
}, 100);
$(".fade-in").hide();
$("#banggia4").show();
} catch (err) {
console.error("Lỗi khi tải bảng giá:", err);
alert("Không thể tải bảng giá Nhiệt & Y tế.");
}
}
async function hienThiBangGia3() {
try {
const response = await fetch(`${BACKEND_URL}/bang_gia_co_doday_apsuat`);
const data = await response.json();
if (!data || !data.rows || data.rows.length === 0) {
$("#tableBangGia3 tbody").html("Không có dữ liệu ");
return;
}
let theadHtml = "";
data.columns.forEach(col => {
theadHtml += `${col} `;
});
theadHtml += " ";
$("#tableBangGia3 thead").html(theadHtml);
let tbodyHtml = "";
data.rows.forEach(row => {
tbodyHtml += "";
row.forEach((cell, i) => {
const columnName = data.columns[i];
if (columnName.toLowerCase().includes("giá") && !isNaN(cell)) {
tbodyHtml += `${Number(cell).toLocaleString("vi-VN")} `;
} else if (columnName.toLowerCase().includes("tên") || columnName.toLowerCase().includes("thiết bị")) {
tbodyHtml += `${cell} `;
} else {
tbodyHtml += `${cell} `;
}
});
tbodyHtml += " ";
});
$("#tableBangGia3 tbody").html(tbodyHtml);
const table = $("#tableBangGia3").DataTable({
destroy: true,
scrollX: true,
autoWidth: false,
pageLength: 25,
language: {
search: "🔍 Tìm kiếm:",
lengthMenu: "Hiển thị _MENU_ dòng",
info: "Đang hiển thị _START_ đến _END_ của _TOTAL_ dòng",
paginate: { previous: "←", next: "→" },
emptyTable: "Không có dữ liệu"
}
});
setTimeout(() => {
table.columns.adjust().draw(false);
}, 100);
$(".fade-in").hide();
$("#banggia3").show();
} catch (err) {
console.error("Lỗi khi tải bảng giá:", err);
alert("Không thể tải bảng giá Cơ – Độ dài – Áp suất.");
}
}
document.getElementById("formUploadKemTheo").addEventListener("submit", async function (e) {
e.preventDefault();
const form = document.getElementById("formUploadKemTheo");
const formData = new FormData(form); // ✅ Tự động lấy đúng theo `name=`
try {
const response = await fetch(`${BACKEND_URL}/upload_kemtheo`, {
method: "POST",
body: formData
});
const result = await response.json();
if (response.ok) {
alert("✅ Tải lên thành công!");
form.reset();
} else {
alert("❌ Lỗi: " + result.message);
}
} catch (error) {
alert("❌ Lỗi khi gửi yêu cầu: " + error.message);
}
});
async function taiDanhSachThuMuc() {
try {
const response = await fetch(`${BACKEND_URL}/thu_muc_khach_hang`);
const thuMucs = await response.json();
const select = document.getElementById("thuMucKhachHang");
select.innerHTML = ""; // Xoá cũ
thuMucs.forEach(name => {
const option = document.createElement("option");
option.value = name;
option.textContent = name;
select.appendChild(option);
});
} catch (error) {
console.error("Lỗi khi tải thư mục khách hàng:", error);
}
}
async function hienThiBangGia5() {
try {
const response = await fetch(`${BACKEND_URL}/bang_gia_dungtich_luuluong`);
const data = await response.json();
if (!data || !data.rows || data.rows.length === 0) {
$("#tableBangGia5 tbody").html("Không có dữ liệu ");
return;
}
// Header
let theadHtml = "";
data.columns.forEach(col => {
theadHtml += `${col} `;
});
theadHtml += " ";
$("#tableBangGia5 thead").html(theadHtml);
// Body
let tbodyHtml = "";
data.rows.forEach(row => {
tbodyHtml += "";
row.forEach((cell, i) => {
const colName = data.columns[i];
if (colName.toLowerCase().includes("giá") && !isNaN(cell)) {
tbodyHtml += `${Number(cell).toLocaleString("vi-VN")} `;
} else if (colName.toLowerCase().includes("tên") || colName.toLowerCase().includes("thiết bị")) {
tbodyHtml += `${cell} `;
} else {
tbodyHtml += `${cell} `;
}
});
tbodyHtml += " ";
});
$("#tableBangGia5 tbody").html(tbodyHtml);
const table = $("#tableBangGia5").DataTable({
destroy: true,
scrollX: true,
autoWidth: false,
pageLength: 25,
language: {
search: "🔍 Tìm kiếm:",
lengthMenu: "Hiển thị _MENU_ dòng",
info: "Đang hiển thị _START_ đến _END_ của _TOTAL_ dòng",
paginate: { previous: "←", next: "→" },
emptyTable: "Không có dữ liệu"
}
});
setTimeout(() => {
table.columns.adjust().draw(false);
}, 100);
$(".fade-in").hide();
$("#banggia5").show();
} catch (err) {
console.error("Lỗi khi tải bảng giá 5:", err);
alert("Không thể tải bảng giá Dung tích – Lưu lượng.");
}
}
// === Toggle sidebar mobile ===
document.getElementById("btnMenu")?.addEventListener("click", () => {
const sb = document.querySelector(".sidebar");
sb.classList.toggle("open");
document.body.classList.toggle("menu-open", sb.classList.contains("open"));
});
// Tự đóng menu sau khi chọn một mục
document.querySelectorAll(".submenu a").forEach(a => {
a.addEventListener("click", () => {
const sb = document.querySelector(".sidebar");
if (sb.classList.contains("open")) {
sb.classList.remove("open");
document.body.classList.remove("menu-open");
}
});
});
// ===== Chatbot client =====
const CHAT_HISTORY = [];
let sendingChat = false;
function appendBubble(text, role = "user"){
const wrap = document.getElementById("chatWindow");
if (!wrap) return;
const bubble = document.createElement("div");
bubble.className = `chat-bubble ${role}`;
bubble.textContent = text;
wrap.appendChild(bubble);
wrap.scrollTop = wrap.scrollHeight;
return bubble;
}
function appendSources(sources){
if (!sources || !sources.length) return;
const wrap = document.getElementById("chatWindow");
if (!wrap) return;
const meta = document.createElement("div");
meta.className = "chat-meta";
meta.textContent = "Nguồn:\n" + sources.map(s => "• " + s).join("\n");
wrap.appendChild(meta);
wrap.scrollTop = wrap.scrollHeight;
}
async function sendChatSmart(){
if (sendingChat) return;
const ip = document.getElementById("chatInput");
const btn = document.getElementById("chatSend");
if (!ip || !btn) return;
const text = (ip.value || "").trim();
if (!text) return;
sendingChat = true; btn.disabled = true;
appendBubble(text, "user");
CHAT_HISTORY.push({ role: "user", content: text });
ip.value = "";
const thinking = appendBubble("...", "bot");
try{
const r = await fetch(`${BACKEND_URL}/chat_smart`, {
method: "POST",
headers: { "Content-Type":"application/json" },
body: JSON.stringify({ message: text, history: CHAT_HISTORY })
});
const data = await r.json();
const intent = data.intent || "general";
const reply = data.reply || "Xin lỗi, mình chưa trả lời được.";
if (thinking) thinking.textContent = `[${intent}] ${reply}`;
appendSources(data.sources);
CHAT_HISTORY.push({ role: "assistant", content: reply });
}catch(err){
console.error("Chatbot error:", err);
if (thinking) thinking.textContent = "Lỗi kết nối backend.";
}finally{
sendingChat = false; btn.disabled = false;
}
}
// Gắn event sau khi DOM sẵn sàng (có kiểm tra phần tử)
// Chạy sau khi DOM sẵn sàng
document.addEventListener('DOMContentLoaded', () => {
// Gắn event chatbot nếu phần tử tồn tại
const sendBtn = document.getElementById('chatSend');
const input = document.getElementById('chatInput');
if (sendBtn && !sendBtn.dataset.bound) {
sendBtn.dataset.bound = '1';
sendBtn.addEventListener('click', sendChatSmart);
}
if (input && !input.dataset.bound) {
input.dataset.bound = '1';
input.addEventListener('keydown', (e) => {
if (e.key === 'Enter') sendChatSmart();
});
}
// Nút mở chatbot (nếu có)
const openBtn = document.getElementById('openChatbotBtn');
if (openBtn && !openBtn.dataset.bound) {
openBtn.dataset.bound = '1';
openBtn.addEventListener('click', () => {
showSection('chatbot');
initChatbot();
});
}
// Nút menu mobile (nếu có)
const btnMenu = document.getElementById('btnMenu');
if (btnMenu && !btnMenu.dataset.bound) {
btnMenu.dataset.bound = '1';
btnMenu.addEventListener('click', () => {
const sb = document.querySelector('.sidebar');
sb?.classList.toggle('open');
document.body.classList.toggle('menu-open', sb?.classList.contains('open'));
});
}
});
// ===== PYC Incremental (frontend) =====
function _fmtVND(v) {
try { return Number(v||0).toLocaleString('vi-VN') + ' VND'; } catch { return v; }
}
async function pycIncRefresh() {
const el = document.getElementById('incStatus');
el.textContent = 'Đang cập nhật file mới...';
try {
const r = await fetch(`${BACKEND_URL}/pyc_incremental/refresh`, { method: 'POST' });
const d = await r.json();
el.textContent = `Đã biết ${d.known} file, thêm mới ${d.added}` + (d.newest_num ? ` (PYC mới nhất: ${d.newest_num})` : '');
} catch (e) {
el.textContent = '⚠ Không cập nhật được: ' + e;
}
}
async function pycIncStats() {
const mSel = document.getElementById('incMonth');
const pSel = document.getElementById('incPeriod');
const box = document.getElementById('incStats');
const list = document.getElementById('incFiles');
const month = mSel?.value || '';
const period = pSel?.value || '';
const url = new URL(`${BACKEND_URL}/pyc_incremental/stats`);
if (month) url.searchParams.set('month', month);
if (period) url.searchParams.set('period', period);
url.searchParams.set('refresh_first', 'false'); // đã refresh riêng
box.innerHTML = 'Đang tải thống kê...';
try {
const r = await fetch(url);
const d = await r.json();
const t = d.totals || {}, rv = d.revenue || {};
box.innerHTML = `
KĐ : ${t['KĐ']||0} | Doanh thu: ${_fmtVND(rv['KĐ']||0)}
HC : ${t['HC']||0} | Doanh thu: ${_fmtVND(rv['HC']||0)}
ĐTN : ${t['ĐTN']||0} | Doanh thu: ${_fmtVND(rv['ĐTN']||0)}
Tổng doanh thu: ${_fmtVND((rv['KĐ']||0)+(rv['HC']||0)+(rv['ĐTN']||0))}
Khách hàng (${(d.customers||[]).length}): ${ (d.customers||[]).slice(0,50).join(', ') }
`;
const files = d.files || [];
list.innerHTML = files.length
? `${files.map(f=>`${f} `).join('')} `
: 'Chưa có file khớp điều kiện lọc. ';
} catch (e) {
box.innerHTML = '⚠ Không lấy được thống kê: ' + e;
}
}
async function refreshAndLoadPYCInc() {
const btn = document.getElementById('incReload');
if (btn && !btn.dataset.bound) {
btn.dataset.bound = '1';
btn.addEventListener('click', async () => {
btn.disabled = true; const txt = btn.textContent; btn.textContent = 'Đang cập nhật...';
await pycIncRefresh();
await pycIncStats();
btn.disabled = false; btn.textContent = txt;
});
}
// lần đầu vào màn: refresh + load
await pycIncRefresh();
await pycIncStats();
// thay đổi filter là tự load lại
const mSel = document.getElementById('incMonth');
const pSel = document.getElementById('incPeriod');
if (mSel && !mSel.dataset.bound) {
mSel.dataset.bound = '1';
mSel.addEventListener('change', pycIncStats);
}
if (pSel && !pSel.dataset.bound) {
pSel.dataset.bound = '1';
pSel.addEventListener('change', pycIncStats);
}
}