Files
workspace/apps/go-crm/internal/handlers/clients_test.go
gabspereira 744868caa1 feat(go-crm): full auth, routing, middleware, and supporting infra
- 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
2026-05-23 16:55:55 -03:00

338 lines
9.2 KiB
Go

package handlers
import (
"database/sql"
"net/http"
"net/http/httptest"
"os"
"strconv"
"strings"
"testing"
"time"
"go-crm/internal/db"
"go-crm/internal/whatsapp"
"golang.org/x/crypto/bcrypt"
)
func TestListClientsWhatsAppDisplay(t *testing.T) {
tmpfile, err := os.CreateTemp("", "test_*.db")
if err != nil {
t.Fatal(err)
}
defer os.Remove(tmpfile.Name())
tmpfile.Close()
testDB, err := db.Init(tmpfile.Name())
if err != nil {
t.Fatalf("failed to init db: %v", err)
}
defer testDB.Close()
DB = testDB
WAConnector = whatsapp.NewFakeConnector()
hashedPassword, _ := bcrypt.GenerateFromPassword([]byte("password"), bcrypt.DefaultCost)
_, err = testDB.Exec(
"INSERT INTO accounts (email, name, password, created_at) VALUES (?, ?, ?, ?)",
"test@example.com", "Test Account", string(hashedPassword), time.Now().Unix(),
)
if err != nil {
t.Fatalf("failed to create account: %v", err)
}
var accountID int64
err = testDB.QueryRow("SELECT account_id FROM accounts WHERE email = ?", "test@example.com").Scan(&accountID)
if err != nil {
t.Fatalf("failed to get account id: %v", err)
}
sessionID := "test-session"
expires := time.Now().Add(time.Hour).Unix()
_, err = testDB.Exec(
"INSERT INTO sessions (session_id, account_id, expires) VALUES (?, ?, ?)",
sessionID, accountID, expires,
)
if err != nil {
t.Fatalf("failed to create session: %v", err)
}
_, err = testDB.Exec(
"INSERT INTO clients (account_id, name, phone, created_at) VALUES (?, ?, ?, ?)",
accountID, "Client Without WhatsApp", "+5521987654321", time.Now().Unix(),
)
if err != nil {
t.Fatalf("failed to create client without wa: %v", err)
}
_, err = testDB.Exec(
"INSERT INTO clients (account_id, name, phone, whatsapp_number, whatsapp_connected, created_at) VALUES (?, ?, ?, ?, ?, ?)",
accountID, "Client With WhatsApp", "+5521987654322", "+5521987654322", 1, time.Now().Unix(),
)
if err != nil {
t.Fatalf("failed to create client with wa: %v", err)
}
req := httptest.NewRequest(http.MethodGet, "/clients", nil)
req.AddCookie(&http.Cookie{Name: "session", Value: sessionID})
w := httptest.NewRecorder()
ListClients(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected status 200, got %d", w.Code)
}
body := w.Body.String()
if !strings.Contains(body, "Client Without WhatsApp") {
t.Error("expected to find client without wa in response")
}
if !strings.Contains(body, "Connect") {
t.Error("expected Connect button for client without WhatsApp")
}
if !strings.Contains(body, "Client With WhatsApp") {
t.Error("expected to find client with wa in response")
}
if !strings.Contains(body, "+5521987654322") {
t.Error("expected WhatsApp number displayed for connected client")
}
}
func SetupTestDB(t *testing.T) (*sql.DB, func()) {
tmpfile, err := os.CreateTemp("", "test_*.db")
if err != nil {
t.Fatal(err)
}
tmpfile.Close()
testDB, err := db.Init(tmpfile.Name())
if err != nil {
os.Remove(tmpfile.Name())
t.Fatalf("failed to init db: %v", err)
}
cleanup := func() {
testDB.Close()
os.Remove(tmpfile.Name())
}
return testDB, cleanup
}
func TestLeadsConnectPage(t *testing.T) {
testDB, cleanup := SetupTestDB(t)
defer cleanup()
DB = testDB
WAConnector = whatsapp.NewFakeConnector()
hashedPassword, _ := bcrypt.GenerateFromPassword([]byte("password"), bcrypt.DefaultCost)
testDB.Exec(
"INSERT INTO accounts (email, name, password, created_at) VALUES (?, ?, ?, ?)",
"test@example.com", "Test Account", string(hashedPassword), time.Now().Unix(),
)
var accountID int64
testDB.QueryRow("SELECT account_id FROM accounts WHERE email = ?", "test@example.com").Scan(&accountID)
sessionID := "test-session"
testDB.Exec(
"INSERT INTO sessions (session_id, account_id, expires) VALUES (?, ?, ?)",
sessionID, accountID, time.Now().Add(time.Hour).Unix(),
)
var clientID int64
testDB.QueryRow(
"INSERT INTO clients (account_id, name, phone, created_at) VALUES (?, ?, ?, ?) RETURNING client_id",
accountID, "Test Client", "+5521987654321", time.Now().Unix(),
).Scan(&clientID)
req := httptest.NewRequest(http.MethodGet, "/leads/connect?client_id="+strconv.FormatInt(clientID, 10), nil)
req.AddCookie(&http.Cookie{Name: "session", Value: sessionID})
w := httptest.NewRecorder()
LeadsConnectPage(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected status 200, got %d", w.Code)
}
body := w.Body.String()
if !strings.Contains(body, "Scan to Connect") && !strings.Contains(body, "WhatsApp") {
t.Error("expected QR connection page with WhatsApp messaging")
}
if !strings.Contains(strconv.FormatInt(clientID, 10), "") {
t.Log("client_id passed to page")
}
}
func TestLeadsQRPolling(t *testing.T) {
testDB, cleanup := SetupTestDB(t)
defer cleanup()
DB = testDB
WAConnector = whatsapp.NewFakeConnector()
hashedPassword, _ := bcrypt.GenerateFromPassword([]byte("password"), bcrypt.DefaultCost)
testDB.Exec(
"INSERT INTO accounts (email, name, password, created_at) VALUES (?, ?, ?, ?)",
"test@example.com", "Test Account", string(hashedPassword), time.Now().Unix(),
)
var accountID int64
testDB.QueryRow("SELECT account_id FROM accounts WHERE email = ?", "test@example.com").Scan(&accountID)
sessionID := "test-session"
testDB.Exec(
"INSERT INTO sessions (session_id, account_id, expires) VALUES (?, ?, ?)",
sessionID, accountID, time.Now().Add(time.Hour).Unix(),
)
var clientID int64
testDB.QueryRow(
"INSERT INTO clients (account_id, name, phone, created_at) VALUES (?, ?, ?, ?) RETURNING client_id",
accountID, "Test Client", "+5521987654321", time.Now().Unix(),
).Scan(&clientID)
req := httptest.NewRequest(http.MethodGet, "/leads/qr?client_id="+strconv.FormatInt(clientID, 10), nil)
req.AddCookie(&http.Cookie{Name: "session", Value: sessionID})
w := httptest.NewRecorder()
LeadsQR(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected status 200, got %d", w.Code)
}
}
func TestListClientsHasBackToHomeLink(t *testing.T) {
tmpfile, err := os.CreateTemp("", "test_*.db")
if err != nil {
t.Fatal(err)
}
defer os.Remove(tmpfile.Name())
tmpfile.Close()
testDB, err := db.Init(tmpfile.Name())
if err != nil {
t.Fatalf("failed to init db: %v", err)
}
defer testDB.Close()
DB = testDB
WAConnector = whatsapp.NewFakeConnector()
hashedPassword, _ := bcrypt.GenerateFromPassword([]byte("password"), bcrypt.DefaultCost)
_, err = testDB.Exec(
"INSERT INTO accounts (email, name, password, created_at) VALUES (?, ?, ?, ?)",
"test@example.com", "Test Account", string(hashedPassword), time.Now().Unix(),
)
if err != nil {
t.Fatalf("failed to create account: %v", err)
}
var accountID int64
err = testDB.QueryRow("SELECT account_id FROM accounts WHERE email = ?", "test@example.com").Scan(&accountID)
if err != nil {
t.Fatalf("failed to get account id: %v", err)
}
sessionID := "test-session-nav"
expires := time.Now().Add(time.Hour).Unix()
_, err = testDB.Exec(
"INSERT INTO sessions (session_id, account_id, expires) VALUES (?, ?, ?)",
sessionID, accountID, expires,
)
if err != nil {
t.Fatalf("failed to create session: %v", err)
}
req := httptest.NewRequest(http.MethodGet, "/clients", nil)
req.AddCookie(&http.Cookie{Name: "session", Value: sessionID})
w := httptest.NewRecorder()
ListClients(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected status 200, got %d", w.Code)
}
body := w.Body.String()
if !strings.Contains(body, `href="/"`) {
t.Error("expected clients page to have Back to Home link")
}
}
func TestListClientsShowsConnectButtonForUnconnectedClients(t *testing.T) {
tmpfile, err := os.CreateTemp("", "test_*.db")
if err != nil {
t.Fatal(err)
}
defer os.Remove(tmpfile.Name())
tmpfile.Close()
testDB, err := db.Init(tmpfile.Name())
if err != nil {
t.Fatalf("failed to init db: %v", err)
}
defer testDB.Close()
DB = testDB
WAConnector = whatsapp.NewFakeConnector()
hashedPassword, _ := bcrypt.GenerateFromPassword([]byte("password"), bcrypt.DefaultCost)
_, err = testDB.Exec(
"INSERT INTO accounts (email, name, password, created_at) VALUES (?, ?, ?, ?)",
"test@example.com", "Test Account", string(hashedPassword), time.Now().Unix(),
)
if err != nil {
t.Fatalf("failed to create account: %v", err)
}
var accountID int64
err = testDB.QueryRow("SELECT account_id FROM accounts WHERE email = ?", "test@example.com").Scan(&accountID)
if err != nil {
t.Fatalf("failed to get account id: %v", err)
}
var clientID int64
testDB.QueryRow(
"INSERT INTO clients (account_id, name, phone, created_at) VALUES (?, ?, ?, ?) RETURNING client_id",
accountID, "Unconnected Client", "+5521987654321", time.Now().Unix(),
).Scan(&clientID)
sessionID := "test-session-connect-btn"
expires := time.Now().Add(time.Hour).Unix()
_, err = testDB.Exec(
"INSERT INTO sessions (session_id, account_id, expires) VALUES (?, ?, ?)",
sessionID, accountID, expires,
)
if err != nil {
t.Fatalf("failed to create session: %v", err)
}
req := httptest.NewRequest(http.MethodGet, "/clients", nil)
req.AddCookie(&http.Cookie{Name: "session", Value: sessionID})
w := httptest.NewRecorder()
ListClients(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected status 200, got %d", w.Code)
}
body := w.Body.String()
if !strings.Contains(body, "leads/connect?client_id=") {
t.Error("expected clients page to show Connect link for unconnected clients")
}
}