Spaces:
Sleeping

QLHT6 / static /script2.js
doluong6's picture
Rename static/script.js to static/script2.js
8042460 verified
Raw History Blame Contribute Delete
24.9 kB
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();
// ❗❗ Ẩn tất cả các phần fade-in trước
document.querySelectorAll(".fade-in").forEach(el => {
if (el) el.style.display = "none";
});
// ✅ Sau đó hiện Hồ sơ năng lực
const hs = document.getElementById("Nl");
if (hs) {
hs.style.display = "block";
hs.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";
// ==== 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(".fade-in").forEach(el => {
if (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("<p style='color:red'>Không có dữ liệu để hiển thị.</p>");
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("<p style='color:red'>Không thể tải dữ liệu.</p>");
});
}
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();
}
}
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 = "<table class='display' id='tablePYCIncomplete'><thead><tr>";
for (let key in data[0]) {
html += `<th>${key}</th>`;
}
html += "</tr></thead><tbody>";
for (let row of data) {
html += "<tr>";
for (let key in row) {
html += `<td>${row[key]}</td>`;
}
html += "</tr>";
}
html += "</tbody></table>";
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 = "<p>Lỗi khi tải biểu đồ.</p>";
}
}
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("<p style='color:red'>Không thể tải dữ liệu.</p>");
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("<p style='color:red'>Lỗi kết nối tới máy chủ.</p>");
}
}
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 = `
<p>Tổng chuyển đến: <strong>${cdStr}</strong></p>
<p>Tổng chuyển đi: <strong>${diStr}</strong></p>
`;
} catch (error) {
console.error("❌ Lỗi khi tải doanh thu nội bộ:", error);
document.getElementById("tongDoanhThuNoiBo").innerHTML = "<p style='color:red'>Không thể tải dữ liệu nội bộ.</p>";
}
}
// 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 = '<option value="">-- Chọn tài liệu để xem --</option>';
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 = `<option value="">-- Chọn tài liệu --</option>`;
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();
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%";
// Chỉ xử lý ô tình trạng
if (colIndex === idxTinhTrang) {
input.readOnly = true;
input.style.fontWeight = "bold";
const hanSD = parseNgayVN(row[idxHanSD]);
let status = "Không xác định";
let color = "black";
if (hanSD instanceof Date && !isNaN(hanSD)) {
const today = new Date();
const diffDays = Math.ceil((hanSD - today) / (1000 * 3600 * 24));
if (diffDays < 0) {
status = "HẾT HẠN";
color = "red";
} else if (diffDays <= 30) {
status = `CÒN: ${diffDays} ngày`;
color = "orange";
} else {
status = `CÒN: ${diffDays} ngày`;
color = "green";
}
}
input.value = status;
input.style.color = color;
}
td.appendChild(input);
});
});
document.getElementById("nutLuuHoaChat").style.display = "block";
} 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");
if ($.fn.DataTable.isDataTable("#bangHSKH")) {
$('#bangHSKH').DataTable().clear().destroy();
}
let tbodyHtml = "";
data.rows.forEach(row => {
tbodyHtml += `<tr>`;
for (let j = 0; j < data.columns.length; j++) {
const col = data.columns[j];
const cell = row[j] || "";
if (["Full", "PYC", "BB", "GCN"].includes(col)) {
const checked = cell.toLowerCase() === "x" ? "checked" : "";
const className = col === "Full" ? "checkbox-full" : "checkbox-cell";
tbodyHtml += `<td><input type="checkbox" class="${className}" ${checked}></td>`;
} else {
tbodyHtml += `<td><input class="input-cell" type="text" value="${cell}" /></td>`;
}
}
tbodyHtml += `</tr>`;
});
$("#bangHSKH").DataTable({
scrollX: true,
autoWidth: false,
pageLength: -1, // hiển thị tất cả
paging: false, // tắt phân trang
ordering: false,
language: {
search: "🔍 Tìm kiếm:",
lengthMenu: "Hiển thị _MENU_ dòng",
info: "Đang hiển thị _TOTAL_ dòng",
emptyTable: "Không có dữ liệu"
},
columnDefs: [
{ targets: "_all", className: "dt-center" }
]
});
// ✅ Tô màu dòng nếu FULL được tick
function capNhatMauDong() {
$("#bangHSKH tbody tr").each(function () {
const checkbox = $(this).find(`td:eq(${fullIndex}) input[type="checkbox"]`);
if (checkbox.prop("checked")) {
$(this).css("background-color", "#d2f8d2"); // Xanh
} else {
$(this).css("background-color", "#fde2e2"); // Hồng
}
});
}
capNhatMauDong();
// ✅ Khi tích/bỏ tick vào cột FULL thì cập nhật màu dòng
$("#bangHSKH").off("change", "input.checkbox-full")
.on("change", "input.checkbox-full", function () {
capNhatMauDong();
});
// ✅ Hiện nút lưu
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 = [];
$(this)
.find("td")
.each(function (i) {
const input = $(this).find("input");
if (input.length > 0) {
if (input.attr("type") === "checkbox") {
row.push(input.prop("checked") ? "x" : "");
} else {
row.push(input.val());
}
} else {
row.push($(this).text());
}
});
rows.push(row);
});
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.");
}
}