up
This commit is contained in:
@@ -43,8 +43,10 @@ func main() {
|
||||
// Ejecutar migraciones
|
||||
migrations.Migrate()
|
||||
} else {
|
||||
// Crear/actualizar tablas de Renovaciones (idempotente)
|
||||
// Crear/actualizar tablas de Renovaciones e idempotente)
|
||||
migrations.MigrateRenovaciones()
|
||||
// Crear/actualizar tablas de Portal, Telegram y Proyectos
|
||||
migrations.MigratePortal()
|
||||
// Crear tablas de integraciones y pasarelas si no existen
|
||||
app.Http.Database.DB.AutoMigrate(
|
||||
&models.QueryHistory{},
|
||||
|
||||
@@ -277,6 +277,31 @@ func SeedPlantillasBase() {
|
||||
log.Println("[SEED] SeedPlantillasBase completado.")
|
||||
}
|
||||
|
||||
// MigratePortal crea/actualiza las tablas del módulo Portal de Clientes, Proyectos,
|
||||
// Facturas y Telegram. Es idempotente.
|
||||
func MigratePortal() {
|
||||
db := app.Http.Database.DB
|
||||
if err := db.AutoMigrate(
|
||||
&models.Roles{}, // agrega columnas es_portal_cliente / es_portal_partner si no existen
|
||||
&models.TelegramConfig{},
|
||||
&models.TelegramLog{},
|
||||
&models.ClienteDocumento{},
|
||||
&models.PortalUser{},
|
||||
&models.PortalAcceso{},
|
||||
&models.Proyecto{},
|
||||
&models.ProyectoFase{},
|
||||
&models.ProyectoAvance{},
|
||||
&models.ProyectoEntregable{},
|
||||
&models.ProyectoTicket{},
|
||||
&models.TicketMensaje{},
|
||||
&models.Factura{},
|
||||
); err != nil {
|
||||
log.Printf("[MIGRATE] Error en MigratePortal: %v", err)
|
||||
} else {
|
||||
log.Println("[MIGRATE] Tablas de Portal OK")
|
||||
}
|
||||
}
|
||||
|
||||
// MigrateRenovaciones crea/actualiza las tablas del módulo de Renovaciones.
|
||||
// Es idempotente: GORM AutoMigrate solo añade columnas/tablas nuevas, nunca las borra.
|
||||
func MigrateRenovaciones() {
|
||||
|
||||
+18
-11
@@ -14,14 +14,16 @@ import (
|
||||
// - 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"`
|
||||
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"`
|
||||
Cliente *Cliente `json:"cliente" gorm:"foreignKey:ClienteID"`
|
||||
Rol string `json:"rol" gorm:"column:rol;default:'cliente'"`
|
||||
RoleID *uint `json:"role_id" gorm:"column:role_id;index"`
|
||||
Role *Roles `json:"role" gorm:"foreignKey:RoleID"`
|
||||
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"`
|
||||
}
|
||||
|
||||
@@ -43,7 +45,7 @@ func (PortalAcceso) TableName() string { return "portal_accesos" }
|
||||
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")
|
||||
db := app.Http.Database.DB.Model(&PortalUser{}).Preload("Cliente").Preload("PortalAccesos.Cliente").Preload("Role")
|
||||
if err := db.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
@@ -55,7 +57,7 @@ func GetAllPortalUsers(limit, offset int) ([]PortalUser, int64, error) {
|
||||
|
||||
func GetPortalUserByID(id uint) (*PortalUser, error) {
|
||||
var item PortalUser
|
||||
err := app.Http.Database.DB.Preload("Cliente").Preload("PortalAccesos.Cliente").First(&item, id).Error
|
||||
err := app.Http.Database.DB.Preload("Cliente").Preload("PortalAccesos.Cliente").Preload("Role").First(&item, id).Error
|
||||
return &item, err
|
||||
}
|
||||
|
||||
@@ -75,6 +77,7 @@ func UpdatePortalUser(u *PortalUser) error {
|
||||
"email": u.Email,
|
||||
"cliente_id": u.ClienteID,
|
||||
"rol": u.Rol,
|
||||
"role_id": u.RoleID,
|
||||
"activo": u.Activo,
|
||||
"notas": u.Notas,
|
||||
}).Error
|
||||
@@ -112,7 +115,11 @@ func RemovePortalAcceso(portalUserID, clienteID uint) error {
|
||||
|
||||
// GetClienteIDsForPortalUser devuelve todos los clienteIDs accesibles para un portal user.
|
||||
func GetClienteIDsForPortalUser(u *PortalUser) []uint {
|
||||
if u.Rol == "partner" {
|
||||
isPartner := u.Rol == "partner"
|
||||
if u.Role != nil {
|
||||
isPartner = u.Role.EsPortalPartner
|
||||
}
|
||||
if isPartner {
|
||||
ids := make([]uint, 0, len(u.PortalAccesos))
|
||||
for _, a := range u.PortalAccesos {
|
||||
ids = append(ids, a.ClienteID)
|
||||
|
||||
+17
-5
@@ -9,11 +9,13 @@ import (
|
||||
|
||||
type Roles struct {
|
||||
gorm.Model
|
||||
ID uint `gorm:"primarykey"`
|
||||
CreatedAt time.Time `json:"created_at" gorm:"column:created_at"`
|
||||
Description string `json:"description" gorm:"column:description"`
|
||||
Name string `json:"name" gorm:"column:name"`
|
||||
Submodules []Submodules `json:"submodules" gorm:"many2many:roles_submodules"` // Asegúrate de que Submodules esté definido
|
||||
ID uint `gorm:"primarykey"`
|
||||
CreatedAt time.Time `json:"created_at" gorm:"column:created_at"`
|
||||
Description string `json:"description" gorm:"column:description"`
|
||||
Name string `json:"name" gorm:"column:name"`
|
||||
EsPortalCliente bool `json:"es_portal_cliente" gorm:"column:es_portal_cliente;default:false"`
|
||||
EsPortalPartner bool `json:"es_portal_partner" gorm:"column:es_portal_partner;default:false"`
|
||||
Submodules []Submodules `json:"submodules" gorm:"many2many:roles_submodules"`
|
||||
}
|
||||
|
||||
// TableName overrides the table name used by Modules to `modules`
|
||||
@@ -88,3 +90,13 @@ func FindRoleByName(name string) (Roles, error) {
|
||||
}
|
||||
return role, nil
|
||||
}
|
||||
|
||||
// GetPortalRoles devuelve los roles marcados como portal cliente o portal partner.
|
||||
func GetPortalRoles() ([]Roles, error) {
|
||||
var roles []Roles
|
||||
err := app.Http.Database.DB.
|
||||
Where("es_portal_cliente = ? OR es_portal_partner = ?", true, true).
|
||||
Order("name ASC").
|
||||
Find(&roles).Error
|
||||
return roles, err
|
||||
}
|
||||
|
||||
@@ -33,13 +33,13 @@
|
||||
<td class="px-4 py-3 font-medium text-slate-800" x-text="u.nombre"></td>
|
||||
<td class="px-4 py-3 text-slate-600" x-text="u.email"></td>
|
||||
<td class="px-4 py-3">
|
||||
<span class="badge" :class="u.rol==='partner' ? 'badge-blue' : 'badge-green'" x-text="u.rol"></span>
|
||||
<span class="badge" :class="(u.role?.es_portal_partner || u.rol==='partner') ? 'badge-blue' : 'badge-green'" x-text="u.role?.name || u.rol"></span>
|
||||
</td>
|
||||
<td class="px-4 py-3 text-slate-500 text-xs">
|
||||
<template x-if="u.rol==='cliente' && u.cliente">
|
||||
<template x-if="!(u.role?.es_portal_partner || u.rol==='partner') && u.cliente">
|
||||
<span x-text="u.cliente?.empresa || u.cliente?.nombre"></span>
|
||||
</template>
|
||||
<template x-if="u.rol==='partner'">
|
||||
<template x-if="u.role?.es_portal_partner || u.rol==='partner'">
|
||||
<div class="flex flex-wrap gap-1">
|
||||
<template x-for="acc in (u.portal_accesos||[])" :key="acc.ID">
|
||||
<span class="bg-slate-100 px-2 py-0.5 rounded text-xs flex items-center gap-1">
|
||||
@@ -82,12 +82,16 @@
|
||||
</div>
|
||||
<div>
|
||||
<label class="label">Rol</label>
|
||||
<select x-model="form.rol" class="input-field w-full">
|
||||
<option value="cliente">Cliente</option>
|
||||
<option value="partner">Partner</option>
|
||||
<select x-model.number="form.role_id" class="input-field w-full">
|
||||
<option value="">Sin rol asignado</option>
|
||||
<template x-for="r in portalRoles" :key="r.ID">
|
||||
<option :value="r.ID">
|
||||
<span x-text="r.name + (r.es_portal_partner ? ' (Partner)' : ' (Cliente)')"></span>
|
||||
</option>
|
||||
</template>
|
||||
</select>
|
||||
</div>
|
||||
<div x-show="form.rol==='cliente'">
|
||||
<div x-show="portalRoles.find(r => r.ID === form.role_id)?.es_portal_cliente">
|
||||
<label class="label">Cliente asignado</label>
|
||||
<select x-model.number="form.cliente_id" class="input-field w-full">
|
||||
<option value="">Sin asignar</option>
|
||||
@@ -146,11 +150,11 @@
|
||||
<script>
|
||||
function portalUsuariosApp() {
|
||||
return {
|
||||
items: [], clientes: [], loading: false, saving: false,
|
||||
items: [], clientes: [], portalRoles: [], loading: false, saving: false,
|
||||
showModal: false, showDelete: false, showAccesoModal: false,
|
||||
editId: null, deleteId: null, error: '',
|
||||
accesoUserId: null, accesoClienteId: '',
|
||||
form: { nombre:'', email:'', password:'', rol:'cliente', cliente_id:'', activo:true, notas:'' },
|
||||
form: { nombre:'', email:'', password:'', role_id:'', cliente_id:'', activo:true, notas:'' },
|
||||
|
||||
async init() { await this.load(); },
|
||||
|
||||
@@ -160,23 +164,25 @@ function portalUsuariosApp() {
|
||||
const r = await axios.get('/app/loadportalusuarios');
|
||||
this.items = r.data.items || [];
|
||||
this.clientes = r.data.clientes || [];
|
||||
this.portalRoles = r.data.portalRoles || [];
|
||||
} finally { this.loading = false; }
|
||||
},
|
||||
|
||||
openCreate() {
|
||||
this.editId=null; this.error='';
|
||||
this.form={nombre:'',email:'',password:'',rol:'cliente',cliente_id:'',activo:true,notas:''};
|
||||
this.form={nombre:'',email:'',password:'',role_id:'',cliente_id:'',activo:true,notas:''};
|
||||
this.showModal=true;
|
||||
},
|
||||
openEdit(u) {
|
||||
this.editId=u.ID; this.error='';
|
||||
this.form={nombre:u.nombre,email:u.email,password:'',rol:u.rol,cliente_id:u.cliente_id||'',activo:u.activo,notas:u.notas||''};
|
||||
this.form={nombre:u.nombre,email:u.email,password:'',role_id:u.role_id||'',cliente_id:u.cliente_id||'',activo:u.activo,notas:u.notas||''};
|
||||
this.showModal=true;
|
||||
},
|
||||
async save() {
|
||||
this.saving=true; this.error='';
|
||||
const payload={...this.form};
|
||||
if(payload.cliente_id==='') payload.cliente_id=null;
|
||||
if(payload.role_id==='') payload.role_id=null;
|
||||
try {
|
||||
if(this.editId) await axios.put(`/app/portal-usuarios/${this.editId}`, payload);
|
||||
else await axios.post('/app/portal-usuarios', payload);
|
||||
|
||||
@@ -51,6 +51,7 @@
|
||||
<th class="py-2 px-4 border-b w-52 ">Nombre</th>
|
||||
<th class="py-2 px-4 border-b">Descripción</th>
|
||||
<th class="py-2 px-4 border-b">Submodulos</th>
|
||||
<th class="py-2 px-4 border-b w-28">Portal</th>
|
||||
<th class="py-2 px-4 border-b w-32"></th>
|
||||
</tr>
|
||||
</thead>
|
||||
@@ -86,6 +87,16 @@
|
||||
</span>
|
||||
</template>
|
||||
</td>
|
||||
<td class="py-3 text-xs px-4 border-b">
|
||||
<div class="flex flex-col gap-1">
|
||||
<template x-if="registro.es_portal_cliente">
|
||||
<span class="bg-blue-100 text-blue-700 px-2 py-0.5 rounded text-xs font-medium">Usuario Final</span>
|
||||
</template>
|
||||
<template x-if="registro.es_portal_partner">
|
||||
<span class="bg-purple-100 text-purple-700 px-2 py-0.5 rounded text-xs font-medium">Partner</span>
|
||||
</template>
|
||||
</div>
|
||||
</td>
|
||||
<td class="py-3 text-xs px-4 border-b ">
|
||||
<div class="flex justify-between space-x-1">
|
||||
<button
|
||||
@@ -105,6 +116,8 @@
|
||||
Name = registro.name;
|
||||
Description = registro.description;
|
||||
Submodules = [...registro.submodules];
|
||||
EsPortalCliente = registro.es_portal_cliente || false;
|
||||
EsPortalPartner = registro.es_portal_partner || false;
|
||||
modulos.forEach(modulo => {
|
||||
modulo.submodules.forEach(submodulo => {
|
||||
submodulo.checked = Submodules.some(sm => sm.ID === submodulo.ID);
|
||||
@@ -209,6 +222,19 @@
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
<div class="mt-4 p-3 border rounded-md bg-slate-50">
|
||||
<p class="font-semibold text-sm mb-2">Tipo de acceso Portal</p>
|
||||
<div class="flex gap-6">
|
||||
<label class="flex items-center gap-2 text-sm cursor-pointer">
|
||||
<input type="checkbox" x-model="EsPortalCliente" @change="if(EsPortalCliente) EsPortalPartner=false" class="rounded">
|
||||
Usuario Final (Cliente)
|
||||
</label>
|
||||
<label class="flex items-center gap-2 text-sm cursor-pointer">
|
||||
<input type="checkbox" x-model="EsPortalPartner" @change="if(EsPortalPartner) EsPortalCliente=false" class="rounded">
|
||||
Partner
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-4 flex justify-between">
|
||||
<button type="submit" class="bg-[#8eb02f] text-white px-4 py-2 rounded">Guardar Cambios</button>
|
||||
<button type="button" class="bg-gray-600 text-white px-4 py-2 rounded"
|
||||
@@ -253,6 +279,19 @@
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<div class="mt-4 p-3 border rounded-md bg-slate-50">
|
||||
<p class="font-semibold text-sm mb-2">Tipo de acceso Portal</p>
|
||||
<div class="flex gap-6">
|
||||
<label class="flex items-center gap-2 text-sm cursor-pointer">
|
||||
<input type="checkbox" x-model="newEsPortalCliente" @change="if(newEsPortalCliente) newEsPortalPartner=false" class="rounded">
|
||||
Usuario Final (Cliente)
|
||||
</label>
|
||||
<label class="flex items-center gap-2 text-sm cursor-pointer">
|
||||
<input type="checkbox" x-model="newEsPortalPartner" @change="if(newEsPortalPartner) newEsPortalCliente=false" class="rounded">
|
||||
Partner
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-4 flex justify-between">
|
||||
<button type="submit" class="bg-[#8eb02f] text-white px-4 py-2 rounded">Guardar</button>
|
||||
@@ -291,9 +330,13 @@
|
||||
|
||||
newName: '',
|
||||
newDescription: '',
|
||||
newEsPortalCliente: false,
|
||||
newEsPortalPartner: false,
|
||||
|
||||
Name: '',
|
||||
Description: '',
|
||||
EsPortalCliente: false,
|
||||
EsPortalPartner: false,
|
||||
modulos: [],
|
||||
Submodules: [],
|
||||
submodulos: [],
|
||||
@@ -415,6 +458,8 @@
|
||||
const requestData = {
|
||||
name: this.newName,
|
||||
description: this.newDescription,
|
||||
es_portal_cliente: this.newEsPortalCliente,
|
||||
es_portal_partner: this.newEsPortalPartner,
|
||||
submodules: selectedSubmodules.flatMap(modulo => modulo.submodules)
|
||||
};
|
||||
|
||||
@@ -427,6 +472,8 @@
|
||||
.then(() => {
|
||||
this.newName = '';
|
||||
this.newDescription = '';
|
||||
this.newEsPortalCliente = false;
|
||||
this.newEsPortalPartner = false;
|
||||
this.modulos.forEach(modulo => {
|
||||
modulo.submodules.forEach(submodulo => submodulo.checked = false); // Reset checkboxes
|
||||
});
|
||||
@@ -471,6 +518,8 @@
|
||||
body: JSON.stringify({
|
||||
name: this.Name,
|
||||
description: this.Description,
|
||||
es_portal_cliente: this.EsPortalCliente,
|
||||
es_portal_partner: this.EsPortalPartner,
|
||||
submodules: this.submodulos
|
||||
})
|
||||
})
|
||||
@@ -478,6 +527,8 @@
|
||||
.then(() => {
|
||||
this.Name = '';
|
||||
this.Description = '';
|
||||
this.EsPortalCliente = false;
|
||||
this.EsPortalPartner = false;
|
||||
this.submodulos = [];
|
||||
this.modulos.forEach(modulo => {
|
||||
modulo.submodules.forEach(submodulo => {
|
||||
|
||||
@@ -78,7 +78,7 @@ func PortalDashboard(c *fiber.Ctx) error {
|
||||
"portalUser": fullUser,
|
||||
"proyectos": proyectos,
|
||||
"grupos": grupos,
|
||||
"isPartner": fullUser.Rol == "partner",
|
||||
"isPartner": fullUser.Rol == "partner" || (fullUser.Role != nil && fullUser.Role.EsPortalPartner),
|
||||
}, "layouts/portal")
|
||||
}
|
||||
|
||||
|
||||
@@ -29,12 +29,14 @@ func LoadPortalUsuarios(c *fiber.Ctx) error {
|
||||
return c.Status(500).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
clientes, _, _ := models.GetAllClientes(200, 0, "")
|
||||
portalRoles, _ := models.GetPortalRoles()
|
||||
return c.JSON(fiber.Map{
|
||||
"items": items,
|
||||
"total": total,
|
||||
"totalPages": int(math.Ceil(float64(total) / float64(limit))),
|
||||
"page": page,
|
||||
"clientes": clientes,
|
||||
"items": items,
|
||||
"total": total,
|
||||
"totalPages": int(math.Ceil(float64(total) / float64(limit))),
|
||||
"page": page,
|
||||
"clientes": clientes,
|
||||
"portalRoles": portalRoles,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -44,7 +46,7 @@ func CreatePortalUsuario(c *fiber.Ctx) error {
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
ClienteID *uint `json:"cliente_id"`
|
||||
Rol string `json:"rol"`
|
||||
RoleID *uint `json:"role_id"`
|
||||
Notas string `json:"notas"`
|
||||
}
|
||||
var req Req
|
||||
@@ -58,15 +60,23 @@ func CreatePortalUsuario(c *fiber.Ctx) error {
|
||||
if err != nil {
|
||||
return c.Status(500).JSON(fiber.Map{"error": "Error al hashear contraseña"})
|
||||
}
|
||||
if req.Rol == "" {
|
||||
req.Rol = "cliente"
|
||||
// Derivar Rol del tipo de rol seleccionado
|
||||
rol := "cliente"
|
||||
if req.RoleID != nil {
|
||||
var role models.Roles
|
||||
if err := app.Http.Database.DB.First(&role, *req.RoleID).Error; err == nil {
|
||||
if role.EsPortalPartner {
|
||||
rol = "partner"
|
||||
}
|
||||
}
|
||||
}
|
||||
u := &models.PortalUser{
|
||||
Nombre: req.Nombre,
|
||||
Email: strings.ToLower(strings.TrimSpace(req.Email)),
|
||||
Password: hashed,
|
||||
ClienteID: req.ClienteID,
|
||||
Rol: req.Rol,
|
||||
RoleID: req.RoleID,
|
||||
Rol: rol,
|
||||
Activo: true,
|
||||
Notas: req.Notas,
|
||||
}
|
||||
@@ -87,7 +97,7 @@ func UpdatePortalUsuario(c *fiber.Ctx) error {
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
ClienteID *uint `json:"cliente_id"`
|
||||
Rol string `json:"rol"`
|
||||
RoleID *uint `json:"role_id"`
|
||||
Activo bool `json:"activo"`
|
||||
Notas string `json:"notas"`
|
||||
}
|
||||
@@ -95,11 +105,22 @@ func UpdatePortalUsuario(c *fiber.Ctx) error {
|
||||
if err := c.BodyParser(&req); err != nil {
|
||||
return c.Status(400).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
// Derivar Rol del tipo de rol seleccionado
|
||||
rol := "cliente"
|
||||
if req.RoleID != nil {
|
||||
var role models.Roles
|
||||
if err := app.Http.Database.DB.First(&role, *req.RoleID).Error; err == nil {
|
||||
if role.EsPortalPartner {
|
||||
rol = "partner"
|
||||
}
|
||||
}
|
||||
}
|
||||
u := &models.PortalUser{
|
||||
Nombre: req.Nombre,
|
||||
Email: strings.ToLower(strings.TrimSpace(req.Email)),
|
||||
ClienteID: req.ClienteID,
|
||||
Rol: req.Rol,
|
||||
RoleID: req.RoleID,
|
||||
Rol: rol,
|
||||
Activo: req.Activo,
|
||||
Notas: req.Notas,
|
||||
}
|
||||
@@ -109,7 +130,7 @@ func UpdatePortalUsuario(c *fiber.Ctx) error {
|
||||
}
|
||||
// Actualizar password solo si se envió
|
||||
if strings.TrimSpace(req.Password) != "" {
|
||||
hashed, err := app.Http.Hash.Create(req.Password)
|
||||
hashed, err := app.Http.Hash.Create(req.Password)
|
||||
if err == nil {
|
||||
_ = models.UpdatePortalUserPassword(uint(id), hashed)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user