package httpapi import ( "context" "encoding/json" "errors" "fmt" "net/http" "os" "strings" "time" "cotizador/internal/audit" "cotizador/internal/auth" "cotizador/internal/db" "cotizador/internal/domain" "cotizador/internal/idempotency" "cotizador/internal/scheduler" "cotizador/internal/uploads" "github.com/go-chi/chi/v5" "github.com/jackc/pgx/v5" ) func (s *Server) queryProgramas(ctx context.Context) ([]map[string]any, error) { rows, err := s.Pool.Query(ctx, ` SELECT p."id", p."clienteId", p."cotizacionId", p."concepto", p."monto", p."moneda", p."frecuencia", p."diaSemana", p."diaMes", p."fechaInicio", p."fechaFin", p."activo", p."createdAt", p."updatedAt", c."nombre", c."empresa", c."email", (SELECT COUNT(*) FROM "PagoRecurrente" pr WHERE pr."programaId" = p."id") AS pagos_count FROM "ProgramaPago" p JOIN "Cliente" c ON c."id" = p."clienteId" ORDER BY p."activo" DESC, p."createdAt" DESC `) if err != nil { return nil, err } defer rows.Close() hoy := domain.HoyCalendario() list := []map[string]any{} for rows.Next() { var id, clienteID, concepto, moneda, frecuencia, cNombre string var cotID, cEmpresa, cEmail *string var monto float64 var diaSemana, diaMes *int var fechaInicio, createdAt, updatedAt time.Time var fechaFin *time.Time var activo bool var pagosCount int if rows.Scan(&id, &clienteID, &cotID, &concepto, &monto, &moneda, &frecuencia, &diaSemana, &diaMes, &fechaInicio, &fechaFin, &activo, &createdAt, &updatedAt, &cNombre, &cEmpresa, &cEmail, &pagosCount) == nil { var prox *time.Time if activo { prox = domain.ProximaFecha(domain.ProgramaCalendario{ Frecuencia: frecuencia, DiaSemana: diaSemana, DiaMes: diaMes, FechaInicio: fechaInicio, FechaFin: fechaFin, }, hoy) } list = append(list, map[string]any{ "id": id, "clienteId": clienteID, "cotizacionId": cotID, "concepto": concepto, "monto": monto, "moneda": moneda, "frecuencia": frecuencia, "diaSemana": diaSemana, "diaMes": diaMes, "fechaInicio": fechaInicio, "fechaFin": fechaFin, "activo": activo, "proximaFecha": prox, "createdAt": createdAt, "updatedAt": updatedAt, "cliente": map[string]any{"id": clienteID, "nombre": cNombre, "empresa": cEmpresa, "email": cEmail}, "pagosCount": pagosCount, "_count": map[string]any{"pagos": pagosCount}, }) } } return list, nil } func (s *Server) handleCobrosResumen(w http.ResponseWriter, r *http.Request) { if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "cobros"}); !ok { return } ctx := r.Context() hoy := domain.HoyCalendario() programas, err := s.queryProgramas(ctx) if err != nil { writeError(w, http.StatusInternalServerError, "Error cargando programas") return } // Clientes for dropdown cRows, _ := s.Pool.Query(ctx, `SELECT "id", "nombre", "empresa" FROM "Cliente" WHERE "archivado" = false ORDER BY "nombre" ASC`) clientes := []map[string]any{} if cRows != nil { for cRows.Next() { var cid, cnom string var cemp *string if cRows.Scan(&cid, &cnom, &cemp) == nil { clientes = append(clientes, map[string]any{"id": cid, "nombre": cnom, "empresa": cemp}) } } cRows.Close() } // Pagos en revision revPagos, _ := s.queryPagos(ctx, `p."estado" = 'en_revision'`, nil) // Pagos por cobrar (pendiente | rechazado, fecha <= hoy, including inactive programs) porCobrarRows, _ := s.Pool.Query(ctx, ` SELECT p."id", p."programaId", p."fecha", p."monto", p."estado", p."ultimoRecordatorioAt", p."recordatoriosEnviados", pr."concepto", pr."moneda", c."id", c."nombre", c."empresa", c."email", (SELECT COUNT(*) FROM "SuscripcionPush" sp JOIN "User" u ON u."id" = sp."userId" WHERE u."clienteId" = c."id") AS push_count FROM "PagoRecurrente" p JOIN "ProgramaPago" pr ON pr."id" = p."programaId" JOIN "Cliente" c ON c."id" = pr."clienteId" WHERE p."estado" IN ('pendiente', 'rechazado') AND p."fecha" <= $1 ORDER BY c."nombre" ASC, p."fecha" ASC `, hoy) type saldoClient struct { ClienteID string ClienteNombre string ClienteEmpresa *string ClienteEmail *string Contactable bool Totales map[string]float64 MasAntigua time.Time UltimoRecordatorio *time.Time PagosCount int } saldoMap := map[string]*saldoClient{} var saldoOrder []string if porCobrarRows != nil { for porCobrarRows.Next() { var pid, prid, estado, concepto, moneda, cid, cnom string var cemp, cemail *string var fecha time.Time var monto float64 var ultRec *time.Time var recCnt, pushCnt int if porCobrarRows.Scan(&pid, &prid, &fecha, &monto, &estado, &ultRec, &recCnt, &concepto, &moneda, &cid, &cnom, &cemp, &cemail, &pushCnt) == nil { sc, ok := saldoMap[cid] if !ok { sc = &saldoClient{ ClienteID: cid, ClienteNombre: cnom, ClienteEmpresa: cemp, ClienteEmail: cemail, Contactable: (cemail != nil && strings.TrimSpace(*cemail) != "") || pushCnt > 0, Totales: map[string]float64{}, MasAntigua: fecha, } saldoMap[cid] = sc saldoOrder = append(saldoOrder, cid) } if fecha.Before(sc.MasAntigua) { sc.MasAntigua = fecha } sc.Totales[moneda] = domain.Round2(sc.Totales[moneda] + monto) if ultRec != nil && (sc.UltimoRecordatorio == nil || ultRec.After(*sc.UltimoRecordatorio)) { t := *ultRec sc.UltimoRecordatorio = &t } sc.PagosCount++ } } porCobrarRows.Close() } saldos := make([]map[string]any, 0, len(saldoOrder)) for _, cid := range saldoOrder { sc := saldoMap[cid] saldos = append(saldos, map[string]any{ "clienteId": sc.ClienteID, "nombre": sc.ClienteNombre, "empresa": sc.ClienteEmpresa, "pagos": sc.PagosCount, "totales": sc.Totales, "masAntigua": sc.MasAntigua, "diasAtraso": domain.DiasDeAtraso(sc.MasAntigua, hoy), "ultimoRecordatorio": sc.UltimoRecordatorio, "contactable": sc.Contactable, }) } writeJSON(w, http.StatusOK, map[string]any{ "programas": programas, "clientes": clientes, "pagosEnRevision": revPagos, "saldos": saldos, "diasRecordatorio": s.Cfg.CobrosRecordatorioDias, }) } func (s *Server) handleProgramasList(w http.ResponseWriter, r *http.Request) { if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{Scopes: []string{"cobros:leer"}, RecursoTipo: "programa_pago"}); !ok { return } list, err := s.queryProgramas(r.Context()) if err != nil { writeError(w, http.StatusInternalServerError, "Error listando programas") return } writeJSON(w, http.StatusOK, list) } func (s *Server) handleProgramasCreate(w http.ResponseWriter, r *http.Request) { if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "programa_pago"}); !ok { return } var body struct { ClienteID string `json:"clienteId"` CotizacionID *string `json:"cotizacionId"` Concepto string `json:"concepto"` Monto float64 `json:"monto"` Moneda string `json:"moneda"` Frecuencia string `json:"frecuencia"` DiaSemana *int `json:"diaSemana"` DiaMes *int `json:"diaMes"` FechaInicio string `json:"fechaInicio"` FechaFin *string `json:"fechaFin"` } if err := decodeJSON(r, &body); err != nil { writeError(w, http.StatusBadRequest, "JSON invalido") return } if body.ClienteID == "" || strings.TrimSpace(body.Concepto) == "" || body.Monto <= 0 { writeError(w, http.StatusBadRequest, "clienteId, concepto y monto > 0 son obligatorios") return } fIni, err := domain.ParseFechaCalendario(body.FechaInicio) if err != nil { writeError(w, http.StatusBadRequest, err.Error()) return } var fFin *time.Time if body.FechaFin != nil && strings.TrimSpace(*body.FechaFin) != "" { t, err := domain.ParseFechaCalendario(*body.FechaFin) if err != nil { writeError(w, http.StatusBadRequest, err.Error()) return } fFin = &t } frec := firstNonEmptyStr(body.Frecuencia, "semanal") mon := firstNonEmptyStr(body.Moneda, "MXN") id := db.NewID() _, err = s.Pool.Exec(r.Context(), ` INSERT INTO "ProgramaPago" ( "id", "clienteId", "cotizacionId", "concepto", "monto", "moneda", "frecuencia", "diaSemana", "diaMes", "fechaInicio", "fechaFin", "activo", "createdAt", "updatedAt" ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,true,NOW(),NOW()) `, id, body.ClienteID, trimPtr(body.CotizacionID), strings.TrimSpace(body.Concepto), body.Monto, mon, frec, body.DiaSemana, body.DiaMes, fIni, fFin) if err != nil { writeError(w, http.StatusInternalServerError, "Error creando programa de pago") return } // Generate initial due charges right away if nuevos, err := scheduler.GenerarCobros(r.Context(), s.Pool, id, nil); err == nil && len(nuevos) > 0 { go s.Notify.NotificarCobrosNuevos(context.Background(), nuevos) } writeJSON(w, http.StatusCreated, map[string]any{"id": id, "ok": true}) } func (s *Server) handleProgramasUpdate(w http.ResponseWriter, r *http.Request) { if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "programa_pago"}); !ok { return } id := chi.URLParam(r, "id") var raw map[string]any if err := decodeJSON(r, &raw); err != nil { writeError(w, http.StatusBadRequest, "JSON invalido") 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 v, ok := raw["concepto"]; ok { add("concepto", strings.TrimSpace(asString(v))) } if v, ok := raw["monto"]; ok { if m, okF := asFloat(v); okF && m > 0 { add("monto", m) } } if v, ok := raw["moneda"]; ok { add("moneda", strings.TrimSpace(asString(v))) } if v, ok := raw["frecuencia"]; ok { add("frecuencia", strings.TrimSpace(asString(v))) } if v, ok := raw["diaSemana"]; ok { if n, okI := asInt(v); okI { add("diaSemana", n) } else { add("diaSemana", nil) } } if v, ok := raw["diaMes"]; ok { if n, okI := asInt(v); okI { add("diaMes", n) } else { add("diaMes", nil) } } if v, ok := raw["fechaFin"]; ok { sVal := strings.TrimSpace(asString(v)) if sVal == "" { add("fechaFin", nil) } else if t, err := domain.ParseFechaCalendario(sVal); err == nil { add("fechaFin", t) } } if v, ok := raw["activo"].(bool); ok { add("activo", v) } args = append(args, id) tag, err := s.Pool.Exec(r.Context(), fmt.Sprintf(`UPDATE "ProgramaPago" SET %s WHERE "id" = $%d`, strings.Join(sets, ", "), len(args)), args...) if err != nil || tag.RowsAffected() == 0 { writeError(w, http.StatusNotFound, "Programa no encontrado") return } writeJSON(w, http.StatusOK, map[string]any{"ok": true, "id": id}) } func (s *Server) handleCobrosGenerar(w http.ResponseWriter, r *http.Request) { if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "cobros"}); !ok { return } var body struct { ProgramaID string `json:"programaId"` Hasta string `json:"hasta"` } _ = decodeJSON(r, &body) var hasta *time.Time if strings.TrimSpace(body.Hasta) != "" { t, err := domain.ParseFechaCalendario(body.Hasta) if err != nil { writeError(w, http.StatusBadRequest, err.Error()) return } hasta = &t } nuevos, err := scheduler.GenerarCobros(r.Context(), s.Pool, body.ProgramaID, hasta) if err != nil { writeError(w, http.StatusInternalServerError, "Error generando cobros") return } if len(nuevos) > 0 { go s.Notify.NotificarCobrosNuevos(context.Background(), nuevos) } writeJSON(w, http.StatusOK, map[string]any{"ok": true, "generados": len(nuevos), "ids": nuevos}) } func (s *Server) queryPagos(ctx context.Context, whereSQL string, args []any) ([]map[string]any, error) { rows, err := s.Pool.Query(ctx, ` SELECT p."id", p."programaId", p."fecha", p."monto", p."estado", p."verificadoAt", p."rechazadoAt", p."rechazoMotivo", p."ultimoRecordatorioAt", p."recordatoriosEnviados", p."nota", pr."concepto", pr."moneda", pr."frecuencia", pr."clienteId", c."nombre", c."empresa", c."email", comp."id", comp."archivoNombre", comp."mime", comp."tamano", comp."subidoAt" FROM "PagoRecurrente" p JOIN "ProgramaPago" pr ON pr."id" = p."programaId" JOIN "Cliente" c ON c."id" = pr."clienteId" LEFT JOIN "ComprobantePago" comp ON comp."pagoId" = p."id" WHERE `+whereSQL+` ORDER BY p."fecha" DESC `, args...) if err != nil { return nil, err } defer rows.Close() list := []map[string]any{} for rows.Next() { var id, progID, estado, concepto, moneda, frec, cid, cnom string var rechazoMotivo, nota, cemp, cemail, compID, compNom, compMime *string var fecha time.Time var monto float64 var verifAt, rechAt, ultRec, compSub *time.Time var recCnt int var compTam *int if rows.Scan(&id, &progID, &fecha, &monto, &estado, &verifAt, &rechAt, &rechazoMotivo, &ultRec, &recCnt, ¬a, &concepto, &moneda, &frec, &cid, &cnom, &cemp, &cemail, &compID, &compNom, &compMime, &compTam, &compSub) == nil { var comp any if compID != nil { comp = map[string]any{ "id": *compID, "pagoId": id, "archivoNombre": compNom, "mime": compMime, "tamano": compTam, "subidoAt": compSub, } } list = append(list, map[string]any{ "id": id, "programaId": progID, "fecha": fecha, "monto": monto, "estado": estado, "verificadoAt": verifAt, "rechazadoAt": rechAt, "rechazoMotivo": rechazoMotivo, "ultimoRecordatorioAt": ultRec, "recordatoriosEnviados": recCnt, "nota": nota, "programa": map[string]any{ "id": progID, "concepto": concepto, "moneda": moneda, "frecuencia": frec, "clienteId": cid, "cliente": map[string]any{"id": cid, "nombre": cnom, "empresa": cemp, "email": cemail}, }, "comprobante": comp, }) } } return list, nil } func (s *Server) handlePagosList(w http.ResponseWriter, r *http.Request) { if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{Scopes: []string{"cobros:leer"}, RecursoTipo: "pago"}); !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)) } if est := strings.TrimSpace(q.Get("estado")); est != "" { if est == "por_pagar" { conds = append(conds, `p."estado" IN ('pendiente', 'rechazado')`) } else { conds = append(conds, `p."estado" = `+add(est)) } } if cid := strings.TrimSpace(q.Get("clienteId")); cid != "" { conds = append(conds, `pr."clienteId" = `+add(cid)) } if pid := strings.TrimSpace(q.Get("programaId")); pid != "" { conds = append(conds, `p."programaId" = `+add(pid)) } if d := strings.TrimSpace(q.Get("desde")); d != "" { if t, err := domain.ParseFechaCalendario(d); err == nil { conds = append(conds, `p."fecha" >= `+add(t)) } } if h := strings.TrimSpace(q.Get("hasta")); h != "" { if t, err := domain.ParseFechaCalendario(h); err == nil { conds = append(conds, `p."fecha" <= `+add(t)) } } list, err := s.queryPagos(r.Context(), strings.Join(conds, " AND "), args) if err != nil { writeError(w, http.StatusInternalServerError, "Error listando pagos") return } writeJSON(w, http.StatusOK, list) } func (s *Server) handlePagoAprobar(w http.ResponseWriter, r *http.Request) { actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "pago"}) if !ok { return } id := chi.URLParam(r, "id") var estado string var monto float64 if err := s.Pool.QueryRow(r.Context(), `SELECT "estado", "monto" FROM "PagoRecurrente" WHERE "id" = $1`, id).Scan(&estado, &monto); err != nil { writeError(w, http.StatusNotFound, "Cobro no encontrado") return } if estado != domain.EstadoPagoEnRevision { writeError(w, http.StatusConflict, "Solo se pueden aprobar cobros en revision") return } now := time.Now() _, err := s.Pool.Exec(r.Context(), ` UPDATE "PagoRecurrente" SET "estado"='verificado', "verificadoAt"=$1, "rechazadoAt"=NULL, "rechazoMotivo"=NULL, "updatedAt"=NOW() WHERE "id" = $2 `, now, id) if err != nil { writeError(w, http.StatusInternalServerError, "Error aprobando comprobante") return } tipo, aid, anom := actor.AuditActor() audit.Registrar(r.Context(), s.Pool, audit.Entry{ ActorTipo: tipo, ActorID: aid, ActorNombre: anom, Accion: "pago.aprobar_comprobante", RecursoTipo: "pago", RecursoID: id, IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true, }) go s.Notify.NotificarVerificacion(context.Background(), id) go s.Webhooks.Emitir(context.Background(), "pago.registrado", map[string]any{ "pagoId": id, "monto": monto, "metodo": "comprobante_verificado", "verificadoAt": now.UTC().Format(time.RFC3339), }) writeJSON(w, http.StatusOK, map[string]any{"ok": true, "id": id, "estado": "verificado", "verificadoAt": now}) } func (s *Server) handlePagoRechazar(w http.ResponseWriter, r *http.Request) { if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "pago"}); !ok { return } id := chi.URLParam(r, "id") var body struct { Motivo string `json:"motivo"` } _ = decodeJSON(r, &body) motivo := strings.TrimSpace(body.Motivo) if motivo == "" { writeError(w, http.StatusBadRequest, "El motivo del rechazo es obligatorio") return } var ruta string _ = s.Pool.QueryRow(r.Context(), `SELECT "archivoRuta" FROM "ComprobantePago" WHERE "pagoId" = $1`, id).Scan(&ruta) if ruta != "" { _ = uploads.EliminarComprobante(s.Cfg.UploadDir, ruta) _, _ = s.Pool.Exec(r.Context(), `DELETE FROM "ComprobantePago" WHERE "pagoId" = $1`, id) } tag, err := s.Pool.Exec(r.Context(), ` UPDATE "PagoRecurrente" SET "estado"='rechazado', "rechazadoAt"=NOW(), "rechazoMotivo"=$1, "updatedAt"=NOW() WHERE "id" = $2 `, motivo, id) if err != nil || tag.RowsAffected() == 0 { writeError(w, http.StatusNotFound, "Cobro no encontrado") return } go s.Notify.NotificarRechazo(context.Background(), id, motivo) writeJSON(w, http.StatusOK, map[string]any{"ok": true, "id": id, "estado": "rechazado"}) } func (s *Server) handlePagoRegistrar(w http.ResponseWriter, r *http.Request) { actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{Scopes: []string{"cobros:registrar"}, RecursoTipo: "pago"}) 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 { Fecha string `json:"fecha"` Nota *string `json:"nota"` } if err := json.Unmarshal(rawBody, &body); err != nil { return http.StatusBadRequest, map[string]any{"error": "JSON invalido"} } hoy := domain.HoyCalendario() fPago := hoy if strings.TrimSpace(body.Fecha) != "" { t, err := domain.ParseFechaCalendario(body.Fecha) if err != nil { return http.StatusBadRequest, map[string]any{"error": err.Error()} } if t.After(hoy) { return http.StatusBadRequest, map[string]any{"error": "La fecha de pago no puede ser futura"} } fPago = t } var estado string var monto float64 if err := s.Pool.QueryRow(r.Context(), `SELECT "estado", "monto" FROM "PagoRecurrente" WHERE "id" = $1`, id).Scan(&estado, &monto); err != nil { return http.StatusNotFound, map[string]any{"error": "Cobro no encontrado"} } if estado != domain.EstadoPagoPendiente && estado != domain.EstadoPagoRechazado { return http.StatusConflict, map[string]any{"error": "Solo se pueden registrar cobros pendientes o rechazados"} } verifAt := domain.InstanteDePago(fPago) _, err := s.Pool.Exec(r.Context(), ` UPDATE "PagoRecurrente" SET "estado"='verificado', "verificadoAt"=$1, "nota"=$2, "rechazadoAt"=NULL, "rechazoMotivo"=NULL, "updatedAt"=NOW() WHERE "id" = $3 `, verifAt, trimPtr(body.Nota), id) if err != nil { return http.StatusInternalServerError, map[string]any{"error": "Error registrando pago"} } tipo, aid, anom := actor.AuditActor() audit.Registrar(r.Context(), s.Pool, audit.Entry{ ActorTipo: tipo, ActorID: aid, ActorNombre: anom, Accion: "pago.registrar", RecursoTipo: "pago", RecursoID: id, IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true, Detalle: map[string]any{"fecha": fPago.Format("2006-01-02"), "nota": body.Nota}, }) go s.Notify.NotificarVerificacion(context.Background(), id) go s.Webhooks.Emitir(context.Background(), "pago.registrado", map[string]any{ "pagoId": id, "monto": monto, "metodo": "registro_manual", "verificadoAt": verifAt.UTC().Format(time.RFC3339), }) return http.StatusOK, map[string]any{"ok": true, "id": id, "estado": "verificado", "verificadoAt": verifAt} }) } func (s *Server) handlePagoAnular(w http.ResponseWriter, r *http.Request) { if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "pago"}); !ok { return } id := chi.URLParam(r, "id") var body struct { Motivo string `json:"motivo"` } _ = decodeJSON(r, &body) motivo := strings.TrimSpace(body.Motivo) if motivo == "" { writeError(w, http.StatusBadRequest, "El motivo es obligatorio") return } var estado string if err := s.Pool.QueryRow(r.Context(), `SELECT "estado" FROM "PagoRecurrente" WHERE "id" = $1`, id).Scan(&estado); err != nil { writeError(w, http.StatusNotFound, "Cobro no encontrado") return } if estado != domain.EstadoPagoPendiente && estado != domain.EstadoPagoRechazado { writeError(w, http.StatusConflict, "Solo se pueden anular cobros pendientes o rechazados") return } _, _ = s.Pool.Exec(r.Context(), `UPDATE "PagoRecurrente" SET "estado"='anulado', "nota"=$1, "updatedAt"=NOW() WHERE "id" = $2`, motivo, id) writeJSON(w, http.StatusOK, map[string]any{"ok": true, "id": id, "estado": "anulado"}) } func (s *Server) handlePagoReabrir(w http.ResponseWriter, r *http.Request) { if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "pago"}); !ok { return } id := chi.URLParam(r, "id") var estado string var hasComp bool err := s.Pool.QueryRow(r.Context(), ` SELECT p."estado", EXISTS(SELECT 1 FROM "ComprobantePago" c WHERE c."pagoId" = p."id") FROM "PagoRecurrente" p WHERE p."id" = $1 `, id).Scan(&estado, &hasComp) if err != nil { writeError(w, http.StatusNotFound, "Cobro no encontrado") return } if estado == domain.EstadoPagoVerificado && hasComp { writeError(w, http.StatusConflict, "No se puede reabrir un cobro verificado con comprobante") return } if estado != domain.EstadoPagoVerificado && estado != domain.EstadoPagoAnulado { writeError(w, http.StatusConflict, "Solo se pueden reabrir cobros anulados o registrados manualmente") return } _, _ = s.Pool.Exec(r.Context(), ` UPDATE "PagoRecurrente" SET "estado"='pendiente', "verificadoAt"=NULL, "nota"=NULL, "updatedAt"=NOW() WHERE "id" = $1 `, id) writeJSON(w, http.StatusOK, map[string]any{"ok": true, "id": id, "estado": "pendiente"}) } func (s *Server) handleCobrosRecordatorios(w http.ResponseWriter, r *http.Request) { if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "cobros"}); !ok { return } var body struct { ClienteID string `json:"clienteId"` } _ = decodeJSON(r, &body) res, err := s.Notify.EnviarRecordatoriosPendientes(r.Context(), strings.TrimSpace(body.ClienteID), true) if err != nil { writeError(w, http.StatusInternalServerError, "Error enviando recordatorios") return } writeJSON(w, http.StatusOK, res) } func (s *Server) handleComprobanteGet(w http.ResponseWriter, r *http.Request) { sess, ok := s.Auth.SessionFromRequest(r) if !ok { writeError(w, http.StatusUnauthorized, "No autenticado") return } pagoID := chi.URLParam(r, "pagoId") var ruta, nombre, mime, ownerClienteID string err := s.Pool.QueryRow(r.Context(), ` SELECT c."archivoRuta", c."archivoNombre", c."mime", pr."clienteId" FROM "ComprobantePago" c JOIN "PagoRecurrente" p ON p."id" = c."pagoId" JOIN "ProgramaPago" pr ON pr."id" = p."programaId" WHERE c."pagoId" = $1 `, pagoID).Scan(&ruta, &nombre, &mime, &ownerClienteID) if err != nil { if errors.Is(err, pgx.ErrNoRows) { writeError(w, http.StatusNotFound, "Comprobante no encontrado") return } writeError(w, http.StatusInternalServerError, "Error consultando comprobante") return } if sess.Role == "cliente" && sess.ClienteID != ownerClienteID { writeError(w, http.StatusForbidden, "No tienes acceso a este comprobante") return } absPath, err := uploads.RutaAbsoluta(s.Cfg.UploadDir, ruta) if err != nil { writeError(w, http.StatusForbidden, "Ruta invalida") return } data, err := os.ReadFile(absPath) if err != nil { writeError(w, http.StatusNotFound, "Archivo no encontrado en disco") return } w.Header().Set("Content-Type", mime) w.Header().Set("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, domain.SanitizeFilename(nombre))) w.Header().Set("Cache-Control", "private, no-store") w.WriteHeader(http.StatusOK) _, _ = w.Write(data) }