Private
Public Access
393 lines
11 KiB
Go
393 lines
11 KiB
Go
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 && !utils.EsPlataformaAdmin(c) {
|
|
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 utils.EsPlataformaAdmin(c) || 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
|
|
}
|