Files
zibo-dashboard/public/userarea/scadenzario/include/deadline_modal_js.php
T
2026-05-24 00:15:09 +03:00

281 lines
13 KiB
PHP

<?php
/**
* Self-contained JS for the deadline modal (deadline_modal.php).
* Requires jQuery, Bootstrap, flatpickr, select2 and SweetAlert2 to be loaded first.
*
* Exposes:
* window.openDeadlineCreate() — open the modal empty (new deadline)
* window.openDeadlineEdit(id) — fetch a deadline and open the modal in edit mode
*
* Auto-open on load:
* #edit=<id> → opens edit for that id
* #edit → opens edit for window.SCAD_DETAIL_ID (used by detail.php)
*/
?>
<script>
$(document).ready(function() {
// --- Flatpickr date fields (visible dd/mm/yyyy, submitted yyyy-mm-dd) ---
var fpOptsDate = {
dateFormat: 'Y-m-d',
altInput: true,
altFormat: 'd/m/Y',
locale: 'it',
allowInput: true
};
var fpDocDate = flatpickr('#dlDocDate', fpOptsDate);
var fpDueDate = flatpickr('#dlDueDate', fpOptsDate);
var fpCheckDate = flatpickr('#dlCheckDate', fpOptsDate);
// --- Select2 ---
var s2Opts = {
theme: 'bootstrap-5',
allowClear: true,
dropdownParent: $('#deadlineModal .modal-body'),
language: 'it',
width: '100%'
};
$('#dlSubject').select2($.extend({}, s2Opts, { placeholder: 'Seleziona argomento...' }));
$('#dlDepartments').select2($.extend({}, s2Opts, { placeholder: 'Seleziona reparti...' }));
$('#dlEmployees').select2($.extend({}, s2Opts, { placeholder: 'Seleziona persone...' }));
$('#dlFunction').select2($.extend({}, s2Opts, { placeholder: 'Seleziona funzione...' }));
// --- Auto-calc due_date from document_date + recurrence ---
var RECURRENCE_OFFSETS = {
monthly: { months: 1 },
quarterly: { months: 3 },
semiannual: { months: 6 },
annual: { years: 1 },
biennial: { years: 2 },
triennial: { years: 3 },
quadriennial: { years: 4 },
quinquennial: { years: 5 },
decennial: { years: 10 },
quindecennial: { years: 15 }
};
function computeDueDate() {
var docVal = document.getElementById('dlDocDate').value;
var recurrence = document.getElementById('dlRecurrence').value;
var offset = RECURRENCE_OFFSETS[recurrence];
if (!docVal || !offset) return;
var d = new Date(docVal + 'T00:00:00');
if (isNaN(d.getTime())) return;
if (offset.months) d.setMonth(d.getMonth() + offset.months);
if (offset.years) d.setFullYear(d.getFullYear() + offset.years);
var iso = d.getFullYear() + '-' +
String(d.getMonth() + 1).padStart(2, '0') + '-' +
String(d.getDate()).padStart(2, '0');
fpDueDate.setDate(iso, true, 'Y-m-d');
}
$('#dlDocDate, #dlRecurrence').on('change', computeDueDate);
// --- Modal instance ---
var modal = new bootstrap.Modal(document.getElementById('deadlineModal'));
var form = document.getElementById('deadlineForm');
// --- Render attachments list ---
function renderAttachments(attachments) {
var container = document.getElementById('attachmentsList');
if (!attachments || attachments.length === 0) {
container.innerHTML = '<div class="text-muted" style="font-size:0.85rem">Nessun allegato</div>';
return;
}
container.innerHTML = attachments.map(function(a) {
return '<div class="att-item" data-att-id="' + a.id + '">' +
'<span class="att-name"><i class="fa-solid fa-paperclip me-1"></i>' + $('<span>').text(a.original_name).html() + '</span>' +
'<span class="att-actions">' +
'<a href="scadenzario/ajax/download_attachment.php?id=' + a.id + '" class="att-download" title="Scarica"><i class="fa-solid fa-download"></i></a>' +
'<button type="button" class="att-remove" title="Elimina" data-att-id="' + a.id + '"><i class="fa-solid fa-xmark"></i></button>' +
'</span></div>';
}).join('');
}
// --- Open modal (create) ---
window.openDeadlineCreate = function() {
form.reset();
document.getElementById('dlId').value = '';
document.getElementById('dlNotifDays').value = '7';
document.getElementById('modalTitle').textContent = 'Nuova Scadenza';
document.getElementById('dlFiles').value = '';
fpDocDate.clear();
fpDueDate.clear();
fpCheckDate.clear();
$('#dlSubject').val('').trigger('change');
$('#dlDepartments').val(null).trigger('change');
$('#dlEmployees').val(null).trigger('change');
$('#dlFunction').val('').trigger('change');
renderAttachments([]);
modal.show();
};
// --- Open modal (edit) ---
window.openDeadlineEdit = function(id) {
fetch('scadenzario/ajax/get_deadline.php?id=' + id)
.then(function(r) {
return r.json();
})
.then(function(data) {
if (!data.success) {
Swal.fire('Errore', data.message, 'error');
return;
}
var d = data.data;
document.getElementById('dlId').value = d.id;
$('#dlSubject').val(d.subject_id || '').trigger('change');
document.getElementById('dlTopic').value = d.topic || '';
$('#dlFunction').val(d.function_id || '').trigger('change');
document.getElementById('dlLaw').value = d.law_regulation || '';
document.getElementById('dlRecurrence').value = d.recurrence_type || 'once';
fpDocDate.setDate(d.document_date || null, false, 'Y-m-d');
fpDueDate.setDate(d.due_date || null, false, 'Y-m-d');
fpCheckDate.setDate(d.check_date || null, false, 'Y-m-d');
document.getElementById('dlNotifDays').value = d.notification_days || 7;
document.getElementById('dlStorage').value = d.storage_location || '';
document.getElementById('dlNotes').value = d.notes || '';
document.getElementById('dlFiles').value = '';
document.getElementById('modalTitle').textContent = 'Modifica Scadenza';
$('#dlDepartments').val(d.department_names || []).trigger('change');
if (Array.isArray(d.employee_ids)) {
$('#dlEmployees').val(d.employee_ids.map(String)).trigger('change');
} else {
$('#dlEmployees').val(null).trigger('change');
}
renderAttachments(d.attachments || []);
modal.show();
})
.catch(function() {
Swal.fire('Errore', 'Errore di connessione.', 'error');
});
};
// --- Save ---
var isSaving = false;
form.addEventListener('submit', function(e) {
e.preventDefault();
if (isSaving) return;
isSaving = true;
var saveBtn = form.querySelector('[type="submit"]');
saveBtn.disabled = true;
saveBtn.innerHTML = '<i class="fa-solid fa-spinner fa-spin me-1"></i> Salvataggio...';
var formData = new FormData(form);
fetch('scadenzario/ajax/save_deadline.php', {
method: 'POST',
body: formData
})
.then(function(r) {
return r.json();
})
.then(function(data) {
if (data.success) {
var deadlineId = data.id;
var fileInput = document.getElementById('dlFiles');
if (fileInput.files.length > 0) {
var fileData = new FormData();
fileData.append('deadline_id', deadlineId);
for (var i = 0; i < fileInput.files.length; i++) {
fileData.append('files[]', fileInput.files[i]);
}
return fetch('scadenzario/ajax/upload_attachment.php', {
method: 'POST',
body: fileData
})
.then(function(r) {
return r.json();
})
.then(function(upData) {
modal.hide();
Swal.fire({
icon: 'success',
title: 'Salvato',
text: data.message + ' ' + upData.message,
timer: 2000,
showConfirmButton: false
})
.then(function() {
location.reload();
});
});
} else {
modal.hide();
Swal.fire({
icon: 'success',
title: 'Salvato',
text: data.message,
timer: 1500,
showConfirmButton: false
})
.then(function() {
location.reload();
});
}
} else {
Swal.fire('Errore', data.message, 'error');
isSaving = false;
saveBtn.disabled = false;
saveBtn.innerHTML = '<i class="fa-solid fa-check me-1"></i> Salva';
}
})
.catch(function() {
Swal.fire('Errore', 'Errore di connessione.', 'error');
isSaving = false;
saveBtn.disabled = false;
saveBtn.innerHTML = '<i class="fa-solid fa-check me-1"></i> Salva';
});
});
// --- Delete attachment ---
$(document).on('click', '.att-remove', function(e) {
e.preventDefault();
var btn = $(this);
var attId = btn.data('att-id');
Swal.fire({
title: 'Rimuovere l\'allegato?',
text: 'Il collegamento verrà rimosso da questa scadenza. Il file resta disponibile se è usato da altre scadenze.',
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#dc3545',
cancelButtonText: 'Annulla',
confirmButtonText: 'Rimuovi',
reverseButtons: true
}).then(function(result) {
if (result.isConfirmed) {
fetch('scadenzario/ajax/delete_attachment.php?id=' + attId)
.then(function(r) {
return r.json();
})
.then(function(data) {
if (data.success) {
btn.closest('.att-item').remove();
if ($('#attachmentsList .att-item').length === 0) {
renderAttachments([]);
}
Swal.fire({
icon: 'success',
title: 'Fatto',
text: data.message,
timer: 1800,
showConfirmButton: false
});
} else {
Swal.fire('Errore', data.message, 'error');
}
});
}
});
});
// --- Auto-open from hash (#edit=ID or #edit for the current detail page) ---
var hash = window.location.hash;
var hashMatch = hash.match(/^#edit=(\d+)$/);
var autoEditId = hashMatch ? hashMatch[1] :
(hash === '#edit' && window.SCAD_DETAIL_ID ? window.SCAD_DETAIL_ID : null);
if (autoEditId) {
history.replaceState(null, '', window.location.pathname + window.location.search);
window.openDeadlineEdit(autoEditId);
}
});
</script>