File size: 54,524 Bytes
92b2045 fc268c0 92b2045 fc268c0 92b2045 fc268c0 92b2045 6330c75 92b2045 4609f0a b382da9 92b2045 927f27a 6ee9ef4 927f27a 5a6faaf c0efcb1 6fe02a4 c14bad5 473ce77 1a24efa 473ce77 ba7158a a211d7f 4609f0a fb46731 6330c75 cc4724c fb46731 3caecef 1bbde86 92b2045 7cc8e57 6197eda 92b2045 c18755c 7cc8e57 c18755c 7cc8e57 c18755c 7cc8e57 c18755c 6197eda 7cc8e57 6197eda 7cc8e57 6197eda 7cc8e57 6197eda 92b2045 6197eda c18755c 92b2045 c411a8b 7cc8e57 c411a8b 7cc8e57 c411a8b 7cc8e57 c411a8b 7cc8e57 c411a8b 7cc8e57 c411a8b 92b2045 7cc8e57 92b2045 add6ff5 92b2045 add6ff5 92b2045 0079a06 92b2045 790aab3 92b2045 7091e4e 790aab3 92b2045 9826de2 92b2045 9826de2 92b2045 b13691e 92b2045 9826de2 35078bd b13691e 92b2045 9826de2 790aab3 92b2045 0079a06 68ee6c7 0079a06 18e8b31 68ee6c7 0079a06 68ee6c7 0079a06 ffb1b6e 18e8b31 68ee6c7 92b2045 0079a06 92b2045 0821bf7 92b2045 0821bf7 92b2045 0821bf7 92b2045 0821bf7 92b2045 0821bf7 9f19cd0 5a6faaf c0efcb1 e892dfd c0efcb1 7fb459d c0efcb1 7fb459d c0efcb1 7fb459d c0efcb1 1b5e1df c0efcb1 7fb459d c0efcb1 1b5e1df c0efcb1 6fe02a4 c14bad5 473ce77 ebc7466 ad29799 ebc7466 ad29799 ebc7466 ad29799 ebc7466 ad29799 ebc7466 ad29799 ebc7466 2c70c47 ba7158a 047246d ba7158a 4789b54 047246d ba7158a 047246d ba7158a 047246d ba7158a 4789b54 047246d ba7158a 047246d 4789b54 047246d 4789b54 047246d ba7158a 047246d ba7158a 047246d ba7158a 047246d ba7158a 047246d ba7158a 047246d ba7158a 25b308b 0c5fccd 047246d 436a9c5 3caecef 436a9c5 3caecef 436a9c5 3caecef 436a9c5 3caecef 436a9c5 3caecef 436a9c5 3caecef 436a9c5 3caecef 436a9c5 3caecef 436a9c5 3caecef 436a9c5 3caecef 2de1bb2 3caecef 436a9c5 3caecef 436a9c5 3caecef 436a9c5 3caecef 436a9c5 6330c75 436a9c5 2de1bb2 6330c75 2de1bb2 6330c75 4c62636 1bbde86 | 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 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 | 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("<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();
}
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 = "<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();
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 += `<tr class="${rowClass}">`;
// ✅ TT = index + 1
tbodyHtml += `<td>${index + 1}</td>`;
// ✅ Số PYC = 25/ĐL6/ + (index + 1).padStart(4, '0')
const soPYC = `25/ĐL6/${(index + 1).toString().padStart(4, "0")}`;
tbodyHtml += `<td>${soPYC}</td>`;
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 += `<td><input type="checkbox" class="${className}" ${checked}></td>`;
} else if (col === "Tên Khách hàng" || col === "Tên Cơ sở sử dụng") {
tbodyHtml += `<td><textarea class="input-area">${cell}</textarea></td>`;
} else if (col === "Người tiếp nhận") {
tbodyHtml += `<td><select class="input-cell">`;
tbodyHtml += `<option value="" ${(cell === "" || cell == null) ? "selected" : ""}>--chọn--</option>`;
danhSachNguoiTiepNhan.forEach(name => {
const selected = name === cell ? "selected" : "";
tbodyHtml += `<option value="${name}" ${selected}>${name}</option>`;
});
tbodyHtml += `</select></td>`;
} else if (col === "Phòng yêu cầu") {
tbodyHtml += `<td><select class="input-cell">`;
tbodyHtml += `<option value="" ${(cell === "" || cell == null) ? "selected" : ""}>--chọn--</option>`;
danhSachPhongYeuCau.forEach(phong => {
const selected = phong === cell ? "selected" : "";
tbodyHtml += `<option value="${phong}" ${selected}>${phong}</option>`;
});
tbodyHtml += `</select></td>`;
} else {
tbodyHtml += `<td><input class="input-cell" type="text" value="${cell}" /></td>`;
}
}
tbodyHtml += `</tr>`;
});
$("#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("<tr><td colspan='100%'>Không có dữ liệu</td></tr>");
return;
}
// Hiển thị tiêu đề
let theadHtml = "<tr>";
data.columns.forEach(col => {
theadHtml += `<th>${col}</th>`;
});
theadHtml += "</tr>";
$("#tableBangGia6 thead").html(theadHtml);
// Hiển thị dữ liệu
let tbodyHtml = "";
data.rows.forEach(row => {
tbodyHtml += "<tr>";
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 += `<td>${formatted}</td>`;
} else {
tbodyHtml += `<td>${cell}</td>`;
}
});
tbodyHtml += "</tr>";
});
$("#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("<tr><td colspan='100%'>Không có dữ liệu</td></tr>");
return;
}
// Tạo tiêu đề
let theadHtml = "<tr>";
data.columns.forEach(col => {
theadHtml += `<th>${col}</th>`;
});
theadHtml += "</tr>";
$("#tableBangGia2 thead").html(theadHtml);
// Tạo dữ liệu
let tbodyHtml = "";
data.rows.forEach(row => {
tbodyHtml += "<tr>";
row.forEach((cell, i) => {
const columnName = data.columns[i];
if (columnName.toLowerCase().includes("đơn giá") && !isNaN(cell)) {
tbodyHtml += `<td style="text-align:right">${Number(cell).toLocaleString("vi-VN")}</td>`;
} else if (columnName.toLowerCase().includes("tên thiết bị")) {
tbodyHtml += `<td style="text-align:left">${cell}</td>`;
} else {
tbodyHtml += `<td>${cell}</td>`;
}
});
tbodyHtml += "</tr>";
});
$("#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("<tr><td colspan='100%'>Không có dữ liệu</td></tr>");
return;
}
let theadHtml = "<tr>";
data.columns.forEach(col => {
theadHtml += `<th>${col}</th>`;
});
theadHtml += "</tr>";
$("#tableBangGia4 thead").html(theadHtml);
let tbodyHtml = "";
data.rows.forEach(row => {
tbodyHtml += "<tr>";
row.forEach((cell, i) => {
const columnName = data.columns[i];
if (columnName.toLowerCase().includes("giá") && !isNaN(cell)) {
tbodyHtml += `<td style="text-align:right">${Number(cell).toLocaleString("vi-VN")}</td>`;
} else if (columnName.toLowerCase().includes("tên") || columnName.toLowerCase().includes("thiết bị")) {
tbodyHtml += `<td style="text-align:left">${cell}</td>`;
} else {
tbodyHtml += `<td>${cell}</td>`;
}
});
tbodyHtml += "</tr>";
});
$("#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("<tr><td colspan='100%'>Không có dữ liệu</td></tr>");
return;
}
let theadHtml = "<tr>";
data.columns.forEach(col => {
theadHtml += `<th>${col}</th>`;
});
theadHtml += "</tr>";
$("#tableBangGia3 thead").html(theadHtml);
let tbodyHtml = "";
data.rows.forEach(row => {
tbodyHtml += "<tr>";
row.forEach((cell, i) => {
const columnName = data.columns[i];
if (columnName.toLowerCase().includes("giá") && !isNaN(cell)) {
tbodyHtml += `<td style="text-align:right">${Number(cell).toLocaleString("vi-VN")}</td>`;
} else if (columnName.toLowerCase().includes("tên") || columnName.toLowerCase().includes("thiết bị")) {
tbodyHtml += `<td style="text-align:left">${cell}</td>`;
} else {
tbodyHtml += `<td>${cell}</td>`;
}
});
tbodyHtml += "</tr>";
});
$("#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("<tr><td colspan='100%'>Không có dữ liệu</td></tr>");
return;
}
// Header
let theadHtml = "<tr>";
data.columns.forEach(col => {
theadHtml += `<th>${col}</th>`;
});
theadHtml += "</tr>";
$("#tableBangGia5 thead").html(theadHtml);
// Body
let tbodyHtml = "";
data.rows.forEach(row => {
tbodyHtml += "<tr>";
row.forEach((cell, i) => {
const colName = data.columns[i];
if (colName.toLowerCase().includes("giá") && !isNaN(cell)) {
tbodyHtml += `<td style="text-align:right">${Number(cell).toLocaleString("vi-VN")}</td>`;
} else if (colName.toLowerCase().includes("tên") || colName.toLowerCase().includes("thiết bị")) {
tbodyHtml += `<td style="text-align:left">${cell}</td>`;
} else {
tbodyHtml += `<td>${cell}</td>`;
}
});
tbodyHtml += "</tr>";
});
$("#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 = `
<div>
<div><b>KĐ</b>: ${t['KĐ']||0} | Doanh thu: <b>${_fmtVND(rv['KĐ']||0)}</b></div>
<div><b>HC</b>: ${t['HC']||0} | Doanh thu: <b>${_fmtVND(rv['HC']||0)}</b></div>
<div><b>ĐTN</b>: ${t['ĐTN']||0} | Doanh thu: <b>${_fmtVND(rv['ĐTN']||0)}</b></div>
<hr/>
<div><b>Tổng doanh thu:</b> ${_fmtVND((rv['KĐ']||0)+(rv['HC']||0)+(rv['ĐTN']||0))}</div>
</div>
<div style="margin-top:8px">
<b>Khách hàng (${(d.customers||[]).length}):</b> ${ (d.customers||[]).slice(0,50).join(', ') }
</div>
`;
const files = d.files || [];
list.innerHTML = files.length
? `<ul style="margin:0;padding-left:20px">${files.map(f=>`<li>${f}</li>`).join('')}</ul>`
: '<i>Chưa có file khớp điều kiện lọc.</i>';
} 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);
}
}
|