Private
Public Access
añadido crud de grupos
This commit is contained in:
1 parent
ed3b51668b
commit
e3a2b1a47f
8 files changed
+418
No files matched your search
@@ -5,11 +5,17 @@ import (
|
||||
|
||||
"repuestera_back/config"
|
||||
"repuestera_back/models"
|
||||
"repuestera_back/utils"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func ObtenerGrupos(c *gin.Context) {
|
||||
if !utils.UsuarioTienePermiso(c, 2) {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "No tienes permiso para listar grupos"})
|
||||
return
|
||||
}
|
||||
|
||||
var grupos []models.Grupo
|
||||
if err := config.DB.Preload("Permisos").Preload("Grupos").Find(&grupos).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
@@ -19,6 +25,11 @@ func ObtenerGrupos(c *gin.Context) {
|
||||
}
|
||||
|
||||
func CrearGrupo(c *gin.Context) {
|
||||
if !utils.UsuarioTienePermiso(c, 2) {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "No tienes permiso para crear grupos"})
|
||||
return
|
||||
}
|
||||
|
||||
var grupo models.Grupo
|
||||
if err := c.ShouldBindJSON(&grupo); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
@@ -32,6 +43,11 @@ func CrearGrupo(c *gin.Context) {
|
||||
}
|
||||
|
||||
func ActualizarGrupo(c *gin.Context) {
|
||||
if !utils.UsuarioTienePermiso(c, 2) {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "No tienes permiso para crear grupos"})
|
||||
return
|
||||
}
|
||||
|
||||
id := c.Param("id")
|
||||
var grupo models.Grupo
|
||||
if err := config.DB.First(&grupo, id).Error; err != nil {
|
||||
@@ -48,6 +64,11 @@ func ActualizarGrupo(c *gin.Context) {
|
||||
}
|
||||
|
||||
func EliminarGrupo(c *gin.Context) {
|
||||
if !utils.UsuarioTienePermiso(c, 2) {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "No tienes permiso para crear grupos"})
|
||||
return
|
||||
}
|
||||
|
||||
id := c.Param("id")
|
||||
if err := config.DB.Delete(&models.Grupo{}, id).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
|
||||
@@ -9,5 +9,9 @@ export { obtenerPermisos } from './hooks/obtenerPermisos';
|
||||
export { crearPermiso } from './hooks/crearPermiso';
|
||||
export { actualizarPermiso } from './hooks/actualizarPermiso';
|
||||
export { eliminarPermiso } from './hooks/eliminarPermiso';
|
||||
export { obtenerGrupos } from './hooks/obtenerGrupos';
|
||||
export { crearGrupo } from './hooks/crearGrupo';
|
||||
export { actualizarGrupo } from './hooks/actualizarGrupo';
|
||||
export { eliminarGrupo } from './hooks/eliminarGrupo';
|
||||
export { setToken, removeToken, getToken } from './hooks/token';
|
||||
export { getCurrentUser, setCurrentUser, removeCurrentUser } from './hooks/user';
|
||||
@@ -0,0 +1,23 @@
|
||||
import type { Grupo } from '../../types';
|
||||
import { API_URL } from '../env';
|
||||
import { getToken } from './token';
|
||||
|
||||
async function handleResponse<T>(response: Response): Promise<T> {
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ message: 'Error desconocido' }));
|
||||
throw new Error(error.message || 'Error en la petición');
|
||||
}
|
||||
return response.json();
|
||||
}
|
||||
|
||||
export async function actualizarGrupo(id: number, data: Partial<Grupo>): Promise<Grupo> {
|
||||
const response = await fetch(`${API_URL}/grupos/${id}`, {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${getToken()}`
|
||||
},
|
||||
body: JSON.stringify(data)
|
||||
});
|
||||
return handleResponse<Grupo>(response);
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import type { Grupo } from '../../types';
|
||||
import { API_URL } from '../env';
|
||||
import { getToken } from './token';
|
||||
|
||||
async function handleResponse<T>(response: Response): Promise<T> {
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ message: 'Error desconocido' }));
|
||||
throw new Error(error.message || 'Error en la petición');
|
||||
}
|
||||
return response.json();
|
||||
}
|
||||
|
||||
export async function crearGrupo(data: Partial<Grupo>): Promise<Grupo> {
|
||||
const response = await fetch(`${API_URL}/grupos`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${getToken()}`
|
||||
},
|
||||
body: JSON.stringify(data)
|
||||
});
|
||||
return handleResponse<Grupo>(response);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { API_URL } from '../env';
|
||||
import { getToken } from './token';
|
||||
|
||||
export async function eliminarGrupo(id: number): Promise<void> {
|
||||
const response = await fetch(`${API_URL}/grupos/${id}`, {
|
||||
method: 'DELETE',
|
||||
headers: { Authorization: `Bearer ${getToken()}` }
|
||||
});
|
||||
if (!response.ok) throw new Error('Error al eliminar grupo');
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { Grupo } from '../../types';
|
||||
import { API_URL } from '../env';
|
||||
import { getToken } from './token';
|
||||
|
||||
async function handleResponse<T>(response: Response): Promise<T> {
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ message: 'Error desconocido' }));
|
||||
throw new Error(error.error || 'Error en la petición');
|
||||
}
|
||||
return response.json();
|
||||
}
|
||||
|
||||
export async function obtenerGrupos(): Promise<Grupo[]> {
|
||||
const response = await fetch(`${API_URL}/grupos`, {
|
||||
headers: { Authorization: `Bearer ${getToken()}` }
|
||||
});
|
||||
return handleResponse<Grupo[]>(response);
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
Button,
|
||||
DataTableSkeleton,
|
||||
InlineNotification,
|
||||
Modal,
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableContainer,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
TextInput,
|
||||
TextArea
|
||||
} from 'carbon-components-svelte';
|
||||
import Header from '$lib/components/Header.svelte';
|
||||
import Toast from '$lib/components/Toast.svelte';
|
||||
import { obtenerGrupos, crearGrupo, actualizarGrupo, eliminarGrupo } from '$lib/api';
|
||||
import type { Grupo } from '../../types';
|
||||
import Add from 'carbon-icons-svelte/lib/Add.svelte';
|
||||
import Edit from 'carbon-icons-svelte/lib/Edit.svelte';
|
||||
import TrashCan from 'carbon-icons-svelte/lib/TrashCan.svelte';
|
||||
|
||||
let grupos: Grupo[] = $state([]);
|
||||
let loading = $state(true);
|
||||
let error = $state('');
|
||||
|
||||
let modalOpen = $state(false);
|
||||
let modalEditando = $state(false);
|
||||
let formId = $state(0);
|
||||
let formNombre = $state('');
|
||||
let formDescripcion = $state('');
|
||||
|
||||
let deleteModalOpen = $state(false);
|
||||
let deleteId = $state(0);
|
||||
let deleteNombre = $state('');
|
||||
|
||||
let selectedGrupo: Grupo | null = $state(null);
|
||||
|
||||
let successMsg = $state('');
|
||||
let errorMsg = $state('');
|
||||
let notifOpen = $state(false);
|
||||
|
||||
const headers = [
|
||||
{ key: 'id' as const, value: 'ID' },
|
||||
{ key: 'nombre' as const, value: 'Nombre' },
|
||||
{ key: 'descripcion' as const, value: 'Descripción' }
|
||||
];
|
||||
|
||||
async function cargarGrupos() {
|
||||
loading = true;
|
||||
error = '';
|
||||
try {
|
||||
grupos = await obtenerGrupos();
|
||||
} catch (e) {
|
||||
error = e instanceof Error ? e.message : 'Error al cargar grupos';
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
function abrirModalCrear() {
|
||||
modalEditando = false;
|
||||
formId = 0;
|
||||
formNombre = '';
|
||||
formDescripcion = '';
|
||||
modalOpen = true;
|
||||
}
|
||||
|
||||
function abrirModalEditar(g: Grupo) {
|
||||
modalEditando = true;
|
||||
formId = g.id;
|
||||
formNombre = g.nombre;
|
||||
formDescripcion = g.descripcion ?? '';
|
||||
modalOpen = true;
|
||||
}
|
||||
|
||||
function abrirModalEliminar(g: Grupo) {
|
||||
deleteId = g.id;
|
||||
deleteNombre = g.nombre;
|
||||
deleteModalOpen = true;
|
||||
}
|
||||
|
||||
function seleccionarGrupo(g: Grupo) {
|
||||
selectedGrupo = selectedGrupo?.id === g.id ? null : g;
|
||||
}
|
||||
|
||||
function mostrarNotificacion(titulo: string, msg: string) {
|
||||
successMsg = titulo;
|
||||
errorMsg = msg;
|
||||
notifOpen = true;
|
||||
setTimeout(() => {
|
||||
notifOpen = false;
|
||||
}, 4000);
|
||||
}
|
||||
|
||||
function handleSecondary() {
|
||||
modalOpen = false;
|
||||
}
|
||||
|
||||
function handleDeleteSecondary() {
|
||||
deleteModalOpen = false;
|
||||
}
|
||||
|
||||
async function guardarGrupo() {
|
||||
if (!formNombre) {
|
||||
errorMsg = 'Nombre es obligatorio';
|
||||
notifOpen = true;
|
||||
setTimeout(() => {
|
||||
notifOpen = false;
|
||||
}, 4000);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
if (modalEditando) {
|
||||
await actualizarGrupo(formId, {
|
||||
nombre: formNombre,
|
||||
descripcion: formDescripcion
|
||||
});
|
||||
mostrarNotificacion('Grupo actualizado', '');
|
||||
} else {
|
||||
await crearGrupo({
|
||||
nombre: formNombre,
|
||||
descripcion: formDescripcion
|
||||
});
|
||||
mostrarNotificacion('Grupo creado', '');
|
||||
}
|
||||
modalOpen = false;
|
||||
selectedGrupo = null;
|
||||
await cargarGrupos();
|
||||
} catch (e) {
|
||||
errorMsg = e instanceof Error ? e.message : 'Error al guardar grupo';
|
||||
notifOpen = true;
|
||||
setTimeout(() => {
|
||||
notifOpen = false;
|
||||
}, 4000);
|
||||
}
|
||||
}
|
||||
|
||||
async function confirmarEliminar() {
|
||||
try {
|
||||
await eliminarGrupo(deleteId);
|
||||
deleteModalOpen = false;
|
||||
selectedGrupo = null;
|
||||
mostrarNotificacion('Grupo eliminado', '');
|
||||
await cargarGrupos();
|
||||
} catch (e) {
|
||||
errorMsg = e instanceof Error ? e.message : 'Error al eliminar grupo';
|
||||
notifOpen = true;
|
||||
setTimeout(() => {
|
||||
notifOpen = false;
|
||||
}, 4000);
|
||||
}
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
cargarGrupos();
|
||||
});
|
||||
</script>
|
||||
|
||||
<Header />
|
||||
|
||||
<div class="page-container">
|
||||
<div class="flex justify-between">
|
||||
<h1 class="page-title">Gestión de Grupos</h1>
|
||||
<Button onclick={abrirModalCrear} icon={Add}>Nuevo Grupo</Button>
|
||||
</div>
|
||||
|
||||
{#if error}
|
||||
<InlineNotification kind="error" title="Error" subtitle={error} hideCloseButton />
|
||||
{/if}
|
||||
|
||||
{#if loading}
|
||||
<DataTableSkeleton {headers} rows={5} size="compact" showHeader={false} showToolbar={false} />
|
||||
{:else}
|
||||
<TableContainer title="Grupos" description="Listado de grupos del sistema">
|
||||
<Table>
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
{#each headers as header}
|
||||
<TableHeader>{header.value}</TableHeader>
|
||||
{/each}
|
||||
<TableHeader>Acciones</TableHeader>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{#each grupos as g (g.id)}
|
||||
<TableRow
|
||||
class="selected-row={selectedGrupo?.id === g.id}"
|
||||
onclick={() => seleccionarGrupo(g)}
|
||||
onkeydown={(e) => e.key === 'Enter' && seleccionarGrupo(g)}
|
||||
tabindex={0}
|
||||
style="cursor: pointer"
|
||||
>
|
||||
{#each headers as header}
|
||||
<TableCell>{String(g[header.key] ?? '-')}</TableCell>
|
||||
{/each}
|
||||
<TableCell class="acciones-cell">
|
||||
<Button kind="ghost" size="small" icon={Edit} onclick={() => abrirModalEditar(g)}>
|
||||
Editar
|
||||
</Button>
|
||||
<Button
|
||||
kind="ghost"
|
||||
size="small"
|
||||
icon={TrashCan}
|
||||
onclick={() => abrirModalEliminar(g)}
|
||||
>
|
||||
Eliminar
|
||||
</Button>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
{/each}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
|
||||
{#if selectedGrupo}
|
||||
<section class="permisos-section">
|
||||
<h2 class="section-title">
|
||||
Permisos de <strong>{selectedGrupo.nombre}</strong>
|
||||
</h2>
|
||||
{#if selectedGrupo.permisos && selectedGrupo.permisos.length > 0}
|
||||
<div class="permisos-list">
|
||||
<Table>
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableHeader>Nombre</TableHeader>
|
||||
<TableHeader>Alias</TableHeader>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{#each selectedGrupo.permisos as permiso}
|
||||
<TableRow>
|
||||
<TableCell>{permiso.nombre}</TableCell>
|
||||
<TableCell>{permiso.alias || '-'}</TableCell>
|
||||
</TableRow>
|
||||
{/each}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
{:else}
|
||||
<p class="text-secondary">Este grupo no tiene permisos asignados.</p>
|
||||
{/if}
|
||||
</section>
|
||||
{/if}
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<form id="grupo-form" onsubmit={guardarGrupo}>
|
||||
<Modal
|
||||
bind:open={modalOpen}
|
||||
modalHeading={modalEditando ? 'Editar Grupo' : 'Nuevo Grupo'}
|
||||
primaryButtonText={modalEditando ? 'Guardar' : 'Crear'}
|
||||
secondaryButtonText="Cancelar"
|
||||
formId="grupo-form"
|
||||
on:click:button--secondary={handleSecondary}
|
||||
hasForm
|
||||
>
|
||||
<TextInput bind:value={formNombre} labelText="Nombre" placeholder="ej: Administradores" />
|
||||
<TextArea
|
||||
bind:value={formDescripcion}
|
||||
labelText="Descripción"
|
||||
placeholder="Descripción del grupo"
|
||||
/>
|
||||
</Modal>
|
||||
</form>
|
||||
|
||||
<Modal
|
||||
bind:open={deleteModalOpen}
|
||||
modalHeading="Eliminar Grupo"
|
||||
primaryButtonText="Eliminar"
|
||||
secondaryButtonText="Cancelar"
|
||||
onsubmit={confirmarEliminar}
|
||||
on:click:button--secondary={handleDeleteSecondary}
|
||||
danger
|
||||
>
|
||||
<p>¿Estás seguro de que querés eliminar el grupo <strong>{deleteNombre}</strong>?</p>
|
||||
</Modal>
|
||||
|
||||
<Toast
|
||||
kind={successMsg ? 'success' : 'error'}
|
||||
title={successMsg || 'Error'}
|
||||
subtitle={successMsg ? '' : errorMsg}
|
||||
open={notifOpen}
|
||||
/>
|
||||
|
||||
<style>
|
||||
.page-container {
|
||||
padding: 6rem 0 4rem;
|
||||
max-width: 1200px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.page-title {
|
||||
font-size: 1.75rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.permisos-section {
|
||||
margin-top: 2rem;
|
||||
padding: 1rem;
|
||||
border: 1px solid var(--cds-border-subtle-01);
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.section-title {
|
||||
font-size: 1rem;
|
||||
font-weight: 600;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.permisos-list {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
</style>
|
||||
Vendored
+1
@@ -6,6 +6,7 @@ export interface Usuario {
|
||||
export interface Grupo {
|
||||
id: number;
|
||||
nombre: string;
|
||||
descripcion?: string;
|
||||
permisos?: Permiso[];
|
||||
grupos?: Grupo[];
|
||||
usuarios?: Usuario[];
|
||||
|
||||
Reference in new issue
Block a user