Repository navigation
Expand file tree
/
Copy pathadmin.html
More file actions
421 lines (387 loc) · 21.9 KB
/
Copy pathadmin.html
File metadata and controls
421 lines (387 loc) · 21.9 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
<!doctype html>
<html lang="id">
<head>
<!-- prettier-ignore -->
<script>try{var __m=matchMedia('(prefers-color-scheme: dark)').matches,__s;try{__s=localStorage.getItem('igo-theme')}catch(e){}var __t=__s==='light'||__s==='dark'?__s:__m?'dark':'light';if(__t==='dark')document.documentElement.classList.add('dark');}catch(e){}</script>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Admin - igo</title>
<meta name="description" content="Manajemen pengguna igo." />
<meta name="robots" content="noindex, nofollow" />
<link rel="manifest" href="/site.webmanifest" />
<link rel="icon" type="image/png" href="/images/favicon-192x192.png" />
<link href="src/css/styles.css" rel="stylesheet" />
</head>
<body class="overflow-x-clip antialiased bg-background text-on-background">
{{> navbar }}
<main class="container mx-auto min-h-screen w-full max-w-full overflow-x-clip px-4 py-8">
<div class="mb-8 flex flex-col gap-2 md:flex-row md:items-end md:justify-between">
<div>
<p class="text-sm font-semibold uppercase text-vibrant-palm">Admin</p>
<h1 class="text-3xl font-bold text-deep-forest dark:text-content">Manajemen Pengguna</h1>
</div>
<p class="max-w-2xl text-sm text-on-surface-variant">
Import CSV dapat memakai satu kolom <code>Email</code>. Jika password kosong atau kolom password tidak ada, default password adalah <strong>SawitItuBaik</strong>.
</p>
</div>
<section id="admin-message" class="mb-4 hidden rounded px-4 py-3 text-sm"></section>
<section class="mb-8 grid gap-4 md:grid-cols-5">
<div class="rounded border border-outline-variant bg-paper-white p-4">
<p class="text-sm text-on-surface-variant">Total user</p>
<p id="stat-total" class="mt-2 text-2xl font-bold text-deep-forest dark:text-content">-</p>
</div>
<div class="rounded border border-outline-variant bg-paper-white p-4">
<p class="text-sm text-on-surface-variant">Aktif</p>
<p id="stat-active" class="mt-2 text-2xl font-bold text-deep-forest dark:text-content">-</p>
</div>
<div class="rounded border border-outline-variant bg-paper-white p-4">
<p class="text-sm text-on-surface-variant">Nonaktif</p>
<p id="stat-inactive" class="mt-2 text-2xl font-bold text-deep-forest dark:text-content">-</p>
</div>
<div class="rounded border border-outline-variant bg-paper-white p-4">
<p class="text-sm text-on-surface-variant">Admin</p>
<p id="stat-admin" class="mt-2 text-2xl font-bold text-deep-forest dark:text-content">-</p>
</div>
<div class="rounded border border-outline-variant bg-paper-white p-4">
<p class="text-sm text-on-surface-variant">User</p>
<p id="stat-user" class="mt-2 text-2xl font-bold text-deep-forest dark:text-content">-</p>
</div>
</section>
<div class="grid min-w-0 gap-6 lg:grid-cols-[360px_minmax(0,1fr)]">
<aside class="min-w-0 space-y-6">
<section class="rounded border border-outline-variant bg-paper-white p-5">
<h2 class="mb-1 text-lg font-bold text-ink-slate dark:text-content">Status login AD</h2>
<p class="mb-4 text-sm text-on-surface-variant">Pilih pengecekan otomatis atau tampilkan maintenance kepada pengguna di halaman login.</p>
<div id="admin-service-status" class="mb-4 rounded border border-outline-variant bg-surface-gray px-3 py-2 text-sm">Memuat status layanan...</div>
<form id="service-status-form" class="space-y-4">
<div>
<label for="service-status-mode" class="mb-1 block text-sm font-medium">Mode status</label>
<select id="service-status-mode" class="w-full rounded border border-outline-variant px-3 py-2">
<option value="auto">Otomatis — cek AD</option>
<option value="maintenance">Maintenance</option>
</select>
</div>
<div id="service-maintenance-fields" class="space-y-4">
<div>
<label for="service-status-message" class="mb-1 block text-sm font-medium">Pesan untuk pengguna</label>
<textarea id="service-status-message" rows="3" maxlength="500" class="w-full rounded border border-outline-variant px-3 py-2 text-sm" placeholder="Login AD sedang maintenance."></textarea>
</div>
<div>
<label for="service-status-until" class="mb-1 block text-sm font-medium">Selesai pada (opsional)</label>
<input id="service-status-until" type="datetime-local" class="w-full rounded border border-outline-variant px-3 py-2" />
</div>
</div>
<button id="save-service-status-btn" class="w-full rounded bg-vibrant-palm px-4 py-2 font-semibold text-white hover:bg-orange-600" type="submit">Simpan status</button>
</form>
</section>
<section class="rounded border border-outline-variant bg-paper-white p-5">
<h2 class="mb-4 text-lg font-bold text-ink-slate dark:text-content">Tambah user</h2>
<form id="create-user-form" class="space-y-4">
<div>
<label for="new-username" class="mb-1 block text-sm font-medium">Username atau email</label>
<input id="new-username" required minlength="3" maxlength="150" class="w-full rounded border border-outline-variant px-3 py-2" />
</div>
<div>
<label for="new-password" class="mb-1 block text-sm font-medium">Password</label>
<input id="new-password" type="password" required minlength="8" class="w-full rounded border border-outline-variant px-3 py-2" />
</div>
<div>
<label for="new-role" class="mb-1 block text-sm font-medium">Role</label>
<select id="new-role" class="w-full rounded border border-outline-variant px-3 py-2">
<option value="user">user</option>
<option value="admin">admin</option>
</select>
</div>
<button class="w-full rounded bg-deep-forest px-4 py-2 font-semibold text-white hover:bg-green-800" type="submit">Buat user</button>
</form>
</section>
<section class="rounded border border-outline-variant bg-paper-white p-5">
<h2 class="mb-4 text-lg font-bold text-ink-slate dark:text-content">Bulk import</h2>
<div class="space-y-4">
<input id="import-file" type="file" accept=".csv,.txt,text/csv,text/plain" class="w-full text-sm" />
<textarea id="import-content" rows="8" class="w-full rounded border border-outline-variant px-3 py-2 text-sm" placeholder="Email nama@bpdp.or.id"></textarea>
<div class="grid grid-cols-2 gap-2">
<button id="preview-import-btn" class="min-w-0 rounded border border-deep-forest px-3 py-2 text-sm font-semibold text-deep-forest dark:text-content hover:bg-green-50 dark:hover:bg-deep-forest/40" type="button">Preview</button>
<button id="run-import-btn" class="min-w-0 rounded bg-vibrant-palm px-3 py-2 text-sm font-semibold text-white hover:bg-orange-600" type="button">Import</button>
</div>
<pre id="import-preview" class="max-h-56 overflow-auto rounded bg-surface-gray p-3 text-xs text-on-surface"></pre>
</div>
</section>
</aside>
<section class="min-w-0 max-w-full overflow-hidden rounded border border-outline-variant bg-paper-white">
<div class="flex flex-col gap-3 border-b border-outline-variant p-4 md:flex-row md:items-center md:justify-between">
<h2 class="text-lg font-bold text-ink-slate dark:text-content">Daftar user</h2>
<div class="grid w-full min-w-0 gap-2 sm:flex sm:w-auto sm:flex-wrap">
<input id="user-search" class="min-w-0 rounded border border-outline-variant px-3 py-2 text-sm sm:flex-1" placeholder="Cari username" />
<select id="role-filter" class="min-w-0 rounded border border-outline-variant px-3 py-2 text-sm">
<option value="">Semua role</option>
<option value="admin">admin</option>
<option value="user">user</option>
</select>
<button id="refresh-users-btn" class="rounded border border-deep-forest px-3 py-2 text-sm font-semibold text-deep-forest dark:text-content hover:bg-green-50 dark:hover:bg-deep-forest/40" type="button">Refresh</button>
</div>
</div>
<div class="max-w-full overflow-x-auto">
<table class="admin-users-table min-w-full divide-y divide-outline-variant text-sm">
<thead class="bg-surface-gray text-left text-on-surface-variant">
<tr>
<th class="px-4 py-3 font-semibold">Username</th>
<th class="px-4 py-3 font-semibold">Role</th>
<th class="px-4 py-3 font-semibold">Status</th>
<th class="px-4 py-3 font-semibold">Last login</th>
<th class="px-4 py-3 font-semibold">Aksi</th>
</tr>
</thead>
<tbody id="users-body" class="divide-y divide-outline-variant"></tbody>
</table>
</div>
<div class="grid grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-2 border-t border-outline-variant p-4 text-sm">
<button id="prev-page-btn" class="rounded border border-outline-variant px-3 py-2 disabled:opacity-40" type="button">Sebelumnya</button>
<span id="page-label" class="min-w-0 text-center">Halaman 1</span>
<button id="next-page-btn" class="rounded border border-outline-variant px-3 py-2 disabled:opacity-40" type="button">Berikutnya</button>
</div>
</section>
</div>
</main>
{{> footer }}
<script type="module" src="src/js/utils/lucide-init.ts"></script>
<script type="module" src="src/js/mobileMenu.ts"></script>
<script type="module" src="src/js/main.ts"></script>
<script type="module" src="src/js/sw-register.ts"></script>
<script type="module">
import { getCurrentUser } from './src/js/auth/session.js';
const currentUser = await getCurrentUser();
if (!currentUser || currentUser.role !== 'admin') {
window.location.href = '/index.html';
}
const state = { page: 1, totalPages: 1, search: '', role: '' };
const usersBody = document.getElementById('users-body');
const message = document.getElementById('admin-message');
async function api(path, options = {}) {
const response = await fetch(`/api${path}`, {
credentials: 'include',
headers: { 'Content-Type': 'application/json', ...(options.headers || {}) },
...options,
});
const data = await response.json();
if (!response.ok || !data.success) {
throw new Error(data.error || 'Request failed');
}
return data;
}
function showMessage(text, ok = true) {
message.textContent = text;
message.className = `mb-4 rounded px-4 py-3 text-sm ${ok ? 'bg-green-50 text-green-700 border border-green-200' : 'bg-red-50 text-red-700 border border-red-200'}`;
}
function formatDate(value) {
return value ? new Date(value).toLocaleString('id-ID') : '-';
}
function toDateTimeLocal(value) {
if (!value) return '';
const date = new Date(value);
if (Number.isNaN(date.getTime())) return '';
const pad = (part) => String(part).padStart(2, '0');
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`;
}
function updateServiceStatusFields() {
const mode = document.getElementById('service-status-mode').value;
document.getElementById('service-maintenance-fields').classList.toggle('hidden', mode !== 'maintenance');
}
function renderServiceStatus(status) {
const stateLabel = status.status === 'maintenance'
? 'Maintenance'
: status.status === 'operational'
? 'Operasional'
: 'Offline';
const adLabel = status.adReachable ? 'AD terjangkau' : 'AD tidak terjangkau';
const until = status.maintenanceUntil ? ` sampai ${formatDate(status.maintenanceUntil)}` : '';
document.getElementById('admin-service-status').textContent = `${stateLabel} · ${adLabel}${until}`;
document.getElementById('service-status-mode').value = status.mode;
document.getElementById('service-status-message').value = status.message || '';
document.getElementById('service-status-until').value = toDateTimeLocal(status.maintenanceUntil);
updateServiceStatusFields();
}
async function loadServiceStatus() {
const result = await api('/admin/service-status');
renderServiceStatus(result.data);
}
async function saveServiceStatus(event) {
event.preventDefault();
const button = document.getElementById('save-service-status-btn');
const mode = document.getElementById('service-status-mode').value;
const untilValue = document.getElementById('service-status-until').value;
button.disabled = true;
try {
const result = await api('/admin/service-status', {
method: 'PUT',
body: JSON.stringify({
mode,
message: mode === 'maintenance' ? document.getElementById('service-status-message').value : null,
maintenanceUntil: mode === 'maintenance' && untilValue ? new Date(untilValue).toISOString() : null,
}),
});
renderServiceStatus(result.data);
showMessage('Status login AD berhasil diperbarui.');
} catch (error) {
showMessage(error.message || 'Status layanan gagal diperbarui.', false);
} finally {
button.disabled = false;
}
}
async function loadStats() {
const result = await api('/admin/dashboard');
const stats = result.data;
document.getElementById('stat-total').textContent = stats.totalUsers;
document.getElementById('stat-active').textContent = stats.activeUsers;
document.getElementById('stat-inactive').textContent = stats.inactiveUsers;
document.getElementById('stat-admin').textContent = stats.adminCount;
document.getElementById('stat-user').textContent = stats.userCount;
}
async function loadUsers() {
const params = new URLSearchParams({
page: String(state.page),
limit: '20',
});
if (state.search) params.set('search', state.search);
if (state.role) params.set('role', state.role);
const result = await api(`/admin/users?${params.toString()}`);
state.totalPages = result.totalPages || 1;
document.getElementById('page-label').textContent = `Halaman ${state.page} dari ${state.totalPages}`;
document.getElementById('prev-page-btn').disabled = state.page <= 1;
document.getElementById('next-page-btn').disabled = state.page >= state.totalPages;
usersBody.innerHTML = '';
for (const user of result.data) {
const row = document.createElement('tr');
row.innerHTML = `
<td data-label="Username" class="px-4 py-3 font-medium text-ink-slate dark:text-content"></td>
<td data-label="Role" class="px-4 py-3"></td>
<td data-label="Status" class="px-4 py-3"></td>
<td data-label="Last login" class="px-4 py-3"></td>
<td data-label="Aksi" class="px-4 py-3">
<div data-user-actions class="flex flex-wrap gap-2">
<button data-action="role" class="rounded border border-outline-variant px-2 py-1 text-xs">Toggle role</button>
<button data-action="status" class="rounded border border-outline-variant px-2 py-1 text-xs">Aktif/nonaktif</button>
<button data-action="reset" class="rounded border border-outline-variant px-2 py-1 text-xs">Reset password</button>
<button data-action="delete" class="rounded border border-red-300 px-2 py-1 text-xs text-red-700 dark:border-red-500/50 dark:text-red-400">Hapus</button>
</div>
</td>
`;
row.children[0].textContent = user.username;
row.children[1].textContent = user.role;
row.children[2].textContent = user.isActive ? 'Aktif' : 'Nonaktif';
row.children[3].textContent = formatDate(user.lastLogin);
row.querySelector('[data-action="role"]').addEventListener('click', () => updateUser(user.id, { role: user.role === 'admin' ? 'user' : 'admin' }));
row.querySelector('[data-action="status"]').addEventListener('click', () => updateUser(user.id, { isActive: !user.isActive }));
row.querySelector('[data-action="reset"]').addEventListener('click', () => resetPassword(user.id));
row.querySelector('[data-action="delete"]').addEventListener('click', () => deleteUser(user.id, user.username));
usersBody.appendChild(row);
}
}
async function refreshAll() {
await Promise.all([loadStats(), loadUsers(), loadServiceStatus()]);
}
async function updateUser(id, payload) {
try {
await api(`/admin/users/${id}`, { method: 'PUT', body: JSON.stringify(payload) });
showMessage('User berhasil diperbarui.');
await refreshAll();
} catch (error) {
showMessage(error.message, false);
}
}
async function resetPassword(id) {
const newPassword = prompt('Password baru (kosongkan untuk generate otomatis):');
try {
const body = newPassword ? { newPassword } : {};
const result = await api(`/admin/users/${id}/reset-password`, { method: 'POST', body: JSON.stringify(body) });
showMessage(result.data?.newPassword ? `Password baru: ${result.data.newPassword}` : 'Password berhasil direset.');
} catch (error) {
showMessage(error.message, false);
}
}
async function deleteUser(id, username) {
if (!confirm(`Hapus user ${username}?`)) return;
try {
await api(`/admin/users/${id}`, { method: 'DELETE' });
showMessage('User berhasil dihapus.');
await refreshAll();
} catch (error) {
showMessage(error.message, false);
}
}
document.getElementById('create-user-form').addEventListener('submit', async (event) => {
event.preventDefault();
try {
await api('/admin/users', {
method: 'POST',
body: JSON.stringify({
username: document.getElementById('new-username').value.trim(),
password: document.getElementById('new-password').value,
role: document.getElementById('new-role').value,
}),
});
event.target.reset();
showMessage('User berhasil dibuat.');
await refreshAll();
} catch (error) {
showMessage(error.message, false);
}
});
document.getElementById('import-file').addEventListener('change', async (event) => {
const file = event.target.files?.[0];
if (!file) return;
document.getElementById('import-content').value = await file.text();
});
async function importRequest(path) {
const content = document.getElementById('import-content').value;
const fileName = document.getElementById('import-file').files?.[0]?.name || '';
const format = fileName.toLowerCase().endsWith('.txt') ? 'txt' : 'csv';
return api(path, { method: 'POST', body: JSON.stringify({ content, format }) });
}
document.getElementById('preview-import-btn').addEventListener('click', async () => {
try {
const result = await importRequest('/admin/users/import-preview');
document.getElementById('import-preview').textContent = JSON.stringify(result.data, null, 2);
} catch (error) {
showMessage(error.message, false);
}
});
document.getElementById('run-import-btn').addEventListener('click', async () => {
try {
const result = await importRequest('/admin/users/bulk-import');
document.getElementById('import-preview').textContent = JSON.stringify(result.data, null, 2);
showMessage(result.message || 'Import selesai.');
await refreshAll();
} catch (error) {
showMessage(error.message, false);
}
});
document.getElementById('service-status-mode').addEventListener('change', updateServiceStatusFields);
document.getElementById('service-status-form').addEventListener('submit', saveServiceStatus);
document.getElementById('refresh-users-btn').addEventListener('click', refreshAll);
document.getElementById('user-search').addEventListener('input', (event) => {
state.search = event.target.value.trim();
state.page = 1;
loadUsers().catch((error) => showMessage(error.message, false));
});
document.getElementById('role-filter').addEventListener('change', (event) => {
state.role = event.target.value;
state.page = 1;
loadUsers().catch((error) => showMessage(error.message, false));
});
document.getElementById('prev-page-btn').addEventListener('click', () => {
if (state.page > 1) {
state.page -= 1;
loadUsers().catch((error) => showMessage(error.message, false));
}
});
document.getElementById('next-page-btn').addEventListener('click', () => {
if (state.page < state.totalPages) {
state.page += 1;
loadUsers().catch((error) => showMessage(error.message, false));
}
});
refreshAll().catch((error) => showMessage(error.message, false));
</script>
</body>
</html>