Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

feat(reporting): enhance PDF reports with Executive Summary and actionable insights

rcourtman442d29e9b936
diff --git a/internal/api/saml_handlers.go b/internal/api/saml_handlers.go
index b816259eea..9a87de3ed9 100644
--- a/internal/api/saml_handlers.go
+++ b/internal/api/saml_handlers.go
@@ -258,8 +258,8 @@ func (r *Router) handleSAMLACS(w http.ResponseWriter, req *http.Request) {
LogAuditEventForTenant(GetOrgID(req.Context()), "saml_login", username, GetClientIP(req), req.URL.Path, true, "SAML login success via "+providerID)
- // Redirect to return URL
- target := relayState
+ // Redirect to return URL - sanitize relayState to prevent open redirect
+ target := sanitizeOIDCReturnTo(relayState)
if target == "" {
target = "/"
}
@@ -455,22 +455,45 @@ func (r *Router) getSAMLSessionInfo(req *http.Request) *SAMLSessionInfo {
}
}
-// clearSession clears the current session
+// clearSession clears the current session - properly invalidates server-side session
+// and clears both pulse_session and pulse_csrf cookies
func (r *Router) clearSession(w http.ResponseWriter, req *http.Request) {
- // Clear session cookie
+ isSecure, sameSitePolicy := getCookieSettings(req)
+
+ // Invalidate server-side session first
+ if cookie, err := req.Cookie("pulse_session"); err == nil && cookie.Value != "" {
+ // Get username before deleting session for untracking
+ if username := GetSessionUsername(cookie.Value); username != "" {
+ UntrackUserSession(username, cookie.Value)
+ }
+ GetSessionStore().InvalidateSession(cookie.Value)
+ }
+
+ // Clear pulse_session cookie
http.SetCookie(w, &http.Cookie{
- Name: "session",
+ Name: "pulse_session",
Value: "",
Path: "/",
MaxAge: -1,
HttpOnly: true,
- Secure: req.TLS != nil,
- SameSite: http.SameSiteLaxMode,
+ Secure: isSecure,
+ SameSite: sameSitePolicy,
+ })
+
+ // Clear pulse_csrf cookie
+ http.SetCookie(w, &http.Cookie{
+ Name: "pulse_csrf",
+ Value: "",
+ Path: "/",
+ MaxAge: -1,
+ Secure: isSecure,
+ SameSite: sameSitePolicy,
})
}
func (r *Router) redirectSAMLError(w http.ResponseWriter, req *http.Request, returnTo string, code string) {
- target := returnTo
+ // Sanitize returnTo to prevent open redirect attacks
+ target := sanitizeOIDCReturnTo(returnTo)
if target == "" {
target = "/"
}
diff --git a/pkg/reporting/pdf.go b/pkg/reporting/pdf.go
index cc376aa48c..6310a21530 100644
--- a/pkg/reporting/pdf.go
+++ b/pkg/reporting/pdf.go
@@ -10,6 +10,21 @@ import (
"github.com/go-pdf/fpdf"
)
+// Color scheme - professional dark blue theme
+var (
+ colorPrimary = [3]int{30, 58, 95} // Dark navy
+ colorSecondary = [3]int{52, 152, 219} // Bright blue
+ colorAccent = [3]int{46, 204, 113} // Green
+ colorWarning = [3]int{241, 196, 15} // Yellow
+ colorDanger = [3]int{231, 76, 60} // Red
+ colorTextDark = [3]int{44, 62, 80} // Dark text
+ colorTextMuted = [3]int{127, 140, 141} // Muted text
+ colorBackground = [3]int{248, 249, 250} // Light gray bg
+ colorTableHeader = [3]int{30, 58, 95} // Navy header
+ colorTableAlt = [3]int{241, 245, 249} // Alternating row
+ colorGridLine = [3]int{220, 220, 220} // Chart grid
+)
+
// PDFGenerator handles PDF report generation.
type PDFGenerator struct{}
@@ -21,123 +36,674 @@ func NewPDFGenerator() *PDFGenerator {
// Generate creates a PDF report from the provided data.
func (g *PDFGenerator) Generate(data *ReportData) ([]byte, error) {
pdf := fpdf.New("P", "mm", "A4", "")
- pdf.SetMargins(15, 15, 15)
- pdf.SetAutoPageBreak(true, 15)
+ pdf.SetMargins(20, 20, 20)
+ pdf.SetAutoPageBreak(true, 25)
- // Add first page
+ // Cover page
+ g.writeCoverPage(pdf, data)
+
+ // Executive Summary page
pdf.AddPage()
+ g.addPageHeader(pdf, data, "Executive Summary")
+ g.writeExecutiveSummary(pdf, data)
+
+ // Resource details page (if enrichment data available)
+ if data.Resource != nil {
+ pdf.AddPage()
+ g.addPageHeader(pdf, data, "Resource Details")
+ g.writeResourceDetails(pdf, data)
- // Header
- g.writeHeader(pdf, data)
+ // Storage section for nodes
+ if len(data.Storage) > 0 {
+ g.writeStorageSection(pdf, data)
+ }
- // Summary section
- g.writeSummary(pdf, data)
+ // Physical disks section for nodes
+ if len(data.Disks) > 0 {
+ g.writeDisksSection(pdf, data)
+ }
- // Charts for each metric
- g.writeCharts(pdf, data)
+ // Backups section for VMs/containers
+ if len(data.Backups) > 0 {
+ g.writeBackupsSection(pdf, data)
+ }
+ }
+
+ // Alerts section (if any)
+ if len(data.Alerts) > 0 {
+ if pdf.GetY() > 180 {
+ pdf.AddPage()
+ g.addPageHeader(pdf, data, "Alerts")
+ }
+ g.writeAlertsSection(pdf, data)
+ }
+
+ // Summary page with metrics
+ pdf.AddPage()
+ g.addPageHeader(pdf, data, "Performance Summary")
+ g.writeSummarySection(pdf, data)
- // Data table
- g.writeDataTable(pdf, data)
+ // Charts page(s)
+ g.writeChartsSection(pdf, data)
- // Footer with generation info
- g.writeFooter(pdf, data)
+ // Data table page(s)
+ g.writeDataSection(pdf, data)
+
+ // Add page numbers to all pages except cover
+ g.addPageNumbers(pdf)
// Output to buffer
var buf bytes.Buffer
- err := pdf.Output(&buf)
- if err != nil {
+ if err := pdf.Output(&buf); err != nil {
return nil, fmt.Errorf("PDF output error: %w", err)
}
return buf.Bytes(), nil
}
-// writeHeader writes the report header.
-func (g *PDFGenerator) writeHeader(pdf *fpdf.Fpdf, data *ReportData) {
- // Title
- pdf.SetFont("Arial", "B", 18)
- pdf.SetTextColor(51, 51, 51)
- pdf.CellFormat(0, 12, "Pulse Metrics Report", "", 1, "C", false, 0, "")
+// writeCoverPage creates a professional cover page.
+func (g *PDFGenerator) writeCoverPage(pdf *fpdf.Fpdf, data *ReportData) {
+ pdf.AddPage()
- // Subtitle with title
- pdf.SetFont("Arial", "", 14)
- pdf.SetTextColor(102, 102, 102)
- pdf.CellFormat(0, 8, data.Title, "", 1, "C", false, 0, "")
+ pageWidth, pageHeight := pdf.GetPageSize()
- pdf.Ln(5)
+ // Top accent bar
+ pdf.SetFillColor(colorPrimary[0], colorPrimary[1], colorPrimary[2])
+ pdf.Rect(0, 0, pageWidth, 8, "F")
- // Report details box
- pdf.SetFillColor(245, 245, 245)
- pdf.SetDrawColor(200, 200, 200)
- pdf.SetFont("Arial", "", 10)
- pdf.SetTextColor(51, 51, 51)
+ // Pulse branding area
+ pdf.SetY(50)
+ pdf.SetFont("Arial", "B", 32)
+ pdf.SetTextColor(colorPrimary[0], colorPrimary[1], colorPrimary[2])
+ pdf.CellFormat(0, 15, "PULSE", "", 1, "C", false, 0, "")
- boxX := 15.0
- boxWidth := 180.0
- boxHeight := 35.0
+ pdf.SetFont("Arial", "", 12)
+ pdf.SetTextColor(colorTextMuted[0], colorTextMuted[1], colorTextMuted[2])
+ pdf.CellFormat(0, 8, "Infrastructure Monitoring", "", 1, "C", false, 0, "")
- pdf.Rect(boxX, pdf.GetY(), boxWidth, boxHeight, "FD")
- pdf.SetXY(boxX+5, pdf.GetY()+3)
+ // Main title
+ pdf.SetY(100)
+ pdf.SetFont("Arial", "B", 28)
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+ pdf.CellFormat(0, 12, "Performance Report", "", 1, "C", false, 0, "")
- // Resource info
- pdf.SetFont("Arial", "B", 10)
- pdf.CellFormat(30, 6, "Resource Type:", "", 0, "L", false, 0, "")
- pdf.SetFont("Arial", "", 10)
- pdf.CellFormat(50, 6, GetResourceTypeDisplayName(data.ResourceType), "", 0, "L", false, 0, "")
+ // Resource info box
+ pdf.SetY(130)
+ boxX := 40.0
+ boxWidth := pageWidth - 80
+ boxHeight := 50.0
- pdf.SetFont("Arial", "B", 10)
- pdf.CellFormat(30, 6, "Resource ID:", "", 0, "L", false, 0, "")
- pdf.SetFont("Arial", "", 10)
- pdf.CellFormat(0, 6, data.ResourceID, "", 1, "L", false, 0, "")
+ pdf.SetFillColor(colorBackground[0], colorBackground[1], colorBackground[2])
+ pdf.SetDrawColor(colorGridLine[0], colorGridLine[1], colorGridLine[2])
+ pdf.RoundedRect(boxX, pdf.GetY(), boxWidth, boxHeight, 3, "1234", "FD")
- pdf.SetX(boxX + 5)
+ // Resource details inside box
+ pdf.SetY(pdf.GetY() + 10)
+ pdf.SetFont("Arial", "B", 11)
+ pdf.SetTextColor(colorTextMuted[0], colorTextMuted[1], colorTextMuted[2])
+ pdf.CellFormat(0, 7, "RESOURCE", "", 1, "C", false, 0, "")
+
+ pdf.SetFont("Arial", "B", 16)
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+ pdf.CellFormat(0, 10, data.ResourceID, "", 1, "C", false, 0, "")
+
+ pdf.SetFont("Arial", "", 11)
+ pdf.SetTextColor(colorTextMuted[0], colorTextMuted[1], colorTextMuted[2])
+ pdf.CellFormat(0, 7, GetResourceTypeDisplayName(data.ResourceType), "", 1, "C", false, 0, "")
// Time period
- pdf.SetFont("Arial", "B", 10)
- pdf.CellFormat(30, 6, "Period:", "", 0, "L", false, 0, "")
+ pdf.SetY(200)
+ pdf.SetFont("Arial", "B", 11)
+ pdf.SetTextColor(colorTextMuted[0], colorTextMuted[1], colorTextMuted[2])
+ pdf.CellFormat(0, 7, "REPORTING PERIOD", "", 1, "C", false, 0, "")
+
+ pdf.SetFont("Arial", "", 12)
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+ periodStr := fmt.Sprintf("%s - %s",
+ data.Start.Format("January 2, 2006 15:04"),
+ data.End.Format("January 2, 2006 15:04"))
+ pdf.CellFormat(0, 8, periodStr, "", 1, "C", false, 0, "")
+
+ // Duration
+ duration := data.End.Sub(data.Start)
+ durationStr := formatDuration(duration)
pdf.SetFont("Arial", "", 10)
- periodStr := fmt.Sprintf("%s to %s", data.Start.Format("2006-01-02 15:04"), data.End.Format("2006-01-02 15:04"))
- pdf.CellFormat(0, 6, periodStr, "", 1, "L", false, 0, "")
-
- pdf.SetX(boxX + 5)
+ pdf.SetTextColor(colorTextMuted[0], colorTextMuted[1], colorTextMuted[2])
+ pdf.CellFormat(0, 6, fmt.Sprintf("(%s)", durationStr), "", 1, "C", false, 0, "")
- // Data points
- pdf.SetFont("Arial", "B", 10)
- pdf.CellFormat(30, 6, "Data Points:", "", 0, "L", false, 0, "")
+ // Bottom section
+ pdf.SetY(pageHeight - 50)
pdf.SetFont("Arial", "", 10)
- pdf.CellFormat(50, 6, fmt.Sprintf("%d", data.TotalPoints), "", 0, "L", false, 0, "")
+ pdf.SetTextColor(colorTextMuted[0], colorTextMuted[1], colorTextMuted[2])
+ pdf.CellFormat(0, 6, fmt.Sprintf("Generated: %s", data.GeneratedAt.Format("January 2, 2006 at 15:04 MST")), "", 1, "C", false, 0, "")
+ pdf.CellFormat(0, 6, fmt.Sprintf("Data Points: %d", data.TotalPoints), "", 1, "C", false, 0, "")
- pdf.SetFont("Arial", "B", 10)
- pdf.CellFormat(30, 6, "Generated:", "", 0, "L", false, 0, "")
+ // Bottom accent bar
+ pdf.SetFillColor(colorPrimary[0], colorPrimary[1], colorPrimary[2])
+ pdf.Rect(0, pageHeight-8, pageWidth, 8, "F")
+}
+
+// writeExecutiveSummary writes the executive summary with health status
+func (g *PDFGenerator) writeExecutiveSummary(pdf *fpdf.Fpdf, data *ReportData) {
+ pageWidth, _ := pdf.GetPageSize()
+
+ // Determine overall health status
+ healthStatus := "HEALTHY"
+ healthColor := colorAccent // Green
+ healthMessage := "All systems operating normally"
+
+ activeAlerts := 0
+ criticalAlerts := 0
+ warningAlerts := 0
+ for _, alert := range data.Alerts {
+ if alert.ResolvedTime == nil {
+ activeAlerts++
+ if alert.Level == "critical" {
+ criticalAlerts++
+ } else {
+ warningAlerts++
+ }
+ }
+ }
+
+ if criticalAlerts > 0 {
+ healthStatus = "CRITICAL"
+ healthColor = colorDanger
+ if criticalAlerts == 1 {
+ healthMessage = "1 critical issue requires immediate attention"
+ } else {
+ healthMessage = fmt.Sprintf("%d critical issues require immediate attention", criticalAlerts)
+ }
+ } else if warningAlerts > 0 {
+ healthStatus = "WARNING"
+ healthColor = colorWarning
+ if warningAlerts == 1 {
+ healthMessage = "1 warning detected - review recommended"
+ } else {
+ healthMessage = fmt.Sprintf("%d warnings detected - review recommended", warningAlerts)
+ }
+ }
+
+ // Health Status Card
+ cardX := 20.0
+ cardWidth := pageWidth - 40
+ cardHeight := 35.0
+
+ pdf.SetFillColor(healthColor[0], healthColor[1], healthColor[2])
+ pdf.RoundedRect(cardX, pdf.GetY(), cardWidth, cardHeight, 3, "1234", "F")
+
+ // Health status text
+ pdf.SetXY(cardX, pdf.GetY()+8)
+ pdf.SetFont("Arial", "B", 24)
+ pdf.SetTextColor(255, 255, 255)
+ pdf.CellFormat(cardWidth, 12, healthStatus, "", 1, "C", false, 0, "")
+
+ pdf.SetFont("Arial", "", 11)
+ pdf.CellFormat(cardWidth, 8, healthMessage, "", 1, "C", false, 0, "")
+
+ pdf.SetY(pdf.GetY() + 15)
+
+ // Quick Stats - simple table format (avoids fpdf positioning bugs)
+ pdf.SetFont("Arial", "B", 11)
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+ pdf.CellFormat(0, 8, "Quick Stats", "", 1, "L", false, 0, "")
+ pdf.Ln(2)
+
+ // Calculate stats
+ var avgCPU, avgMem, avgDisk float64
+ if stats, ok := data.Summary.ByMetric["cpu"]; ok {
+ avgCPU = stats.Avg
+ }
+ if stats, ok := data.Summary.ByMetric["memory"]; ok {
+ avgMem = stats.Avg
+ }
+ if stats, ok := data.Summary.ByMetric["disk"]; ok {
+ avgDisk = stats.Avg
+ } else if stats, ok := data.Summary.ByMetric["usage"]; ok {
+ avgDisk = stats.Avg
+ }
+
+ // Simple table header - darker text for better visibility
+ colWidth := 42.5
+ pdf.SetFillColor(colorBackground[0], colorBackground[1], colorBackground[2])
+ pdf.SetFont("Arial", "B", 9)
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+ pdf.CellFormat(colWidth, 7, "CPU", "0", 0, "C", true, 0, "")
+ pdf.CellFormat(colWidth, 7, "Memory", "0", 0, "C", true, 0, "")
+ pdf.CellFormat(colWidth, 7, "Disk", "0", 0, "C", true, 0, "")
+ pdf.CellFormat(colWidth, 7, "Alerts", "0", 1, "C", true, 0, "")
+
+ // Values row - large numbers
+ pdf.SetFont("Arial", "B", 16)
+ pdf.SetTextColor(getStatColor(avgCPU)[0], getStatColor(avgCPU)[1], getStatColor(avgCPU)[2])
+ pdf.CellFormat(colWidth, 9, fmt.Sprintf("%.1f%%", avgCPU), "0", 0, "C", false, 0, "")
+ pdf.SetTextColor(getStatColor(avgMem)[0], getStatColor(avgMem)[1], getStatColor(avgMem)[2])
+ pdf.CellFormat(colWidth, 9, fmt.Sprintf("%.1f%%", avgMem), "0", 0, "C", false, 0, "")
+ pdf.SetTextColor(getStatColor(avgDisk)[0], getStatColor(avgDisk)[1], getStatColor(avgDisk)[2])
+ pdf.CellFormat(colWidth, 9, fmt.Sprintf("%.1f%%", avgDisk), "0", 0, "C", false, 0, "")
+ pdf.SetTextColor(getAlertCountColor(activeAlerts)[0], getAlertCountColor(activeAlerts)[1], getAlertCountColor(activeAlerts)[2])
+ pdf.CellFormat(colWidth, 9, fmt.Sprintf("%d", activeAlerts), "0", 1, "C", false, 0, "")
+
+ // Labels row with trend indicators
+ pdf.SetFont("Arial", "", 7)
+ pdf.SetTextColor(colorTextMuted[0], colorTextMuted[1], colorTextMuted[2])
+
+ // Calculate trends (compare first half avg to second half avg)
+ cpuTrend := g.calculateTrend(data, "cpu")
+ memTrend := g.calculateTrend(data, "memory")
+ diskTrend := g.calculateTrend(data, "disk")
+ if diskTrend == "" {
+ diskTrend = g.calculateTrend(data, "usage")
+ }
+
+ pdf.CellFormat(colWidth, 5, "avg "+cpuTrend, "0", 0, "C", false, 0, "")
+ pdf.CellFormat(colWidth, 5, "avg "+memTrend, "0", 0, "C", false, 0, "")
+ pdf.CellFormat(colWidth, 5, "avg "+diskTrend, "0", 0, "C", false, 0, "")
+ pdf.CellFormat(colWidth, 5, "active now", "0", 1, "C", false, 0, "")
+
+ pdf.Ln(5)
+
+ // Key Observations section
+ pdf.SetFont("Arial", "B", 11)
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+ pdf.CellFormat(0, 8, "Key Observations", "", 1, "L", false, 0, "")
+ pdf.Ln(2)
+
+ observations := g.generateObservations(data)
pdf.SetFont("Arial", "", 10)
- pdf.CellFormat(0, 6, data.GeneratedAt.Format("2006-01-02 15:04:05"), "", 1, "L", false, 0, "")
+ for _, obs := range observations {
+ // Draw colored bullet circle
+ bulletX := pdf.GetX() + 3
+ bulletY := pdf.GetY() + 3
+ pdf.SetFillColor(obs.color[0], obs.color[1], obs.color[2])
+ pdf.Circle(bulletX, bulletY, 2, "F")
+ pdf.SetX(pdf.GetX() + 8)
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+ pdf.CellFormat(0, 6, obs.text, "", 1, "L", false, 0, "")
+ pdf.Ln(1)
+ }
+
+ // Active Alerts summary (if any)
+ if activeAlerts > 0 {
+ pdf.Ln(5)
+ pdf.SetFont("Arial", "B", 11)
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+ pdf.CellFormat(0, 8, "Active Alerts", "", 1, "L", false, 0, "")
+ pdf.Ln(2)
+
+ pdf.SetFont("Arial", "", 9)
+ alertCount := 0
+ for _, alert := range data.Alerts {
+ if alert.ResolvedTime == nil && alertCount < 5 {
+ if alert.Level == "critical" {
+ pdf.SetTextColor(colorDanger[0], colorDanger[1], colorDanger[2])
+ pdf.CellFormat(8, 5, "!", "", 0, "C", false, 0, "")
+ } else {
+ pdf.SetTextColor(colorWarning[0], colorWarning[1], colorWarning[2])
+ pdf.CellFormat(8, 5, "!", "", 0, "C", false, 0, "")
+ }
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+ msg := alert.Message
+ if len(msg) > 70 {
+ msg = msg[:67] + "..."
+ }
+ pdf.CellFormat(0, 5, msg, "", 1, "L", false, 0, "")
+ alertCount++
+ }
+ }
+ if activeAlerts > 5 {
+ pdf.SetTextColor(colorTextMuted[0], colorTextMuted[1], colorTextMuted[2])
+ pdf.CellFormat(0, 5, fmt.Sprintf("... and %d more alerts", activeAlerts-5), "", 1, "L", false, 0, "")
+ }
+ }
+
+ // Recommendations section
+ recommendations := g.generateRecommendations(data, criticalAlerts, warningAlerts)
+ if len(recommendations) > 0 {
+ pdf.Ln(5)
+ pdf.SetFont("Arial", "B", 11)
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+ pdf.CellFormat(0, 8, "Recommended Actions", "", 1, "L", false, 0, "")
+ pdf.Ln(2)
+
+ pdf.SetFont("Arial", "", 9)
+ for i, rec := range recommendations {
+ if i >= 4 {
+ break // Limit to 4 recommendations
+ }
+ pdf.SetTextColor(colorSecondary[0], colorSecondary[1], colorSecondary[2])
+ pdf.CellFormat(6, 5, fmt.Sprintf("%d.", i+1), "", 0, "L", false, 0, "")
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+ pdf.CellFormat(0, 5, rec, "", 1, "L", false, 0, "")
+ pdf.Ln(1)
+ }
+ }
pdf.Ln(10)
}
-// writeSummary writes the metrics summary table.
-func (g *PDFGenerator) writeSummary(pdf *fpdf.Fpdf, data *ReportData) {
- pdf.SetFont("Arial", "B", 14)
- pdf.SetTextColor(51, 51, 51)
- pdf.CellFormat(0, 10, "Summary", "", 1, "L", false, 0, "")
+// observation represents a key observation for the executive summary
+type observation struct {
+ icon string
+ text string
+ color [3]int
+}
- // Table header
- pdf.SetFillColor(66, 139, 202)
- pdf.SetTextColor(255, 255, 255)
- pdf.SetFont("Arial", "B", 10)
+// generateObservations analyzes the data and generates key observations
+func (g *PDFGenerator) generateObservations(data *ReportData) []observation {
+ var obs []observation
+
+ // Analyze CPU
+ if stats, ok := data.Summary.ByMetric["cpu"]; ok {
+ if stats.Max > 90 {
+ obs = append(obs, observation{
+ icon: "-",
+ text: fmt.Sprintf("CPU peaked at %.1f%% - potential capacity constraint", stats.Max),
+ color: colorDanger,
+ })
+ } else if stats.Avg < 20 {
+ obs = append(obs, observation{
+ icon: "-",
+ text: fmt.Sprintf("CPU averaging %.1f%% - resource is underutilized", stats.Avg),
+ color: colorAccent,
+ })
+ } else {
+ obs = append(obs, observation{
+ icon: "-",
+ text: fmt.Sprintf("CPU usage normal (avg %.1f%%, max %.1f%%)", stats.Avg, stats.Max),
+ color: colorAccent,
+ })
+ }
+ }
- colWidths := []float64{40, 25, 25, 25, 25, 25, 15}
- headers := []string{"Metric", "Count", "Min", "Max", "Avg", "Current", "Unit"}
+ // Analyze Memory
+ if stats, ok := data.Summary.ByMetric["memory"]; ok {
+ if stats.Avg > 85 {
+ obs = append(obs, observation{
+ icon: "-",
+ text: fmt.Sprintf("Memory consistently high at %.1f%% avg - consider scaling", stats.Avg),
+ color: colorDanger,
+ })
+ } else if stats.Max > 95 {
+ obs = append(obs, observation{
+ icon: "-",
+ text: fmt.Sprintf("Memory peaked at %.1f%% - near capacity", stats.Max),
+ color: colorWarning,
+ })
+ } else {
+ obs = append(obs, observation{
+ icon: "-",
+ text: fmt.Sprintf("Memory usage healthy (avg %.1f%%)", stats.Avg),
+ color: colorAccent,
+ })
+ }
+ }
- for i, header := range headers {
- pdf.CellFormat(colWidths[i], 8, header, "1", 0, "C", true, 0, "")
+ // Analyze Disk
+ diskKey := "disk"
+ if _, hasDisk := data.Summary.ByMetric["disk"]; !hasDisk {
+ if _, hasUsage := data.Summary.ByMetric["usage"]; hasUsage {
+ diskKey = "usage"
+ }
+ }
+ if stats, ok := data.Summary.ByMetric[diskKey]; ok {
+ if stats.Avg > 85 {
+ obs = append(obs, observation{
+ icon: "-",
+ text: fmt.Sprintf("Disk at %.1f%% - plan capacity expansion", stats.Avg),
+ color: colorDanger,
+ })
+ } else if stats.Avg > 70 {
+ obs = append(obs, observation{
+ icon: "-",
+ text: fmt.Sprintf("Disk at %.1f%% - monitor growth trend", stats.Avg),
+ color: colorWarning,
+ })
+ } else {
+ obs = append(obs, observation{
+ icon: "-",
+ text: fmt.Sprintf("Disk usage acceptable at %.1f%%", stats.Avg),
+ color: colorAccent,
+ })
+ }
}
- pdf.Ln(-1)
- // Table rows
- pdf.SetFillColor(255, 255, 255)
- pdf.SetTextColor(51, 51, 51)
+ // Alert summary
+ resolved := 0
+ for _, alert := range data.Alerts {
+ if alert.ResolvedTime != nil {
+ resolved++
+ }
+ }
+ if resolved > 0 {
+ obs = append(obs, observation{
+ icon: "-",
+ text: fmt.Sprintf("%d alerts were triggered and resolved during this period", resolved),
+ color: colorSecondary,
+ })
+ }
+
+ // Physical disk wear level check
+ for _, disk := range data.Disks {
+ if disk.WearLevel >= 90 {
+ obs = append(obs, observation{
+ icon: "-",
+ text: fmt.Sprintf("CRITICAL: Disk %s at %d%% wear - replace immediately", disk.Device, disk.WearLevel),
+ color: colorDanger,
+ })
+ } else if disk.WearLevel >= 70 {
+ obs = append(obs, observation{
+ icon: "-",
+ text: fmt.Sprintf("Disk %s at %d%% wear - plan replacement", disk.Device, disk.WearLevel),
+ color: colorWarning,
+ })
+ }
+ // Check disk health
+ if disk.Health == "FAILED" {
+ obs = append(obs, observation{
+ icon: "-",
+ text: fmt.Sprintf("CRITICAL: Disk %s SMART health check FAILED", disk.Device),
+ color: colorDanger,
+ })
+ }
+ }
+
+ // Uptime observation
+ if data.Resource != nil && data.Resource.Uptime > 0 {
+ uptimeDays := data.Resource.Uptime / 86400
+ if uptimeDays > 90 {
+ obs = append(obs, observation{
+ icon: "-",
+ text: fmt.Sprintf("System uptime: %d days - consider scheduling maintenance", uptimeDays),
+ color: colorWarning,
+ })
+ }
+ }
+
+ // If no observations, add a default one
+ if len(obs) == 0 {
+ obs = append(obs, observation{
+ icon: "-",
+ text: "Insufficient data for detailed analysis",
+ color: colorTextMuted,
+ })
+ }
+
+ return obs
+}
+
+// calculateTrend compares first half to second half of data points
+func (g *PDFGenerator) calculateTrend(data *ReportData, metricType string) string {
+ points, ok := data.Metrics[metricType]
+ if !ok || len(points) < 10 {
+ return ""
+ }
+
+ // Calculate average of first half and second half
+ mid := len(points) / 2
+ var firstSum, secondSum float64
+ for i := 0; i < mid; i++ {
+ firstSum += points[i].Value
+ }
+ for i := mid; i < len(points); i++ {
+ secondSum += points[i].Value
+ }
+ firstAvg := firstSum / float64(mid)
+ secondAvg := secondSum / float64(len(points)-mid)
+
+ // Calculate percentage change
+ if firstAvg == 0 {
+ return ""
+ }
+ change := ((secondAvg - firstAvg) / firstAvg) * 100
+
+ // Only show trend if significant (>5% change)
+ if change > 5 {
+ return "(trending up)"
+ } else if change < -5 {
+ return "(trending down)"
+ }
+ return "(stable)"
+}
+
+// generateRecommendations creates actionable recommendations based on data
+func (g *PDFGenerator) generateRecommendations(data *ReportData, criticalAlerts, warningAlerts int) []string {
+ var recs []string
+
+ // Critical disk wear - highest priority
+ for _, disk := range data.Disks {
+ if disk.WearLevel >= 90 {
+ recs = append(recs, fmt.Sprintf("Replace disk %s immediately (wear level at %d%%)", disk.Device, disk.WearLevel))
+ } else if disk.WearLevel >= 70 {
+ recs = append(recs, fmt.Sprintf("Schedule replacement for disk %s within 3-6 months", disk.Device))
+ }
+ if disk.Health == "FAILED" {
+ recs = append(recs, fmt.Sprintf("Investigate and replace disk %s - SMART health check failed", disk.Device))
+ }
+ }
+
+ // Critical alerts need attention
+ if criticalAlerts > 0 {
+ recs = append(recs, "Investigate and resolve critical alerts immediately")
+ }
+
+ // High resource usage
+ if stats, ok := data.Summary.ByMetric["memory"]; ok {
+ if stats.Avg > 85 {
+ recs = append(recs, "Consider adding memory or optimizing memory-intensive workloads")
+ }
+ }
+ if stats, ok := data.Summary.ByMetric["cpu"]; ok {
+ if stats.Max > 90 {
+ recs = append(recs, "Review CPU-intensive processes during peak usage periods")
+ }
+ }
+
+ // Disk space
+ diskKey := "disk"
+ if _, ok := data.Summary.ByMetric["disk"]; !ok {
+ diskKey = "usage"
+ }
+ if stats, ok := data.Summary.ByMetric[diskKey]; ok {
+ if stats.Avg > 85 {
+ recs = append(recs, "Clean up disk space or expand storage capacity")
+ }
+ }
+
+ // Storage pool warnings
+ for _, storage := range data.Storage {
+ if storage.UsagePerc >= 90 {
+ recs = append(recs, fmt.Sprintf("Expand storage pool '%s' (currently at %.0f%% capacity)", storage.Name, storage.UsagePerc))
+ }
+ }
+
+ // Long uptime
+ if data.Resource != nil && data.Resource.Uptime > 0 {
+ uptimeDays := data.Resource.Uptime / 86400
+ if uptimeDays > 90 {
+ recs = append(recs, "Schedule maintenance window to apply pending updates and reboot")
+ }
+ }
+
+ // Underutilization suggestion
+ if stats, ok := data.Summary.ByMetric["cpu"]; ok {
+ if stats.Avg < 10 && len(recs) == 0 {
+ recs = append(recs, "System is underutilized - consider consolidating workloads")
+ }
+ }
+
+ // Default good state message
+ if len(recs) == 0 {
+ recs = append(recs, "No immediate action required - continue monitoring")
+ }
+
+ return recs
+}
+
+// getStatColor returns color based on percentage value
+func getStatColor(val float64) [3]int {
+ if val >= 90 {
+ return colorDanger
+ } else if val >= 75 {
+ return colorWarning
+ }
+ return colorAccent
+}
+
+// getAlertCountColor returns color based on alert count
+func getAlertCountColor(count int) [3]int {
+ if count > 0 {
+ return colorDanger
+ }
+ return colorAccent
+}
+
+// addPageHeader adds a consistent header to content pages.
+func (g *PDFGenerator) addPageHeader(pdf *fpdf.Fpdf, data *ReportData, section string) {
+ pageWidth, _ := pdf.GetPageSize()
+
+ // Top line
+ pdf.SetDrawColor(colorPrimary[0], colorPrimary[1], colorPrimary[2])
+ pdf.SetLineWidth(0.5)
+ pdf.Line(20, 15, pageWidth-20, 15)
+
+ // Header text
+ pdf.SetY(18)
+ pdf.SetFont("Arial", "B", 9)
+ pdf.SetTextColor(colorPrimary[0], colorPrimary[1], colorPrimary[2])
+ pdf.CellFormat(0, 5, "PULSE PERFORMANCE REPORT", "", 0, "L", false, 0, "")
+
pdf.SetFont("Arial", "", 9)
+ pdf.SetTextColor(colorTextMuted[0], colorTextMuted[1], colorTextMuted[2])
+ pdf.CellFormat(0, 5, data.ResourceID, "", 1, "R", false, 0, "")
+
+ // Section title
+ pdf.SetY(30)
+ pdf.SetFont("Arial", "B", 18)
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+ pdf.CellFormat(0, 10, section, "", 1, "L", false, 0, "")
+
+ pdf.Ln(5)
+}
+
+// writeSummarySection writes the metrics summary with stats cards.
+func (g *PDFGenerator) writeSummarySection(pdf *fpdf.Fpdf, data *ReportData) {
+ // Time period subtitle
+ pdf.SetFont("Arial", "", 10)
+ pdf.SetTextColor(colorTextMuted[0], colorTextMuted[1], colorTextMuted[2])
+ periodStr := fmt.Sprintf("Statistics for %s to %s (%s)",
+ data.Start.Format("Jan 2, 2006 15:04"),
+ data.End.Format("Jan 2, 2006 15:04"),
+ formatDuration(data.End.Sub(data.Start)))
+ pdf.CellFormat(0, 6, periodStr, "", 1, "L", false, 0, "")
+ pdf.Ln(5)
+
+ if len(data.Summary.ByMetric) == 0 {
+ pdf.SetFont("Arial", "I", 11)
+ pdf.SetTextColor(colorTextMuted[0], colorTextMuted[1], colorTextMuted[2])
+ pdf.CellFormat(0, 10, "No metrics data available for this period.", "", 1, "L", false, 0, "")
+ return
+ }
// Get sorted metric names
metricNames := make([]string, 0, len(data.Summary.ByMetric))
@@ -146,42 +712,104 @@ func (g *PDFGenerator) writeSummary(pdf *fpdf.Fpdf, data *ReportData) {
}
sort.Strings(metricNames)
- fill := false
- for _, metricType := range metricNames {
+ // Stats cards - 2 per row
+ cardWidth := 82.0
+ cardHeight := 45.0
+ cardGap := 6.0
+ startX := 20.0
+ rowStartY := pdf.GetY()
+
+ for i, metricType := range metricNames {
stats := data.Summary.ByMetric[metricType]
unit := GetMetricUnit(metricType)
- if fill {
- pdf.SetFillColor(245, 245, 245)
- } else {
- pdf.SetFillColor(255, 255, 255)
+ col := i % 2
+ if col == 0 && i > 0 {
+ // Move to next row
+ rowStartY = rowStartY + cardHeight + cardGap
+ pdf.SetY(rowStartY)
+ } else if col == 1 {
+ // Second column - return to row start Y
+ pdf.SetY(rowStartY)
}
- pdf.CellFormat(colWidths[0], 7, GetMetricTypeDisplayName(metricType), "1", 0, "L", fill, 0, "")
- pdf.CellFormat(colWidths[1], 7, fmt.Sprintf("%d", stats.Count), "1", 0, "C", fill, 0, "")
- pdf.CellFormat(colWidths[2], 7, formatValue(stats.Min, unit), "1", 0, "C", fill, 0, "")
- pdf.CellFormat(colWidths[3], 7, formatValue(stats.Max, unit), "1", 0, "C", fill, 0, "")
- pdf.CellFormat(colWidths[4], 7, formatValue(stats.Avg, unit), "1", 0, "C", fill, 0, "")
- pdf.CellFormat(colWidths[5], 7, formatValue(stats.Current, unit), "1", 0, "C", fill, 0, "")
- pdf.CellFormat(colWidths[6], 7, unit, "1", 0, "C", fill, 0, "")
- pdf.Ln(-1)
-
- fill = !fill
+ cardX := startX + float64(col)*(cardWidth+cardGap)
+ cardY := rowStartY
+
+ // Card background
+ pdf.SetFillColor(255, 255, 255)
+ pdf.SetDrawColor(colorGridLine[0], colorGridLine[1], colorGridLine[2])
+ pdf.RoundedRect(cardX, cardY, cardWidth, cardHeight, 2, "1234", "FD")
+
+ // Card header with color bar
+ headerColor := getMetricColor(metricType)
+ pdf.SetFillColor(headerColor[0], headerColor[1], headerColor[2])
+ pdf.Rect(cardX, cardY, cardWidth, 3, "F")
+
+ // Metric name
+ pdf.SetXY(cardX+5, cardY+6)
+ pdf.SetFont("Arial", "B", 10)
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+ pdf.CellFormat(cardWidth-10, 6, GetMetricTypeDisplayName(metricType), "", 1, "L", false, 0, "")
+
+ // Current value (large)
+ pdf.SetXY(cardX+5, cardY+14)
+ pdf.SetFont("Arial", "B", 20)
+ pdf.SetTextColor(headerColor[0], headerColor[1], headerColor[2])
+ pdf.CellFormat(cardWidth-10, 10, formatValue(stats.Current, unit)+unit, "", 1, "L", false, 0, "")
+
+ // Stats row
+ pdf.SetFont("Arial", "", 8)
+ pdf.SetTextColor(colorTextMuted[0], colorTextMuted[1], colorTextMuted[2])
+ statsY := cardY + 28
+
+ // Min
+ pdf.SetXY(cardX+5, statsY)
+ pdf.CellFormat(25, 5, "Min", "", 0, "L", false, 0, "")
+ pdf.SetFont("Arial", "B", 8)
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+ pdf.CellFormat(0, 5, formatValue(stats.Min, unit)+unit, "", 1, "L", false, 0, "")
+
+ // Max
+ pdf.SetFont("Arial", "", 8)
+ pdf.SetTextColor(colorTextMuted[0], colorTextMuted[1], colorTextMuted[2])
+ pdf.SetXY(cardX+5, statsY+6)
+ pdf.CellFormat(25, 5, "Max", "", 0, "L", false, 0, "")
+ pdf.SetFont("Arial", "B", 8)
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+ pdf.CellFormat(0, 5, formatValue(stats.Max, unit)+unit, "", 1, "L", false, 0, "")
+
+ // Avg
+ pdf.SetFont("Arial", "", 8)
+ pdf.SetTextColor(colorTextMuted[0], colorTextMuted[1], colorTextMuted[2])
+ pdf.SetXY(cardX+45, statsY)
+ pdf.CellFormat(15, 5, "Avg", "", 0, "L", false, 0, "")
+ pdf.SetFont("Arial", "B", 8)
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+ pdf.CellFormat(0, 5, formatValue(stats.Avg, unit)+unit, "", 1, "L", false, 0, "")
+
+ // Count
+ pdf.SetFont("Arial", "", 8)
+ pdf.SetTextColor(colorTextMuted[0], colorTextMuted[1], colorTextMuted[2])
+ pdf.SetXY(cardX+45, statsY+6)
+ pdf.CellFormat(15, 5, "Samples", "", 0, "L", false, 0, "")
+ pdf.SetFont("Arial", "B", 8)
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+ pdf.CellFormat(0, 5, fmt.Sprintf("%d", stats.Count), "", 1, "L", false, 0, "")
}
- pdf.Ln(10)
+ // Calculate final Y position based on number of rows
+ numRows := (len(metricNames) + 1) / 2 // Round up
+ finalY := rowStartY + float64(numRows)*(cardHeight+cardGap)
+ pdf.SetY(finalY)
}
-// writeCharts writes simple line charts for each metric.
-func (g *PDFGenerator) writeCharts(pdf *fpdf.Fpdf, data *ReportData) {
+// writeChartsSection writes charts for each metric.
+func (g *PDFGenerator) writeChartsSection(pdf *fpdf.Fpdf, data *ReportData) {
if len(data.Metrics) == 0 {
return
}
- pdf.SetFont("Arial", "B", 14)
- pdf.SetTextColor(51, 51, 51)
- pdf.CellFormat(0, 10, "Charts", "", 1, "L", false, 0, "")
-
// Get sorted metric names
metricNames := make([]string, 0, len(data.Metrics))
for name := range data.Metrics {
@@ -189,141 +817,196 @@ func (g *PDFGenerator) writeCharts(pdf *fpdf.Fpdf, data *ReportData) {
}
sort.Strings(metricNames)
- chartWidth := 180.0
- chartHeight := 50.0
- colors := [][]int{
- {66, 139, 202}, // Blue
- {92, 184, 92}, // Green
- {240, 173, 78}, // Orange
- {217, 83, 79}, // Red
- {153, 102, 204}, // Purple
+ chartWidth := 170.0
+ chartHeight := 55.0
+
+ // Count valid charts
+ validCharts := 0
+ for _, metricType := range metricNames {
+ if len(data.Metrics[metricType]) >= 2 {
+ validCharts++
+ }
+ }
+ if validCharts == 0 {
+ return
}
- for i, metricType := range metricNames {
+ // Always start charts on a new page with proper header
+ pdf.AddPage()
+ g.addPageHeader(pdf, data, "Performance Charts")
+
+ for _, metricType := range metricNames {
points := data.Metrics[metricType]
if len(points) < 2 {
continue
}
- // Check if we need a new page
- if pdf.GetY() > 220 {
+ // Check if we need a new page (need space for chart title + chart + labels)
+ if pdf.GetY() > 195 {
pdf.AddPage()
+ g.addPageHeader(pdf, data, "Performance Charts")
}
// Chart title
pdf.SetFont("Arial", "B", 11)
- pdf.SetTextColor(51, 51, 51)
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
unit := GetMetricUnit(metricType)
titleStr := GetMetricTypeDisplayName(metricType)
if unit != "" {
titleStr = fmt.Sprintf("%s (%s)", titleStr, unit)
}
- pdf.CellFormat(0, 8, titleStr, "", 1, "L", false, 0, "")
+ pdf.CellFormat(0, 7, titleStr, "", 1, "L", false, 0, "")
- // Draw chart background
- chartX := 15.0
+ chartX := 20.0
chartY := pdf.GetY()
- pdf.SetFillColor(250, 250, 250)
- pdf.SetDrawColor(200, 200, 200)
- pdf.Rect(chartX, chartY, chartWidth, chartHeight, "FD")
+ g.drawChart(pdf, points, chartX, chartY, chartWidth, chartHeight, metricType)
- // Find min/max for scaling
- minVal, maxVal := points[0].Value, points[0].Value
- for _, p := range points {
- if p.Value < minVal {
- minVal = p.Value
- }
- if p.Value > maxVal {
- maxVal = p.Value
- }
- }
+ pdf.SetY(chartY + chartHeight + 12)
+ }
+}
- // Add padding to min/max
- valRange := maxVal - minVal
- if valRange < 0.1 {
- valRange = 10 // Minimum range for flat lines
+// drawChart draws a single chart with grid, area fill, and line.
+func (g *PDFGenerator) drawChart(pdf *fpdf.Fpdf, points []MetricDataPoint, x, y, width, height float64, metricType string) {
+ // Chart background
+ pdf.SetFillColor(255, 255, 255)
+ pdf.SetDrawColor(colorGridLine[0], colorGridLine[1], colorGridLine[2])
+ pdf.SetLineWidth(0.3)
+ pdf.Rect(x, y, width, height, "FD")
+
+ // Find min/max for scaling
+ minVal, maxVal := points[0].Value, points[0].Value
+ for _, p := range points {
+ if p.Value < minVal {
+ minVal = p.Value
+ }
+ if p.Value > maxVal {
+ maxVal = p.Value
}
- minVal = math.Max(0, minVal-valRange*0.1)
- maxVal = maxVal + valRange*0.1
+ }
- // Draw Y-axis labels
- pdf.SetFont("Arial", "", 7)
- pdf.SetTextColor(128, 128, 128)
+ // Add padding to range
+ valRange := maxVal - minVal
+ if valRange < 1 {
+ valRange = 10
+ }
+ minVal = math.Max(0, minVal-valRange*0.1)
+ maxVal = maxVal + valRange*0.1
+
+ // Draw horizontal grid lines and Y-axis labels
+ pdf.SetFont("Arial", "", 7)
+ numGridLines := 5
+ for i := 0; i <= numGridLines; i++ {
+ gridY := y + height - (float64(i)/float64(numGridLines))*height
+ val := minVal + (float64(i)/float64(numGridLines))*(maxVal-minVal)
+
+ // Grid line
+ pdf.SetDrawColor(colorGridLine[0], colorGridLine[1], colorGridLine[2])
+ pdf.SetLineWidth(0.1)
+ pdf.Line(x, gridY, x+width, gridY)
+
+ // Y-axis label
+ pdf.SetTextColor(colorTextMuted[0], colorTextMuted[1], colorTextMuted[2])
+ pdf.SetXY(x-15, gridY-2)
+ pdf.CellFormat(12, 5, fmt.Sprintf("%.0f", val), "", 0, "R", false, 0, "")
+ }
- // Max label
- pdf.SetXY(chartX-12, chartY)
- pdf.CellFormat(10, 5, fmt.Sprintf("%.0f", maxVal), "", 0, "R", false, 0, "")
+ // Time calculations
+ startTime := points[0].Timestamp.Unix()
+ endTime := points[len(points)-1].Timestamp.Unix()
+ timeRange := float64(endTime - startTime)
+ if timeRange == 0 {
+ timeRange = 1
+ }
- // Min label
- pdf.SetXY(chartX-12, chartY+chartHeight-5)
- pdf.CellFormat(10, 5, fmt.Sprintf("%.0f", minVal), "", 0, "R", false, 0, "")
+ // Build polygon points for area fill
+ chartColor := getMetricColor(metricType)
- // Draw line chart
- color := colors[i%len(colors)]
- pdf.SetDrawColor(color[0], color[1], color[2])
- pdf.SetLineWidth(0.5)
+ // Draw area fill
+ pdf.SetFillColor(chartColor[0], chartColor[1], chartColor[2])
+ pdf.SetAlpha(0.15, "Normal")
- startTime := points[0].Timestamp.Unix()
- endTime := points[len(points)-1].Timestamp.Unix()
- timeRange := float64(endTime - startTime)
- if timeRange == 0 {
- timeRange = 1
- }
+ polyStr := ""
+ for i, p := range points {
+ xPos := x + 2 + (float64(p.Timestamp.Unix()-startTime)/timeRange)*(width-4)
+ yPos := y + height - 2 - ((p.Value-minVal)/(maxVal-minVal))*(height-4)
+ yPos = math.Max(y+2, math.Min(y+height-2, yPos))
- prevX, prevY := 0.0, 0.0
- for j, p := range points {
- // Calculate position
- xPos := chartX + 2 + (float64(p.Timestamp.Unix()-startTime)/timeRange)*(chartWidth-4)
- yPos := chartY + chartHeight - 2 - ((p.Value-minVal)/(maxVal-minVal))*(chartHeight-4)
+ if i == 0 {
+ polyStr = fmt.Sprintf("%.2f %.2f m ", xPos, y+height-2)
+ }
+ polyStr += fmt.Sprintf("%.2f %.2f l ", xPos, yPos)
+ }
+ // Close polygon
+ lastX := x + 2 + (float64(points[len(points)-1].Timestamp.Unix()-startTime)/timeRange)*(width-4)
+ polyStr += fmt.Sprintf("%.2f %.2f l h f", lastX, y+height-2)
+
+ // Use raw PDF drawing for polygon
+ // Actually, fpdf doesn't support arbitrary polygons easily, so we'll use a different approach
+ // Draw as many small rectangles to approximate the fill
+ pdf.SetAlpha(0.2, "Normal")
+ for i := 1; i < len(points); i++ {
+ p1 := points[i-1]
+ p2 := points[i]
+
+ x1 := x + 2 + (float64(p1.Timestamp.Unix()-startTime)/timeRange)*(width-4)
+ x2 := x + 2 + (float64(p2.Timestamp.Unix()-startTime)/timeRange)*(width-4)
+ y1 := y + height - 2 - ((p1.Value-minVal)/(maxVal-minVal))*(height-4)
+ y2 := y + height - 2 - ((p2.Value-minVal)/(maxVal-minVal))*(height-4)
+
+ y1 = math.Max(y+2, math.Min(y+height-2, y1))
+ y2 = math.Max(y+2, math.Min(y+height-2, y2))
+
+ // Draw trapezoid approximation using polygon
+ pdf.Polygon([]fpdf.PointType{
+ {X: x1, Y: y1},
+ {X: x2, Y: y2},
+ {X: x2, Y: y + height - 2},
+ {X: x1, Y: y + height - 2},
+ }, "F")
+ }
- // Clamp Y position
- if yPos < chartY+2 {
- yPos = chartY + 2
- }
- if yPos > chartY+chartHeight-2 {
- yPos = chartY + chartHeight - 2
- }
+ pdf.SetAlpha(1, "Normal")
- if j > 0 {
- pdf.Line(prevX, prevY, xPos, yPos)
- }
- prevX, prevY = xPos, yPos
- }
+ // Draw the line
+ pdf.SetDrawColor(chartColor[0], chartColor[1], chartColor[2])
+ pdf.SetLineWidth(0.8)
- // Draw X-axis labels (start and end time)
- pdf.SetFont("Arial", "", 7)
- pdf.SetTextColor(128, 128, 128)
- pdf.SetXY(chartX, chartY+chartHeight+1)
- pdf.CellFormat(40, 4, points[0].Timestamp.Format("01/02 15:04"), "", 0, "L", false, 0, "")
- pdf.SetXY(chartX+chartWidth-40, chartY+chartHeight+1)
- pdf.CellFormat(40, 4, points[len(points)-1].Timestamp.Format("01/02 15:04"), "", 0, "R", false, 0, "")
+ prevX, prevY := 0.0, 0.0
+ for i, p := range points {
+ xPos := x + 2 + (float64(p.Timestamp.Unix()-startTime)/timeRange)*(width-4)
+ yPos := y + height - 2 - ((p.Value-minVal)/(maxVal-minVal))*(height-4)
+ yPos = math.Max(y+2, math.Min(y+height-2, yPos))
- pdf.SetY(chartY + chartHeight + 10)
+ if i > 0 {
+ pdf.Line(prevX, prevY, xPos, yPos)
+ }
+ prevX, prevY = xPos, yPos
}
- pdf.Ln(5)
+ // X-axis labels
+ pdf.SetFont("Arial", "", 7)
+ pdf.SetTextColor(colorTextMuted[0], colorTextMuted[1], colorTextMuted[2])
+ pdf.SetXY(x, y+height+1)
+ pdf.CellFormat(40, 4, points[0].Timestamp.Format("Jan 2 15:04"), "", 0, "L", false, 0, "")
+ pdf.SetXY(x+width-40, y+height+1)
+ pdf.CellFormat(40, 4, points[len(points)-1].Timestamp.Format("Jan 2 15:04"), "", 0, "R", false, 0, "")
}
-// writeDataTable writes a detailed data table (limited rows).
-func (g *PDFGenerator) writeDataTable(pdf *fpdf.Fpdf, data *ReportData) {
+// writeDataSection writes the data table.
+func (g *PDFGenerator) writeDataSection(pdf *fpdf.Fpdf, data *ReportData) {
if len(data.Metrics) == 0 {
return
}
- // Check if we need a new page
- if pdf.GetY() > 200 {
- pdf.AddPage()
- }
-
- pdf.SetFont("Arial", "B", 14)
- pdf.SetTextColor(51, 51, 51)
- pdf.CellFormat(0, 10, "Data Sample", "", 1, "L", false, 0, "")
+ // Always start data section on a new page with proper header
+ pdf.AddPage()
+ g.addPageHeader(pdf, data, "Data Sample")
- pdf.SetFont("Arial", "", 8)
- pdf.SetTextColor(128, 128, 128)
- pdf.CellFormat(0, 5, "Showing first 50 data points. Export as CSV for complete data.", "", 1, "L", false, 0, "")
- pdf.Ln(2)
+ pdf.SetFont("Arial", "", 9)
+ pdf.SetTextColor(colorTextMuted[0], colorTextMuted[1], colorTextMuted[2])
+ pdf.CellFormat(0, 6, "Showing up to 50 data points. Export as CSV for the complete dataset.", "", 1, "L", false, 0, "")
+ pdf.Ln(3)
// Get sorted metric names
metricNames := make([]string, 0, len(data.Metrics))
@@ -332,29 +1015,34 @@ func (g *PDFGenerator) writeDataTable(pdf *fpdf.Fpdf, data *ReportData) {
}
sort.Strings(metricNames)
- // Build columns
- numCols := len(metricNames) + 1 // +1 for timestamp
- colWidth := 180.0 / float64(numCols)
- if colWidth < 25 {
- colWidth = 25
+ // Calculate column widths - ensure enough space for metric headers
+ timestampWidth := 35.0
+ availableWidth := 170.0 - timestampWidth
+ metricWidth := availableWidth / float64(len(metricNames))
+ if metricWidth < 30 {
+ metricWidth = 30
}
// Table header
- pdf.SetFillColor(66, 139, 202)
+ pdf.SetFillColor(colorTableHeader[0], colorTableHeader[1], colorTableHeader[2])
pdf.SetTextColor(255, 255, 255)
- pdf.SetFont("Arial", "B", 8)
+ pdf.SetFont("Arial", "B", 7)
- pdf.CellFormat(35, 6, "Timestamp", "1", 0, "C", true, 0, "")
+ pdf.CellFormat(timestampWidth, 7, "Timestamp", "1", 0, "C", true, 0, "")
for _, name := range metricNames {
displayName := GetMetricTypeDisplayName(name)
- if len(displayName) > 12 {
- displayName = displayName[:12]
+ unit := GetMetricUnit(name)
+ if unit != "" {
+ displayName = fmt.Sprintf("%s (%s)", displayName, unit)
+ }
+ if len(displayName) > 18 {
+ displayName = displayName[:18]
}
- pdf.CellFormat(colWidth, 6, displayName, "1", 0, "C", true, 0, "")
+ pdf.CellFormat(metricWidth, 7, displayName, "1", 0, "C", true, 0, "")
}
pdf.Ln(-1)
- // Collect all timestamps
+ // Collect timestamps
timestampSet := make(map[int64]bool)
metricsByTime := make(map[string]map[int64]float64)
@@ -373,63 +1061,617 @@ func (g *PDFGenerator) writeDataTable(pdf *fpdf.Fpdf, data *ReportData) {
}
sort.Slice(timestamps, func(i, j int) bool { return timestamps[i] < timestamps[j] })
- // Limit to 50 rows
+ // Limit rows
if len(timestamps) > 50 {
timestamps = timestamps[:50]
}
// Table rows
- pdf.SetTextColor(51, 51, 51)
- pdf.SetFont("Arial", "", 8)
+ pdf.SetFont("Arial", "", 7)
fill := false
- for _, ts := range timestamps {
+ for rowIdx, ts := range timestamps {
// Check page break
- if pdf.GetY() > 270 {
+ if pdf.GetY() > 260 {
pdf.AddPage()
+ g.addPageHeader(pdf, data, "Data Sample (continued)")
+ pdf.Ln(5)
+
// Re-draw header
- pdf.SetFillColor(66, 139, 202)
+ pdf.SetFillColor(colorTableHeader[0], colorTableHeader[1], colorTableHeader[2])
pdf.SetTextColor(255, 255, 255)
- pdf.SetFont("Arial", "B", 8)
- pdf.CellFormat(35, 6, "Timestamp", "1", 0, "C", true, 0, "")
+ pdf.SetFont("Arial", "B", 7)
+ pdf.CellFormat(timestampWidth, 7, "Timestamp", "1", 0, "C", true, 0, "")
for _, name := range metricNames {
displayName := GetMetricTypeDisplayName(name)
- if len(displayName) > 12 {
- displayName = displayName[:12]
+ unit := GetMetricUnit(name)
+ if unit != "" {
+ displayName = fmt.Sprintf("%s (%s)", displayName, unit)
}
- pdf.CellFormat(colWidth, 6, displayName, "1", 0, "C", true, 0, "")
+ if len(displayName) > 18 {
+ displayName = displayName[:18]
+ }
+ pdf.CellFormat(metricWidth, 7, displayName, "1", 0, "C", true, 0, "")
}
pdf.Ln(-1)
- pdf.SetTextColor(51, 51, 51)
- pdf.SetFont("Arial", "", 8)
+ pdf.SetFont("Arial", "", 7)
fill = false
}
if fill {
- pdf.SetFillColor(245, 245, 245)
+ pdf.SetFillColor(colorTableAlt[0], colorTableAlt[1], colorTableAlt[2])
} else {
pdf.SetFillColor(255, 255, 255)
}
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
t := time.Unix(ts, 0)
- pdf.CellFormat(35, 5, t.Format("01/02 15:04:05"), "1", 0, "L", fill, 0, "")
+ pdf.CellFormat(timestampWidth, 6, t.Format("Jan 02 15:04:05"), "1", 0, "L", fill, 0, "")
for _, metricName := range metricNames {
if val, ok := metricsByTime[metricName][ts]; ok {
- pdf.CellFormat(colWidth, 5, fmt.Sprintf("%.2f", val), "1", 0, "C", fill, 0, "")
+ pdf.CellFormat(metricWidth, 6, fmt.Sprintf("%.2f", val), "1", 0, "C", fill, 0, "")
} else {
- pdf.CellFormat(colWidth, 5, "-", "1", 0, "C", fill, 0, "")
+ pdf.SetTextColor(colorTextMuted[0], colorTextMuted[1], colorTextMuted[2])
+ pdf.CellFormat(metricWidth, 6, "-", "1", 0, "C", fill, 0, "")
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+ }
+ }
+ pdf.Ln(-1)
+ fill = !fill
+ _ = rowIdx
+ }
+}
+
+// writeResourceDetails writes resource information section
+func (g *PDFGenerator) writeResourceDetails(pdf *fpdf.Fpdf, data *ReportData) {
+ if data.Resource == nil {
+ return
+ }
+
+ res := data.Resource
+
+ // Info grid - 2 columns for short fields, full width for long fields
+ pdf.SetFont("Arial", "", 10)
+ leftCol := 20.0
+ rightCol := 105.0
+ labelWidth := 30.0
+ valueWidth := 50.0
+
+ // Helper to write a label-value pair in a column
+ writeField := func(x float64, label, value string) {
+ pdf.SetXY(x, pdf.GetY())
+ pdf.SetFont("Arial", "", 9)
+ pdf.SetTextColor(colorTextMuted[0], colorTextMuted[1], colorTextMuted[2])
+ pdf.CellFormat(labelWidth, 6, label, "", 0, "L", false, 0, "")
+ pdf.SetFont("Arial", "B", 9)
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+ // Truncate long values to fit in column
+ if len(value) > 35 {
+ value = value[:32] + "..."
+ }
+ pdf.CellFormat(valueWidth, 6, value, "", 0, "L", false, 0, "")
+ }
+
+ // Helper to write a full-width label-value pair
+ writeFullWidth := func(label, value string) {
+ pdf.SetX(leftCol)
+ pdf.SetFont("Arial", "", 9)
+ pdf.SetTextColor(colorTextMuted[0], colorTextMuted[1], colorTextMuted[2])
+ pdf.CellFormat(labelWidth, 6, label, "", 0, "L", false, 0, "")
+ pdf.SetFont("Arial", "B", 9)
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+ // Allow longer values for full-width fields
+ if len(value) > 80 {
+ value = value[:77] + "..."
+ }
+ pdf.CellFormat(0, 6, value, "", 1, "L", false, 0, "")
+ }
+
+ startY := pdf.GetY()
+
+ // Left column - basic info
+ writeField(leftCol, "Name:", res.Name)
+ pdf.SetY(pdf.GetY() + 7)
+ writeField(leftCol, "Status:", res.Status)
+ pdf.SetY(pdf.GetY() + 7)
+ if res.Node != "" {
+ writeField(leftCol, "Node:", res.Node)
+ pdf.SetY(pdf.GetY() + 7)
+ }
+ if res.Host != "" {
+ writeField(leftCol, "Host:", res.Host)
+ pdf.SetY(pdf.GetY() + 7)
+ }
+ if res.Uptime > 0 {
+ writeField(leftCol, "Uptime:", formatUptime(res.Uptime))
+ pdf.SetY(pdf.GetY() + 7)
+ }
+
+ leftEndY := pdf.GetY()
+
+ // Right column - hardware info
+ pdf.SetY(startY)
+ if res.CPUCores > 0 {
+ coreStr := fmt.Sprintf("%d cores", res.CPUCores)
+ if res.CPUSockets > 0 {
+ coreStr = fmt.Sprintf("%d cores (%d sockets)", res.CPUCores, res.CPUSockets)
+ }
+ writeField(rightCol, "Cores:", coreStr)
+ pdf.SetY(pdf.GetY() + 7)
+ }
+ if res.MemoryTotal > 0 {
+ writeField(rightCol, "Memory:", formatBytes(float64(res.MemoryTotal)))
+ pdf.SetY(pdf.GetY() + 7)
+ }
+ if res.DiskTotal > 0 {
+ writeField(rightCol, "Disk:", formatBytes(float64(res.DiskTotal)))
+ pdf.SetY(pdf.GetY() + 7)
+ }
+ if res.Temperature != nil {
+ writeField(rightCol, "CPU Temp:", fmt.Sprintf("%.0fC", *res.Temperature))
+ pdf.SetY(pdf.GetY() + 7)
+ }
+ if len(res.LoadAverage) >= 3 {
+ writeField(rightCol, "Load:", fmt.Sprintf("%.2f, %.2f, %.2f", res.LoadAverage[0], res.LoadAverage[1], res.LoadAverage[2]))
+ pdf.SetY(pdf.GetY() + 7)
+ }
+
+ rightEndY := pdf.GetY()
+ if leftEndY > rightEndY {
+ pdf.SetY(leftEndY)
+ }
+ pdf.SetY(pdf.GetY() + 3)
+
+ // Full-width fields for long values
+ if res.CPUModel != "" {
+ writeFullWidth("CPU:", res.CPUModel)
+ }
+ if res.KernelVersion != "" {
+ writeFullWidth("Kernel:", res.KernelVersion)
+ }
+ if res.PVEVersion != "" {
+ writeFullWidth("PVE:", res.PVEVersion)
+ }
+ if res.OSName != "" {
+ osStr := res.OSName
+ if res.OSVersion != "" {
+ osStr = fmt.Sprintf("%s %s", res.OSName, res.OSVersion)
+ }
+ writeFullWidth("OS:", osStr)
+ }
+ if len(res.IPAddresses) > 0 {
+ writeFullWidth("IP:", res.IPAddresses[0])
+ }
+
+ // Tags
+ if len(res.Tags) > 0 {
+ pdf.SetY(pdf.GetY() + 3)
+ pdf.SetX(leftCol)
+ pdf.SetFont("Arial", "", 9)
+ pdf.SetTextColor(colorTextMuted[0], colorTextMuted[1], colorTextMuted[2])
+ pdf.CellFormat(labelWidth, 6, "Tags:", "", 0, "L", false, 0, "")
+ pdf.SetFont("Arial", "", 9)
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+ tagStr := ""
+ for i, tag := range res.Tags {
+ if i > 0 {
+ tagStr += ", "
+ }
+ tagStr += tag
+ }
+ pdf.CellFormat(0, 6, tagStr, "", 1, "L", false, 0, "")
+ }
+
+ pdf.Ln(8)
+}
+
+// writeAlertsSection writes the alerts table
+func (g *PDFGenerator) writeAlertsSection(pdf *fpdf.Fpdf, data *ReportData) {
+ if len(data.Alerts) == 0 {
+ return
+ }
+
+ pdf.SetFont("Arial", "B", 12)
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+ pdf.CellFormat(0, 8, "Alerts During Period", "", 1, "L", false, 0, "")
+ pdf.Ln(2)
+
+ // Table header
+ colWidths := []float64{25, 20, 65, 30, 30}
+ headers := []string{"Type", "Level", "Message", "Started", "Resolved"}
+
+ pdf.SetFillColor(colorTableHeader[0], colorTableHeader[1], colorTableHeader[2])
+ pdf.SetTextColor(255, 255, 255)
+ pdf.SetFont("Arial", "B", 8)
+
+ for i, header := range headers {
+ pdf.CellFormat(colWidths[i], 7, header, "1", 0, "C", true, 0, "")
+ }
+ pdf.Ln(-1)
+
+ // Table rows
+ pdf.SetFont("Arial", "", 8)
+ fill := false
+
+ for _, alert := range data.Alerts {
+ if fill {
+ pdf.SetFillColor(colorTableAlt[0], colorTableAlt[1], colorTableAlt[2])
+ } else {
+ pdf.SetFillColor(255, 255, 255)
+ }
+
+ // Type
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+ pdf.CellFormat(colWidths[0], 6, alert.Type, "1", 0, "L", fill, 0, "")
+
+ // Level with color
+ if alert.Level == "critical" {
+ pdf.SetTextColor(colorDanger[0], colorDanger[1], colorDanger[2])
+ } else {
+ pdf.SetTextColor(colorWarning[0], colorWarning[1], colorWarning[2])
+ }
+ pdf.CellFormat(colWidths[1], 6, alert.Level, "1", 0, "C", fill, 0, "")
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+
+ // Message (truncate if too long)
+ msg := alert.Message
+ if len(msg) > 45 {
+ msg = msg[:42] + "..."
+ }
+ pdf.CellFormat(colWidths[2], 6, msg, "1", 0, "L", fill, 0, "")
+
+ // Started
+ pdf.CellFormat(colWidths[3], 6, alert.StartTime.Format("Jan 02 15:04"), "1", 0, "C", fill, 0, "")
+
+ // Resolved
+ if alert.ResolvedTime != nil {
+ pdf.SetTextColor(colorAccent[0], colorAccent[1], colorAccent[2])
+ pdf.CellFormat(colWidths[4], 6, alert.ResolvedTime.Format("Jan 02 15:04"), "1", 0, "C", fill, 0, "")
+ } else {
+ pdf.SetTextColor(colorDanger[0], colorDanger[1], colorDanger[2])
+ pdf.CellFormat(colWidths[4], 6, "Active", "1", 0, "C", fill, 0, "")
+ }
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+
+ pdf.Ln(-1)
+ fill = !fill
+ }
+
+ pdf.Ln(10)
+}
+
+// writeStorageSection writes storage pools table
+func (g *PDFGenerator) writeStorageSection(pdf *fpdf.Fpdf, data *ReportData) {
+ if len(data.Storage) == 0 {
+ return
+ }
+
+ // Check if we need a new page
+ if pdf.GetY() > 200 {
+ pdf.AddPage()
+ g.addPageHeader(pdf, data, "Storage Pools")
+ }
+
+ pdf.SetFont("Arial", "B", 12)
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+ pdf.CellFormat(0, 8, "Storage Pools", "", 1, "L", false, 0, "")
+ pdf.Ln(2)
+
+ // Table header
+ colWidths := []float64{35, 25, 20, 30, 30, 30}
+ headers := []string{"Name", "Type", "Status", "Used", "Total", "Usage"}
+
+ pdf.SetFillColor(colorTableHeader[0], colorTableHeader[1], colorTableHeader[2])
+ pdf.SetTextColor(255, 255, 255)
+ pdf.SetFont("Arial", "B", 8)
+
+ for i, header := range headers {
+ pdf.CellFormat(colWidths[i], 7, header, "1", 0, "C", true, 0, "")
+ }
+ pdf.Ln(-1)
+
+ // Table rows
+ pdf.SetFont("Arial", "", 8)
+ fill := false
+
+ for _, storage := range data.Storage {
+ if fill {
+ pdf.SetFillColor(colorTableAlt[0], colorTableAlt[1], colorTableAlt[2])
+ } else {
+ pdf.SetFillColor(255, 255, 255)
+ }
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+
+ pdf.CellFormat(colWidths[0], 6, storage.Name, "1", 0, "L", fill, 0, "")
+ pdf.CellFormat(colWidths[1], 6, storage.Type, "1", 0, "C", fill, 0, "")
+
+ // Status with color
+ if storage.Status == "active" || storage.Status == "available" {
+ pdf.SetTextColor(colorAccent[0], colorAccent[1], colorAccent[2])
+ } else {
+ pdf.SetTextColor(colorWarning[0], colorWarning[1], colorWarning[2])
+ }
+ pdf.CellFormat(colWidths[2], 6, storage.Status, "1", 0, "C", fill, 0, "")
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+
+ pdf.CellFormat(colWidths[3], 6, formatBytes(float64(storage.Used)), "1", 0, "R", fill, 0, "")
+ pdf.CellFormat(colWidths[4], 6, formatBytes(float64(storage.Total)), "1", 0, "R", fill, 0, "")
+
+ // Usage with color coding
+ usageStr := fmt.Sprintf("%.1f%%", storage.UsagePerc)
+ if storage.UsagePerc >= 90 {
+ pdf.SetTextColor(colorDanger[0], colorDanger[1], colorDanger[2])
+ } else if storage.UsagePerc >= 80 {
+ pdf.SetTextColor(colorWarning[0], colorWarning[1], colorWarning[2])
+ } else {
+ pdf.SetTextColor(colorAccent[0], colorAccent[1], colorAccent[2])
+ }
+ pdf.CellFormat(colWidths[5], 6, usageStr, "1", 0, "C", fill, 0, "")
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+
+ pdf.Ln(-1)
+ fill = !fill
+ }
+
+ pdf.Ln(10)
+}
+
+// writeDisksSection writes physical disks table
+func (g *PDFGenerator) writeDisksSection(pdf *fpdf.Fpdf, data *ReportData) {
+ if len(data.Disks) == 0 {
+ return
+ }
+
+ // Check if we need a new page
+ if pdf.GetY() > 200 {
+ pdf.AddPage()
+ g.addPageHeader(pdf, data, "Physical Disks")
+ }
+
+ pdf.SetFont("Arial", "B", 12)
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+ pdf.CellFormat(0, 8, "Physical Disks", "", 1, "L", false, 0, "")
+ pdf.Ln(2)
+
+ // Table header
+ colWidths := []float64{25, 50, 25, 25, 20, 25}
+ headers := []string{"Device", "Model", "Size", "Health", "Temp", "Wear"}
+
+ pdf.SetFillColor(colorTableHeader[0], colorTableHeader[1], colorTableHeader[2])
+ pdf.SetTextColor(255, 255, 255)
+ pdf.SetFont("Arial", "B", 8)
+
+ for i, header := range headers {
+ pdf.CellFormat(colWidths[i], 7, header, "1", 0, "C", true, 0, "")
+ }
+ pdf.Ln(-1)
+
+ // Table rows
+ pdf.SetFont("Arial", "", 8)
+ fill := false
+
+ for _, disk := range data.Disks {
+ if fill {
+ pdf.SetFillColor(colorTableAlt[0], colorTableAlt[1], colorTableAlt[2])
+ } else {
+ pdf.SetFillColor(255, 255, 255)
+ }
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+
+ pdf.CellFormat(colWidths[0], 6, disk.Device, "1", 0, "L", fill, 0, "")
+
+ // Model (truncate if too long)
+ model := disk.Model
+ if len(model) > 30 {
+ model = model[:27] + "..."
+ }
+ pdf.CellFormat(colWidths[1], 6, model, "1", 0, "L", fill, 0, "")
+
+ pdf.CellFormat(colWidths[2], 6, formatBytes(float64(disk.Size)), "1", 0, "R", fill, 0, "")
+
+ // Health with color
+ if disk.Health == "PASSED" {
+ pdf.SetTextColor(colorAccent[0], colorAccent[1], colorAccent[2])
+ } else if disk.Health == "FAILED" {
+ pdf.SetTextColor(colorDanger[0], colorDanger[1], colorDanger[2])
+ } else {
+ pdf.SetTextColor(colorWarning[0], colorWarning[1], colorWarning[2])
+ }
+ pdf.CellFormat(colWidths[3], 6, disk.Health, "1", 0, "C", fill, 0, "")
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+
+ // Temperature
+ tempStr := "-"
+ if disk.Temperature > 0 {
+ tempStr = fmt.Sprintf("%dC", disk.Temperature)
+ if disk.Temperature >= 60 {
+ pdf.SetTextColor(colorDanger[0], colorDanger[1], colorDanger[2])
+ } else if disk.Temperature >= 50 {
+ pdf.SetTextColor(colorWarning[0], colorWarning[1], colorWarning[2])
+ }
+ }
+ pdf.CellFormat(colWidths[4], 6, tempStr, "1", 0, "C", fill, 0, "")
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+
+ // Wear level
+ wearStr := "-"
+ if disk.WearLevel >= 0 && disk.WearLevel <= 100 {
+ wearStr = fmt.Sprintf("%d%%", disk.WearLevel)
+ if disk.WearLevel >= 80 {
+ pdf.SetTextColor(colorDanger[0], colorDanger[1], colorDanger[2])
+ } else if disk.WearLevel >= 50 {
+ pdf.SetTextColor(colorWarning[0], colorWarning[1], colorWarning[2])
}
}
+ pdf.CellFormat(colWidths[5], 6, wearStr, "1", 0, "C", fill, 0, "")
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+
pdf.Ln(-1)
fill = !fill
}
+
+ pdf.Ln(10)
}
-// writeFooter writes the report footer.
-func (g *PDFGenerator) writeFooter(pdf *fpdf.Fpdf, data *ReportData) {
- pdf.SetY(-20)
- pdf.SetFont("Arial", "I", 8)
- pdf.SetTextColor(128, 128, 128)
- pdf.CellFormat(0, 5, fmt.Sprintf("Generated by Pulse - %s", data.GeneratedAt.Format(time.RFC3339)), "", 0, "C", false, 0, "")
+// writeBackupsSection writes backups table
+func (g *PDFGenerator) writeBackupsSection(pdf *fpdf.Fpdf, data *ReportData) {
+ if len(data.Backups) == 0 {
+ return
+ }
+
+ // Check if we need a new page
+ if pdf.GetY() > 200 {
+ pdf.AddPage()
+ g.addPageHeader(pdf, data, "Backups")
+ }
+
+ pdf.SetFont("Arial", "B", 12)
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+ pdf.CellFormat(0, 8, "Backups", "", 1, "L", false, 0, "")
+ pdf.Ln(2)
+
+ // Table header
+ colWidths := []float64{25, 35, 45, 35, 30}
+ headers := []string{"Type", "Storage", "Date", "Size", "Protected"}
+
+ pdf.SetFillColor(colorTableHeader[0], colorTableHeader[1], colorTableHeader[2])
+ pdf.SetTextColor(255, 255, 255)
+ pdf.SetFont("Arial", "B", 8)
+
+ for i, header := range headers {
+ pdf.CellFormat(colWidths[i], 7, header, "1", 0, "C", true, 0, "")
+ }
+ pdf.Ln(-1)
+
+ // Table rows
+ pdf.SetFont("Arial", "", 8)
+ fill := false
+
+ for _, backup := range data.Backups {
+ if fill {
+ pdf.SetFillColor(colorTableAlt[0], colorTableAlt[1], colorTableAlt[2])
+ } else {
+ pdf.SetFillColor(255, 255, 255)
+ }
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+
+ pdf.CellFormat(colWidths[0], 6, backup.Type, "1", 0, "C", fill, 0, "")
+ pdf.CellFormat(colWidths[1], 6, backup.Storage, "1", 0, "L", fill, 0, "")
+ pdf.CellFormat(colWidths[2], 6, backup.Timestamp.Format("2006-01-02 15:04"), "1", 0, "C", fill, 0, "")
+ pdf.CellFormat(colWidths[3], 6, formatBytes(float64(backup.Size)), "1", 0, "R", fill, 0, "")
+
+ // Protected
+ if backup.Protected {
+ pdf.SetTextColor(colorAccent[0], colorAccent[1], colorAccent[2])
+ pdf.CellFormat(colWidths[4], 6, "Yes", "1", 0, "C", fill, 0, "")
+ } else {
+ pdf.SetTextColor(colorTextMuted[0], colorTextMuted[1], colorTextMuted[2])
+ pdf.CellFormat(colWidths[4], 6, "No", "1", 0, "C", fill, 0, "")
+ }
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+
+ pdf.Ln(-1)
+ fill = !fill
+ }
+
+ pdf.Ln(10)
+}
+
+// formatUptime converts seconds to human-readable uptime
+func formatUptime(seconds int64) string {
+ days := seconds / 86400
+ hours := (seconds % 86400) / 3600
+ mins := (seconds % 3600) / 60
+
+ if days > 0 {
+ return fmt.Sprintf("%dd %dh %dm", days, hours, mins)
+ }
+ if hours > 0 {
+ return fmt.Sprintf("%dh %dm", hours, mins)
+ }
+ return fmt.Sprintf("%dm", mins)
+}
+
+// addPageNumbers adds page numbers to all pages except the first (cover).
+func (g *PDFGenerator) addPageNumbers(pdf *fpdf.Fpdf) {
+ // Disable auto page break while adding footers to prevent creating new pages
+ pdf.SetAutoPageBreak(false, 0)
+
+ totalPages := pdf.PageCount()
+
+ // Iterate through pages 2 to totalPages (skip cover page)
+ for i := 2; i <= totalPages; i++ {
+ pdf.SetPage(i)
+ pageWidth, pageHeight := pdf.GetPageSize()
+
+ pdf.SetY(pageHeight - 15)
+ pdf.SetFont("Arial", "", 8)
+ pdf.SetTextColor(colorTextMuted[0], colorTextMuted[1], colorTextMuted[2])
+
+ pageNum := i - 1
+ totalContent := totalPages - 1
+ pdf.CellFormat(0, 5, fmt.Sprintf("Page %d of %d", pageNum, totalContent), "", 0, "C", false, 0, "")
+
+ // Bottom line
+ pdf.SetDrawColor(colorGridLine[0], colorGridLine[1], colorGridLine[2])
+ pdf.SetLineWidth(0.3)
+ pdf.Line(20, pageHeight-20, pageWidth-20, pageHeight-20)
+ }
+}
+
+// getMetricColor returns a color for a metric type.
+func getMetricColor(metricType string) [3]int {
+ switch metricType {
+ case "cpu":
+ return colorSecondary // Blue
+ case "memory":
+ return [3]int{155, 89, 182} // Purple
+ case "disk", "usage":
+ return colorAccent // Green
+ default:
+ return colorSecondary
+ }
+}
+
+// formatDuration formats a duration in human-readable form.
+func formatDuration(d time.Duration) string {
+ hours := int(d.Hours())
+ if hours >= 24 {
+ days := hours / 24
+ remainingHours := hours % 24
+ dayWord := "days"
+ if days == 1 {
+ dayWord = "day"
+ }
+ if remainingHours > 0 {
+ hourWord := "hours"
+ if remainingHours == 1 {
+ hourWord = "hour"
+ }
+ return fmt.Sprintf("%d %s, %d %s", days, dayWord, remainingHours, hourWord)
+ }
+ return fmt.Sprintf("%d %s", days, dayWord)
+ }
+ if hours > 0 {
+ minutes := int(d.Minutes()) % 60
+ hourWord := "hours"
+ if hours == 1 {
+ hourWord = "hour"
+ }
+ if minutes > 0 {
+ minWord := "minutes"
+ if minutes == 1 {
+ minWord = "minute"
+ }
+ return fmt.Sprintf("%d %s, %d %s", hours, hourWord, minutes, minWord)
+ }
+ return fmt.Sprintf("%d %s", hours, hourWord)
+ }
+ minutes := int(d.Minutes())
+ minWord := "minutes"
+ if minutes == 1 {
+ minWord = "minute"
+ }
+ return fmt.Sprintf("%d %s", minutes, minWord)
}