4 Commits

Author SHA1 Message Date
Erik Silva
99d828869a chore(release): snapshot 1.4.2 2025-12-17 13:36:23 -03:00
Erik Silva
2a112f169d refactor: redesign planos interface with design system patterns
- Create CreatePlanModal component with Headless UI Dialog
- Implement dark mode support throughout plans UI
- Update plans/page.tsx with professional card layout
- Update plans/[id]/page.tsx with consistent styling
- Add proper spacing, typography, and color consistency
- Implement smooth animations and transitions
- Add success/error message feedback
- Improve form UX with better input styling
2025-12-13 19:26:38 -03:00
Erik Silva
2f1cf2bb2a v1.4: Segurança multi-tenant, file serving via API e UX humanizada
-  Validação cross-tenant no login e rotas protegidas
-  File serving via /api/files/{bucket}/{path} (eliminação DNS)
-  Mensagens de erro humanizadas inline (sem pop-ups)
-  Middleware tenant detection via headers customizados
-  Upload de logos retorna URLs via API
-  README atualizado com changelog v1.4 completo
2025-12-13 15:05:51 -03:00
Erik Silva
04c954c3d9 feat: Implementação de submenus laterais (flyout), correções de UI e proteção de rotas (AuthGuard) 2025-12-12 15:24:38 -03:00
146 changed files with 16043 additions and 2202 deletions

View File

@@ -8,7 +8,9 @@
"Bash(docker logs:*)",
"Bash(docker exec:*)",
"Bash(npx tsc:*)",
"Bash(docker-compose restart:*)"
"Bash(docker-compose restart:*)",
"Bash(npm install:*)",
"Bash(docker-compose build:*)"
]
}
}

0
1. docs/planos-aggios.md Normal file
View File

173
1. docs/planos-roadmap.md Normal file
View File

@@ -0,0 +1,173 @@
# Sistema de Planos - Roadmap
## Status: Estrutura Frontend Criada ✅
### O que foi criado no Frontend:
1. **Menu Item** adicionado em `/superadmin/layout.tsx`
- Nova rota: `/superadmin/plans`
2. **Página Principal de Planos** (`/superadmin/plans/page.tsx`)
- Lista todos os planos em grid
- Mostra: nome, descrição, faixa de usuários, preços, features, diferenciais
- Botão "Novo Plano"
- Botões Editar e Deletar
- Status visual (ativo/inativo)
3. **Página de Edição de Plano** (`/superadmin/plans/[id]/page.tsx`)
- Formulário completo para editar:
- Informações básicas (nome, slug, descrição)
- Faixa de usuários (min/max)
- Preços (mensal/anual)
- Armazenamento (GB)
- Status (ativo/inativo)
- TODO: Editor de Features e Diferenciais
---
## Próximos Passos - Backend
### 1. Modelo de Dados (Domain)
```go
// internal/domain/plan.go
type Plan struct {
ID string `json:"id"`
Name string `json:"name"`
Slug string `json:"slug"`
Description string `json:"description"`
MinUsers int `json:"min_users"`
MaxUsers int `json:"max_users"` // -1 = unlimited
MonthlyPrice *decimal.Decimal `json:"monthly_price"`
AnnualPrice *decimal.Decimal `json:"annual_price"`
Features pq.StringArray `json:"features"` // CRM, ERP, etc
Differentiators pq.StringArray `json:"differentiators"`
StorageGB int `json:"storage_gb"`
IsActive bool `json:"is_active"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
type Subscription struct {
ID string `json:"id"`
AgencyID string `json:"agency_id"`
PlanID string `json:"plan_id"`
BillingType string `json:"billing_type"` // monthly/annual
CurrentUsers int `json:"current_users"`
Status string `json:"status"` // active/suspended/cancelled
StartDate time.Time `json:"start_date"`
RenewalDate time.Time `json:"renewal_date"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
```
### 2. Migrations
- `001_create_plans_table.sql`
- `002_create_agency_subscriptions_table.sql`
- `003_add_plan_id_to_agencies.sql`
### 3. Repository
- `PlanRepository` (CRUD)
- `SubscriptionRepository` (CRUD)
### 4. Service
- `PlanService` (validações, lógica)
- `SubscriptionService` (validar limite de usuários, etc)
### 5. Handlers (API)
```
GET /api/admin/plans - Listar planos
POST /api/admin/plans - Criar plano
GET /api/admin/plans/:id - Obter plano
PUT /api/admin/plans/:id - Atualizar plano
DELETE /api/admin/plans/:id - Deletar plano
GET /api/admin/subscriptions - Listar subscrições
```
### 6. Seeds
- Seed dos 4 planos padrão (Ignição, Órbita, Cosmos, Enterprise)
---
## Dados Padrão para Seed
```json
[
{
"name": "Ignição",
"slug": "ignition",
"description": "Ideal para pequenas agências iniciantes",
"min_users": 1,
"max_users": 30,
"monthly_price": 199.99,
"annual_price": 1919.90,
"features": ["CRM", "ERP", "Projetos", "Helpdesk", "Pagamentos", "Contratos", "Documentos"],
"differentiators": [],
"storage_gb": 1,
"is_active": true
},
{
"name": "Órbita",
"slug": "orbit",
"description": "Para agências em crescimento",
"min_users": 31,
"max_users": 100,
"monthly_price": 399.99,
"annual_price": 3839.90,
"features": ["CRM", "ERP", "Projetos", "Helpdesk", "Pagamentos", "Contratos", "Documentos"],
"differentiators": ["Suporte prioritário"],
"storage_gb": 1,
"is_active": true
},
{
"name": "Cosmos",
"slug": "cosmos",
"description": "Para agências consolidadas",
"min_users": 101,
"max_users": 300,
"monthly_price": 799.99,
"annual_price": 7679.90,
"features": ["CRM", "ERP", "Projetos", "Helpdesk", "Pagamentos", "Contratos", "Documentos"],
"differentiators": ["Gerente de conta dedicado", "API integrações"],
"storage_gb": 1,
"is_active": true
},
{
"name": "Enterprise",
"slug": "enterprise",
"description": "Solução customizada para grandes agências",
"min_users": 301,
"max_users": -1,
"monthly_price": null,
"annual_price": null,
"features": ["CRM", "ERP", "Projetos", "Helpdesk", "Pagamentos", "Contratos", "Documentos"],
"differentiators": ["Armazenamento customizado", "Treinamento personalizado"],
"storage_gb": 1,
"is_active": true
}
]
```
---
## Integração com Agências
Quando agência se cadastra:
1. Seleciona um plano
2. Sistema cria `Subscription` com status `active` ou `pending_payment`
3. Agência herda limite de usuários do plano
4. Ao criar usuário: validar se não ultrapassou limite
---
## Features Futuras
- [ ] Editor de Features e Diferenciais (drag-drop no frontend)
- [ ] Planos promocionais (duplicar existente, editar preço)
- [ ] Validações de limite de usuários por plano
- [ ] Dashboard com uso atual vs limite
- [ ] Alertas quando próximo do limite
- [ ] Integração com Stripe/PagSeguro
---
**Pronto para começar?**

103
README.md
View File

@@ -4,27 +4,60 @@ Plataforma composta por serviços de autenticação, painel administrativo (supe
## Visão geral
- **Objetivo**: permitir que superadministradores cadastrem e gerenciem agências (tenants) enquanto o site institucional apresenta informações públicas da empresa.
- **Stack**: Go (backend), Next.js 14 (dashboard e site), PostgreSQL, Traefik, Docker.
- **Status**: fluxo de autenticação e gestão de agências concluído; ambiente dockerizável pronto para uso local.
- **Stack**: Go (backend), Next.js 16 (dashboard e site), PostgreSQL, Traefik, Docker.
- **Status**: Sistema multi-tenant completo com segurança cross-tenant validada, branding dinâmico e file serving via API.
## Componentes principais
- `backend/`: API Go com serviços de autenticação, operadores e CRUD de agências (endpoints `/api/admin/agencies` e `/api/admin/agencies/{id}`).
- `front-end-agency/`: Painel Next.js para agências - branding dinâmico, upload de logos, gestão de perfil e autenticação tenant-aware.
- `front-end-dash.aggios.app/`: painel Next.js login do superadmin, listagem de agências, exibição detalhada e exclusão definitiva.
- `frontend-aggios.app/`: site institucional Next.js com suporte a temas claro/escuro e compartilhamento de tokens de design.
- `backend/internal/data/postgres/`: scripts de inicialização do banco (estrutura base de tenants e usuários).
- `traefik/`: reverse proxy e certificados automatizados.
## Funcionalidades entregues
- **Redesign da Interface (v1.2)**: Adoção de design "Flat" (sem sombras), focado em bordas e limpeza visual em todas as rotas principais (Login, Dashboard, Agências, Cadastro).
- **Gestão Avançada de Agências**:
- Listagem com filtros robustos: Busca textual, Status (Ativo/Inativo) e Filtros de Data (Presets de 7/15/30 dias e intervalo personalizado).
- Detalhamento completo da agência com visualização de logo, cores e dados cadastrais.
- Edição e Exclusão de agências.
- **Login de Superadmin**: Autenticação via JWT com restrição de rotas protegidas.
- **Cadastro de Agências**: Criação de tenant e usuário administrador atrelado.
- **Proxy Interno**: Camada de API no Next.js (`app/api/...`) garantindo chamadas autenticadas e seguras ao backend Go.
- **Site Institucional**: Suporte a dark mode, componentes compartilhados e tokens de design centralizados.
- **Documentação**: Atualizada em `1. docs/` com fluxos, arquiteturas e changelog.
### **v1.4 - Segurança Multi-tenant e File Serving (13/12/2025)**
- **🔒 Segurança Cross-Tenant Crítica**:
- Validação de tenant_id em endpoints de login (bloqueio de cross-tenant authentication)
- Validação de tenant em todas rotas protegidas via middleware
- Mensagens de erro genéricas (sem exposição de arquitetura multi-tenant)
- Logs detalhados de tentativas de acesso cross-tenant bloqueadas
- **📁 File Serving via API**:
- Nova rota `/api/files/{bucket}/{path}` para servir arquivos do MinIO através do backend Go
- Eliminação de dependência de DNS (`files.localhost`) - arquivos servidos via `api.localhost`
- Headers de cache otimizados (Cache-Control: public, max-age=31536000)
- CORS e content-type corretos automaticamente
- **🎨 Melhorias de UX**:
- Mensagens de erro humanizadas no formulário de login (sem pop-ups/toasts)
- Erros inline com ícones e cores apropriadas
- Feedback em tempo real ao digitar (limpeza automática de erros)
- Mensagens específicas para cada tipo de erro (401, 403, 404, 429, 5xx)
- **🔧 Melhorias Técnicas**:
- Next.js middleware injetando headers `X-Tenant-Subdomain` para routing correto
- TenantDetector middleware prioriza headers customizados sobre Host
- Upload de logos retorna URLs via API ao invés de MinIO direto
- Configuração MinIO com variáveis de ambiente `MINIO_SERVER_URL` e `MINIO_BROWSER_REDIRECT_URL`
### **v1.3 - Branding Dinâmico e Favicon (12/12/2025)**
- **Branding Multi-tenant**: Logo, favicon e cores personalizadas por agência
- **Favicon Dinâmico**: Atualização em tempo real via localStorage e SSR metadata
- **Upload de Arquivos**: Sistema de upload para MinIO com bucket público
- **Rate Limiting**: 1000 requisições/minuto por IP
### **v1.2 - Redesign Interface Flat**
- Adoção de design "Flat" (sem sombras), focado em bordas e limpeza visual
- Gestão avançada de agências com filtros robustos
- Detalhamento completo com visualização de branding
### **v1.1 - Fundação Multi-tenant**
- Login de Superadmin com JWT
- Cadastro de Agências
- Proxy Interno Next.js para chamadas autenticadas
- Site Institucional com dark mode
## Executando o projeto
1. **Pré-requisitos**: Docker Desktop e Node.js 20+ (para utilitários opcionais).
@@ -34,15 +67,35 @@ Plataforma composta por serviços de autenticação, painel administrativo (supe
docker-compose up --build
```
4. **Hosts locais**:
- Painel: `https://dash.localhost`
- Site: `https://aggios.app.localhost`
- API: `https://api.localhost`
- Painel SuperAdmin: `http://dash.localhost`
- Painel Agência: `http://{agencia}.localhost` (ex: `http://idealpages.localhost`)
- Site: `http://aggios.app.localhost`
- API: `http://api.localhost`
- Console MinIO: `http://minio.localhost` (admin: minioadmin / M1n10_S3cur3_P@ss_2025!)
5. **Credenciais padrão**: ver `backend/internal/data/postgres/init-db.sql` para usuário superadmin seed.
## Segurança
- ✅ **Cross-Tenant Authentication**: Usuários não podem fazer login em agências que não pertencem
- ✅ **Tenant Isolation**: Todas rotas protegidas validam tenant_id no JWT vs tenant_id do contexto
- ✅ **Erro Handling**: Mensagens genéricas que não expõem arquitetura interna
- ✅ **JWT Validation**: Tokens validados em cada requisição autenticada
- ✅ **Rate Limiting**: 1000 req/min por IP para prevenir brute force
## Estrutura de diretórios (resumo)
```
backend/ API Go (config, domínio, handlers, serviços)
internal/
api/
handlers/
files.go 🆕 Handler para servir arquivos via API
auth.go 🔒 Validação cross-tenant no login
middleware/
auth.go 🔒 Validação tenant em rotas protegidas
tenant.go 🔧 Detecção de tenant via headers
backend/internal/data/postgres/ Scripts SQL de seed
front-end-agency/ 🆕 Dashboard Next.js para Agências
app/login/page.tsx 🎨 Login com mensagens humanizadas
middleware.ts 🔧 Injeção de headers tenant
front-end-dash.aggios.app/ Dashboard Next.js Superadmin
frontend-aggios.app/ Site institucional Next.js
traefik/ Regras de roteamento e TLS
@@ -51,15 +104,21 @@ traefik/ Regras de roteamento e TLS
## Testes e validação
- Consultar `1. docs/TESTING_GUIDE.md` para cenários funcionais.
- Requisições de verificação recomendadas:
- `curl http://api.localhost/api/admin/agencies` (lista) requer token JWT válido.
- `curl http://dash.localhost/api/admin/agencies` (proxy Next) usado pelo painel.
- Fluxo manual via painel `dash.localhost/superadmin`.
- **Testes de Segurança**:
- ✅ Tentativa de login cross-tenant retorna 403
- ✅ JWT de uma agência não funciona em outra agência
- ✅ Logs registram tentativas de acesso cross-tenant
- **Testes de File Serving**:
- ✅ Upload de logo gera URL via API (`http://api.localhost/api/files/...`)
- ✅ Imagens carregam sem problemas de CORS ou DNS
- ✅ Cache headers aplicados corretamente
## Próximos passos sugeridos
- Implementar soft delete e trilhas de auditoria para exclusão de agências.
- Expandir testes automatizados (unitários e e2e) focados no fluxo do dashboard.
- Disponibilizar pipeline CI/CD com validações de lint/build.
- Implementar soft delete e trilhas de auditoria para exclusão de agências
- Adicionar validação de permissões por tenant em rotas de files (se necessário)
- Expandir testes automatizados (unitários e e2e) focados no fluxo do dashboard
- Disponibilizar pipeline CI/CD com validações de lint/build
## Repositório
- Principal: https://git.stackbyte.cloud/erik/aggios.app.git
- Branch: dev-1.4 (Segurança Multi-tenant + File Serving)

View File

@@ -19,7 +19,7 @@ RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o server ./cmd/serv
# Runtime image
FROM alpine:latest
RUN apk --no-cache add ca-certificates tzdata
RUN apk --no-cache add ca-certificates tzdata postgresql-client
WORKDIR /root/

View File

@@ -18,7 +18,7 @@ import (
func initDB(cfg *config.Config) (*sql.DB, error) {
connStr := fmt.Sprintf(
"host=%s port=%s user=%s password=%s dbname=%s sslmode=disable",
"host=%s port=%s user=%s password=%s dbname=%s sslmode=disable client_encoding=UTF8",
cfg.Database.Host,
cfg.Database.Port,
cfg.Database.User,
@@ -56,22 +56,31 @@ func main() {
companyRepo := repository.NewCompanyRepository(db)
signupTemplateRepo := repository.NewSignupTemplateRepository(db)
agencyTemplateRepo := repository.NewAgencyTemplateRepository(db)
planRepo := repository.NewPlanRepository(db)
subscriptionRepo := repository.NewSubscriptionRepository(db)
crmRepo := repository.NewCRMRepository(db)
solutionRepo := repository.NewSolutionRepository(db)
// Initialize services
authService := service.NewAuthService(userRepo, tenantRepo, cfg)
agencyService := service.NewAgencyService(userRepo, tenantRepo, cfg)
tenantService := service.NewTenantService(tenantRepo)
agencyService := service.NewAgencyService(userRepo, tenantRepo, cfg, db)
tenantService := service.NewTenantService(tenantRepo, db)
companyService := service.NewCompanyService(companyRepo)
planService := service.NewPlanService(planRepo, subscriptionRepo)
// Initialize handlers
healthHandler := handlers.NewHealthHandler()
authHandler := handlers.NewAuthHandler(authService)
agencyProfileHandler := handlers.NewAgencyHandler(tenantRepo)
agencyProfileHandler := handlers.NewAgencyHandler(tenantRepo, cfg)
agencyHandler := handlers.NewAgencyRegistrationHandler(agencyService, cfg)
tenantHandler := handlers.NewTenantHandler(tenantService)
companyHandler := handlers.NewCompanyHandler(companyService)
planHandler := handlers.NewPlanHandler(planService)
crmHandler := handlers.NewCRMHandler(crmRepo)
solutionHandler := handlers.NewSolutionHandler(solutionRepo)
signupTemplateHandler := handlers.NewSignupTemplateHandler(signupTemplateRepo, userRepo, tenantRepo, agencyService)
agencyTemplateHandler := handlers.NewAgencyTemplateHandler(agencyTemplateRepo, agencyService, userRepo, tenantRepo)
filesHandler := handlers.NewFilesHandler(cfg)
// Initialize upload handler
uploadHandler, err := handlers.NewUploadHandler(cfg)
@@ -79,6 +88,9 @@ func main() {
log.Fatalf("❌ Erro ao inicializar upload handler: %v", err)
}
// Initialize backup handler
backupHandler := handlers.NewBackupHandler()
// Create middleware chain
tenantDetector := middleware.TenantDetector(tenantRepo)
corsMiddleware := middleware.CORS(cfg)
@@ -111,11 +123,16 @@ func main() {
router.HandleFunc("/api/signup-templates/slug/{slug}", signupTemplateHandler.GetTemplateBySlug).Methods("GET")
router.HandleFunc("/api/signup/register", signupTemplateHandler.PublicRegister).Methods("POST")
// Public plans (for signup flow)
router.HandleFunc("/api/plans", planHandler.ListActivePlans).Methods("GET")
router.HandleFunc("/api/plans/{id}", planHandler.GetActivePlan).Methods("GET")
// File upload (public for signup, will also work with auth)
router.HandleFunc("/api/upload", uploadHandler.Upload).Methods("POST")
// Tenant check (public)
router.HandleFunc("/api/tenant/check", tenantHandler.CheckExists).Methods("GET")
router.HandleFunc("/api/tenant/config", tenantHandler.GetPublicConfig).Methods("GET")
// Hash generator (dev only - remove in production)
router.HandleFunc("/api/hash", handlers.GenerateHash).Methods("POST")
@@ -130,6 +147,12 @@ func main() {
router.HandleFunc("/api/admin/agencies", tenantHandler.ListAll).Methods("GET")
router.HandleFunc("/api/admin/agencies/{id}", agencyHandler.HandleAgency).Methods("GET", "PATCH", "DELETE")
// SUPERADMIN: Backup & Restore
router.Handle("/api/superadmin/backups", authMiddleware(http.HandlerFunc(backupHandler.ListBackups))).Methods("GET")
router.Handle("/api/superadmin/backup/create", authMiddleware(http.HandlerFunc(backupHandler.CreateBackup))).Methods("POST")
router.Handle("/api/superadmin/backup/restore", authMiddleware(http.HandlerFunc(backupHandler.RestoreBackup))).Methods("POST")
router.Handle("/api/superadmin/backup/download/{filename}", authMiddleware(http.HandlerFunc(backupHandler.DownloadBackup))).Methods("GET")
// SUPERADMIN: Agency template management
router.Handle("/api/admin/agency-templates", authMiddleware(http.HandlerFunc(agencyTemplateHandler.ListTemplates))).Methods("GET")
router.Handle("/api/admin/agency-templates", authMiddleware(http.HandlerFunc(agencyTemplateHandler.CreateTemplate))).Methods("POST")
@@ -154,6 +177,40 @@ func main() {
}
}))).Methods("GET", "PUT", "PATCH", "DELETE")
// SUPERADMIN: Plans management
planHandler.RegisterRoutes(router)
// SUPERADMIN: Solutions management
router.Handle("/api/admin/solutions", authMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
solutionHandler.GetAllSolutions(w, r)
case http.MethodPost:
solutionHandler.CreateSolution(w, r)
}
}))).Methods("GET", "POST")
router.Handle("/api/admin/solutions/{id}", authMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
solutionHandler.GetSolution(w, r)
case http.MethodPut, http.MethodPatch:
solutionHandler.UpdateSolution(w, r)
case http.MethodDelete:
solutionHandler.DeleteSolution(w, r)
}
}))).Methods("GET", "PUT", "PATCH", "DELETE")
// SUPERADMIN: Plan <-> Solutions
router.Handle("/api/admin/plans/{plan_id}/solutions", authMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
solutionHandler.GetPlanSolutions(w, r)
case http.MethodPut:
solutionHandler.SetPlanSolutions(w, r)
}
}))).Methods("GET", "PUT")
// ADMIN_AGENCIA: Client registration
router.Handle("/api/agencies/clients/register", authMiddleware(http.HandlerFunc(agencyHandler.RegisterClient))).Methods("POST")
@@ -170,10 +227,70 @@ func main() {
// Agency logo upload (protected)
router.Handle("/api/agency/logo", authMiddleware(http.HandlerFunc(agencyProfileHandler.UploadLogo))).Methods("POST")
// File serving route (public - serves files from MinIO through API)
router.PathPrefix("/api/files/{bucket}/").HandlerFunc(filesHandler.ServeFile).Methods("GET")
// Company routes (protected)
router.Handle("/api/companies", authMiddleware(http.HandlerFunc(companyHandler.List))).Methods("GET")
router.Handle("/api/companies/create", authMiddleware(http.HandlerFunc(companyHandler.Create))).Methods("POST")
// ==================== CRM ROUTES (TENANT) ====================
// Tenant solutions (which solutions the tenant has access to)
router.Handle("/api/tenant/solutions", authMiddleware(http.HandlerFunc(solutionHandler.GetTenantSolutions))).Methods("GET")
// Customers
router.Handle("/api/crm/customers", authMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
crmHandler.GetCustomers(w, r)
case http.MethodPost:
crmHandler.CreateCustomer(w, r)
}
}))).Methods("GET", "POST")
router.Handle("/api/crm/customers/{id}", authMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
crmHandler.GetCustomer(w, r)
case http.MethodPut, http.MethodPatch:
crmHandler.UpdateCustomer(w, r)
case http.MethodDelete:
crmHandler.DeleteCustomer(w, r)
}
}))).Methods("GET", "PUT", "PATCH", "DELETE")
// Lists
router.Handle("/api/crm/lists", authMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
crmHandler.GetLists(w, r)
case http.MethodPost:
crmHandler.CreateList(w, r)
}
}))).Methods("GET", "POST")
router.Handle("/api/crm/lists/{id}", authMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
crmHandler.GetList(w, r)
case http.MethodPut, http.MethodPatch:
crmHandler.UpdateList(w, r)
case http.MethodDelete:
crmHandler.DeleteList(w, r)
}
}))).Methods("GET", "PUT", "PATCH", "DELETE")
// Customer <-> List relationship
router.Handle("/api/crm/customers/{customer_id}/lists/{list_id}", authMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodPost:
crmHandler.AddCustomerToList(w, r)
case http.MethodDelete:
crmHandler.RemoveCustomerFromList(w, r)
}
}))).Methods("POST", "DELETE")
// Apply global middlewares: tenant -> cors -> security -> rateLimit -> router
handler := tenantDetector(corsMiddleware(securityMiddleware(rateLimitMiddleware(router))))

15
backend/generate_hash.go Normal file
View File

@@ -0,0 +1,15 @@
package main
import (
"fmt"
"golang.org/x/crypto/bcrypt"
)
func main() {
password := "Android@2020"
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
panic(err)
}
fmt.Println(string(hash))
}

View File

@@ -9,6 +9,7 @@ import (
"log"
"net/http"
"path/filepath"
"strings"
"time"
"aggios-app/backend/internal/api/middleware"
@@ -172,20 +173,28 @@ func (h *AgencyHandler) UploadLogo(w http.ResponseWriter, r *http.Request) {
return
}
// Generate public URL
logoURL := fmt.Sprintf("http://localhost:9000/%s/%s", bucketName, filename)
// Generate public URL through API (not direct MinIO access)
// This is more secure and doesn't require DNS configuration
logoURL := fmt.Sprintf("http://api.localhost/api/files/%s/%s", bucketName, filename)
log.Printf("Logo uploaded successfully: %s", logoURL)
// Delete old logo file from MinIO if exists
if currentLogoURL != "" && currentLogoURL != "https://via.placeholder.com/150" {
// Extract object key from URL
// Example: http://localhost:9000/aggios-logos/tenants/uuid/logo-123.png -> tenants/uuid/logo-123.png
// Example: http://api.localhost/api/files/aggios-logos/tenants/uuid/logo-123.png -> tenants/uuid/logo-123.png
oldFilename := ""
if len(currentLogoURL) > 0 {
// Split by bucket name
if idx := len("http://localhost:9000/aggios-logos/"); idx < len(currentLogoURL) {
oldFilename = currentLogoURL[idx:]
// Split by /api/files/{bucket}/ to get the file path
apiPrefix := fmt.Sprintf("http://api.localhost/api/files/%s/", bucketName)
if strings.HasPrefix(currentLogoURL, apiPrefix) {
oldFilename = strings.TrimPrefix(currentLogoURL, apiPrefix)
} else {
// Fallback for old MinIO URLs
baseURL := fmt.Sprintf("%s/%s/", h.config.Minio.PublicURL, bucketName)
if len(currentLogoURL) > len(baseURL) {
oldFilename = currentLogoURL[len(baseURL):]
}
}
}
@@ -202,6 +211,8 @@ func (h *AgencyHandler) UploadLogo(w http.ResponseWriter, r *http.Request) {
// Update tenant record in database
var err2 error
log.Printf("Updating database: tenant_id=%s, logo_type=%s, logo_url=%s", tenantID, logoType, logoURL)
if logoType == "horizontal" {
_, err2 = h.tenantRepo.DB().Exec("UPDATE tenants SET logo_horizontal_url = $1, updated_at = NOW() WHERE id = $2", logoURL, tenantID)
} else {
@@ -209,11 +220,13 @@ func (h *AgencyHandler) UploadLogo(w http.ResponseWriter, r *http.Request) {
}
if err2 != nil {
log.Printf("Failed to update logo: %v", err2)
http.Error(w, "Failed to update database", http.StatusInternalServerError)
log.Printf("ERROR: Failed to update logo in database: %v", err2)
http.Error(w, fmt.Sprintf("Failed to update database: %v", err2), http.StatusInternalServerError)
return
}
log.Printf("SUCCESS: Logo saved to database successfully!")
// Return success response
response := map[string]string{
"logo_url": logoURL,

View File

@@ -6,6 +6,7 @@ import (
"net/http"
"aggios-app/backend/internal/api/middleware"
"aggios-app/backend/internal/config"
"aggios-app/backend/internal/repository"
"github.com/google/uuid"
@@ -13,11 +14,13 @@ import (
type AgencyHandler struct {
tenantRepo *repository.TenantRepository
config *config.Config
}
func NewAgencyHandler(tenantRepo *repository.TenantRepository) *AgencyHandler {
func NewAgencyHandler(tenantRepo *repository.TenantRepository, cfg *config.Config) *AgencyHandler {
return &AgencyHandler{
tenantRepo: tenantRepo,
config: cfg,
}
}

View File

@@ -7,6 +7,7 @@ import (
"net/http"
"strings"
"aggios-app/backend/internal/api/middleware"
"aggios-app/backend/internal/domain"
"aggios-app/backend/internal/service"
)
@@ -96,6 +97,23 @@ func (h *AuthHandler) Login(w http.ResponseWriter, r *http.Request) {
return
}
// VALIDAÇÃO DE SEGURANÇA: Verificar se o tenant do usuário corresponde ao subdomain acessado
tenantIDFromContext := ""
if ctxTenantID := r.Context().Value(middleware.TenantIDKey); ctxTenantID != nil {
tenantIDFromContext, _ = ctxTenantID.(string)
}
// Se foi detectado um tenant no contexto (não é superadmin ou site institucional)
if tenantIDFromContext != "" && response.User.TenantID != nil {
userTenantID := response.User.TenantID.String()
if userTenantID != tenantIDFromContext {
log.Printf("❌ LOGIN BLOCKED: User from tenant %s tried to login in tenant %s subdomain", userTenantID, tenantIDFromContext)
http.Error(w, "Forbidden: Invalid credentials for this tenant", http.StatusForbidden)
return
}
log.Printf("✅ TENANT LOGIN VALIDATION PASSED: %s", userTenantID)
}
log.Printf("✅ Login successful for %s, role=%s", response.User.Email, response.User.Role)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)

View File

@@ -0,0 +1,264 @@
package handlers
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"os/exec"
"path/filepath"
"sort"
"strings"
"time"
)
type BackupHandler struct {
backupDir string
}
type BackupInfo struct {
Filename string `json:"filename"`
Size string `json:"size"`
Date string `json:"date"`
Timestamp string `json:"timestamp"`
}
func NewBackupHandler() *BackupHandler {
// Usa o caminho montado no container
backupDir := "/backups"
// Garante que o diretório existe
if _, err := os.Stat(backupDir); os.IsNotExist(err) {
os.MkdirAll(backupDir, 0755)
}
return &BackupHandler{
backupDir: backupDir,
}
}
// ListBackups lista todos os backups disponíveis
func (h *BackupHandler) ListBackups(w http.ResponseWriter, r *http.Request) {
files, err := ioutil.ReadDir(h.backupDir)
if err != nil {
http.Error(w, "Error reading backups directory", http.StatusInternalServerError)
return
}
var backups []BackupInfo
for _, file := range files {
if strings.HasPrefix(file.Name(), "aggios_backup_") && strings.HasSuffix(file.Name(), ".sql") {
// Extrai timestamp do nome do arquivo
timestamp := strings.TrimPrefix(file.Name(), "aggios_backup_")
timestamp = strings.TrimSuffix(timestamp, ".sql")
// Formata a data
t, _ := time.Parse("2006-01-02_15-04-05", timestamp)
dateStr := t.Format("02/01/2006 15:04:05")
// Formata o tamanho
sizeMB := float64(file.Size()) / 1024
sizeStr := fmt.Sprintf("%.2f KB", sizeMB)
backups = append(backups, BackupInfo{
Filename: file.Name(),
Size: sizeStr,
Date: dateStr,
Timestamp: timestamp,
})
}
}
// Ordena por data (mais recente primeiro)
sort.Slice(backups, func(i, j int) bool {
return backups[i].Timestamp > backups[j].Timestamp
})
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"backups": backups,
})
}
// CreateBackup cria um novo backup do banco de dados
func (h *BackupHandler) CreateBackup(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
timestamp := time.Now().Format("2006-01-02_15-04-05")
filename := fmt.Sprintf("aggios_backup_%s.sql", timestamp)
filepath := filepath.Join(h.backupDir, filename)
// Usa pg_dump diretamente (backend e postgres estão na mesma rede docker)
dbPassword := os.Getenv("DB_PASSWORD")
if dbPassword == "" {
dbPassword = "A9g10s_S3cur3_P@ssw0rd_2025!"
}
cmd := exec.Command("pg_dump",
"-h", "postgres",
"-U", "aggios",
"-d", "aggios_db",
"--no-password")
// Define a variável de ambiente para a senha
cmd.Env = append(os.Environ(), fmt.Sprintf("PGPASSWORD=%s", dbPassword))
output, err := cmd.Output()
if err != nil {
http.Error(w, fmt.Sprintf("Error creating backup: %v", err), http.StatusInternalServerError)
return
}
// Salva o backup no arquivo
err = ioutil.WriteFile(filepath, output, 0644)
if err != nil {
http.Error(w, fmt.Sprintf("Error saving backup: %v", err), http.StatusInternalServerError)
return
}
// Limpa backups antigos (mantém apenas os últimos 10)
h.cleanOldBackups()
fileInfo, _ := os.Stat(filepath)
sizeMB := float64(fileInfo.Size()) / 1024
sizeStr := fmt.Sprintf("%.2f KB", sizeMB)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"message": "Backup created successfully",
"filename": filename,
"size": sizeStr,
})
}
// RestoreBackup restaura um backup específico
func (h *BackupHandler) RestoreBackup(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
var req struct {
Filename string `json:"filename"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "Invalid request", http.StatusBadRequest)
return
}
if req.Filename == "" {
http.Error(w, "Filename is required", http.StatusBadRequest)
return
}
// Valida que o arquivo existe e está no diretório correto
backupPath := filepath.Join(h.backupDir, req.Filename)
if !strings.HasPrefix(backupPath, h.backupDir) {
http.Error(w, "Invalid filename", http.StatusBadRequest)
return
}
if _, err := os.Stat(backupPath); os.IsNotExist(err) {
http.Error(w, "Backup file not found", http.StatusNotFound)
return
}
// Lê o conteúdo do backup
backupContent, err := ioutil.ReadFile(backupPath)
if err != nil {
http.Error(w, fmt.Sprintf("Error reading backup: %v", err), http.StatusInternalServerError)
return
}
// Restaura o backup usando psql diretamente
dbPassword := os.Getenv("DB_PASSWORD")
if dbPassword == "" {
dbPassword = "A9g10s_S3cur3_P@ssw0rd_2025!"
}
cmd := exec.Command("psql",
"-h", "postgres",
"-U", "aggios",
"-d", "aggios_db",
"--no-password")
cmd.Stdin = strings.NewReader(string(backupContent))
cmd.Env = append(os.Environ(), fmt.Sprintf("PGPASSWORD=%s", dbPassword))
if err := cmd.Run(); err != nil {
http.Error(w, fmt.Sprintf("Error restoring backup: %v", err), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"message": "Backup restored successfully",
})
}
// DownloadBackup permite fazer download de um backup
func (h *BackupHandler) DownloadBackup(w http.ResponseWriter, r *http.Request) {
// Extrai o filename da URL
parts := strings.Split(r.URL.Path, "/")
filename := parts[len(parts)-1]
if filename == "" {
http.Error(w, "Filename is required", http.StatusBadRequest)
return
}
// Valida que o arquivo existe e está no diretório correto
backupPath := filepath.Join(h.backupDir, filename)
if !strings.HasPrefix(backupPath, h.backupDir) {
http.Error(w, "Invalid filename", http.StatusBadRequest)
return
}
if _, err := os.Stat(backupPath); os.IsNotExist(err) {
http.Error(w, "Backup file not found", http.StatusNotFound)
return
}
// Lê o arquivo
data, err := ioutil.ReadFile(backupPath)
if err != nil {
http.Error(w, "Error reading file", http.StatusInternalServerError)
return
}
// Define headers para download
w.Header().Set("Content-Type", "application/sql")
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", filename))
w.Write(data)
}
// cleanOldBackups mantém apenas os últimos 10 backups
func (h *BackupHandler) cleanOldBackups() {
files, err := ioutil.ReadDir(h.backupDir)
if err != nil {
return
}
var backupFiles []os.FileInfo
for _, file := range files {
if strings.HasPrefix(file.Name(), "aggios_backup_") && strings.HasSuffix(file.Name(), ".sql") {
backupFiles = append(backupFiles, file)
}
}
// Ordena por data de modificação (mais recente primeiro)
sort.Slice(backupFiles, func(i, j int) bool {
return backupFiles[i].ModTime().After(backupFiles[j].ModTime())
})
// Remove backups antigos (mantém os 10 mais recentes)
if len(backupFiles) > 10 {
for _, file := range backupFiles[10:] {
os.Remove(filepath.Join(h.backupDir, file.Name()))
}
}
}

View File

@@ -0,0 +1,470 @@
package handlers
import (
"aggios-app/backend/internal/domain"
"aggios-app/backend/internal/repository"
"aggios-app/backend/internal/api/middleware"
"encoding/json"
"log"
"net/http"
"github.com/google/uuid"
"github.com/gorilla/mux"
)
type CRMHandler struct {
repo *repository.CRMRepository
}
func NewCRMHandler(repo *repository.CRMRepository) *CRMHandler {
return &CRMHandler{repo: repo}
}
// ==================== CUSTOMERS ====================
func (h *CRMHandler) CreateCustomer(w http.ResponseWriter, r *http.Request) {
tenantID, _ := r.Context().Value(middleware.TenantIDKey).(string)
userID, _ := r.Context().Value(middleware.UserIDKey).(string)
if tenantID == "" {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{
"error": "Missing tenant_id",
})
return
}
var customer domain.CRMCustomer
if err := json.NewDecoder(r.Body).Decode(&customer); err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{
"error": "Invalid request body",
"message": err.Error(),
})
return
}
customer.ID = uuid.New().String()
customer.TenantID = tenantID
customer.CreatedBy = userID
customer.IsActive = true
if err := h.repo.CreateCustomer(&customer); err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{
"error": "Failed to create customer",
"message": err.Error(),
})
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(map[string]interface{}{
"customer": customer,
})
}
func (h *CRMHandler) GetCustomers(w http.ResponseWriter, r *http.Request) {
tenantID, _ := r.Context().Value(middleware.TenantIDKey).(string)
if tenantID == "" {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{
"error": "Missing tenant_id",
})
return
}
customers, err := h.repo.GetCustomersByTenant(tenantID)
if err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{
"error": "Failed to fetch customers",
"message": err.Error(),
})
return
}
if customers == nil {
customers = []domain.CRMCustomer{}
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"customers": customers,
})
}
func (h *CRMHandler) GetCustomer(w http.ResponseWriter, r *http.Request) {
tenantID, _ := r.Context().Value(middleware.TenantIDKey).(string)
if tenantID == "" {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{
"error": "Missing tenant_id",
})
return
}
vars := mux.Vars(r)
customerID := vars["id"]
customer, err := h.repo.GetCustomerByID(customerID, tenantID)
if err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusNotFound)
json.NewEncoder(w).Encode(map[string]string{
"error": "Customer not found",
"message": err.Error(),
})
return
}
// Buscar listas do cliente
lists, _ := h.repo.GetCustomerLists(customerID)
if lists == nil {
lists = []domain.CRMList{}
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"customer": customer,
"lists": lists,
})
}
func (h *CRMHandler) UpdateCustomer(w http.ResponseWriter, r *http.Request) {
tenantID, _ := r.Context().Value(middleware.TenantIDKey).(string)
if tenantID == "" {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{
"error": "Missing tenant_id",
})
return
}
vars := mux.Vars(r)
customerID := vars["id"]
var customer domain.CRMCustomer
if err := json.NewDecoder(r.Body).Decode(&customer); err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{
"error": "Invalid request body",
"message": err.Error(),
})
return
}
customer.ID = customerID
customer.TenantID = tenantID
if err := h.repo.UpdateCustomer(&customer); err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{
"error": "Failed to update customer",
"message": err.Error(),
})
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{
"message": "Customer updated successfully",
})
}
func (h *CRMHandler) DeleteCustomer(w http.ResponseWriter, r *http.Request) {
tenantID, _ := r.Context().Value(middleware.TenantIDKey).(string)
if tenantID == "" {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{
"error": "Missing tenant_id",
})
return
}
vars := mux.Vars(r)
customerID := vars["id"]
if err := h.repo.DeleteCustomer(customerID, tenantID); err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{
"error": "Failed to delete customer",
"message": err.Error(),
})
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{
"message": "Customer deleted successfully",
})
}
// ==================== LISTS ====================
func (h *CRMHandler) CreateList(w http.ResponseWriter, r *http.Request) {
tenantIDVal := r.Context().Value(middleware.TenantIDKey)
userIDVal := r.Context().Value(middleware.UserIDKey)
log.Printf("🔍 CreateList DEBUG: tenantID type=%T value=%v | userID type=%T value=%v",
tenantIDVal, tenantIDVal, userIDVal, userIDVal)
tenantID, ok := tenantIDVal.(string)
if !ok || tenantID == "" {
log.Printf("❌ CreateList: Missing or invalid tenant_id")
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{
"error": "Missing tenant_id",
})
return
}
userID, _ := userIDVal.(string)
var list domain.CRMList
if err := json.NewDecoder(r.Body).Decode(&list); err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{
"error": "Invalid request body",
"message": err.Error(),
})
return
}
list.ID = uuid.New().String()
list.TenantID = tenantID
list.CreatedBy = userID
if list.Color == "" {
list.Color = "#3b82f6"
}
if err := h.repo.CreateList(&list); err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{
"error": "Failed to create list",
"message": err.Error(),
})
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(map[string]interface{}{
"list": list,
})
}
func (h *CRMHandler) GetLists(w http.ResponseWriter, r *http.Request) {
tenantID, _ := r.Context().Value(middleware.TenantIDKey).(string)
if tenantID == "" {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{
"error": "Missing tenant_id",
})
return
}
lists, err := h.repo.GetListsByTenant(tenantID)
if err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{
"error": "Failed to fetch lists",
"message": err.Error(),
})
return
}
if lists == nil {
lists = []domain.CRMListWithCustomers{}
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"lists": lists,
})
}
func (h *CRMHandler) GetList(w http.ResponseWriter, r *http.Request) {
tenantID, _ := r.Context().Value(middleware.TenantIDKey).(string)
if tenantID == "" {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{
"error": "Missing tenant_id",
})
return
}
vars := mux.Vars(r)
listID := vars["id"]
list, err := h.repo.GetListByID(listID, tenantID)
if err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusNotFound)
json.NewEncoder(w).Encode(map[string]string{
"error": "List not found",
"message": err.Error(),
})
return
}
// Buscar clientes da lista
customers, _ := h.repo.GetListCustomers(listID, tenantID)
if customers == nil {
customers = []domain.CRMCustomer{}
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"list": list,
"customers": customers,
})
}
func (h *CRMHandler) UpdateList(w http.ResponseWriter, r *http.Request) {
tenantID, _ := r.Context().Value(middleware.TenantIDKey).(string)
if tenantID == "" {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{
"error": "Missing tenant_id",
})
return
}
vars := mux.Vars(r)
listID := vars["id"]
var list domain.CRMList
if err := json.NewDecoder(r.Body).Decode(&list); err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{
"error": "Invalid request body",
"message": err.Error(),
})
return
}
list.ID = listID
list.TenantID = tenantID
if err := h.repo.UpdateList(&list); err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{
"error": "Failed to update list",
"message": err.Error(),
})
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{
"message": "List updated successfully",
})
}
func (h *CRMHandler) DeleteList(w http.ResponseWriter, r *http.Request) {
tenantID, _ := r.Context().Value(middleware.TenantIDKey).(string)
if tenantID == "" {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{
"error": "Missing tenant_id",
})
return
}
vars := mux.Vars(r)
listID := vars["id"]
if err := h.repo.DeleteList(listID, tenantID); err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{
"error": "Failed to delete list",
"message": err.Error(),
})
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{
"message": "List deleted successfully",
})
}
// ==================== CUSTOMER <-> LIST ====================
func (h *CRMHandler) AddCustomerToList(w http.ResponseWriter, r *http.Request) {
userID, _ := r.Context().Value(middleware.UserIDKey).(string)
vars := mux.Vars(r)
customerID := vars["customer_id"]
listID := vars["list_id"]
if err := h.repo.AddCustomerToList(customerID, listID, userID); err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{
"error": "Failed to add customer to list",
"message": err.Error(),
})
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{
"message": "Customer added to list successfully",
})
}
func (h *CRMHandler) RemoveCustomerFromList(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
customerID := vars["customer_id"]
listID := vars["list_id"]
if err := h.repo.RemoveCustomerFromList(customerID, listID); err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{
"error": "Failed to remove customer from list",
"message": err.Error(),
})
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{
"message": "Customer removed from list successfully",
})
}

View File

@@ -0,0 +1,104 @@
package handlers
import (
"context"
"fmt"
"io"
"log"
"net/http"
"strings"
"aggios-app/backend/internal/config"
"github.com/gorilla/mux"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
)
type FilesHandler struct {
config *config.Config
}
func NewFilesHandler(cfg *config.Config) *FilesHandler {
return &FilesHandler{
config: cfg,
}
}
// ServeFile serves files from MinIO through the API
func (h *FilesHandler) ServeFile(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
bucket := vars["bucket"]
// Get the file path (everything after /api/files/{bucket}/)
prefix := fmt.Sprintf("/api/files/%s/", bucket)
filePath := strings.TrimPrefix(r.URL.Path, prefix)
if filePath == "" {
http.Error(w, "File path is required", http.StatusBadRequest)
return
}
// Whitelist de buckets públicos permitidos
allowedBuckets := map[string]bool{
"aggios-logos": true,
}
if !allowedBuckets[bucket] {
log.Printf("🚫 Access denied to bucket: %s", bucket)
http.Error(w, "Access denied", http.StatusForbidden)
return
}
// Proteção contra path traversal
if strings.Contains(filePath, "..") {
log.Printf("🚫 Path traversal attempt detected: %s", filePath)
http.Error(w, "Invalid path", http.StatusBadRequest)
return
}
log.Printf("📁 Serving file: bucket=%s, path=%s", bucket, filePath)
// Initialize MinIO client
minioClient, err := minio.New("aggios-minio:9000", &minio.Options{
Creds: credentials.NewStaticV4("minioadmin", "M1n10_S3cur3_P@ss_2025!", ""),
Secure: false,
})
if err != nil {
log.Printf("Failed to create MinIO client: %v", err)
http.Error(w, "Storage service unavailable", http.StatusInternalServerError)
return
}
// Get object from MinIO
ctx := context.Background()
object, err := minioClient.GetObject(ctx, bucket, filePath, minio.GetObjectOptions{})
if err != nil {
log.Printf("Failed to get object: %v", err)
http.Error(w, "File not found", http.StatusNotFound)
return
}
defer object.Close()
// Get object info for content type and size
objInfo, err := object.Stat()
if err != nil {
log.Printf("Failed to stat object: %v", err)
http.Error(w, "File not found", http.StatusNotFound)
return
}
// Set appropriate headers
w.Header().Set("Content-Type", objInfo.ContentType)
w.Header().Set("Content-Length", fmt.Sprintf("%d", objInfo.Size))
w.Header().Set("Cache-Control", "public, max-age=31536000") // Cache for 1 year
w.Header().Set("Access-Control-Allow-Origin", "*")
// Copy file content to response
_, err = io.Copy(w, object)
if err != nil {
log.Printf("Failed to copy object content: %v", err)
return
}
log.Printf("✅ File served successfully: %s", filePath)
}

View File

@@ -0,0 +1,274 @@
package handlers
import (
"encoding/json"
"log"
"net/http"
"strconv"
"aggios-app/backend/internal/domain"
"aggios-app/backend/internal/service"
"github.com/google/uuid"
"github.com/gorilla/mux"
)
// PlanHandler handles plan-related endpoints
type PlanHandler struct {
planService *service.PlanService
}
// NewPlanHandler creates a new plan handler
func NewPlanHandler(planService *service.PlanService) *PlanHandler {
return &PlanHandler{
planService: planService,
}
}
// RegisterRoutes registers plan routes
func (h *PlanHandler) RegisterRoutes(r *mux.Router) {
// Note: Route protection is done in main.go with authMiddleware wrapper
r.HandleFunc("/api/admin/plans", h.CreatePlan).Methods(http.MethodPost)
r.HandleFunc("/api/admin/plans", h.ListPlans).Methods(http.MethodGet)
r.HandleFunc("/api/admin/plans/{id}", h.GetPlan).Methods(http.MethodGet)
r.HandleFunc("/api/admin/plans/{id}", h.UpdatePlan).Methods(http.MethodPut)
r.HandleFunc("/api/admin/plans/{id}", h.DeletePlan).Methods(http.MethodDelete)
// Public routes (for signup flow)
r.HandleFunc("/api/plans", h.ListActivePlans).Methods(http.MethodGet)
r.HandleFunc("/api/plans/{id}", h.GetActivePlan).Methods(http.MethodGet)
}
// CreatePlan creates a new plan (admin only)
func (h *PlanHandler) CreatePlan(w http.ResponseWriter, r *http.Request) {
log.Printf("📋 CREATE PLAN - Method: %s", r.Method)
var req domain.CreatePlanRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
log.Printf("❌ Invalid request body: %v", err)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{"error": "Invalid request body", "message": err.Error()})
return
}
plan, err := h.planService.CreatePlan(&req)
if err != nil {
log.Printf("❌ Error creating plan: %v", err)
w.Header().Set("Content-Type", "application/json")
switch err {
case service.ErrPlanSlugTaken:
w.WriteHeader(http.StatusConflict)
json.NewEncoder(w).Encode(map[string]string{"error": "Slug already taken", "message": err.Error()})
case service.ErrInvalidUserRange:
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{"error": "Invalid user range", "message": err.Error()})
default:
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{"error": "Internal server error", "message": err.Error()})
}
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(map[string]interface{}{
"message": "Plan created successfully",
"plan": plan,
})
log.Printf("✅ Plan created: %s", plan.ID)
}
// GetPlan retrieves a plan by ID (admin only)
func (h *PlanHandler) GetPlan(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
idStr := vars["id"]
id, err := uuid.Parse(idStr)
if err != nil {
http.Error(w, "Invalid plan ID", http.StatusBadRequest)
return
}
plan, err := h.planService.GetPlan(id)
if err != nil {
if err == service.ErrPlanNotFound {
http.Error(w, "Plan not found", http.StatusNotFound)
} else {
http.Error(w, "Internal server error", http.StatusInternalServerError)
}
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"plan": plan,
})
}
// ListPlans retrieves all plans (admin only)
func (h *PlanHandler) ListPlans(w http.ResponseWriter, r *http.Request) {
plans, err := h.planService.ListPlans()
if err != nil {
log.Printf("❌ Error listing plans: %v", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"plans": plans,
})
log.Printf("✅ Listed %d plans", len(plans))
}
// ListActivePlans retrieves all active plans (public)
func (h *PlanHandler) ListActivePlans(w http.ResponseWriter, r *http.Request) {
plans, err := h.planService.ListActivePlans()
if err != nil {
log.Printf("❌ Error listing active plans: %v", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"plans": plans,
})
}
// GetActivePlan retrieves an active plan by ID (public)
func (h *PlanHandler) GetActivePlan(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
idStr := vars["id"]
id, err := uuid.Parse(idStr)
if err != nil {
http.Error(w, "Invalid plan ID", http.StatusBadRequest)
return
}
plan, err := h.planService.GetPlan(id)
if err != nil {
if err == service.ErrPlanNotFound {
http.Error(w, "Plan not found", http.StatusNotFound)
} else {
http.Error(w, "Internal server error", http.StatusInternalServerError)
}
return
}
// Check if plan is active
if !plan.IsActive {
http.Error(w, "Plan not available", http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"plan": plan,
})
}
// UpdatePlan updates a plan (admin only)
func (h *PlanHandler) UpdatePlan(w http.ResponseWriter, r *http.Request) {
log.Printf("📋 UPDATE PLAN - Method: %s", r.Method)
vars := mux.Vars(r)
idStr := vars["id"]
id, err := uuid.Parse(idStr)
if err != nil {
http.Error(w, "Invalid plan ID", http.StatusBadRequest)
return
}
var req domain.UpdatePlanRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
log.Printf("❌ Invalid request body: %v", err)
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
plan, err := h.planService.UpdatePlan(id, &req)
if err != nil {
log.Printf("❌ Error updating plan: %v", err)
switch err {
case service.ErrPlanNotFound:
http.Error(w, "Plan not found", http.StatusNotFound)
case service.ErrPlanSlugTaken:
http.Error(w, err.Error(), http.StatusConflict)
case service.ErrInvalidUserRange:
http.Error(w, err.Error(), http.StatusBadRequest)
default:
http.Error(w, "Internal server error", http.StatusInternalServerError)
}
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"message": "Plan updated successfully",
"plan": plan,
})
log.Printf("✅ Plan updated: %s", plan.ID)
}
// DeletePlan deletes a plan (admin only)
func (h *PlanHandler) DeletePlan(w http.ResponseWriter, r *http.Request) {
log.Printf("📋 DELETE PLAN - Method: %s", r.Method)
vars := mux.Vars(r)
idStr := vars["id"]
id, err := uuid.Parse(idStr)
if err != nil {
http.Error(w, "Invalid plan ID", http.StatusBadRequest)
return
}
err = h.planService.DeletePlan(id)
if err != nil {
log.Printf("❌ Error deleting plan: %v", err)
switch err {
case service.ErrPlanNotFound:
http.Error(w, "Plan not found", http.StatusNotFound)
default:
http.Error(w, "Internal server error", http.StatusInternalServerError)
}
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(map[string]interface{}{
"message": "Plan deleted successfully",
})
log.Printf("✅ Plan deleted: %s", idStr)
}
// GetPlanByUserCount returns a plan for a given user count
func (h *PlanHandler) GetPlanByUserCount(w http.ResponseWriter, r *http.Request) {
userCountStr := r.URL.Query().Get("user_count")
if userCountStr == "" {
http.Error(w, "user_count parameter required", http.StatusBadRequest)
return
}
userCount, err := strconv.Atoi(userCountStr)
if err != nil {
http.Error(w, "Invalid user_count", http.StatusBadRequest)
return
}
plan, err := h.planService.GetPlanByUserCount(userCount)
if err != nil {
http.Error(w, "No plan available for this user count", http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"plan": plan,
})
}

View File

@@ -0,0 +1,252 @@
package handlers
import (
"aggios-app/backend/internal/domain"
"aggios-app/backend/internal/repository"
"aggios-app/backend/internal/api/middleware"
"encoding/json"
"log"
"net/http"
"github.com/google/uuid"
"github.com/gorilla/mux"
)
type SolutionHandler struct {
repo *repository.SolutionRepository
}
func NewSolutionHandler(repo *repository.SolutionRepository) *SolutionHandler {
return &SolutionHandler{repo: repo}
}
// ==================== CRUD SOLUTIONS (SUPERADMIN) ====================
func (h *SolutionHandler) CreateSolution(w http.ResponseWriter, r *http.Request) {
var solution domain.Solution
if err := json.NewDecoder(r.Body).Decode(&solution); err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{
"error": "Invalid request body",
"message": err.Error(),
})
return
}
solution.ID = uuid.New().String()
if err := h.repo.CreateSolution(&solution); err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{
"error": "Failed to create solution",
"message": err.Error(),
})
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(map[string]interface{}{
"solution": solution,
})
}
func (h *SolutionHandler) GetAllSolutions(w http.ResponseWriter, r *http.Request) {
solutions, err := h.repo.GetAllSolutions()
if err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{
"error": "Failed to fetch solutions",
"message": err.Error(),
})
return
}
if solutions == nil {
solutions = []domain.Solution{}
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"solutions": solutions,
})
}
func (h *SolutionHandler) GetSolution(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
solutionID := vars["id"]
solution, err := h.repo.GetSolutionByID(solutionID)
if err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusNotFound)
json.NewEncoder(w).Encode(map[string]string{
"error": "Solution not found",
"message": err.Error(),
})
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"solution": solution,
})
}
func (h *SolutionHandler) UpdateSolution(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
solutionID := vars["id"]
var solution domain.Solution
if err := json.NewDecoder(r.Body).Decode(&solution); err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{
"error": "Invalid request body",
"message": err.Error(),
})
return
}
solution.ID = solutionID
if err := h.repo.UpdateSolution(&solution); err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{
"error": "Failed to update solution",
"message": err.Error(),
})
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{
"message": "Solution updated successfully",
})
}
func (h *SolutionHandler) DeleteSolution(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
solutionID := vars["id"]
if err := h.repo.DeleteSolution(solutionID); err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{
"error": "Failed to delete solution",
"message": err.Error(),
})
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{
"message": "Solution deleted successfully",
})
}
// ==================== TENANT SOLUTIONS (AGENCY) ====================
func (h *SolutionHandler) GetTenantSolutions(w http.ResponseWriter, r *http.Request) {
tenantID, _ := r.Context().Value(middleware.TenantIDKey).(string)
log.Printf("🔍 GetTenantSolutions: tenantID=%s", tenantID)
if tenantID == "" {
log.Printf("❌ GetTenantSolutions: Missing tenant_id")
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{
"error": "Missing tenant_id",
})
return
}
solutions, err := h.repo.GetTenantSolutions(tenantID)
if err != nil {
log.Printf("❌ GetTenantSolutions: Error fetching solutions: %v", err)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{
"error": "Failed to fetch solutions",
"message": err.Error(),
})
return
}
log.Printf("✅ GetTenantSolutions: Found %d solutions for tenant %s", len(solutions), tenantID)
if solutions == nil {
solutions = []domain.Solution{}
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"solutions": solutions,
})
}
// ==================== PLAN SOLUTIONS ====================
func (h *SolutionHandler) GetPlanSolutions(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
planID := vars["plan_id"]
solutions, err := h.repo.GetPlanSolutions(planID)
if err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{
"error": "Failed to fetch plan solutions",
"message": err.Error(),
})
return
}
if solutions == nil {
solutions = []domain.Solution{}
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"solutions": solutions,
})
}
func (h *SolutionHandler) SetPlanSolutions(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
planID := vars["plan_id"]
var req struct {
SolutionIDs []string `json:"solution_ids"`
}
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",
"message": err.Error(),
})
return
}
if err := h.repo.SetPlanSolutions(planID, req.SolutionIDs); err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{
"error": "Failed to update plan solutions",
"message": err.Error(),
})
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{
"message": "Plan solutions updated successfully",
})
}

View File

@@ -2,9 +2,9 @@ package handlers
import (
"encoding/json"
"log"
"net/http"
"aggios-app/backend/internal/domain"
"aggios-app/backend/internal/service"
)
@@ -27,14 +27,15 @@ func (h *TenantHandler) ListAll(w http.ResponseWriter, r *http.Request) {
return
}
tenants, err := h.tenantService.ListAll()
tenants, err := h.tenantService.ListAllWithDetails()
if err != nil {
log.Printf("Error listing tenants with details: %v", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
if tenants == nil {
tenants = []*domain.Tenant{}
tenants = []map[string]interface{}{}
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
@@ -67,3 +68,41 @@ func (h *TenantHandler) CheckExists(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
}
// GetPublicConfig returns public branding info for a tenant by subdomain
func (h *TenantHandler) GetPublicConfig(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
subdomain := r.URL.Query().Get("subdomain")
if subdomain == "" {
http.Error(w, "subdomain is required", http.StatusBadRequest)
return
}
tenant, err := h.tenantService.GetBySubdomain(subdomain)
if err != nil {
if err == service.ErrTenantNotFound {
http.NotFound(w, r)
return
}
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
// Return only public info
response := map[string]string{
"name": tenant.Name,
"primary_color": tenant.PrimaryColor,
"secondary_color": tenant.SecondaryColor,
"logo_url": tenant.LogoURL,
"logo_horizontal_url": tenant.LogoHorizontalURL,
}
log.Printf("📤 Returning tenant config for %s: logo_url=%s", subdomain, tenant.LogoURL)
w.Header().Set("Content-Type", "application/json; charset=utf-8")
json.NewEncoder(w).Encode(response)
}

View File

@@ -2,6 +2,7 @@ package middleware
import (
"context"
"log"
"net/http"
"strings"
@@ -59,13 +60,40 @@ func Auth(cfg *config.Config) func(http.Handler) http.Handler {
}
// tenant_id pode ser nil para SuperAdmin
var tenantID string
var tenantIDFromJWT string
if tenantIDClaim, ok := claims["tenant_id"]; ok && tenantIDClaim != nil {
tenantID, _ = tenantIDClaim.(string)
tenantIDFromJWT, _ = tenantIDClaim.(string)
}
ctx := context.WithValue(r.Context(), UserIDKey, userID)
ctx = context.WithValue(ctx, TenantIDKey, tenantID)
// VALIDAÇÃO DE SEGURANÇA: Verificar se o tenant_id do JWT corresponde ao subdomínio acessado
// Pegar o tenant_id do contexto (detectado pelo TenantDetector middleware ANTES deste)
tenantIDFromContext := ""
if ctxTenantID := r.Context().Value(TenantIDKey); ctxTenantID != nil {
tenantIDFromContext, _ = ctxTenantID.(string)
}
log.Printf("🔐 AUTH VALIDATION: JWT tenant=%s | Context tenant=%s | Path=%s",
tenantIDFromJWT, tenantIDFromContext, r.RequestURI)
// Se o usuário não é SuperAdmin (tem tenant_id) e está acessando uma agência (subdomain detectado)
if tenantIDFromJWT != "" && tenantIDFromContext != "" {
// Validar se o tenant_id do JWT corresponde ao tenant detectado
if tenantIDFromJWT != tenantIDFromContext {
log.Printf("❌ CROSS-TENANT ACCESS BLOCKED: User from tenant %s tried to access tenant %s",
tenantIDFromJWT, tenantIDFromContext)
http.Error(w, "Forbidden: You don't have access to this tenant", http.StatusForbidden)
return
}
log.Printf("✅ TENANT VALIDATION PASSED: %s", tenantIDFromJWT)
}
// Preservar TODOS os valores do contexto anterior (incluindo o tenantID do TenantDetector)
ctx := r.Context()
ctx = context.WithValue(ctx, UserIDKey, userID)
// Só sobrescrever o TenantIDKey se vier do JWT (para não perder o do TenantDetector)
if tenantIDFromJWT != "" {
ctx = context.WithValue(ctx, TenantIDKey, tenantIDFromJWT)
}
next.ServeHTTP(w, r.WithContext(ctx))
})
}

View File

@@ -16,15 +16,25 @@ func TenantDetector(tenantRepo *repository.TenantRepository) func(http.Handler)
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Get host from X-Forwarded-Host header (set by Next.js proxy) or Host header
host := r.Header.Get("X-Forwarded-Host")
if host == "" {
host = r.Header.Get("X-Original-Host")
}
if host == "" {
host = r.Host
}
// Priority order: X-Tenant-Subdomain (set by Next.js middleware) > X-Forwarded-Host > X-Original-Host > Host
tenantSubdomain := r.Header.Get("X-Tenant-Subdomain")
log.Printf("TenantDetector: host = %s (from headers), path = %s", host, r.RequestURI)
var host string
if tenantSubdomain != "" {
// Use direct subdomain from Next.js middleware
host = tenantSubdomain
log.Printf("TenantDetector: using X-Tenant-Subdomain = %s", tenantSubdomain)
} else {
// Fallback to extracting from host headers
host = r.Header.Get("X-Forwarded-Host")
if host == "" {
host = r.Header.Get("X-Original-Host")
}
if host == "" {
host = r.Host
}
log.Printf("TenantDetector: host = %s (from headers), path = %s", host, r.RequestURI)
}
// Extract subdomain
// Examples:
@@ -33,17 +43,28 @@ func TenantDetector(tenantRepo *repository.TenantRepository) func(http.Handler)
// - dash.localhost -> dash (master admin)
// - localhost -> (institutional site)
parts := strings.Split(host, ".")
var subdomain string
if len(parts) >= 2 {
// Has subdomain
subdomain = parts[0]
// If we got the subdomain directly from X-Tenant-Subdomain, use it
if tenantSubdomain != "" {
subdomain = tenantSubdomain
// Remove port if present
if strings.Contains(subdomain, ":") {
subdomain = strings.Split(subdomain, ":")[0]
}
} else {
// Extract from host
parts := strings.Split(host, ".")
if len(parts) >= 2 {
// Has subdomain
subdomain = parts[0]
// Remove port if present
if strings.Contains(subdomain, ":") {
subdomain = strings.Split(subdomain, ":")[0]
}
}
}
log.Printf("TenantDetector: extracted subdomain = %s", subdomain)

View File

@@ -49,6 +49,7 @@ type SecurityConfig struct {
// MinioConfig holds MinIO configuration
type MinioConfig struct {
Endpoint string
PublicURL string // URL pública para acesso ao MinIO (para gerar links)
RootUser string
RootPassword string
UseSSL bool
@@ -64,9 +65,9 @@ func Load() *Config {
}
// Rate limit: more lenient in dev, strict in prod
maxAttempts := 30
maxAttempts := 1000 // Aumentado drasticamente para evitar 429 durante debug
if env == "production" {
maxAttempts = 5
maxAttempts = 100 // Mais restritivo em produção
}
return &Config{
@@ -102,6 +103,7 @@ func Load() *Config {
},
Minio: MinioConfig{
Endpoint: getEnvOrDefault("MINIO_ENDPOINT", "minio:9000"),
PublicURL: getEnvOrDefault("MINIO_PUBLIC_URL", "http://localhost:9000"),
RootUser: getEnvOrDefault("MINIO_ROOT_USER", "minioadmin"),
RootPassword: getEnvOrDefault("MINIO_ROOT_PASSWORD", "changeme"),
UseSSL: getEnvOrDefault("MINIO_USE_SSL", "false") == "true",

View File

@@ -0,0 +1,53 @@
package domain
import "time"
type CRMCustomer struct {
ID string `json:"id" db:"id"`
TenantID string `json:"tenant_id" db:"tenant_id"`
Name string `json:"name" db:"name"`
Email string `json:"email" db:"email"`
Phone string `json:"phone" db:"phone"`
Company string `json:"company" db:"company"`
Position string `json:"position" db:"position"`
Address string `json:"address" db:"address"`
City string `json:"city" db:"city"`
State string `json:"state" db:"state"`
ZipCode string `json:"zip_code" db:"zip_code"`
Country string `json:"country" db:"country"`
Notes string `json:"notes" db:"notes"`
Tags []string `json:"tags" db:"tags"`
IsActive bool `json:"is_active" db:"is_active"`
CreatedBy string `json:"created_by" db:"created_by"`
CreatedAt time.Time `json:"created_at" db:"created_at"`
UpdatedAt time.Time `json:"updated_at" db:"updated_at"`
}
type CRMList struct {
ID string `json:"id" db:"id"`
TenantID string `json:"tenant_id" db:"tenant_id"`
Name string `json:"name" db:"name"`
Description string `json:"description" db:"description"`
Color string `json:"color" db:"color"`
CreatedBy string `json:"created_by" db:"created_by"`
CreatedAt time.Time `json:"created_at" db:"created_at"`
UpdatedAt time.Time `json:"updated_at" db:"updated_at"`
}
type CRMCustomerList struct {
CustomerID string `json:"customer_id" db:"customer_id"`
ListID string `json:"list_id" db:"list_id"`
AddedAt time.Time `json:"added_at" db:"added_at"`
AddedBy string `json:"added_by" db:"added_by"`
}
// DTO com informações extras
type CRMCustomerWithLists struct {
CRMCustomer
Lists []CRMList `json:"lists"`
}
type CRMListWithCustomers struct {
CRMList
CustomerCount int `json:"customer_count"`
}

View File

@@ -0,0 +1,78 @@
package domain
import (
"time"
"github.com/google/uuid"
"github.com/lib/pq"
"github.com/shopspring/decimal"
)
// Plan represents a subscription plan in the system
type Plan struct {
ID uuid.UUID `json:"id" db:"id"`
Name string `json:"name" db:"name"`
Slug string `json:"slug" db:"slug"`
Description string `json:"description" db:"description"`
MinUsers int `json:"min_users" db:"min_users"`
MaxUsers int `json:"max_users" db:"max_users"` // -1 means unlimited
MonthlyPrice *decimal.Decimal `json:"monthly_price" db:"monthly_price"`
AnnualPrice *decimal.Decimal `json:"annual_price" db:"annual_price"`
Features pq.StringArray `json:"features" db:"features"`
Differentiators pq.StringArray `json:"differentiators" db:"differentiators"`
StorageGB int `json:"storage_gb" db:"storage_gb"`
IsActive bool `json:"is_active" db:"is_active"`
CreatedAt time.Time `json:"created_at" db:"created_at"`
UpdatedAt time.Time `json:"updated_at" db:"updated_at"`
}
// CreatePlanRequest represents the request to create a new plan
type CreatePlanRequest struct {
Name string `json:"name" validate:"required"`
Slug string `json:"slug" validate:"required"`
Description string `json:"description"`
MinUsers int `json:"min_users" validate:"required,min=1"`
MaxUsers int `json:"max_users" validate:"required"` // -1 for unlimited
MonthlyPrice *float64 `json:"monthly_price"`
AnnualPrice *float64 `json:"annual_price"`
Features []string `json:"features"`
Differentiators []string `json:"differentiators"`
StorageGB int `json:"storage_gb" validate:"required,min=1"`
IsActive bool `json:"is_active"`
}
// UpdatePlanRequest represents the request to update a plan
type UpdatePlanRequest struct {
Name *string `json:"name"`
Slug *string `json:"slug"`
Description *string `json:"description"`
MinUsers *int `json:"min_users"`
MaxUsers *int `json:"max_users"`
MonthlyPrice *float64 `json:"monthly_price"`
AnnualPrice *float64 `json:"annual_price"`
Features []string `json:"features"`
Differentiators []string `json:"differentiators"`
StorageGB *int `json:"storage_gb"`
IsActive *bool `json:"is_active"`
}
// Subscription represents an agency's subscription to a plan
type Subscription struct {
ID uuid.UUID `json:"id" db:"id"`
AgencyID uuid.UUID `json:"agency_id" db:"agency_id"`
PlanID uuid.UUID `json:"plan_id" db:"plan_id"`
BillingType string `json:"billing_type" db:"billing_type"` // monthly or annual
CurrentUsers int `json:"current_users" db:"current_users"`
Status string `json:"status" db:"status"` // active, suspended, cancelled
StartDate time.Time `json:"start_date" db:"start_date"`
RenewalDate time.Time `json:"renewal_date" db:"renewal_date"`
CreatedAt time.Time `json:"created_at" db:"created_at"`
UpdatedAt time.Time `json:"updated_at" db:"updated_at"`
}
// CreateSubscriptionRequest represents the request to create a subscription
type CreateSubscriptionRequest struct {
AgencyID uuid.UUID `json:"agency_id" validate:"required"`
PlanID uuid.UUID `json:"plan_id" validate:"required"`
BillingType string `json:"billing_type" validate:"required,oneof=monthly annual"`
}

View File

@@ -0,0 +1,20 @@
package domain
import "time"
type Solution struct {
ID string `json:"id" db:"id"`
Name string `json:"name" db:"name"`
Slug string `json:"slug" db:"slug"`
Icon string `json:"icon" db:"icon"`
Description string `json:"description" db:"description"`
IsActive bool `json:"is_active" db:"is_active"`
CreatedAt time.Time `json:"created_at" db:"created_at"`
UpdatedAt time.Time `json:"updated_at" db:"updated_at"`
}
type PlanSolution struct {
PlanID string `json:"plan_id" db:"plan_id"`
SolutionID string `json:"solution_id" db:"solution_id"`
CreatedAt time.Time `json:"created_at" db:"created_at"`
}

View File

@@ -45,7 +45,15 @@ type CreateTenantRequest struct {
// AgencyDetails aggregates tenant info with its admin user for superadmin view
type AgencyDetails struct {
Tenant *Tenant `json:"tenant"`
Admin *User `json:"admin,omitempty"`
AccessURL string `json:"access_url"`
Tenant *Tenant `json:"tenant"`
Admin *User `json:"admin,omitempty"`
Subscription *AgencySubscriptionInfo `json:"subscription,omitempty"`
AccessURL string `json:"access_url"`
}
type AgencySubscriptionInfo struct {
PlanID string `json:"plan_id"`
PlanName string `json:"plan_name"`
Status string `json:"status"`
Solutions []Solution `json:"solutions"`
}

View File

@@ -0,0 +1,346 @@
package repository
import (
"aggios-app/backend/internal/domain"
"database/sql"
"fmt"
"github.com/lib/pq"
)
type CRMRepository struct {
db *sql.DB
}
func NewCRMRepository(db *sql.DB) *CRMRepository {
return &CRMRepository{db: db}
}
// ==================== CUSTOMERS ====================
func (r *CRMRepository) CreateCustomer(customer *domain.CRMCustomer) error {
query := `
INSERT INTO crm_customers (
id, tenant_id, name, email, phone, company, position,
address, city, state, zip_code, country, notes, tags,
is_active, created_by
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16)
RETURNING created_at, updated_at
`
return r.db.QueryRow(
query,
customer.ID, customer.TenantID, customer.Name, customer.Email, customer.Phone,
customer.Company, customer.Position, customer.Address, customer.City, customer.State,
customer.ZipCode, customer.Country, customer.Notes, pq.Array(customer.Tags),
customer.IsActive, customer.CreatedBy,
).Scan(&customer.CreatedAt, &customer.UpdatedAt)
}
func (r *CRMRepository) GetCustomersByTenant(tenantID string) ([]domain.CRMCustomer, error) {
query := `
SELECT id, tenant_id, name, email, phone, company, position,
address, city, state, zip_code, country, notes, tags,
is_active, created_by, created_at, updated_at
FROM crm_customers
WHERE tenant_id = $1 AND is_active = true
ORDER BY created_at DESC
`
rows, err := r.db.Query(query, tenantID)
if err != nil {
return nil, err
}
defer rows.Close()
var customers []domain.CRMCustomer
for rows.Next() {
var c domain.CRMCustomer
err := rows.Scan(
&c.ID, &c.TenantID, &c.Name, &c.Email, &c.Phone, &c.Company, &c.Position,
&c.Address, &c.City, &c.State, &c.ZipCode, &c.Country, &c.Notes, pq.Array(&c.Tags),
&c.IsActive, &c.CreatedBy, &c.CreatedAt, &c.UpdatedAt,
)
if err != nil {
return nil, err
}
customers = append(customers, c)
}
return customers, nil
}
func (r *CRMRepository) GetCustomerByID(id string, tenantID string) (*domain.CRMCustomer, error) {
query := `
SELECT id, tenant_id, name, email, phone, company, position,
address, city, state, zip_code, country, notes, tags,
is_active, created_by, created_at, updated_at
FROM crm_customers
WHERE id = $1 AND tenant_id = $2
`
var c domain.CRMCustomer
err := r.db.QueryRow(query, id, tenantID).Scan(
&c.ID, &c.TenantID, &c.Name, &c.Email, &c.Phone, &c.Company, &c.Position,
&c.Address, &c.City, &c.State, &c.ZipCode, &c.Country, &c.Notes, pq.Array(&c.Tags),
&c.IsActive, &c.CreatedBy, &c.CreatedAt, &c.UpdatedAt,
)
if err != nil {
return nil, err
}
return &c, nil
}
func (r *CRMRepository) UpdateCustomer(customer *domain.CRMCustomer) error {
query := `
UPDATE crm_customers SET
name = $1, email = $2, phone = $3, company = $4, position = $5,
address = $6, city = $7, state = $8, zip_code = $9, country = $10,
notes = $11, tags = $12, is_active = $13
WHERE id = $14 AND tenant_id = $15
`
result, err := r.db.Exec(
query,
customer.Name, customer.Email, customer.Phone, customer.Company, customer.Position,
customer.Address, customer.City, customer.State, customer.ZipCode, customer.Country,
customer.Notes, pq.Array(customer.Tags), customer.IsActive,
customer.ID, customer.TenantID,
)
if err != nil {
return err
}
rows, err := result.RowsAffected()
if err != nil {
return err
}
if rows == 0 {
return fmt.Errorf("customer not found")
}
return nil
}
func (r *CRMRepository) DeleteCustomer(id string, tenantID string) error {
query := `DELETE FROM crm_customers WHERE id = $1 AND tenant_id = $2`
result, err := r.db.Exec(query, id, tenantID)
if err != nil {
return err
}
rows, err := result.RowsAffected()
if err != nil {
return err
}
if rows == 0 {
return fmt.Errorf("customer not found")
}
return nil
}
// ==================== LISTS ====================
func (r *CRMRepository) CreateList(list *domain.CRMList) error {
query := `
INSERT INTO crm_lists (id, tenant_id, name, description, color, created_by)
VALUES ($1, $2, $3, $4, $5, $6)
RETURNING created_at, updated_at
`
return r.db.QueryRow(
query,
list.ID, list.TenantID, list.Name, list.Description, list.Color, list.CreatedBy,
).Scan(&list.CreatedAt, &list.UpdatedAt)
}
func (r *CRMRepository) GetListsByTenant(tenantID string) ([]domain.CRMListWithCustomers, error) {
query := `
SELECT l.id, l.tenant_id, l.name, l.description, l.color, l.created_by,
l.created_at, l.updated_at,
COUNT(cl.customer_id) as customer_count
FROM crm_lists l
LEFT JOIN crm_customer_lists cl ON l.id = cl.list_id
WHERE l.tenant_id = $1
GROUP BY l.id
ORDER BY l.created_at DESC
`
rows, err := r.db.Query(query, tenantID)
if err != nil {
return nil, err
}
defer rows.Close()
var lists []domain.CRMListWithCustomers
for rows.Next() {
var l domain.CRMListWithCustomers
err := rows.Scan(
&l.ID, &l.TenantID, &l.Name, &l.Description, &l.Color, &l.CreatedBy,
&l.CreatedAt, &l.UpdatedAt, &l.CustomerCount,
)
if err != nil {
return nil, err
}
lists = append(lists, l)
}
return lists, nil
}
func (r *CRMRepository) GetListByID(id string, tenantID string) (*domain.CRMList, error) {
query := `
SELECT id, tenant_id, name, description, color, created_by, created_at, updated_at
FROM crm_lists
WHERE id = $1 AND tenant_id = $2
`
var l domain.CRMList
err := r.db.QueryRow(query, id, tenantID).Scan(
&l.ID, &l.TenantID, &l.Name, &l.Description, &l.Color, &l.CreatedBy,
&l.CreatedAt, &l.UpdatedAt,
)
if err != nil {
return nil, err
}
return &l, nil
}
func (r *CRMRepository) UpdateList(list *domain.CRMList) error {
query := `
UPDATE crm_lists SET
name = $1, description = $2, color = $3
WHERE id = $4 AND tenant_id = $5
`
result, err := r.db.Exec(query, list.Name, list.Description, list.Color, list.ID, list.TenantID)
if err != nil {
return err
}
rows, err := result.RowsAffected()
if err != nil {
return err
}
if rows == 0 {
return fmt.Errorf("list not found")
}
return nil
}
func (r *CRMRepository) DeleteList(id string, tenantID string) error {
query := `DELETE FROM crm_lists WHERE id = $1 AND tenant_id = $2`
result, err := r.db.Exec(query, id, tenantID)
if err != nil {
return err
}
rows, err := result.RowsAffected()
if err != nil {
return err
}
if rows == 0 {
return fmt.Errorf("list not found")
}
return nil
}
// ==================== CUSTOMER <-> LIST ====================
func (r *CRMRepository) AddCustomerToList(customerID, listID, addedBy string) error {
query := `
INSERT INTO crm_customer_lists (customer_id, list_id, added_by)
VALUES ($1, $2, $3)
ON CONFLICT (customer_id, list_id) DO NOTHING
`
_, err := r.db.Exec(query, customerID, listID, addedBy)
return err
}
func (r *CRMRepository) RemoveCustomerFromList(customerID, listID string) error {
query := `DELETE FROM crm_customer_lists WHERE customer_id = $1 AND list_id = $2`
_, err := r.db.Exec(query, customerID, listID)
return err
}
func (r *CRMRepository) GetCustomerLists(customerID string) ([]domain.CRMList, error) {
query := `
SELECT l.id, l.tenant_id, l.name, l.description, l.color, l.created_by,
l.created_at, l.updated_at
FROM crm_lists l
INNER JOIN crm_customer_lists cl ON l.id = cl.list_id
WHERE cl.customer_id = $1
ORDER BY l.name
`
rows, err := r.db.Query(query, customerID)
if err != nil {
return nil, err
}
defer rows.Close()
var lists []domain.CRMList
for rows.Next() {
var l domain.CRMList
err := rows.Scan(
&l.ID, &l.TenantID, &l.Name, &l.Description, &l.Color, &l.CreatedBy,
&l.CreatedAt, &l.UpdatedAt,
)
if err != nil {
return nil, err
}
lists = append(lists, l)
}
return lists, nil
}
func (r *CRMRepository) GetListCustomers(listID string, tenantID string) ([]domain.CRMCustomer, error) {
query := `
SELECT c.id, c.tenant_id, c.name, c.email, c.phone, c.company, c.position,
c.address, c.city, c.state, c.zip_code, c.country, c.notes, c.tags,
c.is_active, c.created_by, c.created_at, c.updated_at
FROM crm_customers c
INNER JOIN crm_customer_lists cl ON c.id = cl.customer_id
WHERE cl.list_id = $1 AND c.tenant_id = $2 AND c.is_active = true
ORDER BY c.name
`
rows, err := r.db.Query(query, listID, tenantID)
if err != nil {
return nil, err
}
defer rows.Close()
var customers []domain.CRMCustomer
for rows.Next() {
var c domain.CRMCustomer
err := rows.Scan(
&c.ID, &c.TenantID, &c.Name, &c.Email, &c.Phone, &c.Company, &c.Position,
&c.Address, &c.City, &c.State, &c.ZipCode, &c.Country, &c.Notes, pq.Array(&c.Tags),
&c.IsActive, &c.CreatedBy, &c.CreatedAt, &c.UpdatedAt,
)
if err != nil {
return nil, err
}
customers = append(customers, c)
}
return customers, nil
}

View File

@@ -0,0 +1,283 @@
package repository
import (
"database/sql"
"time"
"aggios-app/backend/internal/domain"
"github.com/google/uuid"
"github.com/lib/pq"
)
// PlanRepository handles database operations for plans
type PlanRepository struct {
db *sql.DB
}
// NewPlanRepository creates a new plan repository
func NewPlanRepository(db *sql.DB) *PlanRepository {
return &PlanRepository{db: db}
}
// Create creates a new plan
func (r *PlanRepository) Create(plan *domain.Plan) error {
query := `
INSERT INTO plans (id, name, slug, description, min_users, max_users, monthly_price, annual_price, features, differentiators, storage_gb, is_active, created_at, updated_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)
RETURNING id, created_at, updated_at
`
now := time.Now()
plan.ID = uuid.New()
plan.CreatedAt = now
plan.UpdatedAt = now
features := pq.Array(plan.Features)
differentiators := pq.Array(plan.Differentiators)
return r.db.QueryRow(
query,
plan.ID,
plan.Name,
plan.Slug,
plan.Description,
plan.MinUsers,
plan.MaxUsers,
plan.MonthlyPrice,
plan.AnnualPrice,
features,
differentiators,
plan.StorageGB,
plan.IsActive,
plan.CreatedAt,
plan.UpdatedAt,
).Scan(&plan.ID, &plan.CreatedAt, &plan.UpdatedAt)
}
// GetByID retrieves a plan by ID
func (r *PlanRepository) GetByID(id uuid.UUID) (*domain.Plan, error) {
query := `
SELECT id, name, slug, description, min_users, max_users, monthly_price, annual_price, features, differentiators, storage_gb, is_active, created_at, updated_at
FROM plans
WHERE id = $1
`
plan := &domain.Plan{}
var features, differentiators pq.StringArray
err := r.db.QueryRow(query, id).Scan(
&plan.ID,
&plan.Name,
&plan.Slug,
&plan.Description,
&plan.MinUsers,
&plan.MaxUsers,
&plan.MonthlyPrice,
&plan.AnnualPrice,
&features,
&differentiators,
&plan.StorageGB,
&plan.IsActive,
&plan.CreatedAt,
&plan.UpdatedAt,
)
if err != nil {
return nil, err
}
plan.Features = []string(features)
plan.Differentiators = []string(differentiators)
return plan, nil
}
// GetBySlug retrieves a plan by slug
func (r *PlanRepository) GetBySlug(slug string) (*domain.Plan, error) {
query := `
SELECT id, name, slug, description, min_users, max_users, monthly_price, annual_price, features, differentiators, storage_gb, is_active, created_at, updated_at
FROM plans
WHERE slug = $1
`
plan := &domain.Plan{}
var features, differentiators pq.StringArray
err := r.db.QueryRow(query, slug).Scan(
&plan.ID,
&plan.Name,
&plan.Slug,
&plan.Description,
&plan.MinUsers,
&plan.MaxUsers,
&plan.MonthlyPrice,
&plan.AnnualPrice,
&features,
&differentiators,
&plan.StorageGB,
&plan.IsActive,
&plan.CreatedAt,
&plan.UpdatedAt,
)
if err != nil {
return nil, err
}
plan.Features = []string(features)
plan.Differentiators = []string(differentiators)
return plan, nil
}
// ListAll retrieves all plans
func (r *PlanRepository) ListAll() ([]*domain.Plan, error) {
query := `
SELECT id, name, slug, description, min_users, max_users, monthly_price, annual_price, features, differentiators, storage_gb, is_active, created_at, updated_at
FROM plans
ORDER BY min_users ASC
`
rows, err := r.db.Query(query)
if err != nil {
return nil, err
}
defer rows.Close()
var plans []*domain.Plan
for rows.Next() {
plan := &domain.Plan{}
var features, differentiators pq.StringArray
err := rows.Scan(
&plan.ID,
&plan.Name,
&plan.Slug,
&plan.Description,
&plan.MinUsers,
&plan.MaxUsers,
&plan.MonthlyPrice,
&plan.AnnualPrice,
&features,
&differentiators,
&plan.StorageGB,
&plan.IsActive,
&plan.CreatedAt,
&plan.UpdatedAt,
)
if err != nil {
return nil, err
}
plan.Features = []string(features)
plan.Differentiators = []string(differentiators)
plans = append(plans, plan)
}
return plans, rows.Err()
}
// ListActive retrieves all active plans
func (r *PlanRepository) ListActive() ([]*domain.Plan, error) {
query := `
SELECT id, name, slug, description, min_users, max_users, monthly_price, annual_price, features, differentiators, storage_gb, is_active, created_at, updated_at
FROM plans
WHERE is_active = true
ORDER BY min_users ASC
`
rows, err := r.db.Query(query)
if err != nil {
return nil, err
}
defer rows.Close()
var plans []*domain.Plan
for rows.Next() {
plan := &domain.Plan{}
var features, differentiators pq.StringArray
err := rows.Scan(
&plan.ID,
&plan.Name,
&plan.Slug,
&plan.Description,
&plan.MinUsers,
&plan.MaxUsers,
&plan.MonthlyPrice,
&plan.AnnualPrice,
&features,
&differentiators,
&plan.StorageGB,
&plan.IsActive,
&plan.CreatedAt,
&plan.UpdatedAt,
)
if err != nil {
return nil, err
}
plan.Features = []string(features)
plan.Differentiators = []string(differentiators)
plans = append(plans, plan)
}
return plans, rows.Err()
}
// Update updates a plan
func (r *PlanRepository) Update(plan *domain.Plan) error {
query := `
UPDATE plans
SET name = $2, slug = $3, description = $4, min_users = $5, max_users = $6, monthly_price = $7, annual_price = $8, features = $9, differentiators = $10, storage_gb = $11, is_active = $12, updated_at = $13
WHERE id = $1
RETURNING updated_at
`
plan.UpdatedAt = time.Now()
features := pq.Array(plan.Features)
differentiators := pq.Array(plan.Differentiators)
return r.db.QueryRow(
query,
plan.ID,
plan.Name,
plan.Slug,
plan.Description,
plan.MinUsers,
plan.MaxUsers,
plan.MonthlyPrice,
plan.AnnualPrice,
features,
differentiators,
plan.StorageGB,
plan.IsActive,
plan.UpdatedAt,
).Scan(&plan.UpdatedAt)
}
// Delete deletes a plan
func (r *PlanRepository) Delete(id uuid.UUID) error {
query := `DELETE FROM plans WHERE id = $1`
result, err := r.db.Exec(query, id)
if err != nil {
return err
}
rowsAffected, err := result.RowsAffected()
if err != nil {
return err
}
if rowsAffected == 0 {
return sql.ErrNoRows
}
return nil
}

View File

@@ -0,0 +1,300 @@
package repository
import (
"aggios-app/backend/internal/domain"
"database/sql"
"fmt"
)
type SolutionRepository struct {
db *sql.DB
}
func NewSolutionRepository(db *sql.DB) *SolutionRepository {
return &SolutionRepository{db: db}
}
// ==================== SOLUTIONS ====================
func (r *SolutionRepository) CreateSolution(solution *domain.Solution) error {
query := `
INSERT INTO solutions (id, name, slug, icon, description, is_active)
VALUES ($1, $2, $3, $4, $5, $6)
RETURNING created_at, updated_at
`
return r.db.QueryRow(
query,
solution.ID, solution.Name, solution.Slug, solution.Icon,
solution.Description, solution.IsActive,
).Scan(&solution.CreatedAt, &solution.UpdatedAt)
}
func (r *SolutionRepository) GetAllSolutions() ([]domain.Solution, error) {
query := `
SELECT id, name, slug, icon, description, is_active, created_at, updated_at
FROM solutions
ORDER BY created_at DESC
`
rows, err := r.db.Query(query)
if err != nil {
return nil, err
}
defer rows.Close()
var solutions []domain.Solution
for rows.Next() {
var s domain.Solution
err := rows.Scan(
&s.ID, &s.Name, &s.Slug, &s.Icon, &s.Description,
&s.IsActive, &s.CreatedAt, &s.UpdatedAt,
)
if err != nil {
return nil, err
}
solutions = append(solutions, s)
}
return solutions, nil
}
func (r *SolutionRepository) GetActiveSolutions() ([]domain.Solution, error) {
query := `
SELECT id, name, slug, icon, description, is_active, created_at, updated_at
FROM solutions
WHERE is_active = true
ORDER BY name
`
rows, err := r.db.Query(query)
if err != nil {
return nil, err
}
defer rows.Close()
var solutions []domain.Solution
for rows.Next() {
var s domain.Solution
err := rows.Scan(
&s.ID, &s.Name, &s.Slug, &s.Icon, &s.Description,
&s.IsActive, &s.CreatedAt, &s.UpdatedAt,
)
if err != nil {
return nil, err
}
solutions = append(solutions, s)
}
return solutions, nil
}
func (r *SolutionRepository) GetSolutionByID(id string) (*domain.Solution, error) {
query := `
SELECT id, name, slug, icon, description, is_active, created_at, updated_at
FROM solutions
WHERE id = $1
`
var s domain.Solution
err := r.db.QueryRow(query, id).Scan(
&s.ID, &s.Name, &s.Slug, &s.Icon, &s.Description,
&s.IsActive, &s.CreatedAt, &s.UpdatedAt,
)
if err != nil {
return nil, err
}
return &s, nil
}
func (r *SolutionRepository) GetSolutionBySlug(slug string) (*domain.Solution, error) {
query := `
SELECT id, name, slug, icon, description, is_active, created_at, updated_at
FROM solutions
WHERE slug = $1
`
var s domain.Solution
err := r.db.QueryRow(query, slug).Scan(
&s.ID, &s.Name, &s.Slug, &s.Icon, &s.Description,
&s.IsActive, &s.CreatedAt, &s.UpdatedAt,
)
if err != nil {
return nil, err
}
return &s, nil
}
func (r *SolutionRepository) UpdateSolution(solution *domain.Solution) error {
query := `
UPDATE solutions SET
name = $1, slug = $2, icon = $3, description = $4, is_active = $5, updated_at = CURRENT_TIMESTAMP
WHERE id = $6
`
result, err := r.db.Exec(
query,
solution.Name, solution.Slug, solution.Icon, solution.Description,
solution.IsActive, solution.ID,
)
if err != nil {
return err
}
rows, err := result.RowsAffected()
if err != nil {
return err
}
if rows == 0 {
return fmt.Errorf("solution not found")
}
return nil
}
func (r *SolutionRepository) DeleteSolution(id string) error {
query := `DELETE FROM solutions WHERE id = $1`
result, err := r.db.Exec(query, id)
if err != nil {
return err
}
rows, err := result.RowsAffected()
if err != nil {
return err
}
if rows == 0 {
return fmt.Errorf("solution not found")
}
return nil
}
// ==================== PLAN <-> SOLUTION ====================
func (r *SolutionRepository) AddSolutionToPlan(planID, solutionID string) error {
query := `
INSERT INTO plan_solutions (plan_id, solution_id)
VALUES ($1, $2)
ON CONFLICT (plan_id, solution_id) DO NOTHING
`
_, err := r.db.Exec(query, planID, solutionID)
return err
}
func (r *SolutionRepository) RemoveSolutionFromPlan(planID, solutionID string) error {
query := `DELETE FROM plan_solutions WHERE plan_id = $1 AND solution_id = $2`
_, err := r.db.Exec(query, planID, solutionID)
return err
}
func (r *SolutionRepository) GetPlanSolutions(planID string) ([]domain.Solution, error) {
query := `
SELECT s.id, s.name, s.slug, s.icon, s.description, s.is_active, s.created_at, s.updated_at
FROM solutions s
INNER JOIN plan_solutions ps ON s.id = ps.solution_id
WHERE ps.plan_id = $1
ORDER BY s.name
`
rows, err := r.db.Query(query, planID)
if err != nil {
return nil, err
}
defer rows.Close()
var solutions []domain.Solution
for rows.Next() {
var s domain.Solution
err := rows.Scan(
&s.ID, &s.Name, &s.Slug, &s.Icon, &s.Description,
&s.IsActive, &s.CreatedAt, &s.UpdatedAt,
)
if err != nil {
return nil, err
}
solutions = append(solutions, s)
}
return solutions, nil
}
func (r *SolutionRepository) SetPlanSolutions(planID string, solutionIDs []string) error {
// Inicia transação
tx, err := r.db.Begin()
if err != nil {
return err
}
// Remove todas as soluções antigas do plano
_, err = tx.Exec(`DELETE FROM plan_solutions WHERE plan_id = $1`, planID)
if err != nil {
tx.Rollback()
return err
}
// Adiciona as novas soluções
stmt, err := tx.Prepare(`INSERT INTO plan_solutions (plan_id, solution_id) VALUES ($1, $2)`)
if err != nil {
tx.Rollback()
return err
}
defer stmt.Close()
for _, solutionID := range solutionIDs {
_, err = stmt.Exec(planID, solutionID)
if err != nil {
tx.Rollback()
return err
}
}
return tx.Commit()
}
func (r *SolutionRepository) GetTenantSolutions(tenantID string) ([]domain.Solution, error) {
query := `
SELECT DISTINCT s.id, s.name, s.slug, s.icon, s.description, s.is_active, s.created_at, s.updated_at
FROM solutions s
INNER JOIN plan_solutions ps ON s.id = ps.solution_id
INNER JOIN agency_subscriptions asub ON ps.plan_id = asub.plan_id
WHERE asub.agency_id = $1 AND s.is_active = true AND asub.status = 'active'
ORDER BY s.name
`
rows, err := r.db.Query(query, tenantID)
if err != nil {
return nil, err
}
defer rows.Close()
var solutions []domain.Solution
for rows.Next() {
var s domain.Solution
err := rows.Scan(
&s.ID, &s.Name, &s.Slug, &s.Icon, &s.Description,
&s.IsActive, &s.CreatedAt, &s.UpdatedAt,
)
if err != nil {
return nil, err
}
solutions = append(solutions, s)
}
// Se não encontrou via subscription, retorna array vazio
if solutions == nil {
solutions = []domain.Solution{}
}
return solutions, nil
}

View File

@@ -0,0 +1,203 @@
package repository
import (
"database/sql"
"time"
"aggios-app/backend/internal/domain"
"github.com/google/uuid"
)
// SubscriptionRepository handles database operations for subscriptions
type SubscriptionRepository struct {
db *sql.DB
}
// NewSubscriptionRepository creates a new subscription repository
func NewSubscriptionRepository(db *sql.DB) *SubscriptionRepository {
return &SubscriptionRepository{db: db}
}
// Create creates a new subscription
func (r *SubscriptionRepository) Create(subscription *domain.Subscription) error {
query := `
INSERT INTO agency_subscriptions (id, agency_id, plan_id, billing_type, current_users, status, start_date, renewal_date, created_at, updated_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
RETURNING id, created_at, updated_at
`
now := time.Now()
subscription.ID = uuid.New()
subscription.CreatedAt = now
subscription.UpdatedAt = now
subscription.StartDate = now
// Set renewal date based on billing type
if subscription.BillingType == "annual" {
subscription.RenewalDate = now.AddDate(1, 0, 0)
} else {
subscription.RenewalDate = now.AddDate(0, 1, 0)
}
return r.db.QueryRow(
query,
subscription.ID,
subscription.AgencyID,
subscription.PlanID,
subscription.BillingType,
subscription.CurrentUsers,
subscription.Status,
subscription.StartDate,
subscription.RenewalDate,
subscription.CreatedAt,
subscription.UpdatedAt,
).Scan(&subscription.ID, &subscription.CreatedAt, &subscription.UpdatedAt)
}
// GetByID retrieves a subscription by ID
func (r *SubscriptionRepository) GetByID(id uuid.UUID) (*domain.Subscription, error) {
query := `
SELECT id, agency_id, plan_id, billing_type, current_users, status, start_date, renewal_date, created_at, updated_at
FROM agency_subscriptions
WHERE id = $1
`
subscription := &domain.Subscription{}
err := r.db.QueryRow(query, id).Scan(
&subscription.ID,
&subscription.AgencyID,
&subscription.PlanID,
&subscription.BillingType,
&subscription.CurrentUsers,
&subscription.Status,
&subscription.StartDate,
&subscription.RenewalDate,
&subscription.CreatedAt,
&subscription.UpdatedAt,
)
return subscription, err
}
// GetByAgencyID retrieves a subscription by agency ID
func (r *SubscriptionRepository) GetByAgencyID(agencyID uuid.UUID) (*domain.Subscription, error) {
query := `
SELECT id, agency_id, plan_id, billing_type, current_users, status, start_date, renewal_date, created_at, updated_at
FROM agency_subscriptions
WHERE agency_id = $1 AND status = 'active'
LIMIT 1
`
subscription := &domain.Subscription{}
err := r.db.QueryRow(query, agencyID).Scan(
&subscription.ID,
&subscription.AgencyID,
&subscription.PlanID,
&subscription.BillingType,
&subscription.CurrentUsers,
&subscription.Status,
&subscription.StartDate,
&subscription.RenewalDate,
&subscription.CreatedAt,
&subscription.UpdatedAt,
)
return subscription, err
}
// ListAll retrieves all subscriptions
func (r *SubscriptionRepository) ListAll() ([]*domain.Subscription, error) {
query := `
SELECT id, agency_id, plan_id, billing_type, current_users, status, start_date, renewal_date, created_at, updated_at
FROM agency_subscriptions
ORDER BY created_at DESC
`
rows, err := r.db.Query(query)
if err != nil {
return nil, err
}
defer rows.Close()
var subscriptions []*domain.Subscription
for rows.Next() {
subscription := &domain.Subscription{}
err := rows.Scan(
&subscription.ID,
&subscription.AgencyID,
&subscription.PlanID,
&subscription.BillingType,
&subscription.CurrentUsers,
&subscription.Status,
&subscription.StartDate,
&subscription.RenewalDate,
&subscription.CreatedAt,
&subscription.UpdatedAt,
)
if err != nil {
return nil, err
}
subscriptions = append(subscriptions, subscription)
}
return subscriptions, rows.Err()
}
// Update updates a subscription
func (r *SubscriptionRepository) Update(subscription *domain.Subscription) error {
query := `
UPDATE agency_subscriptions
SET plan_id = $2, billing_type = $3, current_users = $4, status = $5, renewal_date = $6, updated_at = $7
WHERE id = $1
RETURNING updated_at
`
subscription.UpdatedAt = time.Now()
return r.db.QueryRow(
query,
subscription.ID,
subscription.PlanID,
subscription.BillingType,
subscription.CurrentUsers,
subscription.Status,
subscription.RenewalDate,
subscription.UpdatedAt,
).Scan(&subscription.UpdatedAt)
}
// Delete deletes a subscription
func (r *SubscriptionRepository) Delete(id uuid.UUID) error {
query := `DELETE FROM agency_subscriptions WHERE id = $1`
result, err := r.db.Exec(query, id)
if err != nil {
return err
}
rowsAffected, err := result.RowsAffected()
if err != nil {
return err
}
if rowsAffected == 0 {
return sql.ErrNoRows
}
return nil
}
// UpdateUserCount updates the current user count for a subscription
func (r *SubscriptionRepository) UpdateUserCount(agencyID uuid.UUID, userCount int) error {
query := `
UPDATE agency_subscriptions
SET current_users = $2, updated_at = $3
WHERE agency_id = $1 AND status = 'active'
`
_, err := r.db.Exec(query, agencyID, userCount, time.Now())
return err
}

View File

@@ -188,17 +188,23 @@ func (r *TenantRepository) FindByID(id uuid.UUID) (*domain.Tenant, error) {
// FindBySubdomain finds a tenant by subdomain
func (r *TenantRepository) FindBySubdomain(subdomain string) (*domain.Tenant, error) {
query := `
SELECT id, name, domain, subdomain, created_at, updated_at
SELECT id, name, domain, subdomain, primary_color, secondary_color, logo_url, logo_horizontal_url, created_at, updated_at
FROM tenants
WHERE subdomain = $1
`
tenant := &domain.Tenant{}
var primaryColor, secondaryColor, logoURL, logoHorizontalURL sql.NullString
err := r.db.QueryRow(query, subdomain).Scan(
&tenant.ID,
&tenant.Name,
&tenant.Domain,
&tenant.Subdomain,
&primaryColor,
&secondaryColor,
&logoURL,
&logoHorizontalURL,
&tenant.CreatedAt,
&tenant.UpdatedAt,
)
@@ -207,7 +213,24 @@ func (r *TenantRepository) FindBySubdomain(subdomain string) (*domain.Tenant, er
return nil, nil
}
return tenant, err
if err != nil {
return nil, err
}
if primaryColor.Valid {
tenant.PrimaryColor = primaryColor.String
}
if secondaryColor.Valid {
tenant.SecondaryColor = secondaryColor.String
}
if logoURL.Valid {
tenant.LogoURL = logoURL.String
}
if logoHorizontalURL.Valid {
tenant.LogoHorizontalURL = logoHorizontalURL.String
}
return tenant, nil
}
// SubdomainExists checks if a subdomain is already taken

View File

@@ -4,6 +4,7 @@ import (
"aggios-app/backend/internal/config"
"aggios-app/backend/internal/domain"
"aggios-app/backend/internal/repository"
"database/sql"
"fmt"
"github.com/google/uuid"
@@ -15,14 +16,16 @@ type AgencyService struct {
userRepo *repository.UserRepository
tenantRepo *repository.TenantRepository
cfg *config.Config
db *sql.DB
}
// NewAgencyService creates a new agency service
func NewAgencyService(userRepo *repository.UserRepository, tenantRepo *repository.TenantRepository, cfg *config.Config) *AgencyService {
func NewAgencyService(userRepo *repository.UserRepository, tenantRepo *repository.TenantRepository, cfg *config.Config, db *sql.DB) *AgencyService {
return &AgencyService{
userRepo: userRepo,
tenantRepo: tenantRepo,
cfg: cfg,
db: db,
}
}
@@ -180,6 +183,43 @@ func (s *AgencyService) GetAgencyDetails(id uuid.UUID) (*domain.AgencyDetails, e
details.Admin = admin
}
// Buscar subscription e soluções
var subscription domain.AgencySubscriptionInfo
query := `
SELECT
s.plan_id,
p.name as plan_name,
s.status
FROM agency_subscriptions s
JOIN plans p ON s.plan_id = p.id
WHERE s.agency_id = $1
LIMIT 1
`
err = s.db.QueryRow(query, id).Scan(&subscription.PlanID, &subscription.PlanName, &subscription.Status)
if err == nil {
// Buscar soluções do plano
solutionsQuery := `
SELECT sol.id, sol.name, sol.slug, sol.icon
FROM solutions sol
JOIN plan_solutions ps ON sol.id = ps.solution_id
WHERE ps.plan_id = $1
ORDER BY sol.name
`
rows, err := s.db.Query(solutionsQuery, subscription.PlanID)
if err == nil {
defer rows.Close()
var solutions []domain.Solution
for rows.Next() {
var solution domain.Solution
if err := rows.Scan(&solution.ID, &solution.Name, &solution.Slug, &solution.Icon); err == nil {
solutions = append(solutions, solution)
}
}
subscription.Solutions = solutions
details.Subscription = &subscription
}
}
return details, nil
}

View File

@@ -0,0 +1,286 @@
package service
import (
"database/sql"
"errors"
"fmt"
"aggios-app/backend/internal/domain"
"aggios-app/backend/internal/repository"
"github.com/google/uuid"
"github.com/shopspring/decimal"
)
var (
ErrPlanNotFound = errors.New("plan not found")
ErrPlanSlugTaken = errors.New("plan slug already exists")
ErrInvalidUserRange = errors.New("invalid user range: min_users must be less than or equal to max_users")
ErrSubscriptionNotFound = errors.New("subscription not found")
ErrUserLimitExceeded = errors.New("user limit exceeded for this plan")
ErrSubscriptionExists = errors.New("agency already has an active subscription")
)
// PlanService handles plan business logic
type PlanService struct {
planRepo *repository.PlanRepository
subscriptionRepo *repository.SubscriptionRepository
}
// NewPlanService creates a new plan service
func NewPlanService(planRepo *repository.PlanRepository, subscriptionRepo *repository.SubscriptionRepository) *PlanService {
return &PlanService{
planRepo: planRepo,
subscriptionRepo: subscriptionRepo,
}
}
// CreatePlan creates a new plan
func (s *PlanService) CreatePlan(req *domain.CreatePlanRequest) (*domain.Plan, error) {
// Validate user range
if req.MinUsers > req.MaxUsers && req.MaxUsers != -1 {
return nil, ErrInvalidUserRange
}
// Check if slug is unique
existing, _ := s.planRepo.GetBySlug(req.Slug)
if existing != nil {
return nil, ErrPlanSlugTaken
}
plan := &domain.Plan{
Name: req.Name,
Slug: req.Slug,
Description: req.Description,
MinUsers: req.MinUsers,
MaxUsers: req.MaxUsers,
Features: req.Features,
Differentiators: req.Differentiators,
StorageGB: req.StorageGB,
IsActive: req.IsActive,
}
// Convert prices if provided
if req.MonthlyPrice != nil {
price := decimal.NewFromFloat(*req.MonthlyPrice)
plan.MonthlyPrice = &price
}
if req.AnnualPrice != nil {
price := decimal.NewFromFloat(*req.AnnualPrice)
plan.AnnualPrice = &price
}
if err := s.planRepo.Create(plan); err != nil {
return nil, err
}
return plan, nil
}
// GetPlan retrieves a plan by ID
func (s *PlanService) GetPlan(id uuid.UUID) (*domain.Plan, error) {
plan, err := s.planRepo.GetByID(id)
if err != nil {
if err == sql.ErrNoRows {
return nil, ErrPlanNotFound
}
return nil, err
}
return plan, nil
}
// ListPlans retrieves all plans
func (s *PlanService) ListPlans() ([]*domain.Plan, error) {
return s.planRepo.ListAll()
}
// ListActivePlans retrieves all active plans
func (s *PlanService) ListActivePlans() ([]*domain.Plan, error) {
return s.planRepo.ListActive()
}
// UpdatePlan updates a plan
func (s *PlanService) UpdatePlan(id uuid.UUID, req *domain.UpdatePlanRequest) (*domain.Plan, error) {
plan, err := s.planRepo.GetByID(id)
if err != nil {
if err == sql.ErrNoRows {
return nil, ErrPlanNotFound
}
return nil, err
}
// Update fields if provided
if req.Name != nil {
plan.Name = *req.Name
}
if req.Slug != nil {
// Check if new slug is unique
existing, _ := s.planRepo.GetBySlug(*req.Slug)
if existing != nil && existing.ID != plan.ID {
return nil, ErrPlanSlugTaken
}
plan.Slug = *req.Slug
}
if req.Description != nil {
plan.Description = *req.Description
}
if req.MinUsers != nil {
plan.MinUsers = *req.MinUsers
}
if req.MaxUsers != nil {
plan.MaxUsers = *req.MaxUsers
}
if req.MonthlyPrice != nil {
price := decimal.NewFromFloat(*req.MonthlyPrice)
plan.MonthlyPrice = &price
}
if req.AnnualPrice != nil {
price := decimal.NewFromFloat(*req.AnnualPrice)
plan.AnnualPrice = &price
}
if req.Features != nil {
plan.Features = req.Features
}
if req.Differentiators != nil {
plan.Differentiators = req.Differentiators
}
if req.StorageGB != nil {
plan.StorageGB = *req.StorageGB
}
if req.IsActive != nil {
plan.IsActive = *req.IsActive
}
// Validate user range
if plan.MinUsers > plan.MaxUsers && plan.MaxUsers != -1 {
return nil, ErrInvalidUserRange
}
if err := s.planRepo.Update(plan); err != nil {
return nil, err
}
return plan, nil
}
// DeletePlan deletes a plan
func (s *PlanService) DeletePlan(id uuid.UUID) error {
// Check if plan exists
if _, err := s.planRepo.GetByID(id); err != nil {
if err == sql.ErrNoRows {
return ErrPlanNotFound
}
return err
}
return s.planRepo.Delete(id)
}
// CreateSubscription creates a new subscription for an agency
func (s *PlanService) CreateSubscription(req *domain.CreateSubscriptionRequest) (*domain.Subscription, error) {
// Check if plan exists
plan, err := s.planRepo.GetByID(req.PlanID)
if err != nil {
if err == sql.ErrNoRows {
return nil, ErrPlanNotFound
}
return nil, err
}
// Check if agency already has active subscription
existing, err := s.subscriptionRepo.GetByAgencyID(req.AgencyID)
if err != nil && err != sql.ErrNoRows {
return nil, err
}
if existing != nil {
return nil, ErrSubscriptionExists
}
subscription := &domain.Subscription{
AgencyID: req.AgencyID,
PlanID: req.PlanID,
BillingType: req.BillingType,
Status: "active",
CurrentUsers: 0,
}
if err := s.subscriptionRepo.Create(subscription); err != nil {
return nil, err
}
// Load plan details
subscription.PlanID = plan.ID
return subscription, nil
}
// GetSubscription retrieves a subscription by ID
func (s *PlanService) GetSubscription(id uuid.UUID) (*domain.Subscription, error) {
subscription, err := s.subscriptionRepo.GetByID(id)
if err != nil {
if err == sql.ErrNoRows {
return nil, ErrSubscriptionNotFound
}
return nil, err
}
return subscription, nil
}
// GetAgencySubscription retrieves an agency's active subscription
func (s *PlanService) GetAgencySubscription(agencyID uuid.UUID) (*domain.Subscription, error) {
subscription, err := s.subscriptionRepo.GetByAgencyID(agencyID)
if err != nil {
if err == sql.ErrNoRows {
return nil, ErrSubscriptionNotFound
}
return nil, err
}
return subscription, nil
}
// ListSubscriptions retrieves all subscriptions
func (s *PlanService) ListSubscriptions() ([]*domain.Subscription, error) {
return s.subscriptionRepo.ListAll()
}
// ValidateUserLimit checks if adding a user would exceed plan limit
func (s *PlanService) ValidateUserLimit(agencyID uuid.UUID, newUserCount int) error {
subscription, err := s.subscriptionRepo.GetByAgencyID(agencyID)
if err != nil {
if err == sql.ErrNoRows {
return ErrSubscriptionNotFound
}
return err
}
plan, err := s.planRepo.GetByID(subscription.PlanID)
if err != nil {
if err == sql.ErrNoRows {
return ErrPlanNotFound
}
return err
}
if plan.MaxUsers != -1 && newUserCount > plan.MaxUsers {
return fmt.Errorf("%w (limit: %d, requested: %d)", ErrUserLimitExceeded, plan.MaxUsers, newUserCount)
}
return nil
}
// GetPlanByUserCount returns the appropriate plan for a given user count
func (s *PlanService) GetPlanByUserCount(userCount int) (*domain.Plan, error) {
plans, err := s.planRepo.ListActive()
if err != nil {
return nil, err
}
// Find the plan that fits the user count
for _, plan := range plans {
if userCount >= plan.MinUsers && (plan.MaxUsers == -1 || userCount <= plan.MaxUsers) {
return plan, nil
}
}
return nil, fmt.Errorf("no plan found for user count: %d", userCount)
}

View File

@@ -17,12 +17,14 @@ var (
// TenantService handles tenant business logic
type TenantService struct {
tenantRepo *repository.TenantRepository
db *sql.DB
}
// NewTenantService creates a new tenant service
func NewTenantService(tenantRepo *repository.TenantRepository) *TenantService {
func NewTenantService(tenantRepo *repository.TenantRepository, db *sql.DB) *TenantService {
return &TenantService{
tenantRepo: tenantRepo,
db: db,
}
}
@@ -79,6 +81,84 @@ func (s *TenantService) ListAll() ([]*domain.Tenant, error) {
return s.tenantRepo.FindAll()
}
// ListAllWithDetails retrieves all tenants with their plan and solutions information
func (s *TenantService) ListAllWithDetails() ([]map[string]interface{}, error) {
tenants, err := s.tenantRepo.FindAll()
if err != nil {
return nil, err
}
var result []map[string]interface{}
for _, tenant := range tenants {
tenantData := map[string]interface{}{
"id": tenant.ID,
"name": tenant.Name,
"subdomain": tenant.Subdomain,
"domain": tenant.Domain,
"email": tenant.Email,
"phone": tenant.Phone,
"cnpj": tenant.CNPJ,
"is_active": tenant.IsActive,
"created_at": tenant.CreatedAt,
"logo_url": tenant.LogoURL,
"logo_horizontal_url": tenant.LogoHorizontalURL,
"primary_color": tenant.PrimaryColor,
"secondary_color": tenant.SecondaryColor,
}
// Buscar subscription e soluções
var planName sql.NullString
var planID string
query := `
SELECT
s.plan_id,
p.name as plan_name
FROM agency_subscriptions s
JOIN plans p ON s.plan_id = p.id
WHERE s.agency_id = $1 AND s.status = 'active'
LIMIT 1
`
err = s.db.QueryRow(query, tenant.ID).Scan(&planID, &planName)
if err == nil && planName.Valid {
tenantData["plan_name"] = planName.String
// Buscar soluções do plano
solutionsQuery := `
SELECT sol.id, sol.name, sol.slug, sol.icon
FROM solutions sol
JOIN plan_solutions ps ON sol.id = ps.solution_id
WHERE ps.plan_id = $1
ORDER BY sol.name
`
rows, err := s.db.Query(solutionsQuery, planID)
if err == nil {
defer rows.Close()
var solutions []map[string]interface{}
for rows.Next() {
var id, name, slug string
var icon sql.NullString
if err := rows.Scan(&id, &name, &slug, &icon); err == nil {
solution := map[string]interface{}{
"id": id,
"name": name,
"slug": slug,
}
if icon.Valid {
solution["icon"] = icon.String
}
solutions = append(solutions, solution)
}
}
tenantData["solutions"] = solutions
}
}
result = append(result, tenantData)
}
return result, nil
}
// Delete removes a tenant by ID
func (s *TenantService) Delete(id uuid.UUID) error {
if err := s.tenantRepo.Delete(id); err != nil {

View File

@@ -65,9 +65,24 @@ services:
container_name: aggios-minio
restart: unless-stopped
command: server /data --console-address ":9001"
labels:
- "traefik.enable=true"
# Router para acesso aos arquivos (API S3)
- "traefik.http.routers.minio.rule=Host(`files.aggios.local`) || Host(`files.localhost`)"
- "traefik.http.routers.minio.entrypoints=web"
- "traefik.http.routers.minio.priority=100" # Prioridade alta para evitar captura pelo wildcard
- "traefik.http.services.minio.loadbalancer.server.port=9000"
- "traefik.http.services.minio.loadbalancer.passhostheader=true"
# Router para o Console do MinIO
- "traefik.http.routers.minio-console.rule=Host(`minio.aggios.local`) || Host(`minio.localhost`)"
- "traefik.http.routers.minio-console.entrypoints=web"
- "traefik.http.routers.minio-console.priority=100"
- "traefik.http.services.minio-console.loadbalancer.server.port=9001"
environment:
MINIO_ROOT_USER: minioadmin
MINIO_ROOT_PASSWORD: ${MINIO_PASSWORD:-M1n10_S3cur3_P@ss_2025!}
MINIO_BROWSER_REDIRECT_URL: http://minio.localhost
MINIO_SERVER_URL: http://files.localhost
volumes:
- minio_data:/data
ports:
@@ -89,12 +104,15 @@ services:
dockerfile: Dockerfile
container_name: aggios-backend
restart: unless-stopped
ports:
- "8085:8080"
labels:
- "traefik.enable=true"
- "traefik.http.routers.backend.rule=Host(`api.aggios.local`) || Host(`api.localhost`)"
- "traefik.http.routers.backend.entrypoints=web"
- "traefik.http.services.backend.loadbalancer.server.port=8080"
environment:
TZ: America/Sao_Paulo
SERVER_HOST: 0.0.0.0
SERVER_PORT: 8080
JWT_SECRET: ${JWT_SECRET:-Th1s_1s_A_V3ry_S3cur3_JWT_S3cr3t_K3y_2025_Ch@ng3_In_Pr0d!}
@@ -107,8 +125,11 @@ services:
REDIS_PORT: 6379
REDIS_PASSWORD: ${REDIS_PASSWORD:-R3d1s_S3cur3_P@ss_2025!}
MINIO_ENDPOINT: minio:9000
MINIO_PUBLIC_URL: http://files.localhost
MINIO_ROOT_USER: minioadmin
MINIO_ROOT_PASSWORD: ${MINIO_PASSWORD:-M1n10_S3cur3_P@ss_2025!}
volumes:
- ./backups:/backups
depends_on:
postgres:
condition: service_healthy
@@ -178,6 +199,7 @@ services:
- "traefik.enable=true"
- "traefik.http.routers.agency.rule=Host(`agency.aggios.local`) || Host(`agency.localhost`) || HostRegexp(`^.+\\.localhost$`)"
- "traefik.http.routers.agency.entrypoints=web"
- "traefik.http.routers.agency.priority=1" # Prioridade baixa para não conflitar com files/minio
environment:
- NODE_ENV=production
- NEXT_PUBLIC_API_URL=http://api.localhost

186
docs/backup-system.md Normal file
View File

@@ -0,0 +1,186 @@
# 📦 Sistema de Backup & Restore - Aggios
## 🎯 Funcionalidades Implementadas
### Interface Web (Superadmin)
**URL:** `http://dash.localhost/superadmin/backup`
Disponível apenas para usuários com role `superadmin`.
#### Recursos:
1. **Criar Backup**
- Botão para criar novo backup instantâneo
- Mostra nome do arquivo e tamanho
- Mantém automaticamente apenas os últimos 10 backups
2. **Listar Backups**
- Exibe todos os backups disponíveis
- Informações: nome, data, tamanho
- Seleção visual do backup ativo
3. **Restaurar Backup**
- Seleção de backup na lista
- Confirmação de segurança (alerta de sobrescrita)
- Recarrega a página após restauração
4. **Download de Backup**
- Botão de download em cada backup
- Download direto do arquivo .sql
### API Endpoints
#### 1. Listar Backups
```
GET /api/superadmin/backups
Authorization: Bearer {token}
```
**Resposta:**
```json
{
"backups": [
{
"filename": "aggios_backup_2025-12-13_20-23-08.sql",
"size": "20.49 KB",
"date": "13/12/2025 20:23:08",
"timestamp": "2025-12-13_20-23-08"
}
]
}
```
#### 2. Criar Backup
```
POST /api/superadmin/backup/create
Authorization: Bearer {token}
```
**Resposta:**
```json
{
"message": "Backup created successfully",
"filename": "aggios_backup_2025-12-13_20-30-15.sql",
"size": "20.52 KB"
}
```
#### 3. Restaurar Backup
```
POST /api/superadmin/backup/restore
Authorization: Bearer {token}
Content-Type: application/json
{
"filename": "aggios_backup_2025-12-13_20-23-08.sql"
}
```
**Resposta:**
```json
{
"message": "Backup restored successfully"
}
```
#### 4. Download de Backup
```
GET /api/superadmin/backup/download/{filename}
Authorization: Bearer {token}
```
**Resposta:** Arquivo .sql para download
## 📂 Estrutura de Arquivos
```
backups/
├── aggios_backup_2025-12-13_19-56-18.sql
├── aggios_backup_2025-12-13_20-12-49.sql
├── aggios_backup_2025-12-13_20-17-59.sql
└── aggios_backup_2025-12-13_20-23-08.sql (mais recente)
```
## ⚙️ Scripts PowerShell (ainda funcionam!)
### Backup Manual
```powershell
cd g:\Projetos\aggios-app\scripts
.\backup-db.ps1
```
### Restaurar Último Backup
```powershell
cd g:\Projetos\aggios-app\scripts
.\restore-db.ps1
```
## 🔒 Segurança
1. ✅ Apenas superadmins podem acessar
2. ✅ Validação de arquivos (apenas .sql na pasta backups/)
3. ✅ Proteção contra path traversal
4. ✅ Autenticação JWT obrigatória
5. ✅ Confirmação dupla antes de restaurar
## ⚠️ Avisos Importantes
1. **Backup Automático:**
- Ainda não configurado
- Por enquanto, fazer backups manuais antes de `docker-compose down -v`
2. **Limite de Backups:**
- Sistema mantém apenas os **últimos 10 backups**
- Backups antigos são deletados automaticamente
3. **Restauração:**
- ⚠️ **SOBRESCREVE TODOS OS DADOS ATUAIS**
- Sempre peça confirmação dupla
- Cria um backup automático antes? (implementar depois)
## 🚀 Como Usar
1. **Acesse o Superadmin:**
- Login: admin@aggios.app
- Senha: Ag@}O%}Z;if)97o*JOgNMbP2025!
2. **No Menu Lateral:**
- Clique em "Backup & Restore" (ícone de servidor)
3. **Criar Backup:**
- Clique em "Criar Novo Backup"
- Aguarde confirmação
4. **Restaurar:**
- Selecione o backup desejado na lista
- Clique em "Restaurar Backup"
- Confirme o alerta
- Aguarde reload da página
## 🐛 Troubleshooting
### Erro ao criar backup
```bash
# Verificar se o container está rodando
docker ps | grep aggios-postgres
# Verificar logs
docker logs aggios-backend --tail 50
```
### Erro ao restaurar
```bash
# Verificar permissões
ls -la g:\Projetos\aggios-app\backups\
# Testar manualmente
docker exec -i aggios-postgres psql -U aggios aggios_db < backup.sql
```
## 📝 TODO Futuro
- [ ] Backup automático agendado (diário)
- [ ] Backup antes de restaurar (safety)
- [ ] Upload de backup externo
- [ ] Exportar/importar apenas tabelas específicas
- [ ] Histórico de restaurações
- [ ] Notificações por email

View File

@@ -0,0 +1,181 @@
'use client';
import { DashboardLayout } from '@/components/layout/DashboardLayout';
import { AgencyBranding } from '@/components/layout/AgencyBranding';
import AuthGuard from '@/components/auth/AuthGuard';
import { useState, useEffect } from 'react';
import {
HomeIcon,
RocketLaunchIcon,
ChartBarIcon,
BriefcaseIcon,
LifebuoyIcon,
CreditCardIcon,
DocumentTextIcon,
FolderIcon,
ShareIcon,
} from '@heroicons/react/24/outline';
const AGENCY_MENU_ITEMS = [
{ id: 'dashboard', label: 'Visão Geral', href: '/dashboard', icon: HomeIcon },
{
id: 'crm',
label: 'CRM',
href: '/crm',
icon: RocketLaunchIcon,
subItems: [
{ label: 'Dashboard', href: '/crm' },
{ label: 'Clientes', href: '/crm/clientes' },
{ label: 'Funis', href: '/crm/funis' },
{ label: 'Negociações', href: '/crm/negociacoes' },
]
},
{
id: 'erp',
label: 'ERP',
href: '/erp',
icon: ChartBarIcon,
subItems: [
{ label: 'Dashboard', href: '/erp' },
{ label: 'Fluxo de Caixa', href: '/erp/fluxo-caixa' },
{ label: 'Contas a Pagar', href: '/erp/contas-pagar' },
{ label: 'Contas a Receber', href: '/erp/contas-receber' },
]
},
{
id: 'projetos',
label: 'Projetos',
href: '/projetos',
icon: BriefcaseIcon,
subItems: [
{ label: 'Dashboard', href: '/projetos' },
{ label: 'Meus Projetos', href: '/projetos/lista' },
{ label: 'Tarefas', href: '/projetos/tarefas' },
{ label: 'Cronograma', href: '/projetos/cronograma' },
]
},
{
id: 'helpdesk',
label: 'Helpdesk',
href: '/helpdesk',
icon: LifebuoyIcon,
subItems: [
{ label: 'Dashboard', href: '/helpdesk' },
{ label: 'Chamados', href: '/helpdesk/chamados' },
{ label: 'Base de Conhecimento', href: '/helpdesk/kb' },
]
},
{
id: 'pagamentos',
label: 'Pagamentos',
href: '/pagamentos',
icon: CreditCardIcon,
subItems: [
{ label: 'Dashboard', href: '/pagamentos' },
{ label: 'Cobranças', href: '/pagamentos/cobrancas' },
{ label: 'Assinaturas', href: '/pagamentos/assinaturas' },
]
},
{
id: 'contratos',
label: 'Contratos',
href: '/contratos',
icon: DocumentTextIcon,
subItems: [
{ label: 'Dashboard', href: '/contratos' },
{ label: 'Ativos', href: '/contratos/ativos' },
{ label: 'Modelos', href: '/contratos/modelos' },
]
},
{
id: 'documentos',
label: 'Documentos',
href: '/documentos',
icon: FolderIcon,
subItems: [
{ label: 'Meus Arquivos', href: '/documentos' },
{ label: 'Compartilhados', href: '/documentos/compartilhados' },
{ label: 'Lixeira', href: '/documentos/lixeira' },
]
},
{
id: 'social',
label: 'Redes Sociais',
href: '/social',
icon: ShareIcon,
subItems: [
{ label: 'Dashboard', href: '/social' },
{ label: 'Agendamento', href: '/social/agendamento' },
{ label: 'Relatórios', href: '/social/relatorios' },
]
},
];
interface AgencyLayoutClientProps {
children: React.ReactNode;
colors?: {
primary: string;
secondary: string;
} | null;
}
export function AgencyLayoutClient({ children, colors }: AgencyLayoutClientProps) {
const [filteredMenuItems, setFilteredMenuItems] = useState(AGENCY_MENU_ITEMS);
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchTenantSolutions = async () => {
try {
console.log('🔍 Buscando soluções do tenant...');
const response = await fetch('/api/tenant/solutions', {
headers: {
'Authorization': `Bearer ${localStorage.getItem('token')}`,
},
});
console.log('📡 Response status:', response.status);
if (response.ok) {
const data = await response.json();
console.log('📦 Dados recebidos:', data);
const solutions = data.solutions || [];
console.log('✅ Soluções:', solutions);
// Mapear slugs de solutions para IDs de menu
const solutionSlugs = solutions.map((s: any) => s.slug.toLowerCase());
console.log('🏷️ Slugs das soluções:', solutionSlugs);
// Sempre mostrar dashboard + soluções disponíveis
const filtered = AGENCY_MENU_ITEMS.filter(item => {
if (item.id === 'dashboard') return true;
return solutionSlugs.includes(item.id);
});
console.log('📋 Menu filtrado:', filtered.map(i => i.id));
setFilteredMenuItems(filtered);
} else {
console.error('❌ Erro na resposta:', response.status);
// Em caso de erro, mostrar todos (fallback)
setFilteredMenuItems(AGENCY_MENU_ITEMS);
}
} catch (error) {
console.error('❌ Error fetching solutions:', error);
// Em caso de erro, mostrar todos (fallback)
setFilteredMenuItems(AGENCY_MENU_ITEMS);
} finally {
setLoading(false);
}
};
fetchTenantSolutions();
}, []);
return (
<AuthGuard>
<AgencyBranding colors={colors} />
<DashboardLayout menuItems={loading ? [AGENCY_MENU_ITEMS[0]] : filteredMenuItems}>
{children}
</DashboardLayout>
</AuthGuard>
);
}

View File

@@ -1,26 +0,0 @@
"use client";
export default function ClientesPage() {
return (
<div className="p-6">
<div className="mb-6">
<h1 className="text-2xl font-bold text-gray-900 dark:text-white mb-2">Clientes</h1>
<p className="text-gray-600 dark:text-gray-400">Gerencie sua carteira de clientes</p>
</div>
<div className="bg-white dark:bg-gray-800 rounded-lg p-12 border border-gray-200 dark:border-gray-700 text-center">
<div className="max-w-md mx-auto">
<div className="w-24 h-24 bg-blue-100 dark:bg-blue-900/30 rounded-full flex items-center justify-center mx-auto mb-6">
<i className="ri-user-line text-5xl text-blue-600 dark:text-blue-400"></i>
</div>
<h2 className="text-2xl font-bold text-gray-900 dark:text-white mb-3">
Módulo CRM em Desenvolvimento
</h2>
<p className="text-gray-600 dark:text-gray-400">
Em breve você poderá gerenciar seus clientes com recursos avançados de CRM.
</p>
</div>
</div>
</div>
);
}

View File

@@ -2,7 +2,7 @@
import { useState, useEffect } from 'react';
import { Tab } from '@headlessui/react';
import { Button, Dialog } from '@/components/ui';
import { Button, Dialog, Input } from '@/components/ui';
import { Toaster, toast } from 'react-hot-toast';
import {
BuildingOfficeIcon,
@@ -44,6 +44,7 @@ export default function ConfiguracoesPage() {
const [showSupportDialog, setShowSupportDialog] = useState(false);
const [supportMessage, setSupportMessage] = useState('Para alterar estes dados, contate o suporte.');
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [loadingCep, setLoadingCep] = useState(false);
const [uploadingLogo, setUploadingLogo] = useState(false);
const [logoPreview, setLogoPreview] = useState<string | null>(null);
@@ -70,8 +71,32 @@ export default function ConfiguracoesPage() {
teamSize: '',
logoUrl: '',
logoHorizontalUrl: '',
primaryColor: '#ff3a05',
secondaryColor: '#ff0080',
});
// Live Preview da Cor Primária
useEffect(() => {
if (agencyData.primaryColor) {
const root = document.documentElement;
const hexToRgb = (hex: string) => {
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? `${parseInt(result[1], 16)} ${parseInt(result[2], 16)} ${parseInt(result[3], 16)}` : null;
};
const primaryRgb = hexToRgb(agencyData.primaryColor);
if (primaryRgb) {
root.style.setProperty('--brand-rgb', primaryRgb);
root.style.setProperty('--brand-strong-rgb', primaryRgb);
root.style.setProperty('--brand-hover-rgb', primaryRgb);
}
root.style.setProperty('--brand-color', agencyData.primaryColor);
root.style.setProperty('--gradient', `linear-gradient(135deg, ${agencyData.primaryColor}, ${agencyData.primaryColor})`);
}
}, [agencyData.primaryColor]);
// Dados para alteração de senha
const [passwordData, setPasswordData] = useState({
currentPassword: '',
@@ -102,9 +127,6 @@ export default function ConfiguracoesPage() {
if (response.ok) {
const data = await response.json();
console.log('DEBUG: API response data:', data);
console.log('DEBUG: logo_url:', data.logo_url);
console.log('DEBUG: logo_horizontal_url:', data.logo_horizontal_url);
const parsedAddress = parseAddressParts(data.address || '');
setAgencyData({
@@ -125,19 +147,26 @@ export default function ConfiguracoesPage() {
description: data.description || '',
industry: data.industry || '',
teamSize: data.team_size || '',
logoUrl: data.logo_url || '',
logoHorizontalUrl: data.logo_horizontal_url || '',
logoUrl: data.logo_url || localStorage.getItem('agency-logo-url') || '',
logoHorizontalUrl: data.logo_horizontal_url || localStorage.getItem('agency-logo-horizontal-url') || '',
primaryColor: data.primary_color || '#ff3a05',
secondaryColor: data.secondary_color || '#ff0080',
});
// Set logo previews
console.log('DEBUG: Setting previews...');
if (data.logo_url) {
console.log('DEBUG: Setting logoPreview to:', data.logo_url);
setLogoPreview(data.logo_url);
// Set logo previews - usar localStorage como fallback se API não retornar
const cachedLogo = localStorage.getItem('agency-logo-url');
const cachedHorizontal = localStorage.getItem('agency-logo-horizontal-url');
const finalLogoUrl = data.logo_url || cachedLogo;
const finalHorizontalUrl = data.logo_horizontal_url || cachedHorizontal;
if (finalLogoUrl) {
setLogoPreview(finalLogoUrl);
localStorage.setItem('agency-logo-url', finalLogoUrl);
}
if (data.logo_horizontal_url) {
console.log('DEBUG: Setting logoHorizontalPreview to:', data.logo_horizontal_url);
setLogoHorizontalPreview(data.logo_horizontal_url);
if (finalHorizontalUrl) {
setLogoHorizontalPreview(finalHorizontalUrl);
localStorage.setItem('agency-logo-horizontal-url', finalHorizontalUrl);
}
} else {
console.error('Erro ao buscar dados:', response.status);
@@ -166,6 +195,8 @@ export default function ConfiguracoesPage() {
teamSize: data.formData?.teamSize || '',
logoUrl: '',
logoHorizontalUrl: '',
primaryColor: '#ff3a05',
secondaryColor: '#ff0080',
});
}
}
@@ -223,11 +254,18 @@ export default function ConfiguracoesPage() {
if (type === 'logo') {
setAgencyData(prev => ({ ...prev, logoUrl }));
setLogoPreview(logoUrl);
// Salvar no localStorage para uso do favicon
localStorage.setItem('agency-logo-url', logoUrl);
} else {
setAgencyData(prev => ({ ...prev, logoHorizontalUrl: logoUrl }));
setLogoHorizontalPreview(logoUrl);
}
// Disparar evento para atualizar branding em tempo real
if (typeof window !== 'undefined') {
window.dispatchEvent(new Event('branding-update'));
}
toast.success('Logo enviado com sucesso!');
} else {
const errorData = await response.json().catch(() => ({}));
@@ -319,11 +357,13 @@ export default function ConfiguracoesPage() {
};
const handleSaveAgency = async () => {
setSaving(true);
try {
const token = localStorage.getItem('token');
if (!token) {
setSuccessMessage('Você precisa estar autenticado.');
setShowSuccessDialog(true);
setSaving(false);
return;
}
@@ -354,17 +394,47 @@ export default function ConfiguracoesPage() {
description: agencyData.description,
industry: agencyData.industry,
team_size: agencyData.teamSize,
primary_color: agencyData.primaryColor,
secondary_color: agencyData.secondaryColor,
}),
});
if (response.ok) {
setSuccessMessage('Dados da agência salvos com sucesso!');
// Atualiza localStorage imediatamente para persistência instantânea
localStorage.setItem('agency-primary-color', agencyData.primaryColor);
localStorage.setItem('agency-secondary-color', agencyData.secondaryColor);
// Preservar logos no localStorage (não sobrescrever com valores vazios)
// Logos são gerenciados separadamente via upload
const currentLogoCache = localStorage.getItem('agency-logo-url');
const currentHorizontalCache = localStorage.getItem('agency-logo-horizontal-url');
// Só atualizar se temos valores novos no estado
if (agencyData.logoUrl) {
localStorage.setItem('agency-logo-url', agencyData.logoUrl);
} else if (!currentLogoCache && logoPreview) {
// Se não tem cache mas tem preview, usar o preview
localStorage.setItem('agency-logo-url', logoPreview);
}
if (agencyData.logoHorizontalUrl) {
localStorage.setItem('agency-logo-horizontal-url', agencyData.logoHorizontalUrl);
} else if (!currentHorizontalCache && logoHorizontalPreview) {
localStorage.setItem('agency-logo-horizontal-url', logoHorizontalPreview);
}
// Disparar evento para atualizar o tema em tempo real
window.dispatchEvent(new Event('branding-update'));
} else {
setSuccessMessage('Erro ao salvar dados. Tente novamente.');
}
} catch (error) {
console.error('Erro ao salvar:', error);
setSuccessMessage('Erro ao salvar dados. Verifique sua conexão.');
} finally {
setSaving(false);
}
setShowSuccessDialog(true);
};
@@ -437,7 +507,7 @@ export default function ConfiguracoesPage() {
{/* Loading State */}
{loading ? (
<div className="flex items-center justify-center py-12">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-gray-900 dark:border-gray-100"></div>
<div className="animate-spin rounded-full h-12 w-12 border-b border-gray-900 dark:border-gray-100"></div>
</div>
) : (
<>
@@ -475,52 +545,40 @@ export default function ConfiguracoesPage() {
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Nome da Agência
</label>
<input
type="text"
<Input
label="Nome da Agência"
value={agencyData.name}
onChange={(e) => setAgencyData({ ...agencyData, name: e.target.value })}
className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-900 text-gray-900 dark:text-white focus:ring-2 focus:ring-gray-400 dark:focus:ring-gray-600 focus:outline-none"
placeholder="Ex: Minha Agência"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Razão Social
</label>
<input
type="text"
<Input
label="Razão Social"
value={agencyData.razaoSocial}
onChange={(e) => setAgencyData({ ...agencyData, razaoSocial: e.target.value })}
className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-900 text-gray-900 dark:text-white focus:ring-2 focus:ring-gray-400 dark:focus:ring-gray-600 focus:outline-none"
placeholder="Razão Social Ltda"
/>
</div>
<div>
<label className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-2 flex items-center justify-between">
<span>CNPJ</span>
<span className="text-xs text-gray-500">Alteração via suporte</span>
</label>
<input
type="text"
<Input
label="CNPJ"
value={agencyData.cnpj}
readOnly
onClick={() => {
setSupportMessage('Para alterar CNPJ, contate o suporte.');
setShowSupportDialog(true);
}}
className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-gray-50 dark:bg-gray-800 text-gray-900 dark:text-white focus:outline-none cursor-pointer"
className="cursor-pointer bg-gray-50 dark:bg-gray-800"
helperText="Alteração via suporte"
/>
</div>
<div>
<label className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-2 flex items-center justify-between">
<span>E-mail (acesso)</span>
<span className="text-xs text-gray-500">Alteração via suporte</span>
</label>
<input
<Input
label="E-mail (acesso)"
type="email"
value={agencyData.email}
readOnly
@@ -528,55 +586,47 @@ export default function ConfiguracoesPage() {
setSupportMessage('Para alterar o e-mail de acesso, contate o suporte.');
setShowSupportDialog(true);
}}
className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-gray-50 dark:bg-gray-800 text-gray-900 dark:text-white focus:outline-none cursor-pointer"
className="cursor-pointer bg-gray-50 dark:bg-gray-800"
helperText="Alteração via suporte"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Telefone / WhatsApp
</label>
<input
<Input
label="Telefone / WhatsApp"
type="tel"
value={agencyData.phone}
onChange={(e) => setAgencyData({ ...agencyData, phone: e.target.value })}
className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-900 text-gray-900 dark:text-white focus:ring-2 focus:ring-gray-400 dark:focus:ring-gray-600 focus:outline-none"
placeholder="(00) 00000-0000"
/>
</div>
<div className="md:col-span-2">
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Website
</label>
<input
<Input
label="Website"
type="url"
value={agencyData.website}
onChange={(e) => setAgencyData({ ...agencyData, website: e.target.value })}
className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-900 text-gray-900 dark:text-white focus:ring-2 focus:ring-gray-400 dark:focus:ring-gray-600 focus:outline-none"
placeholder="https://www.suaagencia.com.br"
leftIcon="ri-global-line"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Segmento / Indústria
</label>
<input
type="text"
<Input
label="Segmento / Indústria"
value={agencyData.industry}
onChange={(e) => setAgencyData({ ...agencyData, industry: e.target.value })}
className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-900 text-gray-900 dark:text-white focus:ring-2 focus:ring-gray-400 dark:focus:ring-gray-600 focus:outline-none"
placeholder="Ex: Marketing Digital"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Tamanho da Equipe
</label>
<input
type="text"
<Input
label="Tamanho da Equipe"
value={agencyData.teamSize}
onChange={(e) => setAgencyData({ ...agencyData, teamSize: e.target.value })}
className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-900 text-gray-900 dark:text-white focus:ring-2 focus:ring-gray-400 dark:focus:ring-gray-600 focus:outline-none"
placeholder="Ex: 10-50 funcionários"
/>
</div>
</div>
@@ -591,11 +641,8 @@ export default function ConfiguracoesPage() {
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
CEP
</label>
<input
type="text"
<Input
label="CEP"
value={agencyData.zip}
onChange={(e) => {
const formatted = formatCep(e.target.value);
@@ -617,85 +664,74 @@ export default function ConfiguracoesPage() {
}));
}
}}
className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-900 text-gray-900 dark:text-white focus:ring-2 focus:ring-gray-400 dark:focus:ring-gray-600 focus:outline-none"
placeholder="00000-000"
rightIcon={loadingCep ? "ri-loader-4-line animate-spin" : undefined}
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Estado
</label>
<input
type="text"
<Input
label="Estado"
value={agencyData.state}
readOnly
className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-gray-50 dark:bg-gray-800 text-gray-900 dark:text-white focus:outline-none cursor-not-allowed"
className="bg-gray-50 dark:bg-gray-800 cursor-not-allowed"
/>
</div> <div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Cidade
</label>
<input
type="text"
</div>
<div>
<Input
label="Cidade"
value={agencyData.city}
readOnly
className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-gray-50 dark:bg-gray-800 text-gray-900 dark:text-white focus:outline-none cursor-not-allowed"
className="bg-gray-50 dark:bg-gray-800 cursor-not-allowed"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Bairro
</label>
<input
type="text"
<Input
label="Bairro"
value={agencyData.neighborhood}
readOnly
className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-gray-50 dark:bg-gray-800 text-gray-900 dark:text-white focus:outline-none cursor-not-allowed"
className="bg-gray-50 dark:bg-gray-800 cursor-not-allowed"
/>
</div> <div className="md:col-span-2">
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Rua/Avenida
</label>
<input
type="text"
</div>
<div className="md:col-span-2">
<Input
label="Rua/Avenida"
value={agencyData.street}
readOnly
className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-gray-50 dark:bg-gray-800 text-gray-900 dark:text-white focus:outline-none cursor-not-allowed"
/>
</div> <div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Número
</label>
<input
type="text"
value={agencyData.number}
onChange={(e) => setAgencyData({ ...agencyData, number: e.target.value })}
className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-900 text-gray-900 dark:text-white focus:ring-2 focus:ring-gray-400 dark:focus:ring-gray-600 focus:outline-none"
className="bg-gray-50 dark:bg-gray-800 cursor-not-allowed"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Complemento (opcional)
</label>
<input
type="text"
<Input
label="Número"
value={agencyData.number}
onChange={(e) => setAgencyData({ ...agencyData, number: e.target.value })}
placeholder="123"
/>
</div>
<div>
<Input
label="Complemento (opcional)"
value={agencyData.complement}
onChange={(e) => setAgencyData({ ...agencyData, complement: e.target.value })}
className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-900 text-gray-900 dark:text-white focus:ring-2 focus:ring-gray-400 dark:focus:ring-gray-600 focus:outline-none"
placeholder="Apto 101, Bloco B"
/>
</div>
</div>
<div className="mt-6 flex justify-end">
<button
<Button
onClick={handleSaveAgency}
className="px-6 py-2 rounded-lg text-white font-medium transition-all hover:scale-105"
style={{ background: 'var(--gradient-primary)' }}
variant="primary"
size="lg"
>
Salvar Alterações
</button>
</Button>
</div>
</div>
</Tab.Panel>
@@ -789,7 +825,7 @@ export default function ConfiguracoesPage() {
className="hidden"
disabled={uploadingLogo}
/>
<div className="border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-xl p-8 text-center hover:border-gray-400 dark:hover:border-gray-500 transition-colors bg-gray-50/50 dark:bg-gray-900/50">
<div className="border-2 border-dashed border-gray-200 dark:border-gray-600 rounded-xl p-8 text-center hover:border-gray-400 dark:hover:border-gray-500 transition-colors bg-gray-50/50 dark:bg-gray-900/50">
<div className="flex flex-col items-center">
<div className="w-16 h-16 rounded-full bg-gray-100 dark:bg-gray-800 flex items-center justify-center mb-4">
<PhotoIcon className="w-8 h-8 text-gray-400 dark:text-gray-500" />
@@ -897,7 +933,7 @@ export default function ConfiguracoesPage() {
className="hidden"
disabled={uploadingLogo}
/>
<div className="border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-xl p-8 text-center hover:border-gray-400 dark:hover:border-gray-500 transition-colors bg-gray-50/50 dark:bg-gray-900/50">
<div className="border-2 border-dashed border-gray-200 dark:border-gray-600 rounded-xl p-8 text-center hover:border-gray-400 dark:hover:border-gray-500 transition-colors bg-gray-50/50 dark:bg-gray-900/50">
<div className="flex flex-col items-center">
<div className="w-16 h-16 rounded-full bg-gray-100 dark:bg-gray-800 flex items-center justify-center mb-4">
<PhotoIcon className="w-8 h-8 text-gray-400 dark:text-gray-500" />
@@ -928,6 +964,69 @@ export default function ConfiguracoesPage() {
)}
</div>
</div>
{/* Cores da Marca */}
<div className="pt-6 border-t border-gray-200 dark:border-gray-700">
<h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
Personalização de Cores
</h3>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div>
<div className="flex items-end gap-3">
<div className="relative w-[50px] h-[42px] rounded-lg overflow-hidden border border-gray-200 dark:border-gray-700 shadow-sm shrink-0 mb-[2px]">
<input
type="color"
value={agencyData.primaryColor}
onChange={(e) => setAgencyData({ ...agencyData, primaryColor: e.target.value })}
className="absolute -top-2 -left-2 w-24 h-24 cursor-pointer p-0 border-0"
/>
</div>
<div className="flex-1">
<Input
label="Cor Primária"
type="text"
value={agencyData.primaryColor}
onChange={(e) => setAgencyData({ ...agencyData, primaryColor: e.target.value })}
className="uppercase"
maxLength={7}
/>
</div>
</div>
</div>
<div>
<div className="flex items-end gap-3">
<div className="relative w-[50px] h-[42px] rounded-lg overflow-hidden border border-gray-200 dark:border-gray-700 shadow-sm shrink-0 mb-[2px]">
<input
type="color"
value={agencyData.secondaryColor}
onChange={(e) => setAgencyData({ ...agencyData, secondaryColor: e.target.value })}
className="absolute -top-2 -left-2 w-24 h-24 cursor-pointer p-0 border-0"
/>
</div>
<div className="flex-1">
<Input
label="Cor Secundária"
type="text"
value={agencyData.secondaryColor}
onChange={(e) => setAgencyData({ ...agencyData, secondaryColor: e.target.value })}
className="uppercase"
maxLength={7}
/>
</div>
</div>
</div>
</div>
<div className="mt-6 flex justify-end">
<Button
onClick={handleSaveAgency}
variant="primary"
isLoading={saving}
style={{ backgroundColor: agencyData.primaryColor }}
>
Salvar Cores
</Button>
</div>
</div>
</div>
{/* Info adicional */}
@@ -950,9 +1049,9 @@ export default function ConfiguracoesPage() {
<p className="text-gray-600 dark:text-gray-400 mb-4">
Em breve: gerenciamento completo de usuários e permissões
</p>
<button className="px-6 py-2 bg-gray-900 dark:bg-gray-100 text-white dark:text-gray-900 rounded-lg font-medium hover:scale-105 transition-all">
<Button variant="primary">
Convidar Membro
</button>
</Button>
</div>
</Tab.Panel>
@@ -970,52 +1069,42 @@ export default function ConfiguracoesPage() {
<div className="space-y-4">
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Senha Atual
</label>
<input
<Input
label="Senha Atual"
type="password"
value={passwordData.currentPassword}
onChange={(e) => setPasswordData({ ...passwordData, currentPassword: e.target.value })}
className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-900 text-gray-900 dark:text-white focus:ring-2 focus:ring-gray-400 dark:focus:ring-gray-600 focus:outline-none"
placeholder="Digite sua senha atual"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Nova Senha
</label>
<input
<Input
label="Nova Senha"
type="password"
value={passwordData.newPassword}
onChange={(e) => setPasswordData({ ...passwordData, newPassword: e.target.value })}
className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-900 text-gray-900 dark:text-white focus:ring-2 focus:ring-gray-400 dark:focus:ring-gray-600 focus:outline-none"
placeholder="Digite a nova senha (mínimo 8 caracteres)"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Confirmar Nova Senha
</label>
<input
<Input
label="Confirmar Nova Senha"
type="password"
value={passwordData.confirmPassword}
onChange={(e) => setPasswordData({ ...passwordData, confirmPassword: e.target.value })}
className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-900 text-gray-900 dark:text-white focus:ring-2 focus:ring-gray-400 dark:focus:ring-gray-600 focus:outline-none"
placeholder="Digite a nova senha novamente"
/>
</div>
<div className="pt-4">
<button
<Button
onClick={handleChangePassword}
className="px-6 py-2 rounded-lg text-white font-medium transition-all hover:scale-105"
style={{ background: 'var(--gradient-primary)' }}
variant="primary"
>
Alterar Senha
</button>
</Button>
</div>
</div>
@@ -1071,13 +1160,12 @@ export default function ConfiguracoesPage() {
<p className="text-center py-4">{successMessage}</p>
</Dialog.Body>
<Dialog.Footer>
<button
<Button
onClick={() => setShowSuccessDialog(false)}
className="px-6 py-2 rounded-lg text-white font-medium transition-all hover:scale-105"
style={{ background: 'var(--gradient-primary)' }}
variant="primary"
>
OK
</button>
</Button>
</Dialog.Footer>
</Dialog>
@@ -1092,12 +1180,12 @@ export default function ConfiguracoesPage() {
<p className="mt-3 text-sm text-gray-500">Envie um e-mail para suporte@aggios.app ou abra um chamado para ajuste desses dados.</p>
</Dialog.Body>
<Dialog.Footer>
<button
<Button
onClick={() => setShowSupportDialog(false)}
className="px-4 py-2 bg-gray-900 dark:bg-gray-100 text-white dark:text-gray-900 rounded-lg font-medium hover:scale-105 transition-all"
variant="primary"
>
Fechar
</button>
</Button>
</Dialog.Footer>
</Dialog>
</div>

View File

@@ -0,0 +1,16 @@
'use client';
import { SolutionGuard } from '@/components/auth/SolutionGuard';
export default function ContratosPage() {
return (
<SolutionGuard requiredSolution="contratos">
<div className="p-6">
<h1 className="text-2xl font-bold text-gray-900 dark:text-white mb-4">Contratos</h1>
<div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-800 p-8 text-center">
<p className="text-gray-500">Gestão de Contratos e Assinaturas em breve</p>
</div>
</div>
</SolutionGuard>
);
}

View File

@@ -0,0 +1,548 @@
"use client";
import { Fragment, useEffect, useState } from 'react';
import { Menu, Transition } from '@headlessui/react';
import ConfirmDialog from '@/components/layout/ConfirmDialog';
import { useToast } from '@/components/layout/ToastContext';
import {
UserIcon,
TrashIcon,
PencilIcon,
EllipsisVerticalIcon,
MagnifyingGlassIcon,
PlusIcon,
XMarkIcon,
PhoneIcon,
EnvelopeIcon,
MapPinIcon,
TagIcon,
} from '@heroicons/react/24/outline';
interface Customer {
id: string;
tenant_id: string;
name: string;
email: string;
phone: string;
company: string;
position: string;
address: string;
city: string;
state: string;
zip_code: string;
country: string;
tags: string[];
notes: string;
created_at: string;
updated_at: string;
}
export default function CustomersPage() {
const toast = useToast();
const [customers, setCustomers] = useState<Customer[]>([]);
const [loading, setLoading] = useState(true);
const [isModalOpen, setIsModalOpen] = useState(false);
const [editingCustomer, setEditingCustomer] = useState<Customer | null>(null);
const [confirmOpen, setConfirmOpen] = useState(false);
const [customerToDelete, setCustomerToDelete] = useState<string | null>(null);
const [searchTerm, setSearchTerm] = useState('');
const [formData, setFormData] = useState({
name: '',
email: '',
phone: '',
company: '',
position: '',
address: '',
city: '',
state: '',
zip_code: '',
country: 'Brasil',
tags: '',
notes: '',
});
useEffect(() => {
fetchCustomers();
}, []);
const fetchCustomers = async () => {
try {
const response = await fetch('/api/crm/customers', {
headers: {
'Authorization': `Bearer ${localStorage.getItem('token')}`,
},
});
if (response.ok) {
const data = await response.json();
setCustomers(data.customers || []);
}
} catch (error) {
console.error('Error fetching customers:', error);
} finally {
setLoading(false);
}
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
const url = editingCustomer
? `/api/crm/customers/${editingCustomer.id}`
: '/api/crm/customers';
const method = editingCustomer ? 'PUT' : 'POST';
const payload = {
...formData,
tags: formData.tags.split(',').map(t => t.trim()).filter(t => t.length > 0),
};
try {
const response = await fetch(url, {
method,
headers: {
'Authorization': `Bearer ${localStorage.getItem('token')}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(payload),
});
if (response.ok) {
toast.success(
editingCustomer ? 'Cliente atualizado' : 'Cliente criado',
editingCustomer ? 'O cliente foi atualizado com sucesso.' : 'O novo cliente foi criado com sucesso.'
);
fetchCustomers();
handleCloseModal();
} else {
const error = await response.json();
toast.error('Erro', error.message || 'Não foi possível salvar o cliente.');
}
} catch (error) {
console.error('Error saving customer:', error);
toast.error('Erro', 'Ocorreu um erro ao salvar o cliente.');
}
};
const handleEdit = (customer: Customer) => {
setEditingCustomer(customer);
setFormData({
name: customer.name,
email: customer.email,
phone: customer.phone,
company: customer.company,
position: customer.position,
address: customer.address,
city: customer.city,
state: customer.state,
zip_code: customer.zip_code,
country: customer.country,
tags: customer.tags?.join(', ') || '',
notes: customer.notes,
});
setIsModalOpen(true);
};
const handleDeleteClick = (id: string) => {
setCustomerToDelete(id);
setConfirmOpen(true);
};
const handleConfirmDelete = async () => {
if (!customerToDelete) return;
try {
const response = await fetch(`/api/crm/customers/${customerToDelete}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${localStorage.getItem('token')}`,
},
});
if (response.ok) {
setCustomers(customers.filter(c => c.id !== customerToDelete));
toast.success('Cliente excluído', 'O cliente foi excluído com sucesso.');
} else {
toast.error('Erro ao excluir', 'Não foi possível excluir o cliente.');
}
} catch (error) {
console.error('Error deleting customer:', error);
toast.error('Erro ao excluir', 'Ocorreu um erro ao excluir o cliente.');
} finally {
setConfirmOpen(false);
setCustomerToDelete(null);
}
};
const handleCloseModal = () => {
setIsModalOpen(false);
setEditingCustomer(null);
setFormData({
name: '',
email: '',
phone: '',
company: '',
position: '',
address: '',
city: '',
state: '',
zip_code: '',
country: 'Brasil',
tags: '',
notes: '',
});
};
const filteredCustomers = customers.filter((customer) => {
const searchLower = searchTerm.toLowerCase();
return (
(customer.name?.toLowerCase() || '').includes(searchLower) ||
(customer.email?.toLowerCase() || '').includes(searchLower) ||
(customer.company?.toLowerCase() || '').includes(searchLower) ||
(customer.phone?.toLowerCase() || '').includes(searchLower)
);
});
return (
<div className="p-6 max-w-[1600px] mx-auto space-y-6">
{/* Header */}
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
<div>
<h1 className="text-2xl font-bold text-zinc-900 dark:text-white tracking-tight">Clientes</h1>
<p className="text-sm text-zinc-500 dark:text-zinc-400 mt-1">
Gerencie seus clientes e contatos
</p>
</div>
<button
onClick={() => setIsModalOpen(true)}
className="inline-flex items-center justify-center gap-2 px-4 py-2.5 text-sm font-medium text-white rounded-lg hover:opacity-90 transition-opacity"
style={{ background: 'var(--gradient)' }}
>
<PlusIcon className="w-4 h-4" />
Novo Cliente
</button>
</div>
{/* Search */}
<div className="relative w-full lg:w-96">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<MagnifyingGlassIcon className="h-5 w-5 text-zinc-400" aria-hidden="true" />
</div>
<input
type="text"
className="block w-full pl-10 pr-3 py-2 border border-zinc-200 dark:border-zinc-700 rounded-lg leading-5 bg-white dark:bg-zinc-900 text-zinc-900 dark:text-zinc-100 placeholder-zinc-400 focus:outline-none focus:ring-1 focus:ring-[var(--brand-color)] focus:border-[var(--brand-color)] sm:text-sm transition duration-150 ease-in-out"
placeholder="Buscar por nome, email, empresa..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
</div>
{/* Table */}
{loading ? (
<div className="flex items-center justify-center h-64 bg-white dark:bg-zinc-900 rounded-xl border border-zinc-200 dark:border-zinc-800">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[var(--brand-color)]"></div>
</div>
) : filteredCustomers.length === 0 ? (
<div className="flex flex-col items-center justify-center h-64 bg-white dark:bg-zinc-900 rounded-xl border border-zinc-200 dark:border-zinc-800 text-center p-8">
<div className="w-16 h-16 bg-zinc-50 dark:bg-zinc-800 rounded-full flex items-center justify-center mb-4">
<UserIcon className="w-8 h-8 text-zinc-400" />
</div>
<h3 className="text-lg font-medium text-zinc-900 dark:text-white mb-1">
Nenhum cliente encontrado
</h3>
<p className="text-zinc-500 dark:text-zinc-400 max-w-sm mx-auto">
{searchTerm ? 'Nenhum cliente corresponde à sua busca.' : 'Comece adicionando seu primeiro cliente.'}
</p>
</div>
) : (
<div className="bg-white dark:bg-zinc-900 rounded-xl border border-zinc-200 dark:border-zinc-800 overflow-hidden">
<div className="overflow-x-auto">
<table className="w-full">
<thead>
<tr className="bg-zinc-50/50 dark:bg-zinc-800/50 border-b border-zinc-200 dark:border-zinc-800">
<th className="px-6 py-4 text-left text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Cliente</th>
<th className="px-6 py-4 text-left text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Empresa</th>
<th className="px-6 py-4 text-left text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Contato</th>
<th className="px-6 py-4 text-left text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Tags</th>
<th className="px-6 py-4 text-right text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Ações</th>
</tr>
</thead>
<tbody className="divide-y divide-zinc-100 dark:divide-zinc-800">
{filteredCustomers.map((customer) => (
<tr key={customer.id} className="group hover:bg-zinc-50 dark:hover:bg-zinc-800/50 transition-colors">
<td className="px-6 py-4 whitespace-nowrap">
<div className="flex items-center gap-3">
<div
className="w-10 h-10 rounded-full flex items-center justify-center text-white font-bold text-sm"
style={{ background: 'var(--gradient)' }}
>
{customer.name.substring(0, 2).toUpperCase()}
</div>
<div>
<div className="text-sm font-semibold text-zinc-900 dark:text-white">
{customer.name}
</div>
{customer.position && (
<div className="text-xs text-zinc-500 dark:text-zinc-400">
{customer.position}
</div>
)}
</div>
</div>
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-zinc-700 dark:text-zinc-300">
{customer.company || '-'}
</td>
<td className="px-6 py-4 text-sm text-zinc-600 dark:text-zinc-400">
<div className="space-y-1">
{customer.email && (
<div className="flex items-center gap-2">
<EnvelopeIcon className="w-4 h-4 text-zinc-400" />
<span>{customer.email}</span>
</div>
)}
{customer.phone && (
<div className="flex items-center gap-2">
<PhoneIcon className="w-4 h-4 text-zinc-400" />
<span>{customer.phone}</span>
</div>
)}
</div>
</td>
<td className="px-6 py-4">
<div className="flex flex-wrap gap-1">
{customer.tags && customer.tags.length > 0 ? (
customer.tags.slice(0, 3).map((tag, idx) => (
<span
key={idx}
className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400"
>
{tag}
</span>
))
) : (
<span className="text-xs text-zinc-400">-</span>
)}
{customer.tags && customer.tags.length > 3 && (
<span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-zinc-100 text-zinc-600 dark:bg-zinc-800 dark:text-zinc-400">
+{customer.tags.length - 3}
</span>
)}
</div>
</td>
<td className="px-6 py-4 whitespace-nowrap text-right">
<Menu as="div" className="relative inline-block text-left">
<Menu.Button className="p-2 rounded-lg hover:bg-zinc-100 dark:hover:bg-zinc-800 text-zinc-400 hover:text-zinc-600 dark:hover:text-zinc-300 transition-colors outline-none">
<EllipsisVerticalIcon className="w-5 h-5" />
</Menu.Button>
<Menu.Items
transition
portal
anchor="bottom end"
className="w-48 origin-top-right divide-y divide-zinc-100 dark:divide-zinc-800 rounded-xl bg-white dark:bg-zinc-900 focus:outline-none z-50 border border-zinc-200 dark:border-zinc-800 [--anchor-gap:8px] transition duration-100 ease-out data-[closed]:scale-95 data-[closed]:opacity-0"
>
<div className="px-1 py-1">
<Menu.Item>
{({ active }) => (
<button
onClick={() => handleEdit(customer)}
className={`${active ? 'bg-zinc-50 dark:bg-zinc-800' : ''
} group flex w-full items-center rounded-lg px-2 py-2 text-sm text-zinc-700 dark:text-zinc-300`}
>
<PencilIcon className="mr-2 h-4 w-4 text-zinc-400" />
Editar
</button>
)}
</Menu.Item>
</div>
<div className="px-1 py-1">
<Menu.Item>
{({ active }) => (
<button
onClick={() => handleDeleteClick(customer.id)}
className={`${active ? 'bg-red-50 dark:bg-red-900/20' : ''
} group flex w-full items-center rounded-lg px-2 py-2 text-sm text-red-600 dark:text-red-400`}
>
<TrashIcon className="mr-2 h-4 w-4" />
Excluir
</button>
)}
</Menu.Item>
</div>
</Menu.Items>
</Menu>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
)}
{/* Modal */}
{isModalOpen && (
<div className="fixed inset-0 z-50 overflow-y-auto">
<div className="flex min-h-full items-end justify-center p-4 text-center sm:items-center sm:p-0">
<div className="fixed inset-0 bg-zinc-900/40 backdrop-blur-sm transition-opacity" onClick={handleCloseModal}></div>
<div className="relative transform overflow-hidden rounded-2xl bg-white dark:bg-zinc-900 text-left shadow-xl transition-all sm:my-8 sm:w-full sm:max-w-2xl border border-zinc-200 dark:border-zinc-800">
<div className="absolute right-0 top-0 pr-6 pt-6">
<button
type="button"
className="rounded-lg p-1.5 text-zinc-400 hover:text-zinc-600 dark:hover:text-zinc-300 hover:bg-zinc-100 dark:hover:bg-zinc-800 transition-colors"
onClick={handleCloseModal}
>
<XMarkIcon className="h-5 w-5" />
</button>
</div>
<form onSubmit={handleSubmit} className="p-6 sm:p-8">
<div className="flex items-start gap-4 mb-6">
<div
className="flex h-12 w-12 flex-shrink-0 items-center justify-center rounded-xl shadow-lg"
style={{ background: 'var(--gradient)' }}
>
<UserIcon className="h-6 w-6 text-white" />
</div>
<div>
<h3 className="text-xl font-bold text-zinc-900 dark:text-white">
{editingCustomer ? 'Editar Cliente' : 'Novo Cliente'}
</h3>
<p className="mt-1 text-sm text-zinc-500 dark:text-zinc-400">
{editingCustomer ? 'Atualize as informações do cliente.' : 'Adicione um novo cliente ao seu CRM.'}
</p>
</div>
</div>
<div className="space-y-4">
<div className="grid grid-cols-2 gap-4">
<div className="col-span-2">
<label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
Nome Completo *
</label>
<input
type="text"
value={formData.name}
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
required
className="w-full px-3 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-[var(--brand-color)] focus:border-transparent transition-all"
/>
</div>
<div>
<label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
Email
</label>
<input
type="email"
value={formData.email}
onChange={(e) => setFormData({ ...formData, email: e.target.value })}
className="w-full px-3 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-[var(--brand-color)] focus:border-transparent transition-all"
/>
</div>
<div>
<label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
Telefone
</label>
<input
type="tel"
value={formData.phone}
onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
className="w-full px-3 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-[var(--brand-color)] focus:border-transparent transition-all"
/>
</div>
<div>
<label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
Empresa
</label>
<input
type="text"
value={formData.company}
onChange={(e) => setFormData({ ...formData, company: e.target.value })}
className="w-full px-3 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-[var(--brand-color)] focus:border-transparent transition-all"
/>
</div>
<div>
<label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
Cargo
</label>
<input
type="text"
value={formData.position}
onChange={(e) => setFormData({ ...formData, position: e.target.value })}
className="w-full px-3 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-[var(--brand-color)] focus:border-transparent transition-all"
/>
</div>
<div className="col-span-2">
<label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
Tags <span className="text-xs font-normal text-zinc-500">(separadas por vírgula)</span>
</label>
<input
type="text"
value={formData.tags}
onChange={(e) => setFormData({ ...formData, tags: e.target.value })}
placeholder="vip, premium, lead-quente"
className="w-full px-3 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-[var(--brand-color)] focus:border-transparent transition-all"
/>
</div>
<div className="col-span-2">
<label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
Observações
</label>
<textarea
value={formData.notes}
onChange={(e) => setFormData({ ...formData, notes: e.target.value })}
rows={3}
className="w-full px-3 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-[var(--brand-color)] focus:border-transparent resize-none transition-all"
/>
</div>
</div>
</div>
<div className="mt-8 pt-6 border-t border-zinc-200 dark:border-zinc-700 flex gap-3">
<button
type="button"
onClick={handleCloseModal}
className="flex-1 px-4 py-2.5 border border-zinc-200 dark:border-zinc-700 text-zinc-700 dark:text-zinc-300 font-medium rounded-lg hover:bg-zinc-50 dark:hover:bg-zinc-800 transition-colors"
>
Cancelar
</button>
<button
type="submit"
className="flex-1 px-4 py-2.5 text-white font-medium rounded-lg transition-all shadow-lg hover:shadow-xl"
style={{ background: 'var(--gradient)' }}
>
{editingCustomer ? 'Atualizar' : 'Criar Cliente'}
</button>
</div>
</form>
</div>
</div>
</div>
)}
<ConfirmDialog
isOpen={confirmOpen}
onClose={() => {
setConfirmOpen(false);
setCustomerToDelete(null);
}}
onConfirm={handleConfirmDelete}
title="Excluir Cliente"
message="Tem certeza que deseja excluir este cliente? Esta ação não pode ser desfeita."
confirmText="Excluir"
cancelText="Cancelar"
variant="danger"
/>
</div>
);
}

View File

@@ -0,0 +1,31 @@
"use client";
import { FunnelIcon } from '@heroicons/react/24/outline';
export default function FunisPage() {
return (
<div className="p-6 h-full flex items-center justify-center">
<div className="text-center max-w-md">
<div className="mx-auto mb-6 flex h-20 w-20 items-center justify-center rounded-full bg-gradient-to-br from-blue-500 to-purple-600">
<FunnelIcon className="h-10 w-10 text-white" />
</div>
<h1 className="text-2xl font-bold text-gray-900 dark:text-white mb-2">
Funis de Vendas
</h1>
<p className="text-gray-600 dark:text-gray-400 mb-4">
Esta funcionalidade está em desenvolvimento
</p>
<div className="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800">
<div className="flex gap-1">
<span className="animate-bounce inline-block h-2 w-2 rounded-full bg-blue-600" style={{ animationDelay: '0ms' }}></span>
<span className="animate-bounce inline-block h-2 w-2 rounded-full bg-blue-600" style={{ animationDelay: '150ms' }}></span>
<span className="animate-bounce inline-block h-2 w-2 rounded-full bg-blue-600" style={{ animationDelay: '300ms' }}></span>
</div>
<span className="text-sm font-medium text-blue-600 dark:text-blue-400">
Em breve
</span>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,432 @@
"use client";
import { Fragment, useEffect, useState } from 'react';
import { Menu, Transition } from '@headlessui/react';
import ConfirmDialog from '@/components/layout/ConfirmDialog';
import { useToast } from '@/components/layout/ToastContext';
import {
ListBulletIcon,
TrashIcon,
PencilIcon,
EllipsisVerticalIcon,
MagnifyingGlassIcon,
PlusIcon,
XMarkIcon,
UserGroupIcon,
} from '@heroicons/react/24/outline';
interface List {
id: string;
tenant_id: string;
name: string;
description: string;
color: string;
customer_count: number;
created_at: string;
updated_at: string;
}
const COLORS = [
{ name: 'Azul', value: '#3B82F6' },
{ name: 'Verde', value: '#10B981' },
{ name: 'Roxo', value: '#8B5CF6' },
{ name: 'Rosa', value: '#EC4899' },
{ name: 'Laranja', value: '#F97316' },
{ name: 'Amarelo', value: '#EAB308' },
{ name: 'Vermelho', value: '#EF4444' },
{ name: 'Cinza', value: '#6B7280' },
];
export default function ListsPage() {
const toast = useToast();
const [lists, setLists] = useState<List[]>([]);
const [loading, setLoading] = useState(true);
const [isModalOpen, setIsModalOpen] = useState(false);
const [editingList, setEditingList] = useState<List | null>(null);
const [confirmOpen, setConfirmOpen] = useState(false);
const [listToDelete, setListToDelete] = useState<string | null>(null);
const [searchTerm, setSearchTerm] = useState('');
const [formData, setFormData] = useState({
name: '',
description: '',
color: COLORS[0].value,
});
useEffect(() => {
fetchLists();
}, []);
const fetchLists = async () => {
try {
const response = await fetch('/api/crm/lists', {
headers: {
'Authorization': `Bearer ${localStorage.getItem('token')}`,
},
});
if (response.ok) {
const data = await response.json();
setLists(data.lists || []);
}
} catch (error) {
console.error('Error fetching lists:', error);
} finally {
setLoading(false);
}
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
const url = editingList
? `/api/crm/lists/${editingList.id}`
: '/api/crm/lists';
const method = editingList ? 'PUT' : 'POST';
try {
const response = await fetch(url, {
method,
headers: {
'Authorization': `Bearer ${localStorage.getItem('token')}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(formData),
});
if (response.ok) {
toast.success(
editingList ? 'Lista atualizada' : 'Lista criada',
editingList ? 'A lista foi atualizada com sucesso.' : 'A nova lista foi criada com sucesso.'
);
fetchLists();
handleCloseModal();
} else {
const error = await response.json();
toast.error('Erro', error.message || 'Não foi possível salvar a lista.');
}
} catch (error) {
console.error('Error saving list:', error);
toast.error('Erro', 'Ocorreu um erro ao salvar a lista.');
}
};
const handleEdit = (list: List) => {
setEditingList(list);
setFormData({
name: list.name,
description: list.description,
color: list.color,
});
setIsModalOpen(true);
};
const handleDeleteClick = (id: string) => {
setListToDelete(id);
setConfirmOpen(true);
};
const handleConfirmDelete = async () => {
if (!listToDelete) return;
try {
const response = await fetch(`/api/crm/lists/${listToDelete}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${localStorage.getItem('token')}`,
},
});
if (response.ok) {
setLists(lists.filter(l => l.id !== listToDelete));
toast.success('Lista excluída', 'A lista foi excluída com sucesso.');
} else {
toast.error('Erro ao excluir', 'Não foi possível excluir a lista.');
}
} catch (error) {
console.error('Error deleting list:', error);
toast.error('Erro ao excluir', 'Ocorreu um erro ao excluir a lista.');
} finally {
setConfirmOpen(false);
setListToDelete(null);
}
};
const handleCloseModal = () => {
setIsModalOpen(false);
setEditingList(null);
setFormData({
name: '',
description: '',
color: COLORS[0].value,
});
};
const filteredLists = lists.filter((list) => {
const searchLower = searchTerm.toLowerCase();
return (
(list.name?.toLowerCase() || '').includes(searchLower) ||
(list.description?.toLowerCase() || '').includes(searchLower)
);
});
return (
<div className="p-6 max-w-[1600px] mx-auto space-y-6">
{/* Header */}
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
<div>
<h1 className="text-2xl font-bold text-zinc-900 dark:text-white tracking-tight">Listas</h1>
<p className="text-sm text-zinc-500 dark:text-zinc-400 mt-1">
Organize seus clientes em listas personalizadas
</p>
</div>
<button
onClick={() => setIsModalOpen(true)}
className="inline-flex items-center justify-center gap-2 px-4 py-2.5 text-sm font-medium text-white rounded-lg hover:opacity-90 transition-opacity"
style={{ background: 'var(--gradient)' }}
>
<PlusIcon className="w-4 h-4" />
Nova Lista
</button>
</div>
{/* Search */}
<div className="relative w-full lg:w-96">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<MagnifyingGlassIcon className="h-5 w-5 text-zinc-400" aria-hidden="true" />
</div>
<input
type="text"
className="block w-full pl-10 pr-3 py-2 border border-zinc-200 dark:border-zinc-700 rounded-lg leading-5 bg-white dark:bg-zinc-900 text-zinc-900 dark:text-zinc-100 placeholder-zinc-400 focus:outline-none focus:ring-1 focus:ring-[var(--brand-color)] focus:border-[var(--brand-color)] sm:text-sm transition duration-150 ease-in-out"
placeholder="Buscar listas..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
</div>
{/* Grid */}
{loading ? (
<div className="flex items-center justify-center h-64 bg-white dark:bg-zinc-900 rounded-xl border border-zinc-200 dark:border-zinc-800">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[var(--brand-color)]"></div>
</div>
) : filteredLists.length === 0 ? (
<div className="flex flex-col items-center justify-center h-64 bg-white dark:bg-zinc-900 rounded-xl border border-zinc-200 dark:border-zinc-800 text-center p-8">
<div className="w-16 h-16 bg-zinc-50 dark:bg-zinc-800 rounded-full flex items-center justify-center mb-4">
<ListBulletIcon className="w-8 h-8 text-zinc-400" />
</div>
<h3 className="text-lg font-medium text-zinc-900 dark:text-white mb-1">
Nenhuma lista encontrada
</h3>
<p className="text-zinc-500 dark:text-zinc-400 max-w-sm mx-auto">
{searchTerm ? 'Nenhuma lista corresponde à sua busca.' : 'Comece criando sua primeira lista.'}
</p>
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{filteredLists.map((list) => (
<div
key={list.id}
className="group relative bg-white dark:bg-zinc-900 rounded-xl border border-zinc-200 dark:border-zinc-800 p-6 hover:shadow-lg transition-all"
>
{/* Color indicator */}
<div
className="absolute top-0 left-0 w-1 h-full rounded-l-xl"
style={{ backgroundColor: list.color }}
/>
<div className="flex items-start justify-between mb-4 pl-3">
<div className="flex items-center gap-3">
<div
className="w-12 h-12 rounded-lg flex items-center justify-center text-white"
style={{ backgroundColor: list.color }}
>
<ListBulletIcon className="w-6 h-6" />
</div>
<div>
<h3 className="text-lg font-semibold text-zinc-900 dark:text-white">
{list.name}
</h3>
<div className="flex items-center gap-1 mt-1 text-sm text-zinc-500 dark:text-zinc-400">
<UserGroupIcon className="w-4 h-4" />
<span>{list.customer_count || 0} clientes</span>
</div>
</div>
</div>
<Menu as="div" className="relative">
<Menu.Button className="p-1.5 rounded-lg hover:bg-zinc-100 dark:hover:bg-zinc-800 text-zinc-400 hover:text-zinc-600 dark:hover:text-zinc-300 transition-colors outline-none opacity-0 group-hover:opacity-100">
<EllipsisVerticalIcon className="w-5 h-5" />
</Menu.Button>
<Menu.Items
transition
portal
anchor="bottom end"
className="w-48 origin-top-right divide-y divide-zinc-100 dark:divide-zinc-800 rounded-xl bg-white dark:bg-zinc-900 focus:outline-none z-50 border border-zinc-200 dark:border-zinc-800 [--anchor-gap:8px] transition duration-100 ease-out data-[closed]:scale-95 data-[closed]:opacity-0"
>
<div className="px-1 py-1">
<Menu.Item>
{({ active }) => (
<button
onClick={() => handleEdit(list)}
className={`${active ? 'bg-zinc-50 dark:bg-zinc-800' : ''
} group flex w-full items-center rounded-lg px-2 py-2 text-sm text-zinc-700 dark:text-zinc-300`}
>
<PencilIcon className="mr-2 h-4 w-4 text-zinc-400" />
Editar
</button>
)}
</Menu.Item>
</div>
<div className="px-1 py-1">
<Menu.Item>
{({ active }) => (
<button
onClick={() => handleDeleteClick(list.id)}
className={`${active ? 'bg-red-50 dark:bg-red-900/20' : ''
} group flex w-full items-center rounded-lg px-2 py-2 text-sm text-red-600 dark:text-red-400`}
>
<TrashIcon className="mr-2 h-4 w-4" />
Excluir
</button>
)}
</Menu.Item>
</div>
</Menu.Items>
</Menu>
</div>
{list.description && (
<p className="text-sm text-zinc-600 dark:text-zinc-400 pl-3 line-clamp-2">
{list.description}
</p>
)}
</div>
))}
</div>
)}
{/* Modal */}
{isModalOpen && (
<div className="fixed inset-0 z-50 overflow-y-auto">
<div className="flex min-h-full items-end justify-center p-4 text-center sm:items-center sm:p-0">
<div className="fixed inset-0 bg-zinc-900/40 backdrop-blur-sm transition-opacity" onClick={handleCloseModal}></div>
<div className="relative transform overflow-hidden rounded-2xl bg-white dark:bg-zinc-900 text-left shadow-xl transition-all sm:my-8 sm:w-full sm:max-w-lg border border-zinc-200 dark:border-zinc-800">
<div className="absolute right-0 top-0 pr-6 pt-6">
<button
type="button"
className="rounded-lg p-1.5 text-zinc-400 hover:text-zinc-600 dark:hover:text-zinc-300 hover:bg-zinc-100 dark:hover:bg-zinc-800 transition-colors"
onClick={handleCloseModal}
>
<XMarkIcon className="h-5 w-5" />
</button>
</div>
<form onSubmit={handleSubmit} className="p-6 sm:p-8">
<div className="flex items-start gap-4 mb-6">
<div
className="flex h-12 w-12 flex-shrink-0 items-center justify-center rounded-xl shadow-lg"
style={{ backgroundColor: formData.color }}
>
<ListBulletIcon className="h-6 w-6 text-white" />
</div>
<div>
<h3 className="text-xl font-bold text-zinc-900 dark:text-white">
{editingList ? 'Editar Lista' : 'Nova Lista'}
</h3>
<p className="mt-1 text-sm text-zinc-500 dark:text-zinc-400">
{editingList ? 'Atualize as informações da lista.' : 'Crie uma nova lista para organizar seus clientes.'}
</p>
</div>
</div>
<div className="space-y-4">
<div>
<label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
Nome da Lista *
</label>
<input
type="text"
value={formData.name}
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
placeholder="Ex: Clientes VIP"
required
className="w-full px-3 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-[var(--brand-color)] focus:border-transparent transition-all"
/>
</div>
<div>
<label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
Descrição
</label>
<textarea
value={formData.description}
onChange={(e) => setFormData({ ...formData, description: e.target.value })}
placeholder="Descreva o propósito desta lista"
rows={3}
className="w-full px-3 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-[var(--brand-color)] focus:border-transparent resize-none transition-all"
/>
</div>
<div>
<label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-3">
Cor
</label>
<div className="grid grid-cols-8 gap-2">
{COLORS.map((color) => (
<button
key={color.value}
type="button"
onClick={() => setFormData({ ...formData, color: color.value })}
className={`w-10 h-10 rounded-lg transition-all ${formData.color === color.value
? 'ring-2 ring-offset-2 ring-zinc-400 dark:ring-zinc-600 scale-110'
: 'hover:scale-105'
}`}
style={{ backgroundColor: color.value }}
title={color.name}
/>
))}
</div>
</div>
</div>
<div className="mt-8 pt-6 border-t border-zinc-200 dark:border-zinc-700 flex gap-3">
<button
type="button"
onClick={handleCloseModal}
className="flex-1 px-4 py-2.5 border border-zinc-200 dark:border-zinc-700 text-zinc-700 dark:text-zinc-300 font-medium rounded-lg hover:bg-zinc-50 dark:hover:bg-zinc-800 transition-colors"
>
Cancelar
</button>
<button
type="submit"
className="flex-1 px-4 py-2.5 text-white font-medium rounded-lg transition-all shadow-lg hover:shadow-xl"
style={{ background: 'var(--gradient)' }}
>
{editingList ? 'Atualizar' : 'Criar Lista'}
</button>
</div>
</form>
</div>
</div>
</div>
)}
<ConfirmDialog
isOpen={confirmOpen}
onClose={() => {
setConfirmOpen(false);
setListToDelete(null);
}}
onConfirm={handleConfirmDelete}
title="Excluir Lista"
message="Tem certeza que deseja excluir esta lista? Os clientes não serão excluídos, apenas removidos da lista."
confirmText="Excluir"
cancelText="Cancelar"
variant="danger"
/>
</div>
);
}

View File

@@ -0,0 +1,31 @@
"use client";
import { CurrencyDollarIcon } from '@heroicons/react/24/outline';
export default function NegociacoesPage() {
return (
<div className="p-6 h-full flex items-center justify-center">
<div className="text-center max-w-md">
<div className="mx-auto mb-6 flex h-20 w-20 items-center justify-center rounded-full bg-gradient-to-br from-green-500 to-emerald-600">
<CurrencyDollarIcon className="h-10 w-10 text-white" />
</div>
<h1 className="text-2xl font-bold text-gray-900 dark:text-white mb-2">
Negociações
</h1>
<p className="text-gray-600 dark:text-gray-400 mb-4">
Esta funcionalidade está em desenvolvimento
</p>
<div className="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800">
<div className="flex gap-1">
<span className="animate-bounce inline-block h-2 w-2 rounded-full bg-green-600" style={{ animationDelay: '0ms' }}></span>
<span className="animate-bounce inline-block h-2 w-2 rounded-full bg-green-600" style={{ animationDelay: '150ms' }}></span>
<span className="animate-bounce inline-block h-2 w-2 rounded-full bg-green-600" style={{ animationDelay: '300ms' }}></span>
</div>
<span className="text-sm font-medium text-green-600 dark:text-green-400">
Em breve
</span>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,134 @@
"use client";
import Link from 'next/link';
import { SolutionGuard } from '@/components/auth/SolutionGuard';
import {
UsersIcon,
CurrencyDollarIcon,
ChartPieIcon,
ArrowTrendingUpIcon,
ListBulletIcon,
ArrowRightIcon,
} from '@heroicons/react/24/outline';
export default function CRMPage() {
const stats = [
{ name: 'Leads Totais', value: '124', icon: UsersIcon, color: 'blue' },
{ name: 'Oportunidades', value: 'R$ 450k', icon: CurrencyDollarIcon, color: 'green' },
{ name: 'Taxa de Conversão', value: '24%', icon: ChartPieIcon, color: 'purple' },
{ name: 'Crescimento', value: '+12%', icon: ArrowTrendingUpIcon, color: 'orange' },
];
const quickLinks = [
{
name: 'Clientes',
description: 'Gerencie seus contatos e clientes',
icon: UsersIcon,
href: '/crm/clientes',
color: 'blue',
},
{
name: 'Listas',
description: 'Organize clientes em listas',
icon: ListBulletIcon,
href: '/crm/listas',
color: 'purple',
},
];
return (
<SolutionGuard requiredSolution="crm">
<div className="p-6 h-full overflow-auto">
<div className="space-y-6">
<div>
<h1 className="text-2xl font-bold text-gray-900 dark:text-white">
CRM
</h1>
<p className="mt-1 text-sm text-gray-600 dark:text-gray-400">
Visão geral do relacionamento com clientes
</p>
</div>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
{stats.map((stat) => {
const Icon = stat.icon;
return (
<div
key={stat.name}
className="group relative overflow-hidden rounded-xl bg-white dark:bg-gray-900 p-4 border border-gray-200 dark:border-gray-800 transition-all"
>
<div className="flex items-center justify-between">
<div>
<p className="text-xs font-medium text-gray-600 dark:text-gray-400">
{stat.name}
</p>
<p className="mt-1 text-2xl font-bold text-gray-900 dark:text-white">
{stat.value}
</p>
</div>
<div
className={`rounded-lg p-2 bg-${stat.color}-100 dark:bg-${stat.color}-900/20`}
>
<Icon
className={`h-5 w-5 text-${stat.color}-600 dark:text-${stat.color}-400`}
/>
</div>
</div>
</div>
);
})}
</div>
{/* Quick Links */}
<div className="mb-6">
<h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
Acesso Rápido
</h2>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{quickLinks.map((link) => {
const Icon = link.icon;
return (
<Link
key={link.name}
href={link.href}
className="group relative overflow-hidden rounded-xl bg-white dark:bg-gray-900 p-6 border border-gray-200 dark:border-gray-800 hover:border-gray-300 dark:hover:border-gray-700 transition-all hover:shadow-lg"
>
<div className="flex items-start justify-between">
<div className="flex items-start gap-4">
<div
className={`rounded-lg p-3 bg-${link.color}-100 dark:bg-${link.color}-900/20`}
>
<Icon
className={`h-6 w-6 text-${link.color}-600 dark:text-${link.color}-400`}
/>
</div>
<div>
<h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-1">
{link.name}
</h3>
<p className="text-sm text-gray-600 dark:text-gray-400">
{link.description}
</p>
</div>
</div>
<ArrowRightIcon className="w-5 h-5 text-gray-400 group-hover:text-gray-600 dark:group-hover:text-gray-300 group-hover:translate-x-1 transition-all" />
</div>
</Link>
);
})}
</div>
</div>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
<div className="rounded-xl bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-800 p-6 h-64 flex items-center justify-center">
<p className="text-gray-500">Funil de Vendas (Em breve)</p>
</div>
<div className="rounded-xl bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-800 p-6 h-64 flex items-center justify-center">
<p className="text-gray-500">Atividades Recentes (Em breve)</p>
</div>
</div>
</div>
</div>
</SolutionGuard>
);
}

View File

@@ -1,178 +1,233 @@
"use client";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { getUser } from "@/lib/auth";
import { useEffect, useState } from 'react';
import { getUser } from '@/lib/auth';
import {
RocketLaunchIcon,
ChartBarIcon,
UserGroupIcon,
BriefcaseIcon,
LifebuoyIcon,
CreditCardIcon,
DocumentTextIcon,
FolderIcon,
CurrencyDollarIcon,
ShareIcon,
ArrowTrendingUpIcon,
ArrowTrendingDownIcon
ArrowTrendingDownIcon,
CheckCircleIcon,
ClockIcon,
} from '@heroicons/react/24/outline';
interface StatCardProps {
title: string;
value: string | number;
icon: React.ComponentType<React.SVGProps<SVGSVGElement>>;
trend?: number;
color: 'blue' | 'purple' | 'gray' | 'green';
}
const colorClasses = {
blue: {
iconBg: 'bg-blue-50 dark:bg-blue-900/20',
iconColor: 'text-blue-600 dark:text-blue-400',
trend: 'text-blue-600 dark:text-blue-400'
},
purple: {
iconBg: 'bg-purple-50 dark:bg-purple-900/20',
iconColor: 'text-purple-600 dark:text-purple-400',
trend: 'text-purple-600 dark:text-purple-400'
},
gray: {
iconBg: 'bg-gray-50 dark:bg-gray-900/20',
iconColor: 'text-gray-600 dark:text-gray-400',
trend: 'text-gray-600 dark:text-gray-400'
},
green: {
iconBg: 'bg-emerald-50 dark:bg-emerald-900/20',
iconColor: 'text-emerald-600 dark:text-emerald-400',
trend: 'text-emerald-600 dark:text-emerald-400'
}
};
function StatCard({ title, value, icon: Icon, trend, color }: StatCardProps) {
const colors = colorClasses[color];
const isPositive = trend && trend > 0;
return (
<div className="bg-white dark:bg-gray-800 rounded-xl p-6 border border-gray-200 dark:border-gray-700 hover:shadow-lg transition-shadow">
<div className="flex items-center justify-between">
<div className="flex-1">
<p className="text-sm font-medium text-gray-600 dark:text-gray-400">{title}</p>
<p className="text-3xl font-semibold text-gray-900 dark:text-white mt-2">{value}</p>
{trend !== undefined && (
<div className="flex items-center mt-2">
{isPositive ? (
<ArrowTrendingUpIcon className="w-4 h-4 text-emerald-500" />
) : (
<ArrowTrendingDownIcon className="w-4 h-4 text-red-500" />
)}
<span className={`text-sm font-medium ml-1 ${isPositive ? 'text-emerald-600 dark:text-emerald-400' : 'text-red-600 dark:text-red-400'}`}>
{Math.abs(trend)}%
</span>
<span className="text-xs text-gray-500 dark:text-gray-400 ml-1">vs mês anterior</span>
</div>
)}
</div>
<div className={`${colors.iconBg} p-3 rounded-xl`}>
<Icon className={`w-8 h-8 ${colors.iconColor}`} />
</div>
</div>
</div>
);
}
export default function DashboardPage() {
const router = useRouter();
const [stats, setStats] = useState({
clientes: 0,
projetos: 0,
tarefas: 0,
faturamento: 0
});
const [userName, setUserName] = useState('');
const [greeting, setGreeting] = useState('');
useEffect(() => {
// Verificar se é SUPERADMIN e redirecionar
const user = getUser();
if (user && user.role === 'SUPERADMIN') {
router.push('/superadmin');
return;
if (user) {
setUserName(user.name.split(' ')[0]); // Primeiro nome
}
// Simulando carregamento de dados
setTimeout(() => {
setStats({
clientes: 127,
projetos: 18,
tarefas: 64,
faturamento: 87500
});
}, 300);
}, [router]);
const hour = new Date().getHours();
if (hour >= 5 && hour < 12) setGreeting('Bom dia');
else if (hour >= 12 && hour < 18) setGreeting('Boa tarde');
else setGreeting('Boa noite');
}, []);
const overviewStats = [
{ name: 'Receita Total (Mês)', value: 'R$ 124.500', change: '+12%', changeType: 'increase', icon: ChartBarIcon, color: 'green' },
{ name: 'Novos Leads', value: '45', change: '+5%', changeType: 'increase', icon: RocketLaunchIcon, color: 'blue' },
{ name: 'Projetos Ativos', value: '12', change: '-1', changeType: 'decrease', icon: BriefcaseIcon, color: 'purple' },
{ name: 'Chamados Abertos', value: '3', change: '-2', changeType: 'decrease', icon: LifebuoyIcon, color: 'orange' },
];
const modules = [
{
title: 'CRM & Vendas',
icon: RocketLaunchIcon,
color: 'blue',
stats: [
{ label: 'Propostas Enviadas', value: '8' },
{ label: 'Aguardando Aprovação', value: '3' },
{ label: 'Taxa de Conversão', value: '24%' },
]
},
{
title: 'Financeiro & ERP',
icon: ChartBarIcon,
color: 'green',
stats: [
{ label: 'A Receber', value: 'R$ 45.200' },
{ label: 'A Pagar', value: 'R$ 12.800' },
{ label: 'Fluxo de Caixa', value: 'Positivo' },
]
},
{
title: 'Projetos & Tarefas',
icon: BriefcaseIcon,
color: 'purple',
stats: [
{ label: 'Em Andamento', value: '12' },
{ label: 'Atrasados', value: '1' },
{ label: 'Concluídos (Mês)', value: '4' },
]
},
{
title: 'Helpdesk',
icon: LifebuoyIcon,
color: 'orange',
stats: [
{ label: 'Novos Chamados', value: '3' },
{ label: 'Tempo Médio Resposta', value: '2h' },
{ label: 'Satisfação', value: '4.8/5' },
]
},
{
title: 'Documentos & Contratos',
icon: DocumentTextIcon,
color: 'indigo',
stats: [
{ label: 'Contratos Ativos', value: '28' },
{ label: 'A Vencer (30 dias)', value: '2' },
{ label: 'Docs Armazenados', value: '1.2GB' },
]
},
{
title: 'Redes Sociais',
icon: ShareIcon,
color: 'pink',
stats: [
{ label: 'Posts Agendados', value: '14' },
{ label: 'Engajamento', value: '+8.5%' },
{ label: 'Novos Seguidores', value: '120' },
]
}
];
return (
<div className="p-6 max-w-7xl mx-auto">
{/* Header */}
<div className="mb-8">
<h1 className="text-2xl font-bold text-gray-900 dark:text-white mb-2">
Dashboard
</h1>
<p className="text-gray-600 dark:text-gray-400">
Bem-vindo ao seu painel de controle
</p>
</div>
{/* Stats Grid */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
<StatCard
title="Clientes Ativos"
value={stats.clientes}
icon={UserGroupIcon}
trend={12.5}
color="blue"
/>
<StatCard
title="Projetos em Andamento"
value={stats.projetos}
icon={FolderIcon}
trend={8.2}
color="purple"
/>
<StatCard
title="Tarefas Pendentes"
value={stats.tarefas}
icon={ChartBarIcon}
trend={-3.1}
color="gray"
/>
<StatCard
title="Faturamento"
value={new Intl.NumberFormat('pt-BR', {
style: 'currency',
currency: 'BRL',
minimumFractionDigits: 0
}).format(stats.faturamento)}
icon={CurrencyDollarIcon}
trend={25.3}
color="green"
/>
</div>
{/* Coming Soon Card */}
<div className="bg-linear-to-br from-gray-50 to-gray-100 dark:from-gray-800 dark:to-gray-900 rounded-2xl border border-gray-200 dark:border-gray-700 p-12">
<div className="max-w-2xl mx-auto text-center">
<div className="inline-flex items-center justify-center w-16 h-16 rounded-2xl mb-6" style={{ background: 'var(--gradient-primary)' }}>
<ChartBarIcon className="w-8 h-8 text-white" />
<div className="p-6 h-full overflow-auto">
<div className="space-y-8">
{/* Header Personalizado */}
<div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
<div>
<h1 className="text-2xl font-heading font-bold text-gray-900 dark:text-white">
{greeting}, {userName || 'Administrador'}! 👋
</h1>
<p className="mt-1 text-sm text-gray-600 dark:text-gray-400">
Aqui está o resumo da sua agência hoje. Tudo parece estar sob controle.
</p>
</div>
<h2 className="text-3xl font-bold text-gray-900 dark:text-white mb-3">
Em Desenvolvimento
<div className="flex items-center gap-3">
<span className="text-xs font-medium px-3 py-1 rounded-full bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400 border border-green-200 dark:border-green-800 flex items-center gap-1">
<span className="w-2 h-2 rounded-full bg-green-500 animate-pulse"></span>
Sistema Operacional
</span>
<span className="text-xs text-gray-500 dark:text-gray-400">
{new Date().toLocaleDateString('pt-BR', { weekday: 'long', day: 'numeric', month: 'long' })}
</span>
</div>
</div>
{/* Top Stats */}
<div>
{/* Mobile: Scroll Horizontal */}
<div className="md:hidden overflow-x-auto scrollbar-hide">
<div className="flex gap-4 min-w-max">
{overviewStats.map((stat) => {
const Icon = stat.icon;
return (
<div
key={stat.name}
className="relative overflow-hidden rounded-xl bg-white dark:bg-zinc-900 p-4 border border-gray-200 dark:border-zinc-800 shadow-sm w-[280px] flex-shrink-0"
>
<div className="flex items-center justify-between">
<div className={`rounded-lg p-2 bg-${stat.color}-50 dark:bg-${stat.color}-900/20`}>
<Icon className={`h-6 w-6 text-${stat.color}-600 dark:text-${stat.color}-400`} />
</div>
<div className={`flex items-baseline text-sm font-semibold ${stat.changeType === 'increase' ? 'text-green-600' : 'text-red-600'
}`}>
{stat.changeType === 'increase' ? (
<ArrowTrendingUpIcon className="h-4 w-4 mr-1" />
) : (
<ArrowTrendingDownIcon className="h-4 w-4 mr-1" />
)}
{stat.change}
</div>
</div>
<div className="mt-4">
<p className="text-sm font-medium text-gray-500 dark:text-gray-400">{stat.name}</p>
<p className="text-2xl font-bold text-gray-900 dark:text-white">{stat.value}</p>
</div>
</div>
);
})}
</div>
</div>
{/* Desktop: Grid */}
<div className="hidden md:grid md:grid-cols-2 lg:grid-cols-4 gap-4">
{overviewStats.map((stat) => {
const Icon = stat.icon;
return (
<div
key={stat.name}
className="relative overflow-hidden rounded-xl bg-white dark:bg-zinc-900 p-4 border border-gray-200 dark:border-zinc-800 shadow-sm"
>
<div className="flex items-center justify-between">
<div className={`rounded-lg p-2 bg-${stat.color}-50 dark:bg-${stat.color}-900/20`}>
<Icon className={`h-6 w-6 text-${stat.color}-600 dark:text-${stat.color}-400`} />
</div>
<div className={`flex items-baseline text-sm font-semibold ${stat.changeType === 'increase' ? 'text-green-600' : 'text-red-600'
}`}>
{stat.changeType === 'increase' ? (
<ArrowTrendingUpIcon className="h-4 w-4 mr-1" />
) : (
<ArrowTrendingDownIcon className="h-4 w-4 mr-1" />
)}
{stat.change}
</div>
</div>
<div className="mt-4">
<p className="text-sm font-medium text-gray-500 dark:text-gray-400">{stat.name}</p>
<p className="text-2xl font-bold text-gray-900 dark:text-white">{stat.value}</p>
</div>
</div>
);
})}
</div>
</div>
{/* Modules Grid */}
<div>
<h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
Performance por Módulo
</h2>
<p className="text-lg text-gray-600 dark:text-gray-400 mb-8">
Estamos construindo recursos incríveis de CRM e ERP para sua agência.
Em breve você terá acesso a análises detalhadas, gestão completa de clientes e muito mais.
</p>
<div className="flex flex-wrap items-center justify-center gap-3">
{['CRM', 'ERP', 'Projetos', 'Pagamentos', 'Documentos', 'Suporte', 'Contratos'].map((item) => (
<span
key={item}
className="inline-flex items-center px-4 py-2 rounded-full text-sm font-medium bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 border border-gray-200 dark:border-gray-700"
>
{item}
</span>
))}
<div className="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3">
{modules.map((module) => {
const Icon = module.icon;
return (
<div
key={module.title}
className="rounded-xl bg-white dark:bg-zinc-900 border border-gray-200 dark:border-zinc-800 p-6 hover:border-gray-200 dark:hover:border-zinc-700 transition-colors"
>
<div className="flex items-center gap-3 mb-6">
<div className={`p-2 rounded-lg bg-${module.color}-50 dark:bg-${module.color}-900/20`}>
<Icon className={`h-5 w-5 text-${module.color}-600 dark:text-${module.color}-400`} />
</div>
<h3 className="font-semibold text-gray-900 dark:text-white">
{module.title}
</h3>
</div>
<div className="space-y-4">
{module.stats.map((stat, idx) => (
<div key={idx} className="flex items-center justify-between text-sm">
<span className="text-gray-500 dark:text-gray-400">{stat.label}</span>
<span className="font-medium text-gray-900 dark:text-white">{stat.value}</span>
</div>
))}
</div>
</div>
);
})}
</div>
</div>
</div>

View File

@@ -0,0 +1,16 @@
'use client';
import { SolutionGuard } from '@/components/auth/SolutionGuard';
export default function DocumentosPage() {
return (
<SolutionGuard requiredSolution="documentos">
<div className="p-6">
<h1 className="text-2xl font-bold text-gray-900 dark:text-white mb-4">Documentos</h1>
<div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-800 p-8 text-center">
<p className="text-gray-500">Gestão Eletrônica de Documentos (GED) em breve</p>
</div>
</div>
</SolutionGuard>
);
}

View File

@@ -0,0 +1,16 @@
'use client';
import { SolutionGuard } from '@/components/auth/SolutionGuard';
export default function ERPPage() {
return (
<SolutionGuard requiredSolution="erp">
<div className="p-6">
<h1 className="text-2xl font-bold text-gray-900 dark:text-white mb-4">ERP</h1>
<div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-800 p-8 text-center">
<p className="text-gray-500">Sistema Integrado de Gestão Empresarial em breve</p>
</div>
</div>
</SolutionGuard>
);
}

View File

@@ -0,0 +1,16 @@
'use client';
import { SolutionGuard } from '@/components/auth/SolutionGuard';
export default function HelpdeskPage() {
return (
<SolutionGuard requiredSolution="helpdesk">
<div className="p-6">
<h1 className="text-2xl font-bold text-gray-900 dark:text-white mb-4">Helpdesk</h1>
<div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-800 p-8 text-center">
<p className="text-gray-500">Central de Suporte e Chamados em breve</p>
</div>
</div>
</SolutionGuard>
);
}

View File

@@ -1,635 +1,34 @@
"use client";
import { Metadata } from 'next';
import { getAgencyLogo, getAgencyColors } from '@/lib/server-api';
import { AgencyLayoutClient } from './AgencyLayoutClient';
import { useEffect, useState, Fragment } from 'react';
import { usePathname, useRouter } from 'next/navigation';
import dynamic from 'next/dynamic';
import { Menu, Transition } from '@headlessui/react';
import {
Bars3Icon,
XMarkIcon,
MagnifyingGlassIcon,
BellIcon,
Cog6ToothIcon,
UserCircleIcon,
ArrowRightOnRectangleIcon,
ChevronDownIcon,
ChevronRightIcon,
UserGroupIcon,
BuildingOfficeIcon,
FolderIcon,
CreditCardIcon,
DocumentTextIcon,
LifebuoyIcon,
DocumentCheckIcon,
UsersIcon,
UserPlusIcon,
PhoneIcon,
FunnelIcon,
ChartBarIcon,
HomeIcon,
CubeIcon,
ShoppingCartIcon,
BanknotesIcon,
DocumentDuplicateIcon,
ShareIcon,
DocumentMagnifyingGlassIcon,
TrashIcon,
RectangleStackIcon,
CalendarIcon,
UserGroupIcon as TeamIcon,
ReceiptPercentIcon,
CreditCardIcon as PaymentIcon,
ChatBubbleLeftRightIcon,
BookOpenIcon,
ArchiveBoxIcon,
PencilSquareIcon,
} from '@heroicons/react/24/outline';
// Forçar renderização dinâmica (não estática) para este layout
// Necessário porque usamos headers() para pegar o subdomínio
export const dynamic = 'force-dynamic';
const ThemeToggle = dynamic(() => import('@/components/ThemeToggle'), { ssr: false });
const ThemeTester = dynamic(() => import('@/components/ThemeTester'), { ssr: false });
const DynamicFavicon = dynamic(() => import('@/components/DynamicFavicon'), { ssr: false });
/**
* generateMetadata - Executado no servidor antes do render
* Define o favicon dinamicamente baseado no subdomínio da agência
*/
export async function generateMetadata(): Promise<Metadata> {
const logoUrl = await getAgencyLogo();
const DEFAULT_GRADIENT = 'linear-gradient(135deg, #ff3a05, #ff0080)';
return {
icons: {
icon: logoUrl || '/favicon.ico',
shortcut: logoUrl || '/favicon.ico',
apple: logoUrl || '/favicon.ico',
},
};
}
const setGradientVariables = (gradient: string) => {
document.documentElement.style.setProperty('--gradient-primary', gradient);
document.documentElement.style.setProperty('--gradient', gradient);
document.documentElement.style.setProperty('--gradient-text', gradient.replace('90deg', 'to right'));
document.documentElement.style.setProperty('--color-gradient-brand', gradient.replace('90deg', 'to right'));
};
export default function AgencyLayout({
export default async function AgencyLayout({
children,
}: {
children: React.ReactNode;
}) {
const router = useRouter();
const pathname = usePathname();
const [user, setUser] = useState<any>(null);
const [agencyName, setAgencyName] = useState('');
const [agencyLogo, setAgencyLogo] = useState('');
const [sidebarOpen, setSidebarOpen] = useState(true);
const [searchOpen, setSearchOpen] = useState(false);
const [activeSubmenu, setActiveSubmenu] = useState<number | null>(null);
const [selectedClient, setSelectedClient] = useState<any>(null);
// Buscar cores da agência no servidor
const colors = await getAgencyColors();
// Mock de clientes - no futuro virá da API
const clients = [
{ id: 1, name: 'Todos os Clientes', avatar: null },
{ id: 2, name: 'Empresa ABC Ltda', avatar: 'A' },
{ id: 3, name: 'Tech Solutions Inc', avatar: 'T' },
{ id: 4, name: 'Marketing Pro', avatar: 'M' },
{ id: 5, name: 'Design Studio', avatar: 'D' },
];
useEffect(() => {
const token = localStorage.getItem('token');
const userData = localStorage.getItem('user');
if (!token || !userData) {
router.push('/login');
return;
}
const parsedUser = JSON.parse(userData);
setUser(parsedUser);
if (parsedUser.role === 'SUPERADMIN') {
router.push('/superadmin');
return;
}
const hostname = window.location.hostname;
const hostSubdomain = hostname.split('.')[0] || 'default';
const themeKey = parsedUser?.subdomain || parsedUser?.tenantId || parsedUser?.tenant_id || hostSubdomain;
setAgencyName(parsedUser?.subdomain || hostSubdomain);
// Buscar logo da agência
const fetchAgencyLogo = async () => {
try {
const response = await fetch('/api/agency/profile', {
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
});
if (response.ok) {
const data = await response.json();
if (data.logo_url) {
setAgencyLogo(data.logo_url);
}
}
} catch (error) {
console.error('Erro ao buscar logo da agência:', error);
}
};
fetchAgencyLogo();
const storedGradient = localStorage.getItem(`agency-theme:${themeKey}`);
setGradientVariables(storedGradient || DEFAULT_GRADIENT);
// Inicializar com "Todos os Clientes"
setSelectedClient(clients[0]);
// Atalho de teclado para abrir pesquisa (Ctrl/Cmd + K)
const handleKeyDown = (e: KeyboardEvent) => {
if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
e.preventDefault();
setSearchOpen(true);
}
if (e.key === 'Escape') {
setSearchOpen(false);
}
};
window.addEventListener('keydown', handleKeyDown);
return () => {
window.removeEventListener('keydown', handleKeyDown);
setGradientVariables(DEFAULT_GRADIENT);
};
}, [router]);
useEffect(() => {
const hostname = window.location.hostname;
const hostSubdomain = hostname.split('.')[0] || 'default';
const userData = localStorage.getItem('user');
const parsedUser = userData ? JSON.parse(userData) : null;
const themeKey = parsedUser?.subdomain || parsedUser?.tenantId || parsedUser?.tenant_id || hostSubdomain;
const storedGradient = localStorage.getItem(`agency-theme:${themeKey}`) || DEFAULT_GRADIENT;
setGradientVariables(storedGradient);
}, [pathname]);
if (!user) {
return null;
}
const menuItems = [
{
icon: UserGroupIcon,
label: 'CRM',
href: '/crm',
submenu: [
{ icon: UsersIcon, label: 'Clientes', href: '/crm/clientes' },
{ icon: UserPlusIcon, label: 'Leads', href: '/crm/leads' },
{ icon: PhoneIcon, label: 'Contatos', href: '/crm/contatos' },
{ icon: FunnelIcon, label: 'Funil de Vendas', href: '/crm/funil' },
{ icon: ChartBarIcon, label: 'Relatórios', href: '/crm/relatorios' },
]
},
{
icon: BuildingOfficeIcon,
label: 'ERP',
href: '/erp',
submenu: [
{ icon: HomeIcon, label: 'Dashboard', href: '/erp/dashboard' },
{ icon: CubeIcon, label: 'Estoque', href: '/erp/estoque' },
{ icon: ShoppingCartIcon, label: 'Compras', href: '/erp/compras' },
{ icon: BanknotesIcon, label: 'Vendas', href: '/erp/vendas' },
{ icon: ChartBarIcon, label: 'Financeiro', href: '/erp/financeiro' },
]
},
{
icon: FolderIcon,
label: 'Projetos',
href: '/projetos',
submenu: [
{ icon: RectangleStackIcon, label: 'Todos Projetos', href: '/projetos/todos' },
{ icon: RectangleStackIcon, label: 'Kanban', href: '/projetos/kanban' },
{ icon: CalendarIcon, label: 'Calendário', href: '/projetos/calendario' },
{ icon: TeamIcon, label: 'Equipes', href: '/projetos/equipes' },
]
},
{
icon: CreditCardIcon,
label: 'Pagamentos',
href: '/pagamentos',
submenu: [
{ icon: DocumentTextIcon, label: 'Faturas', href: '/pagamentos/faturas' },
{ icon: ReceiptPercentIcon, label: 'Recebimentos', href: '/pagamentos/recebimentos' },
{ icon: PaymentIcon, label: 'Assinaturas', href: '/pagamentos/assinaturas' },
{ icon: BanknotesIcon, label: 'Gateway', href: '/pagamentos/gateway' },
]
},
{
icon: DocumentTextIcon,
label: 'Documentos',
href: '/documentos',
submenu: [
{ icon: FolderIcon, label: 'Meus Arquivos', href: '/documentos/arquivos' },
{ icon: ShareIcon, label: 'Compartilhados', href: '/documentos/compartilhados' },
{ icon: DocumentDuplicateIcon, label: 'Modelos', href: '/documentos/modelos' },
{ icon: TrashIcon, label: 'Lixeira', href: '/documentos/lixeira' },
]
},
{
icon: LifebuoyIcon,
label: 'Suporte',
href: '/suporte',
submenu: [
{ icon: DocumentMagnifyingGlassIcon, label: 'Tickets', href: '/suporte/tickets' },
{ icon: BookOpenIcon, label: 'Base de Conhecimento', href: '/suporte/kb' },
{ icon: ChatBubbleLeftRightIcon, label: 'Chat', href: '/suporte/chat' },
]
},
{
icon: DocumentCheckIcon,
label: 'Contratos',
href: '/contratos',
submenu: [
{ icon: DocumentCheckIcon, label: 'Ativos', href: '/contratos/ativos' },
{ icon: PencilSquareIcon, label: 'Rascunhos', href: '/contratos/rascunhos' },
{ icon: ArchiveBoxIcon, label: 'Arquivados', href: '/contratos/arquivados' },
{ icon: DocumentDuplicateIcon, label: 'Modelos', href: '/contratos/modelos' },
]
},
];
const handleLogout = () => {
localStorage.removeItem('token');
localStorage.removeItem('user');
router.push('/login');
};
return (
<div className="flex h-screen bg-gray-50 dark:bg-gray-950">
{/* Favicon Dinâmico */}
<DynamicFavicon logoUrl={agencyLogo} />
{/* Sidebar */}
<aside className={`${activeSubmenu !== null ? 'w-20' : (sidebarOpen ? 'w-64' : 'w-20')} transition-all duration-300 bg-white dark:bg-gray-900 border-r border-gray-200 dark:border-gray-800 flex flex-col`}>
{/* Logo */}
<div className="h-16 flex items-center justify-center border-b border-gray-200 dark:border-gray-800">
{(sidebarOpen && activeSubmenu === null) ? (
<div className="flex items-center justify-between px-4 w-full">
<div className="flex items-center space-x-3">
{agencyLogo ? (
<img src={agencyLogo} alt="Logo" className="w-8 h-8 rounded-lg object-contain shrink-0" />
) : (
<div className="w-8 h-8 rounded-lg shrink-0" style={{ background: 'var(--gradient-primary)' }}></div>
)}
<span className="font-bold text-lg dark:text-white capitalize">{agencyName}</span>
</div>
<button
onClick={() => setSidebarOpen(!sidebarOpen)}
className="p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors cursor-pointer"
>
<XMarkIcon className="w-4 h-4 text-gray-500 dark:text-gray-400" />
</button>
</div>
) : (
<>
{agencyLogo ? (
<img src={agencyLogo} alt="Logo" className="w-8 h-8 rounded-lg object-contain" />
) : (
<div className="w-8 h-8 rounded-lg" style={{ background: 'var(--gradient-primary)' }}></div>
)}
</>
)}
</div>
{/* Menu */}
<nav className="flex-1 overflow-y-auto py-4 px-3">
{menuItems.map((item, idx) => {
const Icon = item.icon;
const isActive = activeSubmenu === idx;
return (
<button
key={idx}
onClick={() => setActiveSubmenu(isActive ? null : idx)}
className={`w-full flex items-center ${(sidebarOpen && activeSubmenu === null) ? 'space-x-3 px-3' : 'justify-center px-0'} py-2.5 mb-1 rounded-lg transition-all group cursor-pointer ${isActive
? 'bg-gray-900 dark:bg-gray-100 text-white dark:text-gray-900'
: 'hover:bg-gray-100 dark:hover:bg-gray-800 text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white'
}`}
>
<Icon className={`${(sidebarOpen && activeSubmenu === null) ? 'w-5 h-5' : 'w-[18px] h-[18px]'} stroke-[1.5]`} />
{(sidebarOpen && activeSubmenu === null) && (
<>
<span className="flex-1 text-left text-sm font-normal">{item.label}</span>
<ChevronRightIcon className={`w-4 h-4 transition-transform ${isActive ? 'rotate-90' : ''}`} />
</>
)}
</button>
);
})}
</nav>
{/* User Menu */}
<div className="p-4 border-t border-gray-200 dark:border-gray-800">
{(sidebarOpen && activeSubmenu === null) ? (
<Menu as="div" className="relative">
<Menu.Button className="w-full flex items-center space-x-3 p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-xl transition-colors">
<div className="w-10 h-10 rounded-full flex items-center justify-center text-white font-semibold" style={{ background: 'var(--gradient-primary)' }}>
{user?.name?.charAt(0).toUpperCase()}
</div>
<div className="flex-1 text-left">
<p className="text-sm font-medium text-gray-900 dark:text-white truncate">{user?.name}</p>
<p className="text-xs text-gray-500 dark:text-gray-400">{user?.role === 'ADMIN_AGENCIA' ? 'Admin' : 'Cliente'}</p>
</div>
<ChevronDownIcon className="w-4 h-4 text-gray-400" />
</Menu.Button>
<Transition
as={Fragment}
enter="transition ease-out duration-100"
enterFrom="transform opacity-0 scale-95"
enterTo="transform opacity-100 scale-100"
leave="transition ease-in duration-75"
leaveFrom="transform opacity-100 scale-100"
leaveTo="transform opacity-0 scale-95"
>
<Menu.Items className="absolute bottom-full left-0 right-0 mb-2 bg-white dark:bg-gray-800 rounded-xl shadow-lg border border-gray-200 dark:border-gray-700 overflow-hidden">
<Menu.Item>
{({ active }) => (
<a
href="/perfil"
className={`${active ? 'bg-gray-100 dark:bg-gray-700' : ''} flex items-center px-4 py-3 text-sm text-gray-700 dark:text-gray-300`}
>
<UserCircleIcon className="w-5 h-5 mr-3" />
Meu Perfil
</a>
)}
</Menu.Item>
<Menu.Item>
{({ active }) => (
<button
onClick={handleLogout}
className={`${active ? 'bg-gray-100 dark:bg-gray-700' : ''} w-full flex items-center px-4 py-3 text-sm text-red-600 dark:text-red-400`}
>
<ArrowRightOnRectangleIcon className="w-5 h-5 mr-3" />
Sair
</button>
)}
</Menu.Item>
</Menu.Items>
</Transition>
</Menu>
) : (
<button
onClick={handleLogout}
className="w-10 h-10 mx-auto rounded-full flex items-center justify-center text-white cursor-pointer"
style={{ background: 'var(--gradient-primary)' }}
title="Sair"
>
<ArrowRightOnRectangleIcon className="w-5 h-5" />
</button>
)}
</div>
</aside>
{/* Submenu Lateral */}
<Transition
show={activeSubmenu !== null}
as={Fragment}
enter="transition ease-out duration-200"
enterFrom="transform -translate-x-full opacity-0"
enterTo="transform translate-x-0 opacity-100"
leave="transition ease-in duration-150"
leaveFrom="transform translate-x-0 opacity-100"
leaveTo="transform -translate-x-full opacity-0"
>
<aside className="w-64 bg-white dark:bg-gray-900 border-r border-gray-200 dark:border-gray-800 flex flex-col">
{activeSubmenu !== null && (
<>
<div className="h-16 flex items-center justify-between px-4 border-b border-gray-200 dark:border-gray-800">
<h2 className="font-semibold text-gray-900 dark:text-white">{menuItems[activeSubmenu].label}</h2>
<button
onClick={() => setActiveSubmenu(null)}
className="p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors cursor-pointer"
>
<XMarkIcon className="w-4 h-4 text-gray-500 dark:text-gray-400" />
</button>
</div>
<nav className="flex-1 overflow-y-auto py-4 px-3">
{menuItems[activeSubmenu].submenu?.map((subItem, idx) => {
const SubIcon = subItem.icon;
return (
<a
key={idx}
href={subItem.href}
className="flex items-center space-x-3 px-4 py-2.5 mb-1 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-800 text-sm text-gray-700 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white transition-colors cursor-pointer"
>
<SubIcon className="w-5 h-5 stroke-[1.5]" />
<span>{subItem.label}</span>
</a>
);
})}
</nav>
</>
)}
</aside>
</Transition>
{/* Main Content */}
<div className="flex-1 flex flex-col overflow-hidden">
{/* Header */}
<header className="h-16 bg-white dark:bg-gray-900 border-b border-gray-200 dark:border-gray-800 flex items-center justify-between px-6">
<div className="flex items-center space-x-4">
<h1 className="text-lg font-semibold text-gray-900 dark:text-white">
Dashboard
</h1>
{/* Seletor de Cliente */}
<Menu as="div" className="relative">
<Menu.Button className="flex items-center space-x-2 px-3 py-1.5 bg-gray-100 dark:bg-gray-800 hover:bg-gray-200 dark:hover:bg-gray-700 rounded-lg transition-colors cursor-pointer">
{selectedClient?.avatar ? (
<div className="w-6 h-6 rounded-full flex items-center justify-center text-white text-xs font-semibold" style={{ background: 'var(--gradient-primary)' }}>
{selectedClient.avatar}
</div>
) : (
<UsersIcon className="w-4 h-4 text-gray-600 dark:text-gray-400" />
)}
<span className="text-sm font-medium text-gray-700 dark:text-gray-300">
{selectedClient?.name || 'Selecionar Cliente'}
</span>
<ChevronDownIcon className="w-4 h-4 text-gray-500 dark:text-gray-400" />
</Menu.Button>
<Transition
as={Fragment}
enter="transition ease-out duration-100"
enterFrom="transform opacity-0 scale-95"
enterTo="transform opacity-100 scale-100"
leave="transition ease-in duration-75"
leaveFrom="transform opacity-100 scale-100"
leaveTo="transform opacity-0 scale-95"
>
<Menu.Items className="absolute left-0 mt-2 w-72 bg-white dark:bg-gray-800 rounded-xl shadow-lg border border-gray-200 dark:border-gray-700 overflow-hidden z-50">
<div className="p-3 border-b border-gray-200 dark:border-gray-700">
<div className="relative">
<MagnifyingGlassIcon className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
<input
type="text"
placeholder="Buscar cliente..."
className="w-full pl-9 pr-3 py-2 bg-gray-50 dark:bg-gray-900 border border-gray-200 dark:border-gray-700 rounded-lg text-sm text-gray-900 dark:text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-400 dark:focus:ring-gray-600"
/>
</div>
</div>
<div className="max-h-64 overflow-y-auto p-2">
{clients.map((client) => (
<Menu.Item key={client.id}>
{({ active }) => (
<button
onClick={() => setSelectedClient(client)}
className={`${active ? 'bg-gray-100 dark:bg-gray-700' : ''
} ${selectedClient?.id === client.id ? 'bg-gray-100 dark:bg-gray-800' : ''
} w-full flex items-center space-x-3 px-3 py-2.5 rounded-lg transition-colors cursor-pointer`}
>
{client.avatar ? (
<div className="w-8 h-8 rounded-full flex items-center justify-center text-white text-sm font-semibold shrink-0" style={{ background: 'var(--gradient-primary)' }}>
{client.avatar}
</div>
) : (
<div className="w-8 h-8 rounded-full bg-gray-200 dark:bg-gray-700 flex items-center justify-center shrink-0">
<UsersIcon className="w-4 h-4 text-gray-600 dark:text-gray-400" />
</div>
)}
<span className="flex-1 text-left text-sm font-medium text-gray-900 dark:text-white">
{client.name}
</span>
{selectedClient?.id === client.id && (
<div className="w-2 h-2 rounded-full bg-gray-900 dark:bg-gray-100"></div>
)}
</button>
)}
</Menu.Item>
))}
</div>
</Menu.Items>
</Transition>
</Menu>
</div>
<div className="flex items-center space-x-2">
{/* Pesquisa */}
<button
onClick={() => setSearchOpen(true)}
className="flex items-center space-x-2 px-3 py-2 bg-gray-100 dark:bg-gray-800 hover:bg-gray-200 dark:hover:bg-gray-700 rounded-lg transition-colors"
>
<MagnifyingGlassIcon className="w-4 h-4 text-gray-500 dark:text-gray-400" />
<span className="text-sm text-gray-500 dark:text-gray-400">Pesquisar...</span>
<kbd className="hidden sm:inline-flex items-center px-2 py-0.5 text-xs font-medium text-gray-500 dark:text-gray-400 bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded">
Ctrl K
</kbd>
</button>
<ThemeToggle />
{/* Notificações */}
<Menu as="div" className="relative">
<Menu.Button className="p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg relative transition-colors">
<BellIcon className="w-5 h-5 text-gray-600 dark:text-gray-400" />
<span className="absolute top-1.5 right-1.5 w-2 h-2 bg-red-500 rounded-full"></span>
</Menu.Button>
<Transition
as={Fragment}
enter="transition ease-out duration-100"
enterFrom="transform opacity-0 scale-95"
enterTo="transform opacity-100 scale-100"
leave="transition ease-in duration-75"
leaveFrom="transform opacity-100 scale-100"
leaveTo="transform opacity-0 scale-95"
>
<Menu.Items className="absolute right-0 mt-2 w-80 bg-white dark:bg-gray-800 rounded-xl shadow-lg border border-gray-200 dark:border-gray-700 overflow-hidden">
<div className="p-4 border-b border-gray-200 dark:border-gray-700">
<h3 className="font-semibold text-gray-900 dark:text-white">Notificações</h3>
</div>
<div className="p-4 text-center text-sm text-gray-500 dark:text-gray-400">
Nenhuma notificação no momento
</div>
</Menu.Items>
</Transition>
</Menu>
{/* Configurações */}
<a
href="/configuracoes"
className="p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors"
>
<Cog6ToothIcon className="w-5 h-5 text-gray-600 dark:text-gray-400" />
</a>
</div>
</header>
{/* Page Content */}
<main className="flex-1 overflow-y-auto bg-gray-50 dark:bg-gray-950">
{children}
</main>
</div>
{/* Modal de Pesquisa */}
<Transition appear show={searchOpen} as={Fragment}>
<div className="fixed inset-0 z-50 overflow-y-auto">
<Transition.Child
as={Fragment}
enter="ease-out duration-200"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="ease-in duration-150"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<div className="fixed inset-0 bg-black/50 backdrop-blur-sm" onClick={() => setSearchOpen(false)} />
</Transition.Child>
<div className="flex min-h-full items-start justify-center p-4 pt-[15vh]">
<Transition.Child
as={Fragment}
enter="ease-out duration-200"
enterFrom="opacity-0 scale-95"
enterTo="opacity-100 scale-100"
leave="ease-in duration-150"
leaveFrom="opacity-100 scale-100"
leaveTo="opacity-0 scale-95"
>
<div className="w-full max-w-2xl bg-white dark:bg-gray-900 rounded-xl shadow-2xl border border-gray-200 dark:border-gray-800 overflow-hidden relative z-10">
<div className="flex items-center px-4 border-b border-gray-200 dark:border-gray-800">
<MagnifyingGlassIcon className="w-5 h-5 text-gray-400" />
<input
type="text"
placeholder="Pesquisar páginas, clientes, projetos..."
autoFocus
className="w-full px-4 py-4 bg-transparent text-gray-900 dark:text-white placeholder-gray-400 focus:outline-none"
/>
<button
onClick={() => setSearchOpen(false)}
className="text-xs text-gray-500 dark:text-gray-400 px-2 py-1 border border-gray-300 dark:border-gray-700 rounded"
>
ESC
</button>
</div>
<div className="p-4 max-h-96 overflow-y-auto">
<div className="text-center py-12">
<MagnifyingGlassIcon className="w-12 h-12 text-gray-300 dark:text-gray-700 mx-auto mb-3" />
<p className="text-sm text-gray-500 dark:text-gray-400">
Digite para buscar...
</p>
</div>
</div>
<div className="px-4 py-3 border-t border-gray-200 dark:border-gray-800 bg-gray-50 dark:bg-gray-950">
<div className="flex items-center justify-between text-xs text-gray-500 dark:text-gray-400">
<div className="flex items-center space-x-4">
<span className="flex items-center">
<kbd className="px-2 py-1 bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded mr-1"></kbd>
navegar
</span>
<span className="flex items-center">
<kbd className="px-2 py-1 bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded mr-1"></kbd>
selecionar
</span>
</div>
</div>
</div>
</div>
</Transition.Child>
</div>
</div>
</Transition>
{/* Theme Tester - Temporário para desenvolvimento */}
<ThemeTester />
</div>
);
return <AgencyLayoutClient colors={colors}>{children}</AgencyLayoutClient>;
}

View File

@@ -0,0 +1,16 @@
'use client';
import { SolutionGuard } from '@/components/auth/SolutionGuard';
export default function PagamentosPage() {
return (
<SolutionGuard requiredSolution="pagamentos">
<div className="p-6">
<h1 className="text-2xl font-bold text-gray-900 dark:text-white mb-4">Pagamentos</h1>
<div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-800 p-8 text-center">
<p className="text-gray-500">Gestão de Pagamentos e Cobranças em breve</p>
</div>
</div>
</SolutionGuard>
);
}

View File

@@ -0,0 +1,5 @@
import { redirect } from 'next/navigation';
export default function AgencyRootPage() {
redirect('/dashboard');
}

View File

@@ -0,0 +1,16 @@
'use client';
import { SolutionGuard } from '@/components/auth/SolutionGuard';
export default function ProjetosPage() {
return (
<SolutionGuard requiredSolution="projetos">
<div className="p-6">
<h1 className="text-2xl font-bold text-gray-900 dark:text-white mb-4">Projetos</h1>
<div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-800 p-8 text-center">
<p className="text-gray-500">Gestão de Projetos em breve</p>
</div>
</div>
</SolutionGuard>
);
}

View File

@@ -0,0 +1,16 @@
'use client';
import { SolutionGuard } from '@/components/auth/SolutionGuard';
export default function SocialPage() {
return (
<SolutionGuard requiredSolution="social">
<div className="p-6">
<h1 className="text-2xl font-bold text-gray-900 dark:text-white mb-4">Gestão de Redes Sociais</h1>
<div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-800 p-8 text-center">
<p className="text-gray-500">Planejamento e Publicação de Posts em breve</p>
</div>
</div>
</SolutionGuard>
);
}

View File

@@ -1,14 +1,26 @@
"use client";
import { useState } from "react";
import { useState, useEffect } from "react";
import Link from "next/link";
import { Button, Input } from "@/components/ui";
import toast, { Toaster } from 'react-hot-toast';
import { EnvelopeIcon } from "@heroicons/react/24/outline";
export default function RecuperarSenhaPage() {
const [isLoading, setIsLoading] = useState(false);
const [email, setEmail] = useState("");
const [emailSent, setEmailSent] = useState(false);
const [subdomain, setSubdomain] = useState<string>('');
const [isSuperAdmin, setIsSuperAdmin] = useState(false);
useEffect(() => {
if (typeof window !== 'undefined') {
const hostname = window.location.hostname;
const sub = hostname.split('.')[0];
setSubdomain(sub);
setIsSuperAdmin(sub === 'dash');
}
}, []);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
@@ -77,8 +89,10 @@ export default function RecuperarSenhaPage() {
<div className="w-full max-w-md">
{/* Logo mobile */}
<div className="lg:hidden text-center mb-8">
<div className="inline-block px-6 py-3 rounded-2xl" style={{ background: 'var(--gradient-primary)' }}>
<h1 className="text-3xl font-bold text-white">aggios</h1>
<div className="inline-block px-6 py-3 rounded-2xl" style={{ background: 'var(--brand-color)' }}>
<h1 className="text-3xl font-bold text-white">
{isSuperAdmin ? 'aggios' : subdomain}
</h1>
</div>
</div>
@@ -100,7 +114,7 @@ export default function RecuperarSenhaPage() {
label="Email"
type="email"
placeholder="seu@email.com"
leftIcon="ri-mail-line"
leftIcon={<EnvelopeIcon className="w-5 h-5" />}
value={email}
onChange={(e) => setEmail(e.target.value)}
required
@@ -109,142 +123,71 @@ export default function RecuperarSenhaPage() {
<Button
type="submit"
variant="primary"
className="w-full"
size="lg"
className="w-full"
isLoading={isLoading}
>
Enviar link de recuperação
</Button>
</form>
{/* Back to login */}
<div className="mt-6 text-center">
<Link
href="/login"
className="text-[14px] gradient-text hover:underline inline-flex items-center gap-2 font-medium cursor-pointer"
>
<i className="ri-arrow-left-line" />
Voltar para o login
</Link>
</div>
<div className="text-center">
<Link
href="/login"
className="text-[14px] font-medium hover:opacity-80 transition-opacity"
style={{ color: 'var(--brand-color)' }}
>
Voltar para o login
</Link>
</div>
</form>
</>
) : (
<>
{/* Success Message */}
<div className="text-center">
<div className="w-20 h-20 rounded-full bg-[#10B981]/10 flex items-center justify-center mx-auto mb-6">
<i className="ri-mail-check-line text-4xl text-[#10B981]" />
</div>
<h2 className="text-[28px] font-bold text-zinc-900 dark:text-white mb-4">
Email enviado!
</h2>
<p className="text-[14px] text-zinc-600 dark:text-zinc-400 mb-2">
Enviamos um link de recuperação para:
</p>
<p className="text-[16px] font-semibold text-zinc-900 dark:text-white mb-6">
{email}
</p>
<div className="p-6 bg-[#F0F9FF] border border-[#BAE6FD] rounded-md text-left mb-6">
<div className="flex gap-4">
<i className="ri-information-line text-[#ff3a05] text-xl mt-0.5" />
<div>
<h4 className="text-sm font-semibold text-zinc-900 dark:text-white mb-1">
Verifique sua caixa de entrada
</h4>
<p className="text-xs text-zinc-600 dark:text-zinc-400">
Clique no link que enviamos para redefinir sua senha.
Se não receber em alguns minutos, verifique sua pasta de spam.
</p>
</div>
</div>
</div>
<Button
variant="outline"
className="w-full mb-4"
onClick={() => setEmailSent(false)}
>
Enviar novamente
</Button>
<div className="text-center">
<div className="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-6">
<i className="ri-mail-check-line text-3xl text-green-600"></i>
</div>
<h2 className="text-[24px] font-bold text-zinc-900 dark:text-white mb-2">
Verifique seu email
</h2>
<p className="text-zinc-600 dark:text-zinc-400 mb-8">
Enviamos um link de recuperação para <strong>{email}</strong>
</p>
<Button
variant="outline"
className="w-full"
onClick={() => setEmailSent(false)}
>
Tentar outro email
</Button>
<div className="mt-6">
<Link
href="/login"
className="text-[14px] gradient-text hover:underline inline-flex items-center gap-2 font-medium cursor-pointer"
className="text-[14px] font-medium hover:opacity-80 transition-opacity"
style={{ color: 'var(--brand-color)' }}
>
<i className="ri-arrow-left-line" />
Voltar para o login
</Link>
</div>
</>
</div>
)}
</div>
</div>
{/* Lado Direito - Branding */}
<div className="hidden lg:flex lg:w-1/2 relative overflow-hidden" style={{ background: 'var(--gradient-primary)' }}>
<div className="relative z-10 flex flex-col justify-center items-center w-full p-12 text-white">
{/* Logo */}
<div className="mb-8">
<div className="inline-block px-6 py-3 rounded-2xl bg-white/10 backdrop-blur-sm border border-white/20">
<h1 className="text-5xl font-bold tracking-tight text-white">
aggios
</h1>
</div>
</div>
{/* Conteúdo */}
<div className="max-w-lg text-center">
<div className="w-20 h-20 rounded-2xl bg-white/20 flex items-center justify-center mb-6 mx-auto">
<i className="ri-lock-password-line text-4xl" />
</div>
<h2 className="text-4xl font-bold mb-4">Recuperação segura</h2>
<p className="text-white/80 text-lg mb-8">
Protegemos seus dados com os mais altos padrões de segurança.
Seu link de recuperação é único e expira em 24 horas.
<div className="hidden lg:flex lg:w-1/2 relative overflow-hidden" style={{ background: 'var(--brand-color)' }}>
<div className="absolute inset-0 flex flex-col items-center justify-center p-12 text-white">
<div className="max-w-md text-center">
<h1 className="text-5xl font-bold mb-6">
{isSuperAdmin ? 'aggios' : subdomain}
</h1>
<p className="text-xl opacity-90">
Recupere o acesso à sua conta de forma segura e rápida.
</p>
{/* Features */}
<div className="space-y-4 text-left">
<div className="flex items-start gap-3">
<div className="w-6 h-6 rounded-full bg-white/20 flex items-center justify-center shrink-0 mt-0.5">
<i className="ri-shield-check-line text-sm" />
</div>
<div>
<h4 className="font-semibold mb-1">Criptografia de ponta</h4>
<p className="text-white/70 text-sm">Seus dados são protegidos com tecnologia de última geração</p>
</div>
</div>
<div className="flex items-start gap-3">
<div className="w-6 h-6 rounded-full bg-white/20 flex items-center justify-center shrink-0 mt-0.5">
<i className="ri-time-line text-sm" />
</div>
<div>
<h4 className="font-semibold mb-1">Link temporário</h4>
<p className="text-white/70 text-sm">O link expira em 24h para sua segurança</p>
</div>
</div>
<div className="flex items-start gap-3">
<div className="w-6 h-6 rounded-full bg-white/20 flex items-center justify-center shrink-0 mt-0.5">
<i className="ri-customer-service-2-line text-sm" />
</div>
<div>
<h4 className="font-semibold mb-1">Suporte disponível</h4>
<p className="text-white/70 text-sm">Nossa equipe está pronta para ajudar caso precise</p>
</div>
</div>
</div>
</div>
</div>
{/* Círculos decorativos */}
<div className="absolute top-0 right-0 w-96 h-96 bg-white/5 rounded-full blur-3xl" />
<div className="absolute bottom-0 left-0 w-96 h-96 bg-white/5 rounded-full blur-3xl" />
</div>
</div>
</>
);
}

View File

@@ -0,0 +1,7 @@
'use client';
import { ToastProvider } from '@/components/layout/ToastContext';
export function ClientProviders({ children }: { children: React.ReactNode }) {
return <ToastProvider>{children}</ToastProvider>;
}

View File

@@ -1,25 +1,53 @@
'use client';
import { ReactNode } from 'react';
import { useEffect } from 'react';
import { usePathname } from 'next/navigation';
const DEFAULT_GRADIENT = 'linear-gradient(135deg, #ff3a05, #ff0080)';
// Helper to lighten color
const lightenColor = (color: string, percent: number) => {
const num = parseInt(color.replace("#", ""), 16),
amt = Math.round(2.55 * percent),
R = (num >> 16) + amt,
B = ((num >> 8) & 0x00ff) + amt,
G = (num & 0x0000ff) + amt;
return (
"#" +
(
0x1000000 +
(R < 255 ? (R < 1 ? 0 : R) : 255) * 0x10000 +
(B < 255 ? (B < 1 ? 0 : B) : 255) * 0x100 +
(G < 255 ? (G < 1 ? 0 : G) : 255)
)
.toString(16)
.slice(1)
);
};
const setGradientVariables = (gradient: string) => {
document.documentElement.style.setProperty('--gradient-primary', gradient);
document.documentElement.style.setProperty('--gradient', gradient);
document.documentElement.style.setProperty('--gradient-text', gradient.replace('90deg', 'to right'));
document.documentElement.style.setProperty('--color-gradient-brand', gradient.replace('90deg', 'to right'));
const setBrandColors = (primary: string, secondary: string) => {
document.documentElement.style.setProperty('--brand-color', primary);
document.documentElement.style.setProperty('--brand-color-strong', secondary);
// Create a lighter version of primary for hover
const primaryLight = lightenColor(primary, 20); // Lighten by 20%
document.documentElement.style.setProperty('--brand-color-hover', primaryLight);
// Set RGB variables if needed by other components
const hexToRgb = (hex: string) => {
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? `${parseInt(result[1], 16)} ${parseInt(result[2], 16)} ${parseInt(result[3], 16)}` : null;
};
const primaryRgb = hexToRgb(primary);
const secondaryRgb = hexToRgb(secondary);
const primaryLightRgb = hexToRgb(primaryLight);
if (primaryRgb) document.documentElement.style.setProperty('--brand-rgb', primaryRgb);
if (secondaryRgb) document.documentElement.style.setProperty('--brand-strong-rgb', secondaryRgb);
if (primaryLightRgb) document.documentElement.style.setProperty('--brand-hover-rgb', primaryLightRgb);
};
export default function LayoutWrapper({ children }: { children: ReactNode }) {
const pathname = usePathname();
useEffect(() => {
// Em toda troca de rota, volta para o tema padrão; layouts específicos (ex.: agência) aplicam o próprio na sequência
setGradientVariables(DEFAULT_GRADIENT);
}, [pathname]);
// Temporariamente desativado o carregamento dinâmico de cores/tema para eliminar possíveis
// efeitos colaterais de hidratação e 429 no middleware/backend. Se precisar reativar, mover
// para nível de servidor (next/head ou metadata) para evitar mutações de DOM no cliente.
return <>{children}</>;
}

View File

@@ -4,19 +4,33 @@ const BACKEND_URL = process.env.API_INTERNAL_URL || 'http://aggios-backend:8080'
export async function POST(request: NextRequest) {
try {
console.log('🔵 [Next.js] Logo upload route called');
const authorization = request.headers.get('authorization');
if (!authorization) {
console.log('❌ [Next.js] No authorization header');
return NextResponse.json(
{ error: 'Unauthorized' },
{ status: 401 }
);
}
console.log('✅ [Next.js] Authorization header present');
// Get form data from request
const formData = await request.formData();
const logo = formData.get('logo');
const type = formData.get('type');
console.log('Forwarding logo upload to backend:', BACKEND_URL);
console.log('📦 [Next.js] FormData received:', {
hasLogo: !!logo,
logoType: logo ? (logo as File).type : null,
logoSize: logo ? (logo as File).size : null,
type: type
});
console.log('🚀 [Next.js] Forwarding to backend:', BACKEND_URL);
// Forward to backend
const response = await fetch(`${BACKEND_URL}/api/agency/logo`, {
@@ -27,7 +41,7 @@ export async function POST(request: NextRequest) {
body: formData,
});
console.log('Backend response status:', response.status);
console.log('📡 [Next.js] Backend response status:', response.status);
if (!response.ok) {
const errorText = await response.text();

View File

@@ -0,0 +1,51 @@
import { NextRequest, NextResponse } from 'next/server';
const API_BASE_URL = process.env.API_INTERNAL_URL || 'http://backend:8080';
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url);
const subdomain = searchParams.get('subdomain');
if (!subdomain) {
return NextResponse.json(
{ error: 'Subdomain is required' },
{ status: 400 }
);
}
// Buscar configuração pública do tenant
const response = await fetch(
`${API_BASE_URL}/api/tenant/config?subdomain=${subdomain}`,
{
cache: 'no-store',
headers: {
'Content-Type': 'application/json',
},
}
);
if (!response.ok) {
return NextResponse.json(
{ error: 'Tenant not found' },
{ status: 404 }
);
}
const data = await response.json();
// Retornar apenas dados públicos
return NextResponse.json({
name: data.name,
primary_color: data.primary_color,
secondary_color: data.secondary_color,
logo_url: data.logo_url,
});
} catch (error) {
console.error('Error fetching tenant config:', error);
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
);
}
}

View File

@@ -47,7 +47,7 @@ html.dark {
@layer base {
* {
font-family: var(--font-inter), ui-sans-serif, system-ui, sans-serif;
font-family: var(--font-arimo), ui-sans-serif, system-ui, sans-serif;
}
a,
@@ -67,16 +67,16 @@ html.dark {
}
::selection {
background-color: var(--color-brand-500);
color: var(--color-text-inverse);
background-color: var(--color-brand-100);
color: var(--color-text-primary);
}
/* Seleção em campos de formulário usa o gradiente padrão da marca */
/* Seleção em campos de formulário usa cor mais visível */
input::selection,
textarea::selection,
select::selection {
background: var(--color-gradient-brand);
color: var(--color-text-inverse);
background-color: var(--color-brand-200);
color: var(--color-text-primary);
}
.surface-card {
@@ -181,3 +181,14 @@ html.dark {
@apply bg-background text-foreground;
}
}
@layer utilities {
.scrollbar-hide::-webkit-scrollbar {
display: none;
}
.scrollbar-hide {
-ms-overflow-style: none;
scrollbar-width: none;
}
}

View File

@@ -1,11 +1,13 @@
import type { Metadata } from "next";
import { Inter, Open_Sans, Fira_Code } from "next/font/google";
import { Arimo, Open_Sans, Fira_Code } from "next/font/google";
import "./globals.css";
import LayoutWrapper from "./LayoutWrapper";
import { ThemeProvider } from "next-themes";
import { getAgencyLogo } from "@/lib/server-api";
import { ClientProviders } from "./ClientProviders";
const inter = Inter({
variable: "--font-inter",
const arimo = Arimo({
variable: "--font-arimo",
subsets: ["latin"],
weight: ["400", "500", "600", "700"],
});
@@ -22,10 +24,24 @@ const firaCode = Fira_Code({
weight: ["400", "600"],
});
export const metadata: Metadata = {
title: "Aggios - Dashboard",
description: "Plataforma SaaS para agências digitais",
};
export async function generateMetadata(): Promise<Metadata> {
const logoUrl = await getAgencyLogo();
// Adicionar timestamp para forçar atualização do favicon
const faviconUrl = logoUrl
? `${logoUrl}?v=${Date.now()}`
: '/favicon.ico';
return {
title: "Aggios - Dashboard",
description: "Plataforma SaaS para agências digitais",
icons: {
icon: faviconUrl,
shortcut: faviconUrl,
apple: faviconUrl,
},
};
}
export default function RootLayout({
children,
@@ -37,11 +53,13 @@ export default function RootLayout({
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/remixicon@4.3.0/fonts/remixicon.css" />
</head>
<body className={`${inter.variable} ${openSans.variable} ${firaCode.variable} antialiased`}>
<body className={`${arimo.variable} ${openSans.variable} ${firaCode.variable} antialiased`} suppressHydrationWarning>
<ThemeProvider attribute="class" defaultTheme="light" enableSystem={false}>
<LayoutWrapper>
{children}
</LayoutWrapper>
<ClientProviders>
<LayoutWrapper>
{children}
</LayoutWrapper>
</ClientProviders>
</ThemeProvider>
</body>
</html>

View File

@@ -3,25 +3,29 @@
import { useState, useEffect } from "react";
import Link from "next/link";
import { Button, Input, Checkbox } from "@/components/ui";
import toast, { Toaster } from 'react-hot-toast';
import { saveAuth, isAuthenticated } from '@/lib/auth';
import { saveAuth, isAuthenticated, getToken, clearAuth } from '@/lib/auth';
import { API_ENDPOINTS } from '@/lib/api';
import dynamic from 'next/dynamic';
import { LoginBranding } from '@/components/auth/LoginBranding';
import {
EnvelopeIcon,
LockClosedIcon,
ShieldCheckIcon,
BoltIcon,
UserGroupIcon,
ChartBarIcon,
ExclamationCircleIcon,
CheckCircleIcon
} from "@heroicons/react/24/outline";
const ThemeToggle = dynamic(() => import('@/components/ThemeToggle'), { ssr: false });
const DEFAULT_GRADIENT = 'linear-gradient(135deg, #ff3a05, #ff0080)';
const setGradientVariables = (gradient: string) => {
document.documentElement.style.setProperty('--gradient-primary', gradient);
document.documentElement.style.setProperty('--gradient', gradient);
document.documentElement.style.setProperty('--gradient-text', gradient.replace('90deg', 'to right'));
document.documentElement.style.setProperty('--color-gradient-brand', gradient.replace('90deg', 'to right'));
};
export default function LoginPage() {
const [isLoading, setIsLoading] = useState(false);
const [isSuperAdmin, setIsSuperAdmin] = useState(false);
const [subdomain, setSubdomain] = useState<string>('');
const [errorMessage, setErrorMessage] = useState<string>('');
const [successMessage, setSuccessMessage] = useState<string>('');
const [formData, setFormData] = useState({
email: "",
password: "",
@@ -36,44 +40,66 @@ export default function LoginPage() {
setSubdomain(sub);
setIsSuperAdmin(superAdmin);
// Aplicar tema: dash sempre padrão; tenants aplicam o salvo ou vindo via query param
const searchParams = new URLSearchParams(window.location.search);
const themeParam = searchParams.get('theme');
if (superAdmin) {
setGradientVariables(DEFAULT_GRADIENT);
} else {
const stored = localStorage.getItem(`agency-theme:${sub}`);
const gradient = themeParam || stored || DEFAULT_GRADIENT;
setGradientVariables(gradient);
if (themeParam) {
localStorage.setItem(`agency-theme:${sub}`, gradient);
}
// Verificar se tem parâmetro de erro de tenant não encontrado
const urlParams = new URLSearchParams(window.location.search);
if (urlParams.get('error') === 'tenant_not_found') {
console.log('⚠️ Tenant não encontrado, limpando autenticação...');
clearAuth();
localStorage.removeItem('agency-logo-url');
localStorage.removeItem('agency-primary-color');
localStorage.removeItem('agency-secondary-color');
setErrorMessage('Esta agência não existe mais ou foi desativada.');
return;
}
if (isAuthenticated()) {
const target = superAdmin ? '/superadmin' : '/dashboard';
window.location.href = target;
// Validar token antes de redirecionar para evitar loops
const token = getToken();
fetch(API_ENDPOINTS.me, {
headers: {
'Authorization': `Bearer ${token}`
}
})
.then(res => {
if (res.ok) {
const target = superAdmin ? '/superadmin' : '/dashboard';
window.location.href = target;
} else {
// Token inválido ou expirado
clearAuth();
}
})
.catch((err) => {
console.error('Erro ao validar sessão:', err);
// Em caso de erro de rede, não redireciona nem limpa, deixa o usuário tentar logar
});
}
}
}, []);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setErrorMessage('');
setSuccessMessage('');
// Validações do lado do cliente
if (!formData.email) {
toast.error('Por favor, insira seu email');
setErrorMessage('Por favor, insira seu email para continuar.');
return;
}
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
toast.error('Por favor, insira um email válido');
setErrorMessage('Ops! O formato do email não parece correto. Por favor, verifique e tente novamente.');
return;
}
if (!formData.password) {
toast.error('Por favor, insira sua senha');
setErrorMessage('Por favor, insira sua senha para acessar sua conta.');
return;
}
if (formData.password.length < 3) {
setErrorMessage('A senha parece muito curta. Por favor, verifique se digitou corretamente.');
return;
}
@@ -92,8 +118,19 @@ export default function LoginPage() {
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.message || 'Credenciais inválidas');
const error = await response.json().catch(() => ({}));
// Mensagens humanizadas para cada tipo de erro
if (response.status === 401 || response.status === 403) {
setErrorMessage('Email ou senha incorretos. Por favor, verifique seus dados e tente novamente.');
} else if (response.status >= 500) {
setErrorMessage('Estamos com problemas no servidor no momento. Por favor, tente novamente em alguns instantes.');
} else {
setErrorMessage(error.message || 'Algo deu errado ao tentar fazer login. Por favor, tente novamente.');
}
setIsLoading(false);
return;
}
const data = await response.json();
@@ -102,57 +139,60 @@ export default function LoginPage() {
console.log('Login successful:', data.user);
toast.success('Login realizado com sucesso! Redirecionando...');
setSuccessMessage('Login realizado com sucesso! Redirecionando você agora...');
setTimeout(() => {
const target = isSuperAdmin ? '/superadmin' : '/dashboard';
window.location.href = target;
}, 1000);
} catch (error: any) {
toast.error(error.message || 'Erro ao fazer login. Verifique suas credenciais.');
console.error('Login error:', error);
setErrorMessage('Não conseguimos conectar ao servidor. Verifique sua conexão com a internet e tente novamente.');
setIsLoading(false);
}
};
return (
<>
<Toaster
position="top-center"
toastOptions={{
duration: 5000,
style: {
background: '#FFFFFF',
color: '#000000',
padding: '16px',
borderRadius: '8px',
border: '1px solid #E5E5E5',
boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
},
error: {
icon: '⚠️',
style: {
background: '#ef4444',
color: '#FFFFFF',
border: 'none',
},
},
success: {
icon: '✓',
style: {
background: '#10B981',
color: '#FFFFFF',
border: 'none',
},
},
{/* Script inline para aplicar cor primária ANTES do React */}
<script
dangerouslySetInnerHTML={{
__html: `
(function() {
try {
const cachedPrimary = localStorage.getItem('agency-primary-color');
if (cachedPrimary) {
function hexToRgb(hex) {
const result = /^#?([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})$/i.exec(hex);
return result
? parseInt(result[1], 16) + ' ' + parseInt(result[2], 16) + ' ' + parseInt(result[3], 16)
: null;
}
const primaryRgb = hexToRgb(cachedPrimary);
if (primaryRgb) {
const root = document.documentElement;
root.style.setProperty('--brand-color', cachedPrimary);
root.style.setProperty('--gradient', 'linear-gradient(135deg, ' + cachedPrimary + ', ' + cachedPrimary + ')');
root.style.setProperty('--brand-rgb', primaryRgb);
root.style.setProperty('--brand-strong-rgb', primaryRgb);
root.style.setProperty('--brand-hover-rgb', primaryRgb);
}
}
} catch(e) {}
})();
`,
}}
/>
<LoginBranding />
<div className="flex min-h-screen">
{/* Lado Esquerdo - Formulário */}
<div className="w-full lg:w-1/2 flex items-center justify-center px-6 sm:px-12 py-12">
<div className="w-full max-w-md">
{/* Logo mobile */}
<div className="lg:hidden text-center mb-8">
<div className="inline-block px-6 py-3 rounded-2xl" style={{ background: 'var(--gradient-primary)' }}>
<div className="inline-block px-6 py-3 rounded-2xl" style={{ background: 'var(--brand-color)' }}>
<h1 className="text-3xl font-bold text-white">
{isSuperAdmin ? 'aggios' : subdomain}
</h1>
@@ -179,13 +219,36 @@ export default function LoginPage() {
{/* Form */}
<form onSubmit={handleSubmit} className="space-y-5">
{/* Mensagem de Erro */}
{errorMessage && (
<div className="flex items-start gap-3 p-4 rounded-lg bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800">
<ExclamationCircleIcon className="w-5 h-5 text-red-600 dark:text-red-400 flex-shrink-0 mt-0.5" />
<p className="text-sm text-red-800 dark:text-red-300 leading-relaxed">
{errorMessage}
</p>
</div>
)}
{/* Mensagem de Sucesso */}
{successMessage && (
<div className="flex items-start gap-3 p-4 rounded-lg bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800">
<CheckCircleIcon className="w-5 h-5 text-green-600 dark:text-green-400 flex-shrink-0 mt-0.5" />
<p className="text-sm text-green-800 dark:text-green-300 leading-relaxed">
{successMessage}
</p>
</div>
)}
<Input
label="Email"
type="email"
placeholder="seu@email.com"
leftIcon="ri-mail-line"
leftIcon={<EnvelopeIcon className="w-5 h-5" />}
value={formData.email}
onChange={(e) => setFormData({ ...formData, email: e.target.value })}
onChange={(e) => {
setFormData({ ...formData, email: e.target.value });
setErrorMessage(''); // Limpa o erro ao digitar
}}
required
/>
@@ -193,9 +256,12 @@ export default function LoginPage() {
label="Senha"
type="password"
placeholder="Digite sua senha"
leftIcon="ri-lock-line"
leftIcon={<LockClosedIcon className="w-5 h-5" />}
value={formData.password}
onChange={(e) => setFormData({ ...formData, password: e.target.value })}
onChange={(e) => {
setFormData({ ...formData, password: e.target.value });
setErrorMessage(''); // Limpa o erro ao digitar
}}
required
/>
@@ -209,7 +275,7 @@ export default function LoginPage() {
<Link
href="/recuperar-senha"
className="text-[14px] font-medium hover:opacity-80 transition-opacity"
style={{ background: 'var(--gradient-primary)', WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent' }}
style={{ color: 'var(--brand-color)' }}
>
Esqueceu a senha?
</Link>
@@ -232,7 +298,7 @@ export default function LoginPage() {
<a
href="http://dash.localhost/cadastro"
className="font-medium hover:opacity-80 transition-opacity"
style={{ background: 'var(--gradient-primary)', WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent' }}
style={{ color: 'var(--brand-color)' }}
>
Cadastre sua agência
</a>
@@ -243,7 +309,7 @@ export default function LoginPage() {
</div>
{/* Lado Direito - Branding */}
<div className="hidden lg:flex lg:w-1/2 relative overflow-hidden" style={{ background: 'var(--gradient-primary)' }}>
<div className="hidden lg:flex lg:w-1/2 relative overflow-hidden" style={{ background: 'var(--brand-color)' }}>
<div className="absolute inset-0 flex flex-col items-center justify-center p-12 text-white">
<div className="max-w-md text-center">
<h1 className="text-5xl font-bold mb-6">
@@ -257,22 +323,22 @@ export default function LoginPage() {
</p>
<div className="grid grid-cols-2 gap-6 text-left">
<div>
<i className="ri-shield-check-line text-3xl mb-2"></i>
<ShieldCheckIcon className="w-8 h-8 mb-2" />
<h3 className="font-semibold mb-1">Seguro</h3>
<p className="text-sm opacity-80">Proteção de dados</p>
</div>
<div>
<i className="ri-speed-line text-3xl mb-2"></i>
<BoltIcon className="w-8 h-8 mb-2" />
<h3 className="font-semibold mb-1">Rápido</h3>
<p className="text-sm opacity-80">Performance otimizada</p>
</div>
<div>
<i className="ri-team-line text-3xl mb-2"></i>
<UserGroupIcon className="w-8 h-8 mb-2" />
<h3 className="font-semibold mb-1">Colaborativo</h3>
<p className="text-sm opacity-80">Trabalho em equipe</p>
</div>
<div>
<i className="ri-line-chart-line text-3xl mb-2"></i>
<ChartBarIcon className="w-8 h-8 mb-2" />
<h3 className="font-semibold mb-1">Insights</h3>
<p className="text-sm opacity-80">Relatórios detalhados</p>
</div>

View File

@@ -9,6 +9,20 @@
/* Cores sólidas de marca (usadas em textos/bordas) */
--brand-color: #ff3a05;
--brand-color-strong: #ff0080;
--brand-rgb: 255 58 5;
--brand-strong-rgb: 255 0 128;
/* Escala de cores da marca */
--color-brand-50: #fff1f0;
--color-brand-100: #ffe0dd;
--color-brand-200: #ffc7c0;
--color-brand-300: #ffa094;
--color-brand-400: #ff6b57;
--color-brand-500: #ff3a05;
--color-brand-600: #ff0080;
--color-brand-700: #d6006a;
--color-brand-800: #ad0058;
--color-brand-900: #8a004a;
/* Superfícies e tipografia */
--color-surface-light: #ffffff;
@@ -50,5 +64,17 @@
--color-text-primary: #f8fafc;
--color-text-secondary: #cbd5f5;
--color-text-inverse: #0f172a;
/* Cores da marca com maior contraste para dark mode */
--color-brand-50: #4a0029;
--color-brand-100: #660037;
--color-brand-200: #8a004a;
--color-brand-300: #ad0058;
--color-brand-400: #d6006a;
--color-brand-500: #ff0080;
--color-brand-600: #ff3a05;
--color-brand-700: #ff6b57;
--color-brand-800: #ffa094;
--color-brand-900: #ffc7c0;
}
}

View File

@@ -1,33 +1,42 @@
"use client";
import { useEffect } from 'react';
import { useEffect, useState } from 'react';
interface DynamicFaviconProps {
logoUrl?: string;
}
export default function DynamicFavicon({ logoUrl }: DynamicFaviconProps) {
const [mounted, setMounted] = useState(false);
useEffect(() => {
if (!logoUrl) return;
setMounted(true);
}, []);
// Remove favicons antigos
const existingLinks = document.querySelectorAll("link[rel*='icon']");
existingLinks.forEach(link => link.remove());
useEffect(() => {
if (!mounted || !logoUrl) return;
// Adiciona novo favicon
const link = document.createElement('link');
link.type = 'image/x-icon';
link.rel = 'shortcut icon';
link.href = logoUrl;
document.getElementsByTagName('head')[0].appendChild(link);
// Usar requestAnimationFrame para garantir que a hidratação terminou
requestAnimationFrame(() => {
// Remove favicons antigos
const existingLinks = document.querySelectorAll("link[rel*='icon']");
existingLinks.forEach(link => link.remove());
// Adiciona Apple touch icon
const appleLink = document.createElement('link');
appleLink.rel = 'apple-touch-icon';
appleLink.href = logoUrl;
document.getElementsByTagName('head')[0].appendChild(appleLink);
// Adiciona novo favicon
const link = document.createElement('link');
link.type = 'image/x-icon';
link.rel = 'shortcut icon';
link.href = logoUrl;
document.getElementsByTagName('head')[0].appendChild(link);
}, [logoUrl]);
// Adiciona Apple touch icon
const appleLink = document.createElement('link');
appleLink.rel = 'apple-touch-icon';
appleLink.href = logoUrl;
document.getElementsByTagName('head')[0].appendChild(appleLink);
});
}, [mounted, logoUrl]);
return null;
}

View File

@@ -0,0 +1,65 @@
'use client';
import { useEffect, useState } from 'react';
import { useRouter, usePathname } from 'next/navigation';
import { isAuthenticated, clearAuth } from '@/lib/auth';
export default function AuthGuard({ children }: { children: React.ReactNode }) {
const router = useRouter();
const pathname = usePathname();
const [authorized, setAuthorized] = useState<boolean | null>(null);
const [mounted, setMounted] = useState(false);
useEffect(() => {
setMounted(true);
}, []);
useEffect(() => {
if (!mounted) return;
const checkAuth = () => {
const isAuth = isAuthenticated();
if (!isAuth) {
setAuthorized(false);
// Evitar redirect loop se já estiver no login
if (pathname !== '/login') {
router.push('/login?error=unauthorized');
}
} else {
setAuthorized(true);
}
};
checkAuth();
// Listener para logout em outras abas
const handleStorageChange = (e: StorageEvent) => {
if (e.key === 'token' || e.key === 'user') {
checkAuth();
}
};
window.addEventListener('storage', handleStorageChange);
return () => window.removeEventListener('storage', handleStorageChange);
}, [router, pathname, mounted]);
// Enquanto verifica, mostra loading
if (!mounted || authorized === null) {
return (
<div className="flex h-screen w-full items-center justify-center bg-gray-100 dark:bg-zinc-950">
<div className="h-8 w-8 animate-spin rounded-full border-4 border-gray-300 border-t-purple-600" />
</div>
);
}
if (!authorized) {
return (
<div className="flex h-screen w-full items-center justify-center bg-gray-100 dark:bg-zinc-950">
<div className="h-8 w-8 animate-spin rounded-full border-4 border-gray-300 border-t-purple-600" />
</div>
);
}
return <>{children}</>;
}

View File

@@ -0,0 +1,120 @@
'use client';
import { useEffect } from 'react';
/**
* LoginBranding - Aplica cor primária da agência na página de login
* Busca cor do localStorage ou da API se não houver cache
*/
export function LoginBranding() {
useEffect(() => {
const hexToRgb = (hex: string) => {
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? `${parseInt(result[1], 16)} ${parseInt(result[2], 16)} ${parseInt(result[3], 16)}` : null;
};
const applyTheme = (primary: string) => {
if (!primary) return;
const root = document.documentElement;
const primaryRgb = hexToRgb(primary);
root.style.setProperty('--brand-color', primary);
root.style.setProperty('--gradient', `linear-gradient(135deg, ${primary}, ${primary})`);
if (primaryRgb) {
root.style.setProperty('--brand-rgb', primaryRgb);
root.style.setProperty('--brand-strong-rgb', primaryRgb);
root.style.setProperty('--brand-hover-rgb', primaryRgb);
}
};
const updateFavicon = (url: string) => {
if (typeof window === 'undefined' || typeof document === 'undefined') return;
try {
const newHref = `${url}${url.includes('?') ? '&' : '?'}v=${Date.now()}`;
const existingLinks = document.querySelectorAll("link[rel*='icon']");
if (existingLinks.length > 0) {
existingLinks.forEach(link => {
link.setAttribute('href', newHref);
});
} else {
const newLink = document.createElement('link');
newLink.rel = 'icon';
newLink.type = 'image/x-icon';
newLink.href = newHref;
document.head.appendChild(newLink);
}
} catch (error) {
console.error('❌ Erro ao atualizar favicon:', error);
}
};
const loadBranding = async () => {
if (typeof window === 'undefined') return;
const hostname = window.location.hostname;
const subdomain = hostname.split('.')[0];
// Para dash.localhost ou localhost sem subdomínio, não buscar
if (!subdomain || subdomain === 'localhost' || subdomain === 'www' || subdomain === 'dash') {
return;
}
try {
// 1. Buscar DIRETO do backend (bypass da rota Next.js que está com problema)
console.log('LoginBranding: Buscando cores para:', subdomain);
const apiUrl = `/api/tenant/config?subdomain=${subdomain}`;
console.log('LoginBranding: URL:', apiUrl);
const response = await fetch(apiUrl);
if (response.ok) {
const data = await response.json();
if (data.primary_color) {
applyTheme(data.primary_color);
localStorage.setItem('agency-primary-color', data.primary_color);
}
if (data.logo_url) {
updateFavicon(data.logo_url);
localStorage.setItem('agency-logo-url', data.logo_url);
}
return;
} else {
console.error('LoginBranding: API retornou:', response.status);
}
// 2. Fallback para cache
const cachedPrimary = localStorage.getItem('agency-primary-color');
const cachedLogo = localStorage.getItem('agency-logo-url');
if (cachedPrimary) {
applyTheme(cachedPrimary);
}
if (cachedLogo) {
updateFavicon(cachedLogo);
}
} catch (error) {
console.error('LoginBranding: Erro:', error);
const cachedPrimary = localStorage.getItem('agency-primary-color');
const cachedLogo = localStorage.getItem('agency-logo-url');
if (cachedPrimary) {
applyTheme(cachedPrimary);
}
if (cachedLogo) {
updateFavicon(cachedLogo);
}
}
};
loadBranding();
}, []);
return null;
}

View File

@@ -0,0 +1,74 @@
'use client';
import { useEffect, useState } from 'react';
import { useRouter, usePathname } from 'next/navigation';
import { useToast } from '@/components/layout/ToastContext';
interface SolutionGuardProps {
children: React.ReactNode;
requiredSolution: string; // slug da solução (ex: 'crm', 'erp')
}
export function SolutionGuard({ children, requiredSolution }: SolutionGuardProps) {
const router = useRouter();
const pathname = usePathname();
const { error } = useToast();
const [hasAccess, setHasAccess] = useState<boolean | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const checkAccess = async () => {
try {
const response = await fetch('/api/tenant/solutions', {
headers: {
'Authorization': `Bearer ${localStorage.getItem('token')}`,
},
});
if (response.ok) {
const data = await response.json();
const solutions = data.solutions || [];
const solutionSlugs = solutions.map((s: any) => s.slug.toLowerCase());
// Dashboard é sempre permitido
if (requiredSolution === 'dashboard') {
setHasAccess(true);
} else {
const hasPermission = solutionSlugs.includes(requiredSolution.toLowerCase());
if (!hasPermission) {
// Mostra toast de aviso
error('Acesso Negado', 'Você não tem acesso a este módulo. Contate o suporte para mais informações.');
// Redireciona imediatamente
router.replace('/dashboard');
return;
}
setHasAccess(hasPermission);
}
} else {
// Em caso de erro, redireciona para segurança
error('Erro de Acesso', 'Não foi possível verificar suas permissões. Contate o suporte.');
router.replace('/dashboard');
return;
}
} catch (err) {
// Em caso de erro, redireciona para segurança
error('Erro de Acesso', 'Não foi possível verificar suas permissões. Contate o suporte.');
router.replace('/dashboard');
return;
} finally {
setLoading(false);
}
};
checkAccess();
}, [requiredSolution, router, pathname, error]);
if (loading || hasAccess === false) {
return null;
}
return <>{children}</>;
}

View File

@@ -0,0 +1,152 @@
'use client';
import { useEffect, useState } from 'react';
interface AgencyBrandingProps {
colors?: {
primary: string;
secondary: string;
} | null;
}
/**
* AgencyBranding - Aplica as cores da agência via CSS Variables
* O favicon é atualizado dinamicamente via DOM
*/
export function AgencyBranding({ colors }: AgencyBrandingProps) {
useEffect(() => {
const hexToRgb = (hex: string) => {
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? `${parseInt(result[1], 16)} ${parseInt(result[2], 16)} ${parseInt(result[3], 16)}` : null;
};
const applyTheme = (primary: string, secondary: string) => {
if (!primary || !secondary) return;
const root = document.documentElement;
const primaryRgb = hexToRgb(primary);
const secondaryRgb = hexToRgb(secondary);
const gradient = `linear-gradient(135deg, ${primary}, ${primary})`;
const gradientText = `linear-gradient(to right, ${primary}, ${primary})`;
root.style.setProperty('--gradient', gradient);
root.style.setProperty('--gradient-text', gradientText);
root.style.setProperty('--gradient-primary', gradient);
root.style.setProperty('--color-gradient-brand', gradient);
root.style.setProperty('--brand-color', primary);
root.style.setProperty('--brand-color-strong', secondary);
if (primaryRgb) root.style.setProperty('--brand-rgb', primaryRgb);
if (secondaryRgb) root.style.setProperty('--brand-strong-rgb', secondaryRgb);
// Salvar no localStorage para cache
if (typeof window !== 'undefined') {
const hostname = window.location.hostname;
const sub = hostname.split('.')[0];
if (sub && sub !== 'www') {
localStorage.setItem(`agency-theme:${sub}`, gradient);
localStorage.setItem('agency-primary-color', primary);
localStorage.setItem('agency-secondary-color', secondary);
}
}
};
const updateFavicon = (url: string) => {
if (typeof window === 'undefined' || typeof document === 'undefined') return;
try {
const newHref = `${url}${url.includes('?') ? '&' : '?'}v=${Date.now()}`;
// Buscar TODOS os links de ícone (como estava funcionando antes)
const existingLinks = document.querySelectorAll("link[rel*='icon']");
if (existingLinks.length > 0) {
existingLinks.forEach(link => {
link.setAttribute('href', newHref);
});
console.log(`${existingLinks.length} favicons atualizados`);
} else {
const newLink = document.createElement('link');
newLink.rel = 'icon';
newLink.type = 'image/x-icon';
newLink.href = newHref;
document.head.appendChild(newLink);
console.log('✅ Favicon criado');
}
} catch (error) {
console.error('❌ Erro ao atualizar favicon:', error);
}
};
// Se temos cores do servidor, aplicar imediatamente
if (colors) {
applyTheme(colors.primary, colors.secondary);
} else {
// Fallback: tentar pegar do cache do localStorage
const cachedPrimary = localStorage.getItem('agency-primary-color');
const cachedSecondary = localStorage.getItem('agency-secondary-color');
if (cachedPrimary && cachedSecondary) {
applyTheme(cachedPrimary, cachedSecondary);
}
}
// Atualizar favicon se houver logo salvo
const cachedLogo = localStorage.getItem('agency-logo-url');
if (cachedLogo) {
updateFavicon(cachedLogo);
} else {
// Se não tiver no cache, buscar do backend
const fetchAndUpdateFavicon = async () => {
const token = localStorage.getItem('token');
if (!token) return;
try {
const API_BASE = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8080/api';
const res = await fetch(`${API_BASE}/agency/profile`, {
headers: { 'Authorization': `Bearer ${token}` }
});
if (res.ok) {
const data = await res.json();
if (data.logo_url) {
localStorage.setItem('agency-logo-url', data.logo_url);
updateFavicon(data.logo_url);
console.log('✅ Favicon carregado do backend:', data.logo_url);
}
}
} catch (error) {
console.error('❌ Erro ao buscar logo para favicon:', error);
}
};
fetchAndUpdateFavicon();
}
// Listener para atualizações em tempo real
const handleUpdate = () => {
const cachedPrimary = localStorage.getItem('agency-primary-color');
const cachedSecondary = localStorage.getItem('agency-secondary-color');
const cachedLogo = localStorage.getItem('agency-logo-url');
if (cachedPrimary && cachedSecondary) {
applyTheme(cachedPrimary, cachedSecondary);
}
if (cachedLogo) {
updateFavicon(cachedLogo);
}
};
window.addEventListener('branding-update', handleUpdate);
return () => {
window.removeEventListener('branding-update', handleUpdate);
};
}, [colors]);
// Componente não renderiza nada visualmente (apenas efeitos colaterais)
return null;
}

View File

@@ -0,0 +1,123 @@
import { Fragment } from 'react';
import { Dialog, Transition } from '@headlessui/react';
import { ExclamationTriangleIcon, XMarkIcon } from '@heroicons/react/24/outline';
interface ConfirmDialogProps {
isOpen: boolean;
onClose: () => void;
onConfirm: () => void;
title: string;
message: string;
confirmText?: string;
cancelText?: string;
variant?: 'danger' | 'warning' | 'info';
}
export default function ConfirmDialog({
isOpen,
onClose,
onConfirm,
title,
message,
confirmText = 'Confirmar',
cancelText = 'Cancelar',
variant = 'danger'
}: ConfirmDialogProps) {
const handleConfirm = () => {
onConfirm();
onClose();
};
const variantStyles = {
danger: {
icon: 'bg-red-100 dark:bg-red-900/20',
iconColor: 'text-red-600 dark:text-red-400',
button: 'bg-red-600 hover:bg-red-700 dark:bg-red-700 dark:hover:bg-red-800'
},
warning: {
icon: 'bg-yellow-100 dark:bg-yellow-900/20',
iconColor: 'text-yellow-600 dark:text-yellow-400',
button: 'bg-yellow-600 hover:bg-yellow-700 dark:bg-yellow-700 dark:hover:bg-yellow-800'
},
info: {
icon: 'bg-blue-100 dark:bg-blue-900/20',
iconColor: 'text-blue-600 dark:text-blue-400',
button: 'bg-blue-600 hover:bg-blue-700 dark:bg-blue-700 dark:hover:bg-blue-800'
}
};
const style = variantStyles[variant];
return (
<Transition.Root show={isOpen} as={Fragment}>
<Dialog as="div" className="relative z-50" onClose={onClose}>
<Transition.Child
as={Fragment}
enter="ease-out duration-300"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="ease-in duration-200"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<div className="fixed inset-0 bg-zinc-900/40 backdrop-blur-sm transition-opacity" />
</Transition.Child>
<div className="fixed inset-0 z-10 overflow-y-auto">
<div className="flex min-h-full items-end justify-center p-4 text-center sm:items-center sm:p-0">
<Transition.Child
as={Fragment}
enter="ease-out duration-300"
enterFrom="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
enterTo="opacity-100 translate-y-0 sm:scale-100"
leave="ease-in duration-200"
leaveFrom="opacity-100 translate-y-0 sm:scale-100"
leaveTo="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
>
<Dialog.Panel className="relative transform overflow-hidden rounded-2xl bg-white dark:bg-zinc-900 text-left shadow-xl transition-all sm:my-8 sm:w-full sm:max-w-lg border border-zinc-200 dark:border-zinc-800">
<div className="p-6">
<div className="flex items-start gap-4">
<div className={`flex h-12 w-12 flex-shrink-0 items-center justify-center rounded-xl ${style.icon}`}>
<ExclamationTriangleIcon className={`h-6 w-6 ${style.iconColor}`} />
</div>
<div className="flex-1">
<Dialog.Title className="text-lg font-semibold text-zinc-900 dark:text-white">
{title}
</Dialog.Title>
<p className="mt-2 text-sm text-zinc-600 dark:text-zinc-400">
{message}
</p>
</div>
<button
onClick={onClose}
className="rounded-lg p-1.5 text-zinc-400 hover:text-zinc-600 dark:hover:text-zinc-300 hover:bg-zinc-100 dark:hover:bg-zinc-800 transition-colors"
>
<XMarkIcon className="h-5 w-5" />
</button>
</div>
<div className="mt-6 flex gap-3">
<button
type="button"
onClick={onClose}
className="flex-1 px-4 py-2.5 border border-zinc-200 dark:border-zinc-700 text-zinc-700 dark:text-zinc-300 font-medium rounded-lg hover:bg-zinc-50 dark:hover:bg-zinc-800 transition-colors"
>
{cancelText}
</button>
<button
type="button"
onClick={handleConfirm}
className={`flex-1 px-4 py-2.5 text-white font-medium rounded-lg transition-colors ${style.button}`}
>
{confirmText}
</button>
</div>
</div>
</Dialog.Panel>
</Transition.Child>
</div>
</div>
</Dialog>
</Transition.Root>
);
}

View File

@@ -0,0 +1,52 @@
'use client';
import React, { useState } from 'react';
import { usePathname } from 'next/navigation';
import { SidebarRail, MenuItem } from './SidebarRail';
import { TopBar } from './TopBar';
import { MobileBottomBar } from './MobileBottomBar';
interface DashboardLayoutProps {
children: React.ReactNode;
menuItems: MenuItem[];
}
export const DashboardLayout: React.FC<DashboardLayoutProps> = ({ children, menuItems }) => {
// Estado centralizado do layout
const [isExpanded, setIsExpanded] = useState(true);
const pathname = usePathname();
return (
<div className="flex h-screen w-full bg-gray-100 dark:bg-zinc-950 text-slate-900 dark:text-slate-100 overflow-hidden md:p-3 md:gap-3 transition-colors duration-300">
{/* Sidebar controla seu próprio estado visual via props - Desktop Only */}
<div className="hidden md:flex">
<SidebarRail
isExpanded={isExpanded}
onToggle={() => setIsExpanded(!isExpanded)}
menuItems={menuItems}
/>
</div>
{/* Área de Conteúdo (Children) */}
<main className="flex-1 h-full min-w-0 overflow-hidden flex flex-col bg-gray-50 dark:bg-zinc-900 md:rounded-2xl shadow-lg relative transition-colors duration-300 border border-transparent dark:border-zinc-800"
style={{
backgroundImage: `radial-gradient(circle, rgb(200 200 200 / 0.15) 1px, transparent 1px)`,
backgroundSize: '24px 24px'
}}
>
{/* TopBar com Breadcrumbs e Search */}
<TopBar />
{/* Conteúdo das páginas */}
<div className="flex-1 overflow-auto pb-20 md:pb-0">
<div className="max-w-7xl mx-auto w-full h-full">
{children}
</div>
</div>
</main>
{/* Mobile Bottom Bar */}
<MobileBottomBar />
</div>
);
};

View File

@@ -0,0 +1,54 @@
'use client';
import { useEffect, useState } from 'react';
import { getUser } from '@/lib/auth';
export function FaviconUpdater() {
const [mounted, setMounted] = useState(false);
useEffect(() => {
setMounted(true);
}, []);
useEffect(() => {
if (!mounted) return;
const updateFavicon = () => {
const user = getUser();
if (user?.logoUrl) {
// Usar requestAnimationFrame para garantir que o DOM esteja estável após hidratação
requestAnimationFrame(() => {
const link: HTMLLinkElement = document.querySelector("link[rel*='icon']") || document.createElement('link');
link.type = 'image/x-icon';
link.rel = 'shortcut icon';
link.href = user.logoUrl!;
if (!link.parentNode) {
document.getElementsByTagName('head')[0].appendChild(link);
}
});
}
};
// Atraso pequeno para garantir que a hidratação terminou
const timer = setTimeout(() => {
updateFavicon();
}, 0);
// Ouve mudanças no localStorage
const handleStorage = () => {
requestAnimationFrame(() => updateFavicon());
};
window.addEventListener('storage', handleStorage);
// Custom event para atualização interna na mesma aba
window.addEventListener('auth-update', handleStorage);
return () => {
clearTimeout(timer);
window.removeEventListener('storage', handleStorage);
window.removeEventListener('auth-update', handleStorage);
};
}, [mounted]);
return null;
}

View File

@@ -0,0 +1,129 @@
'use client';
import React, { useState } from 'react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import {
HomeIcon,
RocketLaunchIcon,
Squares2X2Icon
} from '@heroicons/react/24/outline';
import {
HomeIcon as HomeIconSolid,
RocketLaunchIcon as RocketIconSolid,
Squares2X2Icon as GridIconSolid
} from '@heroicons/react/24/solid';
export const MobileBottomBar: React.FC = () => {
const pathname = usePathname();
const [showMoreMenu, setShowMoreMenu] = useState(false);
const isActive = (path: string) => {
if (path === '/dashboard') {
return pathname === '/dashboard';
}
return pathname.startsWith(path);
};
const navItems = [
{
label: 'Início',
path: '/dashboard',
icon: HomeIcon,
iconSolid: HomeIconSolid
},
{
label: 'CRM',
path: '/crm',
icon: RocketLaunchIcon,
iconSolid: RocketIconSolid
},
{
label: 'Mais',
path: '#',
icon: Squares2X2Icon,
iconSolid: GridIconSolid,
onClick: () => setShowMoreMenu(true)
}
];
return (
<>
{/* Bottom Navigation - Mobile Only */}
<nav className="md:hidden fixed bottom-0 left-0 right-0 z-50 bg-white dark:bg-zinc-900 border-t border-gray-200 dark:border-zinc-800 shadow-lg">
<div className="flex items-center justify-around h-16 px-4">
{navItems.map((item) => {
const active = isActive(item.path);
const Icon = active ? item.iconSolid : item.icon;
if (item.onClick) {
return (
<button
key={item.label}
onClick={item.onClick}
className="flex flex-col items-center justify-center min-w-[70px] h-full gap-1"
>
<Icon className={`w-6 h-6 ${active ? 'text-[var(--brand-color)]' : 'text-gray-500 dark:text-gray-400'}`} />
<span className={`text-xs font-medium ${active ? 'text-[var(--brand-color)]' : 'text-gray-500 dark:text-gray-400'}`}>
{item.label}
</span>
</button>
);
}
return (
<Link
key={item.label}
href={item.path}
className="flex flex-col items-center justify-center min-w-[70px] h-full gap-1"
>
<Icon className={`w-6 h-6 ${active ? 'text-[var(--brand-color)]' : 'text-gray-500 dark:text-gray-400'}`} />
<span className={`text-xs font-medium ${active ? 'text-[var(--brand-color)]' : 'text-gray-500 dark:text-gray-400'}`}>
{item.label}
</span>
</Link>
);
})}
</div>
</nav>
{/* More Menu Modal */}
{showMoreMenu && (
<div className="md:hidden fixed inset-0 z-[100] bg-black/50 backdrop-blur-sm" onClick={() => setShowMoreMenu(false)}>
<div
className="absolute bottom-0 left-0 right-0 bg-white dark:bg-zinc-900 rounded-t-3xl shadow-2xl max-h-[70vh] overflow-y-auto"
onClick={(e) => e.stopPropagation()}
>
<div className="p-6">
{/* Handle bar */}
<div className="w-12 h-1.5 bg-gray-300 dark:bg-zinc-700 rounded-full mx-auto mb-6" />
<h2 className="text-xl font-bold text-gray-900 dark:text-white mb-6">
Todos os Módulos
</h2>
<div className="grid grid-cols-3 gap-4">
<Link
href="/erp"
onClick={() => setShowMoreMenu(false)}
className="flex flex-col items-center gap-3 p-4 rounded-2xl hover:bg-gray-50 dark:hover:bg-zinc-800 transition-colors"
>
<div className="w-14 h-14 rounded-2xl bg-gradient-to-br from-blue-500 to-blue-600 flex items-center justify-center text-white shadow-lg">
<svg className="w-7 h-7" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M3 13.125C3 12.504 3.504 12 4.125 12h2.25c.621 0 1.125.504 1.125 1.125v6.75C7.5 20.496 6.996 21 6.375 21h-2.25A1.125 1.125 0 013 19.875v-6.75zM9.75 8.625c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125v11.25c0 .621-.504 1.125-1.125 1.125h-2.25a1.125 1.125 0 01-1.125-1.125V8.625zM16.5 4.125c0-.621.504-1.125 1.125-1.125h2.25C20.496 3 21 3.504 21 4.125v15.75c0 .621-.504 1.125-1.125 1.125h-2.25a1.125 1.125 0 01-1.125-1.125V4.125z" />
</svg>
</div>
<span className="text-sm font-medium text-gray-900 dark:text-white text-center">
ERP
</span>
</Link>
{/* Add more modules here */}
</div>
</div>
</div>
</div>
)}
</>
);
};

View File

@@ -0,0 +1,430 @@
'use client';
import React, { useState, useEffect, useRef } from 'react';
import Link from 'next/link';
import { usePathname, useRouter } from 'next/navigation';
import { Menu, MenuButton, MenuItems, MenuItem } from '@headlessui/react';
import { useTheme } from 'next-themes';
import { getUser, User, getToken, saveAuth } from '@/lib/auth';
import { API_ENDPOINTS } from '@/lib/api';
import {
ChevronLeftIcon,
ChevronRightIcon,
ChevronDownIcon,
UserCircleIcon,
ArrowRightOnRectangleIcon,
SunIcon,
MoonIcon,
Cog6ToothIcon,
XMarkIcon,
} from '@heroicons/react/24/outline';
export interface MenuItem {
id: string;
label: string;
href: string;
icon: any;
subItems?: {
label: string;
href: string;
}[];
}
interface SidebarRailProps {
isExpanded: boolean;
onToggle: () => void;
menuItems: MenuItem[];
}
export const SidebarRail: React.FC<SidebarRailProps> = ({
isExpanded,
onToggle,
menuItems
}) => {
const pathname = usePathname();
const router = useRouter();
const { theme, setTheme } = useTheme();
const [mounted, setMounted] = useState(false);
const [user, setUser] = useState<User | null>(null);
const [openSubmenu, setOpenSubmenu] = useState<string | null>(null);
const sidebarRef = useRef<HTMLDivElement>(null);
useEffect(() => {
setMounted(true);
const currentUser = getUser();
setUser(currentUser);
// Buscar perfil da agência para atualizar logo e nome
const fetchProfile = async () => {
const token = getToken();
if (!token) return;
try {
const res = await fetch(API_ENDPOINTS.agencyProfile, {
headers: {
'Authorization': `Bearer ${token}`
}
});
if (res.ok) {
const data = await res.json();
if (currentUser) {
// Usar localStorage como fallback se API não retornar logo
const cachedLogo = localStorage.getItem('agency-logo-url');
const finalLogoUrl = data.logo_url || cachedLogo;
const updatedUser = {
...currentUser,
company: data.name || currentUser.company,
logoUrl: finalLogoUrl
};
setUser(updatedUser);
saveAuth(token, updatedUser); // Persistir atualização
// Atualizar localStorage do logo (preservar se já existe)
if (finalLogoUrl) {
console.log('📝 Salvando logo no localStorage:', finalLogoUrl);
localStorage.setItem('agency-logo-url', finalLogoUrl);
window.dispatchEvent(new Event('auth-update')); // Notificar favicon
window.dispatchEvent(new Event('branding-update')); // Notificar AgencyBranding
}
}
}
} catch (error) {
console.error('Error fetching agency profile:', error);
}
};
fetchProfile();
// Listener para atualizar logo em tempo real após upload
// REMOVIDO: Causa loop infinito com o dispatchEvent dentro do fetchProfile
// O AgencyBranding já cuida de atualizar o favicon/cores
// Se precisar atualizar o sidebar após upload, usar um evento específico 'logo-uploaded'
/*
const handleBrandingUpdate = () => {
console.log('SidebarRail: branding-update event received');
fetchProfile(); // Re-buscar perfil do backend
};
window.addEventListener('branding-update', handleBrandingUpdate);
return () => {
window.removeEventListener('branding-update', handleBrandingUpdate);
};
*/
}, []);
// Fechar submenu ao clicar fora
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (sidebarRef.current && !sidebarRef.current.contains(event.target as Node)) {
// Verifica se o submenu aberto corresponde à rota atual
// Se estivermos navegando dentro do módulo (ex: CRM), o menu deve permanecer fixo
const activeItem = menuItems.find(item => item.id === openSubmenu);
const isRouteActive = activeItem && activeItem.subItems?.some(sub => pathname === sub.href || pathname.startsWith(sub.href));
if (!isRouteActive) {
setOpenSubmenu(null);
}
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => {
document.removeEventListener('mousedown', handleClickOutside);
};
}, [openSubmenu, pathname, menuItems]);
// Auto-open submenu if active
useEffect(() => {
if (isExpanded && pathname) {
const activeItem = menuItems.find(item =>
item.subItems?.some(sub => pathname === sub.href || pathname.startsWith(sub.href))
);
if (activeItem) {
setOpenSubmenu(activeItem.id);
}
}
}, [pathname, isExpanded, menuItems]);
const handleLogout = () => {
localStorage.removeItem('token');
localStorage.removeItem('user');
window.location.href = '/login';
};
const toggleTheme = () => {
setTheme(theme === 'dark' ? 'light' : 'dark');
};
// Encontrar o item ativo para renderizar o submenu
const activeMenuItem = menuItems.find(item => item.id === openSubmenu);
// Lógica de largura do Rail: Se tiver submenu aberto, força recolhimento visual (80px)
// Se não, respeita o estado isExpanded
const railWidth = isExpanded && !openSubmenu ? 'w-[240px]' : 'w-[80px]';
const showLabels = isExpanded && !openSubmenu;
return (
<div className={`
flex h-full relative z-20 transition-all duration-300
${openSubmenu ? 'shadow-xl' : 'shadow-lg'}
rounded-2xl
`} ref={sidebarRef}>
{/* Rail Principal (Ícones + Labels Opcionais) */}
<div
className={`
relative h-full bg-white dark:bg-zinc-900 flex flex-col py-4 gap-1 text-gray-600 dark:text-gray-400 shrink-0 z-30
transition-all duration-300 ease-[cubic-bezier(0.25,0.1,0.25,1)] px-3 border border-gray-100 dark:border-zinc-800
${railWidth}
${openSubmenu ? 'rounded-l-2xl rounded-r-none border-r-0' : 'rounded-2xl'}
`}
>
{/* Toggle Button - Floating on the border */}
{/* Só mostra o toggle se não tiver submenu aberto, para evitar confusão */}
{!openSubmenu && (
<button
onClick={onToggle}
className="absolute -right-3 top-8 z-50 h-6 w-6 flex items-center justify-center rounded-full border border-gray-200 bg-white text-gray-500 shadow-sm hover:bg-gray-50 hover:text-gray-700 dark:border-zinc-700 dark:bg-zinc-800 dark:text-zinc-400 dark:hover:bg-zinc-700 dark:hover:text-zinc-200 transition-colors"
aria-label={isExpanded ? 'Recolher menu' : 'Expandir menu'}
>
{isExpanded ? (
<ChevronLeftIcon className="w-3 h-3" />
) : (
<ChevronRightIcon className="w-3 h-3" />
)}
</button>
)}
{/* Header com Logo */}
<div className={`flex items-center w-full mb-6 ${showLabels ? 'justify-start px-1' : 'justify-center'}`}>
<div
className="w-9 h-9 rounded-xl flex items-center justify-center text-white font-bold shrink-0 shadow-md text-lg overflow-hidden bg-brand-500"
>
{user?.logoUrl ? (
<img src={user.logoUrl} alt={user.company || 'Logo'} className="w-full h-full object-cover" />
) : (
(user?.company?.[0] || 'A').toUpperCase()
)}
</div>
{/* Título com animação */}
<div className={`overflow-hidden transition-all duration-300 ease-in-out whitespace-nowrap ${showLabels ? 'opacity-100 max-w-[120px] ml-3' : 'opacity-0 max-w-0 ml-0'}`}>
<span className="font-heading font-bold text-lg text-gray-900 dark:text-white tracking-tight">
{user?.company || 'Aggios'}
</span>
</div>
</div>
{/* Navegação */}
<div className="flex flex-col gap-1 w-full flex-1 overflow-y-auto items-center">
{menuItems.map((item) => (
<RailButton
key={item.id}
label={item.label}
icon={item.icon}
href={item.href}
active={pathname === item.href || (item.href !== '/dashboard' && pathname?.startsWith(item.href))}
onClick={(e: any) => {
if (item.subItems) {
// Se já estiver aberto, fecha e previne navegação
if (openSubmenu === item.id) {
e.preventDefault();
setOpenSubmenu(null);
} else {
// Se estiver fechado, abre o submenu
setOpenSubmenu(item.id);
}
} else {
setOpenSubmenu(null);
}
}}
showLabel={showLabels}
hasSubItems={!!item.subItems}
isOpen={openSubmenu === item.id}
/>
))}
</div>
{/* Separador */}
<div className="h-px bg-gray-200 dark:bg-zinc-800 my-2 w-full" />
{/* User Menu */}
<div className={`flex ${showLabels ? 'justify-start' : 'justify-center'}`}>
{mounted && (
<Menu>
<MenuButton className={`w-full p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-zinc-800 transition-all duration-300 flex items-center ${showLabels ? '' : 'justify-center'}`}>
<UserCircleIcon className="w-6 h-6 text-gray-600 dark:text-gray-400 shrink-0" />
<div className={`overflow-hidden whitespace-nowrap transition-all duration-300 ease-in-out ${showLabels ? 'max-w-[150px] opacity-100 ml-2' : 'max-w-0 opacity-0 ml-0'}`}>
<span className="font-medium text-xs text-gray-900 dark:text-white">
{user?.name || 'Usuário'}
</span>
</div>
</MenuButton>
<MenuItems
anchor="top start"
transition
className={`w-48 origin-bottom-left rounded-xl bg-white dark:bg-zinc-900 border border-gray-200 dark:border-zinc-800 shadow-lg focus:outline-none overflow-hidden z-50 transition duration-100 ease-out data-[closed]:scale-95 data-[closed]:opacity-0`}
>
<div className="p-1">
<MenuItem>
<button
className="data-[focus]:bg-gray-100 dark:data-[focus]:bg-zinc-800 text-gray-700 dark:text-gray-300 group flex w-full items-center rounded-lg px-3 py-2 text-xs"
>
<UserCircleIcon className="mr-2 h-4 w-4" />
Ver meu perfil
</button>
</MenuItem>
<MenuItem>
<button
onClick={toggleTheme}
className="data-[focus]:bg-gray-100 dark:data-[focus]:bg-zinc-800 text-gray-700 dark:text-gray-300 group flex w-full items-center rounded-lg px-3 py-2 text-xs"
>
{theme === 'dark' ? (
<>
<SunIcon className="mr-2 h-4 w-4" />
Tema Claro
</>
) : (
<>
<MoonIcon className="mr-2 h-4 w-4" />
Tema Escuro
</>
)}
</button>
</MenuItem>
<div className="my-1 h-px bg-gray-200 dark:bg-zinc-800" />
<MenuItem>
<button
onClick={handleLogout}
className="data-[focus]:bg-red-50 dark:data-[focus]:bg-red-900/20 text-red-500 group flex w-full items-center rounded-lg px-3 py-2 text-xs"
>
<ArrowRightOnRectangleIcon className="mr-2 h-4 w-4" />
Sair
</button>
</MenuItem>
</div>
</MenuItems>
</Menu>
)}
{!mounted && (
<div className={`w-full p-2 rounded-lg flex items-center ${showLabels ? '' : 'justify-center'}`}>
<UserCircleIcon className="w-6 h-6 text-gray-600 dark:text-gray-400 shrink-0" />
</div>
)}
</div>
</div>
{/* Painel Secundário (Drawer) - Abre ao lado do Rail */}
<div
className={`
h-full
bg-white dark:bg-zinc-900 rounded-r-2xl border-y border-r border-l border-gray-100 dark:border-zinc-800
transition-all duration-300 ease-in-out origin-left z-20 flex flex-col overflow-hidden
${openSubmenu ? 'w-64 opacity-100 translate-x-0' : 'w-0 opacity-0 -translate-x-10 border-none'}
`}
>
{activeMenuItem && (
<>
<div className="p-4 border-b border-gray-100 dark:border-zinc-800 flex items-center justify-between">
<h3 className="font-heading font-semibold text-gray-900 dark:text-white flex items-center gap-2">
<activeMenuItem.icon className="w-5 h-5 text-brand-500" />
{activeMenuItem.label}
</h3>
<button
onClick={() => setOpenSubmenu(null)}
className="p-1 rounded-md hover:bg-gray-200 dark:hover:bg-zinc-700 text-gray-500 dark:text-gray-400 transition-colors"
aria-label="Fechar submenu"
>
<XMarkIcon className="w-5 h-5" />
</button>
</div>
<div className="p-2 flex-1 overflow-y-auto">
{activeMenuItem.subItems?.map((sub) => (
<Link
key={sub.href}
href={sub.href}
// onClick={() => setOpenSubmenu(null)} // Removido para manter fixo
className={`
flex items-center gap-2 px-3 py-2.5 rounded-lg text-xs font-medium transition-colors mb-1
${pathname === sub.href
? 'bg-brand-50 dark:bg-brand-900/10 text-brand-600 dark:text-brand-400'
: 'text-gray-600 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-zinc-800 hover:text-gray-900 dark:hover:text-white'
}
`}
>
<span className={`w-1.5 h-1.5 rounded-full ${pathname === sub.href ? 'bg-brand-500' : 'bg-gray-300 dark:bg-zinc-600'}`} />
{sub.label}
</Link>
))}
</div>
</>
)}
</div>
</div>
);
};
// Subcomponente do Botão
interface RailButtonProps {
label: string;
icon: React.ComponentType<{ className?: string }>;
href: string;
active: boolean;
onClick: (e?: any) => void;
showLabel: boolean;
hasSubItems?: boolean;
isOpen?: boolean;
}
const RailButton: React.FC<RailButtonProps> = ({ label, icon: Icon, href, active, onClick, showLabel, hasSubItems, isOpen }) => {
// Determine styling based on state
// Sempre usa Link se tiver href, para garantir navegação correta e prefetching
const Wrapper = href ? Link : 'button';
// Desabilitar prefetch para evitar sobrecarga no middleware/backend e loops de redirecionamento
const props = href ? { href, onClick, prefetch: false } : { onClick, type: 'button' };
let baseClasses = "flex items-center p-2 rounded-lg transition-all duration-300 group relative overflow-hidden ";
if (showLabel) {
baseClasses += "w-full justify-start ";
} else {
baseClasses += "w-10 h-10 justify-center mx-auto ";
}
// Lógica unificada de ativo
const isActiveItem = active || isOpen;
if (isActiveItem) {
baseClasses += "bg-brand-500 text-white shadow-sm";
} else {
// Inactive item
baseClasses += "hover:bg-gray-100 dark:hover:bg-zinc-800 hover:text-gray-900 dark:hover:text-white text-gray-600 dark:text-gray-400";
}
return (
<Wrapper
{...props as any}
className={baseClasses}
title={!showLabel ? label : undefined} // Tooltip nativo apenas se recolhido
>
{/* Ícone */}
<Icon className={`shrink-0 w-5 h-5 ${isActiveItem ? 'text-white' : ''}`} />
{/* Texto (Visível apenas se expandido) */}
<div className={`
overflow-hidden whitespace-nowrap transition-all duration-300 ease-in-out flex items-center flex-1
${showLabel ? 'max-w-[150px] opacity-100 ml-3' : 'max-w-0 opacity-0 ml-0'}
`}>
<span className="font-medium text-xs flex-1 text-left">{label}</span>
{hasSubItems && (
<ChevronRightIcon className={`w-3 h-3 transition-transform duration-200 ${isActiveItem ? 'text-white' : 'text-gray-400'}`} />
)}
</div>
{/* Indicador de Ativo (Ponto lateral) - Apenas se recolhido e NÃO tiver gradiente (redundante agora, mas mantido por segurança) */}
{active && !hasSubItems && !showLabel && !isActiveItem && (
<div className="absolute -left-1 top-1/2 -translate-y-1/2 w-1 h-4 bg-white rounded-r-full" />
)}
</Wrapper>
);
};

View File

@@ -0,0 +1,59 @@
'use client';
import { createContext, useContext, useState, useCallback } from 'react';
import ToastNotification, { Toast } from './ToastNotification';
interface ToastContextType {
showToast: (type: Toast['type'], title: string, message?: string) => void;
success: (title: string, message?: string) => void;
error: (title: string, message?: string) => void;
info: (title: string, message?: string) => void;
}
const ToastContext = createContext<ToastContextType | undefined>(undefined);
export function ToastProvider({ children }: { children: React.ReactNode }) {
const [toasts, setToasts] = useState<Toast[]>([]);
const showToast = useCallback((type: Toast['type'], title: string, message?: string) => {
const id = Date.now().toString();
setToasts(prev => [...prev, { id, type, title, message }]);
}, []);
const success = useCallback((title: string, message?: string) => {
showToast('success', title, message);
}, [showToast]);
const error = useCallback((title: string, message?: string) => {
showToast('error', title, message);
}, [showToast]);
const info = useCallback((title: string, message?: string) => {
showToast('info', title, message);
}, [showToast]);
const removeToast = useCallback((id: string) => {
setToasts(prev => prev.filter(toast => toast.id !== id));
}, []);
return (
<ToastContext.Provider value={{ showToast, success, error, info }}>
{children}
<div className="fixed inset-0 z-50 flex items-end justify-end p-4 sm:p-6 pointer-events-none">
<div className="flex w-full flex-col items-end space-y-4 sm:items-end">
{toasts.map(toast => (
<ToastNotification key={toast.id} toast={toast} onClose={removeToast} />
))}
</div>
</div>
</ToastContext.Provider>
);
}
export function useToast() {
const context = useContext(ToastContext);
if (!context) {
throw new Error('useToast must be used within ToastProvider');
}
return context;
}

View File

@@ -0,0 +1,100 @@
import { Fragment, useEffect } from 'react';
import { Transition } from '@headlessui/react';
import {
CheckCircleIcon,
XCircleIcon,
InformationCircleIcon,
XMarkIcon
} from '@heroicons/react/24/outline';
export interface Toast {
id: string;
type: 'success' | 'error' | 'info';
title: string;
message?: string;
}
interface ToastNotificationProps {
toast: Toast;
onClose: (id: string) => void;
}
export default function ToastNotification({ toast, onClose }: ToastNotificationProps) {
useEffect(() => {
const timer = setTimeout(() => {
onClose(toast.id);
}, 5000);
return () => clearTimeout(timer);
}, [toast.id, onClose]);
const styles = {
success: {
bg: 'bg-emerald-50 dark:bg-emerald-900/20',
border: 'border-emerald-200 dark:border-emerald-900/30',
icon: 'text-emerald-600 dark:text-emerald-400',
title: 'text-emerald-900 dark:text-emerald-300',
IconComponent: CheckCircleIcon
},
error: {
bg: 'bg-red-50 dark:bg-red-900/20',
border: 'border-red-200 dark:border-red-900/30',
icon: 'text-red-600 dark:text-red-400',
title: 'text-red-900 dark:text-red-300',
IconComponent: XCircleIcon
},
info: {
bg: 'bg-blue-50 dark:bg-blue-900/20',
border: 'border-blue-200 dark:border-blue-900/30',
icon: 'text-blue-600 dark:text-blue-400',
title: 'text-blue-900 dark:text-blue-300',
IconComponent: InformationCircleIcon
}
};
const style = styles[toast.type];
const Icon = style.IconComponent;
return (
<Transition
show={true}
as={Fragment}
enter="transform ease-out duration-300 transition"
enterFrom="translate-y-2 opacity-0 sm:translate-y-0 sm:translate-x-2"
enterTo="translate-y-0 opacity-100 sm:translate-x-0"
leave="transition ease-in duration-100"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<div className={`pointer-events-auto w-full max-w-md rounded-lg border shadow-lg ${style.bg} ${style.border}`}>
<div className="p-4">
<div className="flex items-start gap-3">
<div className="flex-shrink-0 pt-0.5">
<Icon className={`h-5 w-5 ${style.icon}`} />
</div>
<div className="flex-1 min-w-0">
<p className={`text-sm font-semibold ${style.title}`}>
{toast.title}
</p>
{toast.message && (
<p className="mt-1 text-sm text-zinc-600 dark:text-zinc-400">
{toast.message}
</p>
)}
</div>
<div className="flex-shrink-0">
<button
type="button"
onClick={() => onClose(toast.id)}
className="inline-flex rounded-md text-zinc-400 hover:text-zinc-600 dark:hover:text-zinc-300 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[var(--brand-color)] transition-colors"
>
<span className="sr-only">Fechar</span>
<XMarkIcon className="h-4 w-4" />
</button>
</div>
</div>
</div>
</div>
</Transition>
);
}

View File

@@ -0,0 +1,127 @@
'use client';
import React, { useState, useEffect } from 'react';
import { usePathname } from 'next/navigation';
import Link from 'next/link';
import { MagnifyingGlassIcon, ChevronRightIcon, HomeIcon, BellIcon, Cog6ToothIcon } from '@heroicons/react/24/outline';
import CommandPalette from '@/components/ui/CommandPalette';
import { getUser } from '@/lib/auth';
export const TopBar: React.FC = () => {
const pathname = usePathname();
const [isCommandPaletteOpen, setIsCommandPaletteOpen] = useState(false);
const [user, setUser] = useState<any>(null);
useEffect(() => {
const userData = getUser();
setUser(userData);
}, []);
const generateBreadcrumbs = () => {
const paths = pathname?.split('/').filter(Boolean) || [];
const breadcrumbs: Array<{ name: string; href: string; icon?: React.ComponentType<{ className?: string }> }> = [
{ name: 'Home', href: '/dashboard', icon: HomeIcon }
];
let currentPath = '';
paths.forEach((path, index) => {
currentPath += `/${path}`;
// Mapeamento de nomes amigáveis
const nameMap: Record<string, string> = {
'dashboard': 'Dashboard',
'clientes': 'Clientes',
'projetos': 'Projetos',
'financeiro': 'Financeiro',
'configuracoes': 'Configurações',
'novo': 'Novo',
};
if (path !== 'dashboard') { // Evita duplicar Home/Dashboard se a rota for /dashboard
breadcrumbs.push({
name: nameMap[path] || path.charAt(0).toUpperCase() + path.slice(1),
href: currentPath,
});
}
});
return breadcrumbs;
};
const breadcrumbs = generateBreadcrumbs();
return (
<>
<div className="bg-white dark:bg-zinc-900 border-b border-gray-200 dark:border-zinc-800 px-4 md:px-6 py-3 flex items-center justify-between transition-colors">
{/* Logo Mobile */}
<Link href="/dashboard" className="md:hidden flex items-center gap-2">
<div className="w-8 h-8 rounded-lg flex items-center justify-center text-white font-bold shrink-0 shadow-md overflow-hidden bg-brand-500">
{user?.logoUrl ? (
<img src={user.logoUrl} alt={user?.company || 'Logo'} className="w-full h-full object-cover" />
) : (
(user?.company?.charAt(0)?.toUpperCase() || 'A')
)}
</div>
</Link>
{/* Breadcrumbs Desktop */}
<nav className="hidden md:flex items-center gap-2 text-xs">{breadcrumbs.map((crumb, index) => {
const Icon = crumb.icon;
const isLast = index === breadcrumbs.length - 1;
return (
<div key={crumb.href} className="flex items-center gap-2">
{Icon ? (
<Link
href={crumb.href}
className="flex items-center gap-1.5 text-gray-500 dark:text-zinc-400 hover:text-gray-900 dark:hover:text-zinc-200 transition-colors"
>
<Icon className="w-3.5 h-3.5" />
<span>{crumb.name}</span>
</Link>
) : (
<Link
href={crumb.href}
className={`${isLast ? 'text-gray-900 dark:text-white font-medium' : 'text-gray-500 dark:text-zinc-400 hover:text-gray-900 dark:hover:text-zinc-200'} transition-colors`}
>
{crumb.name}
</Link>
)}
{!isLast && <ChevronRightIcon className="w-3 h-3 text-gray-400 dark:text-zinc-600" />}
</div>
);
})}
</nav>
{/* Search Bar Trigger */}
<div className="flex items-center gap-2 md:gap-4">
<button
onClick={() => setIsCommandPaletteOpen(true)}
className="flex items-center gap-2 px-2 md:px-3 py-1.5 text-sm text-gray-500 dark:text-zinc-400 bg-gray-100 dark:bg-zinc-800 rounded-lg hover:bg-gray-200 dark:hover:bg-zinc-700 transition-colors"
>
<MagnifyingGlassIcon className="w-4 h-4" />
<span className="hidden md:inline">Buscar...</span>
<kbd className="hidden md:inline-flex items-center gap-1 px-1.5 py-0.5 text-[10px] font-medium text-gray-400 bg-white dark:bg-zinc-900 rounded border border-gray-200 dark:border-zinc-700">
Ctrl K
</kbd>
</button>
<div className="flex items-center gap-2 border-l border-gray-200 dark:border-zinc-800 pl-4">
<button className="p-2 text-gray-500 dark:text-zinc-400 hover:bg-gray-100 dark:hover:bg-zinc-800 rounded-lg transition-colors relative">
<BellIcon className="w-5 h-5" />
<span className="absolute top-2 right-2 w-2 h-2 bg-red-500 rounded-full border-2 border-white dark:border-zinc-900"></span>
</button>
<Link
href="/configuracoes"
className="flex p-2 text-gray-500 dark:text-zinc-400 hover:bg-gray-100 dark:hover:bg-zinc-800 rounded-lg transition-colors"
>
<Cog6ToothIcon className="w-5 h-5" />
</Link>
</div>
</div>
</div>
{/* Command Palette */}
<CommandPalette isOpen={isCommandPaletteOpen} setIsOpen={setIsCommandPaletteOpen} />
</>
);
};

View File

@@ -29,30 +29,48 @@ const Button = forwardRef<HTMLButtonElement, ButtonProps>(
"inline-flex items-center justify-center font-medium rounded-[6px] transition-opacity focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-brand-500 disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer";
const variants = {
primary: "text-white hover:opacity-90 active:opacity-80",
primary: "bg-brand-500 text-white hover:opacity-90 active:opacity-80 shadow-sm hover:shadow-md transition-all",
secondary:
"bg-[#E5E5E5] dark:bg-gray-700 text-[#000000] dark:text-white hover:opacity-90 active:opacity-80",
"bg-gray-100 dark:bg-gray-800 text-gray-900 dark:text-white hover:bg-gray-200 dark:hover:bg-gray-700 active:bg-gray-300 dark:active:bg-gray-600",
outline:
"border border-[#E5E5E5] dark:border-gray-600 text-[#000000] dark:text-white hover:bg-[#E5E5E5]/10 dark:hover:bg-gray-700/50 active:bg-[#E5E5E5]/20 dark:active:bg-gray-700",
ghost: "text-[#000000] dark:text-white hover:bg-[#E5E5E5]/20 dark:hover:bg-gray-700/30 active:bg-[#E5E5E5]/30 dark:active:bg-gray-700/50",
"border border-gray-200 dark:border-gray-700 text-gray-700 dark:text-white hover:bg-gray-50 dark:hover:bg-gray-800 active:bg-gray-100 dark:active:bg-gray-700",
ghost: "text-gray-700 dark:text-white hover:bg-gray-100 dark:hover:bg-gray-800 active:bg-gray-200 dark:active:bg-gray-700",
};
const sizes = {
sm: "h-9 px-3 text-[13px]",
md: "h-10 px-4 text-[14px]",
lg: "h-12 px-6 text-[14px]",
sm: "h-8 px-3 text-xs",
md: "h-10 px-4 text-sm",
lg: "h-12 px-6 text-base",
};
return (
<button
ref={ref}
className={`${baseStyles} ${variants[variant]} ${sizes[size]} ${className}`}
style={variant === 'primary' ? { background: 'var(--gradient-primary)' } : undefined}
disabled={disabled || isLoading}
{...props}
>
{isLoading && (
<i className="ri-loader-4-line animate-spin mr-2 text-[20px]" />
<svg
className="animate-spin -ml-1 mr-2 h-4 w-4 text-current"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
>
<circle
className="opacity-25"
cx="12"
cy="12"
r="10"
stroke="currentColor"
strokeWidth="4"
></circle>
<path
className="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
></path>
</svg>
)}
{!isLoading && leftIcon && (
<i className={`${leftIcon} mr-2 text-[20px]`} />

View File

@@ -0,0 +1,227 @@
'use client';
import { useState, useEffect, useRef } from 'react';
import { Combobox, Dialog, DialogBackdrop, DialogPanel } from '@headlessui/react';
import { MagnifyingGlassIcon } from '@heroicons/react/24/outline';
import { useRouter } from 'next/navigation';
import {
HomeIcon,
RocketLaunchIcon,
ChartBarIcon,
BriefcaseIcon,
LifebuoyIcon,
CreditCardIcon,
DocumentTextIcon,
FolderIcon,
ShareIcon,
Cog6ToothIcon,
PlusIcon,
ArrowRightIcon
} from '@heroicons/react/24/outline';
interface CommandPaletteProps {
isOpen: boolean;
setIsOpen: (isOpen: boolean) => void;
}
export default function CommandPalette({ isOpen, setIsOpen }: CommandPaletteProps) {
const [query, setQuery] = useState('');
const [availableSolutions, setAvailableSolutions] = useState<string[]>([]);
const router = useRouter();
const inputRef = useRef<HTMLInputElement>(null);
// Buscar soluções disponíveis
useEffect(() => {
const fetchSolutions = async () => {
try {
const response = await fetch('/api/tenant/solutions', {
headers: {
'Authorization': `Bearer ${localStorage.getItem('token')}`,
},
});
if (response.ok) {
const data = await response.json();
const solutions = data.solutions || [];
const slugs = solutions.map((s: any) => s.slug.toLowerCase());
setAvailableSolutions(['dashboard', ...slugs]); // Dashboard sempre disponível
} else {
// Fallback: mostrar tudo
setAvailableSolutions(['dashboard', 'crm', 'erp', 'projetos', 'helpdesk', 'pagamentos', 'contratos', 'documentos', 'social']);
}
} catch (error) {
console.error('Erro ao buscar soluções:', error);
// Fallback: mostrar tudo
setAvailableSolutions(['dashboard', 'crm', 'erp', 'projetos', 'helpdesk', 'pagamentos', 'contratos', 'documentos', 'social']);
}
};
if (isOpen) {
fetchSolutions();
}
}, [isOpen]);
// Atalho de teclado (Ctrl+K ou Cmd+K)
useEffect(() => {
const onKeydown = (event: KeyboardEvent) => {
if (event.key === 'k' && (event.metaKey || event.ctrlKey)) {
event.preventDefault();
setIsOpen(true);
}
};
window.addEventListener('keydown', onKeydown);
return () => {
window.removeEventListener('keydown', onKeydown);
};
}, [setIsOpen]);
const navigation = [
{ name: 'Visão Geral', href: '/dashboard', icon: HomeIcon, category: 'Navegação', solution: 'dashboard' },
{ name: 'CRM', href: '/crm', icon: RocketLaunchIcon, category: 'Navegação', solution: 'crm' },
{ name: 'ERP', href: '/erp', icon: ChartBarIcon, category: 'Navegação', solution: 'erp' },
{ name: 'Projetos', href: '/projetos', icon: BriefcaseIcon, category: 'Navegação', solution: 'projetos' },
{ name: 'Helpdesk', href: '/helpdesk', icon: LifebuoyIcon, category: 'Navegação', solution: 'helpdesk' },
{ name: 'Pagamentos', href: '/pagamentos', icon: CreditCardIcon, category: 'Navegação', solution: 'pagamentos' },
{ name: 'Contratos', href: '/contratos', icon: DocumentTextIcon, category: 'Navegação', solution: 'contratos' },
{ name: 'Documentos', href: '/documentos', icon: FolderIcon, category: 'Navegação', solution: 'documentos' },
{ name: 'Redes Sociais', href: '/social', icon: ShareIcon, category: 'Navegação', solution: 'social' },
{ name: 'Configurações', href: '/configuracoes', icon: Cog6ToothIcon, category: 'Navegação', solution: 'dashboard' },
// Ações
{ name: 'Novo Projeto', href: '/projetos/novo', icon: PlusIcon, category: 'Ações', solution: 'projetos' },
{ name: 'Novo Chamado', href: '/helpdesk/novo', icon: PlusIcon, category: 'Ações', solution: 'helpdesk' },
{ name: 'Novo Contrato', href: '/contratos/novo', icon: PlusIcon, category: 'Ações', solution: 'contratos' },
];
// Filtrar por soluções disponíveis
const allowedNavigation = navigation.filter(item =>
availableSolutions.includes(item.solution)
);
const filteredItems =
query === ''
? allowedNavigation
: allowedNavigation.filter((item) => {
return item.name.toLowerCase().includes(query.toLowerCase());
});
// Agrupar itens por categoria
const groups = filteredItems.reduce((acc, item) => {
if (!acc[item.category]) {
acc[item.category] = [];
}
acc[item.category].push(item);
return acc;
}, {} as Record<string, typeof filteredItems>);
const handleSelect = (item: typeof navigation[0] | null) => {
if (!item) return;
setIsOpen(false);
router.push(item.href);
setQuery('');
};
return (
<Dialog open={isOpen} onClose={setIsOpen} className="relative z-50" initialFocus={inputRef}>
<DialogBackdrop
transition
className="fixed inset-0 bg-zinc-900/40 backdrop-blur-sm transition-opacity duration-300 data-[closed]:opacity-0"
/>
<div className="fixed inset-0 z-10 overflow-y-auto p-4 sm:p-6 md:p-20">
<DialogPanel
transition
className="mx-auto max-w-2xl transform overflow-hidden rounded-xl bg-white dark:bg-zinc-900 shadow-2xl transition-all duration-300 data-[closed]:opacity-0 data-[closed]:scale-95"
>
<Combobox onChange={handleSelect}>
<div className="relative">
<MagnifyingGlassIcon
className="pointer-events-none absolute left-4 top-3.5 h-5 w-5 text-zinc-400"
aria-hidden="true"
/>
<Combobox.Input
ref={inputRef}
className="h-12 w-full border-0 bg-transparent pl-11 pr-4 text-zinc-900 dark:text-white placeholder:text-zinc-400 focus:ring-0 sm:text-sm font-medium"
placeholder="O que você procura?"
onChange={(event) => setQuery(event.target.value)}
displayValue={(item: any) => item?.name}
autoComplete="off"
/>
</div>
{filteredItems.length > 0 && (
<Combobox.Options static className="max-h-[60vh] scroll-py-2 overflow-y-auto py-2 text-sm text-zinc-800 dark:text-zinc-200">
{Object.entries(groups).map(([category, items]) => (
<div key={category}>
<div className="px-4 py-2 text-[10px] font-bold text-zinc-400 uppercase tracking-wider bg-zinc-50/50 dark:bg-zinc-800/50 mt-2 first:mt-0 mb-1">
{category}
</div>
{items.map((item) => (
<Combobox.Option
key={item.href}
value={item}
className={({ active }) =>
`cursor-pointer select-none px-4 py-2.5 transition-colors ${active
? '[background:var(--gradient)] text-white'
: ''
}`
}
>
{({ active }) => (
<div className="flex items-center gap-3">
<div className={`flex h-8 w-8 items-center justify-center rounded-md ${active
? 'bg-white/20 text-white'
: 'bg-zinc-50 dark:bg-zinc-900 text-zinc-400'
}`}>
<item.icon
className="h-4 w-4"
aria-hidden="true"
/>
</div>
<span className={`flex-auto truncate font-medium ${active ? 'text-white' : 'text-zinc-600 dark:text-zinc-400'}`}>
{item.name}
</span>
{active && (
<ArrowRightIcon className="h-4 w-4 text-white/70" />
)}
</div>
)}
</Combobox.Option>
))}
</div>
))}
</Combobox.Options>
)}
{query !== '' && filteredItems.length === 0 && (
<div className="py-14 px-6 text-center text-sm sm:px-14">
<MagnifyingGlassIcon className="mx-auto h-6 w-6 text-zinc-400" aria-hidden="true" />
<p className="mt-4 font-semibold text-zinc-900 dark:text-white">Nenhum resultado encontrado</p>
<p className="mt-2 text-zinc-500">Não conseguimos encontrar nada para &quot;{query}&quot;. Tente buscar por páginas ou ações.</p>
</div>
)}
<div className="flex items-center justify-between px-4 py-3 bg-zinc-50 dark:bg-zinc-900/50">
<div className="flex gap-4 text-[10px] text-zinc-500 font-medium">
<span className="flex items-center gap-1.5">
<kbd className="flex h-5 w-5 items-center justify-center rounded bg-white font-sans text-xs text-zinc-400 dark:bg-zinc-800"></kbd>
Selecionar
</span>
<span className="flex items-center gap-1.5">
<kbd className="flex h-5 w-5 items-center justify-center rounded bg-white font-sans text-xs text-zinc-400 dark:bg-zinc-800"></kbd>
<kbd className="flex h-5 w-5 items-center justify-center rounded bg-white font-sans text-xs text-zinc-400 dark:bg-zinc-800"></kbd>
Navegar
</span>
</div>
<div className="text-[10px] text-zinc-500 font-medium">
<span className="flex items-center gap-1.5">
<kbd className="flex h-5 w-auto px-1.5 items-center justify-center rounded bg-white font-sans text-xs text-zinc-400 dark:bg-zinc-800">Esc</kbd>
Fechar
</span>
</div>
</div>
</Combobox>
</DialogPanel>
</div>
</Dialog>
);
}

View File

@@ -1,13 +1,14 @@
"use client";
import { InputHTMLAttributes, forwardRef, useState } from "react";
import { InputHTMLAttributes, forwardRef, useState, ReactNode } from "react";
import { EyeIcon, EyeSlashIcon, ExclamationCircleIcon } from "@heroicons/react/24/outline";
interface InputProps extends InputHTMLAttributes<HTMLInputElement> {
label?: string;
error?: string;
helperText?: string;
leftIcon?: string;
rightIcon?: string;
leftIcon?: ReactNode;
rightIcon?: ReactNode;
onRightIconClick?: () => void;
}
@@ -41,26 +42,26 @@ const Input = forwardRef<HTMLInputElement, InputProps>(
)}
<div className="relative">
{leftIcon && (
<i
className={`${leftIcon} absolute left-3.5 top-1/2 -translate-y-1/2 text-[#7D7D7D] dark:text-gray-400 text-[20px]`}
/>
<div className="absolute left-3.5 top-1/2 -translate-y-1/2 text-[#7D7D7D] dark:text-gray-400 w-5 h-5">
{leftIcon}
</div>
)}
<input
ref={ref}
type={inputType}
className={`
w-full px-3.5 py-3 text-[14px] font-normal
border rounded-md bg-white dark:bg-gray-700 dark:text-white
placeholder:text-zinc-500 dark:placeholder:text-gray-400
transition-all
w-full px-4 py-2.5 text-sm font-normal
border rounded-lg bg-white dark:bg-gray-800 dark:text-white
placeholder:text-gray-400 dark:placeholder:text-gray-500
transition-all duration-200
${leftIcon ? "pl-11" : ""}
${isPassword || rightIcon ? "pr-11" : ""}
${error
? "border-red-500 focus:border-red-500"
: "border-zinc-200 dark:border-gray-600 focus:border-brand-500"
? "border-red-500 focus:border-red-500 focus:ring-4 focus:ring-red-500/10"
: "border-gray-200 dark:border-gray-700 focus:border-brand-500 focus:ring-4 focus:ring-brand-500/10"
}
outline-none ring-0 focus:ring-0 shadow-none focus:shadow-none
disabled:bg-zinc-100 disabled:cursor-not-allowed
outline-none
disabled:bg-gray-50 disabled:text-gray-500 disabled:cursor-not-allowed
${className}
`}
{...props}
@@ -71,9 +72,11 @@ const Input = forwardRef<HTMLInputElement, InputProps>(
onClick={() => setShowPassword(!showPassword)}
className="absolute right-3.5 top-1/2 -translate-y-1/2 text-zinc-500 hover:text-zinc-900 transition-colors cursor-pointer"
>
<i
className={`${showPassword ? "ri-eye-off-line" : "ri-eye-line"} text-[20px]`}
/>
{showPassword ? (
<EyeSlashIcon className="w-5 h-5" />
) : (
<EyeIcon className="w-5 h-5" />
)}
</button>
)}
{!isPassword && rightIcon && (
@@ -82,13 +85,13 @@ const Input = forwardRef<HTMLInputElement, InputProps>(
onClick={onRightIconClick}
className="absolute right-3.5 top-1/2 -translate-y-1/2 text-zinc-500 hover:text-zinc-900 transition-colors cursor-pointer"
>
<i className={`${rightIcon} text-[20px]`} />
<div className="w-5 h-5">{rightIcon}</div>
</button>
)}
</div>
{error && (
<p className="mt-1 text-[13px] text-red-500 flex items-center gap-1">
<i className="ri-error-warning-line" />
<ExclamationCircleIcon className="w-4 h-4" />
{error}
</p>
)}

View File

@@ -2,8 +2,9 @@
* API Configuration - URLs e funções de requisição
*/
// URL base da API - pode ser alterada por variável de ambiente
export const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://api.localhost';
// URL base da API - usa path relativo para passar pelo middleware do Next.js
// que adiciona os headers de tenant (X-Tenant-Subdomain)
export const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || '';
/**
* Endpoints da API
@@ -18,6 +19,8 @@ export const API_ENDPOINTS = {
// Admin / Agencies
adminAgencyRegister: `${API_BASE_URL}/api/admin/agencies/register`,
agencyProfile: `${API_BASE_URL}/api/agency/profile`,
tenantConfig: `${API_BASE_URL}/api/tenant/config`,
// Health
health: `${API_BASE_URL}/health`,

View File

@@ -10,6 +10,7 @@ export interface User {
tenantId?: string;
company?: string;
subdomain?: string;
logoUrl?: string;
}
const TOKEN_KEY = 'token';

View File

@@ -0,0 +1,183 @@
/**
* Utilitários para manipulação de cores e garantia de acessibilidade
*/
/**
* Converte hex para RGB
*/
export function hexToRgb(hex: string): { r: number; g: number; b: number } | null {
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result
? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16),
}
: null;
}
/**
* Converte RGB para hex
*/
export function rgbToHex(r: number, g: number, b: number): string {
return '#' + [r, g, b].map((x) => {
const hex = Math.round(x).toString(16);
return hex.length === 1 ? '0' + hex : hex;
}).join('');
}
/**
* Calcula luminosidade relativa (0-1) - WCAG 2.0
*/
export function getLuminance(hex: string): number {
const rgb = hexToRgb(hex);
if (!rgb) return 0;
const [r, g, b] = [rgb.r, rgb.g, rgb.b].map((val) => {
const v = val / 255;
return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);
});
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
}
/**
* Calcula contraste entre duas cores (1-21) - WCAG 2.0
*/
export function getContrast(color1: string, color2: string): number {
const lum1 = getLuminance(color1);
const lum2 = getLuminance(color2);
const lighter = Math.max(lum1, lum2);
const darker = Math.min(lum1, lum2);
return (lighter + 0.05) / (darker + 0.05);
}
/**
* Verifica se a cor é clara (luminosidade > 0.5)
*/
export function isLight(hex: string): boolean {
return getLuminance(hex) > 0.5;
}
/**
* Escurece uma cor em uma porcentagem
*/
export function darken(hex: string, amount: number): string {
const rgb = hexToRgb(hex);
if (!rgb) return hex;
const factor = 1 - amount;
return rgbToHex(
rgb.r * factor,
rgb.g * factor,
rgb.b * factor
);
}
/**
* Clareia uma cor em uma porcentagem
*/
export function lighten(hex: string, amount: number): string {
const rgb = hexToRgb(hex);
if (!rgb) return hex;
const factor = amount;
return rgbToHex(
rgb.r + (255 - rgb.r) * factor,
rgb.g + (255 - rgb.g) * factor,
rgb.b + (255 - rgb.b) * factor
);
}
/**
* Gera cor de hover automática baseada na luminosidade
* Se a cor for clara, escurece 15%
* Se a cor for escura, clareia 15%
*/
export function generateHoverColor(hex: string): string {
return isLight(hex) ? darken(hex, 0.15) : lighten(hex, 0.15);
}
/**
* Determina se deve usar texto branco ou preto sobre uma cor de fundo
* Prioriza branco para cores vibrantes/saturadas
*/
export function getTextColor(backgroundColor: string): string {
const contrastWithWhite = getContrast(backgroundColor, '#FFFFFF');
const contrastWithBlack = getContrast(backgroundColor, '#000000');
// Se o contraste com branco for >= 3.5, prefere branco (mais comum em UIs modernas)
// WCAG AA requer 4.5:1, mas 3:1 para textos grandes
if (contrastWithWhite >= 3.5) {
return '#FFFFFF';
}
// Se não, usa a cor com melhor contraste
return contrastWithWhite > contrastWithBlack ? '#FFFFFF' : '#000000';
}
/**
* Gera paleta completa de cores com hover e variações
*/
export function generateColorPalette(primaryHex: string, secondaryHex: string) {
const primaryRgb = hexToRgb(primaryHex);
const secondaryRgb = hexToRgb(secondaryHex);
if (!primaryRgb || !secondaryRgb) {
throw new Error('Cores inválidas');
}
const primaryHover = generateHoverColor(primaryHex);
const secondaryHover = generateHoverColor(secondaryHex);
const primaryRgbString = `${primaryRgb.r} ${primaryRgb.g} ${primaryRgb.b}`;
const secondaryRgbString = `${secondaryRgb.r} ${secondaryRgb.g} ${secondaryRgb.b}`;
const hoverRgb = hexToRgb(primaryHover);
const hoverRgbString = hoverRgb ? `${hoverRgb.r} ${hoverRgb.g} ${hoverRgb.b}` : secondaryRgbString;
return {
primary: primaryHex,
secondary: secondaryHex,
primaryHover,
secondaryHover,
primaryRgb: primaryRgbString,
secondaryRgb: secondaryRgbString,
hoverRgb: hoverRgbString,
gradient: `linear-gradient(135deg, ${primaryHex}, ${secondaryHex})`,
textOnPrimary: getTextColor(primaryHex),
textOnSecondary: getTextColor(secondaryHex),
isLightPrimary: isLight(primaryHex),
isLightSecondary: isLight(secondaryHex),
contrast: getContrast(primaryHex, secondaryHex),
};
}
/**
* Valida se as cores têm contraste suficiente
*/
export function validateColorContrast(primary: string, secondary: string): {
valid: boolean;
warnings: string[];
} {
const warnings: string[] = [];
const contrast = getContrast(primary, secondary);
if (contrast < 3) {
warnings.push('As cores são muito similares e podem causar problemas de legibilidade');
}
const primaryContrast = getContrast(primary, '#FFFFFF');
if (primaryContrast < 4.5 && !isLight(primary)) {
warnings.push('A cor primária pode ter baixo contraste com texto branco');
}
const secondaryContrast = getContrast(secondary, '#FFFFFF');
if (secondaryContrast < 4.5 && !isLight(secondary)) {
warnings.push('A cor secundária pode ter baixo contraste com texto branco');
}
return {
valid: warnings.length === 0,
warnings,
};
}

View File

@@ -0,0 +1,85 @@
/**
* Server-side API functions
* Estas funções são executadas APENAS no servidor (não no cliente)
*/
import { cookies, headers } from 'next/headers';
const API_BASE_URL = process.env.API_INTERNAL_URL || 'http://backend:8080';
interface AgencyBrandingData {
logo_url?: string;
primary_color?: string;
secondary_color?: string;
name?: string;
}
/**
* Busca os dados de branding da agência no servidor
* Usa o subdomínio do request para identificar a agência
*/
export async function getAgencyBranding(): Promise<AgencyBrandingData | null> {
try {
// Pegar o hostname do request
const headersList = await headers();
const hostname = headersList.get('host') || '';
// Extrair subdomain (remover porta se houver)
const hostnameWithoutPort = hostname.split(':')[0];
const subdomain = hostnameWithoutPort.split('.')[0];
console.log(`[ServerAPI] Full hostname: ${hostname}, Without port: ${hostnameWithoutPort}, Subdomain: ${subdomain}`);
if (!subdomain || subdomain === 'localhost' || subdomain === 'www') {
console.log(`[ServerAPI] Invalid subdomain, skipping: ${subdomain}`);
return null;
}
// Buscar dados da agência pela API
const url = `${API_BASE_URL}/api/tenant/config?subdomain=${subdomain}`;
console.log(`[ServerAPI] Fetching agency config from: ${url}`);
const response = await fetch(url, {
cache: 'no-store', // Sempre buscar dados atualizados
headers: {
'Content-Type': 'application/json',
},
});
if (!response.ok) {
console.error(`[ServerAPI] Failed to fetch agency branding for ${subdomain}: ${response.status}`);
return null;
}
const data = await response.json();
console.log(`[ServerAPI] Agency branding data for ${subdomain}:`, JSON.stringify(data));
return data as AgencyBrandingData;
} catch (error) {
console.error('[ServerAPI] Error fetching agency branding:', error);
return null;
}
}
/**
* Busca apenas o logo da agência (para metadata)
*/
export async function getAgencyLogo(): Promise<string | null> {
const branding = await getAgencyBranding();
return branding?.logo_url || null;
}
/**
* Busca as cores da agência (para passar ao client component)
*/
export async function getAgencyColors(): Promise<{ primary: string; secondary: string } | null> {
const branding = await getAgencyBranding();
if (branding?.primary_color && branding?.secondary_color) {
return {
primary: branding.primary_color,
secondary: branding.secondary_color,
};
}
return null;
}

View File

@@ -7,29 +7,57 @@ export async function middleware(request: NextRequest) {
const apiBase = process.env.API_INTERNAL_URL || 'http://backend:8080';
// Extrair subdomínio
const subdomain = hostname.split('.')[0];
// Extrair subdomínio (remover porta se houver)
const hostnameWithoutPort = hostname.split(':')[0];
const subdomain = hostnameWithoutPort.split('.')[0];
// Validar subdomínio de agência ({subdomain}.localhost)
// Se tem subdomínio (ex: vivo.localhost), SEMPRE validar se existe
if (hostname.includes('.')) {
try {
const res = await fetch(`${apiBase}/api/tenant/check?subdomain=${subdomain}`);
const res = await fetch(`${apiBase}/api/tenant/check?subdomain=${subdomain}`, {
cache: 'no-store',
headers: {
'Content-Type': 'application/json',
}
});
if (!res.ok) {
const baseHost = hostname.split('.').slice(1).join('.') || hostname;
const redirectUrl = new URL(url.toString());
redirectUrl.hostname = baseHost;
redirectUrl.pathname = '/';
return NextResponse.redirect(redirectUrl);
console.error(`❌ Tenant check failed for ${subdomain}: ${res.status}`);
if (res.status === 404) {
console.error(`❌ Tenant ${subdomain} não encontrado - BLOQUEANDO ACESSO`);
// Tenant não existe, redirecionar para página principal (sem subdomínio)
const baseHost = hostname.split('.').slice(1).join('.') || 'localhost';
const redirectUrl = new URL(`http://${baseHost}/`);
return NextResponse.redirect(redirectUrl);
}
}
// Se passou pela validação, tenant existe - continuar
console.log(`✅ Tenant ${subdomain} validado com sucesso`);
} catch (err) {
const baseHost = hostname.split('.').slice(1).join('.') || hostname;
const redirectUrl = new URL(url.toString());
redirectUrl.hostname = baseHost;
redirectUrl.pathname = '/';
console.error('❌ Middleware error:', err);
// Em caso de erro de rede, bloquear por segurança
const baseHost = hostname.split('.').slice(1).join('.') || 'localhost';
const redirectUrl = new URL(`http://${baseHost}/`);
return NextResponse.redirect(redirectUrl);
}
}
// Para requisições de API, adicionar headers com informações do tenant
if (url.pathname.startsWith('/api/')) {
// Cria um header customizado com o subdomain
const requestHeaders = new Headers(request.headers);
requestHeaders.set('X-Tenant-Subdomain', subdomain);
requestHeaders.set('X-Original-Host', hostname);
return NextResponse.rewrite(url, {
request: {
headers: requestHeaders,
},
});
}
// Permitir acesso normal
return NextResponse.next();
}
@@ -38,11 +66,10 @@ export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - api (API routes)
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
*/
'/((?!api|_next/static|_next/image|favicon.ico).*)',
'/((?!_next/static|_next/image|favicon.ico).*)',
],
};

View File

@@ -1,6 +1,7 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
reactStrictMode: false, // Desabilitar StrictMode para evitar double render que causa removeChild
experimental: {
externalDir: true,
},
@@ -23,6 +24,10 @@ const nextConfig: NextConfig = {
key: "X-Forwarded-For",
value: "127.0.0.1",
},
{
key: "X-Forwarded-Host",
value: "${host}",
},
],
},
];

View File

@@ -10,17 +10,18 @@ module.exports = {
},
colors: {
brand: {
50: '#fff4ef',
100: '#ffe8df',
200: '#ffd0c0',
300: '#ffb093',
400: '#ff8a66',
500: '#ff3a05',
600: '#ff1f45',
700: '#ff0080',
800: '#d10069',
900: '#9e0050',
950: '#4b0028',
50: 'rgb(var(--brand-rgb) / 0.05)',
100: 'rgb(var(--brand-rgb) / 0.1)',
200: 'rgb(var(--brand-rgb) / 0.2)',
300: 'rgb(var(--brand-rgb) / 0.4)',
400: 'rgb(var(--brand-rgb) / 0.8)',
500: 'rgb(var(--brand-rgb) / <alpha-value>)',
600: 'rgb(var(--brand-strong-rgb) / <alpha-value>)',
700: 'rgb(var(--brand-strong-rgb) / 0.8)',
800: 'rgb(var(--brand-strong-rgb) / 0.6)',
900: 'rgb(var(--brand-strong-rgb) / 0.4)',
950: 'rgb(var(--brand-strong-rgb) / 0.2)',
hover: 'rgb(var(--brand-hover-rgb) / <alpha-value>)',
},
surface: {
light: '#ffffff',

File diff suppressed because it is too large Load Diff

View File

@@ -67,16 +67,16 @@ html.dark {
}
::selection {
background-color: var(--color-brand-500);
color: var(--color-text-inverse);
background-color: var(--color-brand-100);
color: var(--color-text-primary);
}
/* Seleção em campos de formulário usa o gradiente padrão da marca */
/* Seleção em campos de formulário usa cor mais visível */
input::selection,
textarea::selection,
select::selection {
background: var(--color-gradient-brand);
color: var(--color-text-inverse);
background-color: var(--color-brand-200);
color: var(--color-text-primary);
}
.surface-card {
@@ -181,3 +181,34 @@ html.dark {
@apply bg-background text-foreground;
}
}
/* Animações customizadas para o modal de boas-vindas */
@keyframes fade-in {
from {
opacity: 0;
transform: translateY(20px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes progress {
0% {
width: 0%;
}
100% {
width: 100%;
}
}
.animate-fade-in {
animation: fade-in 0.8s ease-out;
}
.animate-progress {
animation: progress 3.5s ease-in-out;
}

View File

@@ -3,6 +3,7 @@ import { Open_Sans, Fira_Code, Arimo } from "next/font/google";
import "./globals.css";
import LayoutWrapper from "./LayoutWrapper";
import { ThemeProvider } from "next-themes";
import { ToastProvider } from "@/components/layout/ToastContext";
const arimo = Arimo({
variable: "--font-arimo",
@@ -39,9 +40,11 @@ export default function RootLayout({
</head>
<body className={`${arimo.variable} ${openSans.variable} ${firaCode.variable} antialiased`}>
<ThemeProvider attribute="class" defaultTheme="light" enableSystem={false}>
<LayoutWrapper>
{children}
</LayoutWrapper>
<ToastProvider>
<LayoutWrapper>
{children}
</LayoutWrapper>
</ToastProvider>
</ThemeProvider>
</body>
</html>

View File

@@ -3,7 +3,6 @@
import { useState, useEffect } from "react";
import Link from "next/link";
import { Button, Input, Checkbox } from "@/components/ui";
import toast, { Toaster } from 'react-hot-toast';
import { saveAuth, isAuthenticated } from '@/lib/auth';
import dynamic from 'next/dynamic';
@@ -52,17 +51,17 @@ export default function LoginPage() {
e.preventDefault();
if (!formData.email) {
toast.error('Por favor, insira seu email');
console.error('Por favor, insira seu email');
return;
}
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
toast.error('Por favor, insira um email válido');
console.error('Por favor, insira um email válido');
return;
}
if (!formData.password) {
toast.error('Por favor, insira sua senha');
console.error('Por favor, insira sua senha');
return;
}
@@ -90,51 +89,22 @@ export default function LoginPage() {
saveAuth(data.token, data.user);
console.log('Login successful:', data.user);
toast.success('Login realizado com sucesso! Redirecionando...');
console.log('Login realizado com sucesso! Redirecionando...');
setTimeout(() => {
const target = isSuperAdmin ? '/superadmin' : '/dashboard';
window.location.href = target;
}, 1000);
} catch (error: any) {
toast.error(error.message || 'Erro ao fazer login. Verifique suas credenciais.');
const errorMsg = error.message || 'Erro ao fazer login. Verifique suas credenciais.';
console.error('Erro no login:', errorMsg);
alert(errorMsg);
setIsLoading(false);
}
};
return (
<>
<Toaster
position="top-center"
toastOptions={{
duration: 5000,
style: {
background: '#FFFFFF',
color: '#000000',
padding: '16px',
borderRadius: '8px',
border: '1px solid #E5E5E5',
boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
},
error: {
icon: '⚠️',
style: {
background: '#ef4444',
color: '#FFFFFF',
border: 'none',
},
},
success: {
icon: '✓',
style: {
background: '#10B981',
color: '#FFFFFF',
border: 'none',
},
},
}}
/>
<div className="flex min-h-screen">
{/* Lado Esquerdo - Formulário */}
<div className="w-full lg:w-1/2 flex items-center justify-center px-6 sm:px-12 py-12">

View File

@@ -1,9 +1,35 @@
'use client';
import { BuildingOfficeIcon, ArrowLeftIcon, PaintBrushIcon, MapPinIcon } from '@heroicons/react/24/outline';
import {
BuildingOfficeIcon,
ArrowLeftIcon,
PaintBrushIcon,
MapPinIcon,
UserGroupIcon,
ChartBarIcon,
FolderIcon,
LifebuoyIcon,
CreditCardIcon,
DocumentTextIcon,
ArchiveBoxIcon,
ShareIcon
} from '@heroicons/react/24/outline';
import Link from 'next/link';
import { useEffect, useState } from 'react';
import { useParams } from 'next/navigation';
import Tabs, { TabItem } from '@/components/ui/Tabs';
// Mapeamento de ícones para cada solução
const SOLUTION_ICONS: Record<string, React.ComponentType<{ className?: string }>> = {
'crm': UserGroupIcon,
'erp': ChartBarIcon,
'projetos': FolderIcon,
'helpdesk': LifebuoyIcon,
'pagamentos': CreditCardIcon,
'contratos': DocumentTextIcon,
'documentos': ArchiveBoxIcon,
'social': ShareIcon,
};
interface AgencyTenant {
id: string;
@@ -41,6 +67,17 @@ interface AgencyDetails {
email: string;
name: string;
};
subscription?: {
plan_id: string;
plan_name: string;
status: string;
solutions: Array<{
id: string;
name: string;
slug: string;
icon: string;
}>;
};
access_url: string;
}
@@ -110,76 +147,16 @@ export default function AgencyDetailPage() {
const { tenant } = details;
return (
<div className="p-8 max-w-7xl mx-auto">
<div className="mb-8">
<Link
href="/superadmin/agencies"
className="inline-flex items-center gap-2 text-gray-500 hover:text-gray-900 dark:text-gray-400 dark:hover:text-gray-200 mb-6 transition-colors"
>
<ArrowLeftIcon className="w-4 h-4" />
Voltar para Agências
</Link>
<div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
<div className="flex items-center gap-4">
<div className="h-16 w-16 rounded-xl bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 flex items-center justify-center p-2">
{tenant.logo_url ? (
<img src={tenant.logo_url} alt={tenant.name} className="max-h-full max-w-full object-contain" />
) : (
<BuildingOfficeIcon className="w-8 h-8 text-gray-400" />
)}
</div>
<div>
<h1 className="text-2xl font-bold text-gray-900 dark:text-white">{tenant.name}</h1>
<div className="flex items-center gap-2 mt-1">
<a
href={details.access_url}
target="_blank"
rel="noopener noreferrer"
className="text-sm text-blue-600 dark:text-blue-400 hover:underline flex items-center gap-1"
>
{tenant.subdomain}.aggios.app
<ArrowLeftIcon className="w-3 h-3 rotate-135" />
</a>
<span className="text-gray-300 dark:text-gray-600">|</span>
<span className={`px-2 py-0.5 inline-flex text-xs font-medium rounded-full ${tenant.is_active
? 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400'
: 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400'
}`}>
{tenant.is_active ? 'Ativa' : 'Inativa'}
</span>
</div>
</div>
</div>
<div className="flex gap-3">
<Link
href={`/superadmin/agencies/${tenant.id}/edit`}
className="px-4 py-2 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors font-medium text-sm"
>
Editar Dados
</Link>
<button
className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors font-medium text-sm"
>
Acessar Painel
</button>
</div>
</div>
</div>
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
{/* Coluna Esquerda (2/3) */}
<div className="lg:col-span-2 space-y-6">
const tabsConfig: TabItem[] = [
{
name: 'Visão Geral',
icon: BuildingOfficeIcon,
content: (
<div className="space-y-6">
{/* Informações Básicas */}
<div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-800 overflow-hidden">
<div className="px-6 py-4 border-b border-gray-200 dark:border-gray-800 bg-gray-50/50 dark:bg-gray-800/50">
<h2 className="text-base font-semibold text-gray-900 dark:text-white flex items-center gap-2">
<BuildingOfficeIcon className="w-5 h-5 text-gray-500" />
Dados da Empresa
</h2>
</div>
<div className="p-6 grid grid-cols-1 md:grid-cols-2 gap-6">
<div>
<h3 className="text-base font-semibold text-gray-900 dark:text-white mb-4">Dados da Empresa</h3>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div>
<dt className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Razão Social</dt>
<dd className="mt-1 text-sm font-medium text-gray-900 dark:text-white">{tenant.razao_social || '-'}</dd>
@@ -203,15 +180,15 @@ export default function AgencyDetailPage() {
</div>
</div>
{/* Endereço */}
<div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-800 overflow-hidden">
<div className="px-6 py-4 border-b border-gray-200 dark:border-gray-800 bg-gray-50/50 dark:bg-gray-800/50">
<h2 className="text-base font-semibold text-gray-900 dark:text-white flex items-center gap-2">
<MapPinIcon className="w-5 h-5 text-gray-500" />
Localização
</h2>
</div>
<div className="p-6 grid grid-cols-1 md:grid-cols-2 gap-6">
<div className="border-t border-gray-200 dark:border-gray-800 pt-6"></div>
{/* Localização */}
<div>
<h3 className="text-base font-semibold text-gray-900 dark:text-white mb-4 flex items-center gap-2">
<MapPinIcon className="w-5 h-5 text-gray-500" />
Localização
</h3>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div className="md:col-span-2">
<dt className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Endereço</dt>
<dd className="mt-1 text-sm text-gray-900 dark:text-white">
@@ -240,58 +217,13 @@ export default function AgencyDetailPage() {
</div>
</div>
</div>
</div>
{/* Coluna Direita (1/3) */}
<div className="space-y-6">
{/* Branding */}
<div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-800 overflow-hidden">
<div className="px-6 py-4 border-b border-gray-200 dark:border-gray-800 bg-gray-50/50 dark:bg-gray-800/50">
<h2 className="text-base font-semibold text-gray-900 dark:text-white flex items-center gap-2">
<PaintBrushIcon className="w-5 h-5 text-gray-500" />
Identidade Visual
</h2>
</div>
<div className="p-6 space-y-6">
<div>
<dt className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider mb-2">Cores da Marca</dt>
<div className="flex gap-4">
<div className="text-center">
<div
className="w-12 h-12 rounded-lg border border-gray-200 dark:border-gray-700 mb-1"
style={{ backgroundColor: tenant.primary_color || '#000000' }}
/>
<span className="text-xs font-mono text-gray-500">{tenant.primary_color || '-'}</span>
</div>
<div className="text-center">
<div
className="w-12 h-12 rounded-lg border border-gray-200 dark:border-gray-700 mb-1"
style={{ backgroundColor: tenant.secondary_color || '#ffffff' }}
/>
<span className="text-xs font-mono text-gray-500">{tenant.secondary_color || '-'}</span>
</div>
</div>
</div>
{tenant.logo_horizontal_url && (
<div>
<dt className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider mb-2">Logo Horizontal</dt>
<div className="bg-gray-50 dark:bg-gray-800 p-4 rounded-lg border border-gray-200 dark:border-gray-700 flex justify-center">
<img src={tenant.logo_horizontal_url} alt="Logo Horizontal" className="max-h-12 max-w-full object-contain" />
</div>
</div>
)}
</div>
</div>
<div className="border-t border-gray-200 dark:border-gray-800 pt-6"></div>
{/* Contato */}
<div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-800 overflow-hidden">
<div className="px-6 py-4 border-b border-gray-200 dark:border-gray-800 bg-gray-50/50 dark:bg-gray-800/50">
<h2 className="text-base font-semibold text-gray-900 dark:text-white">
Contato
</h2>
</div>
<div className="p-6 space-y-4">
<div>
<h3 className="text-base font-semibold text-gray-900 dark:text-white mb-4">Contato</h3>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div>
<dt className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Email</dt>
<dd className="mt-1 text-sm text-gray-900 dark:text-white break-all">{tenant.email || '-'}</dd>
@@ -300,7 +232,7 @@ export default function AgencyDetailPage() {
<dt className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Telefone</dt>
<dd className="mt-1 text-sm text-gray-900 dark:text-white">{tenant.phone || '-'}</dd>
</div>
<div>
<div className="md:col-span-2">
<dt className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Website</dt>
<dd className="mt-1">
{tenant.website ? (
@@ -308,7 +240,7 @@ export default function AgencyDetailPage() {
href={tenant.website}
target="_blank"
rel="noopener noreferrer"
className="text-sm text-blue-600 dark:text-blue-400 hover:underline break-all"
className="text-sm text-[var(--brand-color)] hover:underline break-all"
>
{tenant.website}
</a>
@@ -318,25 +250,257 @@ export default function AgencyDetailPage() {
</div>
</div>
<div className="border-t border-gray-200 dark:border-gray-800 pt-6"></div>
{/* Metadados */}
<div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-800 p-6">
<dl className="space-y-3">
<div className="flex justify-between">
<dt className="text-sm text-gray-500 dark:text-gray-400">Criada em</dt>
<dd className="text-sm font-medium text-gray-900 dark:text-white">
<div>
<h3 className="text-base font-semibold text-gray-900 dark:text-white mb-4">Metadados</h3>
<dl className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div>
<dt className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Criada em</dt>
<dd className="mt-1 text-sm font-medium text-gray-900 dark:text-white">
{new Date(tenant.created_at).toLocaleDateString('pt-BR')}
</dd>
</div>
<div className="flex justify-between">
<dt className="text-sm text-gray-500 dark:text-gray-400">Última atualização</dt>
<dd className="text-sm font-medium text-gray-900 dark:text-white">
<div>
<dt className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Última atualização</dt>
<dd className="mt-1 text-sm font-medium text-gray-900 dark:text-white">
{new Date(tenant.updated_at).toLocaleDateString('pt-BR')}
</dd>
</div>
</dl>
</div>
</div>
)
},
{
name: 'Identidade Visual',
icon: PaintBrushIcon,
content: (
<div className="space-y-8">
{/* Cores da Marca */}
<div>
<h3 className="text-base font-semibold text-gray-900 dark:text-white mb-4">Cores da Marca</h3>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div>
<dt className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">Cor Primária</dt>
<div className="flex items-center gap-4">
<div
className="w-20 h-20 rounded-lg border-2 border-gray-200 dark:border-gray-700 shadow-sm"
style={{ backgroundColor: tenant.primary_color || '#000000' }}
/>
<div>
<span className="text-xs font-mono text-gray-900 dark:text-white block mb-1">
{tenant.primary_color || '-'}
</span>
<span className="text-xs text-gray-500 dark:text-gray-400">
Cor principal da marca
</span>
</div>
</div>
</div>
<div>
<dt className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">Cor Secundária</dt>
<div className="flex items-center gap-4">
<div
className="w-20 h-20 rounded-lg border-2 border-gray-200 dark:border-gray-700 shadow-sm"
style={{ backgroundColor: tenant.secondary_color || '#ffffff' }}
/>
<div>
<span className="text-xs font-mono text-gray-900 dark:text-white block mb-1">
{tenant.secondary_color || '-'}
</span>
<span className="text-xs text-gray-500 dark:text-gray-400">
Cor de apoio da marca
</span>
</div>
</div>
</div>
</div>
</div>
{/* Logos */}
<div className="border-t border-gray-200 dark:border-gray-800 pt-8">
<h3 className="text-base font-semibold text-gray-900 dark:text-white mb-4">Logotipos</h3>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
{/* Logo Principal */}
<div>
<dt className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">Logo Principal</dt>
<div className="bg-gray-50 dark:bg-gray-800 p-6 rounded-lg border border-gray-200 dark:border-gray-700 flex items-center justify-center min-h-[120px]">
{tenant.logo_url ? (
<img src={tenant.logo_url} alt="Logo" className="max-h-20 max-w-full object-contain" />
) : (
<span className="text-sm text-gray-400">Sem logo</span>
)}
</div>
</div>
{/* Logo Horizontal */}
<div>
<dt className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">Logo Horizontal</dt>
<div className="bg-gray-50 dark:bg-gray-800 p-6 rounded-lg border border-gray-200 dark:border-gray-700 flex items-center justify-center min-h-[120px]">
{tenant.logo_horizontal_url ? (
<img src={tenant.logo_horizontal_url} alt="Logo Horizontal" className="max-h-16 max-w-full object-contain" />
) : (
<span className="text-sm text-gray-400">Sem logo horizontal</span>
)}
</div>
</div>
</div>
</div>
</div>
)
},
{
name: 'Plano e Soluções',
content: (
<div className="space-y-6">
{details.subscription ? (
<>
{/* Informações do Plano */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
<div>
<dt className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Plano</dt>
<dd className="mt-1 text-lg font-semibold text-gray-900 dark:text-white">{details.subscription.plan_name}</dd>
</div>
<div>
<dt className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider mb-2">Status</dt>
<span className={`px-3 py-1 inline-flex text-sm font-medium rounded-full ${details.subscription.status === 'active'
? 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400'
: 'bg-gray-100 text-gray-800 dark:bg-gray-900/30 dark:text-gray-400'
}`}>
{details.subscription.status === 'active' ? 'Ativa' : details.subscription.status}
</span>
</div>
</div>
<div className="border-t border-gray-200 dark:border-gray-800 pt-6"></div>
{/* Soluções Disponíveis */}
{details.subscription.solutions && details.subscription.solutions.length > 0 && (
<div>
<h3 className="text-base font-semibold text-gray-900 dark:text-white mb-4">
Soluções Disponíveis ({details.subscription.solutions.length})
</h3>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{details.subscription.solutions.map((solution) => {
const Icon = SOLUTION_ICONS[solution.slug] || FolderIcon;
return (
<div
key={solution.id}
className="flex items-center gap-3 p-4 bg-gray-50 dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700"
>
<div className="p-2.5 rounded-xl bg-white dark:bg-zinc-800 border border-gray-200 dark:border-gray-700">
<Icon className="w-5 h-5 text-[var(--brand-color)]" />
</div>
<div>
<span className="text-sm font-medium text-gray-900 dark:text-white block">
{solution.name}
</span>
<span className="text-xs text-gray-500 dark:text-gray-400">
{solution.slug}
</span>
</div>
</div>
);
})}
</div>
</div>
)}
<div className="border-t border-gray-200 dark:border-gray-800 pt-6"></div>
{/* Ações */}
<div className="flex gap-3">
<Link
href={`/superadmin/plans/${details.subscription.plan_id}`}
className="inline-flex items-center px-4 py-2 bg-[var(--brand-color)] text-white rounded-lg hover:opacity-90 transition-all font-medium text-sm"
>
Ver Detalhes do Plano
</Link>
<Link
href={`/superadmin/plans/${details.subscription.plan_id}`}
className="inline-flex items-center px-4 py-2 bg-white dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-600 text-zinc-700 dark:text-zinc-300 rounded-lg hover:bg-zinc-50 dark:hover:bg-zinc-700 transition-colors font-medium text-sm"
>
Gerenciar Soluções
</Link>
</div>
</>
) : (
<div className="text-center py-12">
<svg className="w-16 h-16 text-gray-300 dark:text-gray-700 mx-auto mb-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
</svg>
<h3 className="text-lg font-medium text-gray-900 dark:text-white mb-2">Nenhuma Assinatura</h3>
<p className="text-sm text-gray-500 dark:text-gray-400">
Esta agência ainda não possui um plano ativo.
</p>
</div>
)}
</div>
)
}
];
return (
<div className="p-8 max-w-7xl mx-auto">
<div className="mb-8">
<Link
href="/superadmin/agencies"
className="inline-flex items-center gap-2 text-gray-500 hover:text-gray-900 dark:text-gray-400 dark:hover:text-gray-200 mb-6 transition-colors"
>
<ArrowLeftIcon className="w-4 h-4" />
Voltar para Agências
</Link>
<div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
<div className="flex items-center gap-4">
<div className="h-16 w-16 rounded-xl bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 flex items-center justify-center p-2">
{tenant.logo_url ? (
<img src={tenant.logo_url} alt={tenant.name} className="max-h-full max-w-full object-contain" />
) : (
<BuildingOfficeIcon className="w-8 h-8 text-gray-400" />
)}
</div>
<div>
<h1 className="text-2xl font-bold text-gray-900 dark:text-white">{tenant.name}</h1>
<div className="flex items-center gap-2 mt-1">
<a
href={details.access_url}
target="_blank"
rel="noopener noreferrer"
className="text-sm text-[var(--brand-color)] hover:underline flex items-center gap-1"
>
{tenant.subdomain}.aggios.app
<ArrowLeftIcon className="w-3 h-3 rotate-135" />
</a>
<span className="text-gray-300 dark:text-gray-600">|</span>
<span className={`px-2 py-0.5 inline-flex text-xs font-medium rounded-full ${tenant.is_active
? 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400'
: 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400'
}`}>
{tenant.is_active ? 'Ativa' : 'Inativa'}
</span>
</div>
</div>
</div>
<div className="flex gap-3">
<Link
href={`/superadmin/agencies/${tenant.id}/edit`}
className="px-4 py-2 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors font-medium text-sm"
>
Editar Dados
</Link>
<button
className="px-4 py-2 bg-[var(--brand-color)] text-white rounded-lg hover:opacity-90 transition-all font-medium text-sm"
>
Acessar Painel
</button>
</div>
</div>
</div>
<Tabs tabs={tabsConfig} />
</div>
);
}

View File

@@ -99,7 +99,7 @@ export default function NewAgencyPage() {
required
value={formData.agencyName}
onChange={handleChange}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-purple-500"
className="w-full px-3 py-2 border border-gray-200 rounded-md focus:ring-2 focus:ring-purple-500"
/>
</div>
@@ -114,7 +114,7 @@ export default function NewAgencyPage() {
value={formData.subdomain}
onChange={handleChange}
placeholder="exemplo"
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-purple-500"
className="w-full px-3 py-2 border border-gray-200 rounded-md focus:ring-2 focus:ring-purple-500"
/>
<p className="text-xs text-gray-500 mt-1">Será usado como: exemplo.aggios.app</p>
</div>
@@ -126,7 +126,7 @@ export default function NewAgencyPage() {
name="cnpj"
value={formData.cnpj}
onChange={handleChange}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-purple-500"
className="w-full px-3 py-2 border border-gray-200 rounded-md focus:ring-2 focus:ring-purple-500"
/>
</div>
@@ -137,7 +137,7 @@ export default function NewAgencyPage() {
name="razaoSocial"
value={formData.razaoSocial}
onChange={handleChange}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-purple-500"
className="w-full px-3 py-2 border border-gray-200 rounded-md focus:ring-2 focus:ring-purple-500"
/>
</div>
@@ -149,7 +149,7 @@ export default function NewAgencyPage() {
value={formData.website}
onChange={handleChange}
placeholder="https://"
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-purple-500"
className="w-full px-3 py-2 border border-gray-200 rounded-md focus:ring-2 focus:ring-purple-500"
/>
</div>
@@ -160,7 +160,7 @@ export default function NewAgencyPage() {
name="phone"
value={formData.phone}
onChange={handleChange}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-purple-500"
className="w-full px-3 py-2 border border-gray-200 rounded-md focus:ring-2 focus:ring-purple-500"
/>
</div>
@@ -172,7 +172,7 @@ export default function NewAgencyPage() {
value={formData.industry}
onChange={handleChange}
placeholder="Ex: Tecnologia, Marketing"
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-purple-500"
className="w-full px-3 py-2 border border-gray-200 rounded-md focus:ring-2 focus:ring-purple-500"
/>
</div>
@@ -182,7 +182,7 @@ export default function NewAgencyPage() {
name="teamSize"
value={formData.teamSize}
onChange={handleChange}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-purple-500"
className="w-full px-3 py-2 border border-gray-200 rounded-md focus:ring-2 focus:ring-purple-500"
>
<option value="">Selecione</option>
<option value="1-10">1-10 pessoas</option>
@@ -199,7 +199,7 @@ export default function NewAgencyPage() {
value={formData.description}
onChange={handleChange}
rows={3}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-purple-500"
className="w-full px-3 py-2 border border-gray-200 rounded-md focus:ring-2 focus:ring-purple-500"
/>
</div>
</div>
@@ -216,7 +216,7 @@ export default function NewAgencyPage() {
name="cep"
value={formData.cep}
onChange={handleChange}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-purple-500"
className="w-full px-3 py-2 border border-gray-200 rounded-md focus:ring-2 focus:ring-purple-500"
/>
</div>
@@ -229,7 +229,7 @@ export default function NewAgencyPage() {
onChange={handleChange}
maxLength={2}
placeholder="SP"
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-purple-500"
className="w-full px-3 py-2 border border-gray-200 rounded-md focus:ring-2 focus:ring-purple-500"
/>
</div>
@@ -240,7 +240,7 @@ export default function NewAgencyPage() {
name="city"
value={formData.city}
onChange={handleChange}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-purple-500"
className="w-full px-3 py-2 border border-gray-200 rounded-md focus:ring-2 focus:ring-purple-500"
/>
</div>
@@ -251,7 +251,7 @@ export default function NewAgencyPage() {
name="neighborhood"
value={formData.neighborhood}
onChange={handleChange}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-purple-500"
className="w-full px-3 py-2 border border-gray-200 rounded-md focus:ring-2 focus:ring-purple-500"
/>
</div>
@@ -262,7 +262,7 @@ export default function NewAgencyPage() {
name="number"
value={formData.number}
onChange={handleChange}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-purple-500"
className="w-full px-3 py-2 border border-gray-200 rounded-md focus:ring-2 focus:ring-purple-500"
/>
</div>
@@ -273,7 +273,7 @@ export default function NewAgencyPage() {
name="street"
value={formData.street}
onChange={handleChange}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-purple-500"
className="w-full px-3 py-2 border border-gray-200 rounded-md focus:ring-2 focus:ring-purple-500"
/>
</div>
@@ -284,7 +284,7 @@ export default function NewAgencyPage() {
name="complement"
value={formData.complement}
onChange={handleChange}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-purple-500"
className="w-full px-3 py-2 border border-gray-200 rounded-md focus:ring-2 focus:ring-purple-500"
/>
</div>
</div>
@@ -304,7 +304,7 @@ export default function NewAgencyPage() {
required
value={formData.adminName}
onChange={handleChange}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-purple-500"
className="w-full px-3 py-2 border border-gray-200 rounded-md focus:ring-2 focus:ring-purple-500"
/>
</div>
@@ -318,7 +318,7 @@ export default function NewAgencyPage() {
required
value={formData.adminEmail}
onChange={handleChange}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-purple-500"
className="w-full px-3 py-2 border border-gray-200 rounded-md focus:ring-2 focus:ring-purple-500"
/>
</div>
@@ -333,7 +333,7 @@ export default function NewAgencyPage() {
minLength={8}
value={formData.adminPassword}
onChange={handleChange}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-purple-500"
className="w-full px-3 py-2 border border-gray-200 rounded-md focus:ring-2 focus:ring-purple-500"
/>
<p className="text-xs text-gray-500 mt-1">Mínimo 8 caracteres</p>
</div>
@@ -345,7 +345,7 @@ export default function NewAgencyPage() {
<button
type="button"
onClick={() => router.back()}
className="px-6 py-2 border border-gray-300 rounded-md hover:bg-gray-50 transition-colors"
className="px-6 py-2 border border-gray-200 rounded-md hover:bg-gray-50 transition-colors"
>
Cancelar
</button>

View File

@@ -2,8 +2,12 @@
import { Fragment, useEffect, useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { Menu, Listbox, Transition } from '@headlessui/react';
import CreateAgencyModal from '@/components/agencies/CreateAgencyModal';
import ConfirmDialog from '@/components/layout/ConfirmDialog';
import Pagination from '@/components/layout/Pagination';
import { useToast } from '@/components/layout/ToastContext';
import {
BuildingOfficeIcon,
TrashIcon,
@@ -16,7 +20,15 @@ import {
CheckIcon,
ChevronUpDownIcon,
PlusIcon,
XMarkIcon
XMarkIcon,
UserGroupIcon,
ChartBarIcon,
FolderIcon,
LifebuoyIcon,
CreditCardIcon,
DocumentTextIcon,
ArchiveBoxIcon,
ShareIcon
} from '@heroicons/react/24/outline';
interface Agency {
@@ -30,8 +42,22 @@ interface Agency {
is_active: boolean;
created_at: string;
logo_url?: string;
plan_name?: string;
solutions?: Array<{ id: string; name: string; slug: string }>;
}
// Mapeamento de ícones para cada solução
const SOLUTION_ICONS: Record<string, React.ComponentType<{ className?: string }>> = {
'crm': UserGroupIcon,
'erp': ChartBarIcon,
'projetos': FolderIcon,
'helpdesk': LifebuoyIcon,
'pagamentos': CreditCardIcon,
'contratos': DocumentTextIcon,
'documentos': ArchiveBoxIcon,
'social': ShareIcon,
};
const STATUS_OPTIONS = [
{ id: 'all', name: 'Todos os Status' },
{ id: 'active', name: 'Ativas' },
@@ -47,10 +73,21 @@ const DATE_PRESETS = [
];
export default function AgenciesPage() {
const toast = useToast();
const router = useRouter();
const [agencies, setAgencies] = useState<Agency[]>([]);
const [loading, setLoading] = useState(true);
const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
// Confirmação e seleção múltipla
const [confirmOpen, setConfirmOpen] = useState(false);
const [agencyToDelete, setAgencyToDelete] = useState<string | null>(null);
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
// Paginação
const [currentPage, setCurrentPage] = useState(1);
const itemsPerPage = 10;
// Filtros
const [searchTerm, setSearchTerm] = useState('');
const [selectedStatus, setSelectedStatus] = useState(STATUS_OPTIONS[0]);
@@ -80,13 +117,16 @@ export default function AgenciesPage() {
}
};
const handleDelete = async (id: string) => {
if (!confirm('Tem certeza que deseja excluir esta agência? Esta ação não pode ser desfeita.')) {
return;
}
const handleDeleteClick = (id: string) => {
setAgencyToDelete(id);
setConfirmOpen(true);
};
const handleConfirmDelete = async () => {
if (!agencyToDelete) return;
try {
const response = await fetch(`/api/admin/agencies/${id}`, {
const response = await fetch(`/api/admin/agencies/${agencyToDelete}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${localStorage.getItem('token')}`,
@@ -94,16 +134,48 @@ export default function AgenciesPage() {
});
if (response.ok) {
setAgencies(agencies.filter(a => a.id !== id));
setAgencies(agencies.filter(a => a.id !== agencyToDelete));
selectedIds.delete(agencyToDelete);
setSelectedIds(new Set(selectedIds));
toast.success('Agência excluída', 'A agência foi excluída com sucesso.');
} else {
alert('Erro ao excluir agência');
toast.error('Erro ao excluir', 'Não foi possível excluir a agência.');
}
} catch (error) {
console.error('Error deleting agency:', error);
alert('Erro ao excluir agência');
toast.error('Erro ao excluir', 'Ocorreu um erro ao excluir a agência.');
}
};
const handleDeleteSelected = () => {
if (selectedIds.size === 0) return;
setAgencyToDelete('multiple');
setConfirmOpen(true);
};
const handleConfirmDeleteMultiple = async () => {
const idsToDelete = Array.from(selectedIds);
let successCount = 0;
for (const id of idsToDelete) {
try {
const response = await fetch(`/api/admin/agencies/${id}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${localStorage.getItem('token')}`,
},
});
if (response.ok) successCount++;
} catch (error) {
console.error('Error deleting agency:', error);
}
}
setAgencies(agencies.filter(a => !selectedIds.has(a.id)));
setSelectedIds(new Set());
toast.success(`${successCount} agência(s) excluída(s)`, 'As agências selecionadas foram excluídas.');
};
const toggleActive = async (id: string, currentStatus: boolean) => {
try {
const response = await fetch(`/api/admin/agencies/${id}`, {
@@ -176,6 +248,33 @@ export default function AgenciesPage() {
return matchesSearch && matchesStatus && matchesDate;
});
// Paginação
const totalItems = filteredAgencies.length;
const totalPages = Math.ceil(totalItems / itemsPerPage);
const paginatedAgencies = filteredAgencies.slice(
(currentPage - 1) * itemsPerPage,
currentPage * itemsPerPage
);
// Seleção múltipla
const toggleSelectAll = () => {
if (selectedIds.size === paginatedAgencies.length) {
setSelectedIds(new Set());
} else {
setSelectedIds(new Set(paginatedAgencies.map(a => a.id)));
}
};
const toggleSelect = (id: string) => {
const newSelected = new Set(selectedIds);
if (newSelected.has(id)) {
newSelected.delete(id);
} else {
newSelected.add(id);
}
setSelectedIds(newSelected);
};
return (
<div className="p-6 max-w-[1600px] mx-auto space-y-6">
{/* Header */}
@@ -186,14 +285,25 @@ export default function AgenciesPage() {
Gerencie seus parceiros e acompanhe o desempenho.
</p>
</div>
<button
onClick={() => setIsCreateModalOpen(true)}
className="inline-flex items-center justify-center gap-2 px-4 py-2.5 text-sm font-medium text-white rounded-lg hover:opacity-90 transition-opacity"
style={{ background: 'var(--gradient)' }}
>
<PlusIcon className="w-4 h-4" />
Nova Agência
</button>
<div className="flex gap-2">
{selectedIds.size > 0 && (
<button
onClick={handleDeleteSelected}
className="inline-flex items-center justify-center gap-2 px-4 py-2.5 text-sm font-medium text-white rounded-lg bg-red-600 hover:bg-red-700 transition-colors"
>
<TrashIcon className="w-4 h-4" />
Excluir ({selectedIds.size})
</button>
)}
<button
onClick={() => setIsCreateModalOpen(true)}
className="inline-flex items-center justify-center gap-2 px-4 py-2.5 text-sm font-medium text-white rounded-lg hover:opacity-90 transition-opacity"
style={{ background: 'var(--gradient)' }}
>
<PlusIcon className="w-4 h-4" />
Nova Agência
</button>
</div>
</div>
{/* Toolbar de Filtros */}
@@ -380,16 +490,50 @@ export default function AgenciesPage() {
<table className="w-full">
<thead>
<tr className="bg-zinc-50/50 dark:bg-zinc-800/50 border-b border-zinc-200 dark:border-zinc-800">
<th className="px-6 py-4 w-12">
<input
type="checkbox"
checked={selectedIds.size === paginatedAgencies.length && paginatedAgencies.length > 0}
onChange={toggleSelectAll}
className="w-4 h-4 rounded border-zinc-300 dark:border-zinc-600"
style={{ accentColor: 'var(--brand-color)' }}
/>
</th>
<th className="px-6 py-4 text-left text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Agência</th>
<th className="px-6 py-4 text-left text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Contato</th>
<th className="px-6 py-4 text-left text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Plano</th>
<th className="px-6 py-4 text-left text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Soluções</th>
<th className="px-6 py-4 text-left text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Status</th>
<th className="px-6 py-4 text-left text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Data Cadastro</th>
<th className="px-6 py-4 text-right text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Ações</th>
</tr>
</thead>
<tbody className="divide-y divide-zinc-100 dark:divide-zinc-800">
{filteredAgencies.map((agency) => (
<tr key={agency.id} className="group hover:bg-zinc-50 dark:hover:bg-zinc-800/50 transition-colors">
{paginatedAgencies.map((agency) => (
<tr
key={agency.id}
onClick={(e) => {
// Não navegar se clicar no checkbox, botões ou links
if (
(e.target as HTMLElement).closest('input[type="checkbox"]') ||
(e.target as HTMLElement).closest('button') ||
(e.target as HTMLElement).closest('a')
) {
return;
}
router.push(`/superadmin/agencies/${agency.id}`);
}}
className="group hover:bg-zinc-50 dark:hover:bg-zinc-800/50 transition-colors cursor-pointer"
>
<td className="px-6 py-4" onClick={(e) => e.stopPropagation()}>
<input
type="checkbox"
checked={selectedIds.has(agency.id)}
onChange={() => toggleSelect(agency.id)}
className="w-4 h-4 rounded border-zinc-300 dark:border-zinc-600"
style={{ accentColor: 'var(--brand-color)' }}
/>
</td>
<td className="px-6 py-4 whitespace-nowrap">
<div className="flex items-center gap-4">
{agency.logo_url ? (
@@ -428,6 +572,40 @@ export default function AgenciesPage() {
</div>
</td>
<td className="px-6 py-4 whitespace-nowrap">
{agency.plan_name ? (
<span className="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium bg-purple-50 text-purple-700 border border-purple-200 dark:bg-purple-900/20 dark:text-purple-400 dark:border-purple-900/30">
{agency.plan_name}
</span>
) : (
<span className="text-xs text-zinc-400">Sem plano</span>
)}
</td>
<td className="px-6 py-4">
{agency.solutions && agency.solutions.length > 0 ? (
<div className="flex flex-wrap gap-1 max-w-xs">
{agency.solutions.slice(0, 3).map((solution) => {
const Icon = SOLUTION_ICONS[solution.slug] || FolderIcon;
return (
<span
key={solution.id}
className="inline-flex items-center gap-1.5 px-2 py-1 rounded-md text-xs font-medium bg-zinc-100 text-zinc-700 dark:bg-zinc-800 dark:text-zinc-300 border border-zinc-200 dark:border-zinc-700"
>
<Icon className="w-3.5 h-3.5 text-[var(--brand-color)]" />
{solution.name}
</span>
);
})}
{agency.solutions.length > 3 && (
<span className="inline-flex items-center px-2 py-0.5 rounded-md text-xs font-medium bg-zinc-100 text-zinc-500 dark:bg-zinc-800 dark:text-zinc-400">
+{agency.solutions.length - 3}
</span>
)}
</div>
) : (
<span className="text-xs text-zinc-400">Sem soluções</span>
)}
</td>
<td className="px-6 py-4 whitespace-nowrap" onClick={(e) => e.stopPropagation()}>
<button
onClick={() => toggleActive(agency.id, agency.is_active)}
className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium border transition-all ${agency.is_active
@@ -446,7 +624,7 @@ export default function AgenciesPage() {
year: 'numeric'
})}
</td>
<td className="px-6 py-4 whitespace-nowrap text-right">
<td className="px-6 py-4 whitespace-nowrap text-right" onClick={(e) => e.stopPropagation()}>
<Menu as="div" className="relative inline-block text-left">
<Menu.Button className="p-2 rounded-lg hover:bg-zinc-100 dark:hover:bg-zinc-800 text-zinc-400 hover:text-zinc-600 dark:hover:text-zinc-300 transition-colors outline-none">
<EllipsisVerticalIcon className="w-5 h-5" />
@@ -487,7 +665,7 @@ export default function AgenciesPage() {
<Menu.Item>
{({ active }) => (
<button
onClick={() => handleDelete(agency.id)}
onClick={() => handleDeleteClick(agency.id)}
className={`${active ? 'bg-red-50 dark:bg-red-900/20' : ''
} group flex w-full items-center rounded-lg px-2 py-2 text-sm text-red-600 dark:text-red-400`}
>
@@ -506,23 +684,29 @@ export default function AgenciesPage() {
</table>
</div>
{/* Footer da Tabela (Paginação Mockada) */}
<div className="px-6 py-4 border-t border-zinc-200 dark:border-zinc-800 bg-zinc-50/50 dark:bg-zinc-800/50 flex items-center justify-between">
<p className="text-xs text-zinc-500 dark:text-zinc-400">
Mostrando <span className="font-medium">{filteredAgencies.length}</span> resultados
</p>
<div className="flex gap-2">
<button disabled className="px-3 py-1 text-xs font-medium text-zinc-400 bg-white dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700 rounded-md cursor-not-allowed opacity-50">
Anterior
</button>
<button disabled className="px-3 py-1 text-xs font-medium text-zinc-400 bg-white dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700 rounded-md cursor-not-allowed opacity-50">
Próxima
</button>
</div>
</div>
<Pagination
currentPage={currentPage}
totalPages={totalPages}
totalItems={totalItems}
itemsPerPage={itemsPerPage}
onPageChange={setCurrentPage}
/>
</div>
)}
<ConfirmDialog
isOpen={confirmOpen}
onClose={() => setConfirmOpen(false)}
onConfirm={agencyToDelete === 'multiple' ? handleConfirmDeleteMultiple : handleConfirmDelete}
title={agencyToDelete === 'multiple' ? `Excluir ${selectedIds.size} agências` : 'Excluir agência'}
message={agencyToDelete === 'multiple'
? `Tem certeza que deseja excluir ${selectedIds.size} agências? Esta ação não pode ser desfeita.`
: 'Tem certeza que deseja excluir esta agência? Esta ação não pode ser desfeita.'}
confirmText="Excluir"
cancelText="Cancelar"
variant="danger"
/>
<CreateAgencyModal
isOpen={isCreateModalOpen}
onClose={() => setIsCreateModalOpen(false)}

View File

@@ -0,0 +1,385 @@
"use client";
import { useState, useEffect } from "react";
import {
ArrowDownTrayIcon,
ArrowUpTrayIcon,
ClockIcon,
ServerIcon,
CheckCircleIcon,
ExclamationTriangleIcon,
BoltIcon,
} from '@heroicons/react/24/outline';
interface Backup {
filename: string;
size: string;
date: string;
timestamp: string;
}
export default function BackupPage() {
const [loading, setLoading] = useState(false);
const [backups, setBackups] = useState<Backup[]>([]);
const [selectedBackup, setSelectedBackup] = useState<string>("");
const [message, setMessage] = useState<{ type: 'success' | 'error', text: string } | null>(null);
const [autoBackupEnabled, setAutoBackupEnabled] = useState(false);
const [autoBackupInterval, setAutoBackupInterval] = useState<number>(6);
useEffect(() => {
loadBackups();
loadAutoBackupSettings();
}, []);
const loadAutoBackupSettings = () => {
const enabled = localStorage.getItem('autoBackupEnabled') === 'true';
const interval = parseInt(localStorage.getItem('autoBackupInterval') || '6');
setAutoBackupEnabled(enabled);
setAutoBackupInterval(interval);
};
const toggleAutoBackup = () => {
const newValue = !autoBackupEnabled;
setAutoBackupEnabled(newValue);
localStorage.setItem('autoBackupEnabled', newValue.toString());
if (newValue) {
startAutoBackup();
setMessage({ type: 'success', text: `Backup automático ativado (a cada ${autoBackupInterval}h)` });
} else {
stopAutoBackup();
setMessage({ type: 'success', text: 'Backup automático desativado' });
}
};
const startAutoBackup = () => {
const intervalMs = autoBackupInterval * 60 * 60 * 1000; // horas para ms
const intervalId = setInterval(() => {
createBackup();
}, intervalMs);
localStorage.setItem('autoBackupIntervalId', intervalId.toString());
};
const stopAutoBackup = () => {
const intervalId = localStorage.getItem('autoBackupIntervalId');
if (intervalId) {
clearInterval(parseInt(intervalId));
localStorage.removeItem('autoBackupIntervalId');
}
};
const changeInterval = (hours: number) => {
setAutoBackupInterval(hours);
localStorage.setItem('autoBackupInterval', hours.toString());
if (autoBackupEnabled) {
stopAutoBackup();
startAutoBackup();
setMessage({ type: 'success', text: `Intervalo alterado para ${hours}h` });
}
};
const loadBackups = async () => {
try {
const token = localStorage.getItem('token');
const response = await fetch('http://localhost:8085/api/superadmin/backups', {
headers: {
'Authorization': `Bearer ${token}`
}
});
if (response.ok) {
const data = await response.json();
setBackups(data.backups || []);
}
} catch (error) {
console.error('Erro ao carregar backups:', error);
}
};
const createBackup = async () => {
setLoading(true);
setMessage(null);
try {
const token = localStorage.getItem('token');
const response = await fetch('http://localhost:8085/api/superadmin/backup/create', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`
}
});
const data = await response.json();
if (response.ok) {
setMessage({ type: 'success', text: `Backup criado: ${data.filename} (${data.size})` });
await loadBackups();
} else {
setMessage({ type: 'error', text: data.error || 'Erro ao criar backup' });
}
} catch (error) {
setMessage({ type: 'error', text: 'Erro ao criar backup' });
} finally {
setLoading(false);
}
};
const restoreBackup = async () => {
if (!selectedBackup) {
setMessage({ type: 'error', text: 'Selecione um backup para restaurar' });
return;
}
if (!confirm(`⚠️ ATENÇÃO: Isso irá SOBRESCREVER todos os dados atuais!\n\nDeseja restaurar o backup:\n${selectedBackup}?`)) {
return;
}
setLoading(true);
setMessage(null);
try {
const token = localStorage.getItem('token');
const response = await fetch('http://localhost:8085/api/superadmin/backup/restore', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ filename: selectedBackup })
});
const data = await response.json();
if (response.ok) {
setMessage({ type: 'success', text: 'Backup restaurado com sucesso! Recarregando...' });
setTimeout(() => {
window.location.reload();
}, 2000);
} else {
setMessage({ type: 'error', text: data.error || 'Erro ao restaurar backup' });
}
} catch (error) {
setMessage({ type: 'error', text: 'Erro ao restaurar backup' });
} finally {
setLoading(false);
}
};
const downloadBackup = async (filename: string) => {
try {
const token = localStorage.getItem('token');
const response = await fetch(`http://localhost:8085/api/superadmin/backup/download/${filename}`, {
headers: {
'Authorization': `Bearer ${token}`
}
});
if (response.ok) {
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
} else {
setMessage({ type: 'error', text: 'Erro ao baixar backup' });
}
} catch (error) {
setMessage({ type: 'error', text: 'Erro ao baixar backup' });
}
};
return (
<div className="min-h-screen bg-gray-50 dark:bg-gray-900 py-8">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="mb-8">
<h1 className="text-3xl font-bold text-gray-900 dark:text-white">
Backup & Restore
</h1>
<p className="mt-2 text-sm text-gray-600 dark:text-gray-400">
Gerencie backups do banco de dados PostgreSQL
</p>
</div>
{message && (
<div className={`mb-6 p-4 rounded-lg flex items-center gap-3 ${message.type === 'success'
? 'bg-green-50 dark:bg-green-900/20 text-green-800 dark:text-green-200'
: 'bg-red-50 dark:bg-red-900/20 text-red-800 dark:text-red-200'
}`}>
{message.type === 'success' ? (
<CheckCircleIcon className="h-5 w-5" />
) : (
<ExclamationTriangleIcon className="h-5 w-5" />
)}
<span>{message.text}</span>
</div>
)}
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-8">
<div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
<div className="flex items-center gap-3 mb-4">
<div className="p-3 bg-blue-100 dark:bg-blue-900/30 rounded-lg">
<ArrowDownTrayIcon className="h-6 w-6 text-blue-600 dark:text-blue-400" />
</div>
<div>
<h2 className="text-lg font-semibold text-gray-900 dark:text-white">
Criar Backup
</h2>
<p className="text-sm text-gray-600 dark:text-gray-400">
Exportar dados atuais
</p>
</div>
</div>
<button
onClick={createBackup}
disabled={loading}
className="w-full px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:bg-gray-400 disabled:cursor-not-allowed transition-colors"
>
{loading ? 'Criando...' : 'Criar Novo Backup'}
</button>
</div>
<div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
<div className="flex items-center gap-3 mb-4">
<div className="p-3 bg-green-100 dark:bg-green-900/30 rounded-lg">
<BoltIcon className="h-6 w-6 text-green-600 dark:text-green-400" />
</div>
<div>
<h2 className="text-lg font-semibold text-gray-900 dark:text-white">
Backup Automático
</h2>
<p className="text-sm text-gray-600 dark:text-gray-400">
{autoBackupEnabled ? `Ativo (${autoBackupInterval}h)` : 'Desativado'}
</p>
</div>
</div>
<div className="space-y-3">
<select
value={autoBackupInterval}
onChange={(e) => changeInterval(parseInt(e.target.value))}
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
>
<option value={1}>A cada 1 hora</option>
<option value={3}>A cada 3 horas</option>
<option value={6}>A cada 6 horas</option>
<option value={12}>A cada 12 horas</option>
<option value={24}>A cada 24 horas</option>
</select>
<button
onClick={toggleAutoBackup}
className={`w-full px-4 py-2 rounded-lg transition-colors ${
autoBackupEnabled
? 'bg-red-600 hover:bg-red-700 text-white'
: 'bg-green-600 hover:bg-green-700 text-white'
}`}
>
{autoBackupEnabled ? 'Desativar' : 'Ativar'}
</button>
</div>
</div>
<div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
<div className="flex items-center gap-3 mb-4">
<div className="p-3 bg-amber-100 dark:bg-amber-900/30 rounded-lg">
<ArrowUpTrayIcon className="h-6 w-6 text-amber-600 dark:text-amber-400" />
</div>
<div>
<h2 className="text-lg font-semibold text-gray-900 dark:text-white">
Restaurar Backup
</h2>
<p className="text-sm text-gray-600 dark:text-gray-400">
Sobrescreve dados atuais
</p>
</div>
</div>
<select
value={selectedBackup}
onChange={(e) => setSelectedBackup(e.target.value)}
className="w-full mb-3 px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
>
<option value="">Selecione um backup...</option>
{backups.map((backup) => (
<option key={backup.filename} value={backup.filename}>
{backup.filename} - {backup.size}
</option>
))}
</select>
<button
onClick={restoreBackup}
disabled={loading || !selectedBackup}
className="w-full px-4 py-2 bg-amber-600 text-white rounded-lg hover:bg-amber-700 disabled:bg-gray-400 disabled:cursor-not-allowed transition-colors"
>
{loading ? 'Restaurando...' : 'Restaurar Backup'}
</button>
</div>
</div>
<div className="bg-white dark:bg-gray-800 rounded-lg shadow">
<div className="p-6 border-b border-gray-200 dark:border-gray-700">
<div className="flex items-center gap-3">
<ServerIcon className="h-6 w-6 text-gray-600 dark:text-gray-400" />
<h2 className="text-lg font-semibold text-gray-900 dark:text-white">
Backups Disponíveis
</h2>
<span className="ml-auto text-sm text-gray-500 dark:text-gray-400">
{backups.length} arquivo(s)
</span>
</div>
</div>
<div className="p-6">
{backups.length === 0 ? (
<div className="text-center py-12">
<ServerIcon className="mx-auto h-12 w-12 text-gray-400" />
<p className="mt-2 text-sm text-gray-600 dark:text-gray-400">
Nenhum backup encontrado
</p>
</div>
) : (
<div className="space-y-3">
{backups.map((backup) => (
<div
key={backup.filename}
className={`p-4 rounded-lg border transition-colors cursor-pointer ${selectedBackup === backup.filename
? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20'
: 'border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-700/50'
}`}
onClick={() => setSelectedBackup(backup.filename)}
>
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<ClockIcon className="h-5 w-5 text-gray-400" />
<div>
<p className="font-medium text-gray-900 dark:text-white">
{backup.filename}
</p>
<p className="text-sm text-gray-600 dark:text-gray-400">
{backup.date} {backup.size}
</p>
</div>
</div>
<button
onClick={(e) => {
e.stopPropagation();
downloadBackup(backup.filename);
}}
className="px-3 py-1 text-sm text-blue-600 dark:text-blue-400 hover:bg-blue-100 dark:hover:bg-blue-900/30 rounded"
>
Download
</button>
</div>
</div>
))}
</div>
)}
</div>
</div>
</div>
</div>
);
}

View File

@@ -1,6 +1,29 @@
"use client";
import { DashboardLayout } from '@/components/layout/DashboardLayout';
import {
HomeIcon,
BuildingOfficeIcon,
LinkIcon,
DocumentTextIcon,
Cog6ToothIcon,
SparklesIcon,
ServerIcon,
RectangleGroupIcon,
} from '@heroicons/react/24/outline';
const SUPERADMIN_MENU_ITEMS = [
{ id: 'dashboard', label: 'Dashboard', href: '/superadmin', icon: HomeIcon },
{ id: 'agencies', label: 'Agências', href: '/superadmin/agencies', icon: BuildingOfficeIcon },
{ id: 'plans', label: 'Planos', href: '/superadmin/plans', icon: SparklesIcon },
{ id: 'solutions', label: 'Soluções', href: '/superadmin/solutions', icon: RectangleGroupIcon },
{ id: 'templates', label: 'Templates', href: '/superadmin/signup-templates', icon: LinkIcon },
{ id: 'agency-templates', label: 'Templates Agência', href: '/superadmin/agency-templates', icon: DocumentTextIcon },
{ id: 'backup', label: 'Backup & Restore', href: '/superadmin/backup', icon: ServerIcon },
{ id: 'settings', label: 'Configurações', href: '/superadmin/settings', icon: Cog6ToothIcon },
];
import AuthGuard from '@/components/auth/AuthGuard';
export default function SuperAdminLayout({
children,
@@ -8,8 +31,10 @@ export default function SuperAdminLayout({
children: React.ReactNode;
}) {
return (
<DashboardLayout>
{children}
</DashboardLayout>
<AuthGuard>
<DashboardLayout menuItems={SUPERADMIN_MENU_ITEMS}>
{children}
</DashboardLayout>
</AuthGuard>
);
}

View File

@@ -0,0 +1,564 @@
'use client';
import { useEffect, useState } from 'react';
import { useRouter, useParams } from 'next/navigation';
import {
ArrowLeftIcon,
CheckCircleIcon,
UserGroupIcon,
ChartBarIcon,
FolderIcon,
LifebuoyIcon,
CreditCardIcon,
DocumentTextIcon,
ArchiveBoxIcon,
ShareIcon
} from '@heroicons/react/24/outline';
// Mapeamento de ícones para cada solução
const SOLUTION_ICONS: Record<string, React.ComponentType<{ className?: string }>> = {
'crm': UserGroupIcon,
'erp': ChartBarIcon,
'projetos': FolderIcon,
'helpdesk': LifebuoyIcon,
'pagamentos': CreditCardIcon,
'contratos': DocumentTextIcon,
'documentos': ArchiveBoxIcon,
'social': ShareIcon,
};
interface Plan {
id: string;
name: string;
slug: string;
description: string;
min_users: number;
max_users: number;
monthly_price: number | null;
annual_price: number | null;
features: string[];
differentiators: string[];
storage_gb: number;
is_active: boolean;
created_at: string;
}
interface Solution {
id: string;
name: string;
slug: string;
icon: string;
description: string;
is_active: boolean;
}
export default function EditPlanPage() {
const router = useRouter();
const params = useParams();
const planId = params.id as string;
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const [success, setSuccess] = useState(false);
const [plan, setPlan] = useState<Plan | null>(null);
const [formData, setFormData] = useState<Partial<Plan>>({});
const [allSolutions, setAllSolutions] = useState<Solution[]>([]);
const [selectedSolutions, setSelectedSolutions] = useState<string[]>([]);
const [loadingSolutions, setLoadingSolutions] = useState(true);
useEffect(() => {
const token = localStorage.getItem('token');
if (!token) {
router.push('/login');
return;
}
fetchPlan();
fetchSolutions();
fetchPlanSolutions();
}, [planId, router]);
const fetchPlan = async () => {
try {
setLoading(true);
const token = localStorage.getItem('token');
const response = await fetch(`/api/admin/plans/${planId}`, {
headers: {
'Authorization': `Bearer ${token}`,
},
});
if (!response.ok) {
throw new Error('Erro ao carregar plano');
}
const data = await response.json();
setPlan(data.plan);
setFormData(data.plan);
} catch (err) {
setError(err instanceof Error ? err.message : 'Erro ao carregar plano');
} finally {
setLoading(false);
}
};
const fetchSolutions = async () => {
try {
const token = localStorage.getItem('token');
const response = await fetch('/api/admin/solutions', {
headers: {
'Authorization': `Bearer ${token}`,
},
});
if (response.ok) {
const data = await response.json();
setAllSolutions(data.solutions || []);
}
} catch (err) {
console.error('Erro ao carregar soluções:', err);
}
};
const fetchPlanSolutions = async () => {
try {
setLoadingSolutions(true);
const token = localStorage.getItem('token');
const response = await fetch(`/api/admin/plans/${planId}/solutions`, {
headers: {
'Authorization': `Bearer ${token}`,
},
});
if (response.ok) {
const data = await response.json();
const solutionIds = data.solutions?.map((s: Solution) => s.id) || [];
setSelectedSolutions(solutionIds);
}
} catch (err) {
console.error('Erro ao carregar soluções do plano:', err);
} finally {
setLoadingSolutions(false);
}
};
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
const { name, value, type } = e.target;
if (type === 'checkbox') {
setFormData(prev => ({
...prev,
[name]: (e.target as HTMLInputElement).checked,
}));
} else if (type === 'number') {
setFormData(prev => ({
...prev,
[name]: value === '' ? null : parseFloat(value),
}));
} else {
setFormData(prev => ({
...prev,
[name]: value,
}));
}
};
const handleSave = async () => {
try {
setSaving(true);
setError(null);
setSuccess(false);
const token = localStorage.getItem('token');
// Parse features e differentiators
const features = (formData.features as any)
.split(',')
.map((f: string) => f.trim())
.filter((f: string) => f.length > 0);
const differentiators = (formData.differentiators as any)
.split(',')
.map((d: string) => d.trim())
.filter((d: string) => d.length > 0);
const payload = {
...formData,
features,
differentiators,
};
const response = await fetch(`/api/admin/plans/${planId}`, {
method: 'PUT',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(payload),
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.message || 'Erro ao atualizar plano');
}
// Salvar soluções associadas
const solutionsResponse = await fetch(`/api/admin/plans/${planId}/solutions`, {
method: 'PUT',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ solution_ids: selectedSolutions }),
});
if (!solutionsResponse.ok) {
throw new Error('Erro ao atualizar soluções do plano');
}
setSuccess(true);
setTimeout(() => setSuccess(false), 3000);
} catch (err) {
setError(err instanceof Error ? err.message : 'Erro ao atualizar plano');
} finally {
setSaving(false);
}
};
if (loading) {
return (
<div className="flex items-center justify-center min-h-[400px]">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[var(--brand-color)]"></div>
</div>
);
}
if (!plan) {
return (
<div className="text-center py-12">
<p className="text-red-600 dark:text-red-400">Plano não encontrado</p>
</div>
);
}
return (
<div className="p-6 max-w-[1600px] mx-auto space-y-6">
{/* Header */}
<div className="flex items-center gap-4 mb-6">
<button
onClick={() => router.back()}
className="inline-flex items-center gap-2 text-zinc-500 hover:text-zinc-900 dark:text-zinc-400 dark:hover:text-zinc-200 transition-colors"
>
<ArrowLeftIcon className="w-4 h-4" />
Voltar
</button>
</div>
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
<div>
<h1 className="text-2xl font-bold text-zinc-900 dark:text-white tracking-tight">Editar Plano</h1>
<p className="text-sm text-zinc-500 dark:text-zinc-400 mt-1">{plan.name}</p>
</div>
</div>
{/* Success Message */}
{success && (
<div className="rounded-xl bg-emerald-50 dark:bg-emerald-900/20 p-4 border border-emerald-200 dark:border-emerald-800 flex items-center gap-3">
<CheckCircleIcon className="h-5 w-5 text-emerald-600 dark:text-emerald-400 flex-shrink-0" />
<p className="text-sm font-medium text-emerald-800 dark:text-emerald-400">Plano atualizado com sucesso!</p>
</div>
)}
{/* Error Message */}
{error && (
<div className="rounded-xl bg-red-50 dark:bg-red-900/20 p-4 border border-red-200 dark:border-red-800">
<p className="text-sm font-medium text-red-800 dark:text-red-400">{error}</p>
</div>
)}
{/* Form Card */}
<div className="bg-white dark:bg-zinc-900 rounded-xl border border-zinc-200 dark:border-zinc-800 overflow-hidden">
<form className="p-6" onSubmit={(e) => { e.preventDefault(); handleSave(); }}>
<div className="space-y-6">
{/* Row 1: Nome e Slug */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
Nome do Plano
</label>
<input
type="text"
name="name"
value={formData.name || ''}
onChange={handleInputChange}
className="w-full px-3 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-[var(--brand-color)] focus:border-transparent transition-all"
/>
</div>
<div>
<label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
Slug
</label>
<input
type="text"
name="slug"
value={formData.slug || ''}
onChange={handleInputChange}
className="w-full px-3 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-[var(--brand-color)] focus:border-transparent transition-all"
/>
</div>
</div>
{/* Descrição */}
<div>
<label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
Descrição
</label>
<textarea
name="description"
value={formData.description || ''}
onChange={handleInputChange}
rows={3}
className="w-full px-3 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-[var(--brand-color)] focus:border-transparent transition-all resize-none"
/>
</div>
{/* Row 2: Usuários */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
Mínimo de Usuários
</label>
<input
type="number"
name="min_users"
value={formData.min_users || 1}
onChange={handleInputChange}
min="1"
className="w-full px-3 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-[var(--brand-color)] focus:border-transparent transition-all"
/>
</div>
<div>
<label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
Máximo de Usuários (-1 = ilimitado)
</label>
<input
type="number"
name="max_users"
value={formData.max_users || 30}
onChange={handleInputChange}
className="w-full px-3 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-[var(--brand-color)] focus:border-transparent transition-all"
/>
</div>
</div>
{/* Row 3: Preços */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
Preço Mensal (BRL)
</label>
<input
type="number"
name="monthly_price"
value={formData.monthly_price || ''}
onChange={handleInputChange}
step="0.01"
className="w-full px-3 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-[var(--brand-color)] focus:border-transparent transition-all"
/>
</div>
<div>
<label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
Preço Anual (BRL)
</label>
<input
type="number"
name="annual_price"
value={formData.annual_price || ''}
onChange={handleInputChange}
step="0.01"
className="w-full px-3 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-[var(--brand-color)] focus:border-transparent transition-all"
/>
</div>
</div>
{/* Armazenamento */}
<div>
<label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
Armazenamento (GB)
</label>
<input
type="number"
name="storage_gb"
value={formData.storage_gb || 1}
onChange={handleInputChange}
min="1"
className="w-full px-3 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-[var(--brand-color)] focus:border-transparent transition-all"
/>
</div>
{/* Features */}
<div>
<label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
Recursos <span className="text-xs font-normal text-zinc-500 dark:text-zinc-400">(separados por vírgula)</span>
</label>
<textarea
name="features"
value={typeof formData.features === 'string' ? formData.features : (formData.features || []).join(', ')}
onChange={handleInputChange}
rows={3}
className="w-full px-3 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-[var(--brand-color)] focus:border-transparent transition-all resize-none"
/>
</div>
{/* Differentiators */}
<div>
<label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
Diferenciais <span className="text-xs font-normal text-zinc-500 dark:text-zinc-400">(separados por vírgula)</span>
</label>
<textarea
name="differentiators"
value={typeof formData.differentiators === 'string' ? formData.differentiators : (formData.differentiators || []).join(', ')}
onChange={handleInputChange}
rows={3}
className="w-full px-3 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-[var(--brand-color)] focus:border-transparent transition-all resize-none"
/>
</div>
{/* Soluções Incluídas */}
<div className="pt-6 border-t border-zinc-200 dark:border-zinc-700">
<div className="mb-4">
<h3 className="text-base font-medium text-zinc-900 dark:text-white mb-1">
Soluções Incluídas
</h3>
<p className="text-sm text-zinc-600 dark:text-zinc-400">
Selecione quais soluções estarão disponíveis para agências com este plano
</p>
</div>
{loadingSolutions ? (
<div className="flex items-center justify-center py-8">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[var(--brand-color)]"></div>
</div>
) : allSolutions.length === 0 ? (
<div className="rounded-lg bg-zinc-50 dark:bg-zinc-800 p-6 text-center">
<p className="text-sm text-zinc-600 dark:text-zinc-400">
Nenhuma solução cadastrada ainda.
</p>
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{allSolutions.map((solution) => (
<label
key={solution.id}
className={`flex items-start gap-3 p-4 rounded-lg border-2 cursor-pointer transition-all ${selectedSolutions.includes(solution.id)
? 'bg-zinc-50 dark:bg-zinc-800/50'
: 'border-zinc-200 dark:border-zinc-700 hover:border-zinc-300 dark:hover:border-zinc-600'
}`}
style={{
borderColor: selectedSolutions.includes(solution.id) ? 'var(--brand-color)' : undefined
}}
>
<input
type="checkbox"
checked={selectedSolutions.includes(solution.id)}
onChange={(e) => {
if (e.target.checked) {
setSelectedSolutions([...selectedSolutions, solution.id]);
} else {
setSelectedSolutions(selectedSolutions.filter(id => id !== solution.id));
}
}}
className="mt-0.5 h-5 w-5 rounded border-zinc-300 dark:border-zinc-600 text-[var(--brand-color)] focus:ring-[var(--brand-color)] dark:bg-zinc-800 cursor-pointer"
style={{
accentColor: 'var(--brand-color)'
}}
/>
<div className="flex-1">
<div className="flex items-center gap-3">
<div className="w-8 h-8 rounded-lg bg-white dark:bg-zinc-800 border-2 flex items-center justify-center flex-shrink-0" style={{ borderColor: 'var(--brand-color)' }}>
{(() => {
const Icon = SOLUTION_ICONS[solution.slug] || FolderIcon;
return <Icon className="w-4 h-4 text-[var(--brand-color)]" />;
})()}
</div>
<span className="font-medium text-zinc-900 dark:text-white">
{solution.name}
</span>
{!solution.is_active && (
<span className="px-2 py-0.5 text-xs font-medium bg-zinc-200 dark:bg-zinc-700 text-zinc-600 dark:text-zinc-400 rounded">
Inativo
</span>
)}
</div>
{solution.description && (
<p className="mt-1 text-sm text-zinc-600 dark:text-zinc-400">
{solution.description}
</p>
)}
<code className="mt-1 inline-block text-xs text-zinc-500 dark:text-zinc-500">
{solution.slug}
</code>
</div>
</label>
))}
</div>
)}
{selectedSolutions.length > 0 && (
<div className="mt-4 p-4 rounded-lg border" style={{
backgroundColor: 'var(--brand-color-light, rgba(59, 130, 246, 0.1))',
borderColor: 'var(--brand-color)'
}}>
<p className="text-sm font-medium" style={{ color: 'var(--brand-color)' }}>
{selectedSolutions.length} {selectedSolutions.length === 1 ? 'solução selecionada' : 'soluções selecionadas'}
</p>
</div>
)}
</div>
{/* Status Checkbox */}
<div className="pt-4 border-t border-zinc-200 dark:border-zinc-700">
<label className="flex items-center gap-3">
<input
type="checkbox"
name="is_active"
checked={formData.is_active || false}
onChange={handleInputChange}
className="h-5 w-5 rounded border-zinc-300 dark:border-zinc-600 text-[var(--brand-color)] focus:ring-[var(--brand-color)] dark:bg-zinc-800 cursor-pointer"
style={{
accentColor: 'var(--brand-color)'
}}
/>
<span className="text-sm font-medium text-zinc-900 dark:text-white">Plano Ativo</span>
</label>
</div>
{/* Buttons */}
<div className="flex gap-3 pt-6 border-t border-zinc-200 dark:border-zinc-700">
<button
type="submit"
disabled={saving}
className="flex-1 px-6 py-2.5 bg-gradient-to-r text-white font-medium rounded-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed shadow-sm hover:shadow-md"
style={{
backgroundImage: 'var(--gradient)'
}}
>
{saving ? 'Salvando...' : 'Salvar Alterações'}
</button>
<button
type="button"
onClick={() => router.back()}
disabled={saving}
className="flex-1 px-6 py-2.5 border border-zinc-300 dark:border-zinc-600 text-zinc-700 dark:text-zinc-300 font-medium rounded-lg hover:bg-zinc-50 dark:hover:bg-zinc-800 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
>
Cancelar
</button>
</div>
</div>
</form>
</div>
</div>
);
}

View File

@@ -0,0 +1,561 @@
"use client";
import { Fragment, useEffect, useState } from 'react';
import { Menu, Listbox, Transition } from '@headlessui/react';
import CreatePlanModal from '@/components/plans/CreatePlanModal';
import EditPlanModal from '@/components/plans/EditPlanModal';
import ConfirmDialog from '@/components/layout/ConfirmDialog';
import Pagination from '@/components/layout/Pagination';
import { useToast } from '@/components/layout/ToastContext';
import {
SparklesIcon,
TrashIcon,
PencilIcon,
EllipsisVerticalIcon,
MagnifyingGlassIcon,
CheckIcon,
ChevronUpDownIcon,
PlusIcon,
XMarkIcon
} from '@heroicons/react/24/outline';
interface Plan {
id: string;
name: string;
description?: string;
monthly_price?: string;
annual_price?: string;
min_users: number;
max_users: number;
storage_gb: number;
is_active: boolean;
features?: string[];
differentiators?: string[];
solutions_count?: number;
}
const STATUS_OPTIONS = [
{ id: 'all', name: 'Todos os Status' },
{ id: 'active', name: 'Ativos' },
{ id: 'inactive', name: 'Inativos' },
];
export default function PlansPage() {
const toast = useToast();
const [plans, setPlans] = useState<Plan[]>([]);
const [loading, setLoading] = useState(true);
const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
const [isEditModalOpen, setIsEditModalOpen] = useState(false);
const [editingPlanId, setEditingPlanId] = useState<string | null>(null);
const [confirmOpen, setConfirmOpen] = useState(false);
const [planToDelete, setPlanToDelete] = useState<string | null>(null);
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
const [currentPage, setCurrentPage] = useState(1);
const itemsPerPage = 10;
const [searchTerm, setSearchTerm] = useState('');
const [selectedStatus, setSelectedStatus] = useState(STATUS_OPTIONS[0]);
useEffect(() => {
fetchPlans();
}, []);
const fetchPlans = async () => {
try {
const response = await fetch('/api/admin/plans', {
headers: {
'Authorization': `Bearer ${localStorage.getItem('token')}`,
},
});
if (response.ok) {
const data = await response.json();
const plansData = data.plans || [];
// Buscar contagem de soluções para cada plano
const plansWithSolutions = await Promise.all(
plansData.map(async (plan: Plan) => {
try {
const solResponse = await fetch(`/api/admin/plans/${plan.id}/solutions`, {
headers: {
'Authorization': `Bearer ${localStorage.getItem('token')}`,
},
});
if (solResponse.ok) {
const solData = await solResponse.json();
return { ...plan, solutions_count: solData.solutions?.length || 0 };
}
} catch (e) {
console.error('Erro ao buscar soluções do plano:', e);
}
return { ...plan, solutions_count: 0 };
})
);
setPlans(plansWithSolutions);
}
} catch (error) {
console.error('Error fetching plans:', error);
} finally {
setLoading(false);
}
};
const handleDeleteClick = (id: string) => {
setPlanToDelete(id);
setConfirmOpen(true);
};
const handleConfirmDelete = async () => {
if (!planToDelete) return;
try {
const response = await fetch(`/api/admin/plans/${planToDelete}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${localStorage.getItem('token')}`,
},
});
if (response.ok) {
setPlans(plans.filter(p => p.id !== planToDelete));
selectedIds.delete(planToDelete);
setSelectedIds(new Set(selectedIds));
toast.success('Plano excluído', 'O plano foi excluído com sucesso.');
} else {
toast.error('Erro ao excluir', 'Não foi possível excluir o plano.');
}
} catch (error) {
console.error('Error deleting plan:', error);
toast.error('Erro ao excluir', 'Ocorreu um erro ao excluir o plano.');
} finally {
setConfirmOpen(false);
setPlanToDelete(null);
}
};
const handleDeleteSelected = () => {
if (selectedIds.size === 0) return;
setPlanToDelete('multiple');
setConfirmOpen(true);
};
const handleConfirmDeleteMultiple = async () => {
const idsToDelete = Array.from(selectedIds);
let successCount = 0;
for (const id of idsToDelete) {
try {
const response = await fetch(`/api/admin/plans/${id}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${localStorage.getItem('token')}`,
},
});
if (response.ok) successCount++;
} catch (error) {
console.error('Error deleting plan:', error);
}
}
setPlans(plans.filter(p => !selectedIds.has(p.id)));
setSelectedIds(new Set());
toast.success(`${successCount} plano(s) excluído(s)`, 'Os planos selecionados foram excluídos.');
setConfirmOpen(false);
setPlanToDelete(null);
};
const toggleActive = async (id: string, currentStatus: boolean) => {
try {
const response = await fetch(`/api/admin/plans/${id}`, {
method: 'PATCH',
headers: {
'Authorization': `Bearer ${localStorage.getItem('token')}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ is_active: !currentStatus }),
});
if (response.ok) {
setPlans(plans.map(p =>
p.id === id ? { ...p, is_active: !currentStatus } : p
));
}
} catch (error) {
console.error('Error toggling plan status:', error);
}
};
const clearFilters = () => {
setSearchTerm('');
setSelectedStatus(STATUS_OPTIONS[0]);
};
const handleEdit = (planId: string) => {
setEditingPlanId(planId);
setIsEditModalOpen(true);
};
const handleEditSuccess = () => {
fetchPlans();
toast.success('Plano atualizado', 'O plano foi atualizado com sucesso.');
};
// Lógica de Filtragem
const filteredPlans = plans.filter((plan) => {
// Texto
const searchLower = searchTerm.toLowerCase();
const matchesSearch =
(plan.name?.toLowerCase() || '').includes(searchLower) ||
(plan.description?.toLowerCase() || '').includes(searchLower);
// Status
const matchesStatus =
selectedStatus.id === 'all' ? true :
selectedStatus.id === 'active' ? plan.is_active :
!plan.is_active;
return matchesSearch && matchesStatus;
});
// Paginação
const totalItems = filteredPlans.length;
const totalPages = Math.ceil(totalItems / itemsPerPage);
const paginatedPlans = filteredPlans.slice(
(currentPage - 1) * itemsPerPage,
currentPage * itemsPerPage
);
// Seleção múltipla
const toggleSelectAll = () => {
if (selectedIds.size === paginatedPlans.length) {
setSelectedIds(new Set());
} else {
setSelectedIds(new Set(paginatedPlans.map(p => p.id)));
}
};
const toggleSelect = (id: string) => {
const newSelected = new Set(selectedIds);
if (newSelected.has(id)) {
newSelected.delete(id);
} else {
newSelected.add(id);
}
setSelectedIds(newSelected);
};
return (
<div className="p-6 max-w-[1600px] mx-auto space-y-6">
{/* Header */}
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
<div>
<h1 className="text-2xl font-bold text-zinc-900 dark:text-white tracking-tight">Planos</h1>
<p className="text-sm text-zinc-500 dark:text-zinc-400 mt-1">
Gerencie os planos de assinatura da plataforma.
</p>
</div>
<div className="flex items-center gap-2">
{selectedIds.size > 0 && (
<button
onClick={handleDeleteSelected}
className="inline-flex items-center justify-center gap-2 px-4 py-2.5 text-sm font-medium text-white bg-red-600 rounded-lg hover:bg-red-700 transition-colors"
>
<TrashIcon className="w-4 h-4" />
Excluir ({selectedIds.size})
</button>
)}
<button
onClick={() => setIsCreateModalOpen(true)}
className="inline-flex items-center justify-center gap-2 px-4 py-2.5 text-sm font-medium text-white rounded-lg hover:opacity-90 transition-opacity"
style={{ background: 'var(--gradient)' }}
>
<PlusIcon className="w-4 h-4" />
Novo Plano
</button>
</div>
</div>
{/* Toolbar de Filtros */}
<div className="flex flex-col lg:flex-row gap-4 items-center justify-between">
{/* Busca */}
<div className="relative w-full lg:w-96">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<MagnifyingGlassIcon className="h-5 w-5 text-zinc-400" aria-hidden="true" />
</div>
<input
type="text"
className="block w-full pl-10 pr-3 py-2 border border-zinc-200 dark:border-zinc-700 rounded-lg leading-5 bg-white dark:bg-zinc-900 text-zinc-900 dark:text-zinc-100 placeholder-zinc-400 focus:outline-none focus:ring-1 focus:ring-[var(--brand-color)] focus:border-[var(--brand-color)] sm:text-sm transition duration-150 ease-in-out"
placeholder="Buscar por nome, email ou subdomínio..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
</div>
<div className="flex flex-col sm:flex-row gap-3 w-full lg:w-auto">
{/* Filtro de Status */}
<Listbox value={selectedStatus} onChange={setSelectedStatus}>
<div className="relative w-full sm:w-[180px]">
<Listbox.Button className="relative w-full cursor-pointer rounded-lg bg-white dark:bg-zinc-900 py-2 pl-3 pr-10 text-left text-sm border border-zinc-200 dark:border-zinc-700 focus:outline-none focus:border-[var(--brand-color)] focus:ring-1 focus:ring-[var(--brand-color)] text-zinc-700 dark:text-zinc-300">
<span className="block truncate">{selectedStatus.name}</span>
<span className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2">
<ChevronUpDownIcon className="h-4 w-4 text-zinc-400" aria-hidden="true" />
</span>
</Listbox.Button>
<Transition
as={Fragment}
leave="transition ease-in duration-100"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<Listbox.Options className="absolute z-10 mt-1 max-h-60 w-full overflow-auto rounded-md bg-white dark:bg-zinc-800 py-1 text-base ring-1 ring-black ring-opacity-5 focus:outline-none sm:text-sm border border-zinc-200 dark:border-zinc-700">
{STATUS_OPTIONS.map((status, statusIdx) => (
<Listbox.Option
key={statusIdx}
className={({ active, selected }) =>
`relative cursor-default select-none py-2 pl-10 pr-4 ${active ? 'bg-zinc-100 dark:bg-zinc-700 text-zinc-900 dark:text-white' : 'text-zinc-900 dark:text-zinc-100'
}`
}
value={status}
>
{({ selected }) => (
<>
<span className={`block truncate ${selected ? 'font-medium' : 'font-normal'}`}>
{status.name}
</span>
{selected ? (
<span className="absolute inset-y-0 left-0 flex items-center pl-3 text-[var(--brand-color)]">
<CheckIcon className="h-4 w-4" aria-hidden="true" />
</span>
) : null}
</>
)}
</Listbox.Option>
))}
</Listbox.Options>
</Transition>
</div>
</Listbox>
{/* Botão Limpar */}
{(searchTerm || selectedStatus.id !== 'all') && (
<button
onClick={clearFilters}
className="inline-flex items-center justify-center px-3 py-2 border border-zinc-200 dark:border-zinc-700 text-sm font-medium rounded-lg text-zinc-700 dark:text-zinc-200 bg-white dark:bg-zinc-900 hover:bg-zinc-50 dark:hover:bg-zinc-800 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[var(--brand-color)]"
title="Limpar Filtros"
>
<XMarkIcon className="h-4 w-4" />
</button>
)}
</div>
</div>
{/* Tabela */}
{loading ? (
<div className="flex items-center justify-center h-64 bg-white dark:bg-zinc-900 rounded-xl border border-zinc-200 dark:border-zinc-800">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[var(--brand-color)]"></div>
</div>
) : filteredPlans.length === 0 ? (
<div className="flex flex-col items-center justify-center h-64 bg-white dark:bg-zinc-900 rounded-xl border border-zinc-200 dark:border-zinc-800 text-center p-8">
<div className="w-16 h-16 bg-zinc-50 dark:bg-zinc-800 rounded-full flex items-center justify-center mb-4">
<SparklesIcon className="w-8 h-8 text-zinc-400" />
</div>
<h3 className="text-lg font-medium text-zinc-900 dark:text-white mb-1">
Nenhum plano encontrado
</h3>
<p className="text-zinc-500 dark:text-zinc-400 max-w-sm mx-auto">
Não encontramos resultados para os filtros selecionados. Tente limpar a busca ou alterar os filtros.
</p>
<button
onClick={clearFilters}
className="mt-4 text-sm text-[var(--brand-color)] hover:underline font-medium"
>
Limpar todos os filtros
</button>
</div>
) : (
<div className="bg-white dark:bg-zinc-900 rounded-xl border border-zinc-200 dark:border-zinc-800 overflow-hidden">
<div className="overflow-x-auto">
<table className="w-full">
<thead>
<tr className="bg-zinc-50/50 dark:bg-zinc-800/50 border-b border-zinc-200 dark:border-zinc-800">
<th className="px-6 py-4 w-12">
<input
type="checkbox"
checked={selectedIds.size === paginatedPlans.length && paginatedPlans.length > 0}
onChange={toggleSelectAll}
className="w-4 h-4 text-[var(--brand-color)] bg-zinc-100 border-zinc-300 rounded focus:ring-[var(--brand-color)] dark:focus:ring-[var(--brand-color)] dark:ring-offset-zinc-900 focus:ring-2 dark:bg-zinc-700 dark:border-zinc-600"
/>
</th>
<th className="px-6 py-4 text-left text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Plano</th>
<th className="px-6 py-4 text-left text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Preços</th>
<th className="px-6 py-4 text-left text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Usuários</th>
<th className="px-6 py-4 text-left text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Armazenamento</th>
<th className="px-6 py-4 text-left text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Soluções</th>
<th className="px-6 py-4 text-left text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Status</th>
<th className="px-6 py-4 text-right text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Ações</th>
</tr>
</thead>
<tbody className="divide-y divide-zinc-100 dark:divide-zinc-800">
{paginatedPlans.map((plan) => (
<tr key={plan.id} className="group hover:bg-zinc-50 dark:hover:bg-zinc-800/50 transition-colors cursor-pointer" onClick={() => handleEdit(plan.id)}>
<td className="px-6 py-4 w-12" onClick={(e) => e.stopPropagation()}>
<input
type="checkbox"
checked={selectedIds.has(plan.id)}
onChange={() => toggleSelect(plan.id)}
className="w-4 h-4 text-[var(--brand-color)] bg-zinc-100 border-zinc-300 rounded focus:ring-[var(--brand-color)] dark:focus:ring-[var(--brand-color)] dark:ring-offset-zinc-900 focus:ring-2 dark:bg-zinc-700 dark:border-zinc-600"
/>
</td>
<td className="px-6 py-4 whitespace-nowrap">
<div className="flex items-center gap-4">
<div
className="w-10 h-10 rounded-lg flex items-center justify-center text-white font-bold text-sm"
style={{ background: 'var(--gradient)' }}
>
{plan.name?.substring(0, 2).toUpperCase()}
</div>
<div>
<div className="text-sm font-semibold text-zinc-900 dark:text-white">
{plan.name}
</div>
{plan.description && (
<div className="text-xs text-zinc-500">
{plan.description}
</div>
)}
</div>
</div>
</td>
<td className="px-6 py-4 whitespace-nowrap">
<div className="flex flex-col gap-0.5">
<span className="text-sm text-zinc-700 dark:text-zinc-300">
{plan.monthly_price ? `R$ ${plan.monthly_price}/mês` : '-'}
</span>
<span className="text-xs text-zinc-400">
{plan.annual_price ? `R$ ${plan.annual_price}/ano` : '-'}
</span>
</div>
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-zinc-700 dark:text-zinc-300">
{plan.min_users} - {plan.max_users}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-zinc-700 dark:text-zinc-300">
{plan.storage_gb} GB
</td>
<td className="px-6 py-4 whitespace-nowrap">
<span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium bg-zinc-100 dark:bg-zinc-800 text-zinc-700 dark:text-zinc-300 border border-zinc-200 dark:border-zinc-700">
<span className="w-1.5 h-1.5 rounded-full bg-[var(--brand-color)]" />
{plan.solutions_count || 0} {plan.solutions_count === 1 ? 'solução' : 'soluções'}
</span>
</td>
<td className="px-6 py-4 whitespace-nowrap" onClick={(e) => e.stopPropagation()}>
<button
onClick={() => toggleActive(plan.id, plan.is_active)}
className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium border transition-all ${plan.is_active
? 'bg-emerald-50 text-emerald-700 border-emerald-200 dark:bg-emerald-900/20 dark:text-emerald-400 dark:border-emerald-900/30'
: 'bg-zinc-100 text-zinc-600 border-zinc-200 dark:bg-zinc-800 dark:text-zinc-400 dark:border-zinc-700'
}`}
>
<span className={`w-1.5 h-1.5 rounded-full ${plan.is_active ? 'bg-emerald-500' : 'bg-zinc-400'}`} />
{plan.is_active ? 'Ativo' : 'Inativo'}
</button>
</td>
<td className="px-6 py-4 whitespace-nowrap text-right" onClick={(e) => e.stopPropagation()}>
<Menu as="div" className="relative inline-block text-left">
<Menu.Button className="p-2 rounded-lg hover:bg-zinc-100 dark:hover:bg-zinc-800 text-zinc-400 hover:text-zinc-600 dark:hover:text-zinc-300 transition-colors outline-none">
<EllipsisVerticalIcon className="w-5 h-5" />
</Menu.Button>
<Menu.Items
transition
portal
anchor="bottom end"
className="w-48 origin-top-right divide-y divide-zinc-100 dark:divide-zinc-800 rounded-xl bg-white dark:bg-zinc-900 focus:outline-none z-50 border border-zinc-200 dark:border-zinc-800 [--anchor-gap:8px] transition duration-100 ease-out data-[closed]:scale-95 data-[closed]:opacity-0"
>
<div className="px-1 py-1">
<Menu.Item>
{({ active }) => (
<button
onClick={() => handleEdit(plan.id)}
className={`${active ? 'bg-zinc-50 dark:bg-zinc-800' : ''
} group flex w-full items-center rounded-lg px-2 py-2 text-sm text-zinc-700 dark:text-zinc-300`}
>
<PencilIcon className="mr-2 h-4 w-4 text-zinc-400" />
Editar
</button>
)}
</Menu.Item>
</div>
<div className="px-1 py-1">
<Menu.Item>
{({ active }) => (
<button
onClick={() => handleDeleteClick(plan.id)}
className={`${active ? 'bg-red-50 dark:bg-red-900/20' : ''
} group flex w-full items-center rounded-lg px-2 py-2 text-sm text-red-600 dark:text-red-400`}
>
<TrashIcon className="mr-2 h-4 w-4" />
Excluir
</button>
)}
</Menu.Item>
</div>
</Menu.Items>
</Menu>
</td>
</tr>
))}
</tbody>
</table>
</div>
<Pagination
currentPage={currentPage}
totalPages={totalPages}
totalItems={totalItems}
itemsPerPage={itemsPerPage}
onPageChange={setCurrentPage}
/>
</div>
)}
<CreatePlanModal
isOpen={isCreateModalOpen}
onClose={() => setIsCreateModalOpen(false)}
onSuccess={(plan) => {
setPlans([...plans, plan]);
setIsCreateModalOpen(false);
}}
/>
<EditPlanModal
isOpen={isEditModalOpen}
onClose={() => {
setIsEditModalOpen(false);
setEditingPlanId(null);
}}
planId={editingPlanId}
onSuccess={handleEditSuccess}
/>
<ConfirmDialog
isOpen={confirmOpen}
onClose={() => {
setConfirmOpen(false);
setPlanToDelete(null);
}}
onConfirm={planToDelete === 'multiple' ? handleConfirmDeleteMultiple : handleConfirmDelete}
title={planToDelete === 'multiple' ? 'Excluir Planos' : 'Excluir Plano'}
message={
planToDelete === 'multiple'
? `Tem certeza que deseja excluir ${selectedIds.size} plano(s)? Esta ação não pode ser desfeita.`
: 'Tem certeza que deseja excluir este plano? Esta ação não pode ser desfeita.'
}
confirmText="Excluir"
cancelText="Cancelar"
variant="danger"
/>
</div>
);
}

View File

@@ -0,0 +1,480 @@
"use client";
import { Fragment, useEffect, useState } from 'react';
import { Menu, Transition } from '@headlessui/react';
import ConfirmDialog from '@/components/layout/ConfirmDialog';
import { useToast } from '@/components/layout/ToastContext';
import {
SparklesIcon,
TrashIcon,
PencilIcon,
EllipsisVerticalIcon,
MagnifyingGlassIcon,
PlusIcon,
XMarkIcon,
UserGroupIcon,
ChartBarIcon,
FolderIcon,
LifebuoyIcon,
CreditCardIcon,
DocumentTextIcon,
ArchiveBoxIcon,
ShareIcon
} from '@heroicons/react/24/outline';
// Mapeamento de ícones para cada solução
const SOLUTION_ICONS: Record<string, React.ComponentType<{ className?: string }>> = {
'crm': UserGroupIcon,
'erp': ChartBarIcon,
'projetos': FolderIcon,
'helpdesk': LifebuoyIcon,
'pagamentos': CreditCardIcon,
'contratos': DocumentTextIcon,
'documentos': ArchiveBoxIcon,
'social': ShareIcon,
};
interface Solution {
id: string;
name: string;
slug: string;
icon: string;
description: string;
is_active: boolean;
created_at: string;
updated_at: string;
}
export default function SolutionsPage() {
const toast = useToast();
const [solutions, setSolutions] = useState<Solution[]>([]);
const [loading, setLoading] = useState(true);
const [isModalOpen, setIsModalOpen] = useState(false);
const [editingSolution, setEditingSolution] = useState<Solution | null>(null);
const [confirmOpen, setConfirmOpen] = useState(false);
const [solutionToDelete, setSolutionToDelete] = useState<string | null>(null);
const [searchTerm, setSearchTerm] = useState('');
// Form state
const [formData, setFormData] = useState({
name: '',
slug: '',
icon: '',
description: '',
is_active: true,
});
useEffect(() => {
fetchSolutions();
}, []);
const fetchSolutions = async () => {
try {
const response = await fetch('/api/admin/solutions', {
headers: {
'Authorization': `Bearer ${localStorage.getItem('token')}`,
},
});
if (response.ok) {
const data = await response.json();
setSolutions(data.solutions || []);
}
} catch (error) {
console.error('Error fetching solutions:', error);
} finally {
setLoading(false);
}
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
const url = editingSolution
? `/api/admin/solutions/${editingSolution.id}`
: '/api/admin/solutions';
const method = editingSolution ? 'PUT' : 'POST';
try {
const response = await fetch(url, {
method,
headers: {
'Authorization': `Bearer ${localStorage.getItem('token')}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(formData),
});
if (response.ok) {
toast.success(
editingSolution ? 'Solução atualizada' : 'Solução criada',
editingSolution ? 'A solução foi atualizada com sucesso.' : 'A nova solução foi criada com sucesso.'
);
fetchSolutions();
handleCloseModal();
} else {
const error = await response.json();
toast.error('Erro', error.message || 'Não foi possível salvar a solução.');
}
} catch (error) {
console.error('Error saving solution:', error);
toast.error('Erro', 'Ocorreu um erro ao salvar a solução.');
}
};
const handleEdit = (solution: Solution) => {
setEditingSolution(solution);
setFormData({
name: solution.name,
slug: solution.slug,
icon: solution.icon,
description: solution.description,
is_active: solution.is_active,
});
setIsModalOpen(true);
};
const handleDeleteClick = (id: string) => {
setSolutionToDelete(id);
setConfirmOpen(true);
};
const handleConfirmDelete = async () => {
if (!solutionToDelete) return;
try {
const response = await fetch(`/api/admin/solutions/${solutionToDelete}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${localStorage.getItem('token')}`,
},
});
if (response.ok) {
setSolutions(solutions.filter(s => s.id !== solutionToDelete));
toast.success('Solução excluída', 'A solução foi excluída com sucesso.');
} else {
toast.error('Erro ao excluir', 'Não foi possível excluir a solução.');
}
} catch (error) {
console.error('Error deleting solution:', error);
toast.error('Erro ao excluir', 'Ocorreu um erro ao excluir a solução.');
} finally {
setConfirmOpen(false);
setSolutionToDelete(null);
}
};
const handleCloseModal = () => {
setIsModalOpen(false);
setEditingSolution(null);
setFormData({
name: '',
slug: '',
icon: '',
description: '',
is_active: true,
});
};
const filteredSolutions = solutions.filter((solution) => {
const searchLower = searchTerm.toLowerCase();
return (
(solution.name?.toLowerCase() || '').includes(searchLower) ||
(solution.slug?.toLowerCase() || '').includes(searchLower) ||
(solution.description?.toLowerCase() || '').includes(searchLower)
);
});
return (
<div className="p-6 max-w-[1600px] mx-auto space-y-6">
{/* Header */}
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
<div>
<h1 className="text-2xl font-bold text-zinc-900 dark:text-white tracking-tight">Soluções</h1>
<p className="text-sm text-zinc-500 dark:text-zinc-400 mt-1">
Gerencie as soluções disponíveis na plataforma (CRM, ERP, etc.)
</p>
</div>
<button
onClick={() => setIsModalOpen(true)}
className="inline-flex items-center justify-center gap-2 px-4 py-2.5 text-sm font-medium text-white rounded-lg hover:opacity-90 transition-opacity"
style={{ background: 'var(--gradient)' }}
>
<PlusIcon className="w-4 h-4" />
Nova Solução
</button>
</div>
{/* Search */}
<div className="relative w-full lg:w-96">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<MagnifyingGlassIcon className="h-5 w-5 text-zinc-400" aria-hidden="true" />
</div>
<input
type="text"
className="block w-full pl-10 pr-3 py-2 border border-zinc-200 dark:border-zinc-700 rounded-lg leading-5 bg-white dark:bg-zinc-900 text-zinc-900 dark:text-zinc-100 placeholder-zinc-400 focus:outline-none focus:ring-1 focus:ring-[var(--brand-color)] focus:border-[var(--brand-color)] sm:text-sm transition duration-150 ease-in-out"
placeholder="Buscar por nome, slug ou descrição..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
</div>
{/* Table */}
{loading ? (
<div className="flex items-center justify-center h-64 bg-white dark:bg-zinc-900 rounded-xl border border-zinc-200 dark:border-zinc-800">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[var(--brand-color)]"></div>
</div>
) : filteredSolutions.length === 0 ? (
<div className="flex flex-col items-center justify-center h-64 bg-white dark:bg-zinc-900 rounded-xl border border-zinc-200 dark:border-zinc-800 text-center p-8">
<div className="w-16 h-16 bg-zinc-50 dark:bg-zinc-800 rounded-full flex items-center justify-center mb-4">
<SparklesIcon className="w-8 h-8 text-zinc-400" />
</div>
<h3 className="text-lg font-medium text-zinc-900 dark:text-white mb-1">
Nenhuma solução encontrada
</h3>
<p className="text-zinc-500 dark:text-zinc-400 max-w-sm mx-auto">
{searchTerm ? 'Nenhuma solução corresponde à sua busca.' : 'Comece criando sua primeira solução.'}
</p>
</div>
) : (
<div className="bg-white dark:bg-zinc-900 rounded-xl border border-zinc-200 dark:border-zinc-800 overflow-hidden">
<div className="overflow-x-auto">
<table className="w-full">
<thead>
<tr className="bg-zinc-50/50 dark:bg-zinc-800/50 border-b border-zinc-200 dark:border-zinc-800">
<th className="px-6 py-4 text-left text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Solução</th>
<th className="px-6 py-4 text-left text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Slug</th>
<th className="px-6 py-4 text-left text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Descrição</th>
<th className="px-6 py-4 text-left text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Status</th>
<th className="px-6 py-4 text-right text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Ações</th>
</tr>
</thead>
<tbody className="divide-y divide-zinc-100 dark:divide-zinc-800">
{filteredSolutions.map((solution) => {
const Icon = SOLUTION_ICONS[solution.slug] || FolderIcon;
return (
<tr key={solution.id} className="group hover:bg-zinc-50 dark:hover:bg-zinc-800/50 transition-colors cursor-pointer" onClick={() => handleEdit(solution)}>
<td className="px-6 py-4 whitespace-nowrap">
<div className="flex items-center gap-4">
<div className="w-10 h-10 rounded-full flex items-center justify-center" style={{ background: 'var(--gradient)' }}>
<Icon className="w-5 h-5 text-white" />
</div>
<div className="text-sm font-semibold text-zinc-900 dark:text-white">
{solution.name}
</div>
</div>
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-zinc-700 dark:text-zinc-300">
<code className="px-2 py-1 bg-zinc-100 dark:bg-zinc-800 rounded">{solution.slug}</code>
</td>
<td className="px-6 py-4 text-sm text-zinc-600 dark:text-zinc-400">
{solution.description || '-'}
</td>
<td className="px-6 py-4 whitespace-nowrap">
<span
className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium border ${solution.is_active
? 'bg-emerald-50 text-emerald-700 border-emerald-200 dark:bg-emerald-900/20 dark:text-emerald-400 dark:border-emerald-900/30'
: 'bg-zinc-100 text-zinc-600 border-zinc-200 dark:bg-zinc-800 dark:text-zinc-400 dark:border-zinc-700'
}`}
>
<span className={`w-1.5 h-1.5 rounded-full ${solution.is_active ? 'bg-emerald-500' : 'bg-zinc-400'}`} />
{solution.is_active ? 'Ativo' : 'Inativo'}
</span>
</td>
<td className="px-6 py-4 whitespace-nowrap text-right" onClick={(e) => e.stopPropagation()}>
<Menu as="div" className="relative inline-block text-left">
<Menu.Button className="p-2 rounded-lg hover:bg-zinc-100 dark:hover:bg-zinc-800 text-zinc-400 hover:text-zinc-600 dark:hover:text-zinc-300 transition-colors outline-none">
<EllipsisVerticalIcon className="w-5 h-5" />
</Menu.Button>
<Menu.Items
transition
portal
anchor="bottom end"
className="w-48 origin-top-right divide-y divide-zinc-100 dark:divide-zinc-800 rounded-xl bg-white dark:bg-zinc-900 focus:outline-none z-50 border border-zinc-200 dark:border-zinc-800 [--anchor-gap:8px] transition duration-100 ease-out data-[closed]:scale-95 data-[closed]:opacity-0"
>
<div className="px-1 py-1">
<Menu.Item>
{({ active }) => (
<button
onClick={() => handleEdit(solution)}
className={`${active ? 'bg-zinc-50 dark:bg-zinc-800' : ''
} group flex w-full items-center rounded-lg px-2 py-2 text-sm text-zinc-700 dark:text-zinc-300`}
>
<PencilIcon className="mr-2 h-4 w-4 text-zinc-400" />
Editar
</button>
)}
</Menu.Item>
</div>
<div className="px-1 py-1">
<Menu.Item>
{({ active }) => (
<button
onClick={() => handleDeleteClick(solution.id)}
className={`${active ? 'bg-red-50 dark:bg-red-900/20' : ''
} group flex w-full items-center rounded-lg px-2 py-2 text-sm text-red-600 dark:text-red-400`}
>
<TrashIcon className="mr-2 h-4 w-4" />
Excluir
</button>
)}
</Menu.Item>
</div>
</Menu.Items>
</Menu>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
</div>
)}
{/* Modal */}
{isModalOpen && (
<div className="fixed inset-0 z-50 overflow-y-auto">
<div className="flex min-h-full items-end justify-center p-4 text-center sm:items-center sm:p-0">
<div className="fixed inset-0 bg-zinc-900/40 backdrop-blur-sm transition-opacity" onClick={handleCloseModal}></div>
<div className="relative transform overflow-hidden rounded-2xl bg-white dark:bg-zinc-900 text-left shadow-xl transition-all sm:my-8 sm:w-full sm:max-w-lg border border-zinc-200 dark:border-zinc-800">
<div className="absolute right-0 top-0 pr-6 pt-6">
<button
type="button"
className="rounded-lg p-1.5 text-zinc-400 hover:text-zinc-600 dark:hover:text-zinc-300 hover:bg-zinc-100 dark:hover:bg-zinc-800 transition-colors"
onClick={handleCloseModal}
>
<XMarkIcon className="h-5 w-5" />
</button>
</div>
<form onSubmit={handleSubmit} className="p-6 sm:p-8">
<div className="flex items-start gap-4 mb-6">
<div
className="flex h-12 w-12 flex-shrink-0 items-center justify-center rounded-xl shadow-lg"
style={{ background: 'var(--gradient)' }}
>
<SparklesIcon className="h-6 w-6 text-white" />
</div>
<div>
<h3 className="text-xl font-bold text-zinc-900 dark:text-white">
{editingSolution ? 'Editar Solução' : 'Nova Solução'}
</h3>
<p className="mt-1 text-sm text-zinc-500 dark:text-zinc-400">
{editingSolution ? 'Atualize as informações da solução.' : 'Configure uma nova solução para a plataforma.'}
</p>
</div>
</div>
<div className="space-y-4">
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
Nome *
</label>
<input
type="text"
value={formData.name}
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
placeholder="Ex: CRM"
required
className="w-full px-3 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-[var(--brand-color)] focus:border-transparent transition-all"
/>
</div>
<div>
<label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
Slug *
</label>
<input
type="text"
value={formData.slug}
onChange={(e) => setFormData({ ...formData, slug: e.target.value })}
placeholder="Ex: crm"
required
className="w-full px-3 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-[var(--brand-color)] focus:border-transparent transition-all"
/>
</div>
</div>
<div>
<label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
Ícone
</label>
<input
type="text"
value={formData.icon}
onChange={(e) => setFormData({ ...formData, icon: e.target.value })}
placeholder="Ex: 📊 ou users"
className="w-full px-3 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-[var(--brand-color)] focus:border-transparent transition-all"
/>
</div>
<div>
<label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
Descrição
</label>
<textarea
value={formData.description}
onChange={(e) => setFormData({ ...formData, description: e.target.value })}
placeholder="Descrição breve da solução"
rows={3}
className="w-full px-3 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-[var(--brand-color)] focus:border-transparent resize-none transition-all"
/>
</div>
<div className="flex items-center pt-2">
<input
type="checkbox"
checked={formData.is_active}
onChange={(e) => setFormData({ ...formData, is_active: e.target.checked })}
className="h-4 w-4 rounded border-zinc-300 dark:border-zinc-600 focus:ring-2 focus:ring-[var(--brand-color)]"
style={{ accentColor: 'var(--brand-color)' }}
/>
<label className="ml-3 text-sm font-medium text-zinc-700 dark:text-zinc-300">
Solução Ativa
</label>
</div>
</div>
<div className="mt-8 pt-6 border-t border-zinc-200 dark:border-zinc-700 flex gap-3">
<button
type="button"
onClick={handleCloseModal}
className="flex-1 px-4 py-2.5 border border-zinc-200 dark:border-zinc-700 text-zinc-700 dark:text-zinc-300 font-medium rounded-lg hover:bg-zinc-50 dark:hover:bg-zinc-800 transition-colors"
>
Cancelar
</button>
<button
type="submit"
className="flex-1 px-4 py-2.5 text-white font-medium rounded-lg transition-all shadow-lg hover:shadow-xl"
style={{ background: 'var(--gradient)' }}
>
{editingSolution ? 'Atualizar' : 'Criar Solução'}
</button>
</div>
</form>
</div>
</div>
</div>
)}
<ConfirmDialog
isOpen={confirmOpen}
onClose={() => {
setConfirmOpen(false);
setSolutionToDelete(null);
}}
onConfirm={handleConfirmDelete}
title="Excluir Solução"
message="Tem certeza que deseja excluir esta solução? Esta ação não pode ser desfeita e afetará os planos que possuem esta solução."
confirmText="Excluir"
cancelText="Cancelar"
variant="danger"
/>
</div>
);
}

View File

@@ -10,6 +10,18 @@
--brand-color: #ff0080;
--brand-color-strong: #ff0080;
/* Escala de cores da marca */
--color-brand-50: #fff1f8;
--color-brand-100: #ffe0f0;
--color-brand-200: #ffc7e4;
--color-brand-300: #ffa0d2;
--color-brand-400: #ff6bb7;
--color-brand-500: #ff3a9d;
--color-brand-600: #ff0080;
--color-brand-700: #d6006a;
--color-brand-800: #ad0058;
--color-brand-900: #8a004a;
/* Superfícies e tipografia */
--color-surface-light: #ffffff;
--color-surface-dark: #0a0a0a;
@@ -50,5 +62,17 @@
--color-text-primary: #f8fafc;
--color-text-secondary: #cbd5f5;
--color-text-inverse: #0f172a;
/* Cores da marca com maior contraste para dark mode */
--color-brand-50: #4a0029;
--color-brand-100: #660037;
--color-brand-200: #8a004a;
--color-brand-300: #ad0058;
--color-brand-400: #d6006a;
--color-brand-500: #ff0080;
--color-brand-600: #ff3a9d;
--color-brand-700: #ff6bb7;
--color-brand-800: #ffa0d2;
--color-brand-900: #ffc7e4;
}
}

View File

@@ -0,0 +1,44 @@
'use client';
import { useEffect, useState } from 'react';
import { useRouter, usePathname } from 'next/navigation';
import { isAuthenticated } from '@/lib/auth';
export default function AuthGuard({ children }: { children: React.ReactNode }) {
const router = useRouter();
const pathname = usePathname();
const [authorized, setAuthorized] = useState(false);
useEffect(() => {
const checkAuth = () => {
const isAuth = isAuthenticated();
if (!isAuth) {
setAuthorized(false);
// Evitar redirect loop se já estiver no login
if (pathname !== '/login') {
router.push('/login');
}
} else {
setAuthorized(true);
}
};
checkAuth();
const handleStorageChange = (e: StorageEvent) => {
if (e.key === 'token' || e.key === 'user') {
checkAuth();
}
};
window.addEventListener('storage', handleStorageChange);
return () => window.removeEventListener('storage', handleStorageChange);
}, [router, pathname]);
if (!authorized) {
return null;
}
return <>{children}</>;
}

View File

@@ -1,4 +1,4 @@
"use client";
"use client";
import { useEffect, useState } from "react";
import DashboardPreview from "./DashboardPreview";
@@ -14,211 +14,199 @@ interface DynamicBrandingProps {
export default function DynamicBranding({
currentStep,
companyName = '',
subdomain = '',
primaryColor = '#0ea5e9',
secondaryColor = '#0284c7',
logoUrl = ''
companyName = "",
subdomain = "",
primaryColor = "#0ea5e9",
secondaryColor = "#0284c7",
logoUrl = ""
}: DynamicBrandingProps) {
const [activeTestimonial, setActiveTestimonial] = useState(0);
const testimonials = [
{
text: "Com o Aggios, nossa produtividade aumentou 40%. Gestão de projetos nunca foi tão simples!",
author: "Maria Silva",
company: "DigitalWorks",
avatar: "MS"
text: "A implementação do Aggios transformou completamente a gestão da nossa agência. Conseguimos reduzir em 65% o tempo gasto com tarefas administrativas e aumentar nossa capacidade de atendimento.",
author: "Carlos Eduardo Martins",
position: "CEO",
company: "Martins & Associados",
rating: 5
},
{
text: "Reduzi 60% do tempo gasto com controle financeiro. Tudo centralizado em um só lugar.",
author: "João Santos",
company: "TechHub",
avatar: "JS"
text: "Como diretora de operações, preciso de dados precisos em tempo real. O Aggios entrega exatamente isso. A plataforma é intuitiva e os relatórios são excepcionais para tomada de decisão estratégica.",
author: "Patricia Almeida Santos",
position: "Diretora de Operações",
company: "Digital Solutions Group",
rating: 5
},
{
text: "A melhor decisão para nossa agência. Dashboard intuitivo e relatórios incríveis!",
author: "Ana Costa",
company: "CreativeFlow",
avatar: "AC"
text: "Implementamos o Aggios há 6 meses e o ROI foi imediato. Melhor controle financeiro, visibilidade total dos projetos e uma equipe muito mais produtiva. Recomendo sem ressalvas.",
author: "Roberto Henrique Costa",
position: "Diretor Financeiro",
company: "Costa & Partners",
rating: 5
},
{
text: "A integração com nossas ferramentas foi perfeita e o suporte técnico é simplesmente excepcional. O Aggios se tornou parte fundamental da nossa operação diária.",
author: "Fernanda Silva Rodrigues",
position: "Head de TI",
company: "Tech Innovators",
rating: 5
}
];
const stepContent = [
{
icon: "ri-user-heart-line",
title: "Bem-vindo ao Aggios!",
description: "Vamos criar sua conta em poucos passos",
benefits: [
"✓ Acesso completo ao painel",
"✓ Gestão ilimitada de projetos",
"✓ Suporte prioritário"
]
},
{
icon: "ri-building-line",
title: "Configure sua Empresa",
description: "Personalize de acordo com seu negócio",
benefits: [
"✓ Dashboard personalizado",
"✓ Gestão de equipe e clientes",
"✓ Controle financeiro integrado"
]
},
{
icon: "ri-map-pin-line",
title: "Quase lá!",
description: "Informações de localização e contato",
benefits: [
"✓ Multi-contatos configuráveis",
"✓ Integração com WhatsApp",
"✓ Notificações em tempo real"
]
},
{
icon: "ri-palette-line",
title: "Personalize as Cores",
description: "Deixe com a cara da sua empresa",
benefits: [
"✓ Preview em tempo real",
"✓ Paleta de cores customizada",
"✓ Identidade visual única"
]
}
];
const content = stepContent[currentStep - 1] || stepContent[0];
// Auto-rotate testimonials
useEffect(() => {
const interval = setInterval(() => {
setActiveTestimonial((prev) => (prev + 1) % testimonials.length);
}, 5000);
}, 6000);
return () => clearInterval(interval);
}, [testimonials.length]);
// Se for etapa 4, mostrar preview do dashboard
if (currentStep === 4) {
return (
<div className="relative z-10 flex flex-col justify-center items-center w-full p-12">
{/* Logo */}
<div className="mb-8">
<div className="inline-block px-6 py-3 rounded-2xl bg-white/10 backdrop-blur-sm border border-white/20">
<h1 className="text-5xl font-bold tracking-tight bg-linear-to-r from-white to-white/80 bg-clip-text text-transparent">
<div className="relative z-10 flex flex-col h-full w-full overflow-hidden bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900">
{/* Decorative elements */}
<div className="absolute inset-0 opacity-10">
<div className="absolute top-0 left-0 w-96 h-96 bg-blue-500 rounded-full blur-3xl" />
<div className="absolute bottom-0 right-0 w-96 h-96 bg-purple-500 rounded-full blur-3xl" />
</div>
<div className="relative z-10 flex flex-col justify-center items-center h-full p-12 text-white">
<div className="mb-6">
<h1 className="text-4xl font-bold tracking-tight text-white text-center mb-2">
aggios
</h1>
<p className="text-sm text-white/70 font-medium tracking-wide uppercase text-center">
Gestão Inteligente para Agências
</p>
</div>
<div className="max-w-lg text-center mb-8">
<h2 className="text-3xl font-bold mb-2 text-white">Preview do seu Painel</h2>
<p className="text-white/70 text-base">Veja como ficará seu dashboard personalizado</p>
</div>
<div className="w-full max-w-3xl mb-6">
<DashboardPreview
companyName={companyName}
subdomain={subdomain}
primaryColor={primaryColor}
secondaryColor={secondaryColor}
logoUrl={logoUrl}
/>
</div>
<div className="text-center">
<p className="text-white/60 text-sm">
As cores e configurações são atualizadas em tempo real
</p>
</div>
</div>
{/* Conteúdo */}
<div className="max-w-lg text-center">
<h2 className="text-3xl font-bold mb-2 text-white">Preview do seu Painel</h2>
<p className="text-white/80 text-lg">Veja como ficará seu dashboard personalizado</p>
</div>
{/* Preview */}
<div className="w-full max-w-3xl">
<DashboardPreview
companyName={companyName}
subdomain={subdomain}
primaryColor={primaryColor}
secondaryColor={secondaryColor}
logoUrl={logoUrl}
/>
</div>
{/* Info */}
<div className="mt-6 text-center">
<p className="text-white/70 text-sm">
As cores e configurações são atualizadas em tempo real
</p>
</div>
{/* Decorative circles */}
<div className="absolute -bottom-32 -left-32 w-96 h-96 rounded-full bg-white/5" />
<div className="absolute -top-16 -right-16 w-64 h-64 rounded-full bg-white/5" />
</div>
);
}
return (
<div className="relative z-10 flex flex-col justify-between w-full p-12 text-white">
{/* Logo e Conteúdo da Etapa */}
<div className="flex flex-col justify-center flex-1">
{/* Logo */}
<div className="relative z-10 flex flex-col h-full w-full overflow-hidden bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900">
{/* Decorative elements */}
<div className="absolute inset-0 opacity-10">
<div className="absolute top-20 right-20 w-96 h-96 bg-blue-500 rounded-full blur-3xl" />
<div className="absolute bottom-20 left-20 w-80 h-80 bg-indigo-500 rounded-full blur-3xl" />
</div>
<div className="relative z-10 flex flex-col justify-between h-full p-12 text-white">
<div className="mb-8">
<div className="inline-block px-6 py-3 rounded-2xl bg-white/10 backdrop-blur-sm border border-white/20">
<h1 className="text-5xl font-bold tracking-tight bg-linear-to-r from-white to-white/80 bg-clip-text text-transparent">
<div className="inline-block">
<h1 className="text-4xl font-bold tracking-tight text-white mb-2">
aggios
</h1>
<p className="text-sm text-white/70 font-medium tracking-wide uppercase">
Gestão Inteligente para Agências
</p>
</div>
</div>
{/* Ícone e Título da Etapa */}
<div className="mb-6">
<div className="w-16 h-16 rounded-2xl bg-white/20 flex items-center justify-center mb-4">
<i className={`${content.icon} text-3xl`} />
</div>
<h2 className="text-3xl font-bold mb-2">{content.title}</h2>
<p className="text-white/80 text-lg">{content.description}</p>
</div>
<div className="flex-1" />
{/* Benefícios */}
<div className="space-y-3 mb-8">
{content.benefits.map((benefit, index) => (
<div
key={index}
className="flex items-center gap-3 text-white/90 animate-fade-in"
style={{ animationDelay: `${index * 100}ms` }}
>
<span className="text-lg">{benefit}</span>
<div className="space-y-6">
<div className="mb-6">
<h3 className="text-sm font-semibold text-white/60 uppercase tracking-wider mb-1">
Depoimentos
</h3>
<p className="text-2xl font-bold text-white">
O que nossos clientes dizem
</p>
</div>
<div className="relative">
<div className="bg-white/5 backdrop-blur-md rounded-xl p-8 border border-white/10 shadow-2xl">
<div className="flex gap-1 mb-4">
{[...Array(testimonials[activeTestimonial].rating)].map((_, i) => (
<i key={i} className="ri-star-fill text-yellow-400 text-lg" />
))}
</div>
<div className="mb-4">
<i className="ri-double-quotes-l text-4xl text-white/20" />
</div>
<p className="text-white/95 text-lg leading-relaxed mb-6 min-h-[140px]">
{testimonials[activeTestimonial].text}
</p>
<div className="flex items-center gap-4 pt-6 border-t border-white/10">
<div className="relative w-14 h-14 rounded-full overflow-hidden ring-2 ring-white/20 bg-gradient-to-br from-blue-500 to-purple-600 flex items-center justify-center">
<span className="text-white font-bold text-xl">
{testimonials[activeTestimonial].author.split(' ').map(n => n[0]).join('')}
</span>
</div>
<div className="flex-1">
<p className="font-semibold text-white text-lg">
{testimonials[activeTestimonial].author}
</p>
<p className="text-sm text-white/70">
{testimonials[activeTestimonial].position}
</p>
<p className="text-sm text-white/50 font-medium">
{testimonials[activeTestimonial].company}
</p>
</div>
</div>
</div>
))}
<div className="flex gap-2 justify-center mt-6">
{testimonials.map((_, index) => (
<button
key={index}
onClick={() => setActiveTestimonial(index)}
className={`h-2 rounded-full transition-all duration-300 ${index === activeTestimonial
? "w-12 bg-white shadow-lg shadow-white/20"
: "w-2 bg-white/30 hover:bg-white/50"
}`}
aria-label={`Ir para depoimento ${index + 1}`}
/>
))}
</div>
</div>
<div className="flex items-center justify-center gap-6 mt-8 pt-6 border-t border-white/10">
<div className="text-center">
<p className="text-2xl font-bold text-white">10.000+</p>
<p className="text-xs text-white/60 uppercase tracking-wide">Projetos</p>
</div>
<div className="w-px h-8 bg-white/20" />
<div className="text-center">
<p className="text-2xl font-bold text-white">98%</p>
<p className="text-xs text-white/60 uppercase tracking-wide">Satisfação</p>
</div>
<div className="w-px h-8 bg-white/20" />
<div className="text-center">
<p className="text-2xl font-bold text-white">5.000+</p>
<p className="text-xs text-white/60 uppercase tracking-wide">Usuários</p>
</div>
</div>
</div>
</div>
{/* Carrossel de Depoimentos */}
<div className="relative">
<div className="bg-white/10 backdrop-blur-sm rounded-2xl p-6 border border-white/20">
<div className="mb-4">
<i className="ri-double-quotes-l text-3xl text-white/40" />
</div>
<p className="text-white/95 mb-4 min-h-[60px]">
{testimonials[activeTestimonial].text}
</p>
<div className="flex items-center gap-3">
<div className="w-10 h-10 rounded-full bg-white/20 flex items-center justify-center font-semibold">
{testimonials[activeTestimonial].avatar}
</div>
<div>
<p className="font-semibold text-white">
{testimonials[activeTestimonial].author}
</p>
<p className="text-sm text-white/70">
{testimonials[activeTestimonial].company}
</p>
</div>
</div>
</div>
{/* Indicadores */}
<div className="flex gap-2 justify-center mt-4">
{testimonials.map((_, index) => (
<button
key={index}
onClick={() => setActiveTestimonial(index)}
className={`h-1.5 rounded-full transition-all ${index === activeTestimonial
? "w-8 bg-white"
: "w-1.5 bg-white/40 hover:bg-white/60"
}`}
aria-label={`Ir para depoimento ${index + 1}`}
/>
))}
</div>
</div>
{/* Decorative circles */}
<div className="absolute -bottom-32 -left-32 w-96 h-96 rounded-full bg-white/5" />
<div className="absolute -top-16 -right-16 w-64 h-64 rounded-full bg-white/5" />
</div>
);
}

View File

@@ -0,0 +1,123 @@
import { Fragment } from 'react';
import { Dialog, Transition } from '@headlessui/react';
import { ExclamationTriangleIcon, XMarkIcon } from '@heroicons/react/24/outline';
interface ConfirmDialogProps {
isOpen: boolean;
onClose: () => void;
onConfirm: () => void;
title: string;
message: string;
confirmText?: string;
cancelText?: string;
variant?: 'danger' | 'warning' | 'info';
}
export default function ConfirmDialog({
isOpen,
onClose,
onConfirm,
title,
message,
confirmText = 'Confirmar',
cancelText = 'Cancelar',
variant = 'danger'
}: ConfirmDialogProps) {
const handleConfirm = () => {
onConfirm();
onClose();
};
const variantStyles = {
danger: {
icon: 'bg-red-100 dark:bg-red-900/20',
iconColor: 'text-red-600 dark:text-red-400',
button: 'bg-red-600 hover:bg-red-700 dark:bg-red-700 dark:hover:bg-red-800'
},
warning: {
icon: 'bg-yellow-100 dark:bg-yellow-900/20',
iconColor: 'text-yellow-600 dark:text-yellow-400',
button: 'bg-yellow-600 hover:bg-yellow-700 dark:bg-yellow-700 dark:hover:bg-yellow-800'
},
info: {
icon: 'bg-blue-100 dark:bg-blue-900/20',
iconColor: 'text-blue-600 dark:text-blue-400',
button: 'bg-blue-600 hover:bg-blue-700 dark:bg-blue-700 dark:hover:bg-blue-800'
}
};
const style = variantStyles[variant];
return (
<Transition.Root show={isOpen} as={Fragment}>
<Dialog as="div" className="relative z-50" onClose={onClose}>
<Transition.Child
as={Fragment}
enter="ease-out duration-300"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="ease-in duration-200"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<div className="fixed inset-0 bg-zinc-900/40 backdrop-blur-sm transition-opacity" />
</Transition.Child>
<div className="fixed inset-0 z-10 overflow-y-auto">
<div className="flex min-h-full items-end justify-center p-4 text-center sm:items-center sm:p-0">
<Transition.Child
as={Fragment}
enter="ease-out duration-300"
enterFrom="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
enterTo="opacity-100 translate-y-0 sm:scale-100"
leave="ease-in duration-200"
leaveFrom="opacity-100 translate-y-0 sm:scale-100"
leaveTo="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
>
<Dialog.Panel className="relative transform overflow-hidden rounded-2xl bg-white dark:bg-zinc-900 text-left shadow-xl transition-all sm:my-8 sm:w-full sm:max-w-lg border border-zinc-200 dark:border-zinc-800">
<div className="p-6">
<div className="flex items-start gap-4">
<div className={`flex h-12 w-12 flex-shrink-0 items-center justify-center rounded-xl ${style.icon}`}>
<ExclamationTriangleIcon className={`h-6 w-6 ${style.iconColor}`} />
</div>
<div className="flex-1">
<Dialog.Title className="text-lg font-semibold text-zinc-900 dark:text-white">
{title}
</Dialog.Title>
<p className="mt-2 text-sm text-zinc-600 dark:text-zinc-400">
{message}
</p>
</div>
<button
onClick={onClose}
className="rounded-lg p-1.5 text-zinc-400 hover:text-zinc-600 dark:hover:text-zinc-300 hover:bg-zinc-100 dark:hover:bg-zinc-800 transition-colors"
>
<XMarkIcon className="h-5 w-5" />
</button>
</div>
<div className="mt-6 flex gap-3">
<button
type="button"
onClick={onClose}
className="flex-1 px-4 py-2.5 border border-zinc-200 dark:border-zinc-700 text-zinc-700 dark:text-zinc-300 font-medium rounded-lg hover:bg-zinc-50 dark:hover:bg-zinc-800 transition-colors"
>
{cancelText}
</button>
<button
type="button"
onClick={handleConfirm}
className={`flex-1 px-4 py-2.5 text-white font-medium rounded-lg transition-colors ${style.button}`}
>
{confirmText}
</button>
</div>
</div>
</Dialog.Panel>
</Transition.Child>
</div>
</div>
</Dialog>
</Transition.Root>
);
}

View File

@@ -1,14 +1,15 @@
'use client';
import React, { useState } from 'react';
import { SidebarRail } from './SidebarRail';
import { SidebarRail, MenuItem } from './SidebarRail';
import { TopBar } from './TopBar';
interface DashboardLayoutProps {
children: React.ReactNode;
menuItems: MenuItem[];
}
export const DashboardLayout: React.FC<DashboardLayoutProps> = ({ children }) => {
export const DashboardLayout: React.FC<DashboardLayoutProps> = ({ children, menuItems }) => {
// Estado centralizado do layout
const [isExpanded, setIsExpanded] = useState(true);
const [activeTab, setActiveTab] = useState('dashboard');
@@ -21,6 +22,7 @@ export const DashboardLayout: React.FC<DashboardLayoutProps> = ({ children }) =>
onTabChange={setActiveTab}
isExpanded={isExpanded}
onToggle={() => setIsExpanded(!isExpanded)}
menuItems={menuItems}
/>
{/* Área de Conteúdo (Children) */}

Some files were not shown because too many files have changed in this diff Show More