Просмотр исходного кода

feat(reports): CSV export for availability and weekly reports (#327) (#348)

Add ?format=csv query parameter to /api/reports/availability and
/api/reports/weekly endpoints. Returns text/csv with proper headers
and Content-Disposition for browser download.

Backend: CSV writer using encoding/csv in both report handlers.
Frontend: download button next to availability section header.
Test: TestWeeklyReportCSV validates headers and content type.
i18n: reports.downloadCsv (ES/EN).

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 3 месяцев назад
Родитель
Сommit
f243337d2d

+ 2 - 1
app/public/locales/en/translation.json

@@ -710,7 +710,8 @@
     "tabWeek": "Weekly",
     "tabMonth": "Monthly",
     "traffic": "Total traffic (↓+↑)",
-    "upMin": "Minutes with data"
+    "upMin": "Minutes with data",
+    "downloadCsv": "Download as CSV"
   },
   "topology": {
     "animateFlow": "Animate packet flow",

+ 2 - 1
app/public/locales/es/translation.json

@@ -710,7 +710,8 @@
     "tabWeek": "Semanal",
     "tabMonth": "Mensual",
     "traffic": "Tráfico total (↓+↑)",
-    "upMin": "Minutos con datos"
+    "upMin": "Minutos con datos",
+    "downloadCsv": "Descargar como CSV"
   },
   "topology": {
     "animateFlow": "Animar flujo de paquetes",

+ 12 - 1
app/src/pages/Reports.tsx

@@ -3,7 +3,7 @@ import type { KeyboardEvent as ReactKeyboardEvent } from 'react'
 import { useTranslation } from 'react-i18next'
 import { Link } from 'react-router'
 import { motion, useReducedMotion } from 'framer-motion'
-import { CalendarDays, RefreshCw } from 'lucide-react'
+import { CalendarDays, Download, RefreshCw } from 'lucide-react'
 import { cn, fetchJson } from '@/lib/utils'
 import { useNetPulse } from '@/data/DataProvider'
 
@@ -267,6 +267,17 @@ export default function Reports() {
           <div className="mb-4 flex items-center gap-2">
             <CalendarDays className="h-4 w-4 text-accent" strokeWidth={1.75} />
             <h2 className="font-display text-h2 text-text-primary">{t('reports.availability')}</h2>
+            {items.length > 0 && (
+              <a
+                href={`/api/reports/availability?range=${range}&n=${n}&format=csv`}
+                download
+                className="ml-auto inline-flex items-center gap-1 rounded-md border border-border px-2 py-1 text-[11px] font-medium text-text-secondary transition-colors hover:bg-hover hover:text-text-primary"
+                title={t('reports.downloadCsv')}
+              >
+                <Download className="h-3 w-3" strokeWidth={2} />
+                CSV
+              </a>
+            )}
           </div>
           <div className="overflow-x-auto">
             <table className="w-full text-left text-sm">

+ 41 - 0
server-go/internal/httpapi/reports.go

@@ -19,6 +19,7 @@ package httpapi
 
 import (
 	"database/sql"
+	"encoding/csv"
 	"fmt"
 	"net/http"
 	"strconv"
@@ -102,6 +103,26 @@ func (s *server) handleWeeklyReport(w http.ResponseWriter, r *http.Request) {
 		writeError(w, http.StatusInternalServerError, "db_error")
 		return
 	}
+	if r.URL.Query().Get("format") == "csv" {
+		w.Header().Set("Content-Type", "text/csv; charset=utf-8")
+		w.Header().Set("Content-Disposition", "attachment; filename=netpulse-weekly.csv")
+		cw := csv.NewWriter(w)
+		_ = cw.Write([]string{"routerId", "week", "days", "upMin", "upPct", "latAvg", "rxTotal", "txTotal", "cpuAvg", "ramAvg"})
+		for _, e := range out {
+			lat := ""
+			if e.LatAvg != nil {
+				lat = fmt.Sprintf("%.2f", *e.LatAvg)
+			}
+			_ = cw.Write([]string{
+				e.RouterID, e.Week, strconv.Itoa(e.Days),
+				strconv.FormatInt(e.UpMin, 10), fmt.Sprintf("%.2f", e.UpPct),
+				lat, fmt.Sprintf("%.2f", e.RxTotal), fmt.Sprintf("%.2f", e.TxTotal),
+				fmt.Sprintf("%.2f", e.CPUAvg), fmt.Sprintf("%.2f", e.RAMAvg),
+			})
+		}
+		cw.Flush()
+		return
+	}
 	writeJSON(w, http.StatusOK, map[string]any{"items": out, "weeks": weeks})
 }
 
@@ -238,5 +259,25 @@ func (s *server) handleAvailabilityReport(w http.ResponseWriter, r *http.Request
 		writeError(w, http.StatusInternalServerError, "db_error")
 		return
 	}
+	if q.Get("format") == "csv" {
+		w.Header().Set("Content-Type", "text/csv; charset=utf-8")
+		w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=netpulse-availability-%s.csv", rangeParam))
+		cw := csv.NewWriter(w)
+		_ = cw.Write([]string{"routerId", "bucket", "days", "upMin", "upPct", "latAvg", "rxTotal", "txTotal", "cpuAvg", "ramAvg"})
+		for _, e := range out {
+			lat := ""
+			if e.LatAvg != nil {
+				lat = fmt.Sprintf("%.2f", *e.LatAvg)
+			}
+			_ = cw.Write([]string{
+				e.RouterID, e.Bucket, strconv.Itoa(e.Days),
+				strconv.FormatInt(e.UpMin, 10), fmt.Sprintf("%.2f", e.UpPct),
+				lat, fmt.Sprintf("%.2f", e.RxTotal), fmt.Sprintf("%.2f", e.TxTotal),
+				fmt.Sprintf("%.2f", e.CPUAvg), fmt.Sprintf("%.2f", e.RAMAvg),
+			})
+		}
+		cw.Flush()
+		return
+	}
 	writeJSON(w, http.StatusOK, map[string]any{"items": out, "range": rangeParam, "n": n})
 }

+ 35 - 0
server-go/internal/httpapi/reports_test.go

@@ -7,6 +7,7 @@ import (
 	"fmt"
 	"io"
 	"net/http"
+	"strings"
 	"testing"
 	"time"
 )
@@ -219,3 +220,37 @@ func TestWeeklyReportRequiereSesion(t *testing.T) {
 		t.Fatalf("status %d, esperaba 401", res.StatusCode)
 	}
 }
+
+// TestWeeklyReportCSV (#327): format=csv devuelve CSV con headers correctos.
+func TestWeeklyReportCSV(t *testing.T) {
+	ts := makeTestServer(t)
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+
+	req, _ := http.NewRequest("GET", ts.URL+"/api/reports/weekly?format=csv", nil)
+	req.Header.Set("Cookie", "session="+cookie)
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatalf("GET csv: %v", err)
+	}
+	defer res.Body.Close()
+	if res.StatusCode != http.StatusOK {
+		t.Fatalf("status %d", res.StatusCode)
+	}
+	ct := res.Header.Get("Content-Type")
+	if !strings.Contains(ct, "text/csv") {
+		t.Fatalf("Content-Type = %q, esperaba text/csv", ct)
+	}
+	disp := res.Header.Get("Content-Disposition")
+	if !strings.Contains(disp, "netpulse-weekly.csv") {
+		t.Fatalf("Content-Disposition = %q, esperaba netpulse-weekly.csv", disp)
+	}
+	body, _ := io.ReadAll(res.Body)
+	lines := strings.Split(strings.TrimSpace(string(body)), "\n")
+	if len(lines) < 1 {
+		t.Fatal("CSV vacio")
+	}
+	header := lines[0]
+	if !strings.Contains(header, "routerId") || !strings.Contains(header, "upPct") {
+		t.Fatalf("CSV header inesperado: %s", header)
+	}
+}