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
+476
View File
@@ -0,0 +1,476 @@
package propuesta
import (
"fmt"
"math"
"regexp"
"strings"
"unicode"
"golang.org/x/text/unicode/norm"
)
// Aviso describe un hallazgo de validacion post-generacion.
// Severidad: "bloqueante" | "advertencia".
type Aviso struct {
Regla string `json:"regla"`
Severidad string `json:"severidad"`
Mensaje string `json:"mensaje"`
Campo string `json:"campo,omitempty"`
}
// NormalizarTexto quita acentos, pasa a minusculas, elimina puntuacion y
// colapsa espacios. Laxa a proposito para sobrevivir al ruido de transcripcion.
func NormalizarTexto(s string) string {
decomposed := norm.NFD.String(s)
var b strings.Builder
b.Grow(len(decomposed))
for _, r := range decomposed {
if unicode.Is(unicode.Mn, r) {
continue
}
r = unicode.ToLower(r)
if unicode.IsLetter(r) || unicode.IsNumber(r) {
b.WriteRune(r)
} else {
b.WriteByte(' ')
}
}
return strings.Join(strings.Fields(b.String()), " ")
}
var (
reOtroCRM = regexp.MustCompile(`(?i)\b(hubspot|salesforce|pipedrive|zoho|go\s*high\s*level|gohighlevel|clientify|kommo|monday\s*crm)\b`)
rePromesaGarantia = regexp.MustCompile(`(?i)\bgarantiza(mos|do|da|r|remos)?\b|\baseguramos\s+(ventas|resultados|posici)`)
reMontoUSD = regexp.MustCompile(`(?i)\b(usd|d[oóÓ]lares|dlls?)\b|\$\s*[\d,.]+\s*(usd|dls)\b`)
reTemaSensible = regexp.MustCompile(`(?i)\b(sueldo|salario|n[oóÓ]mina|despido|demanda laboral|incapacidad|embarazo|enfermedad)\b`)
)
type campoVisible struct {
campo string
texto string
}
func getMap(m map[string]any, key string) map[string]any {
if m == nil {
return nil
}
if sub, ok := m[key].(map[string]any); ok {
return sub
}
return nil
}
func getSlice(m map[string]any, key string) []any {
if m == nil {
return nil
}
if arr, ok := m[key].([]any); ok {
return arr
}
return nil
}
func getString(m map[string]any, key string) string {
if m == nil {
return ""
}
if s, ok := m[key].(string); ok {
return s
}
return ""
}
// textoVisible recopila TODOS los campos de texto que terminan impresos en el
// documento del cliente (excluyendo notasInternas, redFlags y razon de exclusiones).
func textoVisible(contenido map[string]any) []campoVisible {
hechos := getMap(contenido, "hechos")
diag := getMap(contenido, "diagnostico")
red := getMap(contenido, "redaccion")
hero := getMap(red, "hero")
vp := getMap(diag, "valorProblema")
out := []campoVisible{
{campo: "hero.titulo", texto: getString(hero, "titulo")},
{campo: "hero.subtitulo", texto: getString(hero, "subtitulo")},
{campo: "valorProblema.notaMetodologia", texto: getString(vp, "notaMetodologia")},
}
citaDestID := getString(red, "citaDestacadaId")
for _, raw := range getSlice(hechos, "citas") {
c, ok := raw.(map[string]any)
if !ok {
continue
}
id := getString(c, "id")
if id != "" && id == citaDestID {
out = append(out,
campoVisible{campo: fmt.Sprintf("citas.%s.textoLiteral", id), texto: getString(c, "textoLiteral")},
campoVisible{campo: fmt.Sprintf("citas.%s.quienLoDijo", id), texto: getString(c, "quienLoDijo")},
)
break
}
}
for i, raw := range getSlice(diag, "hallazgos") {
h, ok := raw.(map[string]any)
if !ok {
continue
}
out = append(out,
campoVisible{campo: fmt.Sprintf("hallazgos[%d].titulo", i), texto: getString(h, "titulo")},
campoVisible{campo: fmt.Sprintf("hallazgos[%d].descripcion", i), texto: getString(h, "descripcion")},
)
}
for i, raw := range getSlice(vp, "dimensiones") {
d, ok := raw.(map[string]any)
if !ok {
continue
}
out = append(out, campoVisible{
campo: fmt.Sprintf("valorProblema.dimensiones[%d]", i),
texto: getString(d, "descripcion"),
})
}
for i, raw := range getSlice(diag, "resultados") {
r, ok := raw.(map[string]any)
if !ok {
continue
}
out = append(out,
campoVisible{campo: fmt.Sprintf("resultados[%d].enunciado", i), texto: getString(r, "enunciado")},
campoVisible{campo: fmt.Sprintf("resultados[%d].metrica", i), texto: getString(r, "metrica")},
campoVisible{campo: fmt.Sprintf("resultados[%d].periodoMedicion", i), texto: getString(r, "periodoMedicion")},
)
}
for i, raw := range getSlice(red, "alcance") {
a, ok := raw.(map[string]any)
if !ok {
continue
}
out = append(out, campoVisible{
campo: fmt.Sprintf("alcance[%d]", i),
texto: getString(a, "descripcionResultado"),
})
}
for i, raw := range getSlice(red, "beneficios") {
b, ok := raw.(map[string]any)
if !ok {
continue
}
out = append(out, campoVisible{
campo: fmt.Sprintf("beneficios[%d]", i),
texto: getString(b, "etiqueta") + " " + getString(b, "texto"),
})
}
for i, raw := range getSlice(red, "exclusiones") {
e, ok := raw.(map[string]any)
if !ok {
continue
}
out = append(out, campoVisible{
campo: fmt.Sprintf("exclusiones[%d]", i),
texto: getString(e, "texto"),
})
}
for i, raw := range getSlice(red, "backlogEvolucion") {
b, ok := raw.(map[string]any)
if !ok {
continue
}
out = append(out,
campoVisible{campo: fmt.Sprintf("backlog[%d].problema", i), texto: getString(b, "problema")},
campoVisible{campo: fmt.Sprintf("backlog[%d].momentoSugerido", i), texto: getString(b, "momentoSugerido")},
)
}
for i, raw := range getSlice(hechos, "materialesPendientes") {
m, ok := raw.(map[string]any)
if !ok {
continue
}
out = append(out, campoVisible{
campo: fmt.Sprintf("materiales[%d]", i),
texto: getString(m, "texto"),
})
}
for i, raw := range getSlice(hechos, "decisionesPendientes") {
d, ok := raw.(map[string]any)
if !ok {
continue
}
out = append(out,
campoVisible{campo: fmt.Sprintf("decisiones[%d].texto", i), texto: getString(d, "texto")},
campoVisible{campo: fmt.Sprintf("decisiones[%d].quienDecide", i), texto: getString(d, "quienDecide")},
)
}
return out
}
func ngramas(texto string, n int) map[string]struct{} {
palabras := strings.Fields(NormalizarTexto(texto))
out := make(map[string]struct{})
if n <= 0 || len(palabras) < n {
return out
}
for i := 0; i+n <= len(palabras); i++ {
out[strings.Join(palabras[i:i+n], " ")] = struct{}{}
}
return out
}
func truncar(s string, max int) string {
r := []rune(s)
if len(r) <= max {
return s
}
return string(r[:max])
}
// ValidarPropuesta ejecuta las reglas deterministicas post-generacion:
// R0, R2, R2b, R3, R4, R5, R5b, R6, MARCA, MONEDA, GARANTIA y PII.
func ValidarPropuesta(contenido map[string]any, economia *EconomiaCotizacion, fuentesCliente string, notasInternas string) []Aviso {
avisos := make([]Aviso, 0)
visible := textoVisible(contenido)
hechos := getMap(contenido, "hechos")
diag := getMap(contenido, "diagnostico")
red := getMap(contenido, "redaccion")
vp := getMap(diag, "valorProblema")
// ── R0 (bloqueante): fuga de notas internas del asesor (7-gramas) ──
if strings.TrimSpace(notasInternas) != "" {
internos := ngramas(notasInternas, 7)
if len(internos) > 0 {
for _, v := range visible {
palabras := strings.Fields(NormalizarTexto(v.texto))
for i := 0; i+7 <= len(palabras); i++ {
g := strings.Join(palabras[i:i+7], " ")
if _, leaked := internos[g]; leaked {
avisos = append(avisos, Aviso{
Regla: "R0",
Severidad: "bloqueante",
Campo: v.campo,
Mensaje: fmt.Sprintf("Texto de las notas internas aparece en el documento del cliente: %q", g),
})
break
}
}
}
}
}
// ── R2 (bloqueante) / R2b (advertencia): correspondencia de partidas ──
refsReales := make(map[string]bool)
if economia != nil {
for _, p := range economia.Partidas {
refsReales[p.Ref] = true
}
}
refsUsadas := make(map[string]bool)
for _, raw := range getSlice(red, "alcance") {
a, ok := raw.(map[string]any)
if !ok {
continue
}
ref := getString(a, "refPartida")
refsUsadas[ref] = true
if !refsReales[ref] {
avisos = append(avisos, Aviso{
Regla: "R2",
Severidad: "bloqueante",
Campo: "alcance " + ref,
Mensaje: fmt.Sprintf("La partida %s no existe en la cotizacion.", ref),
})
}
}
if economia != nil {
for _, real := range economia.Partidas {
if !refsUsadas[real.Ref] {
avisos = append(avisos, Aviso{
Regla: "R2b",
Severidad: "advertencia",
Campo: real.Ref,
Mensaje: fmt.Sprintf("La partida %q (%s) esta cotizada pero no aparece descrita.", real.Nombre, real.Ref),
})
}
}
}
// ── R3 (bloqueante): cita destacada existe y aparece literal en fuentesCliente ──
citaID := getString(red, "citaDestacadaId")
var citaEncontrada map[string]any
for _, raw := range getSlice(hechos, "citas") {
c, ok := raw.(map[string]any)
if ok && getString(c, "id") == citaID && citaID != "" {
citaEncontrada = c
break
}
}
if citaEncontrada == nil {
avisos = append(avisos, Aviso{
Regla: "R3",
Severidad: "bloqueante",
Campo: "citaDestacadaId",
Mensaje: fmt.Sprintf("citaDestacadaId %s no corresponde a ninguna cita extraida.", citaID),
})
} else if strings.TrimSpace(fuentesCliente) != "" {
textoLiteral := getString(citaEncontrada, "textoLiteral")
if !strings.Contains(NormalizarTexto(fuentesCliente), NormalizarTexto(textoLiteral)) {
avisos = append(avisos, Aviso{
Regla: "R3",
Severidad: "bloqueante",
Campo: citaID,
Mensaje: fmt.Sprintf("La cita destacada no aparece literal en las fuentes: \"%s...\"", truncar(textoLiteral, 70)),
})
}
}
// ── R4 (advertencia): hallazgo confirmado sin citas ni hechos ──
idsHallazgo := make(map[string]bool)
for i, raw := range getSlice(diag, "hallazgos") {
h, ok := raw.(map[string]any)
if !ok {
continue
}
if id := getString(h, "id"); id != "" {
idsHallazgo[id] = true
}
if getString(h, "confianza") == "confirmado" && len(getSlice(h, "citas"))+len(getSlice(h, "hechos")) == 0 {
avisos = append(avisos, Aviso{
Regla: "R4",
Severidad: "advertencia",
Campo: fmt.Sprintf("hallazgos[%d]", i),
Mensaje: fmt.Sprintf("%q se declara confirmado sin citas ni hechos. Deberia ser por_validar.", getString(h, "titulo")),
})
}
}
// ── R5 (bloqueante) y R5b (advertencia): aritmetica y evidencia del valor anual ──
for i, raw := range getSlice(vp, "dimensiones") {
d, ok := raw.(map[string]any)
if !ok {
continue
}
rawMonto, exists := d["montoAnualMXN"]
if !exists || rawMonto == nil {
continue
}
m, ok := asNumber(rawMonto)
if !ok {
continue
}
factores := getSlice(d, "factores")
producto := 1.0
suma := 0.0
confirmados := 0
for _, fRaw := range factores {
f, ok := fRaw.(map[string]any)
if !ok {
continue
}
val, _ := asNumber(f["valor"])
producto *= val
suma += val
if getString(f, "confianza") == "confirmado" {
confirmados++
}
}
base := math.Max(math.Abs(m), 1.0)
cuadra := math.Abs(producto-m)/base < 0.02 || math.Abs(suma-m)/base < 0.02
if !cuadra {
avisos = append(avisos, Aviso{
Regla: "R5",
Severidad: "bloqueante",
Campo: fmt.Sprintf("valorProblema.dimensiones[%d]", i),
Mensaje: fmt.Sprintf("montoAnualMXN %v no cuadra con sus factores (producto %v, suma %v).", m, producto, suma),
})
}
if confirmados == 0 {
avisos = append(avisos, Aviso{
Regla: "R5b",
Severidad: "advertencia",
Campo: fmt.Sprintf("valorProblema.dimensiones[%d]", i),
Mensaje: fmt.Sprintf(
"La cifra de %v no tiene ni un factor confirmado: descansa entera en estimaciones. Revisa el desglose antes de fiarte del ratio precio/valor.",
m,
),
})
}
}
// ── R6 (advertencia): referencias colgantes de hallazgoId en beneficios ──
for i, raw := range getSlice(red, "beneficios") {
b, ok := raw.(map[string]any)
if !ok {
continue
}
hid := getString(b, "hallazgoId")
if !idsHallazgo[hid] {
avisos = append(avisos, Aviso{
Regla: "R6",
Severidad: "advertencia",
Campo: fmt.Sprintf("beneficios[%d]", i),
Mensaje: fmt.Sprintf("El beneficio apunta al hallazgo %s, que no existe.", hid),
})
}
}
// ── Filtros de contenido sobre lo visible al cliente ──
for _, v := range visible {
if reOtroCRM.MatchString(v.texto) {
avisos = append(avisos, Aviso{
Regla: "MARCA",
Severidad: "bloqueante",
Campo: v.campo,
Mensaje: "Menciona un CRM que no es Bucefalo.",
})
}
if reMontoUSD.MatchString(v.texto) {
avisos = append(avisos, Aviso{
Regla: "MONEDA",
Severidad: "bloqueante",
Campo: v.campo,
Mensaje: "Contiene un monto o referencia en USD.",
})
}
if rePromesaGarantia.MatchString(v.texto) {
avisos = append(avisos, Aviso{
Regla: "GARANTIA",
Severidad: "bloqueante",
Campo: v.campo,
Mensaje: "Promete un resultado garantizado.",
})
}
if reTemaSensible.MatchString(v.texto) {
avisos = append(avisos, Aviso{
Regla: "PII",
Severidad: "advertencia",
Campo: v.campo,
Mensaje: "Menciona un tema laboral, salarial o de salud. Revisalo antes de enviar.",
})
}
}
return avisos
}
// HayBloqueantes devuelve true si algun aviso tiene severidad "bloqueante".
func HayBloqueantes(avisos []Aviso) bool {
for _, a := range avisos {
if a.Severidad == "bloqueante" {
return true
}
}
return false
}