diff --git a/.gitignore b/.gitignore index ec63ec6..92001d8 100644 --- a/.gitignore +++ b/.gitignore @@ -14,3 +14,4 @@ comms/.idea/ skills/ /scripts/.idea /scripts/.bsp +front/.svelte-kit.old/ diff --git a/back/config/permisos.go b/back/config/permisos.go index 8e1e151..a2f5007 100644 --- a/back/config/permisos.go +++ b/back/config/permisos.go @@ -32,6 +32,7 @@ var permisosSemilla = []permisoSemilla{ {14, "Generar Reporte de Stock", "stock/reportes", "Generar y consultar reportes de stock."}, {15, "Gestión de Ventas y Facturación", "facturas", "Consultar y operar la facturación y ventas de la empresa."}, {16, "Gestión de Descuentos", "descuentos", "Crear, editar y eliminar descuentos."}, + {17, "Gestión de Formas de Pago", "formas-pago", "Crear, editar y eliminar formas de pago."}, } // InitPermisos crea el catálogo global de permisos y garantiza que cada diff --git a/back/controllers/formasPago/ActualizarFormaDePago.go b/back/controllers/formasPago/ActualizarFormaDePago.go new file mode 100644 index 0000000..c44a60b --- /dev/null +++ b/back/controllers/formasPago/ActualizarFormaDePago.go @@ -0,0 +1,56 @@ +package formapago + +import ( + "net/http" + "strconv" + + "repuestera_back/models" + r "repuestera_back/repositorios" + + "github.com/gin-gonic/gin" +) + +// ActualizarFormaDePago actualiza una forma de pago existente. +func ActualizarFormaDePago(c *gin.Context) { + id, err := strconv.ParseUint(c.Param("id"), 10, 64) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "ID invalido"}) + return + } + if id < 1 { + c.JSON(http.StatusBadRequest, gin.H{"error": "ID no puede ser menor que 1"}) + return + } + + // Obtener la forma de pago actual + fp, err := r.ObtenerRepositorios(c).FormaDePago.ObtenerPorID(uint(id)) + if err != nil { + c.JSON(http.StatusNotFound, gin.H{"error": "Forma de pago no encontrada"}) + return + } + + var input models.FormaDePago + if err := c.ShouldBindJSON(&input); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + if input.Descripcion == "" { + c.JSON(http.StatusBadRequest, gin.H{"error": "La descripción no puede estar vacía"}) + return + } + + // Verificar que no exista otra forma de pago con la misma descripción + if existing, _ := r.ObtenerRepositorios(c).FormaDePago.ObtenerPorDescripcion(input.Descripcion); existing != nil && existing.ID != fp.ID { + c.JSON(http.StatusConflict, gin.H{"error": "ya existe una forma de pago con esa descripción"}) + return + } + + uid := c.GetUint("userID") + if err := r.ObtenerRepositorios(c).FormaDePago.Actualizar(fp, input, uid); err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + + c.JSON(http.StatusOK, fp) +} diff --git a/back/controllers/formasPago/AltaFormaDePago.go b/back/controllers/formasPago/AltaFormaDePago.go new file mode 100644 index 0000000..f752b0b --- /dev/null +++ b/back/controllers/formasPago/AltaFormaDePago.go @@ -0,0 +1,42 @@ +package formapago + +import ( + "net/http" + r "repuestera_back/repositorios" + "strconv" + + "github.com/gin-gonic/gin" + "gorm.io/gorm" +) + +func AltaFormaDePago(c *gin.Context) { + id, err := strconv.ParseUint(c.Param("id"), 10, 64) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "ID invalido"}) + return + } + if id < 1 { + c.JSON(http.StatusBadRequest, gin.H{"error": "ID no puede ser menor que 1"}) + return + } + + uid := c.GetUint("userID") + fp, err := r.ObtenerRepositorios(c).FormaDePago.ObtenerPorID(uint(id)) + if err != nil { + c.JSON(http.StatusNotFound, gin.H{"error": "Forma de pago no encontrada"}) + return + } + + if !fp.DeletedAt.Valid { + c.JSON(http.StatusBadRequest, gin.H{"error": "Forma de pago no está eliminada"}) + return + } + + fp.DeletedAt = gorm.DeletedAt{} + if err := r.ObtenerRepositorios(c).FormaDePago.Alta(fp, *fp, uid); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + c.Status(http.StatusOK) +} diff --git a/back/controllers/formasPago/CrearFormaDePago.go b/back/controllers/formasPago/CrearFormaDePago.go new file mode 100644 index 0000000..21a10ce --- /dev/null +++ b/back/controllers/formasPago/CrearFormaDePago.go @@ -0,0 +1,41 @@ +package formapago + +import ( + "errors" + "net/http" + + "repuestera_back/models" + r "repuestera_back/repositorios" + + "github.com/gin-gonic/gin" + "gorm.io/gorm" +) + +func CrearFormaDePago(c *gin.Context) { + var fp models.FormaDePago + if err := c.ShouldBindJSON(&fp); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + if fp.Descripcion == "" { + c.JSON(http.StatusBadRequest, gin.H{"error": "La descripción es obligatoria"}) + return + } + + repo := r.ObtenerRepositorios(c).FormaDePago + if _, err := repo.ObtenerPorDescripcion(fp.Descripcion); err == nil { + c.JSON(http.StatusConflict, gin.H{"error": "ya existe una forma de pago con esa descripción"}) + return + } else if !errors.Is(err, gorm.ErrRecordNotFound) { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + + if err := repo.Crear(fp, c.GetUint("userID")); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + c.Status(http.StatusCreated) +} diff --git a/back/controllers/formasPago/EliminarFormaDePago.go b/back/controllers/formasPago/EliminarFormaDePago.go new file mode 100644 index 0000000..a5fb8cc --- /dev/null +++ b/back/controllers/formasPago/EliminarFormaDePago.go @@ -0,0 +1,29 @@ +package formapago + +import ( + "net/http" + r "repuestera_back/repositorios" + "strconv" + + "github.com/gin-gonic/gin" +) + +func EliminarFormaDePago(c *gin.Context) { + id, err := strconv.ParseUint(c.Param("id"), 10, 64) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "ID invalido"}) + return + } + if id < 1 { + c.JSON(http.StatusBadRequest, gin.H{"error": "ID no puede ser menor que 1"}) + return + } + + uid := c.GetUint("userID") + err = r.ObtenerRepositorios(c).FormaDePago.Baja(uint(id), uid) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + c.Status(http.StatusOK) +} diff --git a/back/controllers/formasPago/ObtenerFormaDePago.go b/back/controllers/formasPago/ObtenerFormaDePago.go new file mode 100644 index 0000000..8360b7f --- /dev/null +++ b/back/controllers/formasPago/ObtenerFormaDePago.go @@ -0,0 +1,30 @@ +package formapago + +import ( + "net/http" + "strconv" + + r "repuestera_back/repositorios" + + "github.com/gin-gonic/gin" +) + +func ObtenerFormaDePago(c *gin.Context) { + id, err := strconv.ParseUint(c.Param("id"), 10, 64) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "ID invalido"}) + return + } + if id < 1 { + c.JSON(http.StatusBadRequest, gin.H{"error": "ID no puede ser menor que 1"}) + return + } + + fp, err := r.ObtenerRepositorios(c).FormaDePago.ObtenerPorID(uint(id)) + if err != nil { + c.JSON(http.StatusNotFound, gin.H{"error": "Forma de pago no encontrada"}) + return + } + + c.JSON(http.StatusOK, fp) +} diff --git a/back/repositorios/RepositorioFormaDePago.go b/back/repositorios/RepositorioFormaDePago.go index 85aae45..27abf71 100644 --- a/back/repositorios/RepositorioFormaDePago.go +++ b/back/repositorios/RepositorioFormaDePago.go @@ -8,6 +8,7 @@ import ( type RepositorioFormaDePago interface { IRepositorio[models.FormaDePago] + ObtenerPorDescripcion(descripcion string) (*models.FormaDePago, error) } type repositorioFormaDePago struct { @@ -23,3 +24,13 @@ func NuevoRepositorioFormaDePago(db *gorm.DB, empresaID uint) RepositorioFormaDe empresaID: empresaID, } } + +// ObtenerPorDescripcion busca una forma de pago por descripción dentro de la +// empresa, incluyendo las dadas de baja para validar duplicados al reactivar. +func (r *repositorioFormaDePago) ObtenerPorDescripcion(descripcion string) (*models.FormaDePago, error) { + var fp models.FormaDePago + if err := r.db.Unscoped().Where("descripcion = ?", descripcion).First(&fp).Error; err != nil { + return nil, err + } + return &fp, nil +} diff --git a/back/routes/FormaDePagoRoute.go b/back/routes/FormaDePagoRoute.go index 88967de..2a3e59a 100644 --- a/back/routes/FormaDePagoRoute.go +++ b/back/routes/FormaDePagoRoute.go @@ -8,9 +8,21 @@ import ( ) func FormaDePagoRoute(r *gin.Engine) { - grupo := r.Group("/formas-pago") - grupo.Use(middleware.AuthMiddleware(15)) + // Lectura: facturación (15) necesita las formas de pago activas, y gestión + // de formas de pago (17) necesita el listado completo. + lectura := r.Group("/formas-pago") + lectura.Use(middleware.AuthMiddleware(15, 17)) { - grupo.GET("/", formapago.ObtenerFormasPago) + lectura.GET("/", formapago.ObtenerFormasPago) + lectura.GET("/:id", formapago.ObtenerFormaDePago) + } + + gestion := r.Group("/formas-pago") + gestion.Use(middleware.AuthMiddleware(17)) + { + gestion.POST("/", formapago.CrearFormaDePago) + gestion.PUT("/:id", formapago.ActualizarFormaDePago) + gestion.DELETE("/:id", formapago.EliminarFormaDePago) + gestion.PATCH("/:id/alta", formapago.AltaFormaDePago) } } diff --git a/front/src/lib/hooks/formas-pago/actualizarFormaDePago.ts b/front/src/lib/hooks/formas-pago/actualizarFormaDePago.ts new file mode 100644 index 0000000..0e99b6e --- /dev/null +++ b/front/src/lib/hooks/formas-pago/actualizarFormaDePago.ts @@ -0,0 +1,24 @@ +import { API_URL } from '$lib/env'; +import { getToken } from '../token'; + +export async function actualizarFormaDePago(id: number, descripcion: string) { + descripcion = descripcion.trim(); + if (descripcion === '') return 'No se acepta una descripción vacía o con espacios'; + try { + const req = await fetch(`${API_URL}/formas-pago/${id}`, { + method: 'PUT', + headers: { + Authorization: `Bearer ${getToken()}`, + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ descripcion }) + }); + if (!req.ok) { + const data: { error: string } = await req.json(); + return data.error || 'No se pudo actualizar la forma de pago'; + } + return 'ok'; + } catch { + return 'No se pudo alcanzar el servidor'; + } +} diff --git a/front/src/lib/hooks/formas-pago/altaFormaDePago.ts b/front/src/lib/hooks/formas-pago/altaFormaDePago.ts new file mode 100644 index 0000000..fce6c9f --- /dev/null +++ b/front/src/lib/hooks/formas-pago/altaFormaDePago.ts @@ -0,0 +1,20 @@ +import { API_URL } from '$lib/env'; +import { getToken } from '../token'; + +export async function AltaFormaDePago(id: number) { + try { + const req = await fetch(`${API_URL}/formas-pago/${id}/alta`, { + method: 'PATCH', + headers: { + Authorization: `Bearer ${getToken()}` + } + }); + if (req.ok) { + return 'ok'; + } + const data = await req.json(); + return data.error; + } catch { + return 'no se pudo alcanzar el servidor'; + } +} diff --git a/front/src/lib/hooks/formas-pago/crearFormaDePago.ts b/front/src/lib/hooks/formas-pago/crearFormaDePago.ts new file mode 100644 index 0000000..ea2d8fd --- /dev/null +++ b/front/src/lib/hooks/formas-pago/crearFormaDePago.ts @@ -0,0 +1,24 @@ +import { API_URL } from '$lib/env'; +import { getToken } from '../token'; + +export async function crearFormaDePago(descripcion: string) { + descripcion = descripcion.trim(); + if (descripcion === '') return 'No se acepta una descripción vacía o con espacios'; + try { + const req = await fetch(`${API_URL}/formas-pago/`, { + method: 'POST', + headers: { + Authorization: `Bearer ${getToken()}`, + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ descripcion }) + }); + if (!req.ok) { + const data: { error: string } = await req.json(); + return data.error || 'No se pudo crear la forma de pago'; + } + return 'ok'; + } catch { + return 'No se pudo alcanzar el servidor'; + } +} diff --git a/front/src/lib/hooks/formas-pago/eliminarFormaDePago.ts b/front/src/lib/hooks/formas-pago/eliminarFormaDePago.ts new file mode 100644 index 0000000..555c7e7 --- /dev/null +++ b/front/src/lib/hooks/formas-pago/eliminarFormaDePago.ts @@ -0,0 +1,20 @@ +import { API_URL } from '$lib/env'; +import { getToken } from '../token'; + +export async function eliminarFormaDePago(id: number) { + try { + const req = await fetch(`${API_URL}/formas-pago/${id}`, { + method: 'DELETE', + headers: { + Authorization: `Bearer ${getToken()}` + } + }); + if (req.ok) { + return 'Ok'; + } + const data = await req.json(); + return data.error; + } catch { + return 'no se pudo alcanzar el servidor'; + } +} diff --git a/front/src/lib/hooks/formas-pago/obtenerFormasPago.ts b/front/src/lib/hooks/formas-pago/obtenerFormasPago.ts new file mode 100644 index 0000000..7795852 --- /dev/null +++ b/front/src/lib/hooks/formas-pago/obtenerFormasPago.ts @@ -0,0 +1,15 @@ +import { API_URL } from '$lib/env'; +import type { FormaDePago } from '../../../types'; +import { getToken } from '../token'; + +export async function obtenerFormasPago(fetch2?: Function) { + const fetchFn = fetch2 ? fetch2 : fetch; + const req = await fetchFn(`${API_URL}/formas-pago/`, { + method: 'GET', + headers: { + Authorization: `Bearer ${getToken()}` + } + }); + if (!req.ok) return 'Hubo un error y no se pudieron obtener las formas de pago'; + return (await req.json()) as FormaDePago[]; +} diff --git a/front/src/routes/formas-pago/+page.svelte b/front/src/routes/formas-pago/+page.svelte new file mode 100644 index 0000000..3dfb394 --- /dev/null +++ b/front/src/routes/formas-pago/+page.svelte @@ -0,0 +1,111 @@ + + +
+
+
+

Gestión de Formas de Pago

+ +
+{#if error} + +{/if} +{#if typeof data.formasPago === "undefined" || data.formasPago === null} + +{:else if formasPago.length === 0} + + + + + {#each headers as header} + {header.value} + {/each} + Acciones + + + + + No hay formas de pago para mostrar, registre una + + +
+
+{:else} + + + + + {#each headers as header} + {header.value} + {/each} + Acciones + + + + {#each formasPago as p} + + {#each headers as header} + {header.key === 'DeletedAt' ? (p.DeletedAt ? '✖' : '✔') : String(p[header.key] ?? '-')} + {/each} + + + {#if p.DeletedAt} + + {:else} + + {/if} + + + {/each} + +
+
+{/if} +
+ + + openCrear = false} /> + + { openDelete = false; formaAEliminar = null; }} /> + + openAlta = false} /> + + { openEdit = false; formaSeleccionada = null; }} /> diff --git a/front/src/routes/formas-pago/+page.ts b/front/src/routes/formas-pago/+page.ts new file mode 100644 index 0000000..df74065 --- /dev/null +++ b/front/src/routes/formas-pago/+page.ts @@ -0,0 +1,10 @@ +import { obtenerFormasPago } from '$lib/hooks/formas-pago/obtenerFormasPago'; + +export const ssr = false; + +export async function load({ depends, fetch }) { + depends('formasPago:load'); + const formasPago = await obtenerFormasPago(fetch); + + return { formasPago: formasPago }; +} diff --git a/front/src/routes/formas-pago/AltaFormaDePagoForm.svelte b/front/src/routes/formas-pago/AltaFormaDePagoForm.svelte new file mode 100644 index 0000000..f9c6ef5 --- /dev/null +++ b/front/src/routes/formas-pago/AltaFormaDePagoForm.svelte @@ -0,0 +1,80 @@ + + +
{ + e.preventDefault(); + if (loading) return; + await altaFormaDePago(); + }} +> + + {#if error} + + {/if} + {#if forma} +

¿Dar de alta la forma de pago {forma.descripcion}?

+ {/if} + {#if success} + + {/if} +
+
diff --git a/front/src/routes/formas-pago/CrearFormaDePagoForm.svelte b/front/src/routes/formas-pago/CrearFormaDePagoForm.svelte new file mode 100644 index 0000000..6db4ac5 --- /dev/null +++ b/front/src/routes/formas-pago/CrearFormaDePagoForm.svelte @@ -0,0 +1,68 @@ + + +
{ + e.preventDefault(); + if (enviando) return; + enviando = true; + error = ''; + if (!descripcion.trim()) { + error = 'Falta Descripción'; + } + if (error === '') { + const result = await crearFormaDePago(descripcion); + if (result === 'ok') { + invalidate('formasPago:load'); + handleClose(); + } else { + error = result ?? 'Error desconocido'; + } + } + enviando = false; + }} +> + + {#if error} +
{error}
+ {/if} + +
{String(descripcion).length}/20
+
+
diff --git a/front/src/routes/formas-pago/EditarFormaDePagoForm.svelte b/front/src/routes/formas-pago/EditarFormaDePagoForm.svelte new file mode 100644 index 0000000..04e2d8f --- /dev/null +++ b/front/src/routes/formas-pago/EditarFormaDePagoForm.svelte @@ -0,0 +1,74 @@ + + +
{ + e.preventDefault(); + if (enviando) return; + enviando = true; + error = ''; + if (!descripcion.trim()) { + error = 'Falta Descripción'; + } + if (error === '' && forma) { + const result = await actualizarFormaDePago(forma.ID, descripcion); + if (result === 'ok') { + invalidate('formasPago:load'); + handleClose(); + } else { + error = result ?? 'Error desconocido'; + } + } + enviando = false; + }} +> + + {#if error} +
{error}
+ {/if} + +
{String(descripcion).length}/20
+
+
diff --git a/front/src/routes/formas-pago/EliminarFormaDePagoForm.svelte b/front/src/routes/formas-pago/EliminarFormaDePagoForm.svelte new file mode 100644 index 0000000..749bc6f --- /dev/null +++ b/front/src/routes/formas-pago/EliminarFormaDePagoForm.svelte @@ -0,0 +1,51 @@ + + +
+ + {#if error} +
{error}
+ {/if} + ¿Está seguro de que desea borrar esta Forma de Pago? +
+
diff --git a/front/src/types.d.ts b/front/src/types.d.ts index 0d50da0..f0bb13d 100644 --- a/front/src/types.d.ts +++ b/front/src/types.d.ts @@ -327,3 +327,8 @@ export interface FacturaResumen { precioUnitario: number; }>; } + +export interface FormaDePago extends BaseModel { + empresaId?: number; + descripcion: string; +}