up
This commit is contained in:
@@ -153,3 +153,12 @@ func CheckPortalLogin(email, password string) (*PortalUser, error) {
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
// GetPortalUsersByClienteID devuelve todos los portal users activos de un cliente.
|
||||
func GetPortalUsersByClienteID(clienteID uint) ([]PortalUser, error) {
|
||||
var users []PortalUser
|
||||
err := app.Http.Database.DB.
|
||||
Where("cliente_id = ? AND activo = true", clienteID).
|
||||
Find(&users).Error
|
||||
return users, err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"github.com/sujit-baniya/fiber-boilerplate/app"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// ShieldConfig almacena las credenciales para la API de USITE Shield.
|
||||
type ShieldConfig struct {
|
||||
gorm.Model
|
||||
BaseUrl string `json:"base_url" gorm:"column:base_url;type:text;default:'https://api-shield.u-s.app'"`
|
||||
AdminToken string `json:"admin_token" gorm:"column:admin_token;type:text"`
|
||||
Activo bool `json:"activo" gorm:"column:activo;default:true"`
|
||||
Nota string `json:"nota" gorm:"column:nota;type:text"`
|
||||
}
|
||||
|
||||
func (ShieldConfig) TableName() string { return "shield_config" }
|
||||
|
||||
func GetShieldConfig() (*ShieldConfig, error) {
|
||||
var cfg ShieldConfig
|
||||
err := app.Http.Database.DB.Where("activo = true").First(&cfg).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &cfg, nil
|
||||
}
|
||||
|
||||
func UpsertShieldConfig(cfg *ShieldConfig) error {
|
||||
var existing ShieldConfig
|
||||
if err := app.Http.Database.DB.First(&existing).Error; err != nil {
|
||||
return app.Http.Database.DB.Create(cfg).Error
|
||||
}
|
||||
return app.Http.Database.DB.Model(&existing).Updates(map[string]interface{}{
|
||||
"base_url": cfg.BaseUrl,
|
||||
"admin_token": cfg.AdminToken,
|
||||
"activo": cfg.Activo,
|
||||
"nota": cfg.Nota,
|
||||
}).Error
|
||||
}
|
||||
@@ -176,3 +176,25 @@ func SendTicketRespuestaAdmin(adminEmail, proyectoNombre, autorNombre, titulo, r
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// SendFacturaSubidaPortalUser notifica a un portal user que tiene una nueva factura disponible.
|
||||
func SendFacturaSubidaPortalUser(toEmail, userName, clienteNombre, numero string, monto float64, moneda, portalURL string) {
|
||||
go func() {
|
||||
subject := fmt.Sprintf("Nueva factura disponible: %s", numero)
|
||||
htmlBody := fmt.Sprintf(`
|
||||
<div style="font-family:sans-serif;max-width:520px;margin:0 auto;padding:24px">
|
||||
<h2 style="color:#8eb02f">🧾 Nueva factura disponible</h2>
|
||||
<p>Hola <strong>%s</strong>,</p>
|
||||
<p>Tienes una nueva factura disponible para descargar:</p>
|
||||
<table style="width:100%%;border-collapse:collapse;margin:16px 0">
|
||||
<tr><td style="padding:8px;border:1px solid #e2e8f0;background:#f8fafc;font-weight:bold">Número</td><td style="padding:8px;border:1px solid #e2e8f0">%s</td></tr>
|
||||
<tr><td style="padding:8px;border:1px solid #e2e8f0;background:#f8fafc;font-weight:bold">Monto</td><td style="padding:8px;border:1px solid #e2e8f0">%s %.2f</td></tr>
|
||||
</table>
|
||||
<a href="%s" style="display:inline-block;background:#8eb02f;color:white;padding:12px 24px;border-radius:8px;text-decoration:none;font-weight:bold">Ver en el portal</a>
|
||||
<p style="margin-top:24px;color:#94a3b8;font-size:12px">Este es un mensaje automático.</p>
|
||||
</div>`, userName, numero, moneda, monto, portalURL)
|
||||
if err := app.Http.Mail.Send(toEmail, subject, htmlBody, ""); err != nil {
|
||||
log.Printf("[Notif] Error enviando factura_subida a %s: %v", toEmail, err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"github.com/sujit-baniya/fiber-boilerplate/app"
|
||||
"github.com/sujit-baniya/fiber-boilerplate/pkg/models"
|
||||
)
|
||||
|
||||
@@ -16,7 +15,7 @@ func DispatchTicketNuevo(ticket *models.ProyectoTicket, portalUser *models.Porta
|
||||
if cfg == nil {
|
||||
return
|
||||
}
|
||||
ticketURL := fmt.Sprintf("%s/app/tickets", app.Http.Server.Url)
|
||||
ticketURL := "/app/tickets"
|
||||
titulo := fmt.Sprintf("Nuevo ticket: %s", ticket.Titulo)
|
||||
cuerpo := fmt.Sprintf("Cliente %s abrió: %s", ticket.AutorNombre, ticket.Titulo)
|
||||
|
||||
@@ -50,7 +49,7 @@ func DispatchTicketRespuestaCliente(ticket *models.ProyectoTicket, contenido str
|
||||
if cfg == nil {
|
||||
return
|
||||
}
|
||||
ticketURL := fmt.Sprintf("%s/app/tickets", app.Http.Server.Url)
|
||||
ticketURL := "/app/tickets"
|
||||
titulo := fmt.Sprintf("Respuesta de cliente: %s", ticket.Titulo)
|
||||
cuerpo := fmt.Sprintf("%s respondió: %s", ticket.AutorNombre, contenido)
|
||||
|
||||
@@ -91,7 +90,7 @@ func DispatchTicketRespuestaAdmin(ticket *models.ProyectoTicket, contenido strin
|
||||
return
|
||||
}
|
||||
|
||||
portalURL := fmt.Sprintf("%s/portal/proyecto/%s", app.Http.Server.Url, ticket.Proyecto.Slug)
|
||||
portalURL := fmt.Sprintf("/portal/proyecto/%s", ticket.Proyecto.Slug)
|
||||
titulo := fmt.Sprintf("Respuesta en tu ticket: %s", ticket.Titulo)
|
||||
cuerpo := fmt.Sprintf("El equipo respondió: %s", contenido)
|
||||
|
||||
@@ -160,3 +159,56 @@ func sendTelegramAdmin(mensaje string) {
|
||||
}
|
||||
}
|
||||
}
|
||||
// ─── DispatchFacturaSubida ────────────────────────────────────────────────────
|
||||
// Llamar cuando el admin sube el PDF de una factura.
|
||||
// Notifica a todos los portal_users activos del cliente.
|
||||
func DispatchFacturaSubida(factura *models.Factura) {
|
||||
cfg := models.GetNotifConfig("factura_subida", "portal_user")
|
||||
if cfg == nil {
|
||||
return
|
||||
}
|
||||
if factura.ClienteID == 0 {
|
||||
return
|
||||
}
|
||||
portalUsers, err := models.GetPortalUsersByClienteID(factura.ClienteID)
|
||||
if err != nil || len(portalUsers) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
clienteNombre := ""
|
||||
if factura.Cliente.Nombre != "" {
|
||||
clienteNombre = factura.Cliente.Nombre
|
||||
} else if factura.Cliente.Empresa != "" {
|
||||
clienteNombre = factura.Cliente.Empresa
|
||||
}
|
||||
|
||||
for _, u := range portalUsers {
|
||||
u := u // capture
|
||||
portalURL := "/portal/dashboard"
|
||||
titulo := fmt.Sprintf("Nueva factura disponible: %s", factura.Numero)
|
||||
cuerpo := fmt.Sprintf("Factura %s por %s %s", factura.Numero, factura.Moneda, fmt.Sprintf("%.2f", factura.Monto))
|
||||
|
||||
if cfg.CanalSistema {
|
||||
_ = models.CreateSistemaNotif(&models.SistemaNotificacion{
|
||||
TipoUsuario: "portal_user",
|
||||
UsuarioID: u.ID,
|
||||
Titulo: titulo,
|
||||
Cuerpo: cuerpo,
|
||||
Url: portalURL,
|
||||
Icono: "🧾",
|
||||
})
|
||||
}
|
||||
if cfg.CanalEmail && u.Email != "" {
|
||||
go SendFacturaSubidaPortalUser(u.Email, u.Nombre, clienteNombre, factura.Numero, factura.Monto, factura.Moneda, portalURL)
|
||||
}
|
||||
if cfg.CanalTelegram && u.TelegramChatID != "" {
|
||||
ts := NewTelegramService()
|
||||
msg := fmt.Sprintf("🧾 <b>Nueva factura disponible</b>\nNúmero: <b>%s</b>\nMonto: %s %.2f\n\n🔗 %s",
|
||||
factura.Numero, factura.Moneda, factura.Monto, portalURL)
|
||||
if err := ts.SendMessageWithToken(u.TelegramChatID, msg, getAdminBotToken()); err != nil {
|
||||
log.Printf("[Notif] Error telegram portal_user %d: %v", u.ID, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
log.Printf("[Notif] DispatchFacturaSubida factura=%d clientes notificados=%d", factura.ID, len(portalUsers))
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ShieldClient cliente HTTP para la API de USITE Shield.
|
||||
type ShieldClient struct {
|
||||
baseURL string
|
||||
adminToken string
|
||||
http *http.Client
|
||||
}
|
||||
|
||||
func NewShieldClient(baseURL, adminToken string) *ShieldClient {
|
||||
if baseURL == "" {
|
||||
baseURL = "https://api-shield.u-s.app"
|
||||
}
|
||||
return &ShieldClient{
|
||||
baseURL: baseURL,
|
||||
adminToken: adminToken,
|
||||
http: &http.Client{Timeout: 15 * time.Second},
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ShieldClient) do(method, path string, body interface{}) ([]byte, int, error) {
|
||||
var bodyReader io.Reader
|
||||
if body != nil {
|
||||
b, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
bodyReader = bytes.NewReader(b)
|
||||
}
|
||||
req, err := http.NewRequest(method, s.baseURL+path, bodyReader)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
if s.adminToken != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+s.adminToken)
|
||||
}
|
||||
resp, err := s.http.Do(req)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
data, err := io.ReadAll(resp.Body)
|
||||
return data, resp.StatusCode, err
|
||||
}
|
||||
|
||||
// ─── Health ──────────────────────────────────────────────────────────────────
|
||||
|
||||
func (s *ShieldClient) Health() (map[string]interface{}, error) {
|
||||
data, _, err := s.do("GET", "/health", nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out map[string]interface{}
|
||||
return out, json.Unmarshal(data, &out)
|
||||
}
|
||||
|
||||
// ─── Extension version ───────────────────────────────────────────────────────
|
||||
|
||||
func (s *ShieldClient) ExtensionVersion() (map[string]interface{}, error) {
|
||||
data, _, err := s.do("GET", "/api/extension/version", nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out map[string]interface{}
|
||||
return out, json.Unmarshal(data, &out)
|
||||
}
|
||||
|
||||
// ─── Logs ────────────────────────────────────────────────────────────────────
|
||||
|
||||
func (s *ShieldClient) Logs(limit int, path, method string) (map[string]interface{}, error) {
|
||||
q := fmt.Sprintf("/api/admin/logs?limit=%d", limit)
|
||||
if path != "" {
|
||||
q += "&path=" + path
|
||||
}
|
||||
if method != "" {
|
||||
q += "&method=" + method
|
||||
}
|
||||
data, _, err := s.do("GET", q, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out map[string]interface{}
|
||||
return out, json.Unmarshal(data, &out)
|
||||
}
|
||||
|
||||
func (s *ShieldClient) LogStats() (map[string]interface{}, error) {
|
||||
data, _, err := s.do("GET", "/api/admin/logs/stats", nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out map[string]interface{}
|
||||
return out, json.Unmarshal(data, &out)
|
||||
}
|
||||
|
||||
// ─── Review requests ─────────────────────────────────────────────────────────
|
||||
|
||||
func (s *ShieldClient) ReviewRequests(status string) (map[string]interface{}, error) {
|
||||
if status == "" {
|
||||
status = "pending"
|
||||
}
|
||||
data, _, err := s.do("GET", "/api/admin/review-requests?status="+status, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out map[string]interface{}
|
||||
return out, json.Unmarshal(data, &out)
|
||||
}
|
||||
|
||||
func (s *ShieldClient) ApproveRequest(id, note, reason string) (map[string]interface{}, error) {
|
||||
body := map[string]string{"note": note, "reason": reason}
|
||||
data, code, err := s.do("PUT", "/api/admin/review-requests/"+id+"/approve", body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if code >= 400 {
|
||||
return nil, fmt.Errorf("shield API error %d: %s", code, string(data))
|
||||
}
|
||||
var out map[string]interface{}
|
||||
json.Unmarshal(data, &out)
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (s *ShieldClient) RejectRequest(id, note string) (map[string]interface{}, error) {
|
||||
body := map[string]string{"note": note}
|
||||
data, code, err := s.do("PUT", "/api/admin/review-requests/"+id+"/reject", body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if code >= 400 {
|
||||
return nil, fmt.Errorf("shield API error %d: %s", code, string(data))
|
||||
}
|
||||
var out map[string]interface{}
|
||||
json.Unmarshal(data, &out)
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ─── Whitelist ───────────────────────────────────────────────────────────────
|
||||
|
||||
func (s *ShieldClient) Whitelist() (map[string]interface{}, error) {
|
||||
data, _, err := s.do("GET", "/api/admin/whitelist", nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out map[string]interface{}
|
||||
return out, json.Unmarshal(data, &out)
|
||||
}
|
||||
|
||||
func (s *ShieldClient) AddWhitelist(domain, reason, addedBy string) (map[string]interface{}, error) {
|
||||
body := map[string]string{"domain": domain, "reason": reason, "added_by": addedBy}
|
||||
data, code, err := s.do("POST", "/api/admin/whitelist", body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if code >= 400 {
|
||||
return nil, fmt.Errorf("shield API error %d: %s", code, string(data))
|
||||
}
|
||||
var out map[string]interface{}
|
||||
json.Unmarshal(data, &out)
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (s *ShieldClient) DeleteWhitelist(domain string) error {
|
||||
data, code, err := s.do("DELETE", "/api/admin/whitelist/"+domain, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if code >= 400 {
|
||||
return fmt.Errorf("shield API error %d: %s", code, string(data))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ─── Blacklist ───────────────────────────────────────────────────────────────
|
||||
|
||||
func (s *ShieldClient) Blacklist() (map[string]interface{}, error) {
|
||||
data, _, err := s.do("GET", "/api/admin/blacklist", nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out map[string]interface{}
|
||||
return out, json.Unmarshal(data, &out)
|
||||
}
|
||||
|
||||
func (s *ShieldClient) AddBlacklist(domain, reason, addedBy string) (map[string]interface{}, error) {
|
||||
body := map[string]string{"domain": domain, "reason": reason, "added_by": addedBy}
|
||||
data, code, err := s.do("POST", "/api/admin/blacklist", body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if code >= 400 {
|
||||
return nil, fmt.Errorf("shield API error %d: %s", code, string(data))
|
||||
}
|
||||
var out map[string]interface{}
|
||||
json.Unmarshal(data, &out)
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (s *ShieldClient) DeleteBlacklist(domain string) error {
|
||||
data, code, err := s.do("DELETE", "/api/admin/blacklist/"+domain, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if code >= 400 {
|
||||
return fmt.Errorf("shield API error %d: %s", code, string(data))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ─── Reputación ──────────────────────────────────────────────────────────────
|
||||
|
||||
func (s *ShieldClient) Reputation(domain string) (map[string]interface{}, error) {
|
||||
data, _, err := s.do("GET", "/api/reputation/"+domain, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out map[string]interface{}
|
||||
return out, json.Unmarshal(data, &out)
|
||||
}
|
||||
|
||||
func (s *ShieldClient) AdjustScore(domain string, votesReal, votesFake int) (map[string]interface{}, error) {
|
||||
body := map[string]int{"votes_real": votesReal, "votes_fake": votesFake}
|
||||
data, code, err := s.do("PUT", "/api/admin/reputation/"+domain+"/score", body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if code >= 400 {
|
||||
return nil, fmt.Errorf("shield API error %d: %s", code, string(data))
|
||||
}
|
||||
var out map[string]interface{}
|
||||
json.Unmarshal(data, &out)
|
||||
return out, nil
|
||||
}
|
||||
Reference in New Issue
Block a user