26 changed files with 1003 additions and 163 deletions
+1
View File
@@ -24,4 +24,5 @@ logs
!.env.example
pnpm-*.yaml
.pnpm-store/
AGENTS.md
+47
View File
@@ -29,6 +29,20 @@ textarea {
font-family: var(--visione-font-sans);
}
select,
.form-select {
background-color: #f7f9fc !important;
border-color: #c5d0db !important;
color: var(--visione-text-body) !important;
}
.form-select:focus,
select:focus {
background-color: #fff !important;
border-color: var(--visione-primary) !important;
box-shadow: 0 0 0 2px rgba(0, 102, 204, 0.15) !important;
}
code,
kbd,
pre,
@@ -296,6 +310,35 @@ html body .navbar .navbar-collapsable .navbar-nav li.nav-item a.nav-link[data-fo
line-height: 1;
}
.page-shell {
padding-block: 3rem;
}
.page-shell-header {
align-items: flex-start;
display: flex;
flex-wrap: wrap;
gap: 1rem;
justify-content: space-between;
margin-bottom: 2rem;
}
.page-shell-title {
margin-bottom: 0.25rem;
}
.page-shell-subtitle {
color: var(--visione-text-soft);
margin-bottom: 0;
max-width: 48rem;
}
.surface-card {
background: #fff;
border: 1px solid #dfe4ea;
border-radius: 4px;
}
.it-header-wrapper .header-slim-right-zone .btn .rounded-icon,
.it-header-wrapper .header-slim-right-zone .btn .rounded-icon .icon {
@@ -316,6 +359,10 @@ html body .navbar .navbar-collapsable .navbar-nav li.nav-item a.nav-link[data-fo
}
@media (max-width: 767.98px) {
.page-shell {
padding-block: 2rem;
}
.it-hero-wrapper .container {
min-height: 220px;
}
+2 -1
View File
@@ -18,6 +18,7 @@ const navLinks = [
]
const { isAuthenticated, user, logout } = useAuth()
const panelLabel = computed(() => user.value?.role?.toUpperCase() === 'ADMIN' ? 'Pannello' : 'Dashboard')
</script>
<template>
@@ -49,7 +50,7 @@ const { isAuthenticated, user, logout } = useAuth()
<span class="rounded-icon" aria-hidden="true">
<BIIcon name="it-list" color="black" />
</span>
<span class="d-none d-lg-block">Dashboard</span>
<span class="d-none d-lg-block">{{ panelLabel }}</span>
</NuxtLink>
<NuxtLink class="btn btn-primary btn-icon btn-full" to="/profile"
+332 -41
View File
@@ -2,6 +2,8 @@
import type { Category, CreateReportRequest } from '~/types/api'
import type { LeafletMouseEvent, Map as LeafletMap, Marker as LeafletMarker } from 'leaflet'
import { onMounted, onUnmounted, ref, watch } from 'vue'
import { BARI_BOUNDS, BARI_CENTER, isWithinBariBounds } from '~/utils/bari'
import { reverseGeocode, searchAddresses } from '~/utils/geocoding'
interface Props {
isLoading?: boolean
@@ -12,6 +14,12 @@ interface Emits {
(e: 'submit', report: CreateReportRequest, media: File[]): void
}
interface GeocodingSuggestion {
label: string
latitude: number
longitude: number
}
const props = withDefaults(defineProps<Props>(), {
isLoading: false,
categories: () => []
@@ -31,12 +39,23 @@ const media = ref<File[]>([])
const errors = ref<Record<string, string>>({})
const successMessage = ref(false)
const isGettingLocation = ref(false)
const addressSuggestions = ref<GeocodingSuggestion[]>([])
const isSearchingAddress = ref(false)
const isResolvingAddress = ref(false)
const addressSearchError = ref('')
const showAddressSuggestions = ref(false)
// Map variables
const mapContainer = ref<HTMLElement | null>(null)
let leaflet: typeof import('leaflet') | null = null
let map: LeafletMap | null = null
let marker: LeafletMarker | null = null
let addressSearchTimeout: ReturnType<typeof setTimeout> | null = null
let manualLocationSyncTimeout: ReturnType<typeof setTimeout> | null = null
let addressSearchRequestId = 0
let reverseGeocodeRequestId = 0
let lastSyncedLocationKey = ''
let skipNextAddressSearch = false
const loadLeaflet = async () => {
if (leaflet) return leaflet
@@ -59,51 +78,226 @@ const loadLeaflet = async () => {
return leaflet
}
const initMap = async () => {
if (!import.meta.client || !mapContainer.value || map) return
const toLocationKey = (lat: number, lng: number) => `${lat.toFixed(6)}:${lng.toFixed(6)}`
const L = await loadLeaflet()
if (!mapContainer.value || map) return
const clearAddressSuggestions = () => {
addressSuggestions.value = []
showAddressSuggestions.value = false
}
// Centro Italia default
const defaultLat = 41.8719
const defaultLng = 12.5674
const zoom = 5
const cancelPendingAddressSearch = () => {
addressSearchRequestId += 1
isSearchingAddress.value = false
map = L.map(mapContainer.value).setView([defaultLat, defaultLng], zoom)
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '&copy; OpenStreetMap contributors'
}).addTo(map)
map.on('click', (e: LeafletMouseEvent) => {
updateLocation(e.latlng.lat, e.latlng.lng)
})
// Se c'è già una posizione, imposta il marker
if (form.value.latitude && form.value.longitude) {
updateLocation(form.value.latitude, form.value.longitude, true)
if (addressSearchTimeout) {
clearTimeout(addressSearchTimeout)
addressSearchTimeout = null
}
}
const updateLocation = (lat: number, lng: number, zoomTo = false) => {
form.value.latitude = Number(lat.toFixed(6))
form.value.longitude = Number(lng.toFixed(6))
const cancelPendingReverseGeocode = () => {
reverseGeocodeRequestId += 1
isResolvingAddress.value = false
}
const setAddressValue = (address: string) => {
cancelPendingAddressSearch()
skipNextAddressSearch = true
form.value.address = address
if (errors.value.address && address.trim()) {
errors.value.address = ''
}
}
const fetchAddressSuggestions = async (query: string) => {
const requestId = ++addressSearchRequestId
isSearchingAddress.value = true
addressSearchError.value = ''
try {
if (requestId !== addressSearchRequestId) {
return
}
const suggestions = await searchAddresses(query)
if (requestId !== addressSearchRequestId) {
return
}
addressSuggestions.value = suggestions
showAddressSuggestions.value = suggestions.length > 0
if (!suggestions.length) {
addressSearchError.value = 'Nessun indirizzo trovato nel Comune di Bari.'
}
} catch {
if (requestId !== addressSearchRequestId) {
return
}
clearAddressSuggestions()
addressSearchError.value = 'Ricerca indirizzi non disponibile al momento.'
} finally {
if (requestId === addressSearchRequestId) {
isSearchingAddress.value = false
}
}
}
const resolveAddressFromCoordinates = async (lat: number, lng: number, fallbackAddress = '') => {
const requestId = ++reverseGeocodeRequestId
isResolvingAddress.value = true
addressSearchError.value = ''
try {
if (requestId !== reverseGeocodeRequestId) {
return
}
const resolvedAddress = (await reverseGeocode(lat, lng))?.trim() || fallbackAddress.trim()
if (resolvedAddress) {
setAddressValue(resolvedAddress)
clearAddressSuggestions()
return
}
if (!form.value.address.trim()) {
addressSearchError.value = 'Indirizzo non trovato per coordinate selezionate.'
}
} catch {
if (requestId !== reverseGeocodeRequestId) {
return
}
if (fallbackAddress.trim()) {
setAddressValue(fallbackAddress.trim())
clearAddressSuggestions()
return
}
if (!form.value.address.trim()) {
addressSearchError.value = 'Impossibile recuperare indirizzo da coordinate.'
}
} finally {
if (requestId === reverseGeocodeRequestId) {
isResolvingAddress.value = false
}
}
}
const handleAddressFocus = () => {
if (addressSuggestions.value.length > 0) {
showAddressSuggestions.value = true
}
}
const handleAddressBlur = () => {
setTimeout(() => {
showAddressSuggestions.value = false
}, 150)
}
const updateLocation = async (
lat: number,
lng: number,
options: {
zoomTo?: boolean
syncAddress?: boolean
fallbackAddress?: string
} = {}
) => {
const { zoomTo = false, syncAddress = true, fallbackAddress = '' } = options
if (!isWithinBariBounds(lat, lng)) {
errors.value.location = 'Puoi inserire segnalazioni solo nel Comune di Bari.'
return
}
const roundedLat = Number(lat.toFixed(6))
const roundedLng = Number(lng.toFixed(6))
lastSyncedLocationKey = toLocationKey(roundedLat, roundedLng)
form.value.latitude = roundedLat
form.value.longitude = roundedLng
if (map && leaflet) {
if (!marker) {
marker = leaflet.marker([lat, lng]).addTo(map)
marker = leaflet.marker([roundedLat, roundedLng]).addTo(map)
} else {
marker.setLatLng([lat, lng])
marker.setLatLng([roundedLat, roundedLng])
}
if (zoomTo) {
map.setView([lat, lng], 16)
map.setView([roundedLat, roundedLng], 16)
}
}
if (errors.value.location) {
errors.value.location = ''
}
if (syncAddress) {
await resolveAddressFromCoordinates(roundedLat, roundedLng, fallbackAddress)
} else if (fallbackAddress.trim()) {
setAddressValue(fallbackAddress.trim())
}
}
const initMap = async () => {
if (!import.meta.client || !mapContainer.value || map) return
const L = await loadLeaflet()
if (!mapContainer.value || map) return
const bariBounds = L.latLngBounds(
[BARI_BOUNDS.south, BARI_BOUNDS.west],
[BARI_BOUNDS.north, BARI_BOUNDS.east]
)
map = L.map(mapContainer.value, {
maxBounds: bariBounds,
maxBoundsViscosity: 1,
minZoom: 12
}).setView(BARI_CENTER, 12)
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '&copy; OpenStreetMap contributors'
}).addTo(map)
map.fitBounds(bariBounds)
map.on('click', (e: LeafletMouseEvent) => {
if (!isWithinBariBounds(e.latlng.lat, e.latlng.lng)) {
errors.value.location = 'Puoi inserire segnalazioni solo nel Comune di Bari.'
return
}
void updateLocation(e.latlng.lat, e.latlng.lng)
})
// Se c'è già una posizione, imposta il marker
if (form.value.latitude && form.value.longitude) {
void updateLocation(form.value.latitude, form.value.longitude, { zoomTo: true })
}
}
const selectAddressSuggestion = async (suggestion: GeocodingSuggestion) => {
addressSearchError.value = ''
clearAddressSuggestions()
setAddressValue(suggestion.label)
await updateLocation(suggestion.latitude, suggestion.longitude, {
zoomTo: true,
syncAddress: false
})
}
const handleAddressEnter = async () => {
if (addressSuggestions.value.length === 0) {
return
}
await selectAddressSuggestion(addressSuggestions.value[0])
}
onMounted(() => {
@@ -111,6 +305,14 @@ onMounted(() => {
})
onUnmounted(() => {
cancelPendingAddressSearch()
cancelPendingReverseGeocode()
if (manualLocationSyncTimeout) {
clearTimeout(manualLocationSyncTimeout)
manualLocationSyncTimeout = null
}
if (map) {
map.remove()
map = null
@@ -125,6 +327,8 @@ const validateForm = (): boolean => {
}
if (!form.value.latitude || !form.value.longitude) {
errors.value.location = 'Imposta la posizione sulla mappa'
} else if (!isWithinBariBounds(form.value.latitude, form.value.longitude)) {
errors.value.location = 'La posizione deve essere nel Comune di Bari'
}
if (!form.value.address?.trim()) {
errors.value.address = 'Inserisci l\'indirizzo'
@@ -150,7 +354,7 @@ const getGeolocation = async () => {
navigator.geolocation.getCurrentPosition(resolve, reject)
})
updateLocation(position.coords.latitude, position.coords.longitude, true)
await updateLocation(position.coords.latitude, position.coords.longitude, { zoomTo: true })
} catch (error: any) {
errors.value.location = 'Impossibile ottenere la posizione. Clicca sulla mappa per inserirla manualmente.'
} finally {
@@ -182,11 +386,17 @@ const resetForm = () => {
}
media.value = []
errors.value = {}
addressSearchError.value = ''
clearAddressSuggestions()
cancelPendingAddressSearch()
cancelPendingReverseGeocode()
lastSyncedLocationKey = ''
skipNextAddressSearch = false
if (marker && map) {
map.removeLayer(marker)
marker = null
map.setView([41.8719, 12.5674], 5)
map.setView(BARI_CENTER, 12)
}
}
@@ -196,6 +406,35 @@ watch(() => form.value.category_id, () => {
}
})
watch(() => form.value.address, (newAddress) => {
if (skipNextAddressSearch) {
skipNextAddressSearch = false
return
}
cancelPendingReverseGeocode()
if (errors.value.address && newAddress.trim()) {
errors.value.address = ''
}
if (addressSearchTimeout) {
clearTimeout(addressSearchTimeout)
addressSearchTimeout = null
}
if (newAddress.trim().length < 3) {
isSearchingAddress.value = false
addressSearchError.value = ''
clearAddressSuggestions()
return
}
addressSearchTimeout = setTimeout(() => {
void fetchAddressSuggestions(newAddress.trim())
}, 350)
})
// Sincronizza input manuali con la mappa
watch([() => form.value.latitude, () => form.value.longitude], ([newLat, newLng]) => {
if (newLat && newLng && map && leaflet) {
@@ -208,6 +447,23 @@ watch([() => form.value.latitude, () => form.value.longitude], ([newLat, newLng]
map.setView([newLat, newLng], 16)
}
}
if (!newLat || !newLng) {
return
}
const locationKey = toLocationKey(newLat, newLng)
if (locationKey === lastSyncedLocationKey) {
return
}
if (manualLocationSyncTimeout) {
clearTimeout(manualLocationSyncTimeout)
}
manualLocationSyncTimeout = setTimeout(() => {
void updateLocation(newLat, newLng, { zoomTo: true })
}, 500)
})
</script>
@@ -246,6 +502,7 @@ watch([() => form.value.latitude, () => form.value.longitude], ([newLat, newLng]
<BIIcon name="it-map-marker-circle" size="sm" color="primary" class="me-2" />
Posizione *
</label>
<p class="small text-muted mb-2">Le segnalazioni sono abilitate solo entro confini del Comune di Bari.</p>
<button
type="button"
@@ -301,15 +558,44 @@ watch([() => form.value.latitude, () => form.value.longitude], ([newLat, newLng]
<BIIcon name="it-home" size="sm" color="primary" class="me-2" />
Indirizzo *
</label>
<input
id="address"
v-model="form.address"
type="text"
class="form-control"
:class="{ 'is-invalid': errors.address }"
placeholder="Es. Via Roma 123, Milano"
required
/>
<div class="position-relative">
<input
id="address"
v-model="form.address"
type="text"
class="form-control"
:class="{ 'is-invalid': errors.address }"
placeholder="Es. Via Sparano 12, Bari"
autocomplete="street-address"
required
@focus="handleAddressFocus"
@blur="handleAddressBlur"
@keydown.enter.prevent="handleAddressEnter"
/>
<div
v-if="showAddressSuggestions && addressSuggestions.length > 0"
class="list-group position-absolute w-100 shadow-sm rounded-3 overflow-hidden address-suggestions"
>
<button
v-for="suggestion in addressSuggestions"
:key="`${suggestion.latitude}-${suggestion.longitude}-${suggestion.label}`"
type="button"
class="list-group-item list-group-item-action text-start"
@mousedown.prevent="selectAddressSuggestion(suggestion)"
>
{{ suggestion.label }}
</button>
</div>
</div>
<div v-if="isSearchingAddress" class="form-text">
Ricerca indirizzi in corso...
</div>
<div v-else-if="isResolvingAddress" class="form-text">
Recupero indirizzo da coordinate...
</div>
<div v-else-if="addressSearchError" class="form-text text-muted">
{{ addressSearchError }}
</div>
<div v-if="errors.address" class="invalid-feedback">
{{ errors.address }}
</div>
@@ -380,6 +666,14 @@ watch([() => form.value.latitude, () => form.value.longitude], ([newLat, newLng]
z-index: 1; /* Fix for Bootstrap elements overlapping map */
}
.address-suggestions {
top: calc(100% + 0.25rem);
left: 0;
z-index: 10;
max-height: 16rem;
overflow-y: auto;
}
textarea {
font-family: inherit;
resize: vertical;
@@ -391,6 +685,3 @@ textarea {
align-items: center;
}
</style>
+10 -5
View File
@@ -1,5 +1,4 @@
<script setup lang="ts">
// Presumo tu abbia un useAdmin.ts (come da tuo elenco file) per le statistiche
const { getOverviewStats } = useAdmin()
const { data: statsRes, pending } = useAsyncData('admin-stats', () => getOverviewStats())
@@ -8,7 +7,7 @@ const { data: statsRes, pending } = useAsyncData('admin-stats', () => getOvervie
<template>
<div>
<div class="callout callout-highlight callout-danger mb-4">
<div class="callout-title">Pannello di Amministrazione</div>
<div class="callout-title">Pannello Admin</div>
<p>Accesso di livello 1. Da qui puoi gestire le configurazioni di sistema, le categorie e moderare le segnalazioni.</p>
</div>
@@ -40,10 +39,16 @@ const { data: statsRes, pending } = useAsyncData('admin-stats', () => getOvervie
<h3 class="mb-3">Gestione Sistema</h3>
<div class="row">
<div class="col-12 col-md-4 mb-3">
<NuxtLink to="/admin/catalog" class="btn btn-outline-primary w-100 py-3 d-flex flex-column align-items-center">
<BIIcon name="it-list" size="sm" color="primary" class="mb-2" />
Categorie e Team
</NuxtLink>
</div>
<div class="col-12 col-md-4 mb-3">
<NuxtLink to="/admin/areas" class="btn btn-outline-primary w-100 py-3 d-flex flex-column align-items-center">
<BIIcon name="it-map-marker" size="sm" color="primary" class="mb-2" />
Aree GeoJSON
Aree
</NuxtLink>
</div>
<div class="col-12 col-md-4 mb-3">
@@ -52,7 +57,7 @@ const { data: statsRes, pending } = useAsyncData('admin-stats', () => getOvervie
Gestione Utenti
</NuxtLink>
</div>
<div class="col-12 col-md-4 mb-3">
<div class="col-12 col-md-6 mb-3">
<NuxtLink to="/admin/moderation" class="btn btn-outline-danger w-100 py-3 d-flex flex-column align-items-center">
<BIIcon name="it-warning" size="sm" color="danger" class="mb-2" />
Moderazione Abusi
@@ -60,4 +65,4 @@ const { data: statsRes, pending } = useAsyncData('admin-stats', () => getOvervie
</div>
</div>
</div>
</template>
</template>
+2 -2
View File
@@ -21,7 +21,7 @@ export const useAdmin = () => {
useApiFetch<OkResponse>(`/api/v1/admin/users/${id}/roles`, { method: 'PATCH', body })
const getAreas = () =>
useApiFetch<AreaListResponse>('/api/v1/admin/areas', { method: 'GET' })
useApiFetch<AreaListResponse>('/api/v1/areas', { method: 'GET' })
const createArea = (body: CreateAreaRequest) =>
useApiFetch<OkResponse>('/api/v1/admin/areas', { method: 'POST', body })
@@ -58,4 +58,4 @@ export const useAdmin = () => {
getModerationFlags,
updateModerationFlag,
}
}
}
+2 -17
View File
@@ -27,24 +27,9 @@ export const useApiFetch = <T>(request: string, options: Parameters<typeof $fetc
const status = err?.statusCode || err?.status || err?.response?.status
if (status === 401 || status === 403) {
try {
tokenCookie.value = null
tokenState.value = null
const authUser = useState('auth_user')
authUser.value = null
console.error(`[API] Authentication error (${status}) - token cleared`)
} catch (e) {
console.error('[API] Error clearing auth state:', e)
}
try {
nuxtApp.runWithContext(() => navigateTo('/auth/login'))
} catch (e) {
console.error('[API] Error navigating to login:', e)
}
console.error(`[API] Authentication error (${status})`)
}
throw err
})
}
}
+15 -5
View File
@@ -8,7 +8,6 @@ import type {
} from "~/types/api";
export const useAuth = () => {
const route = useRoute()
const nuxtApp = useNuxtApp()
const token = useCookie<string | null>('auth_token', {
@@ -24,12 +23,17 @@ export const useAuth = () => {
const user = useState<UserContext | null>('auth_user', () => null)
const isSyncingUser = useState<boolean>('auth_syncing', () => false)
const isAuthenticated = computed(() => !!(tokenState.value || token.value))
const isAuthStatusError = (error: any) => {
const status = error?.statusCode || error?.status || error?.response?.status
return status === 401 || status === 403
}
watch(() => token.value, (newVal) => {
tokenState.value = newVal || null
})
const syncUser = async (redirectOnSuccess = false) => {
const syncUser = async (options: { redirectOnSuccess?: boolean; currentPath?: string } = {}) => {
const { redirectOnSuccess = false, currentPath } = options
const tokenVal = tokenState.value || token.value
if (!tokenVal || isSyncingUser.value) return
@@ -38,14 +42,20 @@ export const useAuth = () => {
const res = await fetchCurrentUser()
if (res.ok) {
user.value = res.user
const path = currentPath ?? useNuxtApp().$router.currentRoute.value.path
if (res.user.must_change_password && route.path !== '/auth/change-password') {
if (res.user.must_change_password && path !== '/auth/change-password') {
await nuxtApp.runWithContext(() => navigateTo('/auth/change-password'))
} else if (redirectOnSuccess && route.path.startsWith('/auth')) {
} else if (redirectOnSuccess && path.startsWith('/auth')) {
await nuxtApp.runWithContext(() => navigateTo('/dashboard'))
}
}
} catch (error) {
if (isAuthStatusError(error)) {
console.error('[Auth] Sync failed with authentication error, keeping session state:', error)
return
}
console.error('[Auth] Sync failed, logging out:', error)
logout()
} finally {
@@ -56,7 +66,7 @@ export const useAuth = () => {
const handleLoginSuccess = async (jwtToken: string) => {
token.value = jwtToken
tokenState.value = jwtToken
await syncUser(true)
await syncUser({ redirectOnSuccess: true })
}
const logout = () => {
+6 -1
View File
@@ -3,6 +3,7 @@ import type {
InterventionSummaryResponse,
OkResponse,
PagedReportListResponse,
TeamListResponse,
UpdateStatusRequest
} from "~/types/api";
@@ -16,6 +17,9 @@ export const useOperator = () => {
const getOtherOperatorReports = (query?: { page?: number; per_page?: number }) =>
useApiFetch<PagedReportListResponse>('/api/v1/operator/reports/others', { method: 'GET', query })
const getTeams = () =>
useApiFetch<TeamListResponse>('/api/v1/operator/teams', { method: 'GET' })
const takeReport = (id: number) =>
useApiFetch<OkResponse>(`/api/v1/reports/${id}/take`, { method: 'POST' })
@@ -32,9 +36,10 @@ export const useOperator = () => {
getOpenReports,
getAssignedReports,
getOtherOperatorReports,
getTeams,
takeReport,
updateReportStatus,
assignTeam,
getInterventionSummary,
}
}
}
+6 -1
View File
@@ -1,4 +1,5 @@
import type {
CategoryListResponse,
CreateReportRequest,
CreateReportResponse, FeedbackRequest, FlagRequest, FlagResponse,
MediaUploadResponse,
@@ -11,6 +12,9 @@ export const useReports = () => {
const getReports = (query?: { area_id?: number; category_id?: number; status?: string }) =>
useApiFetch<ReportListResponse>('/api/v1/reports', { method: 'GET', query })
const getCategories = () =>
useApiFetch<CategoryListResponse>('/api/v1/report-categories', { method: 'GET' })
const createReport = (body: CreateReportRequest) =>
useApiFetch<CreateReportResponse>('/api/v1/reports', { method: 'POST', body })
@@ -37,6 +41,7 @@ export const useReports = () => {
return {
getReports,
getCategories,
createReport,
getReportDetail,
uploadMedia,
@@ -46,4 +51,4 @@ export const useReports = () => {
flagReport,
flagMessage,
}
}
}
+2 -2
View File
@@ -4,7 +4,7 @@ export default defineNuxtRouteMiddleware(async (to) => {
// Se c'è un token ma l'utente non è ancora caricato e non stiamo già sincronizzando, sincronizza
if ((auth.token.value || auth.tokenState.value) && !auth.user.value && !auth.isSyncingUser.value) {
try {
await auth.syncUser()
await auth.syncUser({ currentPath: to.path })
} catch (error) {
console.error('[Auth Middleware] Sync failed:', error)
return navigateTo('/auth/login')
@@ -36,4 +36,4 @@ export default defineNuxtRouteMiddleware(async (to) => {
return navigateTo('/')
}
}
})
})
+2 -2
View File
@@ -1,9 +1,9 @@
export default defineNuxtRouteMiddleware(async () => {
export default defineNuxtRouteMiddleware(async (to) => {
const auth = useAuth()
if ((auth.token.value || auth.tokenState.value) && !auth.user.value && !auth.isSyncingUser.value) {
try {
await auth.syncUser()
await auth.syncUser({ currentPath: to.path })
} catch (error) {
console.error('[Guest Middleware] Sync failed:', error)
}
+28 -5
View File
@@ -1,12 +1,13 @@
<script setup lang="ts">
import { ref, reactive, nextTick, onBeforeUnmount } from 'vue'
import { BARI_BOUNDS, BARI_CENTER, isWithinBariBounds } from '~/utils/bari'
definePageMeta({
middleware: 'auth',
auth: { role: 'ADMIN' }
})
useHead({ title: 'Gestione Aree - Admin' })
useHead({ title: 'Aree - Admin' })
const { getAreas, createArea } = useAdmin()
const { data: areasRes, pending, refresh } = useAsyncData('admin-areas', () => getAreas())
@@ -41,15 +42,31 @@ const openCreateModal = () => {
map = null
}
map = L.map('areaMap').setView([41.9028, 12.4964], 6)
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)
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()
@@ -102,6 +119,12 @@ const handleCreate = async () => {
if (!parsedGeojson.type || !parsedGeojson.coordinates) {
throw new Error('GeoJSON non valido. Richiesto "type" e "coordinates".')
}
const coordinates = parsedGeojson.coordinates?.[0] || []
const outsideBari = coordinates.some(([longitude, latitude]: [number, number]) => !isWithinBariBounds(latitude, longitude))
if (outsideBari) {
throw new Error('Area non valida. Tutti i punti devono essere nel Comune di Bari.')
}
} catch (e: any) {
jsonError.value = e.message || 'Formato JSON non valido.'
return
@@ -128,9 +151,9 @@ const handleCreate = async () => {
<template>
<div class="container my-5">
<div class="d-flex justify-content-between align-items-center mb-4">
<h1 class="h3 font-weight-bold mb-0">Gestione Aree GeoJSON</h1>
<h1 class="h3 font-weight-bold mb-0">Gestione Aree</h1>
<div>
<NuxtLink to="/dashboard" class="btn btn-outline-secondary btn-sm me-2">Dashboard</NuxtLink>
<NuxtLink to="/dashboard" class="btn btn-outline-secondary btn-sm me-2">Torna al pannello admin</NuxtLink>
<button class="btn btn-primary btn-sm" @click="openCreateModal">
<BIIcon name="it-plus" size="xs" class="me-1" />
Nuova Area
@@ -218,7 +241,7 @@ const handleCreate = async () => {
</button>
</div>
<div class="alert alert-light border small mb-2 p-2">
Clicca sulla mappa per aggiungere vertici al poligono. Sono necessari almeno 3 punti.
Clicca sulla mappa per aggiungere vertici al poligono. Sono necessari almeno 3 punti. Sono ammessi solo punti nel Comune di Bari.
</div>
<div id="areaMap" class="rounded border" style="height: 400px; width: 100%; z-index: 1;"></div>
</div>
+236
View File
@@ -0,0 +1,236 @@
<script setup lang="ts">
definePageMeta({
middleware: 'auth',
auth: { role: 'ADMIN' }
})
useHead({ title: 'Categorie e Team - Admin' })
const { createCategory, getTeams, createTeam, getAreas } = useAdmin()
const { getCategories } = useReports()
const { data: categoriesRes, refresh: refreshCategories } = await useAsyncData('report-categories-admin-view', () => getCategories())
const { data: teamsRes, refresh: refreshTeams } = await useAsyncData('admin-teams', () => getTeams())
const { data: areasRes } = await useAsyncData('admin-team-areas', () => getAreas())
const categoryForm = reactive({
name: '',
description: '',
})
const teamForm = reactive({
name: '',
description: '',
team_category_id: null as number | null,
area_id: null as number | null,
})
const isSavingCategory = ref(false)
const isSavingTeam = ref(false)
const categoryError = ref('')
const teamError = ref('')
const categories = computed(() => categoriesRes.value?.categories || [])
const teams = computed(() => teamsRes.value?.teams || [])
const areas = computed(() => areasRes.value?.areas || [])
const submitCategory = async () => {
categoryError.value = ''
isSavingCategory.value = true
try {
await createCategory({
name: categoryForm.name.trim(),
description: categoryForm.description.trim() || undefined,
})
categoryForm.name = ''
categoryForm.description = ''
await refreshCategories()
} catch (error: any) {
categoryError.value = error?.data?.message || 'Creazione categoria non riuscita.'
} finally {
isSavingCategory.value = false
}
}
const submitTeam = async () => {
if (!teamForm.team_category_id) return
teamError.value = ''
isSavingTeam.value = true
try {
await createTeam({
name: teamForm.name.trim(),
description: teamForm.description.trim() || undefined,
team_category_id: teamForm.team_category_id,
area_id: teamForm.area_id || undefined,
})
teamForm.name = ''
teamForm.description = ''
teamForm.team_category_id = null
teamForm.area_id = null
await refreshTeams()
} catch (error: any) {
teamError.value = error?.data?.message || 'Creazione team non riuscita.'
} finally {
isSavingTeam.value = false
}
}
</script>
<template>
<div class="container my-5">
<div class="d-flex flex-wrap justify-content-between align-items-center gap-3 mb-4">
<div>
<h1 class="h3 font-weight-bold mb-1">Categorie e Team</h1>
<p class="text-muted mb-0">Gestione dati di riferimento per segnalazioni e interventi.</p>
</div>
<NuxtLink to="/dashboard" class="btn btn-outline-secondary btn-sm">Torna al pannello admin</NuxtLink>
</div>
<div class="row g-4">
<div class="col-12 col-xl-5">
<div class="card card-bg border-0 shadow-sm h-100">
<div class="card-body">
<div class="d-flex align-items-center justify-content-between mb-3">
<h2 class="h5 mb-0">Categorie</h2>
<span class="badge bg-light text-dark border">{{ categories.length }}</span>
</div>
<div v-if="categoryError" class="alert alert-danger py-2" role="alert">
{{ categoryError }}
</div>
<form class="mb-4" @submit.prevent="submitCategory">
<div class="mb-3">
<label class="form-label">Nome categoria</label>
<input v-model="categoryForm.name" type="text" class="form-control" required />
</div>
<div class="mb-3">
<label class="form-label">Descrizione</label>
<textarea v-model="categoryForm.description" class="form-control" rows="3"></textarea>
</div>
<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>
Crea categoria
</button>
</form>
<div class="table-responsive report-table-wrapper">
<table class="table table-hover report-table mb-0">
<thead>
<tr>
<th>ID</th>
<th>Nome</th>
<th>Stato</th>
</tr>
</thead>
<tbody>
<tr v-for="category in categories" :key="category.id">
<td class="report-table-id">#{{ category.id }}</td>
<td>
<strong>{{ category.name }}</strong>
<div v-if="category.description" class="small text-muted mt-1">{{ category.description }}</div>
</td>
<td>
<span class="badge" :class="category.active === false ? 'bg-secondary' : 'bg-success'">
{{ category.active === false ? 'Inattiva' : 'Attiva' }}
</span>
</td>
</tr>
<tr v-if="categories.length === 0">
<td colspan="3" class="text-muted">Nessuna categoria configurata.</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<div class="col-12 col-xl-7">
<div class="card card-bg border-0 shadow-sm h-100">
<div class="card-body">
<div class="d-flex align-items-center justify-content-between mb-3">
<h2 class="h5 mb-0">Team di intervento</h2>
<span class="badge bg-light text-dark border">{{ teams.length }}</span>
</div>
<div v-if="teamError" class="alert alert-danger py-2" role="alert">
{{ teamError }}
</div>
<form class="row g-3 mb-4" @submit.prevent="submitTeam">
<div class="col-12 col-md-6">
<label class="form-label">Nome team</label>
<input v-model="teamForm.name" type="text" class="form-control" required />
</div>
<div class="col-12 col-md-6">
<label class="form-label">Categoria coperta</label>
<select v-model.number="teamForm.team_category_id" class="form-select" required>
<option :value="null">Seleziona categoria</option>
<option v-for="category in categories" :key="category.id" :value="category.id">
{{ category.name }}
</option>
</select>
</div>
<div class="col-12 col-md-6">
<label class="form-label">Area</label>
<select v-model.number="teamForm.area_id" class="form-select">
<option :value="null">Tutte le aree</option>
<option v-for="area in areas" :key="area.id" :value="area.id">
{{ area.name }}
</option>
</select>
</div>
<div class="col-12 col-md-6">
<label class="form-label">Descrizione</label>
<input v-model="teamForm.description" type="text" class="form-control" />
</div>
<div class="col-12">
<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>
Crea team
</button>
</div>
</form>
<div class="table-responsive report-table-wrapper">
<table class="table table-hover report-table mb-0">
<thead>
<tr>
<th>ID</th>
<th>Team</th>
<th>Categoria</th>
<th>Area</th>
<th>Stato</th>
</tr>
</thead>
<tbody>
<tr v-for="team in teams" :key="team.id">
<td class="report-table-id">#{{ team.id }}</td>
<td>
<strong>{{ team.name }}</strong>
<div v-if="team.description" class="small text-muted mt-1">{{ team.description }}</div>
</td>
<td>{{ team.category_name || '-' }}</td>
<td>{{ team.area_name || 'Tutte' }}</td>
<td>
<span class="badge" :class="team.active === false ? 'bg-secondary' : 'bg-success'">
{{ team.active === false ? 'Inattivo' : 'Attivo' }}
</span>
</td>
</tr>
<tr v-if="teams.length === 0">
<td colspan="5" class="text-muted">Nessun team configurato.</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
+1 -1
View File
@@ -65,7 +65,7 @@ const formatDate = (dateStr: string) => {
<div class="container my-5">
<div class="d-flex justify-content-between align-items-center mb-4">
<h1 class="h3 font-weight-bold mb-0">Moderazione Abusi</h1>
<NuxtLink to="/dashboard" class="btn btn-outline-secondary btn-sm">Torna alla Dashboard</NuxtLink>
<NuxtLink to="/dashboard" class="btn btn-outline-secondary btn-sm">Torna al pannello admin</NuxtLink>
</div>
<div class="row mb-4">
+6 -4
View File
@@ -13,6 +13,7 @@ const { getUsers, updateUserBan, updateUserRoles } = useAdmin()
const { data: usersRes, pending, refresh } = useAsyncData('admin-users', () => getUsers())
const search = ref('')
const parseRoles = (roles?: string) => roles ? roles.split(',').map((r) => r.trim().toUpperCase()).filter(Boolean) : []
const filteredUsers = computed(() => {
if (!usersRes.value?.users) return []
@@ -47,7 +48,7 @@ const availableRoles = ['CITIZEN', 'OPERATOR', 'ADMIN']
const openRoleModal = (user: any) => {
editingUserId.value = user.id
selectedRoles.value = user.roles ? user.roles.split(',').map((r: string) => r.trim()) : []
selectedRoles.value = parseRoles(user.roles)
}
const closeRoleModal = () => {
@@ -75,7 +76,7 @@ const saveRoles = async () => {
<div class="container my-5">
<div class="d-flex justify-content-between align-items-center mb-4">
<h1 class="h3 font-weight-bold mb-0">Gestione Utenti</h1>
<NuxtLink to="/dashboard" class="btn btn-outline-secondary btn-sm">Torna alla Dashboard</NuxtLink>
<NuxtLink to="/dashboard" class="btn btn-outline-secondary btn-sm">Torna al pannello admin</NuxtLink>
</div>
<div class="row mb-4">
@@ -118,8 +119,8 @@ const saveRoles = async () => {
<small class="text-muted">{{ user.fiscal_code }}</small>
</td>
<td>
<span v-for="r in (user.roles ? user.roles.split(',') : [])" :key="r" class="badge bg-primary me-1">
{{ r.trim() }}
<span v-for="r in parseRoles(user.roles)" :key="r" class="badge bg-primary me-1">
{{ r }}
</span>
</td>
<td>{{ user.points || 0 }}</td>
@@ -161,6 +162,7 @@ const saveRoles = async () => {
type="checkbox"
:value="role"
:id="'role-'+role"
:checked="selectedRoles.includes(role)"
v-model="selectedRoles"
>
<label class="form-check-label" :for="'role-'+role">
+2 -2
View File
@@ -19,14 +19,14 @@ const currentDashboard = computed(() => {
const heroTitle = computed(() => {
const role = user.value?.role?.toUpperCase()
if (role === 'ADMIN') return 'Pannello di Amministrazione'
if (role === 'ADMIN') return 'Pannello Admin'
if (role === 'OPERATOR') return 'Gestione Operativa'
return 'Dashboard'
})
const heroSubtitle = computed(() => {
const role = user.value?.role?.toUpperCase()
if (role === 'ADMIN') return 'Gestione del sistema, delle aree e moderazione utenti'
if (role === 'ADMIN') return 'Accesso amministrativo per configurazioni, utenti e moderazione'
if (role === 'OPERATOR') return 'Prendi in carico e gestisci le segnalazioni in corso'
return 'Riepilogo rapido delle tue segnalazioni e dei punti cittadino'
})
+2 -2
View File
@@ -87,7 +87,7 @@ useHead({
<BIIcon name="it-settings" size="xl" color="primary" class="mb-3" />
<h3 class="card-title h5 font-weight-bold">Amministrazione</h3>
<p class="card-text text-muted">
Gli amministratori hanno il controllo completo della piattaforma. Possono definire le aree urbane (tramite poligoni GeoJSON), gestire i permessi degli utenti, supervisionare i feedback e moderare eventuali abusi.
Gli amministratori hanno il controllo completo della piattaforma. Possono definire le aree urbane tramite poligoni GeoJSON, gestire i permessi degli utenti, supervisionare i feedback e moderare eventuali abusi.
<br><br>
Hanno inoltre accesso a statistiche avanzate per individuare le criticità sul territorio e monitorare i tempi medi di risoluzione.
</p>
@@ -175,4 +175,4 @@ useHead({
list-style-type: none;
padding-left: 0;
}
</style>
</style>
+126 -12
View File
@@ -1,5 +1,7 @@
<script setup lang="ts">
import { ref, computed } from 'vue'
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue'
import type { Map as LeafletMap, CircleMarker, LatLngBoundsExpression } from 'leaflet'
import { BARI_BOUNDS, BARI_CENTER, isWithinBariBounds } from '~/utils/bari'
// 1. API Fetching Logic
const { getOpenDataReports } = usePublic()
@@ -15,6 +17,10 @@ const { data: openDataResponse, pending } = await useAsyncData(
{ watch: [currentPage] } // Nuxt will re-fetch when currentPage changes
)
const visibleReports = computed(() =>
(openDataResponse.value?.reports || []).filter((report) => isWithinBariBounds(report.latitude, report.longitude))
)
// Pagination logic: If we receive less items than `perPage`, we are on the last page.
const isLastPage = computed(() => {
if (!openDataResponse.value?.reports) return true
@@ -30,6 +36,10 @@ const prevPage = () => {
// 2. View Toggle (Grid vs Map)
const currentView = ref<'grid' | 'map'>('grid')
const mapContainer = ref<HTMLElement | null>(null)
let leaflet: typeof import('leaflet') | null = null
let map: LeafletMap | null = null
let markers: CircleMarker[] = []
// 3. Helper to style status badges
const getStatusBadge = (status: string) => {
@@ -39,6 +49,99 @@ const getStatusBadge = (status: string) => {
default: return { class: 'bg-info', text: status, icon: 'it-info-circle' }
}
}
const loadLeaflet = async () => {
if (leaflet) return leaflet
leaflet = await import('leaflet')
return leaflet
}
const clearMarkers = () => {
if (!map) return
markers.forEach((marker) => marker.removeFrom(map!))
markers = []
}
const renderMapMarkers = async () => {
if (!import.meta.client || !mapContainer.value) return
const L = await loadLeaflet()
if (!map) return
clearMarkers()
if (visibleReports.value.length === 0) {
map.setView(BARI_CENTER, 12)
return
}
visibleReports.value.forEach((report) => {
const marker = L.circleMarker([report.latitude, report.longitude], {
radius: 8,
weight: 2,
color: '#ffffff',
fillColor: getStatusBadge(report.status).class === 'bg-success' ? '#008758' : getStatusBadge(report.status).class === 'bg-secondary' ? '#5c6f82' : '#2f80ed',
fillOpacity: 0.95,
})
marker.bindPopup(`
<div class="open-data-popup">
<strong>${report.category_name}</strong><br/>
<span>ID #${report.id}</span><br/>
<span>${report.area_name || 'Area comunale non specificata'}</span><br/>
<span>Segnalato ${new Date(report.created_at).toLocaleDateString('it-IT')}</span>
</div>
`)
marker.addTo(map!)
markers.push(marker)
})
const fitBounds: LatLngBoundsExpression = visibleReports.value.map((report) => [report.latitude, report.longitude])
map.fitBounds(fitBounds, { padding: [32, 32], maxZoom: 15 })
}
const initMap = async () => {
if (!import.meta.client || !mapContainer.value || map) return
const L = await loadLeaflet()
const bariBounds = L.latLngBounds(
[BARI_BOUNDS.south, BARI_BOUNDS.west],
[BARI_BOUNDS.north, BARI_BOUNDS.east]
)
map = L.map(mapContainer.value, {
maxBounds: bariBounds,
maxBoundsViscosity: 1,
minZoom: 11,
}).setView(BARI_CENTER, 12)
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '&copy; OpenStreetMap contributors'
}).addTo(map)
await renderMapMarkers()
}
watch(currentView, async (view) => {
if (view !== 'map') return
await nextTick()
await initMap()
map?.invalidateSize()
await renderMapMarkers()
})
watch(visibleReports, async () => {
if (currentView.value === 'map' && map) {
await renderMapMarkers()
}
})
onBeforeUnmount(() => {
clearMarkers()
map?.remove()
map = null
})
</script>
<template>
@@ -102,7 +205,7 @@ const getStatusBadge = (status: string) => {
<!-- GRID VIEW -->
<div v-else-if="currentView === 'grid'">
<div class="row" v-if="openDataResponse?.reports && openDataResponse.reports.length > 0">
<div class="col-12 col-md-6 col-lg-4 mb-4" v-for="report in openDataResponse.reports" :key="report.id">
<div class="col-12 col-md-6 col-lg-4 mb-4" v-for="report in visibleReports" :key="report.id">
<!-- Strict BI Card -->
<div class="card-wrapper card-space h-100">
<div class="card card-bg h-100 shadow-sm">
@@ -170,18 +273,15 @@ const getStatusBadge = (status: string) => {
</nav>
</div>
<!-- MAP VIEW (Placeholder for Leaflet/Mapbox) -->
<!-- MAP VIEW -->
<div v-else-if="currentView === 'map'" class="map-view-wrapper">
<div class="alert alert-info d-flex align-items-center" role="alert">
<span>La visualizzazione mappa è un modulo interattivo (ad es. Leaflet o Mapbox) che utilizzerà le coordinate <strong>latitudine</strong> e <strong>longitudine</strong> fornite dalle API.</span>
</div>
<div class="bg-light border rounded d-flex align-items-center justify-content-center" style="height: 500px;">
<div class="text-center text-muted">
<BIIcon name="it-map" size="xl" class="mb-3 opacity-50" />
<h4 class="h5">Mappa Interattiva</h4>
<p>Caricamento dei {{ openDataResponse?.reports?.length || 0 }} punti geografici in corso...</p>
</div>
<div class="d-flex justify-content-between align-items-center flex-wrap gap-2 mb-3">
<p class="text-muted mb-0">Mappa pubblica delle segnalazioni nell'area di Bari.</p>
<span class="badge bg-light text-dark border">{{ visibleReports.length }} punti</span>
</div>
<ClientOnly>
<div ref="mapContainer" class="open-data-map rounded border"></div>
</ClientOnly>
</div>
</div>
@@ -201,4 +301,18 @@ const getStatusBadge = (status: string) => {
transform: translateY(-2px);
box-shadow: 0 4px 15px rgba(0,0,0,0.1) !important;
}
.open-data-map {
height: 520px;
width: 100%;
z-index: 1;
}
:global(.open-data-popup) {
color: #17324d;
font-family: "Titillium Web", Arial, sans-serif;
font-size: 0.875rem;
line-height: 1.4;
min-width: 12rem;
}
</style>
+41 -32
View File
@@ -17,19 +17,22 @@ if (!reportId) {
}
const { getReportDetail, getMessages, addMessage, flagMessage } = useReports()
const { getInterventionSummary, updateReportStatus, assignTeam } = useOperator()
const { getInterventionSummary, updateReportStatus, assignTeam, getTeams } = useOperator()
const { user } = useAuth()
// Dati principali
const { data: reportData, refresh: refreshReport } = await useAsyncData(`op-report-${reportId}`, () => getReportDetail(reportId))
const { data: messagesData, refresh: refreshMessages } = await useAsyncData(`op-messages-${reportId}`, () => getMessages(reportId))
const { data: summaryData, refresh: refreshSummary } = await useAsyncData(`op-summary-${reportId}`, () => getInterventionSummary(reportId))
const { data: teamsData } = await useAsyncData('operator-teams', () => getTeams())
const report = computed(() => (reportData.value as any)?.report)
const media = computed(() => (reportData.value as any)?.media || [])
const statusHistory = computed(() => (reportData.value as any)?.history || [])
const messages = computed(() => (messagesData.value as any)?.messages || [])
const summary = computed(() => (summaryData.value as any)?.summary)
const summaryMedia = computed(() => (summaryData.value as any)?.media || [])
const teams = computed(() => teamsData.value?.teams || [])
const statusMeta: Record<string, string> = {
OPEN: 'Aperta',
UNDER_REVIEW: 'In revisione',
@@ -47,9 +50,7 @@ const isUpdatingStatus = ref(false)
// Form Assegna Squadra
const isAssignModalOpen = ref(false)
const teamName = ref('')
const assignNote = ref('')
const estimatedDate = ref('')
const selectedTeamId = ref<number | null>(null)
const isAssigning = ref(false)
// Messaggi
@@ -90,19 +91,15 @@ const handleStatusUpdate = async () => {
}
const handleAssignTeam = async () => {
if (!teamName.value) return
if (!selectedTeamId.value) return
isAssigning.value = true
try {
const res = await assignTeam(reportId, {
assigned_to_team: teamName.value,
estimated_resolution_date: estimatedDate.value || undefined,
internal_notes: assignNote.value || undefined
team_id: selectedTeamId.value
})
if (res.ok) {
isAssignModalOpen.value = false
teamName.value = ''
assignNote.value = ''
estimatedDate.value = ''
selectedTeamId.value = null
await Promise.all([refreshReport(), refreshSummary()])
}
} catch (e) {
@@ -152,6 +149,15 @@ const formatDate = (dateString: string) => {
hour: '2-digit', minute: '2-digit'
})
}
const latestCitizenMessage = computed(() => {
const reportUserId = report.value?.user_id
if (!reportUserId) return null
return [...messages.value]
.reverse()
.find((message) => message.user_id === reportUserId) || null
})
</script>
<template>
@@ -257,29 +263,31 @@ const formatDate = (dateString: string) => {
<div class="report-sidebar">
<div class="card card-bg border-0 shadow-sm mb-4" v-if="summary">
<div class="card-body">
<h2 class="h6 mb-3">Riepilogo intervento</h2>
<h2 class="h6 mb-3">Quadro operativo</h2>
<ul class="report-summary-list list-unstyled mb-4">
<li>
<span>Operatore</span>
<strong>{{ summary.operator_id ? `#${summary.operator_id}` : 'Nessuno' }}</strong>
<strong>{{ summary.assigned_operator_id ? `#${summary.assigned_operator_id}` : 'Nessuno' }}</strong>
</li>
<li>
<span>Squadra</span>
<strong>{{ summary.assigned_to_team || 'Nessuna' }}</strong>
<span>Team disponibili</span>
<strong>{{ teams.length }}</strong>
</li>
<li>
<span>Data prevista</span>
<strong>{{ summary.estimated_resolution_date ? formatDate(summary.estimated_resolution_date) : 'Non impostata' }}</strong>
<span>Allegati</span>
<strong>{{ summaryMedia.length || media.length }}</strong>
</li>
</ul>
<div class="report-description">
<h3 class="h6 mb-2">Note interne</h3>
<p class="small mb-0">{{ summary.internal_notes || 'Nessuna nota interna' }}</p>
<h3 class="h6 mb-2">Ultimo messaggio cittadino</h3>
<p class="small mb-0">
{{ latestCitizenMessage?.body || 'Nessun messaggio del cittadino disponibile.' }}
</p>
</div>
</div>
<div class="card-body pt-0">
<button class="btn btn-outline-primary w-100" @click="isAssignModalOpen = true">
Gestisci Squadra e Note
<button class="btn btn-outline-primary w-100" @click="isAssignModalOpen = true" :disabled="teams.length === 0">
Assegna team
</button>
</div>
</div>
@@ -342,20 +350,21 @@ const formatDate = (dateString: string) => {
<div class="modal-body">
<form @submit.prevent="handleAssignTeam">
<div class="mb-3">
<label class="form-label">Squadra / Ditta Incaricata</label>
<input type="text" class="form-control" v-model="teamName" placeholder="Es. Squadra Verde SPA" required />
</div>
<div class="mb-3">
<label class="form-label">Data Prevista Risoluzione (opzionale)</label>
<input type="date" class="form-control" v-model="estimatedDate" />
</div>
<div class="mb-3">
<label class="form-label">Note Interne (private)</label>
<textarea class="form-control" v-model="assignNote" rows="3" placeholder="Note ad uso interno, non visibili al cittadino..."></textarea>
<label class="form-label">Team incaricato</label>
<select v-model.number="selectedTeamId" class="form-select" required>
<option :value="null">Seleziona team</option>
<option v-for="team in teams" :key="team.id" :value="team.id">
{{ team.name }}<template v-if="team.category_name"> · {{ team.category_name }}</template>
<template v-if="team.area_name"> · {{ team.area_name }}</template>
</option>
</select>
<small v-if="teams.length === 0" class="form-text text-danger">
Nessun team attivo disponibile.
</small>
</div>
<div class="d-flex justify-content-end gap-2 mt-4">
<button type="button" class="btn btn-outline-secondary" @click="isAssignModalOpen = false">Annulla</button>
<button type="submit" class="btn btn-primary" :disabled="isAssigning || !teamName.trim()">
<button type="submit" class="btn btn-primary" :disabled="isAssigning || !selectedTeamId">
<span v-if="isAssigning" class="spinner-border spinner-border-sm me-2"></span>
Salva Assegnazione
</button>
+4 -1
View File
@@ -1,5 +1,6 @@
<script setup lang="ts">
import type { Report } from '~/types/api'
import { isWithinBariBounds } from '~/utils/bari'
definePageMeta({
middleware: 'auth',
@@ -15,7 +16,9 @@ const filterStatus = ref('')
const { data: reportsRes, pending } = useAsyncData('citizen-reports-list', () => getReports({}))
const reports = computed<Report[]>(() => reportsRes.value?.reports || [])
const reports = computed<Report[]>(() =>
(reportsRes.value?.reports || []).filter((report) => isWithinBariBounds(report.latitude, report.longitude))
)
const filteredReports = computed(() => {
if (!filterStatus.value) return reports.value
if (filterStatus.value === 'IN_PROGRESS') {
+1 -2
View File
@@ -8,8 +8,7 @@ definePageMeta({
useHead({ title: 'Nuova segnalazione - Visione' })
const router = useRouter()
const { createReport, uploadMedia } = useReports()
const { getCategories } = useAdmin()
const { createReport, uploadMedia, getCategories } = useReports()
const { data: categoriesData } = await useAsyncData('categories', () => getCategories())
const categories = computed(() => categoriesData.value?.categories || [])
+9 -2
View File
@@ -1,13 +1,20 @@
export default defineNuxtPlugin(async () => {
const auth = useAuth()
const currentPath = useNuxtApp().$router.currentRoute.value.path
if ((auth.token.value || auth.tokenState.value) && !auth.user.value) {
try {
await auth.syncUser()
await auth.syncUser({ currentPath })
} catch (error) {
const status = (error as any)?.statusCode || (error as any)?.status || (error as any)?.response?.status
if (status === 401 || status === 403) {
console.error('[Auth Plugin] Sync failed with authentication error, keeping session state:', error)
return
}
console.error('[Auth Plugin] Sync failed:', error)
auth.logout()
}
}
})
+15
View File
@@ -0,0 +1,15 @@
export const BARI_BOUNDS = {
south: 41.0160584,
north: 41.1697837,
west: 16.7172376,
east: 17.0334109,
}
export const BARI_CENTER: [number, number] = [41.1257843, 16.8620293]
export const isWithinBariBounds = (latitude: number, longitude: number) =>
latitude >= BARI_BOUNDS.south &&
latitude <= BARI_BOUNDS.north &&
longitude >= BARI_BOUNDS.west &&
longitude <= BARI_BOUNDS.east
+103
View File
@@ -0,0 +1,103 @@
import { BARI_BOUNDS, isWithinBariBounds } from '~/utils/bari'
interface NominatimAddress {
road?: string
house_number?: string
pedestrian?: string
footway?: string
path?: string
cycleway?: string
suburb?: string
neighbourhood?: string
city?: string
town?: string
village?: string
municipality?: string
}
interface NominatimResult {
lat: string
lon: string
display_name: string
address?: NominatimAddress
}
export interface GeocodingSuggestion {
label: string
latitude: number
longitude: number
}
const NOMINATIM_BASE_URL = 'https://nominatim.openstreetmap.org'
const bariViewbox = `${BARI_BOUNDS.west},${BARI_BOUNDS.north},${BARI_BOUNDS.east},${BARI_BOUNDS.south}`
const compactAddress = (displayName: string, address?: NominatimAddress) => {
if (!address) {
return displayName
}
const streetName = address.road || address.pedestrian || address.footway || address.path || address.cycleway
const street = [streetName, address.house_number].filter(Boolean).join(' ')
const locality = address.city || address.town || address.village || address.municipality || 'Bari'
const area = address.suburb || address.neighbourhood
const formatted = [street, locality, area]
.filter(Boolean)
.filter((part, index, all) => all.indexOf(part) === index)
.join(', ')
return formatted || displayName
}
const toSuggestion = (result: NominatimResult): GeocodingSuggestion | null => {
const latitude = Number.parseFloat(result.lat)
const longitude = Number.parseFloat(result.lon)
if (!Number.isFinite(latitude) || !Number.isFinite(longitude)) {
return null
}
return {
label: compactAddress(result.display_name, result.address),
latitude,
longitude
}
}
export const searchAddresses = async (query: string, limit = 5) => {
const params = new URLSearchParams({
q: query,
format: 'jsonv2',
addressdetails: '1',
'accept-language': 'it',
countrycodes: 'it',
bounded: '1',
viewbox: bariViewbox,
limit: String(limit)
})
const results = await $fetch<NominatimResult[]>(`${NOMINATIM_BASE_URL}/search?${params.toString()}`)
return results
.map(toSuggestion)
.filter((result): result is GeocodingSuggestion => Boolean(result))
.filter((result) => isWithinBariBounds(result.latitude, result.longitude))
}
export const reverseGeocode = async (latitude: number, longitude: number) => {
const params = new URLSearchParams({
lat: String(latitude),
lon: String(longitude),
zoom: '18',
format: 'jsonv2',
addressdetails: '1',
'accept-language': 'it'
})
const result = await $fetch<NominatimResult | null>(`${NOMINATIM_BASE_URL}/reverse?${params.toString()}`)
if (!result) {
return ''
}
return compactAddress(result.display_name, result.address)
}
+2 -23
View File
@@ -8,6 +8,8 @@ export default defineNuxtConfig({
'@nuxtjs/sitemap',
'@nuxtjs/robots'
],
// TODO: riattivare prima di pubblicare il sito
ssr: false,
runtimeConfig: {
public: {
@@ -35,29 +37,6 @@ export default defineNuxtConfig({
]
},
nitro: {
devProxy: {
'/api/v1': {
target: 'https://bk.visione.studentindipendenti.it/api/v1',
changeOrigin: true,
headers: {
host: 'bk.visione.studentindipendenti.it',
origin: 'https://visione.studentindipendenti.it',
referer: 'https://visione.studentindipendenti.it/'
}
},
'/uploads': {
target: 'https://bk.visione.studentindipendenti.it/uploads',
changeOrigin: true,
headers: {
host: 'bk.visione.studentindipendenti.it',
origin: 'https://visione.studentindipendenti.it',
referer: 'https://visione.studentindipendenti.it/'
}
}
}
},
app: {
head: {
link: [