Private
Public Access
commit parcial de implementacion de builder
Signed-off-by: fede <federico.nicolas.polidoro@gmail.com>
This commit is contained in:
1 parent
f2cf7927eb
commit
4704777050
53 files changed
+1039
-848
No files matched your search
@@ -6,7 +6,7 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"repuestera_back/dto"
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
"repuestera_back/jwtutils"
|
"repuestera_back/jwtutils"
|
||||||
models_seguridad "repuestera_back/models/seguridad"
|
models_seguridad "repuestera_back/models/seguridad"
|
||||||
r "repuestera_back/repositorios"
|
r "repuestera_back/repositorios"
|
||||||
@@ -28,21 +28,15 @@ func ObtenerInvitacion(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
expirada := time.Now().After(invitacion.ExpiraEn)
|
|
||||||
usada := invitacion.UsadaEn != nil
|
|
||||||
_, errUsuario := repo.Usuario.ObtenerPorEmail(invitacion.Email)
|
_, errUsuario := repo.Usuario.ObtenerPorEmail(invitacion.Email)
|
||||||
|
|
||||||
c.JSON(http.StatusOK, dto.InvitacionInfo{
|
respuesta, err := dto_directors.NewInvitacionDirector().Info(invitacion, errUsuario == nil)
|
||||||
Email: invitacion.Email,
|
if err != nil {
|
||||||
Empresa: invitacion.Empresa.Nombre,
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
EmpresaID: invitacion.EmpresaID,
|
return
|
||||||
Rol: string(invitacion.Rol),
|
}
|
||||||
ExpiraEn: invitacion.ExpiraEn,
|
|
||||||
Valida: !expirada && !usada && invitacion.Empresa.Activa,
|
c.JSON(http.StatusOK, respuesta)
|
||||||
Usada: usada,
|
|
||||||
Expirada: expirada,
|
|
||||||
UsuarioExistente: errUsuario == nil,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// AceptarInvitacion suma al usuario a la empresa. Si la cuenta no existe, la
|
// AceptarInvitacion suma al usuario a la empresa. Si la cuenta no existe, la
|
||||||
@@ -143,11 +137,12 @@ func AceptarInvitacion(c *gin.Context) {
|
|||||||
|
|
||||||
respuesta, err := services.ConstruirSesion(usuario.ID, invitacion.EmpresaID)
|
respuesta, err := services.ConstruirSesion(usuario.ID, invitacion.EmpresaID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusOK, gin.H{
|
aceptada, buildErr := dto_directors.NewInvitacionDirector().Aceptada(usuario.ID, invitacion.EmpresaID)
|
||||||
"message": "Invitación aceptada",
|
if buildErr != nil {
|
||||||
"usuario_id": usuario.ID,
|
c.JSON(http.StatusInternalServerError, gin.H{"error": buildErr.Error()})
|
||||||
"empresa_id": invitacion.EmpresaID,
|
return
|
||||||
})
|
}
|
||||||
|
c.JSON(http.StatusOK, aceptada)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+17
-24
@@ -4,6 +4,7 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"repuestera_back/dto"
|
"repuestera_back/dto"
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
r "repuestera_back/repositorios"
|
r "repuestera_back/repositorios"
|
||||||
"repuestera_back/services"
|
"repuestera_back/services"
|
||||||
"repuestera_back/utils"
|
"repuestera_back/utils"
|
||||||
@@ -25,23 +26,19 @@ func Me(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
empresaID := utils.EmpresaID(c)
|
empresaID := utils.EmpresaID(c)
|
||||||
respuesta, err := services.ConstruirSesion(id, empresaID)
|
sesion, err := services.ConstruirSesion(id, empresaID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
|
c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
c.JSON(http.StatusOK, dto.MeResponse{
|
respuesta, err := dto_directors.NewMeDirector().DesdeSesion(sesion)
|
||||||
ID: respuesta.Usuario.ID,
|
if err != nil {
|
||||||
Email: respuesta.Usuario.Email,
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
Name: respuesta.Usuario.Name,
|
return
|
||||||
Permissions: respuesta.Permissions,
|
}
|
||||||
Empresa: respuesta.Empresa,
|
|
||||||
Empresas: respuesta.Empresas,
|
c.JSON(http.StatusOK, respuesta)
|
||||||
EmpresaRol: respuesta.EmpresaRol,
|
|
||||||
Activo: respuesta.Usuario.Activo,
|
|
||||||
DebeCambiarPassword: respuesta.DebeCambiarPassword,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ObtenerMisEmpresas devuelve las empresas donde el usuario es miembro.
|
// ObtenerMisEmpresas devuelve las empresas donde el usuario es miembro.
|
||||||
@@ -55,9 +52,7 @@ func ObtenerMisEmpresas(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
c.JSON(http.StatusOK, gin.H{
|
c.JSON(http.StatusOK, dto.EmpresasResponse{Empresas: empresas})
|
||||||
"empresas": empresas,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// CambiarEmpresa emite una sesión nueva para otra empresa del usuario.
|
// CambiarEmpresa emite una sesión nueva para otra empresa del usuario.
|
||||||
@@ -96,13 +91,11 @@ func ObtenerEmpresaActual(c *gin.Context) {
|
|||||||
|
|
||||||
miembros, _ := r.ObtenerRepositorios().Empresa.ContarMiembros(empresa.ID)
|
miembros, _ := r.ObtenerRepositorios().Empresa.ContarMiembros(empresa.ID)
|
||||||
|
|
||||||
c.JSON(http.StatusOK, gin.H{
|
respuesta, err := dto_directors.NewEmpresaActualDirector().DesdeEmpresa(empresa, rol, miembros)
|
||||||
"id": empresa.ID,
|
if err != nil {
|
||||||
"nombre": empresa.Nombre,
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
"slug": empresa.Slug,
|
return
|
||||||
"cuit": empresa.Cuit,
|
}
|
||||||
"activa": empresa.Activa,
|
|
||||||
"rol": string(rol),
|
c.JSON(http.StatusOK, respuesta)
|
||||||
"miembros_activos": miembros,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
@@ -4,7 +4,7 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"repuestera_back/dto"
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
models_seguridad "repuestera_back/models/seguridad"
|
models_seguridad "repuestera_back/models/seguridad"
|
||||||
r "repuestera_back/repositorios"
|
r "repuestera_back/repositorios"
|
||||||
"repuestera_back/services"
|
"repuestera_back/services"
|
||||||
@@ -74,7 +74,12 @@ func Register(c *gin.Context) {
|
|||||||
|
|
||||||
respuesta, err := services.ConstruirSesion(user.ID, empresa.ID)
|
respuesta, err := services.ConstruirSesion(user.ID, empresa.ID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusCreated, dto.RegisterResponse{ID: user.ID, Email: user.Email, Name: user.Name})
|
registro, buildErr := dto_directors.NewRegisterDirector().DesdeUsuario(&user)
|
||||||
|
if buildErr != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": buildErr.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusCreated, registro)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
models_seguridad "repuestera_back/models/seguridad"
|
models_seguridad "repuestera_back/models/seguridad"
|
||||||
r "repuestera_back/repositorios"
|
r "repuestera_back/repositorios"
|
||||||
"repuestera_back/utils"
|
"repuestera_back/utils"
|
||||||
@@ -47,5 +48,11 @@ func AltaMiembro(c *gin.Context) {
|
|||||||
miembro.DeletedAt = gorm.DeletedAt{}
|
miembro.DeletedAt = gorm.DeletedAt{}
|
||||||
miembro.Activo = true
|
miembro.Activo = true
|
||||||
|
|
||||||
c.JSON(http.StatusOK, respuestaMiembro(*miembro))
|
respuesta, err := dto_directors.NewMiembroDirector().DesdeMembresia(*miembro)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, respuesta)
|
||||||
}
|
}
|
||||||
@@ -1,392 +0,0 @@
|
|||||||
package empresa
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"net/http"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"repuestera_back/dto"
|
|
||||||
models_seguridad "repuestera_back/models/seguridad"
|
|
||||||
r "repuestera_back/repositorios"
|
|
||||||
"repuestera_back/services"
|
|
||||||
"repuestera_back/utils"
|
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
"golang.org/x/crypto/bcrypt"
|
|
||||||
"gorm.io/gorm"
|
|
||||||
)
|
|
||||||
|
|
||||||
type rolRequest struct {
|
|
||||||
Rol string `json:"rol"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func respuestaMiembro(miembro models_seguridad.EmpresaUsuario) dto.MiembroResponse {
|
|
||||||
respuesta := dto.MiembroResponse{
|
|
||||||
ID: miembro.Usuario.ID,
|
|
||||||
Email: miembro.Usuario.Email,
|
|
||||||
Name: miembro.Usuario.Name,
|
|
||||||
Activo: miembro.Usuario.Activo,
|
|
||||||
DebeCambiarPassword: miembro.Usuario.DebeCambiarPassword,
|
|
||||||
Rol: string(miembro.Rol),
|
|
||||||
MembresiaActiva: miembro.Activo && !miembro.DeletedAt.Valid,
|
|
||||||
CreatedAt: miembro.Usuario.CreatedAt,
|
|
||||||
UpdatedAt: miembro.Usuario.UpdatedAt,
|
|
||||||
}
|
|
||||||
if miembro.DeletedAt.Valid {
|
|
||||||
deletedAt := miembro.DeletedAt.Time
|
|
||||||
respuesta.DeletedAt = &deletedAt
|
|
||||||
}
|
|
||||||
return respuesta
|
|
||||||
}
|
|
||||||
|
|
||||||
func ObtenerMiembros(c *gin.Context) {
|
|
||||||
empresaID := utils.EmpresaID(c)
|
|
||||||
pagina, _ := strconv.Atoi(c.DefaultQuery("p", "0"))
|
|
||||||
tamano, _ := strconv.Atoi(c.DefaultQuery("s", "10"))
|
|
||||||
|
|
||||||
miembros, total, err := r.ObtenerRepositorios().Empresa.ListarMiembros(empresaID, pagina, tamano)
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
respuesta := make([]dto.MiembroResponse, 0, len(miembros))
|
|
||||||
for _, miembro := range miembros {
|
|
||||||
respuesta = append(respuesta, respuestaMiembro(miembro))
|
|
||||||
}
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, gin.H{
|
|
||||||
"usuarios": respuesta,
|
|
||||||
"miembros": respuesta,
|
|
||||||
"total": total,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func ObtenerMiembro(c *gin.Context) {
|
|
||||||
empresaID := utils.EmpresaID(c)
|
|
||||||
usuarioID, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID inválido"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
miembro, err := r.ObtenerRepositorios().Empresa.Membresia(empresaID, uint(usuarioID))
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusNotFound, gin.H{"error": "El usuario no pertenece a esta empresa"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, respuestaMiembro(*miembro))
|
|
||||||
}
|
|
||||||
|
|
||||||
func CrearMiembro(c *gin.Context) {
|
|
||||||
var req struct {
|
|
||||||
Name string `json:"name" binding:"required"`
|
|
||||||
Email string `json:"email" binding:"required,email"`
|
|
||||||
Password string `json:"password"`
|
|
||||||
Rol string `json:"rol"`
|
|
||||||
GrupoID uint `json:"grupo_id"`
|
|
||||||
}
|
|
||||||
if err := c.ShouldBindJSON(&req); err != nil {
|
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
empresaID := utils.EmpresaID(c)
|
|
||||||
callerRol := models_seguridad.RolEmpresa(utils.EmpresaRol(c))
|
|
||||||
rol, err := rolSolicitado(c, callerRol, req.Rol)
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if req.GrupoID > 0 {
|
|
||||||
grupo, err := r.ObtenerRepositorios(c).Grupo.ObtenerPorID(req.GrupoID)
|
|
||||||
if err != nil || grupo.EmpresaID != empresaID {
|
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Grupo inválido para la empresa"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
repo := r.ObtenerRepositorios()
|
|
||||||
email := strings.ToLower(strings.TrimSpace(req.Email))
|
|
||||||
|
|
||||||
usuario, err := repo.Usuario.ObtenerPorEmail(email)
|
|
||||||
passwordTemporal := ""
|
|
||||||
creado := false
|
|
||||||
|
|
||||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
||||||
password := req.Password
|
|
||||||
if password == "" {
|
|
||||||
password, err = services.GenerarPasswordTemporal()
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "No se pudo generar la contraseña"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
passwordTemporal = password
|
|
||||||
}
|
|
||||||
if len(password) < 8 {
|
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": "La contraseña debe tener al menos 8 caracteres"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error al procesar la contraseña"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
usuario = &models_seguridad.Usuario{
|
|
||||||
Email: email,
|
|
||||||
Name: strings.TrimSpace(req.Name),
|
|
||||||
Password: string(hash),
|
|
||||||
Activo: true,
|
|
||||||
DebeCambiarPassword: true,
|
|
||||||
}
|
|
||||||
if err := repo.Usuario.Crear(usuario); err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
creado = true
|
|
||||||
} else if err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
||||||
return
|
|
||||||
} else {
|
|
||||||
if _, err := repo.Empresa.Membresia(empresaID, usuario.ID); err == nil {
|
|
||||||
c.JSON(http.StatusConflict, gin.H{"error": "El usuario ya pertenece a esta empresa"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := repo.Empresa.AgregarMiembro(empresaID, usuario.ID, rol, req.GrupoID); err != nil {
|
|
||||||
if creado {
|
|
||||||
_ = repo.Usuario.Eliminar(usuario.ID)
|
|
||||||
}
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.JSON(http.StatusCreated, gin.H{
|
|
||||||
"usuario": respuestaMiembro(models_seguridad.EmpresaUsuario{
|
|
||||||
Usuario: *usuario,
|
|
||||||
Rol: rol,
|
|
||||||
Activo: true,
|
|
||||||
}),
|
|
||||||
"password_temporal": passwordTemporal,
|
|
||||||
"usuario_existente": !creado,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func ActualizarMiembro(c *gin.Context) {
|
|
||||||
usuarioID, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID inválido"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var req struct {
|
|
||||||
Name string `json:"name"`
|
|
||||||
Email string `json:"email"`
|
|
||||||
Rol string `json:"rol"`
|
|
||||||
GrupoID uint `json:"grupo_id"`
|
|
||||||
Activo *bool `json:"activo"`
|
|
||||||
}
|
|
||||||
if err := c.ShouldBindJSON(&req); err != nil {
|
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
empresaID := utils.EmpresaID(c)
|
|
||||||
repo := r.ObtenerRepositorios()
|
|
||||||
callerRol := models_seguridad.RolEmpresa(utils.EmpresaRol(c))
|
|
||||||
|
|
||||||
miembro, err := repo.Empresa.Membresia(empresaID, uint(usuarioID))
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusNotFound, gin.H{"error": "El usuario no pertenece a esta empresa"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := puedeModificarMiembro(c, callerRol, miembro.Rol); err != nil {
|
|
||||||
c.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
usuario, err := repo.Usuario.ObtenerPorID(uint(usuarioID))
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusNotFound, gin.H{"error": "Usuario no encontrado"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if req.Name != "" {
|
|
||||||
usuario.Name = strings.TrimSpace(req.Name)
|
|
||||||
}
|
|
||||||
if req.Email != "" {
|
|
||||||
email := strings.ToLower(strings.TrimSpace(req.Email))
|
|
||||||
if email != usuario.Email {
|
|
||||||
if existente, err := repo.Usuario.ObtenerPorEmail(email); err == nil && existente.ID != usuario.ID {
|
|
||||||
c.JSON(http.StatusConflict, gin.H{"error": "El email ya está registrado"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
usuario.Email = email
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if err := repo.Usuario.Guardar(usuario); err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if req.Rol != "" {
|
|
||||||
nuevoRol, err := rolSolicitado(c, callerRol, req.Rol)
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if miembro.Rol == models_seguridad.RolOwner && nuevoRol != models_seguridad.RolOwner {
|
|
||||||
if err := validarUltimoOwner(empresaID); err != nil {
|
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if err := repo.Empresa.ActualizarRolMiembro(empresaID, usuario.ID, nuevoRol); err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
miembro.Rol = nuevoRol
|
|
||||||
}
|
|
||||||
|
|
||||||
if req.Activo != nil {
|
|
||||||
if !*req.Activo && miembro.Rol == models_seguridad.RolOwner {
|
|
||||||
if err := validarUltimoOwner(empresaID); err != nil {
|
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if *req.Activo {
|
|
||||||
if err := repo.Empresa.AgregarMiembro(empresaID, usuario.ID, miembro.Rol, 0); err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if err := repo.Empresa.DesactivarMiembro(empresaID, usuario.ID); err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
miembro.Usuario = *usuario
|
|
||||||
if req.Activo != nil {
|
|
||||||
miembro.Activo = *req.Activo
|
|
||||||
}
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, respuestaMiembro(*miembro))
|
|
||||||
}
|
|
||||||
|
|
||||||
func EliminarMiembro(c *gin.Context) {
|
|
||||||
usuarioID, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID inválido"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
empresaID := utils.EmpresaID(c)
|
|
||||||
repo := r.ObtenerRepositorios()
|
|
||||||
callerRol := models_seguridad.RolEmpresa(utils.EmpresaRol(c))
|
|
||||||
|
|
||||||
miembro, err := repo.Empresa.Membresia(empresaID, uint(usuarioID))
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusNotFound, gin.H{"error": "El usuario no pertenece a esta empresa"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := puedeModificarMiembro(c, callerRol, miembro.Rol); err != nil {
|
|
||||||
c.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if miembro.Rol == models_seguridad.RolOwner {
|
|
||||||
if err := validarUltimoOwner(empresaID); err != nil {
|
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := repo.Empresa.EliminarMiembro(empresaID, uint(usuarioID)); err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, gin.H{"message": "El usuario fue removido de la empresa"})
|
|
||||||
}
|
|
||||||
|
|
||||||
func ActualizarEmpresa(c *gin.Context) {
|
|
||||||
var req struct {
|
|
||||||
Nombre string `json:"nombre"`
|
|
||||||
Slug string `json:"slug"`
|
|
||||||
Cuit string `json:"cuit"`
|
|
||||||
}
|
|
||||||
if err := c.ShouldBindJSON(&req); err != nil {
|
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
repo := r.ObtenerRepositorios()
|
|
||||||
empresa, err := repo.Empresa.ObtenerPorID(utils.EmpresaID(c))
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusNotFound, gin.H{"error": "Empresa no encontrada"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
input := models_seguridad.Empresa{Nombre: strings.TrimSpace(req.Nombre), Slug: strings.TrimSpace(req.Slug)}
|
|
||||||
if req.Cuit != "" {
|
|
||||||
cuit := strings.TrimSpace(req.Cuit)
|
|
||||||
input.Cuit = &cuit
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := repo.Empresa.Actualizar(empresa, input); err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, empresa)
|
|
||||||
}
|
|
||||||
|
|
||||||
func rolSolicitado(c *gin.Context, callerRol models_seguridad.RolEmpresa, solicitado string) (models_seguridad.RolEmpresa, error) {
|
|
||||||
rol := models_seguridad.RolEmpresa(strings.ToUpper(strings.TrimSpace(solicitado)))
|
|
||||||
if rol == "" {
|
|
||||||
rol = models_seguridad.RolMiembro
|
|
||||||
}
|
|
||||||
if !rol.Valido() {
|
|
||||||
return "", errors.New("rol inválido")
|
|
||||||
}
|
|
||||||
|
|
||||||
if rol == models_seguridad.RolOwner && callerRol != models_seguridad.RolOwner {
|
|
||||||
return "", errors.New("solo el owner puede asignar el rol OWNER")
|
|
||||||
}
|
|
||||||
return rol, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func puedeModificarMiembro(c *gin.Context, callerRol, targetRol models_seguridad.RolEmpresa) error {
|
|
||||||
if callerRol == models_seguridad.RolOwner {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
if targetRol == models_seguridad.RolOwner {
|
|
||||||
return errors.New("solo el owner puede administrar a otro owner")
|
|
||||||
}
|
|
||||||
if callerRol == models_seguridad.RolAdmin && targetRol == models_seguridad.RolAdmin {
|
|
||||||
return errors.New("un administrador no puede modificar a otro administrador")
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func validarUltimoOwner(empresaID uint) error {
|
|
||||||
owners, err := r.ObtenerRepositorios().Empresa.ContarOwners(empresaID)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if owners <= 1 {
|
|
||||||
return errors.New("la empresa debe conservar al menos un owner activo")
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -8,6 +8,7 @@ import (
|
|||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
|
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
r "repuestera_back/repositorios"
|
r "repuestera_back/repositorios"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -28,5 +29,11 @@ func ObtenerFactura(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
c.JSON(http.StatusOK, factura)
|
respuesta, err := dto_directors.NewFacturaDirector().DesdeFactura(factura)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, respuesta)
|
||||||
}
|
}
|
||||||
@@ -7,6 +7,7 @@ import (
|
|||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
|
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
r "repuestera_back/repositorios"
|
r "repuestera_back/repositorios"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -43,7 +44,14 @@ func ObtenerFacturas(c *gin.Context) {
|
|||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
c.JSON(http.StatusOK, facturas)
|
|
||||||
|
respuesta, err := dto_directors.NewFacturaDirector().Listar(facturas)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, respuesta)
|
||||||
}
|
}
|
||||||
|
|
||||||
func fechaQuery(valor string) (*time.Time, error) {
|
func fechaQuery(valor string) (*time.Time, error) {
|
||||||
|
|||||||
@@ -2,9 +2,11 @@ package grupo
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
models_seguridad "repuestera_back/models/seguridad"
|
models_seguridad "repuestera_back/models/seguridad"
|
||||||
r "repuestera_back/repositorios"
|
r "repuestera_back/repositorios"
|
||||||
"strconv"
|
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
)
|
)
|
||||||
@@ -25,6 +27,16 @@ func ActualizarGrupo(c *gin.Context) {
|
|||||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
r.ObtenerRepositorios(c).Grupo.Actualizar(grupo, input)
|
if err := r.ObtenerRepositorios(c).Grupo.Actualizar(grupo, input); err != nil {
|
||||||
c.JSON(http.StatusOK, grupo)
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
respuesta, err := dto_directors.NewGrupoDirector().DesdeGrupo(grupo)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, respuesta)
|
||||||
}
|
}
|
||||||
@@ -2,6 +2,8 @@ package grupo
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
models_seguridad "repuestera_back/models/seguridad"
|
models_seguridad "repuestera_back/models/seguridad"
|
||||||
r "repuestera_back/repositorios"
|
r "repuestera_back/repositorios"
|
||||||
|
|
||||||
@@ -18,5 +20,12 @@ func CrearGrupo(c *gin.Context) {
|
|||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
c.JSON(http.StatusCreated, grupo)
|
|
||||||
|
respuesta, err := dto_directors.NewGrupoDirector().DesdeGrupo(&grupo)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusCreated, respuesta)
|
||||||
}
|
}
|
||||||
@@ -2,7 +2,7 @@ package grupo
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
dto_builders "repuestera_back/dto/Builders"
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
r "repuestera_back/repositorios"
|
r "repuestera_back/repositorios"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
@@ -21,9 +21,11 @@ func ObtenerGrupo(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
dto := dto_builders.
|
respuesta, err := dto_directors.NewGrupoSimpleDirector().DesdeGrupo(grupo)
|
||||||
NewGrupoSimpleBuilder(grupo).
|
if err != nil {
|
||||||
Build()
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
c.JSON(http.StatusOK, dto)
|
c.JSON(http.StatusOK, respuesta)
|
||||||
}
|
}
|
||||||
@@ -2,6 +2,8 @@ package grupo
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
r "repuestera_back/repositorios"
|
r "repuestera_back/repositorios"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
@@ -13,5 +15,12 @@ func ObtenerGrupos(c *gin.Context) {
|
|||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
c.JSON(http.StatusOK, grupos)
|
|
||||||
|
respuesta, err := dto_directors.NewGrupoDirector().Listar(grupos)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, respuesta)
|
||||||
}
|
}
|
||||||
@@ -2,9 +2,11 @@ package grupo
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
r "repuestera_back/repositorios"
|
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -13,7 +15,7 @@ func ObtenerGruposDeUsuario(c *gin.Context) {
|
|||||||
|
|
||||||
usuarioID, err := strconv.ParseUint(usuarioIDStr, 10, 64)
|
usuarioID, err := strconv.ParseUint(usuarioIDStr, 10, 64)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(400, gin.H{"error": "id invalido"})
|
c.JSON(http.StatusBadRequest, gin.H{"error": "id invalido"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -22,5 +24,12 @@ func ObtenerGruposDeUsuario(c *gin.Context) {
|
|||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "no se ha podido obtener los grupos del usuario"})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "no se ha podido obtener los grupos del usuario"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
c.JSON(http.StatusOK, grupos)
|
|
||||||
|
respuesta, err := dto_directors.NewGrupoDirector().Listar(grupos)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, respuesta)
|
||||||
}
|
}
|
||||||
@@ -2,8 +2,9 @@ package grupo
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
"repuestera_back/dto"
|
|
||||||
dto_builders "repuestera_back/dto/Builders"
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
|
models_seguridad "repuestera_back/models/seguridad"
|
||||||
r "repuestera_back/repositorios"
|
r "repuestera_back/repositorios"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
@@ -40,20 +41,28 @@ func ObtenerGruposYPermisosPorEmail(c *gin.Context) {
|
|||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
grupos := make([]dto.GrupoSimpleDTO, 0, len(usuario.Grupos))
|
|
||||||
|
grupos := make([]*models_seguridad.Grupo, 0, len(usuario.Grupos))
|
||||||
for i := range usuario.Grupos {
|
for i := range usuario.Grupos {
|
||||||
grupoCompleto, err := r.ObtenerRepositorios(c).Grupo.ObtenerPorIDConRelaciones(usuario.Grupos[i].ID, true)
|
grupoCompleto, err := r.ObtenerRepositorios(c).Grupo.ObtenerPorIDConRelaciones(usuario.Grupos[i].ID, true)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
g := dto_builders.NewGrupoSimpleBuilder(grupoCompleto).Build()
|
grupos = append(grupos, grupoCompleto)
|
||||||
g.ID = grupoCompleto.ID
|
|
||||||
grupos = append(grupos, g)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
c.JSON(http.StatusOK, dto.GruposYPermisosResponse{
|
respuesta, err := dto_directors.NewGrupoSimpleDirector().Listar(grupos)
|
||||||
Email: usuario.Email,
|
if err != nil {
|
||||||
Groups: grupos,
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
})
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
envelope, err := dto_directors.NewGrupoDirector().GruposYPermisos(usuario.Email, respuesta)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, envelope)
|
||||||
}
|
}
|
||||||
@@ -2,7 +2,7 @@ package logs
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
dto_builders "repuestera_back/dto/Builders"
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
dto "repuestera_back/dto/Logs"
|
dto "repuestera_back/dto/Logs"
|
||||||
"repuestera_back/models/logs"
|
"repuestera_back/models/logs"
|
||||||
r "repuestera_back/repositorios"
|
r "repuestera_back/repositorios"
|
||||||
@@ -30,7 +30,11 @@ func BusquedaLogs(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
logsdto := dto_builders.NewLogTablaBuilder().ConLogs(logs).Build()
|
logsdto, err := dto_directors.NewLogTablaDirector().Listar(logs)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
cantpags, err := r.ObtenerRepositorios(c).Logs.CantPaginasConFiltros(filtros)
|
cantpags, err := r.ObtenerRepositorios(c).Logs.CantPaginasConFiltros(filtros)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package logs
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
r "repuestera_back/repositorios"
|
r "repuestera_back/repositorios"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
@@ -23,5 +24,11 @@ func ObtenerLog(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
c.JSON(http.StatusOK, logs)
|
respuesta, err := dto_directors.NewLogResponseDirector().Listar(logs)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, respuesta)
|
||||||
}
|
}
|
||||||
@@ -2,7 +2,7 @@ package logs
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
dto_builders "repuestera_back/dto/Builders"
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
r "repuestera_back/repositorios"
|
r "repuestera_back/repositorios"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
@@ -32,7 +32,11 @@ func ObtenerLogs(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
logsdto := dto_builders.NewLogTablaBuilder().ConLogs(logs).Build()
|
logsdto, err := dto_directors.NewLogTablaDirector().Listar(logs)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
c.JSON(http.StatusOK, gin.H{
|
c.JSON(http.StatusOK, gin.H{
|
||||||
"logs": logsdto,
|
"logs": logsdto,
|
||||||
|
|||||||
@@ -2,9 +2,11 @@ package permiso
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
models_seguridad "repuestera_back/models/seguridad"
|
models_seguridad "repuestera_back/models/seguridad"
|
||||||
r "repuestera_back/repositorios"
|
r "repuestera_back/repositorios"
|
||||||
"strconv"
|
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
)
|
)
|
||||||
@@ -25,6 +27,16 @@ func ActualizarPermiso(c *gin.Context) {
|
|||||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
r.ObtenerRepositorios(c).Permiso.Actualizar(permiso, input)
|
if err := r.ObtenerRepositorios(c).Permiso.Actualizar(permiso, input); err != nil {
|
||||||
c.JSON(http.StatusOK, permiso)
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
respuesta, err := dto_directors.NewPermisoDirector().DesdePermiso(permiso)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, respuesta)
|
||||||
}
|
}
|
||||||
@@ -2,6 +2,8 @@ package permiso
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
models_seguridad "repuestera_back/models/seguridad"
|
models_seguridad "repuestera_back/models/seguridad"
|
||||||
r "repuestera_back/repositorios"
|
r "repuestera_back/repositorios"
|
||||||
|
|
||||||
@@ -18,5 +20,12 @@ func CrearPermiso(c *gin.Context) {
|
|||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
c.JSON(http.StatusCreated, permiso)
|
|
||||||
|
respuesta, err := dto_directors.NewPermisoDirector().DesdePermiso(&permiso)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusCreated, respuesta)
|
||||||
}
|
}
|
||||||
@@ -2,6 +2,8 @@ package permiso
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
r "repuestera_back/repositorios"
|
r "repuestera_back/repositorios"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
@@ -13,5 +15,12 @@ func ObtenerPermisos(c *gin.Context) {
|
|||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
c.JSON(http.StatusOK, permisos)
|
|
||||||
|
respuesta, err := dto_directors.NewPermisoDirector().Listar(permisos)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, respuesta)
|
||||||
}
|
}
|
||||||
@@ -1,12 +1,14 @@
|
|||||||
package permiso
|
package permiso
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
"net/http"
|
|
||||||
"repuestera_back/dto"
|
|
||||||
r "repuestera_back/repositorios"
|
|
||||||
"strconv"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func ObtenerPermisosUsuario(c *gin.Context) {
|
func ObtenerPermisosUsuario(c *gin.Context) {
|
||||||
@@ -26,25 +28,11 @@ func ObtenerPermisosUsuario(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
permisoMap := make(map[string]bool)
|
respuesta, err := dto_directors.NewPermisosUsuarioDirector().DesdeGrupos(usuario.Grupos)
|
||||||
var permisos []string
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
for _, grupo := range usuario.Grupos {
|
return
|
||||||
for _, permiso := range grupo.Permisos {
|
|
||||||
if !permisoMap[permiso.Nombre] {
|
|
||||||
permisoMap[permiso.Nombre] = true
|
|
||||||
permisos = append(permisos, permiso.Nombre)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for _, grupoHijo := range grupo.Grupos {
|
|
||||||
for _, permiso := range grupoHijo.Permisos {
|
|
||||||
if !permisoMap[permiso.Nombre] {
|
|
||||||
permisoMap[permiso.Nombre] = true
|
|
||||||
permisos = append(permisos, permiso.Nombre)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
c.JSON(http.StatusOK, dto.PermisosUsuarioResponse{Permisos: permisos})
|
c.JSON(http.StatusOK, respuesta)
|
||||||
}
|
}
|
||||||
@@ -2,7 +2,7 @@ package repuestos
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
dto_builders "repuestera_back/dto/Builders"
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
dto "repuestera_back/dto/Repuestos"
|
dto "repuestera_back/dto/Repuestos"
|
||||||
r "repuestera_back/repositorios"
|
r "repuestera_back/repositorios"
|
||||||
"strconv"
|
"strconv"
|
||||||
@@ -35,10 +35,11 @@ func ActualizarRepuesto(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
repuesto := dto_builders.NewActualizarRepuestoBuilder().
|
repuesto, err := dto_directors.NewRepuestoDirector().Actualizar(data, marca.ID)
|
||||||
ConDto(data).
|
if err != nil {
|
||||||
ConMarca(marca.ID).
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
Build()
|
return
|
||||||
|
}
|
||||||
|
|
||||||
entity, err := r.ObtenerRepositorios(c).Repuesto.ObtenerPorID(uint(id))
|
entity, err := r.ObtenerRepositorios(c).Repuesto.ObtenerPorID(uint(id))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -47,10 +48,10 @@ func ActualizarRepuesto(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
uid, _ := c.Get("userID")
|
uid, _ := c.Get("userID")
|
||||||
if err := r.ObtenerRepositorios(c).Repuesto.Actualizar(entity, &repuesto, uid.(uint)); err != nil {
|
if err := r.ObtenerRepositorios(c).Repuesto.Actualizar(entity, repuesto, uid.(uint)); err != nil {
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
c.JSON(http.StatusCreated, repuesto)
|
c.JSON(http.StatusOK, repuesto)
|
||||||
}
|
}
|
||||||
@@ -2,7 +2,7 @@ package repuestos
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
dto_builders "repuestera_back/dto/Builders"
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
dto "repuestera_back/dto/Repuestos"
|
dto "repuestera_back/dto/Repuestos"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
@@ -28,13 +28,14 @@ func CrearRepuesto(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
repuesto := dto_builders.NewRepuestoBuilder().
|
repuesto, err := dto_directors.NewRepuestoDirector().Crear(data, marca.ID)
|
||||||
ConDto(data).
|
if err != nil {
|
||||||
ConMarca(marca.ID).
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
Build()
|
return
|
||||||
|
}
|
||||||
|
|
||||||
uid, _ := c.Get("userID")
|
uid, _ := c.Get("userID")
|
||||||
if err := r.ObtenerRepositorios(c).Repuesto.Crear(&repuesto, uid.(uint)); err != nil {
|
if err := r.ObtenerRepositorios(c).Repuesto.Crear(repuesto, uid.(uint)); err != nil {
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,8 +6,8 @@ import (
|
|||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
|
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
dto "repuestera_back/dto/Stock"
|
dto "repuestera_back/dto/Stock"
|
||||||
"repuestera_back/models"
|
|
||||||
r "repuestera_back/repositorios"
|
r "repuestera_back/repositorios"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -32,16 +32,23 @@ func ObtenerStock(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if q.Estado != "" {
|
director := dto_directors.NewStockDirector()
|
||||||
filtrado := make([]models.Stock, 0, len(stocks))
|
|
||||||
for i := range stocks {
|
respuesta, err := director.Listar(stocks)
|
||||||
estado := string(estadoDe(&stocks[i], &stocks[i].Repuesto))
|
if err != nil {
|
||||||
if strings.EqualFold(estado, q.Estado) {
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
filtrado = append(filtrado, stocks[i])
|
return
|
||||||
}
|
|
||||||
}
|
|
||||||
stocks = filtrado
|
|
||||||
}
|
}
|
||||||
|
|
||||||
c.JSON(http.StatusOK, stocks)
|
if q.Estado != "" {
|
||||||
|
filtrado := make([]dto.StockResponse, 0, len(respuesta))
|
||||||
|
for _, item := range respuesta {
|
||||||
|
if strings.EqualFold(item.Estado, q.Estado) {
|
||||||
|
filtrado = append(filtrado, item)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
respuesta = filtrado
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, respuesta)
|
||||||
}
|
}
|
||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
|
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
r "repuestera_back/repositorios"
|
r "repuestera_back/repositorios"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -20,5 +21,12 @@ func ObtenerStockPorID(c *gin.Context) {
|
|||||||
c.JSON(http.StatusNotFound, gin.H{"error": "stock no encontrado"})
|
c.JSON(http.StatusNotFound, gin.H{"error": "stock no encontrado"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
c.JSON(http.StatusOK, stock)
|
|
||||||
|
respuesta, err := dto_directors.NewStockDirector().DesdeStock(stock)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, respuesta)
|
||||||
}
|
}
|
||||||
@@ -13,7 +13,7 @@ import (
|
|||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
|
|
||||||
dto_builders "repuestera_back/dto/Builders"
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
"repuestera_back/models"
|
"repuestera_back/models"
|
||||||
"repuestera_back/models/contabilidad"
|
"repuestera_back/models/contabilidad"
|
||||||
models_logs "repuestera_back/models/logs"
|
models_logs "repuestera_back/models/logs"
|
||||||
@@ -44,15 +44,6 @@ var (
|
|||||||
ErrSinAlmacen = errors.New("no hay almacenes cargados en la empresa")
|
ErrSinAlmacen = errors.New("no hay almacenes cargados en la empresa")
|
||||||
)
|
)
|
||||||
|
|
||||||
// estadoStock clasifica un ítem según su cantidad física y su mínimo.
|
|
||||||
type estadoStock string
|
|
||||||
|
|
||||||
const (
|
|
||||||
estadoAgotado estadoStock = "AGOTADO"
|
|
||||||
estadoBajoMinimo estadoStock = "BAJO_MINIMO"
|
|
||||||
estadoNormal estadoStock = "NORMAL"
|
|
||||||
)
|
|
||||||
|
|
||||||
func codigoHTTP(err error) int {
|
func codigoHTTP(err error) int {
|
||||||
switch {
|
switch {
|
||||||
case errors.Is(err, gorm.ErrRecordNotFound):
|
case errors.Is(err, gorm.ErrRecordNotFound):
|
||||||
@@ -107,20 +98,6 @@ func disponible(stock *models.Stock) float64 {
|
|||||||
return redondearCantidad(stock.Cantidad - stock.CantidadReservada)
|
return redondearCantidad(stock.Cantidad - stock.CantidadReservada)
|
||||||
}
|
}
|
||||||
|
|
||||||
// estadoDe devuelve AGOTADO, BAJO_MINIMO o NORMAL.
|
|
||||||
func estadoDe(stock *models.Stock, repuesto *models.Repuesto) estadoStock {
|
|
||||||
if stock == nil {
|
|
||||||
return estadoAgotado
|
|
||||||
}
|
|
||||||
if stock.Cantidad <= 0 {
|
|
||||||
return estadoAgotado
|
|
||||||
}
|
|
||||||
if repuesto != nil && stock.Cantidad < float64(repuesto.StockMinimo) {
|
|
||||||
return estadoBajoMinimo
|
|
||||||
}
|
|
||||||
return estadoNormal
|
|
||||||
}
|
|
||||||
|
|
||||||
// validarCantidad acepta solo cantidades positivas y finitas.
|
// validarCantidad acepta solo cantidades positivas y finitas.
|
||||||
func validarCantidad(cantidad float64) error {
|
func validarCantidad(cantidad float64) error {
|
||||||
if math.IsNaN(cantidad) || math.IsInf(cantidad, 0) || cantidad <= 0 {
|
if math.IsNaN(cantidad) || math.IsInf(cantidad, 0) || cantidad <= 0 {
|
||||||
@@ -247,7 +224,7 @@ func registrarAsiento(tx *gorm.DB, repo *repositorios.Repositorios, comprobanteT
|
|||||||
// registrarLog guarda la auditoría fuera de la transacción: si falla, la
|
// registrarLog guarda la auditoría fuera de la transacción: si falla, la
|
||||||
// operación de negocio ya confirmada no se revierte.
|
// operación de negocio ya confirmada no se revierte.
|
||||||
func registrarLog(repo *repositorios.Repositorios, empresaID, usuarioID uint, accion string, detalles []models_logs.LogDetalle) {
|
func registrarLog(repo *repositorios.Repositorios, empresaID, usuarioID uint, accion string, detalles []models_logs.LogDetalle) {
|
||||||
log, err := dto_builders.NewLogDirector().Custom(usuarioID, accion, detalles)
|
log, err := dto_directors.NewLogDirector().Custom(usuarioID, accion, detalles)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
applog.Printf("stock: no se pudo construir el log de %s: %v", accion, err)
|
applog.Printf("stock: no se pudo construir el log de %s: %v", accion, err)
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -6,6 +6,8 @@ import (
|
|||||||
r "repuestera_back/repositorios"
|
r "repuestera_back/repositorios"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -39,7 +41,16 @@ func ActualizarUsuario(c *gin.Context) {
|
|||||||
usuario.Email = usuarioReq.Email
|
usuario.Email = usuarioReq.Email
|
||||||
usuario.Name = usuarioReq.Name
|
usuario.Name = usuarioReq.Name
|
||||||
|
|
||||||
r.ObtenerRepositorios(c).Usuario.Guardar(usuario)
|
if err := r.ObtenerRepositorios(c).Usuario.Guardar(usuario); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
c.JSON(http.StatusCreated, usuario)
|
respuesta, err := dto_directors.NewUsuarioDirector().DesdeUsuario(usuario)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, respuesta)
|
||||||
}
|
}
|
||||||
@@ -5,6 +5,8 @@ import (
|
|||||||
models_seguridad "repuestera_back/models/seguridad"
|
models_seguridad "repuestera_back/models/seguridad"
|
||||||
r "repuestera_back/repositorios"
|
r "repuestera_back/repositorios"
|
||||||
|
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -20,5 +22,11 @@ func CrearUsuario(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
c.JSON(http.StatusCreated, usuario)
|
respuesta, err := dto_directors.NewUsuarioDirector().DesdeUsuario(&usuario)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusCreated, respuesta)
|
||||||
}
|
}
|
||||||
@@ -2,6 +2,7 @@ package usuarios
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
r "repuestera_back/repositorios"
|
r "repuestera_back/repositorios"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
@@ -21,5 +22,11 @@ func ObtenerUsuario(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
c.JSON(http.StatusOK, usuario)
|
respuesta, err := dto_directors.NewUsuarioDirector().DesdeUsuario(usuario)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, respuesta)
|
||||||
}
|
}
|
||||||
@@ -2,6 +2,7 @@ package usuarios
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
r "repuestera_back/repositorios"
|
r "repuestera_back/repositorios"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
@@ -26,8 +27,14 @@ func ObtenerUsuarios(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
respuesta, err := dto_directors.NewUsuarioDirector().Listar(usuarios)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
c.JSON(http.StatusOK, gin.H{
|
c.JSON(http.StatusOK, gin.H{
|
||||||
"usuarios": usuarios,
|
"usuarios": respuesta,
|
||||||
"total": total,
|
"total": total,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
package dto
|
||||||
|
|
||||||
|
// AlmacenResumen es la representación de un almacén sin sus stocks
|
||||||
|
// asociados.
|
||||||
|
type AlmacenResumen struct {
|
||||||
|
ID uint `json:"id"`
|
||||||
|
EmpresaID uint `json:"empresaId"`
|
||||||
|
Codigo string `json:"codigo"`
|
||||||
|
Ubicacion string `json:"ubicacion"`
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package dto
|
||||||
|
|
||||||
|
import "repuestera_back/dto"
|
||||||
|
|
||||||
|
// GrupoResponse es la representación pública de un grupo, con sus
|
||||||
|
// permisos, subgrupos y usuarios resumidos.
|
||||||
|
type GrupoResponse struct {
|
||||||
|
ID uint `json:"id"`
|
||||||
|
EmpresaID uint `json:"empresaId"`
|
||||||
|
Nombre string `json:"nombre"`
|
||||||
|
Descripcion string `json:"descripcion"`
|
||||||
|
Imagen string `json:"imagen"`
|
||||||
|
Permisos []PermisoResponse `json:"permisos"`
|
||||||
|
GruposHijos []GrupoResponse `json:"grupos_hijos"`
|
||||||
|
Usuarios []dto.UsuarioResumen `json:"usuarios"`
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package dto
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// PermisoResponse es la representación pública de un permiso.
|
||||||
|
type PermisoResponse struct {
|
||||||
|
ID uint `json:"id"`
|
||||||
|
Nombre string `json:"nombre"`
|
||||||
|
Alias string `json:"alias"`
|
||||||
|
Descripcion string `json:"descripcion"`
|
||||||
|
Imagen string `json:"imagen"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
|
}
|
||||||
@@ -1,6 +1,8 @@
|
|||||||
package dto_builders
|
package dto_builders
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"errors"
|
||||||
|
|
||||||
dto "repuestera_back/dto/Repuestos"
|
dto "repuestera_back/dto/Repuestos"
|
||||||
"repuestera_back/models"
|
"repuestera_back/models"
|
||||||
)
|
)
|
||||||
@@ -8,40 +10,67 @@ import (
|
|||||||
type ActualizarRepuestoBuilder struct {
|
type ActualizarRepuestoBuilder struct {
|
||||||
dto *dto.ActualizarRepuestoDto
|
dto *dto.ActualizarRepuestoDto
|
||||||
marcaID uint
|
marcaID uint
|
||||||
|
err error
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var _ IBuilder[models.Repuesto] = (*ActualizarRepuestoBuilder)(nil)
|
||||||
|
|
||||||
func NewActualizarRepuestoBuilder() *ActualizarRepuestoBuilder {
|
func NewActualizarRepuestoBuilder() *ActualizarRepuestoBuilder {
|
||||||
return &ActualizarRepuestoBuilder{}
|
return &ActualizarRepuestoBuilder{}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *ActualizarRepuestoBuilder) ConDto(dto dto.ActualizarRepuestoDto) *ActualizarRepuestoBuilder {
|
func (b *ActualizarRepuestoBuilder) ConDto(data dto.ActualizarRepuestoDto) *ActualizarRepuestoBuilder {
|
||||||
b.dto = &dto
|
b.dto = &data
|
||||||
return b
|
return b
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *ActualizarRepuestoBuilder) ConMarca(marcaID uint) *ActualizarRepuestoBuilder {
|
func (b *ActualizarRepuestoBuilder) ConMarca(marcaID uint) *ActualizarRepuestoBuilder {
|
||||||
|
if marcaID == 0 {
|
||||||
|
AcumularError(&b.err, "la marca es obligatoria")
|
||||||
|
return b
|
||||||
|
}
|
||||||
b.marcaID = marcaID
|
b.marcaID = marcaID
|
||||||
return b
|
return b
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *ActualizarRepuestoBuilder) Build() models.Repuesto {
|
func (b *ActualizarRepuestoBuilder) Build() (*models.Repuesto, error) {
|
||||||
aliases := b.dto.Aliases
|
if b.dto == nil {
|
||||||
if aliases == nil {
|
return nil, errors.New("faltan los datos del repuesto")
|
||||||
aliases = []string{}
|
}
|
||||||
|
if b.dto.ID == nil || *b.dto.ID == 0 {
|
||||||
|
AcumularError(&b.err, "el ID del repuesto es obligatorio")
|
||||||
|
}
|
||||||
|
if b.marcaID == 0 {
|
||||||
|
AcumularError(&b.err, "la marca es obligatoria")
|
||||||
}
|
}
|
||||||
|
|
||||||
repuesto := models.Repuesto{
|
nombre, ok := ValidarTexto(b.dto.Nombre, "el nombre", &b.err)
|
||||||
|
if ok {
|
||||||
|
b.dto.Nombre = nombre
|
||||||
|
}
|
||||||
|
descripcion, ok := ValidarTexto(b.dto.Descripcion, "la descripción", &b.err)
|
||||||
|
if ok {
|
||||||
|
b.dto.Descripcion = descripcion
|
||||||
|
}
|
||||||
|
if b.dto.Precio < 0 {
|
||||||
|
AcumularError(&b.err, "el precio no puede ser negativo")
|
||||||
|
}
|
||||||
|
if b.dto.StockMinimo < 0 {
|
||||||
|
AcumularError(&b.err, "el stock mínimo no puede ser negativo")
|
||||||
|
}
|
||||||
|
if b.err != nil {
|
||||||
|
return nil, b.err
|
||||||
|
}
|
||||||
|
|
||||||
|
repuesto := &models.Repuesto{
|
||||||
Nombre: b.dto.Nombre,
|
Nombre: b.dto.Nombre,
|
||||||
Descripcion: b.dto.Descripcion,
|
Descripcion: b.dto.Descripcion,
|
||||||
Precio: b.dto.Precio,
|
Precio: b.dto.Precio,
|
||||||
StockMinimo: int64(b.dto.StockMinimo),
|
StockMinimo: int64(b.dto.StockMinimo),
|
||||||
MarcaID: b.marcaID,
|
MarcaID: b.marcaID,
|
||||||
Aliases: aliases,
|
Aliases: ListaNoNil(b.dto.Aliases),
|
||||||
}
|
}
|
||||||
|
|
||||||
if b.dto.ID != nil {
|
|
||||||
repuesto.ID = uint(*b.dto.ID)
|
repuesto.ID = uint(*b.dto.ID)
|
||||||
}
|
|
||||||
|
|
||||||
return repuesto
|
return repuesto, nil
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
package dto_builders
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
|
||||||
|
"repuestera_back/dto"
|
||||||
|
models_seguridad "repuestera_back/models/seguridad"
|
||||||
|
)
|
||||||
|
|
||||||
|
type AuthResponseBuilder struct {
|
||||||
|
accessToken string
|
||||||
|
refreshToken string
|
||||||
|
tokenType string
|
||||||
|
expiresIn int
|
||||||
|
permisos []uint
|
||||||
|
empresa *dto.EmpresaResumen
|
||||||
|
empresas []dto.EmpresaResumen
|
||||||
|
usuario *dto.UsuarioResumen
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ IBuilder[dto.AuthResponse] = (*AuthResponseBuilder)(nil)
|
||||||
|
|
||||||
|
func NewAuthResponseBuilder() *AuthResponseBuilder {
|
||||||
|
return &AuthResponseBuilder{tokenType: "Bearer"}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *AuthResponseBuilder) ConTokens(accessToken, refreshToken string, expiresIn int) *AuthResponseBuilder {
|
||||||
|
if accessToken == "" || refreshToken == "" {
|
||||||
|
AcumularError(&b.err, "los tokens de acceso y refresco son obligatorios")
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
if expiresIn <= 0 {
|
||||||
|
AcumularError(&b.err, "la duración del token debe ser positiva")
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
b.accessToken = accessToken
|
||||||
|
b.refreshToken = refreshToken
|
||||||
|
b.expiresIn = expiresIn
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *AuthResponseBuilder) ConPermisos(permisos []uint) *AuthResponseBuilder {
|
||||||
|
b.permisos = ListaNoNil(permisos)
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *AuthResponseBuilder) ConEmpresa(empresa *dto.EmpresaResumen) *AuthResponseBuilder {
|
||||||
|
b.empresa = empresa
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *AuthResponseBuilder) ConEmpresas(empresas []dto.EmpresaResumen) *AuthResponseBuilder {
|
||||||
|
b.empresas = ListaNoNil(empresas)
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *AuthResponseBuilder) ConUsuario(usuario *dto.UsuarioResumen) *AuthResponseBuilder {
|
||||||
|
if usuario == nil {
|
||||||
|
AcumularError(&b.err, "el usuario de la sesión es obligatorio")
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
if usuario.ID == 0 {
|
||||||
|
AcumularError(&b.err, "el usuario de la sesión debe tener un ID válido")
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
b.usuario = usuario
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *AuthResponseBuilder) Build() (*dto.AuthResponse, error) {
|
||||||
|
if b.err != nil {
|
||||||
|
return nil, b.err
|
||||||
|
}
|
||||||
|
if b.usuario == nil {
|
||||||
|
return nil, errors.New("falta el usuario de la sesión")
|
||||||
|
}
|
||||||
|
if b.accessToken == "" || b.refreshToken == "" {
|
||||||
|
return nil, errors.New("faltan los tokens de la sesión")
|
||||||
|
}
|
||||||
|
|
||||||
|
respuesta := &dto.AuthResponse{
|
||||||
|
AccessToken: b.accessToken,
|
||||||
|
RefreshToken: b.refreshToken,
|
||||||
|
TokenType: b.tokenType,
|
||||||
|
ExpiresIn: b.expiresIn,
|
||||||
|
Permissions: b.permisos,
|
||||||
|
Empresa: b.empresa,
|
||||||
|
Empresas: b.empresas,
|
||||||
|
Usuario: *b.usuario,
|
||||||
|
DebeCambiarPassword: b.usuario.DebeCambiarPassword,
|
||||||
|
}
|
||||||
|
if b.empresa != nil {
|
||||||
|
respuesta.EmpresaRol = b.empresa.Rol
|
||||||
|
}
|
||||||
|
|
||||||
|
return respuesta, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SesionDirector arma la respuesta de login, refresh y cambio de empresa.
|
||||||
|
type SesionDirector struct{}
|
||||||
|
|
||||||
|
func NewSesionDirector() *SesionDirector {
|
||||||
|
return &SesionDirector{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *SesionDirector) Construir(
|
||||||
|
usuario *models_seguridad.Usuario,
|
||||||
|
empresa *models_seguridad.Empresa,
|
||||||
|
rol models_seguridad.RolEmpresa,
|
||||||
|
empresas []dto.EmpresaResumen,
|
||||||
|
permisos []uint,
|
||||||
|
accessToken string,
|
||||||
|
refreshToken string,
|
||||||
|
expiresIn int,
|
||||||
|
) (*dto.AuthResponse, error) {
|
||||||
|
empresaResumen, err := NewEmpresaResumenDirector().DesdeEmpresa(empresa, rol)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
usuarioResumen, err := NewUsuarioResumenDirector().DesdeUsuario(usuario)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return NewAuthResponseBuilder().
|
||||||
|
ConTokens(accessToken, refreshToken, expiresIn).
|
||||||
|
ConPermisos(permisos).
|
||||||
|
ConEmpresa(empresaResumen).
|
||||||
|
ConEmpresas(empresas).
|
||||||
|
ConUsuario(usuarioResumen).
|
||||||
|
Build()
|
||||||
|
}
|
||||||
@@ -1,40 +1,70 @@
|
|||||||
package dto_builders
|
package dto_builders
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"errors"
|
||||||
|
|
||||||
dto "repuestera_back/dto/Repuestos"
|
dto "repuestera_back/dto/Repuestos"
|
||||||
"repuestera_back/models"
|
"repuestera_back/models"
|
||||||
)
|
)
|
||||||
|
|
||||||
type RepuestoBuilder struct {
|
type CrearRepuestoBuilder struct {
|
||||||
dto *dto.CrearRepuestoDto
|
dto *dto.CrearRepuestoDto
|
||||||
marcaID uint
|
marcaID uint
|
||||||
|
err error
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewRepuestoBuilder() *RepuestoBuilder {
|
var _ IBuilder[models.Repuesto] = (*CrearRepuestoBuilder)(nil)
|
||||||
return &RepuestoBuilder{}
|
|
||||||
|
func NewCrearRepuestoBuilder() *CrearRepuestoBuilder {
|
||||||
|
return &CrearRepuestoBuilder{}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *RepuestoBuilder) ConDto(dto dto.CrearRepuestoDto) *RepuestoBuilder {
|
func (b *CrearRepuestoBuilder) ConDto(data dto.CrearRepuestoDto) *CrearRepuestoBuilder {
|
||||||
b.dto = &dto
|
b.dto = &data
|
||||||
return b
|
return b
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *RepuestoBuilder) ConMarca(marcaID uint) *RepuestoBuilder {
|
func (b *CrearRepuestoBuilder) ConMarca(marcaID uint) *CrearRepuestoBuilder {
|
||||||
|
if marcaID == 0 {
|
||||||
|
AcumularError(&b.err, "la marca es obligatoria")
|
||||||
|
return b
|
||||||
|
}
|
||||||
b.marcaID = marcaID
|
b.marcaID = marcaID
|
||||||
return b
|
return b
|
||||||
}
|
}
|
||||||
func (b *RepuestoBuilder) Build() models.Repuesto {
|
|
||||||
aliases := b.dto.Aliases
|
|
||||||
|
|
||||||
if aliases == nil {
|
func (b *CrearRepuestoBuilder) Build() (*models.Repuesto, error) {
|
||||||
aliases = []string{}
|
if b.dto == nil {
|
||||||
|
return nil, errors.New("faltan los datos del repuesto")
|
||||||
}
|
}
|
||||||
return models.Repuesto{
|
if b.marcaID == 0 {
|
||||||
|
AcumularError(&b.err, "la marca es obligatoria")
|
||||||
|
}
|
||||||
|
|
||||||
|
nombre, ok := ValidarTexto(b.dto.Nombre, "el nombre", &b.err)
|
||||||
|
if ok {
|
||||||
|
b.dto.Nombre = nombre
|
||||||
|
}
|
||||||
|
descripcion, ok := ValidarTexto(b.dto.Descripcion, "la descripción", &b.err)
|
||||||
|
if ok {
|
||||||
|
b.dto.Descripcion = descripcion
|
||||||
|
}
|
||||||
|
if b.dto.Precio < 0 {
|
||||||
|
AcumularError(&b.err, "el precio no puede ser negativo")
|
||||||
|
}
|
||||||
|
if b.dto.StockMinimo < 0 {
|
||||||
|
AcumularError(&b.err, "el stock mínimo no puede ser negativo")
|
||||||
|
}
|
||||||
|
if b.err != nil {
|
||||||
|
return nil, b.err
|
||||||
|
}
|
||||||
|
|
||||||
|
return &models.Repuesto{
|
||||||
Nombre: b.dto.Nombre,
|
Nombre: b.dto.Nombre,
|
||||||
Descripcion: b.dto.Descripcion,
|
Descripcion: b.dto.Descripcion,
|
||||||
Precio: b.dto.Precio,
|
Precio: b.dto.Precio,
|
||||||
StockMinimo: int64(b.dto.StockMinimo),
|
StockMinimo: int64(b.dto.StockMinimo),
|
||||||
MarcaID: b.marcaID,
|
MarcaID: b.marcaID,
|
||||||
Aliases: aliases,
|
Aliases: ListaNoNil(b.dto.Aliases),
|
||||||
}
|
}, nil
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
package dto_builders
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
|
||||||
|
"repuestera_back/dto"
|
||||||
|
models_seguridad "repuestera_back/models/seguridad"
|
||||||
|
)
|
||||||
|
|
||||||
|
type EmpresaActualResponseBuilder struct {
|
||||||
|
empresa *models_seguridad.Empresa
|
||||||
|
rol models_seguridad.RolEmpresa
|
||||||
|
miembros int64
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ IBuilder[dto.EmpresaActualResponse] = (*EmpresaActualResponseBuilder)(nil)
|
||||||
|
|
||||||
|
func NewEmpresaActualResponseBuilder() *EmpresaActualResponseBuilder {
|
||||||
|
return &EmpresaActualResponseBuilder{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *EmpresaActualResponseBuilder) ConEmpresa(empresa *models_seguridad.Empresa) *EmpresaActualResponseBuilder {
|
||||||
|
if empresa == nil {
|
||||||
|
AcumularError(&b.err, "la empresa no puede ser nula")
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
b.empresa = empresa
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *EmpresaActualResponseBuilder) ConRol(rol models_seguridad.RolEmpresa) *EmpresaActualResponseBuilder {
|
||||||
|
b.rol = rol
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *EmpresaActualResponseBuilder) ConMiembrosActivos(miembros int64) *EmpresaActualResponseBuilder {
|
||||||
|
b.miembros = miembros
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *EmpresaActualResponseBuilder) Build() (*dto.EmpresaActualResponse, error) {
|
||||||
|
if b.err != nil {
|
||||||
|
return nil, b.err
|
||||||
|
}
|
||||||
|
if b.empresa == nil {
|
||||||
|
return nil, errors.New("falta la empresa")
|
||||||
|
}
|
||||||
|
|
||||||
|
return &dto.EmpresaActualResponse{
|
||||||
|
ID: b.empresa.ID,
|
||||||
|
Nombre: b.empresa.Nombre,
|
||||||
|
Slug: b.empresa.Slug,
|
||||||
|
Cuit: b.empresa.Cuit,
|
||||||
|
Activa: b.empresa.Activa,
|
||||||
|
Rol: string(b.rol),
|
||||||
|
MiembrosActivos: b.miembros,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
package dto_builders
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
|
||||||
|
"repuestera_back/dto"
|
||||||
|
models_seguridad "repuestera_back/models/seguridad"
|
||||||
|
)
|
||||||
|
|
||||||
|
type EmpresaAdminResponseBuilder struct {
|
||||||
|
empresa *models_seguridad.Empresa
|
||||||
|
miembros int64
|
||||||
|
owners int64
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ IBuilder[dto.EmpresaAdminResponse] = (*EmpresaAdminResponseBuilder)(nil)
|
||||||
|
|
||||||
|
func NewEmpresaAdminResponseBuilder() *EmpresaAdminResponseBuilder {
|
||||||
|
return &EmpresaAdminResponseBuilder{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *EmpresaAdminResponseBuilder) ConEmpresa(empresa *models_seguridad.Empresa) *EmpresaAdminResponseBuilder {
|
||||||
|
if empresa == nil {
|
||||||
|
AcumularError(&b.err, "la empresa no puede ser nula")
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
b.empresa = empresa
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *EmpresaAdminResponseBuilder) ConContadores(miembros, owners int64) *EmpresaAdminResponseBuilder {
|
||||||
|
if miembros < 0 || owners < 0 {
|
||||||
|
AcumularError(&b.err, "los contadores no pueden ser negativos")
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
b.miembros = miembros
|
||||||
|
b.owners = owners
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *EmpresaAdminResponseBuilder) Build() (*dto.EmpresaAdminResponse, error) {
|
||||||
|
if b.err != nil {
|
||||||
|
return nil, b.err
|
||||||
|
}
|
||||||
|
if b.empresa == nil {
|
||||||
|
return nil, errors.New("falta la empresa")
|
||||||
|
}
|
||||||
|
|
||||||
|
return &dto.EmpresaAdminResponse{
|
||||||
|
ID: b.empresa.ID,
|
||||||
|
Nombre: b.empresa.Nombre,
|
||||||
|
Slug: b.empresa.Slug,
|
||||||
|
Cuit: b.empresa.Cuit,
|
||||||
|
Activa: b.empresa.Activa,
|
||||||
|
Miembros: b.miembros,
|
||||||
|
Owners: b.owners,
|
||||||
|
CreatedAt: b.empresa.CreatedAt,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
@@ -1,39 +1,69 @@
|
|||||||
package dto_builders
|
package dto_builders
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"errors"
|
||||||
|
"sort"
|
||||||
|
|
||||||
"repuestera_back/dto"
|
"repuestera_back/dto"
|
||||||
models_seguridad "repuestera_back/models/seguridad"
|
models_seguridad "repuestera_back/models/seguridad"
|
||||||
)
|
)
|
||||||
|
|
||||||
type GrupoSimpleBuilder struct {
|
type GrupoSimpleBuilder struct {
|
||||||
grupo *models_seguridad.Grupo
|
grupo *models_seguridad.Grupo
|
||||||
|
err error
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var _ IBuilder[dto.GrupoSimpleDTO] = (*GrupoSimpleBuilder)(nil)
|
||||||
|
|
||||||
func NewGrupoSimpleBuilder(grupo *models_seguridad.Grupo) *GrupoSimpleBuilder {
|
func NewGrupoSimpleBuilder(grupo *models_seguridad.Grupo) *GrupoSimpleBuilder {
|
||||||
return &GrupoSimpleBuilder{
|
builder := &GrupoSimpleBuilder{}
|
||||||
grupo: grupo,
|
builder.ConGrupo(grupo)
|
||||||
}
|
return builder
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *GrupoSimpleBuilder) Build() dto.GrupoSimpleDTO {
|
func (b *GrupoSimpleBuilder) ConGrupo(grupo *models_seguridad.Grupo) *GrupoSimpleBuilder {
|
||||||
permisosMap := make(map[uint]models_seguridad.Permiso)
|
if grupo == nil {
|
||||||
|
AcumularError(&b.err, "el grupo no puede ser nulo")
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
b.grupo = grupo
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
b.grupo.ListarPermisos(permisosMap)
|
func (b *GrupoSimpleBuilder) Build() (*dto.GrupoSimpleDTO, error) {
|
||||||
|
if b.err != nil {
|
||||||
|
return nil, b.err
|
||||||
|
}
|
||||||
|
if b.grupo == nil {
|
||||||
|
return nil, errors.New("falta el grupo")
|
||||||
|
}
|
||||||
|
|
||||||
|
permisosMap := make(map[uint]models_seguridad.Permiso)
|
||||||
|
visitados := make(map[uint]bool)
|
||||||
|
b.grupo.ListarPermisos(permisosMap, visitados)
|
||||||
|
|
||||||
permisos := make([]dto.PermisoSimpleDTO, 0, len(permisosMap))
|
permisos := make([]dto.PermisoSimpleDTO, 0, len(permisosMap))
|
||||||
|
|
||||||
for _, permiso := range permisosMap {
|
for _, permiso := range permisosMap {
|
||||||
permisos = append(permisos, dto.PermisoSimpleDTO{
|
permisos = append(permisos, dto.PermisoSimpleDTO{
|
||||||
|
ID: permiso.ID,
|
||||||
Nombre: permiso.Nombre,
|
Nombre: permiso.Nombre,
|
||||||
Alias: permiso.Alias,
|
Alias: permiso.Alias,
|
||||||
Imagen: permiso.Imagen,
|
Imagen: permiso.Imagen,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
return dto.GrupoSimpleDTO{
|
sort.Slice(permisos, func(i, j int) bool {
|
||||||
|
if permisos[i].ID == permisos[j].ID {
|
||||||
|
return permisos[i].Nombre < permisos[j].Nombre
|
||||||
|
}
|
||||||
|
return permisos[i].ID < permisos[j].ID
|
||||||
|
})
|
||||||
|
|
||||||
|
return &dto.GrupoSimpleDTO{
|
||||||
|
ID: b.grupo.ID,
|
||||||
Nombre: b.grupo.Nombre,
|
Nombre: b.grupo.Nombre,
|
||||||
Descripcion: b.grupo.Descripcion,
|
Descripcion: b.grupo.Descripcion,
|
||||||
Imagen: b.grupo.Imagen,
|
Imagen: b.grupo.Imagen,
|
||||||
Permisos: permisos,
|
Permisos: permisos,
|
||||||
}
|
}, nil
|
||||||
}
|
}
|
||||||
@@ -1,223 +0,0 @@
|
|||||||
package dto_builders
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"reflect"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"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, guardando los campos del
|
|
||||||
// registro en la lista de detalles (ValorNuevo).
|
|
||||||
func (d *LogDirector) Crear(uid uint, tabla string, entidad any) (*logs.Log, error) {
|
|
||||||
detalles := generarDetallesCreacion(tabla, entidad)
|
|
||||||
if len(detalles) == 0 {
|
|
||||||
id := ObtenerID(entidad)
|
|
||||||
detalles = []logs.LogDetalle{
|
|
||||||
{
|
|
||||||
NombreTabla: tabla,
|
|
||||||
Columna: "*",
|
|
||||||
ValorNuevo: fmt.Sprintf("Registro creado (ID: %v)", id),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return d.Custom(uid, logs.AccionCrear, detalles)
|
|
||||||
}
|
|
||||||
|
|
||||||
// generarDetallesCreacion recorre los campos exportados de la entidad y los
|
|
||||||
// persiste como detalles con ValorNuevo (no hay estado anterior).
|
|
||||||
func generarDetallesCreacion(tabla string, entidad any) []logs.LogDetalle {
|
|
||||||
var detalles []logs.LogDetalle
|
|
||||||
|
|
||||||
val := reflect.ValueOf(entidad)
|
|
||||||
for val.IsValid() && val.Kind() == reflect.Ptr {
|
|
||||||
if val.IsNil() {
|
|
||||||
return detalles
|
|
||||||
}
|
|
||||||
val = val.Elem()
|
|
||||||
}
|
|
||||||
if !val.IsValid() || val.Kind() != reflect.Struct {
|
|
||||||
return detalles
|
|
||||||
}
|
|
||||||
|
|
||||||
tipo := val.Type()
|
|
||||||
|
|
||||||
// Incluye el ID aunque esté dentro del gorm.Model embebido.
|
|
||||||
if id := ObtenerID(entidad); id != nil {
|
|
||||||
detalles = append(detalles, logs.LogDetalle{
|
|
||||||
NombreTabla: tabla,
|
|
||||||
Columna: "ID",
|
|
||||||
ValorNuevo: fmt.Sprintf("%v", id),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
for i := 0; i < tipo.NumField(); i++ {
|
|
||||||
campo := tipo.Field(i)
|
|
||||||
if campo.PkgPath != "" {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if campo.Name == "Model" || campo.Name == "CreatedAt" || campo.Name == "UpdatedAt" || campo.Name == "DeletedAt" || campo.Name == "ID" {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
valor := val.Field(i)
|
|
||||||
if !valor.CanInterface() {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
v := fmt.Sprintf("%v", valor.Interface())
|
|
||||||
if strings.TrimSpace(v) == "" || v == "0" {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
detalles = append(detalles, logs.LogDetalle{
|
|
||||||
NombreTabla: tabla,
|
|
||||||
Columna: campo.Name,
|
|
||||||
ValorNuevo: v,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
return detalles
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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,35 +0,0 @@
|
|||||||
package dto_builders
|
|
||||||
|
|
||||||
import (
|
|
||||||
dto "repuestera_back/dto/Logs"
|
|
||||||
"repuestera_back/models/logs"
|
|
||||||
)
|
|
||||||
|
|
||||||
type LogTablaBuilder struct {
|
|
||||||
logs []logs.Log
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewLogTablaBuilder() *LogTablaBuilder {
|
|
||||||
return &LogTablaBuilder{}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *LogTablaBuilder) ConLogs(logs []logs.Log) *LogTablaBuilder {
|
|
||||||
b.logs = logs
|
|
||||||
return b
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *LogTablaBuilder) Build() []dto.LogTablaDto {
|
|
||||||
var dtos []dto.LogTablaDto
|
|
||||||
|
|
||||||
for i := 0; i < len(b.logs); i++ {
|
|
||||||
var d = &dto.LogTablaDto{
|
|
||||||
ID: b.logs[i].ID,
|
|
||||||
UsuarioID: b.logs[i].UsuarioID,
|
|
||||||
Accion: b.logs[i].Accion,
|
|
||||||
Detalles: b.logs[i].Detalles,
|
|
||||||
CreatedAt: b.logs[i].CreatedAt,
|
|
||||||
}
|
|
||||||
dtos = append(dtos, *d)
|
|
||||||
}
|
|
||||||
return dtos
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
package dto_builders
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// AcumularError agrega un mensaje al error acumulado por un builder.
|
||||||
|
// Se usa dentro de los métodos Con<Parte> para no interrumpir la
|
||||||
|
// construcción y devolver todos los problemas juntos desde Build().
|
||||||
|
func AcumularError(dst *error, mensaje string) {
|
||||||
|
*dst = errors.Join(*dst, errors.New(mensaje))
|
||||||
|
}
|
||||||
|
|
||||||
|
// AcumularErrores agrega errores no nulos al error acumulado.
|
||||||
|
func AcumularErrores(dst *error, errs ...error) {
|
||||||
|
for _, err := range errs {
|
||||||
|
if err != nil {
|
||||||
|
*dst = errors.Join(*dst, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ValidarTexto recorta los espacios de un texto y verifica que no quede
|
||||||
|
// vacío. Devuelve el texto normalizado y si es válido.
|
||||||
|
func ValidarTexto(valor, campo string, dst *error) (string, bool) {
|
||||||
|
valor = strings.TrimSpace(valor)
|
||||||
|
if valor == "" {
|
||||||
|
AcumularError(dst, campo+" no puede ser nulo o vacío")
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
return valor, true
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListaNoNil devuelve una lista vacía cuando el slice es nil, para que
|
||||||
|
// el JSON de respuesta sea [] y no null.
|
||||||
|
func ListaNoNil[T any](items []T) []T {
|
||||||
|
if items == nil {
|
||||||
|
return []T{}
|
||||||
|
}
|
||||||
|
return items
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package dto
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
// ClienteResumen es la representación de un cliente sin sus
|
||||||
|
// comprobantes asociados. Se usa dentro de respuestas compuestas,
|
||||||
|
// como FacturaResponse.
|
||||||
|
type ClienteResumen struct {
|
||||||
|
ID uint `json:"ID"`
|
||||||
|
CreatedAt time.Time `json:"CreatedAt"`
|
||||||
|
UpdatedAt time.Time `json:"UpdatedAt"`
|
||||||
|
DeletedAt *time.Time `json:"DeletedAt"`
|
||||||
|
EmpresaID uint `json:"empresaId"`
|
||||||
|
Nombre string `json:"nombre"`
|
||||||
|
Cuit string `json:"cuit"`
|
||||||
|
Email string `json:"email,omitempty"`
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
package dto
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
|
||||||
|
dto_base "repuestera_back/dto"
|
||||||
|
dto_clientes "repuestera_back/dto/Clientes"
|
||||||
|
dto_proveedores "repuestera_back/dto/Proveedores"
|
||||||
|
"repuestera_back/models"
|
||||||
|
)
|
||||||
|
|
||||||
|
// FacturaResponse es la representación pública de una factura. Incluye
|
||||||
|
// los resúmenes de cliente, proveedor y responsable, pero no las
|
||||||
|
// relaciones internas de esos modelos.
|
||||||
|
type FacturaResponse struct {
|
||||||
|
ID uint `json:"ID"`
|
||||||
|
CreatedAt time.Time `json:"CreatedAt"`
|
||||||
|
UpdatedAt time.Time `json:"UpdatedAt"`
|
||||||
|
DeletedAt *time.Time `json:"DeletedAt"`
|
||||||
|
EmpresaID uint `json:"empresaId"`
|
||||||
|
Numero string `json:"numero"`
|
||||||
|
Estado string `json:"estado"`
|
||||||
|
Total float64 `json:"total"`
|
||||||
|
ClienteID uint `json:"ClienteID,omitempty"`
|
||||||
|
Cliente dto_clientes.ClienteResumen `json:"cliente"`
|
||||||
|
ProveedorID *uint `json:"proveedorId,omitempty"`
|
||||||
|
Proveedor *dto_proveedores.ProveedorResumen `json:"proveedor,omitempty"`
|
||||||
|
SeAviso bool `json:"seAviso"`
|
||||||
|
Detalles []models.FacturaDetalle `json:"detalles,omitempty"`
|
||||||
|
ResponsableID uint `json:"ResponsableID,omitempty"`
|
||||||
|
Responsable *dto_base.UsuarioResumen `json:"usuario,omitempty"`
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
package dto
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
|
||||||
|
dto_base "repuestera_back/dto"
|
||||||
|
"repuestera_back/models/logs"
|
||||||
|
|
||||||
|
"gorm.io/datatypes"
|
||||||
|
)
|
||||||
|
|
||||||
|
// LogResponse es la representación pública de un log. Incluye un
|
||||||
|
// resumen del usuario que realizó la acción, sin sus relaciones
|
||||||
|
// internas.
|
||||||
|
type LogResponse struct {
|
||||||
|
ID uint64 `json:"id"`
|
||||||
|
EmpresaID uint `json:"empresaId"`
|
||||||
|
UsuarioID uint `json:"usuarioId"`
|
||||||
|
Usuario *dto_base.UsuarioResumen `json:"usuario,omitempty"`
|
||||||
|
Accion string `json:"accion"`
|
||||||
|
Detalles datatypes.JSONSlice[logs.LogDetalle] `json:"detalles,omitempty"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
package dto
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
// MarcaResumen es la representación de una marca sin sus repuestos
|
||||||
|
// asociados.
|
||||||
|
type MarcaResumen struct {
|
||||||
|
ID uint `json:"ID"`
|
||||||
|
CreatedAt time.Time `json:"CreatedAt"`
|
||||||
|
UpdatedAt time.Time `json:"UpdatedAt"`
|
||||||
|
DeletedAt *time.Time `json:"DeletedAt"`
|
||||||
|
EmpresaID uint `json:"empresaId"`
|
||||||
|
Nombre string `json:"nombre"`
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package dto
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
// ProveedorResumen es la representación de un proveedor sin sus
|
||||||
|
// facturas asociadas. Se usa dentro de respuestas compuestas.
|
||||||
|
type ProveedorResumen struct {
|
||||||
|
ID uint `json:"ID"`
|
||||||
|
CreatedAt time.Time `json:"CreatedAt"`
|
||||||
|
UpdatedAt time.Time `json:"UpdatedAt"`
|
||||||
|
DeletedAt *time.Time `json:"DeletedAt"`
|
||||||
|
EmpresaID uint `json:"empresaId"`
|
||||||
|
Nombre string `json:"nombre"`
|
||||||
|
Cuit string `json:"cuit,omitempty"`
|
||||||
|
Email string `json:"email,omitempty"`
|
||||||
|
Telefono string `json:"telefono,omitempty"`
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
package dto
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
|
||||||
|
dto_marcas "repuestera_back/dto/Marcas"
|
||||||
|
)
|
||||||
|
|
||||||
|
// RepuestoResumen es la representación de un repuesto sin sus stocks
|
||||||
|
// asociados. Se usa dentro de respuestas de stock y de facturas.
|
||||||
|
type RepuestoResumen struct {
|
||||||
|
ID uint `json:"ID"`
|
||||||
|
CreatedAt time.Time `json:"CreatedAt"`
|
||||||
|
UpdatedAt time.Time `json:"UpdatedAt"`
|
||||||
|
DeletedAt *time.Time `json:"DeletedAt"`
|
||||||
|
EmpresaID uint `json:"empresaId"`
|
||||||
|
Nombre string `json:"nombre"`
|
||||||
|
Descripcion string `json:"descripcion"`
|
||||||
|
Precio float64 `json:"precio"`
|
||||||
|
StockMinimo int64 `json:"stockMinimo"`
|
||||||
|
MarcaID uint `json:"marcaId"`
|
||||||
|
Marca *dto_marcas.MarcaResumen `json:"marca,omitempty"`
|
||||||
|
Aliases []string `json:"aliases,omitempty"`
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
package dto
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
|
||||||
|
dto_almacenes "repuestera_back/dto/Almacenes"
|
||||||
|
dto_repuestos "repuestera_back/dto/Repuestos"
|
||||||
|
)
|
||||||
|
|
||||||
|
// StockResponse es la representación pública de una fila de stock.
|
||||||
|
// Agrega el disponible y el estado calculados, y evita exponer las
|
||||||
|
// relaciones internas del repuesto y del almacén.
|
||||||
|
type StockResponse struct {
|
||||||
|
ID uint64 `json:"id"`
|
||||||
|
EmpresaID uint64 `json:"empresaId"`
|
||||||
|
RepuestoID uint64 `json:"repuestoId"`
|
||||||
|
Repuesto dto_repuestos.RepuestoResumen `json:"repuesto"`
|
||||||
|
AlmacenID uint `json:"almacenId"`
|
||||||
|
Almacen *dto_almacenes.AlmacenResumen `json:"almacen,omitempty"`
|
||||||
|
Cantidad float64 `json:"cantidad"`
|
||||||
|
CantidadReservada float64 `json:"cantidadReservada"`
|
||||||
|
Disponible float64 `json:"disponible"`
|
||||||
|
Estado string `json:"estado"`
|
||||||
|
Observacion string `json:"observacion"`
|
||||||
|
CreatedAt time.Time `json:"createdAt"`
|
||||||
|
UpdatedAt time.Time `json:"updatedAt"`
|
||||||
|
DeletedAt *time.Time `json:"deletedAt,omitempty"`
|
||||||
|
}
|
||||||
@@ -27,7 +27,6 @@ type AuthResponse struct {
|
|||||||
Empresa *EmpresaResumen `json:"empresa,omitempty"`
|
Empresa *EmpresaResumen `json:"empresa,omitempty"`
|
||||||
Empresas []EmpresaResumen `json:"empresas"`
|
Empresas []EmpresaResumen `json:"empresas"`
|
||||||
EmpresaRol string `json:"empresa_rol"`
|
EmpresaRol string `json:"empresa_rol"`
|
||||||
EsPlataformaAdmin bool `json:"es_plataforma_admin"`
|
|
||||||
Usuario UsuarioResumen `json:"usuario"`
|
Usuario UsuarioResumen `json:"usuario"`
|
||||||
DebeCambiarPassword bool `json:"debe_cambiar_password"`
|
DebeCambiarPassword bool `json:"debe_cambiar_password"`
|
||||||
}
|
}
|
||||||
@@ -55,7 +54,6 @@ type MeResponse struct {
|
|||||||
Empresa *EmpresaResumen `json:"empresa,omitempty"`
|
Empresa *EmpresaResumen `json:"empresa,omitempty"`
|
||||||
Empresas []EmpresaResumen `json:"empresas"`
|
Empresas []EmpresaResumen `json:"empresas"`
|
||||||
EmpresaRol string `json:"empresa_rol"`
|
EmpresaRol string `json:"empresa_rol"`
|
||||||
EsPlataformaAdmin bool `json:"es_plataforma_admin"`
|
|
||||||
Activo bool `json:"activo"`
|
Activo bool `json:"activo"`
|
||||||
DebeCambiarPassword bool `json:"debe_cambiar_password"`
|
DebeCambiarPassword bool `json:"debe_cambiar_password"`
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,121 @@
|
|||||||
|
package dto
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
// EmpresaResponse es la representación pública de una empresa.
|
||||||
|
type EmpresaResponse struct {
|
||||||
|
ID uint `json:"id"`
|
||||||
|
Nombre string `json:"nombre"`
|
||||||
|
Slug string `json:"slug"`
|
||||||
|
Cuit *string `json:"cuit,omitempty"`
|
||||||
|
Activa bool `json:"activa"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// EmpresaActualResponse describe la empresa activa de la sesión.
|
||||||
|
type EmpresaActualResponse struct {
|
||||||
|
ID uint `json:"id"`
|
||||||
|
Nombre string `json:"nombre"`
|
||||||
|
Slug string `json:"slug"`
|
||||||
|
Cuit *string `json:"cuit,omitempty"`
|
||||||
|
Activa bool `json:"activa"`
|
||||||
|
Rol string `json:"rol"`
|
||||||
|
MiembrosActivos int64 `json:"miembros_activos"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// EmpresasResponse es el envelope de empresas del usuario.
|
||||||
|
type EmpresasResponse struct {
|
||||||
|
Empresas []EmpresaResumen `json:"empresas"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// MiembrosListadoResponse conserva las claves usuarios y miembros por
|
||||||
|
// compatibilidad con clientes anteriores.
|
||||||
|
type MiembrosListadoResponse struct {
|
||||||
|
Usuarios []MiembroResponse `json:"usuarios"`
|
||||||
|
Miembros []MiembroResponse `json:"miembros"`
|
||||||
|
Total int64 `json:"total"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// MiembroCreadoResponse es la respuesta de alta de un miembro.
|
||||||
|
type MiembroCreadoResponse struct {
|
||||||
|
Usuario MiembroResponse `json:"usuario"`
|
||||||
|
PasswordTemporal string `json:"password_temporal"`
|
||||||
|
UsuarioExistente bool `json:"usuario_existente"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// InvitacionResponse es la representación pública de una invitación.
|
||||||
|
type InvitacionResponse struct {
|
||||||
|
ID uint `json:"id"`
|
||||||
|
EmpresaID uint `json:"empresa_id"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
Rol string `json:"rol"`
|
||||||
|
GrupoID uint `json:"grupo_id"`
|
||||||
|
ExpiraEn time.Time `json:"expira_en"`
|
||||||
|
UsadaEn *time.Time `json:"usada_en,omitempty"`
|
||||||
|
CreadaPor uint `json:"creada_por"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// InvitacionesResponse es el envelope de invitaciones de una empresa.
|
||||||
|
type InvitacionesResponse struct {
|
||||||
|
Invitaciones []InvitacionResponse `json:"invitaciones"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// InvitacionCreadaResponse Agrega los datos de entrega al alta de invitación.
|
||||||
|
type InvitacionCreadaResponse struct {
|
||||||
|
Invitacion InvitacionResponse `json:"invitacion"`
|
||||||
|
Token string `json:"token"`
|
||||||
|
Link string `json:"link"`
|
||||||
|
EmailEnviado bool `json:"email_enviado"`
|
||||||
|
ExpiraEn time.Time `json:"expira_en"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// EmpresaAdminResponse es la vista de empresa para plataforma.
|
||||||
|
type EmpresaAdminResponse struct {
|
||||||
|
ID uint `json:"id"`
|
||||||
|
Nombre string `json:"nombre"`
|
||||||
|
Slug string `json:"slug"`
|
||||||
|
Cuit *string `json:"cuit,omitempty"`
|
||||||
|
Activa bool `json:"activa"`
|
||||||
|
Miembros int64 `json:"miembros"`
|
||||||
|
Owners int64 `json:"owners"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// EmpresasAdminListadoResponse es el envelope de empresas de plataforma.
|
||||||
|
type EmpresasAdminListadoResponse struct {
|
||||||
|
Empresas []EmpresaAdminResponse `json:"empresas"`
|
||||||
|
Total int `json:"total"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// EmpresaCreadaResponse es la respuesta de alta de empresa desde plataforma.
|
||||||
|
type EmpresaCreadaResponse struct {
|
||||||
|
Empresa EmpresaAdminResponse `json:"empresa"`
|
||||||
|
Owner MiembroResponse `json:"owner"`
|
||||||
|
PasswordTemporal string `json:"password_temporal"`
|
||||||
|
OwnerExistente bool `json:"owner_existente"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// UsuarioAdminResponse es la vista global de usuario para plataforma.
|
||||||
|
type UsuarioAdminResponse struct {
|
||||||
|
ID uint `json:"id"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Activo bool `json:"activo"`
|
||||||
|
DebeCambiarPassword bool `json:"debe_cambiar_password"`
|
||||||
|
Empresas int `json:"empresas"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// UsuariosAdminListadoResponse es el envelope de usuarios de plataforma.
|
||||||
|
type UsuariosAdminListadoResponse struct {
|
||||||
|
Usuarios []UsuarioAdminResponse `json:"usuarios"`
|
||||||
|
Total int64 `json:"total"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// UsuariosListadoResponse es el envelope de usuarios de una empresa.
|
||||||
|
type UsuariosListadoResponse struct {
|
||||||
|
Usuarios []UsuarioResponse `json:"usuarios"`
|
||||||
|
Total int64 `json:"total"`
|
||||||
|
}
|
||||||
@@ -9,6 +9,7 @@ type GrupoSimpleDTO struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type PermisoSimpleDTO struct {
|
type PermisoSimpleDTO struct {
|
||||||
|
ID uint `json:"id"`
|
||||||
Nombre string `json:"nombre"`
|
Nombre string `json:"nombre"`
|
||||||
Alias string `json:"alias"`
|
Alias string `json:"alias"`
|
||||||
Imagen string `json:"imagen"`
|
Imagen string `json:"imagen"`
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package dto
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
// UsuarioResponse es la representación pública de un usuario.
|
||||||
|
// No incluye contraseña, grupos ni empresas; esos datos se exponen
|
||||||
|
// mediante DTOs específicos cuando el endpoint los necesita.
|
||||||
|
type UsuarioResponse struct {
|
||||||
|
ID uint `json:"id"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Activo bool `json:"activo"`
|
||||||
|
DebeCambiarPassword bool `json:"debe_cambiar_password"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
|
DeletedAt *time.Time `json:"deleted_at,omitempty"`
|
||||||
|
}
|
||||||
@@ -23,7 +23,6 @@ const (
|
|||||||
ClaimSubject = "sub"
|
ClaimSubject = "sub"
|
||||||
ClaimEmpresaID = "empresa_id"
|
ClaimEmpresaID = "empresa_id"
|
||||||
ClaimEmpresaRol = "empresa_rol"
|
ClaimEmpresaRol = "empresa_rol"
|
||||||
ClaimPlataformaAdmin = "es_plataforma_admin"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -58,7 +57,7 @@ func GetSecret() ([]byte, error) {
|
|||||||
|
|
||||||
// GenerarToken firma un token HS256 con los datos del usuario, su empresa
|
// GenerarToken firma un token HS256 con los datos del usuario, su empresa
|
||||||
// activa y sus permisos planos.
|
// activa y sus permisos planos.
|
||||||
func GenerarToken(userID uint, empresaID uint, empresaRol string, esPlataformaAdmin bool, email, name, tokenType string, permissions []uint, duration time.Duration) (string, error) {
|
func GenerarToken(userID uint, empresaID uint, empresaRol string, email, name, tokenType string, permissions []uint, duration time.Duration) (string, error) {
|
||||||
secret, err := GetSecret()
|
secret, err := GetSecret()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
@@ -70,7 +69,6 @@ func GenerarToken(userID uint, empresaID uint, empresaRol string, esPlataformaAd
|
|||||||
"name": name,
|
"name": name,
|
||||||
ClaimEmpresaID: empresaID,
|
ClaimEmpresaID: empresaID,
|
||||||
ClaimEmpresaRol: empresaRol,
|
ClaimEmpresaRol: empresaRol,
|
||||||
ClaimPlataformaAdmin: esPlataformaAdmin,
|
|
||||||
ClaimPermissions: permissions,
|
ClaimPermissions: permissions,
|
||||||
ClaimType: tokenType,
|
ClaimType: tokenType,
|
||||||
"exp": time.Now().Add(duration).Unix(),
|
"exp": time.Now().Add(duration).Unix(),
|
||||||
|
|||||||
Reference in new issue
Block a user