103 Commits
74 changed files with 10066 additions and 2635 deletions
+4
View File
@@ -22,3 +22,7 @@ logs
.env
.env.*
!.env.example
pnpm-*.yaml
.pnpm-store/
AGENTS.md
+103 -53
View File
@@ -1,75 +1,125 @@
# Nuxt Minimal Starter
<div align="center">
<img src="https://git.reloia.uk/SnitchItaly/frontend/raw/branch/master/public/icon-512.webp" width="128" height="128" alt="Logo Visione">
<h1>Visione</h1>
<p><b>Un'occhio per la sicurezza del cittadino.</b></p>
</div>
Look at the [Nuxt documentation](https://nuxt.com/docs/getting-started/introduction) to learn more.
**Visione** è una piattaforma progettata per gestire le segnalazioni dei cittadini, implementando un flusso operativo
sicuro, trasparente e istituzionalmente conforme.
## Setup
## Punti di Forza e Funzionalità Principali
Make sure to install dependencies:
- **Conformità Istituzionale e UX/UI Standardizzata:** Il frontend è sviluppato utilizzando **Bootstrap Italia** (creato
da Designers Italia). Questa scelta assicura un'identità visiva coerente con i servizi pubblici italiani, garantendo
uniformità, riconoscibilità e accessibilità.
- **Trasparenza e Open Data:** Il sistema espone un endpoint pubblico Open Data con dataset anonimizzati relativi alle
segnalazioni chiuse o risolte, favorendo la trasparenza amministrativa.
- **Automazione e Smistamento Intelligente:** Il calcolo automatico della "Zona" di competenza tramite le coordinate
geografiche elimina i colli di bottiglia durante il triage iniziale, instradando immediatamente la segnalazione
all'operatore corretto.
- **Sicurezza e Onboarding Smart:** L'autenticazione è gestita tramite **OTP (One-Time Password)** e integrazione con *
*CIE (Carta d'Identità Elettronica)**, riducendo l'uso di password statiche e garantendo identità verificate.
- **Infrastruttura DevOps e CI/CD:** Sfruttiamo un'istanza self-hosted di **Gitea** per il versionamento del codice e un
flusso di deployment automatizzato basato su webhook con **Dokploy**, assicurando un rilascio continuo e stabile.
- **Ottimizzazione SEO e Reperibilità:** Configurazione avanzata per sitemap e `robots.txt` (via `@nuxtjs/robots` e
`@nuxtjs/sitemap`) per esplicitare chiaramente le pagine pubbliche e separarle dalle aree private.
## Tecnologie Utilizzate
Il progetto è costruito su uno stack moderno orientato a performance, accessibilità e manutenibilità:
- **Framework Core:** [Nuxt 4](https://nuxt.com/) (Vue 3) con rendering SSR attivato.
- **UI / Styling:** [Bootstrap Italia](https://italia.github.io/bootstrap-italia/) per componenti accessibili e conformi
agli standard AGID.
- **Mappe e Georeferenziazione:** [Leaflet](https://leafletjs.com/) interfacciato con Nominatim/OpenStreetMap per il
suggerimento e la validazione degli indirizzi.
- **PWA e Ottimizzazione:** Modulo `@vite-pwa/nuxt` per Progressive Web App (manifest auto-generato) e moduli ufficiali
Nuxt per icone, font (Google Fonts: Lora, Roboto Mono, Titillium Web) ed elaborazione immagini.
- **Infrastruttura:** Docker, Docker Compose, NodeJS 22.
- **Package Manager:** **Yarn**.
## Limiti e Punti di Attenzione
L'attuale architettura presenta alcune criticità e aree di miglioramento individuate durante i test:
1. **Rischio di Abuso e Moderazione:** L'apertura della piattaforma all'invio di messaggi e allegati potrebbe generare
un elevato carico di moderazione. In futuro, andranno valutati filtri automatici o code dedicate.
2. **Dipendenza da API Cartografiche di Terze Parti:** L'utilizzo di Nominatim/OpenStreetMap per il geocoding esonera
dal lock-in di provider commerciali (es. Google Maps), ma introduce dipendenze su disponibilità e policy d'uso di
servizi esterni.
3. **Barriere all'Ingresso:** I flussi OTP e CIE, seppur estremamente sicuri, possono rappresentare un "attrito" (
digital divide) per le fasce di utenza più anziane o meno avvezze agli strumenti digitali.
---
## Come utilizzare il progetto (Sviluppo)
### Requisiti
- Node.js (v22 o superiore consigliato)
- **Yarn** (utilizza esclusivamente `yarn`, non `npm`)
### 1. Installazione Dipendenze
```bash
# npm
npm install
# pnpm
pnpm install
# yarn
yarn install
# bun
bun install
```
## Development Server
### 2. Configurazione Variabili d'Ambiente (.env)
Start the development server on `http://localhost:3000`:
Copia il file di esempio per creare la tua configurazione locale:
```bash
# npm
npm run dev
# pnpm
pnpm dev
# yarn
yarn dev
# bun
bun run dev
cp .env.example .env
```
## Production
Il file `.env` richiede le seguenti chiavi:
Build the application for production:
- `NUXT_PUBLIC_URL`: URL pubblico dell'applicativo frontend (es. `http://localhost:3000`).
- `NUXT_PUBLIC_API`: URL base per il backend API (es. `http://localhost:5555`).
*(Nota: il proxy integrato in `nuxt.config.ts` inoltrerà già le richieste di `/api/v1` al target di staging
configurato `https://api.visionebari.it` in ambiente di sviluppo).*
### 3. Avvio del Server di Sviluppo
```bash
# npm
npm run build
# pnpm
pnpm build
# yarn
yarn build
# bun
bun run build
yarn run dev
```
Locally preview production build:
Il server sarà accessibile all'indirizzo [http://localhost:3000](http://localhost:3000).
---
## Distribuzione e Produzione (Docker)
Il progetto è ottimizzato per essere deployato tramite container Docker, sfruttando processi multi-stage per generare
un'immagine finale snella e performante basata su `node:22-bookworm`.
### Build locale e avvio tramite Docker Compose
Il file `docker-compose.yml` espone il servizio `visione-frontend`.
1. Assicurati che il file `.env` sia valorizzato correttamente.
2. Esegui il build e avvia in background:
```bash
# npm
npm run preview
# pnpm
pnpm preview
# yarn
yarn preview
# bun
bun run preview
docker compose up -d --build
```
Check out the [deployment documentation](https://nuxt.com/docs/getting-started/deployment) for more information.
### Dettagli sul Dockerfile
- **Fase di Build (`AS build`):** Copia `package.json` e `yarn.lock`, esegue `yarn install`, copia i sorgenti ed esegue
`yarn run build`. Iniettando gli argomenti di environment per le API.
- **Fase di Run (`AS run`):** Esegue `yarn install --production` per alleggerire le dipendenze finali. Trasferisce
l'artefatto compilato `.output` e avvia il webserver sulla porta `80` tramite `node /app/server/index.mjs`.
## Testing e Azioni Migliorative Future
I test attuali coprono con successo i flussi primari (registrazione, autenticazione, gestione segnalazioni,
moderazione).
Prossimi step suggeriti:
- Consolidamento con test end-to-end (E2E) automatici per le rotte critiche (in particolare CIE/OTP).
- Verifiche di regressione per gli endpoint Open Data per garantirne l'integrità.
- Monitoraggio della qualità del dato geografico (segnalazioni in aree limite).
+3 -2
View File
@@ -1,14 +1,15 @@
<script setup lang="ts">
useSeoMeta({
title: "Visione - UniBA",
ogTitle: "Visione - UniBA",
title: "Visione",
ogTitle: "Visione",
description: "Un'occhio per la sicurezza del cittadino.",
ogDescription: "Un'occhio per la sicurezza del cittadino.",
ogImage: "/favicon.png"
});
</script>
<template>
<NuxtPwaManifest/>
<NuxtLayout>
<NuxtPage />
</NuxtLayout>
+379
View File
@@ -1,7 +1,386 @@
:root {
--visione-primary: #06c;
--visione-primary-dark: #17324d;
--visione-text-muted: #455b71;
--visione-text-body: #17324d;
--visione-text-soft: #455b71;
--visione-success: #008758;
--visione-warning: #a66300;
--visione-danger: #d9364f;
--visione-info: #2f80ed;
--visione-light-bg: #f0f6fc;
--visione-home-hero-bg: var(--visione-light-bg);
--visione-font-sans: "Titillium Web", Arial, sans-serif;
--visione-font-mono: "Roboto Mono", monospace;
}
html,
body {
color: var(--visione-text-body);
font-family: var(--visione-font-sans);
font-size: 1rem;
line-height: 1.5;
}
button,
input,
select,
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,
samp {
font-family: var(--visione-font-mono);
}
a {
text-decoration: none !important;
}
h1,
h2,
h3,
h4,
h5,
h6,
.h1,
.h2,
.h3,
.h4,
.h5,
.h6,
.card-title,
.callout-title {
color: var(--visione-primary-dark);
font-family: var(--visione-font-sans);
line-height: 1.2;
}
p,
li,
td,
th,
label,
small,
.card-text,
.card .card-body .card-text,
.callout p,
.form-text {
color: inherit;
font-family: var(--visione-font-sans) !important;
}
.lead {
color: var(--visione-text-soft);
font-size: 1.125rem;
line-height: 1.55;
}
.text-muted,
.text-secondary {
color: var(--visione-text-soft) !important;
}
.text-dark {
color: var(--visione-text-body) !important;
}
.text-primary,
.category.text-primary {
color: var(--visione-primary) !important;
}
.text-success,
.category.text-success {
color: var(--visione-success) !important;
}
.text-warning {
color: var(--visione-warning) !important;
}
.text-danger {
color: var(--visione-danger) !important;
}
.text-info {
color: var(--visione-info) !important;
}
.display-1 {
font-size: clamp(3rem, 5vw, 4.75rem);
line-height: 1;
}
.display-3 {
font-size: clamp(2.5rem, 4vw, 3.5rem);
line-height: 1;
}
.display-6 {
font-size: clamp(1.75rem, 2.4vw, 2.25rem);
line-height: 1.1;
}
.bg-light {
background-color: var(--visione-home-hero-bg) !important;
}
html body .navbar .navbar-collapsable .navbar-nav li.nav-item a.nav-link[data-focus-mouse="true"], .navbar .navbar-collapsable .navbar-nav li.nav-item button.nav-link[data-focus-mouse="true"] {
border-color: inherit !important
}
.it-hero-wrapper.it-primary,
.it-hero-wrapper.it-primary-bg {
background: var(--visione-primary) !important;
color: #fff;
}
.it-hero-wrapper.it-primary h1,
.it-hero-wrapper.it-primary p,
.it-hero-wrapper.it-primary-bg h1,
.it-hero-wrapper.it-primary-bg p {
color: #fff !important;
}
.it-hero-wrapper .container {
min-height: 240px;
display: flex;
align-items: center;
}
.it-hero-wrapper.hero-compact .container {
min-height: 132px;
}
.it-hero-wrapper .container > .row {
width: 100%;
justify-content: center;
}
.it-hero-wrapper .it-hero-text-wrapper {
max-width: 820px;
margin: 0 auto;
text-align: center;
display: flex;
flex-direction: column;
align-items: center;
}
.it-hero-wrapper .it-hero-text-wrapper h1,
.it-hero-wrapper .it-hero-text-wrapper p {
width: 100%;
}
.it-hero-wrapper.bg-light .it-hero-text-wrapper p {
font-size: 1.3rem;
}
.bg-light h1,
.bg-light h2,
.bg-light h3,
.bg-light h4,
.bg-light h5,
.bg-light h6 {
color: var(--visione-primary-dark) !important;
}
.bg-light p,
.bg-light .lead,
.bg-light .text-muted,
.bg-light .text-secondary {
color: var(--visione-text-soft) !important;
}
.icon {
color: currentColor;
fill: currentColor;
flex-shrink: 0;
}
.icon-primary {
color: var(--visione-primary) !important;
fill: var(--visione-primary) !important;
}
.icon-success {
color: var(--visione-success) !important;
fill: var(--visione-success) !important;
}
.icon-warning {
color: var(--visione-warning) !important;
fill: var(--visione-warning) !important;
}
.icon-danger {
color: var(--visione-danger) !important;
fill: var(--visione-danger) !important;
}
.icon-info {
color: var(--visione-info) !important;
fill: var(--visione-info) !important;
}
.btn-primary .icon:not([class*="icon-"]),
.badge[class*="bg-"] .icon:not([class*="icon-"]),
.rounded-circle[class*="bg-"] .icon:not([class*="icon-"]) {
color: #fff;
fill: #fff;
}
.btn-xs {
--bs-btn-padding-y: 0.25rem;
--bs-btn-padding-x: 0.55rem;
--bs-btn-font-size: 0.875rem;
line-height: 1.2;
}
.btn-icon.btn-xs {
align-items: center;
display: inline-flex;
height: 2rem;
justify-content: center;
padding: 0;
width: 2rem;
}
.report-table-wrapper {
border: 1px solid #dfe4ea;
border-radius: 4px;
}
.report-table thead th {
background: #f7f9fa;
color: var(--visione-text-soft);
font-size: 0.8125rem;
font-weight: 700;
padding: 0.65rem 0.75rem;
text-transform: uppercase;
}
.report-table tbody td {
font-size: 0.9375rem;
padding: 0.75rem;
vertical-align: middle;
}
.report-table-id {
color: var(--visione-primary-dark);
font-weight: 700;
white-space: nowrap;
}
.report-address {
color: var(--visione-text-soft);
display: inline-block;
max-width: min(36vw, 26rem);
overflow: hidden;
text-overflow: ellipsis;
vertical-align: bottom;
white-space: nowrap;
}
.dashboard-stat {
border-left: 4px solid var(--visione-primary);
}
.dashboard-stat .stat-value {
color: var(--visione-primary-dark);
font-size: 1.75rem;
font-weight: 700;
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 {
}
.it-footer,
.it-footer a,
.it-footer h2,
.it-footer h3,
.it-footer h4,
.it-footer .it-brand-text,
.it-footer .it-brand-text h2,
.it-footer .it-brand-text h3,
.it-footer .member-name,
.it-footer .icon {
color: #fff !important;
fill: #fff !important;
}
@media (max-width: 767.98px) {
.page-shell {
padding-block: 2rem;
}
.it-hero-wrapper .container {
min-height: 220px;
}
.it-hero-wrapper .it-hero-text-wrapper {
padding-left: 1rem !important;
padding-right: 1rem !important;
}
.report-address {
max-width: 14rem;
}
}
.alert-danger {
background-position-y: center;
}
.card::after {
margin-top: 0!important;
}
+17 -2
View File
@@ -1,9 +1,24 @@
<script setup lang="ts">
defineProps<{
const iconAliases: Record<string, string> = {
'it-bell': 'it-info-circle',
'it-grid': 'it-list',
'it-history': 'it-clock',
'it-home': 'it-pa',
'it-image': 'it-file-image',
'it-location': 'it-map-marker-circle',
'it-map': 'it-map-marker-circle',
'it-piu': 'it-plus',
'it-star': 'it-star-full',
'it-write': 'it-pencil',
}
const props = defineProps<{
name: string
size?: 'xs' | 'sm' | 'lg' | 'xl'
color?: 'primary' | 'success' | 'warning' | 'danger' | 'info' | 'white'
}>()
const resolvedName = computed(() => iconAliases[props.name] || props.name)
</script>
<template>
@@ -15,6 +30,6 @@ defineProps<{
]"
aria-hidden="true"
>
<use :href="`/sprites.svg#${name}`"></use>
<use :href="`/sprites.svg#${resolvedName}`"></use>
</svg>
</template>
+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>
+252 -25
View File
@@ -1,43 +1,58 @@
<script setup lang="ts">
import MemberDot from "~/components/MemberDot.vue";
import BIIcon from "~/components/BIIcon.vue";
import { useMembers } from "~/composables/useMembers";
const { sortedMembers } = useMembers();
const footerLinks = [
{ label: "Home", path: "/" },
{ label: "Esplora i dati", path: "/open-data" },
{ label: "Come funziona", path: "/info" },
];
const supportItems = [
{ label: "E-mail", value: "[email protected]", href: "mailto:[email protected]" },
{ label: "Telefono", value: "+39 080 468 2010", href: "tel:+390804682010" },
{ label: "Supporto", value: "Lun - Ven, 9:00 - 18:00" },
];
</script>
<template>
<footer class="it-footer">
<div class="it-footer-main">
<div class="container">
<section>
<div class="row clearfix">
<div class="col-sm-12">
<div class="container footer-main-content">
<section class="footer-brand-section">
<div class="it-brand-wrapper">
<a href="#" data-focus-mouse="false">
<BIIcon name="it-code-circle" />
<NuxtLink to="/" data-focus-mouse="false" class="footer-brand-link">
<img alt="Logo Visione" class="footer-brand-logo" src="/logo-light.svg"/>
<div class="it-brand-text">
<h2>Visione</h2>
<h3 class="d-none d-md-block">Segnalazioni anonime e sicure</h3>
</div>
</a>
</div>
<h3>Un occhio per la sicurezza di Bari</h3>
</div>
</NuxtLink>
</div>
</section>
<section class="py-4 border-white border-top">
<div class="row">
<div class="col-12 pb-2">
<div class="pb-2">
<h4>Progetto di</h4>
<div class="members-list d-flex justify-content-center align-items-center gap-5 flex-wrap w-100">
<MemberDot
<section class="footer-content-section">
<div class="footer-support">
<h4>Assistenza per i cittadini</h4>
<ul class="footer-support-list">
<li v-for="item in supportItems" :key="item.label">
<span class="footer-support-label">{{ item.label }}:</span>
<a v-if="item.href" :href="item.href">{{ item.value }}</a>
<span v-else>{{ item.value }}</span>
</li>
</ul>
</div>
<div class="footer-members">
<div class="footer-members-grid">
<div
v-for="member in sortedMembers"
:key="member.name"
:name="member.name"
:image="member.image"
/>
</div>
class="footer-member-card"
>
<img :src="member.image" :alt="member.name" class="footer-member-image">
<div class="footer-member-name">{{ member.name }}</div>
</div>
</div>
</div>
@@ -46,13 +61,225 @@ const { sortedMembers } = useMembers();
</div>
<div class="it-footer-small-prints clearfix">
<div class="container">
<ul class="it-footer-small-prints-list list-inline mb-0 d-flex flex-column flex-md-row">
<div class="footer-lower-bar">
<ul class="footer-primary-menu list-inline mb-0">
<li v-for="link in footerLinks" :key="link.path" class="list-inline-item">
<NuxtLink :to="link.path">{{ link.label }}</NuxtLink>
</li>
</ul>
<ul class="it-footer-small-prints-list list-inline mb-0">
<li class="list-inline-item"><a href="/note-legali">Note legali</a></li>
<li class="list-inline-item"><a href="/privacy">Privacy policy</a></li>
<li class="list-inline-item"><a href="/sitemap.xml">Mappa del sito</a></li>
<li class="list-inline-item"><a href="https://form.agid.gov.it/view/xyz">Dichiarazione di accessibilità <span class="visually-hidden">(link esterno su sito AgID)</span></a></li>
</ul>
</div>
</div>
</div>
</footer>
</template>
<style scoped>
.footer-main-content {
padding-top: 2.5rem;
padding-bottom: 2.5rem;
}
.footer-brand-section {
padding-bottom: 1.75rem;
border-bottom: 1px solid rgba(255, 255, 255, 0.28);
}
.footer-brand-link {
display: inline-flex;
align-items: center;
gap: 1rem;
text-decoration: none;
}
.footer-brand-logo {
width: 52px;
height: 52px;
flex-shrink: 0;
}
.footer-brand-section .it-brand-text h2 {
margin-bottom: 0.25rem;
font-size: 1.75rem;
}
.footer-brand-section .it-brand-text h3 {
margin-bottom: 0;
font-size: 1rem;
font-weight: 400;
}
.footer-content-section {
display: flex;
justify-content: space-between;
align-items: center;
gap: 2rem;
padding-top: 2rem;
}
.footer-support {
max-width: 30rem;
}
.footer-support h4 {
margin-bottom: 1.25rem;
font-size: 1.3rem;
text-transform: uppercase;
}
.footer-support-list {
margin: 0;
padding: 0;
list-style: none;
display: grid;
gap: 0.75rem;
font-size: 1.05rem;
}
.footer-support-label {
font-weight: 700;
margin-right: 0.35rem;
}
.footer-members {
flex: 1;
display: flex;
justify-content: flex-end;
}
.footer-members-grid {
display: grid;
grid-template-columns: repeat(3, minmax(110px, 140px));
gap: 1rem;
align-items: start;
}
.footer-member-card {
display: flex;
flex-direction: column;
align-items: center;
gap: 0.75rem;
text-align: center;
}
.footer-member-image {
width: 100%;
max-width: 126px;
aspect-ratio: 1;
border-radius: 50%;
object-fit: cover;
background: rgba(255, 255, 255, 0.16);
border: 2px solid rgba(255, 255, 255, 0.2);
}
.footer-member-name {
font-size: 0.95rem;
line-height: 1.25;
font-weight: 600;
}
.footer-lower-bar {
display: flex;
justify-content: space-between;
align-items: center;
gap: 1.5rem;
padding-top: 1rem;
padding-bottom: 1rem;
}
.footer-primary-menu,
.it-footer-small-prints-list {
display: flex;
flex-wrap: wrap;
gap: 1rem 1.5rem;
align-items: center;
}
.footer-primary-menu .list-inline-item,
.it-footer-small-prints-list .list-inline-item {
margin: 0;
}
.footer-primary-menu a,
.it-footer-small-prints-list a {
text-decoration: none;
}
.footer-primary-menu a:hover,
.footer-primary-menu a:focus,
.it-footer-small-prints-list a:hover,
.it-footer-small-prints-list a:focus {
text-decoration: underline;
}
@media (max-width: 991.98px) {
.footer-content-section {
align-items: flex-start;
flex-direction: column;
}
.footer-support {
max-width: none;
}
.footer-members {
width: 100%;
justify-content: flex-start;
}
.footer-lower-bar {
flex-direction: column;
align-items: flex-start;
}
}
@media (max-width: 767.98px) {
.footer-main-content {
padding-top: 2rem;
padding-bottom: 2rem;
}
.footer-brand-link {
align-items: flex-start;
}
.footer-brand-section .it-brand-text h2 {
font-size: 1.45rem;
}
.footer-brand-section .it-brand-text h3 {
font-size: 0.95rem;
}
.footer-support h4 {
font-size: 1.1rem;
}
.footer-support-list {
font-size: 1rem;
}
.footer-members-grid {
width: 100%;
grid-template-columns: repeat(2, minmax(110px, 1fr));
}
.footer-primary-menu,
.it-footer-small-prints-list {
flex-direction: column;
align-items: flex-start;
gap: 0.75rem;
}
}
@media (max-width: 479.98px) {
.footer-members-grid {
grid-template-columns: 1fr;
max-width: 150px;
}
}
</style>
+155 -25
View File
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { computed, onUnmounted, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import BIIcon from "~/components/BIIcon.vue";
@@ -10,14 +10,31 @@ watch(() => route.path, () => {
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 { isAuthenticated, user, logout, hasUnreadNotifications } = useAuth()
const panelLabel = computed(() => isAdmin(user.value?.role) ? 'Pannello' : 'Dashboard')
const navLinks = [
{ name: 'Home', path: '/' },
{ name: 'Fai una segnalazione', path: '/reports/create' },
...(isCitizen(user.value?.role) ? [{ name: 'Fai una segnalazione', path: '/reports/new' }] : []),
{ name: 'Esplora i dati', path: '/open-data' },
{ name: 'Come funziona', path: '/info' }
]
const { isAuthenticated, user, logout } = useAuth()
</script>
<template>
@@ -27,51 +44,56 @@ const { isAuthenticated, user, logout } = useAuth()
<div class="row">
<div class="col-12">
<div class="it-header-slim-wrapper-content">
<a class="d-none d-lg-block navbar-brand"
href="https://www.interno.gov.it/it/ministero/dipartimenti/dipartimento-pubblica-sicurezza">
Dipartimento della Pubblica Sicurezza
<a class="d-none d-lg-block navbar-brand" href="https://www.cittametropolitana.ba.it/">
Città metropolitana di Bari
</a>
<div class="nav-mobile">
<nav aria-label="Navigazione secondaria">
<a class="it-opener d-lg-none" data-bs-toggle="collapse"
href="https://www.interno.gov.it/it/ministero/dipartimenti/dipartimento-pubblica-sicurezza"
href="https://www.cittametropolitana.ba.it/"
role="button" aria-expanded="false">
<span>Dipartimento della Pubblica Sicurezza</span>
<span>Città metropolitana di Bari</span>
<BIIcon name="it-expand"/>
</a>
</nav>
</div>
<div class="header-slim-right-zone" role="navigation">
<!-- Utente Autenticato: Bottone Utente + Bottone Esci -->
<div v-if="isAuthenticated" class="d-flex align-items-center gap-2">
<NuxtLink class="btn btn-primary btn-icon btn-full" to="/me"
<NuxtLink class="btn btn-primary btn-icon btn-full" to="/dashboard"
data-element="personal-area-dashboard" data-focus-mouse="false">
<span class="rounded-icon" aria-hidden="true">
<BIIcon name="it-user" />
<BIIcon name="it-list" color="black"/>
</span>
<span class="d-none d-lg-block">{{ user?.first_name }}</span>
<span class="d-none d-lg-block">{{ panelLabel }}</span>
</NuxtLink>
<NuxtLink class="btn btn-primary btn-icon btn-full" to="/profile"
data-element="personal-area-dashboard" data-focus-mouse="false">
<span class="rounded-icon profile-icon-wrap" aria-hidden="true">
<BIIcon name="it-user" color="black"/>
<span v-if="hasUnreadNotifications" class="notification-dot"></span>
</span>
<span class="d-none d-lg-block username">{{ user?.first_name }}</span>
</NuxtLink>
<button class="btn btn-primary btn-icon btn-full border-0" @click="logout"
data-element="personal-area-logout" data-focus-mouse="false">
<span class="rounded-icon" aria-hidden="true">
<BIIcon name="it-logout" /> <!-- usa it-unlocked se it-logout non è presente -->
<BIIcon name="it-logout" color="black"/>
</span>
<span class="d-none d-lg-block">Esci</span>
</button>
</div>
<!-- Utente NON Autenticato: Bottone Login -->
<NuxtLink v-else class="btn btn-primary btn-icon btn-full" to="/auth/login"
data-element="personal-area-login" data-focus-mouse="false">
<span class="rounded-icon" aria-hidden="true">
<BIIcon name="it-user" />
<BIIcon name="it-user" color="black"/>
</span>
<span class="d-none d-lg-block">Login</span>
</NuxtLink>
</div>
</div>
</div>
</div>
@@ -86,7 +108,7 @@ const { isAuthenticated, user, logout } = useAuth()
<div class="it-header-center-content-wrapper">
<div class="it-brand-wrapper">
<NuxtLink to="/">
<BIIcon name="it-pa"/>
<img alt="Logo Visione" class="logo" src="/logo-light.svg"/>
<div class="it-brand-text">
<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>
@@ -104,6 +126,7 @@ const { isAuthenticated, user, logout } = useAuth()
<div class="row">
<div class="col-12">
<nav class="navbar navbar-expand-lg has-megamenu" aria-label="Navigazione principale">
<button
class="custom-navbar-toggler"
type="button"
@@ -117,19 +140,16 @@ const { isAuthenticated, user, logout } = useAuth()
class="overlay"
:class="{ 'show': isMobileMenuOpen }"
@click="isMobileMenuOpen = false"
style="display: block;"
v-show="isMobileMenuOpen"
></div>
<div
class="navbar-collapsable"
:class="{ 'expanded': isMobileMenuOpen }"
style="display: block;"
>
<div class="close-div">
<button class="btn close-menu" type="button" @click="isMobileMenuOpen = false">
<span class="visually-hidden">Nascondi la navigazione</span>
<BIIcon name="it-close-big"/>
<BIIcon name="it-close-big" color="black"/>
</button>
</div>
@@ -177,14 +197,124 @@ const { isAuthenticated, user, logout } = useAuth()
background-color: rgb(0, 76.5, 153);
}
@media (max-width: 991.98px) {
.overlay {
transition: opacity 0.3s ease;
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background-color: rgba(0, 0, 0, 0.6) !important;
z-index: 1040;
opacity: 0;
pointer-events: none;
visibility: hidden;
transition: opacity 0.3s ease, visibility 0.3s ease;
}
.overlay.show {
opacity: 1;
pointer-events: auto;
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;
}
}
.btn-full {
padding: 14px;
}
.logo {
width: 48px;
height: 48px;
margin-inline: 16px;
}
.profile-icon-wrap {
position: relative;
}
.notification-dot {
position: absolute;
top: -2px;
right: -2px;
width: 10px;
height: 10px;
border-radius: 50%;
background: #d9364f;
border: 2px solid #ffffff;
}
.username {
max-width: 8ch;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
</style>
+19 -18
View File
@@ -1,4 +1,4 @@
<script setup lang="ts">
<script lang="ts" setup>
interface Props {
modelValue?: File[]
maxFiles?: number
@@ -72,14 +72,14 @@ const getFileUrl = (file: File) => {
<template>
<div class="media-uploader">
<div
class="upload-area border-2 border-dashed rounded-3 p-4 text-center cursor-pointer position-relative"
:class="{ 'border-primary bg-primary bg-opacity-10': isDragging, 'bg-light': !isDragging }"
class="upload-area border-2 border-dashed rounded-3 p-4 text-center cursor-pointer position-relative"
@click="!disabled && openFileDialog()"
@dragover.prevent="isDragging = true"
@dragleave.prevent="isDragging = false"
@drop.prevent="isDragging = false; handleFilesSelected(($event as DragEvent).dataTransfer?.files || null)"
@click="!disabled && openFileDialog()"
>
<BIIcon name="it-upload" size="xl" color="primary" class="mb-3" />
<BIIcon class="mb-3" color="primary" name="it-upload" size="xl"/>
<div class="h6 font-weight-bold">
Trascina i file qui o <span class="text-primary text-decoration-underline">clicca per selezionare</span>
</div>
@@ -90,11 +90,11 @@ const getFileUrl = (file: File) => {
<input
ref="fileInputRef"
type="file"
:multiple="maxFiles > 1"
:accept="acceptedTypes"
:disabled="disabled"
:multiple="maxFiles > 1"
class="d-none"
type="file"
@change="handleFilesSelected(($event.target as HTMLInputElement).files)"
/>
@@ -106,26 +106,27 @@ const getFileUrl = (file: File) => {
<div v-for="(file, idx) in files" :key="`file-${idx}`" class="col-6 col-md-4 col-lg-3">
<div class="card h-100 position-relative shadow-sm border-0">
<div class="ratio ratio-1x1 bg-light rounded-top overflow-hidden">
<img v-if="file.type.startsWith('image/')" :src="getFileUrl(file)" class="object-fit-cover" :alt="file.name" />
<img v-if="file.type.startsWith('image/')" :alt="file.name" :src="getFileUrl(file)"
class="object-fit-cover"/>
<video v-else-if="file.type.startsWith('video/')" :src="getFileUrl(file)" class="object-fit-cover"></video>
<div v-else class="d-flex align-items-center justify-content-center bg-secondary bg-opacity-25">
<BIIcon name="it-file" size="xl" color="secondary" />
<BIIcon color="secondary" name="it-file" size="xl"/>
</div>
</div>
<button
type="button"
:disabled="disabled"
class="btn btn-danger btn-sm position-absolute top-0 end-0 m-1 rounded-circle p-1 d-flex align-items-center justify-content-center shadow"
style="width: 28px; height: 28px; z-index: 10;"
@click.stop="removeFile(idx)"
:disabled="disabled"
title="Rimuovi file"
type="button"
@click.stop="removeFile(idx)"
>
<BIIcon name="it-close" size="sm" color="white" />
<BIIcon color="white" name="it-close" size="sm"/>
</button>
<div class="card-body p-2 d-flex flex-column justify-content-between">
<div class="small text-truncate fw-semibold" :title="file.name">{{ file.name }}</div>
<div :title="file.name" class="small text-truncate fw-semibold">{{ file.name }}</div>
<div class="small text-muted d-flex justify-content-between align-items-center mt-1">
<span>{{ formatFileSize(file.size) }}</span>
<div class="progress flex-grow-1 ms-2" style="height: 4px;" title="Pronto per l'upload">
@@ -143,27 +144,27 @@ const getFileUrl = (file: File) => {
.upload-area {
transition: all 0.2s ease-in-out;
}
.upload-area:hover:not(.border-primary) {
background-color: #f8f9fa !important;
border-color: #0066cc !important;
}
.cursor-pointer {
cursor: pointer;
}
.border-dashed {
border-style: dashed !important;
}
.border-2 {
border-width: 2px !important;
}
.object-fit-cover {
object-fit: cover;
width: 100%;
height: 100%;
}
</style>
+43 -66
View File
@@ -1,21 +1,20 @@
<script setup lang="ts">
import { ref } from 'vue'
interface Emits {
(e: 'send', message: string, files: File[]): void
(e: 'send', message: string): void
}
const emit = defineEmits<Emits>()
const message = ref('')
const isSubmitting = ref(false)
const files = ref<File[]>([])
const fileInputRef = ref<HTMLInputElement>()
const handleSubmit = () => {
if (message.value.trim() === '' && files.value.length === 0) return
if (message.value.trim() === '') return
emit('send', message.value, [...files.value])
emit('send', message.value)
message.value = ''
files.value = []
}
const handleKeydown = (e: KeyboardEvent) => {
@@ -24,75 +23,34 @@ const handleKeydown = (e: KeyboardEvent) => {
handleSubmit()
}
}
const handleFileSelect = (e: Event) => {
const target = e.target as HTMLInputElement
if (target.files) {
const newFiles = Array.from(target.files)
files.value = [...files.value, ...newFiles].slice(0, 5) // max 5
}
if (fileInputRef.value) {
fileInputRef.value.value = ''
}
}
const removeFile = (idx: number) => {
files.value.splice(idx, 1)
}
</script>
<template>
<div class="message-composer mt-4 border-top pt-3">
<div class="message-composer mt-3">
<form @submit.prevent="handleSubmit">
<!-- Preview Allegati -->
<div v-if="files.length > 0" class="mb-3 d-flex flex-wrap gap-2">
<div v-for="(file, idx) in files" :key="idx" class="badge bg-light text-dark border p-2 d-flex align-items-center gap-2">
<BIIcon name="it-clip" size="xs" />
<span class="text-truncate" style="max-width: 150px;">{{ file.name }}</span>
<button type="button" class="btn-close ms-2" style="font-size: 0.5rem;" @click="removeFile(idx)" aria-label="Rimuovi allegato"></button>
</div>
</div>
<div class="input-group align-items-end">
<button
type="button"
class="btn btn-outline-secondary me-2 rounded"
title="Allega file (max 5)"
@click="fileInputRef?.click()"
:disabled="isSubmitting || files.length >= 5"
>
<BIIcon name="it-clip" size="sm" />
</button>
<input
ref="fileInputRef"
type="file"
multiple
class="d-none"
@change="handleFileSelect"
accept="image/*,video/*,.pdf,.doc,.docx"
/>
<div class="d-flex align-items-stretch gap-2">
<textarea
v-model="message"
class="form-control rounded"
placeholder="Scrivi un messaggio... (Ctrl+Enter per inviare)"
rows="2"
class="form-control chat-textarea m-0"
placeholder="Scrivi aggiornamento o domanda"
:disabled="isSubmitting"
@keydown="handleKeydown"
/>
></textarea>
<button
type="submit"
class="btn btn-primary ms-2 rounded"
:disabled="isSubmitting || (message.trim() === '' && files.length === 0)"
class="btn btn-primary btn-square flex-shrink-0"
:disabled="isSubmitting || message.trim() === ''"
title="Invia"
>
<span v-if="isSubmitting" class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>
<BIIcon v-else name="it-arrow-right" size="sm" color="white" class="me-1" />
Invia
<span v-if="isSubmitting" class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
<BIIcon v-else color="white" name="it-arrow-right" size="sm"/>
</button>
</div>
<small class="text-muted d-block mt-2">
💡 <strong>Tip:</strong> Premi Ctrl+Enter per inviare velocemente
`Ctrl` + `Invio` per inviare.
</small>
</form>
</div>
@@ -100,13 +58,32 @@ const removeFile = (idx: number) => {
<style scoped>
.message-composer {
background-color: #f9f9f9;
border-radius: 0.5rem;
padding: 1rem;
border-top: 1px solid #d9e3ee;
padding-top: 1rem;
}
textarea {
resize: vertical;
font-family: inherit;
.chat-textarea {
resize: none !important;
height: 48px;
min-height: 48px;
overflow-y: auto;
padding-top: 12px;
padding-bottom: 12px;
border-radius: 6px;
}
.chat-textarea:focus {
border-color: #06c;
box-shadow: 0 0 0 2px rgba(0, 102, 204, 0.12);
}
.btn-square {
width: 48px;
height: 48px;
padding: 0;
display: flex;
align-items: center;
justify-content: center;
border-radius: 6px;
}
</style>
+135 -26
View File
@@ -4,12 +4,20 @@ import type { Message } from '~/types/api'
interface Props {
messages: Message[]
isLoading?: boolean
canFlagMessage?: (message: Message) => boolean
isFlaggingMessageId?: number | null
}
withDefaults(defineProps<Props>(), {
isLoading: false
isLoading: false,
canFlagMessage: () => false,
isFlaggingMessageId: null,
})
const emit = defineEmits<{
(e: 'flag', message: Message): void
}>()
const formatDate = (dateString: string): string => {
const date = new Date(dateString)
const today = new Date()
@@ -28,6 +36,9 @@ const formatDate = (dateString: string): string => {
const auth = useAuth()
const isCurrentUser = (userId: number): boolean => auth.user.value?.id === userId
const senderInitials = (msg: Message): string =>
`${msg.first_name?.[0] || ''}${msg.last_name?.[0] || ''}`.toUpperCase() || '?'
</script>
<template>
@@ -38,37 +49,59 @@ const isCurrentUser = (userId: number): boolean => auth.user.value?.id === userI
</div>
</div>
<div v-else-if="messages.length === 0" class="alert alert-info text-center" role="alert">
Nessun messaggio disponibile. Sii il primo a scrivere!
<div v-else-if="messages.length === 0" class="message-empty-state" role="alert">
<BIIcon class="mb-2" color="primary" name="it-comment" size="lg"/>
<strong class="d-block mb-1">Nessun messaggio</strong>
<span>Usa chat per aggiornamenti rapidi tra cittadino e operatori.</span>
</div>
<div v-else class="messages-container">
<div
v-for="msg in messages"
:key="msg.id"
class="message-bubble mb-3 d-flex"
:class="{ 'justify-content-end': isCurrentUser(msg.user_id), 'justify-content-start': !isCurrentUser(msg.user_id) }"
:class="{ 'is-current-user': isCurrentUser(msg.user_id) }"
class="message-row"
>
<div v-if="!isCurrentUser(msg.user_id)" class="message-avatar" aria-hidden="true">
{{ senderInitials(msg) }}
</div>
<div
class="message-bubble-content p-3 rounded-3"
:class="{
'bg-primary text-white': isCurrentUser(msg.user_id),
'bg-light border': !isCurrentUser(msg.user_id)
'message-bubble-outgoing': isCurrentUser(msg.user_id),
'message-bubble-incoming': !isCurrentUser(msg.user_id)
}"
class="message-bubble-content"
>
<!-- Nome mittente (solo per messaggi non miei) -->
<div v-if="!isCurrentUser(msg.user_id)" class="small font-weight-bold mb-2 text-primary">
<div class="message-meta">
<span v-if="!isCurrentUser(msg.user_id)" class="message-author">
{{ msg.first_name }} {{ msg.last_name }}
</span>
<span v-else class="message-author">Tu</span>
<span class="message-time">
{{ formatDate(msg.created_at) }}
</span>
</div>
<div v-if="!isCurrentUser(msg.user_id)" class="small font-weight-bold mb-2 text-primary d-none">
{{ msg.first_name }} {{ msg.last_name }}
</div>
<!-- Corpo messaggio -->
<div class="message-body" :class="{ 'text-break': true }">
<div class="message-body">
{{ msg.body }}
</div>
<!-- Timestamp -->
<div class="small mt-2" :class="{ 'text-white-50': isCurrentUser(msg.user_id), 'text-muted': !isCurrentUser(msg.user_id) }">
{{ formatDate(msg.created_at) }}
<div v-if="canFlagMessage?.(msg)" class="message-actions">
<button
:disabled="isFlaggingMessageId === msg.id"
class="btn btn-link btn-xs px-0"
type="button"
@click="emit('flag', msg)"
>
<span v-if="isFlaggingMessageId === msg.id" aria-hidden="true"
class="spinner-border spinner-border-sm me-1"></span>
<BIIcon v-else class="me-1" name="it-flag" size="xs"/>
Segnala messaggio
</button>
</div>
</div>
</div>
@@ -78,34 +111,110 @@ const isCurrentUser = (userId: number): boolean => auth.user.value?.id === userI
<style scoped>
.message-list {
max-height: 500px;
border: 1px solid #d9e3ee;
border-radius: 4px;
height: 34rem;
overflow-y: auto;
padding: 1rem;
background-color: #f9f9f9;
border-radius: 0.5rem;
border: 1px solid #e9ecef;
display: flex;
flex-direction: column;
}
.messages-container {
display: flex;
flex-direction: column;
gap: 0.875rem;
}
.message-bubble {
.message-empty-state {
align-items: center;
color: #5c6f82;
display: flex;
flex-direction: column;
justify-content: center;
flex: 1;
padding: 2rem 1rem;
text-align: center;
}
.message-row {
align-items: flex-end;
display: flex;
gap: 0.75rem;
justify-content: flex-start;
}
.message-row.is-current-user {
justify-content: flex-end;
}
.message-avatar {
align-items: center;
background: #e6f0fa;
border-radius: 999px;
color: #17324d;
display: inline-flex;
flex: 0 0 2.25rem;
font-size: 0.75rem;
font-weight: 700;
height: 2.25rem;
justify-content: center;
}
.message-bubble-content {
max-width: 75%;
word-wrap: break-word;
border-radius: 4px;
max-width: min(100%, 40rem);
padding: 0.875rem 1rem;
word-break: break-word;
}
.message-bubble-incoming {
background: #f5f7f9;
border: 1px solid #d9e3ee;
color: #17324d;
}
.message-bubble-outgoing {
background: #06c;
color: #fff;
}
.message-meta {
align-items: center;
display: flex;
font-size: 0.8125rem;
gap: 0.75rem;
justify-content: space-between;
margin-bottom: 0.375rem;
}
.message-author {
font-weight: 700;
}
.message-time {
opacity: 0.78;
white-space: nowrap;
}
.message-body {
white-space: pre-wrap;
line-height: 1.4;
white-space: pre-wrap;
}
.message-actions {
margin-top: 0.5rem;
text-align: right;
}
.message-actions .btn {
font-size: 0.75rem;
}
@media (max-width: 767.98px) {
.message-bubble-content {
max-width: calc(100% - 3rem);
}
}
</style>
-4
View File
@@ -57,7 +57,6 @@ const pageNumbers = computed(() => {
<template>
<nav v-if="totalPages > 1" class="d-flex justify-content-center mt-5 mb-5">
<ul class="pagination mb-0">
<!-- Pagina Precedente -->
<li class="page-item" :class="{ disabled: currentPage === 1 }">
<button
class="page-link"
@@ -69,7 +68,6 @@ const pageNumbers = computed(() => {
</button>
</li>
<!-- Numeri Pagine -->
<li v-for="page in pageNumbers" :key="`page-${page}`" class="page-item" :class="{ active: page === currentPage }">
<template v-if="page === '...'">
<span class="page-link">...</span>
@@ -86,7 +84,6 @@ const pageNumbers = computed(() => {
</template>
</li>
<!-- Pagina Successiva -->
<li class="page-item" :class="{ disabled: currentPage === totalPages }">
<button
class="page-link"
@@ -100,7 +97,6 @@ const pageNumbers = computed(() => {
</ul>
</nav>
<!-- Info Pagina -->
<div v-if="totalPages > 1" class="text-center text-muted small mt-3">
Pagina {{ currentPage }} di {{ totalPages }} ({{ totalItems }} elementi totali)
</div>
+352 -53
View File
@@ -1,20 +1,9 @@
<script setup lang="ts">
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 L from 'leaflet'
import 'leaflet/dist/leaflet.css'
// Fix per le icone di Leaflet in Nuxt/Vite
const DefaultIcon = L.icon({
iconUrl: 'https://unpkg.com/[email protected]/dist/images/marker-icon.png',
iconRetinaUrl: 'https://unpkg.com/[email protected]/dist/images/marker-icon-2x.png',
shadowUrl: 'https://unpkg.com/[email protected]/dist/images/marker-shadow.png',
iconSize: [25, 41],
iconAnchor: [12, 41],
popupAnchor: [1, -34],
shadowSize: [41, 41]
});
L.Marker.prototype.options.icon = DefaultIcon;
import { BARI_BOUNDS, BARI_CENTER, isWithinBariBounds } from '~/utils/bari'
import { reverseGeocode, searchAddresses } from '~/utils/geocoding'
interface Props {
isLoading?: boolean
@@ -25,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: () => []
@@ -44,61 +39,277 @@ 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 map: L.Map | null = null
let marker: L.Marker | 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 initMap = () => {
if (!mapContainer.value || map) return
const loadLeaflet = async () => {
if (leaflet) return leaflet
// Centro Italia default
const defaultLat = 41.8719
const defaultLng = 12.5674
const zoom = 5
const leafletModule = await import('leaflet')
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: L.LeafletMouseEvent) => {
updateLocation(e.latlng.lat, e.latlng.lng)
const defaultIcon = leafletModule.icon({
iconUrl: 'https://unpkg.com/[email protected]/dist/images/marker-icon.png',
iconRetinaUrl: 'https://unpkg.com/[email protected]/dist/images/marker-icon-2x.png',
shadowUrl: 'https://unpkg.com/[email protected]/dist/images/marker-shadow.png',
iconSize: [25, 41],
iconAnchor: [12, 41],
popupAnchor: [1, -34],
shadowSize: [41, 41]
})
leafletModule.Marker.prototype.options.icon = defaultIcon
// Se c'è già una posizione, imposta il marker
if (form.value.latitude && form.value.longitude) {
updateLocation(form.value.latitude, form.value.longitude, true)
leaflet = leafletModule
return leaflet
}
const toLocationKey = (lat: number, lng: number) => `${lat.toFixed(6)}:${lng.toFixed(6)}`
const clearAddressSuggestions = () => {
addressSuggestions.value = []
showAddressSuggestions.value = false
}
const cancelPendingAddressSearch = () => {
addressSearchRequestId += 1
isSearchingAddress.value = false
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
}
if (map) {
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 = L.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)
})
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(() => {
// Map logic is handled by ClientOnly placeholder if needed, but we initialize here
void initMap()
})
onUnmounted(() => {
cancelPendingAddressSearch()
cancelPendingReverseGeocode()
if (manualLocationSyncTimeout) {
clearTimeout(manualLocationSyncTimeout)
manualLocationSyncTimeout = null
}
if (map) {
map.remove()
map = null
@@ -113,6 +324,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'
@@ -138,7 +351,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 {
@@ -170,11 +383,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)
}
}
@@ -184,18 +403,63 @@ watch(() => form.value.category_id, () => {
}
})
// Sincronizza input manuali con la mappa
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)
})
watch([() => form.value.latitude, () => form.value.longitude], ([newLat, newLng]) => {
if (newLat && newLng && map) {
if (newLat && newLng && map && leaflet) {
if (!marker || marker.getLatLng().lat !== newLat || marker.getLatLng().lng !== newLng) {
if (!marker) {
marker = L.marker([newLat, newLng]).addTo(map)
marker = leaflet.marker([newLat, newLng]).addTo(map)
} else {
marker.setLatLng([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>
@@ -234,6 +498,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"
@@ -289,15 +554,44 @@ watch([() => form.value.latitude, () => form.value.longitude], ([newLat, newLng]
<BIIcon name="it-home" size="sm" color="primary" class="me-2" />
Indirizzo *
</label>
<div class="position-relative">
<input
id="address"
v-model="form.address"
type="text"
class="form-control"
:class="{ 'is-invalid': errors.address }"
placeholder="Es. Via Roma 123, Milano"
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>
@@ -365,7 +659,16 @@ watch([() => form.value.latitude, () => form.value.longitude], ([newLat, newLng]
.map-container {
height: 300px;
width: 100%;
z-index: 1; /* Fix for Bootstrap elements overlapping map */
z-index: 1;
overflow: hidden;
}
.address-suggestions {
top: calc(100% + 0.25rem);
left: 0;
z-index: 10;
max-height: 16rem;
overflow-y: auto;
}
textarea {
@@ -379,7 +682,3 @@ textarea {
align-items: center;
}
</style>
+94
View File
@@ -0,0 +1,94 @@
<script setup lang="ts">
import type { Report } from '~/types/api'
type ActionVariant = 'open' | 'manage'
interface Props {
reports: Report[]
detailBasePath?: string
actionVariant?: ActionVariant
actionLabel?: string
showAssignee?: boolean
processingIds?: number[]
}
const props = withDefaults(defineProps<Props>(), {
detailBasePath: '/reports',
actionVariant: 'open',
actionLabel: 'Open report',
showAssignee: false,
processingIds: () => [],
})
const emit = defineEmits<{
(e: 'take', id: number): void
}>()
const formatDate = (dateString?: string): string => {
if (!dateString) return '-'
return new Date(dateString).toLocaleDateString('it-IT', {
day: '2-digit',
month: '2-digit',
year: '2-digit',
})
}
const reportHref = (report: Report) => `${props.detailBasePath}/${report.id}`
</script>
<template>
<div class="table-responsive report-table-wrapper">
<table class="table table-hover report-table mb-0">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">Categoria</th>
<th scope="col">Indirizzo</th>
<th scope="col">Stato</th>
<th v-if="showAssignee" scope="col">Operatore</th>
<th scope="col">Creazione</th>
<th scope="col" class="text-end">Azioni</th>
</tr>
</thead>
<tbody>
<tr v-for="report in reports" :key="report.id" class="align-middle">
<td class="report-table-id">#{{ report.id }}</td>
<td class="text-nowrap">{{ report.category_name || '-' }}</td>
<td>
<span class="report-address d-inline-block text-truncate align-middle" style="max-width: 10ch;" :title="report.address">
{{ report.address || '-' }}
</span>
</td>
<td>
<StatusBadge :status="report.status" />
</td>
<td v-if="showAssignee" class="text-muted">
{{ report.assigned_operator_id ? `#${report.assigned_operator_id}` : '-' }}
</td>
<td class="text-muted text-nowrap">{{ formatDate(report.created_at) }}</td>
<td class="text-end">
<button
v-if="actionVariant === 'manage'"
type="button"
class="btn btn-primary btn-xs"
:disabled="processingIds.includes(report.id)"
@click="emit('take', report.id)"
>
<span v-if="processingIds.includes(report.id)" class="spinner-border spinner-border-sm me-1" role="status" aria-hidden="true"></span>
Prendi in carico
</button>
<NuxtLink
v-else
:to="reportHref(report)"
class="btn btn-outline-primary btn-xs"
:aria-label="actionLabel"
:title="actionLabel"
>
{{ actionLabel }}
</NuxtLink>
</td>
</tr>
</tbody>
</table>
</div>
</template>
+1 -1
View File
@@ -15,7 +15,7 @@ const badgeConfig = computed(() => {
IN_PROGRESS: { color: 'primary', text: 'In Lavorazione', icon: 'it-settings' },
RESOLVED: { color: 'success', text: 'Risolta', icon: 'it-check-circle' },
REJECTED: { color: 'danger', text: 'Rifiutata', icon: 'it-close-circle' },
CLOSED: { color: 'secondary', text: 'Chiusa', icon: 'it-locked' }
CLOSED: { color: 'secondary', text: 'Conclusa', icon: 'it-locked' }
}
return config[props.status] || { color: 'secondary', text: props.status, icon: 'it-info-circle' }
+32 -46
View File
@@ -1,63 +1,49 @@
<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())
const adminActions = [
{ to: '/admin/reports', icon: 'it-files', label: 'Report', tone: 'primary' },
{ to: '/admin/catalog', icon: 'it-list', label: 'Categorie e Team', tone: 'primary' },
{ to: '/admin/areas', icon: 'it-map-marker', label: 'Aree', tone: 'primary' },
{ to: '/admin/users', icon: 'it-user', label: 'Gestione Utenti', tone: 'primary' },
{ to: '/admin/moderation', icon: 'it-warning', label: 'Moderazione Abusi', tone: 'danger' }
]
</script>
<template>
<div>
<div class="callout callout-highlight callout-danger mb-4">
<div class="callout-title">Pannello di Amministrazione</div>
<p>Accesso di livello 1. Da qui puoi gestire le configurazioni di sistema, le categorie e moderare le segnalazioni.</p>
<div class="card card-bg">
<div class="card-body">
<div class="d-flex justify-content-between align-items-center mb-3">
<h2 class="h5 card-title mb-0">Gestione sistema</h2>
</div>
<!-- Statistiche Globali (Mock o Reali) -->
<div class="row mb-5" v-if="!pending && statsRes?.ok">
<div class="col-6 col-md-3 mb-3">
<div class="card-wrapper card-space">
<div class="card card-bg text-center">
<div class="card-body">
<h2 class="text-primary">{{ statsRes.total_users || 0 }}</h2>
<p class="card-text">Utenti Registrati</p>
</div>
</div>
</div>
</div>
<div class="col-6 col-md-3 mb-3">
<div class="card-wrapper card-space">
<div class="card card-bg text-center">
<div class="card-body">
<h2 class="text-warning">
{{ statsRes.open_reports ?? statsRes.reports_by_status?.find(s => s.status === 'OPEN')?.total ?? 0 }}
</h2>
<p class="card-text">Segn. Aperte</p>
</div>
</div>
</div>
</div>
</div>
<h3 class="mb-3">Gestione Sistema</h3>
<div class="row">
<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
<div class="row g-2">
<div
v-for="action in adminActions"
:key="action.to"
class="col-12 col-md-6 col-xl-4"
>
<NuxtLink
:to="action.to"
class="btn btn-sm w-100 d-flex align-items-center justify-content-start gap-2 admin-action"
:class="action.tone === 'danger' ? 'btn-outline-danger' : 'btn-outline-primary'"
>
<BIIcon :name="action.icon" size="sm" :color="action.tone === 'danger' ? 'danger' : 'primary'" />
<span>{{ action.label }}</span>
</NuxtLink>
</div>
<div class="col-12 col-md-4 mb-3">
<NuxtLink to="/admin/users" class="btn btn-outline-primary w-100 py-3 d-flex flex-column align-items-center">
<BIIcon name="it-user" size="sm" color="primary" class="mb-2" />
Gestione Utenti
</NuxtLink>
</div>
<div class="col-12 col-md-4 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
</NuxtLink>
</div>
</div>
</div>
</template>
<style scoped>
.admin-action {
min-height: 44px;
text-align: left;
}
</style>
+53 -196
View File
@@ -4,233 +4,90 @@ import type { Report } from '~/types/api'
const { user } = useAuth()
const { getReports } = useReports()
const page = ref(1)
const perPage = ref(10)
const filterStatus = ref<string>('') // Stringa vuota = "Tutte"
const { data: reportsRes, pending } = useAsyncData('citizen-dashboard-reports', () => getReports({}))
// Carichiamo TUTTE le segnalazioni per avere statistiche globali e filtri veloci
const { data: reportsRes, pending } = useAsyncData('citizen-reports-all', () =>
getReports({}) // Non passiamo filtri alla chiamata API
const reports = computed<Report[]>(() => reportsRes.value?.reports || [])
const recentReports = computed(() => reports.value.slice(0, 4))
const stats = computed(() => {
return reports.value.reduce(
(acc, report) => {
acc.total++
if (report.status === 'OPEN') acc.open++
if (report.status === 'IN_PROGRESS' || report.status === 'ASSIGNED') acc.inProgress++
if (report.status === 'RESOLVED' || report.status === 'CLOSED') acc.resolved++
return acc
},
{ total: 0, open: 0, inProgress: 0, resolved: 0 }
)
// Dati grezzi dal server
const rawReports = computed<Report[]>(() => reportsRes.value?.reports || [])
// 1. STATISTICHE GLOBALI (Sempre basate su tutti i dati, ignorano i filtri)
const statsGlobal = computed(() => {
const stats = { total: 0, OPEN: 0, IN_PROGRESS: 0, RESOLVED: 0 }
rawReports.value.forEach((report: Report) => {
stats.total++
if (report.status === 'OPEN') stats.OPEN++
if (report.status === 'IN_PROGRESS' || report.status === 'ASSIGNED') stats.IN_PROGRESS++
if (report.status === 'RESOLVED') stats.RESOLVED++
})
return stats
})
// 2. FILTRO LATO CLIENT (Rende il cambio filtro istantaneo)
const filteredReports = computed(() => {
if (!filterStatus.value) return rawReports.value
return rawReports.value.filter((report: Report) => {
// Raggruppiamo IN_PROGRESS e ASSIGNED sotto la stessa voce per l'utente
if (filterStatus.value === 'IN_PROGRESS') {
return report.status === 'IN_PROGRESS' || report.status === 'ASSIGNED'
}
return report.status === filterStatus.value
})
})
// 3. PAGINAZIONE LATO CLIENT
const paginatedReports = computed(() => {
const start = (page.value - 1) * perPage.value
const end = start + perPage.value
return filteredReports.value.slice(start, end)
})
const totalFiltered = computed(() => filteredReports.value.length)
// GESTIONE FILTRI (Evita reload se clicchi il filtro attivo)
const handleStatusFilter = (status: string) => {
const targetStatus = status === 'all' ? '' : status
// Se clicco sullo stesso filtro, non fare nulla
if (filterStatus.value === targetStatus) return
filterStatus.value = targetStatus
page.value = 1 // Reset alla prima pagina
}
const handlePageChange = (newPage: number) => {
page.value = newPage
}
// Helpers grafici
const formatDate = (dateString?: string): string => {
if (!dateString) return ''
return new Date(dateString).toLocaleDateString('it-IT', {
day: '2-digit', month: '2-digit', year: '2-digit',
})
}
</script>
<template>
<div>
<!-- Callout Gamification -->
<div class="callout callout-highlight callout-success mb-4">
<div class="callout-title d-flex align-items-center">
<BIIcon name="it-star-full" size="sm" color="success" class="me-2" />
I tuoi Punti Cittadino
</div>
<p>
Hai accumulato <strong>{{ user?.points || 0 }} punti</strong>! Continua ad aiutare la comunità segnalando i problemi urbani.
</p>
</div>
<!-- STATISTICHE RAPIDE (Basate su statsGlobal, non cambiano filtrando) -->
<div class="row mb-5">
<div class="col-6 col-md-3 mb-3">
<div class="card card-bg text-center">
<div class="card-body">
<div class="display-6 text-primary font-weight-bold">{{ statsGlobal.total }}</div>
<small class="text-muted">Totali</small>
<div class="row g-3 mb-4">
<div class="col-6 col-lg-3">
<div class="card card-bg dashboard-stat h-100">
<div class="card-body py-3">
<div class="stat-value">{{ stats.total }}</div>
<div class="small text-muted">Segnalazioni</div>
</div>
</div>
</div>
<div class="col-6 col-md-3 mb-3">
<div class="card card-bg text-center">
<div class="card-body">
<div class="display-6 text-warning font-weight-bold">{{ statsGlobal.OPEN }}</div>
<small class="text-muted">Aperte</small>
<div class="col-6 col-lg-3">
<div class="card card-bg dashboard-stat h-100">
<div class="card-body py-3">
<div class="stat-value">{{ stats.open }}</div>
<div class="small text-muted">Aperte</div>
</div>
</div>
</div>
<div class="col-6 col-md-3 mb-3">
<div class="card card-bg text-center">
<div class="card-body">
<div class="display-6 text-info font-weight-bold">{{ statsGlobal.IN_PROGRESS }}</div>
<small class="text-muted">In corso</small>
<div class="col-6 col-lg-3">
<div class="card card-bg dashboard-stat h-100">
<div class="card-body py-3">
<div class="stat-value">{{ stats.inProgress }}</div>
<div class="small text-muted">In corso</div>
</div>
</div>
</div>
<div class="col-6 col-md-3 mb-3">
<div class="card card-bg text-center">
<div class="card-body">
<div class="display-6 text-success font-weight-bold">{{ statsGlobal.RESOLVED }}</div>
<small class="text-muted">Risolte</small>
<div class="col-6 col-lg-3">
<div class="card card-bg dashboard-stat h-100">
<div class="card-body py-3">
<div class="stat-value">{{ user?.points || 0 }}</div>
<div class="small text-muted">Punti cittadino</div>
</div>
</div>
</div>
</div>
<!-- AZIONI RAPIDE E FILTRI -->
<div class="row mb-4">
<div class="col-12">
<div class="d-flex gap-2 flex-wrap align-items-center">
<NuxtLink to="/reports/create" class="btn btn-primary me-md-3">
<div class="d-flex flex-wrap gap-2 mb-4">
<NuxtLink to="/reports/new" class="btn btn-primary">
<BIIcon name="it-plus-circle" size="sm" color="white" class="me-2" />
Nuova segnalazione
</NuxtLink>
<div class="btn-group" role="group" aria-label="Filtri segnalazioni">
<button
type="button"
class="btn btn-sm"
:class="filterStatus === '' ? 'btn-primary' : 'btn-outline-primary'"
@click="handleStatusFilter('all')"
>
Tutte
</button>
<button
type="button"
class="btn btn-sm"
:class="filterStatus === 'OPEN' ? 'btn-primary' : 'btn-outline-primary'"
@click="handleStatusFilter('OPEN')"
>
Aperte
</button>
<button
type="button"
class="btn btn-sm"
:class="filterStatus === 'IN_PROGRESS' ? 'btn-primary' : 'btn-outline-primary'"
@click="handleStatusFilter('IN_PROGRESS')"
>
In corso
</button>
<button
type="button"
class="btn btn-sm"
:class="filterStatus === 'RESOLVED' ? 'btn-primary' : 'btn-outline-primary'"
@click="handleStatusFilter('RESOLVED')"
>
Risolte
</button>
</div>
</div>
</div>
<NuxtLink to="/reports" class="btn btn-outline-primary">
<BIIcon name="it-list" size="sm" class="me-2" />
Le mie segnalazioni
</NuxtLink>
</div>
<div v-if="pending" class="progress-spinner progress-spinner-active my-5 mx-auto">
<div class="card card-bg">
<div class="card-body">
<div class="d-flex justify-content-between align-items-center mb-3">
<h2 class="h5 card-title mb-0">Aggiornamenti recenti</h2>
<NuxtLink to="/reports" class="btn btn-link btn-sm pe-0">Vedi tutte</NuxtLink>
</div>
<div v-if="pending" class="text-center py-4">
<div class="spinner-border text-primary" role="status">
<span class="visually-hidden">Caricamento...</span>
</div>
<!-- TABELLA SEGNALAZIONI -->
<div class="row" v-else>
<div class="col-12">
<div v-if="filteredReports.length === 0" class="alert alert-info text-center" role="alert">
<h6>Nessuna segnalazione trovata</h6>
<p class="small text-muted mb-0">Non ci sono segnalazioni con lo stato "{{ filterStatus || 'Tutte' }}".</p>
</div>
<div v-else class="table-responsive">
<table class="table table-hover border-bottom">
<thead class="table-light">
<tr>
<th scope="col" class="small">#ID</th>
<th scope="col" class="small">Categoria</th>
<th scope="col" class="small">Indirizzo</th>
<th scope="col" class="small">Stato</th>
<th scope="col" class="small">Creazione</th>
<th scope="col" class="text-center small">Azioni</th>
</tr>
</thead>
<tbody>
<tr v-for="report in paginatedReports" :key="report.id" class="align-middle">
<td class="small font-weight-semibold">#{{ report.id }}</td>
<td class="small">{{ report.category_name }}</td>
<td class="small">
<span class="text-muted text-truncate" style="max-width: 200px; display: inline-block;">
{{ report.address }}
</span>
</td>
<td class="small">
<StatusBadge :status="report.status" />
</td>
<td class="small text-muted">{{ formatDate(report.created_at) }}</td>
<td class="text-center">
<NuxtLink :to="`/reports/${report.id}`" class="btn btn-sm btn-outline-primary p-1">
<BIIcon name="it-arrow-right" size="xs" />
</NuxtLink>
</td>
</tr>
</tbody>
</table>
<div v-else-if="recentReports.length === 0" class="alert alert-info mb-0" role="alert">
Non hai ancora creato segnalazioni.
</div>
<Pagination
v-if="totalFiltered > perPage"
:current-page="page"
:per-page="perPage"
:total-items="totalFiltered"
@page-change="handlePageChange"
/>
<ReportTable v-else :reports="recentReports" action-label="Apri segnalazione" />
</div>
</div>
</div>
</template>
<style scoped>
.display-6 { font-size: 2.2rem; line-height: 1; }
.table-hover tbody tr:hover { background-color: rgba(0, 111, 157, 0.03); }
.btn-group .btn { min-width: 80px; }
</style>
+29 -39
View File
@@ -1,59 +1,49 @@
<script setup lang="ts">
const { getOpenReports, getAssignedReports, takeReport } = useOperator()
const { getOpenReports, getAssignedReports } = useOperator()
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 handleTakeReport = async (id: number) => {
const res = await takeReport(id)
if (res.ok) {
await Promise.all([refreshOpen(), refreshAssigned()])
}
}
const { data: openReportsRes } = useAsyncData('open-reports', () => getOpenReports({ per_page: 5 }))
const { data: assignedReportsRes } = useAsyncData('assigned-reports', () => getAssignedReports({ per_page: 5 }))
</script>
<template>
<div class="row">
<!-- Colonna Sinistra: Segnalazioni da prendere in carico -->
<div class="col-12 col-lg-6 mb-4">
<h3 class="mb-3 border-bottom pb-2">Da prendere in carico (OPEN)</h3>
<div class="list-group">
<div v-if="openReportsRes?.ok && openReportsRes.reports.length === 0" class="text-muted">
<div class="card card-bg h-100">
<div class="card-body">
<div class="d-flex justify-content-between align-items-center mb-3">
<h3 class="h5 mb-0">Segnalazioni disponibili</h3>
<NuxtLink to="/operator" class="btn btn-link btn-sm pe-0">Apri elenco</NuxtLink>
</div>
<div v-if="openReportsRes?.ok && openReportsRes.reports.length === 0" class="alert alert-info mb-0">
Nessuna nuova segnalazione in ingresso.
</div>
<div
v-for="report in openReportsRes?.reports" :key="report.id"
class="list-group-item d-flex justify-content-between align-items-center"
>
<div>
<h6 class="mb-1">{{ report.address }}</h6>
<small class="text-muted">{{ report.created_at }}</small>
</div>
<button @click="handleTakeReport(report.id)" class="btn btn-outline-primary btn-sm">
Prendi in carico
</button>
<ReportTable
v-else
:reports="openReportsRes?.reports || []"
detail-base-path="/operator/reports"
action-label="Visualizza"
/>
</div>
</div>
</div>
<!-- Colonna Destra: Segnalazioni in gestione dell'operatore -->
<div class="col-12 col-lg-6 mb-4">
<h3 class="mb-3 border-bottom pb-2">Le mie assegnazioni</h3>
<div class="list-group">
<div v-if="assignedReportsRes?.ok && assignedReportsRes.reports.length === 0" class="text-muted">
<div class="card card-bg h-100">
<div class="card-body">
<div class="d-flex justify-content-between align-items-center mb-3">
<h3 class="h5 mb-0">Le mie assegnazioni</h3>
<NuxtLink to="/operator/assigned" class="btn btn-link btn-sm pe-0">Vedi tutte</NuxtLink>
</div>
<div v-if="assignedReportsRes?.ok && assignedReportsRes.reports.length === 0" class="alert alert-info mb-0">
Non hai segnalazioni in carico.
</div>
<NuxtLink
v-for="report in assignedReportsRes?.reports" :key="report.id"
:to="`/operator/reports/${report.id}`"
class="list-group-item list-group-item-action d-flex justify-content-between align-items-center"
>
<div>
<h6 class="mb-1">{{ report.address }}</h6>
<StatusBadge :status="report.status" />
<ReportTable
v-else
:reports="assignedReportsRes?.reports || []"
detail-base-path="/operator/reports"
action-label="Apri segnalazione"
/>
</div>
<BIIcon name="it-chevron-right" size="sm" color="primary" />
</NuxtLink>
</div>
</div>
</div>
+36 -7
View File
@@ -1,9 +1,18 @@
import type {
AreaListResponse, CategoryListResponse, CreateAreaRequest, CreateCategoryRequest, CreateTeamRequest,
AreaListResponse,
CategoryListResponse,
CreateAreaRequest,
CreateCategoryRequest,
CreateTeamRequest,
ModerationListResponse,
OkResponse,
OverviewStatsResponse, TeamListResponse, UpdateModerationRequest,
UpdateUserBanRequest, UpdateUserRolesRequest,
OverviewStatsResponse,
UpdateAreaRequest,
UpdateCategoryRequest,
UpdateModerationRequest,
UpdateTeamRequest,
UpdateUserBanRequest,
UpdateUserRolesRequest,
UserListResponse
} from "~/types/api";
@@ -21,23 +30,38 @@ 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 })
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 = () =>
useApiFetch<CategoryListResponse>('/api/v1/admin/categories', { method: 'GET' })
const createCategory = (body: CreateCategoryRequest) =>
useApiFetch<OkResponse>('/api/v1/admin/categories', { method: 'POST', body })
const getTeams = () =>
useApiFetch<TeamListResponse>('/api/v1/admin/teams', { method: 'GET' })
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 createTeam = (body: CreateTeamRequest) =>
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 }) =>
useApiFetch<ModerationListResponse>('/api/v1/admin/moderation', { method: 'GET', query })
@@ -51,10 +75,15 @@ export const useAdmin = () => {
updateUserRoles,
getAreas,
createArea,
updateArea,
deleteArea,
getCategories,
createCategory,
getTeams,
updateCategory,
deleteCategory,
createTeam,
updateTeam,
deleteTeam,
getModerationFlags,
updateModerationFlag,
}
+1 -16
View File
@@ -27,22 +27,7 @@ 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
+67 -20
View File
@@ -1,14 +1,20 @@
import type {
ChangePasswordRequest,
CurrentUserResponse, EmailRequest, NotificationListResponse,
CieSessionResponse,
CieStartResponse,
CurrentUserResponse,
EmailRequest,
NotificationListResponse,
OkResponse,
OtpRequestResponse, PasswordLoginRequest, RegisterCitizenRequest,
RegisterCitizenResponse, RewardsResponse,
TokenResponse, VerifyOtpRequest
OtpRequestResponse,
RegisterCitizenRequest,
RegisterCitizenResponse,
RewardsResponse,
TokenResponse,
UpdateProfileRequest,
VerifyOtpRequest
} from "~/types/api";
export const useAuth = () => {
const route = useRoute()
const nuxtApp = useNuxtApp()
const token = useCookie<string | null>('auth_token', {
@@ -23,13 +29,39 @@ export const useAuth = () => {
type UserContext = CurrentUserResponse['user']
const user = useState<UserContext | null>('auth_user', () => null)
const isSyncingUser = useState<boolean>('auth_syncing', () => false)
const unreadNotifications = useState<number>('auth_unread_notifications', () => 0)
const isRefreshingNotifications = useState<boolean>('auth_refreshing_notifications', () => false)
const isAuthenticated = computed(() => !!(tokenState.value || token.value))
const hasUnreadNotifications = computed(() => unreadNotifications.value > 0)
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 refreshUnreadNotifications = async () => {
if (!(tokenState.value || token.value) || !user.value || isRefreshingNotifications.value) {
unreadNotifications.value = user.value ? unreadNotifications.value : 0
return
}
isRefreshingNotifications.value = true
try {
const res = await fetchNotifications({ page: 1, per_page: 20 })
unreadNotifications.value = (res.notifications || []).filter(notification => !notification.read_at).length
} catch (error) {
console.error('[Auth] Failed to refresh notifications:', error)
} finally {
isRefreshingNotifications.value = 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
@@ -37,17 +69,20 @@ export const useAuth = () => {
try {
const res = await fetchCurrentUser()
if (res.ok) {
console.log('[Auth] User synced successfully')
user.value = res.user
await nuxtApp.runWithContext(() => refreshUnreadNotifications())
const path = currentPath ?? nuxtApp.$router.currentRoute.value.path
if (res.user.must_change_password && route.path !== '/auth/change-password') {
console.log('[Auth] User must change password, redirecting...')
await nuxtApp.runWithContext(() => navigateTo('/auth/change-password'))
} else if (redirectOnSuccess && route.path.startsWith('/auth')) {
await nuxtApp.runWithContext(() => navigateTo('/me'))
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 {
@@ -58,13 +93,15 @@ export const useAuth = () => {
const handleLoginSuccess = async (jwtToken: string) => {
token.value = jwtToken
tokenState.value = jwtToken
await syncUser(true)
await syncUser()
window.location.reload();
}
const logout = () => {
token.value = null
tokenState.value = null
user.value = null
unreadNotifications.value = 0
nuxtApp.runWithContext(() => navigateTo('/auth/login'))
}
@@ -77,11 +114,17 @@ export const useAuth = () => {
const verifyOtp = (body: VerifyOtpRequest) =>
useApiFetch<TokenResponse>('/api/v1/auth/otp/verify', { method: 'POST', body })
const loginWithPassword = (body: PasswordLoginRequest) =>
useApiFetch<TokenResponse>('/api/v1/auth/login/password', { method: 'POST', body })
const startCieLogin = (frontendRedirectUri: string) =>
useApiFetch<CieStartResponse>('/api/v1/auth/cie/start', {
method: 'POST',
body: { frontend_redirect_uri: frontendRedirectUri }
})
const changePassword = (body: ChangePasswordRequest) =>
useApiFetch<OkResponse>('/api/v1/auth/change-password', { method: 'POST', body })
const fetchCieSession = (id: string) =>
useApiFetch<CieSessionResponse>(`/api/v1/auth/cie/session/${id}`, { method: 'GET' })
const updateProfile = (body: UpdateProfileRequest) =>
useApiFetch<CurrentUserResponse>('/api/v1/me', { method: 'PATCH', body })
const fetchCurrentUser = () =>
useApiFetch<CurrentUserResponse>('/api/v1/me', { method: 'GET' })
@@ -101,6 +144,9 @@ export const useAuth = () => {
tokenState,
isSyncingUser,
isAuthenticated,
unreadNotifications,
hasUnreadNotifications,
refreshUnreadNotifications,
handleLoginSuccess,
syncUser,
logout,
@@ -108,8 +154,9 @@ export const useAuth = () => {
register,
requestOtp,
verifyOtp,
loginWithPassword,
changePassword,
startCieLogin,
fetchCieSession,
updateProfile,
fetchCurrentUser,
fetchRewards,
fetchNotifications,
+3 -3
View File
@@ -7,9 +7,9 @@ export interface Member {
export function useMembers() {
const members: Member[] = [
{ name: "Renato Loiacono", image: "https://placehold.co/50x50" },
{ name: "Michelangelo Parisi", image: "https://placehold.co/50x50" },
{ name: "Gabriele Schiraldi", image: "https://placehold.co/50x50" },
{ name: "Renato Loiacono", image: "/renatoloiacono.webp" },
{ name: "Michelangelo Parisi", image: "/michelangeloparisi.webp" },
{ name: "Paolo Gabriele Schiraldi", image: "/paologabrieleschiraldi.webp" },
];
const sortedMembers = computed(() => {
+18
View File
@@ -1,8 +1,10 @@
import type {
AssignmentLinkResponse,
AssignTeamRequest,
InterventionSummaryResponse,
OkResponse,
PagedReportListResponse,
TeamListResponse,
UpdateStatusRequest
} from "~/types/api";
@@ -16,6 +18,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' })
@@ -28,13 +33,26 @@ export const useOperator = () => {
const getInterventionSummary = (id: number) =>
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' })
const getPublicIntervention = (token: string) =>
useApiFetch<any>(`/api/v1/interventions/${token}`, { method: 'GET' })
return {
getOpenReports,
getAssignedReports,
getOtherOperatorReports,
getTeams,
takeReport,
updateReportStatus,
assignTeam,
getInterventionSummary,
createInterventionLink,
revokeInterventionLink,
getPublicIntervention,
}
}
+19 -4
View File
@@ -1,16 +1,26 @@
import type {
CategoryListResponse,
CreateReportRequest,
CreateReportResponse, FeedbackRequest, FlagRequest, FlagResponse,
CreateReportResponse,
FeedbackRequest,
FlagRequest,
FlagResponse,
MediaUploadResponse,
MessageListResponse, MessageRequest, OkResponse,
MessageListResponse,
MessageRequest,
OkResponse,
ReportDetailResponse,
ReportListResponse
ReportListResponse,
TeamListResponse
} from "~/types/api";
export const useReports = () => {
const getReports = (query?: { area_id?: number; category_id?: number; status?: string }) =>
const getReports = (query?: { area_id?: number; category_id?: number; status?: string; page?: number; per_page?: number }) =>
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 })
@@ -35,8 +45,12 @@ export const useReports = () => {
const flagMessage = (reportId: number, messageId: number, body: FlagRequest) =>
useApiFetch<FlagResponse>(`/api/v1/reports/${reportId}/messages/${messageId}/flags`, { method: 'POST', body })
const getTeamSuggestions = (id: number) =>
useApiFetch<TeamListResponse>(`/api/v1/reports/${id}/team-suggestions`, { method: 'GET' })
return {
getReports,
getCategories,
createReport,
getReportDetail,
uploadMedia,
@@ -45,5 +59,6 @@ export const useReports = () => {
addFeedback,
flagReport,
flagMessage,
getTeamSuggestions,
}
}
+14
View File
@@ -11,6 +11,7 @@ import Footer from "~/components/Footer.vue";
<slot />
</main>
<div class="italian-flag"></div>
<Footer />
</div>
</template>
@@ -22,6 +23,19 @@ import Footer from "~/components/Footer.vue";
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 {
flex-grow: 1;
}
+6 -16
View File
@@ -1,38 +1,28 @@
import { checkRoleAccess, type MetaRoleRequirement } from '~/utils/roles'
export default defineNuxtRouteMiddleware(async (to) => {
const auth = useAuth()
// 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')
}
}
// Se non autenticato, redirige al login
if (!auth.isAuthenticated.value) {
return navigateTo('/auth/login')
}
// Verifica ruoli se richiesto
const requiredRole = to.meta.auth?.role
const requiredRole = to.meta.auth?.role as MetaRoleRequirement | undefined
if (requiredRole && auth.user.value) {
const userRole = auth.user.value.role
const roleLevels: Record<string, number> = {
'CITIZEN': 1,
'OPERATOR': 2,
'ADMIN': 3
}
const userLevel = roleLevels[userRole] || 0
const requiredLevel = roleLevels[requiredRole] || 0
if (userLevel < requiredLevel) {
console.warn(`[Auth] User role ${userRole} (level ${userLevel}) insufficient for required ${requiredRole} (level ${requiredLevel})`)
if (!checkRoleAccess(userRole, requiredRole)) {
console.warn(`[Auth] User role '${userRole}' rejected for route requirement:`, requiredRole)
return navigateTo('/')
}
}
+3 -3
View File
@@ -1,15 +1,15 @@
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)
}
}
if (auth.isAuthenticated.value && auth.user.value) {
return navigateTo('/me')
return navigateTo('/dashboard')
}
})
+547
View File
@@ -0,0 +1,547 @@
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, reactive, ref, watch } from 'vue'
import { BARI_BOUNDS, BARI_CENTER, isWithinBariBounds } from '~/utils/bari'
definePageMeta({
middleware: 'auth',
auth: { role: 'ADMIN' }
})
useHead({ title: 'Aree - Admin' })
const { getAreas, createArea, updateArea, deleteArea } = useAdmin()
const { data: areasRes, pending, refresh } = useAsyncData('admin-areas', () => getAreas())
const isCreating = ref(false)
const editingAreaId = ref<number | null>(null)
const formData = reactive({
name: '',
description: '',
geojson: ''
})
const jsonError = ref('')
const actionError = ref('')
const modalError = ref('')
const deletingAreaId = ref<number | null>(null)
const areaPendingDelete = ref<any | null>(null)
let map: any = null
let mainMap: any = null
let polygon: any = null
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 initMainMap = async () => {
const mapElement = document.getElementById('mainMap')
if (!mapElement) return
const L = (await import('leaflet')).default
if (mainMap) {
mainMap.remove()
mainMap = null
}
const bariBounds = L.latLngBounds(
[BARI_BOUNDS.south, BARI_BOUNDS.west],
[BARI_BOUNDS.north, BARI_BOUNDS.east]
)
mainMap = L.map('mainMap', {
maxBounds: bariBounds,
maxBoundsViscosity: 1,
minZoom: 11
}).setView(BARI_CENTER, 12)
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
attribution: '© OpenStreetMap'
}).addTo(mainMap)
const featureGroup = L.featureGroup().addTo(mainMap)
let hasLayers = false
areas.value.forEach((area: any) => {
if (area.boundary_geojson) {
try {
const layer = L.geoJSON(JSON.parse(area.boundary_geojson), {
style: {
color: '#0d6efd',
weight: 2,
fillOpacity: 0.2
}
}).bindPopup(`<strong>${area.name}</strong><br/>${area.description || ''}`)
layer.addTo(featureGroup)
hasLayers = true
} catch (e) {
console.error('Invalid geojson for area', area.id, e)
}
}
})
if (hasLayers) {
mainMap.fitBounds(featureGroup.getBounds())
} else {
mainMap.fitBounds(bariBounds)
}
}
watch([areas, pending], () => {
if (!pending.value) {
if (areas.value.length > 0) {
nextTick(() => {
initMainMap()
})
} else if (mainMap) {
mainMap.remove()
mainMap = null
}
}
}, { immediate: true })
const renderExistingAreasInModal = (L: any, currentMap: any) => {
areas.value.forEach((area: any) => {
if (area.id === editingAreaId.value) return
if (area.boundary_geojson) {
try {
L.geoJSON(JSON.parse(area.boundary_geojson), {
style: {
color: '#6c757d',
weight: 2,
dashArray: '5, 5',
fillOpacity: 0.1
},
interactive: false
}).addTo(currentMap)
} catch (e) {
}
}
})
}
const openCreateModal = () => {
actionError.value = ''
modalError.value = ''
editingAreaId.value = null
formData.name = ''
formData.description = ''
formData.geojson = ''
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)
renderExistingAreasInModal(L, map)
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 = ''
modalError.value = ''
mapPoints.value.push([e.latlng.lat, e.latlng.lng])
polygon.setLatLngs(mapPoints.value)
updateGeojson()
})
})
}
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 = ''
modalError.value = ''
editingAreaId.value = area.id
formData.name = area.name || ''
formData.description = area.description || ''
formData.geojson = area.boundary_geojson || ''
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)
console.log(JSON.parse(area.boundary_geojson))
L.geoJSON(JSON.parse(area.boundary_geojson), {
style: {
color: '#0d6efd',
weight: 2,
fillOpacity: 0.2
}
}).addTo(map)
polygon = L.polygon([], { color: 'red' }).addTo(map)
map.fitBounds(bariBounds)
renderExistingAreasInModal(L, map)
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 = ''
modalError.value = ''
mapPoints.value.push([e.latlng.lat, e.latlng.lng])
polygon.setLatLngs(mapPoints.value)
updateGeojson()
})
})
}
const clearMap = () => {
mapPoints.value = []
if (polygon) {
polygon.setLatLngs([])
}
formData.geojson = ''
modalError.value = ''
}
const updateGeojson = () => {
if (mapPoints.value.length < 3) {
formData.geojson = ''
return
}
const coords = mapPoints.value.map(p => [p[1], p[0]] as [number, number])
if (coords[0]) {
coords.push([...coords[0]])
}
formData.geojson = JSON.stringify({
type: "Polygon",
coordinates: [coords]
}, null, 2)
}
const closeCreateModal = () => {
isCreating.value = false
editingAreaId.value = null
if (map) {
map.remove()
map = null
}
}
onBeforeUnmount(() => {
if (map) map.remove()
if (mainMap) mainMap.remove()
})
const handleCreate = async () => {
jsonError.value = ''
modalError.value = ''
let parsedGeojson = null
try {
parsedGeojson = JSON.parse(formData.geojson)
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
}
try {
const payload = {
name: formData.name,
description: formData.description || undefined,
boundary_geojson: parsedGeojson
}
const res = editingAreaId.value
? await updateArea(editingAreaId.value, payload)
: await createArea(payload)
if (res.ok) {
await refresh()
closeCreateModal()
actionError.value = ''
}
} catch (err: any) {
console.error('Failed to save area', err)
const backendError = err?.data?.error || err?.response?.data?.error || err?.response?._data?.error;
if (backendError === 'area_outside_allowed_boundary') {
modalError.value = "Attenzione: l'area disegnata esce dai confini consentiti per il Comune di Bari.";
} else {
modalError.value = err?.data?.message || err?.message || "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>
<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</h1>
<div>
<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 class="me-1" name="it-plus" size="xs"/>
Nuova Area
</button>
</div>
</div>
<div v-if="pending" class="text-center py-5">
<div class="spinner-border text-primary" role="status"></div>
</div>
<div v-else-if="areas.length === 0" class="alert alert-info">
Nessuna area configurata.
</div>
<template v-else>
<div class="card mb-4 shadow-sm border-0">
<div id="mainMap" class="rounded" style="height: 400px; width: 100%; z-index: 1;"></div>
</div>
<div v-if="actionError" class="alert alert-danger">
{{ actionError }}
</div>
<div v-else class="table-responsive">
<table class="table table-hover align-middle bg-white shadow-sm rounded">
<thead class="table-light">
<tr>
<th>ID</th>
<th>Nome</th>
<th>Descrizione</th>
<th>GeoJSON</th>
<th class="text-end">Azioni</th>
</tr>
</thead>
<tbody>
<tr v-for="area in areas" :key="area.id">
<td>{{ area.id }}</td>
<td><strong>{{ area.name }}</strong></td>
<td>{{ area.description || '-' }}</td>
<td>
<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>
</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>
</tbody>
</table>
</div>
</template>
<div v-if="isCreating" class="modal-backdrop fade show d-block"
style="background: rgba(0,0,0,0.5); z-index: 1040;"></div>
<div v-if="isCreating" class="modal fade show d-block" tabindex="-1" style="z-index: 1050;">
<div class="modal-dialog modal-xl modal-dialog-centered modal-dialog-scrollable">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">{{ modalTitle }}</h5>
<button type="button" class="btn-close" @click="closeCreateModal"></button>
</div>
<div class="modal-body">
<div v-if="modalError" class="alert alert-danger mb-4 d-flex align-items-center" role="alert">
<strong>Errore:</strong>&nbsp;{{ modalError }}
</div>
<form @submit.prevent="handleCreate">
<div class="row">
<div class="col-md-5">
<div class="mb-3">
<label class="form-label">Nome Area</label>
<input v-model="formData.name" class="form-control" placeholder="Es. Centro Storico" required
type="text"/>
</div>
<div class="mb-3">
<label class="form-label">Descrizione (opzionale)</label>
<textarea class="form-control" v-model="formData.description" rows="3"></textarea>
</div>
<div class="mb-3">
<label class="form-label">GeoJSON Generato</label>
<textarea
class="form-control font-monospace text-sm"
rows="6"
v-model="formData.geojson"
required
readonly
placeholder='{ "type": "Polygon", "coordinates": [...] }'
></textarea>
<div v-if="jsonError" class="form-text text-danger mt-1">{{ jsonError }}</div>
</div>
</div>
<div class="col-md-7">
<div class="mb-2 d-flex justify-content-between align-items-center">
<label class="form-label mb-0">Disegna Poligono sulla Mappa</label>
<button type="button" class="btn btn-outline-danger btn-sm" @click="clearMap">
Pulisci Mappa
</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. 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>
</div>
</form>
</div>
<div class="modal-footer d-flex justify-content-end gap-2">
<button type="button" class="btn btn-outline-secondary" @click="closeCreateModal">Annulla</button>
<button :disabled="!formData.name || !formData.geojson" class="btn btn-primary" type="button"
@click="handleCreate">
{{ submitLabel }}
</button>
</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>
</template>
<style scoped>
#areaMap, #mainMap {
background: #e9ecef;
}
.modal-dialog {
margin-block: 0 !important;
}
</style>
+477
View File
@@ -0,0 +1,477 @@
<script setup lang="ts">
import type { Category, Team } from '~/types/api'
definePageMeta({
middleware: 'auth',
auth: { role: 'ADMIN' }
})
useHead({ title: 'Categorie e Team - Admin' })
const { createCategory, updateCategory, deleteCategory, createTeam, updateTeam, deleteTeam, getAreas } = useAdmin()
const { getCategories } = useReports()
const { getTeams } = useOperator()
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 editingCategoryId = ref<number | null>(null)
const teamForm = reactive({
name: '',
description: '',
team_category_id: null as number | null,
area_id: null as number | null,
})
const editingTeamId = ref<number | null>(null)
const isSavingCategory = ref(false)
const isSavingTeam = ref(false)
const categoryError = 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 teams = computed(() => teamsRes.value?.teams || [])
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 () => {
categoryError.value = ''
isSavingCategory.value = true
try {
const payload = {
name: categoryForm.name.trim(),
description: categoryForm.description.trim() || undefined,
}
if (editingCategoryId.value) {
await updateCategory(editingCategoryId.value, payload)
} else {
await createCategory(payload)
}
resetCategoryForm()
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 {
const payload = {
name: teamForm.name.trim(),
description: teamForm.description.trim() || undefined,
team_category_id: teamForm.team_category_id,
area_id: teamForm.area_id || undefined,
}
if (editingTeamId.value) {
await updateTeam(editingTeamId.value, payload)
} else {
await createTeam(payload)
}
resetTeamForm()
await refreshTeams()
} catch (error: any) {
teamError.value = error?.data?.message || 'Creazione team non riuscita.'
} finally {
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>
<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" class="form-control" required type="text"/>
</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>
{{ editingCategoryId ? 'Salva categoria' : 'Crea categoria' }}
</button>
<button
v-if="editingCategoryId"
class="btn btn-outline-secondary ms-2"
type="button"
@click="resetCategoryForm"
>
Annulla
</button>
</form>
<div class="table-responsive report-table-wrapper">
<table class="table table-hover report-table mb-0 align-middle">
<thead>
<tr>
<th>ID</th>
<th>Nome</th>
<th>Stato</th>
<th class="text-end">Azioni</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>
<td class="text-end">
<div class="d-flex justify-content-end gap-2">
<button class="btn btn-outline-primary btn-icon" title="Modifica" @click="editCategory(category)">
<Icon name="lucide:pencil" size="16"/>
</button>
<button
:class="category.active === false ? 'btn-outline-success' : 'btn-outline-secondary'"
:title="category.active === false ? 'Attiva' : 'Disattiva'"
class="btn btn-icon"
@click="toggleCategoryActive(category)"
>
<Icon :name="category.active === false ? 'lucide:check-circle' : 'lucide:ban'" size="16"/>
</button>
<button
:disabled="deletingCategoryId === category.id"
class="btn btn-outline-danger btn-icon"
title="Elimina"
@click="askDeleteCategory(category)"
>
<span v-if="deletingCategoryId === category.id" class="spinner-border spinner-icon"></span>
<Icon v-else name="lucide:trash-2" size="16"/>
</button>
</div>
</td>
</tr>
<tr v-if="categories.length === 0">
<td class="text-muted text-center py-4" colspan="4">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" class="form-control" required type="text"/>
</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" class="form-control" type="text"/>
</div>
<div class="col-12">
<button :disabled="isSavingTeam || !teamForm.name.trim() || !teamForm.team_category_id" class="btn btn-primary"
type="submit">
<span v-if="isSavingTeam" class="spinner-border spinner-border-sm me-2"></span>
{{ editingTeamId ? 'Salva team' : 'Crea team' }}
</button>
<button
v-if="editingTeamId"
class="btn btn-outline-secondary ms-2"
type="button"
@click="resetTeamForm"
>
Annulla
</button>
</div>
</form>
<div class="table-responsive report-table-wrapper">
<table class="table table-hover report-table mb-0 align-middle">
<thead>
<tr>
<th>ID</th>
<th>Team</th>
<th>Categoria</th>
<th>Area</th>
<th>Stato</th>
<th class="text-end">Azioni</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>
<td class="text-end">
<div class="d-flex justify-content-end gap-2">
<button class="btn btn-outline-primary btn-icon" title="Modifica" @click="editTeam(team)">
<Icon name="lucide:pencil" size="16"/>
</button>
<button
:class="team.active === false ? 'btn-outline-success' : 'btn-outline-secondary'"
:title="team.active === false ? 'Attiva' : 'Disattiva'"
class="btn btn-icon"
@click="toggleTeamActive(team)"
>
<Icon :name="team.active === false ? 'lucide:check-circle' : 'lucide:ban'" size="16"/>
</button>
<button
:disabled="deletingTeamId === team.id"
class="btn btn-outline-danger btn-icon"
title="Elimina"
@click="askDeleteTeam(team)"
>
<span v-if="deletingTeamId === team.id" class="spinner-border spinner-icon"></span>
<Icon v-else name="lucide:trash-2" size="16"/>
</button>
</div>
</td>
</tr>
<tr v-if="teams.length === 0">
<td class="text-muted text-center py-4" colspan="6">Nessun team configurato.</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<ConfirmModal
:message="categoryDeleteMessage"
:open="categoryPendingDelete !== null"
:pending="deletingCategoryId !== null"
confirm-class="btn-danger"
confirm-label="Elimina categoria"
title="Elimina categoria"
@cancel="closeDeleteCategoryModal"
@confirm="handleDeleteCategory"
/>
<ConfirmModal
:message="teamDeleteMessage"
:open="teamPendingDelete !== null"
:pending="deletingTeamId !== null"
confirm-class="btn-danger"
confirm-label="Elimina team"
title="Elimina team"
@cancel="closeDeleteTeamModal"
@confirm="handleDeleteTeam"
/>
</div>
</template>
<style scoped>
.btn-icon {
width: 32px;
height: 32px;
padding: 0;
display: inline-flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
.spinner-icon {
width: 14px;
height: 14px;
border-width: 2px;
}
</style>
+298
View File
@@ -0,0 +1,298 @@
<script setup lang="ts">
import { reactive, ref } from 'vue'
definePageMeta({
middleware: 'auth',
auth: { role: 'ADMIN' }
})
useHead({ title: 'Moderazione Abusi - Admin' })
const { getModerationFlags, updateModerationFlag } = useAdmin()
const page = ref(1)
const perPage = ref(10)
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(
'admin-moderation-flags',
() => getModerationFlags({ page: page.value, per_page: perPage.value, status: statusFilter.value || undefined }),
{ watch: [page, statusFilter] }
)
const openResolveModal = (id: number, rejectReport: boolean) => {
resolveModal.open = true
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 {
await updateModerationFlag(resolveModal.flagId, {
status: 'RESOLVED',
reject_report: resolveModal.rejectReport,
resolution_note: resolveModal.note || undefined
})
resolveModal.pending = false
await refresh()
closeResolveModal()
} catch (err) {
console.error('Failed to resolve flag', err)
actionError.value = 'Errore durante la risoluzione della segnalazione.'
} finally {
resolveModal.pending = false
}
}
const openDismissModal = (id: number) => {
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 {
await updateModerationFlag(dismissModal.flagId, { status: 'DISMISSED' })
dismissModal.pending = false
await refresh()
closeDismissModal()
} catch (err) {
console.error('Failed to dismiss flag', err)
actionError.value = 'Errore durante l\'aggiornamento.'
} finally {
dismissModal.pending = false
}
}
const formatDate = (dateStr: string) => {
return new Date(dateStr).toLocaleString('it-IT', {
day: '2-digit', month: '2-digit', year: 'numeric',
hour: '2-digit', minute: '2-digit'
})
}
const formatFlagStatus = (status: string) => {
const map: Record<string, string> = {
OPEN: 'Aperto',
RESOLVED: 'Risolto',
DISMISSED: 'Ignorato'
}
return map[status] || status
}
const contentTypeLabel = (type: string) => type === 'REPORT' ? 'Segnalazione' : 'Messaggio'
const canRejectReport = (flag: any) => flag.content_type === 'REPORT'
</script>
<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">Moderazione Abusi</h1>
<NuxtLink to="/dashboard" class="btn btn-outline-secondary btn-sm">Torna al pannello admin</NuxtLink>
</div>
<div class="row mb-4">
<div class="col-md-4">
<label class="form-label">Filtra per Stato</label>
<select class="form-select" v-model="statusFilter">
<option value="">Tutti</option>
<option value="OPEN">Aperti</option>
<option value="RESOLVED">Risolti</option>
<option value="DISMISSED">Ignorati</option>
</select>
</div>
</div>
<div v-if="actionError" class="alert alert-danger mb-4">
{{ actionError }}
</div>
<div v-if="pending" class="text-center py-5">
<div class="spinner-border text-danger" role="status"></div>
</div>
<div v-else-if="!flagsRes || !flagsRes.flags || flagsRes.flags.length === 0" class="alert alert-success">
Nessun elemento da moderare al momento.
</div>
<div v-else>
<div
class="card mb-3 border-0"
:class="flag.status === 'DISMISSED' ? 'dismissed-card shadow-none' : 'shadow-sm'"
v-for="flag in flagsRes.flags"
:key="flag.id"
>
<div class="card-header d-flex justify-content-between align-items-center" :class="flag.status === 'DISMISSED' ? 'bg-transparent' : 'bg-light'">
<div>
<strong>Flag #{{ flag.id }}</strong> -
<span class="badge" :class="{
'bg-warning': flag.status === 'OPEN',
'bg-success': flag.status === 'RESOLVED',
'bg-secondary': flag.status === 'DISMISSED'
}">{{ formatFlagStatus(flag.status) }}</span>
</div>
<small class="text-muted">{{ formatDate(flag.created_at) }}</small>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-8">
<h5 class="card-title">Motivo: {{ flag.reason }}</h5>
<p class="card-text text-muted mb-2">
{{ flag.details || 'Nessun dettaglio aggiuntivo fornito.' }}
</p>
<div class="mt-info">
<span class="badge bg-info me-2">{{ contentTypeLabel(flag.content_type) }}</span>
<span v-if="flag.report_id">
Rif:
<NuxtLink :to="`/operator/reports/${flag.report_id}`" class="text-decoration-none">
Segnalazione #{{ flag.report_id }}
</NuxtLink>
</span>
<span v-if="flag.message_id" class="ms-2">
| Messaggio #{{ flag.message_id }}
</span>
</div>
<div class="mt-info small text-muted">
Segnalato da: {{ flag.created_by_email }} (ID: {{ flag.created_by_user_id }})
</div>
<div v-if="flag.status !== 'OPEN'" class="mt-2 small text-muted border-top pt-2">
<strong>Risolto/Ignorato da:</strong> {{ flag.resolved_by_email }} in data {{ flag.resolved_at ? formatDate(flag.resolved_at) : 'N/D' }}
<div v-if="flag.resolution_note"><strong>Nota:</strong> {{ flag.resolution_note }}</div>
</div>
</div>
<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">
<button class="btn btn-outline-danger btn-sm" @click="openResolveModal(flag.id, canRejectReport(flag))">
<BIIcon name="it-ban" size="xs" /> {{ canRejectReport(flag) ? 'Risolvi & Rigetta Segn.' : 'Risolvi flag' }}
</button>
<button class="btn btn-outline-warning btn-sm" @click="openResolveModal(flag.id, false)">
<BIIcon name="it-check" size="xs" /> {{ canRejectReport(flag) ? 'Risolvi (Solo Avviso)' : 'Risolvi senza rigetto' }}
</button>
<button class="btn btn-outline-secondary btn-sm" @click="openDismissModal(flag.id)">
<BIIcon name="it-close" size="xs" /> Ignora Flag
</button>
</div>
</div>
</div>
</div>
</div>
<Pagination
v-if="(flagsRes.total || flagsRes.flags.length) > perPage"
:current-page="page"
:per-page="perPage"
:total-items="flagsRes.total || (page * perPage + 1)"
@page-change="page = $event"
/>
</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>
</template>
<style scoped>
.dismissed-card {
background-color: #f8f9fa;
opacity: 0.7;
border: 1px solid #e9ecef !important;
}
.dismissed-card .card-header {
padding-top: 0.35rem;
padding-bottom: 0.35rem;
border-bottom: 1px solid rgba(0,0,0,0.05);
}
.dismissed-card .card-body {
padding-top: 0.6rem;
padding-bottom: 0.6rem;
}
.dismissed-card h5.card-title {
font-size: 1rem;
margin-bottom: 0.2rem;
}
.mt-info {
margin-top: 1rem;
}
.dismissed-card .mt-info {
margin-top: 0.4rem;
}
</style>
+258
View File
@@ -0,0 +1,258 @@
<script setup lang="ts">
import type { Report, ReportStatus } from '~/types/api'
definePageMeta({
middleware: 'auth',
auth: { role: 'ADMIN' }
})
useHead({ title: 'Overview Segnalazioni - Admin' })
const { getReports, getCategories } = useReports()
const { getAreas } = useAdmin()
const search = ref('')
const selectedStatus = ref<'ALL' | ReportStatus>('ALL')
const selectedCategoryId = ref<number | 'ALL'>('ALL')
const selectedAreaId = ref<number | 'ALL'>('ALL')
const { data: reportsRes, pending } = await useAsyncData('admin-report-overview', () => getReports())
const { data: categoriesRes } = await useAsyncData('admin-report-overview-categories', () => getCategories())
const { data: areasRes } = await useAsyncData('admin-report-overview-areas', () => getAreas())
const reports = computed<Report[]>(() => reportsRes.value?.reports || [])
const categories = computed(() => categoriesRes.value?.categories || [])
const areas = computed(() => areasRes.value?.areas || [])
const statusMeta: Record<ReportStatus, { label: string; tone: string }> = {
OPEN: { label: 'Aperta', tone: 'danger' },
UNDER_REVIEW: { label: 'In revisione', tone: 'warning' },
ASSIGNED: { label: 'Assegnata', tone: 'info' },
IN_PROGRESS: { label: 'In corso', tone: 'primary' },
RESOLVED: { label: 'Risolta', tone: 'success' },
REJECTED: { label: 'Rigettata', tone: 'secondary' },
CLOSED: { label: 'Chiusa', tone: 'dark' }
}
const filteredReports = computed(() => {
const term = search.value.trim().toLowerCase()
return reports.value.filter((report) => {
const matchesStatus = selectedStatus.value === 'ALL' || report.status === selectedStatus.value
const matchesCategory = selectedCategoryId.value === 'ALL' || report.category_id === selectedCategoryId.value
const matchesArea = selectedAreaId.value === 'ALL' || (report.area_id ?? null) === selectedAreaId.value
const matchesSearch = !term || [
report.id,
report.address,
report.description,
report.category_name,
report.area_name,
report.assigned_operator_id ? `#${report.assigned_operator_id}` : ''
].some((value) => String(value || '').toLowerCase().includes(term))
return matchesStatus && matchesCategory && matchesArea && matchesSearch
})
})
const totalReports = computed(() => reports.value.length)
const openReports = computed(() => reports.value.filter((report) => report.status === 'OPEN').length)
const activeReports = computed(() => reports.value.filter((report) => ['UNDER_REVIEW', 'ASSIGNED', 'IN_PROGRESS'].includes(report.status)).length)
const closedReports = computed(() => reports.value.filter((report) => ['RESOLVED', 'CLOSED'].includes(report.status)).length)
const reportsByStatus = computed(() =>
Object.entries(statusMeta)
.map(([status, meta]) => ({
status: status as ReportStatus,
label: meta.label,
tone: meta.tone,
total: reports.value.filter((report) => report.status === status).length
}))
.filter((item) => item.total > 0)
)
const currentPage = ref(1)
const itemsPerPage = ref(12)
watch([search, selectedStatus, selectedCategoryId, selectedAreaId], () => {
currentPage.value = 1
})
const totalPages = computed(() => Math.ceil(filteredReports.value.length / itemsPerPage.value))
const paginatedReports = computed(() => {
const sorted = [...filteredReports.value].sort(
(a, b) => new Date(b.created_at || '').getTime() - new Date(a.created_at || '').getTime()
)
const start = (currentPage.value - 1) * itemsPerPage.value
const end = start + itemsPerPage.value
return sorted.slice(start, end)
})
const handlePageChange = (page: number) => {
currentPage.value = page
}
const formatDate = (value?: string) => {
if (!value) return '-'
return new Date(value).toLocaleString('it-IT', {
day: '2-digit',
month: '2-digit',
year: 'numeric',
hour: '2-digit',
minute: '2-digit'
})
}
const truncate = (value?: string, max = 120) => {
if (!value) return '-'
return value.length > max ? `${value.slice(0, max).trim()}...` : value
}
</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">Overview Segnalazioni</h1>
<p class="text-muted mb-0">Vista completa in sola lettura per monitorare carico, stato e distribuzione.</p>
</div>
<NuxtLink to="/dashboard" class="btn btn-outline-secondary btn-sm">Torna al pannello admin</NuxtLink>
</div>
<div class="row g-3 mb-4">
<div class="col-6 col-xl-3" v-for="card in [
{ label: 'Totali', value: totalReports, tone: 'primary' },
{ label: 'Aperte', value: openReports, tone: 'danger' },
{ label: 'In lavorazione', value: activeReports, tone: 'warning' },
{ label: 'Chiuse/Risolte', value: closedReports, tone: 'success' }
]" :key="card.label">
<div class="card card-bg dashboard-stat h-100">
<div class="card-body py-3">
<div class="stat-value">{{ card.value }}</div>
<div class="small text-muted">{{ card.label }}</div>
</div>
</div>
</div>
</div>
<div class="card card-bg border-0 shadow-sm mb-4">
<div class="card-body">
<div class="row g-3 align-items-end">
<div class="col-12 col-lg-4">
<label class="form-label">Cerca</label>
<input v-model="search" type="text" class="form-control" placeholder="ID, indirizzo, descrizione, area..." />
</div>
<div class="col-12 col-md-4 col-lg-3">
<label class="form-label">Stato</label>
<select v-model="selectedStatus" class="form-select">
<option value="ALL">Tutti</option>
<option v-for="item in reportsByStatus" :key="item.status" :value="item.status">{{ item.label }}</option>
</select>
</div>
<div class="col-12 col-md-4 col-lg-2">
<label class="form-label">Categoria</label>
<select v-model="selectedCategoryId" class="form-select">
<option value="ALL">Tutte</option>
<option v-for="category in categories" :key="category.id" :value="category.id">{{ category.name }}</option>
</select>
</div>
<div class="col-12 col-md-4 col-lg-3">
<label class="form-label">Area</label>
<select v-model="selectedAreaId" class="form-select">
<option value="ALL">Tutte</option>
<option v-for="area in areas" :key="area.id" :value="area.id">{{ area.name }}</option>
</select>
</div>
</div>
</div>
</div>
<div v-if="pending" class="text-center py-5">
<div class="spinner-border text-primary" role="status"></div>
</div>
<template v-else>
<div class="card card-bg border-0 shadow-sm mb-4">
<div class="card-body">
<div class="d-flex flex-wrap align-items-center justify-content-between gap-2 mb-3">
<h2 class="h5 mb-0">Distribuzione stati</h2>
<span class="text-muted small">{{ filteredReports.length }} elementi trovati</span>
</div>
<div class="table-responsive report-table-wrapper">
<table class="table table-hover report-table mb-0 align-middle">
<thead>
<tr>
<th>Stato</th>
<th class="text-end">Totale</th>
</tr>
</thead>
<tbody>
<tr v-for="item in reportsByStatus" :key="item.status">
<td>
<span class="badge" :class="`bg-${item.tone}`">
{{ item.label }}
</span>
</td>
<td class="text-end">{{ item.total }}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div v-if="filteredReports.length === 0" class="alert alert-info">
Nessuna segnalazione trovata con filtri correnti.
</div>
<div v-else class="card card-bg border-0 shadow-sm mb-5">
<div class="card-body p-0">
<div class="table-responsive report-table-wrapper">
<table class="table table-hover report-table mb-0 align-middle">
<thead>
<tr>
<th>ID</th>
<th>Categoria</th>
<th>Indirizzo</th>
<th>Area</th>
<th>Stato</th>
<th>Operatore</th>
<th>Aggiornata</th>
</tr>
</thead>
<tbody>
<tr v-for="report in paginatedReports" :key="report.id">
<td class="report-table-id">#{{ report.id }}</td>
<td>
<div class="fw-semibold">{{ report.category_name || '-' }}</div>
<small class="text-muted">{{ truncate(report.description, 72) }}</small>
</td>
<td>{{ report.address || '-' }}</td>
<td>{{ report.area_name || 'Non assegnata' }}</td>
<td>
<span class="badge" :class="`bg-${statusMeta[report.status].tone}`">
{{ statusMeta[report.status].label }}
</span>
</td>
<td>{{ report.assigned_operator_id ? `#${report.assigned_operator_id}` : '-' }}</td>
<td class="text-muted text-nowrap">{{ formatDate(report.updated_at || report.created_at) }}</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="card-footer bg-transparent d-flex flex-wrap justify-content-between align-items-center py-3" v-if="totalPages > 1">
<span class="text-muted small mb-2 mb-sm-0">Pagina {{ currentPage }} di {{ totalPages }}</span>
<Pagination
:current-page="currentPage"
:per-page="itemsPerPage"
:total-items="filteredReports.length"
@page-change="handlePageChange"
/>
</div>
</div>
</template>
</div>
</template>
+227
View File
@@ -0,0 +1,227 @@
<script setup lang="ts">
import { ref } from 'vue'
definePageMeta({
middleware: 'auth',
auth: { role: 'ADMIN' }
})
useHead({ title: 'Gestione Utenti - Admin' })
const { getUsers, updateUserBan, updateUserRoles } = useAdmin()
const { data: usersRes, pending, refresh } = useAsyncData('admin-users', () => getUsers())
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(normalizeRole).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(() => {
if (!usersRes.value?.users) return []
if (!search.value) return usersRes.value.users
const s = search.value.toLowerCase()
return usersRes.value.users.filter(u =>
u.first_name.toLowerCase().includes(s) ||
u.last_name.toLowerCase().includes(s) ||
u.email.toLowerCase().includes(s) ||
u.fiscal_code?.toLowerCase().includes(s)
)
})
const askToggleBan = (user: any) => {
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 {
const res = await updateUserBan(user.id, { banned: !user.banned })
if (res.ok) {
await refresh()
pendingBanUser.value = null
}
} catch (err) {
console.error('Failed to update user ban status', err)
banError.value = 'Errore durante l\'aggiornamento dello stato di ban.'
} finally {
isUpdatingBan.value = false
}
}
const editingUserId = ref<number | null>(null)
const selectedRoles = ref<string[]>([])
const availableRoles = ['CITIZEN', 'OPERATOR', 'ADMIN']
const openRoleModal = (user: any) => {
editingUserId.value = user.id
selectedRoles.value = parseRoles(user.roles)
}
const closeRoleModal = () => {
editingUserId.value = null
selectedRoles.value = []
}
const saveRoles = async () => {
if (!editingUserId.value) return
roleError.value = ''
try {
const res = await updateUserRoles(editingUserId.value, { roles: selectedRoles.value })
if (res.ok) {
await refresh()
closeRoleModal()
}
} catch (err) {
console.error('Failed to update roles', err)
roleError.value = 'Errore durante l\'aggiornamento dei ruoli.'
}
}
</script>
<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 Utenti</h1>
<NuxtLink to="/dashboard" class="btn btn-outline-secondary btn-sm">Torna al pannello admin</NuxtLink>
</div>
<div class="row mb-4">
<div class="col-md-6">
<div class="input-group">
<input type="text" class="form-control" placeholder="Cerca per nome, email o CF..." v-model="search">
</div>
</div>
</div>
<div v-if="pending" class="text-center py-5">
<div class="spinner-border text-primary" role="status"></div>
</div>
<div v-else-if="!usersRes?.users || usersRes.users.length === 0" class="alert alert-info">
Nessun utente trovato.
</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">
<table class="table table-hover align-middle">
<thead>
<tr>
<th>ID</th>
<th>Nome</th>
<th>Email / CF</th>
<th>Ruoli</th>
<th>Punti</th>
<th>Stato</th>
<th class="text-end">Azioni</th>
</tr>
</thead>
<tbody>
<tr v-for="user in filteredUsers" :key="user.id">
<td>{{ user.id }}</td>
<td>
<strong>{{ user.first_name }} {{ user.last_name }}</strong>
</td>
<td>
<div>{{ user.email }}</div>
<small class="text-muted">{{ user.fiscal_code }}</small>
</td>
<td>
<span v-for="r in parseRoles(user.roles)" :key="r" class="badge bg-primary me-1">
{{ r }}
</span>
</td>
<td>{{ user.points || 0 }}</td>
<td>
<span v-if="user.banned" class="badge bg-danger">Bannato</span>
<span v-else class="badge bg-success">Attivo</span>
</td>
<td class="text-end">
<button
class="btn btn-sm btn-outline-primary me-2"
@click="openRoleModal(user)"
>
Ruoli
</button>
<button
class="btn btn-sm"
:class="user.banned ? 'btn-outline-success' : 'btn-outline-danger'"
@click="askToggleBan(user)"
>
{{ user.banned ? 'Sblocca' : 'Banna' }}
</button>
</td>
</tr>
</tbody>
</table>
</div>
<div v-if="editingUserId !== null" class="modal d-block" tabindex="-1" style="background: rgba(0,0,0,0.5)">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Modifica Ruoli Utente</h5>
<button type="button" class="btn-close" aria-label="Close" @click="closeRoleModal"></button>
</div>
<div class="modal-body">
<div class="form-check mb-2" v-for="role in availableRoles" :key="role">
<input
class="form-check-input"
type="checkbox"
:value="role"
:id="'role-'+role"
:checked="selectedRoles.includes(role)"
v-model="selectedRoles"
>
<label class="form-check-label" :for="'role-'+role">
{{ role }}
</label>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" @click="closeRoleModal">Annulla</button>
<button type="button" class="btn btn-primary" @click="saveRoles">Salva</button>
</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>
</template>
-188
View File
@@ -1,188 +0,0 @@
<script setup lang="ts">
definePageMeta({
middleware: 'auth'
})
useHead({ title: 'Cambio Password - Visione' })
const { changePassword, user, syncUser } = useAuth()
const router = useRouter()
const formData = reactive({
current_password: '', // FIX: rinominato da old_password
new_password: '',
confirm_password: ''
})
const isLoading = ref(false)
const errorMessage = ref('')
// FIX: Stati separati per la visibilità di ogni campo
const showCurrent = ref(false)
const showNew = ref(false)
const showConfirm = ref(false)
const canSubmit = computed(() => {
return (
formData.current_password.length > 0 &&
formData.new_password.length >= 8 &&
formData.new_password === formData.confirm_password
)
})
const handleSubmit = async () => {
if (!canSubmit.value) return
isLoading.value = true
errorMessage.value = ''
try {
// FIX: Payload con current_password come richiesto dall'API
const res = await changePassword({
current_password: formData.current_password,
new_password: formData.new_password
} as any) // Cast temporaneo se l'interfaccia types/api non è ancora aggiornata
if (res.ok) {
await syncUser()
await router.push('/me')
}
} catch (error: any) {
errorMessage.value = error.data?.message || 'Errore. Verifica la password attuale.'
} finally {
isLoading.value = false
}
}
</script>
<template>
<div class="container my-5">
<div class="row justify-content-center">
<div class="col-12 col-md-8 col-lg-6">
<div v-if="user?.must_change_password" class="callout callout-highlight callout-warning mb-4">
<div class="callout-title d-flex align-items-center">
<BIIcon name="it-warning-circle" size="sm" color="warning" class="me-2" />
Azione Richiesta
</div>
<p>Per motivi di sicurezza, imposta una nuova password per il tuo account.</p>
</div>
<div class="card card-bg shadow-sm">
<div class="card-body p-4">
<h3 class="card-title h4 mb-4">Cambia la tua password</h3>
<form @submit.prevent="handleSubmit">
<!-- 1. PASSWORD ATTUALE -->
<div class="form-group mb-3">
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text"><BIIcon name="it-lock" size="sm" /></div>
</div>
<input
:type="showCurrent ? 'text' : 'password'"
class="form-control"
id="current_password"
v-model="formData.current_password"
>
<!-- FIX: Aggiunta classe 'active' dinamica per evitare sovrapposizione placeholder -->
<label for="current_password" :class="{ 'active': formData.current_password }">Password attuale</label>
<div class="input-group-append">
<button type="button" class="btn btn-primary btn-sm" @click="showCurrent = !showCurrent">
<BIIcon :name="showCurrent ? 'it-password-visible' : 'it-password-invisible'" size="sm" color="white" />
</button>
</div>
</div>
</div>
<hr class="my-4">
<!-- 2. NUOVA PASSWORD -->
<div class="form-group mb-3">
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text"><BIIcon name="it-lock" size="sm" /></div>
</div>
<input
:type="showNew ? 'text' : 'password'"
class="form-control"
id="new_password"
v-model="formData.new_password"
>
<label for="new_password" :class="{ 'active': formData.new_password }">Nuova password</label>
<div class="input-group-append">
<button type="button" class="btn btn-primary btn-sm" @click="showNew = !showNew">
<BIIcon :name="showNew ? 'it-password-visible' : 'it-password-invisible'" size="sm" color="white" />
</button>
</div>
</div>
<small class="form-text text-muted">Minimo 8 caratteri.</small>
</div>
<!-- 3. CONFERMA PASSWORD -->
<div class="form-group mb-4">
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text"><BIIcon name="it-lock" size="sm" /></div>
</div>
<input
:type="showConfirm ? 'text' : 'password'"
class="form-control"
:class="{ 'is-invalid': formData.confirm_password && formData.confirm_password !== formData.new_password }"
id="confirm_password"
v-model="formData.confirm_password"
>
<label for="confirm_password" :class="{ 'active': formData.confirm_password }">Conferma nuova password</label>
<div class="input-group-append">
<button type="button" class="btn btn-primary btn-sm" @click="showConfirm = !showConfirm">
<BIIcon :name="showConfirm ? 'it-password-visible' : 'it-password-invisible'" size="sm" color="white" />
</button>
</div>
</div>
</div>
<div v-if="errorMessage" class="alert alert-danger mb-4" role="alert">
{{ errorMessage }}
</div>
<button
type="submit"
class="btn btn-primary w-100 py-2"
:disabled="!canSubmit || isLoading"
>
<span v-if="isLoading" class="spinner-border spinner-border-sm me-2"></span>
<span v-else>Aggiorna Password</span>
</button>
</form>
</div>
</div>
</div>
</div>
</div>
</template>
<style scoped>
/* Correzione per i bottoni occhio in Bootstrap Italia */
.input-group-append .btn {
z-index: 4;
height: 100%;
}
/* Stile per gestire correttamente le label di Bootstrap Italia che si sovrappongono */
.form-group label.active {
transform: translateY(-140%) scale(0.9);
color: #006f9d;
}
.input-group-text {
background-color: #f0f0f0;
border-right: none;
}
.form-control:focus + label {
color: #006f9d;
}
</style>
+153
View File
@@ -0,0 +1,153 @@
<script setup lang="ts">
import { onBeforeUnmount, onMounted, ref } from 'vue'
definePageMeta({
middleware: 'guest'
})
useHead({ title: 'Accesso CIE - Visione' })
const route = useRoute()
const router = useRouter()
const { fetchCieSession, handleLoginSuccess } = useAuth()
const state = computed(() => {
const value = route.query.state
return typeof value === 'string' ? value : ''
})
const providerError = computed(() => {
const value = route.query.error
return typeof value === 'string' ? value : ''
})
const providerCieError = computed(() => {
const value = route.query.cie_error
return typeof value === 'string' ? value : ''
})
const providerErrorDescription = computed(() => {
const value = route.query.error_description
return typeof value === 'string' ? value : ''
})
const isLoading = ref(true)
const errorMessage = ref('')
const statusMessage = ref('Verifica dell’autenticazione CIE in corso...')
let pollTimer: ReturnType<typeof setTimeout> | null = null
let attempts = 0
const maxAttempts = 30
const stopPolling = () => {
if (pollTimer) {
clearTimeout(pollTimer)
pollTimer = null
}
}
const scheduleNextPoll = () => {
pollTimer = setTimeout(checkSession, 2000)
}
const redirectToLoginError = async (code: string, fallbackMessage: string) => {
stopPolling()
isLoading.value = false
try {
await router.replace({
path: '/auth/login',
query: { cie_error: code }
})
} catch {
errorMessage.value = fallbackMessage
}
}
const checkSession = async () => {
if (providerError.value || providerCieError.value) {
const isCancelled = providerErrorDescription.value.toLowerCase().includes('rejected by user')
|| providerError.value === 'access_denied'
|| providerCieError.value === 'invalid_request'
await redirectToLoginError(
isCancelled ? 'cancelled' : 'failed',
providerErrorDescription.value || 'Autenticazione CIE non completata. Riprova dal login.'
)
return
}
if (!state.value) {
await redirectToLoginError('invalid_session', 'Sessione CIE non valida: parametro state mancante.')
return
}
attempts += 1
try {
const res = await fetchCieSession(state.value)
if (res.status === 'authenticated' && res.auth?.token) {
stopPolling()
await handleLoginSuccess(res.auth.token)
return
}
if (['failed', 'expired', 'cancelled', 'error'].includes(res.status)) {
await redirectToLoginError('failed', 'Autenticazione CIE non completata. Riprova dal login.')
return
}
if (attempts >= maxAttempts) {
await redirectToLoginError('timeout', 'Tempo di attesa scaduto durante la verifica CIE. Riprova.')
return
}
statusMessage.value = 'Autenticazione completata sul provider. Attendo conferma finale da Visione...'
scheduleNextPoll()
} catch (err: any) {
await redirectToLoginError('verification_error', err.data?.message || 'Errore durante la verifica della sessione CIE.')
}
}
onMounted(() => {
checkSession()
})
onBeforeUnmount(() => {
stopPolling()
})
</script>
<template>
<div class="d-flex align-items-center bg-light py-5">
<div class="container">
<div class="row justify-content-center">
<div class="col-12 col-md-8 col-lg-6">
<div class="card card-bg shadow-sm">
<div class="card-body p-4 p-md-5 text-center">
<BIIcon name="it-card" size="xl" color="primary" class="mb-3" />
<h1 class="h3 font-weight-bold mb-3">Accesso con CIE</h1>
<div v-if="isLoading" class="py-3">
<div class="spinner-border text-primary mb-3" role="status">
<span class="visually-hidden">Caricamento...</span>
</div>
<p class="text-muted mb-0">{{ statusMessage }}</p>
</div>
<div v-else-if="errorMessage" class="py-2">
<div class="alert alert-danger text-start mb-4" role="alert">
{{ errorMessage }}
</div>
<button class="btn btn-primary" @click="router.push('/auth/login')">
Torna al login
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
+70 -63
View File
@@ -7,20 +7,35 @@ definePageMeta({
useHead({ title: 'Accedi - Visione' })
const { requestOtp, verifyOtp, loginWithPassword, handleLoginSuccess } = useAuth()
const router = useRouter()
const runtimeConfig = useRuntimeConfig()
const route = useRoute()
const { requestOtp, verifyOtp, handleLoginSuccess, startCieLogin } = useAuth()
// UI State
const loginMethod = ref<'otp' | 'password'>('otp')
const otpStep = ref<1 | 2>(1)
const isLoading = ref(false)
const isCieLoading = ref(false)
const errorMessage = ref('')
// Form State
const email = ref('')
const password = ref('')
const otpCode = ref('')
const showPassword = ref(false)
const cieCallbackUrl = `${runtimeConfig.public.url}/auth/cie/callback`
const cieErrorMessage = computed(() => {
const error = route.query.cie_error
if (typeof error !== 'string') return ''
const messages: Record<string, string> = {
invalid_session: 'Sessione CIE non valida o incompleta. Avvia di nuovo accesso con CIE.',
cancelled: 'Accesso con CIE annullato. Se vuoi, riprova dal pulsante Entra con CIE.',
failed: 'Autenticazione CIE non completata. Riprova dal pulsante Entra con CIE.',
timeout: 'Tempo di attesa scaduto durante verifica CIE. Riprova.',
verification_error: 'Errore durante verifica autenticazione CIE. Riprova tra poco.'
}
return messages[error] || 'Accesso con CIE non riuscito. Riprova.'
})
const handleRequestOtp = async () => {
isLoading.value = true
@@ -48,18 +63,24 @@ const handleVerifyOtp = async () => {
}
}
const handlePasswordLogin = async () => {
isLoading.value = true
const handleCieLogin = async () => {
isCieLoading.value = true
errorMessage.value = ''
try {
const res = await loginWithPassword({ email: email.value, password: password.value })
await handleLoginSuccess(res.token)
const res = await startCieLogin(cieCallbackUrl)
await navigateTo(res.authorization_url, {
external: true,
replace: true,
})
} catch (err: any) {
errorMessage.value = 'Credenziali non valide.'
} finally {
isLoading.value = false
errorMessage.value = err.data?.message || 'Avvio autenticazione CIE non riuscito. Riprova.'
isCieLoading.value = false
}
}
const handleOTPInput = async (value: string) => {
console.log(value)
}
</script>
<template>
@@ -68,9 +89,9 @@ const handlePasswordLogin = async () => {
<div class="row justify-content-center">
<div class="col-12 col-md-8 col-lg-5">
<!-- Intestazione istituzionale -->
<div class="text-center mb-4">
<BIIcon name="it-pa" size="xl" color="primary" class="mb-2" />
<BIIcon name="it-user" size="xl" color="primary" class="mb-2" />
<h1 class="h3 font-weight-bold">Accedi a Visione</h1>
<p class="text-muted">Il portale delle segnalazioni urbane</p>
</div>
@@ -78,10 +99,14 @@ const handlePasswordLogin = async () => {
<div class="card card-bg shadow-sm">
<div class="card-body p-4 p-md-5">
<!-- Finto Bottone CIE -->
<button class="btn btn-primary w-100 mb-4 d-flex align-items-center justify-content-center gap-2" disabled title="Integrazione CIE prevista per la fase successiva">
<BIIcon name="it-card" size="sm" color="white" />
Entra con CIE (Presto disponibile)
<button
class="btn btn-primary w-100 mb-4 d-flex align-items-center justify-content-center gap-2 entraconcie"
:disabled="isCieLoading || isLoading"
@click="handleCieLogin"
>
<span v-if="isCieLoading" class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
&#8203;
</button>
<div class="d-flex align-items-center my-4">
@@ -90,12 +115,14 @@ const handlePasswordLogin = async () => {
<hr class="flex-grow-1">
</div>
<div v-if="cieErrorMessage" class="alert alert-danger mb-4" role="alert">
{{ cieErrorMessage }}
</div>
<div v-if="errorMessage" class="alert alert-danger mb-4" role="alert">
{{ errorMessage }}
</div>
<!-- FLUSSO OTP -->
<div v-if="loginMethod === 'otp'">
<form v-if="otpStep === 1" @submit.prevent="handleRequestOtp">
<div class="form-group mb-4">
<input type="email" class="form-control" id="email" v-model="email" required>
@@ -103,16 +130,27 @@ const handlePasswordLogin = async () => {
</div>
<button type="submit" class="btn btn-primary w-100" :disabled="isLoading">
<span v-if="isLoading" class="spinner-border spinner-border-sm me-2" role="status"></span>
Ricevi codice OTP
Entra
</button>
</form>
<form v-else @submit.prevent="handleVerifyOtp">
<div class="alert alert-success mb-4 small">
<div v-show="!errorMessage" class="alert alert-success mb-4 small">
Abbiamo inviato un codice OTP a <strong>{{ email }}</strong>.
</div>
<div class="form-group mb-4">
<input type="text" class="form-control text-center text-tracking-widest fs-4" id="otp" v-model="otpCode" required maxlength="6" autocomplete="one-time-code">
<input
id="otp"
v-model="otpCode"
autocomplete="one-time-code"
class="form-control text-center text-tracking-widest fs-4"
inputmode="numeric"
maxlength="6"
pattern="[0-9]*"
required
type="text"
@input="otpCode = otpCode.replace(/\D/g, '')"
>
<label for="otp" :class="{ 'active': otpCode.length > 0 }">Codice a 6 cifre</label>
</div>
<button type="submit" class="btn btn-primary w-100 mb-3" :disabled="isLoading">
@@ -123,44 +161,6 @@ const handlePasswordLogin = async () => {
<a href="#" class="small text-decoration-none" @click.prevent="otpStep = 1">Modifica indirizzo email</a>
</div>
</form>
</div>
<!-- FLUSSO PASSWORD -->
<form v-else @submit.prevent="handlePasswordLogin">
<div class="form-group mb-4">
<input type="email" class="form-control" id="emailPwd" v-model="email" required>
<label for="emailPwd" :class="{ 'active': email.length > 0 }">Indirizzo Email</label>
</div>
<!-- INPUT PASSWORD FIXATO -->
<div class="form-group mb-4 position-relative">
<input :type="showPassword ? 'text' : 'password'" class="form-control pe-5" id="password" v-model="password" required>
<label for="password" :class="{ 'active': password.length > 0 }">Password</label>
<button
type="button"
class="btn bg-transparent border-0 shadow-none position-absolute p-2"
style="right: 0; top: 2px; z-index: 10;"
@click="showPassword = !showPassword"
:aria-pressed="showPassword"
aria-label="Mostra/Nascondi password"
>
<BIIcon :name="showPassword ? 'it-password-visible' : 'it-password-invisible'" color="primary" size="sm" />
</button>
</div>
<button type="submit" class="btn btn-primary w-100 mb-3" :disabled="isLoading">
<span v-if="isLoading" class="spinner-border spinner-border-sm me-2" role="status"></span>
Accedi
</button>
</form>
<!-- Switch Method -->
<div class="text-center mt-4">
<a href="#" class="small text-decoration-none" @click.prevent="loginMethod = loginMethod === 'otp' ? 'password' : 'otp'; errorMessage = ''">
{{ loginMethod === 'otp' ? 'Vuoi usare la password? Clicca qui' : 'Usa il login sicuro senza password (OTP)' }}
</a>
</div>
</div>
</div>
@@ -182,4 +182,11 @@ const handlePasswordLogin = async () => {
.pe-5 {
padding-right: 3rem !important;
}
button.entraconcie {
background-image: url('/entraconcie.png');
background-repeat: no-repeat;
background-position: center center;
background-size: 100%;
}
</style>
+19 -53
View File
@@ -1,4 +1,5 @@
<script setup lang="ts">
import CodiceFiscale from 'codice-fiscale-js'
import { ref } from 'vue'
definePageMeta({
@@ -13,34 +14,17 @@ const router = useRouter()
const isLoading = ref(false)
const errorMessage = ref('')
const successMessage = ref(false)
const showPassword = ref(false)
const form = ref({
first_name: '',
last_name: '',
fiscal_code: '',
email: '',
password: '',
phone: '',
privacy: false
})
const computeSurnameCode = (surname = '') => {
const s = surname.toUpperCase().replace(/[^A-Z]/g, '')
const consonants = s.replace(/[AEIOU]/g, '')
const vowels = s.replace(/[^AEIOU]/g, '')
return (consonants + vowels + 'XXX').slice(0, 3)
}
const computeNameCode = (name = '') => {
const s = name.toUpperCase().replace(/[^A-Z]/g, '')
const consonants = s.replace(/[AEIOU]/g, '')
const vowels = s.replace(/[^AEIOU]/g, '')
if (consonants.length >= 4) {
return consonants.charAt(0) + consonants.charAt(2) + consonants.charAt(3)
}
return (consonants + vowels + 'XXX').slice(0, 3)
}
const normalizeFiscalCode = (fiscalCode = '') => fiscalCode.trim().toUpperCase()
const handleRegister = async () => {
if (!form.value.privacy) {
@@ -48,13 +32,17 @@ const handleRegister = async () => {
return
}
const expected = computeSurnameCode(form.value.last_name) + computeNameCode(form.value.first_name)
if (form.value.fiscal_code.trim().length >= 6) {
const provided = form.value.fiscal_code.trim().toUpperCase().slice(0, 6)
if (provided !== expected) {
errorMessage.value = `Il Codice Fiscale non sembra corrispondere a nome/cognome. Atteso: ${expected}`
const fiscalCode = normalizeFiscalCode(form.value.fiscal_code)
const expected = CodiceFiscale.surnameCode(form.value.last_name) + CodiceFiscale.nameCode(form.value.first_name)
if (!CodiceFiscale.check(fiscalCode)) {
errorMessage.value = 'Il Codice Fiscale inserito non è valido.'
return
}
if (fiscalCode.slice(0, 6) !== expected) {
errorMessage.value = 'Il Codice Fiscale non corrisponde a nome e cognome inseriti.'
return
}
isLoading.value = true
@@ -64,9 +52,8 @@ const handleRegister = async () => {
await register({
first_name: form.value.first_name,
last_name: form.value.last_name,
fiscal_code: form.value.fiscal_code.toUpperCase(),
fiscal_code: fiscalCode,
email: form.value.email,
password: form.value.password,
phone: form.value.phone || undefined
})
@@ -99,7 +86,7 @@ const handleRegister = async () => {
<div class="card-body p-4 p-md-5">
<div v-if="successMessage" class="alert alert-success" role="alert">
Registrazione completata con successo! Reindirizzamento al login...
Registrazione completata con successo! Reindirizzamento all'accesso con OTP...
</div>
<div v-if="errorMessage" class="alert alert-danger mb-4" role="alert">
@@ -110,7 +97,6 @@ const handleRegister = async () => {
<h2 class="h5 text-primary font-weight-bold mb-4 border-bottom pb-2">Dati Anagrafici</h2>
<!-- FIX LAYOUT: form-group separato da col -->
<div class="row mb-4">
<div class="col-12 col-md-6 mb-4 mb-md-0">
<div class="form-group">
@@ -132,33 +118,15 @@ const handleRegister = async () => {
<small class="form-text text-muted">Sarà utilizzato come identificativo univoco nel sistema PA.</small>
</div>
<h2 class="h5 text-primary font-weight-bold mt-5 mb-4 border-bottom pb-2">Credenziali e Contatti</h2>
<h2 class="h5 text-primary font-weight-bold mt-5 mb-4 border-bottom pb-2">Contatti</h2>
<div class="row mb-4">
<div class="col-12 col-md-6 mb-4 mb-md-0">
<div class="form-group">
<div class="col-12">
<div class="form-group position-relative">
<input type="email" class="form-control" id="regEmail" v-model="form.email" required>
<label for="regEmail" :class="{ 'active': form.email.length > 0 }">Indirizzo Email</label>
</div>
</div>
<div class="col-12 col-md-6">
<!-- INPUT PASSWORD FIXATO -->
<div class="form-group position-relative">
<input :type="showPassword ? 'text' : 'password'" class="form-control pe-5" id="regPwd" v-model="form.password" required minlength="10">
<label for="regPwd" :class="{ 'active': form.password.length > 0 }">Password (min. 10 crt)</label>
<button
type="button"
class="btn bg-transparent border-0 shadow-none position-absolute p-2"
style="right: 0; top: 2px; z-index: 10;"
@click="showPassword = !showPassword"
:aria-pressed="showPassword"
aria-label="Mostra/Nascondi password"
>
<BIIcon :name="showPassword ? 'it-password-visible' : 'it-password-invisible'" color="primary" size="sm" />
</button>
</div>
</div>
</div>
<div class="form-group mb-5">
@@ -167,7 +135,6 @@ const handleRegister = async () => {
<small class="form-text text-muted">Faciliterà il contatto da parte degli operatori comunali in caso di intervento.</small>
</div>
<!-- Privacy Checkbox -->
<div class="form-check mb-4">
<input class="form-check-input" type="checkbox" id="privacyCheck" v-model="form.privacy" required>
<label class="form-check-label small" for="privacyCheck">
@@ -179,6 +146,9 @@ const handleRegister = async () => {
<span v-if="isLoading" class="spinner-border spinner-border-sm me-2" role="status"></span>
Registra Profilo
</button>
<p class="small text-muted mt-3 mb-0">
Dopo la registrazione potrai accedere usando OTP via email o CIE, quando disponibile.
</p>
</form>
</div>
@@ -195,8 +165,4 @@ const handleRegister = async () => {
</template>
<style scoped>
/* Previene che il testo finisca sotto l'icona */
.pe-5 {
padding-right: 3rem !important;
}
</style>
+12 -25
View File
@@ -9,37 +9,32 @@ import CitizenDashboard from '~/components/dashboard/CitizenDashboard.vue'
import OperatorDashboard from '~/components/dashboard/OperatorDashboard.vue'
import AdminDashboard from '~/components/dashboard/AdminDashboard.vue'
// Normalizziamo in uppercase nel caso il backend risponda con 'citizen' o 'CITIZEN'
const currentDashboard = computed(() => {
const role = user.value?.role?.toUpperCase()
if (role === 'CITIZEN') return CitizenDashboard
if (role === 'OPERATOR') return OperatorDashboard
if (role === 'ADMIN') return AdminDashboard
if (isCitizen(user.value?.role)) return CitizenDashboard
if (isOperator(user.value?.role)) return OperatorDashboard
if (isAdmin(user.value?.role)) return AdminDashboard
return null
})
// Testi dinamici per l'Hero (la fascia blu in alto) in base al ruolo
const heroTitle = computed(() => {
const role = user.value?.role?.toUpperCase()
if (role === 'ADMIN') return 'Pannello di Amministrazione'
if (role === 'OPERATOR') return 'Gestione Operativa'
return 'Le Mie Segnalazioni' // Cittadino
if (isAdmin(user.value?.role)) return 'Pannello Admin'
if (isOperator(user.value?.role)) 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 === 'OPERATOR') return 'Prendi in carico e gestisci le segnalazioni in corso'
return 'Traccia lo stato di tutte le tue segnalazioni e comunica con gli operatori' // Cittadino
if (isAdmin(user.value?.role)) return 'Accesso amministrativo per configurazioni, utenti e moderazione'
if (isOperator(user.value?.role)) return 'Prendi in carico e gestisci le segnalazioni in corso'
return 'Riepilogo rapido delle tue segnalazioni e dei punti cittadino'
})
</script>
<template>
<div>
<div class="it-hero-wrapper it-primary">
<div class="it-hero-wrapper it-primary hero-compact">
<div class="container">
<div class="row">
<div class="col-12">
<div class="col-12 text-center">
<div class="it-hero-text-wrapper p-4">
<h1 class="text-white font-weight-bold">{{ heroTitle }}</h1>
<p class="text-white mt-2 lead">
@@ -53,7 +48,7 @@ const heroSubtitle = computed(() => {
<div class="container my-5">
<div class="row mb-4">
<div class="row mb-3">
<div class="col-12">
<h4 class="mb-2 text-muted">
Benvenuto, <strong>{{ user?.first_name }} {{ user?.last_name }}</strong>.
@@ -61,7 +56,6 @@ const heroSubtitle = computed(() => {
</div>
</div>
<!-- Qui viene montato CitizenDashboard.vue, OperatorDashboard.vue o AdminDashboard.vue -->
<component :is="currentDashboard" v-if="currentDashboard" />
<div v-else class="alert alert-warning" role="alert">
@@ -71,10 +65,3 @@ const heroSubtitle = computed(() => {
</div>
</div>
</template>
<style scoped>
/* Il gradiente originale della pagina rotta */
.it-primary {
background: linear-gradient(135deg, #006f9d 0%, #003d5c 100%);
}
</style>
+73 -30
View File
@@ -3,6 +3,8 @@ import BIIcon from "~/components/BIIcon.vue";
const { getOpenDataReports } = usePublic()
const { user } = useAuth();
const stats = {
total_reports: 14523,
resolved_reports: 13890,
@@ -12,6 +14,17 @@ const stats = {
const { data: openDataResponse } = await useAsyncData('recent-fixes', () =>
getOpenDataReports({ page: 1, per_page: 3 })
)
const getStatusBadge = (status: string) => {
switch (status) {
case 'RESOLVED':
return { class: 'bg-success', text: 'Risolto', icon: 'it-check-circle' }
case 'CLOSED':
return { class: 'bg-secondary', text: 'Chiuso', icon: 'it-lock' }
default:
return { class: 'bg-info', text: status, icon: 'it-info-circle' }
}
}
</script>
<template>
@@ -19,15 +32,15 @@ const { data: openDataResponse } = await useAsyncData('recent-fixes', () =>
<div class="it-hero-wrapper bg-light">
<div class="container">
<div class="row">
<div class="col-12 col-lg-8 offset-lg-2 text-center">
<div class="col-12 col-lg-8 mx-auto text-center">
<div class="it-hero-text-wrapper p-4">
<h1 class="no_toc font-weight-bold text-dark">Miglioriamo insieme la città</h1>
<p class="d-none d-lg-block mt-3 mb-4 text-secondary">
Il portale ufficiale nazionale per segnalare disservizi urbani. Scatta una foto, invia la segnalazione
<h1 class="no_toc font-weight-bold">Miglioriamo insieme la città</h1>
<p class="d-none d-lg-block mt-3 mb-4 text-muted">
Il portale ufficiale della città metropolitana di Bari per segnalare disservizi urbani. Scatta una foto, invia la segnalazione
e monitora l'intervento in totale trasparenza.
</p>
<div class="it-btn-container d-flex justify-content-center gap-3">
<NuxtLink class="btn btn-primary" to="/auth/login">
<NuxtLink v-if="!user || isCitizen(user.role)" class="btn btn-primary" to="/auth/login">
Fai una segnalazione
</NuxtLink>
<NuxtLink class="btn btn-outline-primary" to="/open-data">
@@ -45,30 +58,29 @@ const { data: openDataResponse } = await useAsyncData('recent-fixes', () =>
<div class="row text-center">
<div class="col-12 col-md-4 mb-4">
<div class="mb-3">
<BIIcon name="it-camera" size="xl" color="primary" />
<BIIcon color="primary" name="it-camera" size="xl"/>
</div>
<h3 class="h5 font-weight-semibold">1. Segnala</h3>
<p class="text-muted">Usa lo smartphone per fotografare il problema stradale e inviare la posizione
esatta.</p>
<p class="text-muted">Fotografa il problema stradale e condividi la tua posizione.</p>
</div>
<div class="col-12 col-md-4 mb-4">
<div class="mb-3">
<BIIcon name="it-tool" size="xl" color="primary" />
<BIIcon color="primary" name="it-tool" size="xl"/>
</div>
<h3 class="h5 font-weight-semibold">2. Intervento</h3>
<p class="text-muted">Le squadre comunali prendono in carico la tua segnalazione e avviano i lavori.</p>
<p class="text-muted">Il Comune attiva subito le squadre operative per risolvere il problema.</p>
</div>
<div class="col-12 col-md-4 mb-4">
<div class="mb-3">
<BIIcon name="it-star-outline" size="xl" color="primary" />
<BIIcon color="primary" name="it-star-outline" size="xl"/>
</div>
<h3 class="h5 font-weight-semibold">3. Punti e Feedback</h3>
<p class="text-muted">Problema risolto! Ottieni Punti Cittadino e lascia un feedback sull'intervento.</p>
<p class="text-muted">Problema risolto! Guadagna Punti Cittadino e valuta l'intervento.</p>
</div>
</div>
</div>
<div class="bg-light py-5 border-top border-bottom">
<div class="bg-light py-5">
<div class="container my-4">
<h2 class="text-center mb-5 font-weight-bold">I numeri del nostro Comune</h2>
<div class="row text-center">
@@ -102,26 +114,41 @@ const { data: openDataResponse } = await useAsyncData('recent-fixes', () =>
<div class="row" v-if="openDataResponse?.reports && openDataResponse.reports.length > 0">
<div class="col-12 col-md-4 mb-4" v-for="report in openDataResponse.reports" :key="report.id">
<div class="card-wrapper card-space">
<div class="card card-bg card-big">
<div class="card-body">
<div class="category-top">
<BIIcon name="it-check-circle" size="sm" color="success" />
<span class="category text-success font-weight-semibold">Risolto</span>
</div>
<h3 class="card-title h5 mt-2">{{ report.category_name }}</h3>
<div class="card-wrapper card-space h-100">
<div class="card card-bg h-100 shadow-sm">
<div class="card-body d-flex flex-column">
<p class="card-text text-muted">
<span class="me-1"><BIIcon name="it-map-marker-circle" size="xs" /></span>
{{ report.area_name || 'Area comunale' }}
</p>
<div class="it-card-footer mt-4">
<span class="card-signature">
Aggiornato il {{ new Date(report.updated_at).toLocaleDateString('it-IT') }}
<div class="d-flex justify-content-between align-items-start mb-3">
<div class="category-top m-0">
<span :class="getStatusBadge(report.status).class"
class="badge rounded-pill text-white px-3 py-1">
<BIIcon :name="getStatusBadge(report.status).icon" class="me-1" color="white" size="xs"/>
{{ getStatusBadge(report.status).text }}
</span>
</div>
</div>
<h3 class="card-title h5 font-weight-bold">{{ report.category_name }}</h3>
<p class="card-text text-muted mb-4">
<BIIcon class="me-1" name="it-map-marker-circle" size="sm"/>
{{ report.area_name || 'Area comunale non specificata' }}
</p>
<div class="mt-auto pt-3 border-top">
<div class="row text-muted small">
<div class="col-6">
<div class="fw-bold text-uppercase">Segnalato</div>
<div>{{ new Date(report.created_at).toLocaleDateString('it-IT') }}</div>
</div>
<div class="col-6 text-end">
<div class="fw-bold text-uppercase">Risolto</div>
<div>{{ new Date(report.updated_at).toLocaleDateString('it-IT') }}</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
@@ -132,7 +159,7 @@ const { data: openDataResponse } = await useAsyncData('recent-fixes', () =>
</div>
</div>
<div class="container my-5 pb-5">
<div v-show="!user" class="container my-5 pb-5">
<div class="callout callout-highlight callout-primary">
<div class="callout-title">
<BIIcon name="it-info-circle"/>
@@ -150,3 +177,19 @@ const { data: openDataResponse } = await useAsyncData('recent-fixes', () =>
</div>
</div>
</template>
<style scoped>
.card-wrapper {
height: 100%;
}
.card-bg {
border: 1px solid rgba(0, 0, 0, 0.05);
transition: transform 0.2s ease, box-shadow 0.2s ease;
}
.card-bg:hover {
transform: translateY(-2px);
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1) !important;
}
</style>
+105 -60
View File
@@ -1,22 +1,24 @@
<script setup lang="ts">
// La pagina è statica, usiamo solo i componenti UI
import { useMembers } from "~/composables/useMembers";
useHead({
title: 'Informazioni sul Progetto - Visione',
})
const { sortedMembers } = useMembers();
</script>
<template>
<div>
<!-- HERO SECTION (Senza pt-5/mt-5 come richiesto) -->
<div class="it-hero-wrapper it-primary">
<div class="container">
<div class="row">
<div class="col-12 text-center">
<div class="it-hero-text-wrapper p-4">
<h1 class="text-white font-weight-bold">Il Progetto Visione</h1>
<h1 class="text-white font-weight-bold">Il Progetto "Visione"</h1>
<p class="text-white mt-3 lead font-weight-semibold">
La piattaforma digitale per la gestione intelligente delle segnalazioni urbane,
pensata per avvicinare cittadini e pubblica amministrazione.
La piattaforma digitale della Città Metropolitana di Bari per la partecipazione attiva,
la trasparenza e la gestione condivisa del territorio.
</p>
</div>
</div>
@@ -24,72 +26,89 @@ useHead({
</div>
</div>
<!-- OBIETTIVO DEL PROGETTO -->
<div class="container my-5 py-3">
<div class="row">
<div class="col-12 col-lg-8 offset-lg-2">
<h2 class="mb-4 font-weight-bold">Migliorare la qualità della vita in città</h2>
<h2 class="mb-4 font-weight-bold">Un nuovo dialogo tra Cittadini ed Ente</h2>
<p class="lead text-muted">
Visione nasce dall'esigenza di fornire alle amministrazioni comunali uno strumento moderno per mappare, gestire e risolvere disservizi presenti sul territorio (buche stradali, illuminazione guasta, rifiuti abbandonati).
Il progetto nasce dall'esigenza di digitalizzare e ottimizzare i flussi di comunicazione tra la cittadinanza
e la Pubblica Amministrazione. Sostituisce i tradizionali canali non tracciabili con un unico punto di
accesso telematico.
</p>
<p>
Il sistema non si limita a raccogliere dati, ma automatizza l'assegnazione alle squadre operative competenti tramite logiche geospaziali, traccia l'intero ciclo di vita della segnalazione e restituisce trasparenza ai cittadini tramite un portale Open Data dedicato.
L'adozione della piattaforma persegue un triplice obiettivo strategico: ridurre drasticamente i tempi di
risposta
dell'Ente nella risoluzione dei disservizi (quali buche stradali, illuminazione guasta o degrado urbano),
responsabilizzare la <strong>cittadinanza attiva</strong> tramite meccanismi di partecipazione diretta e
fornire
agli organi competenti un quadro analitico costantemente aggiornato e geolocalizzato delle criticità del
territorio.
</p>
</div>
</div>
</div>
<!-- RUOLI E FUNZIONALITÀ (Card Grid) -->
<div class="bg-light py-5">
<div class="container">
<h2 class="text-center mb-5 font-weight-bold">Come funziona il sistema</h2>
<h2 class="text-center mb-5 font-weight-bold">Come si articola l'ecosistema digitale</h2>
<div class="row">
<!-- Cittadino -->
<div class="col-12 col-md-4 mb-4">
<div class="card-wrapper card-space h-100">
<div class="card card-bg h-100">
<div class="card-body">
<BIIcon name="it-user" size="xl" color="primary" class="mb-3" />
<h3 class="card-title h5 font-weight-bold">Cittadini</h3>
<BIIcon class="mb-3" color="primary" name="it-user" size="xl"/>
<h3 class="card-title h5 font-weight-bold">I Cittadini</h3>
<p class="card-text text-muted">
Tramite autenticazione sicura (OTP via email o CIE), i cittadini possono inviare segnalazioni geolocalizzate complete di foto.
L'accesso è garantito attraverso l'autocompletamento anagrafico e il supporto ai sistemi di identità
digitale
nazionali (<strong>CIE</strong>).
<br><br>
Per incentivare la partecipazione, è integrato un sistema di <strong>gamification</strong>: ogni segnalazione valida e risolta fa guadagnare Punti Cittadino, premiando la cittadinanza attiva. Possono inoltre chattare con gli operatori e lasciare un feedback finale.
Il cittadino può compilare form guidati inserendo descrizioni, documentazione fotografica e
posizione esatta (GPS).
Per incentivare la partecipazione, è previsto il conferimento di "<strong>Punti di Cittadinanza
Attiva</strong>"
per ogni segnalazione validata e risolta dall'Ente.
</p>
</div>
</div>
</div>
</div>
<!-- Operatore -->
<div class="col-12 col-md-4 mb-4">
<div class="card-wrapper card-space h-100">
<div class="card card-bg h-100">
<div class="card-body">
<BIIcon name="it-tool" size="xl" color="primary" class="mb-3" />
<h3 class="card-title h5 font-weight-bold">Operatori e Squadre</h3>
<BIIcon class="mb-3" color="primary" name="it-tool" size="xl"/>
<h3 class="card-title h5 font-weight-bold">Squadre Operative</h3>
<p class="card-text text-muted">
Il personale comunale visualizza una dashboard con le segnalazioni in ingresso. Possono prenderle in carico, comunicare con l'utente e assegnarle alle squadre di intervento sul territorio.
Gli operatori tecnici e logistici dell'Ente prendono in carico la segnalazione per l'immediata
istruttoria.
<br><br>
Il sistema gestisce l'intero flusso di stato: da <em>Aperta</em> a <em>In Revisione</em>, fino a <em>In Lavorazione</em> e <em>Risolta</em>.
La piattaforma provvede a instradare automaticamente l'intervento alla squadra specializzata di
turno in base alla
categoria del problema e all'area geografica, garantendo un canale diretto per le comunicazioni di
servizio e aggiornando in tempo reale lo stato dei lavori.
</p>
</div>
</div>
</div>
</div>
<!-- Amministratore -->
<div class="col-12 col-md-4 mb-4">
<div class="card-wrapper card-space h-100">
<div class="card card-bg h-100">
<div class="card-body">
<BIIcon name="it-settings" size="xl" color="primary" class="mb-3" />
<h3 class="card-title h5 font-weight-bold">Amministrazione</h3>
<BIIcon class="mb-3" color="primary" name="it-settings" size="xl"/>
<h3 class="card-title h5 font-weight-bold">L'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 dispongono del controllo completo sulle operazioni, con privilegi di gestione dei
profili e assegnazione delle nomine agli operatori.
<br><br>
Hanno inoltre accesso a statistiche avanzate per individuare le criticità sul territorio e monitorare i tempi medi di risoluzione.
L'Ente utilizza funzioni di ricerca avanzata e filtraggio per area geografica per prevenire le
duplicazioni
e si avvale di strumenti analitici per il monitoraggio continuo dei tempi medi di risoluzione e
dell'efficienza dei servizi.
</p>
</div>
</div>
@@ -100,68 +119,91 @@ useHead({
</div>
</div>
<!-- STACK TECNOLOGICO E FILOSOFIA -->
<div class="container my-5 py-4">
<div class="row align-items-center">
<div class="col-12 col-lg-6 mb-4 mb-lg-0">
<h2 class="font-weight-bold mb-4">Tecnologia e Indipendenza</h2>
<div class="col-12 col-lg-7 mb-4 mb-lg-0">
<h2 class="font-weight-bold mb-4">Sicurezza, Centralità e Conformità</h2>
<p class="mb-4">Per soddisfare gli elevati standard richiesti da un Ente Pubblico, il sistema adotta precise
scelte organizzative e architetturali:</p>
<ul class="it-list">
<li>
<BIIcon name="it-code-circle" color="primary" class="me-2" />
<strong>Architettura:</strong> Frontend reattivo e multipiattaforma sviluppato in <em>Vue.js/Nuxt 3</em>. Backend ad altissime prestazioni scritto in <em>C++</em> utilizzando il framework <em>Drogon</em>.
<li class="d-flex align-items-start mb-3">
<BIIcon class="me-3 mt-1 flex-shrink-0" color="primary" name="it-pa"/>
<div>
<strong>Modello Centralizzato:</strong> Tutta la gestione logica e la persistenza dei dati risiedono
lato server, garantendo tracciabilità totale dei passaggi di stato e convalida rigorosa dei permessi
utente.
</div>
</li>
<li class="mt-3">
<BIIcon name="it-lock" color="primary" class="me-2" />
<strong>Sicurezza:</strong> Login Passwordless (OTP nativo) e sistema di autorizzazione Role-Based basato su token JWT.
<li class="d-flex align-items-start mb-3">
<BIIcon class="me-3 mt-1 flex-shrink-0" color="primary" name="it-lock"/>
<div>
<strong>Sicurezza e Privacy:</strong> Tutte le comunicazioni sono interamente cifrate (tramite rigidi
protocolli crittografici) per garantire la massima conformità alle normative sulla protezione dei dati
personali.
</div>
</li>
<li class="mt-3">
<BIIcon name="it-piu" color="primary" class="me-2" />
<strong>Open Data:</strong> Piena aderenza alle linee guida AGID sulla trasparenza, con esportazione di dati anonimizzati accessibili al pubblico.
<li class="d-flex align-items-start mb-3">
<BIIcon class="me-3 mt-1 flex-shrink-0" color="primary" name="it-mail"/>
<div>
<strong>Accesso Operatori:</strong> Il personale tecnico comunale accede al sistema tramite un approccio
sicuro basato su One-Time Password (OTP) inviata sull'e-mail aziendale.
</div>
</li>
</ul>
</div>
<div class="col-12 col-lg-5 offset-lg-1">
<!-- Callout Ribellione Gitea -->
<div class="callout callout-highlight callout-warning">
<div class="col-12 col-lg-4 offset-lg-1">
<div class="callout callout-highlight callout-note">
<div class="callout-title">
<BIIcon name="it-warning-circle" />
Un approccio etico al codice sorgente
<BIIcon name="it-info-circle"/>
Customer Satisfaction Integrata
</div>
<p>
In risposta alle policy sempre più aggressive delle grandi piattaforme commerciali riguardo l'addestramento non consensuale di modelli di Intelligenza Artificiale sui repository privati, lo sviluppo di questo progetto è ospitato su un'istanza <strong>self-hosted di Gitea</strong>.
La piattaforma non si esaurisce con l'intervento tecnico, ma chiude il ciclo con un modulo dedicato alla
<strong>Valutazione della Qualità</strong>.
<br><br>
Una scelta di principio per garantire il controllo totale, la privacy e la vera sovranità sui dati e sul codice.
A risoluzione avvenuta, il cittadino viene invitato a esprimere un riscontro sulla tempestività e
sull'efficacia
del lavoro svolto, assicurando all'amministrazione un controllo qualità costante.
</p>
</div>
</div>
</div>
</div>
<!-- CREDITI ACCADEMICI (Footer Style Callout) -->
<div class="container mb-5 pb-5">
<div class="card-wrapper card-space">
<div class="card card-bg border-start border-primary border-5">
<div class="card-body">
<div class="row align-items-center">
<div class="col-12 col-md-8">
<h4 class="h5 font-weight-bold text-primary mb-2">Crediti Accademici</h4>
<div class="col-12 col-md-6 mb-4 mb-md-0">
<h4 class="h5 font-weight-bold text-primary mb-2">Il Team di Sviluppo</h4>
<p class="mb-1">
Questo progetto è stato realizzato nell'ambito del corso di <strong>Laboratorio di Programmazione</strong> (tenuto dal Prof. Vessio).
</p>
<p class="text-muted small mb-0">
Università degli Studi di Bari "Aldo Moro" - Dipartimento di Informatica.
Questo portale è stato ideato e sviluppato per facilitare il percorso di transizione digitale
e modernizzare l'infrastruttura telematica a disposizione della cittadinanza.
</p>
</div>
<div class="col-12 col-md-4 mt-3 mt-md-0 text-md-end">
<p class="font-weight-bold mb-1">Sviluppato da:</p>
<ul class="list-unstyled mb-0">
<li>Renato Loiacono</li>
<li>Michelangelo Parisi</li>
<li>Gabriele Schiraldi</li>
</ul>
<div class="col-12 col-md-6">
<div class="d-flex flex-wrap justify-content-md-end justify-content-center gap-4">
<div
v-for="member in sortedMembers"
:key="member.name"
class="d-flex flex-column align-items-center text-center"
style="max-width: 90px;"
>
<img
:alt="member.name"
:src="member.image"
class="rounded-circle mb-2 shadow-sm"
style="width: 72px; height: 72px; object-fit: cover; border: 2px solid #0066cc;"
>
<span class="font-weight-bold small" style="line-height: 1.2;">{{ member.name }}</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
@@ -170,9 +212,12 @@ useHead({
</template>
<style scoped>
/* Leggere correzioni stilistiche per le liste */
.it-list {
list-style-type: none;
padding-left: 0;
}
h2 {
text-align: center;
}
</style>
+117
View File
@@ -0,0 +1,117 @@
<script setup lang="ts">
definePageMeta({
layout: 'default'
})
useHead({ title: 'Intervento pubblico - Visione' })
const route = useRoute()
const runtimeConfig = useRuntimeConfig()
const token = computed(() => String(route.params.token || ''))
const { getPublicIntervention } = useOperator()
const { data, pending, error } = await useAsyncData(
`public-intervention-${token.value}`,
() => getPublicIntervention(token.value),
)
const payload = computed<any>(() => data.value || null)
const report = computed<any>(() => payload.value?.report || payload.value?.summary || payload.value?.intervention || payload.value)
const media = computed<any[]>(() => payload.value?.media || [])
const messages = computed<any[]>(() => payload.value?.latest_messages || payload.value?.messages || [])
const formatDate = (dateString?: string) => {
if (!dateString) return '-'
return new Date(dateString).toLocaleString('it-IT', {
day: '2-digit',
month: '2-digit',
year: 'numeric',
hour: '2-digit',
minute: '2-digit'
})
}
</script>
<template>
<div class="container my-5">
<div class="row justify-content-center">
<div class="col-12 col-lg-8">
<div v-if="pending" class="text-center py-5">
<div class="spinner-border text-primary" role="status"></div>
</div>
<div v-else-if="error || !report" class="card card-bg border-0 shadow-sm">
<div class="card-body py-5 text-center">
<BIIcon name="it-close-circle" size="lg" color="danger" class="mb-3" />
<h1 class="h4 mb-2">Link non disponibile</h1>
<p class="text-muted mb-0">Questo link di intervento non è valido, è scaduto oppure è stato revocato.</p>
</div>
</div>
<template v-else>
<div class="card card-bg border-0 shadow-sm mb-4">
<div class="card-body">
<h1 class="h4 mb-2">Intervento pubblico</h1>
<p class="text-muted mb-4">Scheda condivisa per team esterno.</p>
<div class="row g-3">
<div class="col-12 col-md-6">
<small class="text-muted d-block">Segnalazione</small>
<strong>#{{ report.id || '-' }}</strong>
</div>
<div class="col-12 col-md-6">
<small class="text-muted d-block">Categoria</small>
<strong>{{ report.category_name || '-' }}</strong>
</div>
<div class="col-12">
<small class="text-muted d-block">Indirizzo</small>
<strong>{{ report.address || '-' }}</strong>
</div>
<div class="col-12">
<small class="text-muted d-block">Descrizione</small>
<p class="mb-0">{{ report.description || '-' }}</p>
</div>
<div class="col-12 col-md-6">
<small class="text-muted d-block">Stato</small>
<strong>{{ report.status || '-' }}</strong>
</div>
<div class="col-12 col-md-6">
<small class="text-muted d-block">Aperta</small>
<strong>{{ formatDate(report.created_at) }}</strong>
</div>
</div>
</div>
</div>
<div v-if="media.length > 0" class="card card-bg border-0 shadow-sm mb-4">
<div class="card-body">
<h2 class="h6 mb-3">Allegati</h2>
<div class="row g-2">
<div v-for="item in media" :key="item.id" class="col-6 col-md-4">
<img
v-if="item.media_kind === 'IMAGE'"
:src="runtimeConfig.public.api + item.url"
class="img-fluid rounded border"
:alt="item.original_filename || 'Allegato'"
/>
</div>
</div>
</div>
</div>
<div v-if="messages.length > 0" class="card card-bg border-0 shadow-sm">
<div class="card-body">
<h2 class="h6 mb-3">Ultimi aggiornamenti</h2>
<ul class="list-unstyled mb-0">
<li v-for="message in messages" :key="message.id" class="border-bottom py-2">
<div class="small text-muted mb-1">{{ formatDate(message.created_at) }}</div>
<div>{{ message.body }}</div>
</li>
</ul>
</div>
</div>
</template>
</div>
</div>
</div>
</template>
-259
View File
@@ -1,259 +0,0 @@
<script setup lang="ts">
definePageMeta({
middleware: 'auth',
})
useHead({ title: 'Il Mio Profilo - Visione' })
const { user, fetchRewards } = useAuth()
// Fetch rewards/punti
const page = ref(1)
const perPage = ref(10)
const { data: rewardsData } = await useAsyncData(() =>
fetchRewards({ page: page.value, per_page: perPage.value })
)
const rewards = computed(() => (rewardsData.value as any)?.reward_events || [])
const totalPoints = computed(() => (rewardsData.value as any)?.points || 0)
const totalRewards = computed(() => rewards.value.length)
const handlePageChange = (newPage: number) => {
page.value = newPage
}
const formatDate = (dateString: string): string => {
return new Date(dateString).toLocaleDateString('it-IT', {
day: '2-digit',
month: '2-digit',
year: 'numeric',
})
}
const handleLogout = () => {
useAuth().logout()
}
</script>
<template>
<div>
<!-- HERO -->
<div class="bg-light border-bottom py-4 mb-5">
<div class="container">
<div class="row">
<div class="col-12">
<h1 class="h3 font-weight-bold mb-3">Il Mio Profilo</h1>
<p class="text-muted">Gestisci i tuoi dati, visualizza i tuoi punti e la cronologia delle segnalazioni</p>
</div>
</div>
</div>
</div>
<!-- CONTENUTO -->
<div class="container mb-5">
<div class="row">
<!-- SINISTRA: Profilo -->
<div class="col-12 col-lg-8">
<!-- DATI PERSONALI -->
<div class="card card-bg mb-4">
<div class="card-body">
<div class="d-flex align-items-center justify-content-between mb-4">
<h5 class="card-title font-weight-bold mb-0">
<BIIcon name="it-user" size="sm" color="primary" class="me-2" />
Dati Personali
</h5>
<NuxtLink to="/settings/profile" class="btn btn-sm btn-outline-primary">
<BIIcon name="it-pencil" size="xs" class="me-1" />
Modifica
</NuxtLink>
</div>
<div class="row">
<div class="col-md-6 mb-3">
<small class="text-muted d-block">Nome</small>
<strong>{{ user?.first_name }}</strong>
</div>
<div class="col-md-6 mb-3">
<small class="text-muted d-block">Cognome</small>
<strong>{{ user?.last_name }}</strong>
</div>
<div class="col-md-6 mb-3">
<small class="text-muted d-block">Email</small>
<strong>{{ user?.email }}</strong>
</div>
<div class="col-md-6 mb-3">
<small class="text-muted d-block">Codice Fiscale</small>
<strong>{{ user?.fiscal_code }}</strong>
</div>
<div class="col-md-6 mb-3">
<small class="text-muted d-block">Telefono</small>
<strong>{{ user?.phone || 'Non fornito' }}</strong>
</div>
<div class="col-md-6 mb-3">
<small class="text-muted d-block">Ruolo</small>
<span class="badge bg-info">{{ user?.role }}</span>
</div>
</div>
</div>
</div>
<!-- PUNTI CITTADINO -->
<div class="card card-bg card-highlight mb-4">
<div class="card-body">
<h5 class="card-title font-weight-bold mb-4">
<BIIcon name="it-star" size="sm" color="warning" class="me-2" />
I Tuoi Punti Cittadino
</h5>
<div class="text-center p-4 bg-light rounded mb-4">
<div class="display-3 font-weight-bold text-primary">{{ totalPoints }}</div>
<small class="text-muted">Segnalazioni risolte completate con successo</small>
</div>
<div class="alert alert-info" role="alert">
<small>
<strong>Come guadagni punti?</strong><br>
Ricevi 1 punto per ogni segnalazione che risolviamo. Quando raggiungi determinati traguardi, potrai sbloccare riconoscimenti speciali!
</small>
</div>
</div>
</div>
<!-- CRONOLOGIA PUNTI -->
<div class="card card-bg">
<div class="card-body">
<h5 class="card-title font-weight-bold mb-4">
<BIIcon name="it-history" size="sm" color="primary" class="me-2" />
Cronologia Punti (ultimi {{ rewards.length }})
</h5>
<div v-if="rewards.length === 0" class="alert alert-info" role="alert">
Non hai ancora accumulato punti. Crea la tua prima segnalazione!
</div>
<div v-else class="table-responsive">
<table class="table table-hover mb-0">
<thead class="table-light">
<tr>
<th scope="col" class="small">Data</th>
<th scope="col" class="small">Segnalazione</th>
<th scope="col" class="text-center small">Punti</th>
<th scope="col" class="small">Motivo</th>
</tr>
</thead>
<tbody>
<tr v-for="reward in rewards" :key="reward.id">
<td class="small">
<small class="text-muted">{{ formatDate(reward.created_at) }}</small>
</td>
<td class="small">
<NuxtLink :to="`/reports/${reward.report_id}`" class="text-decoration-none">
#{{ reward.report_id }}
</NuxtLink>
</td>
<td class="text-center">
<span class="badge bg-success">+{{ reward.points }}</span>
</td>
<td class="small">{{ reward.reason }}</td>
</tr>
</tbody>
</table>
</div>
<!-- PAGINATION -->
<Pagination
v-if="rewards.length > 0"
:current-page="page"
:per-page="perPage"
:total-items="totalRewards"
@page-change="handlePageChange"
/>
</div>
</div>
</div>
<!-- DESTRA: Azioni rapide -->
<div class="col-12 col-lg-4">
<!-- NUOVA SEGNALAZIONE -->
<div class="card card-bg card-highlight mb-4">
<div class="card-body text-center">
<BIIcon name="it-plus-circle" size="xl" color="primary" class="mb-3" />
<h6 class="font-weight-bold mb-3">Crea una nuova segnalazione</h6>
<p class="small text-muted mb-3">Aiutaci a migliorare il tuo quartiere</p>
<NuxtLink to="/reports/create" class="btn btn-primary w-100">
Segnala ora
</NuxtLink>
</div>
</div>
<!-- LE MIE SEGNALAZIONI -->
<div class="card card-bg mb-4">
<div class="card-body">
<h6 class="card-title font-weight-bold mb-3">
<BIIcon name="it-list" size="sm" color="primary" class="me-2" />
Le Mie Segnalazioni
</h6>
<NuxtLink to="/dashboard" class="btn btn-outline-primary w-100 btn-sm">
Vai alla Dashboard
</NuxtLink>
</div>
</div>
<!-- NOTIFICHE -->
<div class="card card-bg mb-4">
<div class="card-body">
<h6 class="card-title font-weight-bold mb-3">
<BIIcon name="it-bell" size="sm" color="primary" class="me-2" />
Centro Notifiche
</h6>
<NuxtLink to="/notifications" class="btn btn-outline-primary w-100 btn-sm">
Visualizza notifiche
</NuxtLink>
</div>
</div>
<!-- IMPOSTAZIONI & LOGOUT -->
<div class="card card-bg">
<div class="card-body">
<h6 class="card-title font-weight-bold mb-3">
<BIIcon name="it-settings" size="sm" color="primary" class="me-2" />
Account
</h6>
<NuxtLink to="/settings/password" class="btn btn-outline-secondary w-100 btn-sm mb-2">
Cambia Password
</NuxtLink>
<button type="button" class="btn btn-outline-danger w-100 btn-sm" @click="handleLogout">
Logout
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<style scoped>
.card-highlight {
border-color: #ffc107;
}
.display-3 {
font-size: 3.5rem;
line-height: 1;
}
.table-hover tbody tr:hover {
background-color: rgba(0, 111, 157, 0.05);
}
</style>
-3
View File
@@ -6,7 +6,6 @@ useHead({
<template>
<div>
<!-- HERO SECTION -->
<div class="it-hero-wrapper it-primary">
<div class="container">
<div class="row">
@@ -22,7 +21,6 @@ useHead({
</div>
</div>
<!-- CONTENUTO PRINCIPALE -->
<div class="container my-5 py-4">
<div class="row">
<div class="col-12 col-lg-8 offset-lg-2">
@@ -53,7 +51,6 @@ useHead({
Gli operatori e gli amministratori di sistema si riservano il diritto di moderare, nascondere o rimuovere segnalazioni contenenti materiale inappropriato, offensivo, non pertinente o illegale. L'abuso ripetuto del sistema comporterà il ban permanente dell'account dell'utente, associato al proprio Codice Fiscale.
</p>
<!-- DISCLAIMER ACCADEMICO -->
<div class="callout callout-highlight callout-info mt-5">
<div class="callout-title">
<BIIcon name="it-info-circle" />
+53 -70
View File
@@ -1,11 +1,13 @@
<script setup lang="ts">
import type { Notification } from '~/types/api'
definePageMeta({
middleware: 'auth',
})
useHead({ title: 'Notifiche - Visione' })
const { fetchNotifications, markNotificationRead } = useAuth()
const { fetchNotifications, markNotificationRead, refreshUnreadNotifications } = useAuth()
const router = useRouter()
const page = ref(1)
@@ -13,27 +15,25 @@ const perPage = ref(15)
const { data: notificationsData, refresh: refreshNotifications } = await useAsyncData(
'notifications',
() => fetchNotifications({ page: page.value, per_page: perPage.value })
() => fetchNotifications({ page: page.value, per_page: perPage.value }),
{ watch: [page] }
)
const notifications = computed(() => notificationsData.value?.notifications || [])
const notifications = computed<Notification[]>(() => notificationsData.value?.notifications || [])
const totalNotifications = computed(() => notificationsData.value?.notifications?.length || 0)
const unreadCount = computed(() => notifications.value.filter((n: any) => !n.read_at).length)
const handlePageChange = (newPage: number) => {
page.value = newPage
}
const unreadCount = computed(() => notifications.value.filter((notification) => !notification.read_at).length)
const handleMarkAsRead = async (notificationId: number) => {
try {
await markNotificationRead(notificationId)
await refreshNotifications()
await refreshUnreadNotifications()
} catch (error) {
console.error('Error marking notification as read:', error)
}
}
const handleNotificationClick = async (notification: any) => {
const handleNotificationClick = async (notification: Notification) => {
if (!notification.read_at) {
await handleMarkAsRead(notification.id)
}
@@ -92,7 +92,6 @@ const getNotificationColor = (type: string): string => {
<template>
<div>
<!-- HERO -->
<div class="bg-light border-bottom py-4 mb-4">
<div class="container">
<div class="row">
@@ -109,75 +108,65 @@ const getNotificationColor = (type: string): string => {
</div>
</div>
<!-- CONTENUTO -->
<div class="container mb-5">
<div class="row">
<div class="col-12 col-lg-10 offset-lg-1">
<!-- FILTRI (Opzionale) -->
<div class="d-flex gap-2 mb-4">
<button class="btn btn-sm btn-outline-primary active">Tutti</button>
<button class="btn btn-sm btn-outline-secondary">Solo non letti</button>
<div v-if="notifications.length === 0" class="card card-bg border-0 shadow-sm">
<div class="card-body py-5 text-center">
<BIIcon name="it-bell" size="lg" color="secondary" class="mb-3 d-block mx-auto" />
<h2 class="h5 mb-2">Nessuna notifica</h2>
<p class="text-muted mb-3">Quando arriveranno aggiornamenti sulle tue segnalazioni, li troverai qui.</p>
<NuxtLink to="/reports" class="btn btn-outline-primary btn-sm">
Vai alle segnalazioni
</NuxtLink>
</div>
</div>
<!-- LISTA NOTIFICHE -->
<div v-if="notifications.length === 0" class="text-center py-5">
<BIIcon name="it-bell" size="xl" color="info" class="mb-3 d-block" />
<h6 class="text-muted">Nessuna notifica</h6>
<p class="small text-muted">Quando riceverai nuovi aggiornamenti sulle tue segnalazioni, appariranno qui.</p>
</div>
<div v-else class="list-group">
<button
<div v-else class="card card-bg border-0 shadow-sm">
<div class="card-body p-0">
<div
v-for="notification in notifications"
:key="notification.id"
type="button"
class="list-group-item list-group-item-action border-0 p-3 mb-3 rounded-2"
:class="{
'bg-light': !notification.read_at,
'bg-white': notification.read_at,
}"
@click="handleNotificationClick(notification)"
class="notification-row p-3"
:class="{ 'notification-row-unread': !notification.read_at }"
>
<div class="d-flex align-items-start gap-3">
<!-- ICONA -->
<div class="flex-shrink-0 mt-1">
<div class="rounded-circle p-2" :class="`bg-${getNotificationColor(notification.type)}`" style="width: 40px; height: 40px; display: flex; align-items: center; justify-content: center;">
<div
class="rounded-circle d-flex align-items-center justify-content-center notification-icon"
:class="`bg-${getNotificationColor(notification.type)}`"
>
<BIIcon :name="getNotificationIcon(notification.type)" size="sm" color="white" />
</div>
</div>
<!-- CONTENUTO -->
<div class="flex-grow-1">
<div class="d-flex align-items-start justify-content-between">
<div class="d-flex flex-wrap justify-content-between gap-2">
<div>
<h6 class="mb-1 font-weight-bold" :class="{ 'text-dark': !notification.read_at }">
{{ notification.title }}
</h6>
<p class="mb-1 small" :class="{ 'text-muted': notification.read_at }">
{{ notification.body }}
</p>
<small class="text-muted">
{{ formatDate(notification.created_at) }}
</small>
<h2 class="h6 mb-1">{{ notification.title }}</h2>
<p class="mb-1 text-muted">{{ notification.body }}</p>
<small class="text-muted">{{ formatDate(notification.created_at) }}</small>
</div>
<!-- INDICATORE NON LETTO -->
<div v-if="!notification.read_at" class="flex-shrink-0">
<span class="badge bg-primary rounded-pill">Nuovo</span>
<span class="badge bg-primary">Nuovo</span>
</div>
</div>
<!-- AZIONI RAPIDE -->
<div v-if="notification.report_id" class="mt-2 d-flex gap-2">
<NuxtLink :to="`/reports/${notification.report_id}`" class="btn btn-sm btn-outline-primary">
<BIIcon name="it-arrow-right" size="xs" class="me-1" />
<div class="mt-3 d-flex flex-wrap gap-2">
<button
type="button"
class="btn btn-outline-primary btn-sm"
@click="handleNotificationClick(notification)"
>
Apri notifica
</button>
<NuxtLink v-if="notification.report_id" :to="`/reports/${notification.report_id}`" class="btn btn-outline-primary btn-sm">
Vedi segnalazione
</NuxtLink>
<button
v-if="!notification.read_at"
type="button"
class="btn btn-sm btn-outline-secondary"
class="btn btn-outline-secondary btn-sm"
@click.stop="handleMarkAsRead(notification.id)"
>
Segna come letta
@@ -185,16 +174,16 @@ const getNotificationColor = (type: string): string => {
</div>
</div>
</div>
</button>
</div>
</div>
</div>
<!-- PAGINATION -->
<Pagination
v-if="notifications.length > 0"
:current-page="page"
:per-page="perPage"
:total-items="totalNotifications"
@page-change="handlePageChange"
@page-change="page = $event"
/>
</div>
@@ -205,23 +194,17 @@ const getNotificationColor = (type: string): string => {
</template>
<style scoped>
.list-group-item {
border: 1px solid #e9ecef;
transition: all 0.2s ease;
cursor: pointer;
&:hover {
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
transform: translateY(-1px);
.notification-row + .notification-row {
border-top: 1px solid #e9ecef;
}
&.bg-light {
border-left: 4px solid #006f9d;
}
.notification-row-unread {
border-left: 4px solid #0066cc;
background: #f8fbff;
}
.rounded-2 {
border-radius: 0.5rem;
.notification-icon {
width: 40px;
height: 40px;
}
</style>
+167 -73
View File
@@ -1,53 +1,154 @@
<script setup lang="ts">
import { ref, computed } from 'vue'
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue'
import type { CircleMarker, LatLngBoundsExpression, Map as LeafletMap } from 'leaflet'
import { BARI_BOUNDS, BARI_CENTER, isWithinBariBounds } from '~/utils/bari'
// 1. API Fetching Logic
const { getOpenDataReports } = usePublic()
// Reactive pagination state
const currentPage = ref(1)
const perPage = ref(9)
// Fetch data automatically when currentPage changes
const { data: openDataResponse, pending } = await useAsyncData(
'open-data-reports',
() => getOpenDataReports({ page: currentPage.value, per_page: perPage.value }),
{ watch: [currentPage] } // Nuxt will re-fetch when currentPage changes
() => getOpenDataReports({ page: 1, per_page: 200 })
)
// Pagination logic: If we receive less items than `perPage`, we are on the last page.
const isLastPage = computed(() => {
if (!openDataResponse.value?.reports) return true
return openDataResponse.value.reports.length < perPage.value
const allVisibleReports = computed(() =>
(openDataResponse.value?.reports || []).filter((report) => isWithinBariBounds(report.latitude, report.longitude))
)
const visibleReports = computed(() => {
const start = (currentPage.value - 1) * perPage.value
const end = start + perPage.value
return allVisibleReports.value.slice(start, end)
})
const nextPage = () => {
if (!isLastPage.value) currentPage.value++
}
const prevPage = () => {
if (currentPage.value > 1) currentPage.value--
const handlePageChange = (page: number) => {
currentPage.value = page
}
// 2. View Toggle (Grid vs Map)
const mapVisibleReports = computed(() => allVisibleReports.value)
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) => {
switch (status) {
case 'RESOLVED': return { class: 'bg-success', text: 'Risolto', icon: 'it-check-circle' }
case 'CLOSED': return { class: 'bg-secondary', text: 'Chiuso', icon: 'it-lock' }
default: return { class: 'bg-info', text: status, icon: 'it-info-circle' }
case 'RESOLVED':
return { class: 'bg-success', text: 'Risolto', icon: 'it-check-circle' }
case 'CLOSED':
return { class: 'bg-secondary', text: 'Chiuso', icon: 'it-lock' }
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 (mapVisibleReports.value.length === 0) {
map.setView(BARI_CENTER, 12)
return
}
mapVisibleReports.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 = mapVisibleReports.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()
if (!map) {
await initMap()
} else {
map.invalidateSize()
await renderMapMarkers()
}
})
watch(mapVisibleReports, async () => {
if (currentView.value === 'map' && map) {
await renderMapMarkers()
}
})
onBeforeUnmount(() => {
clearMarkers()
map?.remove()
map = null
})
</script>
<template>
<div>
<!-- HERO SECTION (Small version for internal pages) -->
<div class="it-hero-wrapper it-primary">
<div class="container">
<div class="row">
<div class="col-12">
<div class="col-12 text-center">
<div class="it-hero-text-wrapper p-4">
<h1 class="text-white font-weight-bold">Open Data Interventi</h1>
<p class="text-white mt-2 lead">
@@ -59,19 +160,15 @@ const getStatusBadge = (status: string) => {
</div>
</div>
<!-- MAIN CONTENT -->
<div class="container my-5">
<!-- TOOLBAR: View Toggles & Export -->
<div class="container my-5" id="grid-start">
<div class="row align-items-center mb-5 pb-3 border-bottom">
<div class="col-12 col-md-6 mb-3 mb-md-0 d-flex gap-2">
<!-- View Toggle Buttons -->
<button
class="btn btn-sm"
:class="currentView === 'grid' ? 'btn-primary' : 'btn-outline-primary'"
@click="currentView = 'grid'"
>
<BIIcon name="it-grid" size="sm" class="me-1" :color="currentView === 'grid' ? 'white' : 'primary'" />
<BIIcon :color="currentView === 'grid' ? 'white' : 'primary'" class="me-1" name="it-grid" size="sm"/>
Griglia Dati
</button>
<button
@@ -79,49 +176,45 @@ const getStatusBadge = (status: string) => {
:class="currentView === 'map' ? 'btn-primary' : 'btn-outline-primary'"
@click="currentView = 'map'"
>
<BIIcon name="it-map-marker" size="sm" class="me-1" :color="currentView === 'map' ? 'white' : 'primary'" />
<BIIcon :color="currentView === 'map' ? 'white' : 'primary'" class="me-1" name="it-map-marker" size="sm"/>
Mappa
</button>
</div>
<div class="col-12 col-md-6 text-md-end">
<!-- Fake Export CTA (Very common in Open Data portals) -->
<button class="btn btn-sm btn-outline-secondary" title="Scarica dataset in formato JSON">
<BIIcon name="it-download" size="sm" class="me-1" />
<BIIcon class="me-1" name="it-download" size="sm"/>
Scarica JSON
</button>
</div>
</div>
<!-- LOADER -->
<div v-if="pending" class="d-flex justify-content-center my-5 py-5">
<div class="progress-spinner progress-spinner-active" role="status">
<span class="visually-hidden">Caricamento in corso...</span>
</div>
</div>
<!-- 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">
<!-- Strict BI Card -->
<div v-show="!pending && currentView === 'grid'">
<div class="row" v-if="allVisibleReports.length > 0">
<div class="col-12 col-md-6 col-lg-4 mb-4" v-for="report in visibleReports" :key="report.id">
<div class="card-wrapper card-space h-100">
<div class="card card-bg h-100 shadow-sm">
<div class="card-body d-flex flex-column">
<div class="d-flex justify-content-between align-items-start mb-3">
<div class="category-top m-0">
<span class="badge rounded-pill text-white px-3 py-1" :class="getStatusBadge(report.status).class">
<BIIcon :name="getStatusBadge(report.status).icon" size="xs" color="white" class="me-1" />
<span :class="getStatusBadge(report.status).class"
class="badge rounded-pill text-white px-3 py-1">
<BIIcon :name="getStatusBadge(report.status).icon" class="me-1" color="white" size="xs"/>
{{ getStatusBadge(report.status).text }}
</span>
</div>
<span class="text-muted small">ID: #{{ report.id }}</span>
</div>
<h3 class="card-title h5 font-weight-bold">{{ report.category_name }}</h3>
<p class="card-text text-muted mb-4">
<BIIcon name="it-map-marker-circle" size="sm" class="me-1" />
<BIIcon class="me-1" name="it-map-marker-circle" size="sm"/>
{{ report.area_name || 'Area comunale non specificata' }}
</p>
@@ -148,40 +241,26 @@ const getStatusBadge = (status: string) => {
Nessun dato pubblico disponibile al momento.
</div>
<!-- BOOTSTRAP ITALIA PAGINATION -->
<nav class="pagination-wrapper justify-content-center mt-5" aria-label="Navigazione pagine open data">
<ul class="pagination">
<li class="page-item" :class="{ disabled: currentPage === 1 }">
<a class="page-link" href="#" tabindex="-1" aria-disabled="true" @click.prevent="prevPage">
<BIIcon name="it-chevron-left" size="sm" />
<span class="visually-hidden">Pagina precedente</span>
</a>
</li>
<li class="page-item">
<span class="page-link font-weight-semibold">Pagina {{ currentPage }}</span>
</li>
<li class="page-item" :class="{ disabled: isLastPage }">
<a class="page-link" href="#" @click.prevent="nextPage">
<span class="visually-hidden">Pagina successiva</span>
<BIIcon name="it-chevron-right" size="sm" />
</a>
</li>
</ul>
</nav>
<Pagination
v-if="allVisibleReports.length > 0"
:current-page="currentPage"
:per-page="perPage"
:total-items="allVisibleReports.length"
@page-change="handlePageChange"
/>
</div>
<!-- MAP VIEW (Placeholder for Leaflet/Mapbox) -->
<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 v-show="!pending && currentView === 'map'" class="map-view-wrapper">
<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">
<template v-if="pending">Caricamento...</template>
<template v-else>{{ mapVisibleReports.length }} punti</template>
</span>
</div>
<ClientOnly>
<div ref="mapContainer" class="open-data-map rounded border"></div>
</ClientOnly>
</div>
</div>
@@ -189,16 +268,31 @@ const getStatusBadge = (status: string) => {
</template>
<style scoped>
/* Ensures the cards inside the grid stretch to equal heights */
.card-wrapper {
height: 100%;
}
.card-bg {
border: 1px solid rgba(0, 0, 0, 0.05);
transition: transform 0.2s ease, box-shadow 0.2s ease;
}
.card-bg:hover {
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>
+8 -36
View File
@@ -1,6 +1,4 @@
<script setup lang="ts">
import type { Report } from '~/types/api'
definePageMeta({
middleware: 'auth',
auth: { role: 'OPERATOR' }
@@ -19,7 +17,6 @@ const { data: reportsRes, pending } = useAsyncData(
{ watch: [page] }
)
const formatDate = (dateString: string) => new Date(dateString).toLocaleDateString('it-IT')
</script>
<template>
@@ -28,7 +25,7 @@ const formatDate = (dateString: string) => new Date(dateString).toLocaleDateStri
<h1 class="h3 font-weight-bold mb-0">Le Mie Assegnazioni</h1>
<div>
<NuxtLink to="/dashboard" class="btn btn-outline-secondary btn-sm me-2">Dashboard</NuxtLink>
<NuxtLink to="/operator" class="btn btn-outline-primary btn-sm">Coda Open</NuxtLink>
<NuxtLink to="/operator" class="btn btn-outline-primary btn-sm">Segnalazioni disponibili</NuxtLink>
</div>
</div>
@@ -41,42 +38,17 @@ const formatDate = (dateString: string) => new Date(dateString).toLocaleDateStri
</div>
<div v-else>
<div class="table-responsive">
<table class="table table-hover border-bottom">
<thead class="table-light">
<tr>
<th scope="col" class="small">#ID</th>
<th scope="col" class="small">Categoria</th>
<th scope="col" class="small">Indirizzo</th>
<th scope="col" class="small">Stato</th>
<th scope="col" class="small">Creata il</th>
<th scope="col" class="text-center small">Azioni</th>
</tr>
</thead>
<tbody>
<tr v-for="report in reportsRes.reports" :key="report.id" class="align-middle">
<td class="small font-weight-semibold">#{{ report.id }}</td>
<td class="small">{{ report.category_name }}</td>
<td class="small">{{ report.address }}</td>
<td class="small">
<StatusBadge :status="report.status" />
</td>
<td class="small text-muted">{{ formatDate(report.created_at) }}</td>
<td class="text-center">
<NuxtLink :to="`/operator/reports/${report.id}`" class="btn btn-sm btn-outline-primary">
Gestisci
</NuxtLink>
</td>
</tr>
</tbody>
</table>
</div>
<ReportTable
:reports="reportsRes.reports"
detail-base-path="/operator/reports"
action-label="Apri segnalazione"
/>
<Pagination
v-if="reportsRes.total > perPage"
v-if="(reportsRes.total || 0) > perPage"
:current-page="page"
:per-page="perPage"
:total-items="reportsRes.total"
:total-items="reportsRes.total!"
@page-change="page = $event"
/>
</div>
+9 -50
View File
@@ -1,6 +1,4 @@
<script setup lang="ts">
import type { Report } from '~/types/api'
definePageMeta({
middleware: 'auth',
auth: { role: 'OPERATOR' }
@@ -8,36 +6,22 @@ definePageMeta({
useHead({ title: 'Segnalazioni Aperte - Operatore' })
const { getOpenReports, takeReport } = useOperator()
const { getOpenReports } = useOperator()
const page = ref(1)
const perPage = ref(10)
const { data: reportsRes, pending, refresh } = useAsyncData(
const { data: reportsRes, pending } = useAsyncData(
'operator-open-reports',
() => getOpenReports({ page: page.value, per_page: perPage.value }),
{ watch: [page] }
)
const handleTakeReport = async (id: number) => {
try {
const res = await takeReport(id)
if (res.ok) {
// Optimistic update or refresh
await refresh()
}
} catch (err) {
console.error('Failed to take report', err)
}
}
const formatDate = (dateString: string) => new Date(dateString).toLocaleDateString('it-IT')
</script>
<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">Segnalazioni da prendere in carico (OPEN)</h1>
<h1 class="h3 font-weight-bold mb-0">Segnalazioni da valutare</h1>
<div>
<NuxtLink to="/dashboard" class="btn btn-outline-secondary btn-sm me-2">Dashboard</NuxtLink>
<NuxtLink to="/operator/assigned" class="btn btn-outline-primary btn-sm">Le mie assegnazioni</NuxtLink>
@@ -49,40 +33,15 @@ const formatDate = (dateString: string) => new Date(dateString).toLocaleDateStri
</div>
<div v-else-if="!reportsRes?.reports || reportsRes.reports.length === 0" class="alert alert-info">
Non ci sono segnalazioni aperte in questo momento.
Non ci sono segnalazioni disponibili in questo momento.
</div>
<div v-else>
<div class="table-responsive">
<table class="table table-hover border-bottom">
<thead class="table-light">
<tr>
<th scope="col" class="small">#ID</th>
<th scope="col" class="small">Categoria</th>
<th scope="col" class="small">Indirizzo</th>
<th scope="col" class="small">Stato</th>
<th scope="col" class="small">Creata il</th>
<th scope="col" class="text-center small">Azioni</th>
</tr>
</thead>
<tbody>
<tr v-for="report in reportsRes.reports" :key="report.id" class="align-middle">
<td class="small font-weight-semibold">#{{ report.id }}</td>
<td class="small">{{ report.category_name }}</td>
<td class="small">{{ report.address }}</td>
<td class="small">
<StatusBadge :status="report.status" />
</td>
<td class="small text-muted">{{ formatDate(report.created_at) }}</td>
<td class="text-center">
<button class="btn btn-primary btn-sm" @click="handleTakeReport(report.id)">
Prendi in carico
</button>
</td>
</tr>
</tbody>
</table>
</div>
<ReportTable
:reports="reportsRes.reports"
detail-base-path="/operator/reports"
action-label="Visualizza"
/>
<Pagination
v-if="reportsRes.total > perPage"
+6 -34
View File
@@ -1,6 +1,4 @@
<script setup lang="ts">
import type { Report } from '~/types/api'
definePageMeta({
middleware: 'auth',
auth: { role: 'OPERATOR' }
@@ -19,7 +17,6 @@ const { data: reportsRes, pending } = useAsyncData(
{ watch: [page] }
)
const formatDate = (dateString: string) => new Date(dateString).toLocaleDateString('it-IT')
</script>
<template>
@@ -28,7 +25,7 @@ const formatDate = (dateString: string) => new Date(dateString).toLocaleDateStri
<h1 class="h3 font-weight-bold mb-0">Gestite da altri Operatori</h1>
<div>
<NuxtLink to="/dashboard" class="btn btn-outline-secondary btn-sm me-2">Dashboard</NuxtLink>
<NuxtLink to="/operator" class="btn btn-outline-primary btn-sm">Coda Open</NuxtLink>
<NuxtLink to="/operator" class="btn btn-outline-primary btn-sm">Segnalazioni disponibili</NuxtLink>
</div>
</div>
@@ -41,36 +38,11 @@ const formatDate = (dateString: string) => new Date(dateString).toLocaleDateStri
</div>
<div v-else>
<div class="table-responsive">
<table class="table table-hover border-bottom">
<thead class="table-light">
<tr>
<th scope="col" class="small">#ID</th>
<th scope="col" class="small">Categoria</th>
<th scope="col" class="small">Indirizzo</th>
<th scope="col" class="small">Stato</th>
<th scope="col" class="small">Creata il</th>
<th scope="col" class="text-center small">Dettagli</th>
</tr>
</thead>
<tbody>
<tr v-for="report in reportsRes.reports" :key="report.id" class="align-middle">
<td class="small font-weight-semibold">#{{ report.id }}</td>
<td class="small">{{ report.category_name }}</td>
<td class="small">{{ report.address }}</td>
<td class="small">
<StatusBadge :status="report.status" />
</td>
<td class="small text-muted">{{ formatDate(report.created_at) }}</td>
<td class="text-center">
<NuxtLink :to="`/operator/reports/${report.id}`" class="btn btn-sm btn-outline-secondary">
Vedi
</NuxtLink>
</td>
</tr>
</tbody>
</table>
</div>
<ReportTable
:reports="reportsRes.reports"
detail-base-path="/operator/reports"
action-label="Apri segnalazione"
/>
<Pagination
v-if="reportsRes.total > perPage"
File diff suppressed because it is too large Load Diff
+1 -3
View File
@@ -6,7 +6,6 @@ useHead({
<template>
<div>
<!-- HERO SECTION -->
<div class="it-hero-wrapper it-primary">
<div class="container">
<div class="row">
@@ -22,7 +21,6 @@ useHead({
</div>
</div>
<!-- CONTENUTO PRINCIPALE -->
<div class="container my-5 py-4">
<div class="row">
<div class="col-12 col-lg-8 offset-lg-2">
@@ -48,7 +46,7 @@ useHead({
<h2 class="h3 font-weight-bold mb-3">3. Finalità del Trattamento</h2>
<p class="text-muted mb-4">
I dati forniti verranno trattati esclusivamente per le seguenti finalità:
<br>- Consentire la registrazione e l'autenticazione sicura (incluso login Passwordless tramite OTP).
<br>- Consentire la registrazione e l'autenticazione sicura tramite OTP.
<br>- Gestire la presa in carico e la risoluzione delle segnalazioni urbane da parte delle squadre operative.
<br>- Fornire comunicazioni di servizio relative allo stato di avanzamento delle segnalazioni.
<br>- Attribuire punteggi virtuali all'utente nell'ambito del sistema di <em>Gamification</em> volto a incentivare la cittadinanza attiva.
+162
View File
@@ -0,0 +1,162 @@
<script setup lang="ts">
definePageMeta({
middleware: 'auth',
})
useHead({ title: 'Profilo - Visione' })
const { user, fetchRewards, logout } = useAuth()
const page = ref(1)
const perPage = ref(10)
const { data: rewardsData } = await useAsyncData(
'profile-rewards',
() => fetchRewards({ page: page.value, per_page: perPage.value }),
{ watch: [page] }
)
const rewards = computed(() => rewardsData.value?.reward_events || [])
const totalPoints = computed(() => rewardsData.value?.points || 0)
const totalRewards = computed(() => rewards.value.length)
const formatDate = (dateString: string) =>
new Date(dateString).toLocaleDateString('it-IT', {
day: '2-digit',
month: '2-digit',
year: 'numeric',
})
</script>
<template>
<div>
<div class="bg-light border-bottom py-4 mb-4">
<div class="container">
<h1 class="h3 font-weight-bold mb-1">Profilo</h1>
<p class="text-muted mb-0">Dati account, punti cittadino e impostazioni personali.</p>
</div>
</div>
<div class="container mb-5">
<div class="row g-4">
<div class="col-12 col-lg-8">
<div class="card card-bg mb-4">
<div class="card-body">
<div class="d-flex justify-content-between align-items-center mb-3">
<h2 class="h5 card-title mb-0">Dati personali</h2>
<NuxtLink to="/settings/profile" class="btn btn-outline-primary btn-sm">
Modifica
</NuxtLink>
</div>
<div class="row">
<div class="col-md-6 mb-3">
<small class="text-muted d-block">Nome</small>
<strong>{{ user?.first_name }}</strong>
</div>
<div class="col-md-6 mb-3">
<small class="text-muted d-block">Cognome</small>
<strong>{{ user?.last_name }}</strong>
</div>
<div class="col-md-6 mb-3">
<small class="text-muted d-block">Email</small>
<strong>{{ user?.email }}</strong>
</div>
<div class="col-md-6 mb-3">
<small class="text-muted d-block">Telefono</small>
<strong>{{ user?.phone || 'Non fornito' }}</strong>
</div>
<div class="col-md-6 mb-0">
<small class="text-muted d-block">Codice fiscale</small>
<strong>{{ user?.fiscal_code }}</strong>
</div>
<div class="col-md-6 mb-0">
<small class="text-muted d-block">Ruolo</small>
<span class="badge bg-info">{{ normalizeRole(user?.role) }}</span>
</div>
</div>
</div>
</div>
<div class="card card-bg">
<div class="card-body">
<div class="d-flex justify-content-between align-items-center mb-3">
<h2 class="h5 card-title mb-0">Cronologia punti</h2>
<span class="badge bg-primary">{{ totalPoints }} punti</span>
</div>
<div v-if="rewards.length === 0" class="alert alert-info mb-0" role="alert">
Nessun punto registrato.
</div>
<template v-else>
<div class="table-responsive">
<table class="table table-hover mb-0">
<thead class="table-light">
<tr>
<th scope="col">Data</th>
<th scope="col">Segnalazione</th>
<th scope="col">Motivo</th>
<th scope="col" class="text-end">Punti</th>
</tr>
</thead>
<tbody>
<tr v-for="reward in rewards" :key="reward.id">
<td class="text-muted">{{ formatDate(reward.created_at) }}</td>
<td>
<NuxtLink :to="`/reports/${reward.report_id}`">#{{ reward.report_id }}</NuxtLink>
</td>
<td>{{ reward.reason }}</td>
<td class="text-end">
<span class="badge bg-success">+{{ reward.points }}</span>
</td>
</tr>
</tbody>
</table>
</div>
<Pagination
v-if="totalRewards > perPage"
:current-page="page"
:per-page="perPage"
:total-items="totalRewards"
@page-change="page = $event"
/>
</template>
</div>
</div>
</div>
<div class="col-12 col-lg-4">
<div class="card card-bg mb-4">
<div class="card-body">
<h2 class="h6 card-title mb-3">Azioni account</h2>
<div class="d-grid gap-2">
<NuxtLink v-if="isCitizen(user?.role)" class="btn btn-primary" to="/reports/new">Nuova segnalazione
</NuxtLink>
<NuxtLink to="/notifications" class="btn btn-outline-primary">Notifiche</NuxtLink>
<button type="button" class="btn btn-outline-danger" @click="logout">
Logout
</button>
</div>
</div>
</div>
<div class="card card-bg">
<div class="card-body">
<h2 class="h6 card-title mb-2">Punti cittadino</h2>
<div class="display-6 text-primary font-weight-bold mb-2">{{ totalPoints }}</div>
<p class="small text-muted mb-0">
I punti vengono accreditati sulle segnalazioni concluse con esito positivo.
</p>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<style>
.card .card-body .d-grid > a {
padding-block: 8px;
}
</style>
+295 -180
View File
@@ -1,4 +1,6 @@
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
definePageMeta({
middleware: 'auth',
})
@@ -6,9 +8,8 @@ definePageMeta({
useHead({ title: 'Dettaglio Segnalazione - Visione' })
const runtimeConfig = useRuntimeConfig()
const route = useRoute()
const { getReportDetail, getMessages, addMessage, addFeedback, flagReport } = useReports()
const { getReportDetail, getMessages, addMessage, addFeedback } = useReports()
const { user } = useAuth()
const reportId = Number(route.params.id)
@@ -16,7 +17,6 @@ if (!reportId) {
navigateTo('/')
}
// Fetch dati
const { data: reportData, refresh: refreshReport } = await useAsyncData(`report-${reportId}`, () =>
getReportDetail(reportId)
)
@@ -30,25 +30,31 @@ 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 newMessage = ref('')
const isSubmittingMessage = ref(false)
const isFeedbackOpen = ref(false)
const feedbackRating = ref(5)
const feedbackComment = ref('')
const isSubmittingFeedback = ref(false)
const flagMessage = ref('')
const isFlagging = ref(false)
const selectedMediaIndex = ref(0)
const isGalleryOpen = ref(false)
const submittedFeedback = ref<{ rating: number; comment?: string } | null>(null)
// Invia messaggio
const handleSendMessage = async (msgText: string, files: File[]) => {
if (!msgText.trim() && files.length === 0) return
// Carica l'eventuale feedback da local storage dopo il mount (per evitare mismatch nel SSR)
onMounted(() => {
try {
const saved = localStorage.getItem(`feedback_${reportId}`)
if (saved) {
submittedFeedback.value = JSON.parse(saved)
}
} catch (error) {
console.error('Errore nel recupero del feedback da local storage:', error)
}
})
const handleSendMessage = async (messageText: string, files: File[]) => {
isSubmittingMessage.value = true
try {
// Gestione mock di file, nella realtà si usa FormData o simle
await addMessage(reportId, { body: msgText })
await addMessage(reportId, { body: messageText })
await refreshMessages()
} catch (error) {
console.error('Error sending message:', error)
@@ -57,17 +63,21 @@ const handleSendMessage = async (msgText: string, files: File[]) => {
}
}
// Invia feedback (solo se risolta)
const handleSubmitFeedback = async () => {
isSubmittingFeedback.value = true
try {
await addFeedback(reportId, {
const feedbackData = {
rating: feedbackRating.value,
comment: feedbackComment.value || undefined,
})
}
await addFeedback(reportId, feedbackData)
// Salva in local storage in mancanza di un endpoint dal backend
localStorage.setItem(`feedback_${reportId}`, JSON.stringify(feedbackData))
submittedFeedback.value = feedbackData
isFeedbackOpen.value = false
feedbackRating.value = 5
feedbackComment.value = ''
await refreshReport()
} catch (error) {
console.error('Error submitting feedback:', error)
@@ -76,26 +86,24 @@ const handleSubmitFeedback = async () => {
}
}
// Segnala abuso
const handleFlag = async () => {
if (!flagMessage.value.trim()) return
isFlagging.value = true
try {
await flagReport(reportId, {
reason: flagMessage.value,
})
flagMessage.value = ''
// Mostra messaggio di successo
} catch (error) {
console.error('Error flagging report:', error)
} finally {
isFlagging.value = false
}
}
const isOwner = computed(() => report.value?.user_id === user.value?.id)
const canFeedback = computed(() => report.value?.status === 'RESOLVED' || report.value?.status === 'CLOSED')
const canFeedback = computed(() => report.value?.status === 'RESOLVED')
const canChat = computed(() => {
if (!report.value) return false
const closedStatuses = ['RESOLVED', 'CLOSED', 'REJECTED']
return !closedStatuses.includes(report.value.status)
})
const statusMeta: Record<string, { label: string; tone: string }> = {
OPEN: { label: 'Aperta', tone: 'info' },
UNDER_REVIEW: { label: 'In revisione', tone: 'warning' },
ASSIGNED: { label: 'Assegnata', tone: 'info' },
IN_PROGRESS: { label: 'In lavorazione', tone: 'primary' },
RESOLVED: { label: 'Risolta', tone: 'success' },
REJECTED: { label: 'Respinta', tone: 'danger' },
CLOSED: { label: 'Conclusa', tone: 'secondary' },
}
const formatDate = (dateString: string): string => {
return new Date(dateString).toLocaleDateString('it-IT', {
@@ -110,139 +118,191 @@ const formatDate = (dateString: string): string => {
<template>
<div v-if="report">
<!-- HEADER -->
<div class="bg-light border-bottom py-4">
<div class="report-hero py-4 py-lg-5">
<div class="container">
<div class="row">
<div class="col-12 col-md-8">
<h1 class="h3 font-weight-bold mb-2">{{ report.category_name }}</h1>
<div class="d-flex align-items-center gap-3">
<div class="row align-items-end g-3">
<div class="col-12 col-lg-8">
<div class="report-hero-meta mb-2">
<span class="report-id">Segnalazione #{{ report.id }}</span>
<StatusBadge :status="report.status"/>
<small class="text-muted">
<BIIcon name="it-clock" size="xs" class="me-1" />
Creata il {{ formatDate(report.created_at) }}
</small>
</div>
<h1 class="h3 font-weight-bold mb-2">{{ report.category_name }}</h1>
<p class="mb-0 report-hero-address">{{ report.address }}</p>
</div>
<div class="col-12 col-lg-4">
<div class="report-hero-stats">
<div class="hero-stat">
<span class="hero-stat-label">Stato</span>
<strong>{{ statusMeta[report.status]?.label || report.status }}</strong>
</div>
<div class="hero-stat">
<span class="hero-stat-label">Creata</span>
<strong>{{ formatDate(report.created_at) }}</strong>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- CONTENUTO PRINCIPALE -->
<div class="container my-5">
<div class="row">
<!-- SINISTRA: Dettagli segnalazione -->
<div class="col-12 col-lg-8 mb-4">
<!-- INDIRIZZO E COORDINATE -->
<div class="card card-bg mb-4">
<div class="row g-4">
<div class="col-12 col-xl-8">
<div class="card card-bg border-0 shadow-sm mb-4">
<div class="card-body">
<h6 class="card-title font-weight-bold mb-3">
<BIIcon name="it-map-marker-circle" size="sm" color="primary" class="me-2" />
Posizione
</h6>
<div class="mb-2">
<strong>{{ report.address }}</strong>
<div class="report-section-head mb-3">
<BIIcon class="me-2" color="primary" name="it-map-marker-circle" size="sm"/>
<h2 class="h6 mb-0">Posizione e dettagli</h2>
</div>
<dl class="report-detail-grid mb-0">
<div>
<dt>Indirizzo</dt>
<dd>{{ report.address }}</dd>
</div>
<div>
<dt>Coordinate</dt>
<dd>{{ report.latitude }}, {{ report.longitude }}</dd>
</div>
<div v-if="report.area_name">
<dt>Area</dt>
<dd>{{ report.area_name }}</dd>
</div>
<div>
<dt>Ultimo aggiornamento</dt>
<dd>{{ formatDate(report.updated_at || report.created_at) }}</dd>
</div>
</dl>
<div class="report-description mt-4">
<h3 class="h6 mb-2">Descrizione</h3>
<p class="mb-0 text-break">{{ report.description }}</p>
</div>
<small class="text-muted d-block">
Coordinate: {{ report.latitude }}, {{ report.longitude }}
</small>
<small v-if="report.area_name" class="text-muted d-block">
Area: {{ report.area_name }}
</small>
</div>
</div>
<!-- DESCRIZIONE -->
<div class="card card-bg mb-4">
<div v-if="media.length > 0" class="card card-bg border-0 shadow-sm mb-4">
<div class="card-body">
<h6 class="card-title font-weight-bold mb-3">
<BIIcon name="it-write" size="sm" color="primary" class="me-2" />
Descrizione
</h6>
<p class="card-text text-break">{{ report.description }}</p>
<div class="report-section-head mb-3">
<BIIcon class="me-2" color="primary" name="it-camera" size="sm"/>
<h2 class="h6 mb-0">Allegati ({{ media.length }})</h2>
</div>
</div>
<!-- GALLERY MEDIA -->
<div v-if="media.length > 0" class="card card-bg mb-4">
<div class="card-body">
<h6 class="card-title font-weight-bold mb-3">
<BIIcon name="it-camera" size="sm" color="primary" class="me-2" />
Allegati ({{ media.length }})
</h6>
<div class="row">
<div class="row g-3">
<div v-for="(m, idx) in media" :key="m.id" class="col-6 col-md-4 mb-3">
<div v-if="m.media_kind === 'IMAGE'" class="ratio ratio-1x1 bg-light rounded overflow-hidden">
<img :src="runtimeConfig.public.api + m.url" :alt="`Allegato ${Number(idx) + 1}`" class="object-fit-cover" />
<div v-if="m.media_kind === 'IMAGE'"
class="ratio ratio-1x1 bg-light rounded overflow-hidden report-media-frame">
<img :alt="`Allegato ${Number(idx) + 1}`" :src="runtimeConfig.public.api + m.url"
class="object-fit-cover"/>
</div>
<div v-else class="ratio ratio-1x1 bg-dark rounded d-flex align-items-center justify-content-center">
<BIIcon name="it-video" size="xl" color="white" />
<div v-else
class="ratio ratio-1x1 bg-dark rounded d-flex align-items-center justify-content-center report-media-frame">
<BIIcon color="white" name="it-video" size="xl"/>
</div>
</div>
</div>
</div>
</div>
<!-- CRONOLOGIA STATI -->
<div v-if="statusHistory.length > 0" class="card card-bg mb-4">
<div class="card card-bg border-0 shadow-sm mb-4">
<div class="card-body">
<h6 class="card-title font-weight-bold mb-4">
<BIIcon name="it-history" size="sm" color="primary" class="me-2" />
Cronologia
</h6>
<div class="timeline">
<div v-for="item in statusHistory" :key="item.id" class="timeline-item mb-3">
<div class="d-flex gap-3">
<div class="flex-shrink-0">
<div class="timeline-marker"></div>
</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">
<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>
<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>
</li>
</ul>
</div>
</div>
<!-- MESSAGGI -->
<div class="card card-bg">
<div class="card card-bg border-0 shadow-sm">
<div class="card-body">
<h6 class="card-title font-weight-bold mb-3">
<BIIcon name="it-comment" size="sm" color="primary" class="me-2" />
Chat ({{ messages.length }})
</h6>
<div class="report-chat-header mb-3">
<div>
<div class="report-section-head mb-1">
<BIIcon class="me-2" color="primary" name="it-comment" size="sm"/>
<h2 class="h6 mb-0">Chat segnalazione</h2>
</div>
<p class="text-muted small mb-0">Usa chat per chiarimenti, aggiornamenti operativi e richieste
rapide.</p>
</div>
<span class="badge bg-light text-dark border">{{ messages.length }} messaggi</span>
</div>
<MessageList :messages="messages"/>
<MessageComposer @send="handleSendMessage" />
<MessageComposer v-if="canChat" @send="handleSendMessage"/>
<div v-else class="alert alert-secondary mt-3 mb-0 text-center small">
La chat è disabilitata poiché la segnalazione è in stato
<strong>{{ statusMeta[report.status]?.label || report.status }}</strong>.
</div>
</div>
</div>
</div>
<!-- DESTRA: Sidebar azioni -->
<div class="col-12 col-lg-4">
<!-- FEEDBACK (se risolta) -->
<div v-if="canFeedback && isOwner" class="card card-bg card-highlight mb-4">
<div class="col-12 col-xl-4">
<div class="report-sidebar">
<div class="card card-bg border-0 shadow-sm mb-4">
<div class="card-body">
<h6 class="card-title font-weight-bold mb-3">
<BIIcon name="it-star-outline" size="sm" color="primary" class="me-2" />
Lascia un feedback
</h6>
<h2 class="h6 mb-3">Riepilogo pratica</h2>
<ul class="report-summary-list list-unstyled mb-0">
<li>
<span>Cittadino proprietario</span>
<strong>{{ isOwner ? 'Sì' : 'No' }}</strong>
</li>
<li>
<span>Stato corrente</span>
<strong>{{ statusMeta[report.status]?.label || report.status }}</strong>
</li>
<li>
<span>Canale</span>
<strong>Portale Visione</strong>
</li>
</ul>
</div>
</div>
<div v-if="canFeedback && isOwner" class="card card-bg border-0 shadow-sm mb-4">
<div class="card-body">
<h2 class="h6 mb-3">Valuta intervento</h2>
<template v-if="submittedFeedback">
<div class="alert alert-success small mb-3">
Grazie! Il tuo feedback è stato inviato con successo.
</div>
<div class="mb-3">
<span class="d-block text-muted small mb-1">La tua valutazione</span>
<div class="d-flex gap-1">
<BIIcon
v-for="n in 5"
:key="n"
:name="n <= submittedFeedback.rating ? 'it-star-full' : 'it-star-outline'"
size="sm"
:color="n <= submittedFeedback.rating ? 'warning' : 'primary'"
/>
</div>
</div>
<div v-if="submittedFeedback.comment">
<span class="d-block text-muted small mb-1">Il tuo commento</span>
<p class="mb-0 small text-break">{{ submittedFeedback.comment }}</p>
</div>
</template>
<template v-else>
<p class="text-muted small mb-3">Lascia valutazione finale quando intervento è concluso.</p>
<button
v-if="!isFeedbackOpen"
type="button"
class="btn btn-primary w-100"
@click="isFeedbackOpen = true"
>
Valuta l'intervento
Valuta intervento
</button>
<template v-else>
@@ -252,7 +312,7 @@ const formatDate = (dateString: string): string => {
<button v-for="n in 5" :key="n" type="button" class="btn btn-link p-0"
@click="feedbackRating = n" :aria-label="`${n} stelle`">
<BIIcon
:name="n <= feedbackRating ? 'it-star' : 'it-star-outline'"
:name="n <= feedbackRating ? 'it-star-full' : 'it-star-outline'"
size="lg"
:color="n <= feedbackRating ? 'warning' : 'primary'"
/>
@@ -264,57 +324,31 @@ const formatDate = (dateString: string): string => {
<textarea
v-model="feedbackComment"
class="form-control"
placeholder="Commento (opzionale)"
placeholder="Commento opzionale"
rows="3"
/>
</div>
<div class="d-grid gap-2">
<button type="button" class="btn btn-primary" @click="handleSubmitFeedback" :disabled="isSubmittingFeedback">
<button :disabled="isSubmittingFeedback" class="btn btn-primary" type="button"
@click="handleSubmitFeedback">
<span v-if="isSubmittingFeedback" class="spinner-border spinner-border-sm me-2"></span>
Invia
</button>
<button type="button" class="btn btn-light" @click="isFeedbackOpen = false">
Cancella
<button type="button" class="btn btn-outline-secondary" @click="isFeedbackOpen = false">
Annulla
</button>
</div>
</template>
</template>
</div>
</div>
<!-- SEGNALA ABUSO -->
<div class="card card-bg">
<div class="card-body">
<h6 class="card-title font-weight-bold mb-3">
<BIIcon name="it-flag" size="sm" color="danger" class="me-2" />
Segnala abuso
</h6>
<textarea
v-model="flagMessage"
class="form-control form-control-sm mb-2"
placeholder="Specifica il motivo dell'abuso..."
rows="2"
/>
<button
type="button"
class="btn btn-sm btn-outline-danger w-100"
@click="handleFlag"
:disabled="isFlagging || !flagMessage.trim()"
>
<BIIcon name="it-flag" size="xs" class="me-1" />
Invia segnalazione
</button>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- LOADING STATE -->
<div v-else class="container my-5 text-center">
<div class="spinner-border text-primary" role="status">
<span class="visually-hidden">Caricamento...</span>
@@ -323,27 +357,102 @@ const formatDate = (dateString: string): string => {
</template>
<style scoped>
.card-highlight {
border-color: #006f9d;
.report-hero {
background: #f5f7f9;
border-bottom: 1px solid #d9e3ee;
}
.timeline-marker {
width: 12px;
height: 12px;
background-color: #006f9d;
border-radius: 50%;
border: 3px solid #f0f0f0;
.report-hero-meta,
.report-section-head {
align-items: center;
display: flex;
}
.timeline-item:not(:last-child) .timeline-marker::after {
content: '';
position: absolute;
left: 50%;
top: 20px;
width: 2px;
height: calc(100% + 20px);
background-color: #006f9d;
transform: translateX(-50%);
.report-hero-meta {
flex-wrap: wrap;
gap: 0.75rem;
}
.report-id {
color: #5c6f82;
font-size: 0.875rem;
font-weight: 700;
}
.report-hero-address {
color: #455b71;
font-size: 1.05rem;
}
.report-hero-stats {
background: #fff;
border: 1px solid #d9e3ee;
border-radius: 4px;
display: grid;
gap: 1rem;
grid-template-columns: repeat(2, minmax(0, 1fr));
padding: 1rem;
}
.hero-stat {
display: grid;
gap: 0.25rem;
}
.hero-stat-label,
.report-detail-grid dt {
color: #5c6f82;
font-size: 0.8125rem;
font-weight: 700;
margin: 0 0 0.25rem;
text-transform: uppercase;
}
.report-detail-grid {
display: grid;
gap: 1rem;
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.report-detail-grid dd {
color: #17324d;
font-weight: 600;
margin: 0;
}
.report-description {
background: #f5f7f9;
border: 1px solid #e4ebf1;
border-radius: 4px;
padding: 1rem;
}
.report-media-frame {
border: 1px solid #d9e3ee;
}
.report-chat-header {
align-items: flex-start;
display: flex;
gap: 1rem;
justify-content: space-between;
}
.report-sidebar {
position: sticky;
top: 1.5rem;
}
.report-summary-list {
display: grid;
gap: 0.875rem;
}
.report-summary-list li {
align-items: baseline;
display: flex;
gap: 1rem;
justify-content: space-between;
}
.ratio {
@@ -364,9 +473,15 @@ const formatDate = (dateString: string): string => {
width: 100%;
height: 100%;
}
@media (max-width: 991.98px) {
.report-detail-grid,
.report-hero-stats {
grid-template-columns: 1fr;
}
.report-sidebar {
position: static;
}
}
</style>
-149
View File
@@ -1,149 +0,0 @@
<script setup lang="ts">
import type { CreateReportRequest } from '~/types/api'
definePageMeta({
middleware: 'auth',
})
useHead({ title: 'Crea Segnalazione - Visione' })
const router = useRouter()
const { createReport, uploadMedia } = useReports()
const { user } = useAuth()
// Fetch categories
const { data: categoriesData } = await useAsyncData('categories', () =>
$fetch('/api/v1/admin/categories')
)
const categories = computed(() => (categoriesData.value as any)?.categories || [])
// 👇 Manteniamo una sola dichiarazione per queste variabili
const isLoading = ref(false)
const errorMessage = ref('')
// 👇 Manteniamo una sola funzione handleReportSubmit
const handleReportSubmit = async (reportData: CreateReportRequest, mediaFiles: File[]) => {
isLoading.value = true
errorMessage.value = ''
try {
// Step 1: Carica i file media se presenti
let uploadedMediaUrls: string[] = []
if (mediaFiles.length > 0) {
console.log('📸 Media files to upload:', mediaFiles)
}
// Step 2: Crea la segnalazione
const response = await createReport({
...reportData,
media: uploadedMediaUrls, // Se l'API richiede stringhe pre-uploadate, va bene. Altrimenti passa array vuoto.
})
if (response.ok) {
// Step 3: Se ha media, carica dopo la creazione usando l'ID
if (mediaFiles.length > 0 && response.report_id) {
try {
const formData = new FormData()
mediaFiles.forEach((file) => {
formData.append('files', file)
})
await uploadMedia(response.report_id, formData)
console.log('✅ Media uploaded successfully')
} catch (err) {
console.error('⚠️ Media upload failed (non-critical):', err)
}
}
console.log('✅ Segnalazione creata:', response.report_id)
// Redirect al dettaglio della segnalazione
await router.push(`/reports/${response.report_id}`)
}
} catch (error: any) {
errorMessage.value = error.data?.message || 'Errore durante la creazione della segnalazione. Riprova.'
console.error('❌ Error creating report:', error)
} finally {
isLoading.value = false
}
}
</script>
<template>
<div>
<!-- HERO -->
<div class="it-hero-wrapper it-primary-bg">
<div class="container">
<div class="row">
<div class="col-12">
<div class="it-hero-text-wrapper p-4">
<h1 class="text-white font-weight-bold">Segnala un problema</h1>
<p class="text-white mt-2 lead">
Aiutaci a migliorare la città condividendo i disservizi che noti
</p>
</div>
</div>
</div>
</div>
</div>
<!-- CONTENUTO -->
<div class="container my-5">
<div class="row">
<div class="col-12 col-lg-8 offset-lg-2">
<!-- CALLOUT INFO -->
<div class="callout callout-highlight callout-primary mb-4">
<div class="callout-title">
<BIIcon name="it-info-circle" />
La tua segnalazione è anonima
</div>
<p>
I tuoi dati personali non saranno visibili pubblicamente. La segnalazione verrà elaborata dagli operatori comunali e potrai tracciare lo stato dell'intervento in tempo reale.
</p>
</div>
<!-- ERRORE GLOBALE -->
<div v-if="errorMessage" class="alert alert-danger alert-dismissible fade show" role="alert">
{{ errorMessage }}
<button type="button" class="btn-close" @click="errorMessage = ''"></button>
</div>
<!-- INFO UTENTE -->
<div class="card card-bg mb-4">
<div class="card-body">
<h6 class="card-title font-weight-bold mb-3">
<BIIcon name="it-user" size="sm" color="primary" class="me-2" />
Stai segnalando come:
</h6>
<div class="small">
<strong>{{ user?.first_name }} {{ user?.last_name }}</strong><br>
<span class="text-muted">{{ user?.email }}</span>
</div>
</div>
</div>
<!-- FORM PRINCIPALE -->
<ReportForm :categories="categories" :is-loading="isLoading" @submit="handleReportSubmit" />
<!-- NOTE LEGALI -->
<div class="alert alert-info mt-5" role="alert">
<small class="d-block">
Sottoponendo questa segnalazione accetti i nostri <NuxtLink to="/privacy" target="_blank">Termini di Servizio</NuxtLink>
e l'<NuxtLink to="/privacy" target="_blank">Informativa sulla Privacy</NuxtLink>.
Le segnalazioni con contenuti abusivi o offensivi verranno rimosse e l'utente potrebbe essere sanzionato.
</small>
</div>
</div>
</div>
</div>
</div>
</template>
<style scoped>
.it-primary-bg {
background: linear-gradient(135deg, #006f9d 0%, #003d5c 100%);
}
</style>
+118
View File
@@ -0,0 +1,118 @@
<script setup lang="ts">
import type { Report } from '~/types/api'
import { isWithinBariBounds } from '~/utils/bari'
definePageMeta({
middleware: 'auth',
})
useHead({ title: 'Le mie segnalazioni - Visione' })
const { getReports } = useReports()
const page = ref(1)
const perPage = ref(10)
const filterStatus = ref('')
const { data: reportsRes, pending } = useAsyncData('citizen-reports-list', () => getReports({}))
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') {
return reports.value.filter((report) => report.status === 'IN_PROGRESS' || report.status === 'ASSIGNED')
}
return reports.value.filter((report) => report.status === filterStatus.value)
})
const paginatedReports = computed(() => {
const start = (page.value - 1) * perPage.value
return filteredReports.value.slice(start, start + perPage.value)
})
const handleStatusFilter = (status: string) => {
filterStatus.value = status === 'all' ? '' : status
page.value = 1
}
</script>
<template>
<div>
<div class="bg-light border-bottom py-4 mb-4">
<div class="container">
<div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center gap-3">
<div>
<h1 class="h3 font-weight-bold mb-1">Le mie segnalazioni</h1>
<p class="text-muted mb-0">Consulta stato, cronologia e conversazioni con gli operatori.</p>
</div>
<NuxtLink to="/reports/new" class="btn btn-primary">
<BIIcon name="it-plus-circle" size="sm" color="white" class="me-2" />
Nuova segnalazione
</NuxtLink>
</div>
</div>
</div>
<div class="container mb-5">
<div class="d-flex flex-wrap gap-2 align-items-center mb-3">
<div class="btn-group" role="group" aria-label="Filtri segnalazioni">
<button
type="button"
class="btn btn-sm"
:class="filterStatus === '' ? 'btn-primary' : 'btn-outline-primary'"
@click="handleStatusFilter('all')"
>
Tutte
</button>
<button
type="button"
class="btn btn-sm"
:class="filterStatus === 'OPEN' ? 'btn-primary' : 'btn-outline-primary'"
@click="handleStatusFilter('OPEN')"
>
Aperte
</button>
<button
type="button"
class="btn btn-sm"
:class="filterStatus === 'IN_PROGRESS' ? 'btn-primary' : 'btn-outline-primary'"
@click="handleStatusFilter('IN_PROGRESS')"
>
In corso
</button>
<button
type="button"
class="btn btn-sm"
:class="filterStatus === 'RESOLVED' ? 'btn-primary' : 'btn-outline-primary'"
@click="handleStatusFilter('RESOLVED')"
>
Risolte
</button>
</div>
</div>
<div v-if="pending" class="text-center py-5">
<div class="spinner-border text-primary" role="status">
<span class="visually-hidden">Caricamento...</span>
</div>
</div>
<div v-else-if="filteredReports.length === 0" class="alert alert-info" role="alert">
Nessuna segnalazione trovata.
</div>
<template v-else>
<ReportTable :reports="paginatedReports" action-label="Apri segnalazione" />
<Pagination
v-if="filteredReports.length > perPage"
:current-page="page"
:per-page="perPage"
:total-items="filteredReports.length"
@page-change="page = $event"
/>
</template>
</div>
</div>
</template>
+82
View File
@@ -0,0 +1,82 @@
<script setup lang="ts">
import type { CreateReportRequest } from '~/types/api'
definePageMeta({
middleware: 'auth',
auth: {
role: ['!ADMIN', '!OPERATOR']
}
})
useHead({ title: 'Nuova segnalazione - Visione' })
const router = useRouter()
const { createReport, uploadMedia, getCategories } = useReports()
const { data: categoriesData } = await useAsyncData('categories', () => getCategories())
const categories = computed(() => categoriesData.value?.categories || [])
const isLoading = ref(false)
const errorMessage = ref('')
const handleReportSubmit = async (reportData: CreateReportRequest, mediaFiles: File[]) => {
isLoading.value = true
errorMessage.value = ''
try {
const response = await createReport({
...reportData,
media: [],
})
if (response.ok && response.report_id) {
if (mediaFiles.length > 0) {
try {
const formData = new FormData()
mediaFiles.forEach((file) => formData.append('files', file))
await uploadMedia(response.report_id, formData)
} catch (error) {
console.error('Media upload failed:', error)
}
}
await router.push(`/reports/${response.report_id}`)
}
} catch (error: any) {
errorMessage.value = error.data?.message || 'Errore durante la creazione della segnalazione. Riprova.'
} finally {
isLoading.value = false
}
}
</script>
<template>
<div>
<div class="it-hero-wrapper it-primary-bg hero-compact">
<div class="container">
<div class="row">
<div class="col-12">
<div class="it-hero-text-wrapper p-4">
<h1 class="text-white font-weight-bold">Nuova segnalazione</h1>
<p class="text-white mt-2 lead">
Descrivi il problema urbano, indica la posizione e allega eventuali media.
</p>
</div>
</div>
</div>
</div>
</div>
<div class="container my-5">
<div class="row justify-content-center">
<div class="col-12 col-xl-10">
<div v-if="errorMessage" class="alert alert-danger alert-dismissible fade show mb-4" role="alert">
{{ errorMessage }}
<button type="button" class="btn-close" aria-label="Chiudi" @click="errorMessage = ''"></button>
</div>
<ReportForm :categories="categories" :is-loading="isLoading" @submit="handleReportSubmit" />
</div>
</div>
</div>
</div>
</template>
+199
View File
@@ -0,0 +1,199 @@
<script setup lang="ts">
definePageMeta({
middleware: 'auth'
})
useHead({ title: 'Modifica Profilo - Visione' })
const { user, updateProfile, syncUser } = useAuth()
const router = useRouter()
const formData = reactive({
first_name: user.value?.first_name || '',
last_name: user.value?.last_name || '',
phone: user.value?.phone || ''
})
const isLoading = ref(false)
const errorMessage = ref('')
const successMessage = ref('')
const canSubmit = computed(() => {
return formData.first_name.trim().length > 0 && formData.last_name.trim().length > 0
})
const handleSubmit = async () => {
if (!canSubmit.value) return
isLoading.value = true
errorMessage.value = ''
successMessage.value = ''
try {
const res = await updateProfile({
first_name: formData.first_name,
last_name: formData.last_name,
phone: formData.phone || undefined
})
if (res.ok || res.user) {
await syncUser()
successMessage.value = 'Profilo aggiornato con successo.'
setTimeout(() => {
router.push('/profile')
}, 1500)
}
} catch (error: any) {
errorMessage.value = error.data?.message || 'Errore durante l\'aggiornamento del profilo.'
} finally {
isLoading.value = false
}
}
</script>
<template>
<div class="py-5">
<div class="container">
<div class="row justify-content-center">
<div class="col-12 col-lg-8 col-xl-6">
<div class="card card-bg border-0 shadow-sm">
<div class="card-body p-4 p-lg-5">
<div class="d-flex align-items-center mb-3">
<NuxtLink to="/profile" class="btn btn-sm btn-link text-decoration-none ps-0 me-3">
<BIIcon name="it-arrow-left" size="sm" />
</NuxtLink>
<h1 class="h3 mb-0">Modifica Profilo</h1>
</div>
<p class="text-muted mb-4">
Aggiorna i tuoi dati personali. Email e Codice Fiscale non sono modificabili.
</p>
<form @submit.prevent="handleSubmit" class="d-grid gap-4">
<div class="input-field">
<label for="first_name" class="form-label">Nome</label>
<div class="input-field-control">
<BIIcon name="it-user" size="sm" class="input-field-icon" />
<input
id="first_name"
v-model="formData.first_name"
type="text"
class="form-control"
required
>
</div>
</div>
<div class="input-field">
<label for="last_name" class="form-label">Cognome</label>
<div class="input-field-control">
<BIIcon name="it-user" size="sm" class="input-field-icon" />
<input
id="last_name"
v-model="formData.last_name"
type="text"
class="form-control"
required
>
</div>
</div>
<div class="input-field">
<label for="phone" class="form-label">Telefono (opzionale)</label>
<div class="input-field-control">
<BIIcon name="it-telephone" size="sm" class="input-field-icon" />
<input
id="phone"
v-model="formData.phone"
type="tel"
class="form-control"
>
</div>
</div>
<div class="input-field opacity-50">
<label class="form-label">Email</label>
<div class="input-field-control">
<BIIcon name="it-mail" size="sm" class="input-field-icon" />
<input
type="email"
class="form-control disabled"
:value="user?.email"
disabled
>
</div>
</div>
<div class="input-field opacity-50">
<label class="form-label">Codice Fiscale</label>
<div class="input-field-control">
<BIIcon name="it-card" size="sm" class="input-field-icon" />
<input
type="text"
class="form-control disabled"
:value="user?.fiscal_code"
disabled
>
</div>
</div>
<div v-if="errorMessage" class="alert alert-danger mb-0" role="alert">
{{ errorMessage }}
</div>
<div v-if="successMessage" class="alert alert-success mb-0" role="alert">
{{ successMessage }}
</div>
<button
type="submit"
class="btn btn-primary w-100 py-2 mt-2"
:disabled="!canSubmit || isLoading"
>
<span v-if="isLoading" class="spinner-border spinner-border-sm me-2"></span>
{{ isLoading ? 'Aggiornamento in corso...' : 'Salva modifiche' }}
</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<style scoped>
.input-field {
display: grid;
gap: 0.5rem;
}
.input-field-control {
align-items: center;
background: #fff;
border: 1px solid #c5d0db;
border-radius: 8px;
display: grid;
gap: 0.5rem;
grid-template-columns: auto minmax(0, 1fr);
padding-left: 0.875rem;
}
.input-field-control:focus-within {
border-color: #06c;
box-shadow: 0 0 0 2px rgba(0, 102, 204, 0.16);
}
.input-field-icon {
color: #5c6f82;
}
.input-field-control .form-control {
background: transparent;
border: 0;
border-radius: 0;
box-shadow: none;
min-width: 0;
padding-left: 0;
padding-right: 0;
}
</style>
+9 -5
View File
@@ -1,16 +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()
}
}
console.log('[Auth Plugin] Initialized - User:', auth.user.value?.id || 'None', 'Authenticated:', auth.isAuthenticated.value)
})
+72 -29
View File
@@ -6,6 +6,7 @@ export type FlagContentType = 'REPORT' | 'MESSAGE';
export interface GeoJsonObject {
type: string;
coordinates: any[];
[key: string]: any;
}
@@ -19,9 +20,6 @@ export interface OkResponse {
ok: boolean;
}
/**
* USER & AUTHENTICATION
*/
export interface CurrentUser {
id: number;
first_name: string;
@@ -29,7 +27,6 @@ export interface CurrentUser {
email: string;
fiscal_code: string;
points: number;
must_change_password: boolean;
role: string;
roles: string[];
permissions: string[];
@@ -45,8 +42,7 @@ export interface AdminUser {
phone?: string;
banned?: boolean;
points?: number;
must_change_password?: boolean;
roles?: string; // Comma-separated
roles?: string;
}
export interface TokenResponse {
@@ -56,9 +52,41 @@ export interface TokenResponse {
expires_in_hours: number;
}
/**
* REPORTS & MEDIA
*/
export interface CieStartRequest {
frontend_redirect_uri: string;
}
export interface CieStartResponse {
ok: boolean;
authorization_url: string;
state: string;
status: string;
}
export interface CieExchangeRequest {
state: string;
issuer: string;
subject: string;
fiscal_code: string;
first_name?: string;
last_name?: string;
email?: string;
}
export interface CieSessionAuth {
token?: string;
token_type?: string;
expires_in_hours?: number;
[key: string]: any;
}
export interface CieSessionResponse {
ok: boolean;
status: string;
user_id?: number;
auth?: CieSessionAuth;
}
export interface Report {
id: number;
category_id: number;
@@ -120,9 +148,6 @@ export interface Message {
created_at: string;
}
/**
* ENTITIES (Areas, Teams, Categories, Notifications, Rewards, Moderation)
*/
export interface Area {
id: number;
name: string;
@@ -184,28 +209,20 @@ export interface ModerationFlag {
resolved_at?: string | null;
}
/**
* REQUEST BODIES
*/
export interface RegisterCitizenRequest {
first_name: string;
last_name: string;
email: string;
password: string;
fiscal_code: string;
phone?: string;
birth_date?: string;
birth_place?: string;
}
export interface PasswordLoginRequest {
email: string;
password: string;
}
export interface ChangePasswordRequest {
current_password: string;
new_password: string;
export interface UpdateProfileRequest {
first_name?: string;
last_name?: string;
phone?: string;
}
export interface EmailRequest {
@@ -223,7 +240,7 @@ export interface CreateReportRequest {
longitude: number;
address: string;
description: string;
media?: string[]; // Array of URLs if already uploaded
media?: string[];
}
export interface UpdateStatusRequest {
@@ -240,7 +257,7 @@ export interface MessageRequest {
}
export interface FeedbackRequest {
rating: number; // 1 to 5
rating: number;
comment?: string;
}
@@ -261,11 +278,24 @@ export interface CreateAreaRequest {
description?: string;
}
export interface UpdateAreaRequest {
name?: string;
boundary_geojson?: GeoJsonObject;
description?: string;
active?: boolean;
}
export interface CreateCategoryRequest {
name: string;
description?: string;
}
export interface UpdateCategoryRequest {
name?: string;
description?: string;
active?: boolean;
}
export interface CreateTeamRequest {
team_category_id: number;
name: string;
@@ -273,6 +303,14 @@ export interface CreateTeamRequest {
area_id?: number;
}
export interface UpdateTeamRequest {
team_category_id?: number;
name?: string;
description?: string;
area_id?: number | null;
active?: boolean;
}
export interface UpdateUserBanRequest {
banned: boolean;
}
@@ -281,9 +319,6 @@ export interface UpdateUserRolesRequest {
roles: string[];
}
/**
* RESPONSE BODIES
*/
export interface CurrentUserResponse {
ok: boolean;
user: CurrentUser;
@@ -315,6 +350,7 @@ export interface PagedReportListResponse {
ok: boolean;
page: number;
per_page: number;
total?: number;
reports: Report[];
}
@@ -339,6 +375,12 @@ export interface InterventionSummaryResponse {
latest_messages: Message[];
}
export interface AssignmentLinkResponse {
ok: boolean;
url: string;
expires_at: string;
}
export interface MediaUploadResponse {
ok: boolean;
media: Media[];
@@ -393,6 +435,7 @@ export interface ModerationListResponse {
ok: boolean;
page: number;
per_page: number;
total?: number;
flags: ModerationFlag[];
}
+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)
}
+74
View File
@@ -0,0 +1,74 @@
export const ROLES = {
CITIZEN: 'CITIZEN',
OPERATOR: 'OPERATOR',
ADMIN: 'ADMIN'
} as const
export type Role = keyof typeof ROLES
export type NegatedRole = `!${Role}`
export type MetaRoleRequirement = Role | NegatedRole | Array<Role | NegatedRole>
export const ROLE_LEVELS: Record<string, number> = {
[ROLES.CITIZEN]: 1,
[ROLES.OPERATOR]: 2,
[ROLES.ADMIN]: 3
}
export function normalizeRole(role?: string | null): string {
return role?.trim().toUpperCase() ?? ''
}
export function isRole(userRole: string | undefined | null, targetRole: string): boolean {
return normalizeRole(userRole) === normalizeRole(targetRole)
}
export function hasMinimumRole(userRole: string | undefined | null, requiredRole: string): boolean {
const userLvl = ROLE_LEVELS[normalizeRole(userRole)] || 0
const reqLvl = ROLE_LEVELS[normalizeRole(requiredRole)] || 0
return userLvl >= reqLvl
}
export function isAdmin(userRole?: string | null): boolean {
return isRole(userRole, ROLES.ADMIN)
}
export function isOperator(userRole?: string | null): boolean {
return isRole(userRole, ROLES.OPERATOR)
}
export function isCitizen(userRole?: string | null): boolean {
return isRole(userRole, ROLES.CITIZEN)
}
export function canAccess(userRole: string | undefined | null, requiredRole: string): boolean {
return hasMinimumRole(userRole, requiredRole)
}
export function checkRoleAccess(userRole: string | undefined | null, requirement: MetaRoleRequirement | undefined): boolean {
if (!requirement) return true
const normalizedUserRole = normalizeRole(userRole)
if (!normalizedUserRole) return false
const requirements = Array.isArray(requirement) ? requirement : [requirement]
for (const req of requirements) {
const isNegated = req.startsWith('!')
const rawTarget = isNegated ? req.substring(1) : req
const targetRole = normalizeRole(rawTarget)
if (isNegated) {
console.log("negated", normalizedUserRole, targetRole)
if (normalizedUserRole === targetRole) {
return false
}
} else {
if (!hasMinimumRole(normalizedUserRole, targetRole)) {
return false
}
}
}
return true
}
+53 -26
View File
@@ -6,9 +6,12 @@ export default defineNuxtConfig({
'@nuxt/image',
'@nuxt/fonts',
'@nuxtjs/sitemap',
'@nuxtjs/robots'
'@nuxtjs/robots',
'@vite-pwa/nuxt'
],
ssr: true,
runtimeConfig: {
public: {
url: 'http://localhost:3000',
@@ -21,32 +24,10 @@ export default defineNuxtConfig({
name: 'Visione - Un\'occhio per la sicurezza del cittadino.',
},
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/'
}
}
}
},
css: [
'@/assets/css/style.css',
'bootstrap-italia/dist/css/bootstrap-italia.min.css'
'leaflet/dist/leaflet.css',
'bootstrap-italia/dist/css/bootstrap-italia.min.css',
'@/assets/css/style.css'
],
fonts: {
@@ -55,5 +36,51 @@ export default defineNuxtConfig({
{ name: 'Roboto Mono', provider: 'google' },
{ name: 'Titillium Web', provider: 'google' }
]
},
app: {
head: {
meta: [
{ name: 'viewport', content: 'width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0' },
{ name: 'theme-color', content: '#003366' },
{ name: 'description', content: 'Visione - Un\'occhio per la sicurezza' },
{ name: 'apple-mobile-web-app-capable', content: 'yes' },
{ name: 'apple-mobile-web-app-status-bar-style', content: 'black-translucent' },
{ name: 'apple-mobile-web-app-title', content: 'Visione' }
],
link: [
{ rel: 'icon', type: 'image/svg+xml', href: '/icon.svg' }
]
}
},
pwa: {
registerType: 'autoUpdate',
manifest: {
name: 'Visione - Un\'occhio per la sicurezza',
short_name: 'Visione',
theme_color: '#003366',
background_color: '#003366',
display: 'standalone',
orientation: 'portrait',
icons: [
{
src: '/icon-192.webp',
sizes: '192x192',
type: 'image/webp',
purpose: 'any'
},
{
src: '/icon-512.webp',
sizes: '512x512',
type: 'image/webp',
purpose: 'any'
}
]
},
workbox: {
globPatterns: ['**/*.{js,css,html,png,svg,ico,webp}']
}
}
})
+2
View File
@@ -14,7 +14,9 @@
"@nuxt/image": "^2.0.0",
"@nuxtjs/robots": "6.0.9",
"@nuxtjs/sitemap": "8.0.15",
"@vite-pwa/nuxt": "1.1.1",
"bootstrap-italia": "^2.18.1",
"codice-fiscale-js": "^2.3.23",
"leaflet": "^1.9.4",
"nuxt": "^4.4.7",
"vue": "^3.5.35",
Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.0 KiB

+4
View File
@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1940.28 1402.502">
<path d="M1750.752 723.02a183 183 0 0 0-.378-15.172c-12.607-201.546-306.563-352.873-691.458-375.02L1104.93 0c-32.106 110.228-64.212 220.499-96.318 330.727-52.026-1.47-105.564-.546-160.069 2.858C365.313 363.842-14.414 580.516.42 817.489c14.877 236.972 418.642 404.52 901.83 374.263 115.02-7.186 224.197-24.962 323.584-51.059l255.63 261.809-207.975-275.172c271.389-81.148 459.572-225.752 476.087-383.425 63.582-4.329 127.122-8.657 190.704-12.985-63.162-2.648-126.366-5.253-189.528-7.9M1022.27 597.998c256.178 5.84 455.202 49.924 515.884 116.153-176.29-7.312-352.621-14.666-528.91-22.02 4.328-31.392 8.656-62.742 13.027-94.133ZM39.713 849.637C34.628 768.32 215.876 686.753 480.08 639.182c-69.381 32.568-116.742 97.747-116.742 172.801 0 100.605 85.056 183.392 194.234 193.814-296.562-8.867-512.438-69.381-517.86-156.16m771.22 151.664c-73.878 4.623-145.444 6.303-213.27 5.379 16.599-.84 32.652-3.74 47.906-8.531-16.64 4.664-34.207 7.564-52.32 8.447-2.898.168-5.882.252-8.824.294a165 165 0 0 1-13.742-.714c-99.765-8.573-178.055-92.285-178.055-194.277 0-78.71 46.605-146.536 113.8-177.34 22.778-10.464 47.95-16.641 74.467-17.523h.294q3.214-.127 6.43-.127c9.287 0 18.364.63 27.315 1.891.547-.084 1.093-.126 1.64-.21a77 77 0 0 1-2.396-1.554l6.009 1.134c53.244-6.514 108.758-11.64 165.826-15.213 49.504-3.11 97.915-4.874 144.898-5.421-7.229 24.879-14.499 49.715-21.727 74.592L620.187 618.17a106 106 0 0 0-3.614.42c.252.21.504.378.756.547h.043c11.052 1.722 21.81 4.328 32.19 7.858.21.042.42.084.588.168 28.66 9.666 54.379 25.845 75.307 46.773 35.342 35.3 57.194 84.047 57.194 137.963 0 2.27-.042 4.497-.126 6.724-2.774 82.493-56.816 152.042-131.324 177.72-.841.293-1.724.587-2.606.881 10.338-2.941 20.298-6.64 29.837-10.926 90.561-37.023 159.648-102.664 250-150.193 44.923 46.016 89.846 91.99 134.77 138.006-78.669 12.313-163.557 21.642-252.269 27.19m335.686-41.814-125.483-165.994c178.727-12.145 357.412-24.332 536.139-36.519 1.513 77.408-165.195 154.774-410.656 202.513"
style="fill:#0b7dd1"/>
</svg>

After

Width:  |  Height:  |  Size: 2.0 KiB

+3
View File
@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1940.28 1402.502">
<path d="M1750.752 723.02a183 183 0 0 0-.378-15.172c-12.607-201.546-306.563-352.873-691.458-375.02L1104.93 0c-32.106 110.228-64.212 220.499-96.318 330.727-52.026-1.47-105.564-.546-160.069 2.858C365.313 363.842-14.414 580.516.42 817.489c14.877 236.972 418.642 404.52 901.83 374.263 115.02-7.186 224.197-24.962 323.584-51.059l255.63 261.809-207.975-275.172c271.389-81.148 459.572-225.752 476.087-383.425 63.582-4.329 127.122-8.657 190.704-12.985-63.162-2.648-126.366-5.253-189.528-7.9M1022.27 597.998c256.178 5.84 455.202 49.924 515.884 116.153-176.29-7.312-352.621-14.666-528.91-22.02 4.328-31.392 8.656-62.742 13.027-94.133ZM39.713 849.637C34.628 768.32 215.876 686.753 480.08 639.182c-69.381 32.568-116.742 97.747-116.742 172.801 0 100.605 85.056 183.392 194.234 193.814-296.562-8.867-512.438-69.381-517.86-156.16m771.22 151.664c-73.878 4.623-145.444 6.303-213.27 5.379 16.599-.84 32.652-3.74 47.906-8.531-16.64 4.664-34.207 7.564-52.32 8.447-2.898.168-5.882.252-8.824.294a165 165 0 0 1-13.742-.714c-99.765-8.573-178.055-92.285-178.055-194.277 0-78.71 46.605-146.536 113.8-177.34 22.778-10.464 47.95-16.641 74.467-17.523h.294q3.214-.127 6.43-.127c9.287 0 18.364.63 27.315 1.891.547-.084 1.093-.126 1.64-.21a77 77 0 0 1-2.396-1.554l6.009 1.134c53.244-6.514 108.758-11.64 165.826-15.213 49.504-3.11 97.915-4.874 144.898-5.421-7.229 24.879-14.499 49.715-21.727 74.592L620.187 618.17a106 106 0 0 0-3.614.42c.252.21.504.378.756.547h.043c11.052 1.722 21.81 4.328 32.19 7.858.21.042.42.084.588.168 28.66 9.666 54.379 25.845 75.307 46.773 35.342 35.3 57.194 84.047 57.194 137.963 0 2.27-.042 4.497-.126 6.724-2.774 82.493-56.816 152.042-131.324 177.72-.841.293-1.724.587-2.606.881 10.338-2.941 20.298-6.64 29.837-10.926 90.561-37.023 159.648-102.664 250-150.193 44.923 46.016 89.846 91.99 134.77 138.006-78.669 12.313-163.557 21.642-252.269 27.19m335.686-41.814-125.483-165.994c178.727-12.145 357.412-24.332 536.139-36.519 1.513 77.408-165.195 154.774-410.656 202.513"/>
</svg>

After

Width:  |  Height:  |  Size: 2.0 KiB

+4
View File
@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1940.28 1402.502">
<path d="M1750.752 723.02a183 183 0 0 0-.378-15.172c-12.607-201.546-306.563-352.873-691.458-375.02L1104.93 0c-32.106 110.228-64.212 220.499-96.318 330.727-52.026-1.47-105.564-.546-160.069 2.858C365.313 363.842-14.414 580.516.42 817.489c14.877 236.972 418.642 404.52 901.83 374.263 115.02-7.186 224.197-24.962 323.584-51.059l255.63 261.809-207.975-275.172c271.389-81.148 459.572-225.752 476.087-383.425 63.582-4.329 127.122-8.657 190.704-12.985-63.162-2.648-126.366-5.253-189.528-7.9M1022.27 597.998c256.178 5.84 455.202 49.924 515.884 116.153-176.29-7.312-352.621-14.666-528.91-22.02 4.328-31.392 8.656-62.742 13.027-94.133ZM39.713 849.637C34.628 768.32 215.876 686.753 480.08 639.182c-69.381 32.568-116.742 97.747-116.742 172.801 0 100.605 85.056 183.392 194.234 193.814-296.562-8.867-512.438-69.381-517.86-156.16m771.22 151.664c-73.878 4.623-145.444 6.303-213.27 5.379 16.599-.84 32.652-3.74 47.906-8.531-16.64 4.664-34.207 7.564-52.32 8.447-2.898.168-5.882.252-8.824.294a165 165 0 0 1-13.742-.714c-99.765-8.573-178.055-92.285-178.055-194.277 0-78.71 46.605-146.536 113.8-177.34 22.778-10.464 47.95-16.641 74.467-17.523h.294q3.214-.127 6.43-.127c9.287 0 18.364.63 27.315 1.891.547-.084 1.093-.126 1.64-.21a77 77 0 0 1-2.396-1.554l6.009 1.134c53.244-6.514 108.758-11.64 165.826-15.213 49.504-3.11 97.915-4.874 144.898-5.421-7.229 24.879-14.499 49.715-21.727 74.592L620.187 618.17a106 106 0 0 0-3.614.42c.252.21.504.378.756.547h.043c11.052 1.722 21.81 4.328 32.19 7.858.21.042.42.084.588.168 28.66 9.666 54.379 25.845 75.307 46.773 35.342 35.3 57.194 84.047 57.194 137.963 0 2.27-.042 4.497-.126 6.724-2.774 82.493-56.816 152.042-131.324 177.72-.841.293-1.724.587-2.606.881 10.338-2.941 20.298-6.64 29.837-10.926 90.561-37.023 159.648-102.664 250-150.193 44.923 46.016 89.846 91.99 134.77 138.006-78.669 12.313-163.557 21.642-252.269 27.19m335.686-41.814-125.483-165.994c178.727-12.145 357.412-24.332 536.139-36.519 1.513 77.408-165.195 154.774-410.656 202.513"
style="fill:#fff"/>
</svg>

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

+1 -1
View File
File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 92 KiB

After

Width:  |  Height:  |  Size: 90 KiB

+3193 -149
View File
File diff suppressed because it is too large Load Diff