178 lines
6.3 KiB
Go
178 lines
6.3 KiB
Go
package models
|
|
|
|
import (
|
|
"errors"
|
|
|
|
"github.com/sujit-baniya/fiber-boilerplate/app"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// ─── PortalUser ───────────────────────────────────────────────────────────────
|
|
|
|
// PortalUser representa un usuario del portal de clientes (separado del admin).
|
|
// - Rol "cliente": accede a los proyectos de su ClienteID.
|
|
// - Rol "partner": accede a los proyectos de todos sus ClienteIDs via PortalAccesos.
|
|
type PortalUser struct {
|
|
gorm.Model
|
|
Nombre string `json:"nombre" gorm:"column:nombre;not null"`
|
|
Email string `json:"email" gorm:"column:email;uniqueIndex;not null"`
|
|
Password string `json:"-" gorm:"column:password;type:text"`
|
|
ClienteID *uint `json:"cliente_id" gorm:"column:cliente_id;index"` // nil si es partner
|
|
Cliente *Cliente `json:"cliente" gorm:"foreignKey:ClienteID"`
|
|
Rol string `json:"rol" gorm:"column:rol;default:'cliente'"` // cliente|partner
|
|
Activo bool `json:"activo" gorm:"column:activo;default:true"`
|
|
Notas string `json:"notas" gorm:"column:notas;type:text"`
|
|
PortalAccesos []PortalAcceso `json:"portal_accesos" gorm:"foreignKey:PortalUserID"`
|
|
}
|
|
|
|
func (PortalUser) TableName() string { return "portal_users" }
|
|
|
|
// ─── PortalAcceso (partners → multiple clients) ───────────────────────────────
|
|
|
|
type PortalAcceso struct {
|
|
gorm.Model
|
|
PortalUserID uint `json:"portal_user_id" gorm:"column:portal_user_id;index"`
|
|
ClienteID uint `json:"cliente_id" gorm:"column:cliente_id;index"`
|
|
Cliente Cliente `json:"cliente" gorm:"foreignKey:ClienteID"`
|
|
}
|
|
|
|
func (PortalAcceso) TableName() string { return "portal_accesos" }
|
|
|
|
// ─── CRUD ─────────────────────────────────────────────────────────────────────
|
|
|
|
func GetAllPortalUsers(limit, offset int) ([]PortalUser, int64, error) {
|
|
var items []PortalUser
|
|
var total int64
|
|
db := app.Http.Database.DB.Model(&PortalUser{}).Preload("Cliente").Preload("PortalAccesos.Cliente")
|
|
if err := db.Count(&total).Error; err != nil {
|
|
return nil, 0, err
|
|
}
|
|
if err := db.Order("created_at DESC").Limit(limit).Offset(offset).Find(&items).Error; err != nil {
|
|
return nil, 0, err
|
|
}
|
|
return items, total, nil
|
|
}
|
|
|
|
func GetPortalUserByID(id uint) (*PortalUser, error) {
|
|
var item PortalUser
|
|
err := app.Http.Database.DB.Preload("Cliente").Preload("PortalAccesos.Cliente").First(&item, id).Error
|
|
return &item, err
|
|
}
|
|
|
|
func GetPortalUserByEmail(email string) (*PortalUser, error) {
|
|
var item PortalUser
|
|
err := app.Http.Database.DB.Where("email = ?", email).First(&item).Error
|
|
return &item, err
|
|
}
|
|
|
|
func CreatePortalUser(u *PortalUser) error {
|
|
return app.Http.Database.DB.Create(u).Error
|
|
}
|
|
|
|
func UpdatePortalUser(u *PortalUser) error {
|
|
return app.Http.Database.DB.Model(&PortalUser{}).Where("id = ?", u.ID).Updates(map[string]interface{}{
|
|
"nombre": u.Nombre,
|
|
"email": u.Email,
|
|
"cliente_id": u.ClienteID,
|
|
"rol": u.Rol,
|
|
"activo": u.Activo,
|
|
"notas": u.Notas,
|
|
}).Error
|
|
}
|
|
|
|
func UpdatePortalUserPassword(id uint, hashedPassword string) error {
|
|
return app.Http.Database.DB.Model(&PortalUser{}).Where("id = ?", id).Update("password", hashedPassword).Error
|
|
}
|
|
|
|
func DeletePortalUser(id uint) error {
|
|
// Eliminar también sus accesos de partner
|
|
if err := app.Http.Database.DB.Where("portal_user_id = ?", id).Delete(&PortalAcceso{}).Error; err != nil {
|
|
return err
|
|
}
|
|
return app.Http.Database.DB.Delete(&PortalUser{}, id).Error
|
|
}
|
|
|
|
// GetPortalUsersByClienteID devuelve todos los portal_users activos asociados a un cliente,
|
|
// ya sea directamente (rol cliente) o mediante PortalAcceso (rol partner).
|
|
func GetPortalUsersByClienteID(clienteID uint) ([]PortalUser, error) {
|
|
var result []PortalUser
|
|
db := app.Http.Database.DB
|
|
|
|
// Usuarios directos del cliente
|
|
var directos []PortalUser
|
|
if err := db.Where("cliente_id = ? AND activo = true", clienteID).Find(&directos).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
result = append(result, directos...)
|
|
|
|
// Usuarios partner con acceso al cliente via PortalAcceso
|
|
var accesos []PortalAcceso
|
|
if err := db.Where("cliente_id = ?", clienteID).Find(&accesos).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
seen := make(map[uint]bool)
|
|
for _, d := range directos {
|
|
seen[d.ID] = true
|
|
}
|
|
for _, a := range accesos {
|
|
if seen[a.PortalUserID] {
|
|
continue
|
|
}
|
|
var u PortalUser
|
|
if err := db.Where("id = ? AND activo = true", a.PortalUserID).First(&u).Error; err == nil {
|
|
result = append(result, u)
|
|
seen[u.ID] = true
|
|
}
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
func AddPortalAcceso(portalUserID, clienteID uint) error {
|
|
// Evitar duplicados
|
|
var existing PortalAcceso
|
|
err := app.Http.Database.DB.Where("portal_user_id = ? AND cliente_id = ?", portalUserID, clienteID).First(&existing).Error
|
|
if err == nil {
|
|
return nil // ya existe
|
|
}
|
|
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return err
|
|
}
|
|
return app.Http.Database.DB.Create(&PortalAcceso{PortalUserID: portalUserID, ClienteID: clienteID}).Error
|
|
}
|
|
|
|
func RemovePortalAcceso(portalUserID, clienteID uint) error {
|
|
return app.Http.Database.DB.Where("portal_user_id = ? AND cliente_id = ?", portalUserID, clienteID).
|
|
Delete(&PortalAcceso{}).Error
|
|
}
|
|
|
|
// GetClienteIDsForPortalUser devuelve todos los clienteIDs accesibles para un portal user.
|
|
func GetClienteIDsForPortalUser(u *PortalUser) []uint {
|
|
if u.Rol == "partner" {
|
|
ids := make([]uint, 0, len(u.PortalAccesos))
|
|
for _, a := range u.PortalAccesos {
|
|
ids = append(ids, a.ClienteID)
|
|
}
|
|
return ids
|
|
}
|
|
if u.ClienteID != nil {
|
|
return []uint{*u.ClienteID}
|
|
}
|
|
return []uint{}
|
|
}
|
|
|
|
// CheckPortalLogin valida credenciales y retorna el portal user.
|
|
func CheckPortalLogin(email, password string) (*PortalUser, error) {
|
|
u, err := GetPortalUserByEmail(email)
|
|
if err != nil {
|
|
return nil, errors.New("Usuario no encontrado o inactivo")
|
|
}
|
|
if !u.Activo {
|
|
return nil, errors.New("Usuario inactivo")
|
|
}
|
|
match, err := app.Http.Hash.Match(password, u.Password)
|
|
if err != nil || !match {
|
|
return nil, errors.New("Correo o contraseña incorrectos")
|
|
}
|
|
return u, nil
|
|
}
|