Files
workspace/apps/go-crm/internal/handlers/report.go
gabspereira 9c3bfd131d feat(go-crm): industrial terminal-core UI redesign
Complete visual overhaul of the go-crm web interface:

- New shared layout system (internal/templates/ui.go) with dark zinc
  industrial theme, JetBrains Mono typography, grid/noise textures
- Redesigned all pages: Dashboard, Login/Signup, Clients, Customers,
  Services, Scheduling, Payments, Questions, Answers, Leads,
  Review Queue, Report, Keyword Mapping
- Tailwind CSS via CDN with custom color palette (amber/emerald/rose/sky)
- HTMX-powered interactions with CSS swap animations
- Status pills, KPI cards, data tables, empty states, inline forms
- Mobile-responsive sidebar with collapsible navigation
- All existing tests updated and passing
- Zero new build dependencies — works with existing go run/air workflow
2026-05-23 18:00:32 -03:00

220 lines
7.9 KiB
Go

package handlers
import (
"fmt"
"html/template"
"math"
"net/http"
"time"
"go-crm/internal/templates"
)
type serviceCount struct {
Name string
Count int
}
type reportData struct {
TotalLeads int
ServiceCounts []serviceCount
StatusCounts []serviceCount
TotalScheduled int
ConversionRate float64
TotalRevenue float64
TotalSales int
AverageTicket float64
TopServices []serviceCount
MonthLabel string
}
func (a *App) MonthlyReport(w http.ResponseWriter, r *http.Request) {
accountID, ok := a.requireAuth(w, r)
if !ok {
return
}
clientID := a.clientIDForAccount(accountID)
if clientID == 0 {
http.Error(w, "No client found for account", http.StatusBadRequest)
return
}
now := time.Now()
monthStart := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, now.Location()).Unix()
nextMonth := time.Date(now.Year(), now.Month()+1, 1, 0, 0, 0, 0, now.Location()).Unix()
rd := reportData{MonthLabel: now.Format("January 2006")}
a.DB.QueryRow(
"SELECT COUNT(*) FROM leads WHERE client_id = ? AND created_at >= ? AND created_at < ?",
clientID, monthStart, nextMonth,
).Scan(&rd.TotalLeads)
rows, err := a.DB.Query(
`SELECT service_interest, COUNT(*) as cnt FROM leads
WHERE client_id = ? AND created_at >= ? AND created_at < ?
GROUP BY service_interest ORDER BY cnt DESC`,
clientID, monthStart, nextMonth,
)
if err == nil {
defer rows.Close()
for rows.Next() {
var sc serviceCount
rows.Scan(&sc.Name, &sc.Count)
rd.ServiceCounts = append(rd.ServiceCounts, sc)
}
}
statusRows, err := a.DB.Query(
`SELECT status, COUNT(*) as cnt FROM leads
WHERE client_id = ? AND created_at >= ? AND created_at < ?
GROUP BY status ORDER BY cnt DESC`,
clientID, monthStart, nextMonth,
)
if err == nil {
defer statusRows.Close()
for statusRows.Next() {
var sc serviceCount
statusRows.Scan(&sc.Name, &sc.Count)
rd.StatusCounts = append(rd.StatusCounts, sc)
}
}
a.DB.QueryRow(
"SELECT COUNT(*) FROM leads WHERE client_id = ? AND status = 'Agendou' AND created_at >= ? AND created_at < ?",
clientID, monthStart, nextMonth,
).Scan(&rd.TotalScheduled)
if rd.TotalLeads > 0 {
rd.ConversionRate = math.Round(float64(rd.TotalScheduled)/float64(rd.TotalLeads)*100*10) / 10
}
a.DB.QueryRow(
`SELECT COALESCE(SUM(amount),0), COUNT(*) FROM payments
WHERE client_id = ? AND has_paid = 1 AND created_at >= ? AND created_at < ?`,
clientID, monthStart, nextMonth,
).Scan(&rd.TotalRevenue, &rd.TotalSales)
if rd.TotalSales > 0 {
rd.AverageTicket = math.Round(rd.TotalRevenue/float64(rd.TotalSales)*100) / 100
}
topRows, err := a.DB.Query(
`SELECT s.name, COUNT(*) as cnt
FROM payments p
JOIN scheduling sch ON p.schedule_id = sch.schedule_id
JOIN services s ON sch.service_id = s.service_id
WHERE p.client_id = ? AND p.has_paid = 1 AND p.created_at >= ? AND p.created_at < ?
GROUP BY s.name ORDER BY cnt DESC LIMIT 5`,
clientID, monthStart, nextMonth,
)
if err == nil {
defer topRows.Close()
for topRows.Next() {
var sc serviceCount
topRows.Scan(&sc.Name, &sc.Count)
rd.TopServices = append(rd.TopServices, sc)
}
}
var reviewCount int
a.DB.QueryRow("SELECT COUNT(*) FROM leads WHERE client_id = ? AND needs_review = 1", clientID).Scan(&reviewCount)
buf := templates.BufRender()
fmt.Fprint(buf, templates.PageHeader("Monthly Report", fmt.Sprintf("Performance for %s", rd.MonthLabel)))
// Overview KPIs
fmt.Fprintf(buf, `<div class="grid grid-cols-1 sm:grid-cols-3 gap-4 mb-6">`)
fmt.Fprint(buf, templates.KPICard("Total Leads", fmt.Sprintf("%d", rd.TotalLeads), "", "amber", `<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z"/>`, 1))
fmt.Fprint(buf, templates.KPICard("Scheduled", fmt.Sprintf("%d", rd.TotalScheduled), fmt.Sprintf("%.1f%% conversion", rd.ConversionRate), "emerald", `<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"/>`, 2))
fmt.Fprint(buf, templates.KPICard("Revenue", fmt.Sprintf("R$ %.2f", rd.TotalRevenue), fmt.Sprintf("%d sales", rd.TotalSales), "sky", `<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3-.895 3-2-1.343-2-3-2zm0 0v1m0 0v1m0-1h1m-1 0H9m12 0a2 2 0 012 2v4.5a2.5 2.5 0 01-2.5 2.5h-15a2.5 2.5 0 01-2.5-2.5V10a2 2 0 012-2h15z"/>`, 3))
fmt.Fprintf(buf, `</div>`)
// Revenue details
fmt.Fprintf(buf, `<div class="grid grid-cols-1 sm:grid-cols-3 gap-3 mb-6">`)
miniCards := []struct{ label, value string }{
{"Total Sales", fmt.Sprintf("%d", rd.TotalSales)},
{"Average Ticket", fmt.Sprintf("R$ %.2f", rd.AverageTicket)},
{"Pending Review", fmt.Sprintf("%d", reviewCount)},
}
for _, mc := range miniCards {
fmt.Fprintf(buf, `
<div class="bg-zinc-900 border border-white/[0.06] rounded-lg p-3 animate-slide-up">
<div class="text-[10px] font-mono uppercase tracking-wider text-zinc-500 mb-1">%s</div>
<div class="text-lg font-mono font-semibold text-zinc-200">%s</div>
</div>`, mc.label, mc.value)
}
fmt.Fprintf(buf, `</div>`)
// Tables
fmt.Fprintf(buf, `<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">`)
// Service interest table
serviceTable := renderServiceTable(rd.ServiceCounts, rd.TotalLeads)
fmt.Fprint(buf, templates.SectionCard("Leads by Service Interest", "Distribution of service requests", template.HTML(serviceTable)))
// Status table
statusTable := renderServiceTable(rd.StatusCounts, rd.TotalLeads)
fmt.Fprint(buf, templates.SectionCard("Leads by Status", "Pipeline breakdown", template.HTML(statusTable)))
fmt.Fprintf(buf, `</div>`)
// Top services
if len(rd.TopServices) > 0 {
topTable := renderTopServicesTable(rd.TopServices)
fmt.Fprintf(buf, `<div class="mt-6">%s</div>`, templates.SectionCard("Top 5 Services Sold", "Best performing services this month", template.HTML(topTable)))
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
templates.WritePage(w, buf, "Monthly Report", "report")
}
func renderServiceTable(counts []serviceCount, total int) template.HTML {
if len(counts) == 0 {
return template.HTML(`<p class="text-sm text-zinc-500 py-4">No data for this month.</p>`)
}
out := string(templates.TableStart([]string{"Name", "Quantity", "Percentage"}))
for _, sc := range counts {
pct := 0.0
if total > 0 {
pct = math.Round(float64(sc.Count)/float64(total)*100*10) / 10
}
barWidth := int(pct)
if barWidth > 100 {
barWidth = 100
}
out += fmt.Sprintf(`<tr>
<td class="text-zinc-200">%s</td>
<td class="font-mono text-xs">%d</td>
<td>
<div class="flex items-center gap-2">
<div class="flex-1 h-1.5 bg-zinc-800 rounded-full overflow-hidden max-w-[120px]">
<div class="h-full bg-amber-400 rounded-full" style="width:%d%%"></div>
</div>
<span class="text-xs text-zinc-400 font-mono">%.1f%%</span>
</div>
</td>
</tr>`, htmlEscape(sc.Name), sc.Count, barWidth, pct)
}
out += string(templates.TableEnd())
return template.HTML(out)
}
func renderTopServicesTable(counts []serviceCount) template.HTML {
if len(counts) == 0 {
return template.HTML(`<p class="text-sm text-zinc-500 py-4">No sales data for this month.</p>`)
}
out := string(templates.TableStart([]string{"Service", "Sales"}))
for _, sc := range counts {
out += fmt.Sprintf(`<tr><td class="text-zinc-200">%s</td><td class="font-mono text-xs text-emerald-400">%d</td></tr>`, htmlEscape(sc.Name), sc.Count)
}
out += string(templates.TableEnd())
return template.HTML(out)
}
// MonthlyReport is the package-level shim.
func MonthlyReport(w http.ResponseWriter, r *http.Request) {
(&App{DB: DB, WAConnector: WAConnector}).MonthlyReport(w, r)
}