1745 lines
58 KiB
Go
1745 lines
58 KiB
Go
package cli
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"math"
|
|
"net/http"
|
|
"net/url"
|
|
"os"
|
|
"path/filepath"
|
|
"slices"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Reference resolvers (nombre -> id)
|
|
// ---------------------------------------------------------------------------
|
|
|
|
func asMap(v any) map[string]any {
|
|
m, _ := v.(map[string]any)
|
|
return m
|
|
}
|
|
|
|
func asSlice(v any) []any {
|
|
s, _ := v.([]any)
|
|
return s
|
|
}
|
|
|
|
func mapStr(m map[string]any, key string) string {
|
|
if m == nil {
|
|
return ""
|
|
}
|
|
s, _ := m[key].(string)
|
|
return s
|
|
}
|
|
|
|
func resolverCategoria(c *apiClient, valor string) (any, error) {
|
|
v, isNull := textoOpcional(valor)
|
|
if isNull {
|
|
return nil, nil
|
|
}
|
|
raw, err := c.api(http.MethodGet, "/api/categorias")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
cats := asSlice(raw)
|
|
for _, item := range cats {
|
|
m := asMap(item)
|
|
if mapStr(m, "id") == v {
|
|
return mapStr(m, "id"), nil
|
|
}
|
|
}
|
|
var nombres []string
|
|
for _, item := range cats {
|
|
m := asMap(item)
|
|
nom := mapStr(m, "nombre")
|
|
nombres = append(nombres, nom)
|
|
if strings.EqualFold(nom, v) {
|
|
return mapStr(m, "id"), nil
|
|
}
|
|
}
|
|
return nil, errorUso(
|
|
fmt.Sprintf(`No existe la categoria "%s"`, v),
|
|
fmt.Sprintf(`Categorias disponibles: %s. Crea una con: cotizador categorias crear --nombre "%s"`, strings.Join(nombres, ", "), v),
|
|
)
|
|
}
|
|
|
|
func intentarPorID(c *apiClient, ruta string) (any, error) {
|
|
res, err := c.api(http.MethodGet, ruta)
|
|
if err != nil {
|
|
var ce *cliError
|
|
if errors.As(err, &ce) && ce.Codigo == ExitNoEncontrado {
|
|
return nil, nil
|
|
}
|
|
return nil, err
|
|
}
|
|
return res, nil
|
|
}
|
|
|
|
func resolverServicio(c *apiClient, ref string) (map[string]any, error) {
|
|
porID, err := intentarPorID(c, "/api/catalogo/"+url.PathEscape(ref))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if m := asMap(porID); m != nil {
|
|
return m, nil
|
|
}
|
|
|
|
raw, err := c.api(http.MethodGet, "/api/catalogo?activo=true&q="+url.QueryEscape(ref))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
candidatos := asSlice(raw)
|
|
var exactos []map[string]any
|
|
for _, item := range candidatos {
|
|
m := asMap(item)
|
|
if strings.EqualFold(mapStr(m, "nombre"), ref) {
|
|
exactos = append(exactos, m)
|
|
}
|
|
}
|
|
if len(exactos) == 1 {
|
|
return exactos[0], nil
|
|
}
|
|
if len(candidatos) == 1 {
|
|
return asMap(candidatos[0]), nil
|
|
}
|
|
if len(candidatos) == 0 {
|
|
return nil, &cliError{
|
|
Mensaje: fmt.Sprintf(`No existe el servicio "%s" (ni como id ni como nombre de un servicio activo)`, ref),
|
|
Codigo: ExitNoEncontrado,
|
|
Sugerencia: "Busca con: cotizador servicios listar --q <texto> (agrega --todos para incluir archivados)",
|
|
}
|
|
}
|
|
var sample []string
|
|
limit := len(candidatos)
|
|
if limit > 10 {
|
|
limit = 10
|
|
}
|
|
for _, item := range candidatos[:limit] {
|
|
m := asMap(item)
|
|
sample = append(sample, fmt.Sprintf("%s (%s)", mapStr(m, "id"), mapStr(m, "nombre")))
|
|
}
|
|
return nil, errorUso(
|
|
fmt.Sprintf(`"%s" es ambiguo (%d coincidencias)`, ref, len(candidatos)),
|
|
fmt.Sprintf("Usa el id. Coincidencias: %s", strings.Join(sample, "; ")),
|
|
)
|
|
}
|
|
|
|
func resolverCotizacion(c *apiClient, ref string) (string, error) {
|
|
porID, err := intentarPorID(c, "/api/cotizaciones/"+url.PathEscape(ref))
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if m := asMap(porID); m != nil && mapStr(m, "id") != "" {
|
|
return mapStr(m, "id"), nil
|
|
}
|
|
raw, err := c.api(http.MethodGet, "/api/cotizaciones?q="+url.QueryEscape(ref)+"&limit=20")
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
for _, item := range asSlice(raw) {
|
|
m := asMap(item)
|
|
if strings.EqualFold(mapStr(m, "numero"), ref) {
|
|
return mapStr(m, "id"), nil
|
|
}
|
|
}
|
|
return "", &cliError{
|
|
Mensaje: fmt.Sprintf(`No existe la cotizacion "%s"`, ref),
|
|
Codigo: ExitNoEncontrado,
|
|
Sugerencia: "Pasa el id o el numero exacto (ej. UJ2605AG001). Busca con: cotizador cotizaciones listar --q <texto>",
|
|
}
|
|
}
|
|
|
|
func descargar(c *apiClient, ruta, salida, porDefecto string) (map[string]any, error) {
|
|
raw, err := c.api(http.MethodGet, ruta, apiOpts{Binario: true})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
bin := raw.(*binaryResponse)
|
|
destName := salida
|
|
if destName == "" {
|
|
destName = bin.NombreArchivo
|
|
}
|
|
if destName == "" {
|
|
destName = porDefecto
|
|
}
|
|
destino, err := filepath.Abs(destName)
|
|
if err != nil {
|
|
destino = destName
|
|
}
|
|
if err := os.MkdirAll(filepath.Dir(destino), 0o755); err != nil {
|
|
return nil, err
|
|
}
|
|
if err := os.WriteFile(destino, bin.Buffer, 0o644); err != nil {
|
|
return nil, err
|
|
}
|
|
return map[string]any{
|
|
"ok": true,
|
|
"archivo": destino,
|
|
"bytes": len(bin.Buffer),
|
|
"tipo": bin.Tipo,
|
|
}, nil
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Body builders & shared flags
|
|
// ---------------------------------------------------------------------------
|
|
|
|
var flagConfirmar = flagSpec{
|
|
Flag: "confirmar",
|
|
Tipo: "booleano",
|
|
Descripcion: "Obligatoria: confirma una accion que no se puede deshacer",
|
|
}
|
|
|
|
func toAnySlice(ss []string) []any {
|
|
out := make([]any, len(ss))
|
|
for i, s := range ss {
|
|
out[i] = s
|
|
}
|
|
return out
|
|
}
|
|
|
|
var flagsServicio = []flagSpec{
|
|
{Flag: "nombre", Tipo: "texto", Descripcion: "Nombre del servicio"},
|
|
{Flag: "fase", Tipo: "entero", Valores: []any{0, 1, 2, 3}, Descripcion: "0 Auditoria, 1 Setup, 2 Publicidad, 3 Contenido/SEO"},
|
|
{Flag: "tipo-pago", Tipo: "texto", Valores: []any{"unico", "mensual"}, Descripcion: "unico o mensual"},
|
|
{Flag: "precio", Tipo: "numero", Descripcion: "Precio base en MXN, sin IVA (acepta 4500 o 4,500)"},
|
|
{Flag: "descripcion", Tipo: "texto", Descripcion: `Descripcion (usa "" para borrarla)`},
|
|
{Flag: "tiempo-entrega", Tipo: "texto", Descripcion: `Ej. "4 - 10 dias" (default al crear)`},
|
|
{Flag: "entregable", Tipo: "texto", Repetible: true, Descripcion: "Un entregable; repite la flag para varios. En editar REEMPLAZA la lista"},
|
|
{Flag: "categoria", Tipo: "texto", Descripcion: `Id o nombre de la categoria ("ninguna" para quitarla)`},
|
|
{Flag: "variante", Tipo: "texto", Descripcion: "Ej. WooCommerce, Shopify"},
|
|
{Flag: "nivel", Tipo: "texto", Valores: toAnySlice(nivelesServicio), Descripcion: `Nivel de cliente ("ninguno" para quitarlo)`},
|
|
{Flag: "orden", Tipo: "entero", Descripcion: "Posicion dentro de su fase (default al crear: al final)"},
|
|
{Flag: "datos", Tipo: "json", Descripcion: "Objeto JSON con los campos de la API (en linea, @archivo.json o - para stdin). Las flags tienen prioridad"},
|
|
}
|
|
|
|
func cuerpoServicio(c *apiClient, flags *parsedFlags, stdin io.Reader) (map[string]any, error) {
|
|
base, err := leerDatos(flags.Str("datos"), flags.Has("datos"), stdin)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// Admite categoria por nombre tambien dentro de --datos.
|
|
if catName, ok := base["categoria"].(string); ok {
|
|
if _, hasID := base["categoriaId"]; !hasID {
|
|
resolved, err := resolverCategoria(c, catName)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
base["categoriaId"] = resolved
|
|
delete(base, "categoria")
|
|
}
|
|
}
|
|
|
|
desdeFlags := make(map[string]any)
|
|
if flags.Has("nombre") {
|
|
desdeFlags["nombre"] = flags.Str("nombre")
|
|
}
|
|
if flags.Has("fase") {
|
|
f, err := parseEntero(flags.Str("fase"), "fase")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if f < 0 || f > 3 {
|
|
return nil, errorUso("--fase debe ser 0, 1, 2 o 3")
|
|
}
|
|
desdeFlags["fase"] = f
|
|
}
|
|
if flags.Has("tipoPago") {
|
|
tp, err := unoDe(flags.Str("tipoPago"), []string{"unico", "mensual"}, "tipo-pago")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
desdeFlags["tipoPago"] = tp
|
|
}
|
|
if flags.Has("precio") {
|
|
p, err := parseNumero(flags.Str("precio"), "precio")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
desdeFlags["precioBase"] = p
|
|
}
|
|
if flags.Has("descripcion") {
|
|
v, isNull := textoOpcional(flags.Str("descripcion"))
|
|
if isNull {
|
|
desdeFlags["descripcion"] = nil
|
|
} else {
|
|
desdeFlags["descripcion"] = v
|
|
}
|
|
}
|
|
if flags.Has("tiempoEntrega") {
|
|
desdeFlags["tiempoEntrega"] = flags.Str("tiempoEntrega")
|
|
}
|
|
if flags.Has("entregable") {
|
|
desdeFlags["entregablesDefault"] = flags.List("entregable")
|
|
}
|
|
if flags.Has("categoria") {
|
|
resolved, err := resolverCategoria(c, flags.Str("categoria"))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
desdeFlags["categoriaId"] = resolved
|
|
}
|
|
if flags.Has("variante") {
|
|
v, isNull := textoOpcional(flags.Str("variante"))
|
|
if isNull {
|
|
desdeFlags["variante"] = nil
|
|
} else {
|
|
desdeFlags["variante"] = v
|
|
}
|
|
}
|
|
if flags.Has("nivel") {
|
|
v, isNull := textoOpcional(flags.Str("nivel"))
|
|
if isNull {
|
|
desdeFlags["nivel"] = nil
|
|
} else {
|
|
nv, err := unoDe(v, nivelesServicio, "nivel")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
desdeFlags["nivel"] = nv
|
|
}
|
|
}
|
|
if flags.Has("orden") {
|
|
o, err := parseEntero(flags.Str("orden"), "orden")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
desdeFlags["orden"] = o
|
|
}
|
|
|
|
out := make(map[string]any, len(base)+len(desdeFlags))
|
|
for k, v := range base {
|
|
out[k] = v
|
|
}
|
|
for k, v := range desdeFlags {
|
|
out[k] = v
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
func partidaDesdeCatalogo(s map[string]any, precio *float64) map[string]any {
|
|
p := s["precioBase"]
|
|
if precio != nil {
|
|
p = *precio
|
|
}
|
|
entregables := s["entregablesDefault"]
|
|
if entregables == nil {
|
|
entregables = []any{}
|
|
}
|
|
return map[string]any{
|
|
"catalogoId": s["id"],
|
|
"nombre": s["nombre"],
|
|
"fase": s["fase"],
|
|
"tipoPago": s["tipoPago"],
|
|
"precio": p,
|
|
"tiempoEntrega": s["tiempoEntrega"],
|
|
"entregables": entregables,
|
|
}
|
|
}
|
|
|
|
func partidaPorHoras(texto string) (map[string]any, error) {
|
|
parts := strings.Split(texto, "|")
|
|
var concepto, horasTxt, tarifaTxt string
|
|
if len(parts) > 0 {
|
|
concepto = strings.TrimSpace(parts[0])
|
|
}
|
|
if len(parts) > 1 {
|
|
horasTxt = strings.TrimSpace(parts[1])
|
|
}
|
|
if len(parts) > 2 {
|
|
tarifaTxt = strings.TrimSpace(parts[2])
|
|
}
|
|
if concepto == "" || horasTxt == "" {
|
|
return nil, errorUso(fmt.Sprintf(`--partida-horas debe ser "Concepto|horas|tarifa" (tarifa opcional, default %.0f); recibi "%s"`, tarifaHoraDefault, texto))
|
|
}
|
|
horas, err := parseNumero(horasTxt, "partida-horas")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
tarifa := tarifaHoraDefault
|
|
if tarifaTxt != "" {
|
|
tarifa, err = parseNumero(tarifaTxt, "partida-horas")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
return map[string]any{
|
|
"catalogoId": "custom-" + uuid.NewString(),
|
|
"nombre": concepto,
|
|
"fase": 1,
|
|
"tipoPago": "unico",
|
|
"precio": math.Round(horas*tarifa*100) / 100,
|
|
"tiempoEntrega": "A convenir",
|
|
"entregables": []any{},
|
|
"esPersonalizado": true,
|
|
"modeloCobro": "horas",
|
|
"horas": horas,
|
|
"tarifaHora": tarifa,
|
|
}, nil
|
|
}
|
|
|
|
func resumenCotizacion(c map[string]any) map[string]any {
|
|
sliceDate := func(s string) any {
|
|
if len(s) >= 10 {
|
|
return s[:10]
|
|
}
|
|
if s == "" {
|
|
return nil
|
|
}
|
|
return s
|
|
}
|
|
cliente := asMap(c["cliente"])
|
|
asesor := asMap(c["asesor"])
|
|
plan := asMap(c["planBucefalo"])
|
|
var planNivel any
|
|
if plan != nil && plan["nivel"] != nil {
|
|
planNivel = plan["nivel"]
|
|
}
|
|
return map[string]any{
|
|
"id": c["id"],
|
|
"numero": c["numero"],
|
|
"estado": c["estado"],
|
|
"fecha": sliceDate(mapStr(c, "fecha")),
|
|
"vigencia": sliceDate(mapStr(c, "vigencia")),
|
|
"cliente": cliente["nombre"],
|
|
"empresa": cliente["empresa"],
|
|
"proyecto": c["proyecto"],
|
|
"moneda": c["moneda"],
|
|
"esDoble": c["esDoble"],
|
|
"partidas": len(asSlice(c["servicios"])),
|
|
"planBucefaloCRM": planNivel,
|
|
"asesor": asesor["name"],
|
|
}
|
|
}
|
|
|
|
func exigirConfirmacion(flags *parsedFlags, accion string) error {
|
|
if !flags.Bool("confirmar") && !flags.Bool("dryRun") {
|
|
return errorUso(fmt.Sprintf("%s no se puede deshacer. Repite el comando con --confirmar si es lo que quieres.", accion))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func exigirPosicional(pos []string, i int, nombre, comando string) (string, error) {
|
|
if i >= len(pos) || pos[i] == "" {
|
|
return "", errorUso(
|
|
fmt.Sprintf("Falta el argumento <%s>", nombre),
|
|
fmt.Sprintf("Uso: cotizador %s <%s>", comando, nombre),
|
|
)
|
|
}
|
|
return pos[i], nil
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Command registry (all 30 commands matching cli/cotizador.mjs)
|
|
// ---------------------------------------------------------------------------
|
|
|
|
func allCommands() []commandSpec {
|
|
return []commandSpec{
|
|
// ----- sesion -----
|
|
{
|
|
Comando: "login",
|
|
Descripcion: "Inicia sesion con una cuenta staff y guarda el token en ~/.cotizador-uj/sesiones.json (7 dias).",
|
|
Flags: []flagSpec{
|
|
{Flag: "email", Tipo: "texto", Descripcion: "Correo (o $COTIZADOR_EMAIL)"},
|
|
{Flag: "password", Tipo: "texto", Descripcion: "Contrasena (o $COTIZADOR_PASSWORD)"},
|
|
{Flag: "password-stdin", Tipo: "booleano", Descripcion: "Lee la contrasena de stdin (no queda en el historial)"},
|
|
},
|
|
Ejemplos: []string{
|
|
"cotizador login --email [email protected] --password-stdin < pass.txt",
|
|
"COTIZADOR_EMAIL=... COTIZADOR_PASSWORD=... cotizador login",
|
|
},
|
|
Endpoint: "POST /api/auth/login",
|
|
HasEndpoint: true,
|
|
Run: func(ctx *cmdContext) (any, bool, error) {
|
|
email := ctx.Flags.Str("email")
|
|
if email == "" {
|
|
email = os.Getenv("COTIZADOR_EMAIL")
|
|
}
|
|
password := ctx.Flags.Str("password")
|
|
if password == "" {
|
|
password = os.Getenv("COTIZADOR_PASSWORD")
|
|
}
|
|
if ctx.Flags.Bool("passwordStdin") {
|
|
s, err := leerStdin(ctx.Stdin)
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
password = strings.TrimSpace(s)
|
|
}
|
|
if email == "" || password == "" {
|
|
return nil, false, errorUso(
|
|
"Faltan credenciales",
|
|
"Pasa --email y --password (o --password-stdin), o define COTIZADOR_EMAIL y COTIZADOR_PASSWORD",
|
|
)
|
|
}
|
|
usuario, err := ctx.Cliente.login(email, password)
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
return map[string]any{"ok": true, "url": ctx.Cliente.base, "usuario": usuario}, true, nil
|
|
},
|
|
},
|
|
{
|
|
Comando: "logout",
|
|
Descripcion: "Borra la sesion guardada para la URL actual.",
|
|
Run: func(ctx *cmdContext) (any, bool, error) {
|
|
habia, err := ctx.Cliente.cerrarSesion()
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
return map[string]any{"ok": true, "url": ctx.Cliente.base, "sesionBorrada": habia}, true, nil
|
|
},
|
|
},
|
|
{
|
|
Comando: "whoami",
|
|
Alias: []string{"yo"},
|
|
Descripcion: "Muestra el usuario de la sesion actual.",
|
|
Endpoint: "GET /api/auth/me",
|
|
HasEndpoint: true,
|
|
Run: func(ctx *cmdContext) (any, bool, error) {
|
|
raw, err := ctx.Cliente.api(http.MethodGet, "/api/auth/me")
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
m := asMap(raw)
|
|
return map[string]any{"url": ctx.Cliente.base, "usuario": m["user"]}, true, nil
|
|
},
|
|
},
|
|
|
|
// ----- servicios (catalogo) -----
|
|
{
|
|
Comando: "servicios listar",
|
|
Alias: []string{"servicios", "servicios ls"},
|
|
Descripcion: "Lista servicios del catalogo. Por defecto solo los activos.",
|
|
Flags: []flagSpec{
|
|
{Flag: "q", Tipo: "texto", Descripcion: "Busca en nombre y descripcion"},
|
|
{Flag: "fase", Tipo: "entero", Valores: []any{0, 1, 2, 3}, Descripcion: "Filtra por fase"},
|
|
{Flag: "tipo-pago", Tipo: "texto", Valores: []any{"unico", "mensual"}, Descripcion: "Filtra por tipo de pago"},
|
|
{Flag: "categoria", Tipo: "texto", Descripcion: "Id o nombre de categoria"},
|
|
{Flag: "archivados", Tipo: "booleano", Descripcion: "Solo los archivados"},
|
|
{Flag: "todos", Tipo: "booleano", Descripcion: "Activos y archivados"},
|
|
},
|
|
Ejemplos: []string{
|
|
"cotizador servicios listar --fase 1 --campos id,nombre,precioBase",
|
|
`cotizador servicios listar --q "landing" --formato tabla`,
|
|
},
|
|
Endpoint: "GET /api/catalogo",
|
|
HasEndpoint: true,
|
|
Run: func(ctx *cmdContext) (any, bool, error) {
|
|
p := url.Values{}
|
|
if q := ctx.Flags.Str("q"); q != "" {
|
|
p.Set("q", q)
|
|
}
|
|
if ctx.Flags.Has("fase") {
|
|
f, err := parseEntero(ctx.Flags.Str("fase"), "fase")
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
p.Set("fase", strconv.Itoa(f))
|
|
}
|
|
if ctx.Flags.Has("tipoPago") {
|
|
tp, err := unoDe(ctx.Flags.Str("tipoPago"), []string{"unico", "mensual"}, "tipo-pago")
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
p.Set("tipoPago", tp)
|
|
}
|
|
if ctx.Flags.Has("categoria") {
|
|
catID, err := resolverCategoria(ctx.Cliente, ctx.Flags.Str("categoria"))
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
if s, ok := catID.(string); ok && s != "" {
|
|
p.Set("categoriaId", s)
|
|
}
|
|
}
|
|
if ctx.Flags.Bool("archivados") {
|
|
p.Set("activo", "false")
|
|
} else if !ctx.Flags.Bool("todos") {
|
|
p.Set("activo", "true")
|
|
}
|
|
res, err := ctx.Cliente.api(http.MethodGet, "/api/catalogo?"+p.Encode())
|
|
return res, true, err
|
|
},
|
|
},
|
|
{
|
|
Comando: "servicios ver",
|
|
Descripcion: "Muestra un servicio del catalogo (por id o por nombre exacto).",
|
|
Argumentos: []argSpec{{Nombre: "id", Descripcion: "Id del servicio o su nombre"}},
|
|
Ejemplos: []string{"cotizador servicios ver cmabc123...", `cotizador servicios ver "Landing Page"`},
|
|
Endpoint: "GET /api/catalogo/{id}",
|
|
HasEndpoint: true,
|
|
Run: func(ctx *cmdContext) (any, bool, error) {
|
|
ref, err := exigirPosicional(ctx.Pos, 0, "id", "servicios ver")
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
res, err := resolverServicio(ctx.Cliente, ref)
|
|
return res, true, err
|
|
},
|
|
},
|
|
{
|
|
Comando: "servicios crear",
|
|
Alias: []string{"servicios nuevo"},
|
|
Descripcion: "Crea un servicio en el catalogo. Obligatorios: --nombre, --fase, --tipo-pago, --precio. Queda activo y al final de su fase.",
|
|
Flags: flagsServicio,
|
|
Ejemplos: []string{
|
|
`cotizador servicios crear --nombre "Auditoria SEO tecnica" --fase 0 --tipo-pago unico --precio 6500 --categoria SEO --entregable "Reporte PDF" --entregable "Sesion de 1 h"`,
|
|
`cotizador servicios crear --datos '{"nombre":"Gestion de Google Ads","fase":2,"tipoPago":"mensual","precioBase":5500}'`,
|
|
},
|
|
Endpoint: "POST /api/catalogo",
|
|
HasEndpoint: true,
|
|
Run: func(ctx *cmdContext) (any, bool, error) {
|
|
cuerpo, err := cuerpoServicio(ctx.Cliente, ctx.Flags, ctx.Stdin)
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
required := []struct{ key, flag string }{
|
|
{"nombre", "--nombre"},
|
|
{"fase", "--fase"},
|
|
{"tipoPago", "--tipo-pago"},
|
|
{"precioBase", "--precio"},
|
|
}
|
|
var faltan []string
|
|
for _, r := range required {
|
|
if _, ok := cuerpo[r.key]; !ok {
|
|
faltan = append(faltan, r.flag)
|
|
}
|
|
}
|
|
if len(faltan) > 0 {
|
|
return nil, false, errorUso(
|
|
"Faltan campos obligatorios: "+strings.Join(faltan, ", "),
|
|
`Ejemplo: cotizador servicios crear --nombre "Mi servicio" --fase 1 --tipo-pago unico --precio 5000`,
|
|
)
|
|
}
|
|
res, err := ctx.Cliente.api(http.MethodPost, "/api/catalogo", apiOpts{Cuerpo: cuerpo, HasCuerpo: true})
|
|
return res, true, err
|
|
},
|
|
},
|
|
{
|
|
Comando: "servicios editar",
|
|
Descripcion: "Edita un servicio: solo cambia los campos que pases. Las cotizaciones ya guardadas conservan su precio y entregables.",
|
|
Argumentos: []argSpec{{Nombre: "id", Descripcion: "Id del servicio o su nombre exacto"}},
|
|
Flags: append(append([]flagSpec{}, flagsServicio...),
|
|
flagSpec{Flag: "agregar-entregable", Tipo: "texto", Repetible: true, Descripcion: "Agrega un entregable a la lista actual (sin reemplazarla)"},
|
|
flagSpec{Flag: "quitar-entregable", Tipo: "texto", Repetible: true, Descripcion: "Quita un entregable de la lista actual (texto exacto)"},
|
|
),
|
|
Ejemplos: []string{
|
|
"cotizador servicios editar cmabc123... --precio 7200",
|
|
`cotizador servicios editar "Landing Page" --agregar-entregable "Formulario conectado a Bucefalo CRM"`,
|
|
},
|
|
Endpoint: "PATCH /api/catalogo/{id}",
|
|
HasEndpoint: true,
|
|
Run: func(ctx *cmdContext) (any, bool, error) {
|
|
ref, err := exigirPosicional(ctx.Pos, 0, "id", "servicios editar")
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
actual, err := resolverServicio(ctx.Cliente, ref)
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
cuerpo, err := cuerpoServicio(ctx.Cliente, ctx.Flags, ctx.Stdin)
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
if ctx.Flags.Has("agregarEntregable") || ctx.Flags.Has("quitarEntregable") {
|
|
var lista []string
|
|
if rawList, ok := cuerpo["entregablesDefault"]; ok {
|
|
switch x := rawList.(type) {
|
|
case []string:
|
|
lista = append(lista, x...)
|
|
case []any:
|
|
for _, item := range x {
|
|
lista = append(lista, fmt.Sprint(item))
|
|
}
|
|
}
|
|
} else {
|
|
for _, item := range asSlice(actual["entregablesDefault"]) {
|
|
lista = append(lista, fmt.Sprint(item))
|
|
}
|
|
}
|
|
if quitar := ctx.Flags.List("quitarEntregable"); len(quitar) > 0 {
|
|
var faltantes []string
|
|
for _, q := range quitar {
|
|
if !slices.Contains(lista, q) {
|
|
faltantes = append(faltantes, q)
|
|
}
|
|
}
|
|
if len(faltantes) > 0 {
|
|
actualStr := strings.Join(lista, "; ")
|
|
if actualStr == "" {
|
|
actualStr = "(ninguno)"
|
|
}
|
|
return nil, false, errorUso(
|
|
"No encontre estos entregables: "+strings.Join(faltantes, "; "),
|
|
"Entregables actuales: "+actualStr,
|
|
)
|
|
}
|
|
var nueva []string
|
|
for _, e := range lista {
|
|
if !slices.Contains(quitar, e) {
|
|
nueva = append(nueva, e)
|
|
}
|
|
}
|
|
lista = nueva
|
|
}
|
|
if agregar := ctx.Flags.List("agregarEntregable"); len(agregar) > 0 {
|
|
lista = append(lista, agregar...)
|
|
}
|
|
if lista == nil {
|
|
lista = []string{}
|
|
}
|
|
cuerpo["entregablesDefault"] = lista
|
|
}
|
|
if len(cuerpo) == 0 {
|
|
return nil, false, errorUso("No pasaste ningun campo para cambiar", "Ejemplo: cotizador servicios editar <id> --precio 5000")
|
|
}
|
|
res, err := ctx.Cliente.api(http.MethodPatch, "/api/catalogo/"+mapStr(actual, "id"), apiOpts{Cuerpo: cuerpo, HasCuerpo: true})
|
|
return res, true, err
|
|
},
|
|
},
|
|
{
|
|
Comando: "servicios archivar",
|
|
Descripcion: "Oculta un servicio al cotizar (activo=false). Reversible con `servicios activar`.",
|
|
Argumentos: []argSpec{{Nombre: "id", Descripcion: "Id del servicio o su nombre exacto"}},
|
|
Endpoint: "PATCH /api/catalogo/{id}",
|
|
HasEndpoint: true,
|
|
Run: func(ctx *cmdContext) (any, bool, error) {
|
|
ref, err := exigirPosicional(ctx.Pos, 0, "id", "servicios archivar")
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
s, err := resolverServicio(ctx.Cliente, ref)
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
res, err := ctx.Cliente.api(http.MethodPatch, "/api/catalogo/"+mapStr(s, "id"), apiOpts{
|
|
Cuerpo: map[string]any{"activo": false},
|
|
HasCuerpo: true,
|
|
})
|
|
return res, true, err
|
|
},
|
|
},
|
|
{
|
|
Comando: "servicios activar",
|
|
Descripcion: "Vuelve a mostrar un servicio archivado.",
|
|
Argumentos: []argSpec{{Nombre: "id", Descripcion: "Id del servicio"}},
|
|
Endpoint: "PATCH /api/catalogo/{id}",
|
|
HasEndpoint: true,
|
|
Run: func(ctx *cmdContext) (any, bool, error) {
|
|
id, err := exigirPosicional(ctx.Pos, 0, "id", "servicios activar")
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
res, err := ctx.Cliente.api(http.MethodPatch, "/api/catalogo/"+url.PathEscape(id), apiOpts{
|
|
Cuerpo: map[string]any{"activo": true},
|
|
HasCuerpo: true,
|
|
})
|
|
return res, true, err
|
|
},
|
|
},
|
|
{
|
|
Comando: "servicios eliminar",
|
|
Descripcion: "Borra un servicio. Si alguna cotizacion lo usa, el servidor lo ARCHIVA en vez de borrarlo (respuesta archived=true).",
|
|
Argumentos: []argSpec{{Nombre: "id", Descripcion: "Id del servicio"}},
|
|
Flags: []flagSpec{flagConfirmar},
|
|
Ejemplos: []string{"cotizador servicios eliminar cmabc123... --confirmar"},
|
|
Endpoint: "DELETE /api/catalogo/{id}",
|
|
HasEndpoint: true,
|
|
Run: func(ctx *cmdContext) (any, bool, error) {
|
|
id, err := exigirPosicional(ctx.Pos, 0, "id", "servicios eliminar")
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
if err := exigirConfirmacion(ctx.Flags, "Eliminar un servicio"); err != nil {
|
|
return nil, false, err
|
|
}
|
|
res, err := ctx.Cliente.api(http.MethodDelete, "/api/catalogo/"+url.PathEscape(id))
|
|
return res, true, err
|
|
},
|
|
},
|
|
|
|
// ----- categorias y paquetes -----
|
|
{
|
|
Comando: "categorias listar",
|
|
Alias: []string{"categorias"},
|
|
Descripcion: "Lista las categorias del catalogo.",
|
|
Endpoint: "GET /api/categorias",
|
|
HasEndpoint: true,
|
|
Run: func(ctx *cmdContext) (any, bool, error) {
|
|
res, err := ctx.Cliente.api(http.MethodGet, "/api/categorias")
|
|
return res, true, err
|
|
},
|
|
},
|
|
{
|
|
Comando: "categorias crear",
|
|
Descripcion: "Crea una categoria.",
|
|
Flags: []flagSpec{
|
|
{Flag: "nombre", Tipo: "texto", Descripcion: "Nombre (unico)"},
|
|
{Flag: "color", Tipo: "texto", Descripcion: "Color hex, ej. #2563eb"},
|
|
{Flag: "descripcion", Tipo: "texto", Descripcion: "Descripcion"},
|
|
},
|
|
Ejemplos: []string{`cotizador categorias crear --nombre "Automatizacion" --color "#0ea5e9"`},
|
|
Endpoint: "POST /api/categorias",
|
|
HasEndpoint: true,
|
|
Run: func(ctx *cmdContext) (any, bool, error) {
|
|
if ctx.Flags.Str("nombre") == "" {
|
|
return nil, false, errorUso("Falta --nombre")
|
|
}
|
|
cuerpo := map[string]any{"nombre": ctx.Flags.Str("nombre")}
|
|
if ctx.Flags.Has("color") && ctx.Flags.Str("color") != "" {
|
|
if !colorHexRe.MatchString(ctx.Flags.Str("color")) {
|
|
return nil, false, errorUso("--color debe ser hex de 6 digitos, ej. #2563eb")
|
|
}
|
|
cuerpo["color"] = ctx.Flags.Str("color")
|
|
}
|
|
if ctx.Flags.Has("descripcion") {
|
|
cuerpo["descripcion"] = ctx.Flags.Str("descripcion")
|
|
}
|
|
res, err := ctx.Cliente.api(http.MethodPost, "/api/categorias", apiOpts{Cuerpo: cuerpo, HasCuerpo: true})
|
|
return res, true, err
|
|
},
|
|
},
|
|
{
|
|
Comando: "paquetes listar",
|
|
Alias: []string{"paquetes"},
|
|
Descripcion: "Lista los paquetes activos con sus fases y servicios (resumido; usa `paquetes ver` para el detalle).",
|
|
Endpoint: "GET /api/paquetes",
|
|
HasEndpoint: true,
|
|
Run: func(ctx *cmdContext) (any, bool, error) {
|
|
raw, err := ctx.Cliente.api(http.MethodGet, "/api/paquetes")
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
paquetes := asSlice(raw)
|
|
out := make([]map[string]any, 0, len(paquetes))
|
|
for _, item := range paquetes {
|
|
p := asMap(item)
|
|
rawFases := asSlice(p["fases"])
|
|
fases := make([]map[string]any, 0, len(rawFases))
|
|
for _, fItem := range rawFases {
|
|
f := asMap(fItem)
|
|
rawServs := asSlice(f["servicios"])
|
|
servs := make([]map[string]any, 0, len(rawServs))
|
|
for _, spItem := range rawServs {
|
|
sp := asMap(spItem)
|
|
sv := asMap(sp["servicio"])
|
|
servs = append(servs, map[string]any{
|
|
"id": sv["id"],
|
|
"nombre": sv["nombre"],
|
|
"precioBase": sv["precioBase"],
|
|
"tipoPago": sv["tipoPago"],
|
|
})
|
|
}
|
|
fases = append(fases, map[string]any{
|
|
"nombre": f["nombre"],
|
|
"servicios": servs,
|
|
})
|
|
}
|
|
out = append(out, map[string]any{
|
|
"id": p["id"],
|
|
"nombre": p["nombre"],
|
|
"descripcion": p["descripcion"],
|
|
"fases": fases,
|
|
})
|
|
}
|
|
return out, true, nil
|
|
},
|
|
},
|
|
{
|
|
Comando: "paquetes ver",
|
|
Descripcion: "Detalle completo de un paquete.",
|
|
Argumentos: []argSpec{{Nombre: "id", Descripcion: "Id del paquete"}},
|
|
Endpoint: "GET /api/paquetes/{id}",
|
|
HasEndpoint: true,
|
|
Run: func(ctx *cmdContext) (any, bool, error) {
|
|
id, err := exigirPosicional(ctx.Pos, 0, "id", "paquetes ver")
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
res, err := ctx.Cliente.api(http.MethodGet, "/api/paquetes/"+url.PathEscape(id))
|
|
return res, true, err
|
|
},
|
|
},
|
|
|
|
// ----- clientes -----
|
|
{
|
|
Comando: "clientes listar",
|
|
Alias: []string{"clientes"},
|
|
Descripcion: "Lista clientes.",
|
|
Flags: []flagSpec{{Flag: "q", Tipo: "texto", Descripcion: "Busca en nombre, empresa, correo y RFC"}},
|
|
Endpoint: "GET /api/clientes",
|
|
HasEndpoint: true,
|
|
Run: func(ctx *cmdContext) (any, bool, error) {
|
|
ruta := "/api/clientes"
|
|
if q := ctx.Flags.Str("q"); q != "" {
|
|
ruta += "?q=" + url.QueryEscape(q)
|
|
}
|
|
res, err := ctx.Cliente.api(http.MethodGet, ruta)
|
|
return res, true, err
|
|
},
|
|
},
|
|
{
|
|
Comando: "clientes crear",
|
|
Descripcion: "Da de alta un cliente (nombre + empresa deben ser unicos).",
|
|
Flags: []flagSpec{
|
|
{Flag: "nombre", Tipo: "texto", Descripcion: "Nombre del contacto (obligatorio)"},
|
|
{Flag: "empresa", Tipo: "texto", Descripcion: "Empresa"},
|
|
{Flag: "puesto", Tipo: "texto", Descripcion: "Puesto"},
|
|
{Flag: "email", Tipo: "texto", Descripcion: "Correo"},
|
|
{Flag: "telefono", Tipo: "texto", Descripcion: "Telefono"},
|
|
{Flag: "rfc", Tipo: "texto", Descripcion: "RFC"},
|
|
},
|
|
Ejemplos: []string{`cotizador clientes crear --nombre "Ana Ruiz" --empresa "Panaderia Sol" --email [email protected]`},
|
|
Endpoint: "POST /api/clientes",
|
|
HasEndpoint: true,
|
|
Run: func(ctx *cmdContext) (any, bool, error) {
|
|
if ctx.Flags.Str("nombre") == "" {
|
|
return nil, false, errorUso("Falta --nombre")
|
|
}
|
|
cuerpo := map[string]any{"nombre": ctx.Flags.Str("nombre")}
|
|
for _, k := range []string{"empresa", "puesto", "email", "telefono", "rfc"} {
|
|
if ctx.Flags.Has(k) {
|
|
cuerpo[k] = ctx.Flags.Str(k)
|
|
}
|
|
}
|
|
res, err := ctx.Cliente.api(http.MethodPost, "/api/clientes", apiOpts{Cuerpo: cuerpo, HasCuerpo: true})
|
|
return res, true, err
|
|
},
|
|
},
|
|
{
|
|
Comando: "clientes editar",
|
|
Descripcion: "Edita un cliente (solo los campos que pases).",
|
|
Argumentos: []argSpec{{Nombre: "id", Descripcion: "Id del cliente"}},
|
|
Flags: []flagSpec{
|
|
{Flag: "nombre", Tipo: "texto", Descripcion: "Nombre"},
|
|
{Flag: "empresa", Tipo: "texto", Descripcion: `Empresa ("" para quitarla)`},
|
|
{Flag: "puesto", Tipo: "texto", Descripcion: "Puesto"},
|
|
{Flag: "email", Tipo: "texto", Descripcion: "Correo"},
|
|
{Flag: "telefono", Tipo: "texto", Descripcion: "Telefono"},
|
|
{Flag: "rfc", Tipo: "texto", Descripcion: "RFC"},
|
|
},
|
|
Endpoint: "PATCH /api/clientes/{id}",
|
|
HasEndpoint: true,
|
|
Run: func(ctx *cmdContext) (any, bool, error) {
|
|
id, err := exigirPosicional(ctx.Pos, 0, "id", "clientes editar")
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
cuerpo := map[string]any{}
|
|
for _, k := range []string{"nombre", "empresa", "puesto", "email", "telefono", "rfc"} {
|
|
if ctx.Flags.Has(k) {
|
|
cuerpo[k] = ctx.Flags.Str(k)
|
|
}
|
|
}
|
|
if len(cuerpo) == 0 {
|
|
return nil, false, errorUso("No pasaste ningun campo para cambiar")
|
|
}
|
|
res, err := ctx.Cliente.api(http.MethodPatch, "/api/clientes/"+url.PathEscape(id), apiOpts{Cuerpo: cuerpo, HasCuerpo: true})
|
|
return res, true, err
|
|
},
|
|
},
|
|
|
|
// ----- cotizaciones -----
|
|
{
|
|
Comando: "cotizaciones listar",
|
|
Alias: []string{"cotizaciones", "cotizaciones ls"},
|
|
Descripcion: "Lista cotizaciones resumidas, de la mas reciente a la mas antigua.",
|
|
Flags: []flagSpec{
|
|
{Flag: "estado", Tipo: "texto", Valores: toAnySlice(estadosCotizacion), Descripcion: "Filtra por estado"},
|
|
{Flag: "q", Tipo: "texto", Descripcion: "Busca en numero, proyecto, cliente y empresa"},
|
|
{Flag: "cliente", Tipo: "texto", Descripcion: "Id del cliente"},
|
|
{Flag: "limit", Tipo: "entero", Descripcion: "Maximo de resultados (default 50)"},
|
|
{Flag: "completo", Tipo: "booleano", Descripcion: "Devuelve el registro completo (con partidas) en vez del resumen"},
|
|
},
|
|
Ejemplos: []string{"cotizador cotizaciones listar --estado enviada --formato tabla"},
|
|
Endpoint: "GET /api/cotizaciones",
|
|
HasEndpoint: true,
|
|
Run: func(ctx *cmdContext) (any, bool, error) {
|
|
p := url.Values{}
|
|
if ctx.Flags.Has("estado") {
|
|
e, err := unoDe(ctx.Flags.Str("estado"), estadosCotizacion, "estado")
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
p.Set("estado", e)
|
|
}
|
|
if q := ctx.Flags.Str("q"); q != "" {
|
|
p.Set("q", q)
|
|
}
|
|
if cl := ctx.Flags.Str("cliente"); cl != "" {
|
|
p.Set("clienteId", cl)
|
|
}
|
|
limit := 50
|
|
if ctx.Flags.Has("limit") {
|
|
var err error
|
|
limit, err = parseEntero(ctx.Flags.Str("limit"), "limit")
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
}
|
|
p.Set("limit", strconv.Itoa(limit))
|
|
raw, err := ctx.Cliente.api(http.MethodGet, "/api/cotizaciones?"+p.Encode())
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
if ctx.Flags.Bool("completo") {
|
|
return raw, true, nil
|
|
}
|
|
lista := asSlice(raw)
|
|
out := make([]map[string]any, 0, len(lista))
|
|
for _, item := range lista {
|
|
out = append(out, resumenCotizacion(asMap(item)))
|
|
}
|
|
return out, true, nil
|
|
},
|
|
},
|
|
{
|
|
Comando: "cotizaciones ver",
|
|
Descripcion: "Detalle completo de una cotizacion (por id o por numero, ej. UJ2605AG001).",
|
|
Argumentos: []argSpec{{Nombre: "id", Descripcion: "Id o numero de la cotizacion"}},
|
|
Endpoint: "GET /api/cotizaciones/{id}",
|
|
HasEndpoint: true,
|
|
Run: func(ctx *cmdContext) (any, bool, error) {
|
|
ref, err := exigirPosicional(ctx.Pos, 0, "id", "cotizaciones ver")
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
id, err := resolverCotizacion(ctx.Cliente, ref)
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
res, err := ctx.Cliente.api(http.MethodGet, "/api/cotizaciones/"+id)
|
|
return res, true, err
|
|
},
|
|
},
|
|
{
|
|
Comando: "cotizaciones crear",
|
|
Alias: []string{"cotizaciones nueva"},
|
|
Descripcion: "Crea una cotizacion en borrador. El servidor asigna numero, asesor (tu usuario), fecha y vigencia (15 dias habiles). Si el cliente (nombre+empresa) no existe, se crea.",
|
|
Flags: []flagSpec{
|
|
{Flag: "cliente", Tipo: "texto", Descripcion: "Nombre del cliente (obligatorio)"},
|
|
{Flag: "empresa", Tipo: "texto", Descripcion: "Empresa del cliente"},
|
|
{Flag: "email", Tipo: "texto", Descripcion: "Correo del cliente"},
|
|
{Flag: "telefono", Tipo: "texto", Descripcion: "Telefono del cliente"},
|
|
{Flag: "servicio", Tipo: "texto", Repetible: true, Descripcion: `Servicio del catalogo: "id", "nombre exacto" o "id=precio" para ajustar el precio. Repetible`},
|
|
{Flag: "partida-horas", Tipo: "texto", Repetible: true, Descripcion: `Partida por horas: "Concepto|horas|tarifa" (tarifa opcional). Repetible`},
|
|
{Flag: "proyecto", Tipo: "texto", Descripcion: `Nombre del proyecto (default "MKT Digital")`},
|
|
{Flag: "moneda", Tipo: "texto", Valores: toAnySlice(monedasValidas), Descripcion: "MXN (default) o USD"},
|
|
{Flag: "esquema-pago", Tipo: "texto", Valores: toAnySlice(esquemasPago), Descripcion: `Default "Pago Unico/Mensual"`},
|
|
{Flag: "bucefalo", Tipo: "texto", Valores: toAnySlice(planesBucefaloCRM), Descripcion: "Agrega un plan de Bucefalo CRM (precio de lista)"},
|
|
{Flag: "observaciones", Tipo: "texto", Descripcion: "Observaciones visibles para el cliente"},
|
|
{Flag: "notas-internas", Tipo: "texto", Descripcion: "Observaciones internas (no salen en el PDF)"},
|
|
{Flag: "sin-iva", Tipo: "booleano", Descripcion: "No sumar IVA"},
|
|
{Flag: "bonos", Tipo: "booleano", Descripcion: "Incluir bonos"},
|
|
{Flag: "financiamiento", Tipo: "booleano", Descripcion: "Incluir financiamiento"},
|
|
{Flag: "fecha", Tipo: "fecha", Descripcion: "YYYY-MM-DD (default hoy)"},
|
|
{Flag: "asesor", Tipo: "texto", Descripcion: "Id del asesor (default: el usuario de la sesion)"},
|
|
{Flag: "datos", Tipo: "json", Descripcion: "Cuerpo JSON completo de POST /api/cotizaciones (ver `cotizador esquema`). Las flags tienen prioridad"},
|
|
},
|
|
Ejemplos: []string{
|
|
`cotizador cotizaciones crear --cliente "Ana Ruiz" --empresa "Panaderia Sol" --servicio "Landing Page" --servicio cmabc123...=4500 --bucefalo estandar`,
|
|
`cotizador cotizaciones crear --cliente "Ana Ruiz" --partida-horas "Soporte tecnico|10|700"`,
|
|
},
|
|
Endpoint: "POST /api/cotizaciones",
|
|
HasEndpoint: true,
|
|
Run: func(ctx *cmdContext) (any, bool, error) {
|
|
base, err := leerDatos(ctx.Flags.Str("datos"), ctx.Flags.Has("datos"), ctx.Stdin)
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
partidas := make([]any, 0)
|
|
if arr, ok := base["servicios"].([]any); ok {
|
|
partidas = append(partidas, arr...)
|
|
}
|
|
for _, ref := range ctx.Flags.List("servicio") {
|
|
nombreOId := ref
|
|
var precio *float64
|
|
if m := servicioRefRe.FindStringSubmatch(ref); len(m) == 3 {
|
|
nombreOId = m[1]
|
|
p, err := parseNumero(m[2], "servicio")
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
precio = &p
|
|
}
|
|
s, err := resolverServicio(ctx.Cliente, nombreOId)
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
partidas = append(partidas, partidaDesdeCatalogo(s, precio))
|
|
}
|
|
for _, txt := range ctx.Flags.List("partidaHoras") {
|
|
p, err := partidaPorHoras(txt)
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
partidas = append(partidas, p)
|
|
}
|
|
|
|
clienteBase := asMap(base["cliente"])
|
|
datosCliente := make(map[string]any)
|
|
for k, v := range clienteBase {
|
|
datosCliente[k] = v
|
|
}
|
|
if ctx.Flags.Has("cliente") {
|
|
datosCliente["nombre"] = ctx.Flags.Str("cliente")
|
|
}
|
|
if ctx.Flags.Has("empresa") {
|
|
datosCliente["empresa"] = ctx.Flags.Str("empresa")
|
|
}
|
|
if ctx.Flags.Has("email") {
|
|
datosCliente["email"] = ctx.Flags.Str("email")
|
|
}
|
|
if ctx.Flags.Has("telefono") {
|
|
datosCliente["telefono"] = ctx.Flags.Str("telefono")
|
|
}
|
|
if mapStr(datosCliente, "nombre") == "" {
|
|
return nil, false, errorUso("Falta --cliente", `Ejemplo: cotizador cotizaciones crear --cliente "Ana Ruiz" --servicio "Landing Page"`)
|
|
}
|
|
if len(partidas) == 0 && !ctx.Flags.Has("bucefalo") && base["planBucefalo"] == nil {
|
|
return nil, false, errorUso(
|
|
"La cotizacion no tiene partidas",
|
|
"Agrega --servicio <id|nombre> (busca con `cotizador servicios listar`), --partida-horas o --bucefalo",
|
|
)
|
|
}
|
|
|
|
cuerpo := make(map[string]any, len(base)+12)
|
|
for k, v := range base {
|
|
cuerpo[k] = v
|
|
}
|
|
if ctx.Flags.Has("proyecto") {
|
|
cuerpo["proyecto"] = ctx.Flags.Str("proyecto")
|
|
}
|
|
if ctx.Flags.Has("moneda") {
|
|
m, err := unoDe(ctx.Flags.Str("moneda"), monedasValidas, "moneda")
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
cuerpo["moneda"] = m
|
|
}
|
|
if ctx.Flags.Has("esquemaPago") {
|
|
ep, err := unoDe(ctx.Flags.Str("esquemaPago"), esquemasPago, "esquema-pago")
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
cuerpo["esquemaPago"] = ep
|
|
}
|
|
if ctx.Flags.Has("observaciones") {
|
|
cuerpo["observaciones"] = ctx.Flags.Str("observaciones")
|
|
}
|
|
if ctx.Flags.Has("notasInternas") {
|
|
cuerpo["observacionesInternas"] = ctx.Flags.Str("notasInternas")
|
|
}
|
|
if ctx.Flags.Bool("sinIva") {
|
|
cuerpo["incluirIva"] = false
|
|
}
|
|
if ctx.Flags.Has("bonos") {
|
|
cuerpo["incluirBonos"] = ctx.Flags.Bool("bonos")
|
|
}
|
|
if ctx.Flags.Has("financiamiento") {
|
|
cuerpo["incluirFinanciamiento"] = ctx.Flags.Bool("financiamiento")
|
|
}
|
|
if ctx.Flags.Has("fecha") {
|
|
f, err := validarFechaISO(ctx.Flags.Str("fecha"), "fecha")
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
cuerpo["fecha"] = f
|
|
}
|
|
if ctx.Flags.Has("asesor") {
|
|
cuerpo["asesorId"] = ctx.Flags.Str("asesor")
|
|
}
|
|
if ctx.Flags.Has("bucefalo") {
|
|
niv, err := unoDe(ctx.Flags.Str("bucefalo"), planesBucefaloCRM, "bucefalo")
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
cuerpo["planBucefalo"] = map[string]any{"nivel": niv}
|
|
}
|
|
cuerpo["cliente"] = datosCliente
|
|
cuerpo["servicios"] = partidas
|
|
|
|
raw, err := ctx.Cliente.api(http.MethodPost, "/api/cotizaciones", apiOpts{Cuerpo: cuerpo, HasCuerpo: true})
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
creada := asMap(raw)
|
|
return map[string]any{
|
|
"ok": true,
|
|
"id": creada["id"],
|
|
"numero": creada["numero"],
|
|
"estado": creada["estado"],
|
|
"url": fmt.Sprintf("%s/cotizaciones/%s", ctx.Cliente.base, mapStr(creada, "id")),
|
|
}, true, nil
|
|
},
|
|
},
|
|
{
|
|
Comando: "cotizaciones estado",
|
|
Descripcion: "Cambia el estado de una cotizacion.",
|
|
Argumentos: []argSpec{
|
|
{Nombre: "id", Descripcion: "Id o numero de la cotizacion"},
|
|
{Nombre: "estado", Descripcion: strings.Join(estadosCotizacion, " | ")},
|
|
},
|
|
Ejemplos: []string{"cotizador cotizaciones estado UJ2605AG001 enviada"},
|
|
Endpoint: "PUT /api/cotizaciones/{id}",
|
|
HasEndpoint: true,
|
|
Run: func(ctx *cmdContext) (any, bool, error) {
|
|
ref, err := exigirPosicional(ctx.Pos, 0, "id", "cotizaciones estado")
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
rawEstado, err := exigirPosicional(ctx.Pos, 1, "estado", "cotizaciones estado <id>")
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
estado, err := unoDe(rawEstado, estadosCotizacion, "estado")
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
id, err := resolverCotizacion(ctx.Cliente, ref)
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
raw, err := ctx.Cliente.api(http.MethodPut, "/api/cotizaciones/"+id, apiOpts{
|
|
Cuerpo: map[string]any{"estado": estado},
|
|
HasCuerpo: true,
|
|
})
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
r := asMap(raw)
|
|
return map[string]any{"ok": true, "id": r["id"], "numero": r["numero"], "estado": r["estado"]}, true, nil
|
|
},
|
|
},
|
|
{
|
|
Comando: "cotizaciones pdf",
|
|
Descripcion: "Descarga el PDF de una cotizacion.",
|
|
Argumentos: []argSpec{{Nombre: "id", Descripcion: "Id o numero de la cotizacion"}},
|
|
Flags: []flagSpec{{Flag: "salida", Tipo: "texto", Descripcion: "Ruta del archivo (default: nombre que da el servidor, en la carpeta actual)"}},
|
|
Endpoint: "GET /api/export/pdf/{id}",
|
|
HasEndpoint: true,
|
|
Run: func(ctx *cmdContext) (any, bool, error) {
|
|
ref, err := exigirPosicional(ctx.Pos, 0, "id", "cotizaciones pdf")
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
id, err := resolverCotizacion(ctx.Cliente, ref)
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
res, err := descargar(ctx.Cliente, "/api/export/pdf/"+id, ctx.Flags.Str("salida"), fmt.Sprintf("cotizacion-%s.pdf", id))
|
|
return res, true, err
|
|
},
|
|
},
|
|
{
|
|
Comando: "cotizaciones excel",
|
|
Descripcion: "Descarga el Excel de una cotizacion.",
|
|
Argumentos: []argSpec{{Nombre: "id", Descripcion: "Id o numero de la cotizacion"}},
|
|
Flags: []flagSpec{{Flag: "salida", Tipo: "texto", Descripcion: "Ruta del archivo"}},
|
|
Endpoint: "GET /api/export/excel/{id}",
|
|
HasEndpoint: true,
|
|
Run: func(ctx *cmdContext) (any, bool, error) {
|
|
ref, err := exigirPosicional(ctx.Pos, 0, "id", "cotizaciones excel")
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
id, err := resolverCotizacion(ctx.Cliente, ref)
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
res, err := descargar(ctx.Cliente, "/api/export/excel/"+id, ctx.Flags.Str("salida"), fmt.Sprintf("cotizacion-%s.xlsx", id))
|
|
return res, true, err
|
|
},
|
|
},
|
|
{
|
|
Comando: "cotizaciones eliminar",
|
|
Descripcion: "Borra una cotizacion y sus partidas.",
|
|
Argumentos: []argSpec{{Nombre: "id", Descripcion: "Id o numero de la cotizacion"}},
|
|
Flags: []flagSpec{flagConfirmar},
|
|
Endpoint: "DELETE /api/cotizaciones/{id}",
|
|
HasEndpoint: true,
|
|
Run: func(ctx *cmdContext) (any, bool, error) {
|
|
ref, err := exigirPosicional(ctx.Pos, 0, "id", "cotizaciones eliminar")
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
if err := exigirConfirmacion(ctx.Flags, "Eliminar una cotizacion"); err != nil {
|
|
return nil, false, err
|
|
}
|
|
id, err := resolverCotizacion(ctx.Cliente, ref)
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
res, err := ctx.Cliente.api(http.MethodDelete, "/api/cotizaciones/"+id)
|
|
return res, true, err
|
|
},
|
|
},
|
|
|
|
// ----- horas -----
|
|
{
|
|
Comando: "horas listar",
|
|
Descripcion: "Registros de horas de una cotizacion por tiempo.",
|
|
Argumentos: []argSpec{{Nombre: "cotizacion", Descripcion: "Id o numero de la cotizacion"}},
|
|
Flags: []flagSpec{
|
|
{Flag: "desde", Tipo: "fecha", Descripcion: "YYYY-MM-DD"},
|
|
{Flag: "hasta", Tipo: "fecha", Descripcion: "YYYY-MM-DD"},
|
|
},
|
|
Endpoint: "GET /api/cotizaciones/{id}/horas",
|
|
HasEndpoint: true,
|
|
Run: func(ctx *cmdContext) (any, bool, error) {
|
|
ref, err := exigirPosicional(ctx.Pos, 0, "cotizacion", "horas listar")
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
id, err := resolverCotizacion(ctx.Cliente, ref)
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
p := url.Values{}
|
|
if ctx.Flags.Has("desde") {
|
|
d, err := validarFechaISO(ctx.Flags.Str("desde"), "desde")
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
p.Set("from", d)
|
|
}
|
|
if ctx.Flags.Has("hasta") {
|
|
h, err := validarFechaISO(ctx.Flags.Str("hasta"), "hasta")
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
p.Set("to", h)
|
|
}
|
|
qs := p.Encode()
|
|
ruta := "/api/cotizaciones/" + id + "/horas"
|
|
if qs != "" {
|
|
ruta += "?" + qs
|
|
}
|
|
res, err := ctx.Cliente.api(http.MethodGet, ruta)
|
|
return res, true, err
|
|
},
|
|
},
|
|
{
|
|
Comando: "horas registrar",
|
|
Descripcion: "Registra horas trabajadas (solo en cotizaciones con partidas por horas, retainer o demanda).",
|
|
Argumentos: []argSpec{{Nombre: "cotizacion", Descripcion: "Id o numero de la cotizacion"}},
|
|
Flags: []flagSpec{
|
|
{Flag: "fecha", Tipo: "fecha", Descripcion: "YYYY-MM-DD (obligatoria)"},
|
|
{Flag: "inicio", Tipo: "texto", Descripcion: "HH:MM (obligatoria)"},
|
|
{Flag: "fin", Tipo: "texto", Descripcion: "HH:MM (obligatoria)"},
|
|
{Flag: "descripcion", Tipo: "texto", Descripcion: "Que se hizo (obligatoria)"},
|
|
{Flag: "tarifa", Tipo: "numero", Descripcion: "Tarifa por hora (default: la de la cotizacion)"},
|
|
},
|
|
Ejemplos: []string{`cotizador horas registrar UJ2605AG001 --fecha 2026-11-20 --inicio 09:00 --fin 11:30 --descripcion "Ajustes de campanas"`},
|
|
Endpoint: "POST /api/cotizaciones/{id}/horas",
|
|
HasEndpoint: true,
|
|
Run: func(ctx *cmdContext) (any, bool, error) {
|
|
ref, err := exigirPosicional(ctx.Pos, 0, "cotizacion", "horas registrar")
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
id, err := resolverCotizacion(ctx.Cliente, ref)
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
var faltan []string
|
|
for _, k := range []string{"fecha", "inicio", "fin", "descripcion"} {
|
|
if ctx.Flags.Str(k) == "" {
|
|
faltan = append(faltan, "--"+k)
|
|
}
|
|
}
|
|
if len(faltan) > 0 {
|
|
return nil, false, errorUso("Faltan: " + strings.Join(faltan, ", "))
|
|
}
|
|
fecha, err := validarFechaISO(ctx.Flags.Str("fecha"), "fecha")
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
cuerpo := map[string]any{
|
|
"fecha": fecha,
|
|
"horaInicio": ctx.Flags.Str("inicio"),
|
|
"horaFin": ctx.Flags.Str("fin"),
|
|
"descripcion": ctx.Flags.Str("descripcion"),
|
|
}
|
|
if ctx.Flags.Has("tarifa") {
|
|
t, err := parseNumero(ctx.Flags.Str("tarifa"), "tarifa")
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
cuerpo["tarifaHora"] = t
|
|
}
|
|
res, err := ctx.Cliente.api(http.MethodPost, "/api/cotizaciones/"+id+"/horas", apiOpts{Cuerpo: cuerpo, HasCuerpo: true})
|
|
return res, true, err
|
|
},
|
|
},
|
|
|
|
// ----- utilidades -----
|
|
{
|
|
Comando: "api",
|
|
Descripcion: "Llamada directa a cualquier endpoint de la API (escape para lo que no cubren los comandos). La ruta empieza con /api/.",
|
|
Argumentos: []argSpec{
|
|
{Nombre: "metodo", Descripcion: "GET | POST | PUT | PATCH | DELETE"},
|
|
{Nombre: "ruta", Descripcion: "Ej. /api/configuracion"},
|
|
},
|
|
Flags: []flagSpec{{Flag: "datos", Tipo: "json", Descripcion: "Cuerpo JSON (en linea, @archivo.json o -)"}},
|
|
Ejemplos: []string{"cotizador api GET /api/configuracion", `cotizador api POST /api/cobros/recordatorios --datos '{}'`},
|
|
Endpoint: "*",
|
|
HasEndpoint: true,
|
|
Run: func(ctx *cmdContext) (any, bool, error) {
|
|
rawMetodo, err := exigirPosicional(ctx.Pos, 0, "metodo", "api")
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
metodo, err := unoDe(strings.ToUpper(rawMetodo), []string{"GET", "POST", "PUT", "PATCH", "DELETE"}, "metodo")
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
rawRuta, err := exigirPosicional(ctx.Pos, 1, "ruta", "api <metodo>")
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
ruta := strings.ReplaceAll(rawRuta, `\`, "/")
|
|
if corte := strings.Index(ruta, "/api/"); corte > 0 {
|
|
ruta = ruta[corte:]
|
|
}
|
|
if strings.HasPrefix(ruta, "api/") {
|
|
ruta = "/" + ruta
|
|
}
|
|
if !strings.HasPrefix(ruta, "/api/") {
|
|
return nil, false, errorUso("La ruta debe empezar con /api/ (ej. /api/configuracion)")
|
|
}
|
|
var opts apiOpts
|
|
if ctx.Flags.Has("datos") {
|
|
cuerpo, err := leerDatos(ctx.Flags.Str("datos"), true, ctx.Stdin)
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
opts.Cuerpo = cuerpo
|
|
opts.HasCuerpo = true
|
|
}
|
|
res, err := ctx.Cliente.api(metodo, ruta, opts)
|
|
return res, true, err
|
|
},
|
|
},
|
|
{
|
|
Comando: "esquema",
|
|
Alias: []string{"schema"},
|
|
Descripcion: "Describe en JSON todos los comandos, flags, tipos, ejemplos, codigos de salida y el dominio. Pensado para LLMs.",
|
|
SinServidor: true,
|
|
Run: func(ctx *cmdContext) (any, bool, error) {
|
|
return esquema(allCommands()), true, nil
|
|
},
|
|
},
|
|
{
|
|
Comando: "ayuda",
|
|
Alias: []string{"help"},
|
|
Descripcion: "Ayuda legible. `cotizador ayuda <comando>` para uno en particular.",
|
|
SinServidor: true,
|
|
Run: func(ctx *cmdContext) (any, bool, error) {
|
|
cmds := allCommands()
|
|
if len(ctx.Pos) > 0 {
|
|
cmd, _ := buscarComando(cmds, ctx.Pos)
|
|
if cmd == nil {
|
|
return nil, false, fallarComando(cmds, ctx.Pos)
|
|
}
|
|
_, _ = io.WriteString(ctx.Stdout, ayudaComando(cmd))
|
|
return nil, false, nil
|
|
}
|
|
_, _ = io.WriteString(ctx.Stdout, ayudaGeneral(cmds))
|
|
return nil, false, nil
|
|
},
|
|
},
|
|
{
|
|
Comando: "version",
|
|
SinServidor: true,
|
|
Descripcion: "Version del CLI.",
|
|
Run: func(ctx *cmdContext) (any, bool, error) {
|
|
return map[string]any{"version": Version}, true, nil
|
|
},
|
|
},
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Command lookup, help, and self-describing schema
|
|
// ---------------------------------------------------------------------------
|
|
|
|
func buscarComando(cmds []commandSpec, palabras []string) (*commandSpec, int) {
|
|
maxN := len(palabras)
|
|
if maxN > 3 {
|
|
maxN = 3
|
|
}
|
|
for n := maxN; n >= 1; n-- {
|
|
clave := strings.ToLower(strings.Join(palabras[:n], " "))
|
|
for i := range cmds {
|
|
if cmds[i].Comando == clave || slices.Contains(cmds[i].Alias, clave) {
|
|
return &cmds[i], n
|
|
}
|
|
}
|
|
}
|
|
return nil, 0
|
|
}
|
|
|
|
func fallarComando(cmds []commandSpec, palabras []string) error {
|
|
grupo := ""
|
|
if len(palabras) > 0 {
|
|
grupo = strings.ToLower(palabras[0])
|
|
}
|
|
var delGrupo []string
|
|
for _, c := range cmds {
|
|
first := strings.SplitN(c.Comando, " ", 2)[0]
|
|
if first == grupo {
|
|
delGrupo = append(delGrupo, c.Comando)
|
|
}
|
|
}
|
|
sug := "Ejecuta `cotizador ayuda` o `cotizador esquema` para ver los comandos"
|
|
if len(delGrupo) > 0 {
|
|
sug = fmt.Sprintf(`Comandos de "%s": %s`, grupo, strings.Join(delGrupo, ", "))
|
|
}
|
|
return errorUso("Comando desconocido: "+strings.Join(palabras, " "), sug)
|
|
}
|
|
|
|
func describirFlag(f flagSpec) map[string]any {
|
|
m := map[string]any{
|
|
"flag": "--" + f.Flag,
|
|
"tipo": f.Tipo,
|
|
"descripcion": f.Descripcion,
|
|
}
|
|
if len(f.Valores) > 0 {
|
|
m["valores"] = f.Valores
|
|
}
|
|
if f.Repetible {
|
|
m["repetible"] = true
|
|
}
|
|
return m
|
|
}
|
|
|
|
func usoDe(c *commandSpec) string {
|
|
var args []string
|
|
for _, a := range c.Argumentos {
|
|
args = append(args, "<"+a.Nombre+">")
|
|
}
|
|
s := "cotizador " + c.Comando
|
|
if len(args) > 0 {
|
|
s += " " + strings.Join(args, " ")
|
|
}
|
|
if len(c.Flags) > 0 {
|
|
s += " [flags]"
|
|
}
|
|
return s
|
|
}
|
|
|
|
func esquema(cmds []commandSpec) map[string]any {
|
|
glob := make([]map[string]any, len(flagsGlobales))
|
|
for i, f := range flagsGlobales {
|
|
glob[i] = describirFlag(f)
|
|
}
|
|
cmdList := make([]map[string]any, len(cmds))
|
|
for i := range cmds {
|
|
c := &cmds[i]
|
|
fl := make([]map[string]any, len(c.Flags))
|
|
for j, f := range c.Flags {
|
|
fl[j] = describirFlag(f)
|
|
}
|
|
args := c.Argumentos
|
|
if args == nil {
|
|
args = []argSpec{}
|
|
}
|
|
ejemplos := c.Ejemplos
|
|
if ejemplos == nil {
|
|
ejemplos = []string{}
|
|
}
|
|
var ep any
|
|
if c.HasEndpoint {
|
|
ep = c.Endpoint
|
|
}
|
|
entry := map[string]any{
|
|
"comando": c.Comando,
|
|
"descripcion": c.Descripcion,
|
|
"uso": usoDe(c),
|
|
"argumentos": args,
|
|
"flags": fl,
|
|
"ejemplos": ejemplos,
|
|
"endpoint": ep,
|
|
}
|
|
if len(c.Alias) > 0 {
|
|
entry["alias"] = c.Alias
|
|
}
|
|
cmdList[i] = entry
|
|
}
|
|
|
|
return map[string]any{
|
|
"nombre": "cotizador",
|
|
"version": Version,
|
|
"descripcion": "CLI del Cotizador — Uriel Jareth Consulting. Gestiona el catalogo de servicios, clientes, cotizaciones y horas a traves de la API REST de la plataforma.",
|
|
"convenciones": map[string]string{
|
|
"salida": "JSON en stdout (usa --campos para recortar, --formato tabla para humanos)",
|
|
"errores": "JSON en stderr: { ok:false, error, codigo, status?, detalles?, sugerencia? }",
|
|
"entrada": "Flags --kebab-case; --datos acepta JSON en linea, @archivo.json o - (stdin). Las flags tienen prioridad sobre --datos",
|
|
"ids": "Donde se pide <id> de servicio tambien vale su nombre exacto; para cotizaciones, el numero (UJ...)",
|
|
"escritura": "Usa --dry-run para ver la peticion sin enviarla. Borrar exige --confirmar",
|
|
"montos": "Precios en MXN sin IVA (IVA 16% se calcula al cotizar)",
|
|
},
|
|
"configuracion": map[string]string{
|
|
"COTIZADOR_URL": "URL base (default http://localhost:3000; produccion: https://cotizador.urieljareth.org)",
|
|
"COTIZADOR_EMAIL": "Correo para login automatico cuando no hay sesion o vencio",
|
|
"COTIZADOR_PASSWORD": "Contrasena para login automatico",
|
|
"COTIZADOR_TOKEN": "Token de sesion explicito (omite el archivo de sesiones)",
|
|
"COTIZADOR_HOME": "Carpeta de la sesion guardada (default ~/.cotizador-uj)",
|
|
},
|
|
"codigosSalida": descripcionCodigos,
|
|
"dominio": dominioInfo(),
|
|
"formatos": map[string]any{
|
|
"servicioCatalogo": map[string]string{
|
|
"nombre": "texto (obligatorio)",
|
|
"fase": "0-3 (obligatorio)",
|
|
"tipoPago": "unico | mensual (obligatorio)",
|
|
"precioBase": "numero >= 0 (obligatorio)",
|
|
"descripcion": "texto | null",
|
|
"tiempoEntrega": `texto (default "4 - 10 dias")`,
|
|
"entregablesDefault": "texto[]",
|
|
"categoriaId": "id | null (en el CLI tambien `categoria`: nombre)",
|
|
"variante": "texto | null",
|
|
"nivel": strings.Join(nivelesServicio, " | ") + " | null",
|
|
"orden": "entero (default: al final de su fase)",
|
|
"activo": "booleano (default true)",
|
|
},
|
|
"partidaCotizacion": map[string]string{
|
|
"catalogoId": `id del servicio, o "custom-<uuid>" si esPersonalizado`,
|
|
"nombre": "texto",
|
|
"fase": "0-3",
|
|
"tipoPago": "unico | mensual",
|
|
"precio": "numero: total autoritativo de la partida",
|
|
"tiempoEntrega": "texto",
|
|
"entregables": "texto[]",
|
|
"esPersonalizado": "booleano (partidas fuera del catalogo)",
|
|
"modeloCobro": "fijo | horas | retainer | demanda",
|
|
"horas": "numero (modelo horas)",
|
|
"tarifaHora": "numero",
|
|
"montoMinimo": "numero (retainer)",
|
|
"horasIncluidas": "numero (retainer)",
|
|
"opcion": `"1" | "2" | "ambas" (solo cotizaciones doble propuesta)`,
|
|
},
|
|
},
|
|
"flagsGlobales": glob,
|
|
"comandos": cmdList,
|
|
}
|
|
}
|
|
|
|
func firstSentence(s string) string {
|
|
for i := 0; i < len(s)-2; i++ {
|
|
if s[i] == '.' && s[i+1] == ' ' {
|
|
next := s[i+2]
|
|
if (next >= 'A' && next <= 'Z') || next == '(' {
|
|
return s[:i]
|
|
}
|
|
}
|
|
}
|
|
return s
|
|
}
|
|
|
|
func ayudaGeneral(cmds []commandSpec) string {
|
|
var groupOrder []string
|
|
grupos := make(map[string][]commandSpec)
|
|
ancho := 0
|
|
for _, c := range cmds {
|
|
if len(c.Comando) > ancho {
|
|
ancho = len(c.Comando)
|
|
}
|
|
g := "general"
|
|
if idx := strings.IndexByte(c.Comando, ' '); idx >= 0 {
|
|
g = c.Comando[:idx]
|
|
}
|
|
if _, ok := grupos[g]; !ok {
|
|
groupOrder = append(groupOrder, g)
|
|
}
|
|
grupos[g] = append(grupos[g], c)
|
|
}
|
|
ancho += 2
|
|
|
|
var b strings.Builder
|
|
fmt.Fprintf(&b, "cotizador %s — CLI del Cotizador — Uriel Jareth Consulting\n\nUso: cotizador <comando> [argumentos] [flags]\n", Version)
|
|
for _, g := range groupOrder {
|
|
fmt.Fprintf(&b, "\n%s\n", strings.ToUpper(g))
|
|
for _, c := range grupos[g] {
|
|
pad := strings.Repeat(" ", ancho-len(c.Comando))
|
|
fmt.Fprintf(&b, " %s%s%s\n", c.Comando, pad, firstSentence(c.Descripcion))
|
|
}
|
|
}
|
|
b.WriteString("\nFLAGS GLOBALES\n")
|
|
for _, f := range flagsGlobales {
|
|
padLen := ancho - 2 - len(f.Flag)
|
|
if padLen < 2 {
|
|
padLen = 2
|
|
}
|
|
fmt.Fprintf(&b, " --%s%s%s\n", f.Flag, strings.Repeat(" ", padLen), f.Descripcion)
|
|
}
|
|
b.WriteString("\nPrimeros pasos:\n" +
|
|
" cotizador login --email <correo> --password-stdin\n" +
|
|
" cotizador servicios listar --formato tabla\n" +
|
|
" cotizador esquema (descripcion completa en JSON, para LLMs)\n" +
|
|
"\nMas: cotizador ayuda <comando> · docs/CLI.md\n")
|
|
return b.String()
|
|
}
|
|
|
|
func ayudaComando(c *commandSpec) string {
|
|
var b strings.Builder
|
|
fmt.Fprintf(&b, "%s\n\n%s\n", usoDe(c), c.Descripcion)
|
|
if c.HasEndpoint && c.Endpoint != "" {
|
|
fmt.Fprintf(&b, "\nEndpoint: %s\n", c.Endpoint)
|
|
}
|
|
if len(c.Argumentos) > 0 {
|
|
b.WriteString("\nArgumentos:\n")
|
|
for _, a := range c.Argumentos {
|
|
fmt.Fprintf(&b, " <%s> %s\n", a.Nombre, a.Descripcion)
|
|
}
|
|
}
|
|
if len(c.Flags) > 0 {
|
|
b.WriteString("\nFlags:\n")
|
|
ancho := 0
|
|
for _, f := range c.Flags {
|
|
if len(f.Flag) > ancho {
|
|
ancho = len(f.Flag)
|
|
}
|
|
}
|
|
ancho += 4
|
|
for _, f := range c.Flags {
|
|
var extras []string
|
|
if len(f.Valores) > 0 {
|
|
vs := make([]string, len(f.Valores))
|
|
for i, v := range f.Valores {
|
|
vs[i] = fmt.Sprint(v)
|
|
}
|
|
extras = append(extras, "valores: "+strings.Join(vs, ", "))
|
|
}
|
|
if f.Repetible {
|
|
extras = append(extras, "repetible")
|
|
}
|
|
extra := ""
|
|
if len(extras) > 0 {
|
|
extra = " (" + strings.Join(extras, "; ") + ")"
|
|
}
|
|
fmt.Fprintf(&b, " --%s%s%s%s\n", f.Flag, strings.Repeat(" ", ancho-len(f.Flag)), f.Descripcion, extra)
|
|
}
|
|
}
|
|
if len(c.Ejemplos) > 0 {
|
|
b.WriteString("\nEjemplos:\n")
|
|
for _, e := range c.Ejemplos {
|
|
fmt.Fprintf(&b, " %s\n", e)
|
|
}
|
|
}
|
|
if len(c.Alias) > 0 {
|
|
fmt.Fprintf(&b, "\nAlias: %s\n", strings.Join(c.Alias, ", "))
|
|
}
|
|
return b.String()
|
|
}
|