Repository navigation
Expand file tree
/
Copy pathadmin.html
More file actions
963 lines (882 loc) · 47 KB
/
Copy pathadmin.html
File metadata and controls
963 lines (882 loc) · 47 KB
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
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Админ-панель | Чек-лист обхода аудиторий</title>
<link rel="stylesheet" href="style/style.css">
<link rel="stylesheet" href="style/admin.css">
<link rel="stylesheet" href="style/theme.css">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
</head>
<body>
<button class="mobile-menu-btn" id="mobileMenuBtn" onclick="toggleSidebar()">
<span></span>
<span></span>
<span></span>
</button>
<div class="admin-container">
<aside class="admin-sidebar" id="adminSidebar">
<div class="admin-logo">
<img src="./image/logo.gif" alt="ХПК" style="height: 40px; margin-bottom: 10px; display: block;">
<h2>Админ-панель</h2>
</div>
<nav class="admin-nav">
<a href="#" class="nav-item active" data-page="dashboard" onclick="navigateTo('dashboard')">
<span>Дашборд</span>
</a>
<a href="#" class="nav-item" data-page="users" onclick="navigateTo('users')">
<span>Пользователи</span>
</a>
<a href="#" class="nav-item" data-page="rooms" onclick="navigateTo('rooms')">
<span>Аудитории</span>
</a>
<a href="#" class="nav-item" data-page="issues" onclick="navigateTo('issues')">
<span>Проблемы</span>
</a>
<a href="#" class="nav-item" data-page="inventory" onclick="navigateTo('inventory')">
<span>Ведомость</span>
</a>
<a href="#" class="nav-item" data-page="logs" onclick="navigateTo('logs')">
<span>Логи</span>
</a>
<a href="#" class="nav-item" data-page="audit" onclick="navigateTo('audit')">
<span>Аудит доступов</span>
</a>
<a href="#" class="nav-item" data-page="analytics" onclick="navigateTo('analytics')">
<span>Аналитика</span>
</a>
<a href="#" class="nav-item" data-page="settings" onclick="navigateTo('settings')">
<span>Настройки</span>
</a>
</nav>
<div class="admin-user">
<div class="user-info">
<div class="user-avatar" id="adminAvatar">A</div>
<div>
<div class="user-name" id="adminName">Администратор</div>
<div class="user-role">Администратор</div>
</div>
</div>
<button class="logout-btn" onclick="logout()">Выход</button>
</div>
</aside>
<div class="sidebar-overlay" id="sidebarOverlay" onclick="closeSidebar()"></div>
<main class="admin-content">
<div class="page active" id="dashboard">
<h1>Дашборд</h1>
<div style="margin-bottom: 1rem; display: flex; gap: 10px; flex-wrap: wrap; align-items: center;">
<span style="font-weight: 600; color: var(--hpk-blue);">Экспорт отчета:</span>
<button class="btn btn-primary" onclick="downloadReport('pdf')">Скачать PDF</button>
<button class="btn btn-primary" onclick="downloadReport('excel')">Скачать Excel</button>
<button class="btn btn-primary" onclick="downloadReport('csv')">Скачать CSV</button>
<button class="btn btn-primary" onclick="downloadReport('txt')">Скачать TXT</button>
</div>
<div class="stats-grid" id="dashboardStats"></div>
<div class="dashboard-charts">
<div class="chart-card">
<h3>Последние проверки</h3>
<ul id="recentChecks"><li>Загрузка...</li></ul>
</div>
<div class="chart-card">
<h3>Последние проблемы</h3>
<ul id="recentIssues"><li>Загрузка...</li></ul>
</div>
</div>
</div>
<div class="page" id="users">
<div class="page-header">
<h1>Управление пользователями</h1>
<button class="btn btn-primary" onclick="showAddUserModal()">+ Добавить пользователя</button>
</div>
<div class="table-responsive">
<table class="data-table">
<thead>
<tr>
<th>ID</th>
<th>Логин</th>
<th>ФИО</th>
<th>Email</th>
<th>Роль</th>
<th>Статус</th>
<th>Действия</th>
</tr>
</thead>
<tbody id="usersTableBody"></tbody>
</table>
</div>
</div>
<div class="page" id="rooms">
<div class="page-header">
<h1>Управление аудиториями</h1>
<div class="page-actions">
<button class="btn btn-secondary" onclick="showBulkAddModal()">Массовое добавление</button>
<button class="btn btn-primary" onclick="showAddRoomModal()">+ Добавить аудиторию</button>
<button class="btn btn-secondary btn-sm" onclick="showQR('${room.room_number}')">QR</button>
</div>
</div>
<div class="filter-bar">
<select id="floorFilter" onchange="loadRooms()" class="modern-select" style="width: auto;">
<option value="">Все этажи</option>
<option value="1">1 этаж</option>
<option value="2">2 этаж</option>
<option value="3">3 этаж</option>
<option value="4">4 этаж</option>
</select>
<input type="text" id="roomSearch" placeholder="Поиск аудитории..." onkeyup="loadRooms()" class="modern-input" style="width: auto;">
</div>
<div class="table-responsive">
<table class="data-table">
<thead>
<tr>
<th>ID</th>
<th>Номер</th>
<th>Корпус</th>
<th>Этаж</th>
<th>Описание</th>
<th>Действия</th>
</tr>
</thead>
<tbody id="roomsTableBody"></tbody>
</table>
</div>
</div>
<div class="page" id="issues">
<div class="page-header">
<h1>Управление проблемами</h1>
<select id="issueFilter" onchange="loadIssues()" class="modern-select" style="width: auto;">
<option value="open">Открытые</option>
<option value="resolved">Решенные</option>
<option value="all">Все</option>
</select>
<button class="btn btn-primary" onclick="exportFullReport()">Скачать полный отчет (CSV)</button>
</div>
<div class="table-responsive">
<table class="data-table">
<thead>
<tr>
<th>ID</th>
<th>Аудитория</th>
<th>Тип</th>
<th>Описание</th>
<th>Статус</th>
<th>Действия</th>
</tr>
</thead>
<tbody id="issuesTableBody"></tbody>
</table>
</div>
</div>
<div class="page" id="inventory">
<div class="page-header">
<h1>Инвентарная ведомость</h1>
<button class="btn btn-primary" onclick="exportInventory()">Скачать CSV</button>
</div>
<div class="table-responsive">
<table class="data-table">
<thead>
<tr>
<th>Инв. номер</th>
<th>Наименование</th>
<th>Тип</th>
<th>Аудитория</th>
<th>Этаж</th>
<th>Статус</th>
</tr>
</thead>
<tbody id="inventoryTableBody"></tbody>
</table>
</div>
</div>
<div class="page" id="logs">
<h1>Логи действий</h1>
<div class="table-responsive">
<table class="data-table">
<thead>
<tr>
<th>ID</th>
<th>Время</th>
<th>Пользователь</th>
<th>Действие</th>
<th>Описание</th>
</tr>
</thead>
<tbody id="logsTableBody"></tbody>
</table>
</div>
</div>
<div class="page" id="audit">
<h1>Аудит логинов и паролей</h1>
<div class="table-responsive">
<table class="data-table">
<thead>
<tr>
<th>Дата</th>
<th>Администратор</th>
<th>Целевой пользователь</th>
<th>Действие</th>
<th>Было</th>
<th>Стало</th>
<th>IP</th>
</tr>
</thead>
<tbody id="auditTableBody"></tbody>
</table>
</div>
</div>
<div class="page" id="analytics">
<h1>Аналитика и статистика</h1>
<div class="stats-grid" style="margin-bottom: 2rem;">
<div class="stat-card">
<h3>Выполнение плана обхода</h3>
<div class="stat-value" id="completionRate">0%</div>
<div style="font-size: 0.8rem; color: #6b7280; margin-top: 5px;">За текущий месяц</div>
</div>
<div class="stat-card">
<h3>Среднее время решения проблем</h3>
<div class="stat-value" id="avgResolveTime">0 ч</div>
</div>
</div>
<div class="dashboard-charts" style="grid-template-columns: 1fr 1fr;">
<div class="chart-card">
<h3>Проблемы по типам</h3>
<div class="chart-container">
<canvas id="issuesChart"></canvas>
</div>
</div>
<div class="chart-card">
<h3>Проверки за последние 7 дней</h3>
<div class="chart-container">
<canvas id="checksChart"></canvas>
</div>
</div>
</div>
</div>
<div class="page" id="settings">
<h1>Настройки системы</h1>
<button class="btn btn-primary" onclick="saveSettings()" style="margin-bottom: 1rem;">Сохранить настройки</button>
<div class="settings-form" id="settingsForm"></div>
</div>
</main>
</div>
<!-- Модальные окна -->
<div class="modal" id="userModal">
<div class="modal-content">
<div class="modal-header">
<h2 id="userModalTitle">Добавить пользователя</h2>
<button class="modal-close" onclick="closeModal('userModal')">×</button>
</div>
<div class="modal-body">
<input type="hidden" id="editUserId">
<div class="form-group">
<label>Логин *</label>
<input type="text" id="editUsername" required class="modern-input">
</div>
<div class="form-group">
<label>ФИО *</label>
<input type="text" id="editFullName" required class="modern-input">
</div>
<div class="form-group">
<label>Email</label>
<input type="email" id="editEmail" class="modern-input">
</div>
<div class="form-group">
<label>Пароль</label>
<input type="password" id="editPassword" class="modern-input">
</div>
<div class="form-group">
<label>Роль</label>
<select id="editRole" class="modern-select">
<option value="employee">Сотрудник</option>
<option value="admin">Администратор</option>
</select>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-secondary" onclick="closeModal('userModal')">Отмена</button>
<button class="btn btn-primary" onclick="saveUser()">Сохранить</button>
</div>
</div>
</div>
<div class="modal" id="roomModal">
<div class="modal-content">
<div class="modal-header">
<h2 id="roomModalTitle">Добавить аудиторию</h2>
<button class="modal-close" onclick="closeModal('roomModal')">×</button>
</div>
<div class="modal-body">
<input type="hidden" id="editRoomId">
<div class="form-group">
<label>Номер *</label>
<input type="text" id="editRoomNumber" required class="modern-input">
</div>
<div class="form-group">
<label>Корпус</label>
<input type="text" id="editBuilding" value="Главный корпус" class="modern-input">
</div>
<div class="form-group">
<label>Этаж *</label>
<input type="number" id="editFloor" required class="modern-input" min="1" max="10">
</div>
<div class="form-group">
<label>Описание</label>
<textarea id="editDescription" class="modern-input" rows="3"></textarea>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-secondary" onclick="closeModal('roomModal')">Отмена</button>
<button class="btn btn-primary" onclick="saveRoom()">Сохранить</button>
</div>
</div>
</div>
<div class="modal" id="bulkModal">
<div class="modal-content">
<div class="modal-header">
<h2>Массовое добавление</h2>
<button class="modal-close" onclick="closeModal('bulkModal')">×</button>
</div>
<div class="modal-body">
<div class="form-group">
<label>Корпус</label>
<input type="text" id="bulkBuilding" value="Главный корпус" class="modern-input">
</div>
<div class="form-group">
<label>Этаж</label>
<input type="number" id="bulkFloor" class="modern-input" min="1" max="10">
</div>
<div class="form-group">
<label>Диапазон номеров</label>
<div style="display: flex; gap: 10px; align-items: center;">
<input type="text" id="bulkStart" placeholder="Начало" class="modern-input">
<span>-</span>
<input type="text" id="bulkEnd" placeholder="Конец" class="modern-input">
</div>
</div>
<button class="btn btn-primary" onclick="bulkAddRooms()">Добавить</button>
</div>
</div>
</div>
<script>
// Проверка авторизации
fetch('php/api_auth.php?action=check')
.then(response => response.json())
.then(data => {
if (!data.authenticated || !data.user) {
window.location.replace('login.html');
return;
}
if (data.user.role !== 'admin') {
window.location.replace('index.html');
return;
}
document.getElementById('adminName').textContent = data.user.full_name;
document.getElementById('adminAvatar').textContent =
data.user.full_name.split(' ').map(n => n[0]).join('').substring(0, 2).toUpperCase();
loadDashboard();
})
.catch(error => window.location.replace('login.html'));
function logout() {
fetch('php/api_auth.php?action=logout', { method: 'POST' })
.then(() => window.location.replace('login.html'));
}
// Мобильное меню
function toggleSidebar() {
document.getElementById('adminSidebar').classList.toggle('open');
document.getElementById('sidebarOverlay').classList.toggle('show');
}
function closeSidebar() {
document.getElementById('adminSidebar').classList.remove('open');
document.getElementById('sidebarOverlay').classList.remove('show');
}
// Навигация
function navigateTo(page) {
document.querySelectorAll('.nav-item').forEach(n => n.classList.remove('active'));
const activeLink = document.querySelector(`[data-page="${page}"]`);
if (activeLink) activeLink.classList.add('active');
document.querySelectorAll('.page').forEach(p => p.classList.remove('active'));
const activePage = document.getElementById(page);
if (activePage) activePage.classList.add('active');
switch (page) {
case 'dashboard': loadDashboard(); break;
case 'users': loadUsers(); break;
case 'rooms': loadRooms(); break;
case 'issues': loadIssues(); break;
case 'inventory': loadInventory(); break;
case 'logs': loadLogs(); break;
case 'audit': loadCredentialAudit(); break;
case 'analytics': loadAnalytics(); break;
case 'settings': loadSettings(); break;
}
closeSidebar();
}
// API обертка
async function apiCall(url, data = null, method = 'GET') {
try {
const options = { method, headers: { 'Content-Type': 'application/json' } };
if (data && method !== 'GET') options.body = JSON.stringify(data);
const response = await fetch(url, options);
return await response.json();
} catch (error) {
return { success: false, message: 'Ошибка соединения' };
}
}
async function loadDashboard() {
const stats = await apiCall('php/api_admin.php?action=get_statistics');
if (stats.success) {
document.getElementById('dashboardStats').innerHTML = `
<div class="stat-card"><h3>Пользователей</h3><div class="stat-value">${stats.data.total_users || 0}</div></div>
<div class="stat-card"><h3>Аудиторий</h3><div class="stat-value">${stats.data.total_rooms || 0}</div></div>
<div class="stat-card"><h3>Проверок сегодня</h3><div class="stat-value">${stats.data.today_checks || 0}</div></div>
<div class="stat-card"><h3>Открытых проблем</h3><div class="stat-value">${stats.data.open_issues || 0}</div></div>
`;
}
loadRecentChecks();
loadRecentIssues();
}
async function loadRecentChecks() {
const result = await apiCall('php/get_report.php?type=daily&date=' + new Date().toISOString().split('T')[0]);
if (result.success && result.data) {
const checks = result.data.filter(c => c.check_id !== null).slice(0, 5);
if (checks.length > 0) {
document.getElementById('recentChecks').innerHTML = checks.map(c =>
`<li>Ауд. ${c.room_number} - ${c.needs_attention == 1 ? 'Проблемы' : 'OK'} (${c.employee_name || 'Нет данных'})</li>`
).join('');
} else {
document.getElementById('recentChecks').innerHTML = '<li>Нет проверок за сегодня</li>';
}
}
}
async function loadRecentIssues() {
const result = await apiCall('php/api_admin.php?action=get_all_issues&status=open');
if (result.success && result.data) {
const issues = result.data.slice(0, 5);
if (issues.length > 0) {
document.getElementById('recentIssues').innerHTML = issues.map(i =>
`<li>Ауд. ${i.room_number} - ${i.issue_type}: ${i.description || 'Нет описания'}</li>`
).join('');
} else {
document.getElementById('recentIssues').innerHTML = '<li>Нет открытых проблем</li>';
}
}
}
async function loadUsers() {
const result = await apiCall('php/api_admin.php?action=get_users');
if (result.success) {
document.getElementById('usersTableBody').innerHTML = result.data.map(user => `
<tr>
<td>${user.id}</td>
<td>${user.username}</td>
<td>${user.full_name}</td>
<td>${user.email || '-'}</td>
<td><span class="badge ${user.role === 'admin' ? 'badge-warning' : 'badge-success'}">${user.role}</span></td>
<td><span class="badge ${user.is_active == 1 ? 'badge-success' : 'badge-danger'}">${user.is_active == 1 ? 'Активен' : 'Заблокирован'}</span></td>
<td>
<button class="btn btn-secondary btn-sm" onclick="editUser(${user.id})">Ред.</button>
<button class="btn btn-secondary btn-sm" onclick="toggleUser(${user.id})">${user.is_active == 1 ? 'Блок.' : 'Акт.'}</button>
<button class="btn btn-secondary btn-sm" onclick="deleteUser(${user.id})">Уд.</button>
</td>
</tr>
`).join('');
}
}
function showAddUserModal() {
document.getElementById('userModalTitle').textContent = 'Добавить пользователя';
document.getElementById('editUserId').value = '';
document.getElementById('editUsername').value = '';
document.getElementById('editFullName').value = '';
document.getElementById('editEmail').value = '';
document.getElementById('editPassword').value = '';
document.getElementById('userModal').classList.add('active');
}
async function editUser(id) {
const result = await apiCall('php/api_admin.php?action=get_users');
const user = result.data.find(u => u.id == id);
if (user) {
document.getElementById('userModalTitle').textContent = 'Редактировать пользователя';
document.getElementById('editUserId').value = user.id;
document.getElementById('editUsername').value = user.username;
document.getElementById('editFullName').value = user.full_name;
document.getElementById('editEmail').value = user.email || '';
document.getElementById('editPassword').value = '';
document.getElementById('editRole').value = user.role;
document.getElementById('userModal').classList.add('active');
}
}
async function saveUser() {
const data = {
username: document.getElementById('editUsername').value,
full_name: document.getElementById('editFullName').value,
email: document.getElementById('editEmail').value,
role: document.getElementById('editRole').value
};
const password = document.getElementById('editPassword').value;
if (password) data.password = password;
const id = document.getElementById('editUserId').value;
if (id) data.id = id;
const result = await apiCall(`php/api_admin.php?action=${id ? 'update_user' : 'add_user'}`, data, id ? 'PUT' : 'POST');
if (result.success) { closeModal('userModal'); loadUsers(); }
else alert(result.message || 'Ошибка');
}
async function toggleUser(id) {
if (confirm('Изменить статус?')) {
await apiCall('php/api_admin.php?action=toggle_user', { id }, 'PUT');
loadUsers();
}
}
async function deleteUser(id) {
if (confirm('Удалить пользователя?')) {
await apiCall('php/api_admin.php?action=delete_user', { id }, 'DELETE');
loadUsers();
}
}
async function loadRooms() {
const floor = document.getElementById('floorFilter').value;
const search = document.getElementById('roomSearch').value;
let url = 'php/api.php?action=get_rooms';
if (floor) url += '&floor=' + floor;
if (search) url += '&search=' + search;
const result = await apiCall(url);
if (result.success) {
document.getElementById('roomsTableBody').innerHTML = result.data.map(room => `
<tr>
<td>${room.id}</td>
<td>${room.room_number}</td>
<td>${room.building}</td>
<td>${room.floor}</td>
<td>${room.description || '-'}</td>
<td>
<button class="btn btn-secondary btn-sm" onclick="showQR('${room.room_number}')">QR</button>
<button class="btn btn-secondary btn-sm" onclick="editRoom(${room.id})">Ред.</button>
<button class="btn btn-secondary btn-sm" onclick="deleteRoom(${room.id})">Уд.</button>
</td>
</tr>
`).join('');
}
}
function showAddRoomModal() {
document.getElementById('roomModalTitle').textContent = 'Добавить аудиторию';
document.getElementById('editRoomId').value = '';
document.getElementById('editRoomNumber').value = '';
document.getElementById('editBuilding').value = 'Главный корпус';
document.getElementById('editFloor').value = '';
document.getElementById('editDescription').value = '';
document.getElementById('roomModal').classList.add('active');
}
async function editRoom(id) {
const result = await apiCall('php/api.php?action=get_rooms');
const room = result.data.find(r => r.id == id);
if (room) {
document.getElementById('roomModalTitle').textContent = 'Редактировать аудиторию';
document.getElementById('editRoomId').value = room.id;
document.getElementById('editRoomNumber').value = room.room_number;
document.getElementById('editBuilding').value = room.building;
document.getElementById('editFloor').value = room.floor;
document.getElementById('editDescription').value = room.description || '';
document.getElementById('roomModal').classList.add('active');
}
}
async function saveRoom() {
const data = {
room_number: document.getElementById('editRoomNumber').value,
building: document.getElementById('editBuilding').value,
floor: parseInt(document.getElementById('editFloor').value),
description: document.getElementById('editDescription').value
};
const id = document.getElementById('editRoomId').value;
if (id) data.id = id;
const result = await apiCall(`php/api_admin.php?action=${id ? 'update_room' : 'add_room'}`, data, id ? 'PUT' : 'POST');
if (result.success) { closeModal('roomModal'); loadRooms(); }
else alert(result.message || 'Ошибка');
}
async function deleteRoom(id) {
if (confirm('Удалить аудиторию?')) {
await apiCall('php/api_admin.php?action=delete_room', { id }, 'DELETE');
loadRooms();
}
}
function showBulkAddModal() {
document.getElementById('bulkModal').classList.add('active');
}
async function bulkAddRooms() {
const building = document.getElementById('bulkBuilding').value;
const floor = parseInt(document.getElementById('bulkFloor').value);
const start = document.getElementById('bulkStart').value;
const end = document.getElementById('bulkEnd').value;
if (!floor || !start || !end) { alert('Заполните все поля'); return; }
const rooms = [];
for (let i = parseInt(start); i <= parseInt(end); i++) {
rooms.push({ room_number: i.toString(), building, floor });
}
const result = await apiCall('php/api_admin.php?action=bulk_add_rooms', { rooms }, 'POST');
if (result.success) { alert(result.message); closeModal('bulkModal'); loadRooms(); }
}
async function loadIssues() {
const filter = document.getElementById('issueFilter').value;
const result = await apiCall(`php/api_admin.php?action=get_all_issues&status=${filter}`);
if (result.success) {
document.getElementById('issuesTableBody').innerHTML = result.data.map(issue => `
<tr>
<td>${issue.id}</td>
<td>${issue.room_number}</td>
<td>${issue.issue_type}</td>
<td>${issue.description || '-'}</td>
<td><span class="badge ${issue.is_resolved ? 'badge-success' : 'badge-danger'}">${issue.is_resolved ? 'Решено' : 'Открыто'}</span></td>
<td>
${!issue.is_resolved ?
`<button class="btn btn-secondary btn-sm" onclick="resolveIssue(${issue.id})">Решить</button>` :
`<button class="btn btn-secondary btn-sm" onclick="deleteIssue(${issue.id})">Удалить</button>`
}
</td>
</tr>
`).join('');
}
}
async function resolveIssue(id) {
await apiCall('php/api_admin.php?action=resolve_issue', { id }, 'POST');
loadIssues();
}
async function deleteIssue(id) {
if (confirm('Удалить проблему?')) {
await apiCall('php/api_admin.php?action=delete_issue', { id }, 'DELETE');
loadIssues();
}
}
async function loadInventory() {
const result = await apiCall('php/api_admin.php?action=get_inventory');
if (result.success) {
document.getElementById('inventoryTableBody').innerHTML = result.data.map(item => `
<tr>
<td>${item.inventory_number}</td>
<td>${item.name}</td>
<td>${item.type === 'pc' ? 'ПК' : item.type === 'projector' ? 'Проектор' : item.type === 'chalkboard' ? 'Доска' : 'Прочее'}</td>
<td>${item.room_number}</td>
<td>${item.floor}</td>
<td><span class="badge ${item.status === 'working' ? 'badge-success' : 'badge-danger'}">${item.status === 'working' ? 'Исправно' : 'Неисправно'}</span></td>
</tr>
`).join('');
}
}
function exportInventory() {
window.location.href = 'php/api_admin.php?action=export_inventory_csv';
}
/* Логи */
async function loadLogs() {
const result = await apiCall('php/api_admin.php?action=get_logs');
if (result.success) {
document.getElementById('logsTableBody').innerHTML = result.data.map(log => `
<tr>
<td>${log.id}</td>
<td>${log.created_at}</td>
<td>${log.username}</td>
<td>${log.action}</td>
<td>${log.description || '-'}</td>
</tr>
`).join('');
}
}
async function loadCredentialAudit() {
const result = await apiCall('php/api_admin.php?action=get_credential_audit');
if (result.success) {
document.getElementById('auditTableBody').innerHTML = result.data.map(a => `
<tr>
<td>${a.created_at}</td>
<td>${a.admin_user}</td>
<td>${a.target_user}</td>
<td>${a.action === 'password_reset' ? 'Смена пароля' : a.action === 'login_changed' ? 'Смена логина' : a.action === 'user_created' ? 'Создание' : 'Удаление'}</td>
<td>${a.old_value || '-'}</td>
<td>${a.new_value || '-'}</td>
<td>${a.ip_address || '-'}</td>
</tr>
`).join('');
}
}
/* --- Настройки --- */
async function loadSettings() {
const result = await apiCall('php/api_admin.php?action=get_settings');
if (result.success) {
document.getElementById('settingsForm').innerHTML = result.data.map(setting => `
<div class="form-group">
<label>${setting.description || setting.setting_key}</label>
<input type="text" id="setting_${setting.setting_key}" value="${setting.setting_value}" class="modern-input">
</div>
`).join('');
}
}
async function saveSettings() {
const settings = {};
document.querySelectorAll('[id^="setting_"]').forEach(input => {
settings[input.id.replace('setting_', '')] = input.value;
});
await apiCall('php/api_admin.php?action=update_settings', { settings }, 'POST');
alert('Настройки сохранены');
}
function closeModal(modalId) {
document.getElementById(modalId).classList.remove('active');
}
window.onclick = function(event) {
if (event.target.classList.contains('modal')) {
event.target.classList.remove('active');
}
}
let issuesChartInstance = null;
let checksChartInstance = null;
async function loadAnalytics() {
const stats = await apiCall('php/api_admin.php?action=get_statistics');
if (stats.success) {
const totalRooms = stats.data.total_rooms || 1;
const todayChecks = stats.data.today_checks || 0;
// Процент выполнения ( проверки сегодня / общее количество аудиторий)
let rate = Math.round((todayChecks / totalRooms) * 100);
if (rate > 100) rate = 100;
document.getElementById('completionRate').textContent = rate + '%';
}
const issuesRes = await apiCall('php/api_admin.php?action=get_all_issues&status=resolved');
if (issuesRes.success && issuesRes.data.length > 0) {
document.getElementById('avgResolveTime').textContent = '~24 ч';
} else {
document.getElementById('avgResolveTime').textContent = 'Нет данных';
}
const openIssues = await apiCall('php/api_admin.php?action=get_all_issues&status=open');
if (openIssues.success && !issuesChartInstance) {
const types = { pc: 0, projector: 0, chalk: 0, other: 0 };
openIssues.data.forEach(i => { if (types[i.issue_type] !== undefined) types[i.issue_type]++; });
const ctx = document.getElementById('issuesChart').getContext('2d');
issuesChartInstance = new Chart(ctx, {
type: 'doughnut',
data: {
labels: ['ПК', 'Проектор', 'Мел', 'Другое'],
datasets: [{
data: [types.pc, types.projector, types.chalk, types.other],
backgroundColor: ['#4f46e5', '#0ea5e9', '#f59e0b', '#ef4444']
}]
},
options: { responsive: true, maintainAspectRatio: false }
});
}
if (!checksChartInstance) {
const ctx = document.getElementById('checksChart').getContext('2d');
checksChartInstance = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб', 'Вс'],
datasets: [{
label: 'Проверено аудиторий',
data: [5, 8, 12, stats.data.today_checks || 0, 0, 0, 0], // Заглушка
backgroundColor: '#3b82f6'
}]
},
options: { responsive: true, maintainAspectRatio: false }
});
}
}
async function downloadReport(format) {
const result = await apiCall('php/api_admin.php?action=get_all_checks');
if (!result.success || !result.data) {
alert('Ошибка получения данных');
return;
}
const data = result.data;
const headers = ['Дата', 'Аудитория', 'Этаж', 'Сотрудник', 'ПК', 'Проектор', 'Мел', 'Статус'];
const rows = data.map(c => [
c.check_date,
c.room_number,
c.floor,
c.employee_name || 'Неизвестно',
c.pcs_working ? 'Исправно' : 'Сломано',
c.projector_clean ? 'Чистый' : 'Грязный',
c.chalk_available ? 'Есть' : 'Нет',
c.needs_attention ? 'Проблема' : 'ОК'
]);
if (format === 'csv' || format === 'txt') {
let content = headers.join(format === 'csv' ? ';' : '\t') + '\n';
rows.forEach(row => {
content += row.join(format === 'csv' ? ';' : '\t') + '\n';
});
const blob = new Blob(["\uFEFF" + content], { type: 'text/plain;charset=utf-8' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'Отчет_проверок_' + new Date().toISOString().split('T')[0] + '.' + format;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
else if (format === 'excel') {
const ws = XLSX.utils.aoa_to_sheet([headers, ...rows]);
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, "Отчет");
XLSX.writeFile(wb, 'Отчет_проверок_' + new Date().toISOString().split('T')[0] + '.xlsx');
}
else if (format === 'pdf') {
const printWindow = window.open('', '_blank');
// Собираем HTML через конкатенацию, чтобы не было проблем с кавычками
var html = '<html><head><title>Отчет по обходу аудиторий</title><style>';
html += 'body { font-family: Arial, sans-serif; padding: 20px; color: #333; }';
html += '.header { text-align: center; margin-bottom: 20px; border-bottom: 3px solid #4f46e5; padding-bottom: 10px; }';
html += '.header h1 { color: #1e3a8a; margin: 0 0 10px 0; font-size: 24px; }';
html += '.header p { margin: 0; color: #6b7280; font-size: 14px; }';
html += 'table { width: 100%; border-collapse: collapse; margin-top: 20px; font-size: 12px; }';
html += 'th { background-color: #4f46e5; color: white; padding: 10px; text-align: left; border: 1px solid #ddd; }';
html += 'td { padding: 8px 10px; border: 1px solid #ddd; }';
html += 'tr:nth-child(even) { background-color: #f9fafb; }';
html += '@media print { body { padding: 0; } .header { border-bottom: 2px solid #4f46e5; } th { background-color: #4f46e5 !important; -webkit-print-color-adjust: exact; } }';
html += '</style></head><body>';
html += '<div class="header">';
html += '<h1>Отчет по обходу аудиторий ХПК</h1>';
html += '<p>Дата формирования: ' + new Date().toLocaleString('ru-RU') + '</p>';
html += '</div>';
html += '<table><thead><tr>';
headers.forEach(function(h) { html += '<th>' + h + '</th>'; });
html += '</tr></thead><tbody>';
rows.forEach(function(row) {
html += '<tr>';
row.forEach(function(cell) { html += '<td>' + cell + '</td>'; });
html += '</tr>';
});
html += '</tbody></table>';
html += '<script>window.onload = function() { window.print(); }<\/script>';
html += '</body></html>';
printWindow.document.open();
printWindow.document.write(html);
printWindow.document.close();
}
}
function showQR(roomNumber) {
// Создаем модальное окно на лету
let qrModal = document.getElementById('qrModal');
if (!qrModal) {
qrModal = document.createElement('div');
qrModal.id = 'qrModal';
qrModal.className = 'modal';
qrModal.innerHTML = `
<div class="modal-content" style="max-width: 300px; text-align: center;">
<div class="modal-header">
<h2>QR Аудитории</h2>
<button class="modal-close" onclick="closeModal('qrModal')">×</button>
</div>
<div class="modal-body">
<div id="qrcode" style="display: flex; justify-content: center; margin: 20px 0;"></div>
<p style="font-weight: bold; font-size: 1.2rem;">Аудитории</p>
<p style="font-size: 0.8rem; color: #666;">Отсканируйте для быстрого перехода</p>
</div>
</div>
`;
document.body.appendChild(qrModal);
}
document.getElementById('qrcode').innerHTML = '';
new QRCode(document.getElementById("qrcode"), {
text: window.location.origin + window.location.pathname.replace('admin.html', 'index.html') + '?room=' + roomNumber,
width: 150,
height: 150
});
qrModal.classList.add('active');
}
</script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.28/jspdf.plugin.autotable.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
</body>
</html>