document.addEventListener('DOMContentLoaded', () => {
const tableState = { data: [], page: 1, pageSize: 10, search: '', lastPage: 1, total: 0, startDate: '', endDate: '', mode: 'pengajuan' };
const historyState = { data: [], page: 1, pageSize: 10, search: '', lastPage: 1, total: 0, startDate: '', endDate: '', mode: 'history' };
const tbodyPengajuan = document.getElementById('tablePengajuanFile');
const tbodyHistory = document.getElementById('tableHistoryFile');
const paginationPengajuan = document.getElementById('paginationPengajuan');
const paginationHistory = document.getElementById('paginationHistory');
const summaryEl = document.getElementById('tableSummary');
const pageSizeSelect = document.getElementById('tablePageSize');
const startDateInput = document.getElementById('startDate');
const endDateInput = document.getElementById('endDate');
const tabsEl = document.getElementById('pengajuanTabs');
const titleEl = document.getElementById('pengajuanTitle');
const tabPengajuanEl = document.getElementById('tabPengajuan');
const tabHistoryEl = document.getElementById('tabHistory');
const formCreate = document.getElementById('formFile');
const modalCreate = document.getElementById('modalCreateFile');
let colCount = 1;
const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
const editForm = document.getElementById('formEditPengajuanFile');
const editUnitSelect = $('#edit_id_unit_kerja');
const editSubUnitSelect = $('#edit_id_sub_unit_kerja');
if (pageSizeSelect) {
const initialSize = parseInt(pageSizeSelect.value);
if (!isNaN(initialSize)) {
tableState.pageSize = initialSize;
historyState.pageSize = initialSize;
}
pageSizeSelect.addEventListener('change', (e) => {
const val = parseInt(e.target.value);
if (!isNaN(val) && val > 0) {
tableState.pageSize = val;
historyState.pageSize = val;
tableState.page = 1;
historyState.page = 1;
fetchData();
}
});
}
window.applyDateFilter = function(){
const start = startDateInput.value || '';
const end = endDateInput.value || '';
tableState.startDate = start;
tableState.endDate = end;
historyState.startDate = start;
historyState.endDate = end;
tableState.page = 1;
historyState.page = 1;
fetchData();
}
function formatTanggal(dateString) {
if (!dateString) return '-';
const d = new Date(dateString);
return d.toLocaleDateString('id-ID', {
day: '2-digit',
month: 'short',
year: 'numeric'
});
}
function buildRow(item){
let tanggal = item.entry_at ? formatTanggal(item.entry_at) : '-';
let tanggalExp = item.tgl_expired ? formatTanggal(item.tgl_expired) : '-';
let tanggalTerbit = item.tanggal_terbit ? formatTanggal(item.tanggal_terbit) : '-';
const isApproved = item?.status_action === 'approved';
const isRejected = item?.status_action === 'rejected';
const showEdit = !isApproved;
const showInfo = isRejected;
const aksi = `
`;
openPreview(idDirectory);
$("#previewModal").modal('show')
}
function initEditSelects(){
if (editUnitSelect.length) {
editUnitSelect.select2({
placeholder: '-- Pilih Unit Kerja --',
allowClear: true,
width: '100%',
dropdownParent: $('#modalEditPengajuanFile'),
ajax: {
url: '/select-unit-kerja-mapping',
dataType: 'json',
delay: 250,
data: function (params) {
return { q: params.term || '' };
},
processResults: function (data) {
return {
results: (data?.data || []).map(item => ({
id: `${item.id}/${item.name}`,
text: item.name
}))
};
},
cache: true
},
minimumInputLength: 0
});
}
if (editSubUnitSelect.length) {
editSubUnitSelect.select2({
placeholder: '-- Pilih Sub Unit Kerja --',
allowClear: true,
width: '100%',
dropdownParent: $('#modalEditPengajuanFile')
});
}
editUnitSelect.on('change', function(){
const val = $(this).val();
if (!val) return;
const unitId = String(val).split('/')[0];
loadEditSubUnit(unitId, null, null);
});
}
function loadEditSubUnit(unitId, selectedSubId, selectedSubName){
editSubUnitSelect.empty().append('
');
if (!unitId) return;
$.ajax({
url: `/select-sub-unit-kerja-mapping/${unitId}`,
method: 'GET',
success: function(response) {
if (response?.data) {
response.data.forEach(unit => {
const optVal = `${unit.id}/${unit.name}`;
const isSelected = selectedSubId && String(unit.id) === String(selectedSubId);
const option = new Option(unit.name, optVal, false, isSelected);
editSubUnitSelect.append(option);
});
if (selectedSubId && selectedSubName && editSubUnitSelect.find(`option[value="${selectedSubId}/${selectedSubName}"]`).length === 0) {
editSubUnitSelect.append(new Option(selectedSubName, `${selectedSubId}/${selectedSubName}`, true, true));
}
editSubUnitSelect.trigger('change');
}
}
});
}
window.editFileReject = function(id){
const item = getItemById(id);
if (!item) {
Swal.fire({ icon: 'error', title: 'Gagal', text: 'Data tidak ditemukan.' });
return;
}
const idEl = document.getElementById('edit_file_directory_id');
const noEl = document.getElementById('edit_no_dokumen');
const namaEl = document.getElementById('edit_nama_dokumen');
const tglEl = document.getElementById('edit_tanggal_terbit');
const tglExpiredEl = document.getElementById('edit_tgl_expired');
const hasExpiredEl = document.getElementById('edit_has_expired');
const currentFileEl = document.getElementById('edit_current_file');
const permYes = document.getElementById('edit_perm_yes');
const permNo = document.getElementById('edit_perm_no');
const katEl = document.getElementById('edit_kategori');
if (idEl) idEl.value = item.file_directory_id || '';
if (noEl) noEl.value = item.no_dokumen || '';
if (namaEl) namaEl.value = item.nama_dokumen || '';
if (tglEl) tglEl.value = item.tanggal_terbit || '';
if (tglExpiredEl) tglExpiredEl.value = item.tgl_expired || '';
if (permYes && permNo) {
const isPublic = item.permission_file === true || item.permission_file === 1 || item.permission_file === '1';
permYes.checked = isPublic;
permNo.checked = !isPublic;
}
if (hasExpiredEl && tglExpiredEl) {
const hasExpired = !!item.tgl_expired;
hasExpiredEl.checked = hasExpired;
syncEditExpiredField();
}
if (currentFileEl) {
const displayName = item.fileName || (item.file ? String(item.file).split('/').pop() : '');
currentFileEl.textContent = displayName ? `File saat ini: ${displayName}` : '';
}
const parts = (item.file || '').split('/');
const unitName = parts[0] || '';
const subName = parts[1] || '';
const kategoriName = parts[2] || '';
if (editUnitSelect.length && item.id_unit_kerja) {
const unitVal = `${item.id_unit_kerja}/${unitName}`;
editUnitSelect.append(new Option(unitName || 'Unit', unitVal, true, true)).trigger('change');
const unitId = String(item.id_unit_kerja);
loadEditSubUnit(unitId, item.id_sub_unit_kerja, subName);
}
if (katEl && item.master_kategori_directory_id) {
const katVal = `${item.master_kategori_directory_id}/${kategoriName}`;
if (katEl.querySelector(`option[value="${katVal}"]`)) {
katEl.value = katVal;
} else {
katEl.append(new Option(kategoriName || 'Kategori', katVal, true, true));
katEl.value = katVal;
}
}
const modalEl = document.getElementById('modalEditPengajuanFile');
if (modalEl) {
$("#modalEditPengajuanFile").modal('show');
}
}
function syncEditExpiredField() {
const editHasExpired = document.getElementById('edit_has_expired');
const editExpiredInput = document.getElementById('edit_tgl_expired');
if (!editHasExpired || !editExpiredInput) return;
editExpiredInput.disabled = !editHasExpired.checked;
if (!editHasExpired.checked) {
editExpiredInput.value = '';
}
}
const editHasExpired = document.getElementById('edit_has_expired');
if (editHasExpired) {
editHasExpired.addEventListener('change', syncEditExpiredField);
}
if (editForm) {
editForm.addEventListener('submit', (e) => {
e.preventDefault();
const id = document.getElementById('edit_file_directory_id')?.value;
if (!id) {
Swal.fire({ icon: 'error', title: 'Gagal', text: 'ID dokumen tidak ditemukan.' });
return;
}
const formData = new FormData(editForm);
fetch(`/pengajuan-file/${id}/update`, {
method: 'POST',
headers: {
'X-CSRF-TOKEN': csrfToken
},
body: formData
}).then(async (res) => {
const data = await res.json();
if (!res.ok || !data?.status) {
throw new Error(data?.message || 'Gagal memperbarui data.');
}
Swal.fire({
icon: 'success',
title: 'Berhasil',
text: data.message || 'Data berhasil diperbarui.',
timer: 1500,
showConfirmButton: false
});
$("#modalEditPengajuanFile").modal('hide');
fetchData();
}).catch((err) => {
Swal.fire({
icon: 'error',
title: 'Gagal',
text: err.message || 'Terjadi kesalahan.'
});
});
});
}
initEditSelects();
updateTabUI();
fetchData();
// ===== Upload baru (seperti dataUnit) =====
document.addEventListener('change', function(e){
if(!e.target.classList.contains('toggle-expired')) return;
const targetId = e.target.getAttribute('data-target');
if(!targetId) return;
const fieldWrap = document.getElementById(targetId);
const input = fieldWrap?.querySelector('input');
if (input) input.disabled = !e.target.checked;
});
function resetCreateForm(){
colCount = 1;
const colAdd = document.getElementById('col_add_fileV2');
if (colAdd) colAdd.innerHTML = '';
if (formCreate) {
formCreate.reset();
$(formCreate).find('select').val(null).trigger('change');
$(formCreate).find('input[type="file"]').val('');
$(formCreate).find('.file-name').addClass('d-none').text('');
}
}
function selectOptionUnitKerjaV1(localCol){
const selectUnit = $(`#select_id_unit_kerja_${localCol}`);
const selectSubUnit = $(`#select_id_sub_unit_kerja_${localCol}`);
selectUnit.select2({
placeholder: '-- Pilih Unit Kerja --',
allowClear:true,
width: '100%',
dropdownParent: selectUnit.parent(),
ajax:{
url : '/select-unit-kerja-mapping',
dataType: 'json',
delay: 250,
data: function(params){
return { q: params.term }
},
processResults: function(data){
return {
results : (data?.data || []).map(item => ({
id: item.id+'/'+item.name,
text: item.name,
sub_units: item.sub_unit_kerja
}))
}
},
cache: true,
},
minimumInputLength: 0,
});
selectSubUnit.select2({
placeholder: '-- Pilih Sub Unit Kerja --',
allowClear: true,
width: '100%',
dropdownParent: selectSubUnit.parent()
});
selectUnit.on('select2:select', function (e) {
const data = e.params.data;
selectSubUnit.empty().append('
');
if (data.sub_units && data.sub_units.length > 0) {
data.sub_units.forEach(sub => {
selectSubUnit.append(`
`);
});
}
});
}
window.addFormV2 = function(){
const col = document.getElementById('col_add_fileV2');
if (!col) return;
const katDok = Array.isArray(window.katDok) ? window.katDok : [];
const katOptions = katDok.map(k => `
`).join('');
let html = `
`;
col.insertAdjacentHTML('beforeend', html);
selectOptionUnitKerjaV1(colCount);
colCount++;
}
window.removeCol = function(count){
const el = document.getElementById(`col-${count}`);
if (el) el.remove();
}
if (formCreate) {
const select0 = $('#select_id_unit_kerja_0');
if (select0.length) selectOptionUnitKerjaV1(0);
formCreate.addEventListener('submit', (e) => {
e.preventDefault();
const submitBtn = formCreate.querySelector('button[type="submit"]');
if (submitBtn) submitBtn.disabled = true;
if (submitBtn) submitBtn.textContent = 'menyimpan...';
const formData = new FormData(formCreate);
fetch(`/uploadv2`, {
method: 'POST',
headers: {
'X-CSRF-TOKEN': document.querySelector('input[name="_token"]')?.value || ''
},
body: formData
}).then(async(res) => {
const responseData = await res.json();
if(responseData.status){
Swal.fire({
icon: 'success',
title: 'Berhasil',
text: responseData.message || 'Data berhasil disimpan.',
timer: 1500,
showConfirmButton: false
});
const modalInstance = bootstrap.Modal.getInstance(modalCreate);
modalInstance?.hide();
resetCreateForm();
fetchData();
if(responseData.status_action === null || responseData.status_action === undefined){
Swal.fire({
icon: 'info',
title: 'Perlu Persetujuan',
text: 'Dokumen yang Anda upload butuh persetujuan dari atasan.',
confirmButtonText: 'Tutup'
});
}
} else {
throw new Error(responseData.message || 'Terjadi kesalahan saat menyimpan data.');
}
}).catch(err => {
Swal.fire({
icon: 'error',
title: 'Gagal',
text: err.message || 'Terjadi kesalahan.'
});
}).finally(() => {
if (submitBtn) submitBtn.disabled = false;
if (submitBtn) submitBtn.textContent = 'Simpan';
});
});
}
});
document.addEventListener('click', function(e){
if(e.target.matches('.file-link')){
e.preventDefault();
let fileUrl = e.target.getAttribute('data-file');
let noDokumen = e.target.getAttribute('data-no_dokumen')
let tanggalTerbit = e.target.getAttribute('data-tanggal_terbit')
let permissionFile = e.target.getAttribute('data-permission_file')
let fileName = e.target.getAttribute('data-fileName')
currentFile = fileUrl;
idDirectory = e.target.getAttribute('data-id');
const titleEl = document.getElementById('confirm_preview_file');
if (titleEl) titleEl.textContent = fileName;
// set footer info
const noEl = document.getElementById('confirm-upload-dokumen');
if (noEl) noEl.textContent = noDokumen;
const tglEl = document.getElementById('confirm-time-dokumen');
if (tglEl) tglEl.textContent = tanggalTerbit;
const permEl = document.getElementById('confirm-permission');
if (permEl) {
const publicDoc = isPublic(permissionFile);
permEl.textContent = publicDoc ? 'Umum' : 'Internal Unit';
permEl.className = 'badge ' + (publicDoc ? 'bg-success' : 'bg-secondary');
}
let previewBox = document.getElementById('file-preview');
previewBox.innerHTML = `
`;
openPreview(idDirectory);
$("#previewModal").modal('show')
}
if(e.target.matches('#btn-view-full')){
window.open(`/full-preview/${idDirectory}`, '_blank');
}
})
function isPublic(permissionVal){
if(permissionVal === null || permissionVal === undefined) return false;
const val = String(permissionVal).toLowerCase();
return val === '1' || val === 'true' || val === 'iya' || val === 'yes';
}