up
This commit is contained in:
@@ -738,6 +738,7 @@ func MigratePortal() {
|
||||
&models.TicketMensaje{},
|
||||
&models.PortalUser{},
|
||||
&models.PortalAcceso{},
|
||||
&models.TelegramPortalToken{},
|
||||
&models.Factura{},
|
||||
); err != nil {
|
||||
log.Printf("[MIGRATE] Error en MigratePortal: %v", err)
|
||||
|
||||
@@ -28,8 +28,10 @@ type PortalUser struct {
|
||||
Telefono string `json:"telefono" gorm:"column:telefono"`
|
||||
Indicativo string `json:"indicativo" gorm:"column:indicativo"` // ej: +57, +1
|
||||
Pais string `json:"pais" gorm:"column:pais"`
|
||||
Documento string `json:"documento" gorm:"column:documento"` // RUT, NIT, CC, etc.
|
||||
Empresa string `json:"empresa" gorm:"column:empresa"` // empresa que representa
|
||||
Documento string `json:"documento" gorm:"column:documento"` // RUT, NIT, CC, etc.
|
||||
Empresa string `json:"empresa" gorm:"column:empresa"` // empresa que representa
|
||||
DocumentoRutFile string `json:"documento_rut_file" gorm:"column:documento_rut_file"` // ruta del archivo RUT
|
||||
DocumentoRutNombre string `json:"documento_rut_nombre" gorm:"column:documento_rut_nombre"` // nombre original
|
||||
PortalAccesos []PortalAcceso `json:"portal_accesos" gorm:"foreignKey:PortalUserID"`
|
||||
}
|
||||
|
||||
@@ -99,6 +101,17 @@ func UpdatePortalUserPassword(id uint, hashedPassword string) error {
|
||||
return app.Http.Database.DB.Model(&PortalUser{}).Where("id = ?", id).Update("password", hashedPassword).Error
|
||||
}
|
||||
|
||||
func UpdatePortalUserTelegramChatID(id uint, chatID string) error {
|
||||
return app.Http.Database.DB.Model(&PortalUser{}).Where("id = ?", id).Update("telegram_chat_id", chatID).Error
|
||||
}
|
||||
|
||||
func UpdatePortalUserRutFile(id uint, path, nombre string) error {
|
||||
return app.Http.Database.DB.Model(&PortalUser{}).Where("id = ?", id).Updates(map[string]interface{}{
|
||||
"documento_rut_file": path,
|
||||
"documento_rut_nombre": nombre,
|
||||
}).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 {
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"fmt"
|
||||
|
||||
"github.com/sujit-baniya/fiber-boilerplate/app"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// TelegramPortalToken almacena un código de verificación temporal para vincular
|
||||
// el Telegram de un usuario del portal con el bot de notificaciones.
|
||||
type TelegramPortalToken struct {
|
||||
gorm.Model
|
||||
PortalUserID uint `json:"portal_user_id" gorm:"column:portal_user_id;uniqueIndex"`
|
||||
Token string `json:"token" gorm:"column:token;uniqueIndex;size:8"`
|
||||
}
|
||||
|
||||
func (TelegramPortalToken) TableName() string { return "telegram_portal_tokens" }
|
||||
|
||||
// GenerateTelegramPortalToken genera (o renueva) el código de vinculación para el usuario.
|
||||
// El código tiene 6 caracteres hexadecimales en mayúsculas (e.g. "A3F9B2").
|
||||
func GenerateTelegramPortalToken(portalUserID uint) (*TelegramPortalToken, error) {
|
||||
// Eliminar tokens previos del mismo usuario
|
||||
app.Http.Database.DB.Where("portal_user_id = ?", portalUserID).Delete(&TelegramPortalToken{})
|
||||
|
||||
b := make([]byte, 3)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return nil, fmt.Errorf("no se pudo generar token: %w", err)
|
||||
}
|
||||
token := fmt.Sprintf("%06X", b)
|
||||
|
||||
t := &TelegramPortalToken{PortalUserID: portalUserID, Token: token}
|
||||
if err := app.Http.Database.DB.Create(t).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return t, nil
|
||||
}
|
||||
|
||||
// FindTelegramPortalToken busca un token de vinculación activo.
|
||||
func FindTelegramPortalToken(token string) (*TelegramPortalToken, error) {
|
||||
var t TelegramPortalToken
|
||||
err := app.Http.Database.DB.Where("token = ?", token).First(&t).Error
|
||||
return &t, err
|
||||
}
|
||||
|
||||
// DeleteTelegramPortalToken elimina el token de un usuario (tras vincular correctamente).
|
||||
func DeleteTelegramPortalToken(portalUserID uint) {
|
||||
app.Http.Database.DB.Where("portal_user_id = ?", portalUserID).Delete(&TelegramPortalToken{})
|
||||
}
|
||||
@@ -57,6 +57,28 @@ func (ts *TelegramService) SendMessage(chatID interface{}, message string) error
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetBotUsername obtiene el username (@nombre) del bot a partir de su token.
|
||||
func GetBotUsername(botToken string) string {
|
||||
if botToken == "" {
|
||||
return ""
|
||||
}
|
||||
resp, err := http.Get(fmt.Sprintf("https://api.telegram.org/bot%s/getMe", botToken))
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
var result struct {
|
||||
OK bool `json:"ok"`
|
||||
Result struct {
|
||||
Username string `json:"username"`
|
||||
} `json:"result"`
|
||||
}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
|
||||
return ""
|
||||
}
|
||||
return result.Result.Username
|
||||
}
|
||||
|
||||
// SendMessageWithToken envía un mensaje usando un bot token explícito (útil para notificar a usuarios con su propio chat_id).
|
||||
func (ts *TelegramService) SendMessageWithToken(chatID interface{}, message, botToken string) error {
|
||||
svc := &TelegramService{BotToken: botToken}
|
||||
|
||||
@@ -140,6 +140,10 @@
|
||||
:class="tab==='password' ? 'border-[#8eb02f] text-[#8eb02f]' : 'border-transparent text-slate-500 hover:text-slate-700'">
|
||||
Contraseña
|
||||
</button>
|
||||
<button @click="tab='telegram'" class="py-3 text-sm font-medium border-b-2 -mb-px transition-colors"
|
||||
:class="tab==='telegram' ? 'border-[#8eb02f] text-[#8eb02f]' : 'border-transparent text-slate-500 hover:text-slate-700'">
|
||||
Telegram
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Body scrollable -->
|
||||
@@ -218,6 +222,22 @@
|
||||
<input x-model="perfil.empresa" type="text" placeholder="Nombre de tu empresa"
|
||||
class="w-full border border-slate-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-[#8eb02f] focus:ring-2 focus:ring-[#8eb02f]/20">
|
||||
</div>
|
||||
|
||||
<!-- Documento RUT (archivo) -->
|
||||
<div class="border border-slate-200 rounded-lg p-3 bg-slate-50">
|
||||
<label class="block text-xs font-semibold text-slate-500 uppercase tracking-wide mb-2">Documento RUT / Cámara de comercio (archivo)</label>
|
||||
<div x-show="perfil.documento_rut_nombre" class="flex items-center gap-2 mb-2 text-sm text-slate-600">
|
||||
<svg class="w-4 h-4 text-green-500 flex-shrink-0" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
|
||||
<span x-text="perfil.documento_rut_nombre" class="truncate"></span>
|
||||
</div>
|
||||
<p x-show="rutMsg" x-text="rutMsg"
|
||||
:class="rutOk ? 'text-green-600' : 'text-red-600'"
|
||||
class="text-xs mb-2"></p>
|
||||
<input type="file" id="rutFileInput" accept=".pdf,.jpg,.jpeg,.png,.webp"
|
||||
@change="subirRut($event)"
|
||||
class="block w-full text-sm text-slate-500 file:mr-3 file:py-1.5 file:px-3 file:rounded-lg file:border-0 file:text-xs file:font-semibold file:bg-[#8eb02f]/10 file:text-[#6d8c24] hover:file:bg-[#8eb02f]/20 cursor-pointer">
|
||||
<p class="text-xs text-slate-400 mt-1">PDF, JPG o PNG · Máx. 10 MB</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Tab: Cambiar contraseña -->
|
||||
@@ -245,6 +265,92 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Tab: Telegram -->
|
||||
<div x-show="tab==='telegram'" class="space-y-4">
|
||||
|
||||
<!-- Estado actual -->
|
||||
<div x-show="tg.linked" class="flex items-center gap-3 p-3 bg-green-50 border border-green-200 rounded-lg">
|
||||
<svg class="w-5 h-5 text-green-500 flex-shrink-0" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
|
||||
<div>
|
||||
<p class="text-sm font-semibold text-green-800">Telegram vinculado</p>
|
||||
<p class="text-xs text-green-600">Chat ID: <span class="font-mono" x-text="tg.chat_id"></span></p>
|
||||
</div>
|
||||
</div>
|
||||
<div x-show="!tg.linked" class="flex items-center gap-3 p-3 bg-slate-50 border border-slate-200 rounded-lg">
|
||||
<svg class="w-5 h-5 text-slate-400 flex-shrink-0" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
|
||||
<p class="text-sm text-slate-500">Aún no has vinculado Telegram. Sigue los pasos para recibir notificaciones.</p>
|
||||
</div>
|
||||
|
||||
<!-- Paso a paso vinculación -->
|
||||
<div x-show="!tg.linked" class="space-y-4">
|
||||
<div class="border border-slate-200 rounded-xl p-4 space-y-3">
|
||||
<h3 class="text-sm font-semibold text-slate-700">Cómo vincular Telegram</h3>
|
||||
|
||||
<!-- Paso 1 -->
|
||||
<div class="flex gap-3">
|
||||
<span class="flex-shrink-0 w-6 h-6 rounded-full bg-[#8eb02f] text-white flex items-center justify-center text-xs font-bold">1</span>
|
||||
<div class="flex-1">
|
||||
<p class="text-sm text-slate-700 font-medium">Genera tu código</p>
|
||||
<p class="text-xs text-slate-500 mb-2">Haz clic en el botón para obtener un código único de vinculación.</p>
|
||||
<button @click="tgGenerarCodigo()" :disabled="tg.generando"
|
||||
class="inline-flex items-center gap-1.5 px-3 py-1.5 bg-[#8eb02f] hover:bg-[#6d8c24] text-white text-xs font-semibold rounded-lg transition-colors disabled:opacity-60">
|
||||
<span x-show="!tg.generando">Generar código</span>
|
||||
<span x-show="tg.generando">Generando…</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Código generado -->
|
||||
<div x-show="tg.token" class="ml-9 p-3 bg-slate-800 rounded-lg">
|
||||
<p class="text-xs text-slate-400 mb-1">Tu código de vinculación:</p>
|
||||
<p class="text-2xl font-mono font-bold text-white tracking-widest" x-text="tg.token"></p>
|
||||
</div>
|
||||
|
||||
<!-- Paso 2 -->
|
||||
<div x-show="tg.token" class="flex gap-3">
|
||||
<span class="flex-shrink-0 w-6 h-6 rounded-full bg-[#8eb02f] text-white flex items-center justify-center text-xs font-bold">2</span>
|
||||
<div class="flex-1">
|
||||
<p class="text-sm text-slate-700 font-medium">Envía el código al bot</p>
|
||||
<p class="text-xs text-slate-500 mb-1">Abre el bot en Telegram y envía el siguiente mensaje:</p>
|
||||
<div class="flex items-center gap-2 p-2 bg-slate-100 rounded-lg">
|
||||
<code class="text-sm font-mono text-slate-800" x-text="'/vincular ' + tg.token"></code>
|
||||
<button @click="navigator.clipboard?.writeText('/vincular '+tg.token)"
|
||||
class="ml-auto text-slate-400 hover:text-slate-600 text-xs" title="Copiar">
|
||||
<svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"/></svg>
|
||||
</button>
|
||||
</div>
|
||||
<template x-if="tg.bot_username">
|
||||
<a :href="tg.bot_link" target="_blank"
|
||||
class="inline-flex items-center gap-1 mt-2 text-xs font-semibold text-[#8eb02f] hover:underline">
|
||||
<svg class="w-3.5 h-3.5" fill="currentColor" viewBox="0 0 24 24"><path d="M12 0C5.372 0 0 5.372 0 12s5.372 12 12 12 12-5.372 12-12S18.628 0 12 0zm5.894 8.221l-1.97 9.28c-.145.658-.537.818-1.084.508l-3-2.21-1.447 1.394c-.16.16-.295.295-.605.295l.213-3.053 5.56-5.023c.242-.213-.054-.333-.373-.12l-6.871 4.326-2.962-.924c-.643-.204-.657-.643.136-.953l11.57-4.461c.537-.194 1.006.131.833.941z"/></svg>
|
||||
Abrir @<span x-text="tg.bot_username"></span>
|
||||
</a>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Paso 3 -->
|
||||
<div x-show="tg.token" class="flex gap-3">
|
||||
<span class="flex-shrink-0 w-6 h-6 rounded-full bg-[#8eb02f] text-white flex items-center justify-center text-xs font-bold">3</span>
|
||||
<div class="flex-1">
|
||||
<p class="text-sm text-slate-700 font-medium">Verifica la vinculación</p>
|
||||
<p class="text-xs text-slate-500 mb-2">Después de enviar el mensaje, haz clic en verificar.</p>
|
||||
<button @click="tgVerificar()" :disabled="tg.verificando"
|
||||
class="inline-flex items-center gap-1.5 px-3 py-1.5 border border-[#8eb02f] text-[#8eb02f] text-xs font-semibold rounded-lg transition-colors hover:bg-[#8eb02f]/10 disabled:opacity-60">
|
||||
<span x-show="!tg.verificando">Verificar vinculación</span>
|
||||
<span x-show="tg.verificando">Verificando…</span>
|
||||
</button>
|
||||
<p x-show="tg.verMsg" x-text="tg.verMsg"
|
||||
:class="tg.verOk ? 'text-green-600' : 'text-red-500'"
|
||||
class="text-xs mt-2"></p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
</div><!-- /body -->
|
||||
|
||||
<!-- Footer con botón guardar -->
|
||||
@@ -263,6 +369,9 @@
|
||||
<span x-show="saving">Procesando…</span>
|
||||
</button>
|
||||
</template>
|
||||
<template x-if="tab==='telegram'">
|
||||
<p class="text-xs text-slate-400 text-center">Las notificaciones de Telegram son enviadas por nuestro bot.</p>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
</div><!-- /panel -->
|
||||
@@ -292,16 +401,23 @@ function miCuenta() {
|
||||
open: false,
|
||||
tab: 'perfil',
|
||||
saving: false,
|
||||
perfil: { nombre:'', email:'', telefono:'', indicativo:'', pais:'', documento:'', empresa:'' },
|
||||
perfil: { nombre:'', email:'', telefono:'', indicativo:'', pais:'', documento:'', empresa:'', documento_rut_file:'', documento_rut_nombre:'' },
|
||||
perfilMsg: '', perfilOk: false,
|
||||
pass: { actual:'', nueva:'', confirma:'' },
|
||||
passMsg: '', passOk: false,
|
||||
rutMsg: '', rutOk: false,
|
||||
tg: { linked: false, chat_id: '', token: '', bot_username: '', bot_link: '', generando: false, verificando: false, verMsg: '', verOk: false },
|
||||
|
||||
async init() {
|
||||
try {
|
||||
const r = await axios.get('/portal/mi-perfil');
|
||||
this.perfil = r.data;
|
||||
} catch(e) {}
|
||||
try {
|
||||
const s = await axios.get('/portal/mi-perfil/telegram-status');
|
||||
this.tg.linked = s.data.linked;
|
||||
this.tg.chat_id = s.data.chat_id;
|
||||
} catch(e) {}
|
||||
},
|
||||
|
||||
async guardarPerfil() {
|
||||
@@ -335,6 +451,60 @@ function miCuenta() {
|
||||
this.passOk = false;
|
||||
} finally { this.saving = false; }
|
||||
},
|
||||
|
||||
async subirRut(event) {
|
||||
const file = event.target.files[0];
|
||||
if (!file) return;
|
||||
this.rutMsg = '';
|
||||
const fd = new FormData();
|
||||
fd.append('rut_file', file);
|
||||
try {
|
||||
const r = await axios.post('/portal/mi-perfil/rut-file', fd, { headers: { 'Content-Type': 'multipart/form-data' } });
|
||||
this.perfil.documento_rut_nombre = r.data.nombre;
|
||||
this.rutMsg = '✅ Archivo subido correctamente.';
|
||||
this.rutOk = true;
|
||||
} catch(e) {
|
||||
this.rutMsg = e.response?.data?.error || 'Error al subir archivo.';
|
||||
this.rutOk = false;
|
||||
}
|
||||
event.target.value = '';
|
||||
},
|
||||
|
||||
async tgGenerarCodigo() {
|
||||
this.tg.generando = true;
|
||||
this.tg.token = '';
|
||||
this.tg.verMsg = '';
|
||||
try {
|
||||
const r = await axios.post('/portal/mi-perfil/telegram-init');
|
||||
this.tg.token = r.data.token;
|
||||
this.tg.bot_username = r.data.bot_username || '';
|
||||
this.tg.bot_link = r.data.bot_link || '';
|
||||
} catch(e) {
|
||||
this.tg.verMsg = 'No se pudo generar el código. Intenta de nuevo.';
|
||||
this.tg.verOk = false;
|
||||
} finally { this.tg.generando = false; }
|
||||
},
|
||||
|
||||
async tgVerificar() {
|
||||
this.tg.verificando = true;
|
||||
this.tg.verMsg = '';
|
||||
try {
|
||||
const r = await axios.get('/portal/mi-perfil/telegram-status');
|
||||
if (r.data.linked) {
|
||||
this.tg.linked = true;
|
||||
this.tg.chat_id = r.data.chat_id;
|
||||
this.tg.token = '';
|
||||
this.tg.verMsg = '✅ ¡Telegram vinculado correctamente!';
|
||||
this.tg.verOk = true;
|
||||
} else {
|
||||
this.tg.verMsg = 'Aún no se detectó el mensaje. Asegúrate de enviar el código al bot.';
|
||||
this.tg.verOk = false;
|
||||
}
|
||||
} catch(e) {
|
||||
this.tg.verMsg = 'Error al verificar. Intenta de nuevo.';
|
||||
this.tg.verOk = false;
|
||||
} finally { this.tg.verificando = false; }
|
||||
},
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -60,6 +60,9 @@
|
||||
<span x-show="!u.telegram_chat_id" class="text-slate-300">—</span>
|
||||
</td>
|
||||
<td class="px-4 py-3 flex gap-2">
|
||||
<button @click="openDetail(u)" class="btn-icon text-blue-500" title="Ver detalle">
|
||||
<svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/><path stroke-linecap="round" stroke-linejoin="round" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/></svg>
|
||||
</button>
|
||||
<button @click="openEdit(u)" class="btn-icon text-yellow-500" title="Editar">
|
||||
<svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>
|
||||
</button>
|
||||
@@ -147,6 +150,116 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Panel detalle usuario (slide derecho) -->
|
||||
<div x-show="showDetail" x-cloak class="fixed inset-0 z-50 flex justify-end">
|
||||
<div class="absolute inset-0 bg-black/40" @click="showDetail=false"></div>
|
||||
<div class="relative w-full max-w-md bg-white shadow-2xl flex flex-col overflow-hidden"
|
||||
x-transition:enter="transition ease-out duration-300"
|
||||
x-transition:enter-start="translate-x-full opacity-0"
|
||||
x-transition:enter-end="translate-x-0 opacity-100"
|
||||
x-transition:leave="transition ease-in duration-200"
|
||||
x-transition:leave-start="translate-x-0 opacity-100"
|
||||
x-transition:leave-end="translate-x-full opacity-0">
|
||||
|
||||
<!-- Header -->
|
||||
<div class="flex items-center justify-between px-5 py-4 border-b border-slate-200 flex-shrink-0">
|
||||
<h2 class="text-base font-bold text-slate-800">Detalle del usuario</h2>
|
||||
<button @click="showDetail=false" class="p-1.5 rounded-lg hover:bg-slate-100 text-slate-400 hover:text-slate-600">
|
||||
<svg class="w-5 h-5" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/></svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Loading -->
|
||||
<div x-show="loadingDetail" class="flex-1 flex items-center justify-center">
|
||||
<p class="text-slate-400 text-sm">Cargando…</p>
|
||||
</div>
|
||||
|
||||
<!-- Contenido -->
|
||||
<div x-show="detailUser && !loadingDetail" class="flex-1 overflow-y-auto px-5 py-5 space-y-4">
|
||||
|
||||
<!-- Avatar + nombre -->
|
||||
<div class="flex items-center gap-3 pb-4 border-b border-slate-100">
|
||||
<div class="w-12 h-12 rounded-full bg-primary/20 flex items-center justify-center text-[#8eb02f] font-bold text-xl flex-shrink-0"
|
||||
x-text="detailUser?.nombre?.charAt(0)?.toUpperCase()"></div>
|
||||
<div>
|
||||
<p class="font-semibold text-slate-800 text-base" x-text="detailUser?.nombre"></p>
|
||||
<p class="text-sm text-slate-500" x-text="detailUser?.email"></p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Badges -->
|
||||
<div class="flex items-center gap-2 flex-wrap">
|
||||
<span class="badge" :class="detailUser?.rol==='partner' ? 'badge-blue' : 'badge-green'" x-text="detailUser?.rol"></span>
|
||||
<span class="badge" :class="detailUser?.activo ? 'badge-green' : 'badge-slate'" x-text="detailUser?.activo ? 'Activo' : 'Inactivo'"></span>
|
||||
<span x-show="detailUser?.role" class="badge badge-slate" x-text="detailUser?.role?.display_name || detailUser?.role?.name"></span>
|
||||
</div>
|
||||
|
||||
<!-- Campos -->
|
||||
<div class="grid grid-cols-2 gap-3">
|
||||
<div x-show="detailUser?.telefono || detailUser?.indicativo" class="col-span-2">
|
||||
<p class="label">Teléfono</p>
|
||||
<p class="text-sm text-slate-700" x-text="(detailUser?.indicativo || '') + ' ' + (detailUser?.telefono || '')"></p>
|
||||
</div>
|
||||
<div x-show="detailUser?.pais">
|
||||
<p class="label">País</p>
|
||||
<p class="text-sm text-slate-700" x-text="detailUser?.pais"></p>
|
||||
</div>
|
||||
<div x-show="detailUser?.empresa">
|
||||
<p class="label">Empresa</p>
|
||||
<p class="text-sm text-slate-700" x-text="detailUser?.empresa"></p>
|
||||
</div>
|
||||
<div x-show="detailUser?.documento" class="col-span-2">
|
||||
<p class="label">NIT / Documento</p>
|
||||
<p class="text-sm text-slate-700 font-mono" x-text="detailUser?.documento"></p>
|
||||
</div>
|
||||
<div x-show="detailUser?.telegram_chat_id" class="col-span-2">
|
||||
<p class="label">Telegram Chat ID</p>
|
||||
<p class="text-sm text-slate-700 font-mono" x-text="detailUser?.telegram_chat_id"></p>
|
||||
</div>
|
||||
<div x-show="detailUser?.notas" class="col-span-2">
|
||||
<p class="label">Notas</p>
|
||||
<p class="text-sm text-slate-500 whitespace-pre-wrap" x-text="detailUser?.notas"></p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Documento RUT (archivo) -->
|
||||
<div x-show="detailUser?.documento_rut_file" class="pt-3 border-t border-slate-100">
|
||||
<p class="label">Documento RUT / Cámara de comercio</p>
|
||||
<div class="flex items-center gap-2 mt-1">
|
||||
<svg class="w-4 h-4 text-slate-400 flex-shrink-0" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/></svg>
|
||||
<span class="text-sm text-slate-600 truncate" x-text="detailUser?.documento_rut_nombre || 'Archivo RUT'"></span>
|
||||
<a :href="`/app/portal-usuarios/${detailUser?.ID}/rut-file`" target="_blank"
|
||||
class="text-[#8eb02f] text-xs font-semibold hover:underline flex-shrink-0">Descargar</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Accesos partner -->
|
||||
<div x-show="detailUser?.rol==='partner'" class="pt-3 border-t border-slate-100">
|
||||
<p class="label">Accesos de cliente</p>
|
||||
<div class="flex flex-wrap gap-1 mt-1">
|
||||
<template x-for="acc in (detailUser?.portal_accesos || [])" :key="acc.ID">
|
||||
<span class="bg-slate-100 text-slate-600 px-2 py-0.5 rounded text-xs"
|
||||
x-text="acc.cliente?.empresa || acc.cliente?.nombre || acc.cliente_id"></span>
|
||||
</template>
|
||||
<span x-show="!(detailUser?.portal_accesos?.length)" class="text-slate-400 text-xs">Sin accesos asignados</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Fecha de registro -->
|
||||
<div class="pt-3 border-t border-slate-100 text-xs text-slate-400">
|
||||
Registrado: <span x-text="detailUser?.CreatedAt ? new Date(detailUser.CreatedAt).toLocaleDateString('es-CO', {year:'numeric',month:'long',day:'numeric'}) : '—'"></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Footer -->
|
||||
<div x-show="detailUser && !loadingDetail" class="flex-shrink-0 px-5 py-4 border-t border-slate-200 bg-slate-50 flex gap-2">
|
||||
<button @click="openEdit(detailUser); showDetail=false;" class="btn-secondary flex-1">Editar</button>
|
||||
<button @click="showDetail=false" class="btn-primary flex-1">Cerrar</button>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<script>
|
||||
@@ -154,6 +267,7 @@ function portalUsuariosApp() {
|
||||
return {
|
||||
items: [], clientes: [], loading: false, saving: false,
|
||||
showModal: false, showDelete: false, showAccesoModal: false,
|
||||
showDetail: false, detailUser: null, loadingDetail: false,
|
||||
editId: null, deleteId: null, error: '',
|
||||
accesoUserId: null, accesoClienteId: '',
|
||||
form: { nombre:'', email:'', password:'', rol:'cliente', cliente_id:'', activo:true, notas:'', telegram_chat_id:'' },
|
||||
@@ -169,6 +283,20 @@ function portalUsuariosApp() {
|
||||
} finally { this.loading = false; }
|
||||
},
|
||||
|
||||
async openDetail(u) {
|
||||
this.detailUser = null;
|
||||
this.loadingDetail = true;
|
||||
this.showDetail = true;
|
||||
try {
|
||||
const r = await axios.get(`/app/loadportalusuarios/${u.ID}`);
|
||||
this.detailUser = r.data;
|
||||
} catch(e) {
|
||||
this.showDetail = false;
|
||||
} finally {
|
||||
this.loadingDetail = false;
|
||||
}
|
||||
},
|
||||
|
||||
openCreate() {
|
||||
this.editId=null; this.error='';
|
||||
this.form={nombre:'',email:'',password:'',rol:'cliente',cliente_id:'',activo:true,notas:'',telegram_chat_id:''};
|
||||
|
||||
@@ -3,6 +3,8 @@ package controllers
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
@@ -406,14 +408,16 @@ func PortalGetMiPerfil(c *fiber.Ctx) error {
|
||||
return c.Status(500).JSON(fiber.Map{"error": "error al obtener perfil"})
|
||||
}
|
||||
return c.JSON(fiber.Map{
|
||||
"id": full.ID,
|
||||
"nombre": full.Nombre,
|
||||
"email": full.Email,
|
||||
"telefono": full.Telefono,
|
||||
"indicativo": full.Indicativo,
|
||||
"pais": full.Pais,
|
||||
"documento": full.Documento,
|
||||
"empresa": full.Empresa,
|
||||
"id": full.ID,
|
||||
"nombre": full.Nombre,
|
||||
"email": full.Email,
|
||||
"telefono": full.Telefono,
|
||||
"indicativo": full.Indicativo,
|
||||
"pais": full.Pais,
|
||||
"documento": full.Documento,
|
||||
"empresa": full.Empresa,
|
||||
"documento_rut_file": full.DocumentoRutFile,
|
||||
"documento_rut_nombre": full.DocumentoRutNombre,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -506,3 +510,147 @@ func PortalCambiarPassword(c *fiber.Ctx) error {
|
||||
}
|
||||
return c.JSON(fiber.Map{"ok": true})
|
||||
}
|
||||
|
||||
// POST /portal/mi-perfil/rut-file — sube el documento RUT del usuario autenticado
|
||||
func PortalSubirRutDocumento(c *fiber.Ctx) error {
|
||||
u := middlewares.PortalUserFromLocals(c)
|
||||
if u == nil {
|
||||
return c.Status(401).JSON(fiber.Map{"error": "no autenticado"})
|
||||
}
|
||||
file, err := c.FormFile("rut_file")
|
||||
if err != nil {
|
||||
return c.Status(400).JSON(fiber.Map{"error": "Archivo requerido"})
|
||||
}
|
||||
if file.Size > 10*1024*1024 {
|
||||
return c.Status(400).JSON(fiber.Map{"error": "Máximo 10 MB"})
|
||||
}
|
||||
ext := strings.ToLower(filepath.Ext(file.Filename))
|
||||
allowed := map[string]bool{".pdf": true, ".jpg": true, ".jpeg": true, ".png": true, ".webp": true}
|
||||
if !allowed[ext] {
|
||||
return c.Status(400).JSON(fiber.Map{"error": "Solo se permiten PDF, JPG, PNG o WEBP"})
|
||||
}
|
||||
dir := fmt.Sprintf("uploads/portal_users/%d", u.ID)
|
||||
if err := os.MkdirAll(dir, 0755); err != nil {
|
||||
return c.Status(500).JSON(fiber.Map{"error": "Error al crear directorio"})
|
||||
}
|
||||
savePath := filepath.Join(dir, "rut"+ext)
|
||||
if err := c.SaveFile(file, savePath); err != nil {
|
||||
return c.Status(500).JSON(fiber.Map{"error": "Error al guardar archivo"})
|
||||
}
|
||||
if err := models.UpdatePortalUserRutFile(u.ID, savePath, file.Filename); err != nil {
|
||||
return c.Status(500).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
return c.JSON(fiber.Map{"ok": true, "nombre": file.Filename})
|
||||
}
|
||||
|
||||
// ─── Telegram portal ──────────────────────────────────────────────────────────
|
||||
|
||||
// PortalTelegramInit genera un código de vinculación temporal para el usuario del portal.
|
||||
func PortalTelegramInit(c *fiber.Ctx) error {
|
||||
u := middlewares.PortalUserFromLocals(c)
|
||||
if u == nil {
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "No autenticado"})
|
||||
}
|
||||
token, err := models.GenerateTelegramPortalToken(u.ID)
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "No se pudo generar el código"})
|
||||
}
|
||||
|
||||
// Obtener username del bot desde el primer TelegramConfig activo
|
||||
configs, _ := models.GetAllTelegramConfigs()
|
||||
botToken := ""
|
||||
for _, cfg := range configs {
|
||||
if cfg.Activo && cfg.BotToken != "" {
|
||||
botToken = cfg.BotToken
|
||||
break
|
||||
}
|
||||
}
|
||||
botUsername := services.GetBotUsername(botToken)
|
||||
|
||||
return c.JSON(fiber.Map{
|
||||
"token": token.Token,
|
||||
"bot_username": botUsername,
|
||||
"bot_link": "https://t.me/" + botUsername,
|
||||
})
|
||||
}
|
||||
|
||||
// PortalTelegramStatus devuelve si el usuario del portal tiene Telegram vinculado.
|
||||
func PortalTelegramStatus(c *fiber.Ctx) error {
|
||||
u := middlewares.PortalUserFromLocals(c)
|
||||
if u == nil {
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "No autenticado"})
|
||||
}
|
||||
full, err := models.GetPortalUserByID(u.ID)
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
return c.JSON(fiber.Map{
|
||||
"linked": full.TelegramChatID != "",
|
||||
"chat_id": full.TelegramChatID,
|
||||
})
|
||||
}
|
||||
|
||||
// TelegramPortalWebhook recibe actualizaciones del bot de Telegram y vincula el chat_id
|
||||
// al usuario del portal que envió el código de verificación.
|
||||
// Este endpoint debe estar registrado como webhook en el bot: POST /setWebhook?url=.../webhooks/telegram-portal
|
||||
func TelegramPortalWebhook(c *fiber.Ctx) error {
|
||||
var update struct {
|
||||
Message struct {
|
||||
Chat struct {
|
||||
ID int64 `json:"id"`
|
||||
} `json:"chat"`
|
||||
Text string `json:"text"`
|
||||
} `json:"message"`
|
||||
}
|
||||
if err := c.BodyParser(&update); err != nil {
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
}
|
||||
|
||||
chatID := update.Message.Chat.ID
|
||||
text := strings.TrimSpace(update.Message.Text)
|
||||
if chatID == 0 || text == "" {
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
}
|
||||
|
||||
// Buscar token en el texto: 6 caracteres hex mayúsculas
|
||||
// Acepta "/vincular A3F9B2" o solo "A3F9B2"
|
||||
var token string
|
||||
for _, part := range strings.Fields(text) {
|
||||
candidate := strings.ToUpper(strings.TrimPrefix(strings.TrimPrefix(part, "/vincular"), "/VINCULAR"))
|
||||
candidate = strings.TrimSpace(candidate)
|
||||
if len(candidate) == 6 {
|
||||
token = candidate
|
||||
break
|
||||
}
|
||||
}
|
||||
if token == "" {
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
}
|
||||
|
||||
t, err := models.FindTelegramPortalToken(token)
|
||||
if err != nil {
|
||||
portalTelegramReply(chatID, "❌ Código inválido o expirado. Genera un nuevo código desde el portal.")
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
}
|
||||
|
||||
if err := models.UpdatePortalUserTelegramChatID(t.PortalUserID, fmt.Sprintf("%d", chatID)); err != nil {
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
}
|
||||
models.DeleteTelegramPortalToken(t.PortalUserID)
|
||||
|
||||
portalTelegramReply(chatID, "✅ ¡Tu Telegram ha sido vinculado al portal correctamente!\n\nRecibirás notificaciones importantes por este medio.")
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
}
|
||||
|
||||
// portalTelegramReply envía un mensaje usando el primer bot activo configurado.
|
||||
func portalTelegramReply(chatID int64, text string) {
|
||||
configs, _ := models.GetAllTelegramConfigs()
|
||||
for _, cfg := range configs {
|
||||
if cfg.Activo && cfg.BotToken != "" {
|
||||
svc := &services.TelegramService{BotToken: cfg.BotToken}
|
||||
_ = svc.SendMessage(chatID, text)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -208,3 +208,32 @@ func SendPortalCredentials(c *fiber.Ctx) error {
|
||||
services.SendPortalCredentialsEmail(u.Email, u.Nombre, password)
|
||||
return c.JSON(fiber.Map{"ok": true, "message": "Correo enviado a " + u.Email})
|
||||
}
|
||||
|
||||
// GetPortalUsuarioDetail devuelve todos los campos de un portal_user para el panel de detalle.
|
||||
func GetPortalUsuarioDetail(c *fiber.Ctx) error {
|
||||
id, err := strconv.ParseUint(c.Params("id"), 10, 32)
|
||||
if err != nil {
|
||||
return c.Status(400).JSON(fiber.Map{"error": "ID inválido"})
|
||||
}
|
||||
u, err := models.GetPortalUserByID(uint(id))
|
||||
if err != nil {
|
||||
return c.Status(404).JSON(fiber.Map{"error": "Usuario no encontrado"})
|
||||
}
|
||||
return c.JSON(u)
|
||||
}
|
||||
|
||||
// PortalUsuarioRutFile sirve el archivo RUT/documento del portal user al admin.
|
||||
func PortalUsuarioRutFile(c *fiber.Ctx) error {
|
||||
id, err := strconv.ParseUint(c.Params("id"), 10, 32)
|
||||
if err != nil {
|
||||
return c.Status(400).JSON(fiber.Map{"error": "ID inválido"})
|
||||
}
|
||||
u, err := models.GetPortalUserByID(uint(id))
|
||||
if err != nil {
|
||||
return c.Status(404).JSON(fiber.Map{"error": "Usuario no encontrado"})
|
||||
}
|
||||
if u.DocumentoRutFile == "" {
|
||||
return c.Status(404).JSON(fiber.Map{"error": "Este usuario no tiene archivo RUT"})
|
||||
}
|
||||
return c.SendFile(u.DocumentoRutFile)
|
||||
}
|
||||
|
||||
@@ -45,4 +45,9 @@ func PortalRoutes(app fiber.Router) {
|
||||
portal.Get("/mi-perfil", controllers.PortalGetMiPerfil)
|
||||
portal.Put("/mi-perfil", controllers.PortalUpdateMiPerfil)
|
||||
portal.Put("/mi-perfil/password", controllers.PortalCambiarPassword)
|
||||
portal.Post("/mi-perfil/rut-file", controllers.PortalSubirRutDocumento)
|
||||
|
||||
// Telegram: vinculación guiada
|
||||
portal.Post("/mi-perfil/telegram-init", controllers.PortalTelegramInit)
|
||||
portal.Get("/mi-perfil/telegram-status", controllers.PortalTelegramStatus)
|
||||
}
|
||||
|
||||
@@ -28,7 +28,9 @@ func RutasPublicas(web fiber.Router) {
|
||||
// ─── Documentación pública ────────────────────────────────────────────────
|
||||
web.Get("/docs/:saas", controllers.DocsPublicoIndex)
|
||||
web.Get("/docs/:saas/:slug", controllers.DocsPublicaPagina)
|
||||
|
||||
// ─── Webhook de Telegram para vinculación del portal ──────────────────────
|
||||
// Configurar en el bot: POST https://api.telegram.org/bot{TOKEN}/setWebhook?url={HOST}/webhooks/telegram-portal
|
||||
web.Post("/webhooks/telegram-portal", controllers.TelegramPortalWebhook)
|
||||
// ─── Página de estado del sistema (Atlassian Statuspage) ────────────────
|
||||
web.Get("/status", controllers.StatusPage)
|
||||
}
|
||||
|
||||
+6
-1
@@ -16,7 +16,10 @@ func UserRoutes(app fiber.Router) {
|
||||
middlewares.LoadUserMiddleware, // Middleware para cargar el usuario
|
||||
)
|
||||
|
||||
// Rutas de la aplicación
|
||||
// Perfil del usuario autenticado
|
||||
protected.Get("/profile", middlewares.MenuMiddleware, controllers.Profile)
|
||||
|
||||
// Rutas de la aplicación
|
||||
|
||||
// web me redireccione a /
|
||||
protected.Get("/web", func(c *fiber.Ctx) error { return c.Redirect("/", http.StatusSeeOther) })
|
||||
@@ -249,9 +252,11 @@ func UserRoutes(app fiber.Router) {
|
||||
|
||||
protected.Get("/portal-usuarios", middlewares.MenuMiddleware, controllers.PortalUsuariosIndex)
|
||||
protected.Get("/loadportalusuarios", controllers.LoadPortalUsuarios)
|
||||
protected.Get("/loadportalusuarios/:id", controllers.GetPortalUsuarioDetail)
|
||||
protected.Post("/portal-usuarios", controllers.CreatePortalUsuario)
|
||||
protected.Put("/portal-usuarios/:id", controllers.UpdatePortalUsuario)
|
||||
protected.Delete("/portal-usuarios/:id", controllers.DeletePortalUsuario)
|
||||
protected.Get("/portal-usuarios/:id/rut-file", controllers.PortalUsuarioRutFile)
|
||||
protected.Post("/portal-usuarios/:id/acceso", controllers.AddPortalAcceso)
|
||||
protected.Delete("/portal-usuarios/:id/acceso/:clienteID", controllers.RemovePortalAcceso)
|
||||
protected.Post("/portal-usuarios/:id/send-credentials", controllers.SendPortalCredentials)
|
||||
|
||||
Reference in New Issue
Block a user