up
This commit is contained in:
@@ -67,6 +67,11 @@ func Migrate() {
|
||||
// Integraciones SaaS (dispatcher de pagos)
|
||||
&models.SaasApiConfig{},
|
||||
&models.SaasDispatchLog{},
|
||||
// Documentos de clientes
|
||||
&models.ClienteDocumento{},
|
||||
// Telegram
|
||||
&models.TelegramConfig{},
|
||||
&models.TelegramLog{},
|
||||
); err != nil {
|
||||
log.Fatalf("Error during main migration: %v", err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/sujit-baniya/fiber-boilerplate/app"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// ClienteDocumento almacena los archivos adjuntos de un cliente.
|
||||
type ClienteDocumento struct {
|
||||
gorm.Model
|
||||
ClienteID uint `json:"cliente_id" gorm:"column:cliente_id;not null;index"`
|
||||
Nombre string `json:"nombre" gorm:"column:nombre"` // nombre descriptivo del doc
|
||||
Archivo string `json:"archivo" gorm:"column:archivo"` // ruta relativa en disco
|
||||
OriginalName string `json:"original_name" gorm:"column:original_name"` // nombre original del archivo
|
||||
TipoMime string `json:"tipo_mime" gorm:"column:tipo_mime"`
|
||||
Tamanio int64 `json:"tamanio" gorm:"column:tamanio"` // bytes
|
||||
FechaExpedicion *time.Time `json:"fecha_expedicion" gorm:"column:fecha_expedicion"` // opcional
|
||||
}
|
||||
|
||||
func (ClienteDocumento) TableName() string { return "cliente_documentos" }
|
||||
|
||||
func GetDocumentosByCliente(clienteID uint) ([]ClienteDocumento, error) {
|
||||
var items []ClienteDocumento
|
||||
err := app.Http.Database.DB.
|
||||
Where("cliente_id = ?", clienteID).
|
||||
Order("created_at DESC").
|
||||
Find(&items).Error
|
||||
return items, err
|
||||
}
|
||||
|
||||
func CreateClienteDocumento(d *ClienteDocumento) error {
|
||||
return app.Http.Database.DB.Create(d).Error
|
||||
}
|
||||
|
||||
func GetClienteDocumentoByID(id uint) (*ClienteDocumento, error) {
|
||||
var d ClienteDocumento
|
||||
if err := app.Http.Database.DB.First(&d, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &d, nil
|
||||
}
|
||||
|
||||
func DeleteClienteDocumento(id uint) error {
|
||||
return app.Http.Database.DB.Delete(&ClienteDocumento{}, id).Error
|
||||
}
|
||||
@@ -16,6 +16,7 @@ type Contrato struct {
|
||||
FechaInicio time.Time `json:"fecha_inicio" gorm:"column:fecha_inicio"`
|
||||
FechaVencimiento time.Time `json:"fecha_vencimiento" gorm:"column:fecha_vencimiento"`
|
||||
PrecioAcordado float64 `json:"precio_acordado" gorm:"column:precio_acordado"`
|
||||
Moneda string `json:"moneda" gorm:"column:moneda;default:'COP'"`
|
||||
Estado string `json:"estado" gorm:"column:estado;default:'activo'"` // activo | vencido | cancelado | renovado
|
||||
AutoRenovar bool `json:"auto_renovar" gorm:"column:auto_renovar;default:false"`
|
||||
Notas string `json:"notas" gorm:"column:notas"`
|
||||
@@ -160,6 +161,7 @@ func UpdateContrato(c Contrato, servicioIDs []uint) error {
|
||||
"fecha_inicio": c.FechaInicio,
|
||||
"fecha_vencimiento": c.FechaVencimiento,
|
||||
"precio_acordado": c.PrecioAcordado,
|
||||
"moneda": c.Moneda,
|
||||
"estado": c.Estado,
|
||||
"auto_renovar": c.AutoRenovar,
|
||||
"notas": c.Notas,
|
||||
|
||||
@@ -17,6 +17,7 @@ type SaasProducto struct {
|
||||
Servicio *Servicio `json:"servicio" gorm:"foreignKey:ServicioID"`
|
||||
Activo bool `json:"activo" gorm:"column:activo;default:true"`
|
||||
Orden int `json:"orden" gorm:"column:orden;default:0"`
|
||||
HealthURL string `json:"health_url" gorm:"column:health_url"` // URL para health check (opcional)
|
||||
}
|
||||
|
||||
func (SaasProducto) TableName() string { return "saas_productos" }
|
||||
@@ -74,6 +75,7 @@ func UpdateSaasProducto(s *SaasProducto) error {
|
||||
"servicio_id": s.ServicioID,
|
||||
"activo": s.Activo,
|
||||
"orden": s.Orden,
|
||||
"health_url": s.HealthURL,
|
||||
}).Error
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"github.com/sujit-baniya/fiber-boilerplate/app"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// TelegramConfig almacena un bot configurado con su chat_id de destino.
|
||||
type TelegramConfig struct {
|
||||
gorm.Model
|
||||
Nombre string `json:"nombre" gorm:"column:nombre;not null"`
|
||||
BotToken string `json:"bot_token" gorm:"column:bot_token;type:text;not null"`
|
||||
ChatID string `json:"chat_id" gorm:"column:chat_id;not null"` // puede ser número o @canal
|
||||
Activo bool `json:"activo" gorm:"column:activo;default:true"`
|
||||
Notas string `json:"notas" gorm:"column:notas;type:text"`
|
||||
}
|
||||
|
||||
func (TelegramConfig) TableName() string { return "telegram_configs" }
|
||||
|
||||
// TelegramLog registra cada mensaje enviado.
|
||||
type TelegramLog struct {
|
||||
gorm.Model
|
||||
TelegramConfigID uint `json:"telegram_config_id" gorm:"column:telegram_config_id;index"`
|
||||
TelegramConfig TelegramConfig `json:"telegram_config" gorm:"foreignKey:TelegramConfigID"`
|
||||
Titulo string `json:"titulo" gorm:"column:titulo"`
|
||||
Mensaje string `json:"mensaje" gorm:"column:mensaje;type:text"`
|
||||
Estado string `json:"estado" gorm:"column:estado"` // ok | failed
|
||||
ErrorMsg string `json:"error_msg" gorm:"column:error_msg;type:text"`
|
||||
}
|
||||
|
||||
func (TelegramLog) TableName() string { return "telegram_logs" }
|
||||
|
||||
// ─── Queries ──────────────────────────────────────────────────────────────────
|
||||
|
||||
func GetAllTelegramConfigs() ([]TelegramConfig, error) {
|
||||
var items []TelegramConfig
|
||||
err := app.Http.Database.DB.Order("created_at DESC").Find(&items).Error
|
||||
return items, err
|
||||
}
|
||||
|
||||
func GetTelegramConfigByID(id uint) (*TelegramConfig, error) {
|
||||
var item TelegramConfig
|
||||
err := app.Http.Database.DB.First(&item, id).Error
|
||||
return &item, err
|
||||
}
|
||||
|
||||
func CreateTelegramConfig(c *TelegramConfig) error {
|
||||
return app.Http.Database.DB.Create(c).Error
|
||||
}
|
||||
|
||||
func UpdateTelegramConfig(c *TelegramConfig) error {
|
||||
return app.Http.Database.DB.Model(&TelegramConfig{}).Where("id = ?", c.ID).Updates(map[string]interface{}{
|
||||
"nombre": c.Nombre,
|
||||
"bot_token": c.BotToken,
|
||||
"chat_id": c.ChatID,
|
||||
"activo": c.Activo,
|
||||
"notas": c.Notas,
|
||||
}).Error
|
||||
}
|
||||
|
||||
func DeleteTelegramConfig(id uint) error {
|
||||
return app.Http.Database.DB.Delete(&TelegramConfig{}, id).Error
|
||||
}
|
||||
|
||||
func GetTelegramLogs(limit, offset int) ([]TelegramLog, int64, error) {
|
||||
var items []TelegramLog
|
||||
var total int64
|
||||
db := app.Http.Database.DB.Model(&TelegramLog{}).Preload("TelegramConfig")
|
||||
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 CreateTelegramLog(l *TelegramLog) error {
|
||||
return app.Http.Database.DB.Create(l).Error
|
||||
}
|
||||
@@ -25,7 +25,7 @@
|
||||
<th class="py-2 px-3">Email</th>
|
||||
<th class="py-2 px-3">Teléfono</th>
|
||||
<th class="py-2 px-3">Estado</th>
|
||||
<th class="py-2 px-3 w-24"></th>
|
||||
<th class="py-2 px-3 w-32"></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody class="text-gray-600">
|
||||
@@ -40,10 +40,13 @@
|
||||
</td>
|
||||
<td class="py-2 px-3">
|
||||
<div class="flex gap-2">
|
||||
<button @click="openEdit(d)" class="text-gray-400 hover:text-[#8eb02f]">
|
||||
<button @click="openDocs(d)" title="Documentos" class="text-gray-400 hover:text-blue-500">
|
||||
<svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M18.375 12.739l-7.693 7.693a4.5 4.5 0 0 1-6.364-6.364l10.94-10.94A3 3 0 1 1 19.5 7.372L8.552 18.32m.009-.01-.01.01m5.699-9.941-7.81 7.81a1.5 1.5 0 0 0 2.112 2.13"/></svg>
|
||||
</button>
|
||||
<button @click="openEdit(d)" title="Editar" class="text-gray-400 hover:text-[#8eb02f]">
|
||||
<svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="m16.862 4.487 1.687-1.688a1.875 1.875 0 1 1 2.652 2.652L10.582 16.07a4.5 4.5 0 0 1-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 0 1 1.13-1.897l8.932-8.931Zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0 1 15.75 21H5.25A2.25 2.25 0 0 1 3 18.75V8.25A2.25 2.25 0 0 1 5.25 6H10"/></svg>
|
||||
</button>
|
||||
<button @click="openDelete(d)" class="text-gray-400 hover:text-red-500">
|
||||
<button @click="openDelete(d)" title="Eliminar" class="text-gray-400 hover:text-red-500">
|
||||
<svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 0 1-2.244 2.077H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 0 0-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 0 0-7.5 0"/></svg>
|
||||
</button>
|
||||
</div>
|
||||
@@ -129,6 +132,120 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ─── Modal Documentos ──────────────────────────────────────────────── -->
|
||||
<div x-show="docsModal" x-cloak class="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
|
||||
<div class="bg-white rounded-lg shadow-xl w-full max-w-2xl mx-4 flex flex-col max-h-[90vh]" @click.stop>
|
||||
<!-- Header -->
|
||||
<div class="flex items-center justify-between px-6 py-4 border-b">
|
||||
<div>
|
||||
<h2 class="text-lg font-semibold">Documentos</h2>
|
||||
<p class="text-xs text-gray-400" x-text="'Cliente: ' + (docsCliente?.nombre || '')"></p>
|
||||
</div>
|
||||
<button @click="docsModal=false" class="text-gray-400 hover:text-gray-600">
|
||||
<svg class="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18 18 6M6 6l12 12"/></svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Cuerpo scrollable -->
|
||||
<div class="overflow-y-auto flex-1 px-6 py-4 space-y-4">
|
||||
|
||||
<!-- Formulario de subida -->
|
||||
<div class="border rounded-lg p-4 bg-gray-50">
|
||||
<p class="text-sm font-medium text-gray-700 mb-3">Subir documentos</p>
|
||||
|
||||
<!-- Fecha de expedición compartida -->
|
||||
<div class="mb-3">
|
||||
<label class="text-xs font-medium text-gray-600">Fecha de expedición (opcional, aplica a todos los archivos)</label>
|
||||
<input type="date" x-model="docsUpload.fechaExpedicion"
|
||||
class="mt-1 w-full border rounded px-3 py-2 text-sm" />
|
||||
</div>
|
||||
|
||||
<!-- Zona de arrastre / selección de archivos -->
|
||||
<div class="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center cursor-pointer hover:border-[#8eb02f] transition-colors"
|
||||
@click="$refs.fileInput.click()"
|
||||
@dragover.prevent
|
||||
@drop.prevent="handleDrop($event)">
|
||||
<svg class="w-8 h-8 mx-auto text-gray-400 mb-2" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M3 16.5v2.25A2.25 2.25 0 0 0 5.25 21h13.5A2.25 2.25 0 0 0 21 18.75V16.5m-13.5-9L12 3m0 0 4.5 4.5M12 3v13.5"/></svg>
|
||||
<p class="text-sm text-gray-500">Haz clic o arrastra archivos aquí</p>
|
||||
<p class="text-xs text-gray-400 mt-1">PDF, Word, Excel, imágenes, ZIP — máx. 20 MB c/u</p>
|
||||
<input type="file" x-ref="fileInput" multiple class="hidden"
|
||||
@change="addFiles($event.target.files)" />
|
||||
</div>
|
||||
|
||||
<!-- Lista de archivos pendientes -->
|
||||
<template x-if="docsUpload.files.length > 0">
|
||||
<div class="mt-3 space-y-2">
|
||||
<template x-for="(f, i) in docsUpload.files" :key="i">
|
||||
<div class="flex items-center gap-3 bg-white border rounded px-3 py-2 text-sm">
|
||||
<svg class="w-4 h-4 text-gray-400 shrink-0" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M19.5 14.25v-2.625a3.375 3.375 0 0 0-3.375-3.375h-1.5A1.125 1.125 0 0 1 13.5 7.125v-1.5a3.375 3.375 0 0 0-3.375-3.375H8.25m2.25 0H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 0 0-9-9Z"/></svg>
|
||||
<span class="flex-1 truncate" x-text="f.name"></span>
|
||||
<span class="text-gray-400 text-xs" x-text="formatSize(f.size)"></span>
|
||||
<button @click="removeFile(i)" class="text-red-400 hover:text-red-600">
|
||||
<svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18 18 6M6 6l12 12"/></svg>
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
<button @click="uploadDocs()" :disabled="docsUploading"
|
||||
class="w-full mt-2 bg-[#8eb02f] text-white py-2 rounded text-sm font-medium disabled:opacity-50">
|
||||
<span x-text="docsUploading ? 'Subiendo…' : 'Subir ' + docsUpload.files.length + ' archivo(s)'"></span>
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<!-- Lista de documentos guardados -->
|
||||
<div>
|
||||
<p class="text-sm font-medium text-gray-700 mb-2">Documentos guardados
|
||||
<span class="text-gray-400 font-normal" x-text="'(' + documentos.length + ')'"></span>
|
||||
</p>
|
||||
|
||||
<div x-show="docsLoading" class="text-center text-gray-400 text-sm py-4">Cargando…</div>
|
||||
|
||||
<div x-show="!docsLoading && documentos.length === 0" class="text-center text-gray-400 text-sm py-4">
|
||||
Sin documentos
|
||||
</div>
|
||||
|
||||
<div class="space-y-2">
|
||||
<template x-for="doc in documentos" :key="doc.ID">
|
||||
<div class="flex items-center gap-3 border rounded px-3 py-2 text-sm hover:bg-gray-50">
|
||||
<svg class="w-4 h-4 text-blue-400 shrink-0" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M19.5 14.25v-2.625a3.375 3.375 0 0 0-3.375-3.375h-1.5A1.125 1.125 0 0 1 13.5 7.125v-1.5a3.375 3.375 0 0 0-3.375-3.375H8.25m2.25 0H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 0 0-9-9Z"/></svg>
|
||||
<div class="flex-1 min-w-0">
|
||||
<p class="font-medium truncate" x-text="doc.nombre || doc.original_name"></p>
|
||||
<p class="text-xs text-gray-400">
|
||||
<span x-text="formatSize(doc.tamanio)"></span>
|
||||
<template x-if="doc.fecha_expedicion">
|
||||
<span> · Exp: <span x-text="fmtDate(doc.fecha_expedicion)"></span></span>
|
||||
</template>
|
||||
</p>
|
||||
</div>
|
||||
<a :href="`/app/api/clientes/${docsCliente.ID}/documentos/${doc.ID}/download`"
|
||||
target="_blank"
|
||||
class="text-gray-400 hover:text-blue-500" title="Descargar">
|
||||
<svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M3 16.5v2.25A2.25 2.25 0 0 0 5.25 21h13.5A2.25 2.25 0 0 0 21 18.75V16.5M16.5 12 12 16.5m0 0L7.5 12m4.5 4.5V3"/></svg>
|
||||
</a>
|
||||
<button @click="confirmDeleteDoc(doc)" class="text-gray-400 hover:text-red-500" title="Eliminar">
|
||||
<svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 0 1-2.244 2.077H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 0 0-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 0 0-7.5 0"/></svg>
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Confirm eliminar documento -->
|
||||
<div x-show="deleteDocModal" x-cloak class="fixed inset-0 z-[60] flex items-center justify-center bg-black/50">
|
||||
<div class="bg-white rounded-lg shadow-xl p-6 w-full max-w-sm mx-4 text-center" @click.stop>
|
||||
<p class="font-semibold mb-1">¿Eliminar documento?</p>
|
||||
<p class="text-sm text-gray-400 mb-5" x-text="selectedDoc?.nombre || selectedDoc?.original_name"></p>
|
||||
<div class="flex justify-center gap-3">
|
||||
<button @click="deleteDocModal=false" class="px-4 py-2 border rounded text-sm">Cancelar</button>
|
||||
<button @click="deleteDoc()" class="px-4 py-2 bg-red-500 text-white rounded text-sm">Eliminar</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div x-show="toast.show" x-cloak x-transition
|
||||
class="fixed bottom-4 right-4 z-[100] px-4 py-3 rounded shadow-lg text-sm text-white"
|
||||
:class="toast.type==='error' ? 'bg-red-500' : 'bg-[#8eb02f]'"
|
||||
@@ -146,6 +263,16 @@ document.addEventListener('alpine:init', () => {
|
||||
form: { nombre:'', empresa:'', email:'', email_cc:'', telefono:'', documento:'', notas:'', activo:true },
|
||||
toast: { show: false, msg: '', type: 'ok' },
|
||||
|
||||
// ── Documentos ──────────────────────────────────────────────────────
|
||||
docsModal: false,
|
||||
docsCliente: null,
|
||||
documentos: [],
|
||||
docsLoading: false,
|
||||
docsUploading: false,
|
||||
docsUpload: { fechaExpedicion: '', files: [] },
|
||||
deleteDocModal: false,
|
||||
selectedDoc: null,
|
||||
|
||||
async init() { await this.loadData(); },
|
||||
|
||||
async loadData() {
|
||||
@@ -201,7 +328,96 @@ document.addEventListener('alpine:init', () => {
|
||||
showToast(msg, type='ok') {
|
||||
this.toast = { show: true, msg, type };
|
||||
setTimeout(() => this.toast.show = false, 3000);
|
||||
}
|
||||
},
|
||||
|
||||
// ── Documentos: métodos ─────────────────────────────────────────────
|
||||
async openDocs(d) {
|
||||
this.docsCliente = d;
|
||||
this.docsModal = true;
|
||||
this.docsUpload = { fechaExpedicion: '', files: [] };
|
||||
await this.loadDocs();
|
||||
},
|
||||
|
||||
async loadDocs() {
|
||||
this.docsLoading = true;
|
||||
try {
|
||||
const { data } = await axios.get(`/app/api/clientes/${this.docsCliente.ID}/documentos`);
|
||||
this.documentos = data || [];
|
||||
} catch(e) {
|
||||
this.showToast('Error cargando documentos', 'error');
|
||||
}
|
||||
this.docsLoading = false;
|
||||
},
|
||||
|
||||
addFiles(fileList) {
|
||||
for (const f of fileList) {
|
||||
if (!this.docsUpload.files.find(x => x.name === f.name && x.size === f.size)) {
|
||||
this.docsUpload.files.push(f);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
handleDrop(event) {
|
||||
this.addFiles(event.dataTransfer.files);
|
||||
},
|
||||
|
||||
removeFile(i) {
|
||||
this.docsUpload.files.splice(i, 1);
|
||||
},
|
||||
|
||||
async uploadDocs() {
|
||||
if (this.docsUpload.files.length === 0) return;
|
||||
this.docsUploading = true;
|
||||
try {
|
||||
const fd = new FormData();
|
||||
for (const f of this.docsUpload.files) {
|
||||
fd.append('archivos', f);
|
||||
}
|
||||
if (this.docsUpload.fechaExpedicion) {
|
||||
fd.append('fecha_expedicion', this.docsUpload.fechaExpedicion);
|
||||
}
|
||||
await axios.post(`/app/api/clientes/${this.docsCliente.ID}/documentos`, fd, {
|
||||
headers: { 'Content-Type': 'multipart/form-data' }
|
||||
});
|
||||
this.showToast('Archivos subidos correctamente');
|
||||
this.docsUpload.files = [];
|
||||
this.docsUpload.fechaExpedicion = '';
|
||||
this.$refs.fileInput && (this.$refs.fileInput.value = '');
|
||||
await this.loadDocs();
|
||||
} catch(e) {
|
||||
this.showToast(e.response?.data?.error || 'Error al subir', 'error');
|
||||
}
|
||||
this.docsUploading = false;
|
||||
},
|
||||
|
||||
confirmDeleteDoc(doc) {
|
||||
this.selectedDoc = doc;
|
||||
this.deleteDocModal = true;
|
||||
},
|
||||
|
||||
async deleteDoc() {
|
||||
try {
|
||||
await axios.delete(`/app/api/clientes/${this.docsCliente.ID}/documentos/${this.selectedDoc.ID}`);
|
||||
this.showToast('Documento eliminado');
|
||||
this.deleteDocModal = false;
|
||||
this.selectedDoc = null;
|
||||
await this.loadDocs();
|
||||
} catch(e) {
|
||||
this.showToast(e.response?.data?.error || 'Error al eliminar', 'error');
|
||||
}
|
||||
},
|
||||
|
||||
formatSize(bytes) {
|
||||
if (!bytes) return '0 B';
|
||||
if (bytes < 1024) return bytes + ' B';
|
||||
if (bytes < 1024*1024) return (bytes/1024).toFixed(1) + ' KB';
|
||||
return (bytes/(1024*1024)).toFixed(1) + ' MB';
|
||||
},
|
||||
|
||||
fmtDate(iso) {
|
||||
if (!iso) return '';
|
||||
return iso.substring(0, 10);
|
||||
},
|
||||
}));
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -55,7 +55,7 @@
|
||||
:class="d.urgencia==='rojo' ? 'bg-red-100 text-red-700' : d.urgencia==='amarillo' ? 'bg-yellow-100 text-yellow-700' : 'bg-green-100 text-green-700'"
|
||||
x-text="d.dias_restantes <= 0 ? 'Vencido' : d.dias_restantes+' días'"></span>
|
||||
</td>
|
||||
<td class="py-2 px-3" x-text="Number(d.precio_acordado).toFixed(2)"></td>
|
||||
<td class="py-2 px-3" x-text="fmtPrecio(d.precio_acordado, d.moneda)"></td>
|
||||
<td class="py-2 px-3">
|
||||
<span class="px-2 py-0.5 rounded text-xs font-medium"
|
||||
:class="{
|
||||
@@ -161,9 +161,18 @@
|
||||
<label class="text-xs font-medium text-gray-600">Precio acordado</label>
|
||||
<input x-model="form.precio_acordado" type="number" step="0.01" class="mt-1 w-full border rounded px-3 py-2 text-sm" />
|
||||
<p class="text-xs text-gray-400 mt-0.5" x-show="precioSugerido > 0">
|
||||
Sugerido: <span class="font-medium text-gray-600" x-text="precioSugerido.toFixed(2)"></span>
|
||||
Sugerido: <span class="font-medium text-gray-600" x-text="fmtPrecio(precioSugerido, form.moneda)"></span>
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<label class="text-xs font-medium text-gray-600">Moneda</label>
|
||||
<select x-model="form.moneda" class="mt-1 w-full border rounded px-3 py-2 text-sm">
|
||||
<option value="COP">COP — Pesos colombianos</option>
|
||||
<option value="USD">USD — Dólares</option>
|
||||
<option value="MXN">MXN — Pesos mexicanos</option>
|
||||
<option value="EUR">EUR — Euros</option>
|
||||
</select>
|
||||
</div>
|
||||
<div x-show="editModal">
|
||||
<label class="text-xs font-medium text-gray-600">Estado</label>
|
||||
<select x-model="form.estado" class="mt-1 w-full border rounded px-3 py-2 text-sm">
|
||||
@@ -342,7 +351,7 @@ document.addEventListener('alpine:init', () => {
|
||||
clientes: [], servicios: [], reglas: [], reglasBienvenida: [],
|
||||
selectedId: null,
|
||||
verificandoID: null,
|
||||
form: { cliente_id:'', servicio_ids:[], fecha_inicio:'', fecha_vencimiento:'', precio_acordado:0, estado:'activo', auto_renovar:false, notas:'' },
|
||||
form: { cliente_id:'', servicio_ids:[], fecha_inicio:'', fecha_vencimiento:'', precio_acordado:0, moneda:'COP', estado:'activo', auto_renovar:false, notas:'' },
|
||||
toast: { show: false, msg: '', type: 'ok' },
|
||||
|
||||
async init() {
|
||||
@@ -398,6 +407,7 @@ document.addEventListener('alpine:init', () => {
|
||||
fecha_inicio: d.fecha_inicio ? d.fecha_inicio.substring(0,10) : '',
|
||||
fecha_vencimiento: d.fecha_vencimiento ? d.fecha_vencimiento.substring(0,10) : '',
|
||||
precio_acordado: d.precio_acordado,
|
||||
moneda: d.moneda || 'COP',
|
||||
estado: d.estado,
|
||||
auto_renovar: d.auto_renovar,
|
||||
notas: d.notas
|
||||
@@ -409,7 +419,7 @@ document.addEventListener('alpine:init', () => {
|
||||
closeModals() {
|
||||
this.addModal = this.editModal = this.deleteModal = false;
|
||||
this.selectedId = null;
|
||||
this.form = { cliente_id:'', servicio_ids:[], fecha_inicio:'', fecha_vencimiento:'', precio_acordado:0, estado:'activo', auto_renovar:false, notas:'' };
|
||||
this.form = { cliente_id:'', servicio_ids:[], fecha_inicio:'', fecha_vencimiento:'', precio_acordado:0, moneda:'COP', estado:'activo', auto_renovar:false, notas:'' };
|
||||
},
|
||||
|
||||
async save() {
|
||||
@@ -532,6 +542,18 @@ document.addEventListener('alpine:init', () => {
|
||||
if (!raw) return '—';
|
||||
return new Date(raw).toLocaleDateString('es-ES', { day:'2-digit', month:'2-digit', year:'numeric' });
|
||||
},
|
||||
|
||||
fmtPrecio(valor, moneda) {
|
||||
const v = parseFloat(valor) || 0;
|
||||
const cur = moneda || 'COP';
|
||||
// COP y MXN: sin decimales, separador de miles
|
||||
const sinDecimales = ['COP', 'MXN'];
|
||||
const opts = sinDecimales.includes(cur)
|
||||
? { minimumFractionDigits: 0, maximumFractionDigits: 0 }
|
||||
: { minimumFractionDigits: 2, maximumFractionDigits: 2 };
|
||||
const num = v.toLocaleString('es-CO', opts);
|
||||
return cur + ' ' + num;
|
||||
},
|
||||
prevPage() { if(this.page>1){ this.page--; this.loadData(); } },
|
||||
nextPage() { if(this.page<this.totalPages){ this.page++; this.loadData(); } },
|
||||
showToast(msg, type='ok') {
|
||||
|
||||
@@ -29,6 +29,7 @@
|
||||
<th class="py-2 px-4 border-b">Servicio vinculado</th>
|
||||
<th class="py-2 px-4 border-b">Orden</th>
|
||||
<th class="py-2 px-4 border-b w-10">Estado</th>
|
||||
<th class="py-2 px-4 border-b w-20 text-center">Health</th>
|
||||
<th class="py-2 px-4 border-b w-24"></th>
|
||||
</tr>
|
||||
</thead>
|
||||
@@ -47,6 +48,23 @@
|
||||
:class="item.activo ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'"
|
||||
class="text-xs px-2 py-0.5 rounded-full"></span>
|
||||
</td>
|
||||
<!-- Health check -->
|
||||
<td class="py-2 px-4 text-center">
|
||||
<template x-if="!item.health_url">
|
||||
<span class="inline-block w-3 h-3 rounded-full bg-gray-300" title="Sin URL de health"></span>
|
||||
</template>
|
||||
<template x-if="item.health_url">
|
||||
<div class="flex flex-col items-center gap-1">
|
||||
<span :class="healthStatus[item.ID] === 'ok' ? 'bg-green-400' : healthStatus[item.ID] === 'fail' ? 'bg-red-400' : 'bg-yellow-300'"
|
||||
class="inline-block w-3 h-3 rounded-full"
|
||||
:title="healthInfo[item.ID] || 'Click para verificar'"></span>
|
||||
<button @click="checkHealth(item)" class="text-xs text-gray-400 hover:text-[#8eb02f]" title="Verificar">
|
||||
<span x-show="healthLoading[item.ID]">⏳</span>
|
||||
<span x-show="!healthLoading[item.ID]">check</span>
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
</td>
|
||||
<td class="py-2 px-4 flex gap-2 justify-end">
|
||||
<a :href="`/docs/${item.slug}`" target="_blank" title="Ver documentación" class="text-green-500 hover:text-green-700">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
||||
@@ -111,6 +129,12 @@
|
||||
<input type="text" x-model="form.logo_url"
|
||||
class="border border-gray-300 rounded w-full p-2 text-sm">
|
||||
</div>
|
||||
<div class="col-span-2">
|
||||
<label class="block text-xs font-medium mb-1">Health Check URL <span class="text-gray-400 font-normal">(opcional)</span></label>
|
||||
<input type="url" x-model="form.health_url" placeholder="https://api.tuservicio.com/health"
|
||||
class="border border-gray-300 rounded w-full p-2 text-sm font-mono">
|
||||
<p class="text-xs text-gray-400 mt-0.5">Se usará para verificar que el servicio está activo. Debe devolver HTTP 2xx.</p>
|
||||
</div>
|
||||
<div class="col-span-2">
|
||||
<label class="block text-xs font-medium mb-1">Servicio vinculado <span class="text-gray-400 font-normal">(opcional)</span></label>
|
||||
<select x-model.number="form.servicio_id" class="border border-gray-300 rounded w-full p-2 text-sm">
|
||||
@@ -160,7 +184,8 @@ function saasApp() {
|
||||
loading: false,
|
||||
showModal: false, showDeleteModal: false,
|
||||
editId: null, deleteId: null,
|
||||
form: { nombre: '', slug: '', descripcion: '', logo_url: '', servicio_id: null, activo: true, orden: 0 },
|
||||
form: { nombre: '', slug: '', descripcion: '', logo_url: '', health_url: '', servicio_id: null, activo: true, orden: 0 },
|
||||
healthStatus: {}, healthInfo: {}, healthLoading: {},
|
||||
|
||||
init() { this.load(1); },
|
||||
|
||||
@@ -190,7 +215,7 @@ function saasApp() {
|
||||
|
||||
openAdd() {
|
||||
this.editId = null;
|
||||
this.form = { nombre: '', slug: '', descripcion: '', logo_url: '', servicio_id: null, activo: true, orden: 0 };
|
||||
this.form = { nombre: '', slug: '', descripcion: '', logo_url: '', health_url: '', servicio_id: null, activo: true, orden: 0 };
|
||||
this.showModal = true;
|
||||
},
|
||||
|
||||
@@ -198,12 +223,25 @@ function saasApp() {
|
||||
this.editId = item.ID;
|
||||
this.form = {
|
||||
nombre: item.nombre, slug: item.slug, descripcion: item.descripcion,
|
||||
logo_url: item.logo_url, servicio_id: item.servicio_id,
|
||||
logo_url: item.logo_url, health_url: item.health_url || '',
|
||||
servicio_id: item.servicio_id,
|
||||
activo: item.activo, orden: item.orden
|
||||
};
|
||||
this.showModal = true;
|
||||
},
|
||||
|
||||
async checkHealth(item) {
|
||||
this.$set(this.healthLoading, item.ID, true);
|
||||
const res = await fetch(`/app/saas/${item.ID}/health`);
|
||||
const d = await res.json();
|
||||
this.$set(this.healthStatus, item.ID, d.ok ? 'ok' : 'fail');
|
||||
const info = d.ok
|
||||
? `HTTP ${d.http_status} · ${d.latency_ms}ms`
|
||||
: (d.error || `HTTP ${d.http_status}`);
|
||||
this.$set(this.healthInfo, item.ID, info);
|
||||
this.$set(this.healthLoading, item.ID, false);
|
||||
},
|
||||
|
||||
submitForm() {
|
||||
const url = this.editId ? `/app/saas/${this.editId}` : '/app/saas';
|
||||
const method = this.editId ? 'PUT' : 'POST';
|
||||
|
||||
@@ -55,6 +55,12 @@
|
||||
class="text-xs px-2 py-0.5 rounded-full"></span>
|
||||
</td>
|
||||
<td class="py-2 px-4 flex gap-2 justify-end">
|
||||
<button @click="openProbar(item)" title="Probar endpoint" class="text-[#8eb02f] hover:text-[#6d8a24]">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z"/>
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
|
||||
</svg>
|
||||
</button>
|
||||
<button @click="openEdit(item)" title="Editar" class="text-blue-500 hover:text-blue-700">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
||||
<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"/>
|
||||
@@ -83,6 +89,48 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ── Modal Probar endpoint ─────────────────────────────────────────── -->
|
||||
<div x-show="probarModal" class="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm" style="display:none">
|
||||
<div class="bg-white rounded-lg shadow-xl w-full max-w-2xl mx-4 max-h-screen overflow-y-auto">
|
||||
<div class="flex justify-between items-center p-5 border-b">
|
||||
<div>
|
||||
<h2 class="text-lg font-semibold">Probar endpoint</h2>
|
||||
<p class="text-xs text-gray-500 mt-0.5" x-text="probarItem ? probarItem.metodo + ' ' + probarItem.endpoint_url : ''"></p>
|
||||
</div>
|
||||
<button @click="closeProbar()" class="text-gray-400 hover:text-gray-600 text-xl">✕</button>
|
||||
</div>
|
||||
<div class="p-5 space-y-4">
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 mb-1">Payload JSON (editable)</label>
|
||||
<textarea x-model="probarPayload" rows="8"
|
||||
class="border rounded w-full p-2 text-sm font-mono"
|
||||
placeholder='{"contrato_id":1,"email":"test@example.com"}'></textarea>
|
||||
<p class="text-xs text-gray-400 mt-0.5">Se enviará tal cual al endpoint. Si está vacío se envía sin body.</p>
|
||||
</div>
|
||||
<button @click="runProbar()" :disabled="probarLoading" class="bg-[#8eb02f] text-white px-5 py-2 rounded text-sm disabled:opacity-50">
|
||||
<span x-show="!probarLoading">▶ Enviar petición</span>
|
||||
<span x-show="probarLoading">Enviando…</span>
|
||||
</button>
|
||||
<!-- Resultado -->
|
||||
<div x-show="probarResult" class="border rounded">
|
||||
<div class="flex items-center gap-3 px-4 py-2 border-b bg-gray-50">
|
||||
<span class="text-sm font-semibold">HTTP</span>
|
||||
<span x-text="probarResult && probarResult.http_status"
|
||||
:class="probarResult && probarResult.ok ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'"
|
||||
class="text-xs px-2 py-0.5 rounded-full font-mono font-bold"></span>
|
||||
<span class="text-xs text-gray-500" x-text="probarResult ? probarResult.latency_ms + ' ms' : ''"></span>
|
||||
<span x-show="probarResult && !probarResult.ok" x-text="probarResult && probarResult.error" class="text-xs text-red-600 ml-auto"></span>
|
||||
</div>
|
||||
<pre x-text="probarResult && probarResult.body"
|
||||
class="p-4 text-xs font-mono whitespace-pre-wrap break-all bg-gray-900 text-green-300 rounded-b max-h-64 overflow-auto"></pre>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex justify-end p-5 border-t">
|
||||
<button @click="closeProbar()" class="px-4 py-2 border rounded text-sm">Cerrar</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ── Modal crear / editar ────────────────────────────────────────────── -->
|
||||
<div x-show="showModal" class="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm" style="display:none">
|
||||
<div class="bg-white rounded-lg shadow-xl w-full max-w-2xl mx-4 max-h-screen overflow-y-auto">
|
||||
@@ -190,6 +238,7 @@ function saasApiApp() {
|
||||
loading: false, showModal: false, editMode: false,
|
||||
saving: false, error: '',
|
||||
form: {},
|
||||
probarModal: false, probarItem: null, probarPayload: '', probarResult: null, probarLoading: false,
|
||||
defaultForm() {
|
||||
return { saas_id: 0, nombre: '', pasarela: 'ambas', endpoint_url: '', metodo: 'POST', api_key_header: '', api_key_value: '', payload_template: '', timeout_seg: 10, activo: true };
|
||||
},
|
||||
@@ -250,6 +299,25 @@ function saasApiApp() {
|
||||
await fetch(`/app/saas-api/${id}`, { method: 'DELETE' });
|
||||
await this.load(this.page);
|
||||
},
|
||||
openProbar(item) {
|
||||
this.probarItem = item;
|
||||
this.probarPayload = item.payload_template || '';
|
||||
this.probarResult = null;
|
||||
this.probarModal = true;
|
||||
},
|
||||
closeProbar() { this.probarModal = false; },
|
||||
async runProbar() {
|
||||
this.probarLoading = true;
|
||||
this.probarResult = null;
|
||||
const body = { payload: this.probarPayload };
|
||||
const res = await fetch(`/app/saas-api/${this.probarItem.ID}/probar`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
this.probarResult = await res.json();
|
||||
this.probarLoading = false;
|
||||
},
|
||||
};
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -0,0 +1,318 @@
|
||||
<!-- Vista: Configuración de Telegram -->
|
||||
<div x-data="telegramApp()" x-init="init()" @keydown.escape="closeModal()" class="bg-white rounded-lg shadow">
|
||||
<div class="container mx-auto p-6 w-full">
|
||||
<h1 class="text-2xl font-bold mb-1">Notificaciones Telegram</h1>
|
||||
<p class="text-sm text-gray-500 mb-4">
|
||||
Configura bots de Telegram para enviar notificaciones dinámicas desde el panel.
|
||||
Cada bot requiere un <code class="bg-gray-100 px-1 rounded">bot_token</code> y un <code class="bg-gray-100 px-1 rounded">chat_id</code> (puede ser un canal, grupo o usuario).
|
||||
</p>
|
||||
|
||||
<!-- Tabs -->
|
||||
<div class="flex gap-4 border-b mb-6 text-sm font-medium">
|
||||
<button @click="tab='configs'"
|
||||
:class="tab==='configs' ? 'border-b-2 border-[#8eb02f] text-[#8eb02f]' : 'text-gray-500 hover:text-gray-700'"
|
||||
class="pb-2">Configuraciones</button>
|
||||
<button @click="tab='send'"
|
||||
:class="tab==='send' ? 'border-b-2 border-[#8eb02f] text-[#8eb02f]' : 'text-gray-500 hover:text-gray-700'"
|
||||
class="pb-2">Enviar mensaje</button>
|
||||
<button @click="tab='logs'; loadLogs(1)"
|
||||
:class="tab==='logs' ? 'border-b-2 border-[#8eb02f] text-[#8eb02f]' : 'text-gray-500 hover:text-gray-700'"
|
||||
class="pb-2">Historial</button>
|
||||
</div>
|
||||
|
||||
<!-- ── Tab: Configuraciones ──────────────────────────────────────────── -->
|
||||
<div x-show="tab==='configs'">
|
||||
<div class="flex justify-end mb-4">
|
||||
<button @click="openAdd()" class="bg-[#8eb02f] text-white px-4 py-2 rounded text-sm">+ Nueva configuración</button>
|
||||
</div>
|
||||
|
||||
<template x-if="configs.length === 0">
|
||||
<p class="text-gray-400 text-sm text-center py-8">Sin configuraciones. Agrega una para comenzar.</p>
|
||||
</template>
|
||||
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
<template x-for="cfg in configs" :key="cfg.ID">
|
||||
<div class="border rounded-lg p-4 flex flex-col gap-2 hover:shadow-sm transition-shadow">
|
||||
<div class="flex items-start justify-between gap-2">
|
||||
<div>
|
||||
<p class="font-semibold text-gray-800 text-sm" x-text="cfg.nombre"></p>
|
||||
<p class="text-xs text-gray-400 mt-0.5">Chat ID: <span class="font-mono" x-text="cfg.chat_id"></span></p>
|
||||
</div>
|
||||
<span :class="cfg.activo ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'"
|
||||
x-text="cfg.activo ? 'Activo' : 'Inactivo'"
|
||||
class="text-xs px-2 py-0.5 rounded-full whitespace-nowrap"></span>
|
||||
</div>
|
||||
<p x-show="cfg.notas" x-text="cfg.notas" class="text-xs text-gray-500 italic"></p>
|
||||
<div class="flex gap-2 mt-auto pt-2 border-t">
|
||||
<button @click="testConfig(cfg)" :disabled="testLoading[cfg.ID]"
|
||||
class="flex-1 text-xs border border-[#8eb02f] text-[#8eb02f] px-3 py-1.5 rounded hover:bg-[#8eb02f] hover:text-white transition-colors disabled:opacity-50">
|
||||
<span x-show="!testLoading[cfg.ID]">🔔 Probar</span>
|
||||
<span x-show="testLoading[cfg.ID]">Enviando…</span>
|
||||
</button>
|
||||
<button @click="openEdit(cfg)"
|
||||
class="text-xs border border-blue-400 text-blue-500 px-3 py-1.5 rounded hover:bg-blue-50">Editar</button>
|
||||
<button @click="confirmDelete(cfg.ID)"
|
||||
class="text-xs border border-red-300 text-red-400 px-3 py-1.5 rounded hover:bg-red-50">Eliminar</button>
|
||||
</div>
|
||||
<p x-show="testResult[cfg.ID]" x-text="testResult[cfg.ID]"
|
||||
:class="testOk[cfg.ID] ? 'text-green-600' : 'text-red-600'"
|
||||
class="text-xs mt-1"></p>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ── Tab: Enviar mensaje ───────────────────────────────────────────── -->
|
||||
<div x-show="tab==='send'" class="max-w-lg">
|
||||
<div class="space-y-4">
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 mb-1">Destinos <span class="text-red-500">*</span></label>
|
||||
<div class="border rounded p-3 space-y-2 max-h-48 overflow-y-auto">
|
||||
<template x-for="cfg in configs.filter(c => c.activo)" :key="cfg.ID">
|
||||
<label class="flex items-center gap-2 cursor-pointer">
|
||||
<input type="checkbox" :value="cfg.ID" x-model.number="sendForm.config_ids" class="w-4 h-4">
|
||||
<span class="text-sm" x-text="cfg.nombre"></span>
|
||||
<span class="text-xs text-gray-400 font-mono ml-auto" x-text="cfg.chat_id"></span>
|
||||
</label>
|
||||
</template>
|
||||
<p x-show="configs.filter(c => c.activo).length === 0" class="text-xs text-gray-400">No hay configuraciones activas.</p>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 mb-1">Título (opcional)</label>
|
||||
<input type="text" x-model="sendForm.titulo" placeholder="Ej: Alerta de servidor caído"
|
||||
class="border rounded w-full p-2 text-sm">
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 mb-1">Mensaje <span class="text-red-500">*</span></label>
|
||||
<textarea x-model="sendForm.mensaje" rows="5"
|
||||
placeholder="Escribe el mensaje. Puedes usar HTML básico: <b>negrita</b>, <i>cursiva</i>, <code>código</code>"
|
||||
class="border rounded w-full p-2 text-sm"></textarea>
|
||||
<p class="text-xs text-gray-400 mt-0.5">Soporta HTML básico de Telegram: <b>, <i>, <code>, <pre></p>
|
||||
</div>
|
||||
<div class="flex items-center gap-3">
|
||||
<button @click="sendMessage()" :disabled="sendLoading"
|
||||
class="bg-[#8eb02f] text-white px-5 py-2 rounded text-sm disabled:opacity-50">
|
||||
<span x-show="!sendLoading">📤 Enviar</span>
|
||||
<span x-show="sendLoading">Enviando…</span>
|
||||
</button>
|
||||
<p x-show="sendResult" x-text="sendResult"
|
||||
:class="sendOk ? 'text-green-600' : 'text-red-600'"
|
||||
class="text-sm"></p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ── Tab: Historial ────────────────────────────────────────────────── -->
|
||||
<div x-show="tab==='logs'">
|
||||
<div class="overflow-x-auto">
|
||||
<table class="table-auto w-full text-sm">
|
||||
<thead class="border-b border-gray-200 text-left font-semibold text-gray-600">
|
||||
<tr>
|
||||
<th class="py-2 px-4">Bot / Config</th>
|
||||
<th class="py-2 px-4">Título</th>
|
||||
<th class="py-2 px-4">Mensaje</th>
|
||||
<th class="py-2 px-4">Estado</th>
|
||||
<th class="py-2 px-4">Fecha</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody class="text-gray-500">
|
||||
<template x-if="logs.length === 0">
|
||||
<tr><td colspan="5" class="py-4 text-center text-gray-400">Sin registros</td></tr>
|
||||
</template>
|
||||
<template x-for="log in logs" :key="log.ID">
|
||||
<tr class="hover:bg-gray-50 border-b border-gray-100">
|
||||
<td class="py-2 px-4 text-xs" x-text="log.TelegramConfig ? log.TelegramConfig.nombre : '-'"></td>
|
||||
<td class="py-2 px-4 text-xs" x-text="log.titulo || '-'"></td>
|
||||
<td class="py-2 px-4 text-xs max-w-xs truncate" x-text="log.mensaje"></td>
|
||||
<td class="py-2 px-4">
|
||||
<span :class="log.estado === 'ok' ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'"
|
||||
x-text="log.estado" class="text-xs px-2 py-0.5 rounded-full"></span>
|
||||
<span x-show="log.error_msg" x-text="log.error_msg" class="text-xs text-red-500 ml-1"></span>
|
||||
</td>
|
||||
<td class="py-2 px-4 text-xs text-gray-400" x-text="fmtDate(log.CreatedAt)"></td>
|
||||
</tr>
|
||||
</template>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<!-- Paginación logs -->
|
||||
<div class="flex justify-between items-center mt-4 text-sm text-gray-500">
|
||||
<span>Total: <b x-text="logTotal"></b></span>
|
||||
<div class="flex gap-1">
|
||||
<button @click="loadLogs(logPage-1)" :disabled="logPage<=1" class="px-3 py-1 border rounded disabled:opacity-40">‹</button>
|
||||
<span class="px-3 py-1" x-text="'Pág. ' + logPage + ' / ' + logTotalPages"></span>
|
||||
<button @click="loadLogs(logPage+1)" :disabled="logPage>=logTotalPages" class="px-3 py-1 border rounded disabled:opacity-40">›</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ── Modal Crear / Editar config ────────────────────────────────────────── -->
|
||||
<div x-show="showModal" class="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm" style="display:none">
|
||||
<div class="bg-white rounded-lg shadow-xl w-full max-w-md mx-4">
|
||||
<div class="flex justify-between items-center p-5 border-b">
|
||||
<h2 class="text-lg font-semibold" x-text="editMode ? 'Editar configuración' : 'Nueva configuración'"></h2>
|
||||
<button @click="closeModal()" class="text-gray-400 hover:text-gray-600 text-xl">✕</button>
|
||||
</div>
|
||||
<div class="p-5 space-y-4">
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 mb-1">Nombre / etiqueta <span class="text-red-500">*</span></label>
|
||||
<input type="text" x-model="form.nombre" placeholder="Ej: Bot Alertas Producción"
|
||||
class="border rounded w-full p-2 text-sm">
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 mb-1">Bot Token <span class="text-red-500">*</span></label>
|
||||
<input type="password" x-model="form.bot_token"
|
||||
:placeholder="editMode ? '••••••• (dejar vacío para no cambiar)' : 'Token del bot de @BotFather'"
|
||||
class="border rounded w-full p-2 text-sm font-mono">
|
||||
<p class="text-xs text-gray-400 mt-0.5">Obtén el token en <a href="https://t.me/BotFather" target="_blank" class="underline text-blue-500">@BotFather</a></p>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 mb-1">Chat ID <span class="text-red-500">*</span></label>
|
||||
<input type="text" x-model="form.chat_id" placeholder="Ej: -1001234567890 o @micanal"
|
||||
class="border rounded w-full p-2 text-sm font-mono">
|
||||
<p class="text-xs text-gray-400 mt-0.5">ID del chat, grupo o canal. Para canales usa el formato <code>@nombre_canal</code>.</p>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 mb-1">Notas internas</label>
|
||||
<textarea x-model="form.notas" rows="2" placeholder="Para qué se usa este bot..."
|
||||
class="border rounded w-full p-2 text-sm"></textarea>
|
||||
</div>
|
||||
<div class="flex items-center gap-2">
|
||||
<input type="checkbox" id="tg-activo" x-model="form.activo" class="w-4 h-4">
|
||||
<label for="tg-activo" class="text-sm">Activo</label>
|
||||
</div>
|
||||
<p x-show="formError" x-text="formError" class="text-red-500 text-sm"></p>
|
||||
</div>
|
||||
<div class="flex justify-end gap-3 p-5 border-t">
|
||||
<button @click="closeModal()" class="px-4 py-2 border rounded text-sm">Cancelar</button>
|
||||
<button @click="save()" :disabled="saving"
|
||||
class="bg-[#8eb02f] text-white px-4 py-2 rounded text-sm disabled:opacity-50">
|
||||
<span x-show="!saving">Guardar</span>
|
||||
<span x-show="saving">Guardando…</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ── Modal Confirmar eliminar ────────────────────────────────────────────── -->
|
||||
<div x-show="deleteModal" class="fixed inset-0 z-50 flex items-center justify-center bg-black/40" style="display:none">
|
||||
<div class="bg-white rounded-lg shadow-xl w-full max-w-sm mx-4 p-6">
|
||||
<h2 class="text-lg font-bold mb-3">Confirmar eliminación</h2>
|
||||
<p class="text-gray-600 mb-4 text-sm">¿Eliminar esta configuración de Telegram?</p>
|
||||
<div class="flex justify-end gap-2">
|
||||
<button @click="doDelete()" class="bg-red-500 text-white px-4 py-2 rounded text-sm">Eliminar</button>
|
||||
<button @click="deleteModal=false" class="bg-gray-500 text-white px-4 py-2 rounded text-sm">Cancelar</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
function telegramApp() {
|
||||
return {
|
||||
tab: 'configs',
|
||||
configs: [],
|
||||
showModal: false, editMode: false, saving: false, formError: '',
|
||||
deleteModal: false, deleteId: null,
|
||||
form: { nombre: '', bot_token: '', chat_id: '', notas: '', activo: true },
|
||||
testLoading: {}, testResult: {}, testOk: {},
|
||||
sendForm: { config_ids: [], titulo: '', mensaje: '' },
|
||||
sendLoading: false, sendResult: '', sendOk: true,
|
||||
logs: [], logPage: 1, logTotalPages: 1, logTotal: 0,
|
||||
|
||||
async init() {
|
||||
await this.loadConfigs();
|
||||
},
|
||||
|
||||
async loadConfigs() {
|
||||
const res = await fetch('/app/loadtelegram');
|
||||
this.configs = await res.json();
|
||||
},
|
||||
|
||||
openAdd() {
|
||||
this.editMode = false;
|
||||
this.form = { nombre: '', bot_token: '', chat_id: '', notas: '', activo: true };
|
||||
this.formError = '';
|
||||
this.showModal = true;
|
||||
},
|
||||
|
||||
openEdit(cfg) {
|
||||
this.editMode = true;
|
||||
this.form = { id: cfg.ID, nombre: cfg.nombre, bot_token: '', chat_id: cfg.chat_id, notas: cfg.notas || '', activo: cfg.activo };
|
||||
this.formError = '';
|
||||
this.showModal = true;
|
||||
},
|
||||
|
||||
closeModal() { this.showModal = false; },
|
||||
|
||||
async save() {
|
||||
this.formError = '';
|
||||
if (!this.form.nombre.trim()) { this.formError = 'El nombre es requerido.'; return; }
|
||||
if (!this.editMode && !this.form.bot_token.trim()) { this.formError = 'El bot_token es requerido.'; return; }
|
||||
if (!this.form.chat_id.trim()) { this.formError = 'El chat_id es requerido.'; return; }
|
||||
this.saving = true;
|
||||
const url = this.editMode ? `/app/telegram/${this.form.id}` : '/app/telegram';
|
||||
const method = this.editMode ? 'PUT' : 'POST';
|
||||
const res = await fetch(url, { method, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(this.form) });
|
||||
this.saving = false;
|
||||
if (!res.ok) { const d = await res.json(); this.formError = d.error || 'Error al guardar.'; return; }
|
||||
this.closeModal();
|
||||
await this.loadConfigs();
|
||||
},
|
||||
|
||||
confirmDelete(id) { this.deleteId = id; this.deleteModal = true; },
|
||||
|
||||
async doDelete() {
|
||||
await fetch(`/app/telegram/${this.deleteId}`, { method: 'DELETE' });
|
||||
this.deleteModal = false;
|
||||
await this.loadConfigs();
|
||||
},
|
||||
|
||||
async testConfig(cfg) {
|
||||
this.$set(this.testLoading, cfg.ID, true);
|
||||
this.$set(this.testResult, cfg.ID, '');
|
||||
const res = await fetch(`/app/telegram/${cfg.ID}/test`, { method: 'POST' });
|
||||
const d = await res.json();
|
||||
this.$set(this.testOk, cfg.ID, d.ok);
|
||||
this.$set(this.testResult, cfg.ID, d.ok ? '✅ Mensaje enviado correctamente.' : ('❌ ' + (d.error || 'Error')));
|
||||
this.$set(this.testLoading, cfg.ID, false);
|
||||
},
|
||||
|
||||
async sendMessage() {
|
||||
this.sendResult = '';
|
||||
if (!this.sendForm.mensaje.trim()) { this.sendResult = 'El mensaje no puede estar vacío.'; this.sendOk = false; return; }
|
||||
if (!this.sendForm.config_ids.length) { this.sendResult = 'Selecciona al menos un destino.'; this.sendOk = false; return; }
|
||||
this.sendLoading = true;
|
||||
const res = await fetch('/app/telegram/send', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(this.sendForm),
|
||||
});
|
||||
const d = await res.json();
|
||||
this.sendOk = d.ok;
|
||||
this.sendResult = d.ok
|
||||
? `✅ Enviado a ${d.enviados} destino(s).`
|
||||
: `⚠️ Enviados: ${d.enviados}, Fallidos: ${d.fallidos}`;
|
||||
this.sendLoading = false;
|
||||
},
|
||||
|
||||
async loadLogs(p = 1) {
|
||||
if (p < 1 || p > this.logTotalPages && this.logTotalPages > 0) return;
|
||||
this.logPage = p;
|
||||
const res = await fetch(`/app/telegram/logs?page=${p}`);
|
||||
const d = await res.json();
|
||||
this.logs = d.items || [];
|
||||
this.logTotal = d.total;
|
||||
this.logTotalPages = d.totalPages || 1;
|
||||
},
|
||||
|
||||
fmtDate(s) {
|
||||
if (!s) return '-';
|
||||
const d = new Date(s);
|
||||
return d.toLocaleString('es-CO', { dateStyle: 'short', timeStyle: 'short' });
|
||||
},
|
||||
};
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,206 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"mime/multipart"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/sujit-baniya/fiber-boilerplate/pkg/models"
|
||||
)
|
||||
|
||||
// GetClienteDocumentos devuelve todos los documentos de un cliente.
|
||||
func GetClienteDocumentos(c *fiber.Ctx) error {
|
||||
id, err := strconv.ParseUint(c.Params("clienteID"), 10, 32)
|
||||
if err != nil {
|
||||
return c.Status(400).JSON(fiber.Map{"error": "ID inválido"})
|
||||
}
|
||||
docs, err := models.GetDocumentosByCliente(uint(id))
|
||||
if err != nil {
|
||||
return c.Status(500).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
return c.JSON(docs)
|
||||
}
|
||||
|
||||
// UploadClienteDocumentos recibe uno o más archivos (campo "archivos") y un campo
|
||||
// opcional "fecha_expedicion" (YYYY-MM-DD) por cada archivo o uno compartido.
|
||||
func UploadClienteDocumentos(c *fiber.Ctx) error {
|
||||
id, err := strconv.ParseUint(c.Params("clienteID"), 10, 32)
|
||||
if err != nil {
|
||||
return c.Status(400).JSON(fiber.Map{"error": "ID inválido"})
|
||||
}
|
||||
|
||||
form, err := c.MultipartForm()
|
||||
if err != nil {
|
||||
return c.Status(400).JSON(fiber.Map{"error": "Formulario inválido: " + err.Error()})
|
||||
}
|
||||
|
||||
files := form.File["archivos"]
|
||||
if len(files) == 0 {
|
||||
return c.Status(400).JSON(fiber.Map{"error": "Ningún archivo recibido"})
|
||||
}
|
||||
|
||||
// fecha_expedicion puede venir como un array (uno por archivo) o uno solo compartido
|
||||
fechas := form.Value["fecha_expedicion"]
|
||||
nombres := form.Value["nombre"]
|
||||
|
||||
uploadDir := fmt.Sprintf("uploads/clientes/%d", id)
|
||||
if err := os.MkdirAll(uploadDir, 0750); err != nil {
|
||||
return c.Status(500).JSON(fiber.Map{"error": "No se pudo crear directorio"})
|
||||
}
|
||||
|
||||
var creados []models.ClienteDocumento
|
||||
for i, fh := range files {
|
||||
// Validar tamaño máximo: 20 MB
|
||||
if fh.Size > 20*1024*1024 {
|
||||
return c.Status(400).JSON(fiber.Map{"error": fmt.Sprintf("Archivo '%s' supera 20 MB", fh.Filename)})
|
||||
}
|
||||
|
||||
// Validar extensión permitida
|
||||
if !extensionPermitida(fh.Filename) {
|
||||
return c.Status(400).JSON(fiber.Map{"error": fmt.Sprintf("Tipo de archivo no permitido: %s", fh.Filename)})
|
||||
}
|
||||
|
||||
safeName := sanitizeFilename(fh.Filename)
|
||||
destPath := filepath.Join(uploadDir, fmt.Sprintf("%d_%s", time.Now().UnixNano(), safeName))
|
||||
|
||||
if err := saveUploadedFile(fh, destPath); err != nil {
|
||||
return c.Status(500).JSON(fiber.Map{"error": "Error guardando archivo: " + err.Error()})
|
||||
}
|
||||
|
||||
doc := models.ClienteDocumento{
|
||||
ClienteID: uint(id),
|
||||
Archivo: destPath,
|
||||
OriginalName: fh.Filename,
|
||||
TipoMime: fh.Header.Get("Content-Type"),
|
||||
Tamanio: fh.Size,
|
||||
}
|
||||
|
||||
// Nombre descriptivo
|
||||
if i < len(nombres) && strings.TrimSpace(nombres[i]) != "" {
|
||||
doc.Nombre = strings.TrimSpace(nombres[i])
|
||||
} else {
|
||||
doc.Nombre = fh.Filename
|
||||
}
|
||||
|
||||
// Fecha de expedición
|
||||
if i < len(fechas) && fechas[i] != "" {
|
||||
if t, err := time.Parse("2006-01-02", fechas[i]); err == nil {
|
||||
doc.FechaExpedicion = &t
|
||||
}
|
||||
} else if len(fechas) == 1 && fechas[0] != "" {
|
||||
if t, err := time.Parse("2006-01-02", fechas[0]); err == nil {
|
||||
doc.FechaExpedicion = &t
|
||||
}
|
||||
}
|
||||
|
||||
if err := models.CreateClienteDocumento(&doc); err != nil {
|
||||
return c.Status(500).JSON(fiber.Map{"error": "Error guardando en BD: " + err.Error()})
|
||||
}
|
||||
creados = append(creados, doc)
|
||||
}
|
||||
|
||||
return c.Status(201).JSON(fiber.Map{"ok": true, "creados": len(creados), "documentos": creados})
|
||||
}
|
||||
|
||||
// DeleteClienteDocumento elimina un documento y su archivo en disco.
|
||||
func DeleteClienteDocumento(c *fiber.Ctx) error {
|
||||
docID, err := strconv.ParseUint(c.Params("docID"), 10, 32)
|
||||
if err != nil {
|
||||
return c.Status(400).JSON(fiber.Map{"error": "ID inválido"})
|
||||
}
|
||||
|
||||
doc, err := models.GetClienteDocumentoByID(uint(docID))
|
||||
if err != nil {
|
||||
return c.Status(404).JSON(fiber.Map{"error": "Documento no encontrado"})
|
||||
}
|
||||
|
||||
// Eliminar archivo físico (no fatal si no existe)
|
||||
_ = os.Remove(doc.Archivo)
|
||||
|
||||
if err := models.DeleteClienteDocumento(uint(docID)); err != nil {
|
||||
return c.Status(500).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
return c.JSON(fiber.Map{"ok": true, "message": "Documento eliminado"})
|
||||
}
|
||||
|
||||
// DownloadClienteDocumento sirve el archivo para descarga directa.
|
||||
func DownloadClienteDocumento(c *fiber.Ctx) error {
|
||||
docID, err := strconv.ParseUint(c.Params("docID"), 10, 32)
|
||||
if err != nil {
|
||||
return c.Status(400).JSON(fiber.Map{"error": "ID inválido"})
|
||||
}
|
||||
|
||||
doc, err := models.GetClienteDocumentoByID(uint(docID))
|
||||
if err != nil {
|
||||
return c.Status(404).JSON(fiber.Map{"error": "Documento no encontrado"})
|
||||
}
|
||||
|
||||
// Asegurarse de que el path no escape del directorio uploads/
|
||||
cleanPath := filepath.Clean(doc.Archivo)
|
||||
if !strings.HasPrefix(cleanPath, "uploads/") {
|
||||
return c.Status(403).JSON(fiber.Map{"error": "Acceso denegado"})
|
||||
}
|
||||
|
||||
return c.Download(cleanPath, doc.OriginalName)
|
||||
}
|
||||
|
||||
// ─── helpers ─────────────────────────────────────────────────────────────────
|
||||
|
||||
var extensionesPermitidas = map[string]bool{
|
||||
".pdf": true, ".doc": true, ".docx": true,
|
||||
".xls": true, ".xlsx": true, ".csv": true,
|
||||
".png": true, ".jpg": true, ".jpeg": true,
|
||||
".gif": true, ".webp": true, ".txt": true,
|
||||
".zip": true, ".rar": true,
|
||||
}
|
||||
|
||||
func extensionPermitida(filename string) bool {
|
||||
ext := strings.ToLower(filepath.Ext(filename))
|
||||
return extensionesPermitidas[ext]
|
||||
}
|
||||
|
||||
func sanitizeFilename(name string) string {
|
||||
base := filepath.Base(name)
|
||||
// Eliminar caracteres peligrosos
|
||||
safe := strings.Map(func(r rune) rune {
|
||||
if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') ||
|
||||
(r >= '0' && r <= '9') || r == '.' || r == '-' || r == '_' {
|
||||
return r
|
||||
}
|
||||
return '_'
|
||||
}, base)
|
||||
return safe
|
||||
}
|
||||
|
||||
func saveUploadedFile(fh *multipart.FileHeader, dest string) error {
|
||||
src, err := fh.Open()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer src.Close()
|
||||
|
||||
out, err := os.Create(dest) //nolint:gosec
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer out.Close()
|
||||
|
||||
buf := make([]byte, 32*1024)
|
||||
for {
|
||||
n, err := src.Read(buf)
|
||||
if n > 0 {
|
||||
if _, werr := out.Write(buf[:n]); werr != nil {
|
||||
return werr
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,9 +1,12 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"io"
|
||||
"math"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/sujit-baniya/fiber-boilerplate/pkg/models"
|
||||
@@ -184,6 +187,82 @@ func DeleteSaasApiConfig(c *fiber.Ctx) error {
|
||||
return c.JSON(fiber.Map{"ok": true})
|
||||
}
|
||||
|
||||
// ProbaSaasApiConfig envía una petición de prueba al endpoint configurado.
|
||||
// Body JSON opcional: { "payload": "..." } — si no se envía usa el payload_template tal cual.
|
||||
func ProbaSaasApiConfig(c *fiber.Ctx) error {
|
||||
idParam := c.Params("id")
|
||||
id64, err := strconv.ParseUint(idParam, 10, 64)
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "id inválido"})
|
||||
}
|
||||
cfg, err := models.GetSaasApiConfigByID(uint(id64))
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusNotFound).JSON(fiber.Map{"error": "no encontrado"})
|
||||
}
|
||||
|
||||
type Req struct {
|
||||
Payload string `json:"payload"`
|
||||
}
|
||||
var req Req
|
||||
_ = c.BodyParser(&req)
|
||||
|
||||
body := strings.TrimSpace(req.Payload)
|
||||
if body == "" {
|
||||
body = strings.TrimSpace(cfg.PayloadTemplate)
|
||||
}
|
||||
|
||||
timeout := cfg.TimeoutSeg
|
||||
if timeout <= 0 {
|
||||
timeout = 10
|
||||
}
|
||||
client := &http.Client{Timeout: time.Duration(timeout) * time.Second}
|
||||
|
||||
var httpReq *http.Request
|
||||
metodo := strings.ToUpper(cfg.Metodo)
|
||||
if metodo == "" {
|
||||
metodo = "POST"
|
||||
}
|
||||
|
||||
if body != "" && metodo != "GET" {
|
||||
httpReq, err = http.NewRequest(metodo, cfg.EndpointURL, strings.NewReader(body))
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusUnprocessableEntity).JSON(fiber.Map{"error": "URL inválida: " + err.Error()})
|
||||
}
|
||||
httpReq.Header.Set("Content-Type", "application/json")
|
||||
} else {
|
||||
httpReq, err = http.NewRequest(metodo, cfg.EndpointURL, nil)
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusUnprocessableEntity).JSON(fiber.Map{"error": "URL inválida: " + err.Error()})
|
||||
}
|
||||
}
|
||||
|
||||
if cfg.ApiKeyHeader != "" && cfg.ApiKeyValue != "" {
|
||||
httpReq.Header.Set(cfg.ApiKeyHeader, cfg.ApiKeyValue)
|
||||
}
|
||||
httpReq.Header.Set("User-Agent", "u-site-tester/1.0")
|
||||
|
||||
start := time.Now()
|
||||
resp, err := client.Do(httpReq)
|
||||
latency := time.Since(start).Milliseconds()
|
||||
|
||||
if err != nil {
|
||||
return c.JSON(fiber.Map{
|
||||
"ok": false,
|
||||
"error": err.Error(),
|
||||
"latency_ms": latency,
|
||||
})
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
respBytes, _ := io.ReadAll(io.LimitReader(resp.Body, 64*1024)) // máx 64 KB
|
||||
return c.JSON(fiber.Map{
|
||||
"ok": resp.StatusCode >= 200 && resp.StatusCode < 300,
|
||||
"http_status": resp.StatusCode,
|
||||
"body": string(respBytes),
|
||||
"latency_ms": latency,
|
||||
})
|
||||
}
|
||||
|
||||
// ─── Panel: logs de despacho ──────────────────────────────────────────────────
|
||||
|
||||
// SaasDispatchLogIndex renderiza la vista de logs de despacho.
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"io"
|
||||
"math"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/sujit-baniya/fiber-boilerplate/pkg/models"
|
||||
@@ -57,6 +61,7 @@ func CreateSaasProducto(c *fiber.Ctx) error {
|
||||
ServicioID *uint `json:"servicio_id"`
|
||||
Activo bool `json:"activo"`
|
||||
Orden int `json:"orden"`
|
||||
HealthURL string `json:"health_url"`
|
||||
}
|
||||
var req Req
|
||||
if err := c.BodyParser(&req); err != nil {
|
||||
@@ -73,6 +78,7 @@ func CreateSaasProducto(c *fiber.Ctx) error {
|
||||
ServicioID: req.ServicioID,
|
||||
Activo: req.Activo,
|
||||
Orden: req.Orden,
|
||||
HealthURL: strings.TrimSpace(req.HealthURL),
|
||||
}
|
||||
if err := models.CreateSaasProducto(item); err != nil {
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": err.Error()})
|
||||
@@ -94,6 +100,7 @@ func UpdateSaasProducto(c *fiber.Ctx) error {
|
||||
ServicioID *uint `json:"servicio_id"`
|
||||
Activo bool `json:"activo"`
|
||||
Orden int `json:"orden"`
|
||||
HealthURL string `json:"health_url"`
|
||||
}
|
||||
var req Req
|
||||
if err := c.BodyParser(&req); err != nil {
|
||||
@@ -107,6 +114,7 @@ func UpdateSaasProducto(c *fiber.Ctx) error {
|
||||
ServicioID: req.ServicioID,
|
||||
Activo: req.Activo,
|
||||
Orden: req.Orden,
|
||||
HealthURL: strings.TrimSpace(req.HealthURL),
|
||||
}
|
||||
item.ID = uint(id)
|
||||
if err := models.UpdateSaasProducto(item); err != nil {
|
||||
@@ -126,3 +134,33 @@ func DeleteSaasProducto(c *fiber.Ctx) error {
|
||||
}
|
||||
return c.JSON(fiber.Map{"message": "Producto SaaS eliminado"})
|
||||
}
|
||||
|
||||
// HealthCheckSaas hace un GET a la HealthURL del producto y devuelve status + latencia.
|
||||
func HealthCheckSaas(c *fiber.Ctx) error {
|
||||
id, err := strconv.ParseUint(c.Params("id"), 10, 32)
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "ID inválido"})
|
||||
}
|
||||
item, err := models.GetSaasProductoByID(uint(id))
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusNotFound).JSON(fiber.Map{"error": "no encontrado"})
|
||||
}
|
||||
if strings.TrimSpace(item.HealthURL) == "" {
|
||||
return c.Status(fiber.StatusUnprocessableEntity).JSON(fiber.Map{"error": "Sin URL de health check configurada"})
|
||||
}
|
||||
client := &http.Client{Timeout: 10 * time.Second}
|
||||
start := time.Now()
|
||||
resp, reqErr := client.Get(item.HealthURL) //nolint:noctx
|
||||
latency := time.Since(start).Milliseconds()
|
||||
if reqErr != nil {
|
||||
return c.JSON(fiber.Map{"ok": false, "error": reqErr.Error(), "latency_ms": latency})
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, _ := io.ReadAll(io.LimitReader(resp.Body, 8*1024))
|
||||
return c.JSON(fiber.Map{
|
||||
"ok": resp.StatusCode >= 200 && resp.StatusCode < 300,
|
||||
"http_status": resp.StatusCode,
|
||||
"body": string(body),
|
||||
"latency_ms": latency,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,28 +1,206 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/sujit-baniya/fiber-boilerplate/pkg/services"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/sujit-baniya/fiber-boilerplate/pkg/models"
|
||||
)
|
||||
|
||||
type TelegramController struct {
|
||||
Service *services.TelegramService
|
||||
// TelegramIndex renderiza la vista de configuración de Telegram.
|
||||
func TelegramIndex(c *fiber.Ctx) error {
|
||||
return c.Render("telegram", fiber.Map{
|
||||
"user": c.Locals("user"),
|
||||
"modules": c.Locals("userModules"),
|
||||
}, "layouts/main")
|
||||
}
|
||||
|
||||
func NewTelegramController(service *services.TelegramService) *TelegramController {
|
||||
return &TelegramController{Service: service}
|
||||
}
|
||||
|
||||
func (tc *TelegramController) SendMessage(chatID interface{}, message string) error {
|
||||
if chatID == "" || message == "" {
|
||||
return fmt.Errorf("chat_id and message are required")
|
||||
}
|
||||
|
||||
err := tc.Service.SendMessage(chatID, message)
|
||||
// GetTelegramConfigs devuelve todas las configs en JSON.
|
||||
func GetTelegramConfigs(c *fiber.Ctx) error {
|
||||
items, err := models.GetAllTelegramConfigs()
|
||||
if err != nil {
|
||||
return fmt.Errorf("error sending message: %v", err)
|
||||
return c.Status(500).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
return c.JSON(items)
|
||||
}
|
||||
|
||||
// CreateTelegramConfig crea una nueva configuración.
|
||||
func CreateTelegramConfig(c *fiber.Ctx) error {
|
||||
var m models.TelegramConfig
|
||||
if err := c.BodyParser(&m); err != nil {
|
||||
return c.Status(400).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
if strings.TrimSpace(m.Nombre) == "" || strings.TrimSpace(m.BotToken) == "" || strings.TrimSpace(m.ChatID) == "" {
|
||||
return c.Status(400).JSON(fiber.Map{"error": "nombre, bot_token y chat_id son obligatorios"})
|
||||
}
|
||||
m.Activo = true
|
||||
if err := models.CreateTelegramConfig(&m); err != nil {
|
||||
return c.Status(500).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
return c.Status(201).JSON(m)
|
||||
}
|
||||
|
||||
// UpdateTelegramConfig actualiza una configuración.
|
||||
func UpdateTelegramConfig(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"})
|
||||
}
|
||||
var m models.TelegramConfig
|
||||
if err := c.BodyParser(&m); err != nil {
|
||||
return c.Status(400).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
m.ID = uint(id)
|
||||
// Si no se envía bot_token, mantener el existente
|
||||
if strings.TrimSpace(m.BotToken) == "" {
|
||||
cfg, err := models.GetTelegramConfigByID(uint(id))
|
||||
if err != nil {
|
||||
return c.Status(404).JSON(fiber.Map{"error": "no encontrado"})
|
||||
}
|
||||
m.BotToken = cfg.BotToken
|
||||
}
|
||||
if err := models.UpdateTelegramConfig(&m); err != nil {
|
||||
return c.Status(500).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
return c.JSON(fiber.Map{"ok": true})
|
||||
}
|
||||
|
||||
// DeleteTelegramConfig elimina una configuración.
|
||||
func DeleteTelegramConfig(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"})
|
||||
}
|
||||
if err := models.DeleteTelegramConfig(uint(id)); err != nil {
|
||||
return c.Status(500).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
return c.JSON(fiber.Map{"ok": true})
|
||||
}
|
||||
|
||||
// TestTelegramConfig envía un mensaje de prueba al bot configurado.
|
||||
func TestTelegramConfig(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"})
|
||||
}
|
||||
cfg, err := models.GetTelegramConfigByID(uint(id))
|
||||
if err != nil {
|
||||
return c.Status(404).JSON(fiber.Map{"error": "Configuración no encontrada"})
|
||||
}
|
||||
msg := "✅ <b>Prueba de conexión</b>\nEsta es una notificación de prueba desde <b>u-site admin</b>."
|
||||
sendErr := sendTelegramMessage(cfg.BotToken, cfg.ChatID, msg)
|
||||
logEntry := &models.TelegramLog{
|
||||
TelegramConfigID: cfg.ID,
|
||||
Titulo: "Prueba manual",
|
||||
Mensaje: msg,
|
||||
Estado: "ok",
|
||||
}
|
||||
if sendErr != nil {
|
||||
logEntry.Estado = "failed"
|
||||
logEntry.ErrorMsg = sendErr.Error()
|
||||
_ = models.CreateTelegramLog(logEntry)
|
||||
return c.Status(422).JSON(fiber.Map{"ok": false, "error": sendErr.Error()})
|
||||
}
|
||||
_ = models.CreateTelegramLog(logEntry)
|
||||
return c.JSON(fiber.Map{"ok": true, "message": "Mensaje enviado"})
|
||||
}
|
||||
|
||||
// SendTelegramNotification envía un mensaje personalizado a una o varias configs.
|
||||
// Body: { "config_ids": [1,2], "titulo": "...", "mensaje": "..." }
|
||||
func SendTelegramNotification(c *fiber.Ctx) error {
|
||||
type Req struct {
|
||||
ConfigIDs []uint `json:"config_ids"`
|
||||
Titulo string `json:"titulo"`
|
||||
Mensaje string `json:"mensaje"`
|
||||
}
|
||||
var req Req
|
||||
if err := c.BodyParser(&req); err != nil {
|
||||
return c.Status(400).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
if strings.TrimSpace(req.Mensaje) == "" {
|
||||
return c.Status(400).JSON(fiber.Map{"error": "El mensaje no puede estar vacío"})
|
||||
}
|
||||
if len(req.ConfigIDs) == 0 {
|
||||
return c.Status(400).JSON(fiber.Map{"error": "Selecciona al menos un destino"})
|
||||
}
|
||||
|
||||
text := req.Mensaje
|
||||
if req.Titulo != "" {
|
||||
text = fmt.Sprintf("<b>%s</b>\n\n%s", req.Titulo, req.Mensaje)
|
||||
}
|
||||
|
||||
var enviados, fallidos int
|
||||
for _, cid := range req.ConfigIDs {
|
||||
cfg, err := models.GetTelegramConfigByID(cid)
|
||||
if err != nil || !cfg.Activo {
|
||||
fallidos++
|
||||
continue
|
||||
}
|
||||
sendErr := sendTelegramMessage(cfg.BotToken, cfg.ChatID, text)
|
||||
logEntry := &models.TelegramLog{
|
||||
TelegramConfigID: cfg.ID,
|
||||
Titulo: req.Titulo,
|
||||
Mensaje: req.Mensaje,
|
||||
Estado: "ok",
|
||||
}
|
||||
if sendErr != nil {
|
||||
logEntry.Estado = "failed"
|
||||
logEntry.ErrorMsg = sendErr.Error()
|
||||
fallidos++
|
||||
} else {
|
||||
enviados++
|
||||
}
|
||||
_ = models.CreateTelegramLog(logEntry)
|
||||
}
|
||||
return c.JSON(fiber.Map{"ok": fallidos == 0, "enviados": enviados, "fallidos": fallidos})
|
||||
}
|
||||
|
||||
// GetTelegramLogs devuelve el historial paginado de mensajes enviados.
|
||||
func GetTelegramLogs(c *fiber.Ctx) error {
|
||||
page, _ := strconv.Atoi(c.Query("page", "1"))
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
limit := 30
|
||||
offset := (page - 1) * limit
|
||||
items, total, err := models.GetTelegramLogs(limit, offset)
|
||||
if err != nil {
|
||||
return c.Status(500).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
return c.JSON(fiber.Map{
|
||||
"items": items,
|
||||
"total": total,
|
||||
"totalPages": int(math.Ceil(float64(total) / float64(limit))),
|
||||
"page": page,
|
||||
})
|
||||
}
|
||||
|
||||
// ─── helper interno ───────────────────────────────────────────────────────────
|
||||
|
||||
func sendTelegramMessage(botToken, chatID, text string) error {
|
||||
if botToken == "" {
|
||||
return fmt.Errorf("bot_token vacío")
|
||||
}
|
||||
apiURL := fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", botToken)
|
||||
payload := map[string]interface{}{
|
||||
"chat_id": chatID,
|
||||
"text": text,
|
||||
"parse_mode": "HTML",
|
||||
}
|
||||
body, _ := json.Marshal(payload)
|
||||
resp, err := http.Post(apiURL, "application/json", bytes.NewReader(body)) //nolint:noctx
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("Telegram respondió %d", resp.StatusCode)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -24,6 +24,11 @@ func RenovacionesRoutes(protected fiber.Router) {
|
||||
protected.Post("/api/clientes", controllers.CreateCliente)
|
||||
protected.Put("/api/clientes/:id", controllers.UpdateCliente)
|
||||
protected.Delete("/api/clientes/:id", controllers.DeleteCliente)
|
||||
// Documentos de cliente
|
||||
protected.Get("/api/clientes/:clienteID/documentos", controllers.GetClienteDocumentos)
|
||||
protected.Post("/api/clientes/:clienteID/documentos", controllers.UploadClienteDocumentos)
|
||||
protected.Delete("/api/clientes/:clienteID/documentos/:docID", controllers.DeleteClienteDocumento)
|
||||
protected.Get("/api/clientes/:clienteID/documentos/:docID/download", controllers.DownloadClienteDocumento)
|
||||
|
||||
// ─── Contratos ───────────────────────────────────────────────────
|
||||
protected.Get("/contratos", middlewares.MenuMiddleware, controllers.ContratosView)
|
||||
|
||||
@@ -179,6 +179,7 @@ func UserRoutes(app fiber.Router) {
|
||||
protected.Post("/saas", controllers.CreateSaasProducto)
|
||||
protected.Put("/saas/:id", controllers.UpdateSaasProducto)
|
||||
protected.Delete("/saas/:id", controllers.DeleteSaasProducto)
|
||||
protected.Get("/saas/:id/health", controllers.HealthCheckSaas)
|
||||
|
||||
// ─── Documentación: categorías globales ──────────────────────────────────
|
||||
protected.Get("/doc/categorias", middlewares.MenuMiddleware, controllers.DocCategoriasIndex)
|
||||
@@ -205,11 +206,22 @@ func UserRoutes(app fiber.Router) {
|
||||
protected.Post("/saas-api", controllers.CreateSaasApiConfig)
|
||||
protected.Put("/saas-api/:id", controllers.UpdateSaasApiConfig)
|
||||
protected.Delete("/saas-api/:id", controllers.DeleteSaasApiConfig)
|
||||
protected.Post("/saas-api/:id/probar", controllers.ProbaSaasApiConfig)
|
||||
|
||||
// Logs de despacho
|
||||
protected.Get("/saas-api/logs", middlewares.MenuMiddleware, controllers.SaasDispatchLogIndex)
|
||||
protected.Get("/loadsaasdispatchlogs", controllers.GetSaasDispatchLogs)
|
||||
|
||||
// ─── Telegram ─────────────────────────────────────────────────────────────
|
||||
protected.Get("/telegram", middlewares.MenuMiddleware, controllers.TelegramIndex)
|
||||
protected.Get("/loadtelegram", controllers.GetTelegramConfigs)
|
||||
protected.Post("/telegram", controllers.CreateTelegramConfig)
|
||||
protected.Put("/telegram/:id", controllers.UpdateTelegramConfig)
|
||||
protected.Delete("/telegram/:id", controllers.DeleteTelegramConfig)
|
||||
protected.Post("/telegram/:id/test", controllers.TestTelegramConfig)
|
||||
protected.Post("/telegram/send", controllers.SendTelegramNotification)
|
||||
protected.Get("/telegram/logs", controllers.GetTelegramLogs)
|
||||
|
||||
// ─── Planes dLocal (gestión desde panel protegido) ────────────────────────
|
||||
protected.Get("/dlocal/planes", apiControllers.SeePlanes)
|
||||
protected.Post("/dlocal/planes", apiControllers.CreatePlan)
|
||||
|
||||
Reference in New Issue
Block a user