feat: versão 1.5 - CRM Beta com leads, funis, campanhas e portal do cliente

This commit is contained in:
Erik Silva
2025-12-24 17:36:52 -03:00
parent 99d828869a
commit dfb91c8ba5
98 changed files with 18255 additions and 1465 deletions

View File

@@ -167,3 +167,94 @@ func (h *AuthHandler) ChangePassword(w http.ResponseWriter, r *http.Request) {
"message": "Password changed successfully",
})
}
// UnifiedLogin handles login for all user types (agency, customer, superadmin)
func (h *AuthHandler) UnifiedLogin(w http.ResponseWriter, r *http.Request) {
log.Printf("🔐 UNIFIED LOGIN HANDLER CALLED - Method: %s", r.Method)
if r.Method != http.MethodPost {
log.Printf("❌ Method not allowed: %s", r.Method)
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
bodyBytes, err := io.ReadAll(r.Body)
if err != nil {
log.Printf("❌ Failed to read body: %v", err)
http.Error(w, "Failed to read request body", http.StatusBadRequest)
return
}
defer r.Body.Close()
log.Printf("📥 Raw body: %s", string(bodyBytes))
sanitized := strings.TrimSpace(string(bodyBytes))
var req domain.UnifiedLoginRequest
if err := json.Unmarshal([]byte(sanitized), &req); err != nil {
log.Printf("❌ JSON parse error: %v", err)
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
log.Printf("📧 Unified login attempt for email: %s", req.Email)
response, err := h.authService.UnifiedLogin(req)
if err != nil {
log.Printf("❌ authService.UnifiedLogin error: %v", err)
if err == service.ErrInvalidCredentials || strings.Contains(err.Error(), "não autorizado") {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnauthorized)
json.NewEncoder(w).Encode(map[string]string{
"error": err.Error(),
})
} else {
http.Error(w, "Internal server error", http.StatusInternalServerError)
}
return
}
// VALIDAÇÃO DE SEGURANÇA: Verificar se o tenant corresponde ao subdomain acessado
tenantIDFromContext := ""
if ctxTenantID := r.Context().Value(middleware.TenantIDKey); ctxTenantID != nil {
tenantIDFromContext, _ = ctxTenantID.(string)
}
// Se foi detectado um tenant no contexto E o usuário tem tenant
if tenantIDFromContext != "" && response.TenantID != "" {
if response.TenantID != tenantIDFromContext {
log.Printf("❌ LOGIN BLOCKED: User from tenant %s tried to login in tenant %s subdomain",
response.TenantID, tenantIDFromContext)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusForbidden)
json.NewEncoder(w).Encode(map[string]string{
"error": "Credenciais inválidas para esta agência",
})
return
}
log.Printf("✅ TENANT LOGIN VALIDATION PASSED: %s", response.TenantID)
}
log.Printf("✅ Unified login successful: email=%s, type=%s, role=%s",
response.Email, response.UserType, response.Role)
// Montar resposta compatível com frontend antigo E com novos campos
compatibleResponse := map[string]interface{}{
"token": response.Token,
"user": map[string]interface{}{
"id": response.UserID,
"email": response.Email,
"name": response.Name,
"role": response.Role,
"tenant_id": response.TenantID,
"user_type": response.UserType,
},
// Campos adicionais do sistema unificado
"user_type": response.UserType,
"user_id": response.UserID,
"subdomain": response.Subdomain,
"tenant_id": response.TenantID,
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(compatibleResponse)
}

View File

@@ -0,0 +1,271 @@
package handlers
import (
"aggios-app/backend/internal/api/middleware"
"aggios-app/backend/internal/domain"
"aggios-app/backend/internal/repository"
"aggios-app/backend/internal/service"
"encoding/json"
"log"
"net/http"
"time"
"github.com/google/uuid"
"golang.org/x/crypto/bcrypt"
)
// CollaboratorHandler handles agency collaborator management
type CollaboratorHandler struct {
userRepo *repository.UserRepository
agencyServ *service.AgencyService
}
// NewCollaboratorHandler creates a new collaborator handler
func NewCollaboratorHandler(userRepo *repository.UserRepository, agencyServ *service.AgencyService) *CollaboratorHandler {
return &CollaboratorHandler{
userRepo: userRepo,
agencyServ: agencyServ,
}
}
// AddCollaboratorRequest representa a requisição para adicionar um colaborador
type AddCollaboratorRequest struct {
Email string `json:"email"`
Name string `json:"name"`
}
// CollaboratorResponse representa um colaborador
type CollaboratorResponse struct {
ID string `json:"id"`
Email string `json:"email"`
Name string `json:"name"`
AgencyRole string `json:"agency_role"` // owner ou collaborator
CreatedAt time.Time `json:"created_at"`
CollaboratorCreatedAt *time.Time `json:"collaborator_created_at,omitempty"`
}
// ListCollaborators lista todos os colaboradores da agência (apenas owner pode ver)
func (h *CollaboratorHandler) ListCollaborators(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
ownerID, _ := r.Context().Value(middleware.UserIDKey).(string)
tenantID, _ := r.Context().Value(middleware.TenantIDKey).(string)
agencyRole, _ := r.Context().Value("agency_role").(string)
// Apenas owner pode listar colaboradores
if agencyRole != "owner" {
log.Printf("❌ COLLABORATOR ACCESS BLOCKED: User %s tried to list collaborators", ownerID)
http.Error(w, "Only agency owners can manage collaborators", http.StatusForbidden)
return
}
// Buscar todos os usuários da agência
tenantUUID := parseUUID(tenantID)
if tenantUUID == nil {
http.Error(w, "Invalid tenant ID", http.StatusBadRequest)
return
}
users, err := h.userRepo.ListByTenantID(*tenantUUID)
if err != nil {
log.Printf("Error fetching collaborators: %v", err)
http.Error(w, "Error fetching collaborators", http.StatusInternalServerError)
return
}
// Formatar resposta
collaborators := make([]CollaboratorResponse, 0)
for _, user := range users {
collaborators = append(collaborators, CollaboratorResponse{
ID: user.ID.String(),
Email: user.Email,
Name: user.Name,
AgencyRole: user.AgencyRole,
CreatedAt: user.CreatedAt,
CollaboratorCreatedAt: user.CollaboratorCreatedAt,
})
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"collaborators": collaborators,
})
}
// InviteCollaborator convida um novo colaborador para a agência (apenas owner pode fazer isso)
func (h *CollaboratorHandler) InviteCollaborator(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
ownerID, _ := r.Context().Value(middleware.UserIDKey).(string)
tenantID, _ := r.Context().Value(middleware.TenantIDKey).(string)
agencyRole, _ := r.Context().Value("agency_role").(string)
// Apenas owner pode convidar colaboradores
if agencyRole != "owner" {
log.Printf("❌ COLLABORATOR INVITE BLOCKED: User %s tried to invite collaborator", ownerID)
http.Error(w, "Only agency owners can invite collaborators", http.StatusForbidden)
return
}
var req AddCollaboratorRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
// Validar email
if req.Email == "" {
http.Error(w, "Email is required", http.StatusBadRequest)
return
}
// Validar se email já existe
exists, err := h.userRepo.EmailExists(req.Email)
if err != nil {
log.Printf("Error checking email: %v", err)
http.Error(w, "Error processing request", http.StatusInternalServerError)
return
}
if exists {
http.Error(w, "Email already registered", http.StatusConflict)
return
}
// Gerar senha temporária (8 caracteres aleatórios)
tempPassword := generateTempPassword()
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(tempPassword), bcrypt.DefaultCost)
if err != nil {
log.Printf("Error hashing password: %v", err)
http.Error(w, "Error processing request", http.StatusInternalServerError)
return
}
// Criar novo colaborador
ownerUUID := parseUUID(ownerID)
tenantUUID := parseUUID(tenantID)
now := time.Now()
collaborator := &domain.User{
TenantID: tenantUUID,
Email: req.Email,
Password: string(hashedPassword),
Name: req.Name,
Role: "ADMIN_AGENCIA",
AgencyRole: "collaborator",
CreatedBy: ownerUUID,
CollaboratorCreatedAt: &now,
}
if err := h.userRepo.Create(collaborator); err != nil {
log.Printf("Error creating collaborator: %v", err)
http.Error(w, "Error creating collaborator", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(map[string]interface{}{
"message": "Collaborator invited successfully",
"temporary_password": tempPassword,
"collaborator": CollaboratorResponse{
ID: collaborator.ID.String(),
Email: collaborator.Email,
Name: collaborator.Name,
AgencyRole: collaborator.AgencyRole,
CreatedAt: collaborator.CreatedAt,
CollaboratorCreatedAt: collaborator.CollaboratorCreatedAt,
},
})
}
// RemoveCollaborator remove um colaborador da agência (apenas owner pode fazer isso)
func (h *CollaboratorHandler) RemoveCollaborator(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodDelete {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
ownerID, _ := r.Context().Value(middleware.UserIDKey).(string)
tenantID, _ := r.Context().Value(middleware.TenantIDKey).(string)
agencyRole, _ := r.Context().Value("agency_role").(string)
// Apenas owner pode remover colaboradores
if agencyRole != "owner" {
log.Printf("❌ COLLABORATOR REMOVE BLOCKED: User %s tried to remove collaborator", ownerID)
http.Error(w, "Only agency owners can remove collaborators", http.StatusForbidden)
return
}
collaboratorID := r.URL.Query().Get("id")
if collaboratorID == "" {
http.Error(w, "Collaborator ID is required", http.StatusBadRequest)
return
}
// Converter ID para UUID
collaboratorUUID := parseUUID(collaboratorID)
if collaboratorUUID == nil {
http.Error(w, "Invalid collaborator ID", http.StatusBadRequest)
return
}
// Buscar o colaborador
collaborator, err := h.userRepo.GetByID(*collaboratorUUID)
if err != nil {
http.Error(w, "Collaborator not found", http.StatusNotFound)
return
}
// Verificar se o colaborador pertence à mesma agência
if collaborator.TenantID == nil || collaborator.TenantID.String() != tenantID {
http.Error(w, "Collaborator not found in this agency", http.StatusForbidden)
return
}
// Não permitir remover o owner
if collaborator.AgencyRole == "owner" {
http.Error(w, "Cannot remove the agency owner", http.StatusBadRequest)
return
}
// Remover colaborador
if err := h.userRepo.Delete(*collaboratorUUID); err != nil {
log.Printf("Error removing collaborator: %v", err)
http.Error(w, "Error removing collaborator", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{
"message": "Collaborator removed successfully",
})
}
// generateTempPassword gera uma senha temporária
func generateTempPassword() string {
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*"
return randomString(12, charset)
}
// randomString gera uma string aleatória
func randomString(length int, charset string) string {
b := make([]byte, length)
for i := range b {
b[i] = charset[i%len(charset)]
}
return string(b)
}
// parseUUID converte string para UUID
func parseUUID(s string) *uuid.UUID {
u, err := uuid.Parse(s)
if err != nil {
return nil
}
return &u
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,465 @@
package handlers
import (
"aggios-app/backend/internal/domain"
"aggios-app/backend/internal/repository"
"aggios-app/backend/internal/service"
"aggios-app/backend/internal/config"
"aggios-app/backend/internal/api/middleware"
"context"
"database/sql"
"encoding/json"
"fmt"
"log"
"net/http"
"path/filepath"
"strings"
"time"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
"golang.org/x/crypto/bcrypt"
)
type CustomerPortalHandler struct {
crmRepo *repository.CRMRepository
authService *service.AuthService
cfg *config.Config
minioClient *minio.Client
}
func NewCustomerPortalHandler(crmRepo *repository.CRMRepository, authService *service.AuthService, cfg *config.Config) *CustomerPortalHandler {
// Initialize MinIO client
minioClient, err := minio.New(cfg.Minio.Endpoint, &minio.Options{
Creds: credentials.NewStaticV4(cfg.Minio.RootUser, cfg.Minio.RootPassword, ""),
Secure: cfg.Minio.UseSSL,
})
if err != nil {
log.Printf("❌ Failed to create MinIO client for CustomerPortalHandler: %v", err)
}
return &CustomerPortalHandler{
crmRepo: crmRepo,
authService: authService,
cfg: cfg,
minioClient: minioClient,
}
}
// CustomerLoginRequest representa a requisição de login do cliente
type CustomerLoginRequest struct {
Email string `json:"email"`
Password string `json:"password"`
}
// CustomerLoginResponse representa a resposta de login do cliente
type CustomerLoginResponse struct {
Token string `json:"token"`
Customer *CustomerPortalInfo `json:"customer"`
}
// CustomerPortalInfo representa informações seguras do cliente para o portal
type CustomerPortalInfo struct {
ID string `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
Company string `json:"company"`
HasPortalAccess bool `json:"has_portal_access"`
TenantID string `json:"tenant_id"`
}
// Login autentica um cliente e retorna um token JWT
func (h *CustomerPortalHandler) Login(w http.ResponseWriter, r *http.Request) {
var req CustomerLoginRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{
"error": "Invalid request body",
})
return
}
// Validar entrada
if req.Email == "" || req.Password == "" {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{
"error": "Email e senha são obrigatórios",
})
return
}
// Buscar cliente por email
customer, err := h.crmRepo.GetCustomerByEmail(req.Email)
if err != nil {
if err == sql.ErrNoRows {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnauthorized)
json.NewEncoder(w).Encode(map[string]string{
"error": "Credenciais inválidas",
})
return
}
log.Printf("Error fetching customer: %v", err)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{
"error": "Erro ao processar login",
})
return
}
// Verificar se tem acesso ao portal
if !customer.HasPortalAccess {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusForbidden)
json.NewEncoder(w).Encode(map[string]string{
"error": "Acesso ao portal não autorizado. Entre em contato com o administrador.",
})
return
}
// Verificar senha
if err := bcrypt.CompareHashAndPassword([]byte(customer.PasswordHash), []byte(req.Password)); err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnauthorized)
json.NewEncoder(w).Encode(map[string]string{
"error": "Credenciais inválidas",
})
return
}
// Atualizar último login
if err := h.crmRepo.UpdateCustomerLastLogin(customer.ID); err != nil {
log.Printf("Warning: Failed to update last login for customer %s: %v", customer.ID, err)
}
// Gerar token JWT
token, err := h.authService.GenerateCustomerToken(customer.ID, customer.TenantID, customer.Email)
if err != nil {
log.Printf("Error generating token: %v", err)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{
"error": "Erro ao gerar token de autenticação",
})
return
}
// Resposta de sucesso
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(CustomerLoginResponse{
Token: token,
Customer: &CustomerPortalInfo{
ID: customer.ID,
Name: customer.Name,
Email: customer.Email,
Company: customer.Company,
HasPortalAccess: customer.HasPortalAccess,
TenantID: customer.TenantID,
},
})
}
// GetPortalDashboard retorna dados do dashboard para o cliente autenticado
func (h *CustomerPortalHandler) GetPortalDashboard(w http.ResponseWriter, r *http.Request) {
customerID, _ := r.Context().Value(middleware.CustomerIDKey).(string)
tenantID, _ := r.Context().Value(middleware.TenantIDKey).(string)
// Buscar leads do cliente
leads, err := h.crmRepo.GetLeadsByCustomerID(customerID)
if err != nil {
log.Printf("Error fetching leads: %v", err)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{
"error": "Erro ao buscar leads",
})
return
}
// Buscar informações do cliente
customer, err := h.crmRepo.GetCustomerByID(customerID, tenantID)
if err != nil {
log.Printf("Error fetching customer: %v", err)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{
"error": "Erro ao buscar informações do cliente",
})
return
}
// Calcular estatísticas
rawStats := calculateLeadStats(leads)
stats := map[string]interface{}{
"total_leads": rawStats["total"],
"active_leads": rawStats["novo"].(int) + rawStats["qualificado"].(int) + rawStats["negociacao"].(int),
"converted": rawStats["convertido"],
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"customer": CustomerPortalInfo{
ID: customer.ID,
Name: customer.Name,
Email: customer.Email,
Company: customer.Company,
HasPortalAccess: customer.HasPortalAccess,
TenantID: customer.TenantID,
},
"leads": leads,
"stats": stats,
})
}
// GetPortalLeads retorna apenas os leads do cliente
func (h *CustomerPortalHandler) GetPortalLeads(w http.ResponseWriter, r *http.Request) {
customerID, _ := r.Context().Value(middleware.CustomerIDKey).(string)
leads, err := h.crmRepo.GetLeadsByCustomerID(customerID)
if err != nil {
log.Printf("Error fetching leads: %v", err)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{
"error": "Erro ao buscar leads",
})
return
}
if leads == nil {
leads = []domain.CRMLead{}
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"leads": leads,
})
}
// GetPortalLists retorna as listas que possuem leads do cliente
func (h *CustomerPortalHandler) GetPortalLists(w http.ResponseWriter, r *http.Request) {
customerID, _ := r.Context().Value(middleware.CustomerIDKey).(string)
lists, err := h.crmRepo.GetListsByCustomerID(customerID)
if err != nil {
log.Printf("Error fetching portal lists: %v", err)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{
"error": "Erro ao buscar listas",
})
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"lists": lists,
})
}
// GetPortalProfile retorna o perfil completo do cliente
func (h *CustomerPortalHandler) GetPortalProfile(w http.ResponseWriter, r *http.Request) {
customerID, _ := r.Context().Value(middleware.CustomerIDKey).(string)
tenantID, _ := r.Context().Value(middleware.TenantIDKey).(string)
// Buscar informações do cliente
customer, err := h.crmRepo.GetCustomerByID(customerID, tenantID)
if err != nil {
log.Printf("Error fetching customer: %v", err)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{
"error": "Erro ao buscar perfil",
})
return
}
// Buscar leads para estatísticas
leads, err := h.crmRepo.GetLeadsByCustomerID(customerID)
if err != nil {
log.Printf("Error fetching leads for stats: %v", err)
leads = []domain.CRMLead{}
}
// Calcular estatísticas
stats := calculateLeadStats(leads)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"customer": map[string]interface{}{
"id": customer.ID,
"name": customer.Name,
"email": customer.Email,
"phone": customer.Phone,
"company": customer.Company,
"logo_url": customer.LogoURL,
"portal_last_login": customer.PortalLastLogin,
"created_at": customer.CreatedAt,
"total_leads": len(leads),
"converted_leads": stats["convertido"].(int),
},
})
}
// ChangePasswordRequest representa a requisição de troca de senha
type CustomerChangePasswordRequest struct {
CurrentPassword string `json:"current_password"`
NewPassword string `json:"new_password"`
}
// ChangePassword altera a senha do cliente
func (h *CustomerPortalHandler) ChangePassword(w http.ResponseWriter, r *http.Request) {
customerID, _ := r.Context().Value(middleware.CustomerIDKey).(string)
tenantID, _ := r.Context().Value(middleware.TenantIDKey).(string)
var req CustomerChangePasswordRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{
"error": "Invalid request body",
})
return
}
// Validar entrada
if req.CurrentPassword == "" || req.NewPassword == "" {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{
"error": "Senha atual e nova senha são obrigatórias",
})
return
}
if len(req.NewPassword) < 6 {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{
"error": "A nova senha deve ter no mínimo 6 caracteres",
})
return
}
// Buscar cliente
customer, err := h.crmRepo.GetCustomerByID(customerID, tenantID)
if err != nil {
log.Printf("Error fetching customer: %v", err)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{
"error": "Erro ao processar solicitação",
})
return
}
// Verificar senha atual
if err := bcrypt.CompareHashAndPassword([]byte(customer.PasswordHash), []byte(req.CurrentPassword)); err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnauthorized)
json.NewEncoder(w).Encode(map[string]string{
"error": "Senha atual incorreta",
})
return
}
// Gerar hash da nova senha
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(req.NewPassword), bcrypt.DefaultCost)
if err != nil {
log.Printf("Error hashing password: %v", err)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{
"error": "Erro ao processar nova senha",
})
return
}
// Atualizar senha no banco
if err := h.crmRepo.UpdateCustomerPassword(customerID, string(hashedPassword)); err != nil {
log.Printf("Error updating password: %v", err)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{
"error": "Erro ao atualizar senha",
})
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{
"message": "Senha alterada com sucesso",
})
}
// UploadLogo faz o upload do logo do cliente
func (h *CustomerPortalHandler) UploadLogo(w http.ResponseWriter, r *http.Request) {
customerID, _ := r.Context().Value(middleware.CustomerIDKey).(string)
tenantID, _ := r.Context().Value(middleware.TenantIDKey).(string)
if h.minioClient == nil {
http.Error(w, "Storage service unavailable", http.StatusServiceUnavailable)
return
}
// Parse multipart form (2MB max)
const maxLogoSize = 2 * 1024 * 1024
if err := r.ParseMultipartForm(maxLogoSize); err != nil {
http.Error(w, "File too large", http.StatusBadRequest)
return
}
file, header, err := r.FormFile("logo")
if err != nil {
http.Error(w, "Failed to read file", http.StatusBadRequest)
return
}
defer file.Close()
// Validate file type
contentType := header.Header.Get("Content-Type")
if !strings.HasPrefix(contentType, "image/") {
http.Error(w, "Only images are allowed", http.StatusBadRequest)
return
}
// Generate unique filename
ext := filepath.Ext(header.Filename)
if ext == "" {
ext = ".png" // Default extension
}
filename := fmt.Sprintf("logo-%d%s", time.Now().Unix(), ext)
objectPath := fmt.Sprintf("customers/%s/%s", customerID, filename)
// Upload to MinIO
ctx := context.Background()
bucketName := h.cfg.Minio.BucketName
_, err = h.minioClient.PutObject(ctx, bucketName, objectPath, file, header.Size, minio.PutObjectOptions{
ContentType: contentType,
})
if err != nil {
log.Printf("Error uploading to MinIO: %v", err)
http.Error(w, "Failed to upload file", http.StatusInternalServerError)
return
}
// Generate public URL
logoURL := fmt.Sprintf("%s/api/files/%s/%s", h.cfg.Minio.PublicURL, bucketName, objectPath)
// Update customer in database
err = h.crmRepo.UpdateCustomerLogo(customerID, tenantID, logoURL)
if err != nil {
log.Printf("Error updating customer logo in DB: %v", err)
http.Error(w, "Failed to update profile", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{
"logo_url": logoURL,
})
}

View File

@@ -0,0 +1,210 @@
package handlers
import (
"aggios-app/backend/internal/api/middleware"
"aggios-app/backend/internal/domain"
"encoding/csv"
"encoding/json"
"fmt"
"log"
"net/http"
"strings"
"github.com/xuri/excelize/v2"
)
// ExportLeads handles exporting leads in different formats
func (h *CRMHandler) ExportLeads(w http.ResponseWriter, r *http.Request) {
tenantID, _ := r.Context().Value(middleware.TenantIDKey).(string)
if tenantID == "" {
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{"error": "Missing tenant_id"})
return
}
format := r.URL.Query().Get("format")
if format == "" {
format = "csv"
}
customerID := r.URL.Query().Get("customer_id")
campaignID := r.URL.Query().Get("campaign_id")
var leads []domain.CRMLead
var err error
if campaignID != "" {
leads, err = h.repo.GetLeadsByListID(campaignID)
} else if customerID != "" {
leads, err = h.repo.GetLeadsByTenant(tenantID)
// Filter by customer manually
filtered := []domain.CRMLead{}
for _, lead := range leads {
if lead.CustomerID != nil && *lead.CustomerID == customerID {
filtered = append(filtered, lead)
}
}
leads = filtered
} else {
leads, err = h.repo.GetLeadsByTenant(tenantID)
}
if err != nil {
log.Printf("ExportLeads: Error fetching leads: %v", err)
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{"error": "Failed to fetch leads"})
return
}
switch strings.ToLower(format) {
case "json":
exportJSON(w, leads)
case "xlsx", "excel":
exportXLSX(w, leads)
default:
exportCSV(w, leads)
}
}
func exportJSON(w http.ResponseWriter, leads []domain.CRMLead) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Content-Disposition", "attachment; filename=leads.json")
json.NewEncoder(w).Encode(map[string]interface{}{
"leads": leads,
"count": len(leads),
})
}
func exportCSV(w http.ResponseWriter, leads []domain.CRMLead) {
w.Header().Set("Content-Type", "text/csv")
w.Header().Set("Content-Disposition", "attachment; filename=leads.csv")
writer := csv.NewWriter(w)
defer writer.Flush()
// Header
header := []string{"ID", "Nome", "Email", "Telefone", "Status", "Origem", "Notas", "Tags", "Criado Em"}
writer.Write(header)
// Data
for _, lead := range leads {
tags := ""
if len(lead.Tags) > 0 {
tags = strings.Join(lead.Tags, ", ")
}
phone := ""
if lead.Phone != "" {
phone = lead.Phone
}
notes := ""
if lead.Notes != "" {
notes = lead.Notes
}
row := []string{
lead.ID,
lead.Name,
lead.Email,
phone,
lead.Status,
lead.Source,
notes,
tags,
lead.CreatedAt.Format("02/01/2006 15:04"),
}
writer.Write(row)
}
}
func exportXLSX(w http.ResponseWriter, leads []domain.CRMLead) {
f := excelize.NewFile()
defer f.Close()
sheetName := "Leads"
index, err := f.NewSheet(sheetName)
if err != nil {
log.Printf("Error creating sheet: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
// Set active sheet
f.SetActiveSheet(index)
// Header style
headerStyle, _ := f.NewStyle(&excelize.Style{
Font: &excelize.Font{
Bold: true,
Size: 12,
},
Fill: excelize.Fill{
Type: "pattern",
Color: []string{"#4472C4"},
Pattern: 1,
},
Alignment: &excelize.Alignment{
Horizontal: "center",
Vertical: "center",
},
})
// Headers
headers := []string{"ID", "Nome", "Email", "Telefone", "Status", "Origem", "Notas", "Tags", "Criado Em"}
for i, header := range headers {
cell := fmt.Sprintf("%s1", string(rune('A'+i)))
f.SetCellValue(sheetName, cell, header)
f.SetCellStyle(sheetName, cell, cell, headerStyle)
}
// Data
for i, lead := range leads {
row := i + 2
tags := ""
if len(lead.Tags) > 0 {
tags = strings.Join(lead.Tags, ", ")
}
phone := ""
if lead.Phone != "" {
phone = lead.Phone
}
notes := ""
if lead.Notes != "" {
notes = lead.Notes
}
f.SetCellValue(sheetName, fmt.Sprintf("A%d", row), lead.ID)
f.SetCellValue(sheetName, fmt.Sprintf("B%d", row), lead.Name)
f.SetCellValue(sheetName, fmt.Sprintf("C%d", row), lead.Email)
f.SetCellValue(sheetName, fmt.Sprintf("D%d", row), phone)
f.SetCellValue(sheetName, fmt.Sprintf("E%d", row), lead.Status)
f.SetCellValue(sheetName, fmt.Sprintf("F%d", row), lead.Source)
f.SetCellValue(sheetName, fmt.Sprintf("G%d", row), notes)
f.SetCellValue(sheetName, fmt.Sprintf("H%d", row), tags)
f.SetCellValue(sheetName, fmt.Sprintf("I%d", row), lead.CreatedAt.Format("02/01/2006 15:04"))
}
// Auto-adjust column widths
for i := 0; i < len(headers); i++ {
col := string(rune('A' + i))
f.SetColWidth(sheetName, col, col, 15)
}
f.SetColWidth(sheetName, "B", "B", 25) // Nome
f.SetColWidth(sheetName, "C", "C", 30) // Email
f.SetColWidth(sheetName, "G", "G", 40) // Notas
// Delete default sheet if exists
f.DeleteSheet("Sheet1")
w.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
w.Header().Set("Content-Disposition", "attachment; filename=leads.xlsx")
if err := f.Write(w); err != nil {
log.Printf("Error writing xlsx: %v", err)
}
}

View File

@@ -5,7 +5,10 @@ import (
"log"
"net/http"
"aggios-app/backend/internal/api/middleware"
"aggios-app/backend/internal/service"
"github.com/google/uuid"
)
// TenantHandler handles tenant/agency listing endpoints
@@ -93,7 +96,8 @@ func (h *TenantHandler) GetPublicConfig(w http.ResponseWriter, r *http.Request)
}
// Return only public info
response := map[string]string{
response := map[string]interface{}{
"id": tenant.ID.String(),
"name": tenant.Name,
"primary_color": tenant.PrimaryColor,
"secondary_color": tenant.SecondaryColor,
@@ -106,3 +110,88 @@ func (h *TenantHandler) GetPublicConfig(w http.ResponseWriter, r *http.Request)
w.Header().Set("Content-Type", "application/json; charset=utf-8")
json.NewEncoder(w).Encode(response)
}
// GetBranding returns branding info for the current authenticated tenant
func (h *TenantHandler) GetBranding(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// Get tenant from context (set by auth middleware)
tenantID := r.Context().Value(middleware.TenantIDKey)
if tenantID == nil {
http.Error(w, "Tenant not found in context", http.StatusUnauthorized)
return
}
// Parse tenant ID
tid, err := uuid.Parse(tenantID.(string))
if err != nil {
http.Error(w, "Invalid tenant ID", http.StatusBadRequest)
return
}
// Get tenant from database
tenant, err := h.tenantService.GetByID(tid)
if err != nil {
http.Error(w, "Error fetching branding", http.StatusInternalServerError)
return
}
// Return branding info
response := map[string]interface{}{
"id": tenant.ID.String(),
"name": tenant.Name,
"primary_color": tenant.PrimaryColor,
"secondary_color": tenant.SecondaryColor,
"logo_url": tenant.LogoURL,
"logo_horizontal_url": tenant.LogoHorizontalURL,
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
json.NewEncoder(w).Encode(response)
}
// GetProfile returns public tenant information by tenant ID
func (h *TenantHandler) GetProfile(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// Extract tenant ID from URL path
// URL format: /api/tenants/{id}/profile
tenantIDStr := r.URL.Path[len("/api/tenants/"):]
if idx := len(tenantIDStr) - len("/profile"); idx > 0 {
tenantIDStr = tenantIDStr[:idx]
}
if tenantIDStr == "" {
http.Error(w, "tenant_id is required", http.StatusBadRequest)
return
}
// Para compatibilidade, aceitar tanto UUID quanto ID numérico
// Primeiro tentar como UUID, se falhar buscar tenant diretamente
tenant, err := h.tenantService.GetBySubdomain(tenantIDStr)
if err != nil {
log.Printf("Error getting tenant: %v", err)
http.Error(w, "Tenant not found", http.StatusNotFound)
return
}
// Return public info
response := map[string]interface{}{
"tenant": map[string]string{
"company": tenant.Name,
"primary_color": tenant.PrimaryColor,
"secondary_color": tenant.SecondaryColor,
"logo_url": tenant.LogoURL,
"logo_horizontal_url": tenant.LogoHorizontalURL,
},
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
json.NewEncoder(w).Encode(response)
}