primeros cambios hechos para tener el multitenant

This commit is contained in:
fede committed 2026-11-10 17:06:56 -03:00
1 parent 34ad4424f9
commit 4e082e8767
132 files changed
+6202 -762

No files matched your search

+44 -3
View File
@@ -23,14 +23,18 @@ type IRepositorio[T any] interface {
}
type RepositorioBase[T any] struct {
db *gorm.DB
db *gorm.DB
empresaID uint
}
func NewRepositorioBase[T any](db *gorm.DB) *RepositorioBase[T] {
return &RepositorioBase[T]{db: db}
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
}
@@ -51,6 +55,9 @@ func (r *RepositorioBase[T]) ObtenerPorID(id uint) (*T, error) {
}
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
}
@@ -70,6 +77,9 @@ func (r *RepositorioBase[T]) Actualizar(entidad *T, input T, usuarioID uint) err
}
}
if r.empresaID > 0 {
establecerEmpresaID(&input, r.empresaID)
}
if err := r.db.Model(destinoConsulta(entidad)).Updates(input).Error; err != nil {
return err
}
@@ -117,6 +127,9 @@ func (r *RepositorioBase[T]) Alta(entidad *T, input T, usuarioID uint) error {
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
}
@@ -152,6 +165,9 @@ func (r *RepositorioBase[T]) registrarLog(log *models_logs.Log, err error, usuar
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)
}
@@ -183,3 +199,28 @@ func destinoConsulta[T any](entidad *T) any {
}
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))
}
}