1743 lines
65 KiB
Go
1743 lines
65 KiB
Go
package httpapi
|
|
|
|
import (
|
|
"context"
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
|
|
"cotizador/internal/audit"
|
|
"cotizador/internal/auth"
|
|
"cotizador/internal/db"
|
|
"cotizador/internal/domain"
|
|
"cotizador/internal/idempotency"
|
|
"cotizador/internal/pdf"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
"github.com/jackc/pgx/v5"
|
|
)
|
|
|
|
type cotizacionFull struct {
|
|
ID string
|
|
Numero string
|
|
Fecha time.Time
|
|
Vigencia time.Time
|
|
Moneda string
|
|
TipoCambio string
|
|
Proyecto string
|
|
EsquemaPago string
|
|
Estado string
|
|
IncluirBonos bool
|
|
IncluirFinanciamiento bool
|
|
IncluirIVA bool
|
|
EsDoble bool
|
|
OpcionesMetadata map[string]domain.MetaOpcion
|
|
Observaciones *string
|
|
ObservacionesInternas *string
|
|
ClienteID string
|
|
AsesorID string
|
|
AprobadaPorID *string
|
|
AprobadaAt *time.Time
|
|
AprobacionMetodo *string
|
|
EnviadaAt *time.Time
|
|
EnviadaPor *string
|
|
EnviadaCanal *string
|
|
EnviadaDestino *string
|
|
AceptadaAt *time.Time
|
|
RechazadaAt *time.Time
|
|
VencidaAt *time.Time
|
|
CreadaPorAgente *string
|
|
Archivado bool
|
|
ArchivadoAt *time.Time
|
|
CreatedAt time.Time
|
|
UpdatedAt time.Time
|
|
|
|
ClienteNombre string
|
|
ClienteEmpresa *string
|
|
ClientePuesto *string
|
|
ClienteEmail *string
|
|
ClienteTelefono *string
|
|
ClienteRFC *string
|
|
|
|
AsesorName string
|
|
AsesorEmail string
|
|
AsesorRole string
|
|
|
|
Servicios []map[string]any
|
|
ServiciosCalc []domain.ServicioCalc
|
|
ServiciosPDF []pdf.ServicioPDF
|
|
PlanBucefalo map[string]any
|
|
PlanBucefaloNv *string
|
|
PlanBucefaloPr float64
|
|
RegistrosHoras []map[string]any
|
|
}
|
|
|
|
func (s *Server) loadCotizacionFull(ctx context.Context, id string, redactInternas bool) (*cotizacionFull, map[string]any, error) {
|
|
var c cotizacionFull
|
|
var opMetaRaw []byte
|
|
err := s.Pool.QueryRow(ctx, `
|
|
SELECT q."id", q."numero", q."fecha", q."vigencia", q."moneda", q."tipoCambio", q."proyecto",
|
|
q."esquemaPago", q."estado", q."incluirBonos", q."incluirFinanciamiento", q."incluirIva",
|
|
q."esDoble", q."opcionesMetadata", q."observaciones", q."observacionesInternas",
|
|
q."clienteId", q."asesorId", q."aprobadaPorId", q."aprobadaAt", q."aprobacionMetodo",
|
|
q."enviadaAt", q."enviadaPor", q."enviadaCanal", q."enviadaDestino",
|
|
q."aceptadaAt", q."rechazadaAt", q."vencidaAt", q."creadaPorAgente",
|
|
q."archivado", q."archivadoAt", q."createdAt", q."updatedAt",
|
|
cl."nombre", cl."empresa", cl."puesto", cl."email", cl."telefono", cl."rfc",
|
|
u."name", u."email", u."role"
|
|
FROM "Cotizacion" q
|
|
JOIN "Cliente" cl ON cl."id" = q."clienteId"
|
|
JOIN "User" u ON u."id" = q."asesorId"
|
|
WHERE q."id" = $1
|
|
`, id).Scan(
|
|
&c.ID, &c.Numero, &c.Fecha, &c.Vigencia, &c.Moneda, &c.TipoCambio, &c.Proyecto,
|
|
&c.EsquemaPago, &c.Estado, &c.IncluirBonos, &c.IncluirFinanciamiento, &c.IncluirIVA,
|
|
&c.EsDoble, &opMetaRaw, &c.Observaciones, &c.ObservacionesInternas,
|
|
&c.ClienteID, &c.AsesorID, &c.AprobadaPorID, &c.AprobadaAt, &c.AprobacionMetodo,
|
|
&c.EnviadaAt, &c.EnviadaPor, &c.EnviadaCanal, &c.EnviadaDestino,
|
|
&c.AceptadaAt, &c.RechazadaAt, &c.VencidaAt, &c.CreadaPorAgente,
|
|
&c.Archivado, &c.ArchivadoAt, &c.CreatedAt, &c.UpdatedAt,
|
|
&c.ClienteNombre, &c.ClienteEmpresa, &c.ClientePuesto, &c.ClienteEmail, &c.ClienteTelefono, &c.ClienteRFC,
|
|
&c.AsesorName, &c.AsesorEmail, &c.AsesorRole,
|
|
)
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
if len(opMetaRaw) > 0 {
|
|
_ = json.Unmarshal(opMetaRaw, &c.OpcionesMetadata)
|
|
}
|
|
|
|
// Load ServiciosCotizados
|
|
sRows, _ := s.Pool.Query(ctx, `
|
|
SELECT s."id", s."cotizacionId", s."servicioCatalogoId", s."nombre", s."esPersonalizado",
|
|
s."horas", s."tarifaHora", s."modeloCobro", s."montoMinimo", s."horasIncluidas",
|
|
s."opcion", s."fase", s."tipoPago", s."precio", s."tiempoEntrega",
|
|
s."entregables", s."beneficios", s."notas", s."seleccionado",
|
|
sc."nombre", sc."precioBase"
|
|
FROM "ServicioCotizado" s
|
|
LEFT JOIN "ServicioCatalogo" sc ON sc."id" = s."servicioCatalogoId"
|
|
WHERE s."cotizacionId" = $1
|
|
ORDER BY s."fase" ASC, s."createdAt" ASC
|
|
`, id)
|
|
c.Servicios = []map[string]any{}
|
|
if sRows != nil {
|
|
defer sRows.Close()
|
|
for sRows.Next() {
|
|
var sid, qid, modeloCobro, tipoPago, tiempoEntrega string
|
|
var scid, nombre, opcion, notas, scNombre *string
|
|
var esPers, sel bool
|
|
var horas, tarifaHora, montoMin, horasInc, scPrecioBase *float64
|
|
var fase int
|
|
var precio float64
|
|
var entRaw, benRaw []byte
|
|
if sRows.Scan(&sid, &qid, &scid, &nombre, &esPers, &horas, &tarifaHora, &modeloCobro, &montoMin, &horasInc,
|
|
&opcion, &fase, &tipoPago, &precio, &tiempoEntrega, &entRaw, &benRaw, ¬as, &sel, &scNombre, &scPrecioBase) == nil {
|
|
var ent, ben []string
|
|
_ = json.Unmarshal(entRaw, &ent)
|
|
_ = json.Unmarshal(benRaw, &ben)
|
|
if ent == nil {
|
|
ent = []string{}
|
|
}
|
|
if ben == nil {
|
|
ben = []string{}
|
|
}
|
|
effName := "Servicio"
|
|
if nombre != nil && strings.TrimSpace(*nombre) != "" {
|
|
effName = *nombre
|
|
} else if scNombre != nil && strings.TrimSpace(*scNombre) != "" {
|
|
effName = *scNombre
|
|
}
|
|
var scObj any
|
|
if scid != nil {
|
|
scObj = map[string]any{"id": *scid, "nombre": scNombre, "precioBase": scPrecioBase}
|
|
}
|
|
c.Servicios = append(c.Servicios, map[string]any{
|
|
"id": sid, "cotizacionId": qid, "servicioCatalogoId": scid,
|
|
"nombre": effName, "esPersonalizado": esPers, "horas": horas, "tarifaHora": tarifaHora,
|
|
"modeloCobro": modeloCobro, "montoMinimo": montoMin, "horasIncluidas": horasInc,
|
|
"opcion": opcion, "fase": fase, "tipoPago": tipoPago, "precio": precio,
|
|
"tiempoEntrega": tiempoEntrega, "entregables": ent, "beneficios": ben,
|
|
"notas": notas, "seleccionado": sel, "servicioCatalogo": scObj,
|
|
})
|
|
c.ServiciosCalc = append(c.ServiciosCalc, domain.ServicioCalc{
|
|
Nombre: effName, ModeloCobro: modeloCobro, EsPersonalizado: esPers,
|
|
Horas: horas, TarifaHora: tarifaHora, MontoMinimo: montoMin, HorasIncluidas: horasInc,
|
|
Opcion: opcion, TipoPago: tipoPago, Precio: precio, Seleccionado: sel,
|
|
})
|
|
if sel {
|
|
c.ServiciosPDF = append(c.ServiciosPDF, pdf.ServicioPDF{
|
|
Nombre: effName, Fase: fase, TipoPago: tipoPago, Precio: precio,
|
|
TiempoEntrega: tiempoEntrega, Entregables: ent, EsPersonalizado: esPers,
|
|
Horas: horas, TarifaHora: tarifaHora, ModeloCobro: modeloCobro,
|
|
MontoMinimo: montoMin, HorasIncluidas: horasInc, Opcion: opcion,
|
|
})
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Plan Bucefalo
|
|
var pbid, pbnivel string
|
|
var pbprecio float64
|
|
var pbsel bool
|
|
if err := s.Pool.QueryRow(ctx, `
|
|
SELECT "id", "nivel", "precio", "seleccionado" FROM "PlanBucefaloCotizacion" WHERE "cotizacionId" = $1
|
|
`, id).Scan(&pbid, &pbnivel, &pbprecio, &pbsel); err == nil {
|
|
c.PlanBucefalo = map[string]any{
|
|
"id": pbid, "cotizacionId": id, "nivel": pbnivel, "precio": pbprecio, "seleccionado": pbsel,
|
|
}
|
|
if pbsel {
|
|
nv := pbnivel
|
|
c.PlanBucefaloNv = &nv
|
|
c.PlanBucefaloPr = pbprecio
|
|
}
|
|
}
|
|
|
|
// RegistrosHoras
|
|
hRows, _ := s.Pool.Query(ctx, `
|
|
SELECT "id", "cotizacionId", "fecha", "horaInicio", "horaFin", "horas", "tarifaHora", "descripcion", "estadoPago", "fechaPago", "createdAt"
|
|
FROM "RegistroHoras"
|
|
WHERE "cotizacionId" = $1
|
|
ORDER BY "fecha" DESC, "horaInicio" DESC
|
|
`, id)
|
|
c.RegistrosHoras = []map[string]any{}
|
|
if hRows != nil {
|
|
defer hRows.Close()
|
|
for hRows.Next() {
|
|
var hid, qid, hi, hf, desc, ep string
|
|
var fecha, createdAt time.Time
|
|
var fechaPago *time.Time
|
|
var hrs, th float64
|
|
if hRows.Scan(&hid, &qid, &fecha, &hi, &hf, &hrs, &th, &desc, &ep, &fechaPago, &createdAt) == nil {
|
|
c.RegistrosHoras = append(c.RegistrosHoras, map[string]any{
|
|
"id": hid, "cotizacionId": qid, "fecha": fecha, "horaInicio": hi, "horaFin": hf,
|
|
"horas": hrs, "tarifaHora": th, "descripcion": desc, "estadoPago": ep,
|
|
"fechaPago": fechaPago, "createdAt": createdAt,
|
|
})
|
|
}
|
|
}
|
|
}
|
|
|
|
obsInt := c.ObservacionesInternas
|
|
if redactInternas {
|
|
obsInt = nil
|
|
}
|
|
|
|
jsonMap := map[string]any{
|
|
"id": c.ID, "numero": c.Numero, "fecha": c.Fecha, "vigencia": c.Vigencia,
|
|
"moneda": c.Moneda, "tipoCambio": c.TipoCambio, "proyecto": c.Proyecto,
|
|
"esquemaPago": c.EsquemaPago, "estado": c.Estado,
|
|
"incluirBonos": c.IncluirBonos, "incluirFinanciamiento": c.IncluirFinanciamiento,
|
|
"incluirIva": c.IncluirIVA, "esDoble": c.EsDoble, "opcionesMetadata": c.OpcionesMetadata,
|
|
"observaciones": c.Observaciones, "observacionesInternas": obsInt,
|
|
"clienteId": c.ClienteID, "asesorId": c.AsesorID,
|
|
"aprobadaPorId": c.AprobadaPorID, "aprobadaAt": c.AprobadaAt, "aprobacionMetodo": c.AprobacionMetodo,
|
|
"enviadaAt": c.EnviadaAt, "enviadaPor": c.EnviadaPor, "enviadaCanal": c.EnviadaCanal, "enviadaDestino": c.EnviadaDestino,
|
|
"aceptadaAt": c.AceptadaAt, "rechazadaAt": c.RechazadaAt, "vencidaAt": c.VencidaAt,
|
|
"creadaPorAgente": c.CreadaPorAgente, "archivado": c.Archivado, "archivadoAt": c.ArchivadoAt,
|
|
"createdAt": c.CreatedAt, "updatedAt": c.UpdatedAt,
|
|
"cliente": map[string]any{
|
|
"id": c.ClienteID, "nombre": c.ClienteNombre, "empresa": c.ClienteEmpresa,
|
|
"puesto": c.ClientePuesto, "email": c.ClienteEmail, "telefono": c.ClienteTelefono, "rfc": c.ClienteRFC,
|
|
},
|
|
"asesor": map[string]any{
|
|
"id": c.AsesorID, "name": c.AsesorName, "email": c.AsesorEmail, "role": c.AsesorRole,
|
|
},
|
|
"servicios": c.Servicios,
|
|
"planBucefalo": c.PlanBucefalo,
|
|
"registrosHoras": c.RegistrosHoras,
|
|
}
|
|
return &c, jsonMap, nil
|
|
}
|
|
|
|
func (s *Server) soloAdminCatalogIDs(ctx context.Context) map[string]struct{} {
|
|
out := map[string]struct{}{}
|
|
rows, err := s.Pool.Query(ctx, `SELECT "id" FROM "ServicioCatalogo" WHERE "soloAdmin" = true`)
|
|
if err != nil {
|
|
return out
|
|
}
|
|
defer rows.Close()
|
|
for rows.Next() {
|
|
var id string
|
|
if rows.Scan(&id) == nil {
|
|
out[id] = struct{}{}
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
func (s *Server) crearEnlaceAprobacion(ctx context.Context, cotID string) (string, error) {
|
|
// Invalidate previous unused tokens for this quote
|
|
_, _ = s.Pool.Exec(ctx, `UPDATE "ApprovalToken" SET "usadoAt" = NOW() WHERE "cotizacionId" = $1 AND "usadoAt" IS NULL`, cotID)
|
|
rawToken, tokHash := auth.GenerateRandomToken(32)
|
|
expiraAt := time.Now().Add(72 * time.Hour)
|
|
_, err := s.Pool.Exec(ctx, `
|
|
INSERT INTO "ApprovalToken" ("id", "cotizacionId", "tokenHash", "expiraAt", "createdAt")
|
|
VALUES ($1, $2, $3, $4, NOW())
|
|
`, db.NewID(), cotID, tokHash, expiraAt)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return fmt.Sprintf("%s/aprobar/%s", s.Cfg.AppURL, rawToken), nil
|
|
}
|
|
|
|
func (s *Server) handleCotizacionesList(w http.ResponseWriter, r *http.Request) {
|
|
actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{
|
|
Scopes: []string{"cotizaciones:leer", "cotizaciones:leer_aceptadas"},
|
|
RecursoTipo: "cotizacion",
|
|
})
|
|
if !ok {
|
|
return
|
|
}
|
|
q := r.URL.Query()
|
|
soloAceptadas := actor.EsAgenteSoloAceptadas()
|
|
|
|
estado := strings.TrimSpace(q.Get("estado"))
|
|
if soloAceptadas {
|
|
if estado != "" && estado != "aceptada" {
|
|
tipo, aid, anom := actor.AuditActor()
|
|
audit.Registrar(r.Context(), s.Pool, audit.Entry{
|
|
ActorTipo: tipo, ActorID: aid, ActorNombre: anom,
|
|
Accion: "cotizacion.leer_bloqueado", RecursoTipo: "cotizacion",
|
|
IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: false,
|
|
Detalle: map[string]any{"estadoSolicitado": estado},
|
|
})
|
|
writeError(w, http.StatusForbidden, "Esta clave solo puede consultar cotizaciones aceptadas")
|
|
return
|
|
}
|
|
estado = "aceptada"
|
|
}
|
|
|
|
conds := []string{"1=1"}
|
|
args := []any{}
|
|
add := func(v any) string {
|
|
args = append(args, v)
|
|
return fmt.Sprintf("$%d", len(args))
|
|
}
|
|
|
|
if actor.IsAgent() || q.Get("incluirArchivados") != "true" {
|
|
conds = append(conds, `q."archivado" = false`)
|
|
}
|
|
if estado != "" {
|
|
conds = append(conds, `q."estado" = `+add(estado))
|
|
}
|
|
if v := strings.TrimSpace(q.Get("clienteId")); v != "" {
|
|
conds = append(conds, `q."clienteId" = `+add(v))
|
|
}
|
|
if v := strings.TrimSpace(q.Get("q")); v != "" {
|
|
p := add("%" + v + "%")
|
|
conds = append(conds, fmt.Sprintf(`(q."numero" ILIKE %s OR q."proyecto" ILIKE %s OR cl."nombre" ILIKE %s OR COALESCE(cl."empresa", '') ILIKE %s)`, p, p, p, p))
|
|
}
|
|
if v := strings.TrimSpace(q.Get("clienteEmail")); v != "" {
|
|
conds = append(conds, `LOWER(COALESCE(cl."email", '')) = LOWER(`+add(v)+`)`)
|
|
}
|
|
if v := strings.TrimSpace(q.Get("clienteTelefono")); v != "" {
|
|
conds = append(conds, `COALESCE(cl."telefono", '') ILIKE `+add("%"+v+"%"))
|
|
}
|
|
if v := strings.TrimSpace(q.Get("desde")); v != "" {
|
|
if t, err := time.Parse("2006-01-02", v); err == nil {
|
|
conds = append(conds, `q."fecha" >= `+add(t))
|
|
}
|
|
}
|
|
if v := strings.TrimSpace(q.Get("hasta")); v != "" {
|
|
if t, err := time.Parse("2006-01-02", v); err == nil {
|
|
conds = append(conds, `q."fecha" <= `+add(t.Add(24*time.Hour)))
|
|
}
|
|
}
|
|
|
|
limit := parseIntQuery(r, "limit", 200, 1, 200)
|
|
page := parseIntQuery(r, "page", 1, 1, 10000)
|
|
offset := (page - 1) * limit
|
|
limArg := add(limit)
|
|
offArg := add(offset)
|
|
|
|
rows, err := s.Pool.Query(r.Context(), `
|
|
SELECT q."id", q."numero", q."fecha", q."vigencia", q."moneda", q."proyecto", q."estado",
|
|
q."esDoble", q."incluirIva", q."observaciones", q."observacionesInternas",
|
|
q."archivado", q."createdAt", q."aprobadaAt", q."enviadaAt",
|
|
cl."id", cl."nombre", cl."empresa", cl."email", cl."telefono",
|
|
u."id", u."name", u."email"
|
|
FROM "Cotizacion" q
|
|
JOIN "Cliente" cl ON cl."id" = q."clienteId"
|
|
JOIN "User" u ON u."id" = q."asesorId"
|
|
WHERE `+strings.Join(conds, " AND ")+`
|
|
ORDER BY q."createdAt" DESC
|
|
LIMIT `+limArg+` OFFSET `+offArg, args...)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "Error listando cotizaciones")
|
|
return
|
|
}
|
|
defer rows.Close()
|
|
|
|
list := []map[string]any{}
|
|
var ids []string
|
|
for rows.Next() {
|
|
var id, numero, moneda, proyecto, estadoRow, cid, cnom, uid, uname, uemail string
|
|
var cemp, cemail, ctel, obs, obsInt *string
|
|
var fecha, vigencia, createdAt time.Time
|
|
var aprobadaAt, enviadaAt *time.Time
|
|
var esDoble, incluirIva, archivado bool
|
|
if rows.Scan(&id, &numero, &fecha, &vigencia, &moneda, &proyecto, &estadoRow, &esDoble, &incluirIva,
|
|
&obs, &obsInt, &archivado, &createdAt, &aprobadaAt, &enviadaAt,
|
|
&cid, &cnom, &cemp, &cemail, &ctel, &uid, &uname, &uemail) == nil {
|
|
ids = append(ids, id)
|
|
if soloAceptadas {
|
|
obsInt = nil
|
|
}
|
|
list = append(list, map[string]any{
|
|
"id": id, "numero": numero, "fecha": fecha, "vigencia": vigencia,
|
|
"moneda": moneda, "proyecto": proyecto, "estado": estadoRow,
|
|
"esDoble": esDoble, "incluirIva": incluirIva,
|
|
"observaciones": obs, "observacionesInternas": obsInt,
|
|
"archivado": archivado, "createdAt": createdAt, "aprobadaAt": aprobadaAt, "enviadaAt": enviadaAt,
|
|
"cliente": map[string]any{"id": cid, "nombre": cnom, "empresa": cemp, "email": cemail, "telefono": ctel},
|
|
"asesor": map[string]any{"id": uid, "name": uname, "email": uemail},
|
|
"servicios": []any{},
|
|
})
|
|
}
|
|
}
|
|
|
|
if len(ids) > 0 {
|
|
sRows, err := s.Pool.Query(r.Context(), `
|
|
SELECT "id", "cotizacionId", "nombre", "fase", "tipoPago", "precio", "seleccionado", "modeloCobro", "opcion"
|
|
FROM "ServicioCotizado"
|
|
WHERE "cotizacionId" = ANY($1)
|
|
ORDER BY "fase" ASC, "createdAt" ASC
|
|
`, ids)
|
|
if err == nil {
|
|
defer sRows.Close()
|
|
byCot := map[string][]map[string]any{}
|
|
for sRows.Next() {
|
|
var sid, qid, tp, mc string
|
|
var nom, op *string
|
|
var fase int
|
|
var precio float64
|
|
var sel bool
|
|
if sRows.Scan(&sid, &qid, &nom, &fase, &tp, &precio, &sel, &mc, &op) == nil {
|
|
byCot[qid] = append(byCot[qid], map[string]any{
|
|
"id": sid, "nombre": nom, "fase": fase, "tipoPago": tp, "precio": precio,
|
|
"seleccionado": sel, "modeloCobro": mc, "opcion": op,
|
|
})
|
|
}
|
|
}
|
|
for _, it := range list {
|
|
if svcs, ok := byCot[it["id"].(string)]; ok {
|
|
it["servicios"] = svcs
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
writeJSON(w, http.StatusOK, list)
|
|
}
|
|
|
|
type servicioInputDTO struct {
|
|
ServicioCatalogoID *string `json:"servicioCatalogoId"`
|
|
CatalogoID *string `json:"catalogoId"`
|
|
Nombre *string `json:"nombre"`
|
|
EsPersonalizado bool `json:"esPersonalizado"`
|
|
Horas *float64 `json:"horas"`
|
|
TarifaHora *float64 `json:"tarifaHora"`
|
|
ModeloCobro string `json:"modeloCobro"`
|
|
MontoMinimo *float64 `json:"montoMinimo"`
|
|
HorasIncluidas *float64 `json:"horasIncluidas"`
|
|
Opcion *string `json:"opcion"`
|
|
Fase int `json:"fase"`
|
|
TipoPago string `json:"tipoPago"`
|
|
Precio float64 `json:"precio"`
|
|
TiempoEntrega string `json:"tiempoEntrega"`
|
|
Entregables []string `json:"entregables"`
|
|
Beneficios []string `json:"beneficios"`
|
|
Notas *string `json:"notas"`
|
|
Seleccionado *bool `json:"seleccionado"`
|
|
}
|
|
|
|
func (s *Server) handleCotizacionesCreate(w http.ResponseWriter, r *http.Request) {
|
|
actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{
|
|
Scopes: []string{"cotizaciones:borrador"},
|
|
RecursoTipo: "cotizacion",
|
|
})
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
idempotency.Execute(r.Context(), s.Pool, w, r, actor, func(rawBody []byte) (int, any) {
|
|
var body struct {
|
|
Numero string `json:"numero"`
|
|
Fecha string `json:"fecha"`
|
|
Vigencia string `json:"vigencia"`
|
|
Moneda string `json:"moneda"`
|
|
TipoCambio string `json:"tipoCambio"`
|
|
Proyecto string `json:"proyecto"`
|
|
EsquemaPago string `json:"esquemaPago"`
|
|
IncluirBonos bool `json:"incluirBonos"`
|
|
IncluirFinanciamiento bool `json:"incluirFinanciamiento"`
|
|
IncluirIVA *bool `json:"incluirIva"`
|
|
EsDoble bool `json:"esDoble"`
|
|
OpcionesMetadata map[string]domain.MetaOpcion `json:"opcionesMetadata"`
|
|
Observaciones *string `json:"observaciones"`
|
|
ObservacionesInternas *string `json:"observacionesInternas"`
|
|
ClienteID string `json:"clienteId"`
|
|
Cliente *struct {
|
|
Nombre string `json:"nombre"`
|
|
Empresa *string `json:"empresa"`
|
|
Puesto *string `json:"puesto"`
|
|
Email *string `json:"email"`
|
|
Telefono *string `json:"telefono"`
|
|
RFC *string `json:"rfc"`
|
|
} `json:"cliente"`
|
|
AsesorID string `json:"asesorId"`
|
|
Servicios []servicioInputDTO `json:"servicios"`
|
|
PlanBucefalo *struct {
|
|
Nivel string `json:"nivel"`
|
|
Precio *float64 `json:"precio"`
|
|
Seleccionado *bool `json:"seleccionado"`
|
|
} `json:"planBucefalo"`
|
|
}
|
|
if err := json.Unmarshal(rawBody, &body); err != nil {
|
|
return http.StatusBadRequest, map[string]any{"error": "JSON invalido"}
|
|
}
|
|
|
|
// SoloAdmin check for agents
|
|
draftSvcs := make([]domain.ServicioDraftInput, 0, len(body.Servicios))
|
|
for _, sv := range body.Servicios {
|
|
cid := firstNonEmptyStr(derefStr(sv.ServicioCatalogoID), derefStr(sv.CatalogoID))
|
|
draftSvcs = append(draftSvcs, domain.ServicioDraftInput{
|
|
CatalogoID: cid, Nombre: derefStr(sv.Nombre), EsPersonalizado: sv.EsPersonalizado,
|
|
})
|
|
}
|
|
soloCheck := domain.EvaluarRestriccionSoloAdmin(domain.EvaluarSoloAdminInput{
|
|
EsAgente: actor.IsAgent(),
|
|
HasPlanBucefalo: body.PlanBucefalo != nil,
|
|
Servicios: draftSvcs,
|
|
SoloAdminCatalogIDs: s.soloAdminCatalogIDs(r.Context()),
|
|
})
|
|
if !soloCheck.OK {
|
|
tipo, aid, anom := actor.AuditActor()
|
|
audit.Registrar(r.Context(), s.Pool, audit.Entry{
|
|
ActorTipo: tipo, ActorID: aid, ActorNombre: anom,
|
|
Accion: "cotizacion.servicio_solo_admin_bloqueado", RecursoTipo: "cotizacion",
|
|
IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: false,
|
|
Detalle: map[string]any{"items": soloCheck.ItemsBloqueados, "motivos": soloCheck.Motivos},
|
|
})
|
|
return http.StatusForbidden, map[string]any{
|
|
"error": "Uno o mas servicios solicitados son exclusivos de administrador",
|
|
"reason": "solo_admin_restricted",
|
|
"itemsBloqueados": soloCheck.ItemsBloqueados,
|
|
}
|
|
}
|
|
|
|
// Resolve or upsert Cliente
|
|
clienteID := strings.TrimSpace(body.ClienteID)
|
|
var clienteNombre, clienteEmpresa string
|
|
if clienteID == "" {
|
|
if body.Cliente == nil || strings.TrimSpace(body.Cliente.Nombre) == "" {
|
|
return http.StatusBadRequest, map[string]any{"error": "Se requiere clienteId o datos de cliente"}
|
|
}
|
|
cNom := strings.TrimSpace(body.Cliente.Nombre)
|
|
cEmp := strings.TrimSpace(derefStr(body.Cliente.Empresa))
|
|
err := s.Pool.QueryRow(r.Context(), `
|
|
SELECT "id", "nombre", COALESCE("empresa", '')
|
|
FROM "Cliente"
|
|
WHERE "archivado" = false
|
|
AND LOWER(TRIM("nombre")) = LOWER($1)
|
|
AND LOWER(TRIM(COALESCE("empresa", ''))) = LOWER($2)
|
|
LIMIT 1
|
|
`, cNom, cEmp).Scan(&clienteID, &clienteNombre, &clienteEmpresa)
|
|
if err != nil {
|
|
clienteID = db.NewID()
|
|
clienteNombre = cNom
|
|
clienteEmpresa = cEmp
|
|
_, err = s.Pool.Exec(r.Context(), `
|
|
INSERT INTO "Cliente" ("id", "nombre", "empresa", "puesto", "email", "telefono", "rfc", "archivado", "createdAt", "updatedAt")
|
|
VALUES ($1,$2,$3,$4,$5,$6,$7,false,NOW(),NOW())
|
|
`, clienteID, cNom, nullableTrim(cEmp), trimPtr(body.Cliente.Puesto), trimPtr(body.Cliente.Email), trimPtr(body.Cliente.Telefono), trimPtr(body.Cliente.RFC))
|
|
if err != nil {
|
|
return http.StatusInternalServerError, map[string]any{"error": "Error creando cliente"}
|
|
}
|
|
} else {
|
|
// Update optional contact fields if supplied
|
|
if body.Cliente.Email != nil || body.Cliente.Telefono != nil || body.Cliente.RFC != nil || body.Cliente.Puesto != nil {
|
|
_, _ = s.Pool.Exec(r.Context(), `
|
|
UPDATE "Cliente"
|
|
SET "email" = COALESCE($1, "email"),
|
|
"telefono" = COALESCE($2, "telefono"),
|
|
"rfc" = COALESCE($3, "rfc"),
|
|
"puesto" = COALESCE($4, "puesto"),
|
|
"updatedAt" = NOW()
|
|
WHERE "id" = $5
|
|
`, trimPtr(body.Cliente.Email), trimPtr(body.Cliente.Telefono), trimPtr(body.Cliente.RFC), trimPtr(body.Cliente.Puesto), clienteID)
|
|
}
|
|
}
|
|
} else {
|
|
if err := s.Pool.QueryRow(r.Context(), `SELECT "nombre", COALESCE("empresa", '') FROM "Cliente" WHERE "id" = $1`, clienteID).Scan(&clienteNombre, &clienteEmpresa); err != nil {
|
|
return http.StatusNotFound, map[string]any{"error": "Cliente no encontrado"}
|
|
}
|
|
}
|
|
|
|
// Resolve Asesor
|
|
asesorID := strings.TrimSpace(body.AsesorID)
|
|
var asesorName string
|
|
if asesorID == "" {
|
|
if actor.IsStaff() {
|
|
asesorID = actor.UserID
|
|
asesorName = actor.Name
|
|
} else {
|
|
_ = s.Pool.QueryRow(r.Context(), `SELECT "id", "name" FROM "User" WHERE "role" = 'admin' ORDER BY "createdAt" ASC LIMIT 1`).Scan(&asesorID, &asesorName)
|
|
}
|
|
} else {
|
|
_ = s.Pool.QueryRow(r.Context(), `SELECT "name" FROM "User" WHERE "id" = $1`, asesorID).Scan(&asesorName)
|
|
}
|
|
if asesorID == "" {
|
|
return http.StatusBadRequest, map[string]any{"error": "No se encontro un asesor valido"}
|
|
}
|
|
|
|
// Dates & folio
|
|
fecha := time.Now()
|
|
if body.Fecha != "" {
|
|
if t, err := parseFlexibleDate(body.Fecha); err == nil {
|
|
fecha = t
|
|
}
|
|
}
|
|
vigencia := domain.CalcularVigencia(fecha)
|
|
if body.Vigencia != "" {
|
|
if t, err := parseFlexibleDate(body.Vigencia); err == nil {
|
|
vigencia = t
|
|
}
|
|
}
|
|
numero := strings.TrimSpace(body.Numero)
|
|
if numero == "" {
|
|
numero = s.siguienteNumeroCotizacion(r.Context(), asesorName)
|
|
}
|
|
incluirIVA := true
|
|
if body.IncluirIVA != nil {
|
|
incluirIVA = *body.IncluirIVA
|
|
}
|
|
var opMetaJSON []byte
|
|
if body.OpcionesMetadata != nil {
|
|
opMetaJSON, _ = json.Marshal(body.OpcionesMetadata)
|
|
}
|
|
var creadaPorAgente *string
|
|
if actor.IsAgent() {
|
|
n := actor.KeyNombre
|
|
creadaPorAgente = &n
|
|
}
|
|
|
|
tx, err := s.Pool.Begin(r.Context())
|
|
if err != nil {
|
|
return http.StatusInternalServerError, map[string]any{"error": "Error iniciando transaccion"}
|
|
}
|
|
defer tx.Rollback(r.Context())
|
|
|
|
cotID := db.NewID()
|
|
_, err = tx.Exec(r.Context(), `
|
|
INSERT INTO "Cotizacion" (
|
|
"id", "numero", "fecha", "vigencia", "moneda", "tipoCambio", "proyecto",
|
|
"esquemaPago", "estado", "incluirBonos", "incluirFinanciamiento", "incluirIva",
|
|
"esDoble", "opcionesMetadata", "observaciones", "observacionesInternas",
|
|
"clienteId", "asesorId", "creadaPorAgente", "archivado", "createdAt", "updatedAt"
|
|
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,'borrador',$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,false,NOW(),NOW())
|
|
`, cotID, numero, fecha, vigencia,
|
|
firstNonEmptyStr(body.Moneda, "MXN"),
|
|
firstNonEmptyStr(body.TipoCambio, "NA"),
|
|
firstNonEmptyStr(body.Proyecto, "MKT Digital"),
|
|
firstNonEmptyStr(body.EsquemaPago, "Pago Unico/Mensual"),
|
|
body.IncluirBonos, body.IncluirFinanciamiento, incluirIVA,
|
|
body.EsDoble, opMetaJSON, body.Observaciones, body.ObservacionesInternas,
|
|
clienteID, asesorID, creadaPorAgente)
|
|
if err != nil {
|
|
if strings.Contains(err.Error(), "23505") {
|
|
return http.StatusConflict, map[string]any{"error": "Ya existe una cotizacion con ese numero"}
|
|
}
|
|
return http.StatusInternalServerError, map[string]any{"error": "Error guardando cotizacion: " + err.Error()}
|
|
}
|
|
|
|
var calcSvcs []domain.ServicioCalc
|
|
for _, sv := range body.Servicios {
|
|
scid := nullableTrim(firstNonEmptyStr(derefStr(sv.ServicioCatalogoID), derefStr(sv.CatalogoID)))
|
|
sel := true
|
|
if sv.Seleccionado != nil {
|
|
sel = *sv.Seleccionado
|
|
}
|
|
mc := firstNonEmptyStr(sv.ModeloCobro, "fijo")
|
|
tp := firstNonEmptyStr(sv.TipoPago, "unico")
|
|
te := firstNonEmptyStr(sv.TiempoEntrega, "4 - 10 dias")
|
|
ent := sv.Entregables
|
|
if ent == nil {
|
|
ent = []string{}
|
|
}
|
|
ben := sv.Beneficios
|
|
if ben == nil {
|
|
ben = []string{}
|
|
}
|
|
entJSON, _ := json.Marshal(ent)
|
|
benJSON, _ := json.Marshal(ben)
|
|
_, err = tx.Exec(r.Context(), `
|
|
INSERT INTO "ServicioCotizado" (
|
|
"id", "cotizacionId", "servicioCatalogoId", "nombre", "esPersonalizado",
|
|
"horas", "tarifaHora", "modeloCobro", "montoMinimo", "horasIncluidas",
|
|
"opcion", "fase", "tipoPago", "precio", "tiempoEntrega",
|
|
"entregables", "beneficios", "notas", "seleccionado", "createdAt", "updatedAt"
|
|
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,NOW(),NOW())
|
|
`, db.NewID(), cotID, scid, sv.Nombre, sv.EsPersonalizado,
|
|
sv.Horas, sv.TarifaHora, mc, sv.MontoMinimo, sv.HorasIncluidas,
|
|
sv.Opcion, sv.Fase, tp, sv.Precio, te, entJSON, benJSON, sv.Notas, sel)
|
|
if err != nil {
|
|
return http.StatusInternalServerError, map[string]any{"error": "Error guardando servicios"}
|
|
}
|
|
calcSvcs = append(calcSvcs, domain.ServicioCalc{TipoPago: tp, Precio: sv.Precio, Seleccionado: sel})
|
|
}
|
|
|
|
if body.PlanBucefalo != nil {
|
|
nivel := firstNonEmptyStr(body.PlanBucefalo.Nivel, "basico")
|
|
precio := domain.BucefaloPrecio(nivel)
|
|
if body.PlanBucefalo.Precio != nil {
|
|
precio = *body.PlanBucefalo.Precio
|
|
}
|
|
sel := true
|
|
if body.PlanBucefalo.Seleccionado != nil {
|
|
sel = *body.PlanBucefalo.Seleccionado
|
|
}
|
|
_, err = tx.Exec(r.Context(), `
|
|
INSERT INTO "PlanBucefaloCotizacion" ("id", "cotizacionId", "nivel", "precio", "seleccionado", "createdAt", "updatedAt")
|
|
VALUES ($1,$2,$3,$4,$5,NOW(),NOW())
|
|
`, db.NewID(), cotID, nivel, precio, sel)
|
|
if err != nil {
|
|
return http.StatusInternalServerError, map[string]any{"error": "Error guardando plan Bucefalo"}
|
|
}
|
|
}
|
|
|
|
if err := tx.Commit(r.Context()); err != nil {
|
|
return http.StatusInternalServerError, map[string]any{"error": "Error confirmando cotizacion"}
|
|
}
|
|
|
|
tipo, aid, anom := actor.AuditActor()
|
|
audit.Registrar(r.Context(), s.Pool, audit.Entry{
|
|
ActorTipo: tipo, ActorID: aid, ActorNombre: anom,
|
|
Accion: "cotizacion.crear", RecursoTipo: "cotizacion", RecursoID: cotID,
|
|
IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true,
|
|
Detalle: map[string]any{"numero": numero, "clienteId": clienteID},
|
|
})
|
|
|
|
tot := domain.CalcularTotalesCotizacion(calcSvcs, incluirIVA)
|
|
if actor.IsAgent() {
|
|
if approvalURL, err := s.crearEnlaceAprobacion(r.Context(), cotID); err == nil {
|
|
go s.Notify.NotificarJarethBorrador(context.Background(), cotID, numero, clienteNombre, clienteEmpresa, firstNonEmptyStr(body.Proyecto, "MKT Digital"), actor.KeyNombre, approvalURL, tot.TotalUnico, tot.TotalMensual)
|
|
}
|
|
}
|
|
|
|
go s.Webhooks.Emitir(context.Background(), "cotizacion.creada", map[string]any{
|
|
"cotizacionId": cotID, "numero": numero, "estado": "borrador",
|
|
"clienteId": clienteID, "clienteNombre": clienteNombre, "totalUnico": tot.TotalUnico, "totalMensual": tot.TotalMensual,
|
|
})
|
|
|
|
_, respMap, err := s.loadCotizacionFull(r.Context(), cotID, false)
|
|
if err != nil {
|
|
return http.StatusCreated, map[string]any{"id": cotID, "numero": numero, "estado": "borrador"}
|
|
}
|
|
return http.StatusCreated, respMap
|
|
})
|
|
}
|
|
|
|
func (s *Server) handleCotizacionesGet(w http.ResponseWriter, r *http.Request) {
|
|
actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{
|
|
Scopes: []string{"cotizaciones:leer", "cotizaciones:leer_aceptadas"},
|
|
RecursoTipo: "cotizacion",
|
|
})
|
|
if !ok {
|
|
return
|
|
}
|
|
id := chi.URLParam(r, "id")
|
|
soloAceptadas := actor.EsAgenteSoloAceptadas()
|
|
|
|
full, jsonMap, err := s.loadCotizacionFull(r.Context(), id, soloAceptadas)
|
|
if err != nil {
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
writeError(w, http.StatusNotFound, "Cotizacion no encontrada")
|
|
return
|
|
}
|
|
writeError(w, http.StatusInternalServerError, "Error cargando cotizacion")
|
|
return
|
|
}
|
|
|
|
if soloAceptadas && full.Estado != "aceptada" {
|
|
tipo, aid, anom := actor.AuditActor()
|
|
audit.Registrar(r.Context(), s.Pool, audit.Entry{
|
|
ActorTipo: tipo, ActorID: aid, ActorNombre: anom,
|
|
Accion: "cotizacion.leer_bloqueado", RecursoTipo: "cotizacion", RecursoID: id,
|
|
IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: false,
|
|
})
|
|
writeError(w, http.StatusForbidden, "Esta clave solo puede leer cotizaciones aceptadas")
|
|
return
|
|
}
|
|
|
|
if verif := strings.TrimSpace(r.URL.Query().Get("verificarContacto")); verif != "" {
|
|
if !auth.CoincideContacto(verif, derefStr(full.ClienteEmail), derefStr(full.ClienteTelefono)) {
|
|
tipo, aid, anom := actor.AuditActor()
|
|
audit.Registrar(r.Context(), s.Pool, audit.Entry{
|
|
ActorTipo: tipo, ActorID: aid, ActorNombre: anom,
|
|
Accion: "cotizacion.verificar_contacto_fallo", RecursoTipo: "cotizacion", RecursoID: id,
|
|
IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: false,
|
|
})
|
|
writeError(w, http.StatusForbidden, "El contacto proporcionado no coincide con el cliente de esta cotizacion")
|
|
return
|
|
}
|
|
}
|
|
|
|
writeJSON(w, http.StatusOK, jsonMap)
|
|
}
|
|
|
|
func (s *Server) handleCotizacionesUpdate(w http.ResponseWriter, r *http.Request) {
|
|
actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{
|
|
Scopes: []string{"cotizaciones:borrador"},
|
|
RecursoTipo: "cotizacion",
|
|
})
|
|
if !ok {
|
|
return
|
|
}
|
|
id := chi.URLParam(r, "id")
|
|
full, _, err := s.loadCotizacionFull(r.Context(), id, false)
|
|
if err != nil {
|
|
writeError(w, http.StatusNotFound, "Cotizacion no encontrada")
|
|
return
|
|
}
|
|
|
|
var raw map[string]any
|
|
if err := decodeJSON(r, &raw); err != nil {
|
|
writeError(w, http.StatusBadRequest, "JSON invalido")
|
|
return
|
|
}
|
|
|
|
// Single-key { estado } shortcut
|
|
if len(raw) == 1 {
|
|
if nuevoEstado, ok := raw["estado"].(string); ok {
|
|
s.transitionEstado(w, r, actor, full, nuevoEstado, "put")
|
|
return
|
|
}
|
|
}
|
|
|
|
if actor.IsAgent() && full.Estado != "borrador" {
|
|
tipo, aid, anom := actor.AuditActor()
|
|
audit.Registrar(r.Context(), s.Pool, audit.Entry{
|
|
ActorTipo: tipo, ActorID: aid, ActorNombre: anom,
|
|
Accion: "cotizacion.editar_bloqueado", RecursoTipo: "cotizacion", RecursoID: id,
|
|
IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: false,
|
|
})
|
|
writeError(w, http.StatusForbidden, "Los agentes solo pueden editar cotizaciones en borrador")
|
|
return
|
|
}
|
|
|
|
rawBytes, _ := json.Marshal(raw)
|
|
var body struct {
|
|
Fecha string `json:"fecha"`
|
|
Vigencia string `json:"vigencia"`
|
|
Moneda *string `json:"moneda"`
|
|
TipoCambio *string `json:"tipoCambio"`
|
|
Proyecto *string `json:"proyecto"`
|
|
EsquemaPago *string `json:"esquemaPago"`
|
|
Estado *string `json:"estado"`
|
|
IncluirBonos *bool `json:"incluirBonos"`
|
|
IncluirFinanciamiento *bool `json:"incluirFinanciamiento"`
|
|
IncluirIVA *bool `json:"incluirIva"`
|
|
EsDoble *bool `json:"esDoble"`
|
|
OpcionesMetadata map[string]domain.MetaOpcion `json:"opcionesMetadata"`
|
|
Observaciones *string `json:"observaciones"`
|
|
ObservacionesInternas *string `json:"observacionesInternas"`
|
|
AsesorID *string `json:"asesorId"`
|
|
Cliente *struct {
|
|
Nombre string `json:"nombre"`
|
|
Empresa *string `json:"empresa"`
|
|
Puesto *string `json:"puesto"`
|
|
Email *string `json:"email"`
|
|
Telefono *string `json:"telefono"`
|
|
RFC *string `json:"rfc"`
|
|
} `json:"cliente"`
|
|
Servicios []servicioInputDTO `json:"servicios"`
|
|
PlanBucefalo *struct {
|
|
Nivel string `json:"nivel"`
|
|
Precio *float64 `json:"precio"`
|
|
Seleccionado *bool `json:"seleccionado"`
|
|
} `json:"planBucefalo"`
|
|
}
|
|
_ = json.Unmarshal(rawBytes, &body)
|
|
|
|
if body.Estado != nil && *body.Estado != full.Estado {
|
|
tr := domain.ValidarTransicionEstado(domain.ValidarTransicionInput{
|
|
Actual: full.Estado, Nuevo: *body.Estado, Actor: actor.ToDomainActor(), ViaEndpoint: "put", AprobadaAt: full.AprobadaAt,
|
|
})
|
|
if !tr.OK {
|
|
writeError(w, tr.Status, tr.Error)
|
|
return
|
|
}
|
|
}
|
|
|
|
// SoloAdmin guard
|
|
_, hasPlanKey := raw["planBucefalo"]
|
|
draftSvcs := make([]domain.ServicioDraftInput, 0, len(body.Servicios))
|
|
for _, sv := range body.Servicios {
|
|
cid := firstNonEmptyStr(derefStr(sv.ServicioCatalogoID), derefStr(sv.CatalogoID))
|
|
draftSvcs = append(draftSvcs, domain.ServicioDraftInput{CatalogoID: cid, Nombre: derefStr(sv.Nombre), EsPersonalizado: sv.EsPersonalizado})
|
|
}
|
|
soloCheck := domain.EvaluarRestriccionSoloAdmin(domain.EvaluarSoloAdminInput{
|
|
EsAgente: actor.IsAgent(),
|
|
HasPlanBucefalo: hasPlanKey && body.PlanBucefalo != nil,
|
|
Servicios: draftSvcs,
|
|
SoloAdminCatalogIDs: s.soloAdminCatalogIDs(r.Context()),
|
|
})
|
|
if !soloCheck.OK {
|
|
writeJSON(w, http.StatusForbidden, map[string]any{
|
|
"error": "Servicios exclusivos de administrador bloqueados", "reason": "solo_admin_restricted", "itemsBloqueados": soloCheck.ItemsBloqueados,
|
|
})
|
|
return
|
|
}
|
|
|
|
tx, err := s.Pool.Begin(r.Context())
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "Error iniciando transaccion")
|
|
return
|
|
}
|
|
defer tx.Rollback(r.Context())
|
|
|
|
if body.Cliente != nil && strings.TrimSpace(body.Cliente.Nombre) != "" {
|
|
_, _ = tx.Exec(r.Context(), `
|
|
UPDATE "Cliente" SET "nombre"=$1, "empresa"=$2, "puesto"=$3, "email"=$4, "telefono"=$5, "rfc"=$6, "updatedAt"=NOW()
|
|
WHERE "id" = $7
|
|
`, strings.TrimSpace(body.Cliente.Nombre), trimPtr(body.Cliente.Empresa), trimPtr(body.Cliente.Puesto),
|
|
trimPtr(body.Cliente.Email), trimPtr(body.Cliente.Telefono), trimPtr(body.Cliente.RFC), full.ClienteID)
|
|
}
|
|
|
|
sets := []string{`"updatedAt" = NOW()`}
|
|
args := []any{}
|
|
add := func(col string, val any) {
|
|
args = append(args, val)
|
|
sets = append(sets, fmt.Sprintf(`"%s" = $%d`, col, len(args)))
|
|
}
|
|
if body.Fecha != "" {
|
|
if t, err := parseFlexibleDate(body.Fecha); err == nil {
|
|
add("fecha", t)
|
|
}
|
|
}
|
|
if body.Vigencia != "" {
|
|
if t, err := parseFlexibleDate(body.Vigencia); err == nil {
|
|
add("vigencia", t)
|
|
}
|
|
}
|
|
if body.Moneda != nil {
|
|
add("moneda", *body.Moneda)
|
|
}
|
|
if body.TipoCambio != nil {
|
|
add("tipoCambio", *body.TipoCambio)
|
|
}
|
|
if body.Proyecto != nil {
|
|
add("proyecto", *body.Proyecto)
|
|
}
|
|
if body.EsquemaPago != nil {
|
|
add("esquemaPago", *body.EsquemaPago)
|
|
}
|
|
if body.IncluirBonos != nil {
|
|
add("incluirBonos", *body.IncluirBonos)
|
|
}
|
|
if body.IncluirFinanciamiento != nil {
|
|
add("incluirFinanciamiento", *body.IncluirFinanciamiento)
|
|
}
|
|
if body.IncluirIVA != nil {
|
|
add("incluirIva", *body.IncluirIVA)
|
|
}
|
|
if body.EsDoble != nil {
|
|
add("esDoble", *body.EsDoble)
|
|
}
|
|
if _, ok := raw["opcionesMetadata"]; ok {
|
|
b, _ := json.Marshal(body.OpcionesMetadata)
|
|
add("opcionesMetadata", b)
|
|
}
|
|
if _, ok := raw["observaciones"]; ok {
|
|
add("observaciones", body.Observaciones)
|
|
}
|
|
if _, ok := raw["observacionesInternas"]; ok {
|
|
add("observacionesInternas", body.ObservacionesInternas)
|
|
}
|
|
if body.AsesorID != nil && *body.AsesorID != "" {
|
|
add("asesorId", *body.AsesorID)
|
|
}
|
|
if body.Estado != nil {
|
|
add("estado", *body.Estado)
|
|
}
|
|
|
|
args = append(args, id)
|
|
if _, err := tx.Exec(r.Context(), fmt.Sprintf(`UPDATE "Cotizacion" SET %s WHERE "id" = $%d`, strings.Join(sets, ", "), len(args)), args...); err != nil {
|
|
writeError(w, http.StatusInternalServerError, "Error actualizando cotizacion")
|
|
return
|
|
}
|
|
|
|
if _, hasSvcs := raw["servicios"]; hasSvcs {
|
|
_, _ = tx.Exec(r.Context(), `DELETE FROM "ServicioCotizado" WHERE "cotizacionId" = $1`, id)
|
|
for _, sv := range body.Servicios {
|
|
scid := nullableTrim(firstNonEmptyStr(derefStr(sv.ServicioCatalogoID), derefStr(sv.CatalogoID)))
|
|
sel := true
|
|
if sv.Seleccionado != nil {
|
|
sel = *sv.Seleccionado
|
|
}
|
|
entJSON, _ := json.Marshal(nonNilSlice(sv.Entregables))
|
|
benJSON, _ := json.Marshal(nonNilSlice(sv.Beneficios))
|
|
_, err = tx.Exec(r.Context(), `
|
|
INSERT INTO "ServicioCotizado" (
|
|
"id", "cotizacionId", "servicioCatalogoId", "nombre", "esPersonalizado",
|
|
"horas", "tarifaHora", "modeloCobro", "montoMinimo", "horasIncluidas",
|
|
"opcion", "fase", "tipoPago", "precio", "tiempoEntrega",
|
|
"entregables", "beneficios", "notas", "seleccionado", "createdAt", "updatedAt"
|
|
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,NOW(),NOW())
|
|
`, db.NewID(), id, scid, sv.Nombre, sv.EsPersonalizado,
|
|
sv.Horas, sv.TarifaHora, firstNonEmptyStr(sv.ModeloCobro, "fijo"), sv.MontoMinimo, sv.HorasIncluidas,
|
|
sv.Opcion, sv.Fase, firstNonEmptyStr(sv.TipoPago, "unico"), sv.Precio, firstNonEmptyStr(sv.TiempoEntrega, "4 - 10 dias"),
|
|
entJSON, benJSON, sv.Notas, sel)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "Error actualizando servicios")
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
if hasPlanKey {
|
|
_, _ = tx.Exec(r.Context(), `DELETE FROM "PlanBucefaloCotizacion" WHERE "cotizacionId" = $1`, id)
|
|
if body.PlanBucefalo != nil {
|
|
nivel := firstNonEmptyStr(body.PlanBucefalo.Nivel, "basico")
|
|
precio := domain.BucefaloPrecio(nivel)
|
|
if body.PlanBucefalo.Precio != nil {
|
|
precio = *body.PlanBucefalo.Precio
|
|
}
|
|
sel := true
|
|
if body.PlanBucefalo.Seleccionado != nil {
|
|
sel = *body.PlanBucefalo.Seleccionado
|
|
}
|
|
_, _ = tx.Exec(r.Context(), `
|
|
INSERT INTO "PlanBucefaloCotizacion" ("id", "cotizacionId", "nivel", "precio", "seleccionado", "createdAt", "updatedAt")
|
|
VALUES ($1,$2,$3,$4,$5,NOW(),NOW())
|
|
`, db.NewID(), id, nivel, precio, sel)
|
|
}
|
|
}
|
|
|
|
if err := tx.Commit(r.Context()); err != nil {
|
|
writeError(w, http.StatusInternalServerError, "Error confirmando cambios")
|
|
return
|
|
}
|
|
|
|
tipo, aid, anom := actor.AuditActor()
|
|
audit.Registrar(r.Context(), s.Pool, audit.Entry{
|
|
ActorTipo: tipo, ActorID: aid, ActorNombre: anom,
|
|
Accion: "cotizacion.actualizar", RecursoTipo: "cotizacion", RecursoID: id,
|
|
IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true,
|
|
})
|
|
|
|
_, updatedMap, _ := s.loadCotizacionFull(r.Context(), id, false)
|
|
writeJSON(w, http.StatusOK, updatedMap)
|
|
}
|
|
|
|
func (s *Server) handleCotizacionesDelete(w http.ResponseWriter, r *http.Request) {
|
|
actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{
|
|
StaffOnly: true,
|
|
AccionBloqueo: "cotizacion.eliminar_bloqueado",
|
|
RecursoTipo: "cotizacion",
|
|
})
|
|
if !ok {
|
|
return
|
|
}
|
|
id := chi.URLParam(r, "id")
|
|
tag, err := s.Pool.Exec(r.Context(), `DELETE FROM "Cotizacion" WHERE "id" = $1`, id)
|
|
if err != nil || tag.RowsAffected() == 0 {
|
|
writeError(w, http.StatusNotFound, "Cotizacion no encontrada")
|
|
return
|
|
}
|
|
tipo, aid, anom := actor.AuditActor()
|
|
audit.Registrar(r.Context(), s.Pool, audit.Entry{
|
|
ActorTipo: tipo, ActorID: aid, ActorNombre: anom,
|
|
Accion: "cotizacion.eliminar", RecursoTipo: "cotizacion", RecursoID: id,
|
|
IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true,
|
|
})
|
|
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
|
|
}
|
|
|
|
func (s *Server) handleCotizacionSolicitarAprobacion(w http.ResponseWriter, r *http.Request) {
|
|
actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{
|
|
Scopes: []string{"cotizaciones:borrador"},
|
|
RecursoTipo: "cotizacion",
|
|
})
|
|
if !ok {
|
|
return
|
|
}
|
|
id := chi.URLParam(r, "id")
|
|
full, _, err := s.loadCotizacionFull(r.Context(), id, false)
|
|
if err != nil {
|
|
writeError(w, http.StatusNotFound, "Cotizacion no encontrada")
|
|
return
|
|
}
|
|
if full.Estado != "borrador" {
|
|
writeError(w, http.StatusConflict, "Solo se puede solicitar aprobacion para cotizaciones en borrador")
|
|
return
|
|
}
|
|
approvalURL, err := s.crearEnlaceAprobacion(r.Context(), id)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "Error generando enlace de aprobacion")
|
|
return
|
|
}
|
|
|
|
tot := domain.CalcularTotalesCotizacion(full.ServiciosCalc, full.IncluirIVA)
|
|
_, _, anom := actor.AuditActor()
|
|
go s.Notify.NotificarJarethBorrador(context.Background(), id, full.Numero, full.ClienteNombre, derefStr(full.ClienteEmpresa), full.Proyecto, anom, approvalURL, tot.TotalUnico, tot.TotalMensual)
|
|
|
|
tipo, aid, _ := actor.AuditActor()
|
|
audit.Registrar(r.Context(), s.Pool, audit.Entry{
|
|
ActorTipo: tipo, ActorID: aid, ActorNombre: anom,
|
|
Accion: "cotizacion.solicitar_aprobacion", RecursoTipo: "cotizacion", RecursoID: id,
|
|
IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true,
|
|
})
|
|
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "mensaje": "Solicitud de aprobacion enviada al administrador"})
|
|
}
|
|
|
|
func (s *Server) handleCotizacionAprobar(w http.ResponseWriter, r *http.Request) {
|
|
actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{
|
|
AdminOnly: true,
|
|
AccionBloqueo: "cotizacion.aprobar_bloqueado",
|
|
RecursoTipo: "cotizacion",
|
|
})
|
|
if !ok {
|
|
return
|
|
}
|
|
// Redundant iron-clad human admin check
|
|
if !actor.IsAdmin() {
|
|
writeError(w, http.StatusForbidden, "Solo un administrador humano puede aprobar cotizaciones")
|
|
return
|
|
}
|
|
id := chi.URLParam(r, "id")
|
|
full, _, err := s.loadCotizacionFull(r.Context(), id, false)
|
|
if err != nil {
|
|
writeError(w, http.StatusNotFound, "Cotizacion no encontrada")
|
|
return
|
|
}
|
|
s.transitionEstado(w, r, actor, full, "aprobada", "aprobar")
|
|
}
|
|
|
|
func (s *Server) handleCotizacionEstado(w http.ResponseWriter, r *http.Request) {
|
|
actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{
|
|
StaffOnly: true,
|
|
AccionBloqueo: "cotizacion.estado_bloqueado",
|
|
RecursoTipo: "cotizacion",
|
|
})
|
|
if !ok {
|
|
return
|
|
}
|
|
id := chi.URLParam(r, "id")
|
|
full, _, err := s.loadCotizacionFull(r.Context(), id, false)
|
|
if err != nil {
|
|
writeError(w, http.StatusNotFound, "Cotizacion no encontrada")
|
|
return
|
|
}
|
|
var body struct {
|
|
Estado string `json:"estado"`
|
|
}
|
|
if err := decodeJSON(r, &body); err != nil {
|
|
writeError(w, http.StatusBadRequest, "JSON invalido")
|
|
return
|
|
}
|
|
s.transitionEstado(w, r, actor, full, body.Estado, "estado")
|
|
}
|
|
|
|
func (s *Server) transitionEstado(w http.ResponseWriter, r *http.Request, actor *auth.Actor, full *cotizacionFull, nuevo, via string) {
|
|
tr := domain.ValidarTransicionEstado(domain.ValidarTransicionInput{
|
|
Actual: full.Estado, Nuevo: nuevo, Actor: actor.ToDomainActor(), ViaEndpoint: via, AprobadaAt: full.AprobadaAt,
|
|
})
|
|
tipo, aid, anom := actor.AuditActor()
|
|
if !tr.OK {
|
|
acc := "cotizacion.estado_bloqueado"
|
|
if nuevo == "aprobada" {
|
|
acc = "cotizacion.aprobar_bloqueado"
|
|
}
|
|
audit.Registrar(r.Context(), s.Pool, audit.Entry{
|
|
ActorTipo: tipo, ActorID: aid, ActorNombre: anom,
|
|
Accion: acc, RecursoTipo: "cotizacion", RecursoID: full.ID,
|
|
IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: false,
|
|
Detalle: map[string]any{"actual": full.Estado, "nuevo": nuevo, "error": tr.Error},
|
|
})
|
|
writeError(w, tr.Status, tr.Error)
|
|
return
|
|
}
|
|
|
|
now := time.Now()
|
|
switch nuevo {
|
|
case "aprobada":
|
|
_, _ = s.Pool.Exec(r.Context(), `UPDATE "ApprovalToken" SET "usadoAt" = $1 WHERE "cotizacionId" = $2 AND "usadoAt" IS NULL`, now, full.ID)
|
|
_, _ = s.Pool.Exec(r.Context(), `
|
|
UPDATE "Cotizacion" SET "estado"='aprobada', "aprobadaAt"=$1, "aprobadaPorId"=$2, "aprobacionMetodo"='web_admin', "updatedAt"=NOW()
|
|
WHERE "id" = $3
|
|
`, now, actor.UserID, full.ID)
|
|
case "enviada":
|
|
_, _ = s.Pool.Exec(r.Context(), `
|
|
UPDATE "Cotizacion" SET "estado"='enviada', "enviadaAt"=$1, "enviadaPor"=$2, "updatedAt"=NOW() WHERE "id" = $3
|
|
`, now, anom, full.ID)
|
|
case "aceptada":
|
|
_, _ = s.Pool.Exec(r.Context(), `UPDATE "Cotizacion" SET "estado"='aceptada', "aceptadaAt"=$1, "updatedAt"=NOW() WHERE "id" = $2`, now, full.ID)
|
|
case "rechazada":
|
|
_, _ = s.Pool.Exec(r.Context(), `UPDATE "Cotizacion" SET "estado"='rechazada', "rechazadaAt"=$1, "updatedAt"=NOW() WHERE "id" = $2`, now, full.ID)
|
|
case "vencida":
|
|
_, _ = s.Pool.Exec(r.Context(), `UPDATE "Cotizacion" SET "estado"='vencida', "vencidaAt"=$1, "updatedAt"=NOW() WHERE "id" = $2`, now, full.ID)
|
|
case "borrador":
|
|
_, _ = s.Pool.Exec(r.Context(), `
|
|
UPDATE "Cotizacion" SET "estado"='borrador', "aprobadaAt"=NULL, "aprobadaPorId"=NULL, "aprobacionMetodo"=NULL, "updatedAt"=NOW() WHERE "id" = $1
|
|
`, full.ID)
|
|
}
|
|
|
|
acc := "cotizacion.estado_" + nuevo
|
|
if nuevo == "aprobada" {
|
|
acc = "cotizacion.aprobar"
|
|
}
|
|
audit.Registrar(r.Context(), s.Pool, audit.Entry{
|
|
ActorTipo: tipo, ActorID: aid, ActorNombre: anom,
|
|
Accion: acc, RecursoTipo: "cotizacion", RecursoID: full.ID,
|
|
IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true,
|
|
Detalle: map[string]any{"anterior": full.Estado, "nuevo": nuevo},
|
|
})
|
|
|
|
if nuevo != "borrador" && nuevo != full.Estado {
|
|
go s.Webhooks.Emitir(context.Background(), "cotizacion."+nuevo, map[string]any{
|
|
"cotizacionId": full.ID, "numero": full.Numero, "estado": nuevo,
|
|
})
|
|
}
|
|
|
|
_, updatedMap, _ := s.loadCotizacionFull(r.Context(), full.ID, false)
|
|
writeJSON(w, http.StatusOK, updatedMap)
|
|
}
|
|
|
|
func (s *Server) handleCotizacionEnviar(w http.ResponseWriter, r *http.Request) {
|
|
actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{
|
|
Scopes: []string{"cotizaciones:enviar"},
|
|
AccionBloqueo: "cotizacion.enviar_bloqueado",
|
|
RecursoTipo: "cotizacion",
|
|
})
|
|
if !ok {
|
|
return
|
|
}
|
|
id := chi.URLParam(r, "id")
|
|
idempotency.Execute(r.Context(), s.Pool, w, r, actor, func(rawBody []byte) (int, any) {
|
|
var body struct {
|
|
Canal string `json:"canal"`
|
|
Destino string `json:"destino"`
|
|
VerificarContacto string `json:"verificarContacto"`
|
|
FallbackEmail *bool `json:"fallbackEmail"`
|
|
Mensaje string `json:"mensaje"`
|
|
}
|
|
_ = json.Unmarshal(rawBody, &body)
|
|
canal := firstNonEmptyStr(body.Canal, "whatsapp_chatwoot")
|
|
fallbackEmail := true
|
|
if body.FallbackEmail != nil {
|
|
fallbackEmail = *body.FallbackEmail
|
|
}
|
|
|
|
full, _, err := s.loadCotizacionFull(r.Context(), id, false)
|
|
if err != nil {
|
|
return http.StatusNotFound, map[string]any{"error": "Cotizacion no encontrada"}
|
|
}
|
|
|
|
tipo, aid, anom := actor.AuditActor()
|
|
// Hard approval guard
|
|
tr := domain.ValidarTransicionEstado(domain.ValidarTransicionInput{
|
|
Actual: full.Estado, Nuevo: "enviada", Actor: actor.ToDomainActor(), ViaEndpoint: "enviar", AprobadaAt: full.AprobadaAt,
|
|
})
|
|
if !tr.OK {
|
|
audit.Registrar(r.Context(), s.Pool, audit.Entry{
|
|
ActorTipo: tipo, ActorID: aid, ActorNombre: anom,
|
|
Accion: "cotizacion.enviar_bloqueado", RecursoTipo: "cotizacion", RecursoID: id,
|
|
IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: false,
|
|
Detalle: map[string]any{"estado": full.Estado, "error": tr.Error},
|
|
})
|
|
return tr.Status, map[string]any{"error": tr.Error}
|
|
}
|
|
|
|
if canal == "manual" && !actor.IsAdmin() {
|
|
return http.StatusForbidden, map[string]any{"error": "El canal manual es exclusivo del administrador humano"}
|
|
}
|
|
|
|
if strings.TrimSpace(body.VerificarContacto) != "" {
|
|
if !auth.CoincideContacto(body.VerificarContacto, derefStr(full.ClienteEmail), derefStr(full.ClienteTelefono)) {
|
|
audit.Registrar(r.Context(), s.Pool, audit.Entry{
|
|
ActorTipo: tipo, ActorID: aid, ActorNombre: anom,
|
|
Accion: "cotizacion.enviar_contacto_bloqueado", RecursoTipo: "cotizacion", RecursoID: id,
|
|
IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: false,
|
|
})
|
|
return http.StatusForbidden, map[string]any{"error": "El contacto no coincide con el cliente de la cotizacion"}
|
|
}
|
|
}
|
|
|
|
pdfBytes, err := s.buildQuotePDFBytes(r.Context(), full)
|
|
if err != nil {
|
|
return http.StatusInternalServerError, map[string]any{"error": "Error generando PDF de cotizacion"}
|
|
}
|
|
|
|
canalFinal := canal
|
|
destinoFinal := strings.TrimSpace(body.Destino)
|
|
|
|
switch canal {
|
|
case "whatsapp_chatwoot":
|
|
if destinoFinal == "" {
|
|
destinoFinal = derefStr(full.ClienteTelefono)
|
|
}
|
|
waRes := s.Webhooks.InvocarEnvioWhatsAppN8n(r.Context(), map[string]any{
|
|
"cotizacionId": full.ID,
|
|
"numero": full.Numero,
|
|
"clienteNombre": full.ClienteNombre,
|
|
"telefono": destinoFinal,
|
|
"email": derefStr(full.ClienteEmail),
|
|
"mensaje": body.Mensaje,
|
|
"pdfFilename": fmt.Sprintf("Cotizacion_%s.pdf", domain.SanitizeFilename(full.Numero)),
|
|
"pdfBase64": base64.StdEncoding.EncodeToString(pdfBytes),
|
|
})
|
|
if !waRes.OK {
|
|
if waRes.Outside24h {
|
|
if fallbackEmail && derefStr(full.ClienteEmail) != "" {
|
|
sent := s.Notify.EnviarCotizacionPorCorreo(derefStr(full.ClienteEmail), full.ClienteNombre, full.Numero, full.Proyecto, pdfBytes)
|
|
if sent {
|
|
canalFinal = "email"
|
|
destinoFinal = derefStr(full.ClienteEmail)
|
|
} else {
|
|
return http.StatusBadGateway, map[string]any{"error": "WhatsApp fuera de ventana 24h y fallo el envio por correo"}
|
|
}
|
|
} else {
|
|
audit.Registrar(r.Context(), s.Pool, audit.Entry{
|
|
ActorTipo: tipo, ActorID: aid, ActorNombre: anom,
|
|
Accion: "cotizacion.enviar_fuera_ventana", RecursoTipo: "cotizacion", RecursoID: id,
|
|
IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: false,
|
|
})
|
|
go s.Notify.NotificarJarethWhatsAppFueraVentana(context.Background(), full.Numero, full.ClienteNombre, destinoFinal)
|
|
return http.StatusConflict, map[string]any{
|
|
"error": "WhatsApp fuera de ventana de 24 horas",
|
|
"reason": "outside_24h_window",
|
|
}
|
|
}
|
|
} else {
|
|
audit.Registrar(r.Context(), s.Pool, audit.Entry{
|
|
ActorTipo: tipo, ActorID: aid, ActorNombre: anom,
|
|
Accion: "cotizacion.enviar_error", RecursoTipo: "cotizacion", RecursoID: id,
|
|
IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: false,
|
|
Detalle: map[string]any{"error": waRes.ErrorMessage},
|
|
})
|
|
return http.StatusBadGateway, map[string]any{"error": "Error enviando por WhatsApp: " + waRes.ErrorMessage}
|
|
}
|
|
}
|
|
case "email":
|
|
if destinoFinal == "" {
|
|
destinoFinal = derefStr(full.ClienteEmail)
|
|
}
|
|
if destinoFinal == "" {
|
|
return http.StatusBadRequest, map[string]any{"error": "El cliente no tiene correo electronico configurado"}
|
|
}
|
|
if !s.Notify.EnviarCotizacionPorCorreo(destinoFinal, full.ClienteNombre, full.Numero, full.Proyecto, pdfBytes) {
|
|
return http.StatusBadGateway, map[string]any{"error": "No se pudo enviar el correo (verifica configuracion SMTP)"}
|
|
}
|
|
case "manual":
|
|
if destinoFinal == "" {
|
|
destinoFinal = firstNonEmptyStr(derefStr(full.ClienteEmail), derefStr(full.ClienteTelefono), "manual")
|
|
}
|
|
default:
|
|
return http.StatusBadRequest, map[string]any{"error": "Canal invalido (usa whatsapp_chatwoot, email o manual)"}
|
|
}
|
|
|
|
now := time.Now()
|
|
_, _ = s.Pool.Exec(r.Context(), `
|
|
UPDATE "Cotizacion"
|
|
SET "estado"='enviada', "enviadaAt"=$1, "enviadaPor"=$2, "enviadaCanal"=$3, "enviadaDestino"=$4, "updatedAt"=NOW()
|
|
WHERE "id" = $5
|
|
`, now, anom, canalFinal, destinoFinal, id)
|
|
|
|
audit.Registrar(r.Context(), s.Pool, audit.Entry{
|
|
ActorTipo: tipo, ActorID: aid, ActorNombre: anom,
|
|
Accion: "cotizacion.enviar", RecursoTipo: "cotizacion", RecursoID: id,
|
|
IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true,
|
|
Detalle: map[string]any{"canal": canalFinal, "destino": destinoFinal},
|
|
})
|
|
go s.Webhooks.Emitir(context.Background(), "cotizacion.enviada", map[string]any{
|
|
"cotizacionId": id, "numero": full.Numero, "canal": canalFinal, "destino": destinoFinal, "enviadaAt": now.UTC().Format(time.RFC3339),
|
|
})
|
|
|
|
return http.StatusOK, map[string]any{
|
|
"ok": true, "cotizacionId": id, "numero": full.Numero, "estado": "enviada",
|
|
"canal": canalFinal, "destino": destinoFinal, "enviadaAt": now,
|
|
}
|
|
})
|
|
}
|
|
|
|
func (s *Server) handleCotizacionPrecio(w http.ResponseWriter, r *http.Request) {
|
|
actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{
|
|
Scopes: []string{"cotizaciones:borrador"},
|
|
RecursoTipo: "cotizacion",
|
|
})
|
|
if !ok {
|
|
return
|
|
}
|
|
id := chi.URLParam(r, "id")
|
|
var estado string
|
|
if err := s.Pool.QueryRow(r.Context(), `SELECT "estado" FROM "Cotizacion" WHERE "id" = $1`, id).Scan(&estado); err != nil {
|
|
writeError(w, http.StatusNotFound, "Cotizacion no encontrada")
|
|
return
|
|
}
|
|
if actor.IsAgent() && estado != "borrador" {
|
|
tipo, aid, anom := actor.AuditActor()
|
|
audit.Registrar(r.Context(), s.Pool, audit.Entry{
|
|
ActorTipo: tipo, ActorID: aid, ActorNombre: anom,
|
|
Accion: "cotizacion.editar_precio_bloqueado", RecursoTipo: "cotizacion", RecursoID: id,
|
|
IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: false,
|
|
})
|
|
writeError(w, http.StatusForbidden, "Los agentes solo pueden editar precios en borrador")
|
|
return
|
|
}
|
|
var body struct {
|
|
ServicioID string `json:"servicioId"`
|
|
Precio float64 `json:"precio"`
|
|
}
|
|
if err := decodeJSON(r, &body); err != nil || body.ServicioID == "" || body.Precio < 0 {
|
|
writeError(w, http.StatusBadRequest, "servicioId y precio >= 0 son requeridos")
|
|
return
|
|
}
|
|
tag, err := s.Pool.Exec(r.Context(), `
|
|
UPDATE "ServicioCotizado" SET "precio" = $1, "updatedAt" = NOW()
|
|
WHERE "id" = $2 AND "cotizacionId" = $3
|
|
`, body.Precio, body.ServicioID, id)
|
|
if err != nil || tag.RowsAffected() == 0 {
|
|
writeError(w, http.StatusNotFound, "Partida no encontrada")
|
|
return
|
|
}
|
|
tipo, aid, anom := actor.AuditActor()
|
|
audit.Registrar(r.Context(), s.Pool, audit.Entry{
|
|
ActorTipo: tipo, ActorID: aid, ActorNombre: anom,
|
|
Accion: "cotizacion.actualizar_precio", RecursoTipo: "cotizacion", RecursoID: id,
|
|
IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true,
|
|
Detalle: map[string]any{"servicioId": body.ServicioID, "precio": body.Precio},
|
|
})
|
|
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "servicioId": body.ServicioID, "precio": body.Precio})
|
|
}
|
|
|
|
// ── Registro de Horas & Nota de Horas PDF ────────────────────────────────────
|
|
|
|
func (s *Server) handleHorasList(w http.ResponseWriter, r *http.Request) {
|
|
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "horas"}); !ok {
|
|
return
|
|
}
|
|
cotID := chi.URLParam(r, "id")
|
|
q := r.URL.Query()
|
|
conds := []string{`"cotizacionId" = $1`}
|
|
args := []any{cotID}
|
|
if from := strings.TrimSpace(q.Get("from")); from != "" {
|
|
if t, err := time.Parse("2006-01-02", from); err == nil {
|
|
args = append(args, t)
|
|
conds = append(conds, fmt.Sprintf(`"fecha" >= $%d`, len(args)))
|
|
}
|
|
}
|
|
if to := strings.TrimSpace(q.Get("to")); to != "" {
|
|
if t, err := time.Parse("2006-01-02", to); err == nil {
|
|
args = append(args, t.Add(24*time.Hour))
|
|
conds = append(conds, fmt.Sprintf(`"fecha" < $%d`, len(args)))
|
|
}
|
|
}
|
|
rows, err := s.Pool.Query(r.Context(), `
|
|
SELECT "id", "cotizacionId", "fecha", "horaInicio", "horaFin", "horas", "tarifaHora", "descripcion", "estadoPago", "fechaPago", "createdAt"
|
|
FROM "RegistroHoras"
|
|
WHERE `+strings.Join(conds, " AND ")+`
|
|
ORDER BY "fecha" DESC, "horaInicio" DESC
|
|
`, args...)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "Error listando horas")
|
|
return
|
|
}
|
|
defer rows.Close()
|
|
list := []map[string]any{}
|
|
for rows.Next() {
|
|
var id, qid, hi, hf, desc, ep string
|
|
var fecha, createdAt time.Time
|
|
var fechaPago *time.Time
|
|
var hrs, th float64
|
|
if rows.Scan(&id, &qid, &fecha, &hi, &hf, &hrs, &th, &desc, &ep, &fechaPago, &createdAt) == nil {
|
|
list = append(list, map[string]any{
|
|
"id": id, "cotizacionId": qid, "fecha": fecha, "horaInicio": hi, "horaFin": hf,
|
|
"horas": hrs, "tarifaHora": th, "descripcion": desc, "estadoPago": ep,
|
|
"fechaPago": fechaPago, "createdAt": createdAt,
|
|
})
|
|
}
|
|
}
|
|
writeJSON(w, http.StatusOK, list)
|
|
}
|
|
|
|
func (s *Server) handleHorasCreate(w http.ResponseWriter, r *http.Request) {
|
|
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "horas"}); !ok {
|
|
return
|
|
}
|
|
cotID := chi.URLParam(r, "id")
|
|
full, _, err := s.loadCotizacionFull(r.Context(), cotID, false)
|
|
if err != nil {
|
|
writeError(w, http.StatusNotFound, "Cotizacion no encontrada")
|
|
return
|
|
}
|
|
if !domain.EsCotizacionPorTiempo(full.ServiciosCalc) {
|
|
writeError(w, http.StatusBadRequest, "Esta cotizacion no tiene servicios cobrados por tiempo")
|
|
return
|
|
}
|
|
var body struct {
|
|
Fecha string `json:"fecha"`
|
|
HoraInicio string `json:"horaInicio"`
|
|
HoraFin string `json:"horaFin"`
|
|
TarifaHora *float64 `json:"tarifaHora"`
|
|
Descripcion string `json:"descripcion"`
|
|
}
|
|
if err := decodeJSON(r, &body); err != nil {
|
|
writeError(w, http.StatusBadRequest, "JSON invalido")
|
|
return
|
|
}
|
|
fecha, err := domain.FechaRegistroDesdeISO(body.Fecha)
|
|
if err != nil {
|
|
writeError(w, http.StatusBadRequest, "Fecha invalida (YYYY-MM-DD)")
|
|
return
|
|
}
|
|
horas := domain.CalcularHorasRango(body.HoraInicio, body.HoraFin)
|
|
if horas <= 0 {
|
|
writeError(w, http.StatusBadRequest, "Rango horario invalido (horaFin debe ser mayor a horaInicio)")
|
|
return
|
|
}
|
|
desc := strings.TrimSpace(body.Descripcion)
|
|
if desc == "" {
|
|
writeError(w, http.StatusBadRequest, "La descripcion es obligatoria")
|
|
return
|
|
}
|
|
tarifa := domain.TarifaHoraSugerida(full.ServiciosCalc)
|
|
if body.TarifaHora != nil && *body.TarifaHora >= 0 {
|
|
tarifa = *body.TarifaHora
|
|
}
|
|
id := db.NewID()
|
|
_, err = s.Pool.Exec(r.Context(), `
|
|
INSERT INTO "RegistroHoras" ("id", "cotizacionId", "fecha", "horaInicio", "horaFin", "horas", "tarifaHora", "descripcion", "estadoPago", "createdAt", "updatedAt")
|
|
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,'por_pagar',NOW(),NOW())
|
|
`, id, cotID, fecha, body.HoraInicio, body.HoraFin, horas, tarifa, desc)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "Error registrando horas")
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusCreated, map[string]any{
|
|
"id": id, "cotizacionId": cotID, "fecha": fecha, "horaInicio": body.HoraInicio, "horaFin": body.HoraFin,
|
|
"horas": horas, "tarifaHora": tarifa, "descripcion": desc, "estadoPago": "por_pagar", "fechaPago": nil,
|
|
})
|
|
}
|
|
|
|
func (s *Server) handleHorasUpdate(w http.ResponseWriter, r *http.Request) {
|
|
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "horas"}); !ok {
|
|
return
|
|
}
|
|
cotID := chi.URLParam(r, "id")
|
|
regID := chi.URLParam(r, "registroId")
|
|
var body struct {
|
|
Fecha string `json:"fecha"`
|
|
HoraInicio string `json:"horaInicio"`
|
|
HoraFin string `json:"horaFin"`
|
|
TarifaHora *float64 `json:"tarifaHora"`
|
|
Descripcion string `json:"descripcion"`
|
|
}
|
|
if err := decodeJSON(r, &body); err != nil {
|
|
writeError(w, http.StatusBadRequest, "JSON invalido")
|
|
return
|
|
}
|
|
fecha, err := domain.FechaRegistroDesdeISO(body.Fecha)
|
|
if err != nil {
|
|
writeError(w, http.StatusBadRequest, "Fecha invalida")
|
|
return
|
|
}
|
|
horas := domain.CalcularHorasRango(body.HoraInicio, body.HoraFin)
|
|
if horas <= 0 {
|
|
writeError(w, http.StatusBadRequest, "Rango horario invalido")
|
|
return
|
|
}
|
|
tarifa := 0.0
|
|
if body.TarifaHora != nil {
|
|
tarifa = *body.TarifaHora
|
|
}
|
|
tag, err := s.Pool.Exec(r.Context(), `
|
|
UPDATE "RegistroHoras"
|
|
SET "fecha"=$1, "horaInicio"=$2, "horaFin"=$3, "horas"=$4, "tarifaHora"=$5, "descripcion"=$6, "updatedAt"=NOW()
|
|
WHERE "id"=$7 AND "cotizacionId"=$8
|
|
`, fecha, body.HoraInicio, body.HoraFin, horas, tarifa, strings.TrimSpace(body.Descripcion), regID, cotID)
|
|
if err != nil || tag.RowsAffected() == 0 {
|
|
writeError(w, http.StatusNotFound, "Registro no encontrado")
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]any{
|
|
"id": regID, "cotizacionId": cotID, "fecha": fecha, "horaInicio": body.HoraInicio, "horaFin": body.HoraFin,
|
|
"horas": horas, "tarifaHora": tarifa, "descripcion": strings.TrimSpace(body.Descripcion),
|
|
})
|
|
}
|
|
|
|
func (s *Server) handleHorasEstadoPago(w http.ResponseWriter, r *http.Request) {
|
|
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "horas"}); !ok {
|
|
return
|
|
}
|
|
cotID := chi.URLParam(r, "id")
|
|
regID := chi.URLParam(r, "registroId")
|
|
var body struct {
|
|
EstadoPago string `json:"estadoPago"`
|
|
}
|
|
if err := decodeJSON(r, &body); err != nil || (body.EstadoPago != "por_pagar" && body.EstadoPago != "pagada") {
|
|
writeError(w, http.StatusBadRequest, "estadoPago debe ser por_pagar o pagada")
|
|
return
|
|
}
|
|
var fp *time.Time
|
|
if body.EstadoPago == "pagada" {
|
|
now := time.Now()
|
|
fp = &now
|
|
}
|
|
tag, err := s.Pool.Exec(r.Context(), `
|
|
UPDATE "RegistroHoras" SET "estadoPago"=$1, "fechaPago"=$2, "updatedAt"=NOW()
|
|
WHERE "id"=$3 AND "cotizacionId"=$4
|
|
`, body.EstadoPago, fp, regID, cotID)
|
|
if err != nil || tag.RowsAffected() == 0 {
|
|
writeError(w, http.StatusNotFound, "Registro no encontrado")
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]any{"id": regID, "estadoPago": body.EstadoPago, "fechaPago": fp})
|
|
}
|
|
|
|
func (s *Server) handleHorasDelete(w http.ResponseWriter, r *http.Request) {
|
|
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "horas"}); !ok {
|
|
return
|
|
}
|
|
cotID := chi.URLParam(r, "id")
|
|
regID := chi.URLParam(r, "registroId")
|
|
tag, err := s.Pool.Exec(r.Context(), `DELETE FROM "RegistroHoras" WHERE "id"=$1 AND "cotizacionId"=$2`, regID, cotID)
|
|
if err != nil || tag.RowsAffected() == 0 {
|
|
writeError(w, http.StatusNotFound, "Registro no encontrado")
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
|
|
}
|
|
|
|
func (s *Server) handleNotaHorasPDF(w http.ResponseWriter, r *http.Request) {
|
|
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "horas"}); !ok {
|
|
return
|
|
}
|
|
cotID := chi.URLParam(r, "id")
|
|
full, _, err := s.loadCotizacionFull(r.Context(), cotID, false)
|
|
if err != nil {
|
|
writeError(w, http.StatusNotFound, "Cotizacion no encontrada")
|
|
return
|
|
}
|
|
var body struct {
|
|
Estado string `json:"estado"` // por_pagar | pagada | todas
|
|
Modo string `json:"modo"` // detalle | dia | semana | mes
|
|
From string `json:"from"`
|
|
To string `json:"to"`
|
|
}
|
|
_ = decodeJSON(r, &body)
|
|
estado := firstNonEmptyStr(body.Estado, "por_pagar")
|
|
modo := firstNonEmptyStr(body.Modo, "detalle")
|
|
|
|
conds := []string{`"cotizacionId" = $1`}
|
|
args := []any{cotID}
|
|
if estado == "por_pagar" || estado == "pagada" {
|
|
args = append(args, estado)
|
|
conds = append(conds, fmt.Sprintf(`"estadoPago" = $%d`, len(args)))
|
|
}
|
|
if body.From != "" {
|
|
if t, err := time.Parse("2006-01-02", body.From); err == nil {
|
|
args = append(args, t)
|
|
conds = append(conds, fmt.Sprintf(`"fecha" >= $%d`, len(args)))
|
|
}
|
|
}
|
|
if body.To != "" {
|
|
if t, err := time.Parse("2006-01-02", body.To); err == nil {
|
|
args = append(args, t.Add(24*time.Hour))
|
|
conds = append(conds, fmt.Sprintf(`"fecha" < $%d`, len(args)))
|
|
}
|
|
}
|
|
|
|
rows, err := s.Pool.Query(r.Context(), `
|
|
SELECT "fecha", "horaInicio", "horaFin", "horas", "tarifaHora", "descripcion", "estadoPago"
|
|
FROM "RegistroHoras"
|
|
WHERE `+strings.Join(conds, " AND ")+`
|
|
ORDER BY "fecha" ASC, "horaInicio" ASC
|
|
`, args...)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "Error cargando registros")
|
|
return
|
|
}
|
|
defer rows.Close()
|
|
|
|
var regs []pdf.RegistroHoraPDF
|
|
for rows.Next() {
|
|
var rpdf pdf.RegistroHoraPDF
|
|
if rows.Scan(&rpdf.Fecha, &rpdf.HoraInicio, &rpdf.HoraFin, &rpdf.Horas, &rpdf.TarifaHora, &rpdf.Descripcion, &rpdf.EstadoPago) == nil {
|
|
regs = append(regs, rpdf)
|
|
}
|
|
}
|
|
if len(regs) == 0 {
|
|
writeError(w, http.StatusBadRequest, "No hay registros de horas para emitir la nota")
|
|
return
|
|
}
|
|
|
|
titulo := "Nota de Pago — Registro de Horas"
|
|
if estado == "pagada" {
|
|
titulo = "Recibo — Horas Pagadas"
|
|
} else if estado == "todas" {
|
|
titulo = "Estado de Cuenta — Registro de Horas"
|
|
}
|
|
|
|
branding := s.getConfigBranding(r.Context())
|
|
pdfBytes, err := pdf.GenerateNotaHorasPDF(pdf.NotaHorasPDFData{
|
|
Titulo: titulo,
|
|
Numero: full.Numero,
|
|
ClienteNombre: full.ClienteNombre,
|
|
ClienteEmpresa: derefStr(full.ClienteEmpresa),
|
|
Proyecto: full.Proyecto,
|
|
AsesorNombre: full.AsesorName,
|
|
Moneda: full.Moneda,
|
|
IncluirIVA: full.IncluirIVA,
|
|
Modo: modo,
|
|
MostrarEstado: estado == "todas",
|
|
MostrarBancarios: estado != "pagada",
|
|
Registros: regs,
|
|
ConfigBancaria: s.getConfigBancaria(r.Context()),
|
|
ColorPrimario: branding.ColorPrimario,
|
|
ColorSecundario: branding.ColorSecundario,
|
|
LogoBase64: branding.LogoBase64,
|
|
LogoMime: branding.LogoMime,
|
|
FechaEmision: time.Now(),
|
|
})
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "Error generando nota de horas PDF")
|
|
return
|
|
}
|
|
|
|
w.Header().Set("Content-Type", "application/pdf")
|
|
w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="NotaHoras_%s.pdf"`, domain.SanitizeFilename(full.Numero)))
|
|
w.WriteHeader(http.StatusOK)
|
|
_, _ = w.Write(pdfBytes)
|
|
}
|
|
|
|
func derefStr(p *string) string {
|
|
if p == nil {
|
|
return ""
|
|
}
|
|
return *p
|
|
}
|
|
|
|
func nonNilSlice(s []string) []string {
|
|
if s == nil {
|
|
return []string{}
|
|
}
|
|
return s
|
|
}
|
|
|
|
func parseFlexibleDate(s string) (time.Time, error) {
|
|
s = strings.TrimSpace(s)
|
|
for _, layout := range []string{time.RFC3339, "2006-01-02T15:04:05.000Z", "2006-01-02"} {
|
|
if t, err := time.Parse(layout, s); err == nil {
|
|
return t, nil
|
|
}
|
|
}
|
|
return time.Time{}, fmt.Errorf("fecha invalida: %s", s)
|
|
}
|