rewrite: remove Tailwind CDN dependency, use inline styles
This commit is contained in:
parent
73e3bb8fe1
commit
bb5889c407
189
index.html
189
index.html
@ -3,62 +3,103 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||||
<title>Помощник по обучению ТБ</title>
|
<title>HSE Assistant — Обучение ТБ</title>
|
||||||
<script src="https://cdn.tailwindcss.com"></script>
|
|
||||||
<style>
|
<style>
|
||||||
:root{--ink:#0F1218;--cyan:#00E5FF;--cyan-50:#E8FCFF;--white:#fff;--gray-500:#5B6573;--gray-100:#F2F4F7}
|
|
||||||
*{box-sizing:border-box;margin:0;padding:0}
|
*{box-sizing:border-box;margin:0;padding:0}
|
||||||
body{font:17px/1.6 -apple-system,BlinkMacSystemFont,"Segoe UI",Inter,system-ui,sans-serif;color:var(--ink);background:var(--gray-100)}
|
body{font:15px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;color:#1a1a2e;background:#f0f2f5}
|
||||||
.btn{display:inline-block;background:var(--cyan);color:var(--ink);padding:12px 24px;border-radius:8px;font-weight:700;text-decoration:none;border:none;cursor:pointer;font-size:15px}
|
header{background:#1a1a2e;color:#fff;padding:12px 20px;position:sticky;top:0;z-index:100;display:flex;justify-content:space-between;align-items:center}
|
||||||
.btn:hover{opacity:0.9}
|
header .logo{color:#00d4ff;font-weight:700;font-size:18px}
|
||||||
.btn-outline{background:transparent;border:2px solid var(--ink);color:var(--ink)}
|
.container{max-width:1200px;margin:0 auto;padding:16px}
|
||||||
.btn-danger{background:#ef4444;color:white}
|
.tabs{display:flex;gap:8px;margin-bottom:16px;flex-wrap:wrap}
|
||||||
.card{background:white;border-radius:12px;padding:24px;margin-bottom:16px;box-shadow:0 1px 3px rgba(0,0,0,0.1)}
|
.tab-btn{padding:10px 18px;border:2px solid #1a1a2e;background:transparent;border-radius:8px;cursor:pointer;font-size:14px;font-weight:600;transition:all .2s}
|
||||||
.input{width:100%;padding:12px 16px;border:2px solid var(--gray-100);border-radius:8px;font-size:15px;outline:none}
|
.tab-btn.active{background:#00d4ff;color:#1a1a2e;border-color:#00d4ff}
|
||||||
.input:focus{border-color:var(--cyan)}
|
.card{background:#fff;border-radius:12px;padding:20px;margin-bottom:16px;box-shadow:0 2px 8px rgba(0,0,0,.08)}
|
||||||
.table{width:100%;border-collapse:collapse;font-size:14px}
|
.btn{display:inline-block;background:#00d4ff;color:#1a1a2e;padding:10px 20px;border-radius:8px;font-weight:700;border:none;cursor:pointer;font-size:14px;text-decoration:none}
|
||||||
.table th{background:var(--gray-100);padding:12px;text-align:left;font-weight:600}
|
.btn:hover{opacity:.85}
|
||||||
.table td{padding:12px;border-bottom:1px solid var(--gray-100)}
|
.btn-danger{background:#ef4444;color:#fff}
|
||||||
.status-ok{color:#22c55e;font-weight:600}
|
.btn-green{background:#22c55e;color:#fff}
|
||||||
.status-warn{color:#f59e0b;font-weight:600}
|
.input{padding:10px 14px;border:2px solid #e2e8f0;border-radius:8px;font-size:14px;outline:none;width:100%}
|
||||||
.status-danger{color:#ef4444;font-weight:600}
|
.input:focus{border-color:#00d4ff}
|
||||||
.progress-bar{height:8px;background:var(--gray-100);border-radius:4px;overflow:hidden}
|
select.input{max-width:200px}
|
||||||
.progress-fill{height:100%;background:var(--cyan);transition:width 0.3s}
|
table{width:100%;border-collapse:collapse;font-size:13px}
|
||||||
|
th{background:#f8fafc;padding:10px 12px;text-align:left;font-weight:600;border-bottom:2px solid #e2e8f0}
|
||||||
|
td{padding:10px 12px;border-bottom:1px solid #f1f5f9}
|
||||||
|
.progress{height:8px;background:#e2e8f0;border-radius:4px;overflow:hidden}
|
||||||
|
.progress-fill{height:100%;background:#00d4ff;border-radius:4px}
|
||||||
|
.ok{color:#22c55e;font-weight:600}
|
||||||
|
.warn{color:#f59e0b;font-weight:600}
|
||||||
|
.danger{color:#ef4444;font-weight:600}
|
||||||
|
.grid{display:grid;gap:12px}
|
||||||
|
.grid-2{grid-template-columns:repeat(2,1fr)}
|
||||||
|
.grid-3{grid-template-columns:repeat(3,1fr)}
|
||||||
|
.grid-4{grid-template-columns:repeat(4,1fr)}
|
||||||
|
@media(max-width:768px){.grid-2,.grid-3,.grid-4{grid-template-columns:1fr}.tabs{gap:4px}.tab-btn{padding:8px 12px;font-size:12px}}
|
||||||
|
.stat-card{text-align:center;padding:16px}
|
||||||
|
.stat-num{font-size:28px;font-weight:700}
|
||||||
|
.stat-label{font-size:12px;color:#64748b;margin-top:4px}
|
||||||
|
.upload-area{background:#eff6ff;border:2px dashed #3b82f6;border-radius:12px;padding:20px;display:flex;align-items:center;justify-content:space-between;gap:16px;flex-wrap:wrap}
|
||||||
|
.flex{display:flex;gap:12px;align-items:center;flex-wrap:wrap}
|
||||||
.hidden{display:none!important}
|
.hidden{display:none!important}
|
||||||
@media(max-width:640px){.table{font-size:12px}.table th,.table td{padding:8px}}
|
.msg{padding:10px 14px;border-radius:8px;font-size:13px;margin-top:8px}
|
||||||
|
.msg-ok{background:#f0fdf4;color:#166534;border:1px solid #bbf7d0}
|
||||||
|
.msg-err{background:#fef2f2;color:#991b1b;border:1px solid #fecaca}
|
||||||
|
.city-card{cursor:pointer;padding:16px;border:2px solid transparent;transition:all .2s}
|
||||||
|
.city-card:hover{border-color:#00d4ff}
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="app">
|
|
||||||
<!-- HEADER -->
|
<header>
|
||||||
<header class="bg-[#0F1218] text-white p-4 sticky top-0 z-50">
|
<div class="logo">🛡️ HSE Assistant</div>
|
||||||
<div class="max-w-7xl mx-auto flex justify-between items-center">
|
<div style="font-size:12px;color:#94a3b8">Система учёта обучения ТБ</div>
|
||||||
<div class="flex items-center gap-3">
|
|
||||||
<span class="text-[#00E5FF] text-xl font-bold">🛡️ HSE Assistant</span>
|
|
||||||
</div>
|
|
||||||
<div class="flex items-center gap-4">
|
|
||||||
<span class="text-sm text-gray-400">Открытый доступ</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<div class="max-w-7xl mx-auto p-4">
|
<div class="container">
|
||||||
<!-- ADMIN TABS -->
|
<!-- TABS -->
|
||||||
<div id="admin-panel" class="hidden mb-6">
|
<div class="tabs" id="tabs">
|
||||||
<div class="flex gap-2 mb-4 flex-wrap">
|
<button class="tab-btn active" onclick="showTab('dashboard')">📊 Дашборд</button>
|
||||||
<button onclick="showTab('search')" class="btn tab-btn" data-tab="search">🔍 Поиск</button>
|
<button class="tab-btn" onclick="showTab('search')">🔍 Поиск</button>
|
||||||
<button onclick="showTab('region')" class="btn btn-outline tab-btn" data-tab="region">🏙️ По регионам</button>
|
<button class="tab-btn" onclick="showTab('region')">🏙️ По регионам</button>
|
||||||
<button onclick="showTab('dashboard')" class="btn btn-outline tab-btn" data-tab="dashboard">📊 Дашборд</button>
|
<button class="tab-btn" onclick="showTab('export')">📥 Выгрузка</button>
|
||||||
<button onclick="showTab('export')" class="btn btn-outline tab-btn" data-tab="export">📥 Выгрузка</button>
|
</div>
|
||||||
|
|
||||||
|
<!-- DASHBOARD TAB -->
|
||||||
|
<div id="tab-dashboard">
|
||||||
|
<div class="card">
|
||||||
|
<div class="upload-area">
|
||||||
|
<div>
|
||||||
|
<div style="font-weight:700;font-size:15px">📤 Загрузка данных</div>
|
||||||
|
<div style="font-size:13px;color:#64748b">Загрузите Excel (.xlsx) или CSV файл</div>
|
||||||
|
</div>
|
||||||
|
<label style="cursor:pointer">
|
||||||
|
<div class="btn">📁 Выбрать файл</div>
|
||||||
|
<input type="file" id="file-upload" accept=".csv,.xlsx" style="display:none" onchange="handleFileUpload(event)">
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<div id="upload-results"></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="grid grid-4" id="dash-stats"></div>
|
||||||
|
|
||||||
|
<div class="grid grid-2">
|
||||||
|
<div class="card">
|
||||||
|
<h3 style="margin-bottom:12px">Проблемные филиалы</h3>
|
||||||
|
<div id="dash-problems"></div>
|
||||||
|
</div>
|
||||||
|
<div class="card">
|
||||||
|
<h3 style="margin-bottom:12px">Самые непройденные курсы</h3>
|
||||||
|
<div id="dash-courses"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- SEARCH TAB -->
|
<!-- SEARCH TAB -->
|
||||||
<div id="tab-search" class="tab-content">
|
<div id="tab-search" class="hidden">
|
||||||
<div class="card">
|
<div class="card">
|
||||||
<h2 class="text-xl font-bold mb-4">Поиск сотрудника</h2>
|
<h2 style="margin-bottom:14px">Поиск сотрудника</h2>
|
||||||
<div class="flex gap-3 flex-wrap">
|
<div class="flex">
|
||||||
<input type="text" id="search-input" class="input flex-1" placeholder="Таб.№ или ФИО">
|
<input type="text" id="search-input" class="input" placeholder="Таб.№ или ФИО" style="max-width:400px">
|
||||||
<select id="filter-city" class="input" style="max-width:200px">
|
<select id="filter-city" class="input">
|
||||||
<option value="">Все города</option>
|
<option value="">Все города</option>
|
||||||
<option>Алматы</option>
|
<option>Алматы</option>
|
||||||
<option>Астана</option>
|
<option>Астана</option>
|
||||||
@ -74,74 +115,30 @@ body{font:17px/1.6 -apple-system,BlinkMacSystemFont,"Segoe UI",Inter,system-ui,s
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- REGION TAB -->
|
<!-- REGION TAB -->
|
||||||
<div id="tab-region" class="tab-content hidden">
|
<div id="tab-region" class="hidden">
|
||||||
<div class="card">
|
<div class="card">
|
||||||
<h2 class="text-xl font-bold mb-4">Сотрудники по филиалам</h2>
|
<h2 style="margin-bottom:14px">Сотрудники по филиалам</h2>
|
||||||
<div class="grid grid-cols-2 md:grid-cols-3 gap-3 mb-4" id="city-stats"></div>
|
<div class="grid grid-3" id="city-stats"></div>
|
||||||
</div>
|
|
||||||
<div id="region-results"></div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- DASHBOARD TAB -->
|
|
||||||
<div id="tab-dashboard" class="tab-content hidden">
|
|
||||||
<div class="card">
|
|
||||||
<h2 class="text-xl font-bold mb-4">📊 Дашборд обучения ТБ</h2>
|
|
||||||
<div class="mb-4 p-3 bg-blue-50 rounded-lg border border-blue-200">
|
|
||||||
<div class="flex items-center justify-between">
|
|
||||||
<div>
|
|
||||||
<p class="font-semibold text-blue-800">📤 Загрузка данных</p>
|
|
||||||
<p class="text-sm text-blue-600">Загрузите Excel (.xlsx) или CSV файл с данными сотрудников</p>
|
|
||||||
</div>
|
|
||||||
<label class="cursor-pointer">
|
|
||||||
<div class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition flex items-center gap-2">
|
|
||||||
<span>📁 Выбрать файл</span>
|
|
||||||
<input type="file" id="file-upload" accept=".csv,.xlsx" class="hidden" onchange="handleFileUpload(event)">
|
|
||||||
</div>
|
|
||||||
</label>
|
|
||||||
</div>
|
|
||||||
<div id="upload-results" class="mt-3"></div>
|
|
||||||
</div>
|
|
||||||
<div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6" id="dash-stats"></div>
|
|
||||||
<div class="grid md:grid-cols-2 gap-4">
|
|
||||||
<div class="card">
|
|
||||||
<h3 class="font-bold mb-3">Проблемные филиалы</h3>
|
|
||||||
<div id="dash-problems"></div>
|
|
||||||
</div>
|
|
||||||
<div class="card">
|
|
||||||
<h3 class="font-bold mb-3">Самые непройденные курсы</h3>
|
|
||||||
<div id="dash-courses"></div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- EXPORT TAB -->
|
<!-- EXPORT TAB -->
|
||||||
<div id="tab-export" class="tab-content hidden">
|
<div id="tab-export" class="hidden">
|
||||||
<div class="card">
|
<div class="card">
|
||||||
<h2 class="text-xl font-bold mb-4">📥 Выгрузка данных</h2>
|
<h2 style="margin-bottom:14px">📥 Выгрузка данных</h2>
|
||||||
<div class="flex gap-3 flex-wrap mb-4">
|
<div class="flex" style="margin-bottom:12px">
|
||||||
<button onclick="exportData('overdue')" class="btn btn-danger">⏰ Просроченные</button>
|
<button onclick="exportData('overdue')" class="btn btn-danger">⏰ Просроченные</button>
|
||||||
<button onclick="exportData('city')" class="btn">🏙️ По филиалу</button>
|
<button onclick="exportData('city')" class="btn">🏙️ По филиалу</button>
|
||||||
<button onclick="exportData('employee')" class="btn">👤 По сотруднику</button>
|
<button onclick="exportData('employee')" class="btn">👤 По сотруднику</button>
|
||||||
<button onclick="exportData('summary')" class="btn">📋 Сводный отчёт</button>
|
<button onclick="exportData('summary')" class="btn">📋 Сводный отчёт</button>
|
||||||
<button onclick="exportCSV()" class="btn bg-green-600 text-white">📊 Экспорт CSV</button>
|
<button onclick="exportCSV()" class="btn btn-green">📊 Экспорт CSV</button>
|
||||||
</div>
|
</div>
|
||||||
<div id="export-results"></div>
|
<div id="export-results"></div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- EMPLOYEE VIEW (не-админ) -->
|
|
||||||
<div id="employee-panel" class="hidden">
|
|
||||||
<div class="card">
|
|
||||||
<h2 class="text-xl font-bold mb-4" id="emp-title">Моё HSE обучение</h2>
|
|
||||||
<div id="emp-courses"></div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
</div><!-- /app -->
|
|
||||||
|
|
||||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
|
||||||
<script src="script.js?v=2"></script>
|
<script src="script.js?v=3"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
621
script.js
621
script.js
@ -1,4 +1,4 @@
|
|||||||
// ========== МОК-ДАННЫЕ ==========
|
// ========== ДАННЫЕ ==========
|
||||||
const COURSES = [
|
const COURSES = [
|
||||||
{ id: 1, name: "Безопасная рабочая среда SWE 2", level: 2, periodicity: 12 },
|
{ id: 1, name: "Безопасная рабочая среда SWE 2", level: 2, periodicity: 12 },
|
||||||
{ id: 2, name: "Безопасное вождение (Defensive Driving)", level: 2, periodicity: 24 },
|
{ id: 2, name: "Безопасное вождение (Defensive Driving)", level: 2, periodicity: 24 },
|
||||||
@ -29,7 +29,6 @@ const CITIES = ["Алматы", "Астана", "Атырау", "Актау", "
|
|||||||
const DEPARTMENTS = ["HSE", "Производство", "Логистика", "Администрация", "Техническая служба", "Электроснабжение"];
|
const DEPARTMENTS = ["HSE", "Производство", "Логистика", "Администрация", "Техническая служба", "Электроснабжение"];
|
||||||
const POSITIONS = ["Инженер HSE", "Мастер", "Электромонтёр", "Слесарь", "Водитель", "Начальник смены", "Техник"];
|
const POSITIONS = ["Инженер HSE", "Мастер", "Электромонтёр", "Слесарь", "Водитель", "Начальник смены", "Техник"];
|
||||||
|
|
||||||
// Генерация мок-данных сотрудников
|
|
||||||
function generateEmployees() {
|
function generateEmployees() {
|
||||||
const employees = [];
|
const employees = [];
|
||||||
const lastNames = ["Иванов", "Петров", "Сидоров", "Козлов", "Новиков", "Морозов", "Волков", "Соколов", "Лебедев", "Кузнецов", "Попов", "Васильев", "Зайцев", "Михайлов", "Фёдоров", "Абдуллин", "Нурланов", "Сагиев", "Турсунов", "Касымов", "Жумабаев", "Ермеков", "Баймуханов", "Алиев", "Хасенов"];
|
const lastNames = ["Иванов", "Петров", "Сидоров", "Козлов", "Новиков", "Морозов", "Волков", "Соколов", "Лебедев", "Кузнецов", "Попов", "Васильев", "Зайцев", "Михайлов", "Фёдоров", "Абдуллин", "Нурланов", "Сагиев", "Турсунов", "Касымов", "Жумабаев", "Ермеков", "Баймуханов", "Алиев", "Хасенов"];
|
||||||
@ -50,9 +49,8 @@ function generateEmployees() {
|
|||||||
position: POSITIONS[Math.floor(Math.random() * POSITIONS.length)],
|
position: POSITIONS[Math.floor(Math.random() * POSITIONS.length)],
|
||||||
courses: []
|
courses: []
|
||||||
};
|
};
|
||||||
emp.fullName = `${emp.lastName} ${emp.firstName} ${emp.patronymic}`;
|
emp.fullName = emp.lastName + ' ' + emp.firstName + ' ' + emp.patronymic;
|
||||||
|
|
||||||
// Случайные курсы
|
|
||||||
const courseCount = 5 + Math.floor(Math.random() * 10);
|
const courseCount = 5 + Math.floor(Math.random() * 10);
|
||||||
const shuffled = [...COURSES].sort(() => 0.5 - Math.random());
|
const shuffled = [...COURSES].sort(() => 0.5 - Math.random());
|
||||||
for (let j = 0; j < Math.min(courseCount, COURSES.length); j++) {
|
for (let j = 0; j < Math.min(courseCount, COURSES.length); j++) {
|
||||||
@ -94,541 +92,328 @@ function generateEmployees() {
|
|||||||
return employees;
|
return employees;
|
||||||
}
|
}
|
||||||
|
|
||||||
const EMPLOYEES = generateEmployees();
|
let EMPLOYEES = generateEmployees();
|
||||||
|
|
||||||
// ========== СОСТОЯНИЕ ==========
|
|
||||||
let currentUser = { tab: 'admin', fullName: 'Администратор системы', role: 'admin' };
|
|
||||||
let isAdmin = true;
|
|
||||||
|
|
||||||
// ========== АВТОМАТИЧЕСКАЯ ЗАГРУЗКА ==========
|
|
||||||
document.addEventListener('DOMContentLoaded', function() {
|
|
||||||
try {
|
|
||||||
document.getElementById('admin-panel').classList.remove('hidden');
|
|
||||||
document.getElementById('employee-panel').classList.add('hidden');
|
|
||||||
showTab('dashboard');
|
|
||||||
renderDashboard();
|
|
||||||
renderCityStats();
|
|
||||||
} catch (e) {
|
|
||||||
console.error('Ошибка инициализации:', e);
|
|
||||||
document.body.innerHTML = '<div style="padding:20px;color:red;">Ошибка загрузки: ' + e.message + '</div>';
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// ========== ТАБЫ ==========
|
// ========== ТАБЫ ==========
|
||||||
function showTab(name) {
|
function showTab(name) {
|
||||||
document.querySelectorAll('.tab-content').forEach(el => el.classList.add('hidden'));
|
['dashboard', 'search', 'region', 'export'].forEach(t => {
|
||||||
document.getElementById('tab-' + name).classList.remove('hidden');
|
document.getElementById('tab-' + t).classList.toggle('hidden', t !== name);
|
||||||
document.querySelectorAll('.tab-btn').forEach(btn => {
|
|
||||||
btn.classList.remove('btn');
|
|
||||||
btn.classList.add('btn', 'btn-outline');
|
|
||||||
});
|
});
|
||||||
document.querySelector(`[data-tab="${name}"]`).classList.remove('btn-outline');
|
document.querySelectorAll('.tab-btn').forEach((btn, i) => {
|
||||||
|
const tabs = ['dashboard', 'search', 'region', 'export'];
|
||||||
|
btn.classList.toggle('active', tabs[i] === name);
|
||||||
|
});
|
||||||
|
if (name === 'dashboard') { renderDashboard(); renderCityStats(); }
|
||||||
|
if (name === 'region') renderCityStats();
|
||||||
}
|
}
|
||||||
|
|
||||||
// ========== ПОИСК ==========
|
// ========== ПОИСК ==========
|
||||||
function searchEmployee() {
|
function searchEmployee() {
|
||||||
const query = document.getElementById('search-input').value.trim();
|
const query = document.getElementById('search-input').value.trim().toLowerCase();
|
||||||
const cityFilter = document.getElementById('filter-city').value;
|
const cityFilter = document.getElementById('filter-city').value;
|
||||||
|
|
||||||
let results = EMPLOYEES;
|
let results = EMPLOYEES;
|
||||||
|
if (query) results = results.filter(e => e.tab === query || e.fullName.toLowerCase().includes(query));
|
||||||
if (query) {
|
if (cityFilter) results = results.filter(e => e.city === cityFilter);
|
||||||
results = results.filter(e =>
|
|
||||||
e.tab === query ||
|
|
||||||
e.fullName.toLowerCase().includes(query.toLowerCase())
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (cityFilter) {
|
|
||||||
results = results.filter(e => e.city === cityFilter);
|
|
||||||
}
|
|
||||||
|
|
||||||
renderSearchResults(results);
|
renderSearchResults(results);
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderSearchResults(employees) {
|
function renderSearchResults(employees) {
|
||||||
const container = document.getElementById('search-results');
|
const c = document.getElementById('search-results');
|
||||||
|
if (!employees.length) { c.innerHTML = '<div class="card">Сотрудники не найдены</div>'; return; }
|
||||||
|
|
||||||
if (employees.length === 0) {
|
let h = '<div class="card" style="overflow-x:auto"><table><thead><tr><th>Таб.№</th><th>ФИО</th><th>Город</th><th>Должность</th><th>Пройдено</th><th>Просрочено</th><th>Прогресс</th><th></th></tr></thead><tbody>';
|
||||||
container.innerHTML = '<div class="card">Сотрудники не найдены</div>';
|
for (const e of employees) {
|
||||||
return;
|
const done = e.courses.filter(c => c.completed).length;
|
||||||
|
const ov = e.courses.filter(c => c.overdue).length;
|
||||||
|
const pct = Math.round((done / e.courses.length) * 100);
|
||||||
|
h += '<tr><td style="font-family:monospace">' + e.tab + '</td><td><strong>' + e.fullName + '</strong></td><td>' + e.city + '</td><td>' + e.position + '</td><td class="ok">' + done + '/' + e.courses.length + '</td><td class="' + (ov ? 'danger' : '') + '">' + (ov ? '❌ ' + ov : '✅') + '</td><td><div style="display:flex;align-items:center;gap:8px"><div class="progress" style="flex:1"><div class="progress-fill" style="width:' + pct + '%"></div></div><span style="font-size:12px">' + pct + '%</span></div></td><td><button onclick="showDetail(\'' + e.tab + '\')" class="btn" style="padding:6px 12px;font-size:12px">Подробнее</button></td></tr>';
|
||||||
}
|
}
|
||||||
|
h += '</tbody></table></div>';
|
||||||
let html = '<div class="card overflow-x-auto"><table class="table"><thead><tr>';
|
c.innerHTML = h;
|
||||||
html += '<th>Таб.№</th><th>ФИО</th><th>Город</th><th>Должность</th><th>Пройдено</th><th>Просрочено</th><th>Прогресс</th><th></th>';
|
|
||||||
html += '</tr></thead><tbody>';
|
|
||||||
|
|
||||||
for (const emp of employees) {
|
|
||||||
const completed = emp.courses.filter(c => c.completed).length;
|
|
||||||
const overdue = emp.courses.filter(c => c.overdue).length;
|
|
||||||
const progress = Math.round((completed / emp.courses.length) * 100);
|
|
||||||
|
|
||||||
html += `<tr>
|
|
||||||
<td class="font-mono">${emp.tab}</td>
|
|
||||||
<td class="font-semibold">${emp.fullName}</td>
|
|
||||||
<td>${emp.city}</td>
|
|
||||||
<td>${emp.position}</td>
|
|
||||||
<td class="status-ok">${completed}/${emp.courses.length}</td>
|
|
||||||
<td class="${overdue > 0 ? 'status-danger' : ''}">${overdue > 0 ? '❌ ' + overdue : '✅'}</td>
|
|
||||||
<td>
|
|
||||||
<div class="flex items-center gap-2">
|
|
||||||
<div class="progress-bar flex-1"><div class="progress-fill" style="width:${progress}%"></div></div>
|
|
||||||
<span class="text-sm">${progress}%</span>
|
|
||||||
</div>
|
|
||||||
</td>
|
|
||||||
<td><button onclick="showEmployeeDetail('${emp.tab}')" class="btn text-xs py-1 px-3">Подробнее</button></td>
|
|
||||||
</tr>`;
|
|
||||||
}
|
|
||||||
|
|
||||||
html += '</tbody></table></div>';
|
|
||||||
container.innerHTML = html;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function showEmployeeDetail(tab) {
|
function showDetail(tab) {
|
||||||
const emp = EMPLOYEES.find(e => e.tab === tab);
|
const emp = EMPLOYEES.find(e => e.tab === tab);
|
||||||
if (!emp) return;
|
if (!emp) return;
|
||||||
showTab('search');
|
const c = document.getElementById('search-results');
|
||||||
renderEmployeeCourses(emp, true);
|
const done = emp.courses.filter(c => c.completed);
|
||||||
}
|
const notDone = emp.courses.filter(c => !c.completed);
|
||||||
|
const overdue = done.filter(c => c.overdue);
|
||||||
|
const valid = done.filter(c => !c.overdue);
|
||||||
|
const pct = Math.round((done.length / emp.courses.length) * 100);
|
||||||
|
|
||||||
// ========== ПОКАЗАТЬ КУРСЫ СОТРУДНИКА ==========
|
let h = '<div class="card"><button onclick="searchEmployee()" class="btn" style="padding:6px 12px;font-size:12px;margin-bottom:16px">← Назад</button>';
|
||||||
function renderEmployeeCourses(emp, showBack = false) {
|
h += '<div class="flex" style="margin-bottom:16px;gap:24px"><div><span style="color:#64748b">Таб.№:</span> <strong>' + emp.tab + '</strong></div><div><span style="color:#64748b">Город:</span> <strong>' + emp.city + '</strong></div><div><span style="color:#64748b">Должность:</span> <strong>' + emp.position + '</strong></div><div><span style="color:#64748b">Подразделение:</span> <strong>' + emp.department + '</strong></div></div>';
|
||||||
const container = isAdmin ? document.getElementById('search-results') : document.getElementById('emp-courses');
|
h += '<div style="margin-bottom:16px"><div style="display:flex;justify-content:space-between;margin-bottom:6px"><strong>Общий прогресс</strong><span>' + done.length + ' из ' + emp.courses.length + ' (' + pct + '%)</span></div><div class="progress" style="height:12px"><div class="progress-fill" style="width:' + pct + '%"></div></div></div>';
|
||||||
const titleEl = document.getElementById('emp-title');
|
|
||||||
|
|
||||||
if (titleEl) titleEl.textContent = `Обучение — ${emp.fullName}`;
|
if (overdue.length) {
|
||||||
|
h += '<div style="margin-bottom:16px"><h3 class="danger" style="margin-bottom:8px">⏰ Просрочено (' + overdue.length + ')</h3><table><thead><tr><th>Курс</th><th>Уровень</th><th>Завершён</th><th>Должен пройти</th><th>Просрочка</th></tr></thead><tbody>';
|
||||||
const completed = emp.courses.filter(c => c.completed);
|
for (const c of overdue) h += '<tr><td>' + c.courseName + '</td><td>Ур.' + c.level + '</td><td>' + fmt(c.completedDate) + '</td><td>' + fmt(c.nextDate) + '</td><td class="danger">⚠️ ' + c.daysOverdue + ' дн.</td></tr>';
|
||||||
const notStarted = emp.courses.filter(c => !c.completed);
|
h += '</tbody></table></div>';
|
||||||
const overdue = completed.filter(c => c.overdue);
|
|
||||||
const valid = completed.filter(c => !c.overdue);
|
|
||||||
const progress = Math.round((completed.length / emp.courses.length) * 100);
|
|
||||||
|
|
||||||
let html = `<div class="card">`;
|
|
||||||
if (showBack) html += `<button onclick="searchEmployee()" class="btn btn-outline text-sm mb-4">← Назад к списку</button>`;
|
|
||||||
|
|
||||||
html += `
|
|
||||||
<div class="flex flex-wrap gap-4 mb-4">
|
|
||||||
<div><span class="text-gray-500">Таб.№:</span> <strong>${emp.tab}</strong></div>
|
|
||||||
<div><span class="text-gray-500">Город:</span> <strong>${emp.city}</strong></div>
|
|
||||||
<div><span class="text-gray-500">Должность:</span> <strong>${emp.position}</strong></div>
|
|
||||||
<div><span class="text-gray-500">Подразделение:</span> <strong>${emp.department}</strong></div>
|
|
||||||
</div>
|
|
||||||
<div class="mb-4">
|
|
||||||
<div class="flex justify-between mb-1"><span class="font-semibold">Общий прогресс</span><span>${completed.length} из ${emp.courses.length} (${progress}%)</span></div>
|
|
||||||
<div class="progress-bar"><div class="progress-fill" style="width:${progress}%"></div></div>
|
|
||||||
</div>
|
|
||||||
`;
|
|
||||||
|
|
||||||
if (overdue.length > 0) {
|
|
||||||
html += `<div class="mb-4"><h3 class="font-bold text-red-600 mb-2">⏰ Просрочено (${overdue.length})</h3>
|
|
||||||
<div class="overflow-x-auto"><table class="table"><thead><tr><th>Курс</th><th>Уровень</th><th>Завершён</th><th>Должен пройти</th><th>Просрочка</th></tr></thead><tbody>`;
|
|
||||||
for (const c of overdue) {
|
|
||||||
html += `<tr><td>${c.courseName}</td><td>Ур.${c.level}</td><td>${formatDate(c.completedDate)}</td><td>${formatDate(c.nextDate)}</td><td class="status-danger">⚠️ ${c.daysOverdue} дн.</td></tr>`;
|
|
||||||
}
|
}
|
||||||
html += `</tbody></table></div></div>`;
|
if (valid.length) {
|
||||||
}
|
h += '<div style="margin-bottom:16px"><h3 class="ok" style="margin-bottom:8px">✅ Действует (' + valid.length + ')</h3><table><thead><tr><th>Курс</th><th>Уровень</th><th>Завершён</th><th>Следующее</th></tr></thead><tbody>';
|
||||||
|
|
||||||
if (valid.length > 0) {
|
|
||||||
html += `<div class="mb-4"><h3 class="font-bold text-green-600 mb-2">✅ Действует (${valid.length})</h3>
|
|
||||||
<div class="overflow-x-auto"><table class="table"><thead><tr><th>Курс</th><th>Уровень</th><th>Завершён</th><th>Следующее</th><th></th></tr></thead><tbody>`;
|
|
||||||
for (const c of valid) {
|
for (const c of valid) {
|
||||||
const daysLeft = Math.ceil((new Date(c.nextDate) - new Date()) / 86400000);
|
const left = Math.ceil((new Date(c.nextDate) - new Date()) / 86400000);
|
||||||
const urgency = daysLeft <= 30 ? 'text-yellow-600 font-bold' : '';
|
const urg = left <= 30 ? ' class="warn"' : '';
|
||||||
html += `<tr><td>${c.courseName}</td><td>Ур.${c.level}</td><td>${formatDate(c.completedDate)}</td><td class="${urgency}">${formatDate(c.nextDate)} ${daysLeft <= 30 ? '⚠️ ' + daysLeft + ' дн.' : ''}</td><td></td></tr>`;
|
h += '<tr><td>' + c.courseName + '</td><td>Ур.' + c.level + '</td><td>' + fmt(c.completedDate) + '</td><td' + urg + '>' + fmt(c.nextDate) + (left <= 30 ? ' ⚠️ ' + left + ' дн.' : '') + '</td></tr>';
|
||||||
}
|
}
|
||||||
html += `</tbody></table></div></div>`;
|
h += '</tbody></table></div>';
|
||||||
}
|
}
|
||||||
|
if (notDone.length) {
|
||||||
if (notStarted.length > 0) {
|
h += '<div><h3 style="color:#64748b;margin-bottom:8px">❗ Не пройдено (' + notDone.length + ')</h3><ul style="padding-left:20px;color:#64748b">';
|
||||||
html += `<div><h3 class="font-bold text-gray-500 mb-2">❗ Не пройдено (${notStarted.length})</h3><ul class="list-disc list-inside text-gray-600">`;
|
for (const c of notDone) h += '<li>' + c.courseName + ' (Ур.' + c.level + ')</li>';
|
||||||
for (const c of notStarted) {
|
h += '</ul></div>';
|
||||||
html += `<li>${c.courseName} (Ур.${c.level})</li>`;
|
|
||||||
}
|
|
||||||
html += `</ul></div>`;
|
|
||||||
}
|
|
||||||
|
|
||||||
html += '</div>';
|
|
||||||
container.innerHTML = html;
|
|
||||||
|
|
||||||
if (isAdmin) {
|
|
||||||
document.getElementById('tab-search').classList.remove('hidden');
|
|
||||||
document.querySelectorAll('.tab-content').forEach(el => { if (el.id !== 'tab-search') el.classList.add('hidden'); });
|
|
||||||
}
|
}
|
||||||
|
h += '</div>';
|
||||||
|
c.innerHTML = h;
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatDate(dateStr) {
|
function fmt(d) { if (!d) return '—'; const [y, m, dd] = d.split('-'); return dd + '.' + m + '.' + y; }
|
||||||
if (!dateStr) return '—';
|
|
||||||
const [y, m, d] = dateStr.split('-');
|
|
||||||
return `${d}.${m}.${y}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ========== РЕГИОНЫ ==========
|
// ========== РЕГИОНЫ ==========
|
||||||
function renderCityStats() {
|
function renderCityStats() {
|
||||||
const container = document.getElementById('city-stats');
|
const c = document.getElementById('city-stats');
|
||||||
const stats = CITIES.map(city => {
|
const stats = CITIES.map(city => {
|
||||||
const emps = EMPLOYEES.filter(e => e.city === city);
|
const emps = EMPLOYEES.filter(e => e.city === city);
|
||||||
const totalCourses = emps.reduce((sum, e) => sum + e.courses.length, 0);
|
const total = emps.reduce((s, e) => s + e.courses.length, 0);
|
||||||
const completed = emps.reduce((sum, e) => sum + e.courses.filter(c => c.completed).length, 0);
|
const done = emps.reduce((s, e) => s + e.courses.filter(c => c.completed).length, 0);
|
||||||
const overdue = emps.reduce((sum, e) => sum + e.courses.filter(c => c.overdue).length, 0);
|
const ov = emps.reduce((s, e) => s + e.courses.filter(c => c.overdue).length, 0);
|
||||||
const progress = totalCourses > 0 ? Math.round((completed / totalCourses) * 100) : 0;
|
return { city, count: emps.length, pct: total ? Math.round((done / total) * 100) : 0, overdue: ov };
|
||||||
return { city, count: emps.length, progress, overdue };
|
|
||||||
});
|
});
|
||||||
|
c.innerHTML = stats.map(s =>
|
||||||
container.innerHTML = stats.map(s => `
|
'<div class="card city-card" onclick="showCity(\'' + s.city + '\')">' +
|
||||||
<div class="card cursor-pointer hover:border-[#00E5FF] transition" onclick="showCityEmployees('${s.city}')">
|
'<div style="font-size:24px;font-weight:700">' + s.count + '</div>' +
|
||||||
<div class="text-2xl font-bold">${s.count}</div>
|
'<div style="font-size:13px;color:#64748b">' + s.city + '</div>' +
|
||||||
<div class="text-sm text-gray-500">${s.city}</div>
|
'<div class="progress" style="margin-top:8px"><div class="progress-fill" style="width:' + s.pct + '%"></div></div>' +
|
||||||
<div class="progress-bar mt-2"><div class="progress-fill" style="width:${s.progress}%"></div></div>
|
'<div style="font-size:11px;margin-top:4px">' + s.pct + '% выполнено' + (s.overdue ? ' <span class="danger">| ' + s.overdue + ' просрочено</span>' : '') + '</div>' +
|
||||||
<div class="text-xs mt-1">${s.progress}% выполнено ${s.overdue > 0 ? `<span class="text-red-500">| ${s.overdue} просрочено</span>` : ''}</div>
|
'</div>'
|
||||||
</div>
|
).join('');
|
||||||
`).join('');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function showCityEmployees(city) {
|
function showCity(city) {
|
||||||
const emps = EMPLOYEES.filter(e => e.city === city);
|
|
||||||
renderSearchResults(emps);
|
|
||||||
showTab('search');
|
showTab('search');
|
||||||
|
renderSearchResults(EMPLOYEES.filter(e => e.city === city));
|
||||||
}
|
}
|
||||||
|
|
||||||
// ========== ЗАГРУЗКА ДАННЫХ ==========
|
// ========== ЗАГРУЗКА ==========
|
||||||
function handleFileUpload(event) {
|
function handleFileUpload(event) {
|
||||||
const file = event.target.files[0];
|
const file = event.target.files[0];
|
||||||
if (!file) return;
|
if (!file) return;
|
||||||
|
|
||||||
const reader = new FileReader();
|
const reader = new FileReader();
|
||||||
const extension = file.name.split('.').pop().toLowerCase();
|
const ext = file.name.split('.').pop().toLowerCase();
|
||||||
|
|
||||||
reader.onload = function(e) {
|
reader.onload = function(e) {
|
||||||
let csvData = e.target.result;
|
let data = null;
|
||||||
let parsedData = null;
|
if (ext === 'csv') {
|
||||||
let fileType = '';
|
data = parseCSV(e.target.result);
|
||||||
|
} else if (ext === 'xlsx') {
|
||||||
|
try { data = parseExcel(e.target.result); } catch (err) { msg('Ошибка Excel: ' + err.message, 'err'); return; }
|
||||||
|
} else { msg('Только .csv и .xlsx', 'err'); return; }
|
||||||
|
|
||||||
if (extension === 'csv') {
|
if (data && data.length) {
|
||||||
parsedData = parseCSV(csvData);
|
processData(data);
|
||||||
fileType = 'CSV';
|
msg('Загружено ' + data.length + ' строк', 'ok');
|
||||||
} else if (extension === 'xlsx') {
|
} else { msg('Не удалось распознать данные', 'err'); }
|
||||||
try {
|
|
||||||
parsedData = parseExcel(e.target.result);
|
|
||||||
fileType = 'Excel';
|
|
||||||
} catch (err) {
|
|
||||||
showUploadMessage(`Ошибка при чтении Excel файла: ${err.message}`, 'error');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
showUploadMessage('Поддерживаются только файлы .csv и .xlsx', 'error');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (parsedData && parsedData.length > 0) {
|
|
||||||
showUploadMessage(`Файл успешно загружен! Найдено ${parsedData.length} строк данных.`, 'success');
|
|
||||||
processUploadedData(parsedData, fileType);
|
|
||||||
} else {
|
|
||||||
showUploadMessage('Не удалось распознать данные в файле. Проверьте формат CSV/Excel.', 'error');
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
reader.onerror = function() { msg('Ошибка чтения файла', 'err'); };
|
||||||
|
|
||||||
reader.onerror = function() {
|
if (ext === 'csv') reader.readAsText(file);
|
||||||
showUploadMessage('Ошибка при чтении файла', 'error');
|
else reader.readAsArrayBuffer(file);
|
||||||
};
|
|
||||||
|
|
||||||
if (extension === 'csv') {
|
|
||||||
reader.readAsText(file);
|
|
||||||
} else if (extension === 'xlsx') {
|
|
||||||
reader.readAsArrayBuffer(file);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function parseCSV(csvData) {
|
function parseCSV(text) {
|
||||||
const lines = csvData.split(/\r?\n/).filter(line => line.trim());
|
const lines = text.split(/\r?\n/).filter(l => l.trim());
|
||||||
if (lines.length < 2) return null;
|
if (lines.length < 2) return null;
|
||||||
|
|
||||||
const headers = lines[0].split(';').map(h => h.trim());
|
const headers = lines[0].split(';').map(h => h.trim());
|
||||||
const data = [];
|
const data = [];
|
||||||
|
|
||||||
for (let i = 1; i < lines.length; i++) {
|
for (let i = 1; i < lines.length; i++) {
|
||||||
const values = lines[i].split(';');
|
const vals = lines[i].split(';');
|
||||||
if (values.length < 3) continue;
|
if (vals.length < 3) continue;
|
||||||
|
|
||||||
const row = {};
|
const row = {};
|
||||||
for (let j = 0; j < headers.length; j++) {
|
headers.forEach((h, j) => { if (j < vals.length) row[h] = vals[j]; });
|
||||||
if (j < values.length) {
|
|
||||||
row[headers[j]] = values[j];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
data.push(row);
|
data.push(row);
|
||||||
}
|
}
|
||||||
|
|
||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
function parseExcel(arrayBuffer) {
|
function parseExcel(buf) {
|
||||||
try {
|
const wb = XLSX.read(new Uint8Array(buf), { type: 'array' });
|
||||||
const data = new Uint8Array(arrayBuffer);
|
const ws = wb.Sheets[wb.SheetNames[0]];
|
||||||
const workbook = XLSX.read(data, { type: 'array' });
|
const json = XLSX.utils.sheet_to_json(ws, { header: 1 });
|
||||||
const sheetName = workbook.SheetNames[0];
|
const headers = (json[0] || []).map(h => String(h).trim());
|
||||||
const worksheet = workbook.Sheets[sheetName];
|
|
||||||
const json = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
|
|
||||||
|
|
||||||
const headers = json[0] ? json[0].map(h => {
|
|
||||||
if (typeof h === 'string') return h.trim();
|
|
||||||
return String(h).trim();
|
|
||||||
}) : [];
|
|
||||||
|
|
||||||
const data = [];
|
const data = [];
|
||||||
for (let i = 1; i < json.length; i++) {
|
for (let i = 1; i < json.length; i++) {
|
||||||
if (!json[i] || json[i].length === 0) continue;
|
if (!json[i] || !json[i].length) continue;
|
||||||
|
|
||||||
const row = {};
|
const row = {};
|
||||||
for (let j = 0; j < headers.length; j++) {
|
headers.forEach((h, j) => { if (j < json[i].length) row[h] = json[i][j]; });
|
||||||
if (j < json[i].length) {
|
|
||||||
row[headers[j]] = json[i][j];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
data.push(row);
|
data.push(row);
|
||||||
}
|
}
|
||||||
|
|
||||||
return data;
|
return data;
|
||||||
} catch (err) {
|
|
||||||
console.error('Ошибка парсинга Excel:', err);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function processUploadedData(uploadedData, fileType) {
|
function processData(rows) {
|
||||||
try {
|
const emps = [];
|
||||||
const processedEmployees = [];
|
for (const row of rows) {
|
||||||
|
|
||||||
for (const row of uploadedData) {
|
|
||||||
const emp = {
|
const emp = {
|
||||||
tab: row['Таб.№'] || row['tab'] || row['Табельный'] || '',
|
tab: row['Таб.№'] || row['tab'] || row['Табельный'] || '',
|
||||||
lastName: row['ФИО'] ? row['ФИО'].split(' ')[0] : '',
|
fullName: row['ФИО'] || '',
|
||||||
firstName: row['ФИО'] && row['ФИО'].includes(' ') ? row['ФИО'].split(' ')[1].split(' ')[0] : '',
|
|
||||||
patronymic: row['ФИО'] && row['ФИО'].split(' ').length > 2 ? row['ФИО'].split(' ')[2] : '',
|
|
||||||
fullName: row['ФИО'] || row['ФИО'] || '',
|
|
||||||
city: row['Город'] || '',
|
city: row['Город'] || '',
|
||||||
department: row['Подразделение'] || '',
|
department: row['Подразделение'] || '',
|
||||||
position: row['Должность'] || row['Штатная должность'] || '',
|
position: row['Должность'] || row['Штатная должность'] || '',
|
||||||
courses: []
|
courses: []
|
||||||
};
|
};
|
||||||
|
|
||||||
if (!emp.tab || !emp.fullName) continue;
|
if (!emp.tab || !emp.fullName) continue;
|
||||||
|
|
||||||
const courseHeaders = ['Курс1', 'Курс2', 'Курс3', 'Курс4', 'Курс5'];
|
for (let i = 1; i <= 20; i++) {
|
||||||
const statusHeaders = ['Статус1', 'Статус2', 'Статус3', 'Статус4', 'Статус5'];
|
const name = row['Курс' + i] || row['Курс ' + i];
|
||||||
const dateHeaders = ['Дата1', 'Дата2', 'Дата3', 'Дата4', 'Дата5'];
|
if (!name) break;
|
||||||
|
const status = (row['Статус' + i] || row['Статус ' + i] || '').toLowerCase();
|
||||||
|
const dateStr = row['Дата' + i] || row['Дата ' + i] || '';
|
||||||
|
const completed = status === 'пройдено' || status === 'yes' || status === 'true' || status === '1';
|
||||||
|
const course = { courseId: i, courseName: name, level: 1, completed, completedDate: null, nextDate: null, overdue: false, daysOverdue: 0 };
|
||||||
|
|
||||||
let courseIndex = 1;
|
if (completed && dateStr) {
|
||||||
for (const header of courseHeaders) {
|
let d, m, y;
|
||||||
const courseName = row[header];
|
if (typeof dateStr === 'number') {
|
||||||
if (!courseName) break;
|
const excelDate = new Date((dateStr - 25569) * 86400000);
|
||||||
|
d = String(excelDate.getDate()).padStart(2, '0');
|
||||||
const status = row[statusHeaders[courseIndex - 1]] || row[`Статус ${courseIndex}`] || '';
|
m = String(excelDate.getMonth() + 1).padStart(2, '0');
|
||||||
const dateStr = row[dateHeaders[courseIndex - 1]] || row[`Дата ${courseIndex}`] || '';
|
y = excelDate.getFullYear();
|
||||||
|
} else {
|
||||||
const course = {
|
const match = String(dateStr).match(/(\d{1,2})[\.\/\-](\d{1,2})[\.\/\-](\d{2,4})/);
|
||||||
courseId: courseIndex,
|
if (match) { d = match[1].padStart(2, '0'); m = match[2].padStart(2, '0'); y = match[3].length === 2 ? '20' + match[3] : match[3]; }
|
||||||
courseName: courseName,
|
}
|
||||||
level: Math.floor(Math.random() * 2) + 1,
|
if (d && m && y) {
|
||||||
completed: status.toLowerCase() === 'пройдено' || status.toLowerCase() === 'yes' || status.toLowerCase() === 'true',
|
course.completedDate = y + '-' + m + '-' + d;
|
||||||
completedDate: dateStr && dateStr.match(/\d{2}\.\d{2}\.\d{4}/) ? dateStr.match(/\d{2}\.\d{2}\.\d{4}/)[0] : '',
|
const next = new Date(+y, +m - 1, +d);
|
||||||
nextDate: '',
|
next.setMonth(next.getMonth() + 12);
|
||||||
overdue: false,
|
course.nextDate = next.toISOString().split('T')[0];
|
||||||
daysOverdue: 0
|
course.overdue = next < new Date();
|
||||||
};
|
course.daysOverdue = course.overdue ? Math.floor((new Date() - next) / 86400000) : 0;
|
||||||
|
}
|
||||||
if (course.completed && course.completedDate) {
|
|
||||||
const [day, month, year] = course.completedDate.split('.');
|
|
||||||
const completedDate = new Date(`${year}-${month}-${day}`);
|
|
||||||
course.nextDate = new Date(completedDate);
|
|
||||||
course.nextDate.setMonth(course.nextDate.getMonth() + 12);
|
|
||||||
course.nextDate = course.nextDate.toISOString().split('T')[0];
|
|
||||||
|
|
||||||
const today = new Date();
|
|
||||||
course.overdue = new Date(course.nextDate) < today;
|
|
||||||
course.daysOverdue = course.overdue ? Math.floor((today - new Date(course.nextDate)) / 86400000) : 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
emp.courses.push(course);
|
emp.courses.push(course);
|
||||||
courseIndex++;
|
|
||||||
}
|
}
|
||||||
|
emps.push(emp);
|
||||||
processedEmployees.push(emp);
|
|
||||||
}
|
|
||||||
|
|
||||||
EMPLOYEES.length = 0;
|
|
||||||
EMPLOYEES.push(...processedEmployees);
|
|
||||||
|
|
||||||
saveUploadedDataToLocalStorage(processedEmployees, fileType);
|
|
||||||
updateDashboardAfterUpload();
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
showUploadMessage('Ошибка обработки данных: ' + error.message, 'error');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function saveUploadedDataToLocalStorage(data, fileType) {
|
|
||||||
try {
|
|
||||||
const savedData = {
|
|
||||||
employees: data,
|
|
||||||
fileType: fileType,
|
|
||||||
timestamp: new Date().toISOString(),
|
|
||||||
version: '1.0'
|
|
||||||
};
|
|
||||||
|
|
||||||
localStorage.setItem('tb_assistant_uploaded_data', JSON.stringify(savedData));
|
|
||||||
localStorage.setItem('tb_assistant_last_upload', new Date().toISOString());
|
|
||||||
|
|
||||||
showUploadMessage('Данные успешно загружены и сохранены!', 'success');
|
|
||||||
} catch (error) {
|
|
||||||
showUploadMessage('Данные загружены, но не сохранены в локальное хранилище: ' + error.message, 'warning');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function updateDashboardAfterUpload() {
|
|
||||||
if (currentUser && isAdmin) {
|
|
||||||
if (document.getElementById('tab-dashboard').classList.contains('hidden')) {
|
|
||||||
showTab('dashboard');
|
|
||||||
}
|
}
|
||||||
|
EMPLOYEES = emps;
|
||||||
|
localStorage.setItem('tb_data', JSON.stringify(emps));
|
||||||
renderDashboard();
|
renderDashboard();
|
||||||
renderCityStats();
|
renderCityStats();
|
||||||
if (document.getElementById('admin-panel')) {
|
|
||||||
document.getElementById('admin-panel').classList.remove('hidden');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function showUploadMessage(message, type) {
|
function msg(text, type) {
|
||||||
const container = document.getElementById('upload-results');
|
const c = document.getElementById('upload-results');
|
||||||
if (!container) return;
|
const d = document.createElement('div');
|
||||||
|
d.className = 'msg ' + (type === 'ok' ? 'msg-ok' : 'msg-err');
|
||||||
const msgDiv = document.createElement('div');
|
d.textContent = text;
|
||||||
msgDiv.className = `p-3 mb-2 rounded text-sm ${type === 'error' ? 'bg-red-50 text-red-700 border border-red-200' : type === 'success' ? 'bg-green-50 text-green-700 border border-green-200' : 'bg-yellow-50 text-yellow-700 border border-yellow-200'}`;
|
c.prepend(d);
|
||||||
msgDiv.textContent = message;
|
if (type === 'ok') setTimeout(() => d.remove(), 5000);
|
||||||
|
|
||||||
container.insertBefore(msgDiv, container.firstChild);
|
|
||||||
|
|
||||||
if (type === 'success') {
|
|
||||||
setTimeout(() => {
|
|
||||||
if (msgDiv.parentNode) msgDiv.parentNode.removeChild(msgDiv);
|
|
||||||
}, 5000);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ========== ДАШБОРД ==========
|
// ========== ДАШБОРД ==========
|
||||||
function renderDashboard() {
|
function renderDashboard() {
|
||||||
const totalEmp = EMPLOYEES.length;
|
const total = EMPLOYEES.length;
|
||||||
const totalCourses = EMPLOYEES.reduce((sum, e) => sum + e.courses.length, 0);
|
const allCourses = EMPLOYEES.reduce((s, e) => s + e.courses.length, 0);
|
||||||
const completed = EMPLOYEES.reduce((sum, e) => sum + e.courses.filter(c => c.completed).length, 0);
|
const done = EMPLOYEES.reduce((s, e) => s + e.courses.filter(c => c.completed).length, 0);
|
||||||
const overdue = EMPLOYEES.reduce((sum, e) => sum + e.courses.filter(c => c.overdue).length, 0);
|
const ov = EMPLOYEES.reduce((s, e) => s + e.courses.filter(c => c.overdue).length, 0);
|
||||||
const notStarted = EMPLOYEES.reduce((sum, e) => sum + e.courses.filter(c => !c.completed).length, 0);
|
const notStarted = EMPLOYEES.reduce((s, e) => s + e.courses.filter(c => !c.completed).length, 0);
|
||||||
const progress = totalCourses > 0 ? Math.round((completed / totalCourses) * 100) : 0;
|
const pct = allCourses ? Math.round((done / allCourses) * 100) : 0;
|
||||||
|
|
||||||
document.getElementById('dash-stats').innerHTML = `
|
document.getElementById('dash-stats').innerHTML =
|
||||||
<div class="card text-center"><div class="text-3xl font-bold">${totalEmp}</div><div class="text-sm text-gray-500">Сотрудников</div></div>
|
'<div class="card stat-card"><div class="stat-num">' + total + '</div><div class="stat-label">Сотрудников</div></div>' +
|
||||||
<div class="card text-center"><div class="text-3xl font-bold">${progress}%</div><div class="text-sm text-gray-500">Выполнено</div></div>
|
'<div class="card stat-card"><div class="stat-num">' + pct + '%</div><div class="stat-label">Выполнено</div></div>' +
|
||||||
<div class="card text-center"><div class="text-3xl font-bold text-red-500">${overdue}</div><div class="text-sm text-gray-500">Просрочено</div></div>
|
'<div class="card stat-card"><div class="stat-num" style="color:#ef4444">' + ov + '</div><div class="stat-label">Просрочено</div></div>' +
|
||||||
<div class="card text-center"><div class="text-3xl font-bold text-yellow-500">${notStarted}</div><div class="text-sm text-gray-500">Не начато</div></div>
|
'<div class="card stat-card"><div class="stat-num" style="color:#f59e0b">' + notStarted + '</div><div class="stat-label">Не начато</div></div>';
|
||||||
`;
|
|
||||||
|
|
||||||
const cityStats = CITIES.map(city => {
|
const cs = CITIES.map(city => {
|
||||||
const emps = EMPLOYEES.filter(e => e.city === city);
|
const emps = EMPLOYEES.filter(e => e.city === city);
|
||||||
const ov = emps.reduce((sum, e) => sum + e.courses.filter(c => c.overdue).length, 0);
|
const o = emps.reduce((s, e) => s + e.courses.filter(c => c.overdue).length, 0);
|
||||||
const total = emps.reduce((sum, e) => sum + e.courses.length, 0);
|
const t = emps.reduce((s, e) => s + e.courses.length, 0);
|
||||||
return { city, overdue: ov, pct: total > 0 ? Math.round((ov / total) * 100) : 0 };
|
return { city, overdue: o, pct: t ? Math.round((o / t) * 100) : 0 };
|
||||||
}).sort((a, b) => b.pct - a.pct);
|
}).sort((a, b) => b.pct - a.pct);
|
||||||
|
|
||||||
document.getElementById('dash-problems').innerHTML = cityStats.map((s, i) =>
|
document.getElementById('dash-problems').innerHTML = cs.map((s, i) =>
|
||||||
`<div class="flex justify-between items-center py-2 ${i < cityStats.length - 1 ? 'border-b' : ''}">
|
'<div style="display:flex;justify-content:space-between;padding:8px 0' + (i < cs.length - 1 ? ';border-bottom:1px solid #f1f5f9' : '') + '">' +
|
||||||
<span>${i + 1}. ${s.city}</span>
|
'<span>' + (i + 1) + '. ' + s.city + '</span><span class="danger">' + s.pct + '% просрочено (' + s.overdue + ')</span></div>'
|
||||||
<span class="status-danger">${s.pct}% просрочено (${s.overdue})</span>
|
|
||||||
</div>`
|
|
||||||
).join('');
|
).join('');
|
||||||
|
|
||||||
const courseStats = COURSES.map(c => {
|
const crs = COURSES.map(c => {
|
||||||
const total = EMPLOYEES.length;
|
|
||||||
const notDone = EMPLOYEES.filter(e => !e.courses.find(cc => cc.courseId === c.id && cc.completed)).length;
|
const notDone = EMPLOYEES.filter(e => !e.courses.find(cc => cc.courseId === c.id && cc.completed)).length;
|
||||||
return { name: c.name, notDone, pct: Math.round((notDone / total) * 100) };
|
return { name: c.name, pct: Math.round((notDone / total) * 100) };
|
||||||
}).sort((a, b) => b.pct - a.pct).slice(0, 5);
|
}).sort((a, b) => b.pct - a.pct).slice(0, 5);
|
||||||
|
|
||||||
document.getElementById('dash-courses').innerHTML = courseStats.map((s, i) =>
|
document.getElementById('dash-courses').innerHTML = crs.map((s, i) =>
|
||||||
`<div class="flex justify-between items-center py-2 ${i < courseStats.length - 1 ? 'border-b' : ''}">
|
'<div style="display:flex;justify-content:space-between;padding:8px 0;font-size:13px' + (i < crs.length - 1 ? ';border-bottom:1px solid #f1f5f9' : '') + '">' +
|
||||||
<span class="text-sm">${i + 1}. ${s.name}</span>
|
'<span>' + (i + 1) + '. ' + s.name + '</span><span class="danger">' + s.pct + '%</span></div>'
|
||||||
<span class="status-danger text-sm">${s.pct}%</span>
|
|
||||||
</div>`
|
|
||||||
).join('');
|
).join('');
|
||||||
}
|
}
|
||||||
|
|
||||||
// ========== ВЫГРУЗКА ==========
|
// ========== ВЫГРУЗКА ==========
|
||||||
function exportData(type) {
|
function exportData(type) {
|
||||||
const container = document.getElementById('export-results');
|
const c = document.getElementById('export-results');
|
||||||
let html = '<div class="card overflow-x-auto">';
|
let h = '<div class="card">';
|
||||||
let data = [];
|
let data = [];
|
||||||
|
|
||||||
if (type === 'overdue') {
|
if (type === 'overdue') {
|
||||||
html += '<h3 class="font-bold mb-3">⏰ Просроченные обучения</h3>';
|
h += '<h3 style="margin-bottom:12px">⏰ Просроченные обучения</h3>';
|
||||||
for (const emp of EMPLOYEES) {
|
EMPLOYEES.forEach(e => e.courses.filter(c => c.overdue).forEach(c =>
|
||||||
for (const c of emp.courses.filter(c => c.overdue)) {
|
data.push({ tab: e.tab, fio: e.fullName, city: e.city, course: c.courseName, completed: c.completedDate, overdue: c.nextDate, days: c.daysOverdue })
|
||||||
data.push({ tab: emp.tab, fio: emp.fullName, city: emp.city, course: c.courseName, completed: c.completedDate, overdue: c.nextDate, days: c.daysOverdue });
|
));
|
||||||
}
|
|
||||||
}
|
|
||||||
data.sort((a, b) => b.days - a.days);
|
data.sort((a, b) => b.days - a.days);
|
||||||
} else if (type === 'city') {
|
} else if (type === 'city') {
|
||||||
html += '<h3 class="font-bold mb-3">🏙️ По филиалам</h3>';
|
h += '<h3 style="margin-bottom:12px">🏙️ По филиалам</h3>';
|
||||||
for (const emp of EMPLOYEES) {
|
EMPLOYEES.forEach(e => e.courses.forEach(c =>
|
||||||
for (const c of emp.courses) {
|
data.push({ tab: e.tab, fio: e.fullName, city: e.city, course: c.courseName, status: c.completed ? (c.overdue ? 'Просрочено' : 'Пройдено') : 'Не пройдено' })
|
||||||
data.push({ tab: emp.tab, fio: emp.fullName, city: emp.city, course: c.courseName, status: c.completed ? (c.overdue ? 'Просрочено' : 'Пройдено') : 'Не пройдено' });
|
));
|
||||||
}
|
|
||||||
}
|
|
||||||
} else if (type === 'employee') {
|
} else if (type === 'employee') {
|
||||||
html += '<h3 class="font-bold mb-3">👤 По сотрудникам</h3>';
|
h += '<h3 style="margin-bottom:12px">👤 По сотрудникам</h3>';
|
||||||
for (const emp of EMPLOYEES) {
|
EMPLOYEES.forEach(e => {
|
||||||
const completed = emp.courses.filter(c => c.completed).length;
|
const done = e.courses.filter(c => c.completed).length;
|
||||||
const overdue = emp.courses.filter(c => c.overdue).length;
|
const ov = e.courses.filter(c => c.overdue).length;
|
||||||
data.push({ tab: emp.tab, fio: emp.fullName, city: emp.city, department: emp.department, total: emp.courses.length, completed, overdue, progress: Math.round((completed / emp.courses.length) * 100) + '%' });
|
data.push({ tab: e.tab, fio: e.fullName, city: e.city, dept: e.department, total: e.courses.length, done, ov, pct: Math.round((done / e.courses.length) * 100) + '%' });
|
||||||
}
|
});
|
||||||
} else if (type === 'summary') {
|
} else if (type === 'summary') {
|
||||||
html += '<h3 class="font-bold mb-3">📋 Сводный отчёт по филиалам</h3>';
|
h += '<h3 style="margin-bottom:12px">📋 Сводный отчёт</h3>';
|
||||||
for (const city of CITIES) {
|
CITIES.forEach(city => {
|
||||||
const emps = EMPLOYEES.filter(e => e.city === city);
|
const emps = EMPLOYEES.filter(e => e.city === city);
|
||||||
const total = emps.reduce((sum, e) => sum + e.courses.length, 0);
|
const t = emps.reduce((s, e) => s + e.courses.length, 0);
|
||||||
const completed = emps.reduce((sum, e) => sum + e.courses.filter(c => c.completed).length, 0);
|
const d = emps.reduce((s, e) => s + e.courses.filter(c => c.completed).length, 0);
|
||||||
const overdue = emps.reduce((sum, e) => sum + e.courses.filter(c => c.overdue).length, 0);
|
const o = emps.reduce((s, e) => s + e.courses.filter(c => c.overdue).length, 0);
|
||||||
data.push({ city, employees: emps.length, totalCourses: total, completed, overdue, progress: total > 0 ? Math.round((completed / total) * 100) + '%' : '0%' });
|
data.push({ city, employees: emps.length, total: t, done, overdue: o, pct: t ? Math.round((d / t) * 100) + '%' : '0%' });
|
||||||
}
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (data.length === 0) {
|
if (!data.length) { h += '<p style="color:#64748b">Нет данных</p>'; }
|
||||||
html += '<p class="text-gray-500">Нет данных для выгрузки</p>';
|
else {
|
||||||
} else {
|
const hdrs = Object.keys(data[0]);
|
||||||
const headers = Object.keys(data[0]);
|
h += '<table><thead><tr>' + hdrs.map(x => '<th>' + x + '</th>').join('') + '</tr></thead><tbody>';
|
||||||
html += '<table class="table"><thead><tr>' + headers.map(h => `<th>${h}</th>`).join('') + '</tr></thead><tbody>';
|
data.slice(0, 100).forEach(row => { h += '<tr>' + hdrs.map(x => '<td>' + (row[x] || '') + '</td>').join('') + '</tr>'; });
|
||||||
for (const row of data.slice(0, 100)) {
|
h += '</tbody></table>';
|
||||||
html += '<tr>' + headers.map(h => `<td>${row[h]}</td>`).join('') + '</tr>';
|
if (data.length > 100) h += '<p style="font-size:12px;color:#64748b;margin-top:8px">Показано 100 из ' + data.length + '</p>';
|
||||||
}
|
}
|
||||||
html += '</tbody></table>';
|
h += '</div>';
|
||||||
if (data.length > 100) html += `<p class="text-sm text-gray-500 mt-2">Показано 100 из ${data.length} записей</p>`;
|
c.innerHTML = h;
|
||||||
}
|
|
||||||
|
|
||||||
html += '</div>';
|
|
||||||
container.innerHTML = html;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function exportCSV() {
|
function exportCSV() {
|
||||||
let csv = 'Таб.№;ФИО;Филиал;Должность;Подразделение;Курс;Уровень;Статус;Дата обучения;Дата завершения;Следующее обучение;Просрочено дней\n';
|
let csv = 'Таб.№;ФИО;Филиал;Должность;Подразделение;Курс;Уровень;Статус;Дата обучения;Следующее;Просрочка дн.\n';
|
||||||
|
EMPLOYEES.forEach(e => e.courses.forEach(c => {
|
||||||
for (const emp of EMPLOYEES) {
|
const st = c.completed ? (c.overdue ? 'Просрочено' : 'Пройдено') : 'Не пройдено';
|
||||||
for (const c of emp.courses) {
|
csv += e.tab + ';' + e.fullName + ';' + e.city + ';' + e.position + ';' + e.department + ';' + c.courseName + ';' + c.level + ';' + st + ';' + (c.completedDate || '') + ';' + (c.nextDate || '') + ';' + (c.daysOverdue || 0) + '\n';
|
||||||
const status = c.completed ? (c.overdue ? 'Просрочено' : 'Пройдено') : 'Не пройдено';
|
}));
|
||||||
csv += `${emp.tab};${emp.fullName};${emp.city};${emp.position};${emp.department};${c.courseName};${c.level};${status};${c.completedDate || ''};${c.completedDate || ''};${c.nextDate || ''};${c.daysOverdue || 0}\n`;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const blob = new Blob(['\uFEFF' + csv], { type: 'text/csv;charset=utf-8;' });
|
const blob = new Blob(['\uFEFF' + csv], { type: 'text/csv;charset=utf-8;' });
|
||||||
const url = URL.createObjectURL(blob);
|
|
||||||
const a = document.createElement('a');
|
const a = document.createElement('a');
|
||||||
a.href = url;
|
a.href = URL.createObjectURL(blob);
|
||||||
a.download = 'training_report_' + new Date().toISOString().split('T')[0] + '.csv';
|
a.download = 'training_' + new Date().toISOString().split('T')[0] + '.csv';
|
||||||
a.click();
|
a.click();
|
||||||
URL.revokeObjectURL(url);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ========== ИНИЦИАЛИЗАЦИЯ ==========
|
||||||
|
document.addEventListener('DOMContentLoaded', function() {
|
||||||
|
const saved = localStorage.getItem('tb_data');
|
||||||
|
if (saved) { try { EMPLOYEES = JSON.parse(saved); } catch(e) {} }
|
||||||
|
renderDashboard();
|
||||||
|
renderCityStats();
|
||||||
|
});
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user