Merge remote-tracking branch 'origin/main'
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> # Conflicts: # main.go
This commit is contained in:
@@ -322,8 +322,8 @@ func PortalCrearTicket(c *fiber.Ctx) error {
|
||||
}
|
||||
|
||||
t := &models.ProyectoTicket{
|
||||
ProyectoID: proy.ID,
|
||||
PortalUserID: u.ID,
|
||||
ProyectoID: &proy.ID,
|
||||
PortalUserID: &u.ID,
|
||||
AutorNombre: u.Nombre,
|
||||
Titulo: req.Titulo,
|
||||
Descripcion: req.Descripcion,
|
||||
@@ -361,7 +361,7 @@ func PortalResponderTicket(c *fiber.Ctx) error {
|
||||
if err != nil {
|
||||
return c.Status(404).JSON(fiber.Map{"error": "Ticket no encontrado"})
|
||||
}
|
||||
if ticket.PortalUserID != u.ID {
|
||||
if ticket.PortalUserID == nil || *ticket.PortalUserID != u.ID {
|
||||
return c.Status(403).JSON(fiber.Map{"error": "Sin acceso"})
|
||||
}
|
||||
msg := &models.TicketMensaje{
|
||||
@@ -375,8 +375,10 @@ func PortalResponderTicket(c *fiber.Ctx) error {
|
||||
}
|
||||
go func() {
|
||||
proyNombre := ""
|
||||
if proy, err := models.GetProyectoByID(ticket.ProyectoID); err == nil {
|
||||
proyNombre = proy.Nombre
|
||||
if ticket.ProyectoID != nil {
|
||||
if proy, err := models.GetProyectoByID(*ticket.ProyectoID); err == nil {
|
||||
proyNombre = proy.Nombre
|
||||
}
|
||||
}
|
||||
services.DispatchTicketRespuestaCliente(ticket, req.Contenido, proyNombre)
|
||||
}()
|
||||
@@ -548,7 +550,7 @@ func PortalMarcarTicketLeido(c *fiber.Ctx) error {
|
||||
if err != nil || ticket == nil {
|
||||
return c.Status(404).JSON(fiber.Map{"error": "ticket no encontrado"})
|
||||
}
|
||||
if ticket.PortalUserID != u.ID {
|
||||
if ticket.PortalUserID == nil || *ticket.PortalUserID != u.ID {
|
||||
return c.Status(403).JSON(fiber.Map{"error": "sin permiso"})
|
||||
}
|
||||
_ = models.MarkTicketMessagesReadByPortal(uint(ticketID))
|
||||
|
||||
@@ -578,8 +578,10 @@ func AdminResponderTicket(c *fiber.Ctx) error {
|
||||
return
|
||||
}
|
||||
proyNombre := ""
|
||||
if proy, err := models.GetProyectoByID(ticket.ProyectoID); err == nil {
|
||||
proyNombre = proy.Nombre
|
||||
if ticket.ProyectoID != nil {
|
||||
if proy, err := models.GetProyectoByID(*ticket.ProyectoID); err == nil {
|
||||
proyNombre = proy.Nombre
|
||||
}
|
||||
}
|
||||
services.DispatchTicketRespuestaAdmin(ticket, req.Contenido, proyNombre)
|
||||
}()
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/sujit-baniya/fiber-boilerplate/app"
|
||||
"github.com/sujit-baniya/fiber-boilerplate/pkg/auth"
|
||||
"github.com/sujit-baniya/fiber-boilerplate/pkg/models"
|
||||
"github.com/sujit-baniya/fiber-boilerplate/pkg/services"
|
||||
)
|
||||
@@ -42,10 +43,29 @@ func QueryRunnerPage(c *fiber.Ctx) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetConxDbList devuelve todas las conexiones DB disponibles (para el selector).
|
||||
// GetConxDbList devuelve las conexiones DB disponibles (según el rol del usuario).
|
||||
// Para API calls (Hermes) sin sesión retorna todas.
|
||||
func GetConxDbList(c *fiber.Ctx) error {
|
||||
user, err := auth.User(c)
|
||||
if err != nil || user == nil {
|
||||
var all []models.ConxDb
|
||||
app.Http.Database.DB.Preload("TipoDb").Preload("Servidor").Find(&all)
|
||||
return c.JSON(fiber.Map{"data": all})
|
||||
}
|
||||
|
||||
var items []models.ConxDb
|
||||
app.Http.Database.DB.Preload("TipoDb").Preload("Servidor").Find(&items)
|
||||
if user.IsAdmin {
|
||||
app.Http.Database.DB.Preload("TipoDb").Preload("Servidor").Find(&items)
|
||||
} else {
|
||||
ids := make([]uint, 0)
|
||||
for _, db := range user.Role.ConxDBs {
|
||||
ids = append(ids, db.ID)
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
return c.JSON(fiber.Map{"data": []models.ConxDb{}})
|
||||
}
|
||||
app.Http.Database.DB.Preload("TipoDb").Preload("Servidor").Where("id IN ?", ids).Find(&items)
|
||||
}
|
||||
return c.JSON(fiber.Map{"data": items})
|
||||
}
|
||||
|
||||
@@ -99,10 +119,108 @@ func RunQuery(c *fiber.Ctx) error {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
|
||||
result := services.ExecuteSQL(conx, body.Database, body.SQL)
|
||||
uid := extractUserID(c)
|
||||
result := services.ExecuteSQL(conx, body.Database, body.SQL, uid)
|
||||
return c.JSON(result)
|
||||
}
|
||||
|
||||
// RunBatchQuery ejecuta múltiples consultas en lote.
|
||||
// POST /app/query-runner/run-batch
|
||||
// Body: { conx_db_id, database, sqls: ["...", "..."] }
|
||||
// También soporta multipart/form-data con file .sql
|
||||
func RunBatchQuery(c *fiber.Ctx) error {
|
||||
uid := extractUserID(c)
|
||||
conxDbIDStr := c.FormValue("conx_db_id", c.Query("conx_db_id"))
|
||||
database := c.FormValue("database", c.Query("database"))
|
||||
|
||||
// Obtener statements del body o del archivo subido
|
||||
var statements []string
|
||||
|
||||
// 1. Intentar leer archivo .sql subido
|
||||
if file, err := c.FormFile("file"); err == nil {
|
||||
f, err := file.Open()
|
||||
if err == nil {
|
||||
defer f.Close()
|
||||
buf := new(bytes.Buffer)
|
||||
buf.ReadFrom(f)
|
||||
content := buf.String()
|
||||
// Dividir por ;
|
||||
for _, stmt := range strings.Split(content, ";") {
|
||||
stmt = strings.TrimSpace(stmt)
|
||||
if stmt != "" {
|
||||
statements = append(statements, stmt)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Si no hay archivo, leer del body JSON
|
||||
if len(statements) == 0 {
|
||||
var body struct {
|
||||
ConxDbID uint `json:"conx_db_id"`
|
||||
Database string `json:"database"`
|
||||
SQLs []string `json:"sqls"`
|
||||
}
|
||||
if err := c.BodyParser(&body); err == nil {
|
||||
conxDbIDStr = strconv.Itoa(int(body.ConxDbID))
|
||||
if body.Database != "" {
|
||||
database = body.Database
|
||||
}
|
||||
for _, s := range body.SQLs {
|
||||
s = strings.TrimSpace(s)
|
||||
if s != "" {
|
||||
statements = append(statements, s)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(statements) == 0 {
|
||||
return c.Status(400).JSON(fiber.Map{"error": "No hay consultas para ejecutar. Envía sqls[] o un archivo .sql"})
|
||||
}
|
||||
|
||||
conx, err := loadConxDb(conxDbIDStr)
|
||||
if err != nil {
|
||||
return c.Status(400).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
|
||||
type batchResult struct {
|
||||
Index int `json:"index"`
|
||||
SQL string `json:"sql"`
|
||||
Status string `json:"status"`
|
||||
Duration string `json:"duration"`
|
||||
Rows int `json:"rows"`
|
||||
Columns []string `json:"columns,omitempty"`
|
||||
Data []fiber.Map `json:"data,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
results := make([]batchResult, 0, len(statements))
|
||||
|
||||
for i, stmt := range statements {
|
||||
r := services.ExecuteSQL(conx, database, stmt, uid)
|
||||
br := batchResult{
|
||||
Index: i,
|
||||
SQL: stmt,
|
||||
Status: "ok",
|
||||
Duration: fmt.Sprintf("%dms", r.DurationMs),
|
||||
Rows: r.RowCount,
|
||||
}
|
||||
if r.Error != "" {
|
||||
br.Status = "error"
|
||||
br.Error = r.Error
|
||||
} else {
|
||||
br.Columns = r.Columns
|
||||
br.Data = make([]fiber.Map, len(r.Rows))
|
||||
for j, row := range r.Rows {
|
||||
br.Data[j] = fiber.Map(row)
|
||||
}
|
||||
}
|
||||
results = append(results, br)
|
||||
}
|
||||
|
||||
return c.JSON(fiber.Map{"results": results, "total": len(results)})
|
||||
}
|
||||
|
||||
// TestConnection verifica que la conexión funciona.
|
||||
// GET /app/query-runner/test?conx_db_id=1
|
||||
func TestConnection(c *fiber.Ctx) error {
|
||||
@@ -128,7 +246,19 @@ func GetHistory(c *fiber.Ctx) error {
|
||||
limit := 50
|
||||
offset := (page - 1) * limit
|
||||
|
||||
items, total, err := models.GetQueryHistory(uint(conxID), limit, offset)
|
||||
user, _ := auth.User(c)
|
||||
var items []models.QueryHistory
|
||||
var total int64
|
||||
var err error
|
||||
if user != nil && user.IsAdmin {
|
||||
items, total, err = models.GetQueryHistoryAdmin(uint(conxID), limit, offset)
|
||||
} else {
|
||||
uid := uint(0)
|
||||
if user != nil {
|
||||
uid = user.ID
|
||||
}
|
||||
items, total, err = models.GetQueryHistory(uint(conxID), uid, limit, offset)
|
||||
}
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
@@ -146,7 +276,19 @@ func GetHistory(c *fiber.Ctx) error {
|
||||
func ClearHistory(c *fiber.Ctx) error {
|
||||
conxIDStr := c.Query("conx_db_id", "0")
|
||||
conxID, _ := strconv.ParseUint(conxIDStr, 10, 32)
|
||||
if err := models.DeleteQueryHistory(uint(conxID)); err != nil {
|
||||
|
||||
user, _ := auth.User(c)
|
||||
var err error
|
||||
if user != nil && user.IsAdmin {
|
||||
err = models.DeleteQueryHistoryAdmin(uint(conxID))
|
||||
} else {
|
||||
uid := uint(0)
|
||||
if user != nil {
|
||||
uid = user.ID
|
||||
}
|
||||
err = models.DeleteQueryHistory(uint(conxID), uid)
|
||||
}
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
return c.JSON(fiber.Map{"ok": true})
|
||||
@@ -168,7 +310,8 @@ func ExportCSV(c *fiber.Ctx) error {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
|
||||
result := services.ExecuteSQL(conx, body.Database, body.SQL)
|
||||
uid := extractUserID(c)
|
||||
result := services.ExecuteSQL(conx, body.Database, body.SQL, uid)
|
||||
if result.Error != "" {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": result.Error})
|
||||
}
|
||||
@@ -212,7 +355,8 @@ func ExportJSON(c *fiber.Ctx) error {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
|
||||
result := services.ExecuteSQL(conx, body.Database, body.SQL)
|
||||
uid := extractUserID(c)
|
||||
result := services.ExecuteSQL(conx, body.Database, body.SQL, uid)
|
||||
if result.Error != "" {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": result.Error})
|
||||
}
|
||||
@@ -307,7 +451,8 @@ func UpdateCellHandler(c *fiber.Ctx) error {
|
||||
sqlText := fmt.Sprintf("UPDATE %s SET %s = %s WHERE %s = %s",
|
||||
qTable, qCol, valueSQL, qPkCol, pkValueSQL)
|
||||
|
||||
result := services.ExecuteSQL(conx, body.Database, sqlText)
|
||||
uid := extractUserID(c)
|
||||
result := services.ExecuteSQL(conx, body.Database, sqlText, uid)
|
||||
if result.Error != "" {
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": result.Error})
|
||||
}
|
||||
@@ -676,3 +821,11 @@ func loadConxDb(idStr string) (models.ConxDb, error) {
|
||||
}
|
||||
return conx, nil
|
||||
}
|
||||
|
||||
func extractUserID(c *fiber.Ctx) uint {
|
||||
user, err := auth.User(c)
|
||||
if err != nil || user == nil {
|
||||
return 0
|
||||
}
|
||||
return user.ID
|
||||
}
|
||||
|
||||
@@ -69,6 +69,12 @@ func GetRoles(c *fiber.Ctx) error {
|
||||
// })
|
||||
// }
|
||||
|
||||
// Obtener todas las conexiones disponibles para asignar a roles
|
||||
conexiones, err := models.GetConxDbSelect("")
|
||||
if err != nil {
|
||||
conexiones = []models.ConxDb{}
|
||||
}
|
||||
|
||||
// Calcular el total de páginas
|
||||
totalPages := int(math.Ceil(float64(total) / float64(limit)))
|
||||
|
||||
@@ -76,6 +82,7 @@ func GetRoles(c *fiber.Ctx) error {
|
||||
return c.JSON(fiber.Map{
|
||||
"roles": roles,
|
||||
"modules": modules,
|
||||
"conexiones": conexiones,
|
||||
"total": total, // Total de disponibles
|
||||
"totalPages": totalPages, // Total de páginas
|
||||
"page": page, // Página actual
|
||||
@@ -128,10 +135,18 @@ func UpdateRole(c *fiber.Ctx) error {
|
||||
newSubmodules = append(newSubmodules, newSubmodule)
|
||||
}
|
||||
}
|
||||
|
||||
// Asignar los nuevos submódulos al rol
|
||||
m.Submodules = newSubmodules
|
||||
|
||||
// Agregar las nuevas conexiones a BD
|
||||
var newConxDBs []models.ConxDb
|
||||
for _, db := range m.ConxDBs {
|
||||
var found models.ConxDb
|
||||
if err := app.Http.Database.DB.First(&found, db.ID).Error; err == nil {
|
||||
newConxDBs = append(newConxDBs, found)
|
||||
}
|
||||
}
|
||||
m.ConxDBs = newConxDBs
|
||||
|
||||
// Actualizar el rol en la base de datos
|
||||
if err := app.Http.Database.DB.Session(&gorm.Session{FullSaveAssociations: true}).Save(&m).Error; err != nil {
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
@@ -158,6 +173,16 @@ func CreateRole(c *fiber.Ctx) error {
|
||||
})
|
||||
}
|
||||
|
||||
// Look up ConxDBs by ID
|
||||
var conxDbs []models.ConxDb
|
||||
for _, db := range m.ConxDBs {
|
||||
var found models.ConxDb
|
||||
if err := app.Http.Database.DB.First(&found, db.ID).Error; err == nil {
|
||||
conxDbs = append(conxDbs, found)
|
||||
}
|
||||
}
|
||||
m.ConxDBs = conxDbs
|
||||
|
||||
// Create the role in the database
|
||||
if err := models.CreateRole(m); err != nil {
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
|
||||
@@ -0,0 +1,283 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"log"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/sujit-baniya/fiber-boilerplate/app"
|
||||
"github.com/sujit-baniya/fiber-boilerplate/pkg/models"
|
||||
"github.com/sujit-baniya/fiber-boilerplate/pkg/services"
|
||||
)
|
||||
|
||||
// ─── Webhook de correo entrante ───────────────────────────────────────────────
|
||||
// Recibe notificaciones de SendGrid, Mailgun, etc.
|
||||
// POST /webhooks/soporte/:provider
|
||||
// provider: sendgrid, mailgun, generic
|
||||
|
||||
func SoporteWebhook(c *fiber.Ctx) error {
|
||||
provider := c.Params("provider", "generic")
|
||||
|
||||
cfg, err := models.GetSoporteWebhookActivo()
|
||||
if err != nil {
|
||||
log.Printf("[SoporteWebhook] Sin config activa: %v", err)
|
||||
return c.Status(200).JSON(fiber.Map{"ok": false, "error": "sin config"})
|
||||
}
|
||||
|
||||
var emails []struct {
|
||||
From string `json:"from" form:"from"`
|
||||
Subject string `json:"subject" form:"subject"`
|
||||
Text string `json:"text" form:"text"`
|
||||
Html string `json:"html" form:"html"`
|
||||
Sender string `json:"sender" form:"sender"`
|
||||
FromName string `json:"from_name" form:"from_name"`
|
||||
}
|
||||
|
||||
switch provider {
|
||||
case "sendgrid":
|
||||
var sg struct {
|
||||
From string `json:"from"`
|
||||
Subject string `json:"subject"`
|
||||
Text string `json:"text"`
|
||||
Html string `json:"html"`
|
||||
Sender string `json:"sender"`
|
||||
FromName string `json:"from_name"`
|
||||
}
|
||||
if err := c.BodyParser(&sg); err != nil {
|
||||
return c.Status(200).JSON(fiber.Map{"ok": false, "error": "body inválido"})
|
||||
}
|
||||
emails = append(emails, struct {
|
||||
From string `json:"from" form:"from"`
|
||||
Subject string `json:"subject" form:"subject"`
|
||||
Text string `json:"text" form:"text"`
|
||||
Html string `json:"html" form:"html"`
|
||||
Sender string `json:"sender" form:"sender"`
|
||||
FromName string `json:"from_name" form:"from_name"`
|
||||
}{From: sg.From, Subject: sg.Subject, Text: sg.Text, Html: sg.Html, Sender: sg.Sender, FromName: sg.FromName})
|
||||
case "mailgun":
|
||||
var mg struct {
|
||||
From string `form:"from"`
|
||||
Subject string `form:"subject"`
|
||||
Text string `form:"body-plain"`
|
||||
Html string `form:"body-html"`
|
||||
Sender string `form:"sender"`
|
||||
FromName string `form:"from_name"`
|
||||
}
|
||||
if err := c.BodyParser(&mg); err != nil {
|
||||
return c.Status(200).JSON(fiber.Map{"ok": false})
|
||||
}
|
||||
emails = append(emails, struct {
|
||||
From string `json:"from" form:"from"`
|
||||
Subject string `json:"subject" form:"subject"`
|
||||
Text string `json:"text" form:"text"`
|
||||
Html string `json:"html" form:"html"`
|
||||
Sender string `json:"sender" form:"sender"`
|
||||
FromName string `json:"from_name" form:"from_name"`
|
||||
}{
|
||||
From: mg.From, Subject: mg.Subject, Text: mg.Text,
|
||||
Html: mg.Html, Sender: mg.Sender, FromName: mg.FromName,
|
||||
})
|
||||
default:
|
||||
var generic struct {
|
||||
From string `json:"from"`
|
||||
Subject string `json:"subject"`
|
||||
Text string `json:"text"`
|
||||
Html string `json:"html"`
|
||||
}
|
||||
if err := c.BodyParser(&generic); err != nil {
|
||||
return c.Status(200).JSON(fiber.Map{"ok": false})
|
||||
}
|
||||
emails = append(emails, struct {
|
||||
From string `json:"from" form:"from"`
|
||||
Subject string `json:"subject" form:"subject"`
|
||||
Text string `json:"text" form:"text"`
|
||||
Html string `json:"html" form:"html"`
|
||||
Sender string `json:"sender" form:"sender"`
|
||||
FromName string `json:"from_name" form:"from_name"`
|
||||
}{
|
||||
From: generic.From, Subject: generic.Subject, Text: generic.Text, Html: generic.Html,
|
||||
})
|
||||
}
|
||||
|
||||
for _, e := range emails {
|
||||
if e.From == "" || e.Subject == "" {
|
||||
continue
|
||||
}
|
||||
fromEmail := extractEmail(e.From)
|
||||
fromName := e.FromName
|
||||
if fromName == "" {
|
||||
fromName = extractName(e.From)
|
||||
}
|
||||
if fromName == "" {
|
||||
fromName = fromEmail
|
||||
}
|
||||
|
||||
contenido := e.Text
|
||||
if contenido == "" {
|
||||
contenido = e.Html
|
||||
}
|
||||
contenido = strings.TrimSpace(contenido)
|
||||
if len(contenido) > 5000 {
|
||||
contenido = contenido[:5000]
|
||||
}
|
||||
|
||||
ticket := &models.ProyectoTicket{
|
||||
AutorNombre: fromName,
|
||||
EmailFrom: fromEmail,
|
||||
Titulo: e.Subject,
|
||||
Descripcion: contenido,
|
||||
Estado: "abierto",
|
||||
Origen: "email",
|
||||
}
|
||||
if cfg.AsignarA != nil {
|
||||
ticket.AsignadoA = cfg.AsignarA
|
||||
}
|
||||
if err := models.CreateProyectoTicket(ticket); err != nil {
|
||||
log.Printf("[SoporteWebhook] Error creando ticket: %v", err)
|
||||
continue
|
||||
}
|
||||
log.Printf("[SoporteWebhook] Ticket #%d creado desde email (%s): %s", ticket.ID, fromEmail, e.Subject)
|
||||
|
||||
// Notificar admin
|
||||
services.SendSoporteNotifAdmin(ticket)
|
||||
|
||||
// Auto-responder
|
||||
if cfg.ResponderAuto {
|
||||
services.SendSoporteAutoRespuesta(ticket)
|
||||
}
|
||||
}
|
||||
|
||||
return c.Status(200).JSON(fiber.Map{"ok": true})
|
||||
}
|
||||
|
||||
// ─── Asignar ticket a usuario ─────────────────────────────────────────────────
|
||||
// PUT /app/tickets/:ticketID/asignar
|
||||
|
||||
func AsignarTicket(c *fiber.Ctx) error {
|
||||
ticketID, _ := strconv.ParseUint(c.Params("ticketID"), 10, 32)
|
||||
type Req struct{ AsignadoID uint `json:"asignado_id"` }
|
||||
var req Req
|
||||
if err := c.BodyParser(&req); err != nil {
|
||||
return c.Status(400).JSON(fiber.Map{"error": "body inválido"})
|
||||
}
|
||||
if err := app.Http.Database.DB.Model(&models.ProyectoTicket{}).
|
||||
Where("id = ?", ticketID).
|
||||
Update("asignado_a", req.AsignadoID).Error; err != nil {
|
||||
return c.Status(500).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
return c.JSON(fiber.Map{"ok": true})
|
||||
}
|
||||
|
||||
// ─── Listar admins para asignación ────────────────────────────────────────────
|
||||
// GET /app/tickets/admins
|
||||
|
||||
func GetSoporteAdmins(c *fiber.Ctx) error {
|
||||
var admins []models.Users
|
||||
app.Http.Database.DB.Where("is_admin = ?", true).
|
||||
Or("role_id IN (SELECT id FROM roles WHERE name = 'soporte' OR name = 'admin')").
|
||||
Find(&admins)
|
||||
type item struct {
|
||||
ID uint `json:"id"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
result := make([]item, 0)
|
||||
for _, a := range admins {
|
||||
result = append(result, item{ID: a.ID, Name: a.Name})
|
||||
}
|
||||
return c.JSON(result)
|
||||
}
|
||||
|
||||
// ─── Configuración del webhook ────────────────────────────────────────────────
|
||||
|
||||
func SoporteWebhookConfigPage(c *fiber.Ctx) error {
|
||||
cfg, _ := models.GetSoporteWebhookActivo()
|
||||
return c.Render("soporte_webhook", fiber.Map{
|
||||
"user": c.Locals("user"),
|
||||
"modules": c.Locals("userModules"),
|
||||
"cfg": cfg,
|
||||
}, "layouts/main")
|
||||
}
|
||||
|
||||
func GetSoporteWebhookConfig(c *fiber.Ctx) error {
|
||||
cfg, err := models.GetSoporteWebhookActivo()
|
||||
if err != nil {
|
||||
return c.JSON(fiber.Map{"data": nil})
|
||||
}
|
||||
return c.JSON(fiber.Map{"data": cfg})
|
||||
}
|
||||
|
||||
func SaveSoporteWebhookConfig(c *fiber.Ctx) error {
|
||||
type body struct {
|
||||
ID uint `json:"id"`
|
||||
Nombre string `json:"nombre"`
|
||||
Provider string `json:"provider"`
|
||||
ApiKey string `json:"api_key"`
|
||||
EmailDestino string `json:"email_destino"`
|
||||
ResponderAuto bool `json:"responder_auto"`
|
||||
MensajeAuto string `json:"mensaje_auto"`
|
||||
AsignarA *uint `json:"asignar_a"`
|
||||
SmtpHost string `json:"smtp_host"`
|
||||
SmtpPort int `json:"smtp_port"`
|
||||
SmtpUsername string `json:"smtp_username"`
|
||||
SmtpPassword string `json:"smtp_password"`
|
||||
SmtpEncryption string `json:"smtp_encryption"`
|
||||
SmtpFromAddr string `json:"smtp_from_addr"`
|
||||
SmtpFromName string `json:"smtp_from_name"`
|
||||
}
|
||||
var b body
|
||||
if err := c.BodyParser(&b); err != nil {
|
||||
return c.Status(400).JSON(fiber.Map{"error": "body inválido"})
|
||||
}
|
||||
port := b.SmtpPort
|
||||
if port == 0 {
|
||||
port = 587
|
||||
}
|
||||
enc := b.SmtpEncryption
|
||||
if enc == "" {
|
||||
enc = "starttls"
|
||||
}
|
||||
cfg := &models.SoporteWebhookConfig{
|
||||
Nombre: b.Nombre,
|
||||
Provider: b.Provider,
|
||||
ApiKey: b.ApiKey,
|
||||
EmailDestino: b.EmailDestino,
|
||||
ResponderAuto: b.ResponderAuto,
|
||||
MensajeAuto: b.MensajeAuto,
|
||||
AsignarA: b.AsignarA,
|
||||
SmtpHost: b.SmtpHost,
|
||||
SmtpPort: port,
|
||||
SmtpUsername: b.SmtpUsername,
|
||||
SmtpPassword: b.SmtpPassword,
|
||||
SmtpEncryption: enc,
|
||||
SmtpFromAddr: b.SmtpFromAddr,
|
||||
SmtpFromName: b.SmtpFromName,
|
||||
Activo: true,
|
||||
}
|
||||
cfg.ID = b.ID
|
||||
if err := models.SaveSoporteWebhookConfig(cfg); err != nil {
|
||||
return c.Status(500).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
return c.JSON(fiber.Map{"ok": true})
|
||||
}
|
||||
|
||||
// ─── helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
func extractEmail(s string) string {
|
||||
s = strings.TrimSpace(s)
|
||||
if idx := strings.LastIndex(s, "<"); idx >= 0 {
|
||||
s = s[idx+1:]
|
||||
}
|
||||
if idx := strings.LastIndex(s, ">"); idx >= 0 {
|
||||
s = s[:idx]
|
||||
}
|
||||
return strings.TrimSpace(s)
|
||||
}
|
||||
|
||||
func extractName(s string) string {
|
||||
s = strings.TrimSpace(s)
|
||||
if idx := strings.Index(s, "<"); idx >= 0 {
|
||||
return strings.TrimSpace(s[:idx])
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestExtractEmailSimple(t *testing.T) {
|
||||
tests := []struct {
|
||||
input string
|
||||
want string
|
||||
}{
|
||||
{"user@example.com", "user@example.com"},
|
||||
{"<user@example.com>", "user@example.com"},
|
||||
{"John Doe <john@example.com>", "john@example.com"},
|
||||
{"\"John Doe\" <john@example.com>", "john@example.com"},
|
||||
{" spaced@example.com ", "spaced@example.com"},
|
||||
{"", ""},
|
||||
{"<onlybrackets>", "onlybrackets"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
got := extractEmail(tt.input)
|
||||
if got != tt.want {
|
||||
t.Errorf("extractEmail(%q) = %q, want %q", tt.input, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractNameSimple(t *testing.T) {
|
||||
tests := []struct {
|
||||
input string
|
||||
want string
|
||||
}{
|
||||
{"John Doe <john@example.com>", "John Doe"},
|
||||
{"<user@example.com>", ""},
|
||||
{"user@example.com", ""},
|
||||
{" Spaces Here <spaces@example.com>", "Spaces Here"},
|
||||
{"\"Quoted Name\" <q@example.com>", "\"Quoted Name\""},
|
||||
{"", ""},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
got := extractName(tt.input)
|
||||
if got != tt.want {
|
||||
t.Errorf("extractName(%q) = %q, want %q", tt.input, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractEmailRealWorld(t *testing.T) {
|
||||
inputs := []struct {
|
||||
full string
|
||||
mail string
|
||||
name string
|
||||
}{
|
||||
{"María López <maria@example.com>", "maria@example.com", "María López"},
|
||||
{"soporte@u-s.app", "soporte@u-s.app", ""},
|
||||
{"Cliente Final <cliente+tag@dominio.co>", "cliente+tag@dominio.co", "Cliente Final"},
|
||||
{"", "", ""},
|
||||
}
|
||||
for _, tt := range inputs {
|
||||
gotMail := extractEmail(tt.full)
|
||||
gotName := extractName(tt.full)
|
||||
if gotMail != tt.mail {
|
||||
t.Errorf("extractEmail(%q) = %q, want %q", tt.full, gotMail, tt.mail)
|
||||
}
|
||||
if gotName != tt.name {
|
||||
t.Errorf("extractName(%q) = %q, want %q", tt.full, gotName, tt.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractEmailEdgeCases(t *testing.T) {
|
||||
// Formato RFC 5322 con nombre y ángulos
|
||||
if got := extractEmail("a<b@c.com>"); got != "b@c.com" {
|
||||
t.Errorf("extractEmail('a<b@c.com>') = %q, want 'b@c.com'", got)
|
||||
}
|
||||
// Múltiples brackets — usa el último par
|
||||
if got := extractEmail("<a><b@c.com>"); got != "b@c.com" {
|
||||
t.Errorf("extractEmail('<a><b@c.com>') = %q, want 'b@c.com'", got)
|
||||
}
|
||||
}
|
||||
@@ -334,6 +334,7 @@ func AdminApiRoutes(api fiber.Router) {
|
||||
h.Get("/query-runner/tables", controllers.GetTables)
|
||||
h.Get("/query-runner/test", controllers.TestConnection)
|
||||
h.Post("/query-runner/run", controllers.RunQuery)
|
||||
h.Post("/query-runner/run-batch", controllers.RunBatchQuery)
|
||||
h.Get("/query-runner/history", controllers.GetHistory)
|
||||
h.Get("/query-runner/columns", controllers.GetTableColumnsHandler)
|
||||
|
||||
|
||||
@@ -76,6 +76,10 @@ func RutasPublicas(web fiber.Router) {
|
||||
// ─── Página de estado del sistema (Atlassian Statuspage) ────────────────
|
||||
web.Get("/status", controllers.StatusPage)
|
||||
|
||||
// ─── Webhook de soporte (correo entrante) ────────────────────────────────
|
||||
// Configurar en SendGrid/Mailgun: POST {HOST}/webhooks/soporte/{provider}
|
||||
web.Post("/webhooks/soporte/:provider", controllers.SoporteWebhook)
|
||||
|
||||
// ─── Landing Generator (acceso con X-Landing-Secret) ─────────────────────
|
||||
// Rutas públicas (sin secret) para lectura de preview y polling
|
||||
web.Get("/landing/preview/:token", apiControllers.LandingGetSession)
|
||||
|
||||
@@ -139,6 +139,7 @@ func UserRoutes(app fiber.Router) {
|
||||
protected.Get("/query-runner/tables", controllers.GetTables)
|
||||
protected.Get("/query-runner/test", controllers.TestConnection)
|
||||
protected.Post("/query-runner/run", controllers.RunQuery)
|
||||
protected.Post("/query-runner/run-batch", controllers.RunBatchQuery)
|
||||
protected.Get("/query-runner/history", controllers.GetHistory)
|
||||
protected.Delete("/query-runner/history", controllers.ClearHistory)
|
||||
protected.Post("/query-runner/export/csv", controllers.ExportCSV)
|
||||
@@ -454,6 +455,13 @@ func UserRoutes(app fiber.Router) {
|
||||
protected.Get("/tickets/data", controllers.GetAllTicketsAdmin)
|
||||
protected.Put("/tickets/:ticketID/estado", controllers.UpdateTicketEstadoAdmin)
|
||||
protected.Post("/tickets/:ticketID/mensaje", controllers.AdminResponderTicket)
|
||||
protected.Put("/tickets/:ticketID/asignar", controllers.AsignarTicket)
|
||||
protected.Get("/tickets/admins", controllers.GetSoporteAdmins)
|
||||
|
||||
// Configuración webhook de soporte
|
||||
protected.Get("/soporte/webhook", middlewares.MenuMiddleware, controllers.SoporteWebhookConfigPage)
|
||||
protected.Get("/soporte/webhook/data", controllers.GetSoporteWebhookConfig)
|
||||
protected.Post("/soporte/webhook", controllers.SaveSoporteWebhookConfig)
|
||||
|
||||
// Configuración de notificaciones
|
||||
protected.Get("/notif-config", middlewares.MenuMiddleware, controllers.NotifConfigIndex)
|
||||
|
||||
Reference in New Issue
Block a user