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
This commit is contained in:
Erik Silva
2025-12-13 19:26:38 -03:00
parent 2f1cf2bb2a
commit 2a112f169d
26 changed files with 2580 additions and 119 deletions

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?**

View File

@@ -56,12 +56,15 @@ func main() {
companyRepo := repository.NewCompanyRepository(db) companyRepo := repository.NewCompanyRepository(db)
signupTemplateRepo := repository.NewSignupTemplateRepository(db) signupTemplateRepo := repository.NewSignupTemplateRepository(db)
agencyTemplateRepo := repository.NewAgencyTemplateRepository(db) agencyTemplateRepo := repository.NewAgencyTemplateRepository(db)
planRepo := repository.NewPlanRepository(db)
subscriptionRepo := repository.NewSubscriptionRepository(db)
// Initialize services // Initialize services
authService := service.NewAuthService(userRepo, tenantRepo, cfg) authService := service.NewAuthService(userRepo, tenantRepo, cfg)
agencyService := service.NewAgencyService(userRepo, tenantRepo, cfg) agencyService := service.NewAgencyService(userRepo, tenantRepo, cfg)
tenantService := service.NewTenantService(tenantRepo) tenantService := service.NewTenantService(tenantRepo)
companyService := service.NewCompanyService(companyRepo) companyService := service.NewCompanyService(companyRepo)
planService := service.NewPlanService(planRepo, subscriptionRepo)
// Initialize handlers // Initialize handlers
healthHandler := handlers.NewHealthHandler() healthHandler := handlers.NewHealthHandler()
@@ -70,6 +73,7 @@ func main() {
agencyHandler := handlers.NewAgencyRegistrationHandler(agencyService, cfg) agencyHandler := handlers.NewAgencyRegistrationHandler(agencyService, cfg)
tenantHandler := handlers.NewTenantHandler(tenantService) tenantHandler := handlers.NewTenantHandler(tenantService)
companyHandler := handlers.NewCompanyHandler(companyService) companyHandler := handlers.NewCompanyHandler(companyService)
planHandler := handlers.NewPlanHandler(planService)
signupTemplateHandler := handlers.NewSignupTemplateHandler(signupTemplateRepo, userRepo, tenantRepo, agencyService) signupTemplateHandler := handlers.NewSignupTemplateHandler(signupTemplateRepo, userRepo, tenantRepo, agencyService)
agencyTemplateHandler := handlers.NewAgencyTemplateHandler(agencyTemplateRepo, agencyService, userRepo, tenantRepo) agencyTemplateHandler := handlers.NewAgencyTemplateHandler(agencyTemplateRepo, agencyService, userRepo, tenantRepo)
filesHandler := handlers.NewFilesHandler(cfg) filesHandler := handlers.NewFilesHandler(cfg)
@@ -112,6 +116,10 @@ func main() {
router.HandleFunc("/api/signup-templates/slug/{slug}", signupTemplateHandler.GetTemplateBySlug).Methods("GET") router.HandleFunc("/api/signup-templates/slug/{slug}", signupTemplateHandler.GetTemplateBySlug).Methods("GET")
router.HandleFunc("/api/signup/register", signupTemplateHandler.PublicRegister).Methods("POST") 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) // File upload (public for signup, will also work with auth)
router.HandleFunc("/api/upload", uploadHandler.Upload).Methods("POST") router.HandleFunc("/api/upload", uploadHandler.Upload).Methods("POST")
@@ -156,6 +164,9 @@ func main() {
} }
}))).Methods("GET", "PUT", "PATCH", "DELETE") }))).Methods("GET", "PUT", "PATCH", "DELETE")
// SUPERADMIN: Plans management
planHandler.RegisterRoutes(router)
// ADMIN_AGENCIA: Client registration // ADMIN_AGENCIA: Client registration
router.Handle("/api/agencies/clients/register", authMiddleware(http.HandlerFunc(agencyHandler.RegisterClient))).Methods("POST") router.Handle("/api/agencies/clients/register", authMiddleware(http.HandlerFunc(agencyHandler.RegisterClient))).Methods("POST")

View File

@@ -39,6 +39,23 @@ func (h *FilesHandler) ServeFile(w http.ResponseWriter, r *http.Request) {
return 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) log.Printf("📁 Serving file: bucket=%s, path=%s", bucket, filePath)
// Initialize MinIO client // Initialize MinIO client

View File

@@ -0,0 +1,268 @@
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)
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
plan, err := h.planService.CreatePlan(&req)
if err != nil {
log.Printf("❌ Error creating plan: %v", err)
switch err {
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")
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

@@ -2,6 +2,7 @@ package handlers
import ( import (
"encoding/json" "encoding/json"
"log"
"net/http" "net/http"
"aggios-app/backend/internal/domain" "aggios-app/backend/internal/domain"
@@ -100,6 +101,8 @@ func (h *TenantHandler) GetPublicConfig(w http.ResponseWriter, r *http.Request)
"logo_horizontal_url": tenant.LogoHorizontalURL, "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") w.Header().Set("Content-Type", "application/json; charset=utf-8")
json.NewEncoder(w).Encode(response) json.NewEncoder(w).Encode(response)
} }

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,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,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

@@ -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

@@ -1,15 +0,0 @@
# Teste manual do endpoint de upload de logo
## 1. Login e obter token
curl -X POST http://idealpages.localhost/api/auth/login \
-H "Content-Type: application/json" \
-d '{"email":"admin@idealpages.com","password":"admin123"}'
## 2. Upload de logo (substituir TOKEN pelo valor retornado acima)
curl -X POST http://idealpages.localhost/api/agency/logo \
-H "Authorization: Bearer TOKEN" \
-F "logo=@/caminho/para/imagem.png" \
-F "type=logo"
## 3. Verificar se salvou no banco
docker exec aggios-postgres psql -U aggios -d aggios_db -c "SELECT id, name, logo_url FROM tenants WHERE subdomain = 'idealpages';"

View File

@@ -127,9 +127,6 @@ export default function ConfiguracoesPage() {
if (response.ok) { if (response.ok) {
const data = await response.json(); 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 || ''); const parsedAddress = parseAddressParts(data.address || '');
setAgencyData({ setAgencyData({
@@ -150,21 +147,26 @@ export default function ConfiguracoesPage() {
description: data.description || '', description: data.description || '',
industry: data.industry || '', industry: data.industry || '',
teamSize: data.team_size || '', teamSize: data.team_size || '',
logoUrl: data.logo_url || '', logoUrl: data.logo_url || localStorage.getItem('agency-logo-url') || '',
logoHorizontalUrl: data.logo_horizontal_url || '', logoHorizontalUrl: data.logo_horizontal_url || localStorage.getItem('agency-logo-horizontal-url') || '',
primaryColor: data.primary_color || '#ff3a05', primaryColor: data.primary_color || '#ff3a05',
secondaryColor: data.secondary_color || '#ff0080', secondaryColor: data.secondary_color || '#ff0080',
}); });
// Set logo previews // Set logo previews - usar localStorage como fallback se API não retornar
console.log('DEBUG: Setting previews...'); const cachedLogo = localStorage.getItem('agency-logo-url');
if (data.logo_url) { const cachedHorizontal = localStorage.getItem('agency-logo-horizontal-url');
console.log('DEBUG: Setting logoPreview to:', data.logo_url);
setLogoPreview(data.logo_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) { if (finalHorizontalUrl) {
console.log('DEBUG: Setting logoHorizontalPreview to:', data.logo_horizontal_url); setLogoHorizontalPreview(finalHorizontalUrl);
setLogoHorizontalPreview(data.logo_horizontal_url); localStorage.setItem('agency-logo-horizontal-url', finalHorizontalUrl);
} }
} else { } else {
console.error('Erro ao buscar dados:', response.status); console.error('Erro ao buscar dados:', response.status);
@@ -403,8 +405,25 @@ export default function ConfiguracoesPage() {
// Atualiza localStorage imediatamente para persistência instantânea // Atualiza localStorage imediatamente para persistência instantânea
localStorage.setItem('agency-primary-color', agencyData.primaryColor); localStorage.setItem('agency-primary-color', agencyData.primaryColor);
localStorage.setItem('agency-secondary-color', agencyData.secondaryColor); localStorage.setItem('agency-secondary-color', agencyData.secondaryColor);
if (agencyData.logoUrl) localStorage.setItem('agency-logo-url', agencyData.logoUrl);
if (agencyData.logoHorizontalUrl) localStorage.setItem('agency-logo-horizontal-url', agencyData.logoHorizontalUrl); // 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 // Disparar evento para atualizar o tema em tempo real
window.dispatchEvent(new Event('branding-update')); window.dispatchEvent(new Event('branding-update'));

View File

@@ -47,7 +47,7 @@ html.dark {
@layer base { @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, a,

View File

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

View File

@@ -1,20 +1,13 @@
'use client'; 'use client';
import { useEffect, useState } from 'react'; import { useEffect } from 'react';
/** /**
* LoginBranding - Aplica cor primária da agência na página de login * 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 * Busca cor do localStorage ou da API se não houver cache
*/ */
export function LoginBranding() { export function LoginBranding() {
const [mounted, setMounted] = useState(false);
useEffect(() => { useEffect(() => {
setMounted(true);
}, []);
useEffect(() => {
if (!mounted) return;
const hexToRgb = (hex: string) => { const hexToRgb = (hex: string) => {
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
@@ -41,26 +34,19 @@ export function LoginBranding() {
if (typeof window === 'undefined' || typeof document === 'undefined') return; if (typeof window === 'undefined' || typeof document === 'undefined') return;
try { try {
console.log('🎨 LoginBranding: Atualizando favicon para:', url);
const newHref = `${url}${url.includes('?') ? '&' : '?'}v=${Date.now()}`; const newHref = `${url}${url.includes('?') ? '&' : '?'}v=${Date.now()}`;
// Buscar TODOS os links de ícone existentes
const existingLinks = document.querySelectorAll("link[rel*='icon']"); const existingLinks = document.querySelectorAll("link[rel*='icon']");
if (existingLinks.length > 0) { if (existingLinks.length > 0) {
// Atualizar href de todos os links existentes (SEM REMOVER)
existingLinks.forEach(link => { existingLinks.forEach(link => {
link.setAttribute('href', newHref); link.setAttribute('href', newHref);
}); });
console.log(`${existingLinks.length} favicons atualizados`);
} else { } else {
// Criar novo link apenas se não existir nenhum
const newLink = document.createElement('link'); const newLink = document.createElement('link');
newLink.rel = 'icon'; newLink.rel = 'icon';
newLink.type = 'image/x-icon'; newLink.type = 'image/x-icon';
newLink.href = newHref; newLink.href = newHref;
document.head.appendChild(newLink); document.head.appendChild(newLink);
console.log('✅ Novo favicon criado');
} }
} catch (error) { } catch (error) {
console.error('❌ Erro ao atualizar favicon:', error); console.error('❌ Erro ao atualizar favicon:', error);
@@ -88,18 +74,15 @@ export function LoginBranding() {
if (response.ok) { if (response.ok) {
const data = await response.json(); const data = await response.json();
console.log('LoginBranding: Dados recebidos:', data);
if (data.primary_color) { if (data.primary_color) {
applyTheme(data.primary_color); applyTheme(data.primary_color);
localStorage.setItem('agency-primary-color', data.primary_color); localStorage.setItem('agency-primary-color', data.primary_color);
console.log('LoginBranding: Cor aplicada!');
} }
if (data.logo_url) { if (data.logo_url) {
updateFavicon(data.logo_url); updateFavicon(data.logo_url);
localStorage.setItem('agency-logo-url', data.logo_url); localStorage.setItem('agency-logo-url', data.logo_url);
console.log('LoginBranding: Favicon aplicado!');
} }
return; return;
} else { } else {
@@ -107,7 +90,6 @@ export function LoginBranding() {
} }
// 2. Fallback para cache // 2. Fallback para cache
console.log('LoginBranding: Tentando cache');
const cachedPrimary = localStorage.getItem('agency-primary-color'); const cachedPrimary = localStorage.getItem('agency-primary-color');
const cachedLogo = localStorage.getItem('agency-logo-url'); const cachedLogo = localStorage.getItem('agency-logo-url');
@@ -132,7 +114,7 @@ export function LoginBranding() {
}; };
loadBranding(); loadBranding();
}, [mounted]); }, []);
return null; return null;
} }

View File

@@ -11,20 +11,10 @@ interface AgencyBrandingProps {
/** /**
* AgencyBranding - Aplica as cores da agência via CSS Variables * AgencyBranding - Aplica as cores da agência via CSS Variables
* O favicon agora é tratado via Metadata API no layout (server-side) * O favicon é atualizado dinamicamente via DOM
*/ */
export function AgencyBranding({ colors }: AgencyBrandingProps) { export function AgencyBranding({ colors }: AgencyBrandingProps) {
const [mounted, setMounted] = useState(false);
const [debugInfo, setDebugInfo] = useState<string>('Iniciando...');
useEffect(() => { useEffect(() => {
setMounted(true);
}, []);
useEffect(() => {
if (!mounted) return;
const hexToRgb = (hex: string) => { const hexToRgb = (hex: string) => {
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(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; return result ? `${parseInt(result[1], 16)} ${parseInt(result[2], 16)} ${parseInt(result[3], 16)}` : null;
@@ -67,33 +57,25 @@ export function AgencyBranding({ colors }: AgencyBrandingProps) {
if (typeof window === 'undefined' || typeof document === 'undefined') return; if (typeof window === 'undefined' || typeof document === 'undefined') return;
try { try {
setDebugInfo(`Tentando atualizar favicon: ${url}`);
console.log('🎨 AgencyBranding: Atualizando favicon para:', url);
const newHref = `${url}${url.includes('?') ? '&' : '?'}v=${Date.now()}`; const newHref = `${url}${url.includes('?') ? '&' : '?'}v=${Date.now()}`;
// Buscar TODOS os links de ícone existentes // Buscar TODOS os links de ícone (como estava funcionando antes)
const existingLinks = document.querySelectorAll("link[rel*='icon']"); const existingLinks = document.querySelectorAll("link[rel*='icon']");
if (existingLinks.length > 0) { if (existingLinks.length > 0) {
// Atualizar href de todos os links existentes (SEM REMOVER)
existingLinks.forEach(link => { existingLinks.forEach(link => {
link.setAttribute('href', newHref); link.setAttribute('href', newHref);
}); });
setDebugInfo(`Favicon atualizado (${existingLinks.length} links)`);
console.log(`${existingLinks.length} favicons atualizados`); console.log(`${existingLinks.length} favicons atualizados`);
} else { } else {
// Criar novo link apenas se não existir nenhum
const newLink = document.createElement('link'); const newLink = document.createElement('link');
newLink.rel = 'icon'; newLink.rel = 'icon';
newLink.type = 'image/x-icon'; newLink.type = 'image/x-icon';
newLink.href = newHref; newLink.href = newHref;
document.head.appendChild(newLink); document.head.appendChild(newLink);
setDebugInfo('Novo favicon criado'); console.log('✅ Favicon criado');
console.log('✅ Novo favicon criado');
} }
} catch (error) { } catch (error) {
setDebugInfo(`Erro: ${error}`);
console.error('❌ Erro ao atualizar favicon:', error); console.error('❌ Erro ao atualizar favicon:', error);
} }
}; };
@@ -111,32 +93,23 @@ export function AgencyBranding({ colors }: AgencyBrandingProps) {
} }
} }
// Atualizar favicon se houver logo salvo (após montar) // Atualizar favicon se houver logo salvo
const cachedLogo = localStorage.getItem('agency-logo-url'); const cachedLogo = localStorage.getItem('agency-logo-url');
if (cachedLogo) { if (cachedLogo) {
console.log('🔍 Logo encontrado no cache:', cachedLogo);
updateFavicon(cachedLogo); updateFavicon(cachedLogo);
} else {
setDebugInfo('Nenhum logo no cache');
console.log('⚠️ Nenhum logo encontrado no cache');
} }
// Listener para atualizações em tempo real (ex: da página de configurações) // Listener para atualizações em tempo real
const handleUpdate = () => { const handleUpdate = () => {
console.log('🔔 Evento branding-update recebido!');
setDebugInfo('Evento branding-update recebido');
const cachedPrimary = localStorage.getItem('agency-primary-color'); const cachedPrimary = localStorage.getItem('agency-primary-color');
const cachedSecondary = localStorage.getItem('agency-secondary-color'); const cachedSecondary = localStorage.getItem('agency-secondary-color');
const cachedLogo = localStorage.getItem('agency-logo-url'); const cachedLogo = localStorage.getItem('agency-logo-url');
if (cachedPrimary && cachedSecondary) { if (cachedPrimary && cachedSecondary) {
console.log('🎨 Aplicando cores do cache');
applyTheme(cachedPrimary, cachedSecondary); applyTheme(cachedPrimary, cachedSecondary);
} }
if (cachedLogo) { if (cachedLogo) {
console.log('🖼️ Atualizando favicon do cache:', cachedLogo);
updateFavicon(cachedLogo); updateFavicon(cachedLogo);
} }
}; };
@@ -146,24 +119,8 @@ export function AgencyBranding({ colors }: AgencyBrandingProps) {
return () => { return () => {
window.removeEventListener('branding-update', handleUpdate); window.removeEventListener('branding-update', handleUpdate);
}; };
}, [mounted, colors]); }, [colors]);
if (!mounted) return null; // Componente não renderiza nada visualmente (apenas efeitos colaterais)
return null;
return (
<div style={{
position: 'fixed',
bottom: '10px',
left: '10px',
background: 'rgba(0,0,0,0.8)',
color: 'white',
padding: '5px 10px',
borderRadius: '4px',
fontSize: '10px',
zIndex: 9999,
pointerEvents: 'none'
}}>
DEBUG: {debugInfo}
</div>
);
} }

View File

@@ -69,18 +69,22 @@ export const SidebarRail: React.FC<SidebarRailProps> = ({
if (res.ok) { if (res.ok) {
const data = await res.json(); const data = await res.json();
if (currentUser) { 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 = { const updatedUser = {
...currentUser, ...currentUser,
company: data.name || currentUser.company, company: data.name || currentUser.company,
logoUrl: data.logo_url logoUrl: finalLogoUrl
}; };
setUser(updatedUser); setUser(updatedUser);
saveAuth(token, updatedUser); // Persistir atualização saveAuth(token, updatedUser); // Persistir atualização
// Atualizar localStorage do logo para uso do favicon // Atualizar localStorage do logo (preservar se já existe)
if (data.logo_url) { if (finalLogoUrl) {
console.log('📝 Salvando logo no localStorage:', data.logo_url); console.log('📝 Salvando logo no localStorage:', finalLogoUrl);
localStorage.setItem('agency-logo-url', data.logo_url); localStorage.setItem('agency-logo-url', finalLogoUrl);
window.dispatchEvent(new Event('auth-update')); // Notificar favicon window.dispatchEvent(new Event('auth-update')); // Notificar favicon
window.dispatchEvent(new Event('branding-update')); // Notificar AgencyBranding window.dispatchEvent(new Event('branding-update')); // Notificar AgencyBranding
} }

View File

@@ -23,9 +23,15 @@ export async function getAgencyBranding(): Promise<AgencyBrandingData | null> {
// Pegar o hostname do request // Pegar o hostname do request
const headersList = await headers(); const headersList = await headers();
const hostname = headersList.get('host') || ''; const hostname = headersList.get('host') || '';
const subdomain = hostname.split('.')[0];
// 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') { if (!subdomain || subdomain === 'localhost' || subdomain === 'www') {
console.log(`[ServerAPI] Invalid subdomain, skipping: ${subdomain}`);
return null; return null;
} }

View File

@@ -7,11 +7,16 @@ export async function middleware(request: NextRequest) {
const apiBase = process.env.API_INTERNAL_URL || 'http://backend:8080'; const apiBase = process.env.API_INTERNAL_URL || 'http://backend:8080';
// Extrair subdomínio // Extrair subdomínio (remover porta se houver)
const subdomain = hostname.split('.')[0]; const hostnameWithoutPort = hostname.split(':')[0];
const subdomain = hostnameWithoutPort.split('.')[0];
// Validar subdomínio de agência ({subdomain}.localhost) // Rotas públicas que não precisam de validação de tenant
if (hostname.includes('.')) { const publicPaths = ['/login', '/cadastro', '/'];
const isPublicPath = publicPaths.some(path => url.pathname === path || url.pathname.startsWith(path + '/'));
// Validar subdomínio de agência ({subdomain}.localhost) apenas se não for rota pública
if (hostname.includes('.') && !isPublicPath) {
try { try {
const res = await fetch(`${apiBase}/api/tenant/check?subdomain=${subdomain}`, { const res = await fetch(`${apiBase}/api/tenant/check?subdomain=${subdomain}`, {
cache: 'no-store', cache: 'no-store',

View File

@@ -7,11 +7,13 @@ import {
LinkIcon, LinkIcon,
DocumentTextIcon, DocumentTextIcon,
Cog6ToothIcon, Cog6ToothIcon,
SparklesIcon,
} from '@heroicons/react/24/outline'; } from '@heroicons/react/24/outline';
const SUPERADMIN_MENU_ITEMS = [ const SUPERADMIN_MENU_ITEMS = [
{ id: 'dashboard', label: 'Dashboard', href: '/superadmin', icon: HomeIcon }, { id: 'dashboard', label: 'Dashboard', href: '/superadmin', icon: HomeIcon },
{ id: 'agencies', label: 'Agências', href: '/superadmin/agencies', icon: BuildingOfficeIcon }, { id: 'agencies', label: 'Agências', href: '/superadmin/agencies', icon: BuildingOfficeIcon },
{ id: 'plans', label: 'Planos', href: '/superadmin/plans', icon: SparklesIcon },
{ id: 'templates', label: 'Templates', href: '/superadmin/signup-templates', icon: LinkIcon }, { id: 'templates', label: 'Templates', href: '/superadmin/signup-templates', icon: LinkIcon },
{ id: 'agency-templates', label: 'Templates Agência', href: '/superadmin/agency-templates', icon: DocumentTextIcon }, { id: 'agency-templates', label: 'Templates Agência', href: '/superadmin/agency-templates', icon: DocumentTextIcon },
{ id: 'settings', label: 'Configurações', href: '/superadmin/settings', icon: Cog6ToothIcon }, { id: 'settings', label: 'Configurações', href: '/superadmin/settings', icon: Cog6ToothIcon },

View File

@@ -0,0 +1,371 @@
'use client';
import { useEffect, useState } from 'react';
import { useRouter, useParams } from 'next/navigation';
import { ArrowLeftIcon, CheckCircleIcon } from '@heroicons/react/24/outline';
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;
}
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>>({});
useEffect(() => {
const token = localStorage.getItem('token');
if (!token) {
router.push('/login');
return;
}
fetchPlan();
}, [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 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');
}
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="text-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
<p className="text-zinc-600 dark:text-zinc-400">Carregando plano...</p>
</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="space-y-6">
{/* Header */}
<div className="flex items-center gap-4">
<button
onClick={() => router.back()}
className="p-2 hover:bg-zinc-100 dark:hover:bg-zinc-800 rounded-lg transition-colors"
>
<ArrowLeftIcon className="h-6 w-6 text-zinc-600 dark:text-zinc-400" />
</button>
<div>
<h1 className="text-3xl font-bold text-zinc-900 dark:text-white">Editar Plano</h1>
<p className="mt-1 text-sm text-zinc-600 dark:text-zinc-400">{plan.name}</p>
</div>
</div>
{/* Success Message */}
{success && (
<div className="rounded-lg 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-lg 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="rounded-2xl border border-zinc-200 dark:border-zinc-800 bg-white dark:bg-zinc-900 p-6 sm:p-8">
<form className="space-y-6" onSubmit={(e) => { e.preventDefault(); handleSave(); }}>
{/* Row 1: Nome e Slug */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div>
<label className="block text-sm font-semibold text-zinc-900 dark:text-white mb-2">
Nome do Plano
</label>
<input
type="text"
name="name"
value={formData.name || ''}
onChange={handleInputChange}
className="w-full px-4 py-2.5 border border-zinc-300 dark:border-zinc-600 rounded-lg bg-white dark:bg-zinc-800 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all"
/>
</div>
<div>
<label className="block text-sm font-semibold text-zinc-900 dark:text-white mb-2">
Slug
</label>
<input
type="text"
name="slug"
value={formData.slug || ''}
onChange={handleInputChange}
className="w-full px-4 py-2.5 border border-zinc-300 dark:border-zinc-600 rounded-lg bg-white dark:bg-zinc-800 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all"
/>
</div>
</div>
{/* Descrição */}
<div>
<label className="block text-sm font-semibold text-zinc-900 dark:text-white mb-2">
Descrição
</label>
<textarea
name="description"
value={formData.description || ''}
onChange={handleInputChange}
rows={3}
className="w-full px-4 py-2.5 border border-zinc-300 dark:border-zinc-600 rounded-lg bg-white dark:bg-zinc-800 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all resize-none"
/>
</div>
{/* Row 2: Usuários */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div>
<label className="block text-sm font-semibold text-zinc-900 dark:text-white 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-4 py-2.5 border border-zinc-300 dark:border-zinc-600 rounded-lg bg-white dark:bg-zinc-800 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all"
/>
</div>
<div>
<label className="block text-sm font-semibold text-zinc-900 dark:text-white 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-4 py-2.5 border border-zinc-300 dark:border-zinc-600 rounded-lg bg-white dark:bg-zinc-800 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all"
/>
</div>
</div>
{/* Row 3: Preços */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div>
<label className="block text-sm font-semibold text-zinc-900 dark:text-white 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-4 py-2.5 border border-zinc-300 dark:border-zinc-600 rounded-lg bg-white dark:bg-zinc-800 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all"
/>
</div>
<div>
<label className="block text-sm font-semibold text-zinc-900 dark:text-white 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-4 py-2.5 border border-zinc-300 dark:border-zinc-600 rounded-lg bg-white dark:bg-zinc-800 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all"
/>
</div>
</div>
{/* Armazenamento */}
<div>
<label className="block text-sm font-semibold text-zinc-900 dark:text-white mb-2">
Armazenamento (GB)
</label>
<input
type="number"
name="storage_gb"
value={formData.storage_gb || 1}
onChange={handleInputChange}
min="1"
className="w-full px-4 py-2.5 border border-zinc-300 dark:border-zinc-600 rounded-lg bg-white dark:bg-zinc-800 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all"
/>
</div>
{/* Features */}
<div>
<label className="block text-sm font-semibold text-zinc-900 dark:text-white mb-2">
Recursos <span className="text-xs font-normal text-zinc-500">(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-4 py-2.5 border border-zinc-300 dark:border-zinc-600 rounded-lg bg-white dark:bg-zinc-800 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all resize-none"
/>
</div>
{/* Differentiators */}
<div>
<label className="block text-sm font-semibold text-zinc-900 dark:text-white mb-2">
Diferenciais <span className="text-xs font-normal text-zinc-500">(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-4 py-2.5 border border-zinc-300 dark:border-zinc-600 rounded-lg bg-white dark:bg-zinc-800 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all resize-none"
/>
</div>
{/* Status Checkbox */}
<div className="pt-4 border-t border-zinc-200 dark:border-zinc-800">
<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-blue-600 focus:ring-blue-500 dark:bg-zinc-800 cursor-pointer"
/>
<span className="text-sm font-semibold 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-800">
<button
type="submit"
disabled={saving}
className="flex-1 px-6 py-3 bg-blue-600 hover:bg-blue-700 disabled:bg-blue-400 disabled:cursor-not-allowed text-white font-semibold rounded-lg transition-colors"
>
{saving ? 'Salvando...' : 'Salvar Alterações'}
</button>
<button
type="button"
onClick={() => router.back()}
disabled={saving}
className="flex-1 px-6 py-3 border border-zinc-300 dark:border-zinc-600 text-zinc-700 dark:text-zinc-300 font-semibold rounded-lg hover:bg-zinc-50 dark:hover:bg-zinc-800 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
>
Cancelar
</button>
</div>
</form>
</div>
</div>
);
}

View File

@@ -0,0 +1,271 @@
'use client';
import { useEffect, useState } from 'react';
import { PencilIcon, TrashIcon, PlusIcon } from '@heroicons/react/24/outline';
import CreatePlanModal from '@/components/plans/CreatePlanModal';
export default function PlansPage() {
const [plans, setPlans] = useState<any[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
const [isModalOpen, setIsModalOpen] = useState(false);
useEffect(() => {
fetchPlans();
}, []);
const fetchPlans = async () => {
try {
setLoading(true);
const token = localStorage.getItem('token');
const response = await fetch('/api/admin/plans', {
headers: {
'Authorization': `Bearer ${token}`,
},
});
if (!response.ok) {
throw new Error('Erro ao carregar planos');
}
const data = await response.json();
setPlans(data.plans || []);
setError('');
} catch (err: any) {
setError(err.message);
} finally {
setLoading(false);
}
};
const handleDeletePlan = async (id: string) => {
if (!confirm('Tem certeza que deseja deletar este plano? Esta ação não pode ser desfeita.')) {
return;
}
try {
const token = localStorage.getItem('token');
const response = await fetch(`/api/admin/plans/${id}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${token}`,
},
});
if (!response.ok) {
throw new Error('Erro ao deletar plano');
}
fetchPlans();
} catch (err: any) {
setError(err.message);
}
};
if (loading) {
return (
<div className="flex items-center justify-center min-h-[400px]">
<div className="text-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
<p className="text-zinc-600 dark:text-zinc-400">Carregando planos...</p>
</div>
</div>
);
}
return (
<div className="space-y-6">
{/* Header */}
<div className="flex justify-between items-center">
<div>
<h1 className="text-3xl font-bold text-zinc-900 dark:text-white">Planos</h1>
<p className="mt-2 text-sm text-zinc-600 dark:text-zinc-400">
Gerencie os planos de assinatura disponíveis para as agências
</p>
</div>
<button
onClick={() => setIsModalOpen(true)}
className="inline-flex items-center gap-2 px-4 py-2.5 bg-blue-600 hover:bg-blue-700 text-white font-semibold rounded-lg transition-colors shadow-sm"
>
<PlusIcon className="h-5 w-5" />
Novo Plano
</button>
</div>
{/* Error Message */}
{error && (
<div className="rounded-lg 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>
)}
{/* Plans Grid */}
{plans.length > 0 ? (
<div className="grid grid-cols-1 gap-6 md:grid-cols-2 lg:grid-cols-3">
{plans.map((plan) => (
<div
key={plan.id}
className="group rounded-2xl border border-zinc-200 dark:border-zinc-800 bg-white dark:bg-zinc-900 hover:shadow-lg dark:hover:shadow-2xl transition-all duration-200 overflow-hidden"
>
{/* Header */}
<div className="px-6 pt-6 pb-4 border-b border-zinc-100 dark:border-zinc-800">
<div className="flex items-start justify-between mb-2">
<div>
<h3 className="text-lg font-semibold text-zinc-900 dark:text-white">
{plan.name}
</h3>
{!plan.is_active && (
<span className="inline-block mt-2 px-2 py-1 rounded-full text-xs font-semibold bg-zinc-100 dark:bg-zinc-800 text-zinc-600 dark:text-zinc-400">
Inativo
</span>
)}
</div>
{plan.is_active && (
<span className="px-2.5 py-1 rounded-full text-xs font-semibold bg-emerald-100 dark:bg-emerald-900/30 text-emerald-700 dark:text-emerald-400">
Ativo
</span>
)}
</div>
{plan.description && (
<p className="text-sm text-zinc-600 dark:text-zinc-400 line-clamp-2">
{plan.description}
</p>
)}
</div>
{/* Content */}
<div className="px-6 py-4 space-y-4">
{/* Pricing */}
<div className="space-y-2">
{plan.monthly_price && (
<div className="flex justify-between items-center">
<span className="text-sm text-zinc-600 dark:text-zinc-400">Mensal</span>
<span className="text-2xl font-bold text-zinc-900 dark:text-white">
R$ <span className="text-xl">{parseFloat(plan.monthly_price).toFixed(2)}</span>
</span>
</div>
)}
{plan.annual_price && (
<div className="flex justify-between items-center">
<span className="text-sm text-zinc-600 dark:text-zinc-400">Anual</span>
<span className="text-2xl font-bold text-zinc-900 dark:text-white">
R$ <span className="text-xl">{parseFloat(plan.annual_price).toFixed(2)}</span>
</span>
</div>
)}
</div>
{/* Stats */}
<div className="grid grid-cols-2 gap-3 pt-2 border-t border-zinc-100 dark:border-zinc-800">
<div className="p-3 bg-zinc-50 dark:bg-zinc-800 rounded-lg">
<p className="text-xs text-zinc-600 dark:text-zinc-400 mb-1">Usuários</p>
<p className="text-sm font-semibold text-zinc-900 dark:text-white">
{plan.min_users} - {plan.max_users === -1 ? '∞' : plan.max_users}
</p>
</div>
<div className="p-3 bg-zinc-50 dark:bg-zinc-800 rounded-lg">
<p className="text-xs text-zinc-600 dark:text-zinc-400 mb-1">Armazenamento</p>
<p className="text-sm font-semibold text-zinc-900 dark:text-white">
{plan.storage_gb} GB
</p>
</div>
</div>
{/* Features */}
{plan.features && plan.features.length > 0 && (
<div className="pt-2">
<p className="text-xs font-semibold text-zinc-700 dark:text-zinc-300 uppercase tracking-wide mb-2">
Recursos
</p>
<ul className="space-y-1">
{plan.features.slice(0, 4).map((feature: string, idx: number) => (
<li key={idx} className="text-xs text-zinc-600 dark:text-zinc-400 flex items-center gap-2">
<span className="inline-block h-1.5 w-1.5 bg-blue-600 rounded-full"></span>
{feature}
</li>
))}
{plan.features.length > 4 && (
<li className="text-xs text-zinc-600 dark:text-zinc-400 italic">
+{plan.features.length - 4} mais
</li>
)}
</ul>
</div>
)}
{/* Differentiators */}
{plan.differentiators && plan.differentiators.length > 0 && (
<div className="pt-2">
<p className="text-xs font-semibold text-zinc-700 dark:text-zinc-300 uppercase tracking-wide mb-2">
Diferenciais
</p>
<ul className="space-y-1">
{plan.differentiators.slice(0, 2).map((diff: string, idx: number) => (
<li key={idx} className="text-xs text-zinc-600 dark:text-zinc-400 flex items-center gap-2">
<span className="inline-block h-1.5 w-1.5 bg-emerald-600 rounded-full"></span>
{diff}
</li>
))}
{plan.differentiators.length > 2 && (
<li className="text-xs text-zinc-600 dark:text-zinc-400 italic">
+{plan.differentiators.length - 2} mais
</li>
)}
</ul>
</div>
)}
</div>
{/* Footer */}
<div className="px-6 py-4 bg-zinc-50 dark:bg-zinc-800/50 border-t border-zinc-100 dark:border-zinc-800 flex gap-2">
<a
href={`/superadmin/plans/${plan.id}`}
className="flex-1 inline-flex items-center justify-center gap-2 px-3 py-2 bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-400 hover:bg-blue-200 dark:hover:bg-blue-900/50 font-medium rounded-lg transition-colors text-sm"
>
<PencilIcon className="h-4 w-4" />
Editar
</a>
<button
onClick={() => handleDeletePlan(plan.id)}
className="flex-1 inline-flex items-center justify-center gap-2 px-3 py-2 bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-400 hover:bg-red-200 dark:hover:bg-red-900/50 font-medium rounded-lg transition-colors text-sm"
>
<TrashIcon className="h-4 w-4" />
Deletar
</button>
</div>
</div>
))}
</div>
) : (
<div className="text-center py-12">
<div className="text-zinc-400 dark:text-zinc-600 mb-2">
<svg
className="h-12 w-12 mx-auto"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={1.5}
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>
</div>
<p className="text-zinc-600 dark:text-zinc-400 text-lg font-medium">Nenhum plano criado</p>
<p className="text-zinc-500 dark:text-zinc-500 text-sm">Clique no botão acima para criar o primeiro plano</p>
</div>
)}
{/* Create Plan Modal */}
<CreatePlanModal
isOpen={isModalOpen}
onClose={() => setIsModalOpen(false)}
onSuccess={() => {
fetchPlans();
}}
/>
</div>
);
}

View File

@@ -0,0 +1,415 @@
'use client';
import { Fragment, useState } from 'react';
import { Dialog, Transition } from '@headlessui/react';
import {
XMarkIcon,
SparklesIcon,
} from '@heroicons/react/24/outline';
interface CreatePlanModalProps {
isOpen: boolean;
onClose: () => void;
onSuccess: (plan: any) => void;
}
interface CreatePlanForm {
name: string;
slug: string;
description: string;
min_users: number;
max_users: number;
monthly_price: string;
annual_price: string;
features: string;
differentiators: string;
storage_gb: number;
is_active: boolean;
}
function classNames(...classes: string[]) {
return classes.filter(Boolean).join(' ');
}
export default function CreatePlanModal({ isOpen, onClose, onSuccess }: CreatePlanModalProps) {
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const [formData, setFormData] = useState<CreatePlanForm>({
name: '',
slug: '',
description: '',
min_users: 1,
max_users: 30,
monthly_price: '',
annual_price: '',
features: '',
differentiators: '',
storage_gb: 1,
is_active: true,
});
const handleChange = (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]: parseFloat(value) || 0,
}));
} else {
setFormData(prev => ({
...prev,
[name]: value,
}));
}
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setLoading(true);
setError('');
try {
// Validações básicas
if (!formData.name || !formData.slug) {
setError('Nome e Slug são obrigatórios');
setLoading(false);
return;
}
const token = localStorage.getItem('token');
// Parse features e differentiators
const features = formData.features
.split(',')
.map(f => f.trim())
.filter(f => f.length > 0);
const differentiators = formData.differentiators
.split(',')
.map(d => d.trim())
.filter(d => d.length > 0);
const payload = {
name: formData.name,
slug: formData.slug,
description: formData.description,
min_users: formData.min_users,
max_users: formData.max_users,
monthly_price: formData.monthly_price ? parseFloat(formData.monthly_price) : null,
annual_price: formData.annual_price ? parseFloat(formData.annual_price) : null,
features,
differentiators,
storage_gb: formData.storage_gb,
is_active: formData.is_active,
};
const response = await fetch('/api/admin/plans', {
method: 'POST',
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 criar plano');
}
const data = await response.json();
onSuccess(data.plan);
onClose();
} catch (err: any) {
setError(err.message);
} finally {
setLoading(false);
}
};
const handleClose = () => {
if (!loading) {
setError('');
setFormData({
name: '',
slug: '',
description: '',
min_users: 1,
max_users: 30,
monthly_price: '',
annual_price: '',
features: '',
differentiators: '',
storage_gb: 1,
is_active: true,
});
onClose();
}
};
return (
<Transition.Root show={isOpen} as={Fragment}>
<Dialog as="div" className="relative z-50" onClose={handleClose}>
<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-2xl border border-zinc-200 dark:border-zinc-800">
<div className="absolute right-0 top-0 hidden pr-4 pt-4 sm:block">
<button
type="button"
className="rounded-md bg-white dark:bg-zinc-900 text-zinc-400 hover:text-zinc-500 focus:outline-none"
onClick={handleClose}
disabled={loading}
>
<span className="sr-only">Fechar</span>
<XMarkIcon className="h-6 w-6" aria-hidden="true" />
</button>
</div>
<div className="p-6 sm:p-8">
{/* Header */}
<div className="sm:flex sm:items-start mb-6">
<div className="mx-auto flex h-12 w-12 flex-shrink-0 items-center justify-center rounded-full bg-blue-100 dark:bg-blue-900 sm:mx-0 sm:h-10 sm:w-10">
<SparklesIcon className="h-6 w-6 text-blue-600 dark:text-blue-400" aria-hidden="true" />
</div>
<div className="mt-3 text-center sm:ml-4 sm:mt-0 sm:text-left">
<Dialog.Title as="h3" className="text-xl font-semibold leading-6 text-zinc-900 dark:text-white">
Criar Novo Plano
</Dialog.Title>
<div className="mt-2">
<p className="text-sm text-zinc-500 dark:text-zinc-400">
Configure um novo plano de assinatura para as agências.
</p>
</div>
</div>
</div>
{/* Error Message */}
{error && (
<div className="mb-4 rounded-lg 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 onSubmit={handleSubmit} className="space-y-4">
{/* Row 1: Nome e Slug */}
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-zinc-900 dark:text-zinc-100 mb-1">
Nome do Plano *
</label>
<input
type="text"
name="name"
value={formData.name}
onChange={handleChange}
placeholder="Ex: Ignição"
className="w-full px-3 py-2 border border-zinc-300 dark:border-zinc-600 rounded-lg bg-white dark:bg-zinc-800 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
required
/>
</div>
<div>
<label className="block text-sm font-medium text-zinc-900 dark:text-zinc-100 mb-1">
Slug *
</label>
<input
type="text"
name="slug"
value={formData.slug}
onChange={handleChange}
placeholder="Ex: ignition"
className="w-full px-3 py-2 border border-zinc-300 dark:border-zinc-600 rounded-lg bg-white dark:bg-zinc-800 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
required
/>
</div>
</div>
{/* Descrição */}
<div>
<label className="block text-sm font-medium text-zinc-900 dark:text-zinc-100 mb-1">
Descrição
</label>
<textarea
name="description"
value={formData.description}
onChange={handleChange}
placeholder="Descrição breve do plano"
rows={2}
className="w-full px-3 py-2 border border-zinc-300 dark:border-zinc-600 rounded-lg bg-white dark:bg-zinc-800 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none"
/>
</div>
{/* Row 2: Usuários */}
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-zinc-900 dark:text-zinc-100 mb-1">
Mín. Usuários
</label>
<input
type="number"
name="min_users"
value={formData.min_users}
onChange={handleChange}
min="1"
className="w-full px-3 py-2 border border-zinc-300 dark:border-zinc-600 rounded-lg bg-white dark:bg-zinc-800 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
/>
</div>
<div>
<label className="block text-sm font-medium text-zinc-900 dark:text-zinc-100 mb-1">
Máx. Usuários (-1 = ilimitado)
</label>
<input
type="number"
name="max_users"
value={formData.max_users}
onChange={handleChange}
className="w-full px-3 py-2 border border-zinc-300 dark:border-zinc-600 rounded-lg bg-white dark:bg-zinc-800 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
/>
</div>
</div>
{/* Row 3: Preços */}
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-zinc-900 dark:text-zinc-100 mb-1">
Preço Mensal (BRL)
</label>
<input
type="number"
name="monthly_price"
value={formData.monthly_price}
onChange={handleChange}
placeholder="199.99"
step="0.01"
className="w-full px-3 py-2 border border-zinc-300 dark:border-zinc-600 rounded-lg bg-white dark:bg-zinc-800 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
/>
</div>
<div>
<label className="block text-sm font-medium text-zinc-900 dark:text-zinc-100 mb-1">
Preço Anual (BRL)
</label>
<input
type="number"
name="annual_price"
value={formData.annual_price}
onChange={handleChange}
placeholder="1919.90"
step="0.01"
className="w-full px-3 py-2 border border-zinc-300 dark:border-zinc-600 rounded-lg bg-white dark:bg-zinc-800 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
/>
</div>
</div>
{/* Row 4: Storage */}
<div>
<label className="block text-sm font-medium text-zinc-900 dark:text-zinc-100 mb-1">
Armazenamento (GB)
</label>
<input
type="number"
name="storage_gb"
value={formData.storage_gb}
onChange={handleChange}
min="1"
className="w-full px-3 py-2 border border-zinc-300 dark:border-zinc-600 rounded-lg bg-white dark:bg-zinc-800 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
/>
</div>
{/* Row 5: Features */}
<div>
<label className="block text-sm font-medium text-zinc-900 dark:text-zinc-100 mb-1">
Recursos <span className="text-xs text-zinc-500">(separados por vírgula)</span>
</label>
<textarea
name="features"
value={formData.features}
onChange={handleChange}
placeholder="CRM, ERP, Projetos, Helpdesk, Pagamentos, Contratos, Documentos"
rows={2}
className="w-full px-3 py-2 border border-zinc-300 dark:border-zinc-600 rounded-lg bg-white dark:bg-zinc-800 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none"
/>
</div>
{/* Row 6: Diferenciais */}
<div>
<label className="block text-sm font-medium text-zinc-900 dark:text-zinc-100 mb-1">
Diferenciais <span className="text-xs text-zinc-500">(separados por vírgula)</span>
</label>
<textarea
name="differentiators"
value={formData.differentiators}
onChange={handleChange}
placeholder="Suporte prioritário, Gerente de conta dedicado, API integrações"
rows={2}
className="w-full px-3 py-2 border border-zinc-300 dark:border-zinc-600 rounded-lg bg-white dark:bg-zinc-800 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none"
/>
</div>
{/* Status Checkbox */}
<div className="flex items-center pt-2">
<input
type="checkbox"
name="is_active"
checked={formData.is_active}
onChange={handleChange}
className="h-4 w-4 text-blue-600 rounded border-zinc-300 focus:ring-blue-500"
/>
<label className="ml-3 text-sm font-medium text-zinc-900 dark:text-zinc-100">
Plano Ativo
</label>
</div>
{/* Buttons */}
<div className="mt-6 pt-4 border-t border-zinc-200 dark:border-zinc-700 flex gap-3">
<button
type="submit"
disabled={loading}
className="flex-1 px-4 py-2.5 bg-blue-600 hover:bg-blue-700 disabled:bg-blue-400 disabled:cursor-not-allowed text-white font-medium rounded-lg transition-colors"
>
{loading ? 'Criando...' : 'Criar Plano'}
</button>
<button
type="button"
onClick={handleClose}
disabled={loading}
className="flex-1 px-4 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>
</form>
</div>
</Dialog.Panel>
</Transition.Child>
</div>
</div>
</Dialog>
</Transition.Root>
);
}

View File

@@ -0,0 +1,25 @@
-- Create plans table
CREATE TABLE IF NOT EXISTS plans (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
name VARCHAR(255) NOT NULL,
slug VARCHAR(100) NOT NULL UNIQUE,
description TEXT,
min_users INTEGER NOT NULL DEFAULT 1,
max_users INTEGER NOT NULL DEFAULT 30, -- -1 means unlimited
monthly_price NUMERIC(10, 2),
annual_price NUMERIC(10, 2),
features TEXT[] NOT NULL DEFAULT '{}',
differentiators TEXT[] NOT NULL DEFAULT '{}',
storage_gb INTEGER NOT NULL DEFAULT 1,
is_active BOOLEAN NOT NULL DEFAULT true,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- Add indexes
CREATE INDEX idx_plans_slug ON plans(slug);
CREATE INDEX idx_plans_is_active ON plans(is_active);
-- Add comments
COMMENT ON TABLE plans IS 'Subscription plans for agencies';
COMMENT ON COLUMN plans.max_users IS '-1 means unlimited users';

View File

@@ -0,0 +1,24 @@
-- Create agency_subscriptions table
CREATE TABLE IF NOT EXISTS agency_subscriptions (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
agency_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
plan_id UUID NOT NULL REFERENCES plans(id) ON DELETE RESTRICT,
billing_type VARCHAR(20) NOT NULL DEFAULT 'monthly', -- monthly or annual
current_users INTEGER NOT NULL DEFAULT 0,
status VARCHAR(50) NOT NULL DEFAULT 'active', -- active, suspended, cancelled
start_date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
renewal_date TIMESTAMP NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE(agency_id) -- One active subscription per agency
);
-- Add indexes
CREATE INDEX idx_agency_subscriptions_agency_id ON agency_subscriptions(agency_id);
CREATE INDEX idx_agency_subscriptions_plan_id ON agency_subscriptions(plan_id);
CREATE INDEX idx_agency_subscriptions_status ON agency_subscriptions(status);
-- Add comments
COMMENT ON TABLE agency_subscriptions IS 'Tracks agency subscription to plans';
COMMENT ON COLUMN agency_subscriptions.billing_type IS 'Monthly or annual billing';
COMMENT ON COLUMN agency_subscriptions.current_users IS 'Current count of users (collaborators + clients)';

View File

@@ -0,0 +1,68 @@
-- Seed the default plans
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
(
gen_random_uuid(),
'Ignição',
'ignition',
'Ideal para pequenas agências iniciantes',
1,
30,
199.99,
1919.90,
ARRAY['CRM', 'ERP', 'Projetos', 'Helpdesk', 'Pagamentos', 'Contratos', 'Documentos'],
ARRAY[]::text[],
1,
true,
CURRENT_TIMESTAMP,
CURRENT_TIMESTAMP
),
(
gen_random_uuid(),
'Órbita',
'orbit',
'Para agências em crescimento',
31,
100,
399.99,
3839.90,
ARRAY['CRM', 'ERP', 'Projetos', 'Helpdesk', 'Pagamentos', 'Contratos', 'Documentos'],
ARRAY['Suporte prioritário'],
1,
true,
CURRENT_TIMESTAMP,
CURRENT_TIMESTAMP
),
(
gen_random_uuid(),
'Cosmos',
'cosmos',
'Para agências consolidadas',
101,
300,
799.99,
7679.90,
ARRAY['CRM', 'ERP', 'Projetos', 'Helpdesk', 'Pagamentos', 'Contratos', 'Documentos'],
ARRAY['Gerente de conta dedicado', 'API integrações'],
1,
true,
CURRENT_TIMESTAMP,
CURRENT_TIMESTAMP
),
(
gen_random_uuid(),
'Enterprise',
'enterprise',
'Solução customizada para grandes agências',
301,
-1,
NULL,
NULL,
ARRAY['CRM', 'ERP', 'Projetos', 'Helpdesk', 'Pagamentos', 'Contratos', 'Documentos'],
ARRAY['Armazenamento customizado', 'Treinamento personalizado'],
1,
true,
CURRENT_TIMESTAMP,
CURRENT_TIMESTAMP
)
ON CONFLICT DO NOTHING;