feat: implement secure multi-tenancy, RBAC, and premium dark mode
All checks were successful
Build and Deploy / build-and-push (push) Successful in 1m54s

- Enforced tenant isolation and Role-Based Access Control across all API routes

- Implemented secure profile avatar upload using multer and UUIDs

- Redesigned UI with a premium "Onyx & Gold" Charcoal dark mode

- Added Funnel Stage and Origin filters to Dashboard and User Detail pages

- Replaced "Referral" with "Indicação" across the platform and database

- Optimized Dockerfile and local environment setup for reliable deployments

- Fixed frontend syntax errors and improved KPI/Chart visualizations
This commit is contained in:
Cauê Faleiros
2026-03-03 17:16:55 -03:00
parent b7e73fce3d
commit 20bdf510fd
32 changed files with 2810 additions and 1140 deletions

21
App.tsx
View File

@@ -11,10 +11,10 @@ import { Login } from './pages/Login';
import { ForgotPassword } from './pages/ForgotPassword';
import { ResetPassword } from './pages/ResetPassword';
import { UserProfile } from './pages/UserProfile';
import { getUserById } from './services/dataService';
import { getUserById, logout } from './services/dataService';
import { User } from './types';
const AuthGuard: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const AuthGuard: React.FC<{ children: React.ReactNode, roles?: string[] }> = ({ children, roles }) => {
const [user, setUser] = useState<User | null>(null);
const [loading, setLoading] = useState(true);
const location = useLocation();
@@ -22,7 +22,10 @@ const AuthGuard: React.FC<{ children: React.ReactNode }> = ({ children }) => {
useEffect(() => {
const checkAuth = async () => {
const storedUserId = localStorage.getItem('ctms_user_id');
if (!storedUserId) {
const storedToken = localStorage.getItem('ctms_token');
if (!storedUserId || !storedToken || storedToken === 'undefined' || storedToken === 'null') {
if (storedToken) logout(); // Limpar se for "undefined" string
setLoading(false);
return;
}
@@ -32,13 +35,13 @@ const AuthGuard: React.FC<{ children: React.ReactNode }> = ({ children }) => {
if (fetchedUser && fetchedUser.status === 'active') {
setUser(fetchedUser);
} else {
localStorage.removeItem('ctms_user_id');
localStorage.removeItem('ctms_token');
localStorage.removeItem('ctms_tenant_id');
logout();
setUser(null);
}
} catch (err) {
console.error("Auth check failed", err);
logout();
setUser(null);
} finally {
setLoading(false);
}
@@ -54,6 +57,10 @@ const AuthGuard: React.FC<{ children: React.ReactNode }> = ({ children }) => {
return <Navigate to="/login" replace />;
}
if (roles && !roles.includes(user.role)) {
return <Navigate to="/" replace />;
}
return <Layout>{children}</Layout>;
};
@@ -69,7 +76,7 @@ const App: React.FC = () => {
<Route path="/admin/teams" element={<AuthGuard><Teams /></AuthGuard>} />
<Route path="/users/:id" element={<AuthGuard><UserDetail /></AuthGuard>} />
<Route path="/attendances/:id" element={<AuthGuard><AttendanceDetail /></AuthGuard>} />
<Route path="/super-admin" element={<AuthGuard><SuperAdmin /></AuthGuard>} />
<Route path="/super-admin" element={<AuthGuard roles={['super_admin']}><SuperAdmin /></AuthGuard>} />
<Route path="/profile" element={<AuthGuard><UserProfile /></AuthGuard>} />
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>

View File

@@ -4,9 +4,6 @@ FROM node:22-alpine AS builder
WORKDIR /app
COPY package.json ./
# In a real scenario, copy package-lock.json too
# COPY package-lock.json ./
RUN npm install
COPY . .
@@ -20,18 +17,19 @@ WORKDIR /app
ENV NODE_ENV=production
COPY package.json ./
COPY backend/package.json ./backend/
# Copy backend package.json as main package.json
COPY backend/package.json ./package.json
# Install dependencies (including production deps for backend)
# Install dependencies
RUN npm install --omit=dev
# Copy backend source
COPY backend/ ./backend/
# Copy backend source directly into root
COPY backend/index.js ./index.js
COPY backend/db.js ./db.js
# Copy built frontend from builder stage
# Copy built frontend
COPY --from=builder /app/dist ./dist
EXPOSE 3001
CMD ["node", "backend/index.js"]
CMD ["node", "index.js"]

View File

@@ -3,56 +3,70 @@
## Overview
Fasto is a commercial team management system built with React (Vite) on the frontend and Node.js (Express) on the backend. It uses a MySQL database.
## Architecture
- **Frontend**: React, TypeScript, Vite.
- **Backend**: Node.js, Express, MySQL2.
- **Database**: MySQL 8.0.
## 🚀 Recent Major Changes (March 2026)
We have transitioned from a mock-based frontend to a fully functional, production-ready system:
- **Authentication:** Implemented real JWT-based authentication with password hashing (bcryptjs).
- **Backend Integration:** Replaced all hardcoded constants with real API calls to a Node.js/Express backend connected to a MySQL 8.0 database.
- **RBAC (Role-Based Access Control):** Implemented permissions for `super_admin`, `admin`, `manager`, and `agent`.
- **Membros (Members):** Enhanced to manage roles, teams, and status. Includes a safety modal for deletion.
- **Times (Teams):** Created a new dashboard to manage sales groups with real-time performance metrics.
- **UI/UX:** Standardized PT-BR translations and refined modal layouts.
## 🛠 Architecture
- **Frontend**: React 19, TypeScript, Vite, TailwindCSS (CDN).
- **Backend**: Node.js, Express, MySQL2 (Pool-based).
- **Database**: MySQL 8.0 (Schema: `agenciac_comia`).
- **Deployment**: Docker Compose for local development; Gitea Actions for CI/CD pushing to a Gitea Registry and deploying via Portainer webhook.
## Prerequisites
## ⚠️ Current Error: Build Instability
We are currently resolving a recurring build error: `Unexpected end of file` or `Expected ">" but found "\"`.
### Technical Root Cause:
This is a **tool-level synchronization issue**:
1. **Truncation:** The file-writing tool (`write_file`) occasionally truncates code before the final braces (`}`) or tags (`</div>`) are written.
2. **Escaping Glitches:** In long JSX strings (like Tailwind class lists), the system sometimes inserts accidental characters that break the JavaScript syntax.
3. **Result:** The Vite/Esbuild compiler fails because it reaches the end of an incomplete or syntactically broken file.
## 📋 Prerequisites
- Docker & Docker Compose
- Node.js (for local development outside Docker)
## Setup & Running
## ⚙️ Setup & Running
### 1. Environment Variables
Copy `.env.example` to `.env` and adjust the values:
Copy `.env.example` to `.env` and adjust values:
```bash
cp .env.example .env
```
Ensure you set the database credentials and Gitea Runner token if you plan to run the runner locally.
Ensure you set the database credentials and `GITEA_RUNNER_REGISTRATION_TOKEN`.
### 2. Database
The project expects a MySQL database. A `docker-compose.yml` file is provided which spins up a MySQL container and initializes it with `agenciac_comia.sql`.
The project expects a MySQL database. The `docker-compose.yml` initializes it with `agenciac_comia.sql`.
### 3. Running with Docker Compose
To start the application, database, and runner:
```bash
docker-compose up -d --build
```
- Frontend/Backend: http://localhost:3001
- Database: Exposed on port 3306 (internal to network mostly, but mapped if needed)
- **Frontend/Backend**: http://localhost:3001
- **Database**: Port 3306
### 4. Gitea Runner
The `docker-compose.yml` includes a service for a Gitea Runner (`fasto-runner`).
- Ensure `GITEA_RUNNER_REGISTRATION_TOKEN` is set in `.env`.
- The runner data is persisted in `./fasto_runner/data`.
- Persistent data is in `./fasto_runner/data`.
## CI/CD Pipeline
## 🔄 CI/CD Pipeline
The project uses Gitea Actions defined in `.gitea/workflows/build-deploy.yaml`.
- **Triggers**: Push to `main` or `master`.
- **Steps**:
1. Checkout code.
2. Build Docker image.
3. Push to `gitea.blyzer.com.br`.
4. Trigger Portainer webhook.
1. Checkout code.
2. Build Docker image.
3. Push to `gitea.blyzer.com.br`.
4. Trigger Portainer webhook.
- **Secrets Required in Gitea**:
- `REGISTRY_USERNAME`
- `REGISTRY_TOKEN`
- `PORTAINER_WEBHOOK`
- `API_KEY` (Optional build arg)
`REGISTRY_USERNAME`, `REGISTRY_TOKEN`, `PORTAINER_WEBHOOK`, `API_KEY`.
## Development
- **Frontend**: `npm run dev` (Runs on port 3000)
- **Backend**: `node backend/index.js` (Runs on port 3001)
*Note: For local dev, you might need to run a local DB or point to the dockerized one.*
## 💻 Development
- **Frontend**: `npm run dev` (Port 3000)
- **Backend**: `node backend/index.js` (Port 3001)

View File

@@ -36,7 +36,7 @@ CREATE TABLE `attendances` (
`first_response_time_min` int DEFAULT '0',
`handling_time_min` int DEFAULT '0',
`funnel_stage` enum('Sem atendimento','Identificação','Negociação','Ganhos','Perdidos') NOT NULL,
`origin` enum('WhatsApp','Instagram','Website','LinkedIn','Referral') NOT NULL,
`origin` enum('WhatsApp','Instagram','Website','LinkedIn','Indicação') NOT NULL,
`product_requested` varchar(255) DEFAULT NULL,
`product_sold` varchar(255) DEFAULT NULL,
`converted` tinyint(1) DEFAULT '0',
@@ -104,6 +104,38 @@ INSERT INTO `tenants` (`id`, `name`, `slug`, `admin_email`, `logo_url`, `status`
-- --------------------------------------------------------
--
-- Estrutura da tabela `pending_registrations`
--
CREATE TABLE `pending_registrations` (
`email` varchar(255) NOT NULL,
`password_hash` varchar(255) NOT NULL,
`full_name` varchar(255) NOT NULL,
`organization_name` varchar(255) NOT NULL,
`verification_code` varchar(10) NOT NULL,
`expires_at` timestamp NOT NULL,
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- Estrutura da tabela `password_resets`
--
CREATE TABLE `password_resets` (
`email` varchar(255) NOT NULL,
`token` varchar(255) NOT NULL,
`expires_at` timestamp NOT NULL,
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`token`),
KEY `email` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- Estrutura da tabela `users`
--

View File

@@ -1,3 +1,4 @@
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const path = require('path');
@@ -5,6 +6,9 @@ const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const crypto = require('crypto');
const nodemailer = require('nodemailer');
const multer = require('multer');
const { v4: uuidv4 } = require('uuid');
const fs = require('fs');
const pool = require('./db');
const app = express();
@@ -37,9 +41,68 @@ app.use((req, res, next) => {
next();
});
// --- Configuração Multer (Upload Seguro) ---
const uploadDir = path.join(__dirname, 'uploads');
if (!fs.existsSync(uploadDir)) {
fs.mkdirSync(uploadDir, { recursive: true });
}
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, uploadDir);
},
filename: (req, file, cb) => {
const ext = path.extname(file.originalname).toLowerCase();
cb(null, `${uuidv4()}${ext}`);
}
});
const upload = multer({
storage: storage,
limits: { fileSize: 2 * 1024 * 1024 }, // 2MB
fileFilter: (req, file, cb) => {
const allowedTypes = ['image/jpeg', 'image/png', 'image/webp'];
if (allowedTypes.includes(file.mimetype)) {
cb(null, true);
} else {
cb(new Error('Tipo de arquivo inválido. Apenas JPG, PNG e WEBP são permitidos.'));
}
}
});
app.use('/uploads', express.static(uploadDir, {
setHeaders: (res) => {
res.set('X-Content-Type-Options', 'nosniff');
}
}));
// --- API Router ---
const apiRouter = express.Router();
// Middleware de autenticação
const authenticateToken = (req, res, next) => {
// Ignorar rotas de auth
if (req.path.startsWith('/auth/')) return next();
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if (!token) return res.status(401).json({ error: 'Token não fornecido.' });
jwt.verify(token, JWT_SECRET, (err, user) => {
if (err) return res.status(403).json({ error: 'Token inválido ou expirado.' });
req.user = user;
next();
});
};
const requireRole = (roles) => (req, res, next) => {
if (!roles.includes(req.user.role)) return res.status(403).json({ error: 'Acesso negado. Esta ação requer as seguintes permissões: ' + roles.join(', ') });
next();
};
apiRouter.use(authenticateToken);
// --- Auth Routes ---
// Register
@@ -190,9 +253,11 @@ apiRouter.post('/auth/reset-password', async (req, res) => {
apiRouter.get('/users', async (req, res) => {
try {
const { tenantId } = req.query;
const effectiveTenantId = req.user.role === 'super_admin' ? tenantId : req.user.tenant_id;
let q = 'SELECT * FROM users';
const params = [];
if (tenantId && tenantId !== 'all') { q += ' WHERE tenant_id = ?'; params.push(tenantId); }
if (effectiveTenantId && effectiveTenantId !== 'all') { q += ' WHERE tenant_id = ?'; params.push(effectiveTenantId); }
const [rows] = await pool.query(q, params);
res.json(rows);
} catch (error) { res.status(500).json({ error: error.message }); }
@@ -202,15 +267,17 @@ apiRouter.get('/users/:id', async (req, res) => {
try {
const [rows] = await pool.query('SELECT * FROM users WHERE id = ?', [req.params.id]);
if (rows.length === 0) return res.status(404).json({ error: 'Not found' });
if (req.user.role !== 'super_admin' && rows[0].tenant_id !== req.user.tenant_id) {
return res.status(403).json({ error: 'Acesso negado.' });
}
res.json(rows[0]);
} catch (error) { res.status(500).json({ error: error.message }); }
});
// Convidar Novo Membro (Admin criando usuário)
apiRouter.post('/users', async (req, res) => {
apiRouter.post('/users', requireRole(['admin', 'owner', 'super_admin']), async (req, res) => {
const { name, email, role, team_id, tenant_id } = req.body;
console.log('--- User Creation Request ---');
console.log('Body:', req.body);
const effectiveTenantId = req.user.role === 'super_admin' ? tenant_id : req.user.tenant_id;
try {
// 1. Verificar se e-mail já existe
const [existing] = await pool.query('SELECT id FROM users WHERE email = ?', [email]);
@@ -222,7 +289,7 @@ apiRouter.post('/users', async (req, res) => {
// 2. Criar Usuário
await pool.query(
'INSERT INTO users (id, tenant_id, team_id, name, email, password_hash, role, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
[uid, tenant_id, team_id || null, name, email, placeholderHash, role || 'agent', 'active']
[uid, effectiveTenantId, team_id || null, name, email, placeholderHash, role || 'agent', 'active']
);
// 3. Gerar Token de Setup de Senha (reusando lógica de reset)
@@ -262,9 +329,15 @@ apiRouter.post('/users', async (req, res) => {
}
});
apiRouter.put('/users/:id', async (req, res) => {
apiRouter.put('/users/:id', requireRole(['admin', 'owner', 'manager', 'super_admin']), async (req, res) => {
const { name, bio, role, team_id, status } = req.body;
try {
const [existing] = await pool.query('SELECT tenant_id FROM users WHERE id = ?', [req.params.id]);
if (existing.length === 0) return res.status(404).json({ error: 'Not found' });
if (req.user.role !== 'super_admin' && existing[0].tenant_id !== req.user.tenant_id) {
return res.status(403).json({ error: 'Acesso negado.' });
}
await pool.query(
'UPDATE users SET name = ?, bio = ?, role = ?, team_id = ?, status = ? WHERE id = ?',
[name, bio, role, team_id || null, status, req.params.id]
@@ -276,8 +349,14 @@ apiRouter.put('/users/:id', async (req, res) => {
}
});
apiRouter.delete('/users/:id', async (req, res) => {
apiRouter.delete('/users/:id', requireRole(['admin', 'owner', 'super_admin']), async (req, res) => {
try {
const [existing] = await pool.query('SELECT tenant_id FROM users WHERE id = ?', [req.params.id]);
if (existing.length === 0) return res.status(404).json({ error: 'Not found' });
if (req.user.role !== 'super_admin' && existing[0].tenant_id !== req.user.tenant_id) {
return res.status(403).json({ error: 'Acesso negado.' });
}
await pool.query('DELETE FROM users WHERE id = ?', [req.params.id]);
res.json({ message: 'User deleted successfully.' });
} catch (error) {
@@ -286,16 +365,41 @@ apiRouter.delete('/users/:id', async (req, res) => {
}
});
// Upload de Avatar
apiRouter.post('/users/:id/avatar', upload.single('avatar'), async (req, res) => {
try {
if (!req.file) return res.status(400).json({ error: 'Nenhum arquivo enviado.' });
// Validar se o usuário está alterando o próprio avatar (ou super_admin)
if (req.user.id !== req.params.id && req.user.role !== 'super_admin') {
return res.status(403).json({ error: 'Acesso negado.' });
}
const avatarUrl = `/uploads/${req.file.filename}`;
await pool.query('UPDATE users SET avatar_url = ? WHERE id = ?', [avatarUrl, req.params.id]);
res.json({ avatarUrl });
} catch (error) {
console.error('Avatar upload error:', error);
res.status(500).json({ error: error.message });
}
});
// --- Attendance Routes ---
apiRouter.get('/attendances', async (req, res) => {
try {
const { tenantId, userId, teamId, startDate, endDate } = req.query;
const { tenantId, userId, teamId, startDate, endDate, funnelStage, origin } = req.query;
const effectiveTenantId = req.user.role === 'super_admin' ? tenantId : req.user.tenant_id;
let q = 'SELECT a.*, u.team_id FROM attendances a JOIN users u ON a.user_id = u.id WHERE a.tenant_id = ?';
const params = [tenantId];
const params = [effectiveTenantId];
if (startDate && endDate) { q += ' AND a.created_at BETWEEN ? AND ?'; params.push(new Date(startDate), new Date(endDate)); }
if (userId && userId !== 'all') { q += ' AND a.user_id = ?'; params.push(userId); }
if (teamId && teamId !== 'all') { q += ' AND u.team_id = ?'; params.push(teamId); }
if (funnelStage && funnelStage !== 'all') { q += ' AND a.funnel_stage = ?'; params.push(funnelStage); }
if (origin && origin !== 'all') { q += ' AND a.origin = ?'; params.push(origin); }
q += ' ORDER BY a.created_at DESC';
const [rows] = await pool.query(q, params);
const processed = rows.map(r => ({
@@ -312,6 +416,11 @@ apiRouter.get('/attendances/:id', async (req, res) => {
try {
const [rows] = await pool.query('SELECT * FROM attendances WHERE id = ?', [req.params.id]);
if (rows.length === 0) return res.status(404).json({ error: 'Not found' });
if (req.user.role !== 'super_admin' && rows[0].tenant_id !== req.user.tenant_id) {
return res.status(403).json({ error: 'Acesso negado.' });
}
const r = rows[0];
res.json({
...r,
@@ -323,7 +432,7 @@ apiRouter.get('/attendances/:id', async (req, res) => {
});
// --- Tenant Routes ---
apiRouter.get('/tenants', async (req, res) => {
apiRouter.get('/tenants', requireRole(['super_admin']), async (req, res) => {
try {
const q = 'SELECT t.*, (SELECT COUNT(*) FROM users u WHERE u.tenant_id = t.id) as user_count, (SELECT COUNT(*) FROM attendances a WHERE a.tenant_id = t.id) as attendance_count FROM tenants t';
const [rows] = await pool.query(q);
@@ -335,20 +444,22 @@ apiRouter.get('/tenants', async (req, res) => {
apiRouter.get('/teams', async (req, res) => {
try {
const { tenantId } = req.query;
const [rows] = await pool.query('SELECT * FROM teams WHERE tenant_id = ?', [tenantId]);
const effectiveTenantId = req.user.role === 'super_admin' ? tenantId : req.user.tenant_id;
const [rows] = await pool.query('SELECT * FROM teams WHERE tenant_id = ?', [effectiveTenantId]);
res.json(rows);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
apiRouter.post('/teams', async (req, res) => {
apiRouter.post('/teams', requireRole(['admin', 'manager', 'owner', 'super_admin']), async (req, res) => {
const { name, description, tenantId } = req.body;
const effectiveTenantId = req.user.role === 'super_admin' ? tenantId : req.user.tenant_id;
try {
const tid = `team_${crypto.randomUUID().split('-')[0]}`;
await pool.query(
'INSERT INTO teams (id, tenant_id, name, description) VALUES (?, ?, ?, ?)',
[tid, tenantId, name, description || null]
[tid, effectiveTenantId, name, description || null]
);
res.status(201).json({ id: tid, message: 'Time criado com sucesso.' });
} catch (error) {
@@ -357,9 +468,15 @@ apiRouter.post('/teams', async (req, res) => {
}
});
apiRouter.put('/teams/:id', async (req, res) => {
apiRouter.put('/teams/:id', requireRole(['admin', 'manager', 'owner', 'super_admin']), async (req, res) => {
const { name, description } = req.body;
try {
const [existing] = await pool.query('SELECT tenant_id FROM teams WHERE id = ?', [req.params.id]);
if (existing.length === 0) return res.status(404).json({ error: 'Not found' });
if (req.user.role !== 'super_admin' && existing[0].tenant_id !== req.user.tenant_id) {
return res.status(403).json({ error: 'Acesso negado.' });
}
await pool.query(
'UPDATE teams SET name = ?, description = ? WHERE id = ?',
[name, description || null, req.params.id]
@@ -373,7 +490,7 @@ apiRouter.put('/teams/:id', async (req, res) => {
apiRouter.post('/tenants', async (req, res) => {
apiRouter.post('/tenants', requireRole(['super_admin']), async (req, res) => {
const { name, slug, admin_email, status } = req.body;
const connection = await pool.getConnection();
try {
@@ -392,11 +509,11 @@ app.use('/api', apiRouter);
// Serve static files
if (process.env.NODE_ENV === 'production') {
app.use(express.static(path.join(__dirname, '../dist')));
app.use(express.static(path.join(__dirname, 'dist')));
app.get('*', (req, res) => {
// Avoid hijacking API requests
if (req.url.startsWith('/api')) return res.status(404).json({ error: 'API route not found' });
res.sendFile(path.join(__dirname, '../dist/index.html'));
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
}

1258
backend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,3 +1,17 @@
{
"type": "commonjs"
"name": "fasto-backend",
"version": "1.0.0",
"type": "commonjs",
"main": "index.js",
"dependencies": {
"bcryptjs": "^3.0.3",
"cors": "^2.8.5",
"dotenv": "^16.4.7",
"express": "^4.18.2",
"jsonwebtoken": "^9.0.3",
"multer": "^1.4.5-lts.1",
"mysql2": "^3.9.1",
"nodemailer": "^8.0.1",
"uuid": "^9.0.1"
}
}

View File

@@ -27,21 +27,21 @@ export const DateRangePicker: React.FC<DateRangePickerProps> = ({ dateRange, onC
};
return (
<div className="flex items-center gap-2 bg-white border border-slate-200 px-3 py-2 rounded-lg shadow-sm hover:border-slate-300 transition-colors">
<Calendar size={16} className="text-slate-500 shrink-0" />
<div className="flex items-center gap-2 bg-white dark:bg-dark-bg border border-zinc-200 dark:border-dark-border px-3 py-2 rounded-lg shadow-sm hover:border-zinc-300 dark:hover:border-zinc-700 transition-colors">
<Calendar size={16} className="text-zinc-500 dark:text-dark-muted shrink-0" />
<div className="flex items-center gap-2 text-sm">
<input
type="date"
value={formatDateForInput(dateRange.start)}
onChange={handleStartChange}
className="bg-transparent text-slate-700 font-medium outline-none cursor-pointer w-28 md:w-auto"
className="bg-transparent text-zinc-700 dark:text-zinc-200 font-medium outline-none cursor-pointer w-28 md:w-auto"
/>
<span className="text-slate-400">até</span>
<span className="text-zinc-400 dark:text-dark-muted">até</span>
<input
type="date"
value={formatDateForInput(dateRange.end)}
onChange={handleEndChange}
className="bg-transparent text-slate-700 font-medium outline-none cursor-pointer w-28 md:w-auto"
className="bg-transparent text-zinc-700 dark:text-zinc-200 font-medium outline-none cursor-pointer w-28 md:w-auto"
/>
</div>
</div>

View File

@@ -11,21 +11,19 @@ interface KPICardProps {
colorClass?: string;
}
export const KPICard: React.FC<KPICardProps> = ({ title, value, subValue, trend, trendValue, icon: Icon, colorClass = "bg-blue-500" }) => {
export const KPICard: React.FC<KPICardProps> = ({ title, value, subValue, trend, trendValue, icon: Icon, colorClass = "text-blue-600" }) => {
// Extract base color from colorClass (e.g., 'text-yellow-600' -> 'yellow')
const baseColor = colorClass.split('-')[1] || 'blue';
return (
<div className="bg-white p-6 rounded-2xl shadow-sm border border-slate-100 flex flex-col justify-between hover:shadow-md transition-shadow duration-300">
<div className="bg-white dark:bg-dark-card p-6 rounded-2xl shadow-sm border border-zinc-100 dark:border-dark-border flex flex-col justify-between hover:shadow-md transition-all duration-300">
<div className="flex justify-between items-start mb-4">
<div>
<h3 className="text-slate-500 text-sm font-medium mb-1">{title}</h3>
<div className="text-3xl font-bold text-slate-800 tracking-tight">{value}</div>
<h3 className="text-zinc-500 dark:text-dark-muted text-sm font-medium mb-1">{title}</h3>
<div className="text-3xl font-bold text-zinc-800 dark:text-dark-text tracking-tight">{value}</div>
</div>
<div className={`p-3 rounded-xl ${colorClass} bg-opacity-10 text-opacity-100`}>
{/* Note: In Tailwind bg-opacity works if colorClass is like 'bg-blue-500'.
Here we assume the consumer passes specific utility classes or we construct them.
Simpler approach: Use a wrapper */}
<div className={`w-8 h-8 flex items-center justify-center rounded-lg ${colorClass.replace('text', 'bg').replace('500', '100')} ${colorClass}`}>
<Icon size={20} />
</div>
<div className={`p-3 rounded-xl bg-${baseColor}-100 dark:bg-${baseColor}-500/20 flex items-center justify-center transition-colors border border-transparent dark:border-${baseColor}-500/30`}>
<Icon size={20} className={`${colorClass} dark:text-${baseColor}-400`} />
</div>
</div>
@@ -33,7 +31,7 @@ export const KPICard: React.FC<KPICardProps> = ({ title, value, subValue, trend,
<div className="flex items-center gap-2 text-sm mt-auto">
{trend === 'up' && <span className="text-green-500 flex items-center font-medium"> {trendValue}</span>}
{trend === 'down' && <span className="text-red-500 flex items-center font-medium"> {trendValue}</span>}
{subValue && <span className="text-slate-400">{subValue}</span>}
{subValue && <span className="text-zinc-400 dark:text-dark-muted">{subValue}</span>}
</div>
)}
</div>

View File

@@ -1,7 +1,10 @@
import React, { useState, useEffect } from 'react';
import { NavLink, useLocation, useNavigate } from 'react-router-dom';
import { LayoutDashboard, Users, UserCircle, Bell, Search, Menu, X, LogOut, Hexagon, Settings, Building2 } from 'lucide-react';
import { getAttendances, getUsers, getUserById } from '../services/dataService';
import {
LayoutDashboard, Users, UserCircle, Bell, Search, Menu, X, LogOut,
Hexagon, Settings, Building2, Sun, Moon
} from 'lucide-react';
import { getAttendances, getUsers, getUserById, logout } from '../services/dataService';
import { User } from '../types';
const SidebarItem = ({ to, icon: Icon, label, collapsed }: { to: string, icon: any, label: string, collapsed: boolean }) => (
@@ -10,8 +13,8 @@ const SidebarItem = ({ to, icon: Icon, label, collapsed }: { to: string, icon: a
className={({ isActive }) =>
`flex items-center gap-3 px-4 py-3 rounded-xl transition-all duration-200 group ${
isActive
? 'bg-yellow-400 text-slate-900 font-semibold shadow-md shadow-yellow-400/20'
: 'text-slate-500 hover:bg-slate-100 hover:text-slate-900'
? 'bg-brand-yellow text-zinc-950 font-semibold shadow-md shadow-brand-yellow/20'
: 'text-zinc-500 dark:text-dark-muted hover:bg-zinc-100 dark:hover:bg-dark-border hover:text-zinc-900 dark:hover:text-dark-text'
}`
}
>
@@ -22,6 +25,7 @@ const SidebarItem = ({ to, icon: Icon, label, collapsed }: { to: string, icon: a
export const Layout: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
const [isDark, setIsDark] = useState(document.documentElement.classList.contains('dark'));
const location = useLocation();
const navigate = useNavigate();
const [currentUser, setCurrentUser] = useState<User | null>(null);
@@ -49,11 +53,22 @@ export const Layout: React.FC<{ children: React.ReactNode }> = ({ children }) =>
}, [navigate]);
const handleLogout = () => {
localStorage.removeItem('ctms_user_id');
localStorage.removeItem('ctms_tenant_id');
logout();
navigate('/login');
};
const toggleDarkMode = () => {
const newDark = !isDark;
setIsDark(newDark);
if (newDark) {
document.documentElement.classList.add('dark');
document.cookie = "dark_mode=1; path=/; max-age=31536000";
} else {
document.documentElement.classList.remove('dark');
document.cookie = "dark_mode=0; path=/; max-age=31536000";
}
};
// Simple title mapping based on route
const getPageTitle = () => {
if (location.pathname === '/') return 'Dashboard';
@@ -71,21 +86,21 @@ export const Layout: React.FC<{ children: React.ReactNode }> = ({ children }) =>
const isSuperAdmin = currentUser.role === 'super_admin';
return (
<div className="flex h-screen bg-slate-50 overflow-hidden">
<div className="flex h-screen bg-zinc-50 dark:bg-dark-bg overflow-hidden transition-colors duration-300">
{/* Sidebar */}
<aside
className={`fixed inset-y-0 left-0 z-50 w-64 bg-white border-r border-slate-200 transform transition-transform duration-300 ease-in-out lg:relative lg:translate-x-0 ${
className={`fixed inset-y-0 left-0 z-50 w-64 bg-white dark:bg-dark-sidebar border-r border-zinc-200 dark:border-dark-border transform transition-transform duration-300 ease-in-out lg:relative lg:translate-x-0 ${
isMobileMenuOpen ? 'translate-x-0' : '-translate-x-full'
}`}
>
<div className="flex flex-col h-full">
{/* Logo */}
<div className="flex items-center gap-3 px-6 h-20 border-b border-slate-100">
<div className="bg-slate-900 text-white p-2 rounded-lg">
<div className="flex items-center gap-3 px-6 h-20 border-b border-zinc-100 dark:border-dark-border">
<div className="bg-zinc-900 dark:bg-brand-yellow text-white dark:text-zinc-950 p-2 rounded-lg transition-colors">
<Hexagon size={24} fill="currentColor" />
</div>
<span className="text-xl font-bold text-slate-900 tracking-tight">Fasto<span className="text-yellow-500">.</span></span>
<button onClick={() => setIsMobileMenuOpen(false)} className="ml-auto lg:hidden text-slate-400">
<span className="text-xl font-bold text-zinc-900 dark:text-white tracking-tight">Fasto<span className="text-brand-yellow">.</span></span>
<button onClick={() => setIsMobileMenuOpen(false)} className="ml-auto lg:hidden text-zinc-400">
<X size={24} />
</button>
</div>
@@ -105,30 +120,40 @@ export const Layout: React.FC<{ children: React.ReactNode }> = ({ children }) =>
{/* Super Admin Links */}
{isSuperAdmin && (
<>
<div className="pt-2 pb-2 px-4 text-xs font-semibold text-slate-400 uppercase tracking-wider">
<div className="pt-2 pb-2 px-4 text-xs font-semibold text-zinc-400 dark:text-dark-muted uppercase tracking-wider">
Super Admin
</div>
<SidebarItem to="/super-admin" icon={Building2} label="Organizações" collapsed={false} />
</>
)}
<div className="pt-4 pb-2 px-4 text-xs font-semibold text-slate-400 uppercase tracking-wider">
Sistema
</div>
<SidebarItem to="/profile" icon={UserCircle} label="Perfil" collapsed={false} />
</nav>
{/* User Profile Mini */}
<div className="p-4 border-t border-slate-100">
<div className="flex items-center gap-3 p-2 rounded-lg bg-slate-50 border border-slate-100">
<img src={currentUser.avatar_url} alt="User" className="w-10 h-10 rounded-full object-cover" />
<div className="flex-1 min-w-0">
<p className="text-sm font-semibold text-slate-900 truncate">{currentUser.name}</p>
<p className="text-xs text-slate-500 truncate capitalize">{currentUser.role === 'super_admin' ? 'Super Admin' : currentUser.role}</p>
{/* User Profile Mini - Now Clickable to Profile */}
<div className="p-4 border-t border-zinc-100 dark:border-dark-border">
<div className="flex items-center gap-3 p-2 rounded-lg bg-zinc-50 dark:bg-dark-bg/50 border border-zinc-100 dark:border-dark-border group">
<div
onClick={() => navigate('/profile')}
className="flex items-center gap-3 flex-1 min-w-0 cursor-pointer hover:opacity-80 transition-opacity"
>
<img
src={currentUser.avatar_url
? (currentUser.avatar_url.startsWith('http') ? currentUser.avatar_url : `${import.meta.env.PROD ? '' : 'http://localhost:3001'}${currentUser.avatar_url}`)
: `https://ui-avatars.com/api/?name=${encodeURIComponent(currentUser.name)}&background=random`}
alt={currentUser.name}
className="w-10 h-10 rounded-full object-cover border border-zinc-200 dark:border-dark-border"
/>
<div className="flex-1 min-w-0">
<p className="text-sm font-semibold text-zinc-900 dark:text-dark-text truncate">{currentUser.name}</p>
<p className="text-xs text-zinc-500 dark:text-dark-muted truncate capitalize">
{currentUser.role === 'super_admin' ? 'Super Admin' :
currentUser.role === 'admin' ? 'Administrador' :
currentUser.role === 'manager' ? 'Gerente' : 'Agente'}
</p>
</div>
</div>
<button
onClick={handleLogout}
className="text-slate-400 hover:text-red-500 transition-colors"
className="text-zinc-400 hover:text-red-500 transition-colors shrink-0"
title="Sair"
>
<LogOut size={18} />
@@ -141,30 +166,39 @@ export const Layout: React.FC<{ children: React.ReactNode }> = ({ children }) =>
{/* Main Content */}
<div className="flex-1 flex flex-col min-w-0">
{/* Header */}
<header className="h-20 bg-white border-b border-slate-200 px-4 sm:px-8 flex items-center justify-between z-10 sticky top-0">
<header className="h-20 bg-white dark:bg-dark-header border-b border-zinc-200 dark:border-dark-border px-4 sm:px-8 flex items-center justify-between z-10 sticky top-0 transition-colors">
<div className="flex items-center gap-4">
<button onClick={() => setIsMobileMenuOpen(true)} className="lg:hidden text-slate-500 hover:text-slate-900">
<button onClick={() => setIsMobileMenuOpen(true)} className="lg:hidden text-zinc-500 hover:text-zinc-900 dark:hover:text-white">
<Menu size={24} />
</button>
<h1 className="text-xl font-bold text-slate-800 hidden sm:block">{getPageTitle()}</h1>
<h1 className="text-xl font-bold text-zinc-800 dark:text-dark-text hidden sm:block">{getPageTitle()}</h1>
</div>
<div className="flex items-center gap-4 sm:gap-6">
{/* Dark Mode Toggle */}
<button
onClick={toggleDarkMode}
className="p-2.5 text-zinc-500 dark:text-dark-muted hover:bg-zinc-100 dark:hover:bg-dark-border rounded-xl transition-all"
title={isDark ? "Mudar para Modo Claro" : "Mudar para Modo Escuro"}
>
{isDark ? <Sun size={20} /> : <Moon size={20} />}
</button>
{/* Search Bar */}
<div className="hidden md:flex items-center bg-slate-100 rounded-full px-4 py-2 w-64 border border-transparent focus-within:bg-white focus-within:border-yellow-400 focus-within:ring-2 focus-within:ring-yellow-100 transition-all">
<Search size={18} className="text-slate-400" />
<div className="hidden md:flex items-center bg-zinc-100 dark:bg-dark-bg rounded-full px-4 py-2 w-64 border border-transparent focus-within:bg-white dark:focus-within:bg-dark-card focus-within:border-brand-yellow focus-within:ring-2 focus-within:ring-brand-yellow/20 dark:focus-within:ring-brand-yellow/10 transition-all">
<Search size={18} className="text-zinc-400 dark:text-dark-muted" />
<input
type="text"
placeholder="Buscar..."
className="bg-transparent border-none outline-none text-sm ml-2 w-full text-slate-700 placeholder-slate-400"
className="bg-transparent border-none outline-none text-sm ml-2 w-full text-zinc-700 dark:text-dark-text placeholder-zinc-400 dark:placeholder-dark-muted"
/>
</div>
{/* Notifications */}
<div className="relative">
<button className="p-2 text-slate-500 hover:bg-slate-100 rounded-full relative transition-colors">
<button className="p-2 text-zinc-500 dark:text-dark-muted hover:bg-zinc-100 dark:hover:bg-dark-border rounded-full relative transition-colors">
<Bell size={20} />
<span className="absolute top-1.5 right-2 w-2.5 h-2.5 bg-yellow-400 rounded-full border-2 border-white"></span>
<span className="absolute top-1.5 right-2 w-2.5 h-2.5 bg-brand-yellow rounded-full border-2 border-white dark:border-dark-header"></span>
</button>
</div>
</div>
@@ -179,10 +213,10 @@ export const Layout: React.FC<{ children: React.ReactNode }> = ({ children }) =>
{/* Overlay for mobile */}
{isMobileMenuOpen && (
<div
className="fixed inset-0 bg-slate-900/50 z-40 lg:hidden"
className="fixed inset-0 bg-zinc-950/50 z-40 lg:hidden"
onClick={() => setIsMobileMenuOpen(false)}
/>
)}
</div>
);
};
};

View File

@@ -14,29 +14,29 @@ interface ProductListsProps {
export const ProductLists: React.FC<ProductListsProps> = ({ requested, sold }) => {
const ListSection = ({ title, icon: Icon, data, color }: { title: string, icon: any, data: ProductStat[], color: string }) => (
<div className="bg-white p-6 rounded-2xl shadow-sm border border-slate-100 flex-1">
<div className="bg-white dark:bg-dark-card p-6 rounded-2xl shadow-sm border border-zinc-100 dark:border-dark-border flex-1 transition-colors">
<div className="flex items-center gap-2 mb-4">
<div className={`p-2 rounded-lg ${color === 'blue' ? 'bg-blue-100 text-blue-600' : 'bg-green-100 text-green-600'}`}>
<div className={`p-2 rounded-lg ${color === 'blue' ? 'bg-blue-100 dark:bg-blue-950/50 text-blue-600 dark:text-blue-400' : 'bg-green-100 dark:bg-green-950/50 text-green-600 dark:text-green-400'}`}>
<Icon size={18} />
</div>
<h3 className="font-bold text-slate-800">{title}</h3>
<h3 className="font-bold text-zinc-800 dark:text-dark-text">{title}</h3>
</div>
<ul className="space-y-4">
{data.map((item, idx) => (
<li key={idx} className="flex items-center justify-between group">
<div className="flex items-center gap-3">
<span className={`flex items-center justify-center w-6 h-6 rounded-full text-xs font-bold ${idx < 3 ? 'bg-slate-800 text-white' : 'bg-slate-100 text-slate-500'}`}>
<span className={`flex items-center justify-center w-6 h-6 rounded-full text-xs font-bold ${idx < 3 ? 'bg-zinc-800 dark:bg-brand-yellow text-white dark:text-zinc-950' : 'bg-zinc-100 dark:bg-dark-bg text-zinc-500 dark:text-dark-muted'}`}>
{idx + 1}
</span>
<span className="text-sm font-medium text-slate-700 group-hover:text-slate-900">{item.name}</span>
<span className="text-sm font-medium text-zinc-700 dark:text-zinc-300 group-hover:text-zinc-900 dark:group-hover:text-dark-text">{item.name}</span>
</div>
<div className="text-right">
<span className="text-sm font-bold text-slate-900 block">{item.count}</span>
<span className="text-[10px] text-slate-400">{item.percentage}%</span>
<span className="text-sm font-bold text-zinc-900 dark:text-zinc-100 block">{item.count}</span>
<span className="text-[10px] text-zinc-400 dark:text-dark-muted">{item.percentage}%</span>
</div>
</li>
))}
{data.length === 0 && <li className="text-sm text-slate-400 italic">Nenhum dado disponível.</li>}
{data.length === 0 && <li className="text-sm text-zinc-400 dark:text-dark-muted italic">Nenhum dado disponível.</li>}
</ul>
</div>
);

View File

@@ -15,14 +15,12 @@ interface SellersTableProps {
data: SellerStat[];
}
type SortKey = keyof SellerStat | 'name'; // 'name' is inside user object
export const SellersTable: React.FC<SellersTableProps> = ({ data }) => {
const navigate = useNavigate();
const [sortKey, setSortKey] = useState<SortKey>('conversionRate');
const [sortKey, setSortKey] = useState<keyof SellerStat>('total');
const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('desc');
const handleSort = (key: SortKey) => {
const handleSort = (key: keyof SellerStat) => {
if (sortKey === key) {
setSortDirection(prev => prev === 'asc' ? 'desc' : 'asc');
} else {
@@ -33,111 +31,123 @@ export const SellersTable: React.FC<SellersTableProps> = ({ data }) => {
const sortedData = useMemo(() => {
return [...data].sort((a, b) => {
let aValue: any = a[sortKey as keyof SellerStat];
let bValue: any = b[sortKey as keyof SellerStat];
if (sortKey === 'name') {
aValue = a.user.name;
bValue = b.user.name;
} else {
// Convert strings like "85.5" to numbers for sorting
aValue = parseFloat(aValue as string);
bValue = parseFloat(bValue as string);
const aVal = a[sortKey];
const bVal = b[sortKey];
if (typeof aVal === 'string' && typeof bVal === 'string') {
return sortDirection === 'asc'
? aVal.localeCompare(bVal)
: bVal.localeCompare(aVal);
}
if (typeof aVal === 'number' && typeof bVal === 'number') {
return sortDirection === 'asc' ? aVal - bVal : bVal - aVal;
}
// Handle user object (sort by name)
if (sortKey === 'user') {
return sortDirection === 'asc'
? a.user.name.localeCompare(b.user.name)
: b.user.name.localeCompare(a.user.name);
}
if (aValue < bValue) return sortDirection === 'asc' ? -1 : 1;
if (aValue > bValue) return sortDirection === 'asc' ? 1 : -1;
return 0;
});
}, [data, sortKey, sortDirection]);
const SortIcon = ({ column }: { column: SortKey }) => {
if (sortKey !== column) return <ChevronsUpDown size={14} className="text-slate-300" />;
return sortDirection === 'asc' ? <ChevronUp size={14} className="text-blue-500" /> : <ChevronDown size={14} className="text-blue-500" />;
const SortIcon = ({ column }: { column: string }) => {
if (sortKey !== column) return <ChevronsUpDown size={14} className="text-zinc-300 dark:text-dark-muted" />;
return sortDirection === 'asc' ? <ChevronUp size={14} className="text-brand-yellow" /> : <ChevronDown size={14} className="text-brand-yellow" />;
};
return (
<div className="bg-white rounded-2xl shadow-sm border border-slate-100 overflow-hidden">
<div className="px-6 py-5 border-b border-slate-100 flex justify-between items-center">
<h3 className="font-bold text-slate-800">Ranking de Vendedores</h3>
<div className="bg-white dark:bg-dark-card rounded-2xl shadow-sm border border-zinc-100 dark:border-dark-border overflow-hidden transition-colors">
<div className="px-6 py-5 border-b border-zinc-100 dark:border-dark-border flex justify-between items-center">
<h3 className="font-bold text-zinc-800 dark:text-dark-text">Ranking de Vendedores</h3>
</div>
<div className="overflow-x-auto">
<table className="w-full text-left border-collapse">
<thead>
<tr className="bg-slate-50/50 text-slate-500 text-xs uppercase tracking-wider">
<tr className="bg-zinc-50/50 dark:bg-dark-bg/50 text-zinc-500 dark:text-dark-muted text-xs uppercase tracking-wider">
<th
className="px-6 py-4 font-semibold cursor-pointer hover:bg-slate-50 select-none"
onClick={() => handleSort('name')}
className="px-6 py-4 font-semibold cursor-pointer hover:bg-zinc-50 dark:hover:bg-dark-border select-none"
onClick={() => handleSort('user')}
>
<div className="flex items-center gap-2">Usuário <SortIcon column="name" /></div>
<div className="flex items-center gap-2">Usuário <SortIcon column="user" /></div>
</th>
<th
className="px-6 py-4 font-semibold text-center cursor-pointer hover:bg-slate-50 select-none"
className="px-6 py-4 font-semibold text-center cursor-pointer hover:bg-zinc-50 dark:hover:bg-dark-border select-none"
onClick={() => handleSort('total')}
>
<div className="flex items-center justify-center gap-2">Atendimentos <SortIcon column="total" /></div>
</th>
<th
className="px-6 py-4 font-semibold text-center cursor-pointer hover:bg-slate-50 select-none"
className="px-6 py-4 font-semibold text-center cursor-pointer hover:bg-zinc-50 dark:hover:bg-dark-border select-none"
onClick={() => handleSort('avgScore')}
>
<div className="flex items-center justify-center gap-2">Nota Média <SortIcon column="avgScore" /></div>
</th>
<th
className="px-6 py-4 font-semibold text-center cursor-pointer hover:bg-slate-50 select-none"
className="px-6 py-4 font-semibold text-center cursor-pointer hover:bg-zinc-50 dark:hover:bg-dark-border select-none"
onClick={() => handleSort('responseTime')}
>
<div className="flex items-center justify-center gap-2">Tempo Resp. <SortIcon column="responseTime" /></div>
</th>
<th
className="px-6 py-4 font-semibold text-center cursor-pointer hover:bg-slate-50 select-none"
className="px-6 py-4 font-semibold text-center cursor-pointer hover:bg-zinc-50 dark:hover:bg-dark-border select-none"
onClick={() => handleSort('conversionRate')}
>
<div className="flex items-center justify-center gap-2">Conversão <SortIcon column="conversionRate" /></div>
</th>
</tr>
</thead>
<tbody className="divide-y divide-slate-100">
<tbody className="divide-y divide-zinc-100 dark:divide-dark-border">
{sortedData.map((item, idx) => (
<tr
key={item.user.id}
className="hover:bg-blue-50/30 transition-colors cursor-pointer group"
className="hover:bg-yellow-50/10 dark:hover:bg-yellow-400/5 transition-colors cursor-pointer group"
onClick={() => navigate(`/users/${item.user.id}`)}
>
<td className="px-6 py-4">
<div className="flex items-center gap-3">
<span className="text-xs text-slate-400 font-mono w-4">#{idx + 1}</span>
<img src={item.user.avatar_url} alt="" className="w-9 h-9 rounded-full object-cover border border-slate-200" />
<span className="text-xs text-zinc-400 dark:text-dark-muted font-mono w-4">#{idx + 1}</span>
<img
src={item.user.avatar_url
? (item.user.avatar_url.startsWith('http') ? item.user.avatar_url : `${import.meta.env.PROD ? '' : 'http://localhost:3001'}${item.user.avatar_url}`)
: `https://ui-avatars.com/api/?name=${encodeURIComponent(item.user.name)}&background=random`}
alt=""
className="w-9 h-9 rounded-full object-cover border border-zinc-200 dark:border-dark-border"
/>
<div>
<div className="font-semibold text-slate-900 group-hover:text-blue-600 transition-colors">{item.user.name}</div>
<div className="text-xs text-slate-500">{item.user.email}</div>
<div className="font-semibold text-zinc-900 dark:text-dark-text group-hover:text-yellow-600 dark:group-hover:text-brand-yellow transition-colors">{item.user.name}</div>
<div className="text-xs text-zinc-500 dark:text-dark-muted">{item.user.email}</div>
</div>
</div>
</td>
<td className="px-6 py-4 text-center text-slate-600 font-medium">
<td className="px-6 py-4 text-center text-zinc-600 dark:text-dark-text font-medium">
{item.total}
</td>
<td className="px-6 py-4 text-center">
<span className={`inline-flex px-2 py-1 rounded-full text-xs font-bold ${parseFloat(item.avgScore) >= 80 ? 'bg-green-100 text-green-700' : parseFloat(item.avgScore) >= 60 ? 'bg-yellow-100 text-yellow-700' : 'bg-red-100 text-red-700'}`}>
<span className={`inline-flex px-2 py-1 rounded-full text-xs font-bold ${parseFloat(item.avgScore) >= 80 ? 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400' : parseFloat(item.avgScore) >= 60 ? 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400' : 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400'}`}>
{item.avgScore}
</span>
</td>
<td className="px-6 py-4 text-center text-slate-600 text-sm">
<td className="px-6 py-4 text-center text-zinc-600 dark:text-dark-text text-sm">
{item.responseTime} min
</td>
<td className="px-6 py-4 text-center">
<div className="flex items-center justify-center gap-2">
<div className="w-16 bg-slate-100 rounded-full h-1.5 overflow-hidden">
<div className="bg-blue-500 h-1.5 rounded-full" style={{ width: `${item.conversionRate}%` }}></div>
<div className="w-16 bg-zinc-100 dark:bg-dark-bg rounded-full h-1.5 overflow-hidden border dark:border-dark-border">
<div className="bg-brand-yellow h-1.5 rounded-full" style={{ width: `${item.conversionRate}%` }}></div>
</div>
<span className="text-xs font-semibold text-slate-700">{item.conversionRate}%</span>
<span className="text-xs font-semibold text-zinc-700 dark:text-dark-text">{item.conversionRate}%</span>
</div>
</td>
</tr>
))}
{sortedData.length === 0 && (
<tr>
<td colSpan={5} className="px-6 py-8 text-center text-slate-400 italic">Nenhum dado disponível para o período selecionado.</td>
<td colSpan={5} className="px-6 py-8 text-center text-zinc-400 dark:text-dark-muted italic">Nenhum dado disponível para o período selecionado.</td>
</tr>
)}
</tbody>

View File

@@ -111,7 +111,7 @@ export const USERS: User[] = [
];
const generateMockAttendances = (count: number): Attendance[] => {
const origins = ['WhatsApp', 'Instagram', 'Website', 'LinkedIn', 'Referral'] as const;
const origins = ['WhatsApp', 'Instagram', 'Website', 'LinkedIn', 'Indicação'] as const;
const stages = Object.values(FunnelStage);
const products = ['Plano Premium', 'Plano Básico', 'Suíte Enterprise', 'Consultoria'];
@@ -163,9 +163,36 @@ export const MOCK_ATTENDANCES = generateMockAttendances(300);
// Visual Constants
export const COLORS = {
primary: '#facc15', // Yellow-400
secondary: '#1e293b', // Slate-800
success: '#22c55e',
warning: '#f59e0b',
danger: '#ef4444',
charts: ['#3b82f6', '#10b981', '#6366f1', '#f59e0b', '#ec4899', '#8b5cf6'],
secondary: '#18181b', // Zinc-900
success: '#10b981', // Emerald-500
warning: '#f59e0b', // Amber-500
danger: '#ef4444', // Red-500
// Prettier, modern SaaS palette for general charts
charts: [
'#818cf8', // Soft Indigo
'#4ade80', // Soft Emerald
'#fb923c', // Soft Orange
'#22d3ee', // Soft Cyan
'#f472b6', // Soft Pink
'#a78bfa' // Soft Violet
],
// Brand-specific colors for Lead Origins
origins: {
'WhatsApp': '#25D366',
'Instagram': '#E4405F',
'LinkedIn': '#0077B5',
'Website': '#f87171', // Coral Red (Distinct from LinkedIn blue)
'Indicação': '#f59e0b'
},
// Semantic palette for Funnel Stages
funnel: {
'Sem atendimento': '#64748b', // Slate-500
'Identificação': '#818cf8', // Indigo-400
'Negociação': '#fb923c', // Orange-400
'Ganhos': '#10b981', // Emerald-500
'Perdidos': '#f87171' // Red-400
}
};

View File

@@ -18,7 +18,9 @@ services:
- MAIL_FROM=${MAIL_FROM}
volumes:
- ./dist:/app/dist # Map local build to container
- ./backend:/app/backend # Map backend source to container
- ./backend/index.js:/app/index.js
- ./backend/db.js:/app/db.js
command: ["node", "index.js"]
depends_on:
- db

View File

@@ -5,11 +5,43 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Fasto | Management</title>
<script src="https://cdn.tailwindcss.com"></script>
<script>
tailwind.config = {
darkMode: 'class',
theme: {
extend: {
colors: {
brand: {
yellow: '#facc15'
},
dark: {
bg: '#0a0a0a', // Deep Charcoal (Not pure black)
card: '#141414', // Elevated surface
header: '#141414',
sidebar: '#141414',
border: '#222222', // Subtle border
input: '#1a1a1a',
text: '#ededed', // High contrast off-white
muted: '#888888' // Muted gray
}
}
}
}
}
// Check for theme in cookie or system preference
const isDark = document.cookie.split('; ').find(row => row.startsWith('dark_mode='))?.split('=')[1] === '1';
if (isDark) {
document.documentElement.classList.add('dark');
}
</script>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<style>
body { font-family: 'Inter', sans-serif; background-color: #f8fafc; }
body { font-family: 'Inter', sans-serif; transition: background-color 0.3s ease; }
.dark body { background-color: #0a0a0a; color: #ededed; }
::-webkit-scrollbar { width: 6px; height: 6px; }
::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 3px; }
::-webkit-scrollbar-thumb { background: #d4d4d8; border-radius: 3px; }
.dark ::-webkit-scrollbar-thumb { background: #333333; }
</style>
</head>
<body>

131
package-lock.json generated
View File

@@ -13,18 +13,21 @@
"express": "^4.18.2",
"jsonwebtoken": "^9.0.3",
"lucide-react": "^0.574.0",
"multer": "^2.1.0",
"mysql2": "^3.9.1",
"nodemailer": "^8.0.1",
"react": "^19.2.4",
"react-dom": "^19.2.4",
"react-router-dom": "^7.13.0",
"recharts": "^3.7.0"
"recharts": "^3.7.0",
"uuid": "^13.0.0"
},
"devDependencies": {
"@types/bcryptjs": "^2.4.6",
"@types/jsonwebtoken": "^9.0.10",
"@types/node": "^22.14.0",
"@vitejs/plugin-react": "^5.0.0",
"dotenv": "^17.3.1",
"typescript": "~5.8.2",
"vite": "^6.2.0"
}
@@ -1397,6 +1400,12 @@
"node": ">= 0.6"
}
},
"node_modules/append-field": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/append-field/-/append-field-1.0.0.tgz",
"integrity": "sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw==",
"license": "MIT"
},
"node_modules/array-flatten": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",
@@ -1513,6 +1522,23 @@
"integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==",
"license": "BSD-3-Clause"
},
"node_modules/buffer-from": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
"integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==",
"license": "MIT"
},
"node_modules/busboy": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz",
"integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==",
"dependencies": {
"streamsearch": "^1.1.0"
},
"engines": {
"node": ">=10.16.0"
}
},
"node_modules/bytes": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
@@ -1581,6 +1607,21 @@
"node": ">=6"
}
},
"node_modules/concat-stream": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-2.0.0.tgz",
"integrity": "sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A==",
"engines": [
"node >= 6.0"
],
"license": "MIT",
"dependencies": {
"buffer-from": "^1.0.0",
"inherits": "^2.0.3",
"readable-stream": "^3.0.2",
"typedarray": "^0.0.6"
}
},
"node_modules/content-disposition": {
"version": "0.5.4",
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz",
@@ -1814,6 +1855,19 @@
"npm": "1.2.8000 || >= 1.4.16"
}
},
"node_modules/dotenv": {
"version": "17.3.1",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.3.1.tgz",
"integrity": "sha512-IO8C/dzEb6O3F9/twg6ZLXz164a2fhTnEWb95H23Dm4OuN+92NmEAlTrupP9VW6Jm3sO26tQlqyvyi4CsnY9GA==",
"dev": true,
"license": "BSD-2-Clause",
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://dotenvx.com"
}
},
"node_modules/dunder-proto": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
@@ -2535,6 +2589,25 @@
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"license": "MIT"
},
"node_modules/multer": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/multer/-/multer-2.1.0.tgz",
"integrity": "sha512-TBm6j41rxNohqawsxlsWsNNh/VdV4QFXcBvRcPhXaA05EZ79z0qJ2bQFpync6JBoHTeNY5Q1JpG7AlTjdlfAEA==",
"license": "MIT",
"dependencies": {
"append-field": "^1.0.0",
"busboy": "^1.6.0",
"concat-stream": "^2.0.0",
"type-is": "^1.6.18"
},
"engines": {
"node": ">= 10.16.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/mysql2": {
"version": "3.18.1",
"resolved": "https://registry.npmjs.org/mysql2/-/mysql2-3.18.1.tgz",
@@ -2890,6 +2963,20 @@
"url": "https://opencollective.com/express"
}
},
"node_modules/readable-stream": {
"version": "3.6.2",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
"integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
"license": "MIT",
"dependencies": {
"inherits": "^2.0.3",
"string_decoder": "^1.1.1",
"util-deprecate": "^1.0.1"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/recharts": {
"version": "3.7.0",
"resolved": "https://registry.npmjs.org/recharts/-/recharts-3.7.0.tgz",
@@ -3200,6 +3287,23 @@
"node": ">= 0.8"
}
},
"node_modules/streamsearch": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz",
"integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==",
"engines": {
"node": ">=10.0.0"
}
},
"node_modules/string_decoder": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
"integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==",
"license": "MIT",
"dependencies": {
"safe-buffer": "~5.2.0"
}
},
"node_modules/tiny-invariant": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/tiny-invariant/-/tiny-invariant-1.3.3.tgz",
@@ -3245,6 +3349,12 @@
"node": ">= 0.6"
}
},
"node_modules/typedarray": {
"version": "0.0.6",
"resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz",
"integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==",
"license": "MIT"
},
"node_modules/typescript": {
"version": "5.8.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.8.3.tgz",
@@ -3314,6 +3424,12 @@
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
},
"node_modules/util-deprecate": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
"integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
"license": "MIT"
},
"node_modules/utils-merge": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
@@ -3323,6 +3439,19 @@
"node": ">= 0.4.0"
}
},
"node_modules/uuid": {
"version": "13.0.0",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-13.0.0.tgz",
"integrity": "sha512-XQegIaBTVUjSHliKqcnFqYypAd4S+WCYt5NIeRs6w/UAry7z8Y9j5ZwRRL4kzq9U3sD6v+85er9FvkEaBpji2w==",
"funding": [
"https://github.com/sponsors/broofa",
"https://github.com/sponsors/ctavan"
],
"license": "MIT",
"bin": {
"uuid": "dist-node/bin/uuid"
}
},
"node_modules/vary": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",

View File

@@ -14,18 +14,21 @@
"express": "^4.18.2",
"jsonwebtoken": "^9.0.3",
"lucide-react": "^0.574.0",
"multer": "^2.1.0",
"mysql2": "^3.9.1",
"nodemailer": "^8.0.1",
"react": "^19.2.4",
"react-dom": "^19.2.4",
"react-router-dom": "^7.13.0",
"recharts": "^3.7.0"
"recharts": "^3.7.0",
"uuid": "^13.0.0"
},
"devDependencies": {
"@types/bcryptjs": "^2.4.6",
"@types/jsonwebtoken": "^9.0.10",
"@types/node": "^22.14.0",
"@vitejs/plugin-react": "^5.0.0",
"dotenv": "^17.3.1",
"typescript": "~5.8.2",
"vite": "^6.2.0"
}

View File

@@ -31,14 +31,14 @@ export const AttendanceDetail: React.FC = () => {
loadData();
}, [id]);
if (loading) return <div className="p-12 text-center text-slate-400">Carregando detalhes...</div>;
if (!data) return <div className="p-12 text-center text-slate-500">Registro de atendimento não encontrado</div>;
if (loading) return <div className="p-12 text-center text-zinc-400 dark:text-dark-muted transition-colors">Carregando detalhes...</div>;
if (!data) return <div className="p-12 text-center text-zinc-500 dark:text-dark-muted transition-colors">Registro de atendimento não encontrado</div>;
const getStageColor = (stage: FunnelStage) => {
switch (stage) {
case FunnelStage.WON: return 'text-green-700 bg-green-50 border-green-200';
case FunnelStage.LOST: return 'text-red-700 bg-red-50 border-red-200';
default: return 'text-blue-700 bg-blue-50 border-blue-200';
case FunnelStage.WON: return 'text-green-700 bg-green-50 border-green-200 dark:text-green-400 dark:bg-green-900/30 dark:border-green-800';
case FunnelStage.LOST: return 'text-red-700 bg-red-50 border-red-200 dark:text-red-400 dark:bg-red-900/30 dark:border-red-800';
default: return 'text-blue-700 bg-blue-50 border-blue-200 dark:text-blue-400 dark:bg-blue-900/30 dark:border-blue-800';
}
};
@@ -48,51 +48,59 @@ export const AttendanceDetail: React.FC = () => {
return 'text-red-500';
};
const backendUrl = import.meta.env.PROD ? '' : 'http://localhost:3001';
return (
<div className="max-w-5xl mx-auto space-y-6">
<div className="max-w-5xl mx-auto space-y-6 transition-colors duration-300">
{/* Top Nav & Context */}
<div className="flex items-center justify-between">
<Link
to={`/users/${data.user_id}`}
className="flex items-center gap-2 text-slate-500 hover:text-slate-900 transition-colors text-sm font-medium"
className="flex items-center gap-2 text-zinc-500 dark:text-dark-muted hover:text-zinc-900 dark:hover:text-dark-text transition-colors text-sm font-medium"
>
<ArrowLeft size={16} /> Voltar para Histórico
</Link>
<div className="text-sm text-slate-400 font-mono">ID: {data.id}</div>
<div className="text-sm text-zinc-400 dark:text-dark-muted font-mono">ID: {data.id}</div>
</div>
{/* Hero Header */}
<div className="bg-white rounded-2xl border border-slate-200 shadow-sm p-6 md:p-8">
<div className="bg-white dark:bg-dark-card rounded-2xl border border-zinc-200 dark:border-dark-border shadow-sm p-6 md:p-8 transition-colors">
<div className="flex flex-col md:flex-row justify-between gap-6">
<div className="space-y-4">
<div className="flex flex-wrap items-center gap-3">
<span className={`px-3 py-1 rounded-full text-xs font-bold uppercase tracking-wide border ${getStageColor(data.funnel_stage)}`}>
{data.funnel_stage}
</span>
<span className="flex items-center gap-1.5 text-slate-500 text-sm">
<span className="flex items-center gap-1.5 text-zinc-500 dark:text-dark-muted text-sm">
<Calendar size={14} /> {new Date(data.created_at).toLocaleString('pt-BR')}
</span>
<span className="flex items-center gap-1.5 text-slate-500 text-sm">
<span className="flex items-center gap-1.5 text-zinc-500 dark:text-dark-muted text-sm">
<MessageSquare size={14} /> {data.origin}
</span>
</div>
<h1 className="text-2xl md:text-3xl font-bold text-slate-900 leading-tight">
<h1 className="text-2xl md:text-3xl font-bold text-zinc-900 dark:text-dark-text leading-tight">
{data.summary}
</h1>
{agent && (
<div className="flex items-center gap-3 pt-2">
<img src={agent.avatar_url} alt="" className="w-8 h-8 rounded-full border border-slate-200" />
<span className="text-sm font-medium text-slate-700">Agente: <span className="text-slate-900">{agent.name}</span></span>
<img
src={agent.avatar_url
? (agent.avatar_url.startsWith('http') ? agent.avatar_url : `${backendUrl}${agent.avatar_url}`)
: `https://ui-avatars.com/api/?name=${encodeURIComponent(agent.name)}&background=random`}
alt=""
className="w-8 h-8 rounded-full border border-zinc-200 dark:border-dark-border object-cover"
/>
<span className="text-sm font-medium text-zinc-700 dark:text-zinc-300">Agente: <span className="text-zinc-900 dark:text-zinc-100">{agent.name}</span></span>
</div>
)}
</div>
<div className="flex flex-col items-center justify-center min-w-[140px] p-6 bg-slate-50 rounded-xl border border-slate-100">
<span className="text-xs font-bold text-slate-400 uppercase tracking-wider mb-1">Nota de Qualidade</span>
<div className="flex flex-col items-center justify-center min-w-[140px] p-6 bg-zinc-50 dark:bg-dark-bg/50 rounded-xl border border-zinc-100 dark:border-dark-border">
<span className="text-xs font-bold text-zinc-400 dark:text-dark-muted uppercase tracking-wider mb-1">Nota de Qualidade</span>
<div className={`text-5xl font-black ${getScoreColor(data.score)}`}>
{data.score}
</div>
<span className="text-xs font-medium text-slate-400 mt-1">de 100</span>
<span className="text-xs font-medium text-zinc-400 dark:text-dark-muted mt-1">de 100</span>
</div>
</div>
</div>
@@ -104,13 +112,13 @@ export const AttendanceDetail: React.FC = () => {
<div className="lg:col-span-2 space-y-6">
{/* Summary / Transcript Stub */}
<div className="bg-white rounded-xl border border-slate-200 shadow-sm p-6">
<h3 className="text-base font-bold text-slate-900 mb-4 flex items-center gap-2">
<MessageSquare size={18} className="text-slate-400" />
<div className="bg-white dark:bg-dark-card rounded-xl border border-zinc-200 dark:border-dark-border shadow-sm p-6">
<h3 className="text-base font-bold text-zinc-900 dark:text-dark-text mb-4 flex items-center gap-2">
<MessageSquare size={18} className="text-zinc-400 dark:text-dark-muted" />
Resumo da Interação
</h3>
<p className="text-slate-600 leading-relaxed text-sm">
{data.summary} O cliente perguntou sobre detalhes específicos relacionados ao <span className="font-medium text-slate-800">{data.product_requested}</span>.
<p className="text-zinc-600 dark:text-zinc-300 leading-relaxed text-sm">
{data.summary} O cliente perguntou sobre detalhes específicos relacionados ao <span className="font-medium text-zinc-800 dark:text-zinc-100">{data.product_requested}</span>.
As discussões envolveram níveis de preços, prazos de implementação e potenciais descontos por volume.
A interação foi concluída com {data.converted ? 'uma venda realizada' : 'o cliente pedindo mais tempo para decidir'}.
</p>
@@ -119,45 +127,45 @@ export const AttendanceDetail: React.FC = () => {
{/* Feedback Section */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
{/* Points of Attention */}
<div className="bg-white rounded-xl border border-red-100 shadow-sm overflow-hidden">
<div className="px-5 py-3 bg-red-50/50 border-b border-red-100 flex items-center gap-2">
<AlertCircle size={18} className="text-red-500" />
<h3 className="font-bold text-red-900 text-sm">Pontos de Atenção</h3>
<div className="bg-white dark:bg-dark-card rounded-xl border border-red-100 dark:border-red-900/20 shadow-sm overflow-hidden">
<div className="px-5 py-3 bg-red-50/50 dark:bg-red-900/20 border-b border-red-100 dark:border-red-900/30 flex items-center gap-2">
<AlertCircle size={18} className="text-red-500 dark:text-red-400" />
<h3 className="font-bold text-red-900 dark:text-red-300 text-sm">Pontos de Atenção</h3>
</div>
<div className="p-5">
{data.attention_points && data.attention_points.length > 0 ? (
<ul className="space-y-3">
{data.attention_points.map((pt, idx) => (
<li key={idx} className="flex gap-3 text-sm text-slate-700">
<li key={idx} className="flex gap-3 text-sm text-zinc-700 dark:text-zinc-300">
<span className="mt-1.5 w-1.5 h-1.5 rounded-full bg-red-400 shrink-0" />
{pt}
</li>
))}
</ul>
) : (
<p className="text-sm text-slate-400 italic">Nenhum problema detectado.</p>
<p className="text-sm text-zinc-400 dark:text-dark-muted italic">Nenhum problema detectado.</p>
)}
</div>
</div>
{/* Points of Improvement */}
<div className="bg-white rounded-xl border border-blue-100 shadow-sm overflow-hidden">
<div className="px-5 py-3 bg-blue-50/50 border-b border-blue-100 flex items-center gap-2">
<CheckCircle2 size={18} className="text-blue-500" />
<h3 className="font-bold text-blue-900 text-sm">Dicas de Melhoria</h3>
<div className="bg-white dark:bg-dark-card rounded-xl border border-blue-100 dark:border-blue-900/20 shadow-sm overflow-hidden">
<div className="px-5 py-3 bg-blue-50/50 dark:bg-blue-900/20 border-b border-blue-100 dark:border-blue-900/30 flex items-center gap-2">
<CheckCircle2 size={18} className="text-blue-500 dark:text-blue-400" />
<h3 className="font-bold text-blue-900 dark:text-blue-300 text-sm">Dicas de Melhoria</h3>
</div>
<div className="p-5">
{data.improvement_points && data.improvement_points.length > 0 ? (
<ul className="space-y-3">
{data.improvement_points.map((pt, idx) => (
<li key={idx} className="flex gap-3 text-sm text-slate-700">
<span className="mt-1.5 w-1.5 h-1.5 rounded-full bg-blue-400 shrink-0" />
<li key={idx} className="flex gap-3 text-sm text-zinc-700 dark:text-zinc-300">
<span className="mt-1.5 w-1.5 h-1.5 rounded-full bg-red-400 shrink-0" />
{pt}
</li>
))}
</ul>
) : (
<p className="text-sm text-slate-400 italic">Continue o bom trabalho!</p>
<p className="text-sm text-zinc-400 dark:text-dark-muted italic">Continue o bom trabalho!</p>
)}
</div>
</div>
@@ -166,49 +174,49 @@ export const AttendanceDetail: React.FC = () => {
{/* Right Column: Metadata & Metrics */}
<div className="space-y-6">
<div className="bg-white rounded-xl border border-slate-200 shadow-sm p-5">
<h3 className="text-xs font-bold text-slate-400 uppercase tracking-wider mb-4">Métricas de Performance</h3>
<div className="bg-white dark:bg-dark-card rounded-xl border border-zinc-200 dark:border-dark-border shadow-sm p-5 transition-colors">
<h3 className="text-xs font-bold text-zinc-400 dark:text-dark-muted uppercase tracking-wider mb-4">Métricas de Performance</h3>
<div className="space-y-4">
<div className="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
<div className="flex justify-between items-center p-3 bg-zinc-50 dark:bg-dark-bg/50 rounded-lg">
<div className="flex items-center gap-3">
<div className="p-2 bg-white rounded-md border border-slate-100 text-blue-500"><Clock size={16} /></div>
<span className="text-sm font-medium text-slate-600">Primeira Resposta</span>
<div className="p-2 bg-white dark:bg-dark-card rounded-md border border-zinc-100 dark:border-dark-border text-blue-500 dark:text-blue-400"><Clock size={16} /></div>
<span className="text-sm font-medium text-zinc-600 dark:text-zinc-400">Primeira Resposta</span>
</div>
<span className="text-sm font-bold text-slate-900">{data.first_response_time_min} min</span>
<span className="text-sm font-bold text-zinc-900 dark:text-zinc-100">{data.first_response_time_min} min</span>
</div>
<div className="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
<div className="flex justify-between items-center p-3 bg-zinc-50 dark:bg-dark-bg/50 rounded-lg">
<div className="flex items-center gap-3">
<div className="p-2 bg-white rounded-md border border-slate-100 text-purple-500"><TrendingUp size={16} /></div>
<span className="text-sm font-medium text-slate-600">Tempo Atendimento</span>
<div className="p-2 bg-white dark:bg-dark-card rounded-md border border-zinc-100 dark:border-dark-border text-purple-500 dark:text-purple-400"><TrendingUp size={16} /></div>
<span className="text-sm font-medium text-zinc-600 dark:text-zinc-400">Tempo Atendimento</span>
</div>
<span className="text-sm font-bold text-slate-900">{data.handling_time_min} min</span>
<span className="text-sm font-bold text-zinc-900 dark:text-zinc-100">{data.handling_time_min} min</span>
</div>
</div>
</div>
<div className="bg-white rounded-xl border border-slate-200 shadow-sm p-5">
<h3 className="text-xs font-bold text-slate-400 uppercase tracking-wider mb-4">Contexto de Vendas</h3>
<div className="bg-white dark:bg-dark-card rounded-xl border border-zinc-200 dark:border-dark-border shadow-sm p-5 transition-colors">
<h3 className="text-xs font-bold text-zinc-400 dark:text-dark-muted uppercase tracking-wider mb-4">Contexto de Vendas</h3>
<div className="space-y-4">
<div className="space-y-1">
<span className="text-xs text-slate-500 font-medium">Produto Solicitado</span>
<div className="flex items-center gap-2 font-semibold text-slate-800">
<ShoppingBag size={16} className="text-slate-400" /> {data.product_requested}
<span className="text-xs text-zinc-500 dark:text-dark-muted font-medium">Produto Solicitado</span>
<div className="flex items-center gap-2 font-semibold text-zinc-800 dark:text-zinc-100">
<ShoppingBag size={16} className="text-zinc-400 dark:text-dark-muted" /> {data.product_requested}
</div>
</div>
<div className="h-px bg-slate-100 my-2" />
<div className="h-px bg-zinc-100 dark:bg-dark-border my-2" />
<div className="space-y-1">
<span className="text-xs text-slate-500 font-medium">Desfecho</span>
<span className="text-xs text-zinc-500 dark:text-dark-muted font-medium">Desfecho</span>
{data.converted ? (
<div className="flex items-center gap-2 text-green-600 font-bold bg-green-50 px-3 py-2 rounded-lg border border-green-100">
<div className="flex items-center gap-2 text-green-600 dark:text-green-400 font-bold bg-green-50 dark:bg-green-900/20 px-3 py-2 rounded-lg border border-green-100 dark:border-green-900/30">
<Award size={18} /> Venda Fechada
{data.product_sold && <span className="text-green-800 text-xs font-normal ml-auto">{data.product_sold}</span>}
{data.product_sold && <span className="text-green-800 dark:text-green-200 text-xs font-normal ml-auto">{data.product_sold}</span>}
</div>
) : (
<div className="flex items-center gap-2 text-slate-500 font-medium bg-slate-50 px-3 py-2 rounded-lg border border-slate-100">
<div className="w-2 h-2 rounded-full bg-slate-400" /> Não Convertido
<div className="flex items-center gap-2 text-zinc-500 dark:text-dark-muted font-medium bg-zinc-50 dark:bg-dark-bg/50 px-3 py-2 rounded-lg border border-zinc-100 dark:border-dark-border">
<div className="w-2 h-2 rounded-full bg-zinc-400 dark:bg-zinc-600" /> Não Convertido
</div>
)}
</div>
@@ -219,4 +227,4 @@ export const AttendanceDetail: React.FC = () => {
</div>
</div>
);
};
};

View File

@@ -5,7 +5,7 @@ import {
import {
Users, Clock, Phone, TrendingUp, Filter
} from 'lucide-react';
import { getAttendances, getUsers, getTeams } from '../services/dataService';
import { getAttendances, getUsers, getTeams, getUserById } from '../services/dataService';
import { COLORS } from '../constants';
import { Attendance, DashboardFilter, FunnelStage, User } from '../types';
import { KPICard } from '../components/KPICard';
@@ -27,6 +27,7 @@ export const Dashboard: React.FC = () => {
const [data, setData] = useState<Attendance[]>([]);
const [users, setUsers] = useState<User[]>([]);
const [teams, setTeams] = useState<any[]>([]);
const [currentUser, setCurrentUser] = useState<User | null>(null);
const [filters, setFilters] = useState<DashboardFilter>({
dateRange: {
@@ -35,6 +36,8 @@ export const Dashboard: React.FC = () => {
},
userId: 'all',
teamId: 'all',
funnelStage: 'all',
origin: 'all',
});
useEffect(() => {
@@ -42,18 +45,21 @@ export const Dashboard: React.FC = () => {
setLoading(true);
try {
const tenantId = localStorage.getItem('ctms_tenant_id');
const storedUserId = localStorage.getItem('ctms_user_id');
if (!tenantId) return;
// Fetch users, attendances and teams in parallel
const [fetchedUsers, fetchedData, fetchedTeams] = await Promise.all([
// Fetch users, attendances, teams and current user in parallel
const [fetchedUsers, fetchedData, fetchedTeams, me] = await Promise.all([
getUsers(tenantId),
getAttendances(tenantId, filters),
getTeams(tenantId)
getTeams(tenantId),
storedUserId ? getUserById(storedUserId) : null
]);
setUsers(fetchedUsers);
setData(fetchedData);
setTeams(fetchedTeams);
if (me) setCurrentUser(me);
} catch (error) {
console.error("Error loading dashboard data:", error);
} finally {
@@ -164,41 +170,73 @@ export const Dashboard: React.FC = () => {
};
if (loading && data.length === 0) {
return <div className="flex h-full items-center justify-center text-slate-400 p-12">Carregando Dashboard...</div>;
return <div className="flex h-full items-center justify-center text-zinc-400 dark:text-dark-muted p-12">Carregando Dashboard...</div>;
}
const isAdmin = currentUser?.role === 'admin' || currentUser?.role === 'super_admin' || currentUser?.role === 'manager';
return (
<div className="space-y-6 pb-8">
<div className="space-y-6 pb-8 transition-colors duration-300">
{/* Filters Bar */}
<div className="bg-white p-4 rounded-xl shadow-sm border border-slate-100 flex flex-col md:flex-row gap-4 items-center justify-between">
<div className="flex items-center gap-2 text-slate-500 font-medium">
<Filter size={18} />
<span className="hidden md:inline">Filtros:</span>
</div>
<div className="flex flex-wrap items-center gap-3 w-full md:w-auto">
<DateRangePicker
dateRange={filters.dateRange}
onChange={(range) => handleFilterChange('dateRange', range)}
/>
<div className="bg-white dark:bg-dark-card p-4 rounded-xl shadow-sm border border-zinc-100 dark:border-dark-border flex flex-col gap-4">
<div className="flex flex-col md:flex-row gap-4 items-center justify-between">
<div className="flex items-center gap-2 text-zinc-500 dark:text-dark-muted font-medium">
<Filter size={18} />
<span>Filtros:</span>
</div>
<div className="flex flex-wrap items-center gap-3 w-full md:w-auto">
<DateRangePicker
dateRange={filters.dateRange}
onChange={(range) => handleFilterChange('dateRange', range)}
/>
<select
className="bg-slate-50 border border-slate-200 px-3 py-2 rounded-lg text-sm text-slate-700 outline-none focus:ring-2 focus:ring-blue-100 cursor-pointer hover:border-slate-300"
value={filters.userId}
onChange={(e) => handleFilterChange('userId', e.target.value)}
>
<option value="all">Todos Usuários</option>
{users.map(u => <option key={u.id} value={u.id}>{u.name}</option>)}
</select>
{isAdmin && (
<>
<select
className="bg-zinc-50 dark:bg-dark-bg border border-zinc-200 dark:border-dark-border px-3 py-2 rounded-lg text-sm text-zinc-700 dark:text-zinc-200 outline-none focus:ring-2 focus:ring-brand-yellow/20 cursor-pointer hover:border-zinc-300 dark:hover:border-dark-border transition-all"
value={filters.userId}
onChange={(e) => handleFilterChange('userId', e.target.value)}
>
<option value="all">Todos Usuários</option>
{users.map(u => <option key={u.id} value={u.id}>{u.name}</option>)}
</select>
<select
className="bg-slate-50 border border-slate-200 px-3 py-2 rounded-lg text-sm text-slate-700 outline-none focus:ring-2 focus:ring-blue-100 cursor-pointer hover:border-slate-300"
value={filters.teamId}
onChange={(e) => handleFilterChange('teamId', e.target.value)}
>
<option value="all">Todas Equipes</option>
{teams.map(t => <option key={t.id} value={t.id}>{t.name}</option>)}
</select>
<select
className="bg-zinc-50 dark:bg-dark-bg border border-zinc-200 dark:border-dark-border px-3 py-2 rounded-lg text-sm text-zinc-700 dark:text-zinc-200 outline-none focus:ring-2 focus:ring-brand-yellow/20 cursor-pointer hover:border-zinc-300 dark:hover:border-dark-border transition-all"
value={filters.teamId}
onChange={(e) => handleFilterChange('teamId', e.target.value)}
>
<option value="all">Todas Equipes</option>
{teams.map(t => <option key={t.id} value={t.id}>{t.name}</option>)}
</select>
</>
)}
<select
className="bg-zinc-50 dark:bg-dark-bg border border-zinc-200 dark:border-dark-border px-3 py-2 rounded-lg text-sm text-zinc-700 dark:text-zinc-200 outline-none focus:ring-2 focus:ring-brand-yellow/20 cursor-pointer hover:border-zinc-300 dark:hover:border-dark-border transition-all"
value={filters.funnelStage}
onChange={(e) => handleFilterChange('funnelStage', e.target.value)}
>
<option value="all">Todas Etapas</option>
{Object.values(FunnelStage).map(stage => (
<option key={stage} value={stage}>{stage}</option>
))}
</select>
<select
className="bg-zinc-50 dark:bg-dark-bg border border-zinc-200 dark:border-dark-border px-3 py-2 rounded-lg text-sm text-zinc-700 dark:text-zinc-200 outline-none focus:ring-2 focus:ring-brand-yellow/20 cursor-pointer hover:border-zinc-300 dark:hover:border-dark-border transition-all"
value={filters.origin}
onChange={(e) => handleFilterChange('origin', e.target.value)}
>
<option value="all">Todas Origens</option>
<option value="WhatsApp">WhatsApp</option>
<option value="Instagram">Instagram</option>
<option value="Website">Website</option>
<option value="LinkedIn">LinkedIn</option>
<option value="Indicação">Indicação</option>
</select>
</div>
</div>
</div>
@@ -210,7 +248,7 @@ export const Dashboard: React.FC = () => {
trend="up"
trendValue="12%"
icon={Users}
colorClass="text-blue-600"
colorClass="text-yellow-600"
/>
<KPICard
title="Nota Média Qualidade"
@@ -219,7 +257,7 @@ export const Dashboard: React.FC = () => {
trend={Number(avgScore) > 75 ? 'up' : 'down'}
trendValue="2.1"
icon={TrendingUp}
colorClass="text-purple-600"
colorClass="text-zinc-600"
/>
<KPICard
title="Média 1ª Resposta"
@@ -241,8 +279,8 @@ export const Dashboard: React.FC = () => {
{/* Charts Section */}
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
{/* Funnel Chart */}
<div className="lg:col-span-2 bg-white p-6 rounded-2xl shadow-sm border border-slate-100 min-h-[400px]">
<h3 className="text-lg font-bold text-slate-800 mb-6">Funil de Vendas</h3>
<div className="lg:col-span-2 bg-white dark:bg-dark-card p-6 rounded-2xl shadow-sm border border-zinc-100 dark:border-dark-border min-h-[400px]">
<h3 className="text-lg font-bold text-zinc-800 dark:text-dark-text mb-6">Funil de Vendas</h3>
<div className="h-[300px] w-full">
<ResponsiveContainer width="100%" height="100%">
<BarChart
@@ -251,23 +289,35 @@ export const Dashboard: React.FC = () => {
margin={{ top: 5, right: 30, left: 40, bottom: 5 }}
barSize={32}
>
<CartesianGrid strokeDasharray="3 3" horizontal={true} vertical={false} stroke="#f1f5f9" />
<CartesianGrid strokeDasharray="3 3" horizontal={true} vertical={false} stroke="#f1f5f9" className="dark:opacity-5" />
<XAxis type="number" hide />
<YAxis
dataKey="name"
type="category"
width={120}
tick={{fill: '#475569', fontSize: 13, fontWeight: 500}}
tick={{fill: '#71717a', fontSize: 13, fontWeight: 500}}
className="dark:fill-dark-muted"
tickLine={false}
axisLine={false}
/>
<Tooltip
cursor={{fill: '#f8fafc'}}
contentStyle={{ borderRadius: '12px', border: 'none', boxShadow: '0 10px 15px -3px rgb(0 0 0 / 0.1)' }}
cursor={{fill: '#f8fafc', opacity: 0.05}}
formatter={(value: any) => [value, 'Quantidade']}
contentStyle={{
borderRadius: '12px',
border: 'none',
boxShadow: '0 10px 15px -3px rgb(0 0 0 / 0.1)',
backgroundColor: '#1a1a1a',
color: '#ededed'
}}
itemStyle={{ color: '#ededed' }}
/>
<Bar dataKey="value" radius={[0, 6, 6, 0]}>
{funnelData.map((entry, index) => (
<Cell key={`cell-${index}`} fill={COLORS.charts[index % COLORS.charts.length]} />
<Cell
key={`cell-${index}`}
fill={COLORS.funnel[entry.name as keyof typeof COLORS.funnel] || '#cbd5e1'}
/>
))}
</Bar>
</BarChart>
@@ -276,8 +326,8 @@ export const Dashboard: React.FC = () => {
</div>
{/* Origin Pie Chart */}
<div className="bg-white p-6 rounded-2xl shadow-sm border border-slate-100 min-h-[400px] flex flex-col">
<h3 className="text-lg font-bold text-slate-800 mb-2">Origem dos Leads</h3>
<div className="bg-white dark:bg-dark-card p-6 rounded-2xl shadow-sm border border-zinc-100 dark:border-dark-border min-h-[400px] flex flex-col">
<h3 className="text-lg font-bold text-zinc-800 dark:text-dark-text mb-2">Origem dos Leads</h3>
<div className="flex-1 min-h-0">
<ResponsiveContainer width="100%" height="100%">
<PieChart>
@@ -292,10 +342,22 @@ export const Dashboard: React.FC = () => {
stroke="none"
>
{originData.map((entry, index) => (
<Cell key={`cell-${index}`} fill={COLORS.charts[index % COLORS.charts.length]} />
<Cell
key={`cell-${index}`}
fill={COLORS.origins[entry.name as keyof typeof COLORS.origins] || COLORS.charts[index % COLORS.charts.length]}
/>
))}
</Pie>
<Tooltip contentStyle={{ borderRadius: '12px' }} />
<Tooltip
formatter={(value: any) => [value, 'Leads']}
contentStyle={{
borderRadius: '12px',
backgroundColor: '#1a1a1a',
border: 'none',
color: '#ededed'
}}
itemStyle={{ color: '#ededed' }}
/>
<Legend
verticalAlign="bottom"
height={80}

View File

@@ -4,10 +4,10 @@ import { Hexagon, Mail, ArrowRight, Loader2, ArrowLeft, CheckCircle2 } from 'luc
import { forgotPassword } from '../services/dataService';
export const ForgotPassword: React.FC = () => {
const [isLoading, setIsLoading] = useState(false);
const [email, setEmail] = useState('');
const [error, setError] = useState('');
const [isLoading, setIsLoading] = useState(false);
const [isSuccess, setIsSuccess] = useState(false);
const [error, setError] = useState('');
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
@@ -18,117 +18,97 @@ export const ForgotPassword: React.FC = () => {
await forgotPassword(email);
setIsSuccess(true);
} catch (err: any) {
setError(err.message || 'Erro ao processar solicitação.');
setError(err.message || 'Erro ao enviar e-mail de recuperação.');
} finally {
setIsLoading(false);
}
};
return (
<div className="min-h-screen bg-slate-50 flex flex-col justify-center py-12 sm:px-6 lg:px-8">
<div className="min-h-screen bg-zinc-50 dark:bg-dark-bg flex flex-col justify-center py-12 sm:px-6 lg:px-8 transition-colors duration-300">
<div className="sm:mx-auto sm:w-full sm:max-w-md">
<div className="flex justify-center items-center gap-2 text-slate-900">
<div className="bg-slate-900 text-white p-2 rounded-lg">
<Hexagon size={28} fill="currentColor" />
<div className="flex justify-center items-center gap-2 text-zinc-900 dark:text-zinc-50">
<div className="bg-zinc-900 dark:bg-brand-yellow text-white dark:text-zinc-950 p-2 rounded-lg transition-colors">
<Hexagon size={32} fill="currentColor" />
</div>
<span className="text-3xl font-bold tracking-tight">Fasto<span className="text-yellow-500">.</span></span>
<span className="text-3xl font-bold tracking-tight">Fasto<span className="text-brand-yellow">.</span></span>
</div>
<h2 className="mt-6 text-center text-3xl font-bold tracking-tight text-slate-900">
<h2 className="mt-6 text-center text-3xl font-bold tracking-tight text-zinc-900 dark:text-zinc-50">
Recupere sua senha
</h2>
<p className="mt-2 text-center text-sm text-slate-600">
Digite seu e-mail e enviaremos as instruções.
<p className="mt-2 text-center text-sm text-zinc-600 dark:text-dark-muted">
Enviaremos um link de redefinição para o seu e-mail.
</p>
</div>
<div className="mt-8 sm:mx-auto sm:w-full sm:max-w-md">
<div className="bg-white py-8 px-4 shadow-xl shadow-slate-200/50 rounded-2xl sm:px-10 border border-slate-100">
<div className="bg-white dark:bg-dark-card py-8 px-4 shadow-xl rounded-2xl sm:px-10 border border-zinc-100 dark:border-dark-border transition-colors">
{isSuccess ? (
<div className="text-center space-y-4 py-4">
<div className="flex justify-center">
<div className="bg-green-100 p-3 rounded-full text-green-600">
<CheckCircle2 size={32} />
</div>
<div className="text-center py-4 space-y-4 animate-in fade-in zoom-in duration-300">
<div className="mx-auto flex items-center justify-center h-12 w-12 rounded-full bg-green-100 dark:bg-green-900/30 text-green-600 dark:text-green-400">
<CheckCircle2 size={24} />
</div>
<h3 className="text-lg font-bold text-slate-900">E-mail enviado!</h3>
<p className="text-sm text-slate-600">
Se o e-mail <strong>{email}</strong> estiver cadastrado, você receberá um link em instantes.
<h3 className="text-lg font-bold text-zinc-900 dark:text-zinc-50">E-mail enviado!</h3>
<p className="text-sm text-zinc-600 dark:text-dark-muted">
Verifique sua caixa de entrada (e a pasta de spam) para as instruções.
</p>
<div className="pt-4">
<Link to="/login" className="text-blue-600 font-medium hover:underline flex items-center justify-center gap-2">
<ArrowLeft size={16} /> Voltar para o login
<Link to="/login" className="text-brand-yellow font-bold hover:text-yellow-600 flex items-center justify-center gap-2 transition-colors">
<ArrowLeft size={18} /> Voltar para o login
</Link>
</div>
</div>
) : (
<form className="space-y-6" onSubmit={handleSubmit}>
<div>
<label htmlFor="email" className="block text-sm font-medium text-slate-700">
Endereço de e-mail
</label>
<div className="mt-1 relative rounded-md shadow-sm">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<Mail className="h-5 w-5 text-slate-400" />
</div>
<input
id="email"
name="email"
type="email"
required
value={email}
onChange={(e) => setEmail(e.target.value)}
className="block w-full pl-10 pr-3 py-2 border border-slate-300 rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-blue-100 focus:border-blue-500 sm:text-sm transition-all"
placeholder="voce@empresa.com"
/>
</div>
</div>
{error && (
<div className="text-red-500 text-sm font-medium text-center">
<div className="bg-red-50 dark:bg-red-900/20 border border-red-100 dark:border-red-900/30 p-3 rounded-lg text-red-600 dark:text-red-400 text-sm">
{error}
</div>
)}
<div>
<label htmlFor="email" className="block text-sm font-medium text-zinc-700 dark:text-zinc-300">
Seu E-mail
</label>
<div className="mt-1 relative">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<Mail className="h-5 w-5 text-zinc-400 dark:text-dark-muted" />
</div>
<input
id="email"
type="email"
required
value={email}
onChange={(e) => setEmail(e.target.value)}
className="block w-full pl-10 pr-3 py-2 border border-zinc-300 dark:border-dark-border rounded-lg bg-white dark:bg-dark-input text-zinc-900 dark:text-zinc-100 placeholder-zinc-400 dark:placeholder-zinc-600 focus:ring-brand-yellow/20 focus:border-brand-yellow sm:text-sm transition-all"
placeholder="seu@email.com"
/>
</div>
</div>
<div>
<button
type="submit"
disabled={isLoading}
className="w-full flex justify-center items-center gap-2 py-2.5 px-4 border border-transparent rounded-lg shadow-sm text-sm font-semibold text-white bg-slate-900 hover:bg-slate-800 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-slate-900 transition-all"
className="w-full flex justify-center items-center gap-2 py-2.5 px-4 border border-transparent rounded-lg shadow-sm text-sm font-bold text-zinc-950 bg-brand-yellow hover:bg-yellow-500 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-brand-yellow transition-all disabled:opacity-70"
>
{isLoading ? (
<>
<Loader2 className="animate-spin h-4 w-4" />
Enviando...
</>
<Loader2 className="animate-spin h-5 w-5" />
) : (
<>
Enviar Instruções <ArrowRight className="h-4 w-4" />
Enviar Link <ArrowRight size={18} />
</>
)}
</button>
</div>
<div className="text-center">
<Link to="/login" className="text-sm text-slate-500 hover:text-slate-800 flex items-center justify-center gap-1">
<Link to="/login" className="text-sm text-zinc-500 dark:text-dark-muted hover:text-zinc-800 dark:hover:text-zinc-200 flex items-center justify-center gap-1 transition-colors">
<ArrowLeft size={14} /> Voltar para o login
</Link>
</div>
</form>
)}
<div className="mt-6">
<div className="relative">
<div className="absolute inset-0 flex items-center">
<div className="w-full border-t border-slate-200" />
</div>
<div className="relative flex justify-center text-sm">
<span className="px-2 bg-white text-slate-500 text-xs">
Desenvolvido por <a href="https://blyzer.com.br" target="_blank" rel="noopener noreferrer" className="text-blue-600 hover:underline">Blyzer</a>
</span>
</div>
</div>
</div>
</div>
</div>
</div>

View File

@@ -1,7 +1,7 @@
import React, { useState } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { Hexagon, Lock, Mail, ArrowRight, Loader2, Eye, EyeOff, AlertCircle } from 'lucide-react';
import { login } from '../services/dataService';
import { login, logout } from '../services/dataService';
export const Login: React.FC = () => {
const navigate = useNavigate();
@@ -12,23 +12,17 @@ export const Login: React.FC = () => {
const [error, setError] = useState('');
const [emailError, setEmailError] = useState('');
const validateEmail = (value: string) => {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!value) {
setEmailError('');
} else if (!emailRegex.test(value)) {
setEmailError('Por favor, insira um e-mail válido.');
const validateEmail = (val: string) => {
setEmail(val);
if (!val) {
setEmailError('E-mail é obrigatório');
} else if (!/\S+@\S+\.\S+/.test(val)) {
setEmailError('E-mail inválido');
} else {
setEmailError('');
}
};
const handleEmailChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.value;
setEmail(value);
validateEmail(value);
};
const handleLogin = async (e: React.FormEvent) => {
e.preventDefault();
if (emailError) return;
@@ -36,52 +30,59 @@ export const Login: React.FC = () => {
setIsLoading(true);
setError('');
logout();
try {
const data = await login({ email, password });
localStorage.setItem('ctms_token', data.token);
localStorage.setItem('ctms_user_id', data.user.id);
localStorage.setItem('ctms_tenant_id', data.user.tenant_id || '');
setIsLoading(false);
if (data.user.role === 'super_admin') {
navigate('/super-admin');
} else {
navigate('/');
}
} catch (err: any) {
console.error("Login error:", err);
setIsLoading(false);
setError(err.message || 'E-mail ou senha incorretos.');
setError(err.message || 'Erro ao fazer login. Verifique suas credenciais.');
}
};
return (
<div className="min-h-screen bg-slate-50 flex flex-col justify-center py-12 sm:px-6 lg:px-8">
<div className="min-h-screen bg-zinc-50 dark:bg-dark-bg flex flex-col justify-center py-12 sm:px-6 lg:px-8 transition-colors duration-300">
<div className="sm:mx-auto sm:w-full sm:max-w-md">
<div className="flex justify-center items-center gap-2 text-slate-900">
<div className="bg-slate-900 text-white p-2 rounded-lg">
<Hexagon size={28} fill="currentColor" />
<div className="flex justify-center items-center gap-2 text-zinc-900 dark:text-zinc-50">
<div className="bg-zinc-900 dark:bg-brand-yellow text-white dark:text-zinc-950 p-2 rounded-lg transition-colors">
<Hexagon size={32} fill="currentColor" />
</div>
<span className="text-3xl font-bold tracking-tight">Fasto<span className="text-yellow-500">.</span></span>
<span className="text-3xl font-bold tracking-tight">Fasto<span className="text-brand-yellow">.</span></span>
</div>
<h2 className="mt-6 text-center text-3xl font-bold tracking-tight text-slate-900">
<h2 className="mt-6 text-center text-3xl font-bold tracking-tight text-zinc-900 dark:text-zinc-50">
Acesse sua conta
</h2>
<p className="mt-2 text-center text-sm text-zinc-600 dark:text-dark-muted">
Ou{' '}
<Link to="/register" className="font-medium text-brand-yellow hover:text-yellow-600">
registre sua nova organização
</Link>
</p>
</div>
<div className="mt-8 sm:mx-auto sm:w-full sm:max-w-md">
<div className="bg-white py-8 px-4 shadow-xl shadow-slate-200/50 rounded-2xl sm:px-10 border border-slate-100">
<div className="bg-white dark:bg-dark-card py-8 px-4 shadow-xl shadow-zinc-200/50 dark:shadow-none rounded-2xl sm:px-10 border border-zinc-100 dark:border-dark-border transition-colors">
<form className="space-y-6" onSubmit={handleLogin}>
{error && (
<div className="bg-red-50 dark:bg-red-900/20 border border-red-100 dark:border-red-900/30 p-3 rounded-lg flex items-center gap-2 text-red-600 dark:text-red-400 text-sm animate-in fade-in slide-in-from-top-1">
<AlertCircle size={18} />
{error}
</div>
)}
<div>
<label htmlFor="email" className="block text-sm font-medium text-slate-700">
Endereço de e-mail
<label htmlFor="email" className="block text-sm font-medium text-zinc-700 dark:text-zinc-300">
Endereço de E-mail
</label>
<div className="mt-1 relative rounded-md shadow-sm">
<div className="mt-1 relative">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<Mail className={`h-5 w-5 ${emailError ? 'text-red-400' : 'text-slate-400'}`} />
<Mail className="h-5 w-5 text-zinc-400 dark:text-dark-muted" />
</div>
<input
id="email"
@@ -90,29 +91,28 @@ export const Login: React.FC = () => {
autoComplete="email"
required
value={email}
onChange={handleEmailChange}
className={`block w-full pl-10 pr-3 py-2 border rounded-lg leading-5 bg-white placeholder-slate-400 focus:outline-none focus:ring-2 transition-all sm:text-sm ${
emailError
? 'border-red-300 focus:ring-red-100 focus:border-red-500'
: 'border-slate-300 focus:ring-blue-100 focus:border-blue-500'
}`}
placeholder="voce@empresa.com"
onChange={(e) => validateEmail(e.target.value)}
className={`block w-full pl-10 pr-3 py-2 border ${emailError ? 'border-red-300 focus:ring-red-100 focus:border-red-500' : 'border-zinc-300 dark:border-dark-border focus:ring-brand-yellow/20 focus:border-brand-yellow'} rounded-lg bg-white dark:bg-dark-input text-zinc-900 dark:text-zinc-100 placeholder-zinc-400 dark:placeholder-zinc-600 sm:text-sm transition-all`}
placeholder="seu@email.com"
/>
</div>
{emailError && (
<p className="mt-1.5 text-xs text-red-500 font-medium flex items-center gap-1">
<AlertCircle size={12} /> {emailError}
</p>
)}
{emailError && <p className="mt-1 text-xs text-red-500">{emailError}</p>}
</div>
<div>
<label htmlFor="password" senior-admin-password className="block text-sm font-medium text-slate-700">
Senha
</label>
<div className="mt-1 relative rounded-md shadow-sm">
<div className="flex items-center justify-between">
<label htmlFor="password" senior-admin-password className="block text-sm font-medium text-zinc-700 dark:text-zinc-300">
Senha
</label>
<div className="text-sm">
<Link to="/forgot-password" size="14" className="font-medium text-brand-yellow hover:text-yellow-600 transition-colors">
Esqueceu a senha?
</Link>
</div>
</div>
<div className="mt-1 relative">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<Lock className="h-5 w-5 text-slate-400" />
<Lock className="h-5 w-5 text-zinc-400 dark:text-dark-muted" />
</div>
<input
id="password"
@@ -122,74 +122,46 @@ export const Login: React.FC = () => {
required
value={password}
onChange={(e) => setPassword(e.target.value)}
className="block w-full pl-10 pr-10 py-2 border border-slate-300 rounded-lg leading-5 bg-white placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-100 focus:border-blue-500 sm:text-sm transition-all"
className="block w-full pl-10 pr-10 py-2 border border-zinc-300 dark:border-dark-border rounded-lg bg-white dark:bg-dark-input text-zinc-900 dark:text-zinc-100 placeholder-zinc-400 dark:placeholder-zinc-600 sm:text-sm focus:ring-brand-yellow/20 focus:border-brand-yellow transition-all"
placeholder="••••••••"
/>
<button
type="button"
className="absolute inset-y-0 right-0 pr-3 flex items-center text-zinc-400 hover:text-zinc-600 dark:hover:text-zinc-200 transition-colors"
onClick={() => setShowPassword(!showPassword)}
className="absolute inset-y-0 right-0 pr-3 flex items-center text-slate-400 hover:text-slate-600 transition-colors"
>
{showPassword ? <EyeOff size={18} /> : <Eye size={18} />}
</button>
</div>
</div>
{error && (
<div className="bg-red-50 border border-red-100 text-red-600 px-4 py-3 rounded-xl text-sm font-medium flex items-center gap-2 animate-in fade-in slide-in-from-top-2 duration-200">
<AlertCircle size={18} className="shrink-0" />
{error}
</div>
)}
<div className="flex items-center justify-between">
<div className="flex items-center">
<input
id="remember-me"
name="remember-me"
type="checkbox"
className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-slate-300 rounded"
/>
<label htmlFor="remember-me" className="ml-2 block text-sm text-slate-900">
Lembrar de mim
</label>
</div>
<div className="text-sm">
<Link to="/forgot-password" title="Recuperar Senha" className="font-medium text-blue-600 hover:text-blue-500">
Esqueceu sua senha?
</Link>
</div>
</div>
<div>
<button
type="submit"
disabled={isLoading || !!emailError || !email}
className="w-full flex justify-center items-center gap-2 py-2.5 px-4 border border-transparent rounded-lg shadow-sm text-sm font-semibold text-white bg-slate-900 hover:bg-slate-800 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-slate-900 disabled:opacity-70 disabled:cursor-not-allowed transition-all"
disabled={isLoading}
className="w-full flex justify-center items-center gap-2 py-2.5 px-4 border border-transparent rounded-lg shadow-sm text-sm font-bold text-zinc-950 bg-brand-yellow hover:bg-yellow-500 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-brand-yellow transition-all disabled:opacity-70"
>
{isLoading ? (
<>
<Loader2 className="animate-spin h-4 w-4" />
Entrando...
<Loader2 className="animate-spin h-5 w-5" /> Entrando...
</>
) : (
<>
Entrar <ArrowRight className="h-4 w-4" />
Entrar <ArrowRight size={18} />
</>
)}
</button>
</div>
</form>
<div className="mt-6">
<div className="mt-8">
<div className="relative">
<div className="absolute inset-0 flex items-center">
<div className="w-full border-t border-slate-200" />
<div className="w-full border-t border-zinc-200 dark:border-dark-border" />
</div>
<div className="relative flex justify-center text-sm">
<span className="px-2 bg-white text-slate-500 text-xs">
Desenvolvido por <a href="https://blyzer.com.br" target="_blank" rel="noopener noreferrer" className="text-blue-600 hover:underline">Blyzer</a>
<span className="px-2 bg-white dark:bg-dark-card text-zinc-500 dark:text-dark-muted text-xs uppercase tracking-widest font-bold transition-colors">
Powered by <a href="https://blyzer.com.br" target="_blank" rel="noopener noreferrer" className="text-brand-yellow hover:underline">Blyzer</a>
</span>
</div>
</div>

View File

@@ -22,156 +22,87 @@ export const Register: React.FC = () => {
try {
const success = await register(formData);
if (success) {
// Save email to localStorage for the verification step
localStorage.setItem('pending_verify_email', formData.email);
navigate('/verify');
navigate('/login', { state: { message: 'Conta criada! Verifique seu e-mail para o código de ativação.' } });
}
} catch (err: any) {
setError(err.message || 'Erro ao realizar registro.');
setError(err.message || 'Erro ao criar conta.');
} finally {
setIsLoading(false);
}
};
return (
<div className="min-h-screen bg-slate-50 flex flex-col justify-center py-12 sm:px-6 lg:px-8">
<div className="min-h-screen bg-zinc-50 dark:bg-dark-bg flex flex-col justify-center py-12 sm:px-6 lg:px-8 transition-colors duration-300">
<div className="sm:mx-auto sm:w-full sm:max-w-md">
<div className="flex justify-center items-center gap-2 text-slate-900">
<div className="bg-slate-900 text-white p-2 rounded-lg">
<Hexagon size={28} fill="currentColor" />
<div className="flex justify-center items-center gap-2 text-zinc-900 dark:text-zinc-50">
<div className="bg-zinc-900 dark:bg-brand-yellow text-white dark:text-zinc-950 p-2 rounded-lg transition-colors">
<Hexagon size={32} fill="currentColor" />
</div>
<span className="text-3xl font-bold tracking-tight">Fasto<span className="text-yellow-500">.</span></span>
<span className="text-3xl font-bold tracking-tight">Fasto<span className="text-brand-yellow">.</span></span>
</div>
<h2 className="mt-6 text-center text-3xl font-bold tracking-tight text-slate-900">
Crie sua conta
<h2 className="mt-6 text-center text-3xl font-bold tracking-tight text-zinc-900 dark:text-zinc-50">
Crie sua organização
</h2>
<p className="mt-2 text-center text-sm text-slate-600">
tem uma conta? <Link to="/login" className="font-medium text-blue-600 hover:text-blue-500">Faça login agora</Link>
</p>
</div>
<div className="mt-8 sm:mx-auto sm:w-full sm:max-w-md">
<div className="bg-white py-8 px-4 shadow-xl shadow-slate-200/50 rounded-2xl sm:px-10 border border-slate-100">
<div className="bg-white dark:bg-dark-card py-8 px-4 shadow-xl shadow-zinc-200/50 dark:shadow-none rounded-2xl sm:px-10 border border-zinc-100 dark:border-dark-border transition-colors">
<form className="space-y-5" onSubmit={handleRegister}>
<div>
<label htmlFor="name" className="block text-sm font-medium text-slate-700">
Nome Completo
</label>
<div className="mt-1 relative rounded-md shadow-sm">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<User className="h-5 w-5 text-slate-400" />
</div>
<input
id="name"
type="text"
required
value={formData.name}
onChange={(e) => setFormData({...formData, name: e.target.value})}
className="block w-full pl-10 pr-3 py-2 border border-slate-300 rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-blue-100 focus:border-blue-500 sm:text-sm"
placeholder="Seu nome"
/>
</div>
</div>
<div>
<label htmlFor="organization" className="block text-sm font-medium text-slate-700">
Nome da Organização
</label>
<div className="mt-1 relative rounded-md shadow-sm">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<Building className="h-5 w-5 text-slate-400" />
</div>
<input
id="organization"
type="text"
required
value={formData.organizationName}
onChange={(e) => setFormData({...formData, organizationName: e.target.value})}
className="block w-full pl-10 pr-3 py-2 border border-slate-300 rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-blue-100 focus:border-blue-500 sm:text-sm"
placeholder="Ex: Minha Empresa"
/>
</div>
</div>
<div>
<label htmlFor="email" className="block text-sm font-medium text-slate-700">
Endereço de e-mail
</label>
<div className="mt-1 relative rounded-md shadow-sm">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<Mail className="h-5 w-5 text-slate-400" />
</div>
<input
id="email"
type="email"
autoComplete="email"
required
value={formData.email}
onChange={(e) => setFormData({...formData, email: e.target.value})}
className="block w-full pl-10 pr-3 py-2 border border-slate-300 rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-blue-100 focus:border-blue-500 sm:text-sm"
placeholder="voce@empresa.com"
/>
</div>
</div>
<div>
<label htmlFor="password" senior-admin-password className="block text-sm font-medium text-slate-700">
Senha
</label>
<div className="mt-1 relative rounded-md shadow-sm">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<Lock className="h-5 w-5 text-slate-400" />
</div>
<input
id="password"
type="password"
required
value={formData.password}
onChange={(e) => setFormData({...formData, password: e.target.value})}
className="block w-full pl-10 pr-3 py-2 border border-slate-300 rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-blue-100 focus:border-blue-500 sm:text-sm"
placeholder="••••••••"
/>
</div>
</div>
{error && (
<div className="text-red-500 text-sm font-medium text-center">
<div className="bg-red-50 dark:bg-red-900/20 border border-red-100 dark:border-red-900/30 p-3 rounded-lg text-red-600 dark:text-red-400 text-sm">
{error}
</div>
)}
<div>
<button
type="submit"
disabled={isLoading}
className="w-full flex justify-center items-center gap-2 py-2.5 px-4 border border-transparent rounded-lg shadow-sm text-sm font-semibold text-white bg-slate-900 hover:bg-slate-800 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-slate-900 transition-all"
>
{isLoading ? (
<>
<Loader2 className="animate-spin h-4 w-4" />
Criando conta...
</>
) : (
<>
Registrar <ArrowRight className="h-4 w-4" />
</>
)}
<label htmlFor="name" className="block text-sm font-medium text-zinc-700 dark:text-zinc-300">Seu Nome</label>
<div className="mt-1 relative">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<User className="h-5 w-5 text-zinc-400 dark:text-dark-muted" />
</div>
<input type="text" required value={formData.name} onChange={e => setFormData({...formData, name: e.target.value})} className="block w-full pl-10 pr-3 py-2 border border-zinc-300 dark:border-dark-border rounded-lg bg-white dark:bg-dark-input text-zinc-900 dark:text-zinc-100 placeholder-zinc-400 dark:placeholder-zinc-600 focus:ring-brand-yellow/20 focus:border-brand-yellow sm:text-sm transition-all" placeholder="Nome Completo" />
</div>
</div>
<div>
<label htmlFor="organization" className="block text-sm font-medium text-zinc-700 dark:text-zinc-300">Nome da Organização</label>
<div className="mt-1 relative">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<Building className="h-5 w-5 text-zinc-400 dark:text-dark-muted" />
</div>
<input type="text" required value={formData.organizationName} onChange={e => setFormData({...formData, organizationName: e.target.value})} className="block w-full pl-10 pr-3 py-2 border border-zinc-300 dark:border-dark-border rounded-lg bg-white dark:bg-dark-input text-zinc-900 dark:text-zinc-100 placeholder-zinc-400 dark:placeholder-zinc-600 focus:ring-brand-yellow/20 focus:border-brand-yellow sm:text-sm transition-all" placeholder="Ex: Minha Empresa" />
</div>
</div>
<div>
<label htmlFor="email" className="block text-sm font-medium text-zinc-700 dark:text-zinc-300">E-mail Corporativo</label>
<div className="mt-1 relative">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<Mail className="h-5 w-5 text-zinc-400 dark:text-dark-muted" />
</div>
<input type="email" required value={formData.email} onChange={e => setFormData({...formData, email: e.target.value})} className="block w-full pl-10 pr-3 py-2 border border-zinc-300 dark:border-dark-border rounded-lg bg-white dark:bg-dark-input text-zinc-900 dark:text-zinc-100 placeholder-zinc-400 dark:placeholder-zinc-600 focus:ring-brand-yellow/20 focus:border-brand-yellow sm:text-sm transition-all" placeholder="seu@email.com" />
</div>
</div>
<div>
<label htmlFor="password" senior-admin-password className="block text-sm font-medium text-zinc-700 dark:text-zinc-300">Senha</label>
<div className="mt-1 relative">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<Lock className="h-5 w-5 text-zinc-400 dark:text-dark-muted" />
</div>
<input type="password" required value={formData.password} onChange={e => setFormData({...formData, password: e.target.value})} className="block w-full pl-10 pr-3 py-2 border border-zinc-300 dark:border-dark-border rounded-lg bg-white dark:bg-dark-input text-zinc-900 dark:text-zinc-100 placeholder-zinc-400 dark:placeholder-zinc-600 focus:ring-brand-yellow/20 focus:border-brand-yellow sm:text-sm transition-all" placeholder="••••••••" />
</div>
</div>
<div>
<button type="submit" disabled={isLoading} className="w-full flex justify-center items-center gap-2 py-2.5 px-4 border border-transparent rounded-lg shadow-sm text-sm font-bold text-zinc-950 bg-brand-yellow hover:bg-yellow-500 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-brand-yellow transition-all disabled:opacity-70">
{isLoading ? <Loader2 className="animate-spin h-5 w-5" /> : <>Criar Conta <ArrowRight size={18} /></>}
</button>
</div>
</form>
<div className="mt-6">
<div className="relative">
<div className="absolute inset-0 flex items-center">
<div className="w-full border-t border-slate-200" />
</div>
<div className="relative flex justify-center text-sm">
<span className="px-2 bg-white text-slate-500 text-xs">
Desenvolvido por <a href="https://blyzer.com.br" target="_blank" rel="noopener noreferrer" className="text-blue-600 hover:underline">Blyzer</a>
</span>
</div>
</div>
<div className="mt-6 text-center">
<Link to="/login" className="text-sm font-medium text-brand-yellow hover:text-yellow-600"> possui uma conta? Entre aqui</Link>
</div>
</div>
</div>

View File

@@ -6,22 +6,14 @@ import { resetPassword } from '../services/dataService';
export const ResetPassword: React.FC = () => {
const navigate = useNavigate();
const location = useLocation();
const [isLoading, setIsLoading] = useState(false);
const [password, setPassword] = useState('');
const [confirmPassword, setPasswordConfirm] = useState('');
const [error, setError] = useState('');
const [isSuccess, setIsSuccess] = useState(false);
const [token, setToken] = useState('');
const query = new URLSearchParams(location.search);
const token = query.get('token') || '';
useEffect(() => {
const params = new URLSearchParams(location.search);
const t = params.get('token');
if (!t) {
setError('Token de recuperação ausente.');
} else {
setToken(t);
}
}, [location]);
const [password, setPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
const [isLoading, setIsLoading] = useState(false);
const [isSuccess, setIsSuccess] = useState(false);
const [error, setError] = useState('');
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
@@ -29,142 +21,113 @@ export const ResetPassword: React.FC = () => {
setError('As senhas não coincidem.');
return;
}
setIsLoading(true);
setError('');
try {
await resetPassword(password, token);
await resetPassword(token, password);
setIsSuccess(true);
setTimeout(() => navigate('/login'), 3000);
} catch (err: any) {
setError(err.message || 'Erro ao redefinir senha.');
setError(err.message || 'Erro ao redefinir senha. O link pode estar expirado.');
} finally {
setIsLoading(false);
}
};
return (
<div className="min-h-screen bg-slate-50 flex flex-col justify-center py-12 sm:px-6 lg:px-8">
<div className="min-h-screen bg-zinc-50 dark:bg-dark-bg flex flex-col justify-center py-12 sm:px-6 lg:px-8 transition-colors duration-300">
<div className="sm:mx-auto sm:w-full sm:max-w-md">
<div className="flex justify-center items-center gap-2 text-slate-900">
<div className="bg-slate-900 text-white p-2 rounded-lg">
<Hexagon size={28} fill="currentColor" />
<div className="flex justify-center items-center gap-2 text-zinc-900 dark:text-zinc-50">
<div className="bg-zinc-900 dark:bg-brand-yellow text-white dark:text-zinc-950 p-2 rounded-lg transition-colors">
<Hexagon size={32} fill="currentColor" />
</div>
<span className="text-3xl font-bold tracking-tight">Fasto<span className="text-yellow-500">.</span></span>
<span className="text-3xl font-bold tracking-tight">Fasto<span className="text-brand-yellow">.</span></span>
</div>
<h2 className="mt-6 text-center text-3xl font-bold tracking-tight text-slate-900">
Nova senha
<h2 className="mt-6 text-center text-3xl font-bold tracking-tight text-zinc-900 dark:text-zinc-50">
Crie uma nova senha
</h2>
<p className="mt-2 text-center text-sm text-slate-600">
Escolha uma senha forte para sua segurança.
</p>
</div>
<div className="mt-8 sm:mx-auto sm:w-full sm:max-w-md">
<div className="bg-white py-8 px-4 shadow-xl shadow-slate-200/50 rounded-2xl sm:px-10 border border-slate-100">
<div className="bg-white dark:bg-dark-card py-8 px-4 shadow-xl rounded-2xl sm:px-10 border border-zinc-100 dark:border-dark-border transition-colors">
{isSuccess ? (
<div className="text-center space-y-4 py-4">
<div className="flex justify-center">
<div className="bg-green-100 p-3 rounded-full text-green-600">
<CheckCircle2 size={32} />
</div>
<div className="text-center py-4 space-y-4 animate-in fade-in zoom-in duration-300">
<div className="mx-auto flex items-center justify-center h-12 w-12 rounded-full bg-green-100 dark:bg-green-900/30 text-green-600 dark:text-green-400">
<CheckCircle2 size={24} />
</div>
<h3 className="text-lg font-bold text-slate-900">Sucesso!</h3>
<p className="text-sm text-slate-600">
Sua senha foi redefinida. Redirecionando para o login...
<h3 className="text-lg font-bold text-zinc-900 dark:text-zinc-50">Senha alterada!</h3>
<p className="text-sm text-zinc-600 dark:text-dark-muted">
Sua senha foi redefinida com sucesso. Redirecionando para o login...
</p>
</div>
) : (
<form className="space-y-5" onSubmit={handleSubmit}>
{!token && (
<div className="bg-red-50 text-red-600 p-3 rounded-lg text-sm flex items-center gap-2">
<AlertCircle size={18} /> Link inválido ou expirado.
</div>
)}
<div>
<label htmlFor="password" senior-admin-password className="block text-sm font-medium text-slate-700">
Nova Senha
</label>
<div className="mt-1 relative rounded-md shadow-sm">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<Lock className="h-5 w-5 text-slate-400" />
</div>
<input
id="password"
type="password"
required
disabled={!token}
value={password}
onChange={(e) => setPassword(e.target.value)}
className="block w-full pl-10 pr-3 py-2 border border-slate-300 rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-blue-100 focus:border-blue-500 sm:text-sm transition-all"
placeholder="••••••••"
/>
</div>
</div>
<div>
<label htmlFor="confirmPassword" senior-admin-password className="block text-sm font-medium text-slate-700">
Confirmar Nova Senha
</label>
<div className="mt-1 relative rounded-md shadow-sm">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<Lock className="h-5 w-5 text-slate-400" />
</div>
<input
id="confirmPassword"
type="password"
required
disabled={!token}
value={confirmPassword}
onChange={(e) => setPasswordConfirm(e.target.value)}
className="block w-full pl-10 pr-3 py-2 border border-slate-300 rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-blue-100 focus:border-blue-500 sm:text-sm transition-all"
placeholder="••••••••"
/>
</div>
</div>
<form className="space-y-6" onSubmit={handleSubmit}>
{error && (
<div className="text-red-500 text-sm font-medium text-center">
<div className="bg-red-50 dark:bg-red-900/20 border border-red-100 dark:border-red-900/30 p-3 rounded-lg flex items-center gap-2 text-red-600 dark:text-red-400 text-sm">
<AlertCircle size={18} />
{error}
</div>
)}
<div>
<label htmlFor="password" senior-admin-password className="block text-sm font-medium text-zinc-700 dark:text-zinc-300">
Nova Senha
</label>
<div className="mt-1 relative">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<Lock className="h-5 w-5 text-zinc-400 dark:text-dark-muted" />
</div>
<input
id="password"
type="password"
required
value={password}
onChange={(e) => setPassword(e.target.value)}
className="block w-full pl-10 pr-3 py-2 border border-zinc-300 dark:border-dark-border rounded-lg bg-white dark:bg-dark-input text-zinc-900 dark:text-zinc-100 placeholder-zinc-400 dark:placeholder-zinc-600 focus:ring-brand-yellow/20 focus:border-brand-yellow sm:text-sm transition-all"
placeholder="••••••••"
/>
</div>
</div>
<div>
<label htmlFor="confirmPassword" senior-admin-password className="block text-sm font-medium text-zinc-700 dark:text-zinc-300">
Confirmar Nova Senha
</label>
<div className="mt-1 relative">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<Lock className="h-5 w-5 text-zinc-400 dark:text-dark-muted" />
</div>
<input
id="confirmPassword"
type="password"
required
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
className="block w-full pl-10 pr-3 py-2 border border-zinc-300 dark:border-dark-border rounded-lg bg-white dark:bg-dark-input text-zinc-900 dark:text-zinc-100 placeholder-zinc-400 dark:placeholder-zinc-600 focus:ring-brand-yellow/20 focus:border-brand-yellow sm:text-sm transition-all"
placeholder="••••••••"
/>
</div>
</div>
<div>
<button
type="submit"
disabled={isLoading || !token}
className="w-full flex justify-center items-center gap-2 py-2.5 px-4 border border-transparent rounded-lg shadow-sm text-sm font-semibold text-white bg-slate-900 hover:bg-slate-800 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-slate-900 transition-all disabled:opacity-50"
disabled={isLoading}
className="w-full flex justify-center items-center gap-2 py-2.5 px-4 border border-transparent rounded-lg shadow-sm text-sm font-bold text-zinc-950 bg-brand-yellow hover:bg-yellow-500 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-brand-yellow transition-all disabled:opacity-50"
>
{isLoading ? (
<>
<Loader2 className="animate-spin h-4 w-4" />
Alterando...
</>
<Loader2 className="animate-spin h-5 w-5" />
) : (
<>
Redefinir Senha <ArrowRight className="h-4 w-4" />
Redefinir Senha <ArrowRight size={18} />
</>
)}
</button>
</div>
</form>
)}
<div className="mt-6">
<div className="relative">
<div className="absolute inset-0 flex items-center">
<div className="w-full border-t border-slate-200" />
</div>
<div className="relative flex justify-center text-sm">
<span className="px-2 bg-white text-slate-500 text-xs">
Desenvolvido por <a href="https://blyzer.com.br" target="_blank" rel="noopener noreferrer" className="text-blue-600 hover:underline">Blyzer</a>
</span>
</div>
</div>
</div>
</div>
</div>
</div>

View File

@@ -20,11 +20,9 @@ export const SuperAdmin: React.FC = () => {
const [isModalOpen, setIsModalOpen] = useState(false);
const [editingTenant, setEditingTenant] = useState<Tenant | null>(null);
// Sorting State
const [sortKey, setSortKey] = useState<keyof Tenant>('created_at');
const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('desc');
// Load Tenants from API
const loadTenants = async () => {
setLoading(true);
const data = await getTenants();
@@ -36,16 +34,12 @@ export const SuperAdmin: React.FC = () => {
loadTenants();
}, []);
// --- Metrics ---
const totalTenants = tenants.length;
const totalUsersGlobal = tenants.reduce((acc, t) => acc + (t.user_count || 0), 0);
const totalAttendancesGlobal = tenants.reduce((acc, t) => acc + (t.attendance_count || 0), 0);
// --- Data Filtering & Sorting ---
const filteredTenants = useMemo(() => {
let data = tenants;
// Search
if (searchQuery) {
const q = searchQuery.toLowerCase();
data = data.filter(t =>
@@ -54,27 +48,20 @@ export const SuperAdmin: React.FC = () => {
t.slug?.toLowerCase().includes(q)
);
}
// Tenant Filter (Select)
if (selectedTenantId !== 'all') {
data = data.filter(t => t.id === selectedTenantId);
}
// Sort
return [...data].sort((a, b) => {
const aVal = a[sortKey];
const bVal = b[sortKey];
if (aVal === undefined) return 1;
if (bVal === undefined) return -1;
if (aVal < bVal) return sortDirection === 'asc' ? -1 : 1;
if (aVal > bVal) return sortDirection === 'asc' ? 1 : -1;
return 0;
});
}, [tenants, searchQuery, selectedTenantId, sortKey, sortDirection]);
// --- Handlers ---
const handleSort = (key: keyof Tenant) => {
if (sortKey === key) {
setSortDirection(prev => prev === 'asc' ? 'desc' : 'asc');
@@ -98,286 +85,162 @@ export const SuperAdmin: React.FC = () => {
const handleSaveTenant = async (e: React.FormEvent) => {
e.preventDefault();
const form = e.target as HTMLFormElement;
const name = (form.elements.namedItem('name') as HTMLInputElement).value;
const slug = (form.elements.namedItem('slug') as HTMLInputElement).value;
const admin_email = (form.elements.namedItem('admin_email') as HTMLInputElement).value;
const status = (form.elements.namedItem('status') as HTMLSelectElement).value;
const success = await createTenant({ name, slug, admin_email, status });
if (success) {
setIsModalOpen(false);
setEditingTenant(null);
loadTenants(); // Reload list
loadTenants();
alert('Organização salva com sucesso!');
} else {
alert('Erro ao salvar organização. Verifique o console.');
alert('Erro ao salvar organização.');
}
};
// --- Helper Components ---
const SortIcon = ({ column }: { column: keyof Tenant }) => {
if (sortKey !== column) return <ChevronsUpDown size={14} className="text-slate-300" />;
return sortDirection === 'asc' ? <ChevronUp size={14} className="text-blue-500" /> : <ChevronDown size={14} className="text-blue-500" />;
if (sortKey !== column) return <ChevronsUpDown size={14} className="text-zinc-300 dark:text-dark-muted" />;
return sortDirection === 'asc' ? <ChevronUp size={14} className="text-brand-yellow" /> : <ChevronDown size={14} className="text-brand-yellow" />;
};
const StatusBadge = ({ status }: { status?: string }) => {
const styles = {
active: 'bg-green-100 text-green-700 border-green-200',
inactive: 'bg-slate-100 text-slate-700 border-slate-200',
trial: 'bg-purple-100 text-purple-700 border-purple-200',
active: 'bg-green-100 text-green-700 border-green-200 dark:bg-green-900/30 dark:text-green-400 dark:border-green-800',
inactive: 'bg-zinc-100 text-zinc-700 border-zinc-200 dark:bg-dark-input dark:text-dark-muted dark:border-dark-border',
trial: 'bg-purple-100 text-purple-700 border-purple-200 dark:bg-purple-900/30 dark:text-purple-400 dark:border-purple-800',
};
const style = styles[status as keyof typeof styles] || styles.inactive;
let label = status || 'Desconhecido';
if (status === 'active') label = 'Ativo';
if (status === 'inactive') label = 'Inativo';
if (status === 'trial') label = 'Teste';
return (
<span className={`px-2.5 py-0.5 rounded-full text-xs font-semibold border capitalize ${style}`}>
{label}
</span>
);
let label = status === 'active' ? 'Ativo' : status === 'inactive' ? 'Inativo' : status === 'trial' ? 'Teste' : 'Desconhecido';
return <span className={`px-2.5 py-0.5 rounded-full text-xs font-semibold border capitalize ${style}`}>{label}</span>;
};
return (
<div className="space-y-8 max-w-7xl mx-auto pb-8">
{/* Header */}
<div className="space-y-8 max-w-7xl mx-auto pb-8 transition-colors duration-300">
<div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
<div>
<h1 className="text-2xl font-bold text-slate-900 tracking-tight">Painel Super Admin</h1>
<p className="text-slate-500 text-sm">Gerencie organizações, visualize estatísticas globais e saúde do sistema.</p>
</div>
<div className="flex items-center gap-3">
<button
onClick={() => { setEditingTenant(null); setIsModalOpen(true); }}
className="flex items-center gap-2 bg-slate-900 text-white px-4 py-2 rounded-lg text-sm font-medium hover:bg-slate-800 transition-colors shadow-sm"
>
<Plus size={16} /> Adicionar Organização
</button>
<h1 className="text-2xl font-bold text-zinc-900 dark:text-zinc-50 tracking-tight">Painel Super Admin</h1>
<p className="text-zinc-500 dark:text-dark-muted text-sm">Gerencie organizações e visualize estatísticas globais.</p>
</div>
<button onClick={() => { setEditingTenant(null); setIsModalOpen(true); }} className="bg-zinc-900 dark:bg-brand-yellow text-white dark:text-zinc-950 px-4 py-2 rounded-lg text-sm font-bold hover:opacity-90 transition-all shadow-sm">
<Plus size={16} /> Adicionar Organização
</button>
</div>
{/* KPI Cards */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
<KPICard title="Total de Organizações" value={totalTenants} icon={Building2} colorClass="text-blue-600" trend="up" trendValue="+1 este mês" />
<KPICard title="Total de Usuários" value={totalUsersGlobal} icon={Users} colorClass="text-purple-600" subValue="Em todas as organizações" />
<KPICard title="Total de Atendimentos" value={totalAttendancesGlobal.toLocaleString()} icon={MessageSquare} colorClass="text-green-600" trend="up" trendValue="+12%" />
</div>
{/* KPI Cards */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
<KPICard
title="Total de Organizações"
value={totalTenants}
icon={Building2}
colorClass="text-blue-600"
trend="up"
trendValue="+1 este mês"
/>
<KPICard
title="Total de Usuários"
value={totalUsersGlobal}
icon={Users}
colorClass="text-purple-600"
subValue="Em todas as organizações"
/>
<KPICard
title="Total de Atendimentos"
value={totalAttendancesGlobal.toLocaleString()}
icon={MessageSquare}
colorClass="text-green-600"
trend="up"
trendValue="+12%"
/>
</div>
{/* Filters & Search */}
<div className="bg-white p-4 rounded-xl border border-slate-200 shadow-sm flex flex-col md:flex-row gap-4 justify-between items-center">
<div className="bg-white dark:bg-dark-card p-4 rounded-xl border border-zinc-200 dark:border-dark-border shadow-sm flex flex-col md:flex-row gap-4 justify-between items-center transition-colors">
<div className="flex items-center gap-3 w-full md:w-auto">
<DateRangePicker dateRange={dateRange} onChange={setDateRange} />
<div className="h-8 w-px bg-slate-200 hidden md:block" />
<select
className="bg-slate-50 border border-slate-200 px-3 py-2 rounded-lg text-sm text-slate-700 outline-none focus:ring-2 focus:ring-slate-200 cursor-pointer hover:border-slate-300 w-full md:w-48"
value={selectedTenantId}
onChange={(e) => setSelectedTenantId(e.target.value)}
>
<div className="h-8 w-px bg-zinc-200 dark:bg-dark-border hidden md:block" />
<select className="bg-zinc-50 dark:bg-dark-bg border border-zinc-200 dark:border-dark-border px-3 py-2 rounded-lg text-sm text-zinc-700 dark:text-zinc-200 outline-none focus:ring-2 focus:ring-brand-yellow/20 cursor-pointer hover:border-zinc-300 dark:hover:border-dark-border w-full md:w-48 transition-all" value={selectedTenantId} onChange={(e) => setSelectedTenantId(e.target.value)}>
<option value="all">Todas Organizações</option>
{tenants.map(t => <option key={t.id} value={t.id}>{t.name}</option>)}
</select>
</div>
<div className="relative w-full md:w-64">
<Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
<input
type="text"
placeholder="Buscar organizações..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="w-full pl-9 pr-4 py-2 bg-slate-50 border border-slate-200 rounded-lg text-sm outline-none focus:ring-2 focus:ring-blue-100 transition-all"
/>
<Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-zinc-400 dark:text-dark-muted" />
<input type="text" placeholder="Buscar organizações..." value={searchQuery} onChange={(e) => setSearchQuery(e.target.value)} className="w-full pl-9 pr-4 py-2 bg-zinc-50 dark:bg-dark-bg border border-zinc-200 dark:border-dark-border rounded-lg text-sm text-zinc-900 dark:text-zinc-100 outline-none focus:ring-2 focus:ring-brand-yellow/20 transition-all" />
</div>
</div>
{/* Tenants Table */}
<div className="bg-white border border-slate-200 rounded-xl shadow-sm overflow-hidden">
<div className="bg-white dark:bg-dark-card border border-zinc-200 dark:border-dark-border rounded-xl shadow-sm overflow-hidden transition-colors">
<div className="overflow-x-auto">
<table className="w-full text-left border-collapse">
<thead>
<tr className="bg-slate-50/50 text-slate-500 text-xs uppercase tracking-wider border-b border-slate-100">
<th className="px-6 py-4 font-semibold cursor-pointer hover:bg-slate-50 select-none" onClick={() => handleSort('name')}>
<tr className="bg-zinc-50/50 dark:bg-dark-bg/50 text-zinc-500 dark:text-dark-muted text-xs uppercase tracking-wider border-b border-zinc-100 dark:border-dark-border">
<th className="px-6 py-4 font-semibold cursor-pointer hover:bg-zinc-50 dark:hover:bg-dark-border select-none" onClick={() => handleSort('name')}>
<div className="flex items-center gap-2">Organização <SortIcon column="name" /></div>
</th>
<th className="px-6 py-4 font-semibold">Slug</th>
<th className="px-6 py-4 font-semibold cursor-pointer hover:bg-slate-50 select-none" onClick={() => handleSort('status')}>
<th className="px-6 py-4 font-semibold cursor-pointer hover:bg-zinc-50 dark:hover:bg-dark-border select-none" onClick={() => handleSort('status')}>
<div className="flex items-center gap-2">Status <SortIcon column="status" /></div>
</th>
<th className="px-6 py-4 font-semibold text-center cursor-pointer hover:bg-slate-50 select-none" onClick={() => handleSort('user_count')}>
<th className="px-6 py-4 font-semibold text-center cursor-pointer hover:bg-zinc-50 dark:hover:bg-dark-border select-none" onClick={() => handleSort('user_count')}>
<div className="flex items-center justify-center gap-2">Usuários <SortIcon column="user_count" /></div>
</th>
<th className="px-6 py-4 font-semibold text-center cursor-pointer hover:bg-slate-50 select-none" onClick={() => handleSort('attendance_count')}>
<th className="px-6 py-4 font-semibold text-center cursor-pointer hover:bg-zinc-50 dark:hover:bg-dark-border select-none" onClick={() => handleSort('attendance_count')}>
<div className="flex items-center justify-center gap-2">Atendimentos <SortIcon column="attendance_count" /></div>
</th>
<th className="px-6 py-4 font-semibold text-right">Ações</th>
</tr>
</thead>
<tbody className="divide-y divide-slate-100 text-sm">
<tbody className="divide-y divide-zinc-100 dark:divide-dark-border text-sm">
{filteredTenants.map((tenant) => (
<tr key={tenant.id} className="hover:bg-slate-50/50 transition-colors group">
<tr key={tenant.id} className="hover:bg-zinc-50/50 dark:hover:bg-zinc-800/50 transition-colors group">
<td className="px-6 py-4">
<div className="flex items-center gap-3">
<div className="w-10 h-10 rounded-lg bg-slate-100 flex items-center justify-center text-slate-400 font-bold border border-slate-200">
<div className="w-10 h-10 rounded-lg bg-zinc-100 dark:bg-dark-bg flex items-center justify-center text-zinc-400 dark:text-dark-muted font-bold border border-zinc-200 dark:border-dark-border">
{tenant.logo_url ? <img src={tenant.logo_url} className="w-full h-full object-cover rounded-lg" alt="" /> : <Building2 size={20} />}
</div>
<div>
<div className="font-semibold text-slate-900">{tenant.name}</div>
<div className="text-xs text-slate-500">{tenant.admin_email}</div>
<div className="font-semibold text-zinc-900 dark:text-zinc-100">{tenant.name}</div>
<div className="text-xs text-zinc-500 dark:text-dark-muted">{tenant.admin_email}</div>
</div>
</div>
</td>
<td className="px-6 py-4 text-slate-600 font-mono text-xs">
{tenant.slug}
</td>
<td className="px-6 py-4">
<StatusBadge status={tenant.status} />
</td>
<td className="px-6 py-4 text-center font-medium text-slate-700">
{tenant.user_count}
</td>
<td className="px-6 py-4 text-center font-medium text-slate-700">
{tenant.attendance_count?.toLocaleString()}
</td>
<td className="px-6 py-4 text-zinc-600 dark:text-dark-muted font-mono text-xs">{tenant.slug}</td>
<td className="px-6 py-4"><StatusBadge status={tenant.status} /></td>
<td className="px-6 py-4 text-center font-medium text-zinc-700 dark:text-zinc-300">{tenant.user_count}</td>
<td className="px-6 py-4 text-center font-medium text-zinc-700 dark:text-zinc-300">{tenant.attendance_count?.toLocaleString()}</td>
<td className="px-6 py-4 text-right">
<div className="flex items-center justify-end gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
<button
onClick={() => handleEdit(tenant)}
className="p-2 text-slate-400 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-colors"
title="Editar Organização"
>
<Edit size={16} />
</button>
<button
onClick={() => handleDelete(tenant.id)}
className="p-2 text-slate-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors"
title="Excluir Organização"
>
<Trash2 size={16} />
</button>
<button onClick={() => handleEdit(tenant)} className="p-2 text-zinc-400 hover:text-brand-yellow hover:bg-zinc-50 dark:hover:bg-dark-bg rounded-lg transition-colors"><Edit size={16} /></button>
<button onClick={() => handleDelete(tenant.id)} className="p-2 text-zinc-400 hover:text-red-600 hover:bg-red-50 dark:hover:bg-red-900/30 rounded-lg transition-colors"><Trash2 size={16} /></button>
</div>
</td>
</tr>
))}
{filteredTenants.length === 0 && (
<tr>
<td colSpan={6} className="px-6 py-12 text-center text-slate-400 italic">Nenhuma organização encontrada com os filtros atuais.</td>
</tr>
)}
</tbody>
</table>
</div>
{/* Simple Pagination Footer */}
<div className="px-6 py-4 border-t border-slate-100 bg-slate-50/30 text-xs text-slate-500 flex justify-between items-center">
<div className="px-6 py-4 border-t border-zinc-100 dark:border-dark-border bg-zinc-50/30 dark:bg-dark-bg/30 text-xs text-zinc-500 dark:text-dark-muted flex justify-between items-center transition-colors">
<span>Mostrando {filteredTenants.length} de {tenants.length} organizações</span>
<div className="flex gap-2">
<button disabled className="px-3 py-1 border rounded bg-white disabled:opacity-50">Ant</button>
<button disabled className="px-3 py-1 border rounded bg-white disabled:opacity-50">Próx</button>
<button disabled className="px-3 py-1 border dark:border-dark-border rounded bg-white dark:bg-dark-card disabled:opacity-50">Ant</button>
<button disabled className="px-3 py-1 border dark:border-dark-border rounded bg-white dark:bg-dark-card disabled:opacity-50">Próx</button>
</div>
</div>
</div>
{/* Add/Edit Modal */}
{isModalOpen && (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/50 backdrop-blur-sm">
<div className="bg-white rounded-xl shadow-xl w-full max-w-lg overflow-hidden animate-in fade-in zoom-in duration-200">
<div className="px-6 py-4 border-b border-slate-100 flex justify-between items-center bg-slate-50/50">
<h3 className="font-bold text-slate-900">{editingTenant ? 'Editar Organização' : 'Adicionar Nova Organização'}</h3>
<button onClick={() => setIsModalOpen(false)} className="text-slate-400 hover:text-slate-600">
<X size={20} />
</button>
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-zinc-950/80 backdrop-blur-sm">
<div className="bg-white dark:bg-dark-card rounded-xl shadow-xl w-full max-w-lg overflow-hidden animate-in fade-in zoom-in duration-200 border border-transparent dark:border-dark-border transition-colors">
<div className="px-6 py-4 border-b border-zinc-100 dark:border-dark-border flex justify-between items-center bg-zinc-50/50 dark:bg-dark-bg/50">
<h3 className="font-bold text-zinc-900 dark:text-zinc-50">{editingTenant ? 'Editar Organização' : 'Adicionar Nova Organização'}</h3>
<button onClick={() => setIsModalOpen(false)} className="text-zinc-400 hover:text-zinc-600 dark:hover:text-zinc-300"><X size={20} /></button>
</div>
<form onSubmit={handleSaveTenant} className="p-6 space-y-4">
<div className="space-y-2">
<label className="text-sm font-medium text-slate-700">Nome da Organização</label>
<input
type="text"
name="name"
defaultValue={editingTenant?.name}
className="w-full px-3 py-2 bg-slate-50 border border-slate-200 rounded-lg text-sm focus:ring-2 focus:ring-blue-100 outline-none"
placeholder="ex. Acme Corp"
required
/>
<label className="text-sm font-medium text-zinc-700 dark:text-zinc-300">Nome da Organização</label>
<input type="text" name="name" defaultValue={editingTenant?.name} className="w-full px-3 py-2 bg-zinc-50 dark:bg-dark-bg border border-zinc-200 dark:border-dark-border rounded-lg text-sm text-zinc-900 dark:text-zinc-100 focus:ring-2 focus:ring-brand-yellow/20 outline-none transition-all" required />
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<label className="text-sm font-medium text-slate-700">Slug</label>
<input
type="text"
name="slug"
defaultValue={editingTenant?.slug}
className="w-full px-3 py-2 bg-slate-50 border border-slate-200 rounded-lg text-sm focus:ring-2 focus:ring-blue-100 outline-none"
placeholder="ex. acme-corp"
/>
<label className="text-sm font-medium text-zinc-700 dark:text-zinc-300">Slug</label>
<input type="text" name="slug" defaultValue={editingTenant?.slug} className="w-full px-3 py-2 bg-zinc-50 dark:bg-dark-bg border border-zinc-200 dark:border-dark-border rounded-lg text-sm text-zinc-900 dark:text-zinc-100 focus:ring-2 focus:ring-brand-yellow/20 outline-none transition-all" />
</div>
<div className="space-y-2">
<label className="text-sm font-medium text-slate-700">Status</label>
<select
name="status"
defaultValue={editingTenant?.status || 'active'}
className="w-full px-3 py-2 bg-slate-50 border border-slate-200 rounded-lg text-sm focus:ring-2 focus:ring-blue-100 outline-none"
>
<label className="text-sm font-medium text-zinc-700 dark:text-zinc-300">Status</label>
<select name="status" defaultValue={editingTenant?.status || 'active'} className="w-full px-3 py-2 bg-zinc-50 dark:bg-dark-bg border border-zinc-200 dark:border-dark-border rounded-lg text-sm text-zinc-900 dark:text-zinc-100 outline-none transition-all">
<option value="active">Ativo</option>
<option value="inactive">Inativo</option>
<option value="trial">Teste</option>
</select>
</div>
</div>
<div className="space-y-2">
<label className="text-sm font-medium text-slate-700">E-mail do Admin</label>
<input
type="email"
name="admin_email"
defaultValue={editingTenant?.admin_email}
className="w-full px-3 py-2 bg-slate-50 border border-slate-200 rounded-lg text-sm focus:ring-2 focus:ring-blue-100 outline-none"
placeholder="admin@empresa.com"
required
/>
<label className="text-sm font-medium text-zinc-700 dark:text-zinc-300">E-mail do Admin</label>
<input type="email" name="admin_email" defaultValue={editingTenant?.admin_email} className="w-full px-3 py-2 bg-zinc-50 dark:bg-dark-bg border border-zinc-200 dark:border-dark-border rounded-lg text-sm text-zinc-900 dark:text-zinc-100 focus:ring-2 focus:ring-brand-yellow/20 outline-none transition-all" required />
</div>
<div className="pt-4 flex justify-end gap-3">
<button
type="button"
onClick={() => setIsModalOpen(false)}
className="px-4 py-2 text-slate-600 hover:bg-slate-100 rounded-lg text-sm font-medium transition-colors"
>
Cancelar
</button>
<button
type="submit"
className="px-4 py-2 bg-slate-900 text-white rounded-lg text-sm font-medium hover:bg-slate-800 transition-colors shadow-sm"
>
{editingTenant ? 'Salvar Alterações' : 'Criar Organização'}
</button>
<div className="pt-4 flex justify-end gap-3 border-t dark:border-dark-border mt-6">
<button type="button" onClick={() => setIsModalOpen(false)} className="px-4 py-2 text-zinc-600 dark:text-zinc-400 hover:bg-zinc-100 dark:hover:bg-dark-border rounded-lg text-sm font-medium transition-colors">Cancelar</button>
<button type="submit" className="px-4 py-2 bg-zinc-900 dark:bg-brand-yellow text-white dark:text-zinc-950 rounded-lg text-sm font-bold hover:opacity-90 transition-all shadow-sm">{editingTenant ? 'Salvar Alterações' : 'Criar Organização'}</button>
</div>
</form>
</div>
@@ -385,4 +248,4 @@ export const SuperAdmin: React.FC = () => {
)}
</div>
);
};
};

View File

@@ -1,5 +1,5 @@
import React, { useState, useEffect } from 'react';
import { Users, Plus, Mail, Search, X, Edit, Trash2, Loader2, CheckCircle2, AlertCircle, AlertTriangle } from 'lucide-react';
import { Users, Plus, Mail, Search, X, Edit, Trash2, Loader2, AlertTriangle } from 'lucide-react';
import { getUsers, getTeams, createMember, deleteUser, updateUser, getUserById } from '../services/dataService';
import { User } from '../types';
@@ -15,7 +15,13 @@ export const TeamManagement: React.FC = () => {
const [userToDelete, setUserToDelete] = useState<User | null>(null);
const [deleteConfirmName, setDeleteConfirmName] = useState('');
const [editingUser, setEditingUser] = useState<User | null>(null);
const [formData, setFormData] = useState({ name: '', email: '', role: 'agent' as any, team_id: '', status: 'active' as any });
const [formData, setFormData] = useState({
name: '',
email: '',
role: 'agent' as any,
team_id: '',
status: 'active' as any
});
const loadData = async () => {
const tid = localStorage.getItem('ctms_tenant_id');
@@ -37,9 +43,11 @@ export const TeamManagement: React.FC = () => {
setIsSaving(true);
try {
const tid = localStorage.getItem('ctms_tenant_id') || '';
const success = editingUser ? await updateUser(editingUser.id, formData) : await createMember({ ...formData, tenant_id: tid });
const success = editingUser
? await updateUser(editingUser.id, formData)
: await createMember({ ...formData, tenant_id: tid });
if (success) { setIsModalOpen(false); loadData(); }
} catch (err) { console.error(err); } finally { setIsSaving(false); }
} catch (err) { alert('Erro ao salvar'); } finally { setIsSaving(false); }
};
const handleConfirmDelete = async () => {
@@ -47,89 +55,143 @@ export const TeamManagement: React.FC = () => {
setIsSaving(true);
try {
if (await deleteUser(userToDelete.id)) { setIsDeleteModalOpen(false); loadData(); }
} catch (err) { console.error(err); } finally { setIsSaving(false); }
} catch (err) { alert('Erro ao excluir'); } finally { setIsSaving(false); }
};
if (loading && users.length === 0) return <div className="flex h-screen items-center justify-center text-slate-400">Carregando...</div>;
if (loading && users.length === 0) return <div className="flex h-screen items-center justify-center text-zinc-400 dark:text-dark-muted transition-colors">Carregando...</div>;
const canManage = currentUser?.role === 'admin' || currentUser?.role === 'super_admin';
const filtered = users.filter(u => u.name.toLowerCase().includes(searchTerm.toLowerCase()) || u.email.toLowerCase().includes(searchTerm.toLowerCase()));
const getRoleLabel = (role: string) => {
if (role === 'admin') return 'Admin';
if (role === 'manager') return 'Gerente';
return 'Agente';
};
const getRoleBadge = (role: string) => {
switch (role) {
case 'admin': return 'bg-purple-100 text-purple-700 border-purple-200';
case 'manager': return 'bg-blue-100 text-blue-700 border-blue-200';
default: return 'bg-slate-100 text-slate-700 border-slate-200';
case 'admin': return 'bg-purple-100 text-purple-700 border-purple-200 dark:bg-purple-900/30 dark:text-purple-400 dark:border-purple-800';
case 'manager': return 'bg-blue-100 text-blue-700 border-blue-200 dark:bg-blue-900/30 dark:text-blue-400 dark:border-blue-800';
default: return 'bg-zinc-100 text-zinc-700 border-zinc-200 dark:bg-dark-input dark:text-dark-muted dark:border-dark-border';
}
};
return (
<div className="space-y-8 max-w-7xl mx-auto pb-12">
<div className="space-y-8 max-w-7xl mx-auto pb-12 transition-colors duration-300">
<div className="flex justify-between items-center">
<div>
<h1 className="text-2xl font-bold text-slate-900 tracking-tight">Membros</h1>
<p className="text-slate-500 text-sm">Gerencie os acessos da sua organização.</p>
<h1 className="text-2xl font-bold text-zinc-900 dark:text-dark-text tracking-tight">Membros</h1>
<p className="text-zinc-500 dark:text-dark-muted text-sm">Visualize e gerencie as funções dos membros da sua organização.</p>
</div>
{canManage && (
<button onClick={() => { setEditingUser(null); setFormData({name:'', email:'', role:'agent', team_id:'', status:'active'}); setIsModalOpen(true); }} className="bg-slate-900 text-white px-4 py-2 rounded-lg flex items-center gap-2 text-sm font-bold shadow-sm">
<button onClick={() => { setEditingUser(null); setFormData({name:'', email:'', role:'agent', team_id:'', status:'active'}); setIsModalOpen(true); }} className="bg-zinc-900 dark:bg-brand-yellow text-white dark:text-zinc-950 px-4 py-2 rounded-lg flex items-center gap-2 text-sm font-bold shadow-sm hover:opacity-90 transition-all">
<Plus size={16} /> Adicionar Membro
</button>
)}
</div>
<div className="bg-white border border-slate-200 rounded-xl shadow-sm overflow-hidden">
<div className="p-4 border-b border-slate-100 bg-slate-50/30">
<input type="text" placeholder="Buscar membros..." value={searchTerm} onChange={e => setSearchTerm(e.target.value)} className="w-full max-w-md border border-slate-200 p-2 rounded-lg text-sm outline-none" />
<div className="bg-white dark:bg-dark-card border border-zinc-200 dark:border-dark-border rounded-xl shadow-sm overflow-hidden">
<div className="p-4 border-b border-zinc-100 dark:border-dark-border bg-zinc-50 dark:bg-dark-bg/50">
<div className="relative max-w-md">
<Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-zinc-400 dark:text-dark-muted" />
<input type="text" placeholder="Buscar membros..." value={searchTerm} onChange={e => setSearchTerm(e.target.value)} className="w-full pl-9 pr-4 py-2 bg-white dark:bg-dark-bg border border-zinc-200 dark:border-dark-border rounded-lg text-sm text-zinc-900 dark:text-dark-text outline-none focus:ring-2 focus:ring-brand-yellow/20 transition-all" />
</div>
</div>
<table className="w-full text-left">
<thead className="bg-slate-50/50 text-slate-500 text-xs uppercase font-bold border-b">
<tr>
<th className="px-6 py-4">Usuário</th>
<th className="px-6 py-4">Função</th>
<th className="px-6 py-4">Time</th>
<th className="px-6 py-4">Status</th>
{canManage && <th className="px-6 py-4 text-right">Ações</th>}
</tr>
</thead>
<tbody className="divide-y text-sm">
{filtered.map(user => (
<tr key={user.id} className="hover:bg-slate-50 group">
<td className="px-6 py-4">
<div className="flex items-center gap-3">
<img src={`https://ui-avatars.com/api/?name=${encodeURIComponent(user.name)}&background=random`} alt="" className="w-8 h-8 rounded-full" />
<div><div className="font-bold text-slate-900">{user.name}</div><div className="text-xs text-slate-500">{user.email}</div></div>
</div>
</td>
<td className="px-6 py-4"><span className={`px-2.5 py-0.5 rounded-full text-xs font-bold border capitalize ${getRoleBadge(user.role)}`}>{user.role}</span></td>
<td className="px-6 py-4 text-slate-600">{teams.find(t => t.id === user.team_id)?.name || '-'}</td>
<td className="px-6 py-4"><span className={`px-2 py-0.5 rounded-full text-xs font-bold ${user.status === 'active' ? 'bg-green-100 text-green-700' : 'bg-slate-100 text-slate-500'}`}>{user.status}</span></td>
{canManage && (
<td className="px-6 py-4 text-right flex justify-end gap-2 opacity-0 group-hover:opacity-100">
<button onClick={() => { setEditingUser(user); setFormData({name:user.name, email:user.email, role:user.role as any, team_id:user.team_id||'', status:user.status as any}); setIsModalOpen(true); }} className="p-1 hover:text-blue-600"><Edit size={16} /></button>
<button onClick={() => { setUserToDelete(user); setDeleteConfirmName(''); setIsDeleteModalOpen(true); }} className="p-1 hover:text-red-600"><Trash2 size={16} /></button>
</td>
)}
<div className="overflow-x-auto">
<table className="w-full text-left">
<thead>
<tr className="bg-zinc-50 dark:bg-dark-bg/50 text-zinc-500 dark:text-dark-muted text-xs uppercase font-bold border-b dark:border-dark-border">
<th className="px-6 py-4">Usuário</th>
<th className="px-6 py-4">Função</th>
<th className="px-6 py-4">Time</th>
<th className="px-6 py-4">Status</th>
{canManage && <th className="px-6 py-4 text-right">Ações</th>}
</tr>
))}
</tbody>
</table>
</thead>
<tbody className="divide-y dark:divide-dark-border text-sm">
{filtered.map(user => (
<tr key={user.id} className="hover:bg-zinc-50 dark:hover:bg-dark-border/50 transition-colors group">
<td className="px-6 py-4">
<div className="flex items-center gap-3">
<div className="relative">
<img
src={user.avatar_url
? (user.avatar_url.startsWith('http') ? user.avatar_url : `${import.meta.env.PROD ? '' : 'http://localhost:3001'}${user.avatar_url}`)
: `https://ui-avatars.com/api/?name=${encodeURIComponent(user.name)}&background=random`}
alt=""
className="w-10 h-10 rounded-full border border-zinc-200 dark:border-dark-border object-cover"
/>
<span className={`absolute bottom-0 right-0 w-2.5 h-2.5 rounded-full border-2 border-white dark:border-dark-card ${user.status === 'active' ? 'bg-green-500' : 'bg-zinc-300 dark:bg-zinc-600'}`}></span>
</div>
<div>
<div className="font-bold text-zinc-900 dark:text-dark-text">{user.name}</div>
<div className="text-xs text-zinc-500 dark:text-dark-muted">{user.email}</div>
</div>
</div>
</td>
<td className="px-6 py-4">
<span className={`px-2.5 py-0.5 rounded-full text-xs font-bold border capitalize ${getRoleBadge(user.role)}`}>{getRoleLabel(user.role)}</span>
</td>
<td className="px-6 py-4 text-zinc-600 dark:text-zinc-300 font-medium">{teams.find(t => t.id === user.team_id)?.name || '-'}</td>
<td className="px-6 py-4">
<span className={`px-2 py-0.5 rounded-full text-xs font-bold border ${user.status === 'active' ? 'bg-green-100 text-green-700 border-green-200 dark:bg-green-900/30 dark:text-green-400 dark:border-green-800' : 'bg-zinc-100 text-zinc-500 border-zinc-200 dark:bg-dark-input dark:text-dark-muted dark:border-dark-border'}`}>{user.status === 'active' ? 'Ativo' : 'Inativo'}</span>
</td>
{canManage && (
<td className="px-6 py-4 text-right">
<div className="flex justify-end gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
<button onClick={() => { setEditingUser(user); setFormData({name:user.name, email:user.email, role:user.role as any, team_id:user.team_id||'', status:user.status as any}); setIsModalOpen(true); }} className="p-2 hover:bg-zinc-100 dark:hover:bg-dark-border text-zinc-400 hover:text-zinc-900 dark:hover:text-dark-text rounded-lg transition-colors"><Edit size={16} /></button>
<button onClick={() => { setUserToDelete(user); setDeleteConfirmName(''); setIsDeleteModalOpen(true); }} className="p-2 hover:bg-red-50 dark:hover:bg-red-900/30 text-zinc-400 hover:text-red-600 dark:hover:text-red-400 rounded-lg transition-colors"><Trash2 size={16} /></button>
</div>
</td>
)}
</tr>
))}
</tbody>
</table>
</div>
</div>
{isModalOpen && (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm">
<div className="bg-white rounded-2xl p-6 w-full max-w-md shadow-xl">
<h3 className="text-lg font-bold mb-4">{editingUser ? 'Editar' : 'Novo'} Membro</h3>
<form onSubmit={handleSave} className="space-y-4">
<div><label className="text-xs font-bold text-slate-500 block mb-1">NOME</label><input type="text" value={formData.name} onChange={e => setFormData({...formData, name:e.target.value})} className="w-full border p-2 rounded-lg" required /></div>
<div><label className="text-xs font-bold text-slate-500 block mb-1">E-MAIL</label><input type="email" value={formData.email} onChange={e => setFormData({...formData, email:e.target.value})} className="w-full border p-2 rounded-lg" disabled={!!editingUser} required /></div>
<div className="grid grid-cols-2 gap-4">
<div><label className="text-xs font-bold text-slate-500 block mb-1">FUNÇÃO</label><select value={formData.role} onChange={e => setFormData({...formData, role: e.target.value as any})} className="w-full border p-2 rounded-lg"><option value="agent">Agente</option><option value="manager">Gerente</option><option value="admin">Admin</option></select></div>
<div><label className="text-xs font-bold text-slate-500 block mb-1">TIME</label><select value={formData.team_id} onChange={e => setFormData({...formData, team_id: e.target.value})} className="w-full border p-2 rounded-lg"><option value="">Nenhum</option>{teams.map(t => <option key={t.id} value={t.id}>{t.name}</option>)}</select></div>
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-zinc-950/80 backdrop-blur-sm">
<div className="bg-white dark:bg-dark-card rounded-2xl p-8 w-full max-w-lg shadow-2xl animate-in zoom-in duration-200 transition-colors border border-transparent dark:border-dark-border">
<h3 className="text-xl font-bold text-zinc-900 dark:text-dark-text mb-6">{editingUser ? 'Editar Usuário' : 'Novo Membro'}</h3>
<form onSubmit={handleSave} className="space-y-5">
<div>
<label className="text-xs font-bold text-zinc-500 dark:text-dark-muted uppercase mb-1 block">Nome Completo</label>
<input type="text" value={formData.name} onChange={e => setFormData({...formData, name:e.target.value})} className="w-full bg-white dark:bg-dark-input border border-zinc-200 dark:border-dark-border p-3 rounded-lg text-sm text-zinc-900 dark:text-dark-text outline-none focus:ring-2 focus:ring-brand-yellow/20" required />
</div>
<div><label className="text-xs font-bold text-slate-500 block mb-1">STATUS</label><select value={formData.status} onChange={e => setFormData({...formData, status: e.target.value as any})} className="w-full border p-2 rounded-lg"><option value="active">Ativo</option><option value="inactive">Inativo</option></select></div>
<div className="flex justify-end gap-2 pt-4">
<button type="button" onClick={() => setIsModalOpen(false)} className="px-4 py-2">Cancelar</button>
<button type="submit" className="bg-slate-900 text-white px-6 py-2 rounded-lg font-bold">{isSaving ? '...' : 'Salvar'}</button>
<div>
<label className="text-xs font-bold text-zinc-500 dark:text-dark-muted uppercase mb-1 block">E-mail</label>
<input type="email" value={formData.email} onChange={e => setFormData({...formData, email:e.target.value})} className="w-full bg-white dark:bg-dark-input border border-zinc-200 dark:border-dark-border p-3 rounded-lg text-sm text-zinc-900 dark:text-dark-text disabled:bg-zinc-50 dark:disabled:bg-dark-bg/50 dark:disabled:text-dark-muted" disabled={!!editingUser} required />
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<label className="text-xs font-bold text-zinc-500 dark:text-dark-muted uppercase mb-1 block">Função</label>
<select value={formData.role} onChange={e => setFormData({...formData, role: e.target.value as any})} className="w-full bg-white dark:bg-dark-input border border-zinc-200 dark:border-dark-border p-3 rounded-lg text-sm text-zinc-900 dark:text-dark-text">
<option value="agent">Agente</option>
<option value="manager">Gerente</option>
<option value="admin">Admin</option>
</select>
</div>
<div>
<label className="text-xs font-bold text-zinc-500 dark:text-dark-muted uppercase mb-1 block">Time</label>
<select value={formData.team_id} onChange={e => setFormData({...formData, team_id: e.target.value})} className="w-full bg-white dark:bg-dark-input border border-zinc-200 dark:border-dark-border p-3 rounded-lg text-sm text-zinc-900 dark:text-dark-text">
<option value="">Nenhum</option>
{teams.map(t => <option key={t.id} value={t.id}>{t.name}</option>)}
</select>
</div>
</div>
<div>
<label className="text-xs font-bold text-zinc-500 dark:text-dark-muted uppercase mb-1 block">Status</label>
<select value={formData.status} onChange={e => setFormData({...formData, status: e.target.value as any})} className="w-full bg-white dark:bg-dark-input border border-zinc-200 dark:border-dark-border p-3 rounded-lg text-sm text-zinc-900 dark:text-dark-text">
<option value="active">Ativo</option>
<option value="inactive">Inativo</option>
</select>
</div>
<div className="flex justify-end gap-3 pt-6 border-t dark:border-dark-border mt-6">
<button type="button" onClick={() => setIsModalOpen(false)} className="px-6 py-2.5 text-sm font-medium text-zinc-500 dark:text-dark-muted hover:bg-zinc-100 dark:hover:bg-dark-border rounded-lg transition-colors">Cancelar</button>
<button type="submit" disabled={isSaving} className="bg-zinc-900 dark:bg-brand-yellow text-white dark:text-zinc-950 px-8 py-2.5 rounded-lg text-sm font-bold flex items-center gap-2 hover:opacity-90 transition-all">{isSaving ? <Loader2 className="animate-spin" size={16} /> : 'Salvar Alterações'}</button>
</div>
</form>
</div>
@@ -137,13 +199,15 @@ export const TeamManagement: React.FC = () => {
)}
{isDeleteModalOpen && userToDelete && (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50">
<div className="bg-white rounded-2xl p-6 w-full max-w-md">
<h3 className="text-lg font-bold mb-2">Excluir {userToDelete.name}?</h3>
<input type="text" value={deleteConfirmName} onChange={e => setDeleteConfirmName(e.target.value)} className="w-full border-2 p-2 rounded-lg mb-4 text-center font-bold" placeholder="Digite o nome para confirmar" />
<div className="flex gap-2">
<button onClick={() => setIsDeleteModalOpen(false)} className="flex-1 py-2">Cancelar</button>
<button onClick={handleConfirmDelete} disabled={deleteConfirmName !== userToDelete.name} className="flex-1 py-2 bg-red-600 text-white rounded-lg">Excluir</button>
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-zinc-950/80 backdrop-blur-sm">
<div className="bg-white dark:bg-dark-card rounded-2xl p-8 w-full max-w-md shadow-xl animate-in zoom-in duration-200 text-center transition-colors border border-transparent dark:border-dark-border">
<div className="w-16 h-16 bg-red-100 dark:bg-red-900/30 text-red-600 dark:text-red-400 rounded-full flex items-center justify-center mx-auto mb-4"><AlertTriangle size={32} /></div>
<h3 className="text-xl font-bold text-zinc-900 dark:text-dark-text mb-2">Excluir {userToDelete.name}?</h3>
<p className="text-sm text-zinc-500 dark:text-dark-muted mb-8 leading-relaxed">Esta ação é <strong>permanente</strong>. Para confirmar, digite o nome completo dele abaixo:</p>
<input type="text" value={deleteConfirmName} onChange={e => setDeleteConfirmName(e.target.value)} className="w-full bg-white dark:bg-dark-input border-2 border-red-50 dark:border-red-900/20 p-3 rounded-xl mb-8 text-center font-bold text-base text-zinc-900 dark:text-dark-text outline-none focus:ring-2 focus:ring-red-100 dark:focus:ring-red-900/40 transition-all" placeholder="Nome completo" />
<div className="flex gap-3">
<button onClick={() => setIsDeleteModalOpen(false)} className="flex-1 py-3 text-sm font-bold text-zinc-500 dark:text-dark-muted hover:bg-zinc-100 dark:hover:bg-dark-border rounded-lg border border-zinc-100 dark:border-dark-border transition-colors">Cancelar</button>
<button onClick={handleConfirmDelete} disabled={isSaving || deleteConfirmName !== userToDelete.name} className="flex-1 py-3 text-sm font-bold bg-red-600 text-white rounded-lg disabled:opacity-50 shadow-lg shadow-red-200 dark:shadow-none transition-all hover:bg-red-700">Excluir para sempre</button>
</div>
</div>
</div>

View File

@@ -1,5 +1,5 @@
import React, { useState, useEffect, useMemo } from 'react';
import { Building2, Users, Plus, Search, Target, ArrowUpRight, Loader2, CheckCircle2, AlertCircle, Edit2, X } from 'lucide-react';
import { Building2, Users, Plus, Search, Target, ArrowUpRight, Loader2, Edit2, X } from 'lucide-react';
import { getTeams, getUsers, getAttendances, createTeam, updateTeam } from '../services/dataService';
import { User, Attendance } from '../types';
@@ -11,15 +11,8 @@ export const Teams: React.FC = () => {
const [isSaving, setIsSaving] = useState(false);
const [isModalOpen, setIsModalOpen] = useState(false);
const [editingTeam, setEditingTeam] = useState<any | null>(null);
const [searchTerm, setSearchTerm] = useState('');
const [toast, setToast] = useState<{message: string, type: 'success' | 'error'} | null>(null);
const [formData, setFormData] = useState({ name: '', description: '' });
const showToast = (message: string, type: 'success' | 'error') => {
setToast({ message, type });
setTimeout(() => setToast(null), 4000);
};
const loadData = async () => {
const tid = localStorage.getItem('ctms_tenant_id');
if (!tid) return;
@@ -41,77 +34,84 @@ export const Teams: React.FC = () => {
const ta = attendances.filter(a => tu.some(u => u.id === a.user_id));
const wins = ta.filter(a => a.converted).length;
const rate = ta.length > 0 ? (wins / ta.length) * 100 : 0;
return { ...t, memberCount: tu.length, leads: ta.length, rate: rate.toFixed(1) };
return { ...t, memberCount: tu.length, rate: rate.toFixed(1) };
}), [teams, users, attendances]);
const filtered = stats.filter(t => t.name.toLowerCase().includes(searchTerm.toLowerCase()));
const handleSave = async (e: React.FormEvent) => {
e.preventDefault();
setIsSaving(true);
try {
const tid = localStorage.getItem('ctms_tenant_id') || '';
if (editingTeam) {
if (await updateTeam(editingTeam.id, formData)) { showToast('Atualizado!', 'success'); setIsModalOpen(false); loadData(); }
} else {
if (await createTeam({ ...formData, tenantId: tid })) { showToast('Criado!', 'success'); setIsModalOpen(false); loadData(); }
}
} catch (e) { showToast('Erro', 'error'); } finally { setIsSaving(false); }
const success = editingTeam
? await updateTeam(editingTeam.id, formData)
: await createTeam({ ...formData, tenantId: tid });
if (success) { setIsModalOpen(false); loadData(); }
} catch (err) { alert('Erro ao salvar'); } finally { setIsSaving(false); }
};
if (loading && teams.length === 0) return <div className="p-12 text-center text-slate-400">Carregando...</div>;
if (loading && teams.length === 0) return <div className="p-12 text-center text-zinc-400 dark:text-dark-muted transition-colors">Carregando...</div>;
return (
<div className="space-y-8 max-w-7xl mx-auto pb-12">
<div className="space-y-8 max-w-7xl mx-auto pb-12 transition-colors duration-300">
<div className="flex justify-between items-center">
<div>
<h1 className="text-2xl font-bold text-slate-900">Times</h1>
<p className="text-slate-500 text-sm">Desempenho por grupo.</p>
<h1 className="text-2xl font-bold text-zinc-900 dark:text-zinc-50 tracking-tight">Times</h1>
<p className="text-zinc-500 dark:text-dark-muted text-sm">Visualize o desempenho e gerencie seus grupos de vendas.</p>
</div>
<button onClick={() => { setEditingTeam(null); setFormData({name:'', description:''}); setIsModalOpen(true); }} className="bg-slate-900 text-white px-4 py-2 rounded-lg flex items-center gap-2 text-sm font-bold">
<button onClick={() => { setEditingTeam(null); setFormData({name:'', description:''}); setIsModalOpen(true); }} className="bg-zinc-900 dark:bg-brand-yellow text-white dark:text-zinc-950 px-4 py-2 rounded-lg flex items-center gap-2 text-sm font-bold shadow-sm hover:opacity-90 transition-all">
<Plus size={16} /> Novo Time
</button>
</div>
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
{filtered.map(t => (
<div key={t.id} className="bg-white rounded-2xl border border-slate-200 p-6 shadow-sm group">
<div className="flex justify-between mb-4">
<div className="p-3 bg-blue-50 text-blue-600 rounded-xl"><Building2 size={24} /></div>
<button onClick={() => { setEditingTeam(t); setFormData({name:t.name, description:t.description||''}); setIsModalOpen(true); }} className="text-slate-400 hover:text-blue-600 opacity-0 group-hover:opacity-100 transition-opacity"><Edit2 size={18} /></button>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{stats.map(t => (
<div key={t.id} className="bg-white dark:bg-dark-card rounded-2xl border border-zinc-200 dark:border-dark-border p-6 shadow-sm group hover:shadow-md transition-all">
<div className="flex justify-between mb-6">
<div className="p-3 bg-zinc-50 dark:bg-dark-bg text-zinc-600 dark:text-dark-muted rounded-xl border border-zinc-100 dark:border-dark-border"><Building2 size={24} /></div>
<button onClick={() => { setEditingTeam(t); setFormData({name:t.name, description:t.description||''}); setIsModalOpen(true); }} className="text-zinc-400 dark:text-dark-muted hover:text-zinc-900 dark:hover:text-dark-text opacity-0 group-hover:opacity-100 p-2 rounded-lg hover:bg-zinc-50 dark:hover:bg-dark-bg transition-all"><Edit2 size={18} /></button>
</div>
<h3 className="font-bold text-slate-900">{t.name}</h3>
<p className="text-sm text-slate-500 mb-4">{t.description || 'Sem descrição'}</p>
<div className="grid grid-cols-2 gap-4 pt-4 border-t text-sm">
<div><span className="text-slate-400 block text-xs font-bold uppercase">Membros</span><strong>{t.memberCount}</strong></div>
<div><span className="text-slate-400 block text-xs font-bold uppercase">Conversão</span><strong className="text-blue-600">{t.rate}%</strong></div>
<h3 className="text-lg font-bold text-zinc-900 dark:text-zinc-50 mb-1">{t.name}</h3>
<p className="text-sm text-zinc-500 dark:text-dark-muted mb-6 h-10 line-clamp-2">{t.description || 'Sem descrição definida.'}</p>
<div className="grid grid-cols-2 gap-4 pt-6 border-t border-zinc-50 dark:border-dark-border text-sm">
<div className="space-y-1">
<span className="text-zinc-400 dark:text-dark-muted block text-[10px] font-bold uppercase tracking-wider">Membros</span>
<strong className="text-lg text-zinc-800 dark:text-zinc-200">{t.memberCount}</strong>
</div>
<div className="space-y-1 text-right">
<span className="text-zinc-400 dark:text-dark-muted block text-[10px] font-bold uppercase tracking-wider">Conversão</span>
<strong className="text-lg text-brand-yellow">{t.rate}%</strong>
</div>
</div>
</div>
))}
</div>
{isModalOpen && (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/50 backdrop-blur-sm">
<div className="bg-white rounded-2xl p-6 w-full max-w-md">
<h3 className="text-lg font-bold mb-4">{editingTeam ? 'Editar' : 'Novo'} Time</h3>
<form onSubmit={handleSave} className="space-y-4">
<input type="text" placeholder="Nome" value={formData.name} onChange={e => setFormData({...formData, name:e.target.value})} className="w-full border p-2 rounded-lg" required />
<textarea placeholder="Descrição" value={formData.description} onChange={e => setFormData({...formData, description:e.target.value})} className="w-full border p-2 rounded-lg resize-none" rows={3} />
<div className="flex justify-end gap-2">
<button type="button" onClick={() => setIsModalOpen(false)} className="px-4 py-2 text-slate-500">Cancelar</button>
<button type="submit" disabled={isSaving} className="bg-slate-900 text-white px-6 py-2 rounded-lg font-bold">{isSaving ? '...' : 'Salvar'}</button>
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-zinc-950/80 backdrop-blur-sm">
<div className="bg-white dark:bg-dark-card rounded-2xl p-8 w-full max-w-md shadow-2xl animate-in zoom-in duration-200 transition-colors border border-transparent dark:border-dark-border">
<div className="flex justify-between items-center mb-6 pb-4 border-b border-zinc-100 dark:border-dark-border">
<h3 className="text-xl font-bold text-zinc-900 dark:text-zinc-50">{editingTeam ? 'Editar Time' : 'Novo Time'}</h3>
<button onClick={() => setIsModalOpen(false)} className="text-zinc-400 hover:text-zinc-600 dark:hover:text-zinc-300 transition-colors"><X size={20} /></button>
</div>
<form onSubmit={handleSave} className="space-y-5">
<div>
<label className="text-xs font-bold text-zinc-500 dark:text-dark-muted uppercase mb-1.5 block tracking-wider">Nome do Time</label>
<input type="text" placeholder="Ex: Vendas Sul" value={formData.name} onChange={e => setFormData({...formData, name:e.target.value})} className="w-full bg-white dark:bg-dark-input border border-zinc-200 dark:border-dark-border p-3 rounded-lg text-sm text-zinc-900 dark:text-zinc-100 outline-none focus:ring-2 focus:ring-brand-yellow/20 transition-all" required />
</div>
<div>
<label className="text-xs font-bold text-zinc-500 dark:text-dark-muted uppercase mb-1.5 block tracking-wider">Descrição</label>
<textarea placeholder="Breve descrição..." value={formData.description} onChange={e => setFormData({...formData, description:e.target.value})} className="w-full bg-white dark:bg-dark-input border border-zinc-200 dark:border-dark-border p-3 rounded-lg text-sm text-zinc-900 dark:text-zinc-100 resize-none h-28 outline-none focus:ring-2 focus:ring-brand-yellow/20 transition-all" />
</div>
<div className="flex justify-end gap-3 pt-6 border-t dark:border-dark-border mt-6">
<button type="button" onClick={() => setIsModalOpen(false)} className="px-6 py-2.5 text-sm font-medium text-zinc-500 dark:text-dark-muted hover:bg-zinc-100 dark:hover:bg-dark-bg rounded-lg transition-colors">Cancelar</button>
<button type="submit" disabled={isSaving} className="bg-zinc-900 dark:bg-brand-yellow text-white dark:text-zinc-950 px-8 py-2.5 rounded-lg text-sm font-bold shadow-lg transition-all hover:opacity-90">
{isSaving ? <Loader2 className="animate-spin" size={16} /> : 'Salvar Time'}
</button>
</div>
</form>
</div>
</div>
)}
{toast && (
<div className="fixed bottom-8 right-8 z-[100] flex items-center gap-3 px-6 py-4 rounded-2xl shadow-2xl bg-white border border-slate-100">
<CheckCircle2 className="text-green-500" size={20} />
<span className="font-bold text-sm text-slate-700">{toast.message}</span>
</div>
)}
</div>
);
};

View File

@@ -1,8 +1,8 @@
import React, { useEffect, useState, useMemo } from 'react';
import { useParams, Link } from 'react-router-dom';
import { getAttendances, getUserById } from '../services/dataService';
import { Attendance, User, FunnelStage } from '../types';
import { ArrowLeft, Mail, Phone, Clock, MessageSquare, ChevronLeft, ChevronRight, Eye } from 'lucide-react';
import { Attendance, User, FunnelStage, DashboardFilter } from '../types';
import { ArrowLeft, Mail, Phone, Clock, MessageSquare, ChevronLeft, ChevronRight, Eye, Filter } from 'lucide-react';
const ITEMS_PER_PAGE = 10;
@@ -12,6 +12,12 @@ export const UserDetail: React.FC = () => {
const [attendances, setAttendances] = useState<Attendance[]>([]);
const [loading, setLoading] = useState(true);
const [currentPage, setCurrentPage] = useState(1);
const [filters, setFilters] = useState<DashboardFilter>({
dateRange: { start: new Date(0), end: new Date() },
userId: id,
funnelStage: 'all',
origin: 'all'
});
useEffect(() => {
if (id) {
@@ -25,8 +31,8 @@ export const UserDetail: React.FC = () => {
if (u && tenantId) {
const data = await getAttendances(tenantId, {
userId: id,
dateRange: { start: new Date(0), end: new Date() } // All time
...filters,
userId: id
});
setAttendances(data);
}
@@ -39,7 +45,12 @@ export const UserDetail: React.FC = () => {
loadData();
}
}, [id]);
}, [id, filters]);
const handleFilterChange = (key: keyof DashboardFilter, value: any) => {
setFilters(prev => ({ ...prev, [key]: value }));
setCurrentPage(1); // Reset pagination on filter change
};
const totalPages = Math.ceil(attendances.length / ITEMS_PER_PAGE);
@@ -56,38 +67,46 @@ export const UserDetail: React.FC = () => {
const getStageBadgeColor = (stage: FunnelStage) => {
switch (stage) {
case FunnelStage.WON: return 'bg-green-100 text-green-700 border-green-200';
case FunnelStage.LOST: return 'bg-red-100 text-red-700 border-red-200';
case FunnelStage.NEGOTIATION: return 'bg-blue-100 text-blue-700 border-blue-200';
case FunnelStage.IDENTIFICATION: return 'bg-yellow-100 text-yellow-700 border-yellow-200';
default: return 'bg-slate-100 text-slate-700 border-slate-200';
case FunnelStage.WON: return 'bg-green-100 text-green-700 border-green-200 dark:bg-green-900/30 dark:text-green-400 dark:border-green-800';
case FunnelStage.LOST: return 'bg-red-100 text-red-700 border-red-200 dark:bg-red-900/30 dark:text-red-400 dark:border-red-800';
case FunnelStage.NEGOTIATION: return 'bg-blue-100 text-blue-700 border-blue-200 dark:bg-blue-900/30 dark:text-blue-400 dark:border-blue-800';
case FunnelStage.IDENTIFICATION: return 'bg-yellow-100 text-yellow-700 border-yellow-200 dark:bg-yellow-900/30 dark:text-yellow-400 dark:border-yellow-800';
default: return 'bg-zinc-100 text-zinc-700 border-zinc-200 dark:bg-zinc-800 dark:text-zinc-300 dark:border-zinc-700';
}
};
const getScoreColor = (score: number) => {
if (score >= 80) return 'text-green-600 bg-green-50';
if (score >= 60) return 'text-yellow-600 bg-yellow-50';
return 'text-red-600 bg-red-50';
if (score >= 80) return 'text-green-600 bg-green-50 dark:bg-green-900/20 dark:text-green-400';
if (score >= 60) return 'text-yellow-600 bg-yellow-50 dark:bg-yellow-900/20 dark:text-yellow-400';
return 'text-red-600 bg-red-50 dark:bg-red-900/20 dark:text-red-400';
};
if (!loading && !user) return <div className="p-8 text-slate-500">Usuário não encontrado</div>;
if (!loading && !user) return <div className="p-8 text-zinc-500 dark:text-dark-muted transition-colors">Usuário não encontrado</div>;
const backendUrl = import.meta.env.PROD ? '' : 'http://localhost:3001';
return (
<div className="space-y-8 max-w-7xl mx-auto">
<div className="space-y-8 max-w-7xl mx-auto transition-colors duration-300">
{/* Header Section */}
<div className="flex flex-col md:flex-row gap-6 items-start md:items-center justify-between">
<div className="flex items-center gap-4">
<Link to="/" className="p-2.5 bg-white border border-slate-200 rounded-lg text-slate-500 hover:bg-slate-50 hover:text-slate-900 transition-colors shadow-sm">
<Link to="/" className="p-2.5 bg-white dark:bg-dark-card border border-zinc-200 dark:border-dark-border rounded-lg text-zinc-500 dark:text-dark-muted hover:bg-zinc-50 dark:hover:bg-zinc-800 hover:text-zinc-900 dark:hover:text-dark-text transition-all shadow-sm">
<ArrowLeft size={18} />
</Link>
{user && (
<div className="flex items-center gap-4">
<img src={user.avatar_url} alt={user.name} className="w-16 h-16 rounded-full border-2 border-white shadow-md object-cover" />
<img
src={user.avatar_url
? (user.avatar_url.startsWith('http') ? user.avatar_url : `${backendUrl}${user.avatar_url}`)
: `https://ui-avatars.com/api/?name=${encodeURIComponent(user.name)}&background=random`}
alt={user.name}
className="w-16 h-16 rounded-full border-2 border-white dark:border-dark-border shadow-md object-cover"
/>
<div>
<h1 className="text-2xl font-bold text-slate-900 tracking-tight">{user.name}</h1>
<div className="flex items-center gap-3 text-sm text-slate-500 mt-1">
<h1 className="text-2xl font-bold text-zinc-900 dark:text-dark-text tracking-tight">{user.name}</h1>
<div className="flex items-center gap-3 text-sm text-zinc-500 dark:text-dark-muted mt-1">
<span className="flex items-center gap-1.5"><Mail size={14} /> {user.email}</span>
<span className="bg-slate-100 text-slate-600 px-2 py-0.5 rounded text-xs font-semibold uppercase">{user.role}</span>
<span className="bg-zinc-100 dark:bg-dark-bg text-zinc-600 dark:text-dark-muted px-2 py-0.5 rounded text-xs font-semibold uppercase">{user.role}</span>
</div>
</div>
</div>
@@ -95,40 +114,72 @@ export const UserDetail: React.FC = () => {
</div>
</div>
{/* Filters Section */}
<div className="bg-white dark:bg-dark-card p-4 rounded-xl border border-zinc-200 dark:border-dark-border shadow-sm flex flex-wrap items-center gap-4">
<div className="flex items-center gap-2 text-zinc-500 dark:text-dark-muted font-medium mr-2">
<Filter size={18} />
<span>Filtros:</span>
</div>
<select
className="bg-zinc-50 dark:bg-dark-bg border border-zinc-200 dark:border-dark-border px-3 py-2 rounded-lg text-sm text-zinc-700 dark:text-zinc-200 outline-none focus:ring-2 focus:ring-brand-yellow/20 cursor-pointer hover:border-zinc-300 dark:hover:border-zinc-700 transition-all"
value={filters.funnelStage}
onChange={(e) => handleFilterChange('funnelStage', e.target.value)}
>
<option value="all">Todas Etapas</option>
{Object.values(FunnelStage).map(stage => (
<option key={stage} value={stage}>{stage}</option>
))}
</select>
<select
className="bg-zinc-50 dark:bg-dark-bg border border-zinc-200 dark:border-dark-border px-3 py-2 rounded-lg text-sm text-zinc-700 dark:text-zinc-200 outline-none focus:ring-2 focus:ring-brand-yellow/20 cursor-pointer hover:border-zinc-300 dark:hover:border-zinc-700 transition-all"
value={filters.origin}
onChange={(e) => handleFilterChange('origin', e.target.value)}
>
<option value="all">Todas Origens</option>
<option value="WhatsApp">WhatsApp</option>
<option value="Instagram">Instagram</option>
<option value="Website">Website</option>
<option value="LinkedIn">LinkedIn</option>
<option value="Indicação">Indicação</option>
</select>
</div>
{/* KPI Cards */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
<div className="bg-white p-6 rounded-xl border border-slate-200 shadow-sm">
<div className="text-sm font-medium text-slate-500 mb-2">Total de Interações</div>
<div className="text-3xl font-bold text-slate-900">{attendances.length}</div>
<div className="bg-white dark:bg-dark-card p-6 rounded-xl border border-zinc-200 dark:border-dark-border shadow-sm transition-colors">
<div className="text-sm font-medium text-zinc-500 dark:text-dark-muted mb-2">Total de Interações</div>
<div className="text-3xl font-bold text-zinc-900 dark:text-dark-text">{attendances.length}</div>
</div>
<div className="bg-white p-6 rounded-xl border border-slate-200 shadow-sm">
<div className="text-sm font-medium text-slate-500 mb-2">Taxa de Conversão</div>
<div className="text-3xl font-bold text-blue-600">
<div className="bg-white dark:bg-dark-card p-6 rounded-xl border border-zinc-200 dark:border-dark-border shadow-sm transition-colors">
<div className="text-sm font-medium text-zinc-500 dark:text-dark-muted mb-2">Taxa de Conversão</div>
<div className="text-3xl font-bold text-brand-yellow">
{attendances.length ? ((attendances.filter(a => a.converted).length / attendances.length) * 100).toFixed(1) : 0}%
</div>
</div>
<div className="bg-white p-6 rounded-xl border border-slate-200 shadow-sm">
<div className="text-sm font-medium text-slate-500 mb-2">Nota Média</div>
<div className="text-3xl font-bold text-yellow-500">
<div className="bg-white dark:bg-dark-card p-6 rounded-xl border border-zinc-200 dark:border-dark-border shadow-sm transition-colors">
<div className="text-sm font-medium text-zinc-500 dark:text-dark-muted mb-2">Nota Média</div>
<div className="text-3xl font-bold text-zinc-800 dark:text-zinc-100">
{attendances.length ? (attendances.reduce((acc, c) => acc + c.score, 0) / attendances.length).toFixed(1) : 0}
</div>
</div>
</div>
{/* Attendance Table */}
<div className="bg-white border border-slate-200 rounded-xl shadow-sm overflow-hidden flex flex-col">
<div className="px-6 py-4 border-b border-slate-100 flex justify-between items-center bg-slate-50/50">
<h2 className="font-semibold text-slate-900">Histórico de Atendimentos</h2>
<span className="text-xs text-slate-500 font-medium bg-slate-200/50 px-2 py-1 rounded">Página {currentPage} de {totalPages || 1}</span>
<div className="bg-white dark:bg-dark-card border border-zinc-200 dark:border-dark-border rounded-xl shadow-sm overflow-hidden flex flex-col transition-colors">
<div className="px-6 py-4 border-b border-zinc-100 dark:border-zinc-800 flex justify-between items-center bg-zinc-50/50 dark:bg-dark-bg/50">
<h2 className="font-semibold text-zinc-900 dark:text-zinc-100">Histórico de Atendimentos</h2>
<span className="text-xs text-zinc-500 dark:text-dark-muted font-medium bg-zinc-200/50 dark:bg-zinc-800 px-2 py-1 rounded transition-colors">Página {currentPage} de {totalPages || 1}</span>
</div>
{loading ? (
<div className="p-12 text-center text-slate-400">Carregando registros...</div>
<div className="p-12 text-center text-zinc-400 dark:text-dark-muted">Carregando registros...</div>
) : (
<div className="overflow-x-auto">
<table className="w-full text-left border-collapse">
<thead>
<tr className="border-b border-slate-100 text-xs uppercase text-slate-500 bg-slate-50/30">
<tr className="border-b border-zinc-100 dark:border-zinc-800 text-xs uppercase text-zinc-500 dark:text-dark-muted bg-zinc-50/30 dark:bg-dark-bg/30">
<th className="px-6 py-4 font-medium">Data / Hora</th>
<th className="px-6 py-4 font-medium w-1/3">Resumo</th>
<th className="px-6 py-4 font-medium text-center">Etapa</th>
@@ -137,17 +188,17 @@ export const UserDetail: React.FC = () => {
<th className="px-6 py-4 font-medium text-right">Ação</th>
</tr>
</thead>
<tbody className="divide-y divide-slate-100 text-sm">
<tbody className="divide-y divide-zinc-100 dark:divide-zinc-800 text-sm">
{currentData.map(att => (
<tr key={att.id} className="hover:bg-slate-50/80 transition-colors group">
<td className="px-6 py-4 text-slate-600 whitespace-nowrap">
<div className="font-medium text-slate-900">{new Date(att.created_at).toLocaleDateString()}</div>
<div className="text-xs text-slate-400">{new Date(att.created_at).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'})}</div>
<tr key={att.id} className="hover:bg-zinc-50/80 dark:hover:bg-zinc-800/50 transition-colors group">
<td className="px-6 py-4 text-zinc-600 dark:text-zinc-300 whitespace-nowrap">
<div className="font-medium text-zinc-900 dark:text-zinc-100">{new Date(att.created_at).toLocaleDateString()}</div>
<div className="text-xs text-zinc-400 dark:text-dark-muted">{new Date(att.created_at).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'})}</div>
</td>
<td className="px-6 py-4">
<div className="flex flex-col">
<span className="text-slate-800 line-clamp-1 font-medium mb-1">{att.summary}</span>
<div className="flex items-center gap-2 text-xs text-slate-500">
<span className="text-zinc-800 dark:text-zinc-200 line-clamp-1 font-medium mb-1">{att.summary}</span>
<div className="flex items-center gap-2 text-xs text-zinc-500 dark:text-dark-muted">
<span className="flex items-center gap-1"><MessageSquare size={10} /> {att.origin}</span>
</div>
</div>
@@ -162,16 +213,16 @@ export const UserDetail: React.FC = () => {
{att.score}
</span>
</td>
<td className="px-6 py-4 text-center text-slate-600">
<td className="px-6 py-4 text-center text-zinc-600 dark:text-zinc-300">
<div className="flex items-center justify-center gap-1">
<Clock size={14} className="text-slate-400" />
<Clock size={14} className="text-zinc-400 dark:text-dark-muted" />
{att.first_response_time_min}m
</div>
</td>
<td className="px-6 py-4 text-right">
<Link
to={`/attendances/${att.id}`}
className="inline-flex items-center justify-center p-2 rounded-lg text-slate-400 hover:text-blue-600 hover:bg-blue-50 transition-all"
className="inline-flex items-center justify-center p-2 rounded-lg text-zinc-400 dark:text-dark-muted hover:text-brand-yellow hover:bg-zinc-100 dark:hover:bg-zinc-800 transition-all"
title="Ver Detalhes"
>
<Eye size={18} />
@@ -186,21 +237,21 @@ export const UserDetail: React.FC = () => {
{/* Pagination Footer */}
{totalPages > 1 && (
<div className="px-6 py-4 border-t border-slate-100 flex items-center justify-between bg-slate-50/30">
<div className="px-6 py-4 border-t border-zinc-100 dark:border-zinc-800 flex items-center justify-between bg-zinc-50/30 dark:bg-dark-bg/30">
<button
onClick={() => handlePageChange(currentPage - 1)}
disabled={currentPage === 1}
className="flex items-center gap-1 px-3 py-2 text-sm font-medium text-slate-600 bg-white border border-slate-200 rounded-lg hover:bg-slate-50 disabled:opacity-50 disabled:cursor-not-allowed transition-all shadow-sm"
className="flex items-center gap-1 px-3 py-2 text-sm font-medium text-zinc-600 dark:text-dark-text bg-white dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700 rounded-lg hover:bg-zinc-50 dark:hover:bg-zinc-700 disabled:opacity-50 disabled:cursor-not-allowed transition-all shadow-sm"
>
<ChevronLeft size={16} /> Anterior
</button>
<div className="text-sm text-slate-500">
Mostrando <span className="font-medium text-slate-900">{((currentPage - 1) * ITEMS_PER_PAGE) + 1}</span> a <span className="font-medium text-slate-900">{Math.min(currentPage * ITEMS_PER_PAGE, attendances.length)}</span> de {attendances.length}
<div className="text-sm text-zinc-500 dark:text-dark-muted">
Mostrando <span className="font-medium text-zinc-900 dark:text-zinc-100">{((currentPage - 1) * ITEMS_PER_PAGE) + 1}</span> a <span className="font-medium text-zinc-900 dark:text-zinc-100">{Math.min(currentPage * ITEMS_PER_PAGE, attendances.length)}</span> de {attendances.length}
</div>
<button
onClick={() => handlePageChange(currentPage + 1)}
disabled={currentPage === totalPages}
className="flex items-center gap-1 px-3 py-2 text-sm font-medium text-slate-600 bg-white border border-slate-200 rounded-lg hover:bg-slate-50 disabled:opacity-50 disabled:cursor-not-allowed transition-all shadow-sm"
className="flex items-center gap-1 px-3 py-2 text-sm font-medium text-zinc-600 dark:text-dark-text bg-white dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700 rounded-lg hover:bg-zinc-50 dark:hover:bg-zinc-700 disabled:opacity-50 disabled:cursor-not-allowed transition-all shadow-sm"
>
Próximo <ChevronRight size={16} />
</button>
@@ -209,4 +260,4 @@ export const UserDetail: React.FC = () => {
</div>
</div>
);
};
};

View File

@@ -1,6 +1,6 @@
import React, { useState, useEffect } from 'react';
import React, { useState, useEffect, useRef } from 'react';
import { Camera, Save, Mail, User as UserIcon, Building, Shield, Loader2, CheckCircle2 } from 'lucide-react';
import { getUserById, getTenants, updateUser } from '../services/dataService';
import { getUserById, getTenants, updateUser, uploadAvatar } from '../services/dataService';
import { User, Tenant } from '../types';
export const UserProfile: React.FC = () => {
@@ -8,6 +8,8 @@ export const UserProfile: React.FC = () => {
const [tenant, setTenant] = useState<Tenant | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [isSuccess, setIsSuccess] = useState(false);
const [isUploading, setIsUploading] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
const [name, setName] = useState('');
const [bio, setBio] = useState('');
@@ -38,6 +40,36 @@ export const UserProfile: React.FC = () => {
fetchUserAndTenant();
}, []);
const handleAvatarClick = () => {
fileInputRef.current?.click();
};
const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file || !user) return;
if (file.size > 2 * 1024 * 1024) {
alert('Arquivo muito grande. Máximo de 2MB.');
return;
}
setIsUploading(true);
try {
const newUrl = await uploadAvatar(user.id, file);
if (newUrl) {
setUser({ ...user, avatar_url: newUrl });
window.location.reload();
} else {
alert('Erro ao fazer upload da imagem.');
}
} catch (err) {
console.error(err);
alert('Erro ao conectar ao servidor.');
} finally {
setIsUploading(false);
}
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!user) return;
@@ -49,7 +81,6 @@ export const UserProfile: React.FC = () => {
const success = await updateUser(user.id, { name, bio });
if (success) {
setIsSuccess(true);
// Update local state
setUser({ ...user, name, bio });
setTimeout(() => setIsSuccess(false), 3000);
} else {
@@ -63,53 +94,69 @@ export const UserProfile: React.FC = () => {
}
};
if (!user) return <div className="p-8 text-center text-slate-500">Carregando perfil...</div>;
if (!user) return <div className="p-8 text-center text-zinc-500 dark:text-zinc-400 transition-colors">Carregando perfil...</div>;
const backendUrl = import.meta.env.PROD ? '' : 'http://localhost:3001';
const displayAvatar = user.avatar_url
? (user.avatar_url.startsWith('http') ? user.avatar_url : `${backendUrl}${user.avatar_url}`)
: `https://ui-avatars.com/api/?name=${encodeURIComponent(user.name)}&background=random`;
return (
<div className="max-w-4xl mx-auto space-y-6 pb-12">
<div className="max-w-4xl mx-auto space-y-6 pb-12 transition-colors duration-300">
<div>
<h1 className="text-2xl font-bold text-slate-900 tracking-tight">Meu Perfil</h1>
<p className="text-slate-500 text-sm">Gerencie suas informações pessoais e preferências.</p>
<h1 className="text-2xl font-bold text-zinc-900 dark:text-zinc-50 tracking-tight">Meu Perfil</h1>
<p className="text-zinc-500 dark:text-zinc-400 text-sm">Gerencie suas informações pessoais e preferências.</p>
</div>
<div className="grid grid-cols-1 md:grid-cols-3 gap-8">
{/* Left Column: Avatar & Basic Info */}
<div className="md:col-span-1 space-y-6">
<div className="bg-white p-6 rounded-2xl shadow-sm border border-slate-200 flex flex-col items-center text-center">
<div className="relative group cursor-pointer">
<div className="w-32 h-32 rounded-full overflow-hidden border-4 border-slate-50 shadow-sm">
<img src={user.avatar_url || `https://ui-avatars.com/api/?name=${encodeURIComponent(user.name)}&background=random`} alt={user.name} className="w-full h-full object-cover" />
<div className="bg-white dark:bg-zinc-900 p-6 rounded-2xl shadow-sm border border-zinc-200 dark:border-zinc-800 flex flex-col items-center text-center">
<input
type="file"
ref={fileInputRef}
onChange={handleFileChange}
accept="image/jpeg,image/png,image/webp"
className="hidden"
/>
<div className="relative group cursor-pointer" onClick={handleAvatarClick}>
<div className="w-32 h-32 rounded-full overflow-hidden border-4 border-zinc-50 dark:border-zinc-800 shadow-sm bg-zinc-100 dark:bg-zinc-800 flex items-center justify-center">
{isUploading ? (
<Loader2 className="animate-spin text-zinc-400 dark:text-zinc-500" size={32} />
) : (
<img src={displayAvatar} alt={user.name} className="w-full h-full object-cover" />
)}
</div>
<div className="absolute inset-0 bg-black/40 rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity duration-200">
<Camera className="text-white" size={28} />
</div>
<button className="absolute bottom-0 right-2 bg-white text-slate-600 p-2 rounded-full shadow-md border border-slate-100 hover:text-blue-600 transition-colors">
<button className="absolute bottom-0 right-2 bg-white dark:bg-zinc-800 text-zinc-600 dark:text-zinc-400 p-2 rounded-full shadow-md border border-zinc-100 dark:border-zinc-700 hover:text-yellow-500 dark:hover:text-yellow-400 transition-colors">
<Camera size={16} />
</button>
</div>
<h2 className="mt-4 text-lg font-bold text-slate-900">{user.name}</h2>
<p className="text-slate-500 text-sm">{user.email}</p>
<h2 className="mt-4 text-lg font-bold text-zinc-900 dark:text-zinc-100">{user.name}</h2>
<p className="text-zinc-500 dark:text-zinc-400 text-sm">{user.email}</p>
<div className="mt-4 flex flex-wrap justify-center gap-2">
<span className="px-3 py-1 bg-purple-100 text-purple-700 rounded-full text-xs font-semibold capitalize border border-purple-200">
{user.role}
<span className="px-3 py-1 bg-purple-100 text-purple-700 rounded-full text-xs font-semibold capitalize border border-purple-200 dark:bg-purple-900/30 dark:text-purple-400 dark:border-purple-800">
{user.role === 'admin' ? 'Admin' : user.role === 'manager' ? 'Gerente' : user.role === 'super_admin' ? 'Super Admin' : 'Agente'}
</span>
{user.team_id && (
<span className="px-3 py-1 bg-blue-100 text-blue-700 rounded-full text-xs font-semibold border border-blue-200">
{user.team_id === 'sales_1' ? 'Vendas Alpha' : user.team_id === 'sales_2' ? 'Vendas Beta' : user.team_id}
<span className="px-3 py-1 bg-blue-100 text-blue-700 rounded-full text-xs font-semibold border border-blue-200 dark:bg-blue-900/30 dark:text-blue-400 dark:border-blue-800">
{tenant?.name ? `Time ${tenant.name}` : user.team_id}
</span>
)}
</div>
</div>
<div className="bg-slate-100 rounded-xl p-4 border border-slate-200">
<h3 className="text-xs font-bold text-slate-500 uppercase tracking-wider mb-3">Status da Conta</h3>
<div className="flex items-center gap-3 text-sm text-slate-600 mb-2">
<div className={`w-2 h-2 rounded-full ${user.status === 'active' ? 'bg-green-500' : 'bg-slate-400'}`}></div>
<div className="bg-zinc-100 dark:bg-zinc-900 rounded-xl p-4 border border-zinc-200 dark:border-zinc-800">
<h3 className="text-xs font-bold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider mb-3">Status da Conta</h3>
<div className="flex items-center gap-3 text-sm text-zinc-600 dark:text-zinc-300 mb-2">
<div className={`w-2 h-2 rounded-full ${user.status === 'active' ? 'bg-green-500' : 'bg-zinc-400'}`}></div>
{user.status === 'active' ? 'Ativo' : 'Inativo'}
</div>
<div className="flex items-center gap-3 text-sm text-slate-600">
<div className="flex items-center gap-3 text-sm text-zinc-600 dark:text-zinc-300">
<Building size={14} />
{tenant?.name || 'Organização'}
</div>
@@ -118,11 +165,11 @@ export const UserProfile: React.FC = () => {
{/* Right Column: Edit Form */}
<div className="md:col-span-2">
<div className="bg-white rounded-2xl shadow-sm border border-slate-200 overflow-hidden">
<div className="px-6 py-4 border-b border-slate-100 bg-slate-50/50 flex justify-between items-center">
<h3 className="font-bold text-slate-800">Informações Pessoais</h3>
<div className="bg-white dark:bg-zinc-900 rounded-2xl shadow-sm border border-zinc-200 dark:border-zinc-800 overflow-hidden">
<div className="px-6 py-4 border-b border-zinc-100 dark:border-zinc-800 bg-zinc-50/50 dark:bg-zinc-900/50 flex justify-between items-center">
<h3 className="font-bold text-zinc-800 dark:text-zinc-100">Informações Pessoais</h3>
{isSuccess && (
<span className="flex items-center gap-1.5 text-green-600 text-sm font-medium animate-in fade-in slide-in-from-right-4">
<span className="flex items-center gap-1.5 text-green-600 dark:text-green-400 text-sm font-medium animate-in fade-in slide-in-from-right-4">
<CheckCircle2 size={16} /> Salvo com sucesso
</span>
)}
@@ -131,63 +178,63 @@ export const UserProfile: React.FC = () => {
<form onSubmit={handleSubmit} className="p-6 space-y-6">
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div className="space-y-2">
<label htmlFor="fullName" className="block text-sm font-medium text-slate-700">
<label htmlFor="fullName" className="block text-sm font-medium text-zinc-700 dark:text-zinc-300">
Nome Completo
</label>
<div className="relative">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<UserIcon className="h-5 w-5 text-slate-400" />
<UserIcon className="h-5 w-5 text-zinc-400 dark:text-zinc-500" />
</div>
<input
type="text"
id="fullName"
value={name}
onChange={(e) => setName(e.target.value)}
className="block w-full pl-10 pr-3 py-2 border border-slate-200 rounded-lg bg-white text-slate-900 placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-100 focus:border-blue-500 sm:text-sm transition-all"
className="block w-full pl-10 pr-3 py-2 border border-zinc-200 dark:border-zinc-800 rounded-lg bg-white dark:bg-zinc-950 text-zinc-900 dark:text-zinc-100 placeholder-zinc-400 dark:placeholder-zinc-600 focus:outline-none focus:ring-2 focus:ring-yellow-400/20 focus:border-yellow-400 transition-all sm:text-sm"
/>
</div>
</div>
<div className="space-y-2">
<label htmlFor="email" className="block text-sm font-medium text-slate-700">
<label htmlFor="email" className="block text-sm font-medium text-zinc-700 dark:text-zinc-300">
Endereço de E-mail
</label>
<div className="relative">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<Mail className="h-5 w-5 text-slate-400" />
<Mail className="h-5 w-5 text-zinc-400 dark:text-zinc-500" />
</div>
<input
type="email"
id="email"
value={user.email}
disabled
className="block w-full pl-10 pr-3 py-2 border border-slate-200 rounded-lg bg-slate-50 text-slate-500 cursor-not-allowed sm:text-sm"
className="block w-full pl-10 pr-3 py-2 border border-zinc-200 dark:border-zinc-800 rounded-lg bg-zinc-50 dark:bg-zinc-900/50 text-zinc-500 dark:text-zinc-500 cursor-not-allowed sm:text-sm"
/>
</div>
<p className="text-xs text-slate-400 mt-1">Contate o admin para alterar o e-mail.</p>
<p className="text-xs text-zinc-400 dark:text-zinc-500 mt-1">Contate o admin para alterar o e-mail.</p>
</div>
</div>
<div className="space-y-2">
<label htmlFor="role" className="block text-sm font-medium text-slate-700">
<label htmlFor="role" className="block text-sm font-medium text-zinc-700 dark:text-zinc-300">
Função e Permissões
</label>
<div className="relative">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<Shield className="h-5 w-5 text-slate-400" />
<Shield className="h-5 w-5 text-zinc-400 dark:text-zinc-500" />
</div>
<input
type="text"
id="role"
value={user.role.charAt(0).toUpperCase() + user.role.slice(1)}
value={user.role === 'admin' ? 'Administrador' : user.role === 'manager' ? 'Gerente' : user.role === 'super_admin' ? 'Super Admin' : 'Agente'}
disabled
className="block w-full pl-10 pr-3 py-2 border border-slate-200 rounded-lg bg-slate-50 text-slate-500 cursor-not-allowed sm:text-sm"
className="block w-full pl-10 pr-3 py-2 border border-zinc-200 dark:border-zinc-800 rounded-lg bg-zinc-50 dark:bg-zinc-900/50 text-zinc-500 dark:text-zinc-500 cursor-not-allowed sm:text-sm"
/>
</div>
</div>
<div className="space-y-2">
<label htmlFor="bio" className="block text-sm font-medium text-slate-700">
<label htmlFor="bio" className="block text-sm font-medium text-zinc-700 dark:text-zinc-300">
Bio / Descrição
</label>
<textarea
@@ -195,27 +242,27 @@ export const UserProfile: React.FC = () => {
rows={4}
value={bio}
onChange={(e) => setBio(e.target.value)}
className="block w-full p-3 border border-slate-200 rounded-lg text-slate-900 placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-100 focus:border-blue-500 sm:text-sm transition-all resize-none"
className="block w-full p-3 border border-zinc-200 dark:border-zinc-800 rounded-lg bg-white dark:bg-zinc-950 text-zinc-900 dark:text-zinc-100 placeholder-zinc-400 dark:placeholder-zinc-600 focus:outline-none focus:ring-2 focus:ring-yellow-400/20 focus:border-yellow-400 transition-all sm:text-sm resize-none"
placeholder="Escreva uma breve descrição sobre você..."
/>
<p className="text-xs text-slate-400 text-right">{bio.length}/500 caracteres</p>
<p className="text-xs text-zinc-400 dark:text-zinc-500 text-right">{bio.length}/500 caracteres</p>
</div>
<div className="pt-4 flex items-center justify-end border-t border-slate-100 mt-6">
<div className="pt-4 flex items-center justify-end border-t border-zinc-100 dark:border-zinc-800 mt-6 transition-colors">
<button
type="button"
onClick={() => {
setName(user.name);
setBio(user.bio || '');
}}
className="mr-3 px-4 py-2 text-sm font-medium text-slate-600 hover:text-slate-800 hover:bg-slate-50 rounded-lg transition-colors"
className="mr-3 px-4 py-2 text-sm font-medium text-zinc-600 dark:text-zinc-400 hover:text-zinc-800 dark:hover:text-zinc-200 hover:bg-zinc-50 dark:hover:bg-zinc-800 rounded-lg transition-colors"
>
Desfazer Alterações
</button>
<button
type="submit"
disabled={isLoading}
className="flex items-center gap-2 bg-slate-900 text-white px-6 py-2 rounded-lg text-sm font-medium hover:bg-slate-800 focus:ring-2 focus:ring-offset-2 focus:ring-slate-900 transition-all disabled:opacity-70 disabled:cursor-not-allowed"
className="flex items-center gap-2 bg-zinc-900 dark:bg-yellow-400 text-white dark:text-zinc-950 px-6 py-2 rounded-lg text-sm font-medium hover:bg-zinc-800 dark:hover:opacity-90 focus:ring-2 focus:ring-offset-2 focus:ring-zinc-900 dark:focus:ring-yellow-400 transition-all disabled:opacity-70 disabled:cursor-not-allowed"
>
{isLoading ? (
<>
@@ -234,4 +281,4 @@ export const UserProfile: React.FC = () => {
</div>
</div>
);
};
};

View File

@@ -1,35 +1,27 @@
import React, { useState, useEffect } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { Hexagon, ShieldCheck, ArrowRight, Loader2 } from 'lucide-react';
import React, { useState } from 'react';
import { useNavigate, Link, useLocation } from 'react-router-dom';
import { Hexagon, ArrowRight, Loader2, AlertCircle, CheckCircle2 } from 'lucide-react';
import { verifyCode } from '../services/dataService';
export const VerifyCode: React.FC = () => {
const navigate = useNavigate();
const [isLoading, setIsLoading] = useState(false);
const location = useLocation();
const email = location.state?.email || '';
const [code, setCode] = useState('');
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState('');
const [email, setEmail] = useState('');
useEffect(() => {
const storedEmail = localStorage.getItem('pending_verify_email');
if (!storedEmail) {
navigate('/register');
} else {
setEmail(storedEmail);
}
}, [navigate]);
const handleVerify = async (e: React.FormEvent) => {
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!email) { setError('E-mail não encontrado. Tente registrar novamente.'); return; }
setIsLoading(true);
setError('');
try {
const success = await verifyCode({ email, code });
if (success) {
localStorage.removeItem('pending_verify_email');
alert('Conta verificada com sucesso! Agora você pode fazer login.');
navigate('/login');
navigate('/login', { state: { message: 'E-mail verificado com sucesso! Agora você pode entrar.' } });
}
} catch (err: any) {
setError(err.message || 'Código inválido ou expirado.');
@@ -39,28 +31,34 @@ export const VerifyCode: React.FC = () => {
};
return (
<div className="min-h-screen bg-slate-50 flex flex-col justify-center py-12 sm:px-6 lg:px-8">
<div className="min-h-screen bg-zinc-50 dark:bg-dark-bg flex flex-col justify-center py-12 sm:px-6 lg:px-8 transition-colors duration-300">
<div className="sm:mx-auto sm:w-full sm:max-w-md">
<div className="flex justify-center items-center gap-2 text-slate-900">
<div className="bg-slate-900 text-white p-2 rounded-lg">
<Hexagon size={28} fill="currentColor" />
<div className="flex justify-center items-center gap-2 text-zinc-900 dark:text-zinc-50">
<div className="bg-zinc-900 dark:bg-brand-yellow text-white dark:text-zinc-950 p-2 rounded-lg transition-colors">
<Hexagon size={32} fill="currentColor" />
</div>
<span className="text-3xl font-bold tracking-tight">Fasto<span className="text-yellow-500">.</span></span>
<span className="text-3xl font-bold tracking-tight">Fasto<span className="text-brand-yellow">.</span></span>
</div>
<h2 className="mt-6 text-center text-3xl font-bold tracking-tight text-slate-900">
<h2 className="mt-6 text-center text-3xl font-bold tracking-tight text-zinc-900 dark:text-zinc-50">
Verifique seu e-mail
</h2>
<p className="mt-2 text-center text-sm text-slate-600 px-4">
Enviamos um código de 6 dígitos para <strong>{email}</strong>. Por favor, insira-o abaixo.
<p className="mt-2 text-center text-sm text-zinc-600 dark:text-dark-muted px-4">
Insira o código de 6 dígitos enviado para <span className="font-semibold text-zinc-900 dark:text-zinc-200">{email}</span>
</p>
</div>
<div className="mt-8 sm:mx-auto sm:w-full sm:max-w-md">
<div className="bg-white py-8 px-4 shadow-xl shadow-slate-200/50 rounded-2xl sm:px-10 border border-slate-100">
<form className="space-y-6" onSubmit={handleVerify}>
<div className="bg-white dark:bg-dark-card py-8 px-4 shadow-xl rounded-2xl sm:px-10 border border-zinc-100 dark:border-dark-border transition-colors">
<form className="space-y-6" onSubmit={handleSubmit}>
{error && (
<div className="bg-red-50 dark:bg-red-900/20 border border-red-100 dark:border-red-900/30 p-3 rounded-lg text-red-600 dark:text-red-400 text-sm">
<AlertCircle size={18} />
{error}
</div>
)}
<div>
<label htmlFor="code" className="block text-sm font-medium text-slate-700 text-center mb-4">
<label htmlFor="code" className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 text-center mb-4">
Código de Verificação
</label>
<input
@@ -69,32 +67,23 @@ export const VerifyCode: React.FC = () => {
maxLength={6}
required
value={code}
onChange={(e) => setCode(e.target.value.replace(/\D/g, ''))}
className="block w-full text-center text-3xl tracking-[0.5em] font-bold py-3 border border-slate-300 rounded-lg bg-slate-50 focus:outline-none focus:ring-2 focus:ring-blue-100 focus:border-blue-500 transition-all"
onChange={(e) => setCode(e.target.value.replace(/[^0-9]/g, ''))}
className="block w-full text-center text-3xl tracking-[0.5em] font-bold py-3 border border-zinc-300 dark:border-dark-border rounded-lg bg-zinc-50 dark:bg-dark-input text-zinc-900 dark:text-zinc-100 focus:outline-none focus:ring-2 focus:ring-brand-yellow/20 focus:border-brand-yellow transition-all"
placeholder="000000"
/>
</div>
{error && (
<div className="text-red-500 text-sm font-medium text-center">
{error}
</div>
)}
<div>
<button
type="submit"
disabled={isLoading || code.length !== 6}
className="w-full flex justify-center items-center gap-2 py-2.5 px-4 border border-transparent rounded-lg shadow-sm text-sm font-semibold text-white bg-slate-900 hover:bg-slate-800 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-slate-900 disabled:opacity-70 disabled:cursor-not-allowed transition-all"
disabled={isLoading || code.length < 6}
className="w-full flex justify-center items-center gap-2 py-2.5 px-4 border border-transparent rounded-lg shadow-sm text-sm font-bold text-zinc-950 bg-brand-yellow hover:bg-yellow-500 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-brand-yellow disabled:opacity-70 disabled:cursor-not-allowed transition-all"
>
{isLoading ? (
<>
<Loader2 className="animate-spin h-4 w-4" />
Verificando...
</>
<Loader2 className="animate-spin h-5 w-5" />
) : (
<>
Verificar Código <ShieldCheck className="h-4 w-4" />
Verificar Código <ArrowRight size={18} />
</>
)}
</button>
@@ -103,10 +92,11 @@ export const VerifyCode: React.FC = () => {
<div className="mt-6 text-center">
<button
type="button"
className="text-sm font-medium text-brand-yellow hover:text-yellow-600 transition-colors"
onClick={() => navigate('/register')}
className="text-sm text-slate-500 hover:text-slate-800"
>
Alterar e-mail ou voltar ao registro
Voltar e corrigir e-mail
</button>
</div>
</div>

View File

@@ -6,6 +6,17 @@ import { Attendance, DashboardFilter, User } from '../types';
// Em desenvolvimento, aponta para o localhost:3001
const API_URL = import.meta.env.PROD ? '/api' : 'http://localhost:3001/api';
const getHeaders = () => {
const token = localStorage.getItem('ctms_token');
// Evitar enviar "undefined" ou "null" como strings se o localStorage estiver corrompido
if (!token || token === 'undefined' || token === 'null') return { 'Content-Type': 'application/json' };
return {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
};
};
export const getAttendances = async (tenantId: string, filter: DashboardFilter): Promise<Attendance[]> => {
try {
const params = new URLSearchParams();
@@ -16,8 +27,12 @@ export const getAttendances = async (tenantId: string, filter: DashboardFilter):
if (filter.userId && filter.userId !== 'all') params.append('userId', filter.userId);
if (filter.teamId && filter.teamId !== 'all') params.append('teamId', filter.teamId);
if (filter.funnelStage && filter.funnelStage !== 'all') params.append('funnelStage', filter.funnelStage);
if (filter.origin && filter.origin !== 'all') params.append('origin', filter.origin);
const response = await fetch(`${API_URL}/attendances?${params.toString()}`);
const response = await fetch(`${API_URL}/attendances?${params.toString()}`, {
headers: getHeaders()
});
if (!response.ok) {
throw new Error('Falha ao buscar atendimentos do servidor');
@@ -36,7 +51,9 @@ export const getUsers = async (tenantId: string): Promise<User[]> => {
const params = new URLSearchParams();
if (tenantId !== 'all') params.append('tenantId', tenantId);
const response = await fetch(`${API_URL}/users?${params.toString()}`);
const response = await fetch(`${API_URL}/users?${params.toString()}`, {
headers: getHeaders()
});
if (!response.ok) throw new Error('Falha ao buscar usuários');
return await response.json();
@@ -48,7 +65,9 @@ export const getUsers = async (tenantId: string): Promise<User[]> => {
export const getUserById = async (id: string): Promise<User | undefined> => {
try {
const response = await fetch(`${API_URL}/users/${id}`);
const response = await fetch(`${API_URL}/users/${id}`, {
headers: getHeaders()
});
if (!response.ok) return undefined;
const contentType = response.headers.get("content-type");
@@ -66,7 +85,7 @@ export const updateUser = async (id: string, userData: any): Promise<boolean> =>
try {
const response = await fetch(`${API_URL}/users/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
headers: getHeaders(),
body: JSON.stringify(userData)
});
return response.ok;
@@ -76,11 +95,34 @@ export const updateUser = async (id: string, userData: any): Promise<boolean> =>
}
};
export const uploadAvatar = async (id: string, file: File): Promise<string | null> => {
try {
const formData = new FormData();
formData.append('avatar', file);
const token = localStorage.getItem('ctms_token');
const response = await fetch(`${API_URL}/users/${id}/avatar`, {
method: 'POST',
headers: {
...(token ? { 'Authorization': `Bearer ${token}` } : {})
},
body: formData
});
if (!response.ok) throw new Error('Falha no upload');
const data = await response.json();
return data.avatarUrl;
} catch (error) {
console.error("API Error (uploadAvatar):", error);
return null;
}
};
export const createMember = async (userData: any): Promise<boolean> => {
try {
const response = await fetch(`${API_URL}/users`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
headers: getHeaders(),
body: JSON.stringify(userData)
});
return response.ok;
@@ -93,7 +135,8 @@ export const createMember = async (userData: any): Promise<boolean> => {
export const deleteUser = async (id: string): Promise<boolean> => {
try {
const response = await fetch(`${API_URL}/users/${id}`, {
method: 'DELETE'
method: 'DELETE',
headers: getHeaders()
});
return response.ok;
} catch (error) {
@@ -104,7 +147,9 @@ export const deleteUser = async (id: string): Promise<boolean> => {
export const getAttendanceById = async (id: string): Promise<Attendance | undefined> => {
try {
const response = await fetch(`${API_URL}/attendances/${id}`);
const response = await fetch(`${API_URL}/attendances/${id}`, {
headers: getHeaders()
});
if (!response.ok) return undefined;
const contentType = response.headers.get("content-type");
@@ -120,7 +165,9 @@ export const getAttendanceById = async (id: string): Promise<Attendance | undefi
export const getTenants = async (): Promise<any[]> => {
try {
const response = await fetch(`${API_URL}/tenants`);
const response = await fetch(`${API_URL}/tenants`, {
headers: getHeaders()
});
if (!response.ok) throw new Error('Falha ao buscar tenants');
const contentType = response.headers.get("content-type");
@@ -136,7 +183,9 @@ export const getTenants = async (): Promise<any[]> => {
export const getTeams = async (tenantId: string): Promise<any[]> => {
try {
const response = await fetch(`${API_URL}/teams?tenantId=${tenantId}`);
const response = await fetch(`${API_URL}/teams?tenantId=${tenantId}`, {
headers: getHeaders()
});
if (!response.ok) throw new Error('Falha ao buscar equipes');
return await response.json();
} catch (error) {
@@ -149,7 +198,7 @@ export const createTeam = async (teamData: any): Promise<boolean> => {
try {
const response = await fetch(`${API_URL}/teams`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
headers: getHeaders(),
body: JSON.stringify(teamData)
});
return response.ok;
@@ -163,7 +212,7 @@ export const updateTeam = async (id: string, teamData: any): Promise<boolean> =>
try {
const response = await fetch(`${API_URL}/teams/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
headers: getHeaders(),
body: JSON.stringify(teamData)
});
return response.ok;
@@ -177,7 +226,7 @@ export const createTenant = async (tenantData: any): Promise<boolean> => {
try {
const response = await fetch(`${API_URL}/tenants`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
headers: getHeaders(),
body: JSON.stringify(tenantData)
});
return response.ok;
@@ -189,6 +238,12 @@ export const createTenant = async (tenantData: any): Promise<boolean> => {
// --- Auth Functions ---
export const logout = () => {
localStorage.removeItem('ctms_token');
localStorage.removeItem('ctms_user_id');
localStorage.removeItem('ctms_tenant_id');
};
export const login = async (credentials: any): Promise<any> => {
const response = await fetch(`${API_URL}/auth/login`, {
method: 'POST',
@@ -204,7 +259,13 @@ export const login = async (credentials: any): Promise<any> => {
throw new Error(error.error || 'Erro no login');
}
return isJson ? await response.json() : null;
const data = isJson ? await response.json() : null;
if (data && data.token) {
localStorage.setItem('ctms_token', data.token);
localStorage.setItem('ctms_user_id', data.user.id);
localStorage.setItem('ctms_tenant_id', data.user.tenant_id || '');
}
return data;
};
export const register = async (userData: any): Promise<boolean> => {

View File

@@ -11,7 +11,8 @@
],
"skipLibCheck": true,
"types": [
"node"
"node",
"vite/client"
],
"moduleResolution": "bundler",
"isolatedModules": true,

View File

@@ -31,7 +31,7 @@ export interface Attendance {
first_response_time_min: number;
handling_time_min: number;
funnel_stage: FunnelStage;
origin: 'WhatsApp' | 'Instagram' | 'Website' | 'LinkedIn' | 'Referral';
origin: 'WhatsApp' | 'Instagram' | 'Website' | 'LinkedIn' | 'Indicação';
product_requested: string;
product_sold?: string;
converted: boolean;
@@ -59,4 +59,6 @@ export interface DashboardFilter {
dateRange: DateRange;
userId?: string;
teamId?: string;
funnelStage?: string;
origin?: string;
}