feat: migrar backend unificado a Go 1.27 + SPA Vite embebido

This commit is contained in:
urieljareth
2026-11-28 09:20:55 -06:00
parent 4f64487b88
commit b5ebcd0b86
332 changed files with 29135 additions and 37275 deletions
+349
View File
@@ -0,0 +1,349 @@
package webhooks
import (
"bytes"
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"slices"
"strconv"
"strings"
"time"
"cotizador/internal/config"
"cotizador/internal/db"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgxpool"
)
var EventosOficiales = []string{
"cotizacion.creada",
"cotizacion.aprobada",
"cotizacion.enviada",
"cotizacion.aceptada",
"cotizacion.rechazada",
"cotizacion.vencida",
"pago.registrado",
"pago.vencido",
}
func EsEventoValido(evento string) bool {
return evento == "*" || slices.Contains(EventosOficiales, evento)
}
// FirmarPayload returns "sha256=<64-hex>" HMAC-SHA256 signature.
func FirmarPayload(rawPayload []byte, secret string) string {
mac := hmac.New(sha256.New, []byte(secret))
mac.Write(rawPayload)
return "sha256=" + hex.EncodeToString(mac.Sum(nil))
}
// VerificarFirma performs constant-time HMAC-SHA256 verification.
func VerificarFirma(rawPayload []byte, signatureHeader, secret string) bool {
if secret == "" || !strings.HasPrefix(signatureHeader, "sha256=") {
return false
}
expected := FirmarPayload(rawPayload, secret)
return hmac.Equal([]byte(expected), []byte(signatureHeader))
}
type Dispatcher struct {
pool *pgxpool.Pool
cfg *config.Config
client *http.Client
}
func NewDispatcher(pool *pgxpool.Pool, cfg *config.Config) *Dispatcher {
return &Dispatcher{
pool: pool,
cfg: cfg,
client: &http.Client{Timeout: 8 * time.Second},
}
}
type target struct {
EndpointID *string
URL string
Secret string
}
func (d *Dispatcher) Emitir(ctx context.Context, evento string, data map[string]any) {
if d == nil || d.pool == nil {
return
}
var targets []target
seenURL := map[string]bool{}
rows, err := d.pool.Query(ctx, `
SELECT "id", "url", "secret", "eventos"
FROM "WebhookEndpoint"
WHERE "activo" = true
`)
if err == nil {
defer rows.Close()
for rows.Next() {
var id, urlStr, secret string
var eventos []string
if err := rows.Scan(&id, &urlStr, &secret, &eventos); err != nil {
continue
}
if slices.Contains(eventos, "*") || slices.Contains(eventos, evento) {
eid := id
targets = append(targets, target{EndpointID: &eid, URL: urlStr, Secret: secret})
seenURL[urlStr] = true
}
}
}
if d.cfg != nil && d.cfg.WebhookN8NURL != "" && !seenURL[d.cfg.WebhookN8NURL] {
targets = append(targets, target{
EndpointID: nil,
URL: d.cfg.WebhookN8NURL,
Secret: d.cfg.WebhookN8NSecret,
})
}
if len(targets) == 0 {
return
}
envelope := map[string]any{
"event": evento,
"timestamp": time.Now().UTC().Format(time.RFC3339),
"data": data,
}
rawPayload, err := json.Marshal(envelope)
if err != nil {
return
}
for _, t := range targets {
d.deliverWithRetry(ctx, t, evento, rawPayload)
}
}
func (d *Dispatcher) deliverWithRetry(ctx context.Context, t target, evento string, rawPayload []byte) {
deliveryID := uuid.NewString()
ts := strconv.FormatInt(time.Now().Unix(), 10)
sig := ""
if t.Secret != "" {
sig = FirmarPayload(rawPayload, t.Secret)
}
var statusCode *int
var lastErr string
exito := false
intentos := 0
for attempt := 1; attempt <= 3; attempt++ {
intentos = attempt
req, err := http.NewRequestWithContext(ctx, http.MethodPost, t.URL, bytes.NewReader(rawPayload))
if err != nil {
lastErr = err.Error()
break
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Cotizador-Event", evento)
req.Header.Set("X-Cotizador-Timestamp", ts)
req.Header.Set("X-Cotizador-Delivery-Id", deliveryID)
if sig != "" {
req.Header.Set("X-Cotizador-Signature", sig)
}
resp, err := d.client.Do(req)
if err != nil {
lastErr = err.Error()
} else {
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))
_ = resp.Body.Close()
sc := resp.StatusCode
statusCode = &sc
if sc >= 200 && sc < 300 {
exito = true
lastErr = ""
break
}
lastErr = fmt.Sprintf("HTTP %d", sc)
if sc < 500 {
break
}
}
if attempt < 3 {
time.Sleep(time.Duration(attempt) * 500 * time.Millisecond)
}
}
var errPtr *string
if lastErr != "" {
errPtr = &lastErr
}
_, err := d.pool.Exec(ctx, `
INSERT INTO "WebhookDelivery" ("id", "endpointId", "url", "evento", "payload", "statusCode", "exito", "intentos", "error")
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
`, db.NewID(), t.EndpointID, t.URL, evento, rawPayload, statusCode, exito, intentos, errPtr)
if err != nil {
log.Printf("[webhooks] error guardando WebhookDelivery (%s -> %s): %v", evento, t.URL, err)
}
}
type WhatsAppSendResult struct {
OK bool
Outside24h bool
StatusCode int
ErrorMessage string
ResponsePayload map[string]any
}
// InvocarEnvioWhatsAppN8n sends cotizacion.enviar_whatsapp to WEBHOOK_WHATSAPP_SEND_URL (15s timeout, no retries).
func (d *Dispatcher) InvocarEnvioWhatsAppN8n(ctx context.Context, payload map[string]any) WhatsAppSendResult {
if d == nil || d.cfg == nil || d.cfg.WebhookWhatsAppSendURL == "" {
return WhatsAppSendResult{
OK: false,
ErrorMessage: "WEBHOOK_WHATSAPP_SEND_URL no esta configurado",
}
}
raw, err := json.Marshal(payload)
if err != nil {
return WhatsAppSendResult{OK: false, ErrorMessage: err.Error()}
}
client := &http.Client{Timeout: 15 * time.Second}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, d.cfg.WebhookWhatsAppSendURL, bytes.NewReader(raw))
if err != nil {
return WhatsAppSendResult{OK: false, ErrorMessage: err.Error()}
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Cotizador-Event", "cotizacion.enviar_whatsapp")
req.Header.Set("X-Cotizador-Timestamp", strconv.FormatInt(time.Now().Unix(), 10))
req.Header.Set("X-Cotizador-Delivery-Id", uuid.NewString())
if d.cfg.WebhookN8NSecret != "" {
req.Header.Set("X-Cotizador-Signature", FirmarPayload(raw, d.cfg.WebhookN8NSecret))
}
resp, err := client.Do(req)
if err != nil {
return WhatsAppSendResult{OK: false, ErrorMessage: err.Error()}
}
defer resp.Body.Close()
bodyBytes, _ := io.ReadAll(io.LimitReader(resp.Body, 64*1024))
var parsed map[string]any
_ = json.Unmarshal(bodyBytes, &parsed)
outside := false
if parsed != nil {
if v, ok := parsed["outside_24h_window"].(bool); ok && v {
outside = true
}
if code, ok := parsed["code"].(string); ok && code == "outside_24h_window" {
outside = true
}
if errStr, ok := parsed["error"].(string); ok && strings.Contains(strings.ToLower(errStr), "outside_24h") {
outside = true
}
}
if resp.StatusCode >= 200 && resp.StatusCode < 300 && !outside {
return WhatsAppSendResult{
OK: true,
StatusCode: resp.StatusCode,
ResponsePayload: parsed,
}
}
errMsg := fmt.Sprintf("HTTP %d", resp.StatusCode)
if parsed != nil {
if m, ok := parsed["error"].(string); ok && m != "" {
errMsg = m
} else if m, ok := parsed["message"].(string); ok && m != "" {
errMsg = m
}
}
return WhatsAppSendResult{
OK: false,
Outside24h: outside,
StatusCode: resp.StatusCode,
ErrorMessage: errMsg,
ResponsePayload: parsed,
}
}
type PagoVencidoItem struct {
PagoID string
ProgramaID string
ClienteID string
ClienteNombre string
ClienteEmpresa string
ClienteEmail string
ClienteTelefono string
Concepto string
Monto float64
Moneda string
Fecha string
DiasAtraso int
}
// PagoVencidoStore abstracts atomic claim for testability.
type PagoVencidoStore interface {
ClaimVencido(ctx context.Context, pagoID string) (bool, error)
}
type pgPagoVencidoStore struct {
pool *pgxpool.Pool
}
func (s pgPagoVencidoStore) ClaimVencido(ctx context.Context, pagoID string) (bool, error) {
tag, err := s.pool.Exec(ctx, `
UPDATE "PagoRecurrente"
SET "vencidoNotificadoAt" = NOW(), "updatedAt" = NOW()
WHERE "id" = $1 AND "vencidoNotificadoAt" IS NULL
`, pagoID)
if err != nil {
return false, err
}
return tag.RowsAffected() == 1, nil
}
// EmitirPagosVencidosIdempotente atomically stamps vencidoNotificadoAt and emits pago.vencido once per charge.
func EmitirPagosVencidosIdempotente(ctx context.Context, store PagoVencidoStore, items []PagoVencidoItem, emit func(ctx context.Context, evento string, data map[string]any)) int {
emitted := 0
for _, it := range items {
claimed, err := store.ClaimVencido(ctx, it.PagoID)
if err != nil || !claimed {
continue
}
emit(ctx, "pago.vencido", map[string]any{
"pagoId": it.PagoID,
"programaId": it.ProgramaID,
"clienteId": it.ClienteID,
"clienteNombre": it.ClienteNombre,
"clienteEmpresa": it.ClienteEmpresa,
"clienteEmail": it.ClienteEmail,
"clienteTelefono": it.ClienteTelefono,
"concepto": it.Concepto,
"monto": it.Monto,
"moneda": it.Moneda,
"fecha": it.Fecha,
"diasAtraso": it.DiasAtraso,
})
emitted++
}
return emitted
}
func (d *Dispatcher) EmitirPagosVencidos(ctx context.Context, items []PagoVencidoItem) int {
if d == nil || d.pool == nil {
return 0
}
return EmitirPagosVencidosIdempotente(ctx, pgPagoVencidoStore{pool: d.pool}, items, d.Emitir)
}