fixed funzioni aziendali

This commit is contained in:
2026-06-05 14:35:19 +02:00
parent 6dd13e5d7d
commit e5bf546ae7
4 changed files with 1127 additions and 50 deletions
@@ -0,0 +1,138 @@
<?php
declare(strict_types=1);
use Phinx\Migration\AbstractMigration;
final class AlterScadFunctionsAddContactFields extends AbstractMigration
{
public function up(): void
{
if (!$this->hasTable('scad_functions')) {
throw new RuntimeException('Table scad_functions does not exist.');
}
$table = $this->table('scad_functions');
if (!$table->hasColumn('person_full_name')) {
$table->addColumn('person_full_name', 'string', [
'limit' => 200,
'null' => true,
'after' => 'description',
'comment' => 'Full name and surname of the person assigned to the function',
]);
}
if (!$table->hasColumn('phone')) {
$table->addColumn('phone', 'string', [
'limit' => 80,
'null' => true,
'after' => 'person_full_name',
]);
}
if (!$table->hasColumn('email')) {
$table->addColumn('email', 'string', [
'limit' => 190,
'null' => true,
'after' => 'phone',
]);
}
if (!$table->hasColumn('notes')) {
$table->addColumn('notes', 'text', [
'null' => true,
'after' => 'email',
]);
}
if (!$table->hasColumn('sort_order')) {
$table->addColumn('sort_order', 'integer', [
'signed' => false,
'null' => false,
'default' => 0,
'after' => 'status',
]);
}
if (!$table->hasIndexByName('idx_scad_functions_name')) {
$table->addIndex(['name'], [
'name' => 'idx_scad_functions_name',
]);
}
if (!$table->hasIndexByName('idx_scad_functions_person_full_name')) {
$table->addIndex(['person_full_name'], [
'name' => 'idx_scad_functions_person_full_name',
]);
}
if (!$table->hasIndexByName('idx_scad_functions_email')) {
$table->addIndex(['email'], [
'name' => 'idx_scad_functions_email',
]);
}
if (!$table->hasIndexByName('idx_scad_functions_status_sort')) {
$table->addIndex(['status', 'sort_order'], [
'name' => 'idx_scad_functions_status_sort',
]);
}
$table->update();
// Set a default order for existing rows without changing their names.
$this->execute("
UPDATE scad_functions
SET sort_order = id * 10
WHERE sort_order = 0
");
}
public function down(): void
{
if (!$this->hasTable('scad_functions')) {
return;
}
$table = $this->table('scad_functions');
if ($table->hasIndexByName('idx_scad_functions_status_sort')) {
$table->removeIndexByName('idx_scad_functions_status_sort');
}
if ($table->hasIndexByName('idx_scad_functions_email')) {
$table->removeIndexByName('idx_scad_functions_email');
}
if ($table->hasIndexByName('idx_scad_functions_person_full_name')) {
$table->removeIndexByName('idx_scad_functions_person_full_name');
}
if ($table->hasIndexByName('idx_scad_functions_name')) {
$table->removeIndexByName('idx_scad_functions_name');
}
if ($table->hasColumn('sort_order')) {
$table->removeColumn('sort_order');
}
if ($table->hasColumn('notes')) {
$table->removeColumn('notes');
}
if ($table->hasColumn('email')) {
$table->removeColumn('email');
}
if ($table->hasColumn('phone')) {
$table->removeColumn('phone');
}
if ($table->hasColumn('person_full_name')) {
$table->removeColumn('person_full_name');
}
$table->update();
}
}
+617
View File
@@ -0,0 +1,617 @@
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
include('include/headscript.php');
$db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection();
function jsonResponse(array $data): void
{
header('Content-Type: application/json; charset=utf-8');
echo json_encode($data);
exit;
}
function normalizeNullableInt($value): ?int
{
return (isset($value) && $value !== '') ? (int)$value : null;
}
function normalizeBoolValue($value): int
{
return ((string)$value === '0') ? 0 : 1;
}
function cleanString(?string $value): string
{
return trim((string)$value);
}
/* ==========================================
AJAX HANDLERS
========================================== */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax']) && $_POST['ajax'] == '1') {
$action = $_POST['action'] ?? '';
try {
if ($action === 'add') {
$functionName = cleanString($_POST['function_name'] ?? '');
$personFullName = cleanString($_POST['person_full_name'] ?? '');
$phone = cleanString($_POST['phone'] ?? '');
$email = cleanString($_POST['email'] ?? '');
$notes = cleanString($_POST['notes'] ?? '');
$sortOrder = normalizeNullableInt($_POST['sort_order'] ?? '0') ?? 0;
$isActive = normalizeBoolValue($_POST['is_active'] ?? '1');
if ($functionName === '') {
jsonResponse(['success' => false, 'message' => 'Il nome funzione è obbligatorio.']);
}
if ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
jsonResponse(['success' => false, 'message' => 'Email non valida.']);
}
$stmt = $pdo->prepare("\n INSERT INTO company_functions\n (function_name, person_full_name, phone, email, notes, sort_order, is_active, created_at, updated_at)\n VALUES\n (:function_name, :person_full_name, :phone, :email, :notes, :sort_order, :is_active, NOW(), NOW())\n ");
$stmt->execute([
'function_name' => $functionName,
'person_full_name' => $personFullName !== '' ? $personFullName : '',
'phone' => $phone !== '' ? $phone : null,
'email' => $email !== '' ? $email : null,
'notes' => $notes !== '' ? $notes : null,
'sort_order' => $sortOrder,
'is_active' => $isActive,
]);
jsonResponse(['success' => true, 'message' => 'Funzione salvata correttamente.']);
}
if ($action === 'edit') {
$id = (int)($_POST['id'] ?? 0);
$functionName = cleanString($_POST['function_name'] ?? '');
$personFullName = cleanString($_POST['person_full_name'] ?? '');
$phone = cleanString($_POST['phone'] ?? '');
$email = cleanString($_POST['email'] ?? '');
$notes = cleanString($_POST['notes'] ?? '');
$sortOrder = normalizeNullableInt($_POST['sort_order'] ?? '0') ?? 0;
$isActive = normalizeBoolValue($_POST['is_active'] ?? '1');
if ($id <= 0) {
jsonResponse(['success' => false, 'message' => 'ID funzione non valido.']);
}
if ($functionName === '') {
jsonResponse(['success' => false, 'message' => 'Il nome funzione è obbligatorio.']);
}
if ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
jsonResponse(['success' => false, 'message' => 'Email non valida.']);
}
$stmt = $pdo->prepare("\n UPDATE company_functions\n SET function_name = :function_name,\n person_full_name = :person_full_name,\n phone = :phone,\n email = :email,\n notes = :notes,\n sort_order = :sort_order,\n is_active = :is_active,\n updated_at = NOW()\n WHERE id = :id\n ");
$stmt->execute([
'function_name' => $functionName,
'person_full_name' => $personFullName !== '' ? $personFullName : '',
'phone' => $phone !== '' ? $phone : null,
'email' => $email !== '' ? $email : null,
'notes' => $notes !== '' ? $notes : null,
'sort_order' => $sortOrder,
'is_active' => $isActive,
'id' => $id,
]);
jsonResponse(['success' => true, 'message' => 'Funzione aggiornata correttamente.']);
}
if ($action === 'delete') {
$id = (int)($_POST['id'] ?? 0);
if ($id <= 0) {
jsonResponse(['success' => false, 'message' => 'ID funzione non valido.']);
}
$stmt = $pdo->prepare("DELETE FROM company_functions WHERE id = :id");
$stmt->execute(['id' => $id]);
jsonResponse(['success' => true, 'message' => 'Funzione cancellata correttamente.']);
}
jsonResponse(['success' => false, 'message' => 'Azione non riconosciuta.']);
} catch (Exception $e) {
jsonResponse(['success' => false, 'message' => $e->getMessage()]);
}
}
/* ==========================================
PAGE DATA
========================================== */
$stmtFunctions = $pdo->query("\n SELECT id, function_name, person_full_name, phone, email, notes, sort_order, is_active, created_at, updated_at\n FROM company_functions\n ORDER BY is_active DESC, sort_order ASC, function_name ASC, person_full_name ASC\n");
$functions = $stmtFunctions->fetchAll(PDO::FETCH_ASSOC);
?>
<!doctype html>
<html lang="it">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="assets/images/favicon-32x32.png" type="image/png" />
<?php include('cssinclude.php'); ?>
<title>Funzioni Aziendali - <?= htmlspecialchars($titlewebsite, ENT_QUOTES, 'UTF-8'); ?></title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
<style>
body {
font-size: 1.05rem;
background: #f8fafc;
}
.card {
border-radius: 16px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}
.back-dashboard {
background-color: #cfe3ff !important;
color: #1f2d3d !important;
border: 1px solid #bcd4f4 !important;
border-radius: 10px;
font-weight: 600;
font-size: 1rem;
padding: 10px 18px;
box-shadow: 0 3px 8px rgba(0, 0, 0, 0.1);
transition: all 0.2s ease-in-out;
}
.back-dashboard:hover {
background-color: #b9d3ff !important;
transform: translateY(-2px);
}
.btn-main-action,
.btn-add {
background-color: #0d6efd;
color: #fff;
border-radius: 8px;
padding: 10px 20px;
font-weight: 500;
transition: all 0.2s ease-in-out;
}
.btn-main-action:hover,
.btn-add:hover {
background-color: #0b5ed7;
color: #fff;
transform: scale(1.02);
}
.table thead {
background-color: #cfe3ff;
color: #1f2d3d;
}
#tabCompanyFunctions thead th {
text-align: center;
vertical-align: middle;
}
.modal-content {
border-radius: 16px;
}
.function-name {
font-weight: 700;
color: #1f2937;
}
.person-name {
font-weight: 600;
color: #334155;
}
.contact-line {
display: block;
font-size: 0.9rem;
text-decoration: none;
}
.notes-small {
color: #64748b;
font-size: 0.9rem;
max-width: 420px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.badge-status {
padding: 0.25rem 0.65rem;
border-radius: 999px;
font-size: 0.82rem;
font-weight: 700;
}
.badge-status.active {
background-color: #d1fae5;
color: #065f46;
}
.badge-status.inactive {
background-color: #e5e7eb;
color: #374151;
}
.empty-text {
color: #94a3b8;
font-style: italic;
}
@media (max-width: 767.98px) {
.card-header {
flex-direction: column;
align-items: flex-start !important;
gap: .5rem;
}
.back-dashboard,
.btn-main-action {
width: 100%;
}
}
</style>
</head>
<body>
<div class="wrapper" id="appWrapper">
<?php include('include/navbar.php'); ?>
<?php include('include/topbar.php'); ?>
<div class="page-wrapper">
<div class="page-content">
<div class="card p-3">
<div class="card-header d-flex justify-content-between align-items-center flex-wrap gap-2">
<h5 class="mb-0">Funzioni Aziendali</h5>
<button type="button" class="btn back-dashboard" onclick="location.href='production_dashboard.php'">
↩️ Torna alla Dashboard
</button>
</div>
<div class="card-body">
<div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
<div>
<h6 class="fw-semibold mb-1">Elenco Funzioni</h6>
<div class="text-muted small">Gestione di RSPP, medico del lavoro, RLS e altre funzioni aziendali.</div>
</div>
<button class="btn btn-main-action" data-bs-toggle="modal" data-bs-target="#companyFunctionModal" onclick="openCompanyFunctionModal()">
Aggiungi Funzione
</button>
</div>
<div class="table-responsive">
<table id="tabCompanyFunctions" class="table table-striped align-middle text-center" style="width:100%;">
<thead>
<tr>
<th>Funzione</th>
<th>Nominativo</th>
<th>Contatti</th>
<th>Note</th>
<th>Ordine</th>
<th>Stato</th>
<th>Azioni</th>
</tr>
</thead>
<tbody>
<?php foreach ($functions as $row): ?>
<?php
$id = (int)$row['id'];
$functionName = (string)($row['function_name'] ?? '');
$personFullName = (string)($row['person_full_name'] ?? '');
$phone = (string)($row['phone'] ?? '');
$email = (string)($row['email'] ?? '');
$notes = (string)($row['notes'] ?? '');
$sortOrder = (int)($row['sort_order'] ?? 0);
$isActive = (int)($row['is_active'] ?? 1);
?>
<tr>
<td class="text-start">
<div class="function-name"><?= htmlspecialchars($functionName, ENT_QUOTES, 'UTF-8') ?></div>
</td>
<td class="text-start">
<?php if ($personFullName !== ''): ?>
<div class="person-name"><?= htmlspecialchars($personFullName, ENT_QUOTES, 'UTF-8') ?></div>
<?php else: ?>
<span class="empty-text">Da definire</span>
<?php endif; ?>
</td>
<td class="text-start">
<?php if ($phone !== ''): ?>
<a class="contact-line" href="tel:<?= htmlspecialchars($phone, ENT_QUOTES, 'UTF-8') ?>">
📞 <?= htmlspecialchars($phone, ENT_QUOTES, 'UTF-8') ?>
</a>
<?php endif; ?>
<?php if ($email !== ''): ?>
<a class="contact-line" href="mailto:<?= htmlspecialchars($email, ENT_QUOTES, 'UTF-8') ?>">
✉️ <?= htmlspecialchars($email, ENT_QUOTES, 'UTF-8') ?>
</a>
<?php endif; ?>
<?php if ($phone === '' && $email === ''): ?>
<span class="empty-text">Nessun contatto</span>
<?php endif; ?>
</td>
<td class="text-start">
<?php if ($notes !== ''): ?>
<div class="notes-small" title="<?= htmlspecialchars($notes, ENT_QUOTES, 'UTF-8') ?>">
<?= htmlspecialchars($notes, ENT_QUOTES, 'UTF-8') ?>
</div>
<?php else: ?>
<span class="empty-text"></span>
<?php endif; ?>
</td>
<td><?= $sortOrder ?></td>
<td>
<?php if ($isActive === 1): ?>
<span class="badge-status active">Attiva</span>
<?php else: ?>
<span class="badge-status inactive">Non attiva</span>
<?php endif; ?>
</td>
<td>
<button
type="button"
class="btn btn-sm btn-outline-secondary edit-function mb-1"
data-id="<?= $id ?>"
data-function_name="<?= htmlspecialchars($functionName, ENT_QUOTES, 'UTF-8') ?>"
data-person_full_name="<?= htmlspecialchars($personFullName, ENT_QUOTES, 'UTF-8') ?>"
data-phone="<?= htmlspecialchars($phone, ENT_QUOTES, 'UTF-8') ?>"
data-email="<?= htmlspecialchars($email, ENT_QUOTES, 'UTF-8') ?>"
data-notes="<?= htmlspecialchars($notes, ENT_QUOTES, 'UTF-8') ?>"
data-sort_order="<?= $sortOrder ?>"
data-is_active="<?= $isActive ?>">
✏️ Modifica
</button>
<button
type="button"
class="btn btn-sm btn-outline-danger delete-function mb-1"
data-id="<?= $id ?>"
data-name="<?= htmlspecialchars($functionName, ENT_QUOTES, 'UTF-8') ?>">
🗑️ Cancella
</button>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<?php include('include/footer.php'); ?>
</div>
<!-- MODALE ADD / EDIT FUNZIONE -->
<div class="modal fade" id="companyFunctionModal" tabindex="-1" aria-hidden="true">
<div class="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable">
<div class="modal-content">
<div class="modal-header" style="background-color:#cfe3ff;">
<h5 class="modal-title" id="companyFunctionModalTitle">Aggiungi Funzione</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<form id="companyFunctionForm">
<input type="hidden" id="functionId">
<div class="mb-3">
<label class="form-label fw-semibold">Nome funzione <span class="text-danger">*</span></label>
<input type="text" class="form-control" id="functionName" placeholder="Es. RSPP, Medico del lavoro, RLS" required>
</div>
<div class="mb-3">
<label class="form-label fw-semibold">Nome e Cognome persona</label>
<input type="text" class="form-control" id="personFullName" placeholder="Es. Mario Rossi">
</div>
<div class="row">
<div class="col-12 col-md-6 mb-3">
<label class="form-label fw-semibold">Telefono</label>
<input type="text" class="form-control" id="phone" placeholder="Es. +39 333 1234567">
</div>
<div class="col-12 col-md-6 mb-3">
<label class="form-label fw-semibold">Email</label>
<input type="email" class="form-control" id="email" placeholder="nome@azienda.it">
</div>
</div>
<div class="row">
<div class="col-12 col-md-6 mb-3">
<label class="form-label fw-semibold">Ordine</label>
<input type="number" class="form-control" id="sortOrder" value="0" min="0" step="1">
<small class="text-muted">Serve solo per ordinare la visualizzazione.</small>
</div>
<div class="col-12 col-md-6 mb-3">
<label class="form-label fw-semibold">Stato</label>
<select class="form-select" id="isActive">
<option value="1">Attiva</option>
<option value="0">Non attiva</option>
</select>
</div>
</div>
<div class="mb-3">
<label class="form-label fw-semibold">Note</label>
<textarea class="form-control" id="notes" rows="3" placeholder="Note interne, riferimenti, disponibilità, ecc."></textarea>
</div>
<div class="text-center">
<button type="submit" class="btn btn-add">💾 Salva</button>
</div>
</form>
</div>
</div>
</div>
</div>
<?php include('jsinclude.php'); ?>
<script>
function escapeHtml(value) {
return $('<div>').text(value || '').html();
}
function openCompanyFunctionModal() {
$('#functionId').val('');
$('#functionName').val('');
$('#personFullName').val('');
$('#phone').val('');
$('#email').val('');
$('#notes').val('');
$('#sortOrder').val('0');
$('#isActive').val('1');
$('#companyFunctionModalTitle').text('Aggiungi Funzione');
}
$(document).ready(function() {
$('#tabCompanyFunctions').DataTable({
order: [
[5, 'asc'],
[4, 'asc'],
[0, 'asc']
],
pageLength: 25,
language: {
url: 'https://cdn.datatables.net/plug-ins/1.13.6/i18n/it-IT.json',
emptyTable: 'Nessuna funzione presente'
},
columnDefs: [{
targets: -1,
orderable: false,
searchable: false
}]
});
$(document).on('click', '.edit-function', function() {
const btn = $(this);
$('#functionId').val(btn.data('id'));
$('#functionName').val(btn.data('function_name'));
$('#personFullName').val(btn.data('person_full_name'));
$('#phone').val(btn.data('phone'));
$('#email').val(btn.data('email'));
$('#notes').val(btn.data('notes'));
$('#sortOrder').val(btn.data('sort_order'));
$('#isActive').val(String(btn.data('is_active')));
$('#companyFunctionModalTitle').text('Modifica Funzione');
$('#companyFunctionModal').modal('show');
});
$('#companyFunctionForm').on('submit', function(e) {
e.preventDefault();
const id = $('#functionId').val();
const payload = new URLSearchParams();
payload.append('ajax', '1');
payload.append('action', id ? 'edit' : 'add');
payload.append('id', id);
payload.append('function_name', $('#functionName').val().trim());
payload.append('person_full_name', $('#personFullName').val().trim());
payload.append('phone', $('#phone').val().trim());
payload.append('email', $('#email').val().trim());
payload.append('notes', $('#notes').val().trim());
payload.append('sort_order', $('#sortOrder').val() || '0');
payload.append('is_active', $('#isActive').val());
fetch('', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: payload.toString()
})
.then(r => r.json())
.then(data => {
if (data.success) {
Swal.fire({
icon: 'success',
title: 'Salvato!',
text: data.message || 'Operazione completata.',
confirmButtonColor: '#3085d6'
}).then(() => location.reload());
} else {
Swal.fire('Errore', data.message || 'Impossibile salvare.', 'error');
}
})
.catch(err => {
console.error(err);
Swal.fire('Errore', 'Errore di comunicazione.', 'error');
});
});
$(document).on('click', '.delete-function', function() {
const id = $(this).data('id');
const name = $(this).data('name');
Swal.fire({
title: 'Confermi la cancellazione?',
text: name ? ('Funzione: ' + name) : 'La funzione verrà cancellata.',
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#d33',
cancelButtonColor: '#6c757d',
confirmButtonText: 'Sì, cancella',
cancelButtonText: 'Annulla'
}).then((result) => {
if (!result.isConfirmed) return;
const payload = new URLSearchParams();
payload.append('ajax', '1');
payload.append('action', 'delete');
payload.append('id', id);
fetch('', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: payload.toString()
})
.then(r => r.json())
.then(data => {
if (data.success) {
Swal.fire({
icon: 'success',
title: 'Cancellato!',
text: data.message || 'Funzione cancellata.',
confirmButtonColor: '#3085d6'
}).then(() => location.reload());
} else {
Swal.fire('Errore', data.message || 'Impossibile cancellare.', 'error');
}
})
.catch(err => {
console.error(err);
Swal.fire('Errore', 'Errore di comunicazione.', 'error');
});
});
});
});
</script>
</body>
</html>
+5
View File
@@ -359,6 +359,11 @@
<i class='bx bx-radio-circle'></i>Calendario
</a>
</li>
<li>
<a href="scadenzario/functions/index.php">
<i class='bx bx-radio-circle'></i>Funzioni Aziendali
</a>
</li>
</ul>
</li>
<?php endif; ?>
+367 -50
View File
@@ -1,15 +1,122 @@
<?php include('../../include/headscript.php'); ?>
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection();
$functions = $pdo->query("
SELECT f.*,
(SELECT COUNT(*) FROM scad_deadlines d WHERE d.function_id = f.id) AS deadline_count,
(SELECT COUNT(*) FROM scad_deadlines d WHERE d.function_id = f.id AND d.status <> 'completed') AS open_count
FROM scad_functions f
ORDER BY f.name ASC
")->fetchAll(PDO::FETCH_ASSOC);
function scadJsonResponse(array $data): void
{
header('Content-Type: application/json; charset=utf-8');
echo json_encode($data);
exit;
}
function scadNullableString($value): ?string
{
$value = trim((string)($value ?? ''));
return $value !== '' ? $value : null;
}
function scadNormalizeStatus(string $status): string
{
return in_array($status, ['active', 'inactive'], true) ? $status : 'active';
}
function scadValidateEmail($email): ?string
{
$email = scadNullableString($email);
if ($email !== null && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new Exception('Email non valida.');
}
return $email;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax']) && $_POST['ajax'] === '1') {
try {
$action = $_POST['action'] ?? '';
if ($action === 'save') {
$id = isset($_POST['id']) && $_POST['id'] !== '' ? (int)$_POST['id'] : 0;
$name = trim($_POST['name'] ?? '');
$description = scadNullableString($_POST['description'] ?? null);
$personFullName = scadNullableString($_POST['person_full_name'] ?? null);
$phone = scadNullableString($_POST['phone'] ?? null);
$email = scadValidateEmail($_POST['email'] ?? null);
$notes = scadNullableString($_POST['notes'] ?? null);
$sortOrder = isset($_POST['sort_order']) && $_POST['sort_order'] !== '' ? (int)$_POST['sort_order'] : 0;
$status = scadNormalizeStatus(trim($_POST['status'] ?? 'active'));
if ($name === '') {
scadJsonResponse(['success' => false, 'message' => 'Il nome funzione è obbligatorio.']);
}
if ($id > 0) {
$stmt = $pdo->prepare("\n UPDATE scad_functions\n SET name = :name,\n description = :description,\n person_full_name = :person_full_name,\n phone = :phone,\n email = :email,\n notes = :notes,\n sort_order = :sort_order,\n status = :status,\n updated_at = NOW()\n WHERE id = :id\n ");
$stmt->execute([
'name' => $name,
'description' => $description,
'person_full_name' => $personFullName,
'phone' => $phone,
'email' => $email,
'notes' => $notes,
'sort_order' => $sortOrder,
'status' => $status,
'id' => $id,
]);
scadJsonResponse(['success' => true, 'message' => 'Funzione aggiornata correttamente.']);
}
$stmt = $pdo->prepare("\n INSERT INTO scad_functions\n (name, description, person_full_name, phone, email, notes, sort_order, status, created_at, updated_at)\n VALUES\n (:name, :description, :person_full_name, :phone, :email, :notes, :sort_order, :status, NOW(), NOW())\n ");
$stmt->execute([
'name' => $name,
'description' => $description,
'person_full_name' => $personFullName,
'phone' => $phone,
'email' => $email,
'notes' => $notes,
'sort_order' => $sortOrder,
'status' => $status,
]);
scadJsonResponse(['success' => true, 'message' => 'Funzione creata correttamente.']);
}
if ($action === 'delete') {
$id = (int)($_POST['id'] ?? 0);
if ($id <= 0) {
scadJsonResponse(['success' => false, 'message' => 'ID funzione non valido.']);
}
$stmtUse = $pdo->prepare('SELECT COUNT(*) FROM scad_deadlines WHERE function_id = ?');
$stmtUse->execute([$id]);
$inUse = (int)$stmtUse->fetchColumn();
if ($inUse > 0) {
scadJsonResponse([
'success' => false,
'message' => 'Impossibile eliminare: la funzione è utilizzata in ' . $inUse . ' scadenza/e.'
]);
}
$stmt = $pdo->prepare('DELETE FROM scad_functions WHERE id = :id');
$stmt->execute(['id' => $id]);
scadJsonResponse(['success' => true, 'message' => 'Funzione eliminata correttamente.']);
}
scadJsonResponse(['success' => false, 'message' => 'Azione non riconosciuta.']);
} catch (Exception $e) {
scadJsonResponse(['success' => false, 'message' => $e->getMessage()]);
}
}
$functions = $pdo->query("\n SELECT f.*,\n (SELECT COUNT(*) FROM scad_deadlines d WHERE d.function_id = f.id) AS deadline_count,\n (SELECT COUNT(*) FROM scad_deadlines d WHERE d.function_id = f.id AND d.status <> 'completed') AS open_count\n FROM scad_functions f\n ORDER BY COALESCE(f.sort_order, 0) ASC, f.name ASC\n")->fetchAll(PDO::FETCH_ASSOC);
?>
<!doctype html>
<html lang="it">
@@ -24,11 +131,13 @@ $functions = $pdo->query("
<base href="<?= $baseHref ?>">
<?php include('../../cssinclude.php'); ?>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<title>Scadenzario - Funzioni</title>
<script>
if (window.innerWidth > 1024) {
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('appWrapper').classList.add('toggled');
const wrapper = document.getElementById('appWrapper');
if (wrapper) wrapper.classList.add('toggled');
});
}
</script>
@@ -39,6 +148,7 @@ $functions = $pdo->query("
--scad-heading: #2c3e6b;
--scad-card-bg: linear-gradient(135deg, #f0f4ff 0%, #e8eeff 100%);
--scad-card-border: #dde4f0;
--scad-muted: #6c757d;
}
.scad-card {
@@ -127,6 +237,63 @@ $functions = $pdo->query("
color: #fff;
}
.function-table th {
font-size: 0.82rem;
color: var(--scad-heading);
background: #f8fafc;
border-bottom: 1px solid var(--scad-card-border);
white-space: nowrap;
}
.function-table td {
font-size: 0.9rem;
vertical-align: middle;
}
.function-name {
font-weight: 700;
color: var(--scad-heading);
}
.function-description,
.function-notes {
color: var(--scad-muted);
font-size: 0.82rem;
margin-top: 2px;
max-width: 280px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.contact-line {
font-size: 0.85rem;
line-height: 1.45;
}
.contact-line a {
text-decoration: none;
}
.badge-function-status {
display: inline-flex;
align-items: center;
border-radius: 999px;
padding: 4px 10px;
font-size: 0.78rem;
font-weight: 700;
}
.badge-function-status.active {
background: #d1fae5;
color: #065f46;
}
.badge-function-status.inactive {
background: #e5e7eb;
color: #374151;
}
.function-card {
background: #fff;
border: 1px solid var(--scad-card-border);
@@ -141,12 +308,19 @@ $functions = $pdo->query("
font-size: 0.95rem;
}
.function-card .fc-meta {
font-size: 0.82rem;
color: var(--scad-muted);
margin-top: 0.35rem;
}
.function-card .fc-stats {
display: flex;
gap: 0.75rem;
font-size: 0.8rem;
color: #6c757d;
color: var(--scad-muted);
margin: 0.5rem 0;
flex-wrap: wrap;
}
.function-card .fc-stats strong {
@@ -156,7 +330,7 @@ $functions = $pdo->query("
.empty-state {
text-align: center;
padding: 3rem 1rem;
color: #6c757d;
color: var(--scad-muted);
}
.empty-state i {
@@ -165,6 +339,15 @@ $functions = $pdo->query("
margin-bottom: 1rem;
}
.modal-content {
border-radius: 0.75rem;
}
.modal-header {
background: var(--scad-card-bg);
border-bottom: 1px solid var(--scad-card-border);
}
@media (max-width: 575.98px) {
.scad-card .card-header {
flex-direction: column;
@@ -223,25 +406,48 @@ $functions = $pdo->query("
<?php else: ?>
<div id="functionsList">
<div class="d-md-none">
<?php foreach ($functions as $f): ?>
<?php
$status = $f['status'] === 'inactive' ? 'inactive' : 'active';
$statusLabel = $status === 'active' ? 'Attiva' : 'Non attiva';
?>
<div class="function-card"
data-id="<?= (int)$f['id'] ?>"
data-name="<?= htmlspecialchars($f['name'], ENT_QUOTES, 'UTF-8') ?>"
data-description="<?= htmlspecialchars($f['description'] ?? '', ENT_QUOTES, 'UTF-8') ?>"
data-status="<?= htmlspecialchars($f['status'], ENT_QUOTES, 'UTF-8') ?>"
data-person-full-name="<?= htmlspecialchars($f['person_full_name'] ?? '', ENT_QUOTES, 'UTF-8') ?>"
data-phone="<?= htmlspecialchars($f['phone'] ?? '', ENT_QUOTES, 'UTF-8') ?>"
data-email="<?= htmlspecialchars($f['email'] ?? '', ENT_QUOTES, 'UTF-8') ?>"
data-notes="<?= htmlspecialchars($f['notes'] ?? '', ENT_QUOTES, 'UTF-8') ?>"
data-sort-order="<?= (int)($f['sort_order'] ?? 0) ?>"
data-status="<?= htmlspecialchars($status, ENT_QUOTES, 'UTF-8') ?>"
data-in-use="<?= (int)$f['deadline_count'] ?>">
<div class="fc-name"><?= htmlspecialchars($f['name'], ENT_QUOTES, 'UTF-8') ?></div>
<div class="d-flex justify-content-between align-items-start gap-2">
<div class="fc-name"><?= htmlspecialchars($f['name'], ENT_QUOTES, 'UTF-8') ?></div>
<span class="badge-function-status <?= $status ?>"><?= $statusLabel ?></span>
</div>
<?php if (!empty($f['description'])): ?>
<div class="text-muted small mt-1"><?= htmlspecialchars($f['description'], ENT_QUOTES, 'UTF-8') ?></div>
<div class="fc-meta"><?= htmlspecialchars($f['description'], ENT_QUOTES, 'UTF-8') ?></div>
<?php endif; ?>
<?php if (!empty($f['person_full_name'])): ?>
<div class="fc-meta"><strong>Referente:</strong> <?= htmlspecialchars($f['person_full_name'], ENT_QUOTES, 'UTF-8') ?></div>
<?php endif; ?>
<?php if (!empty($f['phone']) || !empty($f['email'])): ?>
<div class="fc-meta">
<?php if (!empty($f['phone'])): ?>📞 <?= htmlspecialchars($f['phone'], ENT_QUOTES, 'UTF-8') ?><?php endif; ?>
<?php if (!empty($f['email'])): ?><?= !empty($f['phone']) ? '<br>' : '' ?>✉️ <?= htmlspecialchars($f['email'], ENT_QUOTES, 'UTF-8') ?><?php endif; ?>
</div>
<?php endif; ?>
<div class="fc-stats">
<span>Scadenze: <strong><?= (int)$f['deadline_count'] ?></strong></span>
<span>Aperte: <strong><?= (int)$f['open_count'] ?></strong></span>
<span>Ordine: <strong><?= (int)($f['sort_order'] ?? 0) ?></strong></span>
</div>
<div class="d-flex gap-1 justify-content-end">
@@ -258,30 +464,63 @@ $functions = $pdo->query("
<div class="d-none d-md-block">
<div class="table-responsive">
<table class="table table-hover align-middle mb-0">
<table class="table table-hover align-middle mb-0 function-table">
<thead>
<tr>
<th>Nome</th>
<th>Descrizione</th>
<th class="text-center" style="width:120px">Scadenze</th>
<th class="text-center" style="width:120px">Aperte</th>
<th class="text-center" style="width:120px">Azioni</th>
<th style="width:70px" class="text-center">Ord.</th>
<th>Funzione</th>
<th style="width:220px">Referente</th>
<th style="width:230px">Contatti</th>
<th style="width:120px" class="text-center">Stato</th>
<th style="width:120px" class="text-center">Scadenze</th>
<th style="width:120px" class="text-center">Aperte</th>
<th style="width:120px" class="text-center">Azioni</th>
</tr>
</thead>
<tbody>
<?php foreach ($functions as $f): ?>
<?php
$status = $f['status'] === 'inactive' ? 'inactive' : 'active';
$statusLabel = $status === 'active' ? 'Attiva' : 'Non attiva';
?>
<tr data-id="<?= (int)$f['id'] ?>"
data-name="<?= htmlspecialchars($f['name'], ENT_QUOTES, 'UTF-8') ?>"
data-description="<?= htmlspecialchars($f['description'] ?? '', ENT_QUOTES, 'UTF-8') ?>"
data-status="<?= htmlspecialchars($f['status'], ENT_QUOTES, 'UTF-8') ?>"
data-person-full-name="<?= htmlspecialchars($f['person_full_name'] ?? '', ENT_QUOTES, 'UTF-8') ?>"
data-phone="<?= htmlspecialchars($f['phone'] ?? '', ENT_QUOTES, 'UTF-8') ?>"
data-email="<?= htmlspecialchars($f['email'] ?? '', ENT_QUOTES, 'UTF-8') ?>"
data-notes="<?= htmlspecialchars($f['notes'] ?? '', ENT_QUOTES, 'UTF-8') ?>"
data-sort-order="<?= (int)($f['sort_order'] ?? 0) ?>"
data-status="<?= htmlspecialchars($status, ENT_QUOTES, 'UTF-8') ?>"
data-in-use="<?= (int)$f['deadline_count'] ?>">
<td class="fw-semibold" style="color:var(--scad-heading)">
<?= htmlspecialchars($f['name'], ENT_QUOTES, 'UTF-8') ?>
<td class="text-center"><?= (int)($f['sort_order'] ?? 0) ?></td>
<td>
<div class="function-name"><?= htmlspecialchars($f['name'], ENT_QUOTES, 'UTF-8') ?></div>
<?php if (!empty($f['description'])): ?>
<div class="function-description" title="<?= htmlspecialchars($f['description'], ENT_QUOTES, 'UTF-8') ?>">
<?= htmlspecialchars($f['description'], ENT_QUOTES, 'UTF-8') ?>
</div>
<?php endif; ?>
<?php if (!empty($f['notes'])): ?>
<div class="function-notes" title="<?= htmlspecialchars($f['notes'], ENT_QUOTES, 'UTF-8') ?>">
Note: <?= htmlspecialchars($f['notes'], ENT_QUOTES, 'UTF-8') ?>
</div>
<?php endif; ?>
</td>
<td class="text-muted">
<?= htmlspecialchars($f['description'] ?? '—', ENT_QUOTES, 'UTF-8') ?>
<td><?= !empty($f['person_full_name']) ? htmlspecialchars($f['person_full_name'], ENT_QUOTES, 'UTF-8') : '<span class="text-muted">—</span>' ?></td>
<td>
<?php if (!empty($f['phone'])): ?>
<div class="contact-line">📞 <a href="tel:<?= htmlspecialchars($f['phone'], ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars($f['phone'], ENT_QUOTES, 'UTF-8') ?></a></div>
<?php endif; ?>
<?php if (!empty($f['email'])): ?>
<div class="contact-line">✉️ <a href="mailto:<?= htmlspecialchars($f['email'], ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars($f['email'], ENT_QUOTES, 'UTF-8') ?></a></div>
<?php endif; ?>
<?php if (empty($f['phone']) && empty($f['email'])): ?>
<span class="text-muted"></span>
<?php endif; ?>
</td>
<td class="text-center"><span class="badge-function-status <?= $status ?>"><?= $statusLabel ?></span></td>
<td class="text-center"><?= (int)$f['deadline_count'] ?></td>
<td class="text-center"><?= (int)$f['open_count'] ?></td>
<td class="text-center">
@@ -300,9 +539,7 @@ $functions = $pdo->query("
</table>
</div>
</div>
</div>
<?php endif; ?>
</div>
</div>
@@ -314,7 +551,7 @@ $functions = $pdo->query("
</div>
<div class="modal fade" id="functionModal" tabindex="-1" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-dialog modal-dialog-centered modal-lg modal-dialog-scrollable">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="functionModalTitle">Nuova Funzione</h5>
@@ -325,20 +562,57 @@ $functions = $pdo->query("
<div class="modal-body">
<input type="hidden" id="functionId" name="id" value="">
<div class="mb-3">
<label for="functionName" class="form-label fw-semibold">Nome <span class="text-danger">*</span></label>
<input type="text" class="form-control" id="functionName" name="name" maxlength="255" required>
<div class="row">
<div class="col-12 col-md-8 mb-3">
<label for="functionName" class="form-label fw-semibold">Nome funzione <span class="text-danger">*</span></label>
<input type="text" class="form-control" id="functionName" name="name" maxlength="255" required placeholder="Es. RSPP, Medico del lavoro, RLS">
</div>
<div class="col-12 col-md-4 mb-3">
<label for="functionSortOrder" class="form-label fw-semibold">Ordine</label>
<input type="number" class="form-control" id="functionSortOrder" name="sort_order" min="0" step="1" value="0">
</div>
</div>
<div class="mb-3">
<label for="functionDescription" class="form-label fw-semibold">Descrizione</label>
<textarea class="form-control" id="functionDescription" name="description" rows="3"></textarea>
<textarea class="form-control" id="functionDescription" name="description" rows="2"></textarea>
</div>
<div class="mb-3">
<label for="functionPersonFullName" class="form-label fw-semibold">Nome e cognome referente</label>
<input type="text" class="form-control" id="functionPersonFullName" name="person_full_name" maxlength="200" placeholder="Es. Mario Rossi">
</div>
<div class="row">
<div class="col-12 col-md-6 mb-3">
<label for="functionPhone" class="form-label fw-semibold">Telefono</label>
<input type="text" class="form-control" id="functionPhone" name="phone" maxlength="80">
</div>
<div class="col-12 col-md-6 mb-3">
<label for="functionEmail" class="form-label fw-semibold">Email</label>
<input type="email" class="form-control" id="functionEmail" name="email" maxlength="190">
</div>
</div>
<div class="row">
<div class="col-12 col-md-6 mb-3">
<label for="functionStatus" class="form-label fw-semibold">Stato</label>
<select class="form-select" id="functionStatus" name="status">
<option value="active">Attiva</option>
<option value="inactive">Non attiva</option>
</select>
</div>
</div>
<div class="mb-3">
<label for="functionNotes" class="form-label fw-semibold">Note operative</label>
<textarea class="form-control" id="functionNotes" name="notes" rows="3"></textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light" data-bs-dismiss="modal">Annulla</button>
<button type="submit" class="btn btn-scad-primary">Salva</button>
<button type="submit" class="btn btn-scad-primary" id="functionSaveBtn">Salva</button>
</div>
</form>
</div>
@@ -349,6 +623,33 @@ $functions = $pdo->query("
<script>
$(function() {
function escapeHtml(value) {
return String(value == null ? '' : value).replace(/[&<>'"]/g, function(c) {
return ({
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
"'": '&#39;',
'"': '&quot;'
})[c];
});
}
function getRowData($row) {
return {
id: $row.data('id') || '',
name: $row.data('name') || '',
description: $row.data('description') || '',
person_full_name: $row.data('person-full-name') || '',
phone: $row.data('phone') || '',
email: $row.data('email') || '',
notes: $row.data('notes') || '',
sort_order: $row.data('sort-order') || 0,
status: $row.data('status') || 'active',
in_use: parseInt($row.data('in-use') || 0, 10)
};
}
function openModal(data) {
const isEdit = !!data;
@@ -356,6 +657,13 @@ $functions = $pdo->query("
$('#functionId').val(isEdit ? data.id : '');
$('#functionName').val(isEdit ? data.name : '');
$('#functionDescription').val(isEdit ? data.description : '');
$('#functionPersonFullName').val(isEdit ? data.person_full_name : '');
$('#functionPhone').val(isEdit ? data.phone : '');
$('#functionEmail').val(isEdit ? data.email : '');
$('#functionNotes').val(isEdit ? data.notes : '');
$('#functionSortOrder').val(isEdit ? data.sort_order : 0);
$('#functionStatus').val(isEdit ? data.status : 'active');
$('#functionSaveBtn').prop('disabled', false).html('Salva');
new bootstrap.Modal('#functionModal').show();
}
@@ -366,30 +674,24 @@ $functions = $pdo->query("
$('#functionsList').on('click', '.btn-edit', function() {
const $row = $(this).closest('[data-id]');
openModal({
id: $row.data('id'),
name: $row.data('name'),
description: $row.data('description')
});
openModal(getRowData($row));
});
$('#functionsList').on('click', '.btn-delete', function() {
const $row = $(this).closest('[data-id]');
const inUse = parseInt($row.data('in-use') || 0, 10);
const name = $row.data('name');
const data = getRowData($row);
if (inUse > 0) {
if (data.in_use > 0) {
Swal.fire({
icon: 'warning',
title: 'Impossibile eliminare',
text: `La funzione "${name}" è utilizzata in ${inUse} scadenz${inUse === 1 ? 'a' : 'e'}.`
text: 'La funzione "' + data.name + '" è utilizzata in ' + data.in_use + ' scadenza/e.'
});
return;
}
Swal.fire({
title: `Eliminare "${name}"?`,
title: 'Eliminare "' + data.name + '"?',
icon: 'warning',
showCancelButton: true,
confirmButtonText: 'Elimina',
@@ -398,8 +700,10 @@ $functions = $pdo->query("
}).then(function(result) {
if (!result.isConfirmed) return;
$.post('scadenzario/functions/ajax/delete_function.php', {
id: $row.data('id')
$.post(window.location.href.split('#')[0], {
ajax: '1',
action: 'delete',
id: data.id
})
.done(function(res) {
if (res.success) {
@@ -408,7 +712,7 @@ $functions = $pdo->query("
Swal.fire({
icon: 'error',
title: 'Errore',
text: res.message
text: res.message || 'Impossibile eliminare.'
});
}
})
@@ -424,10 +728,19 @@ $functions = $pdo->query("
$('#functionForm').on('submit', function(e) {
e.preventDefault();
const $btn = $('#functionSaveBtn');
const payload = {
ajax: '1',
action: 'save',
id: $('#functionId').val(),
name: $('#functionName').val().trim(),
description: $('#functionDescription').val().trim()
description: $('#functionDescription').val().trim(),
person_full_name: $('#functionPersonFullName').val().trim(),
phone: $('#functionPhone').val().trim(),
email: $('#functionEmail').val().trim(),
notes: $('#functionNotes').val().trim(),
sort_order: $('#functionSortOrder').val(),
status: $('#functionStatus').val()
};
if (!payload.name) {
@@ -438,19 +751,23 @@ $functions = $pdo->query("
return;
}
$.post('scadenzario/functions/ajax/save_function.php', payload)
$btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-1"></span>Salvataggio...');
$.post(window.location.href.split('#')[0], payload)
.done(function(res) {
if (res.success) {
location.reload();
} else {
$btn.prop('disabled', false).html('Salva');
Swal.fire({
icon: 'error',
title: 'Errore',
text: res.message
text: res.message || 'Impossibile salvare.'
});
}
})
.fail(function() {
$btn.prop('disabled', false).html('Salva');
Swal.fire({
icon: 'error',
title: 'Errore di rete'