- Add auth handlers (signup, login, logout, account management) with bcrypt - Add client, customer, service, scheduling, payment, question, answer handlers - Add dashboard, monthly report, and lead pipeline pages - Add UTF-8 middleware to force charset on HTML responses - Add config package with env-based overrides for DB path, secrets, endpoints - Add parser package for WhatsApp message ingestion - Add clean-arch layers: pkg/domain, pkg/repo, pkg/usecase for leads - Add cmd/migrate utility for DB migrations - Add Makefile, README, run-tests.sh, and dev scripts - Update docker-compose.yml with memory limits - Update .air.toml to exclude DB files and stop on errors - Update whatsapp-sync dependencies and add src/index.js entrypoint - Add whatsme standalone WhatsApp reader app (source only) - Untrack .opencode-sandbox/data/go-crm.db from git history - Expand root .gitignore: ngrok, tmp dirs, sandbox DBs, compiled binaries
220 lines
6.8 KiB
Go
220 lines
6.8 KiB
Go
package handlers
|
|
|
|
import (
|
|
"fmt"
|
|
"math"
|
|
"net/http"
|
|
"time"
|
|
)
|
|
|
|
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
|
|
}
|
|
|
|
// MonthlyReport renders the monthly performance report for the current month.
|
|
// GET /report
|
|
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)
|
|
|
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
|
fmt.Fprintf(w, `<!DOCTYPE html>
|
|
<html>
|
|
<head>
|
|
<title>Monthly Report — %s</title>
|
|
<style>
|
|
body { font-family: sans-serif; padding: 1rem; max-width: 900px; margin: 0 auto; }
|
|
h1, h2 { color: #333; }
|
|
.grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem; margin-bottom: 2rem; }
|
|
.card { border: 1px solid #ddd; border-radius: 8px; padding: 1rem; background: #fafafa; }
|
|
.card .value { font-size: 2rem; font-weight: bold; color: #2c7be5; }
|
|
.card .label { color: #666; font-size: 0.9rem; margin-top: 0.25rem; }
|
|
table { border-collapse: collapse; width: 100%%; margin-bottom: 1.5rem; }
|
|
th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
|
|
th { background: #f5f5f5; }
|
|
.badge { background: #dc3545; color: #fff; border-radius: 1rem; padding: 0.2rem 0.6rem; font-size: 0.8rem; }
|
|
nav { margin-bottom: 1rem; }
|
|
</style>
|
|
</head>
|
|
<body>
|
|
<h1>Monthly Report — %s</h1>
|
|
<nav>
|
|
<a href="/">Home</a> |
|
|
<a href="/leads/review">Review Queue <span class="badge">%d</span></a> |
|
|
<a href="/leads/all">All Leads</a> |
|
|
<a href="/leads/keywords">Keyword Mapping</a>
|
|
</nav>
|
|
|
|
<h2>Overview</h2>
|
|
<div class="grid">
|
|
<div class="card"><div class="value">%d</div><div class="label">Total Leads</div></div>
|
|
<div class="card"><div class="value">%d</div><div class="label">Agendamentos</div></div>
|
|
<div class="card"><div class="value">%.1f%%</div><div class="label">Conversion Rate</div></div>
|
|
</div>
|
|
|
|
<h2>Revenue</h2>
|
|
<div class="grid">
|
|
<div class="card"><div class="value">R$ %.2f</div><div class="label">Total Month Revenue</div></div>
|
|
<div class="card"><div class="value">%d</div><div class="label">Total Sales</div></div>
|
|
<div class="card"><div class="value">R$ %.2f</div><div class="label">Average Ticket</div></div>
|
|
</div>
|
|
|
|
<h2>Leads by Service Interest</h2>
|
|
%s
|
|
|
|
<h2>Leads by Status</h2>
|
|
%s
|
|
|
|
<h2>Top 5 Services Sold</h2>
|
|
%s
|
|
|
|
</body></html>`,
|
|
rd.MonthLabel,
|
|
rd.MonthLabel,
|
|
reviewCount,
|
|
rd.TotalLeads, rd.TotalScheduled, rd.ConversionRate,
|
|
rd.TotalRevenue, rd.TotalSales, rd.AverageTicket,
|
|
renderServiceTable(rd.ServiceCounts, rd.TotalLeads),
|
|
renderServiceTable(rd.StatusCounts, rd.TotalLeads),
|
|
renderTopServicesTable(rd.TopServices),
|
|
)
|
|
}
|
|
|
|
func renderServiceTable(counts []serviceCount, total int) string {
|
|
if len(counts) == 0 {
|
|
return `<p style="color:#888">No data for this month.</p>`
|
|
}
|
|
out := `<table><thead><tr><th>Name</th><th>Quantity</th><th>%</th></tr></thead><tbody>`
|
|
for _, sc := range counts {
|
|
pct := 0.0
|
|
if total > 0 {
|
|
pct = math.Round(float64(sc.Count)/float64(total)*100*10) / 10
|
|
}
|
|
out += fmt.Sprintf(`<tr><td>%s</td><td>%d</td><td>%.1f%%</td></tr>`,
|
|
htmlEscape(sc.Name), sc.Count, pct)
|
|
}
|
|
out += `</tbody></table>`
|
|
return out
|
|
}
|
|
|
|
func renderTopServicesTable(counts []serviceCount) string {
|
|
if len(counts) == 0 {
|
|
return `<p style="color:#888">No sales data for this month.</p>`
|
|
}
|
|
out := `<table><thead><tr><th>Service</th><th>Sales</th></tr></thead><tbody>`
|
|
for _, sc := range counts {
|
|
out += fmt.Sprintf(`<tr><td>%s</td><td>%d</td></tr>`, htmlEscape(sc.Name), sc.Count)
|
|
}
|
|
out += `</tbody></table>`
|
|
return out
|
|
}
|
|
|
|
// --- package-level shim kept for existing tests ---
|
|
|
|
func MonthlyReport(w http.ResponseWriter, r *http.Request) {
|
|
(&App{DB: DB, WAConnector: WAConnector}).MonthlyReport(w, r)
|
|
}
|