419 lines
13 KiB
Go
419 lines
13 KiB
Go
package httpapi
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
|
|
"cotizador/internal/audit"
|
|
"cotizador/internal/auth"
|
|
"cotizador/internal/db"
|
|
"cotizador/internal/idempotency"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
"github.com/jackc/pgx/v5"
|
|
)
|
|
|
|
func (s *Server) queryClientes(ctx context.Context, whereSQL string, args ...any) ([]map[string]any, error) {
|
|
rows, err := s.Pool.Query(ctx, `
|
|
SELECT c."id", c."nombre", c."empresa", c."puesto", c."email", c."telefono", c."rfc",
|
|
c."archivado", c."archivadoAt", c."createdAt", c."updatedAt",
|
|
u."id", u."email",
|
|
(SELECT COUNT(*) FROM "Cotizacion" q WHERE q."clienteId" = c."id" AND q."archivado" = false) AS cot_count,
|
|
(SELECT COUNT(*) FROM "ProgramaPago" p WHERE p."clienteId" = c."id" AND p."activo" = true) AS prog_count
|
|
FROM "Cliente" c
|
|
LEFT JOIN "User" u ON u."clienteId" = c."id"
|
|
WHERE `+whereSQL+`
|
|
ORDER BY c."nombre" ASC
|
|
`, args...)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
|
|
list := []map[string]any{}
|
|
for rows.Next() {
|
|
var id, nombre string
|
|
var empresa, puesto, email, telefono, rfc, uid, uemail *string
|
|
var archivado bool
|
|
var archivadoAt *time.Time
|
|
var createdAt, updatedAt time.Time
|
|
var cotCount, progCount int
|
|
if rows.Scan(&id, &nombre, &empresa, &puesto, &email, &telefono, &rfc, &archivado, &archivadoAt, &createdAt, &updatedAt, &uid, &uemail, &cotCount, &progCount) == nil {
|
|
var usuario any
|
|
if uid != nil {
|
|
usuario = map[string]any{"id": *uid, "email": uemail}
|
|
}
|
|
list = append(list, map[string]any{
|
|
"id": id,
|
|
"nombre": nombre,
|
|
"empresa": empresa,
|
|
"puesto": puesto,
|
|
"email": email,
|
|
"telefono": telefono,
|
|
"rfc": rfc,
|
|
"archivado": archivado,
|
|
"archivadoAt": archivadoAt,
|
|
"createdAt": createdAt,
|
|
"updatedAt": updatedAt,
|
|
"usuario": usuario,
|
|
"_count": map[string]any{
|
|
"cotizaciones": cotCount,
|
|
"programasPago": progCount,
|
|
},
|
|
})
|
|
}
|
|
}
|
|
return list, nil
|
|
}
|
|
|
|
func (s *Server) clienteDuplicadoExiste(ctx context.Context, nombre, empresa, excludeID string) (bool, error) {
|
|
empNorm := strings.ToLower(strings.TrimSpace(empresa))
|
|
var exists bool
|
|
err := s.Pool.QueryRow(ctx, `
|
|
SELECT EXISTS(
|
|
SELECT 1 FROM "Cliente"
|
|
WHERE "archivado" = false
|
|
AND LOWER(TRIM("nombre")) = LOWER(TRIM($1))
|
|
AND LOWER(TRIM(COALESCE("empresa", ''))) = $2
|
|
AND ($3 = '' OR "id" <> $3)
|
|
)
|
|
`, nombre, empNorm, excludeID).Scan(&exists)
|
|
return exists, err
|
|
}
|
|
|
|
func (s *Server) handleClientesList(w http.ResponseWriter, r *http.Request) {
|
|
actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{Scopes: []string{"clientes:leer"}, RecursoTipo: "cliente"})
|
|
if !ok {
|
|
return
|
|
}
|
|
q := r.URL.Query()
|
|
conds := []string{"1=1"}
|
|
args := []any{}
|
|
add := func(v any) string {
|
|
args = append(args, v)
|
|
return fmt.Sprintf("$%d", len(args))
|
|
}
|
|
|
|
incluirArchivados := !actor.IsAgent() && q.Get("incluirArchivados") == "true"
|
|
if !incluirArchivados {
|
|
conds = append(conds, `c."archivado" = false`)
|
|
}
|
|
if search := strings.TrimSpace(q.Get("q")); search != "" {
|
|
p := add("%" + search + "%")
|
|
conds = append(conds, fmt.Sprintf(`(c."nombre" ILIKE %s OR COALESCE(c."empresa", '') ILIKE %s OR COALESCE(c."email", '') ILIKE %s OR COALESCE(c."rfc", '') ILIKE %s)`, p, p, p, p))
|
|
}
|
|
|
|
list, err := s.queryClientes(r.Context(), strings.Join(conds, " AND "), args...)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "Error listando clientes")
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, list)
|
|
}
|
|
|
|
func (s *Server) handleClientesCreate(w http.ResponseWriter, r *http.Request) {
|
|
actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{Scopes: []string{"clientes:escribir"}, RecursoTipo: "cliente"})
|
|
if !ok {
|
|
return
|
|
}
|
|
idempotency.Execute(r.Context(), s.Pool, w, r, actor, func(rawBody []byte) (int, any) {
|
|
var body 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"`
|
|
}
|
|
if err := json.Unmarshal(rawBody, &body); err != nil {
|
|
return http.StatusBadRequest, map[string]any{"error": "JSON invalido"}
|
|
}
|
|
nombre := strings.TrimSpace(body.Nombre)
|
|
if nombre == "" {
|
|
return http.StatusBadRequest, map[string]any{
|
|
"error": "Datos invalidos",
|
|
"detalles": []ValidationDetail{{Campo: "nombre", Mensaje: "El nombre del cliente es obligatorio"}},
|
|
}
|
|
}
|
|
empStr := ""
|
|
if body.Empresa != nil {
|
|
empStr = strings.TrimSpace(*body.Empresa)
|
|
}
|
|
dup, err := s.clienteDuplicadoExiste(r.Context(), nombre, empStr, "")
|
|
if err != nil {
|
|
return http.StatusInternalServerError, map[string]any{"error": "Error validando duplicado"}
|
|
}
|
|
if dup {
|
|
return http.StatusConflict, map[string]any{"error": "Ya existe un cliente con el mismo nombre y empresa"}
|
|
}
|
|
|
|
id := db.NewID()
|
|
_, 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())
|
|
`, id, nombre, nullableTrim(empStr), trimPtr(body.Puesto), trimPtr(body.Email), trimPtr(body.Telefono), trimPtr(body.RFC))
|
|
if err != nil {
|
|
return http.StatusInternalServerError, map[string]any{"error": "Error creando cliente"}
|
|
}
|
|
|
|
tipo, aid, anom := actor.AuditActor()
|
|
audit.Registrar(r.Context(), s.Pool, audit.Entry{
|
|
ActorTipo: tipo, ActorID: aid, ActorNombre: anom,
|
|
Accion: "cliente.crear", RecursoTipo: "cliente", RecursoID: id,
|
|
IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true,
|
|
Detalle: map[string]any{"nombre": nombre, "empresa": empStr},
|
|
})
|
|
|
|
list, _ := s.queryClientes(r.Context(), `c."id" = $1`, id)
|
|
if len(list) == 1 {
|
|
return http.StatusCreated, list[0]
|
|
}
|
|
return http.StatusCreated, map[string]any{"id": id, "nombre": nombre}
|
|
})
|
|
}
|
|
|
|
func (s *Server) handleClientesUpdate(w http.ResponseWriter, r *http.Request) {
|
|
actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{Scopes: []string{"clientes:escribir"}, RecursoTipo: "cliente"})
|
|
if !ok {
|
|
return
|
|
}
|
|
id := chi.URLParam(r, "id")
|
|
var curNombre string
|
|
var curEmpresa *string
|
|
err := s.Pool.QueryRow(r.Context(), `SELECT "nombre", "empresa" FROM "Cliente" WHERE "id" = $1`, id).Scan(&curNombre, &curEmpresa)
|
|
if err != nil {
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
writeError(w, http.StatusNotFound, "Cliente no encontrado")
|
|
return
|
|
}
|
|
writeError(w, http.StatusInternalServerError, "Error consultando cliente")
|
|
return
|
|
}
|
|
|
|
var raw map[string]any
|
|
if err := decodeJSON(r, &raw); err != nil {
|
|
writeError(w, http.StatusBadRequest, "JSON invalido")
|
|
return
|
|
}
|
|
|
|
newNombre := curNombre
|
|
if v, ok := raw["nombre"]; ok {
|
|
newNombre = strings.TrimSpace(asString(v))
|
|
if newNombre == "" {
|
|
writeValidationError(w, []ValidationDetail{{Campo: "nombre", Mensaje: "El nombre no puede estar vacio"}})
|
|
return
|
|
}
|
|
}
|
|
newEmpresa := ""
|
|
if curEmpresa != nil {
|
|
newEmpresa = *curEmpresa
|
|
}
|
|
if v, ok := raw["empresa"]; ok {
|
|
newEmpresa = strings.TrimSpace(asString(v))
|
|
}
|
|
|
|
if dup, _ := s.clienteDuplicadoExiste(r.Context(), newNombre, newEmpresa, id); dup {
|
|
writeError(w, http.StatusConflict, "Ya existe otro cliente con el mismo nombre y empresa")
|
|
return
|
|
}
|
|
|
|
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 _, ok := raw["nombre"]; ok {
|
|
add("nombre", newNombre)
|
|
}
|
|
if _, ok := raw["empresa"]; ok {
|
|
add("empresa", nullableTrim(newEmpresa))
|
|
}
|
|
if v, ok := raw["puesto"]; ok {
|
|
add("puesto", nullableTrim(asString(v)))
|
|
}
|
|
if v, ok := raw["email"]; ok {
|
|
add("email", nullableTrim(asString(v)))
|
|
}
|
|
if v, ok := raw["telefono"]; ok {
|
|
add("telefono", nullableTrim(asString(v)))
|
|
}
|
|
if v, ok := raw["rfc"]; ok {
|
|
add("rfc", nullableTrim(asString(v)))
|
|
}
|
|
args = append(args, id)
|
|
_, err = s.Pool.Exec(r.Context(), fmt.Sprintf(`UPDATE "Cliente" SET %s WHERE "id" = $%d`, strings.Join(sets, ", "), len(args)), args...)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "Error actualizando cliente")
|
|
return
|
|
}
|
|
|
|
tipo, aid, anom := actor.AuditActor()
|
|
audit.Registrar(r.Context(), s.Pool, audit.Entry{
|
|
ActorTipo: tipo, ActorID: aid, ActorNombre: anom,
|
|
Accion: "cliente.actualizar", RecursoTipo: "cliente", RecursoID: id,
|
|
IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true,
|
|
})
|
|
|
|
list, _ := s.queryClientes(r.Context(), `c."id" = $1`, id)
|
|
if len(list) == 1 {
|
|
writeJSON(w, http.StatusOK, list[0])
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]any{"id": id})
|
|
}
|
|
|
|
func (s *Server) handleClienteAccesoCreate(w http.ResponseWriter, r *http.Request) {
|
|
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "cliente_acceso"}); !ok {
|
|
return
|
|
}
|
|
clienteID := chi.URLParam(r, "id")
|
|
var cliNombre string
|
|
if err := s.Pool.QueryRow(r.Context(), `SELECT "nombre" FROM "Cliente" WHERE "id" = $1`, clienteID).Scan(&cliNombre); err != nil {
|
|
writeError(w, http.StatusNotFound, "Cliente no encontrado")
|
|
return
|
|
}
|
|
|
|
var body struct {
|
|
Email string `json:"email"`
|
|
Password string `json:"password"`
|
|
}
|
|
if err := decodeJSON(r, &body); err != nil {
|
|
writeError(w, http.StatusBadRequest, "JSON invalido")
|
|
return
|
|
}
|
|
email := strings.ToLower(strings.TrimSpace(body.Email))
|
|
if email == "" || len(body.Password) < 6 {
|
|
writeError(w, http.StatusBadRequest, "Email y contrasena (minimo 6 caracteres) requeridos")
|
|
return
|
|
}
|
|
|
|
hash, err := auth.HashPassword(body.Password)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "Error encriptando contrasena")
|
|
return
|
|
}
|
|
|
|
// Check if another user owns this email
|
|
var conflict bool
|
|
_ = s.Pool.QueryRow(r.Context(), `
|
|
SELECT EXISTS(SELECT 1 FROM "User" WHERE LOWER("email") = $1 AND ("clienteId" IS NULL OR "clienteId" <> $2))
|
|
`, email, clienteID).Scan(&conflict)
|
|
if conflict {
|
|
writeError(w, http.StatusConflict, "Ese correo ya esta en uso por otra cuenta")
|
|
return
|
|
}
|
|
|
|
var existingID string
|
|
err = s.Pool.QueryRow(r.Context(), `SELECT "id" FROM "User" WHERE "clienteId" = $1`, clienteID).Scan(&existingID)
|
|
if err == nil && existingID != "" {
|
|
_, err = s.Pool.Exec(r.Context(), `
|
|
UPDATE "User" SET "email" = $1, "password" = $2, "name" = $3, "role" = 'cliente', "updatedAt" = NOW()
|
|
WHERE "id" = $4
|
|
`, email, hash, cliNombre, existingID)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "Error actualizando acceso")
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "id": existingID, "email": email, "actualizado": true})
|
|
return
|
|
}
|
|
|
|
uid := db.NewID()
|
|
_, err = s.Pool.Exec(r.Context(), `
|
|
INSERT INTO "User" ("id", "email", "password", "name", "role", "clienteId", "createdAt", "updatedAt")
|
|
VALUES ($1, $2, $3, $4, 'cliente', $5, NOW(), NOW())
|
|
`, uid, email, hash, cliNombre, clienteID)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "Error creando cuenta de cliente")
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusCreated, map[string]any{"ok": true, "id": uid, "email": email})
|
|
}
|
|
|
|
func (s *Server) handleClienteAccesoDelete(w http.ResponseWriter, r *http.Request) {
|
|
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "cliente_acceso"}); !ok {
|
|
return
|
|
}
|
|
clienteID := chi.URLParam(r, "id")
|
|
_, _ = s.Pool.Exec(r.Context(), `DELETE FROM "User" WHERE "clienteId" = $1 AND "role" = 'cliente'`, clienteID)
|
|
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
|
|
}
|
|
|
|
func (s *Server) handleClienteArchivar(w http.ResponseWriter, r *http.Request) {
|
|
actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{
|
|
StaffOnly: true,
|
|
AccionBloqueo: "cliente.archivar_bloqueado",
|
|
RecursoTipo: "cliente",
|
|
})
|
|
if !ok {
|
|
return
|
|
}
|
|
clienteID := chi.URLParam(r, "id")
|
|
var body struct {
|
|
Archivado *bool `json:"archivado"`
|
|
IncluirCotizaciones *bool `json:"incluirCotizaciones"`
|
|
}
|
|
_ = decodeJSON(r, &body)
|
|
archivado := true
|
|
if body.Archivado != nil {
|
|
archivado = *body.Archivado
|
|
}
|
|
incluirCot := true
|
|
if body.IncluirCotizaciones != nil {
|
|
incluirCot = *body.IncluirCotizaciones
|
|
}
|
|
|
|
var archAt *time.Time
|
|
if archivado {
|
|
now := time.Now()
|
|
archAt = &now
|
|
}
|
|
|
|
tag, err := s.Pool.Exec(r.Context(), `
|
|
UPDATE "Cliente" SET "archivado" = $1, "archivadoAt" = $2, "updatedAt" = NOW() WHERE "id" = $3
|
|
`, archivado, archAt, clienteID)
|
|
if err != nil || tag.RowsAffected() == 0 {
|
|
writeError(w, http.StatusNotFound, "Cliente no encontrado")
|
|
return
|
|
}
|
|
var cotAfectadas int64
|
|
if incluirCot {
|
|
ctag, _ := s.Pool.Exec(r.Context(), `
|
|
UPDATE "Cotizacion" SET "archivado" = $1, "archivadoAt" = $2, "updatedAt" = NOW() WHERE "clienteId" = $3
|
|
`, archivado, archAt, clienteID)
|
|
cotAfectadas = ctag.RowsAffected()
|
|
}
|
|
|
|
accion := "cliente.archivar"
|
|
if !archivado {
|
|
accion = "cliente.desarchivar"
|
|
}
|
|
tipo, aid, anom := actor.AuditActor()
|
|
audit.Registrar(r.Context(), s.Pool, audit.Entry{
|
|
ActorTipo: tipo, ActorID: aid, ActorNombre: anom,
|
|
Accion: accion, RecursoTipo: "cliente", RecursoID: clienteID,
|
|
IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true,
|
|
Detalle: map[string]any{"archivado": archivado, "cotizacionesAfectadas": cotAfectadas},
|
|
})
|
|
|
|
writeJSON(w, http.StatusOK, map[string]any{
|
|
"ok": true,
|
|
"id": clienteID,
|
|
"archivado": archivado,
|
|
"cotizacionesAfectadas": cotAfectadas,
|
|
})
|
|
}
|
|
|
|
func trimPtr(p *string) *string {
|
|
if p == nil {
|
|
return nil
|
|
}
|
|
return nullableTrim(*p)
|
|
}
|