first init
This commit is contained in:
@@ -0,0 +1,231 @@
|
||||
const router = require('express').Router();
|
||||
const bcrypt = require('bcryptjs');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { db, tx } = require('../db');
|
||||
const { requireRole, notFound, isValidDate, ROLE_LABEL } = require('../middleware');
|
||||
const { getDosenKegiatan, kegiatanFor } = require('../access');
|
||||
const { UPLOAD_DIR } = require('../upload');
|
||||
|
||||
router.use(requireRole('admin'));
|
||||
|
||||
/* ================= PENGGUNA ================= */
|
||||
|
||||
router.get('/users', (req, res) => {
|
||||
const role = ROLE_LABEL[req.query.role] ? req.query.role : '';
|
||||
const q = String(req.query.q || '').trim();
|
||||
const where = [];
|
||||
const params = [];
|
||||
if (role) { where.push('role = ?'); params.push(role); }
|
||||
if (q) { where.push('(nama LIKE ? OR username LIKE ? OR nomor_induk LIKE ?)'); params.push(`%${q}%`, `%${q}%`, `%${q}%`); }
|
||||
const users = db.prepare(`
|
||||
SELECT u.*,
|
||||
(SELECT COUNT(*) FROM kegiatan k WHERE k.ketua_id = u.id) AS jml_kegiatan_ketua,
|
||||
(SELECT COUNT(*) FROM kegiatan_dosen kd WHERE kd.dosen_id = u.id) AS jml_kegiatan_dosen
|
||||
FROM users u ${where.length ? 'WHERE ' + where.join(' AND ') : ''}
|
||||
ORDER BY CASE role WHEN 'admin' THEN 0 WHEN 'dosen' THEN 1 ELSE 2 END, nama`).all(...params);
|
||||
res.render('admin/users', { title: 'Pengguna', users, role, q });
|
||||
});
|
||||
|
||||
const emptyUser = { id: null, nama: '', username: '', role: 'ketua', nomor_induk: '', aktif: 1 };
|
||||
|
||||
router.get('/users/baru', (req, res) => {
|
||||
const role = ROLE_LABEL[req.query.role] ? req.query.role : 'ketua';
|
||||
res.render('admin/user-form', { title: 'Tambah pengguna', u: { ...emptyUser, role }, errors: {} });
|
||||
});
|
||||
|
||||
function readUserForm(body, isNew) {
|
||||
const u = {
|
||||
nama: String(body.nama || '').trim(),
|
||||
username: String(body.username || '').trim(),
|
||||
role: String(body.role || ''),
|
||||
nomor_induk: String(body.nomor_induk || '').trim(),
|
||||
aktif: body.aktif ? 1 : 0,
|
||||
password: String(body.password || ''),
|
||||
};
|
||||
const errors = {};
|
||||
if (!u.nama) errors.nama = 'Nama wajib diisi.';
|
||||
if (!/^[a-zA-Z0-9._-]{3,40}$/.test(u.username)) errors.username = 'Username 3–40 karakter: huruf, angka, titik, minus, atau garis bawah.';
|
||||
if (!ROLE_LABEL[u.role]) errors.role = 'Pilih level akun.';
|
||||
if (isNew && u.password.length < 8) errors.password = 'Password minimal 8 karakter.';
|
||||
if (!isNew && u.password && u.password.length < 8) errors.password = 'Password minimal 8 karakter, atau kosongkan bila tidak diganti.';
|
||||
return { u, errors };
|
||||
}
|
||||
|
||||
router.post('/users', (req, res) => {
|
||||
const { u, errors } = readUserForm(req.body, true);
|
||||
if (!errors.username && db.prepare('SELECT 1 FROM users WHERE username = ?').get(u.username)) {
|
||||
errors.username = 'Username sudah dipakai.';
|
||||
}
|
||||
if (Object.keys(errors).length) {
|
||||
return res.status(400).render('admin/user-form', { title: 'Tambah pengguna', u: { ...u, id: null }, errors });
|
||||
}
|
||||
db.prepare('INSERT INTO users (username, password_hash, nama, role, nomor_induk, aktif) VALUES (?, ?, ?, ?, ?, ?)')
|
||||
.run(u.username, bcrypt.hashSync(u.password, 10), u.nama, u.role, u.nomor_induk || null, u.aktif);
|
||||
req.flash('success', `Akun ${u.nama} (${ROLE_LABEL[u.role]}) berhasil ditambahkan.`);
|
||||
res.redirect('/admin/users');
|
||||
});
|
||||
|
||||
router.get('/users/:id/edit', (req, res) => {
|
||||
const u = db.prepare('SELECT * FROM users WHERE id = ?').get(Number(req.params.id));
|
||||
if (!u) return notFound(res);
|
||||
res.render('admin/user-form', { title: 'Ubah pengguna', u, errors: {} });
|
||||
});
|
||||
|
||||
router.post('/users/:id', (req, res) => {
|
||||
const id = Number(req.params.id);
|
||||
const existing = db.prepare('SELECT * FROM users WHERE id = ?').get(id);
|
||||
if (!existing) return notFound(res);
|
||||
|
||||
const { u, errors } = readUserForm(req.body, false);
|
||||
if (!errors.username && db.prepare('SELECT 1 FROM users WHERE username = ? AND id <> ?').get(u.username, id)) {
|
||||
errors.username = 'Username sudah dipakai.';
|
||||
}
|
||||
if (id === req.user.id && (u.role !== 'admin' || !u.aktif)) {
|
||||
errors.role = 'Anda tidak bisa menurunkan level atau menonaktifkan akun Anda sendiri.';
|
||||
}
|
||||
if (existing.role === 'ketua' && u.role !== 'ketua' &&
|
||||
db.prepare('SELECT 1 FROM kegiatan WHERE ketua_id = ?').get(id)) {
|
||||
errors.role = 'Akun ini masih menjadi ketua sebuah kegiatan. Ganti ketua kegiatan tersebut dulu.';
|
||||
}
|
||||
if (Object.keys(errors).length) {
|
||||
return res.status(400).render('admin/user-form', { title: 'Ubah pengguna', u: { ...u, id }, errors });
|
||||
}
|
||||
|
||||
tx(() => {
|
||||
db.prepare('UPDATE users SET username = ?, nama = ?, role = ?, nomor_induk = ?, aktif = ? WHERE id = ?')
|
||||
.run(u.username, u.nama, u.role, u.nomor_induk || null, u.aktif, id);
|
||||
if (u.password) {
|
||||
db.prepare('UPDATE users SET password_hash = ? WHERE id = ?').run(bcrypt.hashSync(u.password, 10), id);
|
||||
}
|
||||
if (existing.role === 'dosen' && u.role !== 'dosen') {
|
||||
db.prepare('DELETE FROM kegiatan_dosen WHERE dosen_id = ?').run(id);
|
||||
}
|
||||
});
|
||||
req.flash('success', `Akun ${u.nama} berhasil diperbarui.`);
|
||||
res.redirect('/admin/users');
|
||||
});
|
||||
|
||||
router.post('/users/:id/hapus', (req, res) => {
|
||||
const id = Number(req.params.id);
|
||||
const u = db.prepare('SELECT * FROM users WHERE id = ?').get(id);
|
||||
if (!u) return notFound(res);
|
||||
if (id === req.user.id) {
|
||||
req.flash('error', 'Anda tidak bisa menghapus akun Anda sendiri.');
|
||||
return res.redirect('/admin/users');
|
||||
}
|
||||
const ketuaOf = db.prepare('SELECT COUNT(*) AS n FROM kegiatan WHERE ketua_id = ?').get(id).n;
|
||||
const logs = db.prepare('SELECT COUNT(*) AS n FROM logs WHERE author_id = ?').get(id).n;
|
||||
if (ketuaOf || logs) {
|
||||
req.flash('error', `${u.nama} masih terkait dengan ${ketuaOf} kegiatan dan ${logs} log. Nonaktifkan akunnya saja agar riwayat laporan tetap utuh.`);
|
||||
return res.redirect('/admin/users');
|
||||
}
|
||||
db.prepare('DELETE FROM users WHERE id = ?').run(id);
|
||||
req.flash('success', `Akun ${u.nama} telah dihapus.`);
|
||||
res.redirect('/admin/users');
|
||||
});
|
||||
|
||||
/* ================= KEGIATAN ================= */
|
||||
|
||||
function formOptions() {
|
||||
return {
|
||||
ketuaList: db.prepare("SELECT id, nama, nomor_induk, aktif FROM users WHERE role = 'ketua' ORDER BY nama").all(),
|
||||
dosenList: db.prepare("SELECT id, nama, nomor_induk, aktif FROM users WHERE role = 'dosen' ORDER BY nama").all(),
|
||||
};
|
||||
}
|
||||
|
||||
router.get('/kegiatan', (req, res) => {
|
||||
res.render('admin/kegiatan', { title: 'Kegiatan', kegiatan: kegiatanFor(req.user) });
|
||||
});
|
||||
|
||||
router.get('/kegiatan/baru', (req, res) => {
|
||||
res.render('admin/kegiatan-form', {
|
||||
title: 'Tambah kegiatan',
|
||||
k: { id: null, nama: '', deskripsi: '', ketua_id: null, tanggal_mulai: '', tanggal_selesai: '' },
|
||||
dosenIds: [], errors: {}, ...formOptions(),
|
||||
});
|
||||
});
|
||||
|
||||
function readKegiatanForm(body) {
|
||||
const k = {
|
||||
nama: String(body.nama || '').trim(),
|
||||
deskripsi: String(body.deskripsi || '').trim(),
|
||||
ketua_id: Number(body.ketua_id) || null,
|
||||
tanggal_mulai: String(body.tanggal_mulai || ''),
|
||||
tanggal_selesai: String(body.tanggal_selesai || ''),
|
||||
};
|
||||
const dosenIds = [].concat(body.dosen_ids || []).map(Number).filter(Boolean);
|
||||
const errors = {};
|
||||
if (!k.nama) errors.nama = 'Nama kegiatan wajib diisi.';
|
||||
if (!k.ketua_id || !db.prepare("SELECT 1 FROM users WHERE id = ? AND role = 'ketua'").get(k.ketua_id)) {
|
||||
errors.ketua_id = 'Pilih ketua tim dari akun berlevel Ketua Tim.';
|
||||
}
|
||||
if (k.tanggal_mulai && !isValidDate(k.tanggal_mulai)) errors.tanggal_mulai = 'Tanggal tidak valid.';
|
||||
if (k.tanggal_selesai && !isValidDate(k.tanggal_selesai)) errors.tanggal_selesai = 'Tanggal tidak valid.';
|
||||
if (k.tanggal_mulai && k.tanggal_selesai && k.tanggal_selesai < k.tanggal_mulai) {
|
||||
errors.tanggal_selesai = 'Tanggal selesai tidak boleh sebelum tanggal mulai.';
|
||||
}
|
||||
return { k, dosenIds, errors };
|
||||
}
|
||||
|
||||
function saveDosen(kegiatanId, dosenIds) {
|
||||
db.prepare('DELETE FROM kegiatan_dosen WHERE kegiatan_id = ?').run(kegiatanId);
|
||||
const ins = db.prepare(`INSERT OR IGNORE INTO kegiatan_dosen (kegiatan_id, dosen_id)
|
||||
SELECT ?, id FROM users WHERE id = ? AND role = 'dosen'`);
|
||||
for (const d of dosenIds) ins.run(kegiatanId, d);
|
||||
}
|
||||
|
||||
router.post('/kegiatan', (req, res) => {
|
||||
const { k, dosenIds, errors } = readKegiatanForm(req.body);
|
||||
if (Object.keys(errors).length) {
|
||||
return res.status(400).render('admin/kegiatan-form', { title: 'Tambah kegiatan', k: { ...k, id: null }, dosenIds, errors, ...formOptions() });
|
||||
}
|
||||
const id = tx(() => {
|
||||
const r = db.prepare('INSERT INTO kegiatan (nama, deskripsi, ketua_id, tanggal_mulai, tanggal_selesai) VALUES (?, ?, ?, ?, ?)')
|
||||
.run(k.nama, k.deskripsi || null, k.ketua_id, k.tanggal_mulai || null, k.tanggal_selesai || null);
|
||||
saveDosen(Number(r.lastInsertRowid), dosenIds);
|
||||
return Number(r.lastInsertRowid);
|
||||
});
|
||||
req.flash('success', `Kegiatan "${k.nama}" berhasil ditambahkan.`);
|
||||
res.redirect('/kegiatan/' + id);
|
||||
});
|
||||
|
||||
router.get('/kegiatan/:id/edit', (req, res) => {
|
||||
const k = db.prepare('SELECT * FROM kegiatan WHERE id = ?').get(Number(req.params.id));
|
||||
if (!k) return notFound(res);
|
||||
const dosenIds = getDosenKegiatan(k.id).map((d) => d.id);
|
||||
res.render('admin/kegiatan-form', { title: 'Ubah kegiatan', k, dosenIds, errors: {}, ...formOptions() });
|
||||
});
|
||||
|
||||
router.post('/kegiatan/:id', (req, res) => {
|
||||
const id = Number(req.params.id);
|
||||
if (!db.prepare('SELECT 1 FROM kegiatan WHERE id = ?').get(id)) return notFound(res);
|
||||
const { k, dosenIds, errors } = readKegiatanForm(req.body);
|
||||
if (Object.keys(errors).length) {
|
||||
return res.status(400).render('admin/kegiatan-form', { title: 'Ubah kegiatan', k: { ...k, id }, dosenIds, errors, ...formOptions() });
|
||||
}
|
||||
tx(() => {
|
||||
db.prepare('UPDATE kegiatan SET nama = ?, deskripsi = ?, ketua_id = ?, tanggal_mulai = ?, tanggal_selesai = ? WHERE id = ?')
|
||||
.run(k.nama, k.deskripsi || null, k.ketua_id, k.tanggal_mulai || null, k.tanggal_selesai || null, id);
|
||||
saveDosen(id, dosenIds);
|
||||
});
|
||||
req.flash('success', `Kegiatan "${k.nama}" berhasil diperbarui.`);
|
||||
res.redirect('/kegiatan/' + id);
|
||||
});
|
||||
|
||||
router.post('/kegiatan/:id/hapus', (req, res) => {
|
||||
const id = Number(req.params.id);
|
||||
const k = db.prepare('SELECT * FROM kegiatan WHERE id = ?').get(id);
|
||||
if (!k) return notFound(res);
|
||||
if (String(req.body.konfirmasi || '').trim() !== k.nama) {
|
||||
req.flash('error', 'Nama kegiatan yang diketik tidak cocok. Kegiatan tidak dihapus.');
|
||||
return res.redirect('/admin/kegiatan/' + id + '/edit');
|
||||
}
|
||||
const files = db.prepare(`SELECT i.filename FROM log_images i JOIN logs l ON l.id = i.log_id WHERE l.kegiatan_id = ?`).all(id);
|
||||
db.prepare('DELETE FROM kegiatan WHERE id = ?').run(id);
|
||||
for (const f of files) fs.unlink(path.join(UPLOAD_DIR, f.filename), () => {});
|
||||
req.flash('success', `Kegiatan "${k.nama}" beserta seluruh lognya telah dihapus.`);
|
||||
res.redirect('/admin/kegiatan');
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,79 @@
|
||||
const router = require('express').Router();
|
||||
const bcrypt = require('bcryptjs');
|
||||
const { db } = require('../db');
|
||||
const { requireLogin } = require('../middleware');
|
||||
|
||||
// Pembatasan percobaan login sederhana per IP+username.
|
||||
const attempts = new Map();
|
||||
const WINDOW = 15 * 60 * 1000;
|
||||
const MAX_ATTEMPTS = 8;
|
||||
|
||||
function tooMany(key) {
|
||||
const a = attempts.get(key);
|
||||
if (!a || Date.now() - a.first > WINDOW) return false;
|
||||
return a.count >= MAX_ATTEMPTS;
|
||||
}
|
||||
function recordFail(key) {
|
||||
const a = attempts.get(key);
|
||||
if (!a || Date.now() - a.first > WINDOW) attempts.set(key, { first: Date.now(), count: 1 });
|
||||
else a.count++;
|
||||
}
|
||||
|
||||
router.get('/login', (req, res) => {
|
||||
if (req.user) return res.redirect('/');
|
||||
res.render('login', { title: 'Masuk', username: '', error: null });
|
||||
});
|
||||
|
||||
router.post('/login', (req, res, next) => {
|
||||
const username = String(req.body.username || '').trim();
|
||||
const password = String(req.body.password || '');
|
||||
const key = req.ip + '|' + username.toLowerCase();
|
||||
|
||||
if (tooMany(key)) {
|
||||
return res.status(429).render('login', { title: 'Masuk', username, error: 'Terlalu banyak percobaan. Coba lagi dalam 15 menit.' });
|
||||
}
|
||||
|
||||
const user = db.prepare('SELECT * FROM users WHERE username = ?').get(username);
|
||||
if (!user || !bcrypt.compareSync(password, user.password_hash)) {
|
||||
recordFail(key);
|
||||
return res.status(401).render('login', { title: 'Masuk', username, error: 'Username atau password tidak cocok.' });
|
||||
}
|
||||
if (!user.aktif) {
|
||||
return res.status(403).render('login', { title: 'Masuk', username, error: 'Akun ini sedang dinonaktifkan. Hubungi operator.' });
|
||||
}
|
||||
|
||||
attempts.delete(key);
|
||||
req.session.regenerate((err) => {
|
||||
if (err) return next(err);
|
||||
req.session.userId = user.id;
|
||||
res.redirect('/');
|
||||
});
|
||||
});
|
||||
|
||||
router.post('/logout', (req, res) => {
|
||||
req.session.destroy(() => {
|
||||
res.clearCookie('logharian.sid');
|
||||
res.redirect('/login');
|
||||
});
|
||||
});
|
||||
|
||||
router.get('/akun', requireLogin, (req, res) => {
|
||||
res.render('akun', { title: 'Akun saya', error: null });
|
||||
});
|
||||
|
||||
router.post('/akun/password', requireLogin, (req, res) => {
|
||||
const { lama = '', baru = '', konfirmasi = '' } = req.body;
|
||||
const row = db.prepare('SELECT password_hash FROM users WHERE id = ?').get(req.user.id);
|
||||
let error = null;
|
||||
if (!bcrypt.compareSync(lama, row.password_hash)) error = 'Password lama tidak cocok.';
|
||||
else if (baru.length < 8) error = 'Password baru minimal 8 karakter.';
|
||||
else if (baru !== konfirmasi) error = 'Konfirmasi password baru tidak sama.';
|
||||
|
||||
if (error) return res.status(400).render('akun', { title: 'Akun saya', error });
|
||||
|
||||
db.prepare('UPDATE users SET password_hash = ? WHERE id = ?').run(bcrypt.hashSync(baru, 10), req.user.id);
|
||||
req.flash('success', 'Password berhasil diganti.');
|
||||
res.redirect('/akun');
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,295 @@
|
||||
const router = require('express').Router();
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { db, tx } = require('../db');
|
||||
const { requireLogin, forbidden, notFound, csrfVerify, isValidDate, today } = require('../middleware');
|
||||
const {
|
||||
getKegiatan, getDosenKegiatan, canView, canReport, canEditLog,
|
||||
LOG_SELECT, recentLogsFor, kegiatanFor,
|
||||
} = require('../access');
|
||||
const { handleUpload, removeFiles, UPLOAD_DIR, MAX_FILES, MAX_SIZE_MB } = require('../upload');
|
||||
const cal = require('../calendar');
|
||||
|
||||
const MAX_DESC = 5000;
|
||||
|
||||
router.use(requireLogin);
|
||||
|
||||
/* ---------- Dashboard ---------- */
|
||||
router.get('/', (req, res) => {
|
||||
const u = req.user;
|
||||
const data = { title: 'Dashboard', kegiatan: kegiatanFor(u), logs: recentLogsFor(u, 12) };
|
||||
{
|
||||
// Panel kartu kegiatan (sama untuk semua level akun).
|
||||
const t = today();
|
||||
const filledToday = new Set(db.prepare('SELECT DISTINCT kegiatan_id FROM logs WHERE tanggal = ?').all(t).map((r) => r.kegiatan_id));
|
||||
data.kegiatan.forEach((k) => {
|
||||
k.fase = cal.phase(k, t);
|
||||
k.hari_berjalan = cal.elapsedDays(k, t);
|
||||
k.persen = k.hari_berjalan ? Math.min(100, Math.round((k.hari_terisi / k.hari_berjalan) * 100)) : 0;
|
||||
k.sudah_hari_ini = filledToday.has(k.id);
|
||||
});
|
||||
}
|
||||
if (u.role === 'admin') {
|
||||
data.stats = db.prepare(`SELECT
|
||||
(SELECT COUNT(*) FROM users WHERE role = 'dosen') AS dosen,
|
||||
(SELECT COUNT(*) FROM users WHERE role = 'ketua') AS ketua,
|
||||
(SELECT COUNT(*) FROM kegiatan) AS kegiatan,
|
||||
(SELECT COUNT(*) FROM logs WHERE tanggal = ?) AS log_hari_ini`).get(today());
|
||||
}
|
||||
if (u.role !== 'admin') {
|
||||
const aktif = data.kegiatan.filter((k) => k.fase === 'berjalan');
|
||||
data.roleStats = {
|
||||
kegiatan: data.kegiatan.length,
|
||||
berjalan: aktif.length,
|
||||
terisi: aktif.filter((k) => k.sudah_hari_ini).length,
|
||||
belum: aktif.filter((k) => !k.sudah_hari_ini).length,
|
||||
};
|
||||
}
|
||||
res.render('dashboard', data);
|
||||
});
|
||||
|
||||
/* ---------- Middleware pemuat ---------- */
|
||||
function loadKegiatan(req, res, next) {
|
||||
const k = getKegiatan(req.params.id);
|
||||
if (!k) return notFound(res);
|
||||
if (!canView(req.user, k)) return forbidden(res);
|
||||
req.kegiatan = k;
|
||||
next();
|
||||
}
|
||||
|
||||
function loadLog(req, res, next) {
|
||||
const log = db.prepare(`${LOG_SELECT} WHERE l.id = ?`).get(Number(req.params.id));
|
||||
if (!log) return notFound(res);
|
||||
const k = getKegiatan(log.kegiatan_id);
|
||||
if (!canView(req.user, k)) return forbidden(res);
|
||||
req.log = log;
|
||||
req.kegiatan = k;
|
||||
next();
|
||||
}
|
||||
|
||||
/* ---------- Halaman kegiatan (kalender bulanan) ---------- */
|
||||
router.get('/kegiatan/:id', loadKegiatan, (req, res) => {
|
||||
const k = req.kegiatan;
|
||||
const t = today();
|
||||
const bulan = /^\d{4}-(0[1-9]|1[0-2])$/.test(req.query.bulan || '') ? req.query.bulan : cal.defaultMonth(k, t);
|
||||
const grid = cal.monthGrid(bulan);
|
||||
const p = cal.period(k);
|
||||
|
||||
const rows = db.prepare(`
|
||||
SELECT l.tanggal, COUNT(*) AS n,
|
||||
SUM((SELECT COUNT(*) FROM comments c WHERE c.log_id = l.id)) AS kom,
|
||||
SUM((SELECT COUNT(*) FROM log_images i WHERE i.log_id = l.id)) AS img
|
||||
FROM logs l WHERE l.kegiatan_id = ? AND l.tanggal BETWEEN ? AND ?
|
||||
GROUP BY l.tanggal`).all(k.id, grid.from, grid.to);
|
||||
const byDate = Object.fromEntries(rows.map((r) => [r.tanggal, r]));
|
||||
|
||||
const reporter = canReport(req.user, k);
|
||||
const summary = { filled: 0, missing: 0 };
|
||||
const days = grid.days.map((d) => {
|
||||
const info = byDate[d.date];
|
||||
const status = cal.dayStatus(d.date, !!info, p, t);
|
||||
if (d.inMonth && status === 'filled') summary.filled++;
|
||||
if (d.inMonth && (status === 'missing' || status === 'today')) summary.missing++;
|
||||
// Hari yang bisa diklik: ada log, atau hari wajib lapor yang sudah lewat/hari ini.
|
||||
const clickable = status === 'filled' || status === 'missing' || status === 'today';
|
||||
return { ...d, status, isToday: d.date === t, n: info ? info.n : 0, kom: info ? info.kom : 0, img: info ? info.img : 0, clickable };
|
||||
});
|
||||
|
||||
const openDay = isValidDate(req.query.hari) ? req.query.hari : '';
|
||||
|
||||
res.render('kegiatan', {
|
||||
title: k.nama, k, dosen: getDosenKegiatan(k.id), canReport: reporter,
|
||||
bulan, bulanLabel: cal.monthLabel(bulan), prev: cal.shiftMonth(bulan, -1), next: cal.shiftMonth(bulan, 1),
|
||||
thisMonth: cal.monthKey(t), days, summary, period: p, openDay,
|
||||
totalLog: db.prepare('SELECT COUNT(*) AS n FROM logs WHERE kegiatan_id = ?').get(k.id).n,
|
||||
});
|
||||
});
|
||||
|
||||
/* ---------- Laporan satu hari (isi popup kalender) ---------- */
|
||||
router.get('/kegiatan/:id/hari/:tanggal', loadKegiatan, (req, res) => {
|
||||
const k = req.kegiatan;
|
||||
const tanggal = req.params.tanggal;
|
||||
if (!isValidDate(tanggal)) return notFound(res);
|
||||
const t = today();
|
||||
|
||||
const logs = db.prepare(`${LOG_SELECT} WHERE l.kegiatan_id = ? AND l.tanggal = ? ORDER BY l.id`).all(k.id, tanggal);
|
||||
const imgStmt = db.prepare('SELECT id, original_name FROM log_images WHERE log_id = ? ORDER BY id');
|
||||
const comStmt = db.prepare(`SELECT c.*, u.nama, u.role FROM comments c JOIN users u ON u.id = c.user_id
|
||||
WHERE c.log_id = ? ORDER BY c.id`);
|
||||
logs.forEach((l) => { l.images = imgStmt.all(l.id); l.comments = comStmt.all(l.id); });
|
||||
|
||||
const status = cal.dayStatus(tanggal, logs.length > 0, cal.period(k), t);
|
||||
const data = {
|
||||
k, tanggal, logs, status,
|
||||
canReport: canReport(req.user, k) && tanggal <= t,
|
||||
canEdit: canEditLog(req.user, k),
|
||||
kembali: `/kegiatan/${k.id}?bulan=${tanggal.slice(0, 7)}&hari=${tanggal}`,
|
||||
};
|
||||
res.set('Vary', 'X-Requested-With');
|
||||
if (req.get('X-Requested-With') === 'fetch') return res.render('partials/hari-panel', data);
|
||||
res.render('hari', { title: 'Laporan ' + tanggal, ...data });
|
||||
});
|
||||
|
||||
/* ---------- Tulis log baru (khusus ketua tim) ---------- */
|
||||
function requireReporter(req, res, next) {
|
||||
if (!canReport(req.user, req.kegiatan)) return forbidden(res);
|
||||
next();
|
||||
}
|
||||
|
||||
function readLogForm(req) {
|
||||
const v = {
|
||||
tanggal: String(req.body.tanggal || ''),
|
||||
judul: String(req.body.judul || '').trim(),
|
||||
deskripsi: String(req.body.deskripsi || '').trim(),
|
||||
link_dokumentasi: String(req.body.link_dokumentasi || '').trim(),
|
||||
};
|
||||
const errors = {};
|
||||
if (v.link_dokumentasi) {
|
||||
let ok = false;
|
||||
try {
|
||||
const url = new URL(v.link_dokumentasi);
|
||||
ok = url.protocol === 'https:' && ['drive.google.com', 'docs.google.com'].includes(url.hostname);
|
||||
} catch { ok = false; }
|
||||
if (!ok || v.link_dokumentasi.length > 500) {
|
||||
errors.link_dokumentasi = 'Gunakan link Google Drive yang diawali https://drive.google.com/ atau https://docs.google.com/.';
|
||||
}
|
||||
}
|
||||
if (!isValidDate(v.tanggal)) errors.tanggal = 'Pilih tanggal kegiatan.';
|
||||
else if (v.tanggal > today()) errors.tanggal = 'Tanggal log tidak boleh melewati hari ini.';
|
||||
if (!v.deskripsi) errors.deskripsi = 'Deskripsi kegiatan wajib diisi.';
|
||||
else if (v.deskripsi.length > MAX_DESC) errors.deskripsi = `Deskripsi maksimal ${MAX_DESC} karakter.`;
|
||||
if (v.judul.length > 150) errors.judul = 'Judul maksimal 150 karakter.';
|
||||
if (req.uploadError) errors.gambar = req.uploadError;
|
||||
return { v, errors };
|
||||
}
|
||||
|
||||
function formView(req, extra) {
|
||||
return { k: req.kegiatan, MAX_FILES, MAX_SIZE_MB, MAX_DESC, images: [], ...extra };
|
||||
}
|
||||
|
||||
// Tanggal laporan dipilih dari kalender; tanpa tanggal yang sah, ketua diarahkan ke kalender.
|
||||
router.get('/kegiatan/:id/log/baru', loadKegiatan, requireReporter, (req, res) => {
|
||||
const tanggal = req.query.tanggal;
|
||||
if (!isValidDate(tanggal) || tanggal > today()) {
|
||||
req.flash('info', 'Pilih tanggal laporan pada kalender terlebih dahulu.');
|
||||
return res.redirect('/kegiatan/' + req.kegiatan.id);
|
||||
}
|
||||
res.render('log-form', formView(req, {
|
||||
title: 'Tulis log harian', log: null, errors: {},
|
||||
v: { tanggal, judul: '', deskripsi: '', link_dokumentasi: '' },
|
||||
}));
|
||||
});
|
||||
|
||||
router.post('/kegiatan/:id/log', loadKegiatan, requireReporter, handleUpload('gambar'), csrfVerify, (req, res) => {
|
||||
const { v, errors } = readLogForm(req);
|
||||
if (Object.keys(errors).length) {
|
||||
removeFiles(req.files);
|
||||
if (req.files && req.files.length && !errors.gambar) errors.gambar = 'Gambar perlu dipilih ulang.';
|
||||
return res.status(400).render('log-form', formView(req, { title: 'Tulis log harian', log: null, v, errors }));
|
||||
}
|
||||
const id = tx(() => {
|
||||
const r = db.prepare('INSERT INTO logs (kegiatan_id, author_id, tanggal, judul, deskripsi, link_dokumentasi) VALUES (?, ?, ?, ?, ?, ?)')
|
||||
.run(req.kegiatan.id, req.user.id, v.tanggal, v.judul || null, v.deskripsi, v.link_dokumentasi || null);
|
||||
const logId = Number(r.lastInsertRowid);
|
||||
const ins = db.prepare('INSERT INTO log_images (log_id, filename, original_name) VALUES (?, ?, ?)');
|
||||
for (const f of req.files || []) ins.run(logId, f.filename, f.originalname.slice(0, 200));
|
||||
return logId;
|
||||
});
|
||||
req.flash('success', 'Log harian berhasil disimpan.');
|
||||
// Kembali ke kalender dengan popup tanggal tersebut terbuka.
|
||||
res.redirect(`/kegiatan/${req.kegiatan.id}?bulan=${v.tanggal.slice(0, 7)}&hari=${v.tanggal}#lap-${id}`);
|
||||
});
|
||||
|
||||
/* ---------- Detail log + komentar ---------- */
|
||||
router.get('/log/:id', loadLog, (req, res) => {
|
||||
const images = db.prepare('SELECT * FROM log_images WHERE log_id = ? ORDER BY id').all(req.log.id);
|
||||
const comments = db.prepare(`SELECT c.*, u.nama, u.role FROM comments c JOIN users u ON u.id = c.user_id
|
||||
WHERE c.log_id = ? ORDER BY c.id`).all(req.log.id);
|
||||
res.render('log', {
|
||||
title: req.log.judul || 'Log ' + req.log.tanggal,
|
||||
log: req.log, k: req.kegiatan, images, comments,
|
||||
canEdit: canEditLog(req.user, req.kegiatan),
|
||||
});
|
||||
});
|
||||
|
||||
/* ---------- Ubah / hapus log ---------- */
|
||||
function requireEditor(req, res, next) {
|
||||
if (!canEditLog(req.user, req.kegiatan)) return forbidden(res);
|
||||
next();
|
||||
}
|
||||
|
||||
router.get('/log/:id/edit', loadLog, requireEditor, (req, res) => {
|
||||
const images = db.prepare('SELECT * FROM log_images WHERE log_id = ? ORDER BY id').all(req.log.id);
|
||||
res.render('log-form', formView(req, { title: 'Ubah log', log: req.log, v: req.log, errors: {}, images }));
|
||||
});
|
||||
|
||||
router.post('/log/:id', loadLog, requireEditor, handleUpload('gambar'), csrfVerify, (req, res) => {
|
||||
const images = db.prepare('SELECT * FROM log_images WHERE log_id = ? ORDER BY id').all(req.log.id);
|
||||
const removeIds = new Set([].concat(req.body.hapus_gambar || []).map(Number));
|
||||
const toRemove = images.filter((i) => removeIds.has(i.id));
|
||||
const { v, errors } = readLogForm(req);
|
||||
if (images.length - toRemove.length + (req.files || []).length > MAX_FILES) {
|
||||
errors.gambar = `Total gambar maksimal ${MAX_FILES}. Hapus sebagian gambar lama atau kurangi unggahan.`;
|
||||
}
|
||||
if (Object.keys(errors).length) {
|
||||
removeFiles(req.files);
|
||||
return res.status(400).render('log-form', formView(req, { title: 'Ubah log', log: req.log, v, errors, images }));
|
||||
}
|
||||
tx(() => {
|
||||
db.prepare("UPDATE logs SET tanggal = ?, judul = ?, deskripsi = ?, link_dokumentasi = ?, updated_at = datetime('now','localtime') WHERE id = ?")
|
||||
.run(v.tanggal, v.judul || null, v.deskripsi, v.link_dokumentasi || null, req.log.id);
|
||||
const del = db.prepare('DELETE FROM log_images WHERE id = ? AND log_id = ?');
|
||||
for (const i of toRemove) del.run(i.id, req.log.id);
|
||||
const ins = db.prepare('INSERT INTO log_images (log_id, filename, original_name) VALUES (?, ?, ?)');
|
||||
for (const f of req.files || []) ins.run(req.log.id, f.filename, f.originalname.slice(0, 200));
|
||||
});
|
||||
removeFiles(toRemove);
|
||||
req.flash('success', 'Log berhasil diperbarui.');
|
||||
res.redirect('/log/' + req.log.id);
|
||||
});
|
||||
|
||||
router.post('/log/:id/hapus', loadLog, requireEditor, (req, res) => {
|
||||
const images = db.prepare('SELECT filename FROM log_images WHERE log_id = ?').all(req.log.id);
|
||||
db.prepare('DELETE FROM logs WHERE id = ?').run(req.log.id);
|
||||
removeFiles(images);
|
||||
req.flash('success', 'Log telah dihapus.');
|
||||
res.redirect('/kegiatan/' + req.kegiatan.id);
|
||||
});
|
||||
|
||||
/* ---------- Komentar ---------- */
|
||||
router.post('/log/:id/komentar', loadLog, (req, res) => {
|
||||
const isi = String(req.body.isi || '').trim();
|
||||
// Kembali ke kalender bila komentar dikirim dari popup (hanya path internal yang diizinkan).
|
||||
const kembali = /^\/kegiatan\/\d+\?bulan=\d{4}-\d{2}&hari=\d{4}-\d{2}-\d{2}$/.test(req.body.kembali || '') ? req.body.kembali : null;
|
||||
if (!isi || isi.length > 2000) {
|
||||
req.flash('error', isi ? 'Komentar maksimal 2000 karakter.' : 'Komentar tidak boleh kosong.');
|
||||
return res.redirect(kembali || '/log/' + req.log.id + '#komentar');
|
||||
}
|
||||
const r = db.prepare('INSERT INTO comments (log_id, user_id, isi) VALUES (?, ?, ?)').run(req.log.id, req.user.id, isi);
|
||||
if (kembali) req.flash('success', 'Komentar terkirim.');
|
||||
res.redirect(kembali || '/log/' + req.log.id + '#c' + r.lastInsertRowid);
|
||||
});
|
||||
|
||||
router.post('/komentar/:id/hapus', (req, res) => {
|
||||
const c = db.prepare('SELECT * FROM comments WHERE id = ?').get(Number(req.params.id));
|
||||
if (!c) return notFound(res);
|
||||
if (c.user_id !== req.user.id && req.user.role !== 'admin') return forbidden(res);
|
||||
db.prepare('DELETE FROM comments WHERE id = ?').run(c.id);
|
||||
req.flash('success', 'Komentar dihapus.');
|
||||
res.redirect('/log/' + c.log_id + '#komentar');
|
||||
});
|
||||
|
||||
/* ---------- Gambar (dengan pengecekan akses) ---------- */
|
||||
router.get('/gambar/:id', (req, res) => {
|
||||
const img = db.prepare(`SELECT i.*, l.kegiatan_id FROM log_images i JOIN logs l ON l.id = i.log_id WHERE i.id = ?`)
|
||||
.get(Number(req.params.id));
|
||||
if (!img) return res.sendStatus(404);
|
||||
if (!canView(req.user, getKegiatan(img.kegiatan_id))) return res.sendStatus(403);
|
||||
const file = path.join(UPLOAD_DIR, path.basename(img.filename));
|
||||
if (!fs.existsSync(file)) return res.sendStatus(404);
|
||||
res.set('Cache-Control', 'private, max-age=86400');
|
||||
res.set('X-Content-Type-Options', 'nosniff');
|
||||
res.sendFile(file);
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
Reference in New Issue
Block a user