Private
Public Access
feat: hecha parte del back para crear clientes y correjida alta de
miembros Signed-off-by: fede <federico.nicolas.polidoro@gmail.com>
This commit is contained in:
1 parent
37f1741a77
commit
405eaca25c
20 files changed
+417
-112
No files matched your search
@@ -0,0 +1,62 @@
|
||||
package cliente
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"repuestera_back/models"
|
||||
r "repuestera_back/repositorios"
|
||||
|
||||
dto "repuestera_back/dto/Clientes"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func ActualizarCliente(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID invalido"})
|
||||
return
|
||||
}
|
||||
if id < 1 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID no puede ser menor que 1"})
|
||||
return
|
||||
}
|
||||
|
||||
repo := r.ObtenerRepositorios(c).Cliente
|
||||
cliente, err := repo.ObtenerPorID(uint(id))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Cliente no encontrado"})
|
||||
return
|
||||
}
|
||||
|
||||
var data dto.CrearClienteDto
|
||||
if err := c.ShouldBindJSON(&data); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if existing, _ := repo.BuscarPorCuit(data.Cuit); existing != nil && existing.ID != cliente.ID {
|
||||
c.JSON(http.StatusConflict, gin.H{"error": "ya existe un cliente con ese CUIT"})
|
||||
return
|
||||
}
|
||||
|
||||
input := models.Cliente{
|
||||
Nombre: data.Nombre,
|
||||
Cuit: data.Cuit,
|
||||
Email: data.Email,
|
||||
}
|
||||
uid := c.GetUint("userID")
|
||||
if err := repo.Actualizar(cliente, input, uid); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
actualizado, err := repo.ObtenerPorID(uint(id))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, cliente)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, actualizado)
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package cliente
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
r "repuestera_back/repositorios"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// AltaCliente reactiva un cliente dado de baja lógicamente.
|
||||
func AltaCliente(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID invalido"})
|
||||
return
|
||||
}
|
||||
if id < 1 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID no puede ser menor que 1"})
|
||||
return
|
||||
}
|
||||
|
||||
repo := r.ObtenerRepositorios(c).Cliente
|
||||
cliente, err := repo.ObtenerPorID(uint(id))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Cliente no encontrado"})
|
||||
return
|
||||
}
|
||||
|
||||
if !cliente.DeletedAt.Valid {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "El cliente no está eliminado"})
|
||||
return
|
||||
}
|
||||
|
||||
cliente.DeletedAt = gorm.DeletedAt{}
|
||||
uid := c.GetUint("userID")
|
||||
if err := repo.Alta(cliente, *cliente, uid); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.Status(http.StatusOK)
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package cliente
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
|
||||
dto "repuestera_back/dto/Clientes"
|
||||
"repuestera_back/models"
|
||||
r "repuestera_back/repositorios"
|
||||
)
|
||||
|
||||
func CrearCliente(c *gin.Context) {
|
||||
var data dto.CrearClienteDto
|
||||
if err := c.ShouldBindJSON(&data); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
repo := r.ObtenerRepositorios(c).Cliente
|
||||
if _, err := repo.BuscarPorCuit(data.Cuit); err == nil {
|
||||
c.JSON(http.StatusConflict, gin.H{"error": "ya existe un cliente con ese CUIT"})
|
||||
return
|
||||
} else if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
cliente := models.Cliente{
|
||||
Nombre: data.Nombre,
|
||||
Cuit: data.Cuit,
|
||||
Email: data.Email,
|
||||
}
|
||||
if err := repo.Crear(cliente, c.GetUint("userID")); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
creado, err := repo.BuscarPorCuit(data.Cuit)
|
||||
if err != nil {
|
||||
c.Status(http.StatusCreated)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, creado)
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package cliente
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
r "repuestera_back/repositorios"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func EliminarCliente(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID invalido"})
|
||||
return
|
||||
}
|
||||
if id < 1 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID no puede ser menor que 1"})
|
||||
return
|
||||
}
|
||||
|
||||
uid := c.GetUint("userID")
|
||||
if err := r.ObtenerRepositorios(c).Cliente.Baja(uint(id), uid); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusOK)
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package empresa
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
models_seguridad "repuestera_back/models/seguridad"
|
||||
r "repuestera_back/repositorios"
|
||||
"repuestera_back/utils"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func AltaMiembro(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.MiembrosIncluyendoEliminados(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.DeletedAt.Valid {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "El miembro ya está activo"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := repo.Empresa.RestaurarMiembro(empresaID, uint(usuarioID)); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
miembro.DeletedAt = gorm.DeletedAt{}
|
||||
miembro.Activo = true
|
||||
|
||||
c.JSON(http.StatusOK, respuestaMiembro(*miembro))
|
||||
}
|
||||
@@ -21,6 +21,25 @@ 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"))
|
||||
@@ -34,17 +53,7 @@ func ObtenerMiembros(c *gin.Context) {
|
||||
|
||||
respuesta := make([]dto.MiembroResponse, 0, len(miembros))
|
||||
for _, miembro := range miembros {
|
||||
respuesta = append(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,
|
||||
CreatedAt: miembro.Usuario.CreatedAt,
|
||||
UpdatedAt: miembro.Usuario.UpdatedAt,
|
||||
})
|
||||
respuesta = append(respuesta, respuestaMiembro(miembro))
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
@@ -68,15 +77,7 @@ func ObtenerMiembro(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, 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,
|
||||
})
|
||||
c.JSON(http.StatusOK, respuestaMiembro(*miembro))
|
||||
}
|
||||
|
||||
func CrearMiembro(c *gin.Context) {
|
||||
@@ -167,17 +168,11 @@ func CrearMiembro(c *gin.Context) {
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, gin.H{
|
||||
"usuario": dto.MiembroResponse{
|
||||
ID: usuario.ID,
|
||||
Email: usuario.Email,
|
||||
Name: usuario.Name,
|
||||
Activo: usuario.Activo,
|
||||
DebeCambiarPassword: usuario.DebeCambiarPassword,
|
||||
Rol: string(rol),
|
||||
MembresiaActiva: true,
|
||||
CreatedAt: usuario.CreatedAt,
|
||||
UpdatedAt: usuario.UpdatedAt,
|
||||
},
|
||||
"usuario": respuestaMiembro(models_seguridad.EmpresaUsuario{
|
||||
Usuario: *usuario,
|
||||
Rol: rol,
|
||||
Activo: true,
|
||||
}),
|
||||
"password_temporal": passwordTemporal,
|
||||
"usuario_existente": !creado,
|
||||
})
|
||||
@@ -280,17 +275,12 @@ func ActualizarMiembro(c *gin.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, dto.MiembroResponse{
|
||||
ID: usuario.ID,
|
||||
Email: usuario.Email,
|
||||
Name: usuario.Name,
|
||||
Activo: usuario.Activo,
|
||||
DebeCambiarPassword: usuario.DebeCambiarPassword,
|
||||
Rol: string(miembro.Rol),
|
||||
MembresiaActiva: miembro.Activo,
|
||||
CreatedAt: usuario.CreatedAt,
|
||||
UpdatedAt: usuario.UpdatedAt,
|
||||
})
|
||||
miembro.Usuario = *usuario
|
||||
if req.Activo != nil {
|
||||
miembro.Activo = *req.Activo
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, respuestaMiembro(*miembro))
|
||||
}
|
||||
|
||||
func EliminarMiembro(c *gin.Context) {
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
package dto
|
||||
|
||||
type CrearClienteDto struct {
|
||||
Nombre string `json:"nombre" binding:"required,max=40"`
|
||||
Cuit string `json:"cuit" binding:"required,max=11"`
|
||||
Email string `json:"email" binding:"omitempty,email,max=80"`
|
||||
}
|
||||
+10
-9
@@ -73,13 +73,14 @@ type InvitacionInfo struct {
|
||||
}
|
||||
|
||||
type MiembroResponse struct {
|
||||
ID uint `json:"id"`
|
||||
Email string `json:"email"`
|
||||
Name string `json:"name"`
|
||||
Activo bool `json:"activo"`
|
||||
DebeCambiarPassword bool `json:"debe_cambiar_password"`
|
||||
Rol string `json:"rol"`
|
||||
MembresiaActiva bool `json:"membresia_activa"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
ID uint `json:"id"`
|
||||
Email string `json:"email"`
|
||||
Name string `json:"name"`
|
||||
Activo bool `json:"activo"`
|
||||
DebeCambiarPassword bool `json:"debe_cambiar_password"`
|
||||
Rol string `json:"rol"`
|
||||
MembresiaActiva bool `json:"membresia_activa"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
DeletedAt *time.Time `json:"deleted_at"`
|
||||
}
|
||||
@@ -1,17 +1,15 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type Cliente struct {
|
||||
gorm.Model
|
||||
EmpresaID uint `gorm:"not null;default:1;index;uniqueIndex:uq_cliente_empresa_cuit,priority:1" json:"empresaId"`
|
||||
Nombre string `gorm:"type:varchar(40)" json:"nombre"`
|
||||
Cuit string `gorm:"type:varchar(11);not null;uniqueIndex:uq_cliente_empresa_cuit,priority:2" json:"cuit"`
|
||||
Email sql.NullString `gorm:"type:varchar(80)" json:"email"`
|
||||
Facturas []Factura `gorm:"foreignKey:ClienteID" json:"facturas,omitempty"`
|
||||
Recibos []Recibo `gorm:"foreignKey:ClienteID" json:"recibos,omitempty"`
|
||||
EmpresaID uint `gorm:"not null;default:1;index;uniqueIndex:uq_cliente_empresa_cuit,priority:1" json:"empresaId"`
|
||||
Nombre string `gorm:"type:varchar(40)" json:"nombre"`
|
||||
Cuit string `gorm:"type:varchar(11);not null;uniqueIndex:uq_cliente_empresa_cuit,priority:2" json:"cuit"`
|
||||
Email string `gorm:"type:varchar(80)" json:"email,omitempty"`
|
||||
Facturas []Factura `gorm:"foreignKey:ClienteID" json:"facturas,omitempty"`
|
||||
Recibos []Recibo `gorm:"foreignKey:ClienteID" json:"recibos,omitempty"`
|
||||
}
|
||||
@@ -46,12 +46,13 @@ func (r RolEmpresa) EsAdministrador() bool {
|
||||
|
||||
// EmpresaUsuario es la membresía de un usuario global dentro de una empresa.
|
||||
type EmpresaUsuario struct {
|
||||
EmpresaID uint `gorm:"primaryKey" json:"empresa_id"`
|
||||
UsuarioID uint `gorm:"primaryKey" json:"usuario_id"`
|
||||
Rol RolEmpresa `gorm:"type:varchar(20);not null;default:'MEMBER'" json:"rol"`
|
||||
Activo bool `gorm:"not null;default:true" json:"activo"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
EmpresaID uint `gorm:"primaryKey" json:"empresa_id"`
|
||||
UsuarioID uint `gorm:"primaryKey" json:"usuario_id"`
|
||||
Rol RolEmpresa `gorm:"type:varchar(20);not null;default:'MEMBER'" json:"rol"`
|
||||
Activo bool `gorm:"not null;default:true" json:"activo"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
|
||||
|
||||
Empresa Empresa `gorm:"foreignKey:EmpresaID" json:"empresa,omitempty"`
|
||||
Usuario Usuario `gorm:"foreignKey:UsuarioID" json:"usuario,omitempty"`
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
type RepositorioCliente interface {
|
||||
IRepositorio[models.Cliente]
|
||||
Listar(q string) ([]models.Cliente, error)
|
||||
BuscarPorCuit(cuit string) (*models.Cliente, error)
|
||||
}
|
||||
|
||||
type repositorioCliente struct {
|
||||
@@ -27,7 +28,7 @@ func NuevoRepositorioCliente(db *gorm.DB, empresaID uint) RepositorioCliente {
|
||||
|
||||
func (r *repositorioCliente) Listar(q string) ([]models.Cliente, error) {
|
||||
var clientes []models.Cliente
|
||||
query := r.db.Order("nombre ASC")
|
||||
query := r.db.Unscoped().Order("nombre ASC")
|
||||
if q != "" {
|
||||
like := "%" + q + "%"
|
||||
query = query.Where("nombre LIKE ? OR cuit LIKE ?", like, like)
|
||||
@@ -37,3 +38,13 @@ func (r *repositorioCliente) Listar(q string) ([]models.Cliente, error) {
|
||||
}
|
||||
return clientes, nil
|
||||
}
|
||||
|
||||
// BuscarPorCuit incluye clientes dados de baja porque el CUIT es único por
|
||||
// empresa también para los registros eliminados lógicamente.
|
||||
func (r *repositorioCliente) BuscarPorCuit(cuit string) (*models.Cliente, error) {
|
||||
var cliente models.Cliente
|
||||
if err := r.db.Unscoped().Where("cuit = ?", cuit).First(&cliente).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &cliente, nil
|
||||
}
|
||||
@@ -26,6 +26,8 @@ type RepositorioEmpresa interface {
|
||||
Desactivar(id uint) error
|
||||
|
||||
Membresia(empresaID, usuarioID uint) (*models_seguridad.EmpresaUsuario, error)
|
||||
MiembrosIncluyendoEliminados(empresaID, usuarioID uint) (*models_seguridad.EmpresaUsuario, error)
|
||||
RestaurarMiembro(empresaID, usuarioID uint) error
|
||||
ListarMiembros(empresaID uint, pagina, tamano int) ([]models_seguridad.EmpresaUsuario, int64, error)
|
||||
AgregarMiembro(empresaID, usuarioID uint, rol models_seguridad.RolEmpresa, grupoID uint) error
|
||||
ActualizarRolMiembro(empresaID, usuarioID uint, rol models_seguridad.RolEmpresa) error
|
||||
@@ -80,7 +82,7 @@ func (r *repositorioEmpresa) ListarDeUsuario(usuarioID uint) ([]models_seguridad
|
||||
var empresas []models_seguridad.Empresa
|
||||
err := r.db.Model(&models_seguridad.Empresa{}).
|
||||
Joins("JOIN empresa_usuarios eu ON eu.empresa_id = empresas.id").
|
||||
Where("eu.usuario_id = ? AND eu.activo = ?", usuarioID, true).
|
||||
Where("eu.usuario_id = ? AND eu.activo = ? AND eu.deleted_at IS NULL", usuarioID, true).
|
||||
Where("empresas.activa = ? AND empresas.deleted_at IS NULL", true).
|
||||
Order("empresas.nombre ASC").
|
||||
Find(&empresas).Error
|
||||
@@ -155,6 +157,22 @@ func (r *repositorioEmpresa) Membresia(empresaID, usuarioID uint) (*models_segur
|
||||
return &membresia, nil
|
||||
}
|
||||
|
||||
func (r *repositorioEmpresa) MiembrosIncluyendoEliminados(empresaID, usuarioID uint) (*models_seguridad.EmpresaUsuario, error) {
|
||||
var membresia models_seguridad.EmpresaUsuario
|
||||
if err := r.db.Unscoped().Preload("Usuario").
|
||||
Where("empresa_id = ? AND usuario_id = ?", empresaID, usuarioID).
|
||||
First(&membresia).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &membresia, nil
|
||||
}
|
||||
|
||||
func (r *repositorioEmpresa) RestaurarMiembro(empresaID, usuarioID uint) error {
|
||||
return r.db.Unscoped().Model(&models_seguridad.EmpresaUsuario{}).
|
||||
Where("empresa_id = ? AND usuario_id = ?", empresaID, usuarioID).
|
||||
Updates(map[string]any{"activo": true, "deleted_at": nil}).Error
|
||||
}
|
||||
|
||||
func (r *repositorioEmpresa) ListarMiembros(empresaID uint, pagina, tamano int) ([]models_seguridad.EmpresaUsuario, int64, error) {
|
||||
if pagina < 0 {
|
||||
pagina = 0
|
||||
@@ -164,7 +182,7 @@ func (r *repositorioEmpresa) ListarMiembros(empresaID uint, pagina, tamano int)
|
||||
}
|
||||
|
||||
var total int64
|
||||
query := r.db.Model(&models_seguridad.EmpresaUsuario{}).Where("empresa_id = ?", empresaID)
|
||||
query := r.db.Unscoped().Model(&models_seguridad.EmpresaUsuario{}).Where("empresa_id = ?", empresaID)
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
@@ -191,7 +209,7 @@ func (r *repositorioEmpresa) AgregarMiembro(empresaID, usuarioID uint, rol model
|
||||
|
||||
return r.db.Transaction(func(tx *gorm.DB) error {
|
||||
var membresia models_seguridad.EmpresaUsuario
|
||||
err := tx.Where("empresa_id = ? AND usuario_id = ?", empresaID, usuarioID).First(&membresia).Error
|
||||
err := tx.Unscoped().Where("empresa_id = ? AND usuario_id = ?", empresaID, usuarioID).First(&membresia).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
membresia = models_seguridad.EmpresaUsuario{
|
||||
EmpresaID: empresaID,
|
||||
@@ -204,7 +222,7 @@ func (r *repositorioEmpresa) AgregarMiembro(empresaID, usuarioID uint, rol model
|
||||
}
|
||||
} else if err != nil {
|
||||
return err
|
||||
} else if err := tx.Model(&membresia).Updates(map[string]any{"rol": rol, "activo": true}).Error; err != nil {
|
||||
} else if err := tx.Unscoped().Model(&membresia).Updates(map[string]any{"rol": rol, "activo": true, "deleted_at": nil}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
|
||||
@@ -90,7 +90,7 @@ func (r *repositorioUsuario) ObtenerTodosPaginado(pagina, tamaño int) ([]models
|
||||
|
||||
query := r.db.Model(&models_seguridad.Usuario{}).
|
||||
Joins("JOIN empresa_usuarios eu ON eu.usuario_id = usuarios.id").
|
||||
Where("eu.empresa_id = ? AND eu.activo = ?", r.empresaID, true)
|
||||
Where("eu.empresa_id = ? AND eu.activo = ? AND eu.deleted_at IS NULL", r.empresaID, true)
|
||||
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
@@ -149,7 +149,7 @@ func (r *repositorioUsuario) ObtenerEmpresasDeUsuario(usuarioID uint) ([]models_
|
||||
var empresas []models_seguridad.Empresa
|
||||
err := r.db.Model(&models_seguridad.Empresa{}).
|
||||
Joins("JOIN empresa_usuarios eu ON eu.empresa_id = empresas.id").
|
||||
Where("eu.usuario_id = ? AND eu.activo = ?", usuarioID, true).
|
||||
Where("eu.usuario_id = ? AND eu.activo = ? AND eu.deleted_at IS NULL", usuarioID, true).
|
||||
Find(&empresas).Error
|
||||
return empresas, err
|
||||
}
|
||||
|
||||
@@ -12,5 +12,9 @@ func ClienteRoute(r *gin.Engine) {
|
||||
grupo.Use(middleware.AuthMiddleware(12))
|
||||
{
|
||||
grupo.GET("/", cliente.ObtenerClientes)
|
||||
grupo.POST("/", cliente.CrearCliente)
|
||||
grupo.PUT("/:id", cliente.ActualizarCliente)
|
||||
grupo.DELETE("/:id", cliente.EliminarCliente)
|
||||
grupo.PATCH("/:id/alta", cliente.AltaCliente)
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,7 @@ func EmpresaRoute(r *gin.Engine) {
|
||||
miembros.POST("", empresa.CrearMiembro)
|
||||
miembros.PUT("/:id", empresa.ActualizarMiembro)
|
||||
miembros.DELETE("/:id", empresa.EliminarMiembro)
|
||||
miembros.PATCH("/:id/alta", empresa.AltaMiembro)
|
||||
}
|
||||
|
||||
invitaciones := r.Group("/empresa/invitaciones")
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
HeaderUtilities
|
||||
} from 'carbon-components-svelte';
|
||||
import UserMenu from './UserMenu.svelte';
|
||||
import CommandPalette from './CommandPalette.svelte';
|
||||
import type { GruposYPermisosResponse, Usuario } from '../../types';
|
||||
import { getCurrentUser } from '$lib/hooks/user';
|
||||
import { ObtenerGruposDeUsuario } from '$lib/hooks/gruposPermisosUsuario';
|
||||
@@ -54,8 +55,9 @@
|
||||
{/await}
|
||||
{/if}
|
||||
</HeaderNav>
|
||||
<CommandPalette {grupos} habilitado={!!usuario} />
|
||||
<HeaderUtilities>
|
||||
<div class="flex h-full items-center">
|
||||
<div class="flex h-full items-center gap-1">
|
||||
<UserMenu />
|
||||
</div>
|
||||
</HeaderUtilities>
|
||||
|
||||
@@ -80,6 +80,10 @@ export async function eliminarMiembro(id: number): Promise<void> {
|
||||
await apiFetch(`/empresa/miembros/${id}`, { method: 'DELETE' });
|
||||
}
|
||||
|
||||
export async function altaMiembro(id: number): Promise<Miembro> {
|
||||
return apiFetch<Miembro>(`/empresa/miembros/${id}/alta`, { method: 'PATCH' });
|
||||
}
|
||||
|
||||
export async function resetearPasswordMiembro(id: number, newPassword: string): Promise<void> {
|
||||
await apiFetch('/auth/cambiar-contraseña', {
|
||||
method: 'POST',
|
||||
@@ -87,7 +91,10 @@ export async function resetearPasswordMiembro(id: number, newPassword: string):
|
||||
});
|
||||
}
|
||||
|
||||
export async function cambiarPasswordPropia(oldPassword: string, newPassword: string): Promise<void> {
|
||||
export async function cambiarPasswordPropia(
|
||||
oldPassword: string,
|
||||
newPassword: string
|
||||
): Promise<void> {
|
||||
await apiFetch('/auth/cambiar-contraseña', {
|
||||
method: 'POST',
|
||||
body: { old_password: oldPassword, new_password: newPassword }
|
||||
|
||||
@@ -13,11 +13,12 @@
|
||||
TableRow,
|
||||
Tag
|
||||
} from 'carbon-components-svelte';
|
||||
import { Add, Keychain, Network_4, Pen, TrashCan } from 'carbon-icons-svelte';
|
||||
import { Add, ArrowUp, Keychain, Network_4, Pen, TrashCan } from 'carbon-icons-svelte';
|
||||
import CambiarContraseñaForm from './CambiarContraseñaForm.svelte';
|
||||
import CrearUsuarioForm from './CrearUsuarioForm.svelte';
|
||||
import EditarUsuarioForm from './EditarUsuarioForm.svelte';
|
||||
import EliminarUsuarioForm from './EliminarUsuarioForm.svelte';
|
||||
import AltaUsuarioForm from './AltaUsuarioForm.svelte';
|
||||
import type { Grupo, Miembro } from '../../types.js';
|
||||
import { obtenerGruposDeUsuario } from '$lib/hooks/obtenerGruposDeUsuario.js';
|
||||
import QuitarGrupo from './QuitarGrupo.svelte';
|
||||
@@ -33,6 +34,7 @@
|
||||
let showCrearModal = $state(false);
|
||||
let showEditarModal = $state(false);
|
||||
let showEliminarModal = $state(false);
|
||||
let showAltaModal = $state(false);
|
||||
let showCambiarContraseñaModal = $state(false);
|
||||
let showError = $state('');
|
||||
|
||||
@@ -42,6 +44,7 @@
|
||||
|
||||
let usuarioModificar = $state<Partial<Miembro> & { id: number }>({ id: 0 });
|
||||
let usuarioEliminar = $state<Partial<Miembro> & { id: number }>({ id: 0 });
|
||||
let usuarioAlta = $state<Partial<Miembro> & { id: number }>({ id: 0 });
|
||||
let usuarioCambiarContraseña = $state<Partial<Miembro> & { id: number }>({ id: 0 });
|
||||
|
||||
function recargar() {
|
||||
@@ -52,12 +55,14 @@
|
||||
showCrearModal = false;
|
||||
showEditarModal = false;
|
||||
showEliminarModal = false;
|
||||
showAltaModal = false;
|
||||
showCambiarContraseñaModal = false;
|
||||
showQuitar = false;
|
||||
showAsignar = false;
|
||||
|
||||
usuarioModificar = { id: 0 };
|
||||
usuarioEliminar = { id: 0 };
|
||||
usuarioAlta = { id: 0 };
|
||||
usuarioCambiarContraseña = { id: 0 };
|
||||
usugruSeleccionado = { usuario_id: 0, grupo_id: 0 };
|
||||
}
|
||||
@@ -135,47 +140,62 @@
|
||||
</Tag>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Tag type={u.activo && u.membresia_activa ? 'green' : 'red'}>
|
||||
{u.activo && u.membresia_activa ? 'Activo' : 'Inactivo'}
|
||||
</Tag>
|
||||
{#if u.deleted_at}
|
||||
<Tag type="red">Eliminado</Tag>
|
||||
{:else}
|
||||
<Tag type={u.activo && u.membresia_activa ? 'green' : 'red'}>
|
||||
{u.activo && u.membresia_activa ? 'Activo' : 'Inactivo'}
|
||||
</Tag>
|
||||
{/if}
|
||||
</TableCell>
|
||||
<TableCell>{new Date(u.created_at).toLocaleString()}</TableCell>
|
||||
<TableCell>
|
||||
<div class="flex flex-wrap gap-1">
|
||||
<Button
|
||||
onclick={() => {
|
||||
usuarioModificar = u;
|
||||
showEditarModal = true;
|
||||
}}
|
||||
size="small"
|
||||
icon={Pen}>Editar</Button
|
||||
>
|
||||
{#if u.deleted_at}
|
||||
<Button
|
||||
onclick={() => {
|
||||
usuarioAlta = u;
|
||||
showAltaModal = true;
|
||||
}}
|
||||
size="small"
|
||||
icon={ArrowUp}>Alta</Button
|
||||
>
|
||||
{:else}
|
||||
<Button
|
||||
onclick={() => {
|
||||
usuarioModificar = u;
|
||||
showEditarModal = true;
|
||||
}}
|
||||
size="small"
|
||||
icon={Pen}>Editar</Button
|
||||
>
|
||||
|
||||
<Button
|
||||
onclick={() => {
|
||||
usuarioEliminar = u;
|
||||
showEliminarModal = true;
|
||||
}}
|
||||
size="small"
|
||||
kind="danger"
|
||||
icon={TrashCan}>Quitar</Button
|
||||
>
|
||||
<Button
|
||||
onclick={() => {
|
||||
usuarioEliminar = u;
|
||||
showEliminarModal = true;
|
||||
}}
|
||||
size="small"
|
||||
kind="danger"
|
||||
icon={TrashCan}>Quitar</Button
|
||||
>
|
||||
|
||||
<Button
|
||||
onclick={() => {
|
||||
usuarioCambiarContraseña = u;
|
||||
showCambiarContraseñaModal = true;
|
||||
}}
|
||||
size="small"
|
||||
kind="secondary"
|
||||
icon={Keychain}>Contraseña</Button
|
||||
>
|
||||
<Button
|
||||
size="small"
|
||||
kind="secondary"
|
||||
onclick={() => seleccionarUsuarioGrupo(u)}
|
||||
icon={Network_4}>Grupos</Button
|
||||
>
|
||||
<Button
|
||||
onclick={() => {
|
||||
usuarioCambiarContraseña = u;
|
||||
showCambiarContraseñaModal = true;
|
||||
}}
|
||||
size="small"
|
||||
kind="secondary"
|
||||
icon={Keychain}>Contraseña</Button
|
||||
>
|
||||
<Button
|
||||
size="small"
|
||||
kind="secondary"
|
||||
onclick={() => seleccionarUsuarioGrupo(u)}
|
||||
icon={Network_4}>Grupos</Button
|
||||
>
|
||||
{/if}
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
@@ -293,6 +313,12 @@
|
||||
onclose={cerrarModal}
|
||||
oneliminado={recargar}
|
||||
/>
|
||||
<AltaUsuarioForm
|
||||
bind:show={showAltaModal}
|
||||
usuario={usuarioAlta}
|
||||
onclose={cerrarModal}
|
||||
onalta={recargar}
|
||||
/>
|
||||
<CambiarContraseñaForm
|
||||
bind:show={showCambiarContraseñaModal}
|
||||
usuario={usuarioCambiarContraseña}
|
||||
|
||||
@@ -57,8 +57,8 @@
|
||||
<div class="error-msg">{error}</div>
|
||||
{/if}
|
||||
<p>
|
||||
¿Querés quitar a <strong>{usuario.email}</strong> de la empresa? Su usuario global no se elimina,
|
||||
solo pierde acceso.
|
||||
¿Querés quitar a <strong>{usuario.email}</strong> de la empresa? Su usuario global no se
|
||||
elimina, solo pierde acceso. Podés reactivarlo después con la acción <strong>Alta</strong>.
|
||||
</p>
|
||||
</Modal>
|
||||
</form>
|
||||
|
||||
Vendored
+4
@@ -77,6 +77,7 @@ export interface Miembro {
|
||||
membresia_activa: boolean;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
deleted_at: string | null;
|
||||
}
|
||||
|
||||
export interface EmpresaActual {
|
||||
@@ -247,6 +248,9 @@ export interface StockItem {
|
||||
|
||||
export interface Cliente {
|
||||
ID: number;
|
||||
CreatedAt?: string;
|
||||
UpdatedAt?: string;
|
||||
DeletedAt?: string | null;
|
||||
empresaId?: number;
|
||||
nombre: string;
|
||||
cuit?: string;
|
||||
|
||||
Reference in new issue
Block a user