Private
Public Access
hecha migracion de hooks a un builder de logs
This commit is contained in:
1 parent
5f741b3cc7
commit
38afdcc742
15 files changed
+402
-274
No files matched your search
@@ -1,201 +0,0 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"reflect"
|
||||
"repuestera_back/models/logs"
|
||||
|
||||
"gorm.io/datatypes"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func SetupAuditoria(db *gorm.DB) {
|
||||
if err := db.Callback().Update().Before("gorm:update").Register("auditoria:capturar_anterior", capturarEstadoAnterior); err != nil {
|
||||
log.Println("ERROR registrando capturar_anterior:", err)
|
||||
}
|
||||
if err := db.Callback().Update().After("gorm:update").Register("auditoria:log_update", generarLogUpdate); err != nil {
|
||||
log.Println("ERROR registrando log_update:", err)
|
||||
}
|
||||
if err := db.Callback().Create().After("gorm:create").Register("auditoria:log_create", generarLogCreate); err != nil {
|
||||
log.Println("ERROR registrando log_create:", err)
|
||||
}
|
||||
if err := db.Callback().Delete().Before("gorm:delete").Register("auditoria:log_delete", generarLogDelete); err != nil {
|
||||
log.Println("ERROR registrando log_delete:", err)
|
||||
}
|
||||
}
|
||||
|
||||
func capturarEstadoAnterior(tx *gorm.DB) {
|
||||
if tx.Statement.Schema == nil || auditoriaDeshabilitada(tx) {
|
||||
return
|
||||
}
|
||||
|
||||
pkField := tx.Statement.Schema.PrioritizedPrimaryField
|
||||
if pkField == nil {
|
||||
return
|
||||
}
|
||||
|
||||
reflectValue := tx.Statement.ReflectValue
|
||||
if !reflectValue.IsValid() {
|
||||
return
|
||||
}
|
||||
|
||||
pkValue, isZero := pkField.ValueOf(context.Background(), reflectValue)
|
||||
if isZero {
|
||||
return
|
||||
}
|
||||
|
||||
modeloAnterior := reflect.New(tx.Statement.Schema.ModelType).Interface()
|
||||
|
||||
if err := tx.Session(&gorm.Session{NewDB: true}).
|
||||
Model(modeloAnterior).
|
||||
First(modeloAnterior, pkValue).Error; err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
tx.Set("auditoria:anterior", modeloAnterior)
|
||||
}
|
||||
|
||||
func generarLogUpdate(tx *gorm.DB) {
|
||||
if tx.Statement.Schema == nil || auditoriaDeshabilitada(tx) {
|
||||
return
|
||||
}
|
||||
|
||||
anteriorVal, ok := tx.Get("auditoria:anterior")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
nuevo := tx.Statement.Dest
|
||||
detalles := generarDetalles(tx.Statement.Table, anteriorVal, nuevo)
|
||||
|
||||
if len(detalles) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
guardarLog(tx, "ACTUALIZAR", detalles)
|
||||
}
|
||||
|
||||
func generarLogCreate(tx *gorm.DB) {
|
||||
if tx.Statement.Schema == nil || auditoriaDeshabilitada(tx) {
|
||||
return
|
||||
}
|
||||
|
||||
detalles := []logs.LogDetalle{
|
||||
{
|
||||
ID: 0,
|
||||
NombreTabla: tx.Statement.Table,
|
||||
Columna: "*",
|
||||
ValorNuevo: fmt.Sprintf("Registro creado (ID: %v)", obtenerID(tx.Statement.Dest)),
|
||||
},
|
||||
}
|
||||
|
||||
guardarLog(tx, "CREAR", detalles)
|
||||
}
|
||||
|
||||
func generarLogDelete(tx *gorm.DB) {
|
||||
if tx.Statement.Schema == nil || auditoriaDeshabilitada(tx) {
|
||||
return
|
||||
}
|
||||
|
||||
detalles := []logs.LogDetalle{
|
||||
{
|
||||
ID: 0,
|
||||
NombreTabla: tx.Statement.Table,
|
||||
Columna: "*",
|
||||
ValorAnterior: fmt.Sprintf("Registro eliminado (ID: %v)", obtenerID(tx.Statement.Dest)),
|
||||
},
|
||||
}
|
||||
|
||||
guardarLog(tx, "ELIMINAR", detalles)
|
||||
}
|
||||
|
||||
func generarDetalles(tabla string, anterior, nuevo interface{}) []logs.LogDetalle {
|
||||
var detalles []logs.LogDetalle
|
||||
|
||||
valAnterior := reflect.ValueOf(anterior)
|
||||
valNuevo := reflect.ValueOf(nuevo)
|
||||
|
||||
for valAnterior.Kind() == reflect.Ptr {
|
||||
valAnterior = valAnterior.Elem()
|
||||
}
|
||||
for valNuevo.Kind() == reflect.Ptr {
|
||||
valNuevo = valNuevo.Elem()
|
||||
}
|
||||
|
||||
if valAnterior.Kind() != reflect.Struct || valNuevo.Kind() != reflect.Struct {
|
||||
return detalles
|
||||
}
|
||||
|
||||
tipo := valAnterior.Type()
|
||||
|
||||
for i := 0; i < tipo.NumField(); i++ {
|
||||
campo := tipo.Field(i)
|
||||
|
||||
if campo.PkgPath != "" { // campo no exportado
|
||||
continue
|
||||
}
|
||||
if campo.Name == "CreatedAt" || campo.Name == "UpdatedAt" || campo.Name == "DeletedAt" {
|
||||
continue
|
||||
}
|
||||
|
||||
campoNuevo := valNuevo.FieldByName(campo.Name)
|
||||
if !campoNuevo.IsValid() {
|
||||
continue
|
||||
}
|
||||
|
||||
vAnt := fmt.Sprintf("%v", valAnterior.Field(i).Interface())
|
||||
vNue := fmt.Sprintf("%v", campoNuevo.Interface())
|
||||
|
||||
if vAnt != vNue {
|
||||
detalles = append(detalles, logs.LogDetalle{
|
||||
ID: uint(i),
|
||||
NombreTabla: tabla,
|
||||
Columna: campo.Name,
|
||||
ValorAnterior: vAnt,
|
||||
ValorNuevo: vNue,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return detalles
|
||||
}
|
||||
|
||||
func guardarLog(tx *gorm.DB, accion string, detalles []logs.LogDetalle) {
|
||||
usuarioID, okUsuario := tx.Get("auditoria:usuario_id")
|
||||
|
||||
if !okUsuario {
|
||||
log.Printf("ADVERTENCIA: Operación '%s' en tabla '%s' no auditada: falta 'auditoria:usuario_id' en contexto GORM", accion, tx.Statement.Table)
|
||||
return
|
||||
}
|
||||
|
||||
logEntry := logs.Log{
|
||||
UsuarioID: usuarioID.(uint),
|
||||
Accion: accion,
|
||||
Detalles: datatypes.JSONSlice[logs.LogDetalle](detalles),
|
||||
}
|
||||
|
||||
if err := DB.Create(&logEntry).Error; err != nil {
|
||||
log.Printf("ERROR guardarLog: falló al crear entrada de log: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func auditoriaDeshabilitada(tx *gorm.DB) bool {
|
||||
return tx.Statement.Table == "logs"
|
||||
}
|
||||
|
||||
func obtenerID(dest interface{}) interface{} {
|
||||
val := reflect.ValueOf(dest)
|
||||
for val.Kind() == reflect.Ptr {
|
||||
val = val.Elem()
|
||||
}
|
||||
if val.Kind() != reflect.Struct {
|
||||
return nil
|
||||
}
|
||||
campoID := val.FieldByName("ID")
|
||||
if campoID.IsValid() {
|
||||
return campoID.Interface()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -20,7 +20,7 @@ func EliminarMarca(c *gin.Context) {
|
||||
}
|
||||
|
||||
uid := c.GetUint("userID")
|
||||
err = r.ObtenerRepositorios().Marca.Eliminar(uint(id), uid)
|
||||
err = r.ObtenerRepositorios().Marca.Baja(uint(id), uid)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
|
||||
@@ -8,21 +8,20 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func EliminarRepuesto(c *gin.Context){
|
||||
func EliminarRepuesto(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){
|
||||
if id < 1 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID no puede ser menor que 1"})
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
uid, _ := c.Get("userID")
|
||||
if err := r.ObtenerRepositorios().Repuesto.Eliminar(uint(id), uid.(uint)); err != nil {
|
||||
if err := r.ObtenerRepositorios().Repuesto.Baja(uint(id), uid.(uint)); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -13,6 +13,10 @@ type LogBuilder struct {
|
||||
|
||||
var _ IBuilder[logs.Log] = (*LogBuilder)(nil)
|
||||
|
||||
func NewLogBuilder() *LogBuilder {
|
||||
return &LogBuilder{}
|
||||
}
|
||||
|
||||
func (b *LogBuilder) Uid(uid uint) {
|
||||
if uid < 1 {
|
||||
b.error = errors.Join(b.error, errors.New("La id no es válida"))
|
||||
@@ -32,10 +36,14 @@ func (b *LogBuilder) Accion(acc string) {
|
||||
}
|
||||
|
||||
func (b *LogBuilder) AñadirDetalle(detalle logs.LogDetalle) {
|
||||
b.checkEspacios(&detalle.ValorNuevo, "ValorNuevo no puede ser nulo o vacío")
|
||||
b.checkEspacios(&detalle.ValorAnterior, "ValorAnterior no puede ser nulo o vacío")
|
||||
b.checkEspacios(&detalle.Columna, "Columna no puede ser nula o vacía")
|
||||
b.checkEspacios(&detalle.NombreTabla, "el nombre de tabla no puede ser nulo o vacío")
|
||||
b.checkEspacios(&detalle.Columna, "Columna no puede ser nula o vacía")
|
||||
|
||||
detalle.ValorAnterior = strings.TrimSpace(detalle.ValorAnterior)
|
||||
detalle.ValorNuevo = strings.TrimSpace(detalle.ValorNuevo)
|
||||
if len(detalle.ValorAnterior) == 0 && len(detalle.ValorNuevo) == 0 {
|
||||
b.error = errors.Join(b.error, errors.New("ValorAnterior o ValorNuevo debe tener un valor"))
|
||||
}
|
||||
|
||||
if b.error != nil {
|
||||
return
|
||||
@@ -45,6 +53,12 @@ func (b *LogBuilder) AñadirDetalle(detalle logs.LogDetalle) {
|
||||
b.log.Detalles = append(b.log.Detalles, detalle)
|
||||
}
|
||||
|
||||
func (b *LogBuilder) AñadirDetalles(detalles []logs.LogDetalle) {
|
||||
for _, detalle := range detalles {
|
||||
b.AñadirDetalle(detalle)
|
||||
}
|
||||
}
|
||||
|
||||
func (b *LogBuilder) checkEspacios(a *string, err string) {
|
||||
*a = strings.TrimSpace(*a)
|
||||
if len([]byte(*a)) == 0 {
|
||||
@@ -54,6 +68,12 @@ func (b *LogBuilder) checkEspacios(a *string, err string) {
|
||||
}
|
||||
|
||||
func (b *LogBuilder) Build() (*logs.Log, error) {
|
||||
if b.log.UsuarioID < 1 {
|
||||
b.error = errors.Join(b.error, errors.New("El log debe tener un usuario válido"))
|
||||
}
|
||||
if len(b.log.Accion) == 0 {
|
||||
b.error = errors.Join(b.error, errors.New("El log debe tener una acción"))
|
||||
}
|
||||
if b.error != nil {
|
||||
return nil, b.error
|
||||
}
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
package dto_builders
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
|
||||
"repuestera_back/models/logs"
|
||||
)
|
||||
|
||||
type LogDirector struct{}
|
||||
|
||||
func NewLogDirector() *LogDirector {
|
||||
return &LogDirector{}
|
||||
}
|
||||
|
||||
// Custom construye un log para una acción y detalles arbitrarios.
|
||||
func (d *LogDirector) Custom(uid uint, accion string, detalles []logs.LogDetalle) (*logs.Log, error) {
|
||||
builder := NewLogBuilder()
|
||||
builder.Uid(uid)
|
||||
builder.Accion(accion)
|
||||
builder.AñadirDetalles(detalles)
|
||||
return builder.Build()
|
||||
}
|
||||
|
||||
// Crear construye el log de un registro creado.
|
||||
func (d *LogDirector) Crear(uid uint, tabla string, id any) (*logs.Log, error) {
|
||||
return d.Custom(uid, logs.AccionCrear, []logs.LogDetalle{
|
||||
{
|
||||
NombreTabla: tabla,
|
||||
Columna: "*",
|
||||
ValorNuevo: fmt.Sprintf("Registro creado (ID: %v)", id),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// Modificar construye el log comparando el estado anterior y el nuevo.
|
||||
// Si no hay diferencias, retorna (nil, nil).
|
||||
func (d *LogDirector) Modificar(uid uint, tabla string, anterior, nuevo any) (*logs.Log, error) {
|
||||
detalles := generarDetalles(tabla, anterior, nuevo)
|
||||
if len(detalles) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return d.Custom(uid, logs.AccionModificar, detalles)
|
||||
}
|
||||
|
||||
// Eliminar construye el log de un borrado físico.
|
||||
func (d *LogDirector) Eliminar(uid uint, tabla string, id any) (*logs.Log, error) {
|
||||
return d.Custom(uid, logs.AccionEliminar, []logs.LogDetalle{
|
||||
{
|
||||
NombreTabla: tabla,
|
||||
Columna: "*",
|
||||
ValorAnterior: fmt.Sprintf("Registro eliminado (ID: %v)", id),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// Baja construye el log de un borrado lógico.
|
||||
func (d *LogDirector) Baja(uid uint, tabla string, id any) (*logs.Log, error) {
|
||||
return d.Custom(uid, logs.AccionBaja, []logs.LogDetalle{
|
||||
{
|
||||
NombreTabla: tabla,
|
||||
Columna: "*",
|
||||
ValorAnterior: fmt.Sprintf("Registro activo (ID: %v)", id),
|
||||
ValorNuevo: "Registro dado de baja",
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// Alta construye el log de la restauración de un registro dado de baja.
|
||||
func (d *LogDirector) Alta(uid uint, tabla string, id any) (*logs.Log, error) {
|
||||
return d.Custom(uid, logs.AccionAlta, []logs.LogDetalle{
|
||||
{
|
||||
NombreTabla: tabla,
|
||||
Columna: "*",
|
||||
ValorAnterior: fmt.Sprintf("Registro dado de baja (ID: %v)", id),
|
||||
ValorNuevo: "Registro dado de alta",
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func generarDetalles(tabla string, anterior, nuevo any) []logs.LogDetalle {
|
||||
var detalles []logs.LogDetalle
|
||||
|
||||
valAnterior := reflect.ValueOf(anterior)
|
||||
valNuevo := reflect.ValueOf(nuevo)
|
||||
|
||||
for valAnterior.IsValid() && valAnterior.Kind() == reflect.Ptr {
|
||||
if valAnterior.IsNil() {
|
||||
return detalles
|
||||
}
|
||||
valAnterior = valAnterior.Elem()
|
||||
}
|
||||
for valNuevo.IsValid() && valNuevo.Kind() == reflect.Ptr {
|
||||
if valNuevo.IsNil() {
|
||||
return detalles
|
||||
}
|
||||
valNuevo = valNuevo.Elem()
|
||||
}
|
||||
|
||||
if !valAnterior.IsValid() || !valNuevo.IsValid() {
|
||||
return detalles
|
||||
}
|
||||
if valAnterior.Kind() != reflect.Struct || valNuevo.Kind() != reflect.Struct {
|
||||
return detalles
|
||||
}
|
||||
if valAnterior.Type() != valNuevo.Type() {
|
||||
return detalles
|
||||
}
|
||||
|
||||
tipo := valAnterior.Type()
|
||||
|
||||
for i := 0; i < tipo.NumField(); i++ {
|
||||
campo := tipo.Field(i)
|
||||
|
||||
if campo.PkgPath != "" { // campo no exportado
|
||||
continue
|
||||
}
|
||||
if campo.Name == "Model" || campo.Name == "CreatedAt" || campo.Name == "UpdatedAt" || campo.Name == "DeletedAt" {
|
||||
continue
|
||||
}
|
||||
|
||||
campoNuevo := valNuevo.FieldByName(campo.Name)
|
||||
if !campoNuevo.IsValid() {
|
||||
continue
|
||||
}
|
||||
|
||||
vAnt := fmt.Sprintf("%v", valAnterior.Field(i).Interface())
|
||||
vNue := fmt.Sprintf("%v", campoNuevo.Interface())
|
||||
|
||||
if vAnt != vNue {
|
||||
detalles = append(detalles, logs.LogDetalle{
|
||||
ID: uint(i),
|
||||
NombreTabla: tabla,
|
||||
Columna: campo.Name,
|
||||
ValorAnterior: vAnt,
|
||||
ValorNuevo: vNue,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return detalles
|
||||
}
|
||||
|
||||
// ObtenerID extrae el campo ID de una entidad, siguiendo punteros.
|
||||
func ObtenerID(dest any) any {
|
||||
val := reflect.ValueOf(dest)
|
||||
for val.IsValid() && val.Kind() == reflect.Ptr {
|
||||
if val.IsNil() {
|
||||
return nil
|
||||
}
|
||||
val = val.Elem()
|
||||
}
|
||||
if !val.IsValid() || val.Kind() != reflect.Struct {
|
||||
return nil
|
||||
}
|
||||
campoID := val.FieldByName("ID")
|
||||
if campoID.IsValid() && campoID.CanInterface() {
|
||||
return campoID.Interface()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
package logs
|
||||
|
||||
import "gorm.io/gorm"
|
||||
|
||||
func DBConAuditoria(db *gorm.DB, usuarioID uint) *gorm.DB {
|
||||
return db.Set("auditoria:usuario_id", usuarioID)
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package logs
|
||||
|
||||
const (
|
||||
AccionCustom = "CUSTOM"
|
||||
AccionCrear = "CREAR"
|
||||
AccionModificar = "MODIFICAR"
|
||||
AccionEliminar = "ELIMINAR"
|
||||
AccionBaja = "BAJA"
|
||||
AccionAlta = "ALTA"
|
||||
)
|
||||
@@ -1,7 +1,11 @@
|
||||
package repositorios
|
||||
|
||||
import (
|
||||
"repuestera_back/logs"
|
||||
applog "log"
|
||||
"reflect"
|
||||
|
||||
dto_builders "repuestera_back/dto/Builders"
|
||||
models_logs "repuestera_back/models/logs"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
@@ -13,6 +17,7 @@ type IRepositorio[T any] interface {
|
||||
Crear(entidad T, usuarioID uint) error
|
||||
Actualizar(entidad *T, input T, usuarioID uint) error
|
||||
Eliminar(id uint, usuarioID uint) error
|
||||
Baja(id uint, usuarioID uint) error
|
||||
// Alta updates a soft‑deleted record, clearing DeletedAt so it can be re‑activated.
|
||||
Alta(entidad *T, input T, usuarioID uint) error
|
||||
}
|
||||
@@ -25,10 +30,6 @@ func NewRepositorioBase[T any](db *gorm.DB) *RepositorioBase[T] {
|
||||
return &RepositorioBase[T]{db: db}
|
||||
}
|
||||
|
||||
func (r *RepositorioBase[T]) dbConAuditoria(usuarioID uint) *gorm.DB {
|
||||
return logs.DBConAuditoria(r.db, usuarioID)
|
||||
}
|
||||
|
||||
func (r *RepositorioBase[T]) Guardar(entidad *T) error {
|
||||
return r.db.Save(entidad).Error
|
||||
}
|
||||
@@ -42,29 +43,143 @@ func (r *RepositorioBase[T]) ObtenerTodos() ([]T, error) {
|
||||
}
|
||||
|
||||
func (r *RepositorioBase[T]) ObtenerPorID(id uint) (*T, error) {
|
||||
var entidad T
|
||||
if err := r.db.Unscoped().First(&entidad, id).Error; err != nil {
|
||||
entidad := nuevaEntidad[T]()
|
||||
if err := r.db.Unscoped().First(destinoConsulta(&entidad), id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &entidad, nil
|
||||
}
|
||||
|
||||
func (r *RepositorioBase[T]) Crear(entidad T, usuarioID uint) error {
|
||||
return r.dbConAuditoria(usuarioID).Create(&entidad).Error
|
||||
if err := r.db.Create(destinoConsulta(&entidad)).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
log, err := dto_builders.NewLogDirector().Crear(usuarioID, r.tabla(), dto_builders.ObtenerID(entidad))
|
||||
r.registrarLog(log, err, usuarioID, "creación")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *RepositorioBase[T]) Actualizar(entidad *T, input T, usuarioID uint) error {
|
||||
return r.dbConAuditoria(usuarioID).Model(entidad).Updates(input).Error
|
||||
id := dto_builders.ObtenerID(entidad)
|
||||
|
||||
anterior := nuevaEntidad[T]()
|
||||
if id != nil {
|
||||
if err := r.db.Unscoped().First(destinoConsulta(&anterior), id).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if err := r.db.Model(destinoConsulta(entidad)).Updates(input).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
actual := nuevaEntidad[T]()
|
||||
if id != nil {
|
||||
if err := r.db.Unscoped().First(destinoConsulta(&actual), id).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
actual = input
|
||||
}
|
||||
|
||||
log, err := dto_builders.NewLogDirector().Modificar(usuarioID, r.tabla(), anterior, actual)
|
||||
r.registrarLog(log, err, usuarioID, "modificación")
|
||||
return nil
|
||||
}
|
||||
|
||||
// Eliminar realiza un borrado físico del registro.
|
||||
func (r *RepositorioBase[T]) Eliminar(id uint, usuarioID uint) error {
|
||||
entidad := nuevaEntidad[T]()
|
||||
if err := r.db.Unscoped().Delete(destinoConsulta(&entidad), id).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
log, err := dto_builders.NewLogDirector().Eliminar(usuarioID, r.tabla(), id)
|
||||
r.registrarLog(log, err, usuarioID, "eliminación")
|
||||
return nil
|
||||
}
|
||||
|
||||
// Baja realiza un borrado lógico del registro.
|
||||
func (r *RepositorioBase[T]) Baja(id uint, usuarioID uint) error {
|
||||
entidad := nuevaEntidad[T]()
|
||||
if err := r.db.Delete(destinoConsulta(&entidad), id).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
log, err := dto_builders.NewLogDirector().Baja(usuarioID, r.tabla(), id)
|
||||
r.registrarLog(log, err, usuarioID, "baja")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *RepositorioBase[T]) Alta(entidad *T, input T, usuarioID uint) error {
|
||||
if err := r.dbConAuditoria(usuarioID).Unscoped().Model(entidad).Update("deleted_at", nil).Error; err != nil {
|
||||
modelo := destinoConsulta(entidad)
|
||||
if err := r.db.Unscoped().Model(modelo).Update("deleted_at", nil).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return r.dbConAuditoria(usuarioID).Unscoped().Model(entidad).Updates(input).Error
|
||||
if err := r.db.Unscoped().Model(modelo).Updates(input).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
log, err := dto_builders.NewLogDirector().Alta(usuarioID, r.tabla(), dto_builders.ObtenerID(entidad))
|
||||
r.registrarLog(log, err, usuarioID, "alta")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *RepositorioBase[T]) Eliminar(id uint, usuarioID uint) error {
|
||||
func (r *RepositorioBase[T]) tabla() string {
|
||||
entidad := nuevaEntidad[T]()
|
||||
stmt := &gorm.Statement{DB: r.db}
|
||||
if err := stmt.Parse(destinoConsulta(&entidad)); err == nil && stmt.Schema != nil {
|
||||
return stmt.Schema.Table
|
||||
}
|
||||
|
||||
tipo := reflect.TypeOf(entidad)
|
||||
for tipo != nil && tipo.Kind() == reflect.Ptr {
|
||||
tipo = tipo.Elem()
|
||||
}
|
||||
if tipo == nil {
|
||||
return ""
|
||||
}
|
||||
return r.db.NamingStrategy.TableName(tipo.Name())
|
||||
}
|
||||
|
||||
// registrarLog persiste el log sin interrumpir la operación de negocio si falla.
|
||||
func (r *RepositorioBase[T]) registrarLog(log *models_logs.Log, err error, usuarioID uint, contexto string) {
|
||||
if err != nil {
|
||||
applog.Printf("ERROR construyendo log de %s: %v", contexto, err)
|
||||
return
|
||||
}
|
||||
if log == nil {
|
||||
return
|
||||
}
|
||||
if err := ObtenerRepositorios().Logs.Crear(log, usuarioID); err != nil {
|
||||
applog.Printf("ERROR registrando log de %s: %v", contexto, err)
|
||||
}
|
||||
}
|
||||
|
||||
// nuevaEntidad retorna una instancia no nula del tipo T, incluso si T es un puntero.
|
||||
func nuevaEntidad[T any]() T {
|
||||
var entidad T
|
||||
return r.dbConAuditoria(usuarioID).Delete(&entidad, id).Error
|
||||
tipo := reflect.TypeOf(entidad)
|
||||
if tipo != nil && tipo.Kind() == reflect.Ptr {
|
||||
return reflect.New(tipo.Elem()).Interface().(T)
|
||||
}
|
||||
return entidad
|
||||
}
|
||||
|
||||
// destinoConsulta adapta T al destino que espera GORM, preservando el ID
|
||||
// cuando T es un puntero.
|
||||
func destinoConsulta[T any](entidad *T) any {
|
||||
tipo := reflect.TypeOf(*entidad)
|
||||
if tipo == nil || tipo.Kind() != reflect.Ptr {
|
||||
return entidad
|
||||
}
|
||||
|
||||
valor := reflect.ValueOf(*entidad)
|
||||
if valor.IsNil() {
|
||||
nueva := reflect.New(tipo.Elem())
|
||||
*entidad = nueva.Interface().(T)
|
||||
return *entidad
|
||||
}
|
||||
return *entidad
|
||||
}
|
||||
@@ -28,6 +28,11 @@ func NuevoRepositorioLogs(db *gorm.DB) RepositorioLogs {
|
||||
}
|
||||
}
|
||||
|
||||
// Crear persiste el log directamente, sin auditar la creación del propio log.
|
||||
func (r *repositorioLogs) Crear(entidad *logs.Log, usuarioID uint) error {
|
||||
return r.db.Create(entidad).Error
|
||||
}
|
||||
|
||||
func (r *repositorioLogs) ObtenerPorPaginas(pag uint) ([]logs.Log, error) {
|
||||
var logs []logs.Log
|
||||
if err := r.db.Limit(10).Offset(int(pag) * 10).Find(&logs).Error; err != nil {
|
||||
|
||||
@@ -3,7 +3,6 @@ package repositorios
|
||||
import (
|
||||
dto_builders "repuestera_back/dto/Builders"
|
||||
"repuestera_back/models"
|
||||
"repuestera_back/models/logs"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
@@ -33,26 +32,16 @@ func (r repositorioRepuesto) AltaRepuesto(id uint, uid uint) (*models.Repuesto,
|
||||
}
|
||||
|
||||
err := r.db.Transaction(func(tx *gorm.DB) error {
|
||||
if err := r.dbConAuditoria(uid).Unscoped().Model(&rep).Updates(map[string]any{"deleted_at": nil}).Error; err != nil {
|
||||
if err := tx.Unscoped().Model(&rep).Updates(map[string]any{"deleted_at": nil}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
builder := dto_builders.LogBuilder{}
|
||||
builder.Uid(uid)
|
||||
builder.Accion("Alta")
|
||||
builder.AñadirDetalle(logs.LogDetalle{
|
||||
NombreTabla: "repuestos",
|
||||
Columna: "deleted_at",
|
||||
ValorNuevo: "Borrado deleted_at",
|
||||
ValorAnterior: ".",
|
||||
})
|
||||
|
||||
log, err := builder.Build()
|
||||
log, err := dto_builders.NewLogDirector().Alta(uid, r.tabla(), uint(id))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := ObtenerRepositorios().Logs.Crear(log, uid); err != nil {
|
||||
if err := tx.Create(log).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
|
||||
@@ -52,8 +52,6 @@ func main() {
|
||||
|
||||
fmt.Println("Database connected and migrated successfully")
|
||||
|
||||
config.SetupAuditoria(config.DB)
|
||||
|
||||
repositorios.InicializarRepositorios(config.DB)
|
||||
config.InitPermisos()
|
||||
|
||||
@@ -67,7 +65,5 @@ func main() {
|
||||
routes.LogsRoute(r)
|
||||
routes.MarcaRoute(r)
|
||||
|
||||
fmt.Println("callback registrado:", config.DB.Callback().Create().Get("auditoria:log_create") != nil)
|
||||
|
||||
r.Run(":8080")
|
||||
}
|
||||
@@ -17,8 +17,11 @@ de detalles; ii) el objeto debe armarse por partes, en pasos sucesivos;
|
||||
iii) el objeto no debe entregarse en un estado inválido: si algún paso de
|
||||
la construcción falló, el resultado debe ser un error; iv) el cliente no
|
||||
debe encargarse de detalles internos de la construcción, como la
|
||||
asignación del ID de cada detalle; v) pueden aparecer otros DTOs
|
||||
complejos que requieran su propio constructor bajo el mismo contrato.
|
||||
asignación del ID de cada detalle; v) las secuencias de construcción se
|
||||
repiten para cada operación auditada (crear, modificar, eliminar, baja,
|
||||
alta y acciones personalizadas), por lo que se incorpora un Director que
|
||||
las encapsula. Esta implementación reemplaza a los hooks de GORM que
|
||||
registraban la auditoría de forma automática.
|
||||
|
||||
Estos cambios son los admitidos por el patrón Builder según Gamma et al.
|
||||
(2003): separar la construcción de un objeto complejo de su
|
||||
@@ -30,7 +33,7 @@ where
|
||||
Product is logs.Log (compuesto por logs.LogDetalle)
|
||||
BuildPart() is Uid(uid uint), Accion(acc string), AñadirDetalle(detalle logs.LogDetalle)
|
||||
GetResult() is Build() (*T, error)
|
||||
Director is código cliente que invoca los pasos y luego Build()
|
||||
Director is LogDirector
|
||||
|
||||
comments
|
||||
La interfaz IBuilder[T any] declara únicamente Build() (*T, error), sin
|
||||
@@ -48,20 +51,23 @@ logs.Log) y un campo error. Uid y Accion setean campos de la cabecera.
|
||||
AñadirDetalle asigna al detalle un ID secuencial, igual a la cantidad de
|
||||
detalles ya cargados (por lo tanto comienza en 0), y lo agrega a la lista.
|
||||
Build retorna (nil, error) si el campo error está seteado y, en caso
|
||||
contrario, un puntero al log construido. En el código relevado, los
|
||||
cuerpos de los métodos de construcción están elididos (/* ... */); el
|
||||
campo error es el punto donde pueden registrarse fallas de validación.
|
||||
contrario, un puntero al log construido.
|
||||
|
||||
Director (LogDirector): encapsula las secuencias de construcción para las
|
||||
operaciones auditadas. Expone Custom, Crear, Modificar, Eliminar, Baja y
|
||||
Alta. Cada método configura el builder con el usuario, la acción y los
|
||||
detalles correspondientes, y devuelve el resultado de Build(). Para
|
||||
Modificar compara el estado anterior y el nuevo campo por campo; para las
|
||||
demás acciones genera el detalle adecuado. De este modo, los repositorios
|
||||
no conocen los pasos internos de construcción.
|
||||
|
||||
La declaración `var _ IBuilder[logs.Log] = (*LogBuilder)(nil)` verifica en
|
||||
tiempo de compilación que LogBuilder cumple el contrato de IBuilder para
|
||||
logs.Log.
|
||||
|
||||
No existe una clase Director dedicada: el código cliente cumple ese rol
|
||||
invocando los pasos de construcción y cerrando con Build().
|
||||
|
||||
Verificacion de completitud: Builder, ConcreteBuilder, Product,
|
||||
BuildPart(), GetResult() y Director están mapeados a elementos concretos
|
||||
del diseño; Director no está reificado como clase.
|
||||
del diseño; Director está reificado como LogDirector.
|
||||
#+end_example
|
||||
|
||||
--------------
|
||||
@@ -81,7 +87,7 @@ Where
|
||||
BuildPart() is Accion(acc string)
|
||||
BuildPart() is AñadirDetalle(detalle logs.LogDetalle)
|
||||
GetResult() is Build() (*T, error)
|
||||
Director is código cliente (sin clase dedicada)
|
||||
Director is LogDirector
|
||||
#+end_example
|
||||
|
||||
*** Tabla de equivalencias
|
||||
@@ -92,7 +98,7 @@ Where
|
||||
| =Product= | =logs.Log= | struct (paquete =logs=) | paquete =logs= |
|
||||
| =BuildPart()= | =Uid=, =Accion=, =AñadirDetalle= | métodos | =LogBuilder.go= |
|
||||
| =GetResult()= | =Build() (*T, error)= | método | =IBuilder.go= (contrato), =LogBuilder.go= (implementación) |
|
||||
| =Director= | código cliente | cliente funcional | por completar |
|
||||
| =Director= | =LogDirector= | struct | =back/dto/Builders/LogDirector.go= |
|
||||
|
||||
*** Notas sobre el mapeo
|
||||
- *=BuildPart()= aparece tres veces*: =LogBuilder= tiene un método por
|
||||
@@ -101,9 +107,10 @@ Where
|
||||
- *=BuildPart()= no forma parte de =IBuilder=*: al ser genérica, la
|
||||
interfaz solo puede fijar el contrato común (=Build=); las partes
|
||||
varían por producto.
|
||||
- *=Director= no está reificado*: el cliente cumple ese rol. Si se
|
||||
repitieran secuencias de construcción, podrían extraerse a un
|
||||
Director.
|
||||
- *=Director= está reificado*: =LogDirector= contiene las secuencias de
|
||||
construcción que antes estaban dispersas en los hooks de GORM.
|
||||
- *=LogDirector= expone un método por operación auditada*: =Custom=,
|
||||
=Crear=, =Modificar=, =Eliminar=, =Baja= y =Alta=.
|
||||
|
||||
*** Verificación de completitud
|
||||
- [X] Builder → IBuilder[T any]
|
||||
@@ -111,7 +118,7 @@ Where
|
||||
- [X] Product → logs.Log
|
||||
- [X] BuildPart() → Uid(), Accion(), AñadirDetalle()
|
||||
- [X] GetResult() → Build()
|
||||
- [ ] Director → no reificado (código cliente)
|
||||
- [X] Director → LogDirector
|
||||
|
||||
--------------
|
||||
|
||||
@@ -124,7 +131,7 @@ Where
|
||||
|-------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| *Builder* | Especifica la interfaz abstracta para crear las partes de un objeto producto. Acá se reduce al contrato de obtención: =Build() (*T, error)=. |
|
||||
| *ConcreteBuilder* | Construye y ensambla las partes del producto, mantiene la representación en construcción y provee la operación para obtener el resultado. Acá: =LogBuilder=. |
|
||||
| *Director* | Construye un objeto usando la interfaz del Builder. Acá lo cumple el código cliente. |
|
||||
| *Director* | Construye un objeto usando la interfaz del Builder. Acá: =LogDirector=, que encapsula las secuencias de =Crear=, =Modificar=, =Eliminar=, =Baja=, =Alta= y =Custom=. |
|
||||
| *Product* | Representa el objeto complejo que se construye. Acá: =logs.Log=. |
|
||||
|
||||
--------------
|
||||
@@ -137,16 +144,21 @@ Where
|
||||
| Agregar una nueva parte al =Log= | Sí (nuevo método en =LogBuilder=) | Sin afectar a otros builders |
|
||||
| Cambiar cómo se ensambla el =Log= | Sí (modificar =LogBuilder=) | Los clientes que solo usan =Build()= no se ven afectados |
|
||||
| Agregar validaciones | Sí (registrar en el campo =error=) | =Build()= ya propaga el error |
|
||||
| Agregar una operación auditada | Sí (nuevo método en =LogDirector=) | Reutiliza =LogBuilder= sin modificar el producto |
|
||||
|
||||
*** Cambios Anticipados en el Diseño
|
||||
1. *Nuevos builders* para otros DTOs complejos, reutilizando el contrato
|
||||
=IBuilder[T]=.
|
||||
2. *Más validaciones* durante la construcción (campos obligatorios,
|
||||
coherencia entre acción y detalles).
|
||||
3. *Director* para secuencias repetidas (por ejemplo, logs de alta o
|
||||
baja lógica con los mismos detalles).
|
||||
3. *Nuevas acciones auditadas*: agregar un método al =LogDirector= que
|
||||
reutilice =LogBuilder= (por ejemplo, una acción de negocio específica
|
||||
mediante =Custom=).
|
||||
4. *Copia defensiva* en =Build()= si el builder llegara a reutilizarse
|
||||
(ver consideraciones).
|
||||
5. *Reemplazo de los hooks de GORM*: la auditoría deja de depender de
|
||||
callbacks globales y pasa a ser explícita en los repositorios, que
|
||||
invocan al =LogDirector= después de cada operación.
|
||||
|
||||
*** Restricciones de Diseño Impuestas
|
||||
- *=Build()= sin parámetros:* todo lo necesario debe estar dentro del
|
||||
@@ -173,6 +185,13 @@ entregado comparte memoria con el builder y puede verse modificado. En
|
||||
el uso actual (un builder por log) no es un problema; si se reutilizara,
|
||||
convendría retornar una copia.
|
||||
|
||||
*** Variante 3: Director con secuencias fijas
|
||||
=LogDirector= encapsula las secuencias que antes se repetían en cada
|
||||
operación auditada. Cada método del director crea un =LogBuilder= nuevo,
|
||||
configura usuario, acción y detalles, y delega en =Build()=. De este
|
||||
modo, agregar o cambiar una operación auditada se resuelve en el director
|
||||
sin repetir la secuencia de construcción en los repositorios.
|
||||
|
||||
*** Consideración: detalles con ID secuencial
|
||||
=AñadirDetalle= asigna =detalle.ID = uint(len(b.log.Detalles))=, por lo
|
||||
que el primer detalle recibe el ID 0. El cliente no controla esta
|
||||
@@ -195,6 +214,9 @@ justifican según Gamma et al. (2003):
|
||||
3. *Separación entre construcción y uso:* el cliente obtiene un objeto
|
||||
válido o un error, sin conocer los pasos internos (por ejemplo, la
|
||||
numeración de los detalles).
|
||||
4. *Secuencias repetidas:* las operaciones de crear, modificar, eliminar,
|
||||
dar de baja y restaurar comparten la misma estructura de construcción;
|
||||
el =LogDirector= evita repetirla en cada repositorio.
|
||||
|
||||
*** Análisis de Alternativas
|
||||
| Alternativa | Razón para descartarla |
|
||||
@@ -206,7 +228,7 @@ justifican según Gamma et al. (2003):
|
||||
--------------
|
||||
|
||||
* Verificación con Código Real (EV-COD)
|
||||
Numeración y líneas por completar según el repositorio.
|
||||
Referencias al código actual (los números de línea pueden variar).
|
||||
|
||||
- **EV-COD-___**: =back/dto/Builders/IBuilder.go= ---
|
||||
=type IBuilder[T any] interface { Build() (*T, error) }=.
|
||||
@@ -214,12 +236,27 @@ Numeración y líneas por completar según el repositorio.
|
||||
=log logs.Log= y =error error=.
|
||||
- **EV-COD-___**: =LogBuilder.go= ---
|
||||
=var _ IBuilder[logs.Log] = (*LogBuilder)(nil)=.
|
||||
- **EV-COD-___**: =LogBuilder.go= --- métodos =Uid=, =Accion= y
|
||||
=AñadirDetalle=.
|
||||
- **EV-COD-___**: =LogBuilder.go= --- constructor =NewLogBuilder= y
|
||||
métodos =Uid=, =Accion=, =AñadirDetalle= y =AñadirDetalles=.
|
||||
- **EV-COD-___**: =LogBuilder.go= --- =AñadirDetalle= asigna
|
||||
=detalle.ID = uint(len(b.log.Detalles))=.
|
||||
- **EV-COD-___**: =LogBuilder.go= --- =Build()= retorna =nil, b.error=
|
||||
si hay error, o =&b.log=.
|
||||
- **EV-COD-___**: =LogDirector.go= --- struct =LogDirector= y
|
||||
constructor =NewLogDirector=.
|
||||
- **EV-COD-___**: =LogDirector.go= --- métodos =Custom=, =Crear=,
|
||||
=Modificar=, =Eliminar=, =Baja= y =Alta=.
|
||||
- **EV-COD-___**: =LogDirector.go= --- =Modificar= usa
|
||||
=generarDetalles= para comparar el estado anterior y el nuevo.
|
||||
- **EV-COD-___**: =back/models/logs/acciones.go= --- constantes
|
||||
=AccionCustom=, =AccionCrear=, =AccionModificar=, =AccionEliminar=,
|
||||
=AccionBaja= y =AccionAlta=.
|
||||
- **EV-COD-___**: =back/repositorios/IRepositorio.go= ---
|
||||
=RepositorioBase= invoca al =LogDirector= en =Crear=, =Actualizar=,
|
||||
=Eliminar=, =Baja= y =Alta=, y =registrarLog= persiste el resultado.
|
||||
- **EV-COD-___**: =back/repositorios/IRepositorio.go= --- ya no existe
|
||||
=dbConAuditoria=; los hooks de GORM fueron reemplazados por el
|
||||
director.
|
||||
|
||||
* Referencias
|
||||
- Gamma, E., Helm, R., Johnson, R., & Vlissides, J. (2003). /Design
|
||||
|
||||
@@ -70,8 +70,8 @@ Where
|
||||
|
||||
* Variantes y consideraciones
|
||||
- *Singleton vs. per‑request*: el contenedor usa sync.Once para crear una única instancia.
|
||||
- *Soft‑delete*: el método `Alta` revierte borrados lógicos.
|
||||
- *Auditoría*: `dbConAuditoria` injerta información de usuario en cada operación.
|
||||
- *Soft‑delete*: `Baja` realiza el borrado lógico y `Alta` lo revierte.
|
||||
- *Auditoría*: los repositorios generan logs mediante `LogDirector` y `LogBuilder`; ya no se usan hooks de GORM.
|
||||
|
||||
* Justificación (UNR)
|
||||
Separation of Concerns – mantiene la capa de persistencia aislada.
|
||||
@@ -92,7 +92,7 @@ Open‑Closed – añadir nuevos repositorios no afecta a los existentes.
|
||||
* Análisis de Cambios admitidos
|
||||
- Añadir nuevo repositorio → implementa IRepositorio sin tocar código existente.
|
||||
- Extender repositorio concreto → nuevos métodos (e.g., BuscaPorNombre) sin romper la interfaz.
|
||||
- Cambiar estrategia de auditoría → modificar `dbConAuditoria` en la base.
|
||||
- Cambiar estrategia de auditoría → modificar `registrarLog` en la base de repositorios.
|
||||
|
||||
* Cambios anticipados
|
||||
1. Migrar a otra ORM → cambiar implementación en RepositorioBase.
|
||||
|
||||
@@ -48,10 +48,12 @@
|
||||
<NumberInput fluid labelText="Id de Usuario" min={0} bind:value={filtros.usuarioId} />
|
||||
<Select fluid labelText="Accion del Log" bind:selected={filtros.accion}>
|
||||
<SelectItem text="Todas" value="" />
|
||||
<SelectItem text="Actualizar" value="ACTUALIZAR" />
|
||||
<SelectItem text="Crear" value="CREAR" />
|
||||
<SelectItem text="Modificar" value="MODIFICAR" />
|
||||
<SelectItem text="Eliminar" value="ELIMINAR" />
|
||||
<SelectItem text="Baja" value="BAJA" />
|
||||
<SelectItem text="Alta" value="ALTA" />
|
||||
<SelectItem text="Custom" value="CUSTOM" />
|
||||
</Select>
|
||||
|
||||
<DatePicker
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<script lang="ts">
|
||||
import Header from '$lib/components/Header.svelte';
|
||||
import { Button, DataTableSkeleton, InlineNotification, Table, TableBody, TableCell, TableContainer, TableHead, TableHeader, TableRow } from 'carbon-components-svelte';
|
||||
import { Add, ArrowUp, Edit, Information, TrashCan } from 'carbon-icons-svelte';
|
||||
import { Add, ArrowUp, Edit, TrashCan } from 'carbon-icons-svelte';
|
||||
import type { Marca } from '../../types';
|
||||
import CrearMarcaForm from './CrearMarcaForm.svelte';
|
||||
import EditarMarcaForm from './EditarMarcaForm.svelte';
|
||||
@@ -107,3 +107,5 @@ let marcaAAlta: Marca | null = $state(null);
|
||||
<EliminarMarcaForm bind:open={openDelete} marca={marcaAEliminar} onClose={() => { openDelete = false; marcaAEliminar = null; }} />
|
||||
|
||||
<AltaMarcaForm bind:open={openAlta} marca={marcaAAlta} onClose={()=> openAlta = false} />
|
||||
|
||||
<EditarMarcaForm bind:open={openEdit} marca={marcaSeleccionada} onClose={() => { openEdit = false; marcaSeleccionada = null; }} />
|
||||
Reference in new issue
Block a user