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")
|
||||
}
|
||||
Reference in new issue
Block a user