hecha migracion de hooks a un builder de logs

This commit is contained in:
fede committed 2026-11-06 17:51:40 -03:00
1 parent 5f741b3cc7
commit 38afdcc742
15 files changed
+402 -274

No files matched your search

+23 -3
View File
@@ -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
}
+161
View File
@@ -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
}