reports.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. // reports.go — GET /api/reports/weekly: informe de disponibilidad semanal.
  2. // Calculado de metrics_daily (rollup nocturno de Fase 8.3): un daily por
  3. // router y día con el nº de muestras recolectadas (n), medias de
  4. // latencia/cpu/ram y totales de tráfico. El corte temporal (semana ISO
  5. // lunes-domingo) se normaliza aquí para que el frontend no haga aritmética
  6. // de fechas.
  7. //
  8. // Semántica de disponibilidad (verificada contra datos reales de prod):
  9. // - `n` = suma de muestras del día (poll de 5 s; día completo ≈ 17280).
  10. // - minutos de recolección = n * 5 / 60.
  11. // - upPct = minutos / (días con datos * 1440), clavado a 100 (issue #207):
  12. // un bucket sobre-poblado (más muestras que minutos) no puede superar el
  13. // 100%, igual que availability. La semana en curso queda parcial y se
  14. // normaliza solo sobre los días que tienen datos.
  15. // - `up_count` del daily NO es fiable como base (es COUNT(*) de filas
  16. // bucket, que en prod coincide con muestras porque el rollup no agrega);
  17. // `up_min` del daily es MIN(min_ts) (timestamp), no minutos.
  18. package httpapi
  19. import (
  20. "database/sql"
  21. "encoding/csv"
  22. "fmt"
  23. "net/http"
  24. "strconv"
  25. "time"
  26. )
  27. // weeklyReportEntry es una fila del informe: un router durante una semana.
  28. type weeklyReportEntry struct {
  29. RouterID string `json:"routerId"`
  30. Week string `json:"week"` // semana ISO, formato "2026-W31" (lunes-domingo)
  31. Days int `json:"days"` // días con datos en esa semana (≤7)
  32. UpMin int64 `json:"upMin"` // minutos de recolección en la semana
  33. UpPct float64 `json:"upPct"` // % de disponibilidad sobre los días con datos
  34. LatAvg *float64 `json:"latAvg"` // media de latencia (null si no hay datos)
  35. RxTotal float64 `json:"rxTotal"`
  36. TxTotal float64 `json:"txTotal"`
  37. CPUAvg float64 `json:"cpuAvg"`
  38. RAMAvg float64 `json:"ramAvg"`
  39. }
  40. // handleWeeklyReport sirve GET /api/reports/weekly?weeks=4. weeks ∈ [1,52].
  41. func (s *server) handleWeeklyReport(w http.ResponseWriter, r *http.Request) {
  42. weeks := 4
  43. if raw := r.URL.Query().Get("weeks"); raw != "" {
  44. n, err := strconv.Atoi(raw)
  45. if err != nil || n < 1 || n > 52 {
  46. writeError(w, http.StatusBadRequest, "invalid_query", "weeks must be an integer between 1 and 52")
  47. return
  48. }
  49. weeks = n
  50. }
  51. // El daily se agrupa por día UTC (unixepoch en el rollup). La ventana se
  52. // recorta con la fecha UTC de hoy; la semana en curso queda parcial y
  53. // upPct se calcula solo sobre los días con datos (no penaliza).
  54. since := time.Now().UTC().AddDate(0, 0, -7*weeks).Format("2006-01-02")
  55. rows, err := s.db.Query(`
  56. SELECT
  57. router_id,
  58. strftime('%G-W%V', date) AS week,
  59. COUNT(*),
  60. SUM(n) * 5 / 60,
  61. AVG(lat_avg),
  62. SUM(rx_total),
  63. SUM(tx_total),
  64. AVG(cpu_avg),
  65. AVG(ram_avg)
  66. FROM metrics_daily
  67. WHERE date >= ?
  68. GROUP BY router_id, strftime('%G-W%V', date)
  69. ORDER BY week DESC, router_id`, since)
  70. if err != nil {
  71. writeError(w, http.StatusInternalServerError, "db_error")
  72. return
  73. }
  74. defer rows.Close()
  75. out := []weeklyReportEntry{}
  76. for rows.Next() {
  77. var e weeklyReportEntry
  78. var upMin int64
  79. var lat sql.NullFloat64
  80. if err := rows.Scan(&e.RouterID, &e.Week, &e.Days, &upMin,
  81. &lat, &e.RxTotal, &e.TxTotal, &e.CPUAvg, &e.RAMAvg); err != nil {
  82. continue
  83. }
  84. e.UpMin = upMin
  85. if lat.Valid {
  86. e.LatAvg = &lat.Float64
  87. }
  88. if e.Days > 0 {
  89. e.UpPct = float64(upMin) / (float64(e.Days) * 24 * 60) * 100
  90. if e.UpPct > 100 {
  91. e.UpPct = 100
  92. }
  93. }
  94. out = append(out, e)
  95. }
  96. if err := rows.Err(); err != nil {
  97. writeError(w, http.StatusInternalServerError, "db_error")
  98. return
  99. }
  100. if r.URL.Query().Get("format") == "csv" {
  101. w.Header().Set("Content-Type", "text/csv; charset=utf-8")
  102. w.Header().Set("Content-Disposition", "attachment; filename=netpulse-weekly.csv")
  103. cw := csv.NewWriter(w)
  104. _ = cw.Write([]string{"routerId", "week", "days", "upMin", "upPct", "latAvg", "rxTotal", "txTotal", "cpuAvg", "ramAvg"})
  105. for _, e := range out {
  106. lat := ""
  107. if e.LatAvg != nil {
  108. lat = fmt.Sprintf("%.2f", *e.LatAvg)
  109. }
  110. _ = cw.Write([]string{
  111. e.RouterID, e.Week, strconv.Itoa(e.Days),
  112. strconv.FormatInt(e.UpMin, 10), fmt.Sprintf("%.2f", e.UpPct),
  113. lat, fmt.Sprintf("%.2f", e.RxTotal), fmt.Sprintf("%.2f", e.TxTotal),
  114. fmt.Sprintf("%.2f", e.CPUAvg), fmt.Sprintf("%.2f", e.RAMAvg),
  115. })
  116. }
  117. cw.Flush()
  118. return
  119. }
  120. writeJSON(w, http.StatusOK, map[string]any{"items": out, "weeks": weeks})
  121. }
  122. // ---------------------------------------------------------------------------
  123. // GET /api/reports/availability?range=day|week|month&n=N — Fase 15.1
  124. //
  125. // Disponibilidad por router agregada por día, semana ISO o mes, sobre los
  126. // últimos N buckets (day: 30, week: 8, month: 12 por defecto). Reutiliza la
  127. // semántica de upMin/upPct del weekly. El día actual parcial se normaliza por
  128. // los minutos transcurridos (no penaliza); el mes en curso, por días con datos.
  129. // ---------------------------------------------------------------------------
  130. type availabilityEntry struct {
  131. RouterID string `json:"routerId"`
  132. Bucket string `json:"bucket"` // day "2026-08-07" | week "2026-W31" | month "2026-07"
  133. Days int `json:"days"` // días con datos en el bucket
  134. UpMin int64 `json:"upMin"` // minutos de recolección en el bucket
  135. UpPct float64 `json:"upPct"` // % de disponibilidad
  136. LatAvg *float64 `json:"latAvg"`
  137. RxTotal float64 `json:"rxTotal"`
  138. TxTotal float64 `json:"txTotal"`
  139. CPUAvg float64 `json:"cpuAvg"`
  140. RAMAvg float64 `json:"ramAvg"`
  141. }
  142. // handleAvailabilityReport sirve GET /api/reports/availability.
  143. func (s *server) handleAvailabilityReport(w http.ResponseWriter, r *http.Request) {
  144. q := r.URL.Query()
  145. rangeParam := q.Get("range")
  146. if rangeParam == "" {
  147. rangeParam = "week"
  148. }
  149. // Expresión SQL de agrupación + ventana por defecto según el rango.
  150. var groupExpr string
  151. nDef, nMax := 8, 52
  152. switch rangeParam {
  153. case "day":
  154. groupExpr = "strftime('%Y-%m-%d', date)"
  155. nDef, nMax = 30, 90
  156. case "week":
  157. groupExpr = "strftime('%G-W%V', date)"
  158. nDef, nMax = 8, 52
  159. case "month":
  160. groupExpr = "strftime('%Y-%m', date)"
  161. nDef, nMax = 12, 24
  162. default:
  163. writeError(w, http.StatusBadRequest, "invalid_query", "range must be day, week or month")
  164. return
  165. }
  166. n := nDef
  167. if raw := q.Get("n"); raw != "" {
  168. v, err := strconv.Atoi(raw)
  169. if err != nil || v < 1 || v > nMax {
  170. writeError(w, http.StatusBadRequest, "invalid_query",
  171. fmt.Sprintf("n must be an integer between 1 and %d", nMax))
  172. return
  173. }
  174. n = v
  175. }
  176. // Ventana hacia atrás desde hoy (UTC).
  177. now := time.Now().UTC()
  178. var since string
  179. switch rangeParam {
  180. case "day":
  181. since = now.AddDate(0, 0, -n).Format("2006-01-02")
  182. case "week":
  183. since = now.AddDate(0, 0, -7*n).Format("2006-01-02")
  184. case "month":
  185. since = now.AddDate(0, -n, 0).Format("2006-01-02")
  186. }
  187. query := fmt.Sprintf(`
  188. SELECT
  189. router_id,
  190. %s AS bucket,
  191. COUNT(*),
  192. SUM(n) * 5 / 60,
  193. AVG(lat_avg),
  194. SUM(rx_total),
  195. SUM(tx_total),
  196. AVG(cpu_avg),
  197. AVG(ram_avg)
  198. FROM metrics_daily
  199. WHERE date >= ?
  200. GROUP BY router_id, %s
  201. ORDER BY bucket DESC, router_id`, groupExpr, groupExpr)
  202. rows, err := s.db.Query(query, since)
  203. if err != nil {
  204. writeError(w, http.StatusInternalServerError, "db_error")
  205. return
  206. }
  207. defer rows.Close()
  208. // Para el día actual parcial: divisor = minutos transcurridos del día UTC.
  209. today := now.Format("2006-01-02")
  210. nowMin := now.Hour()*60 + now.Minute()
  211. out := []availabilityEntry{}
  212. for rows.Next() {
  213. var e availabilityEntry
  214. var upMin int64
  215. var lat sql.NullFloat64
  216. if err := rows.Scan(&e.RouterID, &e.Bucket, &e.Days, &upMin,
  217. &lat, &e.RxTotal, &e.TxTotal, &e.CPUAvg, &e.RAMAvg); err != nil {
  218. continue
  219. }
  220. e.UpMin = upMin
  221. if lat.Valid {
  222. e.LatAvg = &lat.Float64
  223. }
  224. var divisor float64
  225. if rangeParam == "day" {
  226. if e.Bucket == today && nowMin > 0 {
  227. divisor = float64(nowMin)
  228. } else {
  229. divisor = 1440
  230. }
  231. } else {
  232. divisor = float64(e.Days) * 1440
  233. }
  234. if divisor > 0 {
  235. e.UpPct = float64(upMin) / divisor * 100
  236. if e.UpPct > 100 {
  237. e.UpPct = 100
  238. }
  239. }
  240. out = append(out, e)
  241. }
  242. if err := rows.Err(); err != nil {
  243. writeError(w, http.StatusInternalServerError, "db_error")
  244. return
  245. }
  246. if q.Get("format") == "csv" {
  247. w.Header().Set("Content-Type", "text/csv; charset=utf-8")
  248. w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=netpulse-availability-%s.csv", rangeParam))
  249. cw := csv.NewWriter(w)
  250. _ = cw.Write([]string{"routerId", "bucket", "days", "upMin", "upPct", "latAvg", "rxTotal", "txTotal", "cpuAvg", "ramAvg"})
  251. for _, e := range out {
  252. lat := ""
  253. if e.LatAvg != nil {
  254. lat = fmt.Sprintf("%.2f", *e.LatAvg)
  255. }
  256. _ = cw.Write([]string{
  257. e.RouterID, e.Bucket, strconv.Itoa(e.Days),
  258. strconv.FormatInt(e.UpMin, 10), fmt.Sprintf("%.2f", e.UpPct),
  259. lat, fmt.Sprintf("%.2f", e.RxTotal), fmt.Sprintf("%.2f", e.TxTotal),
  260. fmt.Sprintf("%.2f", e.CPUAvg), fmt.Sprintf("%.2f", e.RAMAvg),
  261. })
  262. }
  263. cw.Flush()
  264. return
  265. }
  266. writeJSON(w, http.StatusOK, map[string]any{"items": out, "range": rangeParam, "n": n})
  267. }