Nuovi endpoint CRUD implementati lato grafico nel pannello admin #7

Merged
reloia merged 3 commits from crud-admin-panel into master 2026-06-15 15:07:10 +00:00
4 changed files with 261 additions and 24 deletions
Showing only changes of commit 00b0f97505 - Show all commits
+13
View File
@@ -3,6 +3,7 @@ import type {
ModerationListResponse, ModerationListResponse,
OkResponse, OkResponse,
OverviewStatsResponse, TeamListResponse, UpdateModerationRequest, OverviewStatsResponse, TeamListResponse, UpdateModerationRequest,
UpdateAreaRequest, UpdateCategoryRequest, UpdateTeamRequest,
UpdateUserBanRequest, UpdateUserRolesRequest, UpdateUserBanRequest, UpdateUserRolesRequest,
UserListResponse UserListResponse
} from "~/types/api"; } from "~/types/api";
@@ -26,17 +27,26 @@ export const useAdmin = () => {
const createArea = (body: CreateAreaRequest) => const createArea = (body: CreateAreaRequest) =>
useApiFetch<OkResponse>('/api/v1/admin/areas', { method: 'POST', body }) useApiFetch<OkResponse>('/api/v1/admin/areas', { method: 'POST', body })
const updateArea = (id: number, body: UpdateAreaRequest) =>
useApiFetch<OkResponse>(`/api/v1/admin/areas/${id}`, { method: 'PATCH', body })
const getCategories = () => const getCategories = () =>
useApiFetch<CategoryListResponse>('/api/v1/admin/categories', { method: 'GET' }) useApiFetch<CategoryListResponse>('/api/v1/admin/categories', { method: 'GET' })
const createCategory = (body: CreateCategoryRequest) => const createCategory = (body: CreateCategoryRequest) =>
useApiFetch<OkResponse>('/api/v1/admin/categories', { method: 'POST', body }) useApiFetch<OkResponse>('/api/v1/admin/categories', { method: 'POST', body })
const updateCategory = (id: number, body: UpdateCategoryRequest) =>
useApiFetch<OkResponse>(`/api/v1/admin/categories/${id}`, { method: 'PATCH', body })
const getTeams = () => const getTeams = () =>
useApiFetch<TeamListResponse>('/api/v1/admin/teams', { method: 'GET' }) useApiFetch<TeamListResponse>('/api/v1/admin/teams', { method: 'GET' })
const createTeam = (body: CreateTeamRequest) => const createTeam = (body: CreateTeamRequest) =>
useApiFetch<OkResponse>('/api/v1/admin/teams', { method: 'POST', body }) useApiFetch<OkResponse>('/api/v1/admin/teams', { method: 'POST', body })
const updateTeam = (id: number, body: UpdateTeamRequest) =>
useApiFetch<OkResponse>(`/api/v1/admin/teams/${id}`, { method: 'PATCH', body })
const getModerationFlags = (query?: { status?: string; page?: number; per_page?: number }) => const getModerationFlags = (query?: { status?: string; page?: number; per_page?: number }) =>
useApiFetch<ModerationListResponse>('/api/v1/admin/moderation', { method: 'GET', query }) useApiFetch<ModerationListResponse>('/api/v1/admin/moderation', { method: 'GET', query })
@@ -51,10 +61,13 @@ export const useAdmin = () => {
updateUserRoles, updateUserRoles,
getAreas, getAreas,
createArea, createArea,
updateArea,
getCategories, getCategories,
createCategory, createCategory,
updateCategory,
getTeams, getTeams,
createTeam, createTeam,
updateTeam,
getModerationFlags, getModerationFlags,
updateModerationFlag, updateModerationFlag,
} }
+111 -8
View File
@@ -1,5 +1,5 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref, reactive, nextTick, onBeforeUnmount } from 'vue' import { ref, reactive, nextTick, onBeforeUnmount, computed } from 'vue'
import { BARI_BOUNDS, BARI_CENTER, isWithinBariBounds } from '~/utils/bari' import { BARI_BOUNDS, BARI_CENTER, isWithinBariBounds } from '~/utils/bari'
definePageMeta({ definePageMeta({
@@ -9,10 +9,11 @@ definePageMeta({
useHead({ title: 'Aree - Admin' }) useHead({ title: 'Aree - Admin' })
const { getAreas, createArea } = useAdmin() const { getAreas, createArea, updateArea } = useAdmin()
const { data: areasRes, pending, refresh } = useAsyncData('admin-areas', () => getAreas()) const { data: areasRes, pending, refresh } = useAsyncData('admin-areas', () => getAreas())
const isCreating = ref(false) const isCreating = ref(false)
const editingAreaId = ref<number | null>(null)
const formData = reactive({ const formData = reactive({
name: '', name: '',
description: '', description: '',
@@ -25,7 +26,12 @@ let map: any = null
let polygon: any = null let polygon: any = null
const mapPoints = ref<[number, number][]>([]) const mapPoints = ref<[number, number][]>([])
const modalTitle = computed(() => editingAreaId.value ? 'Modifica Area' : 'Nuova Area')
const submitLabel = computed(() => editingAreaId.value ? 'Salva Modifiche' : 'Crea Area')
const isEditing = computed(() => editingAreaId.value !== null)
const openCreateModal = () => { const openCreateModal = () => {
editingAreaId.value = null
formData.name = '' formData.name = ''
formData.description = '' formData.description = ''
formData.geojson = '' formData.geojson = ''
@@ -74,6 +80,73 @@ const openCreateModal = () => {
}) })
} }
const loadPolygonFromGeoJson = (boundaryGeojson: any) => {
const coordinates = boundaryGeojson?.coordinates?.[0]
if (!Array.isArray(coordinates)) {
mapPoints.value = []
return
}
const normalized = coordinates
.slice(0, -1)
.map(([longitude, latitude]: [number, number]) => [latitude, longitude] as [number, number])
mapPoints.value = normalized
if (polygon) {
polygon.setLatLngs(mapPoints.value)
}
}
const openEditModal = (area: any) => {
editingAreaId.value = area.id
formData.name = area.name || ''
formData.description = area.description || ''
formData.geojson = area.boundary_geojson ? JSON.stringify(area.boundary_geojson, null, 2) : ''
jsonError.value = ''
mapPoints.value = []
isCreating.value = true
nextTick(async () => {
const L = (await import('leaflet')).default
if (map) {
map.remove()
map = null
}
const bariBounds = L.latLngBounds(
[BARI_BOUNDS.south, BARI_BOUNDS.west],
[BARI_BOUNDS.north, BARI_BOUNDS.east]
)
map = L.map('areaMap', {
maxBounds: bariBounds,
maxBoundsViscosity: 1,
minZoom: 12
}).setView(BARI_CENTER, 12)
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
attribution: '© OpenStreetMap'
}).addTo(map)
polygon = L.polygon([], { color: 'red' }).addTo(map)
map.fitBounds(bariBounds)
loadPolygonFromGeoJson(area.boundary_geojson)
map.on('click', (e: any) => {
if (!isWithinBariBounds(e.latlng.lat, e.latlng.lng)) {
jsonError.value = 'Puoi disegnare aree solo entro confini del Comune di Bari.'
return
}
jsonError.value = ''
mapPoints.value.push([e.latlng.lat, e.latlng.lng])
polygon.setLatLngs(mapPoints.value)
updateGeojson()
})
})
}
const clearMap = () => { const clearMap = () => {
mapPoints.value = [] mapPoints.value = []
if (polygon) { if (polygon) {
@@ -100,6 +173,7 @@ const updateGeojson = () => {
const closeCreateModal = () => { const closeCreateModal = () => {
isCreating.value = false isCreating.value = false
editingAreaId.value = null
if (map) { if (map) {
map.remove() map.remove()
map = null map = null
@@ -131,19 +205,35 @@ const handleCreate = async () => {
} }
try { try {
const res = await createArea({ const payload = {
name: formData.name, name: formData.name,
description: formData.description || undefined, description: formData.description || undefined,
boundary_geojson: parsedGeojson boundary_geojson: parsedGeojson
}) }
const res = editingAreaId.value
? await updateArea(editingAreaId.value, payload)
: await createArea(payload)
if (res.ok) { if (res.ok) {
await refresh() await refresh()
closeCreateModal() closeCreateModal()
} }
} catch (err) { } catch (err) {
console.error('Failed to create area', err) console.error('Failed to save area', err)
alert('Errore durante la creazione dell\'area.') alert('Errore durante il salvataggio dell\'area.')
}
}
const handleToggleAreaActive = async (area: any) => {
try {
const res = await updateArea(area.id, { active: !area.active })
if (res.ok) {
await refresh()
}
} catch (err) {
console.error('Failed to update area status', err)
alert('Errore durante l\'aggiornamento dello stato area.')
} }
} }
</script> </script>
@@ -178,6 +268,7 @@ const handleCreate = async () => {
<th>Descrizione</th> <th>Descrizione</th>
<th>Stato</th> <th>Stato</th>
<th>GeoJSON</th> <th>GeoJSON</th>
<th class="text-end">Azioni</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@@ -193,6 +284,18 @@ const handleCreate = async () => {
<span v-if="area.boundary_geojson" class="badge border border-primary text-primary">Configurato</span> <span v-if="area.boundary_geojson" class="badge border border-primary text-primary">Configurato</span>
<span v-else class="badge border border-danger text-danger">Mancante</span> <span v-else class="badge border border-danger text-danger">Mancante</span>
</td> </td>
<td class="text-end">
<button class="btn btn-sm btn-outline-primary me-2" @click="openEditModal(area)">
Modifica
</button>
<button
class="btn btn-sm"
:class="area.active ? 'btn-outline-secondary' : 'btn-outline-success'"
@click="handleToggleAreaActive(area)"
>
{{ area.active ? 'Disattiva' : 'Attiva' }}
</button>
</td>
</tr> </tr>
</tbody> </tbody>
</table> </table>
@@ -204,7 +307,7 @@ const handleCreate = async () => {
<div class="modal-dialog modal-xl modal-dialog-centered modal-dialog-scrollable"> <div class="modal-dialog modal-xl modal-dialog-centered modal-dialog-scrollable">
<div class="modal-content"> <div class="modal-content">
<div class="modal-header"> <div class="modal-header">
<h5 class="modal-title">Nuova Area</h5> <h5 class="modal-title">{{ modalTitle }}</h5>
<button type="button" class="btn-close" @click="closeCreateModal"></button> <button type="button" class="btn-close" @click="closeCreateModal"></button>
</div> </div>
<div class="modal-body"> <div class="modal-body">
@@ -251,7 +354,7 @@ const handleCreate = async () => {
<div class="modal-footer d-flex justify-content-end gap-2"> <div class="modal-footer d-flex justify-content-end gap-2">
<button type="button" class="btn btn-outline-secondary" @click="closeCreateModal">Annulla</button> <button type="button" class="btn btn-outline-secondary" @click="closeCreateModal">Annulla</button>
<button type="button" class="btn btn-primary" :disabled="!formData.name || !formData.geojson" @click="handleCreate"> <button type="button" class="btn btn-primary" :disabled="!formData.name || !formData.geojson" @click="handleCreate">
Crea Area {{ submitLabel }}
</button> </button>
</div> </div>
</div> </div>
+115 -15
View File
@@ -1,4 +1,6 @@
<script setup lang="ts"> <script setup lang="ts">
import type { Category, Team } from '~/types/api'
definePageMeta({ definePageMeta({
middleware: 'auth', middleware: 'auth',
auth: { role: 'ADMIN' } auth: { role: 'ADMIN' }
@@ -6,7 +8,7 @@ definePageMeta({
useHead({ title: 'Categorie e Team - Admin' }) useHead({ title: 'Categorie e Team - Admin' })
const { createCategory, getTeams, createTeam, getAreas } = useAdmin() const { createCategory, updateCategory, getTeams, createTeam, updateTeam, getAreas } = useAdmin()
const { getCategories } = useReports() const { getCategories } = useReports()
const { data: categoriesRes, refresh: refreshCategories } = await useAsyncData('report-categories-admin-view', () => getCategories()) const { data: categoriesRes, refresh: refreshCategories } = await useAsyncData('report-categories-admin-view', () => getCategories())
@@ -18,6 +20,8 @@ const categoryForm = reactive({
description: '', description: '',
}) })
const editingCategoryId = ref<number | null>(null)
const teamForm = reactive({ const teamForm = reactive({
name: '', name: '',
description: '', description: '',
@@ -25,6 +29,8 @@ const teamForm = reactive({
area_id: null as number | null, area_id: null as number | null,
}) })
const editingTeamId = ref<number | null>(null)
const isSavingCategory = ref(false) const isSavingCategory = ref(false)
const isSavingTeam = ref(false) const isSavingTeam = ref(false)
const categoryError = ref('') const categoryError = ref('')
@@ -34,17 +40,49 @@ const categories = computed(() => categoriesRes.value?.categories || [])
const teams = computed(() => teamsRes.value?.teams || []) const teams = computed(() => teamsRes.value?.teams || [])
const areas = computed(() => areasRes.value?.areas || []) const areas = computed(() => areasRes.value?.areas || [])
const resetCategoryForm = () => {
editingCategoryId.value = null
categoryForm.name = ''
categoryForm.description = ''
}
const resetTeamForm = () => {
editingTeamId.value = null
teamForm.name = ''
teamForm.description = ''
teamForm.team_category_id = null
teamForm.area_id = null
}
const editCategory = (category: Category) => {
editingCategoryId.value = category.id
categoryForm.name = category.name
categoryForm.description = category.description || ''
}
const editTeam = (team: Team) => {
editingTeamId.value = team.id
teamForm.name = team.name
teamForm.description = team.description || ''
teamForm.team_category_id = team.team_category_id
teamForm.area_id = team.area_id ?? null
}
const submitCategory = async () => { const submitCategory = async () => {
categoryError.value = '' categoryError.value = ''
isSavingCategory.value = true isSavingCategory.value = true
try { try {
await createCategory({ const payload = {
name: categoryForm.name.trim(), name: categoryForm.name.trim(),
description: categoryForm.description.trim() || undefined, description: categoryForm.description.trim() || undefined,
}) }
categoryForm.name = '' if (editingCategoryId.value) {
categoryForm.description = '' await updateCategory(editingCategoryId.value, payload)
} else {
await createCategory(payload)
}
resetCategoryForm()
await refreshCategories() await refreshCategories()
} catch (error: any) { } catch (error: any) {
categoryError.value = error?.data?.message || 'Creazione categoria non riuscita.' categoryError.value = error?.data?.message || 'Creazione categoria non riuscita.'
@@ -60,16 +98,18 @@ const submitTeam = async () => {
isSavingTeam.value = true isSavingTeam.value = true
try { try {
await createTeam({ const payload = {
name: teamForm.name.trim(), name: teamForm.name.trim(),
description: teamForm.description.trim() || undefined, description: teamForm.description.trim() || undefined,
team_category_id: teamForm.team_category_id, team_category_id: teamForm.team_category_id,
area_id: teamForm.area_id || undefined, area_id: teamForm.area_id || undefined,
}) }
teamForm.name = '' if (editingTeamId.value) {
teamForm.description = '' await updateTeam(editingTeamId.value, payload)
teamForm.team_category_id = null } else {
teamForm.area_id = null await createTeam(payload)
}
resetTeamForm()
await refreshTeams() await refreshTeams()
} catch (error: any) { } catch (error: any) {
teamError.value = error?.data?.message || 'Creazione team non riuscita.' teamError.value = error?.data?.message || 'Creazione team non riuscita.'
@@ -77,6 +117,24 @@ const submitTeam = async () => {
isSavingTeam.value = false isSavingTeam.value = false
} }
} }
const toggleCategoryActive = async (category: Category) => {
try {
await updateCategory(category.id, { active: category.active === false })
await refreshCategories()
} catch (error: any) {
categoryError.value = error?.data?.message || 'Aggiornamento categoria non riuscito.'
}
}
const 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.'
}
}
</script> </script>
<template> <template>
@@ -113,7 +171,15 @@ const submitTeam = async () => {
</div> </div>
<button type="submit" class="btn btn-primary" :disabled="isSavingCategory || !categoryForm.name.trim()"> <button type="submit" class="btn btn-primary" :disabled="isSavingCategory || !categoryForm.name.trim()">
<span v-if="isSavingCategory" class="spinner-border spinner-border-sm me-2"></span> <span v-if="isSavingCategory" class="spinner-border spinner-border-sm me-2"></span>
Crea categoria {{ editingCategoryId ? 'Salva categoria' : 'Crea categoria' }}
</button>
<button
v-if="editingCategoryId"
type="button"
class="btn btn-outline-secondary ms-2"
@click="resetCategoryForm"
>
Annulla
</button> </button>
</form> </form>
@@ -124,6 +190,7 @@ const submitTeam = async () => {
<th>ID</th> <th>ID</th>
<th>Nome</th> <th>Nome</th>
<th>Stato</th> <th>Stato</th>
<th class="text-end">Azioni</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@@ -138,9 +205,21 @@ const submitTeam = async () => {
{{ category.active === false ? 'Inattiva' : 'Attiva' }} {{ category.active === false ? 'Inattiva' : 'Attiva' }}
</span> </span>
</td> </td>
<td class="text-end">
<button class="btn btn-sm btn-outline-primary me-2" @click="editCategory(category)">
Modifica
</button>
<button
class="btn btn-sm"
:class="category.active === false ? 'btn-outline-success' : 'btn-outline-secondary'"
@click="toggleCategoryActive(category)"
>
{{ category.active === false ? 'Attiva' : 'Disattiva' }}
</button>
</td>
</tr> </tr>
<tr v-if="categories.length === 0"> <tr v-if="categories.length === 0">
<td colspan="3" class="text-muted">Nessuna categoria configurata.</td> <td colspan="4" class="text-muted">Nessuna categoria configurata.</td>
</tr> </tr>
</tbody> </tbody>
</table> </table>
@@ -191,7 +270,15 @@ const submitTeam = async () => {
<div class="col-12"> <div class="col-12">
<button type="submit" class="btn btn-primary" :disabled="isSavingTeam || !teamForm.name.trim() || !teamForm.team_category_id"> <button type="submit" class="btn btn-primary" :disabled="isSavingTeam || !teamForm.name.trim() || !teamForm.team_category_id">
<span v-if="isSavingTeam" class="spinner-border spinner-border-sm me-2"></span> <span v-if="isSavingTeam" class="spinner-border spinner-border-sm me-2"></span>
Crea team {{ editingTeamId ? 'Salva team' : 'Crea team' }}
</button>
<button
v-if="editingTeamId"
type="button"
class="btn btn-outline-secondary ms-2"
@click="resetTeamForm"
>
Annulla
</button> </button>
</div> </div>
</form> </form>
@@ -205,6 +292,7 @@ const submitTeam = async () => {
<th>Categoria</th> <th>Categoria</th>
<th>Area</th> <th>Area</th>
<th>Stato</th> <th>Stato</th>
<th class="text-end">Azioni</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@@ -221,9 +309,21 @@ const submitTeam = async () => {
{{ team.active === false ? 'Inattivo' : 'Attivo' }} {{ team.active === false ? 'Inattivo' : 'Attivo' }}
</span> </span>
</td> </td>
<td class="text-end">
<button class="btn btn-sm btn-outline-primary me-2" @click="editTeam(team)">
Modifica
</button>
<button
class="btn btn-sm"
:class="team.active === false ? 'btn-outline-success' : 'btn-outline-secondary'"
@click="toggleTeamActive(team)"
>
{{ team.active === false ? 'Attiva' : 'Disattiva' }}
</button>
</td>
</tr> </tr>
<tr v-if="teams.length === 0"> <tr v-if="teams.length === 0">
<td colspan="5" class="text-muted">Nessun team configurato.</td> <td colspan="6" class="text-muted">Nessun team configurato.</td>
</tr> </tr>
</tbody> </tbody>
</table> </table>
+22 -1
View File
@@ -267,11 +267,24 @@ export interface CreateAreaRequest {
description?: string; description?: string;
} }
export interface UpdateAreaRequest {
name?: string;
boundary_geojson?: GeoJsonObject;
description?: string;
active?: boolean;
}
export interface CreateCategoryRequest { export interface CreateCategoryRequest {
name: string; name: string;
description?: string; description?: string;
} }
export interface UpdateCategoryRequest {
name?: string;
description?: string;
active?: boolean;
}
export interface CreateTeamRequest { export interface CreateTeamRequest {
team_category_id: number; team_category_id: number;
name: string; name: string;
@@ -279,6 +292,14 @@ export interface CreateTeamRequest {
area_id?: number; area_id?: number;
} }
export interface UpdateTeamRequest {
team_category_id?: number;
name?: string;
description?: string;
area_id?: number | null;
active?: boolean;
}
export interface UpdateUserBanRequest { export interface UpdateUserBanRequest {
banned: boolean; banned: boolean;
} }
@@ -416,4 +437,4 @@ export interface OverviewStatsResponse {
avg_resolution_hours_by_area: { area: string; value: number }[]; avg_resolution_hours_by_area: { area: string; value: number }[];
total_users?: number; total_users?: number;
open_reports?: number; open_reports?: number;
} }