feat: migrar backend unificado a Go 1.27 + SPA Vite embebido
This commit is contained in:
@@ -0,0 +1,476 @@
|
||||
package propuesta
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"cotizador/internal/config"
|
||||
)
|
||||
|
||||
const (
|
||||
DefaultMinimaxBaseURL = "https://api.minimax.io/anthropic"
|
||||
DefaultMinimaxModel = "MiniMax-M3"
|
||||
anthropicVersion = "2023-06-01"
|
||||
maxTransitoriosDef = 3
|
||||
)
|
||||
|
||||
// UsoTokens acumula el consumo de tokens reportado por el endpoint de mensajes.
|
||||
type UsoTokens struct {
|
||||
Entrada int `json:"entrada"`
|
||||
Salida int `json:"salida"`
|
||||
CacheLectura int `json:"cacheLectura"`
|
||||
CacheEscritura int `json:"cacheEscritura"`
|
||||
}
|
||||
|
||||
// BloqueSystem representa un bloque del prompt de sistema con cache opcional.
|
||||
type BloqueSystem struct {
|
||||
Texto string
|
||||
Cachear bool
|
||||
}
|
||||
|
||||
// Herramienta define la herramienta de salida estructurada para tool-calling.
|
||||
type Herramienta struct {
|
||||
Nombre string
|
||||
Descripcion string
|
||||
InputSchema map[string]any
|
||||
Validar func(datos map[string]any) []string
|
||||
}
|
||||
|
||||
// OpcionesLlamada configura una invocacion con tool-calling y bucle de validacion.
|
||||
type OpcionesLlamada struct {
|
||||
System []BloqueSystem
|
||||
MensajeUsuario string
|
||||
Herramienta Herramienta
|
||||
MaxIntentos int
|
||||
MaxTokens int
|
||||
}
|
||||
|
||||
// ResultadoLlamada contiene la salida validada, el uso acumulado y los intentos.
|
||||
type ResultadoLlamada struct {
|
||||
Datos map[string]any
|
||||
Uso UsoTokens
|
||||
Intentos int
|
||||
}
|
||||
|
||||
// ClienteIA habla con el endpoint compatible con Anthropic Messages de MiniMax
|
||||
// usando net/http puro (sin SDK externo).
|
||||
type ClienteIA struct {
|
||||
APIKey string
|
||||
BaseURL string
|
||||
Model string
|
||||
HTTPClient *http.Client
|
||||
Sleep func(ctx context.Context, d time.Duration) error
|
||||
}
|
||||
|
||||
// NuevoClienteIA construye el cliente de MiniMax leyendo MINIMAX_API_KEY,
|
||||
// MINIMAX_BASE_URL y MINIMAX_MODEL (desde cfg si se pasa, o desde el entorno).
|
||||
// Rechaza explicitamente una clave vacia y advierte cuando solo ANTHROPIC_API_KEY
|
||||
// esta presente para evitar enviar credenciales al proveedor equivocado.
|
||||
func NuevoClienteIA(cfg *config.Config) (*ClienteIA, error) {
|
||||
var apiKey, baseURL, model string
|
||||
if cfg != nil {
|
||||
apiKey = strings.TrimSpace(cfg.MinimaxAPIKey)
|
||||
baseURL = strings.TrimSpace(cfg.MinimaxBaseURL)
|
||||
model = strings.TrimSpace(cfg.MinimaxModel)
|
||||
} else {
|
||||
apiKey = strings.TrimSpace(os.Getenv("MINIMAX_API_KEY"))
|
||||
baseURL = strings.TrimSpace(os.Getenv("MINIMAX_BASE_URL"))
|
||||
model = strings.TrimSpace(os.Getenv("MINIMAX_MODEL"))
|
||||
}
|
||||
|
||||
if apiKey == "" {
|
||||
if strings.TrimSpace(os.Getenv("ANTHROPIC_API_KEY")) != "" {
|
||||
return nil, errors.New(
|
||||
"Falta MINIMAX_API_KEY (se detecto ANTHROPIC_API_KEY en el entorno, pero NO se usa para evitar mandar credenciales al proveedor equivocado). Define MINIMAX_API_KEY en .env.",
|
||||
)
|
||||
}
|
||||
return nil, errors.New(
|
||||
"Falta MINIMAX_API_KEY. Definela en .env. No uses ANTHROPIC_API_KEY: la clave de MiniMax nunca debe enviarse a api.anthropic.com.",
|
||||
)
|
||||
}
|
||||
|
||||
if baseURL == "" {
|
||||
baseURL = DefaultMinimaxBaseURL
|
||||
}
|
||||
baseURL = strings.TrimRight(baseURL, "/")
|
||||
|
||||
if model == "" {
|
||||
model = DefaultMinimaxModel
|
||||
}
|
||||
|
||||
return &ClienteIA{
|
||||
APIKey: apiKey,
|
||||
BaseURL: baseURL,
|
||||
Model: model,
|
||||
HTTPClient: &http.Client{
|
||||
Timeout: 120 * time.Second,
|
||||
},
|
||||
Sleep: sleepContext,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// NormalizarRespuesta corrige rarezas observadas en las respuestas de MiniMax
|
||||
// antes de validar: a veces envuelve elementos de arrays en `{item: {...}}`.
|
||||
// Solo desenvuelve cuando "item" es la UNICA clave del objeto.
|
||||
func NormalizarRespuesta(v any) any {
|
||||
switch val := v.(type) {
|
||||
case []any:
|
||||
out := make([]any, len(val))
|
||||
for i, elem := range val {
|
||||
out[i] = NormalizarRespuesta(elem)
|
||||
}
|
||||
return out
|
||||
case map[string]any:
|
||||
if len(val) == 1 {
|
||||
if inner, ok := val["item"]; ok {
|
||||
return NormalizarRespuesta(inner)
|
||||
}
|
||||
}
|
||||
out := make(map[string]any, len(val))
|
||||
for k, elem := range val {
|
||||
out[k] = NormalizarRespuesta(elem)
|
||||
}
|
||||
return out
|
||||
default:
|
||||
return v
|
||||
}
|
||||
}
|
||||
|
||||
type apiCacheControl struct {
|
||||
Type string `json:"type"`
|
||||
}
|
||||
|
||||
type apiSystemBlock struct {
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text"`
|
||||
CacheControl *apiCacheControl `json:"cache_control,omitempty"`
|
||||
}
|
||||
|
||||
type apiTool struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
InputSchema map[string]any `json:"input_schema"`
|
||||
}
|
||||
|
||||
type apiToolChoice struct {
|
||||
Type string `json:"type"`
|
||||
Name string `json:"name,omitempty"`
|
||||
}
|
||||
|
||||
type apiMessage struct {
|
||||
Role string `json:"role"`
|
||||
Content any `json:"content"`
|
||||
}
|
||||
|
||||
type apiRequest struct {
|
||||
Model string `json:"model"`
|
||||
MaxTokens int `json:"max_tokens"`
|
||||
System []apiSystemBlock `json:"system,omitempty"`
|
||||
Tools []apiTool `json:"tools,omitempty"`
|
||||
ToolChoice *apiToolChoice `json:"tool_choice,omitempty"`
|
||||
Messages []apiMessage `json:"messages"`
|
||||
}
|
||||
|
||||
type apiContentBlock struct {
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text,omitempty"`
|
||||
ID string `json:"id,omitempty"`
|
||||
Name string `json:"name,omitempty"`
|
||||
Input any `json:"input,omitempty"`
|
||||
}
|
||||
|
||||
type apiUsage struct {
|
||||
InputTokens int `json:"input_tokens"`
|
||||
OutputTokens int `json:"output_tokens"`
|
||||
CacheReadInputTokens int `json:"cache_read_input_tokens"`
|
||||
CacheCreationInputTokens int `json:"cache_creation_input_tokens"`
|
||||
}
|
||||
|
||||
type apiResponse struct {
|
||||
ID string `json:"id"`
|
||||
Type string `json:"type"`
|
||||
Role string `json:"role"`
|
||||
Content []apiContentBlock `json:"content"`
|
||||
StopReason string `json:"stop_reason"`
|
||||
Usage apiUsage `json:"usage"`
|
||||
}
|
||||
|
||||
type apiHTTPError struct {
|
||||
Status int
|
||||
Body string
|
||||
}
|
||||
|
||||
func (e *apiHTTPError) Error() string {
|
||||
return fmt.Sprintf("error HTTP %d del proveedor IA: %s", e.Status, e.Body)
|
||||
}
|
||||
|
||||
var (
|
||||
reTransitorio400 = regexp.MustCompile(`(?i)unexpected|internal|parse|unknown`)
|
||||
reTransitorioRed = regexp.MustCompile(`(?i)ECONN|ETIMEDOUT|socket|network|connection reset|EOF|timeout`)
|
||||
)
|
||||
|
||||
func esTransitorio(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
|
||||
return false
|
||||
}
|
||||
var httpErr *apiHTTPError
|
||||
if errors.As(err, &httpErr) {
|
||||
switch httpErr.Status {
|
||||
case http.StatusRequestTimeout, http.StatusConflict, http.StatusTooManyRequests:
|
||||
return true
|
||||
}
|
||||
if httpErr.Status >= 500 {
|
||||
return true
|
||||
}
|
||||
if httpErr.Status == http.StatusBadRequest && reTransitorio400.MatchString(httpErr.Body) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
var netErr net.Error
|
||||
if errors.As(err, &netErr) {
|
||||
return true
|
||||
}
|
||||
return reTransitorioRed.MatchString(err.Error())
|
||||
}
|
||||
|
||||
func sleepContext(ctx context.Context, d time.Duration) error {
|
||||
t := time.NewTimer(d)
|
||||
defer t.Stop()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-t.C:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func (c *ClienteIA) crearMensaje(ctx context.Context, reqBody apiRequest) (*apiResponse, error) {
|
||||
payload, err := json.Marshal(reqBody)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error serializando solicitud IA: %w", err)
|
||||
}
|
||||
|
||||
endpoint := strings.TrimRight(c.BaseURL, "/") + "/v1/messages"
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(payload))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error creando solicitud HTTP: %w", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("x-api-key", c.APIKey)
|
||||
req.Header.Set("anthropic-version", anthropicVersion)
|
||||
|
||||
httpClient := c.HTTPClient
|
||||
if httpClient == nil {
|
||||
httpClient = &http.Client{Timeout: 120 * time.Second}
|
||||
}
|
||||
|
||||
resp, err := httpClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
raw, err := io.ReadAll(io.LimitReader(resp.Body, 10<<20))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
bodyStr := strings.TrimSpace(string(raw))
|
||||
if len(bodyStr) > 1000 {
|
||||
bodyStr = bodyStr[:1000]
|
||||
}
|
||||
return nil, &apiHTTPError{Status: resp.StatusCode, Body: bodyStr}
|
||||
}
|
||||
|
||||
var parsed apiResponse
|
||||
if err := json.Unmarshal(raw, &parsed); err != nil {
|
||||
return nil, fmt.Errorf("error decodificando respuesta IA: %w", err)
|
||||
}
|
||||
return &parsed, nil
|
||||
}
|
||||
|
||||
func (c *ClienteIA) crearMensajeConReintentos(ctx context.Context, reqBody apiRequest, maxTransitorios int) (*apiResponse, error) {
|
||||
if maxTransitorios <= 0 {
|
||||
maxTransitorios = maxTransitoriosDef
|
||||
}
|
||||
sleepFn := c.Sleep
|
||||
if sleepFn == nil {
|
||||
sleepFn = sleepContext
|
||||
}
|
||||
|
||||
var ultimo error
|
||||
for i := 1; i <= maxTransitorios; i++ {
|
||||
res, err := c.crearMensaje(ctx, reqBody)
|
||||
if err == nil {
|
||||
return res, nil
|
||||
}
|
||||
ultimo = err
|
||||
if !esTransitorio(err) || i == maxTransitorios {
|
||||
return nil, err
|
||||
}
|
||||
backoff := time.Duration(1<<(i-1)) * time.Second // 1s, 2s
|
||||
if sleepErr := sleepFn(ctx, backoff); sleepErr != nil {
|
||||
return nil, sleepErr
|
||||
}
|
||||
}
|
||||
return nil, ultimo
|
||||
}
|
||||
|
||||
// LlamarConHerramienta invoca al modelo exigiendo una llamada a opts.Herramienta,
|
||||
// normaliza rarezas de MiniMax, valida contra el contrato y reintenta devolviendo
|
||||
// los errores exactos de validacion hasta opts.MaxIntentos.
|
||||
func (c *ClienteIA) LlamarConHerramienta(ctx context.Context, opts OpcionesLlamada) (*ResultadoLlamada, error) {
|
||||
maxIntentos := opts.MaxIntentos
|
||||
if maxIntentos <= 0 {
|
||||
maxIntentos = 3
|
||||
}
|
||||
maxTokens := opts.MaxTokens
|
||||
if maxTokens <= 0 {
|
||||
maxTokens = 8000
|
||||
}
|
||||
|
||||
systemBlocks := make([]apiSystemBlock, 0, len(opts.System))
|
||||
for _, b := range opts.System {
|
||||
blk := apiSystemBlock{
|
||||
Type: "text",
|
||||
Text: b.Texto,
|
||||
}
|
||||
if b.Cachear {
|
||||
blk.CacheControl = &apiCacheControl{Type: "ephemeral"}
|
||||
}
|
||||
systemBlocks = append(systemBlocks, blk)
|
||||
}
|
||||
|
||||
tools := []apiTool{
|
||||
{
|
||||
Name: opts.Herramienta.Nombre,
|
||||
Description: opts.Herramienta.Descripcion,
|
||||
InputSchema: opts.Herramienta.InputSchema,
|
||||
},
|
||||
}
|
||||
|
||||
toolChoice := &apiToolChoice{
|
||||
Type: "tool",
|
||||
Name: opts.Herramienta.Nombre,
|
||||
}
|
||||
|
||||
mensajes := []apiMessage{
|
||||
{Role: "user", Content: opts.MensajeUsuario},
|
||||
}
|
||||
|
||||
var uso UsoTokens
|
||||
var ultimoError string
|
||||
|
||||
for intento := 1; intento <= maxIntentos; intento++ {
|
||||
res, err := c.crearMensajeConReintentos(ctx, apiRequest{
|
||||
Model: c.Model,
|
||||
MaxTokens: maxTokens,
|
||||
System: systemBlocks,
|
||||
Tools: tools,
|
||||
ToolChoice: toolChoice,
|
||||
Messages: mensajes,
|
||||
}, maxTransitoriosDef)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
uso.Entrada += res.Usage.InputTokens
|
||||
uso.Salida += res.Usage.OutputTokens
|
||||
uso.CacheLectura += res.Usage.CacheReadInputTokens
|
||||
uso.CacheEscritura += res.Usage.CacheCreationInputTokens
|
||||
|
||||
var bloquesTool []apiContentBlock
|
||||
var candidatos []apiContentBlock
|
||||
for _, blk := range res.Content {
|
||||
if blk.Type == "tool_use" {
|
||||
bloquesTool = append(bloquesTool, blk)
|
||||
if blk.Name == opts.Herramienta.Nombre {
|
||||
candidatos = append(candidatos, blk)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var primerFallo *apiContentBlock
|
||||
for i := range candidatos {
|
||||
cand := candidatos[i]
|
||||
norm := NormalizarRespuesta(cand.Input)
|
||||
datos, ok := norm.(map[string]any)
|
||||
var errs []string
|
||||
if !ok {
|
||||
errs = []string{"La entrada de la herramienta debe ser un objeto JSON."}
|
||||
} else if opts.Herramienta.Validar != nil {
|
||||
errs = opts.Herramienta.Validar(datos)
|
||||
}
|
||||
if len(errs) == 0 {
|
||||
return &ResultadoLlamada{
|
||||
Datos: datos,
|
||||
Uso: uso,
|
||||
Intentos: intento,
|
||||
}, nil
|
||||
}
|
||||
if primerFallo == nil {
|
||||
cp := cand
|
||||
primerFallo = &cp
|
||||
ultimoError = strings.Join(errs, "\n")
|
||||
}
|
||||
}
|
||||
|
||||
if len(bloquesTool) > 0 {
|
||||
if primerFallo == nil {
|
||||
ultimoError = fmt.Sprintf("El modelo llamo a una herramienta inesperada. Usa %s.", opts.Herramienta.Nombre)
|
||||
}
|
||||
userBlocks := make([]any, 0, len(bloquesTool)+1)
|
||||
for _, b := range bloquesTool {
|
||||
content := fmt.Sprintf("Herramienta inesperada. Usa %s.", opts.Herramienta.Nombre)
|
||||
if primerFallo != nil && b.ID == primerFallo.ID {
|
||||
content = ultimoError
|
||||
}
|
||||
userBlocks = append(userBlocks, map[string]any{
|
||||
"type": "tool_result",
|
||||
"tool_use_id": b.ID,
|
||||
"is_error": true,
|
||||
"content": content,
|
||||
})
|
||||
}
|
||||
userBlocks = append(userBlocks, map[string]any{
|
||||
"type": "text",
|
||||
"text": fmt.Sprintf(
|
||||
"La llamada no cumple el schema. Corrige EXACTAMENTE estos errores y vuelve a llamar a %s:\n\n%s\n\nRevisa que cada objeto este en el array que le corresponde y que no falte ningun campo obligatorio. No agregues campos que el schema no declara.",
|
||||
opts.Herramienta.Nombre,
|
||||
ultimoError,
|
||||
),
|
||||
})
|
||||
mensajes = append(mensajes,
|
||||
apiMessage{Role: "assistant", Content: res.Content},
|
||||
apiMessage{Role: "user", Content: userBlocks},
|
||||
)
|
||||
continue
|
||||
}
|
||||
|
||||
ultimoError = "El modelo respondio con prosa en vez de llamar a la herramienta."
|
||||
mensajes = append(mensajes,
|
||||
apiMessage{Role: "assistant", Content: res.Content},
|
||||
apiMessage{
|
||||
Role: "user",
|
||||
Content: fmt.Sprintf("Debes responder llamando a la herramienta %s. No escribas prosa suelta.", opts.Herramienta.Nombre),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("El paso %q agoto %d intentos.\nUltimo error:\n%s", opts.Herramienta.Nombre, maxIntentos, ultimoError)
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
package propuesta
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
|
||||
"cotizador/internal/domain"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// PartidaEconomia representa una linea cotizada canonica.
|
||||
// Ref (P01, P02...) es lo unico que identifica la partida ante el modelo de IA;
|
||||
// los precios e importes nunca viajan al prompt y solo los usa el renderizador
|
||||
// o los calculos internos.
|
||||
type PartidaEconomia struct {
|
||||
Ref string `json:"refPartida"`
|
||||
Nombre string `json:"nombre"`
|
||||
Fase int `json:"fase"`
|
||||
TipoPago string `json:"tipoPago"`
|
||||
Precio float64 `json:"precio"`
|
||||
TiempoEntrega string `json:"tiempoEntrega"`
|
||||
Entregables []string `json:"entregables"`
|
||||
ModeloCobro string `json:"modeloCobro"`
|
||||
Horas *float64 `json:"horas"`
|
||||
TarifaHora *float64 `json:"tarifaHora"`
|
||||
MontoMinimo *float64 `json:"montoMinimo"`
|
||||
HorasIncluidas *float64 `json:"horasIncluidas"`
|
||||
}
|
||||
|
||||
// RatioValor resume la lectura precio/valor del anexo interno.
|
||||
type RatioValor struct {
|
||||
Ratio float64 `json:"ratio"`
|
||||
Etiqueta string `json:"etiqueta"`
|
||||
Nota string `json:"nota"`
|
||||
}
|
||||
|
||||
// EconomiaCotizacion agrupa las partidas seleccionadas, el plan Bucefalo
|
||||
// (si fue contratado) y los totales canonicos de la cotizacion.
|
||||
type EconomiaCotizacion struct {
|
||||
Partidas []PartidaEconomia `json:"partidas"`
|
||||
PlanBucefalo *struct {
|
||||
Nivel string `json:"nivel"`
|
||||
Precio float64 `json:"precio"`
|
||||
} `json:"planBucefalo"`
|
||||
Totales domain.TotalesCotizacion `json:"totales"`
|
||||
Moneda string `json:"moneda"`
|
||||
}
|
||||
|
||||
// CalcularRatio calcula el ratio precio/valor para el anexo interno comparando
|
||||
// el desembolso total del primer ano contra el costo anual del problema del cliente.
|
||||
//
|
||||
// Cortes:
|
||||
// - < 0.10: subcotizado
|
||||
// - <= 0.25: en_rango
|
||||
// - <= 0.40: alto
|
||||
// - > 0.40: objecion_probable
|
||||
func CalcularRatio(totalPrimerAnio, valorAnual float64) RatioValor {
|
||||
if valorAnual <= 0 {
|
||||
return RatioValor{
|
||||
Ratio: 0,
|
||||
Etiqueta: "",
|
||||
Nota: "Sin valor anual cuantificado del problema.",
|
||||
}
|
||||
}
|
||||
|
||||
ratio := totalPrimerAnio / valorAnual
|
||||
var etiqueta, nota string
|
||||
switch {
|
||||
case ratio < 0.10:
|
||||
etiqueta = "subcotizado"
|
||||
nota = "La inversion es menos del 10% de lo que el problema le cuesta al cliente cada ano. Probablemente subcotizaste."
|
||||
case ratio <= 0.25:
|
||||
etiqueta = "en_rango"
|
||||
nota = "La inversion cae en el rango de referencia (15-25% del valor anual)."
|
||||
case ratio <= 0.40:
|
||||
etiqueta = "alto"
|
||||
nota = "La inversion esta en la banda alta. Justificable, pero conviene anclar bien el valor antes de dar el numero."
|
||||
default:
|
||||
etiqueta = "objecion_probable"
|
||||
nota = "La inversion supera el 40% del valor anual del problema. Prepara la conversacion de precio: se responde con alcance, no con descuento."
|
||||
}
|
||||
|
||||
return RatioValor{
|
||||
Ratio: math.Round(ratio*1000) / 1000,
|
||||
Etiqueta: etiqueta,
|
||||
Nota: nota,
|
||||
}
|
||||
}
|
||||
|
||||
// CargarEconomiaCotizacion carga desde PostgreSQL las partidas seleccionadas,
|
||||
// el plan Bucefalo (si aplica) y los totales canonicos de una cotizacion.
|
||||
func CargarEconomiaCotizacion(ctx context.Context, pool *pgxpool.Pool, cotizacionID string) (*EconomiaCotizacion, error) {
|
||||
if pool == nil {
|
||||
return nil, errors.New("pool de base de datos no inicializado")
|
||||
}
|
||||
|
||||
var moneda string
|
||||
var incluirIVA bool
|
||||
err := pool.QueryRow(ctx, `
|
||||
SELECT "moneda", "incluirIva"
|
||||
FROM "Cotizacion"
|
||||
WHERE "id" = $1
|
||||
`, cotizacionID).Scan(&moneda, &incluirIVA)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, fmt.Errorf("Cotizacion %s no encontrada", cotizacionID)
|
||||
}
|
||||
return nil, fmt.Errorf("error consultando cotizacion %s: %w", cotizacionID, err)
|
||||
}
|
||||
|
||||
rows, err := pool.Query(ctx, `
|
||||
SELECT
|
||||
COALESCE(NULLIF(cat."nombre", ''), NULLIF(sc."nombre", ''), 'Servicio') AS nombre,
|
||||
sc."fase",
|
||||
sc."tipoPago",
|
||||
sc."precio",
|
||||
sc."tiempoEntrega",
|
||||
sc."entregables",
|
||||
sc."modeloCobro",
|
||||
sc."horas",
|
||||
sc."tarifaHora",
|
||||
sc."montoMinimo",
|
||||
sc."horasIncluidas"
|
||||
FROM "ServicioCotizado" sc
|
||||
LEFT JOIN "ServicioCatalogo" cat ON cat."id" = sc."servicioCatalogoId"
|
||||
WHERE sc."cotizacionId" = $1 AND sc."seleccionado" = true
|
||||
ORDER BY sc."fase" ASC, sc."createdAt" ASC
|
||||
`, cotizacionID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error consultando servicios de cotizacion %s: %w", cotizacionID, err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
partidas := make([]PartidaEconomia, 0)
|
||||
paraTotales := make([]domain.ServicioCalc, 0)
|
||||
idx := 0
|
||||
|
||||
for rows.Next() {
|
||||
var p PartidaEconomia
|
||||
var entregablesRaw []byte
|
||||
if err := rows.Scan(
|
||||
&p.Nombre,
|
||||
&p.Fase,
|
||||
&p.TipoPago,
|
||||
&p.Precio,
|
||||
&p.TiempoEntrega,
|
||||
&entregablesRaw,
|
||||
&p.ModeloCobro,
|
||||
&p.Horas,
|
||||
&p.TarifaHora,
|
||||
&p.MontoMinimo,
|
||||
&p.HorasIncluidas,
|
||||
); err != nil {
|
||||
return nil, fmt.Errorf("error leyendo servicio cotizado: %w", err)
|
||||
}
|
||||
idx++
|
||||
p.Ref = fmt.Sprintf("P%02d", idx)
|
||||
p.Entregables = parseStringSliceJSON(entregablesRaw)
|
||||
partidas = append(partidas, p)
|
||||
paraTotales = append(paraTotales, domain.ServicioCalc{
|
||||
Nombre: p.Nombre,
|
||||
ModeloCobro: p.ModeloCobro,
|
||||
TipoPago: p.TipoPago,
|
||||
Precio: p.Precio,
|
||||
Seleccionado: true,
|
||||
})
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("error iterando servicios cotizados: %w", err)
|
||||
}
|
||||
|
||||
var plan *struct {
|
||||
Nivel string `json:"nivel"`
|
||||
Precio float64 `json:"precio"`
|
||||
}
|
||||
var nivelPlan string
|
||||
var precioPlan float64
|
||||
err = pool.QueryRow(ctx, `
|
||||
SELECT "nivel", "precio"
|
||||
FROM "PlanBucefaloCotizacion"
|
||||
WHERE "cotizacionId" = $1 AND "seleccionado" = true
|
||||
LIMIT 1
|
||||
`, cotizacionID).Scan(&nivelPlan, &precioPlan)
|
||||
if err == nil {
|
||||
plan = &struct {
|
||||
Nivel string `json:"nivel"`
|
||||
Precio float64 `json:"precio"`
|
||||
}{
|
||||
Nivel: nivelPlan,
|
||||
Precio: precioPlan,
|
||||
}
|
||||
// El plan Bucefalo se cobra mensual y entra a los totales igual que en el PDF economico.
|
||||
paraTotales = append(paraTotales, domain.ServicioCalc{
|
||||
TipoPago: "mensual",
|
||||
Precio: precioPlan,
|
||||
Seleccionado: true,
|
||||
})
|
||||
} else if !errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, fmt.Errorf("error consultando plan Bucefalo de %s: %w", cotizacionID, err)
|
||||
}
|
||||
|
||||
return &EconomiaCotizacion{
|
||||
Partidas: partidas,
|
||||
PlanBucefalo: plan,
|
||||
Totales: domain.CalcularTotalesCotizacion(paraTotales, incluirIVA),
|
||||
Moneda: moneda,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func parseStringSliceJSON(raw []byte) []string {
|
||||
if len(raw) == 0 {
|
||||
return []string{}
|
||||
}
|
||||
var out []string
|
||||
if err := json.Unmarshal(raw, &out); err != nil || out == nil {
|
||||
return []string{}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
package propuesta
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"cotizador/internal/config"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// GenerarInput encapsula los datos de entrada para generar una propuesta consultiva.
|
||||
type GenerarInput struct {
|
||||
CotizacionID string
|
||||
Transcripcion string
|
||||
NotasAdicionales string
|
||||
}
|
||||
|
||||
// GenerarResult devuelve el contenido estructurado de la propuesta, la traza
|
||||
// de consumo/intentos, los avisos de validacion y el modelo usado.
|
||||
type GenerarResult struct {
|
||||
Contenido map[string]any
|
||||
Traza map[string]any
|
||||
Avisos []Aviso
|
||||
Modelo string
|
||||
}
|
||||
|
||||
type pasoTraza struct {
|
||||
Paso string `json:"paso"`
|
||||
Intentos int `json:"intentos"`
|
||||
Uso UsoTokens `json:"uso"`
|
||||
}
|
||||
|
||||
// GenerarPropuesta ejecuta el pipeline consultivo de tres pasos (extraccion,
|
||||
// diagnostico, redaccion) contra MiniMax y valida la salida contra las reglas
|
||||
// de negocio y la economia canonica de la cotizacion.
|
||||
func GenerarPropuesta(ctx context.Context, cfg *config.Config, pool *pgxpool.Pool, in GenerarInput) (*GenerarResult, error) {
|
||||
if pool == nil {
|
||||
return nil, errors.New("pool de base de datos no inicializado")
|
||||
}
|
||||
if strings.TrimSpace(in.CotizacionID) == "" {
|
||||
return nil, errors.New("CotizacionID es obligatorio")
|
||||
}
|
||||
|
||||
var proyecto, observaciones, observacionesInternas, clienteNombre, clienteEmpresa string
|
||||
var esDoble bool
|
||||
err := pool.QueryRow(ctx, `
|
||||
SELECT
|
||||
c."proyecto",
|
||||
c."esDoble",
|
||||
COALESCE(c."observaciones", ''),
|
||||
COALESCE(c."observacionesInternas", ''),
|
||||
cl."nombre",
|
||||
COALESCE(cl."empresa", '')
|
||||
FROM "Cotizacion" c
|
||||
JOIN "Cliente" cl ON cl."id" = c."clienteId"
|
||||
WHERE c."id" = $1
|
||||
`, in.CotizacionID).Scan(
|
||||
&proyecto,
|
||||
&esDoble,
|
||||
&observaciones,
|
||||
&observacionesInternas,
|
||||
&clienteNombre,
|
||||
&clienteEmpresa,
|
||||
)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, fmt.Errorf("Cotizacion %s no encontrada", in.CotizacionID)
|
||||
}
|
||||
return nil, fmt.Errorf("error cargando contexto de cotizacion %s: %w", in.CotizacionID, err)
|
||||
}
|
||||
|
||||
if esDoble {
|
||||
return nil, errors.New(
|
||||
"Esta cotizacion es de doble propuesta y el documento consultivo todavia no las soporta: sumaria las dos opciones como si fueran una sola. Genera la propuesta desde una cotizacion de opcion unica.",
|
||||
)
|
||||
}
|
||||
|
||||
rows, err := pool.Query(ctx, `
|
||||
SELECT "notas"
|
||||
FROM "ServicioCotizado"
|
||||
WHERE "cotizacionId" = $1 AND "notas" IS NOT NULL AND BTRIM("notas") <> ''
|
||||
ORDER BY "fase" ASC, "createdAt" ASC
|
||||
`, in.CotizacionID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error consultando notas de partidas: %w", err)
|
||||
}
|
||||
var notasLista []string
|
||||
for rows.Next() {
|
||||
var n string
|
||||
if err := rows.Scan(&n); err != nil {
|
||||
rows.Close()
|
||||
return nil, fmt.Errorf("error leyendo nota de partida: %w", err)
|
||||
}
|
||||
if trimmed := strings.TrimSpace(n); trimmed != "" {
|
||||
notasLista = append(notasLista, trimmed)
|
||||
}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
rows.Close()
|
||||
return nil, fmt.Errorf("error iterando notas de partidas: %w", err)
|
||||
}
|
||||
rows.Close()
|
||||
|
||||
if extra := strings.TrimSpace(in.NotasAdicionales); extra != "" {
|
||||
notasLista = append(notasLista, extra)
|
||||
}
|
||||
notasCombinadas := strings.Join(notasLista, "\n")
|
||||
|
||||
economia, err := CargarEconomiaCotizacion(ctx, pool, in.CotizacionID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(economia.Partidas) == 0 {
|
||||
return nil, errors.New("La cotizacion no tiene partidas seleccionadas. Agrega servicios antes de generar la propuesta.")
|
||||
}
|
||||
|
||||
cliente, err := NuevoClienteIA(cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
entrada := ContextoEntrada{
|
||||
Transcripcion: in.Transcripcion,
|
||||
Notas: notasCombinadas,
|
||||
Observaciones: observaciones,
|
||||
Cliente: clienteNombre,
|
||||
Empresa: clienteEmpresa,
|
||||
Proyecto: proyecto,
|
||||
}
|
||||
|
||||
return ejecutarPipeline(ctx, cliente, entrada, economia, observacionesInternas)
|
||||
}
|
||||
|
||||
func ejecutarPipeline(
|
||||
ctx context.Context,
|
||||
cliente *ClienteIA,
|
||||
entrada ContextoEntrada,
|
||||
economia *EconomiaCotizacion,
|
||||
notasInternas string,
|
||||
) (*GenerarResult, error) {
|
||||
system := []BloqueSystem{{Texto: SystemBase, Cachear: true}}
|
||||
pasos := make([]pasoTraza, 0, 3)
|
||||
var totalUso UsoTokens
|
||||
acumular := func(u UsoTokens) {
|
||||
totalUso.Entrada += u.Entrada
|
||||
totalUso.Salida += u.Salida
|
||||
totalUso.CacheLectura += u.CacheLectura
|
||||
totalUso.CacheEscritura += u.CacheEscritura
|
||||
}
|
||||
|
||||
r1, err := cliente.LlamarConHerramienta(ctx, OpcionesLlamada{
|
||||
System: system,
|
||||
MensajeUsuario: MensajePaso1(entrada),
|
||||
Herramienta: Herramienta{
|
||||
Nombre: "registrar_hechos",
|
||||
Descripcion: "Registra las citas literales, los hechos, los pendientes y las red flags extraidos del material de la reunion.",
|
||||
InputSchema: SchemaHechos(),
|
||||
Validar: ValidarHechos,
|
||||
},
|
||||
MaxIntentos: 5,
|
||||
MaxTokens: 8000,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pasos = append(pasos, pasoTraza{Paso: "extraccion", Intentos: r1.Intentos, Uso: r1.Uso})
|
||||
acumular(r1.Uso)
|
||||
|
||||
r2, err := cliente.LlamarConHerramienta(ctx, OpcionesLlamada{
|
||||
System: system,
|
||||
MensajeUsuario: MensajePaso2(entrada, r1.Datos, economia),
|
||||
Herramienta: Herramienta{
|
||||
Nombre: "registrar_diagnostico",
|
||||
Descripcion: "Registra los hallazgos con su semaforo de urgencia, el valor anual del problema y los resultados de negocio a lograr.",
|
||||
InputSchema: SchemaDiagnostico(),
|
||||
Validar: ValidarDiagnostico,
|
||||
},
|
||||
MaxIntentos: 4,
|
||||
MaxTokens: 8000,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pasos = append(pasos, pasoTraza{Paso: "diagnostico", Intentos: r2.Intentos, Uso: r2.Uso})
|
||||
acumular(r2.Uso)
|
||||
|
||||
r3, err := cliente.LlamarConHerramienta(ctx, OpcionesLlamada{
|
||||
System: system,
|
||||
MensajeUsuario: MensajePaso3(entrada, r1.Datos, r2.Datos, economia),
|
||||
Herramienta: Herramienta{
|
||||
Nombre: "registrar_propuesta",
|
||||
Descripcion: "Registra la redaccion final de la propuesta consultiva para el cliente.",
|
||||
InputSchema: SchemaRedaccion(),
|
||||
Validar: ValidarRedaccion,
|
||||
},
|
||||
MaxIntentos: 4,
|
||||
MaxTokens: 12000,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pasos = append(pasos, pasoTraza{Paso: "redaccion", Intentos: r3.Intentos, Uso: r3.Uso})
|
||||
acumular(r3.Uso)
|
||||
|
||||
contenido := map[string]any{
|
||||
"hechos": r1.Datos,
|
||||
"diagnostico": r2.Datos,
|
||||
"redaccion": r3.Datos,
|
||||
}
|
||||
|
||||
fuentesCliente := strings.Join([]string{entrada.Transcripcion, entrada.Observaciones, entrada.Notas}, "\n")
|
||||
avisos := ValidarPropuesta(contenido, economia, fuentesCliente, notasInternas)
|
||||
|
||||
traza := map[string]any{
|
||||
"modelo": cliente.Model,
|
||||
"pasos": pasos,
|
||||
"totalUso": totalUso,
|
||||
}
|
||||
|
||||
return &GenerarResult{
|
||||
Contenido: contenido,
|
||||
Traza: traza,
|
||||
Avisos: avisos,
|
||||
Modelo: cliente.Model,
|
||||
}, nil
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,876 @@
|
||||
package propuesta
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"cotizador/internal/config"
|
||||
"cotizador/internal/domain"
|
||||
)
|
||||
|
||||
// ─────────────────────────── economia.go ───────────────────────────
|
||||
|
||||
func TestCalcularRatio(t *testing.T) {
|
||||
// Sin valor anual / cero / negativo -> sin etiqueta ni division entre cero
|
||||
for _, val := range []float64{0, -5, -1000} {
|
||||
r := CalcularRatio(100000, val)
|
||||
if r.Ratio != 0 || r.Etiqueta != "" {
|
||||
t.Fatalf("valorAnual=%v: esperado Ratio=0 Etiqueta=\"\", obtuve %+v", val, r)
|
||||
}
|
||||
if r.Nota == "" {
|
||||
t.Fatalf("valorAnual=%v: esperaba Nota explicativa", val)
|
||||
}
|
||||
}
|
||||
|
||||
casos := []struct {
|
||||
nombre string
|
||||
total float64
|
||||
valor float64
|
||||
etiqueta string
|
||||
ratio float64
|
||||
}{
|
||||
{"5% subcotizado", 50000, 1000000, "subcotizado", 0.05},
|
||||
{"corte exacto 10% en_rango", 100000, 1000000, "en_rango", 0.1},
|
||||
{"20% en_rango", 200000, 1000000, "en_rango", 0.2},
|
||||
{"corte exacto 25% en_rango", 250000, 1000000, "en_rango", 0.25},
|
||||
{"35% alto", 350000, 1000000, "alto", 0.35},
|
||||
{"corte exacto 40% alto", 400000, 1000000, "alto", 0.4},
|
||||
{"60% objecion_probable", 600000, 1000000, "objecion_probable", 0.6},
|
||||
{"redondeo a 3 decimales", 123456, 1000000, "en_rango", 0.123},
|
||||
}
|
||||
|
||||
for _, tc := range casos {
|
||||
t.Run(tc.nombre, func(t *testing.T) {
|
||||
got := CalcularRatio(tc.total, tc.valor)
|
||||
if got.Etiqueta != tc.etiqueta {
|
||||
t.Fatalf("etiqueta: esperado %q, obtuve %q (ratio=%v)", tc.etiqueta, got.Etiqueta, got.Ratio)
|
||||
}
|
||||
if got.Ratio != tc.ratio {
|
||||
t.Fatalf("ratio: esperado %v, obtuve %v", tc.ratio, got.Ratio)
|
||||
}
|
||||
if got.Nota == "" {
|
||||
t.Fatalf("se esperaba Nota no vacia para %q", tc.etiqueta)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────────────────── cliente_ia.go ───────────────────────────
|
||||
|
||||
func TestNuevoClienteIA(t *testing.T) {
|
||||
t.Run("rechaza clave faltante nombrando MINIMAX_API_KEY y ANTHROPIC_API_KEY", func(t *testing.T) {
|
||||
t.Setenv("MINIMAX_API_KEY", "")
|
||||
t.Setenv("ANTHROPIC_API_KEY", "")
|
||||
_, err := NuevoClienteIA(&config.Config{})
|
||||
if err == nil {
|
||||
t.Fatal("esperaba error sin MINIMAX_API_KEY")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "MINIMAX_API_KEY") || !strings.Contains(err.Error(), "ANTHROPIC_API_KEY") {
|
||||
t.Fatalf("mensaje debe mencionar MINIMAX_API_KEY y ANTHROPIC_API_KEY: %q", err.Error())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("advierte explicitamente si solo ANTHROPIC_API_KEY esta definida", func(t *testing.T) {
|
||||
t.Setenv("MINIMAX_API_KEY", "")
|
||||
t.Setenv("ANTHROPIC_API_KEY", "sk-ant-solo-prueba")
|
||||
_, err := NuevoClienteIA(&config.Config{})
|
||||
if err == nil {
|
||||
t.Fatal("esperaba error cuando solo ANTHROPIC_API_KEY esta definida")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "ANTHROPIC_API_KEY") || !strings.Contains(err.Error(), "MINIMAX_API_KEY") {
|
||||
t.Fatalf("error debe advertir sobre ANTHROPIC_API_KEY: %q", err.Error())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("defaults e ignorar ANTHROPIC_BASE_URL", func(t *testing.T) {
|
||||
t.Setenv("ANTHROPIC_BASE_URL", "https://api.anthropic.com")
|
||||
c, err := NuevoClienteIA(&config.Config{MinimaxAPIKey: "clave-prueba"})
|
||||
if err != nil {
|
||||
t.Fatalf("error inesperado: %v", err)
|
||||
}
|
||||
if !strings.Contains(c.BaseURL, "api.minimax.io") {
|
||||
t.Fatalf("BaseURL esperado de MiniMax, obtuve %q", c.BaseURL)
|
||||
}
|
||||
if strings.Contains(c.BaseURL, "api.anthropic.com") {
|
||||
t.Fatalf("ANTHROPIC_BASE_URL no debe secuestrar BaseURL: %q", c.BaseURL)
|
||||
}
|
||||
if c.Model != "MiniMax-M3" {
|
||||
t.Fatalf("Model por defecto esperado MiniMax-M3, obtuve %q", c.Model)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("respeta MINIMAX_BASE_URL y MINIMAX_MODEL", func(t *testing.T) {
|
||||
c, err := NuevoClienteIA(&config.Config{
|
||||
MinimaxAPIKey: "clave-prueba",
|
||||
MinimaxBaseURL: "https://ejemplo.local/anthropic/",
|
||||
MinimaxModel: "MiniMax-M2",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("error inesperado: %v", err)
|
||||
}
|
||||
if c.BaseURL != "https://ejemplo.local/anthropic" {
|
||||
t.Fatalf("BaseURL inesperado: %q", c.BaseURL)
|
||||
}
|
||||
if c.Model != "MiniMax-M2" {
|
||||
t.Fatalf("Model inesperado: %q", c.Model)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestNormalizarRespuesta(t *testing.T) {
|
||||
casos := []struct {
|
||||
nombre string
|
||||
in any
|
||||
want any
|
||||
}{
|
||||
{
|
||||
"desenvuelve {item: X} cuando item es la unica clave",
|
||||
map[string]any{"item": map[string]any{"a": 1}},
|
||||
map[string]any{"a": 1},
|
||||
},
|
||||
{
|
||||
"desenvuelve dentro de arrays",
|
||||
[]any{map[string]any{"item": map[string]any{"a": 1}}, map[string]any{"item": map[string]any{"a": 2}}},
|
||||
[]any{map[string]any{"a": 1}, map[string]any{"a": 2}},
|
||||
},
|
||||
{
|
||||
"desenvuelve en profundidad",
|
||||
map[string]any{"lista": []any{map[string]any{"item": map[string]any{"x": []any{map[string]any{"item": 5}}}}}},
|
||||
map[string]any{"lista": []any{map[string]any{"x": []any{5}}}},
|
||||
},
|
||||
{
|
||||
"NO toca un objeto con item junto a otras claves",
|
||||
map[string]any{"item": 1, "otro": 2},
|
||||
map[string]any{"item": 1, "otro": 2},
|
||||
},
|
||||
{
|
||||
"deja intactos valores simples",
|
||||
"texto",
|
||||
"texto",
|
||||
},
|
||||
{
|
||||
"deja intacto nil",
|
||||
nil,
|
||||
nil,
|
||||
},
|
||||
{
|
||||
"no altera un objeto normal",
|
||||
map[string]any{"a": 1, "b": []any{1, 2}},
|
||||
map[string]any{"a": 1, "b": []any{1, 2}},
|
||||
},
|
||||
{
|
||||
"caso real: alcance envuelto",
|
||||
map[string]any{"alcance": []any{map[string]any{"item": map[string]any{"refPartida": "P01", "descripcionResultado": "x"}}}},
|
||||
map[string]any{"alcance": []any{map[string]any{"refPartida": "P01", "descripcionResultado": "x"}}},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range casos {
|
||||
t.Run(tc.nombre, func(t *testing.T) {
|
||||
got := NormalizarRespuesta(tc.in)
|
||||
if !reflect.DeepEqual(got, tc.want) {
|
||||
t.Fatalf("esperado %#v, obtuve %#v", tc.want, got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestClienteIAToolCallingRetryYFeedback(t *testing.T) {
|
||||
var calls int32
|
||||
var sawToolChoice, sawCacheControl, sawToolResultError bool
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
n := atomic.AddInt32(&calls, 1)
|
||||
if r.URL.Path != "/v1/messages" {
|
||||
t.Errorf("path inesperado: %s", r.URL.Path)
|
||||
}
|
||||
if r.Header.Get("x-api-key") != "test-key" {
|
||||
t.Errorf("x-api-key faltante o invalido: %q", r.Header.Get("x-api-key"))
|
||||
}
|
||||
|
||||
var body map[string]any
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
t.Fatalf("body JSON invalido: %v", err)
|
||||
}
|
||||
if tc, ok := body["tool_choice"].(map[string]any); ok && tc["type"] == "tool" && tc["name"] == "registrar_hechos" {
|
||||
sawToolChoice = true
|
||||
}
|
||||
if sys, ok := body["system"].([]any); ok && len(sys) > 0 {
|
||||
if s0, ok := sys[0].(map[string]any); ok {
|
||||
if cc, ok := s0["cache_control"].(map[string]any); ok && cc["type"] == "ephemeral" {
|
||||
sawCacheControl = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Llamada 1: fallo transitorio 429
|
||||
if n == 1 {
|
||||
w.WriteHeader(http.StatusTooManyRequests)
|
||||
_, _ = w.Write([]byte(`{"error":"rate_limit"}`))
|
||||
return
|
||||
}
|
||||
// Llamada 2: devuelve tool_use invalido (cita muy corta -> dispara feedback loop)
|
||||
if n == 2 {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"id": "msg_1",
|
||||
"type": "message",
|
||||
"role": "assistant",
|
||||
"content": []any{
|
||||
map[string]any{
|
||||
"type": "tool_use",
|
||||
"id": "tu_1",
|
||||
"name": "registrar_hechos",
|
||||
"input": map[string]any{
|
||||
"citas": []any{map[string]any{"id": "C01", "textoLiteral": "corta", "quienLoDijo": "socio"}},
|
||||
"hechos": []any{}, "materialesPendientes": []any{},
|
||||
"decisionesPendientes": []any{}, "mencionesFueraDeAlcance": []any{}, "redFlags": []any{},
|
||||
},
|
||||
},
|
||||
},
|
||||
"usage": map[string]any{"input_tokens": 100, "output_tokens": 50, "cache_creation_input_tokens": 80},
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Llamada 3: verificar que llego tool_result con is_error=true y responder valido envuelto en {item:...}
|
||||
if msgs, ok := body["messages"].([]any); ok && len(msgs) >= 3 {
|
||||
if last, ok := msgs[len(msgs)-1].(map[string]any); ok {
|
||||
if blocks, ok := last["content"].([]any); ok {
|
||||
for _, b := range blocks {
|
||||
if bm, ok := b.(map[string]any); ok && bm["type"] == "tool_result" && bm["is_error"] == true {
|
||||
sawToolResultError = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"id": "msg_2",
|
||||
"type": "message",
|
||||
"role": "assistant",
|
||||
"content": []any{
|
||||
map[string]any{
|
||||
"type": "tool_use",
|
||||
"id": "tu_2",
|
||||
"name": "registrar_hechos",
|
||||
"input": map[string]any{
|
||||
"citas": []any{map[string]any{"item": map[string]any{
|
||||
"id": "C01",
|
||||
"textoLiteral": "no llevamos control de quien contesta el whatsapp el fin de semana",
|
||||
"quienLoDijo": "el socio",
|
||||
}}},
|
||||
"hechos": []any{}, "materialesPendientes": []any{},
|
||||
"decisionesPendientes": []any{}, "mencionesFueraDeAlcance": []any{}, "redFlags": []any{},
|
||||
},
|
||||
},
|
||||
},
|
||||
"usage": map[string]any{"input_tokens": 120, "output_tokens": 60, "cache_read_input_tokens": 80},
|
||||
})
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
cliente := &ClienteIA{
|
||||
APIKey: "test-key",
|
||||
BaseURL: srv.URL,
|
||||
Model: "MiniMax-M3",
|
||||
HTTPClient: srv.Client(),
|
||||
Sleep: func(context.Context, time.Duration) error { return nil },
|
||||
}
|
||||
|
||||
res, err := cliente.LlamarConHerramienta(context.Background(), OpcionesLlamada{
|
||||
System: []BloqueSystem{{Texto: SystemBase, Cachear: true}},
|
||||
MensajeUsuario: "extrae hechos",
|
||||
Herramienta: Herramienta{
|
||||
Nombre: "registrar_hechos",
|
||||
Descripcion: "test",
|
||||
InputSchema: SchemaHechos(),
|
||||
Validar: ValidarHechos,
|
||||
},
|
||||
MaxIntentos: 3,
|
||||
MaxTokens: 1000,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("error inesperado: %v", err)
|
||||
}
|
||||
if !sawToolChoice {
|
||||
t.Fatal("esperaba tool_choice: {type: tool, name: registrar_hechos}")
|
||||
}
|
||||
if !sawCacheControl {
|
||||
t.Fatal("esperaba cache_control: {type: ephemeral}")
|
||||
}
|
||||
if !sawToolResultError {
|
||||
t.Fatal("esperaba feedback loop con tool_result is_error=true")
|
||||
}
|
||||
if res.Intentos != 2 {
|
||||
t.Fatalf("esperaba 2 intentos de validacion (mas 1 reintento HTTP 429), obtuve %d", res.Intentos)
|
||||
}
|
||||
if res.Uso.Entrada != 220 || res.Uso.Salida != 110 || res.Uso.CacheEscritura != 80 || res.Uso.CacheLectura != 80 {
|
||||
t.Fatalf("acumulacion de uso incorrecta: %+v", res.Uso)
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────────────────── prompts.go & schemas ───────────────────────────
|
||||
|
||||
func TestSystemBaseCacheInvariants(t *testing.T) {
|
||||
anioActual := strconv.Itoa(time.Now().Year())
|
||||
if strings.Contains(SystemBase, anioActual) {
|
||||
t.Fatalf("SystemBase no debe contener el anio actual (%s)", anioActual)
|
||||
}
|
||||
if regexp.MustCompile(`\d{4}-\d{2}-\d{2}`).MatchString(SystemBase) {
|
||||
t.Fatal("SystemBase no debe contener fechas ISO")
|
||||
}
|
||||
if regexp.MustCompile(`UJ\d{4}`).MatchString(SystemBase) {
|
||||
t.Fatal("SystemBase no debe contener folios de cotizacion")
|
||||
}
|
||||
if len(SystemBase) <= 2500 {
|
||||
t.Fatalf("SystemBase debe superar el minimo cacheable (>2500 chars), tiene %d", len(SystemBase))
|
||||
}
|
||||
|
||||
for _, p := range []string{"P1.", "P2.", "P3.", "P4.", "P5.", "P6.", "P7.", "P8."} {
|
||||
if !strings.Contains(SystemBase, p) {
|
||||
t.Fatalf("SystemBase debe declarar principio %s", p)
|
||||
}
|
||||
}
|
||||
for _, s := range []string{
|
||||
"rojo:", "ambar:", "azul:", "verde:", "entre pares",
|
||||
"Bucefalo", "ningun otro CRM", "USD", "garantizado",
|
||||
"sinergias", "UNICAMENTE servicios digitales",
|
||||
"nombres de empleados", "MATERIAL ES POBRE", "contenido de valor",
|
||||
} {
|
||||
if !strings.Contains(SystemBase, s) {
|
||||
t.Fatalf("SystemBase debe contener %q", s)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBloqueContextoYMensajesSinPrecios(t *testing.T) {
|
||||
sinNada := BloqueContexto(ContextoEntrada{Cliente: "Ana", Proyecto: "P"})
|
||||
if !strings.Contains(sinNada, "No se entrego transcripcion") {
|
||||
t.Fatal("sin transcripcion debe declararlo explicitamente")
|
||||
}
|
||||
if strings.Contains(sinNada, "()") {
|
||||
t.Fatal("sin empresa no debe imprimir parentesis vacios")
|
||||
}
|
||||
|
||||
conTodo := BloqueContexto(ContextoEntrada{
|
||||
Transcripcion: "TRANS", Notas: "NOTAS", Observaciones: "OBS",
|
||||
Cliente: "Ana", Empresa: "ACME", Proyecto: "P",
|
||||
})
|
||||
for _, needle := range []string{"TRANS", "NOTAS", "OBS", "(ACME)"} {
|
||||
if !strings.Contains(conTodo, needle) {
|
||||
t.Fatalf("BloqueContexto debe incluir %q", needle)
|
||||
}
|
||||
}
|
||||
|
||||
econ := &EconomiaCotizacion{
|
||||
Partidas: []PartidaEconomia{
|
||||
{Ref: "P01", Nombre: "Sitio web", Fase: 1, TipoPago: "unico", Precio: 12345, TiempoEntrega: "2 semanas", ModeloCobro: "fijo"},
|
||||
},
|
||||
Totales: domain.TotalesCotizacion{
|
||||
SubtotalUnico: 12345, IVAUnico: 1975.2, TotalUnico: 14320.2, TotalPrimerAnio: 14320.2, IncluyeIVA: true,
|
||||
},
|
||||
Moneda: "MXN",
|
||||
}
|
||||
ctx := ContextoEntrada{Transcripcion: "t", Cliente: "Ana", Empresa: "ACME", Proyecto: "P"}
|
||||
hechos := map[string]any{"citas": []any{}, "hechos": []any{}}
|
||||
diag := map[string]any{"hallazgos": []any{}, "valorProblema": map[string]any{"dimensiones": []any{}, "notaMetodologia": ""}}
|
||||
|
||||
m1 := MensajePaso1(ctx)
|
||||
m2 := MensajePaso2(ctx, hechos, econ)
|
||||
m3 := MensajePaso3(ctx, hechos, diag, econ)
|
||||
|
||||
if !strings.Contains(m1, "registrar_hechos") || !strings.Contains(m1, "TEXTUALES") {
|
||||
t.Fatal("MensajePaso1 debe pedir registrar_hechos y citas TEXTUALES")
|
||||
}
|
||||
if !strings.Contains(m2, "registrar_diagnostico") {
|
||||
t.Fatal("MensajePaso2 debe pedir registrar_diagnostico")
|
||||
}
|
||||
if !strings.Contains(m3, "registrar_propuesta") {
|
||||
t.Fatal("MensajePaso3 debe pedir registrar_propuesta")
|
||||
}
|
||||
|
||||
for nombre, msg := range map[string]string{"paso 2": m2, "paso 3": m3} {
|
||||
if strings.Contains(msg, "12345") || strings.Contains(msg, "14320") {
|
||||
t.Fatalf("%s NO puede filtrar precios o totales", nombre)
|
||||
}
|
||||
if !strings.Contains(msg, "P01") {
|
||||
t.Fatalf("%s SI debe incluir refPartida P01", nombre)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestToolSchemasZeroUJCPriceKeys(t *testing.T) {
|
||||
schemas := []map[string]any{SchemaHechos(), SchemaDiagnostico(), SchemaRedaccion()}
|
||||
rawBytes, err := json.Marshal(schemas)
|
||||
if err != nil {
|
||||
t.Fatalf("error serializando schemas: %v", err)
|
||||
}
|
||||
todos := string(rawBytes)
|
||||
|
||||
prohibidos := []string{"precio", "total", "subtotal", "iva", "montoMinimo", "tarifaHora", "descuento"}
|
||||
for _, p := range prohibidos {
|
||||
if strings.Contains(todos, `"`+p+`"`) {
|
||||
t.Fatalf("ningun tool schema puede declarar propiedad de dinero UJC %q", p)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(todos, `"montoAnualMXN"`) {
|
||||
t.Fatal("SchemaDiagnostico debe incluir montoAnualMXN (costo del problema del cliente)")
|
||||
}
|
||||
if strings.Contains(todos, `"$schema"`) {
|
||||
t.Fatal("los tool schemas no deben llevar $schema")
|
||||
}
|
||||
if strings.Contains(todos, `"calculo"`) {
|
||||
t.Fatal("la dimension de valorProblema debe ser plana, sin objeto calculo")
|
||||
}
|
||||
if !strings.Contains(todos, `"additionalProperties"`) || !strings.Contains(todos, `"description"`) {
|
||||
t.Fatal("los tool schemas deben conservar additionalProperties y description")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidadoresSchemaPasos(t *testing.T) {
|
||||
// Hechos vacios validos (material pobre)
|
||||
if errs := ValidarHechos(map[string]any{
|
||||
"citas": []any{}, "hechos": []any{}, "materialesPendientes": []any{},
|
||||
"decisionesPendientes": []any{}, "mencionesFueraDeAlcance": []any{}, "redFlags": []any{},
|
||||
}); len(errs) != 0 {
|
||||
t.Fatalf("hechos vacios deben ser validos: %v", errs)
|
||||
}
|
||||
|
||||
// Diagnostico: omitir montoAnualMXN se tolera y rellena nil; con monto y <2 factores se rechaza
|
||||
dimSinMonto := map[string]any{
|
||||
"tipo": "tiempo", "descripcion": "Horas perdidas en atencion",
|
||||
"factores": []any{}, "confianza": "por_validar", "hechos": []any{},
|
||||
}
|
||||
diag := map[string]any{
|
||||
"hallazgos": []any{map[string]any{
|
||||
"id": "D01", "urgencia": "rojo", "titulo": "Titulo valido",
|
||||
"descripcion": strings.Repeat("x", 25), "confianza": "confirmado",
|
||||
"citas": []any{}, "hechos": []any{},
|
||||
}},
|
||||
"valorProblema": map[string]any{
|
||||
"dimensiones": []any{dimSinMonto},
|
||||
"notaMetodologia": "sin cifras",
|
||||
},
|
||||
"resultados": []any{},
|
||||
}
|
||||
if errs := ValidarDiagnostico(diag); len(errs) != 0 {
|
||||
t.Fatalf("diagnostico omitiendo montoAnualMXN debe validar: %v", errs)
|
||||
}
|
||||
if val, exists := dimSinMonto["montoAnualMXN"]; !exists || val != nil {
|
||||
t.Fatalf("omitir montoAnualMXN debe rellenar nil, obtuve exists=%v val=%v", exists, val)
|
||||
}
|
||||
|
||||
// Con montoAnualMXN y solo 1 factor -> error
|
||||
dimUnFactor := map[string]any{
|
||||
"tipo": "tiempo", "descripcion": "Horas perdidas en atencion",
|
||||
"factores": []any{map[string]any{"nombre": "a", "valor": 1.0, "confianza": "estimado"}},
|
||||
"montoAnualMXN": 1.0, "confianza": "estimado", "hechos": []any{},
|
||||
}
|
||||
diag["valorProblema"].(map[string]any)["dimensiones"] = []any{dimUnFactor}
|
||||
if errs := ValidarDiagnostico(diag); len(errs) == 0 {
|
||||
t.Fatal("esperaba rechazo al declarar montoAnualMXN con menos de 2 factores")
|
||||
}
|
||||
|
||||
// Redaccion estricta rechaza propiedad desconocida `precioTotal`
|
||||
red := map[string]any{
|
||||
"hero": map[string]any{"titulo": "Titulo valido", "subtitulo": strings.Repeat("x", 25)},
|
||||
"citaDestacadaId": "C01",
|
||||
"alcance": []any{map[string]any{"refPartida": "P01", "descripcionResultado": strings.Repeat("x", 25)}},
|
||||
"beneficios": []any{},
|
||||
"exclusiones": []any{map[string]any{"texto": strings.Repeat("x", 20), "razon": "porque si"}},
|
||||
"backlogEvolucion": []any{},
|
||||
"notasInternas": []any{},
|
||||
"precioTotal": 99999,
|
||||
}
|
||||
if errs := ValidarRedaccion(red); len(errs) == 0 {
|
||||
t.Fatal("ValidarRedaccion debe rechazar propiedades desconocidas")
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────────────────── validacion.go ───────────────────────────
|
||||
|
||||
const citaPrueba = "no llevamos control de quien contesta el whatsapp el fin de semana"
|
||||
|
||||
func econPrueba() *EconomiaCotizacion {
|
||||
return &EconomiaCotizacion{
|
||||
Partidas: []PartidaEconomia{
|
||||
{Ref: "P01", Nombre: "Sitio web", Fase: 1, TipoPago: "unico", Precio: 12000, TiempoEntrega: "2 semanas", ModeloCobro: "fijo"},
|
||||
},
|
||||
Totales: domain.TotalesCotizacion{
|
||||
SubtotalUnico: 12000, IVAUnico: 1920, TotalUnico: 13920, TotalPrimerAnio: 13920, IncluyeIVA: true,
|
||||
},
|
||||
Moneda: "MXN",
|
||||
}
|
||||
}
|
||||
|
||||
func propuestaBase() map[string]any {
|
||||
return map[string]any{
|
||||
"hechos": map[string]any{
|
||||
"citas": []any{
|
||||
map[string]any{"id": "C01", "textoLiteral": citaPrueba, "quienLoDijo": "el socio"},
|
||||
},
|
||||
"hechos": []any{
|
||||
map[string]any{"id": "H01", "enunciado": "No hay control de la atencion", "confianza": "confirmado", "citas": []any{"C01"}},
|
||||
},
|
||||
"materialesPendientes": []any{map[string]any{"texto": "Accesos al dominio", "bloqueaEntrega": true}},
|
||||
"decisionesPendientes": []any{map[string]any{"texto": "Definir responsable de atencion", "quienDecide": "el socio"}},
|
||||
"mencionesFueraDeAlcance": []any{},
|
||||
"redFlags": []any{},
|
||||
},
|
||||
"diagnostico": map[string]any{
|
||||
"hallazgos": []any{
|
||||
map[string]any{
|
||||
"id": "D01", "urgencia": "rojo", "titulo": "Prospectos sin seguimiento",
|
||||
"descripcion": "Los mensajes del fin de semana se pierden.",
|
||||
"confianza": "confirmado", "citas": []any{"C01"}, "hechos": []any{"H01"},
|
||||
},
|
||||
},
|
||||
"valorProblema": map[string]any{
|
||||
"dimensiones": []any{
|
||||
map[string]any{
|
||||
"tipo": "tiempo", "descripcion": "Horas perdidas de atencion",
|
||||
"factores": []any{
|
||||
map[string]any{"nombre": "horas por semana", "valor": 8.0, "confianza": "confirmado"},
|
||||
map[string]any{"nombre": "semanas", "valor": 52.0, "confianza": "confirmado"},
|
||||
map[string]any{"nombre": "costo por hora", "valor": 400.0, "confianza": "estimado"},
|
||||
},
|
||||
"montoAnualMXN": 166400.0, "confianza": "estimado", "hechos": []any{"H01"},
|
||||
},
|
||||
},
|
||||
"notaMetodologia": "Ocho horas por semana a costo cargado.",
|
||||
},
|
||||
"resultados": []any{
|
||||
map[string]any{
|
||||
"enunciado": "Ningun mensaje sin respuesta en mas de 24 horas",
|
||||
"metrica": "tiempo de respuesta", "lineaBase": nil, "periodoMedicion": "mensual",
|
||||
},
|
||||
},
|
||||
},
|
||||
"redaccion": map[string]any{
|
||||
"hero": map[string]any{
|
||||
"titulo": "Propuesta de digitalizacion",
|
||||
"subtitulo": "Ordenar la atencion para dejar de perder prospectos.",
|
||||
},
|
||||
"citaDestacadaId": "C01",
|
||||
"alcance": []any{
|
||||
map[string]any{"refPartida": "P01", "descripcionResultado": "Un lugar a donde mandar a los prospectos que llegan de los anuncios."},
|
||||
},
|
||||
"beneficios": []any{
|
||||
map[string]any{"etiqueta": "Respuesta", "texto": "Cada mensaje queda registrado y con responsable.", "hallazgoId": "D01"},
|
||||
},
|
||||
"exclusiones": []any{
|
||||
map[string]any{"texto": "No incluye migrar el historico de pedidos de los ultimos 4 anos.", "razon": "Se evalua en fase 2."},
|
||||
},
|
||||
"backlogEvolucion": []any{},
|
||||
"notasInternas": []any{"El socio es quien decide."},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func tieneRegla(avisos []Aviso, regla string) bool {
|
||||
for _, a := range avisos {
|
||||
if a.Regla == regla {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func severidadRegla(avisos []Aviso, regla string) string {
|
||||
for _, a := range avisos {
|
||||
if a.Regla == regla {
|
||||
return a.Severidad
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func TestNormalizarTexto(t *testing.T) {
|
||||
if got := NormalizarTexto("¿Cómo estás, Juan?"); got != "como estas juan" {
|
||||
t.Fatalf("esperado %q, obtuve %q", "como estas juan", got)
|
||||
}
|
||||
if got := NormalizarTexto(" a b "); got != "a b" {
|
||||
t.Fatalf("esperado %q, obtuve %q", "a b", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidarPropuestaTodasLasReglas(t *testing.T) {
|
||||
econ := econPrueba()
|
||||
fuentes := "El socio dijo: " + citaPrueba + ". Nada mas."
|
||||
|
||||
t.Run("propuesta limpia sin bloqueantes", func(t *testing.T) {
|
||||
avisos := ValidarPropuesta(propuestaBase(), econ, fuentes, "")
|
||||
if HayBloqueantes(avisos) {
|
||||
t.Fatalf("propuesta limpia no debe producir bloqueantes: %+v", avisos)
|
||||
}
|
||||
if len(avisos) != 0 {
|
||||
t.Fatalf("propuesta limpia no debe producir avisos: %+v", avisos)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("R0 fuga de notas internas 7-gramas", func(t *testing.T) {
|
||||
interno := "el socio pidio descuento antes de entender el alcance del proyecto completo"
|
||||
|
||||
// Fuga en hero
|
||||
p := propuestaBase()
|
||||
p["redaccion"].(map[string]any)["hero"].(map[string]any)["subtitulo"] = "Contexto del proyecto: " + interno + "."
|
||||
av := ValidarPropuesta(p, econ, fuentes, interno)
|
||||
if !tieneRegla(av, "R0") || severidadRegla(av, "R0") != "bloqueante" {
|
||||
t.Fatalf("R0 debe bloquear fuga en hero: %+v", av)
|
||||
}
|
||||
|
||||
// Fuga en hallazgo
|
||||
p = propuestaBase()
|
||||
p["diagnostico"].(map[string]any)["hallazgos"].([]any)[0].(map[string]any)["descripcion"] = "Observado: " + interno + "."
|
||||
av = ValidarPropuesta(p, econ, fuentes, interno)
|
||||
if !tieneRegla(av, "R0") {
|
||||
t.Fatalf("R0 debe revisar todos los campos visibles (hallazgo): %+v", av)
|
||||
}
|
||||
|
||||
// Sin fuga -> ok
|
||||
if tieneRegla(ValidarPropuesta(propuestaBase(), econ, fuentes, interno), "R0") {
|
||||
t.Fatal("R0 no debe disparar si no hay fuga")
|
||||
}
|
||||
|
||||
// En notasInternas del propio resultado -> NO se imprime, NO dispara R0
|
||||
p = propuestaBase()
|
||||
p["redaccion"].(map[string]any)["notasInternas"] = []any{interno}
|
||||
if tieneRegla(ValidarPropuesta(p, econ, fuentes, interno), "R0") {
|
||||
t.Fatal("R0 no debe quejarse de notasInternas (no se imprimen)")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("R2 y R2b referencias de partidas", func(t *testing.T) {
|
||||
p := propuestaBase()
|
||||
p["redaccion"].(map[string]any)["alcance"].([]any)[0].(map[string]any)["refPartida"] = "P99"
|
||||
av := ValidarPropuesta(p, econ, fuentes, "")
|
||||
if !tieneRegla(av, "R2") || severidadRegla(av, "R2") != "bloqueante" {
|
||||
t.Fatalf("R2 debe bloquear partida inventada P99: %+v", av)
|
||||
}
|
||||
|
||||
p = propuestaBase()
|
||||
p["redaccion"].(map[string]any)["alcance"] = []any{}
|
||||
av = ValidarPropuesta(p, econ, fuentes, "")
|
||||
if !tieneRegla(av, "R2b") || severidadRegla(av, "R2b") != "advertencia" {
|
||||
t.Fatalf("R2b debe advertir partida cotizada no descrita: %+v", av)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("R3 cita destacada existe y es literal", func(t *testing.T) {
|
||||
p := propuestaBase()
|
||||
p["redaccion"].(map[string]any)["citaDestacadaId"] = "C09"
|
||||
av := ValidarPropuesta(p, econ, fuentes, "")
|
||||
if !tieneRegla(av, "R3") || severidadRegla(av, "R3") != "bloqueante" {
|
||||
t.Fatalf("R3 debe bloquear cita inexistente: %+v", av)
|
||||
}
|
||||
|
||||
p = propuestaBase()
|
||||
p["hechos"].(map[string]any)["citas"].([]any)[0].(map[string]any)["textoLiteral"] = "esto nunca lo dijo nadie en la reunion"
|
||||
av = ValidarPropuesta(p, econ, fuentes, "")
|
||||
if !tieneRegla(av, "R3") {
|
||||
t.Fatalf("R3 debe bloquear cita no literal: %+v", av)
|
||||
}
|
||||
|
||||
// Tolera acentos, mayusculas y puntuacion
|
||||
p = propuestaBase()
|
||||
p["hechos"].(map[string]any)["citas"].([]any)[0].(map[string]any)["textoLiteral"] = "NO LLEVAMOS CONTROL, de quién contesta... el WhatsApp el fin de semana!"
|
||||
if tieneRegla(ValidarPropuesta(p, econ, fuentes, ""), "R3") {
|
||||
t.Fatal("R3 debe tolerar acentos, mayusculas y puntuacion")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("R4 confirmado sin evidencia", func(t *testing.T) {
|
||||
p := propuestaBase()
|
||||
h0 := p["diagnostico"].(map[string]any)["hallazgos"].([]any)[0].(map[string]any)
|
||||
h0["citas"] = []any{}
|
||||
h0["hechos"] = []any{}
|
||||
av := ValidarPropuesta(p, econ, fuentes, "")
|
||||
if !tieneRegla(av, "R4") || severidadRegla(av, "R4") != "advertencia" {
|
||||
t.Fatalf("R4 debe advertir hallazgo confirmado sin citas ni hechos: %+v", av)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("R5 aritmetica dentro de 2% y R5b sin factores confirmados", func(t *testing.T) {
|
||||
// No cuadra -> R5 bloqueante
|
||||
p := propuestaBase()
|
||||
dim := p["diagnostico"].(map[string]any)["valorProblema"].(map[string]any)["dimensiones"].([]any)[0].(map[string]any)
|
||||
dim["montoAnualMXN"] = 999999.0
|
||||
av := ValidarPropuesta(p, econ, fuentes, "")
|
||||
if !tieneRegla(av, "R5") || severidadRegla(av, "R5") != "bloqueante" {
|
||||
t.Fatalf("R5 debe bloquear aritmetica inconsistente: %+v", av)
|
||||
}
|
||||
|
||||
// Cuadra por suma dentro de 2% -> sin R5
|
||||
p = propuestaBase()
|
||||
dim = p["diagnostico"].(map[string]any)["valorProblema"].(map[string]any)["dimensiones"].([]any)[0].(map[string]any)
|
||||
dim["factores"] = []any{
|
||||
map[string]any{"nombre": "a", "valor": 10000.0, "confianza": "confirmado"},
|
||||
map[string]any{"nombre": "b", "valor": 5000.0, "confianza": "estimado"},
|
||||
}
|
||||
dim["montoAnualMXN"] = 15100.0 // diferencia < 1%
|
||||
if tieneRegla(ValidarPropuesta(p, econ, fuentes, ""), "R5") {
|
||||
t.Fatal("R5 debe aceptar suma dentro del margen de 2%")
|
||||
}
|
||||
|
||||
// Sin cifra (nil) -> sin R5 ni R5b
|
||||
p = propuestaBase()
|
||||
dim = p["diagnostico"].(map[string]any)["valorProblema"].(map[string]any)["dimensiones"].([]any)[0].(map[string]any)
|
||||
dim["montoAnualMXN"] = nil
|
||||
dim["factores"] = []any{}
|
||||
av = ValidarPropuesta(p, econ, fuentes, "")
|
||||
if tieneRegla(av, "R5") || tieneRegla(av, "R5b") {
|
||||
t.Fatalf("sin montoAnualMXN no debe disparar R5 ni R5b: %+v", av)
|
||||
}
|
||||
|
||||
// Solo estimados -> R5b advertencia
|
||||
p = propuestaBase()
|
||||
dim = p["diagnostico"].(map[string]any)["valorProblema"].(map[string]any)["dimensiones"].([]any)[0].(map[string]any)
|
||||
for _, f := range dim["factores"].([]any) {
|
||||
f.(map[string]any)["confianza"] = "estimado"
|
||||
}
|
||||
av = ValidarPropuesta(p, econ, fuentes, "")
|
||||
if !tieneRegla(av, "R5b") || severidadRegla(av, "R5b") != "advertencia" {
|
||||
t.Fatalf("R5b debe advertir cuando ningun factor es confirmado: %+v", av)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("R6 hallazgoId colgante", func(t *testing.T) {
|
||||
p := propuestaBase()
|
||||
p["redaccion"].(map[string]any)["beneficios"].([]any)[0].(map[string]any)["hallazgoId"] = "D99"
|
||||
av := ValidarPropuesta(p, econ, fuentes, "")
|
||||
if !tieneRegla(av, "R6") || severidadRegla(av, "R6") != "advertencia" {
|
||||
t.Fatalf("R6 debe advertir beneficio colgante: %+v", av)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("MARCA MONEDA GARANTIA PII", func(t *testing.T) {
|
||||
// MARCA
|
||||
p := propuestaBase()
|
||||
p["redaccion"].(map[string]any)["beneficios"].([]any)[0].(map[string]any)["texto"] = "Lo integramos con HubSpot sin problema alguno."
|
||||
av := ValidarPropuesta(p, econ, fuentes, "")
|
||||
if !tieneRegla(av, "MARCA") || severidadRegla(av, "MARCA") != "bloqueante" {
|
||||
t.Fatalf("MARCA debe bloquear otro CRM: %+v", av)
|
||||
}
|
||||
|
||||
// MONEDA
|
||||
p = propuestaBase()
|
||||
p["redaccion"].(map[string]any)["hero"].(map[string]any)["subtitulo"] = "Una inversion de 1,800 USD al mes para tu negocio."
|
||||
av = ValidarPropuesta(p, econ, fuentes, "")
|
||||
if !tieneRegla(av, "MONEDA") || severidadRegla(av, "MONEDA") != "bloqueante" {
|
||||
t.Fatalf("MONEDA debe bloquear USD: %+v", av)
|
||||
}
|
||||
|
||||
// GARANTIA
|
||||
p = propuestaBase()
|
||||
p["redaccion"].(map[string]any)["beneficios"].([]any)[0].(map[string]any)["texto"] = "Te garantizamos la posicion numero uno en Google."
|
||||
av = ValidarPropuesta(p, econ, fuentes, "")
|
||||
if !tieneRegla(av, "GARANTIA") || severidadRegla(av, "GARANTIA") != "bloqueante" {
|
||||
t.Fatalf("GARANTIA debe bloquear promesa garantizada: %+v", av)
|
||||
}
|
||||
|
||||
// PII (advertencia, no bloqueante)
|
||||
p = propuestaBase()
|
||||
p["redaccion"].(map[string]any)["hero"].(map[string]any)["subtitulo"] = "El sueldo de quien atiende sale muy caro hoy en dia."
|
||||
av = ValidarPropuesta(p, econ, fuentes, "")
|
||||
if !tieneRegla(av, "PII") || severidadRegla(av, "PII") != "advertencia" || HayBloqueantes(av) {
|
||||
t.Fatalf("PII debe ser advertencia no bloqueante: %+v", av)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// ─────────────────────────── pipeline.go ───────────────────────────
|
||||
|
||||
func TestEjecutarPipelineTresPasos(t *testing.T) {
|
||||
base := propuestaBase()
|
||||
var step int32
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
n := atomic.AddInt32(&step, 1)
|
||||
var toolName string
|
||||
var payload any
|
||||
switch n {
|
||||
case 1:
|
||||
toolName = "registrar_hechos"
|
||||
payload = base["hechos"]
|
||||
case 2:
|
||||
toolName = "registrar_diagnostico"
|
||||
payload = base["diagnostico"]
|
||||
case 3:
|
||||
toolName = "registrar_propuesta"
|
||||
payload = base["redaccion"]
|
||||
default:
|
||||
t.Fatalf("llamada inesperada #%d", n)
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"id": "msg_" + strconv.Itoa(int(n)),
|
||||
"type": "message",
|
||||
"role": "assistant",
|
||||
"content": []any{
|
||||
map[string]any{
|
||||
"type": "tool_use",
|
||||
"id": "tu_" + strconv.Itoa(int(n)),
|
||||
"name": toolName,
|
||||
"input": payload,
|
||||
},
|
||||
},
|
||||
"usage": map[string]any{
|
||||
"input_tokens": 100 * int(n),
|
||||
"output_tokens": 50 * int(n),
|
||||
"cache_read_input_tokens": 40,
|
||||
"cache_creation_input_tokens": 10,
|
||||
},
|
||||
})
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
cliente := &ClienteIA{
|
||||
APIKey: "test-key",
|
||||
BaseURL: srv.URL,
|
||||
Model: "MiniMax-M3",
|
||||
HTTPClient: srv.Client(),
|
||||
Sleep: func(context.Context, time.Duration) error { return nil },
|
||||
}
|
||||
|
||||
res, err := ejecutarPipeline(
|
||||
context.Background(),
|
||||
cliente,
|
||||
ContextoEntrada{
|
||||
Transcripcion: "El socio dijo: " + citaPrueba + ".",
|
||||
Cliente: "Juan Perez",
|
||||
Empresa: "ACME",
|
||||
Proyecto: "MKT Digital",
|
||||
},
|
||||
econPrueba(),
|
||||
"nota confidencial que no debe aparecer en la propuesta final jamas",
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("error en pipeline: %v", err)
|
||||
}
|
||||
if res.Modelo != "MiniMax-M3" {
|
||||
t.Fatalf("Modelo esperado MiniMax-M3, obtuve %q", res.Modelo)
|
||||
}
|
||||
if HayBloqueantes(res.Avisos) {
|
||||
t.Fatalf("no esperaba bloqueantes en pipeline limpio: %+v", res.Avisos)
|
||||
}
|
||||
if res.Contenido["hechos"] == nil || res.Contenido["diagnostico"] == nil || res.Contenido["redaccion"] == nil {
|
||||
t.Fatalf("Contenido incompleto: %+v", res.Contenido)
|
||||
}
|
||||
totalUso, ok := res.Traza["totalUso"].(UsoTokens)
|
||||
if !ok || totalUso.Entrada != 600 || totalUso.Salida != 300 || totalUso.CacheLectura != 120 || totalUso.CacheEscritura != 30 {
|
||||
t.Fatalf("Traza totalUso incorrecta: %#v", res.Traza["totalUso"])
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
Reference in New Issue
Block a user