Files
Repuestera/back/repositorios/IRepositorio.go
T

227 lines
6.0 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package repositorios
import (
applog "log"
"reflect"
dto_builders "repuestera_back/dto/Builders"
models_logs "repuestera_back/models/logs"
"gorm.io/gorm"
)
type IRepositorio[T any] interface {
Guardar(entidad *T) error
ObtenerTodos() ([]T, error)
ObtenerPorID(id uint) (*T, error)
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
}
type RepositorioBase[T any] struct {
db *gorm.DB
empresaID uint
}
func NewRepositorioBase[T any](db *gorm.DB, empresaID uint) *RepositorioBase[T] {
return &RepositorioBase[T]{db: dbConEmpresa(db, empresaID), empresaID: empresaID}
}
func (r *RepositorioBase[T]) Guardar(entidad *T) error {
if r.empresaID > 0 {
establecerEmpresaID(entidad, r.empresaID)
}
return r.db.Save(entidad).Error
}
func (r *RepositorioBase[T]) ObtenerTodos() ([]T, error) {
var entidades []T
if err := r.db.Unscoped().Find(&entidades).Error; err != nil {
return nil, err
}
return entidades, nil
}
func (r *RepositorioBase[T]) ObtenerPorID(id uint) (*T, error) {
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 {
if r.empresaID > 0 {
establecerEmpresaID(&entidad, r.empresaID)
}
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 {
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 r.empresaID > 0 {
establecerEmpresaID(&input, r.empresaID)
}
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 {
modelo := destinoConsulta(entidad)
if err := r.db.Unscoped().Model(modelo).Update("deleted_at", nil).Error; err != nil {
return err
}
if r.empresaID > 0 {
establecerEmpresaID(&input, r.empresaID)
}
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]) 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 r.empresaID > 0 {
log.EmpresaID = r.empresaID
}
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
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
}
// establecerEmpresaID setea el campo EmpresaID de una entidad, si existe.
func establecerEmpresaID(dest any, empresaID uint) {
if empresaID == 0 || dest == nil {
return
}
val := reflect.ValueOf(dest)
for val.IsValid() && val.Kind() == reflect.Ptr {
if val.IsNil() {
return
}
val = val.Elem()
}
if !val.IsValid() || val.Kind() != reflect.Struct {
return
}
campo := val.FieldByName("EmpresaID")
if !campo.IsValid() || !campo.CanSet() {
return
}
switch campo.Kind() {
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
campo.SetUint(uint64(empresaID))
}
}