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"
|
||||
"time"
|
||||
|
||||
"repuestera_back/dto"
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
"repuestera_back/jwtutils"
|
||||
models_seguridad "repuestera_back/models/seguridad"
|
||||
r "repuestera_back/repositorios"
|
||||
@@ -28,21 +28,15 @@ func ObtenerInvitacion(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
expirada := time.Now().After(invitacion.ExpiraEn)
|
||||
usada := invitacion.UsadaEn != nil
|
||||
_, errUsuario := repo.Usuario.ObtenerPorEmail(invitacion.Email)
|
||||
|
||||
c.JSON(http.StatusOK, dto.InvitacionInfo{
|
||||
Email: invitacion.Email,
|
||||
Empresa: invitacion.Empresa.Nombre,
|
||||
EmpresaID: invitacion.EmpresaID,
|
||||
Rol: string(invitacion.Rol),
|
||||
ExpiraEn: invitacion.ExpiraEn,
|
||||
Valida: !expirada && !usada && invitacion.Empresa.Activa,
|
||||
Usada: usada,
|
||||
Expirada: expirada,
|
||||
UsuarioExistente: errUsuario == nil,
|
||||
})
|
||||
respuesta, err := dto_directors.NewInvitacionDirector().Info(invitacion, errUsuario == nil)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, respuesta)
|
||||
}
|
||||
|
||||
// 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)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"message": "Invitación aceptada",
|
||||
"usuario_id": usuario.ID,
|
||||
"empresa_id": invitacion.EmpresaID,
|
||||
})
|
||||
aceptada, buildErr := dto_directors.NewInvitacionDirector().Aceptada(usuario.ID, invitacion.EmpresaID)
|
||||
if buildErr != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": buildErr.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, aceptada)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
+17
-24
@@ -4,6 +4,7 @@ import (
|
||||
"net/http"
|
||||
|
||||
"repuestera_back/dto"
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
r "repuestera_back/repositorios"
|
||||
"repuestera_back/services"
|
||||
"repuestera_back/utils"
|
||||
@@ -25,23 +26,19 @@ func Me(c *gin.Context) {
|
||||
}
|
||||
|
||||
empresaID := utils.EmpresaID(c)
|
||||
respuesta, err := services.ConstruirSesion(id, empresaID)
|
||||
sesion, err := services.ConstruirSesion(id, empresaID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, dto.MeResponse{
|
||||
ID: respuesta.Usuario.ID,
|
||||
Email: respuesta.Usuario.Email,
|
||||
Name: respuesta.Usuario.Name,
|
||||
Permissions: respuesta.Permissions,
|
||||
Empresa: respuesta.Empresa,
|
||||
Empresas: respuesta.Empresas,
|
||||
EmpresaRol: respuesta.EmpresaRol,
|
||||
Activo: respuesta.Usuario.Activo,
|
||||
DebeCambiarPassword: respuesta.DebeCambiarPassword,
|
||||
})
|
||||
respuesta, err := dto_directors.NewMeDirector().DesdeSesion(sesion)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, respuesta)
|
||||
}
|
||||
|
||||
// ObtenerMisEmpresas devuelve las empresas donde el usuario es miembro.
|
||||
@@ -55,9 +52,7 @@ func ObtenerMisEmpresas(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"empresas": empresas,
|
||||
})
|
||||
c.JSON(http.StatusOK, dto.EmpresasResponse{Empresas: empresas})
|
||||
}
|
||||
|
||||
// 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)
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"id": empresa.ID,
|
||||
"nombre": empresa.Nombre,
|
||||
"slug": empresa.Slug,
|
||||
"cuit": empresa.Cuit,
|
||||
"activa": empresa.Activa,
|
||||
"rol": string(rol),
|
||||
"miembros_activos": miembros,
|
||||
})
|
||||
respuesta, err := dto_directors.NewEmpresaActualDirector().DesdeEmpresa(empresa, rol, miembros)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, respuesta)
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"repuestera_back/dto"
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
models_seguridad "repuestera_back/models/seguridad"
|
||||
r "repuestera_back/repositorios"
|
||||
"repuestera_back/services"
|
||||
@@ -74,7 +74,12 @@ func Register(c *gin.Context) {
|
||||
|
||||
respuesta, err := services.ConstruirSesion(user.ID, empresa.ID)
|
||||
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
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
models_seguridad "repuestera_back/models/seguridad"
|
||||
r "repuestera_back/repositorios"
|
||||
"repuestera_back/utils"
|
||||
@@ -47,5 +48,11 @@ func AltaMiembro(c *gin.Context) {
|
||||
miembro.DeletedAt = gorm.DeletedAt{}
|
||||
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"
|
||||
"gorm.io/gorm"
|
||||
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
r "repuestera_back/repositorios"
|
||||
)
|
||||
|
||||
@@ -28,5 +29,11 @@ func ObtenerFactura(c *gin.Context) {
|
||||
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"
|
||||
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
r "repuestera_back/repositorios"
|
||||
)
|
||||
|
||||
@@ -43,7 +44,14 @@ func ObtenerFacturas(c *gin.Context) {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
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) {
|
||||
|
||||
@@ -2,9 +2,11 @@ package grupo
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
models_seguridad "repuestera_back/models/seguridad"
|
||||
r "repuestera_back/repositorios"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
@@ -25,6 +27,16 @@ func ActualizarGrupo(c *gin.Context) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
r.ObtenerRepositorios(c).Grupo.Actualizar(grupo, input)
|
||||
c.JSON(http.StatusOK, grupo)
|
||||
if err := r.ObtenerRepositorios(c).Grupo.Actualizar(grupo, input); err != nil {
|
||||
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 (
|
||||
"net/http"
|
||||
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
models_seguridad "repuestera_back/models/seguridad"
|
||||
r "repuestera_back/repositorios"
|
||||
|
||||
@@ -18,5 +20,12 @@ func CrearGrupo(c *gin.Context) {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
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 (
|
||||
"net/http"
|
||||
dto_builders "repuestera_back/dto/Builders"
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
r "repuestera_back/repositorios"
|
||||
"strconv"
|
||||
|
||||
@@ -21,9 +21,11 @@ func ObtenerGrupo(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
dto := dto_builders.
|
||||
NewGrupoSimpleBuilder(grupo).
|
||||
Build()
|
||||
respuesta, err := dto_directors.NewGrupoSimpleDirector().DesdeGrupo(grupo)
|
||||
if err != nil {
|
||||
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 (
|
||||
"net/http"
|
||||
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
r "repuestera_back/repositorios"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -13,5 +15,12 @@ func ObtenerGrupos(c *gin.Context) {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
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 (
|
||||
"net/http"
|
||||
r "repuestera_back/repositorios"
|
||||
"strconv"
|
||||
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
r "repuestera_back/repositorios"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
@@ -13,7 +15,7 @@ func ObtenerGruposDeUsuario(c *gin.Context) {
|
||||
|
||||
usuarioID, err := strconv.ParseUint(usuarioIDStr, 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(400, gin.H{"error": "id invalido"})
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "id invalido"})
|
||||
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"})
|
||||
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 (
|
||||
"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"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -40,20 +41,28 @@ func ObtenerGruposYPermisosPorEmail(c *gin.Context) {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
grupos := make([]dto.GrupoSimpleDTO, 0, len(usuario.Grupos))
|
||||
|
||||
grupos := make([]*models_seguridad.Grupo, 0, len(usuario.Grupos))
|
||||
for i := range usuario.Grupos {
|
||||
grupoCompleto, err := r.ObtenerRepositorios(c).Grupo.ObtenerPorIDConRelaciones(usuario.Grupos[i].ID, true)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
g := dto_builders.NewGrupoSimpleBuilder(grupoCompleto).Build()
|
||||
g.ID = grupoCompleto.ID
|
||||
grupos = append(grupos, g)
|
||||
grupos = append(grupos, grupoCompleto)
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, dto.GruposYPermisosResponse{
|
||||
Email: usuario.Email,
|
||||
Groups: grupos,
|
||||
})
|
||||
respuesta, err := dto_directors.NewGrupoSimpleDirector().Listar(grupos)
|
||||
if err != nil {
|
||||
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 (
|
||||
"net/http"
|
||||
dto_builders "repuestera_back/dto/Builders"
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
dto "repuestera_back/dto/Logs"
|
||||
"repuestera_back/models/logs"
|
||||
r "repuestera_back/repositorios"
|
||||
@@ -30,7 +30,11 @@ func BusquedaLogs(c *gin.Context) {
|
||||
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)
|
||||
if err != nil {
|
||||
|
||||
@@ -2,6 +2,7 @@ package logs
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
r "repuestera_back/repositorios"
|
||||
"strconv"
|
||||
|
||||
@@ -23,5 +24,11 @@ func ObtenerLog(c *gin.Context) {
|
||||
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 (
|
||||
"net/http"
|
||||
dto_builders "repuestera_back/dto/Builders"
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
r "repuestera_back/repositorios"
|
||||
"strconv"
|
||||
|
||||
@@ -32,7 +32,11 @@ func ObtenerLogs(c *gin.Context) {
|
||||
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{
|
||||
"logs": logsdto,
|
||||
|
||||
@@ -2,9 +2,11 @@ package permiso
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
models_seguridad "repuestera_back/models/seguridad"
|
||||
r "repuestera_back/repositorios"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
@@ -25,6 +27,16 @@ func ActualizarPermiso(c *gin.Context) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
r.ObtenerRepositorios(c).Permiso.Actualizar(permiso, input)
|
||||
c.JSON(http.StatusOK, permiso)
|
||||
if err := r.ObtenerRepositorios(c).Permiso.Actualizar(permiso, input); err != nil {
|
||||
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 (
|
||||
"net/http"
|
||||
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
models_seguridad "repuestera_back/models/seguridad"
|
||||
r "repuestera_back/repositorios"
|
||||
|
||||
@@ -18,5 +20,12 @@ func CrearPermiso(c *gin.Context) {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
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 (
|
||||
"net/http"
|
||||
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
r "repuestera_back/repositorios"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -13,5 +15,12 @@ func ObtenerPermisos(c *gin.Context) {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
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
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
r "repuestera_back/repositorios"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
"net/http"
|
||||
"repuestera_back/dto"
|
||||
r "repuestera_back/repositorios"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
func ObtenerPermisosUsuario(c *gin.Context) {
|
||||
@@ -26,25 +28,11 @@ func ObtenerPermisosUsuario(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
permisoMap := make(map[string]bool)
|
||||
var permisos []string
|
||||
|
||||
for _, grupo := range usuario.Grupos {
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
respuesta, err := dto_directors.NewPermisosUsuarioDirector().DesdeGrupos(usuario.Grupos)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, dto.PermisosUsuarioResponse{Permisos: permisos})
|
||||
c.JSON(http.StatusOK, respuesta)
|
||||
}
|
||||
@@ -2,7 +2,7 @@ package repuestos
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
dto_builders "repuestera_back/dto/Builders"
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
dto "repuestera_back/dto/Repuestos"
|
||||
r "repuestera_back/repositorios"
|
||||
"strconv"
|
||||
@@ -35,10 +35,11 @@ func ActualizarRepuesto(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
repuesto := dto_builders.NewActualizarRepuestoBuilder().
|
||||
ConDto(data).
|
||||
ConMarca(marca.ID).
|
||||
Build()
|
||||
repuesto, err := dto_directors.NewRepuestoDirector().Actualizar(data, marca.ID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
entity, err := r.ObtenerRepositorios(c).Repuesto.ObtenerPorID(uint(id))
|
||||
if err != nil {
|
||||
@@ -47,10 +48,10 @@ func ActualizarRepuesto(c *gin.Context) {
|
||||
}
|
||||
|
||||
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()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, repuesto)
|
||||
c.JSON(http.StatusOK, repuesto)
|
||||
}
|
||||
@@ -2,7 +2,7 @@ package repuestos
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
dto_builders "repuestera_back/dto/Builders"
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
dto "repuestera_back/dto/Repuestos"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -28,13 +28,14 @@ func CrearRepuesto(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
repuesto := dto_builders.NewRepuestoBuilder().
|
||||
ConDto(data).
|
||||
ConMarca(marca.ID).
|
||||
Build()
|
||||
repuesto, err := dto_directors.NewRepuestoDirector().Crear(data, marca.ID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
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()})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -6,8 +6,8 @@ import (
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
dto "repuestera_back/dto/Stock"
|
||||
"repuestera_back/models"
|
||||
r "repuestera_back/repositorios"
|
||||
)
|
||||
|
||||
@@ -32,16 +32,23 @@ func ObtenerStock(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if q.Estado != "" {
|
||||
filtrado := make([]models.Stock, 0, len(stocks))
|
||||
for i := range stocks {
|
||||
estado := string(estadoDe(&stocks[i], &stocks[i].Repuesto))
|
||||
if strings.EqualFold(estado, q.Estado) {
|
||||
filtrado = append(filtrado, stocks[i])
|
||||
}
|
||||
}
|
||||
stocks = filtrado
|
||||
director := dto_directors.NewStockDirector()
|
||||
|
||||
respuesta, err := director.Listar(stocks)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
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"
|
||||
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
r "repuestera_back/repositorios"
|
||||
)
|
||||
|
||||
@@ -20,5 +21,12 @@ func ObtenerStockPorID(c *gin.Context) {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "stock no encontrado"})
|
||||
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"
|
||||
"gorm.io/gorm"
|
||||
|
||||
dto_builders "repuestera_back/dto/Builders"
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
"repuestera_back/models"
|
||||
"repuestera_back/models/contabilidad"
|
||||
models_logs "repuestera_back/models/logs"
|
||||
@@ -44,15 +44,6 @@ var (
|
||||
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 {
|
||||
switch {
|
||||
case errors.Is(err, gorm.ErrRecordNotFound):
|
||||
@@ -107,20 +98,6 @@ func disponible(stock *models.Stock) float64 {
|
||||
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.
|
||||
func validarCantidad(cantidad float64) error {
|
||||
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
|
||||
// operación de negocio ya confirmada no se revierte.
|
||||
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 {
|
||||
applog.Printf("stock: no se pudo construir el log de %s: %v", accion, err)
|
||||
return
|
||||
|
||||
@@ -6,6 +6,8 @@ import (
|
||||
r "repuestera_back/repositorios"
|
||||
"strconv"
|
||||
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
@@ -39,7 +41,16 @@ func ActualizarUsuario(c *gin.Context) {
|
||||
usuario.Email = usuarioReq.Email
|
||||
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"
|
||||
r "repuestera_back/repositorios"
|
||||
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
@@ -20,5 +22,11 @@ func CrearUsuario(c *gin.Context) {
|
||||
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 (
|
||||
"net/http"
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
r "repuestera_back/repositorios"
|
||||
"strconv"
|
||||
|
||||
@@ -21,5 +22,11 @@ func ObtenerUsuario(c *gin.Context) {
|
||||
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 (
|
||||
"net/http"
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
r "repuestera_back/repositorios"
|
||||
"strconv"
|
||||
|
||||
@@ -26,8 +27,14 @@ func ObtenerUsuarios(c *gin.Context) {
|
||||
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{
|
||||
"usuarios": usuarios,
|
||||
"usuarios": respuesta,
|
||||
"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
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
dto "repuestera_back/dto/Repuestos"
|
||||
"repuestera_back/models"
|
||||
)
|
||||
@@ -8,40 +10,67 @@ import (
|
||||
type ActualizarRepuestoBuilder struct {
|
||||
dto *dto.ActualizarRepuestoDto
|
||||
marcaID uint
|
||||
err error
|
||||
}
|
||||
|
||||
var _ IBuilder[models.Repuesto] = (*ActualizarRepuestoBuilder)(nil)
|
||||
|
||||
func NewActualizarRepuestoBuilder() *ActualizarRepuestoBuilder {
|
||||
return &ActualizarRepuestoBuilder{}
|
||||
}
|
||||
|
||||
func (b *ActualizarRepuestoBuilder) ConDto(dto dto.ActualizarRepuestoDto) *ActualizarRepuestoBuilder {
|
||||
b.dto = &dto
|
||||
func (b *ActualizarRepuestoBuilder) ConDto(data dto.ActualizarRepuestoDto) *ActualizarRepuestoBuilder {
|
||||
b.dto = &data
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *ActualizarRepuestoBuilder) ConMarca(marcaID uint) *ActualizarRepuestoBuilder {
|
||||
if marcaID == 0 {
|
||||
AcumularError(&b.err, "la marca es obligatoria")
|
||||
return b
|
||||
}
|
||||
b.marcaID = marcaID
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *ActualizarRepuestoBuilder) Build() models.Repuesto {
|
||||
aliases := b.dto.Aliases
|
||||
if aliases == nil {
|
||||
aliases = []string{}
|
||||
func (b *ActualizarRepuestoBuilder) Build() (*models.Repuesto, error) {
|
||||
if b.dto == nil {
|
||||
return nil, errors.New("faltan los datos del repuesto")
|
||||
}
|
||||
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,
|
||||
Descripcion: b.dto.Descripcion,
|
||||
Precio: b.dto.Precio,
|
||||
StockMinimo: int64(b.dto.StockMinimo),
|
||||
MarcaID: b.marcaID,
|
||||
Aliases: aliases,
|
||||
Aliases: ListaNoNil(b.dto.Aliases),
|
||||
}
|
||||
|
||||
if b.dto.ID != nil {
|
||||
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
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
dto "repuestera_back/dto/Repuestos"
|
||||
"repuestera_back/models"
|
||||
)
|
||||
|
||||
type RepuestoBuilder struct {
|
||||
type CrearRepuestoBuilder struct {
|
||||
dto *dto.CrearRepuestoDto
|
||||
marcaID uint
|
||||
err error
|
||||
}
|
||||
|
||||
func NewRepuestoBuilder() *RepuestoBuilder {
|
||||
return &RepuestoBuilder{}
|
||||
var _ IBuilder[models.Repuesto] = (*CrearRepuestoBuilder)(nil)
|
||||
|
||||
func NewCrearRepuestoBuilder() *CrearRepuestoBuilder {
|
||||
return &CrearRepuestoBuilder{}
|
||||
}
|
||||
|
||||
func (b *RepuestoBuilder) ConDto(dto dto.CrearRepuestoDto) *RepuestoBuilder {
|
||||
b.dto = &dto
|
||||
func (b *CrearRepuestoBuilder) ConDto(data dto.CrearRepuestoDto) *CrearRepuestoBuilder {
|
||||
b.dto = &data
|
||||
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
|
||||
return b
|
||||
}
|
||||
func (b *RepuestoBuilder) Build() models.Repuesto {
|
||||
aliases := b.dto.Aliases
|
||||
|
||||
if aliases == nil {
|
||||
aliases = []string{}
|
||||
func (b *CrearRepuestoBuilder) Build() (*models.Repuesto, error) {
|
||||
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,
|
||||
Descripcion: b.dto.Descripcion,
|
||||
Precio: b.dto.Precio,
|
||||
StockMinimo: int64(b.dto.StockMinimo),
|
||||
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
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"sort"
|
||||
|
||||
"repuestera_back/dto"
|
||||
models_seguridad "repuestera_back/models/seguridad"
|
||||
)
|
||||
|
||||
type GrupoSimpleBuilder struct {
|
||||
grupo *models_seguridad.Grupo
|
||||
err error
|
||||
}
|
||||
|
||||
var _ IBuilder[dto.GrupoSimpleDTO] = (*GrupoSimpleBuilder)(nil)
|
||||
|
||||
func NewGrupoSimpleBuilder(grupo *models_seguridad.Grupo) *GrupoSimpleBuilder {
|
||||
return &GrupoSimpleBuilder{
|
||||
grupo: grupo,
|
||||
}
|
||||
builder := &GrupoSimpleBuilder{}
|
||||
builder.ConGrupo(grupo)
|
||||
return builder
|
||||
}
|
||||
|
||||
func (b *GrupoSimpleBuilder) Build() dto.GrupoSimpleDTO {
|
||||
permisosMap := make(map[uint]models_seguridad.Permiso)
|
||||
func (b *GrupoSimpleBuilder) ConGrupo(grupo *models_seguridad.Grupo) *GrupoSimpleBuilder {
|
||||
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))
|
||||
|
||||
for _, permiso := range permisosMap {
|
||||
permisos = append(permisos, dto.PermisoSimpleDTO{
|
||||
ID: permiso.ID,
|
||||
Nombre: permiso.Nombre,
|
||||
Alias: permiso.Alias,
|
||||
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,
|
||||
Descripcion: b.grupo.Descripcion,
|
||||
Imagen: b.grupo.Imagen,
|
||||
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"`
|
||||
Empresas []EmpresaResumen `json:"empresas"`
|
||||
EmpresaRol string `json:"empresa_rol"`
|
||||
EsPlataformaAdmin bool `json:"es_plataforma_admin"`
|
||||
Usuario UsuarioResumen `json:"usuario"`
|
||||
DebeCambiarPassword bool `json:"debe_cambiar_password"`
|
||||
}
|
||||
@@ -55,7 +54,6 @@ type MeResponse struct {
|
||||
Empresa *EmpresaResumen `json:"empresa,omitempty"`
|
||||
Empresas []EmpresaResumen `json:"empresas"`
|
||||
EmpresaRol string `json:"empresa_rol"`
|
||||
EsPlataformaAdmin bool `json:"es_plataforma_admin"`
|
||||
Activo bool `json:"activo"`
|
||||
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 {
|
||||
ID uint `json:"id"`
|
||||
Nombre string `json:"nombre"`
|
||||
Alias string `json:"alias"`
|
||||
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"
|
||||
ClaimEmpresaID = "empresa_id"
|
||||
ClaimEmpresaRol = "empresa_rol"
|
||||
ClaimPlataformaAdmin = "es_plataforma_admin"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -58,7 +57,7 @@ func GetSecret() ([]byte, error) {
|
||||
|
||||
// GenerarToken firma un token HS256 con los datos del usuario, su empresa
|
||||
// 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()
|
||||
if err != nil {
|
||||
return "", err
|
||||
@@ -70,7 +69,6 @@ func GenerarToken(userID uint, empresaID uint, empresaRol string, esPlataformaAd
|
||||
"name": name,
|
||||
ClaimEmpresaID: empresaID,
|
||||
ClaimEmpresaRol: empresaRol,
|
||||
ClaimPlataformaAdmin: esPlataformaAdmin,
|
||||
ClaimPermissions: permissions,
|
||||
ClaimType: tokenType,
|
||||
"exp": time.Now().Add(duration).Unix(),
|
||||
|
||||
Reference in new issue
Block a user