18 changed files with 1291 additions and 351 deletions
+8
View File
@@ -376,3 +376,11 @@ html body .navbar .navbar-collapsable .navbar-nav li.nav-item a.nav-link[data-fo
max-width: 14rem; max-width: 14rem;
} }
} }
.alert-danger {
background-position-y: center;
}
.card::after {
margin-top: 0!important;
}
+60
View File
@@ -0,0 +1,60 @@
<script setup lang="ts">
const props = withDefaults(defineProps<{
open: boolean
title: string
message: string
confirmLabel?: string
cancelLabel?: string
confirmClass?: string
pending?: boolean
}>(), {
confirmLabel: 'Conferma',
cancelLabel: 'Annulla',
confirmClass: 'btn-danger',
pending: false,
})
const emit = defineEmits<{
cancel: []
confirm: []
}>()
const handleBackdropClick = (event: MouseEvent) => {
if (event.target === event.currentTarget && !props.pending) {
emit('cancel')
}
}
</script>
<template>
<div v-if="open">
<div class="modal-backdrop fade show d-block" style="background: rgba(0,0,0,0.5); z-index: 1040;"></div>
<div
class="modal fade show d-block"
tabindex="-1"
style="z-index: 1050;"
@click="handleBackdropClick"
>
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content shadow">
<div class="modal-header">
<h5 class="modal-title">{{ title }}</h5>
<button type="button" class="btn-close" :disabled="pending" @click="emit('cancel')"></button>
</div>
<div class="modal-body">
<p class="mb-0">{{ message }}</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline-secondary" :disabled="pending" @click="emit('cancel')">
{{ cancelLabel }}
</button>
<button type="button" class="btn" :class="confirmClass" :disabled="pending" @click="emit('confirm')">
<span v-if="pending" class="spinner-border spinner-border-sm me-2"></span>
{{ confirmLabel }}
</button>
</div>
</div>
</div>
</div>
</div>
</template>
+126 -26
View File
@@ -1,5 +1,5 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref, computed, watch } from 'vue' import { ref, computed, watch, onUnmounted } from 'vue'
import { useRoute } from 'vue-router' import { useRoute } from 'vue-router'
import BIIcon from "~/components/BIIcon.vue"; import BIIcon from "~/components/BIIcon.vue";
@@ -10,6 +10,22 @@ watch(() => route.path, () => {
isMobileMenuOpen.value = false isMobileMenuOpen.value = false
}) })
watch(isMobileMenuOpen, (isOpen) => {
if (typeof document !== 'undefined') {
if (isOpen) {
document.body.style.overflow = 'hidden'
} else {
document.body.style.overflow = ''
}
}
})
onUnmounted(() => {
if (typeof document !== 'undefined') {
document.body.style.overflow = ''
}
})
const navLinks = [ const navLinks = [
{ name: 'Home', path: '/' }, { name: 'Home', path: '/' },
{ name: 'Fai una segnalazione', path: '/reports/new' }, { name: 'Fai una segnalazione', path: '/reports/new' },
@@ -28,8 +44,7 @@ const panelLabel = computed(() => user.value?.role?.toUpperCase() === 'ADMIN' ?
<div class="row"> <div class="row">
<div class="col-12"> <div class="col-12">
<div class="it-header-slim-wrapper-content"> <div class="it-header-slim-wrapper-content">
<a class="d-none d-lg-block navbar-brand" <a class="d-none d-lg-block navbar-brand" href="https://www.cittametropolitana.ba.it/">
href="https://www.cittametropolitana.ba.it/">
Città metropolitana di Bari Città metropolitana di Bari
</a> </a>
<div class="nav-mobile"> <div class="nav-mobile">
@@ -48,7 +63,7 @@ const panelLabel = computed(() => user.value?.role?.toUpperCase() === 'ADMIN' ?
<NuxtLink class="btn btn-primary btn-icon btn-full" to="/dashboard" <NuxtLink class="btn btn-primary btn-icon btn-full" to="/dashboard"
data-element="personal-area-dashboard" data-focus-mouse="false"> data-element="personal-area-dashboard" data-focus-mouse="false">
<span class="rounded-icon" aria-hidden="true"> <span class="rounded-icon" aria-hidden="true">
<BIIcon name="it-list" color="black" /> <BIIcon name="it-list" color="black"/>
</span> </span>
<span class="d-none d-lg-block">{{ panelLabel }}</span> <span class="d-none d-lg-block">{{ panelLabel }}</span>
</NuxtLink> </NuxtLink>
@@ -56,7 +71,7 @@ const panelLabel = computed(() => user.value?.role?.toUpperCase() === 'ADMIN' ?
<NuxtLink class="btn btn-primary btn-icon btn-full" to="/profile" <NuxtLink class="btn btn-primary btn-icon btn-full" to="/profile"
data-element="personal-area-dashboard" data-focus-mouse="false"> data-element="personal-area-dashboard" data-focus-mouse="false">
<span class="rounded-icon" aria-hidden="true"> <span class="rounded-icon" aria-hidden="true">
<BIIcon name="it-user" color="black" /> <BIIcon name="it-user" color="black"/>
</span> </span>
<span class="d-none d-lg-block">{{ user?.first_name }}</span> <span class="d-none d-lg-block">{{ user?.first_name }}</span>
</NuxtLink> </NuxtLink>
@@ -64,7 +79,7 @@ const panelLabel = computed(() => user.value?.role?.toUpperCase() === 'ADMIN' ?
<button class="btn btn-primary btn-icon btn-full border-0" @click="logout" <button class="btn btn-primary btn-icon btn-full border-0" @click="logout"
data-element="personal-area-logout" data-focus-mouse="false"> data-element="personal-area-logout" data-focus-mouse="false">
<span class="rounded-icon" aria-hidden="true"> <span class="rounded-icon" aria-hidden="true">
<BIIcon name="it-logout" color="black" /> <BIIcon name="it-logout" color="black"/>
</span> </span>
<span class="d-none d-lg-block">Esci</span> <span class="d-none d-lg-block">Esci</span>
</button> </button>
@@ -73,12 +88,11 @@ const panelLabel = computed(() => user.value?.role?.toUpperCase() === 'ADMIN' ?
<NuxtLink v-else class="btn btn-primary btn-icon btn-full" to="/auth/login" <NuxtLink v-else class="btn btn-primary btn-icon btn-full" to="/auth/login"
data-element="personal-area-login" data-focus-mouse="false"> data-element="personal-area-login" data-focus-mouse="false">
<span class="rounded-icon" aria-hidden="true"> <span class="rounded-icon" aria-hidden="true">
<BIIcon name="it-user" color="black" /> <BIIcon name="it-user" color="black"/>
</span> </span>
<span class="d-none d-lg-block">Login</span> <span class="d-none d-lg-block">Login</span>
</NuxtLink> </NuxtLink>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
@@ -92,13 +106,13 @@ const panelLabel = computed(() => user.value?.role?.toUpperCase() === 'ADMIN' ?
<div class="col-12"> <div class="col-12">
<div class="it-header-center-content-wrapper"> <div class="it-header-center-content-wrapper">
<div class="it-brand-wrapper"> <div class="it-brand-wrapper">
<NuxtLink to="/"> <NuxtLink to="/">
<img src="/icon.svg" alt="Logo Visione" style="width: 48px; height: 48px; margin-right: 16px;" /> <img src="/icon.svg" alt="Logo Visione" class="logo"/>
<div class="it-brand-text"> <div class="it-brand-text">
<div class="it-brand-title">Visione</div> <div class="it-brand-title">Visione</div>
<div class="it-brand-tagline d-none d-md-block">Un occhio per la sicurezza del cittadino.</div> <div class="it-brand-tagline d-none d-md-block">Un occhio per la sicurezza del cittadino.</div>
</div> </div>
</NuxtLink> </NuxtLink>
</div> </div>
</div> </div>
</div> </div>
@@ -111,6 +125,7 @@ const panelLabel = computed(() => user.value?.role?.toUpperCase() === 'ADMIN' ?
<div class="row"> <div class="row">
<div class="col-12"> <div class="col-12">
<nav class="navbar navbar-expand-lg has-megamenu" aria-label="Navigazione principale"> <nav class="navbar navbar-expand-lg has-megamenu" aria-label="Navigazione principale">
<button <button
class="custom-navbar-toggler" class="custom-navbar-toggler"
type="button" type="button"
@@ -124,19 +139,16 @@ const panelLabel = computed(() => user.value?.role?.toUpperCase() === 'ADMIN' ?
class="overlay" class="overlay"
:class="{ 'show': isMobileMenuOpen }" :class="{ 'show': isMobileMenuOpen }"
@click="isMobileMenuOpen = false" @click="isMobileMenuOpen = false"
style="display: block;"
v-show="isMobileMenuOpen"
></div> ></div>
<div <div
class="navbar-collapsable" class="navbar-collapsable"
:class="{ 'expanded': isMobileMenuOpen }" :class="{ 'expanded': isMobileMenuOpen }"
style="display: block;"
> >
<div class="close-div"> <div class="close-div">
<button class="btn close-menu" type="button" @click="isMobileMenuOpen = false"> <button class="btn close-menu" type="button" @click="isMobileMenuOpen = false">
<span class="visually-hidden">Nascondi la navigazione</span> <span class="visually-hidden">Nascondi la navigazione</span>
<BIIcon name="it-close-big"/> <BIIcon name="it-close-big" color="black"/>
</button> </button>
</div> </div>
@@ -184,14 +196,102 @@ const panelLabel = computed(() => user.value?.role?.toUpperCase() === 'ADMIN' ?
background-color: rgb(0, 76.5, 153); background-color: rgb(0, 76.5, 153);
} }
.overlay { @media (max-width: 991.98px) {
transition: opacity 0.3s ease; .overlay {
opacity: 0; position: fixed;
pointer-events: none; top: 0;
left: 0;
width: 100vw;
height: 100vh;
background-color: rgba(0, 0, 0, 0.6) !important;
z-index: 1040;
opacity: 0;
visibility: hidden;
transition: opacity 0.3s ease, visibility 0.3s ease;
}
.overlay.show {
opacity: 1;
visibility: visible;
}
.navbar-collapsable {
position: fixed !important;
top: 0;
left: 0;
width: 320px;
max-width: 85vw;
height: 100vh;
background-color: #ffffff !important;
z-index: 1050 !important;
transform: translateX(-100%);
transition: transform 0.3s ease-in-out;
display: flex;
flex-direction: column;
box-shadow: 4px 0 15px rgba(0, 0, 0, 0.2);
overflow-y: auto;
}
.navbar-collapsable.expanded {
transform: translateX(0);
}
.close-div {
display: flex;
justify-content: flex-end;
padding: 1rem 1.5rem;
}
.close-menu {
background: transparent;
border: none;
padding: 0;
}
.close-menu :deep(svg) {
width: 32px;
height: 32px;
}
.menu-wrapper {
padding: 1rem 0;
}
.navbar-nav {
display: flex;
flex-direction: column;
padding: 0;
margin: 0;
list-style: none;
}
.nav-item {
width: 100%;
}
.nav-link {
display: block;
padding: 1rem 1.5rem;
color: #1a1a1a !important;
font-size: 1.1rem;
font-weight: 600;
text-decoration: none;
border-bottom: 1px solid #f0f0f0;
}
.nav-link.active {
color: #004c99 !important;
background-color: #f8f9fa;
}
} }
.overlay.show { .btn-full {
opacity: 1; padding: 14px;
pointer-events: auto; }
.logo {
width: 48px;
height: 48px;
margin-inline: 16px;
} }
</style> </style>
+46 -68
View File
@@ -44,6 +44,7 @@ const removeFile = (idx: number) => {
<template> <template>
<div class="message-composer mt-3"> <div class="message-composer mt-3">
<form @submit.prevent="handleSubmit"> <form @submit.prevent="handleSubmit">
<div v-if="files.length > 0" class="message-files mb-3"> <div v-if="files.length > 0" class="message-files mb-3">
<div v-for="(file, idx) in files" :key="idx" class="message-file-chip"> <div v-for="(file, idx) in files" :key="idx" class="message-file-chip">
<BIIcon name="it-clip" size="xs" /> <BIIcon name="it-clip" size="xs" />
@@ -52,43 +53,42 @@ const removeFile = (idx: number) => {
</div> </div>
</div> </div>
<div class="composer-shell"> <div class="d-flex align-items-stretch gap-2">
<input <input
ref="fileInputRef" ref="fileInputRef"
type="file" type="file"
multiple multiple
class="d-none" class="d-none"
@change="handleFileSelect" @change="handleFileSelect"
accept="image/*,video/*,.pdf,.doc,.docx" accept="image/*,video/*,.pdf,.doc,.docx"
/> />
<button <button
type="button" type="button"
class="btn btn-outline-primary btn-icon composer-attach" class="btn btn-outline-primary btn-square flex-shrink-0"
title="Allega file" title="Allega file"
@click="fileInputRef?.click()" @click="fileInputRef?.click()"
:disabled="isSubmitting || files.length >= 5" :disabled="isSubmitting || files.length >= 5"
> >
<BIIcon name="it-clip" size="sm" /> <BIIcon name="it-clip" size="sm" />
</button> </button>
<textarea <textarea
v-model="message" v-model="message"
class="form-control composer-textarea" class="form-control chat-textarea m-0"
placeholder="Scrivi aggiornamento o domanda" placeholder="Scrivi aggiornamento o domanda"
rows="2" :disabled="isSubmitting"
:disabled="isSubmitting" @keydown="handleKeydown"
@keydown="handleKeydown" ></textarea>
/>
<button <button
type="submit" type="submit"
class="btn btn-primary composer-submit" class="btn btn-primary btn-square flex-shrink-0"
:disabled="isSubmitting || (message.trim() === '' && files.length === 0)" :disabled="isSubmitting || (message.trim() === '' && files.length === 0)"
title="Invia"
> >
<span v-if="isSubmitting" class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span> <span v-if="isSubmitting" class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
<BIIcon v-else name="it-arrow-right" size="sm" color="white" class="me-1" /> <BIIcon v-else name="it-arrow-right" size="sm" color="white" />
Invia
</button> </button>
</div> </div>
@@ -126,54 +126,32 @@ const removeFile = (idx: number) => {
max-width: 14rem; max-width: 14rem;
} }
.composer-shell {
align-items: flex-end;
background: #fff;
border: 1px solid #c5d0db;
border-radius: 4px;
display: grid;
gap: 0.75rem;
grid-template-columns: auto minmax(0, 1fr) auto;
padding: 0.75rem;
}
.composer-shell:focus-within {
border-color: #06c;
box-shadow: 0 0 0 2px rgba(0, 102, 204, 0.12);
}
.composer-attach {
flex-shrink: 0;
}
.composer-textarea {
border: 0;
box-shadow: none;
min-height: 4rem;
padding: 0;
resize: vertical;
}
.composer-submit {
min-width: 7rem;
}
.btn-close-sm { .btn-close-sm {
font-size: 0.55rem; font-size: 0.55rem;
} }
@media (max-width: 767.98px) { .chat-textarea {
.composer-shell { resize: none !important;
grid-template-columns: auto 1fr; height: 48px;
} min-height: 48px;
overflow-y: auto;
padding-top: 12px;
padding-bottom: 12px;
border-radius: 6px;
}
.composer-textarea { .chat-textarea:focus {
grid-column: 1 / -1; border-color: #06c;
} box-shadow: 0 0 0 2px rgba(0, 102, 204, 0.12);
}
.composer-submit { .btn-square {
grid-column: 2; width: 48px;
justify-self: end; height: 48px;
} padding: 0;
display: flex;
align-items: center;
justify-content: center;
border-radius: 6px;
} }
</style> </style>
+38 -34
View File
@@ -9,6 +9,7 @@ interface Props {
actionVariant?: ActionVariant actionVariant?: ActionVariant
actionLabel?: string actionLabel?: string
showAssignee?: boolean showAssignee?: boolean
processingIds?: number[]
} }
const props = withDefaults(defineProps<Props>(), { const props = withDefaults(defineProps<Props>(), {
@@ -16,6 +17,7 @@ const props = withDefaults(defineProps<Props>(), {
actionVariant: 'open', actionVariant: 'open',
actionLabel: 'Open report', actionLabel: 'Open report',
showAssignee: false, showAssignee: false,
processingIds: () => [],
}) })
const emit = defineEmits<{ const emit = defineEmits<{
@@ -38,52 +40,54 @@ const reportHref = (report: Report) => `${props.detailBasePath}/${report.id}`
<div class="table-responsive report-table-wrapper"> <div class="table-responsive report-table-wrapper">
<table class="table table-hover report-table mb-0"> <table class="table table-hover report-table mb-0">
<thead> <thead>
<tr> <tr>
<th scope="col">ID</th> <th scope="col">ID</th>
<th scope="col">Categoria</th> <th scope="col">Categoria</th>
<th scope="col">Indirizzo</th> <th scope="col">Indirizzo</th>
<th scope="col">Stato</th> <th scope="col">Stato</th>
<th v-if="showAssignee" scope="col">Operatore</th> <th v-if="showAssignee" scope="col">Operatore</th>
<th scope="col">Creazione</th> <th scope="col">Creazione</th>
<th scope="col" class="text-end">Azioni</th> <th scope="col" class="text-end">Azioni</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
<tr v-for="report in reports" :key="report.id" class="align-middle"> <tr v-for="report in reports" :key="report.id" class="align-middle">
<td class="report-table-id">#{{ report.id }}</td> <td class="report-table-id">#{{ report.id }}</td>
<td class="text-nowrap">{{ report.category_name || '-' }}</td> <td class="text-nowrap">{{ report.category_name || '-' }}</td>
<td> <td>
<span class="report-address" :title="report.address"> <span class="report-address d-inline-block text-truncate align-middle" style="max-width: 10ch;" :title="report.address">
{{ report.address || '-' }} {{ report.address || '-' }}
</span> </span>
</td> </td>
<td> <td>
<StatusBadge :status="report.status" /> <StatusBadge :status="report.status" />
</td> </td>
<td v-if="showAssignee" class="text-muted"> <td v-if="showAssignee" class="text-muted">
{{ report.assigned_operator_id ? `#${report.assigned_operator_id}` : '-' }} {{ report.assigned_operator_id ? `#${report.assigned_operator_id}` : '-' }}
</td> </td>
<td class="text-muted text-nowrap">{{ formatDate(report.created_at) }}</td> <td class="text-muted text-nowrap">{{ formatDate(report.created_at) }}</td>
<td class="text-end"> <td class="text-end">
<button <button
v-if="actionVariant === 'manage'" v-if="actionVariant === 'manage'"
type="button" type="button"
class="btn btn-primary btn-xs" class="btn btn-primary btn-xs"
:disabled="processingIds.includes(report.id)"
@click="emit('take', report.id)" @click="emit('take', report.id)"
> >
Prendi in carico <span v-if="processingIds.includes(report.id)" class="spinner-border spinner-border-sm me-1" role="status" aria-hidden="true"></span>
</button> Prendi in carico
<NuxtLink </button>
<NuxtLink
v-else v-else
:to="reportHref(report)" :to="reportHref(report)"
class="btn btn-outline-primary btn-xs btn-icon" class="btn btn-outline-primary btn-xs btn-icon d-inline-flex align-items-center justify-content-center"
:aria-label="actionLabel" :aria-label="actionLabel"
:title="actionLabel" :title="actionLabel"
> >
<BIIcon name="it-arrow-right" size="xs" /> <BIIcon name="it-arrow-right" size="xs" />
</NuxtLink> </NuxtLink>
</td> </td>
</tr> </tr>
</tbody> </tbody>
</table> </table>
</div> </div>
+10 -3
View File
@@ -4,10 +4,17 @@ const { getOpenReports, getAssignedReports, takeReport } = useOperator()
const { data: openReportsRes, refresh: refreshOpen } = useAsyncData('open-reports', () => getOpenReports({ per_page: 5 })) const { data: openReportsRes, refresh: refreshOpen } = useAsyncData('open-reports', () => getOpenReports({ per_page: 5 }))
const { data: assignedReportsRes, refresh: refreshAssigned } = useAsyncData('assigned-reports', () => getAssignedReports({ per_page: 5 })) const { data: assignedReportsRes, refresh: refreshAssigned } = useAsyncData('assigned-reports', () => getAssignedReports({ per_page: 5 }))
const processingIds = ref<number[]>([])
const handleTakeReport = async (id: number) => { const handleTakeReport = async (id: number) => {
const res = await takeReport(id) processingIds.value.push(id)
if (res.ok) { try {
await Promise.all([refreshOpen(), refreshAssigned()]) const res = await takeReport(id)
if (res.ok) {
await Promise.all([refreshOpen(), refreshAssigned()])
}
} finally {
processingIds.value = processingIds.value.filter(pid => pid !== id)
} }
} }
</script> </script>
+25
View File
@@ -3,6 +3,7 @@ import type {
ModerationListResponse, ModerationListResponse,
OkResponse, OkResponse,
OverviewStatsResponse, TeamListResponse, UpdateModerationRequest, OverviewStatsResponse, TeamListResponse, UpdateModerationRequest,
UpdateAreaRequest, UpdateCategoryRequest, UpdateTeamRequest,
UpdateUserBanRequest, UpdateUserRolesRequest, UpdateUserBanRequest, UpdateUserRolesRequest,
UserListResponse UserListResponse
} from "~/types/api"; } from "~/types/api";
@@ -26,18 +27,36 @@ export const useAdmin = () => {
const createArea = (body: CreateAreaRequest) => const createArea = (body: CreateAreaRequest) =>
useApiFetch<OkResponse>('/api/v1/admin/areas', { method: 'POST', body }) useApiFetch<OkResponse>('/api/v1/admin/areas', { method: 'POST', body })
const updateArea = (id: number, body: UpdateAreaRequest) =>
useApiFetch<OkResponse>(`/api/v1/admin/areas/${id}`, { method: 'PATCH', body })
const deleteArea = (id: number) =>
useApiFetch<OkResponse>(`/api/v1/admin/areas/${id}`, { method: 'DELETE' })
const getCategories = () => const getCategories = () =>
useApiFetch<CategoryListResponse>('/api/v1/admin/categories', { method: 'GET' }) useApiFetch<CategoryListResponse>('/api/v1/admin/categories', { method: 'GET' })
const createCategory = (body: CreateCategoryRequest) => const createCategory = (body: CreateCategoryRequest) =>
useApiFetch<OkResponse>('/api/v1/admin/categories', { method: 'POST', body }) useApiFetch<OkResponse>('/api/v1/admin/categories', { method: 'POST', body })
const updateCategory = (id: number, body: UpdateCategoryRequest) =>
useApiFetch<OkResponse>(`/api/v1/admin/categories/${id}`, { method: 'PATCH', body })
const deleteCategory = (id: number) =>
useApiFetch<OkResponse>(`/api/v1/admin/categories/${id}`, { method: 'DELETE' })
const getTeams = () => const getTeams = () =>
useApiFetch<TeamListResponse>('/api/v1/admin/teams', { method: 'GET' }) useApiFetch<TeamListResponse>('/api/v1/admin/teams', { method: 'GET' })
const createTeam = (body: CreateTeamRequest) => const createTeam = (body: CreateTeamRequest) =>
useApiFetch<OkResponse>('/api/v1/admin/teams', { method: 'POST', body }) useApiFetch<OkResponse>('/api/v1/admin/teams', { method: 'POST', body })
const updateTeam = (id: number, body: UpdateTeamRequest) =>
useApiFetch<OkResponse>(`/api/v1/admin/teams/${id}`, { method: 'PATCH', body })
const deleteTeam = (id: number) =>
useApiFetch<OkResponse>(`/api/v1/admin/teams/${id}`, { method: 'DELETE' })
const getModerationFlags = (query?: { status?: string; page?: number; per_page?: number }) => const getModerationFlags = (query?: { status?: string; page?: number; per_page?: number }) =>
useApiFetch<ModerationListResponse>('/api/v1/admin/moderation', { method: 'GET', query }) useApiFetch<ModerationListResponse>('/api/v1/admin/moderation', { method: 'GET', query })
@@ -51,10 +70,16 @@ export const useAdmin = () => {
updateUserRoles, updateUserRoles,
getAreas, getAreas,
createArea, createArea,
updateArea,
deleteArea,
getCategories, getCategories,
createCategory, createCategory,
updateCategory,
deleteCategory,
getTeams, getTeams,
createTeam, createTeam,
updateTeam,
deleteTeam,
getModerationFlags, getModerationFlags,
updateModerationFlag, updateModerationFlag,
} }
+9
View File
@@ -1,4 +1,5 @@
import type { import type {
AssignmentLinkResponse,
AssignTeamRequest, AssignTeamRequest,
InterventionSummaryResponse, InterventionSummaryResponse,
OkResponse, OkResponse,
@@ -32,6 +33,12 @@ export const useOperator = () => {
const getInterventionSummary = (id: number) => const getInterventionSummary = (id: number) =>
useApiFetch<InterventionSummaryResponse>(`/api/v1/reports/${id}/intervention-summary`, { method: 'GET' }) useApiFetch<InterventionSummaryResponse>(`/api/v1/reports/${id}/intervention-summary`, { method: 'GET' })
const createInterventionLink = (id: number) =>
useApiFetch<AssignmentLinkResponse>(`/api/v1/reports/${id}/intervention-link`, { method: 'POST' })
const revokeInterventionLink = (id: number) =>
useApiFetch<OkResponse>(`/api/v1/reports/${id}/intervention-link`, { method: 'DELETE' })
return { return {
getOpenReports, getOpenReports,
getAssignedReports, getAssignedReports,
@@ -41,5 +48,7 @@ export const useOperator = () => {
updateReportStatus, updateReportStatus,
assignTeam, assignTeam,
getInterventionSummary, getInterventionSummary,
createInterventionLink,
revokeInterventionLink,
} }
} }
+14
View File
@@ -11,6 +11,7 @@ import Footer from "~/components/Footer.vue";
<slot /> <slot />
</main> </main>
<div class="italian-flag"></div>
<Footer /> <Footer />
</div> </div>
</template> </template>
@@ -22,6 +23,19 @@ import Footer from "~/components/Footer.vue";
min-height: 100vh; min-height: 100vh;
} }
div.italian-flag {
height: 8px;
width: 100%;
background: linear-gradient(to right, #009246 0%, #009246 33.33%, #F1F2F1 33.33%, #F1F2F1 66.66%, #CE2B37 66.66%, #CE2B37 100%);
}
div.italian-flag {
height: 8px;
width: 100%;
box-shadow: rgb(0 0 0 / 0.7) 0 0 30px;
background: linear-gradient(to right, #009246 0%, #009246 33.33%, #F1F2F1 33.33%, #F1F2F1 66.66%, #CE2B37 66.66%, #CE2B37 100%);
}
.app-main { .app-main {
flex-grow: 1; flex-grow: 1;
} }
+161 -15
View File
@@ -1,5 +1,5 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref, reactive, nextTick, onBeforeUnmount } from 'vue' import { ref, reactive, nextTick, onBeforeUnmount, computed } from 'vue'
import { BARI_BOUNDS, BARI_CENTER, isWithinBariBounds } from '~/utils/bari' import { BARI_BOUNDS, BARI_CENTER, isWithinBariBounds } from '~/utils/bari'
definePageMeta({ definePageMeta({
@@ -9,23 +9,37 @@ definePageMeta({
useHead({ title: 'Aree - Admin' }) useHead({ title: 'Aree - Admin' })
const { getAreas, createArea } = useAdmin() const { getAreas, createArea, updateArea, deleteArea } = useAdmin()
const { data: areasRes, pending, refresh } = useAsyncData('admin-areas', () => getAreas()) const { data: areasRes, pending, refresh } = useAsyncData('admin-areas', () => getAreas())
const isCreating = ref(false) const isCreating = ref(false)
const editingAreaId = ref<number | null>(null)
const formData = reactive({ const formData = reactive({
name: '', name: '',
description: '', description: '',
geojson: '' geojson: ''
}) })
const jsonError = ref('') const jsonError = ref('')
const actionError = ref('')
const deletingAreaId = ref<number | null>(null)
const areaPendingDelete = ref<any | null>(null)
// Map variables // Map variables
let map: any = null let map: any = null
let polygon: any = null let polygon: any = null
const mapPoints = ref<[number, number][]>([]) const mapPoints = ref<[number, number][]>([])
const modalTitle = computed(() => editingAreaId.value ? 'Modifica Area' : 'Nuova Area')
const submitLabel = computed(() => editingAreaId.value ? 'Salva Modifiche' : 'Crea Area')
const isEditing = computed(() => editingAreaId.value !== null)
const areas = computed(() => areasRes.value?.areas || [])
const areaDeleteMessage = computed(() =>
areaPendingDelete.value ? `Vuoi eliminare area "${areaPendingDelete.value.name}"? Operazione irreversibile.` : ''
)
const openCreateModal = () => { const openCreateModal = () => {
actionError.value = ''
editingAreaId.value = null
formData.name = '' formData.name = ''
formData.description = '' formData.description = ''
formData.geojson = '' formData.geojson = ''
@@ -74,6 +88,74 @@ const openCreateModal = () => {
}) })
} }
const loadPolygonFromGeoJson = (boundaryGeojson: any) => {
const coordinates = boundaryGeojson?.coordinates?.[0]
if (!Array.isArray(coordinates)) {
mapPoints.value = []
return
}
const normalized = coordinates
.slice(0, -1)
.map(([longitude, latitude]: [number, number]) => [latitude, longitude] as [number, number])
mapPoints.value = normalized
if (polygon) {
polygon.setLatLngs(mapPoints.value)
}
}
const openEditModal = (area: any) => {
actionError.value = ''
editingAreaId.value = area.id
formData.name = area.name || ''
formData.description = area.description || ''
formData.geojson = area.boundary_geojson ? JSON.stringify(area.boundary_geojson, null, 2) : ''
jsonError.value = ''
mapPoints.value = []
isCreating.value = true
nextTick(async () => {
const L = (await import('leaflet')).default
if (map) {
map.remove()
map = null
}
const bariBounds = L.latLngBounds(
[BARI_BOUNDS.south, BARI_BOUNDS.west],
[BARI_BOUNDS.north, BARI_BOUNDS.east]
)
map = L.map('areaMap', {
maxBounds: bariBounds,
maxBoundsViscosity: 1,
minZoom: 12
}).setView(BARI_CENTER, 12)
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
attribution: '© OpenStreetMap'
}).addTo(map)
polygon = L.polygon([], { color: 'red' }).addTo(map)
map.fitBounds(bariBounds)
loadPolygonFromGeoJson(area.boundary_geojson)
map.on('click', (e: any) => {
if (!isWithinBariBounds(e.latlng.lat, e.latlng.lng)) {
jsonError.value = 'Puoi disegnare aree solo entro confini del Comune di Bari.'
return
}
jsonError.value = ''
mapPoints.value.push([e.latlng.lat, e.latlng.lng])
polygon.setLatLngs(mapPoints.value)
updateGeojson()
})
})
}
const clearMap = () => { const clearMap = () => {
mapPoints.value = [] mapPoints.value = []
if (polygon) { if (polygon) {
@@ -100,6 +182,7 @@ const updateGeojson = () => {
const closeCreateModal = () => { const closeCreateModal = () => {
isCreating.value = false isCreating.value = false
editingAreaId.value = null
if (map) { if (map) {
map.remove() map.remove()
map = null map = null
@@ -131,19 +214,58 @@ const handleCreate = async () => {
} }
try { try {
const res = await createArea({ const payload = {
name: formData.name, name: formData.name,
description: formData.description || undefined, description: formData.description || undefined,
boundary_geojson: parsedGeojson boundary_geojson: parsedGeojson
}) }
const res = editingAreaId.value
? await updateArea(editingAreaId.value, payload)
: await createArea(payload)
if (res.ok) { if (res.ok) {
await refresh() await refresh()
closeCreateModal() closeCreateModal()
actionError.value = ''
} }
} catch (err) { } catch (err) {
console.error('Failed to create area', err) console.error('Failed to save area', err)
alert('Errore durante la creazione dell\'area.') actionError.value = 'Errore durante il salvataggio dell\'area.'
}
}
const askDeleteArea = (area: any) => {
areaPendingDelete.value = area
}
const closeDeleteAreaModal = () => {
if (deletingAreaId.value) return
areaPendingDelete.value = null
}
const handleDeleteArea = async () => {
if (!areaPendingDelete.value) return
const area = areaPendingDelete.value
deletingAreaId.value = area.id
actionError.value = ''
try {
const res = await deleteArea(area.id)
if (res.ok) {
if (editingAreaId.value === area.id) {
closeCreateModal()
}
await refresh()
areaPendingDelete.value = null
}
} catch (err: any) {
console.error('Failed to delete area', err)
actionError.value = err?.data?.message || 'Errore durante eliminazione area.'
} finally {
deletingAreaId.value = null
} }
} }
</script> </script>
@@ -165,10 +287,14 @@ const handleCreate = async () => {
<div class="spinner-border text-primary" role="status"></div> <div class="spinner-border text-primary" role="status"></div>
</div> </div>
<div v-else-if="!areasRes?.areas || areasRes.areas.length === 0" class="alert alert-info"> <div v-else-if="areas.length === 0" class="alert alert-info">
Nessuna area configurata. Nessuna area configurata.
</div> </div>
<div v-if="actionError" class="alert alert-danger">
{{ actionError }}
</div>
<div v-else class="table-responsive"> <div v-else class="table-responsive">
<table class="table table-hover align-middle bg-white shadow-sm rounded"> <table class="table table-hover align-middle bg-white shadow-sm rounded">
<thead class="table-light"> <thead class="table-light">
@@ -176,23 +302,32 @@ const handleCreate = async () => {
<th>ID</th> <th>ID</th>
<th>Nome</th> <th>Nome</th>
<th>Descrizione</th> <th>Descrizione</th>
<th>Stato</th>
<th>GeoJSON</th> <th>GeoJSON</th>
<th class="text-end">Azioni</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
<tr v-for="area in areasRes.areas" :key="area.id"> <tr v-for="area in areas" :key="area.id">
<td>{{ area.id }}</td> <td>{{ area.id }}</td>
<td><strong>{{ area.name }}</strong></td> <td><strong>{{ area.name }}</strong></td>
<td>{{ area.description || '-' }}</td> <td>{{ area.description || '-' }}</td>
<td>
<span v-if="area.active" class="badge bg-success">Attiva</span>
<span v-else class="badge bg-secondary">Inattiva</span>
</td>
<td> <td>
<span v-if="area.boundary_geojson" class="badge border border-primary text-primary">Configurato</span> <span v-if="area.boundary_geojson" class="badge border border-primary text-primary">Configurato</span>
<span v-else class="badge border border-danger text-danger">Mancante</span> <span v-else class="badge border border-danger text-danger">Mancante</span>
</td> </td>
<td class="text-end">
<button class="btn btn-sm btn-outline-primary me-2" @click="openEditModal(area)">
Modifica
</button>
<button
class="btn btn-sm btn-outline-danger ms-2"
:disabled="deletingAreaId === area.id"
@click="askDeleteArea(area)"
>
<span v-if="deletingAreaId === area.id" class="spinner-border spinner-border-sm me-1"></span>
Elimina
</button>
</td>
</tr> </tr>
</tbody> </tbody>
</table> </table>
@@ -204,7 +339,7 @@ const handleCreate = async () => {
<div class="modal-dialog modal-xl modal-dialog-centered modal-dialog-scrollable"> <div class="modal-dialog modal-xl modal-dialog-centered modal-dialog-scrollable">
<div class="modal-content"> <div class="modal-content">
<div class="modal-header"> <div class="modal-header">
<h5 class="modal-title">Nuova Area</h5> <h5 class="modal-title">{{ modalTitle }}</h5>
<button type="button" class="btn-close" @click="closeCreateModal"></button> <button type="button" class="btn-close" @click="closeCreateModal"></button>
</div> </div>
<div class="modal-body"> <div class="modal-body">
@@ -251,12 +386,23 @@ const handleCreate = async () => {
<div class="modal-footer d-flex justify-content-end gap-2"> <div class="modal-footer d-flex justify-content-end gap-2">
<button type="button" class="btn btn-outline-secondary" @click="closeCreateModal">Annulla</button> <button type="button" class="btn btn-outline-secondary" @click="closeCreateModal">Annulla</button>
<button type="button" class="btn btn-primary" :disabled="!formData.name || !formData.geojson" @click="handleCreate"> <button type="button" class="btn btn-primary" :disabled="!formData.name || !formData.geojson" @click="handleCreate">
Crea Area {{ submitLabel }}
</button> </button>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
<ConfirmModal
:open="areaPendingDelete !== null"
title="Elimina area"
:message="areaDeleteMessage"
confirm-label="Elimina area"
confirm-class="btn-danger"
:pending="deletingAreaId !== null"
@cancel="closeDeleteAreaModal"
@confirm="handleDeleteArea"
/>
</div> </div>
</template> </template>
+225 -15
View File
@@ -1,4 +1,6 @@
<script setup lang="ts"> <script setup lang="ts">
import type { Category, Team } from '~/types/api'
definePageMeta({ definePageMeta({
middleware: 'auth', middleware: 'auth',
auth: { role: 'ADMIN' } auth: { role: 'ADMIN' }
@@ -6,7 +8,7 @@ definePageMeta({
useHead({ title: 'Categorie e Team - Admin' }) useHead({ title: 'Categorie e Team - Admin' })
const { createCategory, getTeams, createTeam, getAreas } = useAdmin() const { createCategory, updateCategory, deleteCategory, getTeams, createTeam, updateTeam, deleteTeam, getAreas } = useAdmin()
const { getCategories } = useReports() const { getCategories } = useReports()
const { data: categoriesRes, refresh: refreshCategories } = await useAsyncData('report-categories-admin-view', () => getCategories()) const { data: categoriesRes, refresh: refreshCategories } = await useAsyncData('report-categories-admin-view', () => getCategories())
@@ -18,6 +20,8 @@ const categoryForm = reactive({
description: '', description: '',
}) })
const editingCategoryId = ref<number | null>(null)
const teamForm = reactive({ const teamForm = reactive({
name: '', name: '',
description: '', description: '',
@@ -25,26 +29,70 @@ const teamForm = reactive({
area_id: null as number | null, area_id: null as number | null,
}) })
const editingTeamId = ref<number | null>(null)
const isSavingCategory = ref(false) const isSavingCategory = ref(false)
const isSavingTeam = ref(false) const isSavingTeam = ref(false)
const categoryError = ref('') const categoryError = ref('')
const teamError = ref('') const teamError = ref('')
const deletingCategoryId = ref<number | null>(null)
const deletingTeamId = ref<number | null>(null)
const categoryPendingDelete = ref<Category | null>(null)
const teamPendingDelete = ref<Team | null>(null)
const categories = computed(() => categoriesRes.value?.categories || []) const categories = computed(() => categoriesRes.value?.categories || [])
const teams = computed(() => teamsRes.value?.teams || []) const teams = computed(() => teamsRes.value?.teams || [])
const areas = computed(() => areasRes.value?.areas || []) const areas = computed(() => areasRes.value?.areas || [])
const categoryDeleteMessage = computed(() =>
categoryPendingDelete.value ? `Vuoi eliminare categoria "${categoryPendingDelete.value.name}"? Operazione irreversibile.` : ''
)
const teamDeleteMessage = computed(() =>
teamPendingDelete.value ? `Vuoi eliminare team "${teamPendingDelete.value.name}"? Operazione irreversibile.` : ''
)
const resetCategoryForm = () => {
editingCategoryId.value = null
categoryForm.name = ''
categoryForm.description = ''
}
const resetTeamForm = () => {
editingTeamId.value = null
teamForm.name = ''
teamForm.description = ''
teamForm.team_category_id = null
teamForm.area_id = null
}
const editCategory = (category: Category) => {
editingCategoryId.value = category.id
categoryForm.name = category.name
categoryForm.description = category.description || ''
}
const editTeam = (team: Team) => {
editingTeamId.value = team.id
teamForm.name = team.name
teamForm.description = team.description || ''
teamForm.team_category_id = team.team_category_id
teamForm.area_id = team.area_id ?? null
}
const submitCategory = async () => { const submitCategory = async () => {
categoryError.value = '' categoryError.value = ''
isSavingCategory.value = true isSavingCategory.value = true
try { try {
await createCategory({ const payload = {
name: categoryForm.name.trim(), name: categoryForm.name.trim(),
description: categoryForm.description.trim() || undefined, description: categoryForm.description.trim() || undefined,
}) }
categoryForm.name = '' if (editingCategoryId.value) {
categoryForm.description = '' await updateCategory(editingCategoryId.value, payload)
} else {
await createCategory(payload)
}
resetCategoryForm()
await refreshCategories() await refreshCategories()
} catch (error: any) { } catch (error: any) {
categoryError.value = error?.data?.message || 'Creazione categoria non riuscita.' categoryError.value = error?.data?.message || 'Creazione categoria non riuscita.'
@@ -60,16 +108,18 @@ const submitTeam = async () => {
isSavingTeam.value = true isSavingTeam.value = true
try { try {
await createTeam({ const payload = {
name: teamForm.name.trim(), name: teamForm.name.trim(),
description: teamForm.description.trim() || undefined, description: teamForm.description.trim() || undefined,
team_category_id: teamForm.team_category_id, team_category_id: teamForm.team_category_id,
area_id: teamForm.area_id || undefined, area_id: teamForm.area_id || undefined,
}) }
teamForm.name = '' if (editingTeamId.value) {
teamForm.description = '' await updateTeam(editingTeamId.value, payload)
teamForm.team_category_id = null } else {
teamForm.area_id = null await createTeam(payload)
}
resetTeamForm()
await refreshTeams() await refreshTeams()
} catch (error: any) { } catch (error: any) {
teamError.value = error?.data?.message || 'Creazione team non riuscita.' teamError.value = error?.data?.message || 'Creazione team non riuscita.'
@@ -77,6 +127,86 @@ const submitTeam = async () => {
isSavingTeam.value = false isSavingTeam.value = false
} }
} }
const toggleCategoryActive = async (category: Category) => {
try {
await updateCategory(category.id, { active: category.active === false })
await refreshCategories()
} catch (error: any) {
categoryError.value = error?.data?.message || 'Aggiornamento categoria non riuscito.'
}
}
const askDeleteCategory = (category: Category) => {
categoryPendingDelete.value = category
}
const closeDeleteCategoryModal = () => {
if (deletingCategoryId.value) return
categoryPendingDelete.value = null
}
const handleDeleteCategory = async () => {
if (!categoryPendingDelete.value) return
const category = categoryPendingDelete.value
deletingCategoryId.value = category.id
categoryError.value = ''
try {
await deleteCategory(category.id)
if (editingCategoryId.value === category.id) {
resetCategoryForm()
}
await refreshCategories()
categoryPendingDelete.value = null
} catch (error: any) {
categoryError.value = error?.data?.message || 'Eliminazione categoria non riuscita.'
} finally {
deletingCategoryId.value = null
}
}
const toggleTeamActive = async (team: Team) => {
try {
await updateTeam(team.id, { active: team.active === false })
await refreshTeams()
} catch (error: any) {
teamError.value = error?.data?.message || 'Aggiornamento team non riuscito.'
}
}
const askDeleteTeam = (team: Team) => {
teamPendingDelete.value = team
}
const closeDeleteTeamModal = () => {
if (deletingTeamId.value) return
teamPendingDelete.value = null
}
const handleDeleteTeam = async () => {
if (!teamPendingDelete.value) return
const team = teamPendingDelete.value
deletingTeamId.value = team.id
teamError.value = ''
try {
await deleteTeam(team.id)
if (editingTeamId.value === team.id) {
resetTeamForm()
}
await refreshTeams()
teamPendingDelete.value = null
} catch (error: any) {
teamError.value = error?.data?.message || 'Eliminazione team non riuscita.'
} finally {
deletingTeamId.value = null
}
}
</script> </script>
<template> <template>
@@ -113,7 +243,15 @@ const submitTeam = async () => {
</div> </div>
<button type="submit" class="btn btn-primary" :disabled="isSavingCategory || !categoryForm.name.trim()"> <button type="submit" class="btn btn-primary" :disabled="isSavingCategory || !categoryForm.name.trim()">
<span v-if="isSavingCategory" class="spinner-border spinner-border-sm me-2"></span> <span v-if="isSavingCategory" class="spinner-border spinner-border-sm me-2"></span>
Crea categoria {{ editingCategoryId ? 'Salva categoria' : 'Crea categoria' }}
</button>
<button
v-if="editingCategoryId"
type="button"
class="btn btn-outline-secondary ms-2"
@click="resetCategoryForm"
>
Annulla
</button> </button>
</form> </form>
@@ -124,6 +262,7 @@ const submitTeam = async () => {
<th>ID</th> <th>ID</th>
<th>Nome</th> <th>Nome</th>
<th>Stato</th> <th>Stato</th>
<th class="text-end">Azioni</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@@ -138,9 +277,29 @@ const submitTeam = async () => {
{{ category.active === false ? 'Inattiva' : 'Attiva' }} {{ category.active === false ? 'Inattiva' : 'Attiva' }}
</span> </span>
</td> </td>
<td class="text-end">
<button class="btn btn-sm btn-outline-primary me-2" @click="editCategory(category)">
Modifica
</button>
<button
class="btn btn-sm"
:class="category.active === false ? 'btn-outline-success' : 'btn-outline-secondary'"
@click="toggleCategoryActive(category)"
>
{{ category.active === false ? 'Attiva' : 'Disattiva' }}
</button>
<button
class="btn btn-sm btn-outline-danger ms-2"
:disabled="deletingCategoryId === category.id"
@click="askDeleteCategory(category)"
>
<span v-if="deletingCategoryId === category.id" class="spinner-border spinner-border-sm me-1"></span>
Elimina
</button>
</td>
</tr> </tr>
<tr v-if="categories.length === 0"> <tr v-if="categories.length === 0">
<td colspan="3" class="text-muted">Nessuna categoria configurata.</td> <td colspan="4" class="text-muted">Nessuna categoria configurata.</td>
</tr> </tr>
</tbody> </tbody>
</table> </table>
@@ -191,7 +350,15 @@ const submitTeam = async () => {
<div class="col-12"> <div class="col-12">
<button type="submit" class="btn btn-primary" :disabled="isSavingTeam || !teamForm.name.trim() || !teamForm.team_category_id"> <button type="submit" class="btn btn-primary" :disabled="isSavingTeam || !teamForm.name.trim() || !teamForm.team_category_id">
<span v-if="isSavingTeam" class="spinner-border spinner-border-sm me-2"></span> <span v-if="isSavingTeam" class="spinner-border spinner-border-sm me-2"></span>
Crea team {{ editingTeamId ? 'Salva team' : 'Crea team' }}
</button>
<button
v-if="editingTeamId"
type="button"
class="btn btn-outline-secondary ms-2"
@click="resetTeamForm"
>
Annulla
</button> </button>
</div> </div>
</form> </form>
@@ -205,6 +372,7 @@ const submitTeam = async () => {
<th>Categoria</th> <th>Categoria</th>
<th>Area</th> <th>Area</th>
<th>Stato</th> <th>Stato</th>
<th class="text-end">Azioni</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@@ -221,9 +389,29 @@ const submitTeam = async () => {
{{ team.active === false ? 'Inattivo' : 'Attivo' }} {{ team.active === false ? 'Inattivo' : 'Attivo' }}
</span> </span>
</td> </td>
<td class="text-end">
<button class="btn btn-sm btn-outline-primary me-2" @click="editTeam(team)">
Modifica
</button>
<button
class="btn btn-sm"
:class="team.active === false ? 'btn-outline-success' : 'btn-outline-secondary'"
@click="toggleTeamActive(team)"
>
{{ team.active === false ? 'Attiva' : 'Disattiva' }}
</button>
<button
class="btn btn-sm btn-outline-danger ms-2"
:disabled="deletingTeamId === team.id"
@click="askDeleteTeam(team)"
>
<span v-if="deletingTeamId === team.id" class="spinner-border spinner-border-sm me-1"></span>
Elimina
</button>
</td>
</tr> </tr>
<tr v-if="teams.length === 0"> <tr v-if="teams.length === 0">
<td colspan="5" class="text-muted">Nessun team configurato.</td> <td colspan="6" class="text-muted">Nessun team configurato.</td>
</tr> </tr>
</tbody> </tbody>
</table> </table>
@@ -232,5 +420,27 @@ const submitTeam = async () => {
</div> </div>
</div> </div>
</div> </div>
<ConfirmModal
:open="categoryPendingDelete !== null"
title="Elimina categoria"
:message="categoryDeleteMessage"
confirm-label="Elimina categoria"
confirm-class="btn-danger"
:pending="deletingCategoryId !== null"
@cancel="closeDeleteCategoryModal"
@confirm="handleDeleteCategory"
/>
<ConfirmModal
:open="teamPendingDelete !== null"
title="Elimina team"
:message="teamDeleteMessage"
confirm-label="Elimina team"
confirm-class="btn-danger"
:pending="deletingTeamId !== null"
@cancel="closeDeleteTeamModal"
@confirm="handleDeleteTeam"
/>
</div> </div>
</template> </template>
+102 -15
View File
@@ -1,5 +1,5 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref, watch } from 'vue' import { reactive, ref, watch } from 'vue'
definePageMeta({ definePageMeta({
middleware: 'auth', middleware: 'auth',
@@ -13,6 +13,19 @@ const { getModerationFlags, updateModerationFlag } = useAdmin()
const page = ref(1) const page = ref(1)
const perPage = ref(10) const perPage = ref(10)
const statusFilter = ref('') const statusFilter = ref('')
const actionError = ref('')
const resolveModal = reactive({
open: false,
flagId: null as number | null,
rejectReport: false,
note: '',
pending: false,
})
const dismissModal = reactive({
open: false,
flagId: null as number | null,
pending: false,
})
const { data: flagsRes, pending, refresh } = useAsyncData( const { data: flagsRes, pending, refresh } = useAsyncData(
'admin-moderation-flags', 'admin-moderation-flags',
@@ -20,36 +33,72 @@ const { data: flagsRes, pending, refresh } = useAsyncData(
{ watch: [page, statusFilter] } { watch: [page, statusFilter] }
) )
const handleResolve = async (id: number, rejectReport: boolean) => { const openResolveModal = (id: number, rejectReport: boolean) => {
const note = prompt('Inserisci una nota di risoluzione (opzionale):') resolveModal.open = true
if (note === null) return // cancelled resolveModal.flagId = id
resolveModal.rejectReport = rejectReport
resolveModal.note = ''
}
const closeResolveModal = () => {
if (resolveModal.pending) return
resolveModal.open = false
resolveModal.flagId = null
resolveModal.note = ''
}
const handleResolve = async () => {
if (!resolveModal.flagId) return
resolveModal.pending = true
actionError.value = ''
try { try {
const res = await updateModerationFlag(id, { const res = await updateModerationFlag(resolveModal.flagId, {
status: 'RESOLVED', status: 'RESOLVED',
reject_report: rejectReport, reject_report: resolveModal.rejectReport,
resolution_note: note resolution_note: resolveModal.note || undefined
}) })
if (res.ok) { if (res.ok) {
await refresh() await refresh()
closeResolveModal()
} }
} catch (err) { } catch (err) {
console.error('Failed to resolve flag', err) console.error('Failed to resolve flag', err)
alert('Errore durante la risoluzione della segnalazione.') actionError.value = 'Errore durante la risoluzione della segnalazione.'
} finally {
resolveModal.pending = false
} }
} }
const handleDismiss = async (id: number) => { const openDismissModal = (id: number) => {
if (!confirm('Sei sicuro di voler ignorare (dismiss) questo flag?')) return dismissModal.open = true
dismissModal.flagId = id
}
const closeDismissModal = () => {
if (dismissModal.pending) return
dismissModal.open = false
dismissModal.flagId = null
}
const handleDismiss = async () => {
if (!dismissModal.flagId) return
dismissModal.pending = true
actionError.value = ''
try { try {
const res = await updateModerationFlag(id, { status: 'DISMISSED' }) const res = await updateModerationFlag(dismissModal.flagId, { status: 'DISMISSED' })
if (res.ok) { if (res.ok) {
await refresh() await refresh()
closeDismissModal()
} }
} catch (err) { } catch (err) {
console.error('Failed to dismiss flag', err) console.error('Failed to dismiss flag', err)
alert('Errore durante l\'aggiornamento.') actionError.value = 'Errore durante l\'aggiornamento.'
} finally {
dismissModal.pending = false
} }
} }
@@ -88,6 +137,10 @@ const formatDate = (dateStr: string) => {
Nessun elemento da moderare al momento. Nessun elemento da moderare al momento.
</div> </div>
<div v-if="actionError" class="alert alert-danger">
{{ actionError }}
</div>
<div v-else> <div v-else>
<div class="card mb-3 shadow-sm border-0" v-for="flag in flagsRes.flags" :key="flag.id"> <div class="card mb-3 shadow-sm border-0" v-for="flag in flagsRes.flags" :key="flag.id">
<div class="card-header bg-light d-flex justify-content-between align-items-center"> <div class="card-header bg-light d-flex justify-content-between align-items-center">
@@ -134,13 +187,13 @@ const formatDate = (dateStr: string) => {
<div class="col-md-4 text-end" v-if="flag.status === 'OPEN'"> <div class="col-md-4 text-end" v-if="flag.status === 'OPEN'">
<div class="d-flex flex-column gap-2 mt-3 mt-md-0"> <div class="d-flex flex-column gap-2 mt-3 mt-md-0">
<button class="btn btn-outline-danger btn-sm" @click="handleResolve(flag.id, true)"> <button class="btn btn-outline-danger btn-sm" @click="openResolveModal(flag.id, true)">
<BIIcon name="it-ban" size="xs" /> Risolvi & Rigetta Segn. <BIIcon name="it-ban" size="xs" /> Risolvi & Rigetta Segn.
</button> </button>
<button class="btn btn-outline-warning btn-sm" @click="handleResolve(flag.id, false)"> <button class="btn btn-outline-warning btn-sm" @click="openResolveModal(flag.id, false)">
<BIIcon name="it-check" size="xs" /> Risolvi (Solo Avviso) <BIIcon name="it-check" size="xs" /> Risolvi (Solo Avviso)
</button> </button>
<button class="btn btn-outline-secondary btn-sm" @click="handleDismiss(flag.id)"> <button class="btn btn-outline-secondary btn-sm" @click="openDismissModal(flag.id)">
<BIIcon name="it-close" size="xs" /> Ignora Flag <BIIcon name="it-close" size="xs" /> Ignora Flag
</button> </button>
</div> </div>
@@ -157,5 +210,39 @@ const formatDate = (dateStr: string) => {
@page-change="page = $event" @page-change="page = $event"
/> />
</div> </div>
<div v-if="resolveModal.open" class="modal-backdrop fade show d-block" style="background: rgba(0,0,0,0.5); z-index: 1040;"></div>
<div v-if="resolveModal.open" class="modal fade show d-block" tabindex="-1" style="z-index: 1050;">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">{{ resolveModal.rejectReport ? 'Risolvi e rigetta segnalazione' : 'Risolvi flag' }}</h5>
<button type="button" class="btn-close" :disabled="resolveModal.pending" @click="closeResolveModal"></button>
</div>
<div class="modal-body">
<label class="form-label">Nota di risoluzione</label>
<textarea v-model="resolveModal.note" class="form-control" rows="4" placeholder="Nota opzionale"></textarea>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline-secondary" :disabled="resolveModal.pending" @click="closeResolveModal">Annulla</button>
<button type="button" class="btn btn-primary" :disabled="resolveModal.pending" @click="handleResolve">
<span v-if="resolveModal.pending" class="spinner-border spinner-border-sm me-2"></span>
Conferma
</button>
</div>
</div>
</div>
</div>
<ConfirmModal
:open="dismissModal.open"
title="Ignora flag"
message="Vuoi ignorare questo flag? Azione registrata in moderazione."
confirm-label="Ignora flag"
confirm-class="btn-outline-secondary"
:pending="dismissModal.pending"
@cancel="closeDismissModal"
@confirm="handleDismiss"
/>
</div> </div>
</template> </template>
+53 -6
View File
@@ -13,7 +13,18 @@ const { getUsers, updateUserBan, updateUserRoles } = useAdmin()
const { data: usersRes, pending, refresh } = useAsyncData('admin-users', () => getUsers()) const { data: usersRes, pending, refresh } = useAsyncData('admin-users', () => getUsers())
const search = ref('') const search = ref('')
const banError = ref('')
const roleError = ref('')
const pendingBanUser = ref<any | null>(null)
const isUpdatingBan = ref(false)
const parseRoles = (roles?: string) => roles ? roles.split(',').map((r) => r.trim().toUpperCase()).filter(Boolean) : [] const parseRoles = (roles?: string) => roles ? roles.split(',').map((r) => r.trim().toUpperCase()).filter(Boolean) : []
const banConfirmMessage = computed(() =>
pendingBanUser.value
? `Vuoi ${pendingBanUser.value.banned ? 'sbloccare' : 'bannare'} utente ${pendingBanUser.value.first_name} ${pendingBanUser.value.last_name}?`
: ''
)
const banConfirmLabel = computed(() => pendingBanUser.value?.banned ? 'Sblocca utente' : 'Banna utente')
const banConfirmClass = computed(() => pendingBanUser.value?.banned ? 'btn-success' : 'btn-danger')
const filteredUsers = computed(() => { const filteredUsers = computed(() => {
if (!usersRes.value?.users) return [] if (!usersRes.value?.users) return []
@@ -27,17 +38,33 @@ const filteredUsers = computed(() => {
) )
}) })
const handleToggleBan = async (id: number, currentBanStatus: boolean) => { const askToggleBan = (user: any) => {
if (!confirm(`Sei sicuro di voler ${currentBanStatus ? 'sbloccare' : 'bannare'} questo utente?`)) return pendingBanUser.value = user
}
const closeBanModal = () => {
if (isUpdatingBan.value) return
pendingBanUser.value = null
}
const handleToggleBan = async () => {
if (!pendingBanUser.value) return
const user = pendingBanUser.value
isUpdatingBan.value = true
banError.value = ''
try { try {
const res = await updateUserBan(id, { banned: !currentBanStatus }) const res = await updateUserBan(user.id, { banned: !user.banned })
if (res.ok) { if (res.ok) {
await refresh() await refresh()
pendingBanUser.value = null
} }
} catch (err) { } catch (err) {
console.error('Failed to update user ban status', err) console.error('Failed to update user ban status', err)
alert('Errore durante l\'aggiornamento dello stato di ban.') banError.value = 'Errore durante l\'aggiornamento dello stato di ban.'
} finally {
isUpdatingBan.value = false
} }
} }
@@ -59,6 +86,7 @@ const closeRoleModal = () => {
const saveRoles = async () => { const saveRoles = async () => {
if (!editingUserId.value) return if (!editingUserId.value) return
roleError.value = ''
try { try {
const res = await updateUserRoles(editingUserId.value, { roles: selectedRoles.value }) const res = await updateUserRoles(editingUserId.value, { roles: selectedRoles.value })
if (res.ok) { if (res.ok) {
@@ -67,7 +95,7 @@ const saveRoles = async () => {
} }
} catch (err) { } catch (err) {
console.error('Failed to update roles', err) console.error('Failed to update roles', err)
alert('Errore durante l\'aggiornamento dei ruoli.') roleError.value = 'Errore durante l\'aggiornamento dei ruoli.'
} }
} }
</script> </script>
@@ -95,6 +123,14 @@ const saveRoles = async () => {
Nessun utente trovato. Nessun utente trovato.
</div> </div>
<div v-if="banError" class="alert alert-danger">
{{ banError }}
</div>
<div v-if="roleError" class="alert alert-danger">
{{ roleError }}
</div>
<div v-else class="table-responsive"> <div v-else class="table-responsive">
<table class="table table-hover align-middle"> <table class="table table-hover align-middle">
<thead> <thead>
@@ -138,7 +174,7 @@ const saveRoles = async () => {
<button <button
class="btn btn-sm" class="btn btn-sm"
:class="user.banned ? 'btn-outline-success' : 'btn-outline-danger'" :class="user.banned ? 'btn-outline-success' : 'btn-outline-danger'"
@click="handleToggleBan(user.id, !!user.banned)" @click="askToggleBan(user)"
> >
{{ user.banned ? 'Sblocca' : 'Banna' }} {{ user.banned ? 'Sblocca' : 'Banna' }}
</button> </button>
@@ -177,5 +213,16 @@ const saveRoles = async () => {
</div> </div>
</div> </div>
</div> </div>
<ConfirmModal
:open="pendingBanUser !== null"
title="Conferma stato utente"
:message="banConfirmMessage"
:confirm-label="banConfirmLabel"
:confirm-class="banConfirmClass"
:pending="isUpdatingBan"
@cancel="closeBanModal"
@confirm="handleToggleBan"
/>
</div> </div>
</template> </template>
-3
View File
@@ -3,7 +3,6 @@ import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue'
import type { Map as LeafletMap, CircleMarker, LatLngBoundsExpression } from 'leaflet' import type { Map as LeafletMap, CircleMarker, LatLngBoundsExpression } from 'leaflet'
import { BARI_BOUNDS, BARI_CENTER, isWithinBariBounds } from '~/utils/bari' import { BARI_BOUNDS, BARI_CENTER, isWithinBariBounds } from '~/utils/bari'
// 1. API Fetching Logic
const { getOpenDataReports } = usePublic() const { getOpenDataReports } = usePublic()
// Reactive pagination state // Reactive pagination state
@@ -34,14 +33,12 @@ const prevPage = () => {
if (currentPage.value > 1) currentPage.value-- if (currentPage.value > 1) currentPage.value--
} }
// 2. View Toggle (Grid vs Map)
const currentView = ref<'grid' | 'map'>('grid') const currentView = ref<'grid' | 'map'>('grid')
const mapContainer = ref<HTMLElement | null>(null) const mapContainer = ref<HTMLElement | null>(null)
let leaflet: typeof import('leaflet') | null = null let leaflet: typeof import('leaflet') | null = null
let map: LeafletMap | null = null let map: LeafletMap | null = null
let markers: CircleMarker[] = [] let markers: CircleMarker[] = []
// 3. Helper to style status badges
const getStatusBadge = (status: string) => { const getStatusBadge = (status: string) => {
switch (status) { switch (status) {
case 'RESOLVED': return { class: 'bg-success', text: 'Risolto', icon: 'it-check-circle' } case 'RESOLVED': return { class: 'bg-success', text: 'Risolto', icon: 'it-check-circle' }
+298 -93
View File
@@ -17,7 +17,7 @@ if (!reportId) {
} }
const { getReportDetail, getMessages, addMessage, flagMessage } = useReports() const { getReportDetail, getMessages, addMessage, flagMessage } = useReports()
const { getInterventionSummary, updateReportStatus, assignTeam, getTeams } = useOperator() const { getInterventionSummary, updateReportStatus, assignTeam, getTeams, createInterventionLink, revokeInterventionLink } = useOperator()
const { user } = useAuth() const { user } = useAuth()
// Dati principali // Dati principali
@@ -33,6 +33,7 @@ const messages = computed(() => (messagesData.value as any)?.messages || [])
const summary = computed(() => (summaryData.value as any)?.summary) const summary = computed(() => (summaryData.value as any)?.summary)
const summaryMedia = computed(() => (summaryData.value as any)?.media || []) const summaryMedia = computed(() => (summaryData.value as any)?.media || [])
const teams = computed(() => teamsData.value?.teams || []) const teams = computed(() => teamsData.value?.teams || [])
const statusMeta: Record<string, string> = { const statusMeta: Record<string, string> = {
OPEN: 'Aperta', OPEN: 'Aperta',
UNDER_REVIEW: 'In revisione', UNDER_REVIEW: 'In revisione',
@@ -43,19 +44,15 @@ const statusMeta: Record<string, string> = {
CLOSED: 'Chiusa' CLOSED: 'Chiusa'
} }
// Form Cambia Stato const statusTransitions: Record<string, string[]> = {
const newStatus = ref<ReportStatus>('IN_PROGRESS') OPEN: ['UNDER_REVIEW', 'REJECTED'],
const statusNote = ref('') UNDER_REVIEW: ['ASSIGNED', 'REJECTED'],
const isUpdatingStatus = ref(false) ASSIGNED: ['IN_PROGRESS', 'REJECTED'],
IN_PROGRESS: ['RESOLVED', 'REJECTED'],
// Form Assegna Squadra RESOLVED: ['CLOSED'],
const isAssignModalOpen = ref(false) REJECTED: ['CLOSED'],
const selectedTeamId = ref<number | null>(null) CLOSED: []
const isAssigning = ref(false) }
// Messaggi
const isSubmittingMessage = ref(false)
const isFlaggingMessageId = ref<number | null>(null)
const availableStatuses: { value: ReportStatus, label: string }[] = [ const availableStatuses: { value: ReportStatus, label: string }[] = [
{ value: 'OPEN', label: 'Aperta' }, { value: 'OPEN', label: 'Aperta' },
@@ -67,9 +64,50 @@ const availableStatuses: { value: ReportStatus, label: string }[] = [
{ value: 'CLOSED', label: 'Chiusa' } { value: 'CLOSED', label: 'Chiusa' }
] ]
// Inizializza lo stato nel form const selectableStatuses = computed(() => {
if (!report.value?.status) return []
const allowed = statusTransitions[report.value.status] || []
return availableStatuses.filter(s => allowed.includes(s.value))
})
const canCreateInterventionLink = computed(() => {
if (summary.value?.assignments && Array.isArray(summary.value.assignments)) {
return summary.value.assignments.some((a: any) => !a.ended_at)
}
return ['ASSIGNED', 'IN_PROGRESS'].includes(report.value?.status)
})
const newStatus = ref<ReportStatus>('IN_PROGRESS')
const statusNote = ref('')
const isUpdatingStatus = ref(false)
// Form Assegna Squadra
const isAssignModalOpen = ref(false)
const selectedTeamId = ref<number | null>(null)
const isAssigning = ref(false)
const interventionLink = ref('')
const interventionLinkExpiresAt = ref('')
const isGeneratingInterventionLink = ref(false)
const isRevokingInterventionLink = ref(false)
const interventionLinkError = ref('')
const interventionLinkSuccess = ref('')
const isRevokeInterventionModalOpen = ref(false)
// Messaggi
const isSubmittingMessage = ref(false)
const flaggedMessageIds = ref<number[]>([])
const isFlagMessageModalOpen = ref(false)
const messageToFlag = ref<Message | null>(null)
const isFlaggingMessage = ref(false)
const isFlaggingMessageId = computed(() => isFlaggingMessage.value ? messageToFlag.value?.id : null)
watch(() => report.value?.status, (val) => { watch(() => report.value?.status, (val) => {
if (val) newStatus.value = val as ReportStatus if (val) {
const allowed = statusTransitions[val] || []
if (allowed.length > 0) {
newStatus.value = allowed[0] as ReportStatus
}
}
}, { immediate: true }) }, { immediate: true })
const handleStatusUpdate = async () => { const handleStatusUpdate = async () => {
@@ -109,6 +147,73 @@ const handleAssignTeam = async () => {
} }
} }
const copyInterventionLink = async () => {
if (!interventionLink.value || !navigator?.clipboard) return
try {
await navigator.clipboard.writeText(interventionLink.value)
interventionLinkSuccess.value = 'Link copiato negli appunti.'
interventionLinkError.value = ''
} catch {
interventionLinkError.value = 'Copia automatica non riuscita.'
interventionLinkSuccess.value = ''
}
}
const handleCreateInterventionLink = async () => {
if (!canCreateInterventionLink.value) return
isGeneratingInterventionLink.value = true
interventionLinkError.value = ''
interventionLinkSuccess.value = ''
try {
const res = await createInterventionLink(reportId)
if (res.ok) {
interventionLink.value = res.url
interventionLinkExpiresAt.value = res.expires_at
interventionLinkSuccess.value = 'Link intervento generato.'
}
} catch (e: any) {
console.error('Failed to create intervention link', e)
interventionLinkError.value = e?.data?.message || 'Generazione link non riuscita.'
} finally {
isGeneratingInterventionLink.value = false
}
}
const openRevokeInterventionLinkModal = () => {
if (!interventionLink.value) return
isRevokeInterventionModalOpen.value = true
}
const closeRevokeInterventionLinkModal = () => {
if (isRevokingInterventionLink.value) return
isRevokeInterventionModalOpen.value = false
}
const handleRevokeInterventionLink = async () => {
if (!interventionLink.value) return
isRevokingInterventionLink.value = true
interventionLinkError.value = ''
interventionLinkSuccess.value = ''
try {
const res = await revokeInterventionLink(reportId)
if (res.ok) {
interventionLink.value = ''
interventionLinkExpiresAt.value = ''
interventionLinkSuccess.value = 'Link intervento revocato.'
isRevokeInterventionModalOpen.value = false
}
} catch (e: any) {
console.error('Failed to revoke intervention link', e)
interventionLinkError.value = e?.data?.message || 'Revoca link non riuscita.'
} finally {
isRevokingInterventionLink.value = false
}
}
const handleSendMessage = async (msgText: string, files: File[]) => { const handleSendMessage = async (msgText: string, files: File[]) => {
if (!msgText.trim() && files.length === 0) return if (!msgText.trim() && files.length === 0) return
isSubmittingMessage.value = true isSubmittingMessage.value = true
@@ -124,21 +229,35 @@ const handleSendMessage = async (msgText: string, files: File[]) => {
const canFlagMessage = (message: Message) => { const canFlagMessage = (message: Message) => {
if (!user.value) return false if (!user.value) return false
return message.user_id !== user.value.id && message.user_id === report.value?.user_id const isCitizenMessage = message.user_id !== user.value.id && message.user_id === report.value?.user_id
const isAlreadyFlagged = flaggedMessageIds.value.includes(message.id)
return isCitizenMessage && !isAlreadyFlagged
} }
const handleFlagMessage = async (message: Message) => { const handleFlagMessage = (message: Message) => {
if (!canFlagMessage(message)) return if (!canFlagMessage(message)) return
isFlaggingMessageId.value = message.id messageToFlag.value = message
isFlagMessageModalOpen.value = true
}
const executeFlagMessage = async () => {
if (!messageToFlag.value) return
isFlaggingMessage.value = true
try { try {
await flagMessage(reportId, message.id, { await flagMessage(reportId, messageToFlag.value.id, {
reason: 'Messaggio segnalato da operatore responsabile per verifica moderazione', reason: 'Messaggio segnalato da operatore responsabile per verifica moderazione',
}) })
flaggedMessageIds.value.push(messageToFlag.value.id)
isFlagMessageModalOpen.value = false
messageToFlag.value = null
} catch (e) { } catch (e) {
console.error('Failed to flag message', e) console.error('Failed to flag message', e)
} finally { } finally {
isFlaggingMessageId.value = null isFlaggingMessage.value = false
} }
} }
@@ -155,9 +274,13 @@ const latestCitizenMessage = computed(() => {
if (!reportUserId) return null if (!reportUserId) return null
return [...messages.value] return [...messages.value]
.reverse() .reverse()
.find((message) => message.user_id === reportUserId) || null .find((message) => message.user_id === reportUserId) || null
}) })
const formattedInterventionLinkExpiry = computed(() =>
interventionLinkExpiresAt.value ? formatDate(interventionLinkExpiresAt.value) : ''
)
</script> </script>
<template> <template>
@@ -249,10 +372,10 @@ const latestCitizenMessage = computed(() => {
<span class="badge bg-light text-dark border">{{ messages.length }} messaggi</span> <span class="badge bg-light text-dark border">{{ messages.length }} messaggi</span>
</div> </div>
<MessageList <MessageList
:messages="messages" :messages="messages"
:can-flag-message="canFlagMessage" :can-flag-message="canFlagMessage"
:is-flagging-message-id="isFlaggingMessageId" :is-flagging-message-id="isFlaggingMessageId"
@flag="handleFlagMessage" @flag="handleFlagMessage"
/> />
<MessageComposer @send="handleSendMessage" /> <MessageComposer @send="handleSendMessage" />
</div> </div>
@@ -261,78 +384,139 @@ const latestCitizenMessage = computed(() => {
<div class="col-12 col-xl-5"> <div class="col-12 col-xl-5">
<div class="report-sidebar"> <div class="report-sidebar">
<div class="card card-bg border-0 shadow-sm mb-4" v-if="summary"> <div class="card card-bg border-0 shadow-sm mb-4" v-if="summary">
<div class="card-body"> <div class="card-body">
<h2 class="h6 mb-3">Quadro operativo</h2> <h2 class="h6 mb-3">Quadro operativo</h2>
<ul class="report-summary-list list-unstyled mb-4"> <ul class="report-summary-list list-unstyled mb-4">
<li> <li>
<span>Operatore</span> <span>Operatore</span>
<strong>{{ summary.assigned_operator_id ? `#${summary.assigned_operator_id}` : 'Nessuno' }}</strong> <strong>{{ summary.assigned_operator_id ? `#${summary.assigned_operator_id}` : 'Nessuno' }}</strong>
</li> </li>
<li> <li>
<span>Team disponibili</span> <span>Team disponibili</span>
<strong>{{ teams.length }}</strong> <strong>{{ teams.length }}</strong>
</li> </li>
<li> <li>
<span>Allegati</span> <span>Allegati</span>
<strong>{{ summaryMedia.length || media.length }}</strong> <strong>{{ summaryMedia.length || media.length }}</strong>
</li> </li>
</ul> </ul>
<div class="report-description"> <div class="report-description">
<h3 class="h6 mb-2">Ultimo messaggio cittadino</h3> <h3 class="h6 mb-2">Ultimo messaggio cittadino</h3>
<p class="small mb-0"> <p class="small mb-0">
{{ latestCitizenMessage?.body || 'Nessun messaggio del cittadino disponibile.' }} {{ latestCitizenMessage?.body || 'Nessun messaggio del cittadino disponibile.' }}
</p> </p>
</div>
</div>
<div class="card-body pt-0">
<button class="btn btn-outline-primary w-100" @click="isAssignModalOpen = true" :disabled="teams.length === 0">
Assegna team
</button>
</div> </div>
</div> </div>
<div class="card-body pt-0">
<button class="btn btn-outline-primary w-100" @click="isAssignModalOpen = true" :disabled="teams.length === 0">
Assegna team
</button>
</div>
</div>
<div class="card card-bg border-0 shadow-sm mb-4"> <div class="card card-bg border-0 shadow-sm mb-4">
<div class="card-body"> <div class="card-body">
<h2 class="h6 mb-3">Aggiorna stato</h2> <h2 class="h6 mb-3">Link intervento pubblico</h2>
<form @submit.prevent="handleStatusUpdate"> <p class="text-muted small mb-3">Genera link temporaneo per team esterno. Nuova generazione ruota link esistente.</p>
<div class="mb-3">
<label class="form-label">Nuovo Stato</label>
<select class="form-select" v-model="newStatus">
<option v-for="st in availableStatuses" :key="st.value" :value="st.value">
{{ st.label }}
</option>
</select>
</div>
<div class="mb-3">
<label class="form-label">Nota (visibile nella cronologia)</label>
<textarea class="form-control" v-model="statusNote" rows="2" placeholder="Motivazione o dettaglio..."></textarea>
</div>
<button type="submit" class="btn btn-primary w-100" :disabled="isUpdatingStatus || newStatus === report.status">
<span v-if="isUpdatingStatus" class="spinner-border spinner-border-sm me-2"></span>
Aggiorna Stato
</button>
</form>
</div>
</div>
<div class="card card-bg border-0 shadow-sm"> <div v-if="interventionLinkError" class="alert alert-danger py-2" role="alert">
<div class="card-body"> {{ interventionLinkError }}
<h2 class="h6 mb-3">Cronologia eventi</h2> </div>
<div v-if="statusHistory.length === 0" class="small text-muted">Nessun evento registrato.</div> <div v-if="interventionLinkSuccess" class="alert alert-success py-2" role="alert">
<ul class="list-unstyled mb-0 ms-2"> {{ interventionLinkSuccess }}
<li v-for="item in statusHistory" :key="item.id" class="mb-3 border-start border-primary border-3 ps-3"> </div>
<small class="text-muted d-block">{{ formatDate(item.created_at) }}</small>
<div class="d-flex align-items-center gap-2 mt-1"> <template v-if="interventionLink">
<StatusBadge :status="item.old_status" /> <label class="form-label">URL attivo</label>
<BIIcon name="it-arrow-right" size="xs" /> <div class="input-group mb-2">
<StatusBadge :status="item.new_status" /> <input type="text" class="form-control" :value="interventionLink" readonly />
<button type="button" class="btn btn-outline-primary" @click="copyInterventionLink">
Copia
</button>
</div> </div>
<div v-if="item.note" class="small mt-1 bg-light p-1 rounded">{{ item.note }}</div> <p class="small text-muted mb-3">
</li> Scade: {{ formattedInterventionLinkExpiry || '-' }}
</ul> </p>
<div class="d-grid gap-2">
<button type="button" class="btn btn-outline-primary" :disabled="isGeneratingInterventionLink || !canCreateInterventionLink" @click="handleCreateInterventionLink">
<span v-if="isGeneratingInterventionLink" class="spinner-border spinner-border-sm me-2"></span>
Rigenera link
</button>
<button type="button" class="btn btn-outline-danger" :disabled="isRevokingInterventionLink" @click="openRevokeInterventionLinkModal">
<span v-if="isRevokingInterventionLink" class="spinner-border spinner-border-sm me-2"></span>
Revoca link
</button>
</div>
</template>
<button
v-else
type="button"
class="btn btn-outline-primary w-100"
:disabled="isGeneratingInterventionLink || !canCreateInterventionLink"
@click="handleCreateInterventionLink"
>
<span v-if="isGeneratingInterventionLink" class="spinner-border spinner-border-sm me-2"></span>
Genera link
</button>
<div v-if="!canCreateInterventionLink" class="text-danger small mt-2">
È necessaria un'assegnazione in corso per generare o rigenerare questo link.
</div>
</div>
</div>
<div class="card card-bg border-0 shadow-sm mb-4">
<div class="card-body">
<h2 class="h6 mb-3">Aggiorna stato</h2>
<template v-if="selectableStatuses.length > 0">
<form @submit.prevent="handleStatusUpdate">
<div class="mb-3">
<label class="form-label">Nuovo Stato</label>
<select class="form-select" v-model="newStatus">
<option v-for="st in selectableStatuses" :key="st.value" :value="st.value">
{{ st.label }}
</option>
</select>
</div>
<div class="mb-3">
<label class="form-label">Nota (visibile nella cronologia)</label>
<textarea class="form-control" v-model="statusNote" rows="2" placeholder="Motivazione o dettaglio..."></textarea>
</div>
<button type="submit" class="btn btn-primary w-100" :disabled="isUpdatingStatus">
<span v-if="isUpdatingStatus" class="spinner-border spinner-border-sm me-2"></span>
Aggiorna Stato
</button>
</form>
</template>
<template v-else>
<div class="alert alert-info mb-0 small">
La segnalazione è attualmente in stato <strong>{{ statusMeta[report.status] }}</strong>. Non sono consentite ulteriori transizioni.
</div>
</template>
</div>
</div>
<div class="card card-bg border-0 shadow-sm">
<div class="card-body">
<h2 class="h6 mb-3">Cronologia eventi</h2>
<div v-if="statusHistory.length === 0" class="small text-muted">Nessun evento registrato.</div>
<ul class="list-unstyled mb-0 ms-2">
<li v-for="item in statusHistory" :key="item.id" class="mb-3 border-start border-primary border-3 ps-3">
<small class="text-muted d-block">{{ formatDate(item.created_at) }}</small>
<div class="d-flex align-items-center gap-2 mt-1">
<StatusBadge :status="item.old_status" />
<BIIcon name="it-arrow-right" size="xs" />
<StatusBadge :status="item.new_status" />
</div>
<div v-if="item.note" class="small mt-1 bg-light p-1 rounded">{{ item.note }}</div>
</li>
</ul>
</div>
</div> </div>
</div>
</div> </div>
</div> </div>
</div> </div>
@@ -375,6 +559,27 @@ const latestCitizenMessage = computed(() => {
</div> </div>
</div> </div>
<ConfirmModal
:open="isRevokeInterventionModalOpen"
title="Revoca link intervento"
message="Vuoi revocare link pubblico per team esterno? Link non sara piu utilizzabile."
confirm-label="Revoca link"
confirm-class="btn-danger"
:pending="isRevokingInterventionLink"
@cancel="closeRevokeInterventionLinkModal"
@confirm="handleRevokeInterventionLink"
/>
<ConfirmModal
:open="isFlagMessageModalOpen"
title="Segnala messaggio"
message="Sei sicuro di voler segnalare questo messaggio al team di moderazione per una verifica?"
confirm-label="Segnala"
confirm-class="btn-warning"
:pending="isFlaggingMessage"
@cancel="isFlagMessageModalOpen = false; messageToFlag = null"
@confirm="executeFlagMessage"
/>
</div> </div>
<div v-else class="text-center py-5"> <div v-else class="text-center py-5">
<div class="spinner-border text-primary" role="status"></div> <div class="spinner-border text-primary" role="status"></div>
+6
View File
@@ -154,3 +154,9 @@ const formatDate = (dateString: string) =>
</div> </div>
</div> </div>
</template> </template>
<style>
.card .card-body .d-grid > a {
padding-block: 8px;
}
</style>
+69 -59
View File
@@ -18,11 +18,11 @@ if (!reportId) {
// Fetch dati // Fetch dati
const { data: reportData, refresh: refreshReport } = await useAsyncData(`report-${reportId}`, () => const { data: reportData, refresh: refreshReport } = await useAsyncData(`report-${reportId}`, () =>
getReportDetail(reportId) getReportDetail(reportId)
) )
const { data: messagesData, refresh: refreshMessages } = await useAsyncData(`messages-${reportId}`, () => const { data: messagesData, refresh: refreshMessages } = await useAsyncData(`messages-${reportId}`, () =>
getMessages(reportId) getMessages(reportId)
) )
const report = computed(() => (reportData.value as any)?.report) const report = computed(() => (reportData.value as any)?.report)
@@ -31,7 +31,10 @@ const statusHistory = computed(() => (reportData.value as any)?.history || [])
const messages = computed(() => (messagesData.value as any)?.messages || []) const messages = computed(() => (messagesData.value as any)?.messages || [])
const newMessage = ref('') const newMessage = ref('')
const fileInput = ref<HTMLInputElement | null>(null)
const selectedFiles = ref<File[]>([])
const isSubmittingMessage = ref(false) const isSubmittingMessage = ref(false)
const isFeedbackOpen = ref(false) const isFeedbackOpen = ref(false)
const feedbackRating = ref(5) const feedbackRating = ref(5)
const feedbackComment = ref('') const feedbackComment = ref('')
@@ -39,14 +42,27 @@ const isSubmittingFeedback = ref(false)
const selectedMediaIndex = ref(0) const selectedMediaIndex = ref(0)
const isGalleryOpen = ref(false) const isGalleryOpen = ref(false)
// Gestione selezione file
const handleFileSelect = (event: Event) => {
const target = event.target as HTMLInputElement
if (target.files) {
selectedFiles.value = Array.from(target.files)
}
}
// Invia messaggio // Invia messaggio
const handleSendMessage = async (msgText: string, files: File[]) => { const handleSendMessage = async () => {
if (!msgText.trim() && files.length === 0) return if (!newMessage.value.trim() && selectedFiles.value.length === 0) return
isSubmittingMessage.value = true isSubmittingMessage.value = true
try { try {
// Gestione mock di file, nella realtà si usa FormData o simle await addMessage(reportId, { body: newMessage.value })
await addMessage(reportId, { body: msgText })
// Pulisci i campi
newMessage.value = ''
selectedFiles.value = []
if (fileInput.value) fileInput.value.value = ''
await refreshMessages() await refreshMessages()
} catch (error) { } catch (error) {
console.error('Error sending message:', error) console.error('Error sending message:', error)
@@ -75,7 +91,10 @@ const handleSubmitFeedback = async () => {
} }
const isOwner = computed(() => report.value?.user_id === user.value?.id) const isOwner = computed(() => report.value?.user_id === user.value?.id)
const canFeedback = computed(() => report.value?.status === 'RESOLVED' || report.value?.status === 'CLOSED')
// Valutazione solo se lo stato è specificamente "RESOLVED"
const canFeedback = computed(() => report.value?.status === 'RESOLVED')
const statusMeta: Record<string, { label: string; tone: string }> = { const statusMeta: Record<string, { label: string; tone: string }> = {
OPEN: { label: 'Aperta', tone: 'info' }, OPEN: { label: 'Aperta', tone: 'info' },
UNDER_REVIEW: { label: 'In revisione', tone: 'warning' }, UNDER_REVIEW: { label: 'In revisione', tone: 'warning' },
@@ -180,30 +199,21 @@ const formatDate = (dateString: string): string => {
</div> </div>
</div> </div>
<div v-if="statusHistory.length > 0" class="card card-bg border-0 shadow-sm mb-4"> <div class="card card-bg border-0 shadow-sm mb-4">
<div class="card-body"> <div class="card-body">
<div class="report-section-head mb-4"> <h2 class="h6 mb-3">Cronologia eventi</h2>
<BIIcon name="it-history" size="sm" color="primary" class="me-2" /> <div v-if="statusHistory.length === 0" class="small text-muted">Nessun evento registrato.</div>
<h2 class="h6 mb-0">Cronologia</h2> <ul class="list-unstyled mb-0 ms-2">
</div> <li v-for="item in statusHistory" :key="item.id" class="mb-3 border-start border-primary border-3 ps-3">
<div class="timeline"> <small class="text-muted d-block">{{ formatDate(item.created_at) }}</small>
<div v-for="item in statusHistory" :key="item.id" class="timeline-item mb-3"> <div class="d-flex align-items-center gap-2 mt-1">
<div class="d-flex gap-3"> <StatusBadge :status="item.old_status" />
<div class="flex-shrink-0"> <BIIcon name="it-arrow-right" size="xs" />
<div class="timeline-marker"></div> <StatusBadge :status="item.new_status" />
</div>
<div class="flex-grow-1">
<small class="text-muted">{{ formatDate(item.created_at) }}</small>
<div class="small font-weight-semibold d-flex align-items-center gap-2 mt-1">
<StatusBadge :status="item.old_status" />
<BIIcon name="it-arrow-right" size="xs" />
<StatusBadge :status="item.new_status" />
</div>
<small v-if="item.note" class="text-muted d-block">{{ item.note }}</small>
</div>
</div> </div>
</div> <div v-if="item.note" class="small mt-1 bg-light p-1 rounded">{{ item.note }}</div>
</div> </li>
</ul>
</div> </div>
</div> </div>
@@ -219,8 +229,10 @@ const formatDate = (dateString: string): string => {
</div> </div>
<span class="badge bg-light text-dark border">{{ messages.length }} messaggi</span> <span class="badge bg-light text-dark border">{{ messages.length }} messaggi</span>
</div> </div>
<MessageList :messages="messages" /> <MessageList :messages="messages" />
<MessageComposer @send="handleSendMessage" />
<MessageComposer @send=handleSendMessage />
</div> </div>
</div> </div>
</div> </div>
@@ -252,10 +264,10 @@ const formatDate = (dateString: string): string => {
<h2 class="h6 mb-3">Valuta intervento</h2> <h2 class="h6 mb-3">Valuta intervento</h2>
<p class="text-muted small mb-3">Lascia valutazione finale quando intervento è concluso.</p> <p class="text-muted small mb-3">Lascia valutazione finale quando intervento è concluso.</p>
<button <button
v-if="!isFeedbackOpen" v-if="!isFeedbackOpen"
type="button" type="button"
class="btn btn-primary w-100" class="btn btn-primary w-100"
@click="isFeedbackOpen = true" @click="isFeedbackOpen = true"
> >
Valuta intervento Valuta intervento
</button> </button>
@@ -267,9 +279,9 @@ const formatDate = (dateString: string): string => {
<button v-for="n in 5" :key="n" type="button" class="btn btn-link p-0" <button v-for="n in 5" :key="n" type="button" class="btn btn-link p-0"
@click="feedbackRating = n" :aria-label="`${n} stelle`"> @click="feedbackRating = n" :aria-label="`${n} stelle`">
<BIIcon <BIIcon
:name="n <= feedbackRating ? 'it-star-full' : 'it-star-outline'" :name="n <= feedbackRating ? 'it-star-full' : 'it-star-outline'"
size="lg" size="lg"
:color="n <= feedbackRating ? 'warning' : 'primary'" :color="n <= feedbackRating ? 'warning' : 'primary'"
/> />
</button> </button>
</div> </div>
@@ -277,10 +289,10 @@ const formatDate = (dateString: string): string => {
<div class="mb-3"> <div class="mb-3">
<textarea <textarea
v-model="feedbackComment" v-model="feedbackComment"
class="form-control" class="form-control"
placeholder="Commento opzionale" placeholder="Commento opzionale"
rows="3" rows="3"
/> />
</div> </div>
@@ -408,23 +420,24 @@ const formatDate = (dateString: string): string => {
justify-content: space-between; justify-content: space-between;
} }
.timeline-marker { .chat-textarea {
width: 12px; resize: none !important;
height: 12px; height: 48px;
background-color: #006f9d; min-height: 48px;
border-radius: 50%; overflow-y: auto;
border: 3px solid #f0f0f0; padding-top: 12px;
padding-bottom: 12px;
border-radius: 6px;
} }
.timeline-item:not(:last-child) .timeline-marker::after { .btn-square {
content: ''; width: 48px;
position: absolute; height: 48px;
left: 50%; padding: 0;
top: 20px; display: flex;
width: 2px; align-items: center;
height: calc(100% + 20px); justify-content: center;
background-color: #006f9d; border-radius: 6px;
transform: translateX(-50%);
} }
.ratio { .ratio {
@@ -457,6 +470,3 @@ const formatDate = (dateString: string): string => {
} }
} }
</style> </style>
+27
View File
@@ -267,11 +267,24 @@ export interface CreateAreaRequest {
description?: string; description?: string;
} }
export interface UpdateAreaRequest {
name?: string;
boundary_geojson?: GeoJsonObject;
description?: string;
active?: boolean;
}
export interface CreateCategoryRequest { export interface CreateCategoryRequest {
name: string; name: string;
description?: string; description?: string;
} }
export interface UpdateCategoryRequest {
name?: string;
description?: string;
active?: boolean;
}
export interface CreateTeamRequest { export interface CreateTeamRequest {
team_category_id: number; team_category_id: number;
name: string; name: string;
@@ -279,6 +292,14 @@ export interface CreateTeamRequest {
area_id?: number; area_id?: number;
} }
export interface UpdateTeamRequest {
team_category_id?: number;
name?: string;
description?: string;
area_id?: number | null;
active?: boolean;
}
export interface UpdateUserBanRequest { export interface UpdateUserBanRequest {
banned: boolean; banned: boolean;
} }
@@ -346,6 +367,12 @@ export interface InterventionSummaryResponse {
latest_messages: Message[]; latest_messages: Message[];
} }
export interface AssignmentLinkResponse {
ok: boolean;
url: string;
expires_at: string;
}
export interface MediaUploadResponse { export interface MediaUploadResponse {
ok: boolean; ok: boolean;
media: Media[]; media: Media[];