Files
zibo-dashboard/public/userarea/job-roles.php
T

1697 lines
58 KiB
PHP

<?php
include('include/headscript.php');
if (function_exists('requirePermission')) {
requirePermission('hr.employees.view');
}
$db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection();
function jsonResponse(bool $success, string $message = '', array $extra = []): void
{
header('Content-Type: application/json; charset=utf-8');
echo json_encode(array_merge([
'success' => $success,
'message' => $message,
], $extra));
exit;
}
function cleanString(?string $value): string
{
return trim((string)$value);
}
function cleanNullableString(?string $value): ?string
{
$value = trim((string)$value);
return $value === '' ? null : $value;
}
function toActiveValue($value): int
{
return ((string)$value === '1') ? 1 : 0;
}
function syncSubRolePpeLinks(PDO $pdo, int $subRoleId, array $ppeIds): void
{
$stmt = $pdo->prepare("
DELETE FROM job_sub_role_ppe_items
WHERE job_sub_role_id = ?
");
$stmt->execute([$subRoleId]);
$ppeIds = array_values(array_unique(array_filter(array_map('intval', $ppeIds))));
if (!$ppeIds) {
return;
}
$stmt = $pdo->prepare("
INSERT INTO job_sub_role_ppe_items
(
job_sub_role_id,
ppe_item_id,
requirement_type,
sort_order,
is_active,
created_at,
updated_at
)
VALUES
(
:job_sub_role_id,
:ppe_item_id,
'mandatory',
:sort_order,
1,
CURRENT_TIMESTAMP,
CURRENT_TIMESTAMP
)
");
$sortOrder = 1;
foreach ($ppeIds as $ppeId) {
$stmt->execute([
':job_sub_role_id' => $subRoleId,
':ppe_item_id' => $ppeId,
':sort_order' => $sortOrder,
]);
$sortOrder++;
}
}
/*
|--------------------------------------------------------------------------
| AJAX actions
|--------------------------------------------------------------------------
*/
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
try {
$action = $_POST['action'];
if ($action === 'save_role') {
$id = isset($_POST['id']) && $_POST['id'] !== '' ? (int)$_POST['id'] : null;
$name = cleanString($_POST['name'] ?? '');
$description = cleanNullableString($_POST['description'] ?? null);
$sortOrder = isset($_POST['sort_order']) && $_POST['sort_order'] !== '' ? (int)$_POST['sort_order'] : 999;
$isActive = toActiveValue($_POST['is_active'] ?? 1);
if ($name === '') {
jsonResponse(false, 'Il nome della mansione è obbligatorio.');
}
if ($id) {
$stmt = $pdo->prepare("
UPDATE job_roles
SET name = :name,
description = :description,
sort_order = :sort_order,
is_active = :is_active,
updated_at = CURRENT_TIMESTAMP
WHERE id = :id
");
$stmt->execute([
':name' => $name,
':description' => $description,
':sort_order' => $sortOrder,
':is_active' => $isActive,
':id' => $id,
]);
jsonResponse(true, 'Mansione aggiornata correttamente.');
}
$stmt = $pdo->prepare("
INSERT INTO job_roles
(name, description, sort_order, is_active, created_at, updated_at)
VALUES
(:name, :description, :sort_order, :is_active, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
");
$stmt->execute([
':name' => $name,
':description' => $description,
':sort_order' => $sortOrder,
':is_active' => $isActive,
]);
jsonResponse(true, 'Mansione creata correttamente.');
}
if ($action === 'get_role') {
$id = (int)($_POST['id'] ?? 0);
if ($id <= 0) {
jsonResponse(false, 'ID mansione non valido.');
}
$stmt = $pdo->prepare("
SELECT id, name, description, sort_order, is_active
FROM job_roles
WHERE id = ?
LIMIT 1
");
$stmt->execute([$id]);
$role = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$role) {
jsonResponse(false, 'Mansione non trovata.');
}
jsonResponse(true, '', [
'role' => $role,
]);
}
if ($action === 'delete_role') {
$id = (int)($_POST['id'] ?? 0);
if ($id <= 0) {
jsonResponse(false, 'ID mansione non valido.');
}
$pdo->beginTransaction();
$stmt = $pdo->prepare("DELETE FROM job_roles WHERE id = ?");
$stmt->execute([$id]);
$pdo->commit();
jsonResponse(true, 'Mansione eliminata correttamente.');
}
if ($action === 'save_sub_role') {
$id = isset($_POST['id']) && $_POST['id'] !== '' ? (int)$_POST['id'] : null;
$jobRoleId = (int)($_POST['job_role_id'] ?? 0);
$name = cleanString($_POST['name'] ?? '');
$description = cleanNullableString($_POST['description'] ?? null);
$sortOrder = isset($_POST['sort_order']) && $_POST['sort_order'] !== '' ? (int)$_POST['sort_order'] : 999;
$isActive = toActiveValue($_POST['is_active'] ?? 1);
if ($jobRoleId <= 0) {
jsonResponse(false, 'Mansione principale non valida.');
}
if ($name === '') {
jsonResponse(false, 'Il nome della sottomansione è obbligatorio.');
}
$checkRole = $pdo->prepare("SELECT id FROM job_roles WHERE id = ? LIMIT 1");
$checkRole->execute([$jobRoleId]);
if (!$checkRole->fetchColumn()) {
jsonResponse(false, 'La mansione principale selezionata non esiste.');
}
if ($id) {
$stmt = $pdo->prepare("
UPDATE job_sub_roles
SET job_role_id = :job_role_id,
name = :name,
description = :description,
sort_order = :sort_order,
is_active = :is_active,
updated_at = CURRENT_TIMESTAMP
WHERE id = :id
");
$stmt->execute([
':job_role_id' => $jobRoleId,
':name' => $name,
':description' => $description,
':sort_order' => $sortOrder,
':is_active' => $isActive,
':id' => $id,
]);
jsonResponse(true, 'Sottomansione aggiornata correttamente.');
}
$stmt = $pdo->prepare("
INSERT INTO job_sub_roles
(job_role_id, name, description, sort_order, is_active, created_at, updated_at)
VALUES
(:job_role_id, :name, :description, :sort_order, :is_active, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
");
$stmt->execute([
':job_role_id' => $jobRoleId,
':name' => $name,
':description' => $description,
':sort_order' => $sortOrder,
':is_active' => $isActive,
]);
jsonResponse(true, 'Sottomansione creata correttamente.');
}
if ($action === 'get_sub_role') {
$id = (int)($_POST['id'] ?? 0);
if ($id <= 0) {
jsonResponse(false, 'ID sottomansione non valido.');
}
$stmt = $pdo->prepare("
SELECT id, job_role_id, name, description, sort_order, is_active
FROM job_sub_roles
WHERE id = ?
LIMIT 1
");
$stmt->execute([$id]);
$subRole = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$subRole) {
jsonResponse(false, 'Sottomansione non trovata.');
}
jsonResponse(true, '', [
'sub_role' => $subRole,
]);
}
if ($action === 'delete_sub_role') {
$id = (int)($_POST['id'] ?? 0);
if ($id <= 0) {
jsonResponse(false, 'ID sottomansione non valido.');
}
$stmt = $pdo->prepare("DELETE FROM job_sub_roles WHERE id = ?");
$stmt->execute([$id]);
jsonResponse(true, 'Sottomansione eliminata correttamente.');
}
if ($action === 'get_sub_role_ppe') {
$subRoleId = (int)($_POST['sub_role_id'] ?? 0);
if ($subRoleId <= 0) {
jsonResponse(false, 'ID sottomansione non valido.');
}
$stmt = $pdo->prepare("
SELECT jsr.id, jsr.name, jr.name AS role_name
FROM job_sub_roles jsr
INNER JOIN job_roles jr ON jr.id = jsr.job_role_id
WHERE jsr.id = ?
LIMIT 1
");
$stmt->execute([$subRoleId]);
$subRole = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$subRole) {
jsonResponse(false, 'Sottomansione non trovata.');
}
$stmt = $pdo->prepare("
SELECT ppe_item_id
FROM job_sub_role_ppe_items
WHERE job_sub_role_id = ?
AND is_active = 1
");
$stmt->execute([$subRoleId]);
$selectedPpeIds = array_map('intval', $stmt->fetchAll(PDO::FETCH_COLUMN));
jsonResponse(true, '', [
'sub_role' => $subRole,
'selected_ppe_ids' => $selectedPpeIds,
]);
}
if ($action === 'save_sub_role_ppe') {
$subRoleId = (int)($_POST['sub_role_id'] ?? 0);
$ppeIds = $_POST['ppe_items'] ?? [];
if ($subRoleId <= 0) {
jsonResponse(false, 'ID sottomansione non valido.');
}
$stmt = $pdo->prepare("SELECT id FROM job_sub_roles WHERE id = ? LIMIT 1");
$stmt->execute([$subRoleId]);
if (!$stmt->fetchColumn()) {
jsonResponse(false, 'Sottomansione non trovata.');
}
syncSubRolePpeLinks($pdo, $subRoleId, is_array($ppeIds) ? $ppeIds : []);
jsonResponse(true, 'DPI associati correttamente.');
}
jsonResponse(false, 'Azione non riconosciuta.');
} catch (Throwable $e) {
if ($pdo->inTransaction()) {
$pdo->rollBack();
}
jsonResponse(false, 'Errore: ' . $e->getMessage());
}
}
/*
|--------------------------------------------------------------------------
| Page data
|--------------------------------------------------------------------------
*/
$stmt = $pdo->prepare("
SELECT
jr.id,
jr.name,
jr.description,
jr.sort_order,
jr.is_active,
jr.created_at,
jr.updated_at,
COUNT(jsr.id) AS sub_roles_count
FROM job_roles jr
LEFT JOIN job_sub_roles jsr ON jsr.job_role_id = jr.id
GROUP BY
jr.id,
jr.name,
jr.description,
jr.sort_order,
jr.is_active,
jr.created_at,
jr.updated_at
ORDER BY jr.sort_order ASC, jr.name ASC
");
$stmt->execute();
$roles = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt = $pdo->prepare("
SELECT
jsr.id,
jsr.job_role_id,
jsr.name,
jsr.description,
jsr.sort_order,
jsr.is_active,
jr.name AS role_name
FROM job_sub_roles jsr
INNER JOIN job_roles jr ON jr.id = jsr.job_role_id
ORDER BY jr.sort_order ASC, jr.name ASC, jsr.sort_order ASC, jsr.name ASC
");
$stmt->execute();
$subRoles = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt = $pdo->prepare("
SELECT
id,
name,
category,
photo,
standard_reference,
is_active
FROM ppe_items
WHERE is_active = 1
ORDER BY sort_order ASC, name ASC
");
$stmt->execute();
$ppeItems = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt = $pdo->prepare("
SELECT
jsp.job_sub_role_id,
jsp.ppe_item_id,
p.name AS ppe_name,
p.category AS ppe_category,
p.photo AS ppe_photo
FROM job_sub_role_ppe_items jsp
INNER JOIN ppe_items p ON p.id = jsp.ppe_item_id
WHERE jsp.is_active = 1
AND p.is_active = 1
ORDER BY jsp.sort_order ASC, p.name ASC
");
$stmt->execute();
$ppeLinksRows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$ppeLinksBySubRole = [];
foreach ($ppeLinksRows as $ppeLink) {
$ppeLinksBySubRole[(int)$ppeLink['job_sub_role_id']][] = $ppeLink;
}
$subRolesByRole = [];
foreach ($subRoles as $subRole) {
$subRoleId = (int)$subRole['id'];
$subRole['ppe_items'] = $ppeLinksBySubRole[$subRoleId] ?? [];
$subRolesByRole[(int)$subRole['job_role_id']][] = $subRole;
}
$totalRoles = count($roles);
$totalActiveRoles = 0;
$totalSubRoles = count($subRoles);
$totalActiveSubRoles = 0;
foreach ($roles as $role) {
if ((int)$role['is_active'] === 1) {
$totalActiveRoles++;
}
}
foreach ($subRoles as $subRole) {
if ((int)$subRole['is_active'] === 1) {
$totalActiveSubRoles++;
}
}
$jsonFlags = JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT;
$subRolesByRoleJson = json_encode($subRolesByRole, $jsonFlags);
?>
<!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>Mansioni e Sottomansioni - <?= 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>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<style>
body {
font-size: 1rem;
background: #f8fafc;
}
.card {
border: 0;
border-radius: 18px;
box-shadow: 0 8px 24px rgba(15, 23, 42, 0.08);
}
.page-title-box {
background: linear-gradient(135deg, #e8f1ff 0%, #ffffff 70%);
border: 1px solid #dbeafe;
border-radius: 18px;
padding: 16px 18px;
margin-bottom: 16px;
}
.page-title-box h4 {
color: #1f2d3d;
font-weight: 800;
}
.page-title-box p {
color: #64748b;
margin-bottom: 0;
}
.back-dashboard {
background-color: #cfe3ff !important;
color: #1f2d3d !important;
border: 1px solid #bcd4f4 !important;
border-radius: 10px;
font-weight: 600;
padding: 9px 16px;
box-shadow: 0 3px 8px rgba(0, 0, 0, 0.08);
transition: all 0.2s ease-in-out;
}
.back-dashboard:hover {
background-color: #b9d3ff !important;
transform: translateY(-2px);
}
.btn-main-action {
background: #2563eb;
color: #ffffff;
border: 1px solid #2563eb;
border-radius: 10px;
font-weight: 700;
padding: 9px 16px;
box-shadow: 0 5px 14px rgba(37, 99, 235, 0.22);
transition: all 0.2s ease-in-out;
}
.btn-main-action:hover {
color: #ffffff;
background: #1d4ed8;
transform: translateY(-2px);
}
.stat-card {
background: #ffffff;
border: 1px solid #e2e8f0;
border-radius: 14px;
padding: 12px 14px;
height: 100%;
}
.stat-label {
color: #64748b;
font-size: 0.78rem;
font-weight: 800;
text-transform: uppercase;
letter-spacing: .04em;
}
.stat-number {
color: #0f172a;
font-size: 1.45rem;
font-weight: 800;
margin-top: 4px;
}
.table thead {
background-color: #cfe3ff;
color: #1f2d3d;
}
#tabJobRoles {
table-layout: fixed;
width: 100% !important;
}
#tabJobRoles th,
#tabJobRoles td {
vertical-align: middle;
padding-top: 8px;
padding-bottom: 8px;
}
#tabJobRoles th:nth-child(1),
#tabJobRoles td:nth-child(1) {
width: 46px;
text-align: center;
}
#tabJobRoles th:nth-child(3),
#tabJobRoles td:nth-child(3) {
width: 130px;
text-align: center;
}
#tabJobRoles th:nth-child(4),
#tabJobRoles td:nth-child(4) {
width: 105px;
text-align: center;
}
#tabJobRoles th:nth-child(5),
#tabJobRoles td:nth-child(5) {
width: 260px;
text-align: center;
}
.toggle-subroles {
border: 0;
background: #eff6ff;
color: #1d4ed8;
border-radius: 9px;
width: 30px;
height: 30px;
font-weight: 900;
line-height: 1;
transition: all 0.15s ease-in-out;
}
.toggle-subroles.is-open {
transform: rotate(90deg);
background: #dbeafe;
}
.role-name {
font-weight: 800;
color: #0f172a;
line-height: 1.15;
}
.role-description {
color: #64748b;
font-size: 0.86rem;
margin-top: 2px;
max-width: 850px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.badge-active {
background: #dcfce7;
color: #166534;
border: 1px solid #bbf7d0;
font-weight: 800;
}
.badge-inactive {
background: #fee2e2;
color: #991b1b;
border: 1px solid #fecaca;
font-weight: 800;
}
.action-btn {
border-radius: 9px;
font-weight: 700;
padding: 4px 8px;
}
.modal-content {
border: 0;
border-radius: 18px;
box-shadow: 0 24px 60px rgba(15, 23, 42, 0.22);
}
.modal-header {
border-bottom: 1px solid #e2e8f0;
background: #f8fafc;
border-radius: 18px 18px 0 0;
}
.modal-title {
font-weight: 800;
color: #1f2d3d;
}
.form-label {
font-weight: 700;
color: #334155;
}
.form-control,
.form-select {
border-radius: 10px;
}
.subroles-child-wrap {
background: #f8fafc;
border: 1px solid #e2e8f0;
border-radius: 14px;
padding: 12px;
}
.subrole-mini-card {
background: #ffffff;
border: 1px solid #e2e8f0;
border-radius: 12px;
padding: 9px 12px;
margin-bottom: 8px;
}
.subrole-mini-card:last-child {
margin-bottom: 0;
}
.subrole-row {
display: grid;
grid-template-columns: 260px minmax(260px, 1fr) 120px 260px;
gap: 12px;
align-items: center;
}
.subrole-title {
font-weight: 800;
color: #0f172a;
}
.subrole-description {
color: #64748b;
font-size: 0.86rem;
margin-top: 0;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.subrole-description.empty {
color: #94a3b8;
font-style: italic;
}
.subrole-meta {
font-size: 0.78rem;
color: #94a3b8;
font-weight: 700;
}
.subrole-ppe-cell {
text-align: center;
}
.subrole-actions-cell {
display: flex;
gap: 6px;
justify-content: flex-end;
flex-wrap: wrap;
}
@media (max-width: 1100px) {
.subrole-row {
grid-template-columns: 1fr;
gap: 8px;
}
.subrole-ppe-cell {
text-align: left;
}
.subrole-actions-cell {
justify-content: flex-start;
}
.subrole-description {
white-space: normal;
}
}
.ppe-pill {
display: inline-flex;
align-items: center;
gap: 5px;
background: #ecfdf5;
color: #166534;
border: 1px solid #bbf7d0;
border-radius: 999px;
padding: 4px 9px;
font-size: 0.78rem;
font-weight: 800;
margin: 2px;
}
.ppe-count-badge {
display: inline-flex;
align-items: center;
gap: 6px;
background: #ecfdf5;
color: #166534;
border: 1px solid #bbf7d0;
border-radius: 999px;
padding: 5px 12px;
font-size: 0.82rem;
font-weight: 800;
cursor: pointer;
transition: all 0.15s ease-in-out;
}
.ppe-count-badge:hover {
background: #d1fae5;
transform: translateY(-1px);
}
.ppe-list-popup {
text-align: left;
padding-left: 18px;
margin-bottom: 0;
}
.ppe-list-popup li {
margin-bottom: 6px;
font-weight: 600;
}
.empty-subroles-box {
border: 1px dashed #cbd5e1;
background: #ffffff;
color: #64748b;
border-radius: 12px;
padding: 14px;
text-align: center;
}
.select2-container--bootstrap-5 .select2-selection--multiple {
min-height: 120px;
border-radius: 12px;
}
.select2-container--bootstrap-5 .select2-selection--multiple .select2-selection__choice {
font-weight: 700;
}
</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="page-title-box d-flex justify-content-between align-items-center flex-wrap gap-3">
<div>
<h4 class="mb-1">Mansioni e Sottomansioni</h4>
<p>Gestione compatta delle mansioni, sottomansioni e DPI necessari.</p>
</div>
<div class="d-flex gap-2">
<button type="button" class="btn back-dashboard" onclick="history.back();">
↩️ Indietro
</button>
<button type="button" class="btn btn-main-action" id="btnOpenCreateRole">
+ Nuova Mansione
</button>
</div>
</div>
<div class="row g-3 mb-3">
<div class="col-12 col-md-3">
<div class="stat-card">
<div class="stat-label">Mansioni totali</div>
<div class="stat-number"><?= (int)$totalRoles; ?></div>
</div>
</div>
<div class="col-12 col-md-3">
<div class="stat-card">
<div class="stat-label">Mansioni attive</div>
<div class="stat-number"><?= (int)$totalActiveRoles; ?></div>
</div>
</div>
<div class="col-12 col-md-3">
<div class="stat-card">
<div class="stat-label">Sottomansioni totali</div>
<div class="stat-number"><?= (int)$totalSubRoles; ?></div>
</div>
</div>
<div class="col-12 col-md-3">
<div class="stat-card">
<div class="stat-label">Sottomansioni attive</div>
<div class="stat-number"><?= (int)$totalActiveSubRoles; ?></div>
</div>
</div>
</div>
<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">Elenco Mansioni</h5>
<div class="d-flex align-items-center gap-2">
<label class="fw-semibold mb-0">Filtro:</label>
<select id="filterStatus" class="form-select form-select-sm" style="width: 180px;">
<option value="">Tutte</option>
<option value="Attiva">Solo attive</option>
<option value="Inattiva">Solo inattive</option>
</select>
</div>
</div>
<div class="card-body">
<div class="table-responsive">
<table id="tabJobRoles" class="table table-striped align-middle" style="width:100%;">
<thead>
<tr>
<th></th>
<th>Mansione</th>
<th>Sottomansioni</th>
<th>Stato</th>
<th>Azioni</th>
</tr>
</thead>
<tbody>
<?php foreach ($roles as $role): ?>
<?php
$roleId = (int)$role['id'];
$isActive = (int)$role['is_active'] === 1;
?>
<tr data-role-id="<?= $roleId; ?>">
<td>
<button type="button"
class="toggle-subroles"
data-role-id="<?= $roleId; ?>"
title="Mostra sottomansioni">
</button>
</td>
<td>
<div class="role-name">
<?= htmlspecialchars($role['name'], ENT_QUOTES, 'UTF-8'); ?>
</div>
<?php if (!empty($role['description'])): ?>
<div class="role-description">
<?= htmlspecialchars($role['description'], ENT_QUOTES, 'UTF-8'); ?>
</div>
<?php endif; ?>
</td>
<td>
<span class="badge rounded-pill bg-primary">
<?= (int)$role['sub_roles_count']; ?>
</span>
</td>
<td>
<?php if ($isActive): ?>
<span class="badge badge-active">Attiva</span>
<?php else: ?>
<span class="badge badge-inactive">Inattiva</span>
<?php endif; ?>
</td>
<td>
<div class="d-flex justify-content-center flex-wrap gap-1">
<button type="button"
class="btn btn-sm btn-outline-success action-btn btnOpenCreateSubRole"
data-role-id="<?= $roleId; ?>"
data-role-name="<?= htmlspecialchars($role['name'], ENT_QUOTES, 'UTF-8'); ?>">
+ Sotto
</button>
<button type="button"
class="btn btn-sm btn-outline-warning action-btn btnEditRole"
data-role-id="<?= $roleId; ?>">
Edita
</button>
<button type="button"
class="btn btn-sm btn-outline-danger action-btn btnDeleteRole"
data-role-id="<?= $roleId; ?>"
data-role-name="<?= htmlspecialchars($role['name'], ENT_QUOTES, 'UTF-8'); ?>">
Cancella
</button>
</div>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<div class="text-muted small mt-3">
Usa la freccia per espandere la mansione e gestire le sottomansioni. I DPI si associano dalla singola sottomansione con selezione multipla.
</div>
</div>
</div>
</div>
</div>
<?php include('include/footer.php'); ?>
</div>
<!-- ROLE MODAL -->
<div class="modal fade" id="roleModal" tabindex="-1" aria-labelledby="roleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg modal-dialog-centered">
<form id="roleForm" class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="roleModalLabel">Nuova Mansione</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Chiudi"></button>
</div>
<div class="modal-body">
<input type="hidden" name="id" id="role_id">
<input type="hidden" name="action" value="save_role">
<div class="row g-3">
<div class="col-12 col-md-8">
<label class="form-label" for="role_name">Nome mansione *</label>
<input type="text" class="form-control" name="name" id="role_name" required maxlength="255">
</div>
<div class="col-12 col-md-2">
<label class="form-label" for="role_sort_order">Ordine</label>
<input type="number" class="form-control" name="sort_order" id="role_sort_order" value="999" min="0">
</div>
<div class="col-12 col-md-2">
<label class="form-label" for="role_is_active">Stato</label>
<select class="form-select" name="is_active" id="role_is_active">
<option value="1">Attiva</option>
<option value="0">Inattiva</option>
</select>
</div>
<div class="col-12">
<label class="form-label" for="role_description">Descrizione</label>
<textarea class="form-control" name="description" id="role_description" rows="4"></textarea>
</div>
</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-primary">Salva Mansione</button>
</div>
</form>
</div>
</div>
<!-- SUB ROLE MODAL -->
<div class="modal fade" id="subRoleModal" tabindex="-1" aria-labelledby="subRoleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg modal-dialog-centered">
<form id="subRoleForm" class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="subRoleModalLabel">Nuova Sottomansione</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Chiudi"></button>
</div>
<div class="modal-body">
<input type="hidden" name="id" id="sub_role_id">
<input type="hidden" name="action" value="save_sub_role">
<div class="row g-3">
<div class="col-12 col-md-8">
<label class="form-label" for="sub_role_job_role_id">Mansione principale *</label>
<select class="form-select" name="job_role_id" id="sub_role_job_role_id" required>
<option value="">Seleziona mansione</option>
<?php foreach ($roles as $role): ?>
<option value="<?= (int)$role['id']; ?>">
<?= htmlspecialchars($role['name'], ENT_QUOTES, 'UTF-8'); ?>
</option>
<?php endforeach; ?>
</select>
</div>
<div class="col-12 col-md-2">
<label class="form-label" for="sub_role_sort_order">Ordine</label>
<input type="number" class="form-control" name="sort_order" id="sub_role_sort_order" value="999" min="0">
</div>
<div class="col-12 col-md-2">
<label class="form-label" for="sub_role_is_active">Stato</label>
<select class="form-select" name="is_active" id="sub_role_is_active">
<option value="1">Attiva</option>
<option value="0">Inattiva</option>
</select>
</div>
<div class="col-12">
<label class="form-label" for="sub_role_name">Nome sottomansione *</label>
<input type="text" class="form-control" name="name" id="sub_role_name" required maxlength="255">
</div>
<div class="col-12">
<label class="form-label" for="sub_role_description">Descrizione</label>
<textarea class="form-control" name="description" id="sub_role_description" rows="4"></textarea>
</div>
</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-primary">Salva Sottomansione</button>
</div>
</form>
</div>
</div>
<!-- SUB ROLE PPE MODAL -->
<div class="modal fade" id="subRolePpeModal" tabindex="-1" aria-labelledby="subRolePpeModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg modal-dialog-centered">
<form id="subRolePpeForm" class="modal-content">
<div class="modal-header">
<div>
<h5 class="modal-title" id="subRolePpeModalLabel">Aggiungi DPI</h5>
<div class="text-muted small" id="subRolePpeSubtitle"></div>
</div>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Chiudi"></button>
</div>
<div class="modal-body">
<input type="hidden" name="action" value="save_sub_role_ppe">
<input type="hidden" name="sub_role_id" id="ppe_sub_role_id">
<div class="mb-3 text-muted small">
Cerca e seleziona uno o più DPI necessari per questa sottomansione. Tutti i DPI selezionati saranno considerati obbligatori.
</div>
<label class="form-label" for="ppe_items_select">DPI necessari</label>
<select class="form-select" name="ppe_items[]" id="ppe_items_select" multiple="multiple" style="width: 100%;">
<?php foreach ($ppeItems as $ppeItem): ?>
<?php
$labelParts = [$ppeItem['name']];
if (!empty($ppeItem['category'])) {
$labelParts[] = $ppeItem['category'];
}
if (!empty($ppeItem['standard_reference'])) {
$labelParts[] = $ppeItem['standard_reference'];
}
$label = implode(' · ', $labelParts);
?>
<option value="<?= (int)$ppeItem['id']; ?>">
<?= htmlspecialchars($label, ENT_QUOTES, 'UTF-8'); ?>
</option>
<?php endforeach; ?>
</select>
<?php if (empty($ppeItems)): ?>
<div class="alert alert-warning mt-3 mb-0">
Nessun DPI attivo disponibile. Crea prima i DPI dalla pagina Gestione DPI.
</div>
<?php endif; ?>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light" data-bs-dismiss="modal">Annulla</button>
<button type="submit" class="btn btn-primary">Salva DPI</button>
</div>
</form>
</div>
</div>
<?php include('jsinclude.php'); ?>
<script>
const subRolesByRole = <?= $subRolesByRoleJson ?: '{}'; ?>;
let dt;
let roleModal;
let subRoleModal;
let subRolePpeModal;
function htmlEscape(value) {
return String(value ?? '')
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#039;');
}
function showSuccess(message) {
Swal.fire({
icon: 'success',
title: message,
timer: 1100,
showConfirmButton: false
}).then(() => {
window.location.reload();
});
}
function showError(message) {
Swal.fire({
icon: 'error',
title: 'Errore',
text: message || 'Operazione non riuscita'
});
}
function ajaxPost(data) {
return fetch(window.location.href, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: new URLSearchParams(data)
})
.then(async response => {
const text = await response.text();
try {
return JSON.parse(text);
} catch (e) {
throw new Error('Risposta non JSON: ' + text);
}
});
}
function ajaxForm(form) {
const formData = new FormData(form);
return fetch(window.location.href, {
method: 'POST',
body: new URLSearchParams(formData)
})
.then(async response => {
const text = await response.text();
try {
return JSON.parse(text);
} catch (e) {
throw new Error('Risposta non JSON: ' + text);
}
});
}
function resetRoleForm() {
$('#roleForm')[0].reset();
$('#role_id').val('');
$('#role_sort_order').val('999');
$('#role_is_active').val('1');
}
function resetSubRoleForm() {
$('#subRoleForm')[0].reset();
$('#sub_role_id').val('');
$('#sub_role_sort_order').val('999');
$('#sub_role_is_active').val('1');
}
function findSubRoleById(subRoleId) {
const wantedId = String(subRoleId);
for (const roleId in subRolesByRole) {
if (!Object.prototype.hasOwnProperty.call(subRolesByRole, roleId)) {
continue;
}
const found = subRolesByRole[roleId].find(function(item) {
return String(item.id) === wantedId;
});
if (found) {
return found;
}
}
return null;
}
function buildSubRolesHtml(roleId) {
const items = subRolesByRole[String(roleId)] || [];
if (!items.length) {
return `
<div class="subroles-child-wrap">
<div class="empty-subroles-box">
Nessuna sottomansione presente per questa mansione.
</div>
</div>
`;
}
let html = '<div class="subroles-child-wrap">';
items.forEach(function(item) {
const isActive = String(item.is_active) === '1';
const statusBadge = isActive ?
'<span class="badge badge-active">Attiva</span>' :
'<span class="badge badge-inactive">Inattiva</span>';
const description = item.description ?
`<div class="subrole-description" title="${htmlEscape(item.description)}">${htmlEscape(item.description)}</div>` :
'<div class="subrole-description empty">Nessuna descrizione</div>';
let ppeHtml = '<span class="text-muted small">0 DPI</span>';
if (Array.isArray(item.ppe_items) && item.ppe_items.length) {
const ppeCount = item.ppe_items.length;
ppeHtml = `
<button type="button"
class="ppe-count-badge btnShowSubRolePpeList"
data-sub-role-id="${htmlEscape(item.id)}">
🦺 ${ppeCount} DPI
</button>
`;
}
html += `
<div class="subrole-mini-card">
<div class="subrole-row">
<div>
<div class="d-flex align-items-center gap-2 flex-wrap">
<div class="subrole-title">${htmlEscape(item.name)}</div>
${statusBadge}
</div>
</div>
<div>
${description}
</div>
<div class="subrole-ppe-cell">
${ppeHtml}
</div>
<div class="subrole-actions-cell">
<button type="button"
class="btn btn-sm btn-outline-warning action-btn btnEditSubRole"
data-sub-role-id="${htmlEscape(item.id)}">
Edita
</button>
<button type="button"
class="btn btn-sm btn-outline-primary action-btn btnManageSubRolePpe"
data-sub-role-id="${htmlEscape(item.id)}"
data-sub-role-name="${htmlEscape(item.name)}">
Aggiungi DPI
</button>
<button type="button"
class="btn btn-sm btn-outline-danger action-btn btnDeleteSubRole"
data-sub-role-id="${htmlEscape(item.id)}"
data-sub-role-name="${htmlEscape(item.name)}">
Cancella
</button>
</div>
</div>
</div>
`;
});
html += '</div>';
return html;
}
$(document).ready(function() {
roleModal = new bootstrap.Modal(document.getElementById('roleModal'));
subRoleModal = new bootstrap.Modal(document.getElementById('subRoleModal'));
subRolePpeModal = new bootstrap.Modal(document.getElementById('subRolePpeModal'));
$('#ppe_items_select').select2({
theme: 'bootstrap-5',
dropdownParent: $('#subRolePpeModal'),
placeholder: 'Cerca DPI per nome, categoria o standard...',
width: '100%',
allowClear: true,
closeOnSelect: false,
minimumResultsForSearch: 0,
language: {
noResults: function() {
return 'Nessun DPI trovato';
},
searching: function() {
return 'Ricerca...';
}
}
});
$('#ppe_items_select').on('select2:open', function() {
setTimeout(function() {
const searchField = document.querySelector('.select2-container--open .select2-search__field');
if (searchField) {
searchField.focus();
}
}, 50);
});
dt = $('#tabJobRoles').DataTable({
order: [
[1, 'asc']
],
pageLength: 25,
language: {
url: 'https://cdn.datatables.net/plug-ins/1.13.6/i18n/it-IT.json'
},
columnDefs: [{
targets: [0, 4],
orderable: false,
searchable: false
}]
});
$('#filterStatus').on('change', function() {
dt.column(3).search($(this).val()).draw();
});
});
$(document).on('click', '.toggle-subroles', function() {
const button = $(this);
const roleId = button.data('role-id');
const tr = button.closest('tr');
const row = dt.row(tr);
if (row.child.isShown()) {
row.child.hide();
button.removeClass('is-open');
return;
}
row.child(buildSubRolesHtml(roleId)).show();
button.addClass('is-open');
});
$(document).on('click', '#btnOpenCreateRole', function() {
resetRoleForm();
$('#roleModalLabel').text('Nuova Mansione');
roleModal.show();
});
$(document).on('click', '.btnEditRole', function() {
const roleId = $(this).data('role-id');
ajaxPost({
action: 'get_role',
id: roleId
})
.then(data => {
if (!data.success) {
showError(data.message);
return;
}
resetRoleForm();
$('#roleModalLabel').text('Modifica Mansione');
$('#role_id').val(data.role.id);
$('#role_name').val(data.role.name);
$('#role_description').val(data.role.description || '');
$('#role_sort_order').val(data.role.sort_order);
$('#role_is_active').val(data.role.is_active);
roleModal.show();
})
.catch(err => {
showError(err.message);
});
});
$('#roleForm').on('submit', function(e) {
e.preventDefault();
const formData = Object.fromEntries(new FormData(this).entries());
ajaxPost(formData)
.then(data => {
if (data.success) {
showSuccess(data.message);
} else {
showError(data.message);
}
})
.catch(err => {
showError(err.message);
});
});
$(document).on('click', '.btnDeleteRole', function() {
const roleId = $(this).data('role-id');
const roleName = $(this).data('role-name');
Swal.fire({
icon: 'warning',
title: 'Confermi la cancellazione?',
html: `La mansione <strong>${htmlEscape(roleName)}</strong> verrà eliminata.<br>Se esistono sottomansioni collegate, verranno eliminate automaticamente.`,
showCancelButton: true,
confirmButtonText: 'Sì, cancella',
cancelButtonText: 'Annulla',
confirmButtonColor: '#dc2626'
}).then(result => {
if (!result.isConfirmed) {
return;
}
ajaxPost({
action: 'delete_role',
id: roleId
})
.then(data => {
if (data.success) {
showSuccess(data.message);
} else {
showError(data.message);
}
})
.catch(err => {
showError(err.message);
});
});
});
$(document).on('click', '.btnOpenCreateSubRole', function() {
const roleId = $(this).data('role-id');
resetSubRoleForm();
$('#subRoleModalLabel').text('Nuova Sottomansione');
$('#sub_role_job_role_id').val(roleId);
$('#sub_role_name').focus();
subRoleModal.show();
});
$(document).on('click', '.btnEditSubRole', function() {
const subRoleId = $(this).data('sub-role-id');
ajaxPost({
action: 'get_sub_role',
id: subRoleId
})
.then(data => {
if (!data.success) {
showError(data.message);
return;
}
resetSubRoleForm();
$('#subRoleModalLabel').text('Modifica Sottomansione');
$('#sub_role_id').val(data.sub_role.id);
$('#sub_role_job_role_id').val(data.sub_role.job_role_id);
$('#sub_role_name').val(data.sub_role.name);
$('#sub_role_description').val(data.sub_role.description || '');
$('#sub_role_sort_order').val(data.sub_role.sort_order);
$('#sub_role_is_active').val(data.sub_role.is_active);
subRoleModal.show();
})
.catch(err => {
showError(err.message);
});
});
$('#subRoleForm').on('submit', function(e) {
e.preventDefault();
ajaxForm(this)
.then(data => {
if (data.success) {
showSuccess(data.message);
} else {
showError(data.message);
}
})
.catch(err => {
showError(err.message);
});
});
$(document).on('click', '.btnDeleteSubRole', function() {
const subRoleId = $(this).data('sub-role-id');
const subRoleName = $(this).data('sub-role-name');
Swal.fire({
icon: 'warning',
title: 'Confermi la cancellazione?',
html: `La sottomansione <strong>${htmlEscape(subRoleName)}</strong> verrà eliminata definitivamente.`,
showCancelButton: true,
confirmButtonText: 'Sì, cancella',
cancelButtonText: 'Annulla',
confirmButtonColor: '#dc2626'
}).then(result => {
if (!result.isConfirmed) {
return;
}
ajaxPost({
action: 'delete_sub_role',
id: subRoleId
})
.then(data => {
if (data.success) {
showSuccess(data.message);
} else {
showError(data.message);
}
})
.catch(err => {
showError(err.message);
});
});
});
$(document).on('click', '.btnShowSubRolePpeList', function(e) {
e.preventDefault();
e.stopPropagation();
const subRoleId = $(this).data('sub-role-id');
const subRole = findSubRoleById(subRoleId);
if (!subRole || !Array.isArray(subRole.ppe_items) || !subRole.ppe_items.length) {
Swal.fire({
icon: 'info',
title: 'DPI associati',
text: 'Nessun DPI collegato a questa sottomansione.'
});
return;
}
const listHtml = `
<ul class="ppe-list-popup">
${subRole.ppe_items.map(function(ppe) {
const category = ppe.ppe_category ? ` <span class="text-muted">(${htmlEscape(ppe.ppe_category)})</span>` : '';
return `
<li>
🦺 ${htmlEscape(ppe.ppe_name)}${category}
</li>
`;
}).join('')}
</ul>
`;
Swal.fire({
icon: 'info',
title: 'DPI associati',
html: listHtml,
confirmButtonText: 'Chiudi'
});
});
$(document).on('click', '.btnManageSubRolePpe', function() {
const subRoleId = $(this).data('sub-role-id');
const subRoleName = $(this).data('sub-role-name');
$('#ppe_sub_role_id').val(subRoleId);
$('#subRolePpeSubtitle').text(subRoleName);
$('#ppe_items_select').val(null).trigger('change');
ajaxPost({
action: 'get_sub_role_ppe',
sub_role_id: subRoleId
})
.then(data => {
if (!data.success) {
showError(data.message);
return;
}
const selectedPpeIds = (data.selected_ppe_ids || []).map(String);
$('#ppe_items_select').val(selectedPpeIds).trigger('change');
subRolePpeModal.show();
})
.catch(err => {
showError(err.message);
});
});
$('#subRolePpeForm').on('submit', function(e) {
e.preventDefault();
ajaxForm(this)
.then(data => {
if (data.success) {
showSuccess(data.message);
} else {
showError(data.message);
}
})
.catch(err => {
showError(err.message);
});
});
</script>
</body>
</html>