feat: Implement backend API and basic frontend structure
Adds initial backend API endpoints for fetching users and attendances, including basic filtering. Sets up the frontend routing with a layout component and includes placeholder pages for dashboard, users, and login. Refactors the README for local development setup.
This commit is contained in:
24
.gitignore
vendored
Normal file
24
.gitignore
vendored
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
# Logs
|
||||||
|
logs
|
||||||
|
*.log
|
||||||
|
npm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
pnpm-debug.log*
|
||||||
|
lerna-debug.log*
|
||||||
|
|
||||||
|
node_modules
|
||||||
|
dist
|
||||||
|
dist-ssr
|
||||||
|
*.local
|
||||||
|
|
||||||
|
# Editor directories and files
|
||||||
|
.vscode/*
|
||||||
|
!.vscode/extensions.json
|
||||||
|
.idea
|
||||||
|
.DS_Store
|
||||||
|
*.suo
|
||||||
|
*.ntvs*
|
||||||
|
*.njsproj
|
||||||
|
*.sln
|
||||||
|
*.sw?
|
||||||
43
App.tsx
Normal file
43
App.tsx
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { HashRouter as Router, Routes, Route, Navigate, useLocation } from 'react-router-dom';
|
||||||
|
import { Layout } from './components/Layout';
|
||||||
|
import { Dashboard } from './pages/Dashboard';
|
||||||
|
import { UserDetail } from './pages/UserDetail';
|
||||||
|
import { AttendanceDetail } from './pages/AttendanceDetail';
|
||||||
|
import { SuperAdmin } from './pages/SuperAdmin';
|
||||||
|
import { TeamManagement } from './pages/TeamManagement';
|
||||||
|
import { Login } from './pages/Login';
|
||||||
|
import { UserProfile } from './pages/UserProfile';
|
||||||
|
|
||||||
|
const AppLayout: React.FC<{ children: React.ReactNode }> = ({ children }) => {
|
||||||
|
const location = useLocation();
|
||||||
|
const isLoginPage = location.pathname === '/login';
|
||||||
|
|
||||||
|
if (isLoginPage) {
|
||||||
|
return <>{children}</>;
|
||||||
|
}
|
||||||
|
|
||||||
|
return <Layout>{children}</Layout>;
|
||||||
|
};
|
||||||
|
|
||||||
|
const App: React.FC = () => {
|
||||||
|
return (
|
||||||
|
<Router>
|
||||||
|
<AppLayout>
|
||||||
|
<Routes>
|
||||||
|
<Route path="/login" element={<Login />} />
|
||||||
|
<Route path="/" element={<Dashboard />} />
|
||||||
|
<Route path="/users" element={<Navigate to="/admin/users" replace />} />
|
||||||
|
<Route path="/admin/users" element={<TeamManagement />} />
|
||||||
|
<Route path="/users/:id" element={<UserDetail />} />
|
||||||
|
<Route path="/attendances/:id" element={<AttendanceDetail />} />
|
||||||
|
<Route path="/super-admin" element={<SuperAdmin />} />
|
||||||
|
<Route path="/profile" element={<UserProfile />} />
|
||||||
|
<Route path="*" element={<Navigate to="/" replace />} />
|
||||||
|
</Routes>
|
||||||
|
</AppLayout>
|
||||||
|
</Router>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default App;
|
||||||
25
README.md
25
README.md
@@ -1,11 +1,20 @@
|
|||||||
<div align="center">
|
<div align="center">
|
||||||
|
|
||||||
<img width="1200" height="475" alt="GHBanner" src="https://github.com/user-attachments/assets/0aa67016-6eaf-458a-adb2-6e31a0763ed6" />
|
<img width="1200" height="475" alt="GHBanner" src="https://github.com/user-attachments/assets/0aa67016-6eaf-458a-adb2-6e31a0763ed6" />
|
||||||
|
|
||||||
<h1>Built with AI Studio</h2>
|
|
||||||
|
|
||||||
<p>The fastest path from prompt to production with Gemini.</p>
|
|
||||||
|
|
||||||
<a href="https://aistudio.google.com/apps">Start building</a>
|
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
# Run and deploy your AI Studio app
|
||||||
|
|
||||||
|
This contains everything you need to run your app locally.
|
||||||
|
|
||||||
|
View your app in AI Studio: https://ai.studio/apps/3aacfdea-56fa-4154-a6b9-09ebdedfa306
|
||||||
|
|
||||||
|
## Run Locally
|
||||||
|
|
||||||
|
**Prerequisites:** Node.js
|
||||||
|
|
||||||
|
|
||||||
|
1. Install dependencies:
|
||||||
|
`npm install`
|
||||||
|
2. Set the `GEMINI_API_KEY` in [.env.local](.env.local) to your Gemini API key
|
||||||
|
3. Run the app:
|
||||||
|
`npm run dev`
|
||||||
|
|||||||
28
backend/db.js
Normal file
28
backend/db.js
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
|
||||||
|
const mysql = require('mysql2/promise');
|
||||||
|
|
||||||
|
// Configuração da conexão com o banco de dados
|
||||||
|
// Em produção, estes valores devem vir de variáveis de ambiente (.env)
|
||||||
|
const pool = mysql.createPool({
|
||||||
|
host: '162.240.103.190',
|
||||||
|
user: 'agenciac_comia',
|
||||||
|
password: 'Blyzer@2025#',
|
||||||
|
database: 'agenciac_comia',
|
||||||
|
waitForConnections: true,
|
||||||
|
connectionLimit: 10,
|
||||||
|
queueLimit: 0,
|
||||||
|
// Opções de SSL podem ser necessárias dependendo do servidor,
|
||||||
|
// mas vamos tentar sem SSL inicialmente dado o host.
|
||||||
|
});
|
||||||
|
|
||||||
|
// Teste de conexão simples ao iniciar
|
||||||
|
pool.getConnection()
|
||||||
|
.then(connection => {
|
||||||
|
console.log('✅ Conectado ao MySQL com sucesso!');
|
||||||
|
connection.release();
|
||||||
|
})
|
||||||
|
.catch(err => {
|
||||||
|
console.error('❌ Erro ao conectar ao MySQL:', err.message);
|
||||||
|
});
|
||||||
|
|
||||||
|
module.exports = pool;
|
||||||
130
backend/index.js
Normal file
130
backend/index.js
Normal file
@@ -0,0 +1,130 @@
|
|||||||
|
|
||||||
|
const express = require('express');
|
||||||
|
const cors = require('cors');
|
||||||
|
const pool = require('./db');
|
||||||
|
|
||||||
|
const app = express();
|
||||||
|
const PORT = 3001; // Porta do backend
|
||||||
|
|
||||||
|
app.use(cors()); // Permite que o React (localhost:3000) acesse este servidor
|
||||||
|
app.use(express.json());
|
||||||
|
|
||||||
|
// --- Rotas de Usuários ---
|
||||||
|
|
||||||
|
// Listar Usuários (com filtro opcional de tenant)
|
||||||
|
app.get('/api/users', async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { tenantId } = req.query;
|
||||||
|
let query = 'SELECT * FROM users';
|
||||||
|
const params = [];
|
||||||
|
|
||||||
|
if (tenantId && tenantId !== 'all') {
|
||||||
|
query += ' WHERE tenant_id = ?';
|
||||||
|
params.push(tenantId);
|
||||||
|
}
|
||||||
|
|
||||||
|
const [rows] = await pool.query(query, params);
|
||||||
|
res.json(rows);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Erro ao buscar usuários:', error);
|
||||||
|
res.status(500).json({ error: error.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Detalhe do Usuário
|
||||||
|
app.get('/api/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({ message: 'User not found' });
|
||||||
|
res.json(rows[0]);
|
||||||
|
} catch (error) {
|
||||||
|
res.status(500).json({ error: error.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- Rotas de Atendimentos ---
|
||||||
|
|
||||||
|
// Listar Atendimentos (Dashboard)
|
||||||
|
app.get('/api/attendances', async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { tenantId, userId, teamId, startDate, endDate } = req.query;
|
||||||
|
|
||||||
|
let query = `
|
||||||
|
SELECT a.*, u.team_id
|
||||||
|
FROM attendances a
|
||||||
|
JOIN users u ON a.user_id = u.id
|
||||||
|
WHERE a.tenant_id = ?
|
||||||
|
`;
|
||||||
|
const params = [tenantId];
|
||||||
|
|
||||||
|
// Filtro de Data
|
||||||
|
if (startDate && endDate) {
|
||||||
|
query += ' AND a.created_at BETWEEN ? AND ?';
|
||||||
|
params.push(new Date(startDate), new Date(endDate));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Filtro de Usuário
|
||||||
|
if (userId && userId !== 'all') {
|
||||||
|
query += ' AND a.user_id = ?';
|
||||||
|
params.push(userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Filtro de Time (baseado na tabela users ou teams)
|
||||||
|
if (teamId && teamId !== 'all') {
|
||||||
|
query += ' AND u.team_id = ?';
|
||||||
|
params.push(teamId);
|
||||||
|
}
|
||||||
|
|
||||||
|
query += ' ORDER BY a.created_at DESC';
|
||||||
|
|
||||||
|
const [rows] = await pool.query(query, params);
|
||||||
|
|
||||||
|
// Tratamento de campos JSON se o MySQL retornar como string
|
||||||
|
const processedRows = rows.map(row => ({
|
||||||
|
...row,
|
||||||
|
attention_points: typeof row.attention_points === 'string' ? JSON.parse(row.attention_points) : row.attention_points,
|
||||||
|
improvement_points: typeof row.improvement_points === 'string' ? JSON.parse(row.improvement_points) : row.improvement_points,
|
||||||
|
converted: Boolean(row.converted) // Garantir booleano
|
||||||
|
}));
|
||||||
|
|
||||||
|
res.json(processedRows);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Erro ao buscar atendimentos:', error);
|
||||||
|
res.status(500).json({ error: error.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Detalhe do Atendimento
|
||||||
|
app.get('/api/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({ message: 'Attendance not found' });
|
||||||
|
|
||||||
|
const row = rows[0];
|
||||||
|
const processedRow = {
|
||||||
|
...row,
|
||||||
|
attention_points: typeof row.attention_points === 'string' ? JSON.parse(row.attention_points) : row.attention_points,
|
||||||
|
improvement_points: typeof row.improvement_points === 'string' ? JSON.parse(row.improvement_points) : row.improvement_points,
|
||||||
|
converted: Boolean(row.converted)
|
||||||
|
};
|
||||||
|
|
||||||
|
res.json(processedRow);
|
||||||
|
} catch (error) {
|
||||||
|
res.status(500).json({ error: error.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- Rotas de Tenants (Super Admin) ---
|
||||||
|
app.get('/api/tenants', async (req, res) => {
|
||||||
|
try {
|
||||||
|
const [rows] = await pool.query('SELECT * FROM tenants');
|
||||||
|
res.json(rows);
|
||||||
|
} catch (error) {
|
||||||
|
res.status(500).json({ error: error.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
app.listen(PORT, () => {
|
||||||
|
console.log(`🚀 Servidor Backend rodando em http://localhost:${PORT}`);
|
||||||
|
});
|
||||||
49
components/DateRangePicker.tsx
Normal file
49
components/DateRangePicker.tsx
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { Calendar } from 'lucide-react';
|
||||||
|
import { DateRange } from '../types';
|
||||||
|
|
||||||
|
interface DateRangePickerProps {
|
||||||
|
dateRange: DateRange;
|
||||||
|
onChange: (range: DateRange) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const DateRangePicker: React.FC<DateRangePickerProps> = ({ dateRange, onChange }) => {
|
||||||
|
const formatDateForInput = (date: Date) => {
|
||||||
|
return date.toISOString().split('T')[0];
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleStartChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
|
const newStart = new Date(e.target.value);
|
||||||
|
if (!isNaN(newStart.getTime())) {
|
||||||
|
onChange({ ...dateRange, start: newStart });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleEndChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
|
const newEnd = new Date(e.target.value);
|
||||||
|
if (!isNaN(newEnd.getTime())) {
|
||||||
|
onChange({ ...dateRange, end: newEnd });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
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 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"
|
||||||
|
/>
|
||||||
|
<span className="text-slate-400">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"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
41
components/KPICard.tsx
Normal file
41
components/KPICard.tsx
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { LucideIcon } from 'lucide-react';
|
||||||
|
|
||||||
|
interface KPICardProps {
|
||||||
|
title: string;
|
||||||
|
value: string | number;
|
||||||
|
subValue?: string;
|
||||||
|
trend?: 'up' | 'down' | 'neutral';
|
||||||
|
trendValue?: string;
|
||||||
|
icon: LucideIcon;
|
||||||
|
colorClass?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const KPICard: React.FC<KPICardProps> = ({ title, value, subValue, trend, trendValue, icon: Icon, colorClass = "bg-blue-500" }) => {
|
||||||
|
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="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>
|
||||||
|
</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>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{(trend || subValue) && (
|
||||||
|
<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>}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
171
components/Layout.tsx
Normal file
171
components/Layout.tsx
Normal file
@@ -0,0 +1,171 @@
|
|||||||
|
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 { USERS } from '../constants';
|
||||||
|
import { User } from '../types';
|
||||||
|
|
||||||
|
const SidebarItem = ({ to, icon: Icon, label, collapsed }: { to: string, icon: any, label: string, collapsed: boolean }) => (
|
||||||
|
<NavLink
|
||||||
|
to={to}
|
||||||
|
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'
|
||||||
|
}`
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<Icon size={20} className="shrink-0" />
|
||||||
|
{!collapsed && <span>{label}</span>}
|
||||||
|
</NavLink>
|
||||||
|
);
|
||||||
|
|
||||||
|
export const Layout: React.FC<{ children: React.ReactNode }> = ({ children }) => {
|
||||||
|
const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
|
||||||
|
const location = useLocation();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const [currentUser, setCurrentUser] = useState<User>(USERS[1]); // Default to standard user fallback
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const storedUserId = localStorage.getItem('ctms_user_id');
|
||||||
|
if (storedUserId) {
|
||||||
|
const user = USERS.find(u => u.id === storedUserId);
|
||||||
|
if (user) {
|
||||||
|
setCurrentUser(user);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleLogout = () => {
|
||||||
|
localStorage.removeItem('ctms_user_id');
|
||||||
|
navigate('/login');
|
||||||
|
};
|
||||||
|
|
||||||
|
// Simple title mapping based on route
|
||||||
|
const getPageTitle = () => {
|
||||||
|
if (location.pathname === '/') return 'Dashboard';
|
||||||
|
if (location.pathname.includes('/admin/users')) return 'Gestão de Equipe';
|
||||||
|
if (location.pathname.includes('/users/')) return 'Histórico do Usuário';
|
||||||
|
if (location.pathname.includes('/attendances')) return 'Detalhes do Atendimento';
|
||||||
|
if (location.pathname.includes('/super-admin')) return 'Gestão de Organizações';
|
||||||
|
if (location.pathname.includes('/profile')) return 'Meu Perfil';
|
||||||
|
return 'CTMS';
|
||||||
|
};
|
||||||
|
|
||||||
|
const isSuperAdmin = currentUser.role === 'super_admin';
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex h-screen bg-slate-50 overflow-hidden">
|
||||||
|
{/* 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 ${
|
||||||
|
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">
|
||||||
|
<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">
|
||||||
|
<X size={24} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Navigation */}
|
||||||
|
<nav className="flex-1 px-4 py-6 space-y-2">
|
||||||
|
|
||||||
|
{/* Standard User Links */}
|
||||||
|
{!isSuperAdmin && (
|
||||||
|
<>
|
||||||
|
<SidebarItem to="/" icon={LayoutDashboard} label="Dashboard" collapsed={false} />
|
||||||
|
<SidebarItem to="/admin/users" icon={Users} label="Equipe" collapsed={false} />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Super Admin Links */}
|
||||||
|
{isSuperAdmin && (
|
||||||
|
<>
|
||||||
|
<div className="pt-2 pb-2 px-4 text-xs font-semibold text-slate-400 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>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={handleLogout}
|
||||||
|
className="text-slate-400 hover:text-red-500 transition-colors"
|
||||||
|
title="Sair"
|
||||||
|
>
|
||||||
|
<LogOut size={18} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
|
||||||
|
{/* 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">
|
||||||
|
<div className="flex items-center gap-4">
|
||||||
|
<button onClick={() => setIsMobileMenuOpen(true)} className="lg:hidden text-slate-500 hover:text-slate-900">
|
||||||
|
<Menu size={24} />
|
||||||
|
</button>
|
||||||
|
<h1 className="text-xl font-bold text-slate-800 hidden sm:block">{getPageTitle()}</h1>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-4 sm:gap-6">
|
||||||
|
{/* 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" />
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
placeholder="Buscar..."
|
||||||
|
className="bg-transparent border-none outline-none text-sm ml-2 w-full text-slate-700 placeholder-slate-400"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Notifications */}
|
||||||
|
<div className="relative">
|
||||||
|
<button className="p-2 text-slate-500 hover:bg-slate-100 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>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
{/* Scrollable Content Area */}
|
||||||
|
<main className="flex-1 overflow-y-auto p-4 sm:p-8">
|
||||||
|
{children}
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Overlay for mobile */}
|
||||||
|
{isMobileMenuOpen && (
|
||||||
|
<div
|
||||||
|
className="fixed inset-0 bg-slate-900/50 z-40 lg:hidden"
|
||||||
|
onClick={() => setIsMobileMenuOpen(false)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
60
components/ProductLists.tsx
Normal file
60
components/ProductLists.tsx
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
import React, { useState } from 'react';
|
||||||
|
import { ShoppingBag, TrendingUp } from 'lucide-react';
|
||||||
|
|
||||||
|
interface ProductStat {
|
||||||
|
name: string;
|
||||||
|
count: number;
|
||||||
|
percentage: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ProductListsProps {
|
||||||
|
requested: ProductStat[];
|
||||||
|
sold: ProductStat[];
|
||||||
|
}
|
||||||
|
|
||||||
|
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="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'}`}>
|
||||||
|
<Icon size={18} />
|
||||||
|
</div>
|
||||||
|
<h3 className="font-bold text-slate-800">{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'}`}>
|
||||||
|
{idx + 1}
|
||||||
|
</span>
|
||||||
|
<span className="text-sm font-medium text-slate-700 group-hover:text-slate-900">{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>
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
{data.length === 0 && <li className="text-sm text-slate-400 italic">Nenhum dado disponível.</li>}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||||
|
<ListSection
|
||||||
|
title="Produtos Mais Solicitados"
|
||||||
|
icon={ShoppingBag}
|
||||||
|
data={requested}
|
||||||
|
color="blue"
|
||||||
|
/>
|
||||||
|
<ListSection
|
||||||
|
title="Produtos Mais Vendidos"
|
||||||
|
icon={TrendingUp}
|
||||||
|
data={sold}
|
||||||
|
color="green"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
148
components/SellersTable.tsx
Normal file
148
components/SellersTable.tsx
Normal file
@@ -0,0 +1,148 @@
|
|||||||
|
import React, { useState, useMemo } from 'react';
|
||||||
|
import { useNavigate } from 'react-router-dom';
|
||||||
|
import { ChevronDown, ChevronUp, ChevronsUpDown } from 'lucide-react';
|
||||||
|
import { User } from '../types';
|
||||||
|
|
||||||
|
interface SellerStat {
|
||||||
|
user: User;
|
||||||
|
total: number;
|
||||||
|
avgScore: string;
|
||||||
|
conversionRate: string;
|
||||||
|
responseTime: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
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 [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('desc');
|
||||||
|
|
||||||
|
const handleSort = (key: SortKey) => {
|
||||||
|
if (sortKey === key) {
|
||||||
|
setSortDirection(prev => prev === 'asc' ? 'desc' : 'asc');
|
||||||
|
} else {
|
||||||
|
setSortKey(key);
|
||||||
|
setSortDirection('desc');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
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" />;
|
||||||
|
};
|
||||||
|
|
||||||
|
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>
|
||||||
|
<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">
|
||||||
|
<th
|
||||||
|
className="px-6 py-4 font-semibold cursor-pointer hover:bg-slate-50 select-none"
|
||||||
|
onClick={() => handleSort('name')}
|
||||||
|
>
|
||||||
|
<div className="flex items-center gap-2">Usuário <SortIcon column="name" /></div>
|
||||||
|
</th>
|
||||||
|
<th
|
||||||
|
className="px-6 py-4 font-semibold text-center cursor-pointer hover:bg-slate-50 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"
|
||||||
|
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"
|
||||||
|
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"
|
||||||
|
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">
|
||||||
|
{sortedData.map((item, idx) => (
|
||||||
|
<tr
|
||||||
|
key={item.user.id}
|
||||||
|
className="hover:bg-blue-50/30 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" />
|
||||||
|
<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>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
<td className="px-6 py-4 text-center text-slate-600 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'}`}>
|
||||||
|
{item.avgScore}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td className="px-6 py-4 text-center text-slate-600 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>
|
||||||
|
<span className="text-xs font-semibold text-slate-700">{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>
|
||||||
|
</tr>
|
||||||
|
)}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
173
constants.ts
Normal file
173
constants.ts
Normal file
@@ -0,0 +1,173 @@
|
|||||||
|
|
||||||
|
import { Attendance, FunnelStage, Tenant, User } from './types';
|
||||||
|
|
||||||
|
export const CURRENT_TENANT_ID = 'tenant_123';
|
||||||
|
|
||||||
|
export const TENANTS: Tenant[] = [
|
||||||
|
{
|
||||||
|
id: 'tenant_123',
|
||||||
|
name: 'Fasto Corp',
|
||||||
|
slug: 'fasto',
|
||||||
|
admin_email: 'admin@fasto.com',
|
||||||
|
status: 'active',
|
||||||
|
user_count: 12,
|
||||||
|
attendance_count: 1450,
|
||||||
|
created_at: '2023-01-15T10:00:00Z'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'tenant_456',
|
||||||
|
name: 'Acme Inc',
|
||||||
|
slug: 'acme-inc',
|
||||||
|
admin_email: 'contact@acme.com',
|
||||||
|
status: 'trial',
|
||||||
|
user_count: 5,
|
||||||
|
attendance_count: 320,
|
||||||
|
created_at: '2023-06-20T14:30:00Z'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'tenant_789',
|
||||||
|
name: 'Globex Utils',
|
||||||
|
slug: 'globex',
|
||||||
|
admin_email: 'sysadmin@globex.com',
|
||||||
|
status: 'inactive',
|
||||||
|
user_count: 2,
|
||||||
|
attendance_count: 45,
|
||||||
|
created_at: '2022-11-05T09:15:00Z'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'tenant_101',
|
||||||
|
name: 'Soylent Green',
|
||||||
|
slug: 'soylent',
|
||||||
|
admin_email: 'admin@soylent.com',
|
||||||
|
status: 'active',
|
||||||
|
user_count: 25,
|
||||||
|
attendance_count: 5600,
|
||||||
|
created_at: '2023-02-10T11:20:00Z'
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
export const USERS: User[] = [
|
||||||
|
{
|
||||||
|
id: 'sa1',
|
||||||
|
tenant_id: 'system',
|
||||||
|
name: 'Super Administrator',
|
||||||
|
email: 'root@system.com',
|
||||||
|
role: 'super_admin',
|
||||||
|
team_id: '',
|
||||||
|
avatar_url: 'https://ui-avatars.com/api/?name=Super+Admin&background=0f172a&color=fff',
|
||||||
|
bio: 'Administrador do Sistema Global',
|
||||||
|
status: 'active'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'u1',
|
||||||
|
tenant_id: 'tenant_123',
|
||||||
|
name: 'Lidya Chan',
|
||||||
|
email: 'lidya@fasto.com',
|
||||||
|
role: 'manager',
|
||||||
|
team_id: 'sales_1',
|
||||||
|
avatar_url: 'https://picsum.photos/id/1011/200/200',
|
||||||
|
bio: 'Gerente de Vendas com mais de 10 anos de experiência em SaaS. Apaixonada por construção de equipes e crescimento de receita.',
|
||||||
|
status: 'active'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'u2',
|
||||||
|
tenant_id: 'tenant_123',
|
||||||
|
name: 'Alex Noer',
|
||||||
|
email: 'alex@fasto.com',
|
||||||
|
role: 'agent',
|
||||||
|
team_id: 'sales_1',
|
||||||
|
avatar_url: 'https://picsum.photos/id/1012/200/200',
|
||||||
|
bio: 'Melhor desempenho no Q3. Focado em clientes corporativos e relacionamentos de longo prazo.',
|
||||||
|
status: 'active'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'u3',
|
||||||
|
tenant_id: 'tenant_123',
|
||||||
|
name: 'Angela Moss',
|
||||||
|
email: 'angela@fasto.com',
|
||||||
|
role: 'agent',
|
||||||
|
team_id: 'sales_1',
|
||||||
|
avatar_url: 'https://picsum.photos/id/1013/200/200',
|
||||||
|
status: 'inactive'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'u4',
|
||||||
|
tenant_id: 'tenant_123',
|
||||||
|
name: 'Brian Samuel',
|
||||||
|
email: 'brian@fasto.com',
|
||||||
|
role: 'agent',
|
||||||
|
team_id: 'sales_2',
|
||||||
|
avatar_url: 'https://picsum.photos/id/1014/200/200',
|
||||||
|
status: 'active'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'u5',
|
||||||
|
tenant_id: 'tenant_123',
|
||||||
|
name: 'Benny Chagur',
|
||||||
|
email: 'benny@fasto.com',
|
||||||
|
role: 'agent',
|
||||||
|
team_id: 'sales_2',
|
||||||
|
avatar_url: 'https://picsum.photos/id/1025/200/200',
|
||||||
|
status: 'active'
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const generateMockAttendances = (count: number): Attendance[] => {
|
||||||
|
const origins = ['WhatsApp', 'Instagram', 'Website', 'LinkedIn', 'Referral'] as const;
|
||||||
|
const stages = Object.values(FunnelStage);
|
||||||
|
const products = ['Plano Premium', 'Plano Básico', 'Suíte Enterprise', 'Consultoria'];
|
||||||
|
|
||||||
|
return Array.from({ length: count }).map((_, i) => {
|
||||||
|
const user = USERS.slice(1)[Math.floor(Math.random() * (USERS.length - 1))]; // Skip super admin
|
||||||
|
const rand = Math.random();
|
||||||
|
// Weighted stages for realism
|
||||||
|
let stage = FunnelStage.IDENTIFICATION;
|
||||||
|
let isConverted = false;
|
||||||
|
|
||||||
|
if (rand > 0.85) {
|
||||||
|
stage = FunnelStage.WON;
|
||||||
|
isConverted = true;
|
||||||
|
} else if (rand > 0.7) {
|
||||||
|
stage = FunnelStage.LOST;
|
||||||
|
} else if (rand > 0.5) {
|
||||||
|
stage = FunnelStage.NEGOTIATION;
|
||||||
|
} else if (rand > 0.2) {
|
||||||
|
stage = FunnelStage.IDENTIFICATION;
|
||||||
|
} else {
|
||||||
|
stage = FunnelStage.NO_CONTACT;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Force won/lost logic consistency
|
||||||
|
if (stage === FunnelStage.WON) isConverted = true;
|
||||||
|
|
||||||
|
return {
|
||||||
|
id: `att_${i}`,
|
||||||
|
tenant_id: 'tenant_123',
|
||||||
|
user_id: user.id,
|
||||||
|
created_at: new Date(Date.now() - Math.floor(Math.random() * 60 * 24 * 60 * 60 * 1000)).toISOString(),
|
||||||
|
summary: "Cliente perguntou sobre detalhes do produto e níveis de preços.",
|
||||||
|
attention_points: Math.random() > 0.8 ? ["Resposta demorada", "Verificar tom de voz"] : [],
|
||||||
|
improvement_points: ["Sugerir plano anual", "Fazer follow-up mais cedo"],
|
||||||
|
score: Math.floor(Math.random() * (100 - 50) + 50),
|
||||||
|
first_response_time_min: Math.floor(Math.random() * 120),
|
||||||
|
handling_time_min: Math.floor(Math.random() * 45),
|
||||||
|
funnel_stage: stage,
|
||||||
|
origin: origins[Math.floor(Math.random() * origins.length)],
|
||||||
|
product_requested: products[Math.floor(Math.random() * products.length)],
|
||||||
|
product_sold: isConverted ? products[Math.floor(Math.random() * products.length)] : undefined,
|
||||||
|
converted: isConverted,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
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'],
|
||||||
|
};
|
||||||
45
index.html
Normal file
45
index.html
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>CTMS | Commercial Team Management</title>
|
||||||
|
<script src="https://cdn.tailwindcss.com"></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;
|
||||||
|
}
|
||||||
|
/* Custom scrollbar for webkit */
|
||||||
|
::-webkit-scrollbar {
|
||||||
|
width: 6px;
|
||||||
|
height: 6px;
|
||||||
|
}
|
||||||
|
::-webkit-scrollbar-track {
|
||||||
|
background: transparent;
|
||||||
|
}
|
||||||
|
::-webkit-scrollbar-thumb {
|
||||||
|
background: #cbd5e1;
|
||||||
|
border-radius: 3px;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
<script type="importmap">
|
||||||
|
{
|
||||||
|
"imports": {
|
||||||
|
"react": "https://esm.sh/react@^19.2.4",
|
||||||
|
"react-dom/": "https://esm.sh/react-dom@^19.2.4/",
|
||||||
|
"react/": "https://esm.sh/react@^19.2.4/",
|
||||||
|
"react-router-dom": "https://esm.sh/react-router-dom@^7.13.0",
|
||||||
|
"lucide-react": "https://esm.sh/lucide-react@^0.574.0",
|
||||||
|
"recharts": "https://esm.sh/recharts@^3.7.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
<link rel="stylesheet" href="/index.css">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="root"></div>
|
||||||
|
<script type="module" src="/index.tsx"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
15
index.tsx
Normal file
15
index.tsx
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import ReactDOM from 'react-dom/client';
|
||||||
|
import App from './App';
|
||||||
|
|
||||||
|
const rootElement = document.getElementById('root');
|
||||||
|
if (!rootElement) {
|
||||||
|
throw new Error("Could not find root element to mount to");
|
||||||
|
}
|
||||||
|
|
||||||
|
const root = ReactDOM.createRoot(rootElement);
|
||||||
|
root.render(
|
||||||
|
<React.StrictMode>
|
||||||
|
<App />
|
||||||
|
</React.StrictMode>
|
||||||
|
);
|
||||||
5
metadata.json
Normal file
5
metadata.json
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
{
|
||||||
|
"name": "CTMS - Commercial Team Management System",
|
||||||
|
"description": "A multi-tenant dashboard for commercial teams to track sales performance, analyzing attendance scores and funnel metrics.",
|
||||||
|
"requestFramePermissions": []
|
||||||
|
}
|
||||||
24
package.json
Normal file
24
package.json
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
{
|
||||||
|
"name": "ctms---commercial-team-management-system",
|
||||||
|
"private": true,
|
||||||
|
"version": "0.0.0",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite",
|
||||||
|
"build": "vite build",
|
||||||
|
"preview": "vite preview"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"react": "^19.2.4",
|
||||||
|
"react-dom": "^19.2.4",
|
||||||
|
"react-router-dom": "^7.13.0",
|
||||||
|
"lucide-react": "^0.574.0",
|
||||||
|
"recharts": "^3.7.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/node": "^22.14.0",
|
||||||
|
"@vitejs/plugin-react": "^5.0.0",
|
||||||
|
"typescript": "~5.8.2",
|
||||||
|
"vite": "^6.2.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
222
pages/AttendanceDetail.tsx
Normal file
222
pages/AttendanceDetail.tsx
Normal file
@@ -0,0 +1,222 @@
|
|||||||
|
import React, { useEffect, useState } from 'react';
|
||||||
|
import { useParams, Link } from 'react-router-dom';
|
||||||
|
import { getAttendanceById, getUserById } from '../services/dataService';
|
||||||
|
import { Attendance, User, FunnelStage } from '../types';
|
||||||
|
import { ArrowLeft, CheckCircle2, AlertCircle, Clock, Calendar, MessageSquare, ShoppingBag, Award, TrendingUp } from 'lucide-react';
|
||||||
|
|
||||||
|
export const AttendanceDetail: React.FC = () => {
|
||||||
|
const { id } = useParams<{ id: string }>();
|
||||||
|
const [data, setData] = useState<Attendance | undefined>();
|
||||||
|
const [agent, setAgent] = useState<User | undefined>();
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const loadData = async () => {
|
||||||
|
if (id) {
|
||||||
|
setLoading(true);
|
||||||
|
try {
|
||||||
|
const att = await getAttendanceById(id);
|
||||||
|
setData(att);
|
||||||
|
if (att) {
|
||||||
|
const u = await getUserById(att.user_id);
|
||||||
|
setAgent(u);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error loading details", error);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
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>;
|
||||||
|
|
||||||
|
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';
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const getScoreColor = (score: number) => {
|
||||||
|
if (score >= 80) return 'text-green-500';
|
||||||
|
if (score >= 60) return 'text-yellow-500';
|
||||||
|
return 'text-red-500';
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="max-w-5xl mx-auto space-y-6">
|
||||||
|
{/* 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"
|
||||||
|
>
|
||||||
|
<ArrowLeft size={16} /> Voltar para Histórico
|
||||||
|
</Link>
|
||||||
|
<div className="text-sm text-slate-400 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="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">
|
||||||
|
<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">
|
||||||
|
<MessageSquare size={14} /> {data.origin}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<h1 className="text-2xl md:text-3xl font-bold text-slate-900 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>
|
||||||
|
</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={`text-5xl font-black ${getScoreColor(data.score)}`}>
|
||||||
|
{data.score}
|
||||||
|
</div>
|
||||||
|
<span className="text-xs font-medium text-slate-400 mt-1">de 100</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Main Content Grid */}
|
||||||
|
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
||||||
|
|
||||||
|
{/* Left Column: Analysis */}
|
||||||
|
<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" />
|
||||||
|
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>.
|
||||||
|
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>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 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>
|
||||||
|
<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">
|
||||||
|
<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>
|
||||||
|
)}
|
||||||
|
</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>
|
||||||
|
<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" />
|
||||||
|
{pt}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
) : (
|
||||||
|
<p className="text-sm text-slate-400 italic">Continue o bom trabalho!</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 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="space-y-4">
|
||||||
|
<div className="flex justify-between items-center p-3 bg-slate-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>
|
||||||
|
<span className="text-sm font-bold text-slate-900">{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 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>
|
||||||
|
<span className="text-sm font-bold text-slate-900">{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="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}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="h-px bg-slate-100 my-2" />
|
||||||
|
|
||||||
|
<div className="space-y-1">
|
||||||
|
<span className="text-xs text-slate-500 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">
|
||||||
|
<Award size={18} /> Venda Fechada
|
||||||
|
{data.product_sold && <span className="text-green-800 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>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
314
pages/Dashboard.tsx
Normal file
314
pages/Dashboard.tsx
Normal file
@@ -0,0 +1,314 @@
|
|||||||
|
import React, { useState, useEffect, useMemo } from 'react';
|
||||||
|
import {
|
||||||
|
BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Cell, PieChart, Pie, Legend
|
||||||
|
} from 'recharts';
|
||||||
|
import {
|
||||||
|
Users, Clock, Phone, TrendingUp, Filter
|
||||||
|
} from 'lucide-react';
|
||||||
|
import { getAttendances, getUsers } from '../services/dataService';
|
||||||
|
import { CURRENT_TENANT_ID, COLORS } from '../constants';
|
||||||
|
import { Attendance, DashboardFilter, FunnelStage, User } from '../types';
|
||||||
|
import { KPICard } from '../components/KPICard';
|
||||||
|
import { DateRangePicker } from '../components/DateRangePicker';
|
||||||
|
import { SellersTable } from '../components/SellersTable';
|
||||||
|
import { ProductLists } from '../components/ProductLists';
|
||||||
|
|
||||||
|
// Interface for seller statistics accumulator
|
||||||
|
interface SellerStats {
|
||||||
|
total: number;
|
||||||
|
converted: number;
|
||||||
|
scoreSum: number;
|
||||||
|
count: number;
|
||||||
|
timeSum: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const Dashboard: React.FC = () => {
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [data, setData] = useState<Attendance[]>([]);
|
||||||
|
const [users, setUsers] = useState<User[]>([]);
|
||||||
|
|
||||||
|
const [filters, setFilters] = useState<DashboardFilter>({
|
||||||
|
dateRange: {
|
||||||
|
start: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000), // Last 30 days
|
||||||
|
end: new Date(),
|
||||||
|
},
|
||||||
|
userId: 'all',
|
||||||
|
teamId: 'all',
|
||||||
|
});
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const fetchData = async () => {
|
||||||
|
setLoading(true);
|
||||||
|
try {
|
||||||
|
// Fetch users and attendances in parallel
|
||||||
|
const [fetchedUsers, fetchedData] = await Promise.all([
|
||||||
|
getUsers(CURRENT_TENANT_ID),
|
||||||
|
getAttendances(CURRENT_TENANT_ID, filters)
|
||||||
|
]);
|
||||||
|
|
||||||
|
setUsers(fetchedUsers);
|
||||||
|
setData(fetchedData);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error loading dashboard data:", error);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
fetchData();
|
||||||
|
}, [filters]);
|
||||||
|
|
||||||
|
// --- Metrics Calculations ---
|
||||||
|
const totalLeads = data.length;
|
||||||
|
const avgScore = data.length > 0 ? (data.reduce((acc, curr) => acc + curr.score, 0) / data.length).toFixed(1) : "0";
|
||||||
|
const avgResponseTime = data.length > 0 ? (data.reduce((acc, curr) => acc + curr.first_response_time_min, 0) / data.length).toFixed(0) : "0";
|
||||||
|
const avgHandleTime = data.length > 0 ? (data.reduce((acc, curr) => acc + curr.handling_time_min, 0) / data.length).toFixed(0) : "0";
|
||||||
|
|
||||||
|
// --- Chart Data: Funnel ---
|
||||||
|
const funnelData = useMemo(() => {
|
||||||
|
const stagesOrder = [
|
||||||
|
FunnelStage.NO_CONTACT,
|
||||||
|
FunnelStage.IDENTIFICATION,
|
||||||
|
FunnelStage.NEGOTIATION,
|
||||||
|
FunnelStage.WON,
|
||||||
|
FunnelStage.LOST
|
||||||
|
];
|
||||||
|
|
||||||
|
const counts = data.reduce((acc, curr) => {
|
||||||
|
acc[curr.funnel_stage] = (acc[curr.funnel_stage] || 0) + 1;
|
||||||
|
return acc;
|
||||||
|
}, {} as Record<string, number>);
|
||||||
|
|
||||||
|
return stagesOrder.map(stage => ({
|
||||||
|
name: stage,
|
||||||
|
value: counts[stage] || 0
|
||||||
|
}));
|
||||||
|
}, [data]);
|
||||||
|
|
||||||
|
// --- Chart Data: Origin ---
|
||||||
|
const originData = useMemo(() => {
|
||||||
|
const origins = data.reduce((acc, curr) => {
|
||||||
|
acc[curr.origin] = (acc[curr.origin] || 0) + 1;
|
||||||
|
return acc;
|
||||||
|
}, {} as Record<string, number>);
|
||||||
|
|
||||||
|
// Ensure type safety for value in sort
|
||||||
|
return (Object.entries(origins) as [string, number][])
|
||||||
|
.map(([name, value]) => ({ name, value }))
|
||||||
|
.sort((a, b) => b.value - a.value);
|
||||||
|
}, [data]);
|
||||||
|
|
||||||
|
// --- Table Data: Sellers Ranking ---
|
||||||
|
const sellersRanking = useMemo(() => {
|
||||||
|
const stats = data.reduce<Record<string, SellerStats>>((acc, curr) => {
|
||||||
|
if (!acc[curr.user_id]) {
|
||||||
|
acc[curr.user_id] = { total: 0, converted: 0, scoreSum: 0, count: 0, timeSum: 0 };
|
||||||
|
}
|
||||||
|
acc[curr.user_id].total += 1;
|
||||||
|
if (curr.converted) acc[curr.user_id].converted += 1;
|
||||||
|
acc[curr.user_id].scoreSum += curr.score;
|
||||||
|
acc[curr.user_id].timeSum += curr.first_response_time_min;
|
||||||
|
acc[curr.user_id].count += 1;
|
||||||
|
return acc;
|
||||||
|
}, {});
|
||||||
|
|
||||||
|
return Object.entries(stats)
|
||||||
|
.map(([userId, s]) => {
|
||||||
|
const stat = s as SellerStats;
|
||||||
|
const user = users.find(u => u.id === userId);
|
||||||
|
if (!user) return null;
|
||||||
|
return {
|
||||||
|
user,
|
||||||
|
total: stat.total,
|
||||||
|
avgScore: (stat.scoreSum / stat.count).toFixed(1),
|
||||||
|
conversionRate: ((stat.converted / stat.total) * 100).toFixed(1),
|
||||||
|
responseTime: (stat.timeSum / stat.count).toFixed(0)
|
||||||
|
};
|
||||||
|
})
|
||||||
|
.filter((item): item is NonNullable<typeof item> => item !== null);
|
||||||
|
}, [data, users]);
|
||||||
|
|
||||||
|
// --- Lists Data: Products ---
|
||||||
|
const productStats = useMemo(() => {
|
||||||
|
const requested: Record<string, number> = {};
|
||||||
|
const sold: Record<string, number> = {};
|
||||||
|
|
||||||
|
data.forEach(d => {
|
||||||
|
if (d.product_requested) requested[d.product_requested] = (requested[d.product_requested] || 0) + 1;
|
||||||
|
if (d.product_sold) sold[d.product_sold] = (sold[d.product_sold] || 0) + 1;
|
||||||
|
});
|
||||||
|
|
||||||
|
const formatList = (record: Record<string, number>, total: number) =>
|
||||||
|
Object.entries(record)
|
||||||
|
.map(([name, count]) => ({ name, count, percentage: Math.round((count / (total || 1)) * 100) }))
|
||||||
|
.sort((a, b) => b.count - a.count)
|
||||||
|
.slice(0, 5);
|
||||||
|
|
||||||
|
const totalReq = Object.values(requested).reduce((a, b) => a + b, 0);
|
||||||
|
const totalSold = Object.values(sold).reduce((a, b) => a + b, 0);
|
||||||
|
|
||||||
|
return {
|
||||||
|
requested: formatList(requested, totalReq),
|
||||||
|
sold: formatList(sold, totalSold)
|
||||||
|
};
|
||||||
|
}, [data]);
|
||||||
|
|
||||||
|
|
||||||
|
const handleFilterChange = (key: keyof DashboardFilter, value: any) => {
|
||||||
|
setFilters(prev => ({ ...prev, [key]: value }));
|
||||||
|
};
|
||||||
|
|
||||||
|
if (loading && data.length === 0) {
|
||||||
|
return <div className="flex h-full items-center justify-center text-slate-400">Carregando Dashboard...</div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-6 pb-8">
|
||||||
|
{/* 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)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<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>
|
||||||
|
|
||||||
|
<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>
|
||||||
|
<option value="sales_1">Vendas Alpha</option>
|
||||||
|
<option value="sales_2">Vendas Beta</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* KPI Cards */}
|
||||||
|
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
|
||||||
|
<KPICard
|
||||||
|
title="Total de Leads"
|
||||||
|
value={totalLeads}
|
||||||
|
trend="up"
|
||||||
|
trendValue="12%"
|
||||||
|
icon={Users}
|
||||||
|
colorClass="text-blue-600"
|
||||||
|
/>
|
||||||
|
<KPICard
|
||||||
|
title="Nota Média Qualidade"
|
||||||
|
value={avgScore}
|
||||||
|
subValue="/ 100"
|
||||||
|
trend={Number(avgScore) > 75 ? 'up' : 'down'}
|
||||||
|
trendValue="2.1"
|
||||||
|
icon={TrendingUp}
|
||||||
|
colorClass="text-purple-600"
|
||||||
|
/>
|
||||||
|
<KPICard
|
||||||
|
title="Média 1ª Resposta"
|
||||||
|
value={`${avgResponseTime}m`}
|
||||||
|
trend="down"
|
||||||
|
trendValue="bom"
|
||||||
|
icon={Clock}
|
||||||
|
colorClass="text-orange-500"
|
||||||
|
/>
|
||||||
|
<KPICard
|
||||||
|
title="Tempo Médio Atend."
|
||||||
|
value={`${avgHandleTime}m`}
|
||||||
|
subValue="por lead"
|
||||||
|
icon={Phone}
|
||||||
|
colorClass="text-green-600"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 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="h-[300px] w-full">
|
||||||
|
<ResponsiveContainer width="100%" height="100%">
|
||||||
|
<BarChart
|
||||||
|
data={funnelData}
|
||||||
|
layout="vertical"
|
||||||
|
margin={{ top: 5, right: 30, left: 40, bottom: 5 }}
|
||||||
|
barSize={32}
|
||||||
|
>
|
||||||
|
<CartesianGrid strokeDasharray="3 3" horizontal={true} vertical={false} stroke="#f1f5f9" />
|
||||||
|
<XAxis type="number" hide />
|
||||||
|
<YAxis
|
||||||
|
dataKey="name"
|
||||||
|
type="category"
|
||||||
|
width={120}
|
||||||
|
tick={{fill: '#475569', fontSize: 13, fontWeight: 500}}
|
||||||
|
tickLine={false}
|
||||||
|
axisLine={false}
|
||||||
|
/>
|
||||||
|
<Tooltip
|
||||||
|
cursor={{fill: '#f8fafc'}}
|
||||||
|
contentStyle={{ borderRadius: '12px', border: 'none', boxShadow: '0 10px 15px -3px rgb(0 0 0 / 0.1)' }}
|
||||||
|
/>
|
||||||
|
<Bar dataKey="value" radius={[0, 6, 6, 0]}>
|
||||||
|
{funnelData.map((entry, index) => (
|
||||||
|
<Cell key={`cell-${index}`} fill={COLORS.charts[index % COLORS.charts.length]} />
|
||||||
|
))}
|
||||||
|
</Bar>
|
||||||
|
</BarChart>
|
||||||
|
</ResponsiveContainer>
|
||||||
|
</div>
|
||||||
|
</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="flex-1 min-h-0">
|
||||||
|
<ResponsiveContainer width="100%" height="100%">
|
||||||
|
<PieChart>
|
||||||
|
<Pie
|
||||||
|
data={originData}
|
||||||
|
cx="50%"
|
||||||
|
cy="50%"
|
||||||
|
innerRadius={70}
|
||||||
|
outerRadius={100}
|
||||||
|
paddingAngle={5}
|
||||||
|
dataKey="value"
|
||||||
|
stroke="none"
|
||||||
|
>
|
||||||
|
{originData.map((entry, index) => (
|
||||||
|
<Cell key={`cell-${index}`} fill={COLORS.charts[index % COLORS.charts.length]} />
|
||||||
|
))}
|
||||||
|
</Pie>
|
||||||
|
<Tooltip contentStyle={{ borderRadius: '12px' }} />
|
||||||
|
<Legend
|
||||||
|
verticalAlign="bottom"
|
||||||
|
height={80}
|
||||||
|
iconType="circle"
|
||||||
|
iconSize={10}
|
||||||
|
wrapperStyle={{ fontSize: '12px', paddingTop: '20px' }}
|
||||||
|
/>
|
||||||
|
</PieChart>
|
||||||
|
</ResponsiveContainer>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Ranking Table */}
|
||||||
|
<SellersTable data={sellersRanking} />
|
||||||
|
|
||||||
|
{/* Product Lists */}
|
||||||
|
<ProductLists requested={productStats.requested} sold={productStats.sold} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
190
pages/Login.tsx
Normal file
190
pages/Login.tsx
Normal file
@@ -0,0 +1,190 @@
|
|||||||
|
import React, { useState } from 'react';
|
||||||
|
import { useNavigate } from 'react-router-dom';
|
||||||
|
import { Hexagon, Lock, Mail, ArrowRight, Loader2, Info } from 'lucide-react';
|
||||||
|
import { USERS } from '../constants';
|
||||||
|
|
||||||
|
export const Login: React.FC = () => {
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
|
const [email, setEmail] = useState('lidya@fasto.com');
|
||||||
|
const [password, setPassword] = useState('password');
|
||||||
|
const [error, setError] = useState('');
|
||||||
|
|
||||||
|
const handleLogin = (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setIsLoading(true);
|
||||||
|
setError('');
|
||||||
|
|
||||||
|
// Simulate API call and validation
|
||||||
|
setTimeout(() => {
|
||||||
|
const user = USERS.find(u => u.email.toLowerCase() === email.toLowerCase());
|
||||||
|
|
||||||
|
if (user) {
|
||||||
|
// Mock Login: Save to local storage
|
||||||
|
localStorage.setItem('ctms_user_id', user.id);
|
||||||
|
|
||||||
|
setIsLoading(false);
|
||||||
|
|
||||||
|
// Redirect based on role
|
||||||
|
if (user.role === 'super_admin') {
|
||||||
|
navigate('/super-admin');
|
||||||
|
} else {
|
||||||
|
navigate('/');
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
setIsLoading(false);
|
||||||
|
setError('Usuário não encontrado. Tente lidya@fasto.com ou root@system.com');
|
||||||
|
}
|
||||||
|
}, 1000);
|
||||||
|
};
|
||||||
|
|
||||||
|
const fillCredentials = (type: 'admin' | 'super') => {
|
||||||
|
if (type === 'admin') {
|
||||||
|
setEmail('lidya@fasto.com');
|
||||||
|
} else {
|
||||||
|
setEmail('root@system.com');
|
||||||
|
}
|
||||||
|
setPassword('password');
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen bg-slate-50 flex flex-col justify-center py-12 sm:px-6 lg:px-8">
|
||||||
|
<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>
|
||||||
|
<span className="text-3xl font-bold tracking-tight">Fasto<span className="text-yellow-500">.</span></span>
|
||||||
|
</div>
|
||||||
|
<h2 className="mt-6 text-center text-3xl font-bold tracking-tight text-slate-900">
|
||||||
|
Acesse sua conta
|
||||||
|
</h2>
|
||||||
|
<p className="mt-2 text-center text-sm text-slate-600">
|
||||||
|
Ou <a href="#" className="font-medium text-blue-600 hover:text-blue-500">inicie seu teste grátis de 14 dias</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">
|
||||||
|
|
||||||
|
{/* Demo Helper - Remove in production */}
|
||||||
|
<div className="mb-6 p-3 bg-blue-50 border border-blue-100 rounded-lg text-xs text-blue-700">
|
||||||
|
<div className="flex items-center gap-2 font-bold mb-2">
|
||||||
|
<Info size={14} /> Dicas de Acesso (Demo):
|
||||||
|
</div>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<button onClick={() => fillCredentials('admin')} className="px-2 py-1 bg-white border border-blue-200 rounded shadow-sm hover:bg-blue-100 transition">
|
||||||
|
Admin da Empresa
|
||||||
|
</button>
|
||||||
|
<button onClick={() => fillCredentials('super')} className="px-2 py-1 bg-white border border-blue-200 rounded shadow-sm hover:bg-blue-100 transition">
|
||||||
|
Super Admin
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<form className="space-y-6" onSubmit={handleLogin}>
|
||||||
|
<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"
|
||||||
|
autoComplete="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 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"
|
||||||
|
placeholder="voce@empresa.com"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label htmlFor="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"
|
||||||
|
name="password"
|
||||||
|
type="password"
|
||||||
|
autoComplete="current-password"
|
||||||
|
required
|
||||||
|
value={password}
|
||||||
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
|
className="block w-full pl-10 pr-3 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"
|
||||||
|
placeholder="••••••••"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<div className="text-red-500 text-sm font-medium text-center">
|
||||||
|
{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">
|
||||||
|
<a href="#" className="font-medium text-blue-600 hover:text-blue-500">
|
||||||
|
Esqueceu sua senha?
|
||||||
|
</a>
|
||||||
|
</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 disabled:opacity-70 disabled:cursor-not-allowed transition-all"
|
||||||
|
>
|
||||||
|
{isLoading ? (
|
||||||
|
<>
|
||||||
|
<Loader2 className="animate-spin h-4 w-4" />
|
||||||
|
Entrando...
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
Entrar <ArrowRight className="h-4 w-4" />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</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">Protegido por SSO Corporativo</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
362
pages/SuperAdmin.tsx
Normal file
362
pages/SuperAdmin.tsx
Normal file
@@ -0,0 +1,362 @@
|
|||||||
|
import React, { useState, useMemo } from 'react';
|
||||||
|
import {
|
||||||
|
Building2, Users, MessageSquare, Plus, Search, MoreHorizontal,
|
||||||
|
Edit, Trash2, Shield, Calendar, ChevronDown, ChevronUp, ChevronsUpDown, X
|
||||||
|
} from 'lucide-react';
|
||||||
|
import { TENANTS, MOCK_ATTENDANCES, USERS } from '../constants';
|
||||||
|
import { Tenant } from '../types';
|
||||||
|
import { DateRangePicker } from '../components/DateRangePicker';
|
||||||
|
import { KPICard } from '../components/KPICard';
|
||||||
|
|
||||||
|
// Reusing KPICard but simplifying logic for this view if needed
|
||||||
|
// We can use the existing KPICard component.
|
||||||
|
|
||||||
|
export const SuperAdmin: React.FC = () => {
|
||||||
|
const [dateRange, setDateRange] = useState({
|
||||||
|
start: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000),
|
||||||
|
end: new Date()
|
||||||
|
});
|
||||||
|
const [selectedTenantId, setSelectedTenantId] = useState<string>('all');
|
||||||
|
const [searchQuery, setSearchQuery] = useState('');
|
||||||
|
const [tenants, setTenants] = useState<Tenant[]>(TENANTS);
|
||||||
|
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');
|
||||||
|
|
||||||
|
// --- Metrics ---
|
||||||
|
const totalTenants = tenants.length;
|
||||||
|
// Mock aggregation for demo
|
||||||
|
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 =>
|
||||||
|
t.name.toLowerCase().includes(q) ||
|
||||||
|
t.admin_email?.toLowerCase().includes(q) ||
|
||||||
|
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');
|
||||||
|
} else {
|
||||||
|
setSortKey(key);
|
||||||
|
setSortDirection('asc');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleEdit = (tenant: Tenant) => {
|
||||||
|
setEditingTenant(tenant);
|
||||||
|
setIsModalOpen(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDelete = (id: string) => {
|
||||||
|
if (confirm('Tem certeza que deseja excluir esta organização? Esta ação não pode ser desfeita.')) {
|
||||||
|
setTenants(prev => prev.filter(t => t.id !== id));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSaveTenant = (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
// Logic to save (mock)
|
||||||
|
setIsModalOpen(false);
|
||||||
|
setEditingTenant(null);
|
||||||
|
alert('Organização salva com sucesso (Mock)');
|
||||||
|
};
|
||||||
|
|
||||||
|
// --- 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" />;
|
||||||
|
};
|
||||||
|
|
||||||
|
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',
|
||||||
|
};
|
||||||
|
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>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-8 max-w-7xl mx-auto pb-8">
|
||||||
|
{/* Header */}
|
||||||
|
<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>
|
||||||
|
</div>
|
||||||
|
</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="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)}
|
||||||
|
>
|
||||||
|
<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"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Tenants Table */}
|
||||||
|
<div className="bg-white border border-slate-200 rounded-xl shadow-sm overflow-hidden">
|
||||||
|
<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')}>
|
||||||
|
<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')}>
|
||||||
|
<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')}>
|
||||||
|
<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')}>
|
||||||
|
<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">
|
||||||
|
{filteredTenants.map((tenant) => (
|
||||||
|
<tr key={tenant.id} className="hover:bg-slate-50/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">
|
||||||
|
{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>
|
||||||
|
</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-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>
|
||||||
|
</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">
|
||||||
|
<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>
|
||||||
|
</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>
|
||||||
|
|
||||||
|
<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"
|
||||||
|
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
|
||||||
|
/>
|
||||||
|
</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"
|
||||||
|
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"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label className="text-sm font-medium text-slate-700">Status</label>
|
||||||
|
<select
|
||||||
|
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"
|
||||||
|
>
|
||||||
|
<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"
|
||||||
|
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
|
||||||
|
/>
|
||||||
|
</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>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
285
pages/TeamManagement.tsx
Normal file
285
pages/TeamManagement.tsx
Normal file
@@ -0,0 +1,285 @@
|
|||||||
|
import React, { useState } from 'react';
|
||||||
|
import { Users, Plus, MoreHorizontal, Mail, Shield, Search, X, Edit, Trash2, Save } from 'lucide-react';
|
||||||
|
import { USERS } from '../constants';
|
||||||
|
import { User } from '../types';
|
||||||
|
|
||||||
|
export const TeamManagement: React.FC = () => {
|
||||||
|
const [users, setUsers] = useState<User[]>(USERS.filter(u => u.role !== 'super_admin')); // Default hide super admin from list
|
||||||
|
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||||
|
const [searchTerm, setSearchTerm] = useState('');
|
||||||
|
|
||||||
|
// State for handling Add/Edit
|
||||||
|
const [editingUser, setEditingUser] = useState<User | null>(null);
|
||||||
|
const [formData, setFormData] = useState({
|
||||||
|
name: '',
|
||||||
|
email: '',
|
||||||
|
role: 'agent' as 'super_admin' | 'admin' | 'manager' | 'agent',
|
||||||
|
team_id: 'sales_1',
|
||||||
|
status: 'active' as 'active' | 'inactive'
|
||||||
|
});
|
||||||
|
|
||||||
|
const filteredUsers = users.filter(u =>
|
||||||
|
u.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||||
|
u.email.toLowerCase().includes(searchTerm.toLowerCase())
|
||||||
|
);
|
||||||
|
|
||||||
|
const getRoleBadge = (role: string) => {
|
||||||
|
switch (role) {
|
||||||
|
case 'super_admin': return 'bg-slate-900 text-white border-slate-700';
|
||||||
|
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';
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const getStatusBadge = (status: string) => {
|
||||||
|
if (status === 'active') {
|
||||||
|
return 'bg-green-100 text-green-700 border-green-200';
|
||||||
|
}
|
||||||
|
return 'bg-slate-100 text-slate-500 border-slate-200';
|
||||||
|
};
|
||||||
|
|
||||||
|
// Actions
|
||||||
|
const handleDelete = (userId: string) => {
|
||||||
|
if (window.confirm('Tem certeza que deseja excluir este usuário? Esta ação não pode ser desfeita.')) {
|
||||||
|
setUsers(prev => prev.filter(u => u.id !== userId));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const openAddModal = () => {
|
||||||
|
setEditingUser(null);
|
||||||
|
setFormData({ name: '', email: '', role: 'agent', team_id: 'sales_1', status: 'active' });
|
||||||
|
setIsModalOpen(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
const openEditModal = (user: User) => {
|
||||||
|
setEditingUser(user);
|
||||||
|
setFormData({
|
||||||
|
name: user.name,
|
||||||
|
email: user.email,
|
||||||
|
role: user.role,
|
||||||
|
team_id: user.team_id,
|
||||||
|
status: user.status
|
||||||
|
});
|
||||||
|
setIsModalOpen(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSave = (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
|
||||||
|
if (editingUser) {
|
||||||
|
// Update existing user
|
||||||
|
setUsers(prev => prev.map(u => u.id === editingUser.id ? { ...u, ...formData } : u));
|
||||||
|
} else {
|
||||||
|
// Create new user
|
||||||
|
const newUser: User = {
|
||||||
|
id: Date.now().toString(),
|
||||||
|
tenant_id: 'tenant_123', // Mock default
|
||||||
|
avatar_url: `https://ui-avatars.com/api/?name=${encodeURIComponent(formData.name)}&background=random`,
|
||||||
|
...formData
|
||||||
|
};
|
||||||
|
setUsers(prev => [...prev, newUser]);
|
||||||
|
}
|
||||||
|
setIsModalOpen(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-8 max-w-7xl mx-auto">
|
||||||
|
<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">Gerenciamento de Equipe</h1>
|
||||||
|
<p className="text-slate-500 text-sm">Gerencie acesso, funções e times de vendas da sua organização.</p>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={openAddModal}
|
||||||
|
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 Membro
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="bg-white border border-slate-200 rounded-xl shadow-sm overflow-hidden">
|
||||||
|
{/* Toolbar */}
|
||||||
|
<div className="p-4 border-b border-slate-100 flex items-center justify-between gap-4">
|
||||||
|
<div className="relative w-full max-w-sm">
|
||||||
|
<Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
placeholder="Buscar por nome ou e-mail..."
|
||||||
|
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"
|
||||||
|
value={searchTerm}
|
||||||
|
onChange={(e) => setSearchTerm(e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="text-sm text-slate-500 hidden sm:block">
|
||||||
|
{filteredUsers.length} membros encontrados
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Table */}
|
||||||
|
<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">Usuário</th>
|
||||||
|
<th className="px-6 py-4 font-semibold">Função</th>
|
||||||
|
<th className="px-6 py-4 font-semibold">Time</th>
|
||||||
|
<th className="px-6 py-4 font-semibold">Status</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">
|
||||||
|
{filteredUsers.map((user) => (
|
||||||
|
<tr key={user.id} className="hover:bg-slate-50/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} alt="" className="w-10 h-10 rounded-full border border-slate-200 object-cover" />
|
||||||
|
<span className={`absolute bottom-0 right-0 w-3 h-3 rounded-full border-2 border-white ${user.status === 'active' ? 'bg-green-500' : 'bg-slate-300'}`}></span>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div className="font-semibold text-slate-900">{user.name}</div>
|
||||||
|
<div className="flex items-center gap-1.5 text-xs text-slate-500">
|
||||||
|
<Mail size={12} /> {user.email}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
<td className="px-6 py-4">
|
||||||
|
<span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-semibold border capitalize ${getRoleBadge(user.role)}`}>
|
||||||
|
{user.role === 'manager' ? 'Gerente' : user.role === 'agent' ? 'Agente' : user.role === 'admin' ? 'Admin' : 'Super Admin'}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td className="px-6 py-4 text-slate-600 font-medium">
|
||||||
|
{user.team_id === 'sales_1' ? 'Vendas Alpha' : user.team_id === 'sales_2' ? 'Vendas Beta' : '-'}
|
||||||
|
</td>
|
||||||
|
<td className="px-6 py-4">
|
||||||
|
<span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-semibold border capitalize ${getStatusBadge(user.status)}`}>
|
||||||
|
{user.status === 'active' ? 'Ativo' : 'Inativo'}
|
||||||
|
</span>
|
||||||
|
</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={() => openEditModal(user)}
|
||||||
|
className="p-2 text-slate-400 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-colors"
|
||||||
|
title="Editar Usuário"
|
||||||
|
>
|
||||||
|
<Edit size={16} />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => handleDelete(user.id)}
|
||||||
|
className="p-2 text-slate-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors"
|
||||||
|
title="Excluir Usuário"
|
||||||
|
>
|
||||||
|
<Trash2 size={16} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
{filteredUsers.length === 0 && (
|
||||||
|
<tr>
|
||||||
|
<td colSpan={5} className="px-6 py-8 text-center text-slate-400 italic">Nenhum usuário encontrado.</td>
|
||||||
|
</tr>
|
||||||
|
)}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</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-md 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="text-lg font-bold text-slate-900">{editingUser ? 'Editar Usuário' : 'Convidar Novo Membro'}</h3>
|
||||||
|
<button onClick={() => setIsModalOpen(false)} className="text-slate-400 hover:text-slate-600 transition-colors"><X size={20} /></button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<form onSubmit={handleSave} className="p-6 space-y-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label className="text-sm font-medium text-slate-700">Nome Completo</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
required
|
||||||
|
className="w-full px-3 py-2 border border-slate-200 bg-slate-50 rounded-lg text-sm outline-none focus:ring-2 focus:ring-blue-100 focus:border-blue-400 transition-all"
|
||||||
|
placeholder="João Silva"
|
||||||
|
value={formData.name}
|
||||||
|
onChange={(e) => setFormData({...formData, name: e.target.value})}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label className="text-sm font-medium text-slate-700">Endereço de E-mail</label>
|
||||||
|
<input
|
||||||
|
type="email"
|
||||||
|
required
|
||||||
|
className="w-full px-3 py-2 border border-slate-200 bg-slate-50 rounded-lg text-sm outline-none focus:ring-2 focus:ring-blue-100 focus:border-blue-400 transition-all"
|
||||||
|
placeholder="joao@empresa.com"
|
||||||
|
value={formData.email}
|
||||||
|
onChange={(e) => setFormData({...formData, email: e.target.value})}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-2 gap-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label className="text-sm font-medium text-slate-700">Função</label>
|
||||||
|
<select
|
||||||
|
className="w-full px-3 py-2 border border-slate-200 bg-slate-50 rounded-lg text-sm outline-none focus:ring-2 focus:ring-blue-100 transition-all cursor-pointer"
|
||||||
|
value={formData.role}
|
||||||
|
onChange={(e) => setFormData({...formData, role: e.target.value as any})}
|
||||||
|
>
|
||||||
|
<option value="agent">Agente</option>
|
||||||
|
<option value="manager">Gerente</option>
|
||||||
|
<option value="admin">Admin</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label className="text-sm font-medium text-slate-700">Time</label>
|
||||||
|
<select
|
||||||
|
className="w-full px-3 py-2 border border-slate-200 bg-slate-50 rounded-lg text-sm outline-none focus:ring-2 focus:ring-blue-100 transition-all cursor-pointer"
|
||||||
|
value={formData.team_id}
|
||||||
|
onChange={(e) => setFormData({...formData, team_id: e.target.value})}
|
||||||
|
>
|
||||||
|
<option value="sales_1">Vendas Alpha</option>
|
||||||
|
<option value="sales_2">Vendas Beta</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label className="text-sm font-medium text-slate-700">Status da Conta</label>
|
||||||
|
<select
|
||||||
|
className="w-full px-3 py-2 border border-slate-200 bg-slate-50 rounded-lg text-sm outline-none focus:ring-2 focus:ring-blue-100 transition-all cursor-pointer"
|
||||||
|
value={formData.status}
|
||||||
|
onChange={(e) => setFormData({...formData, status: e.target.value as any})}
|
||||||
|
>
|
||||||
|
<option value="active">Ativo</option>
|
||||||
|
<option value="inactive">Inativo</option>
|
||||||
|
</select>
|
||||||
|
</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="flex items-center gap-2 px-4 py-2 bg-slate-900 text-white rounded-lg font-medium text-sm hover:bg-slate-800 transition-colors shadow-sm"
|
||||||
|
>
|
||||||
|
<Save size={16} /> {editingUser ? 'Salvar Alterações' : 'Adicionar Membro'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
212
pages/UserDetail.tsx
Normal file
212
pages/UserDetail.tsx
Normal file
@@ -0,0 +1,212 @@
|
|||||||
|
import React, { useEffect, useState, useMemo } from 'react';
|
||||||
|
import { useParams, Link } from 'react-router-dom';
|
||||||
|
import { getAttendances, getUserById } from '../services/dataService';
|
||||||
|
import { CURRENT_TENANT_ID } from '../constants';
|
||||||
|
import { Attendance, User, FunnelStage } from '../types';
|
||||||
|
import { ArrowLeft, Mail, Phone, Clock, MessageSquare, ChevronLeft, ChevronRight, Eye } from 'lucide-react';
|
||||||
|
|
||||||
|
const ITEMS_PER_PAGE = 10;
|
||||||
|
|
||||||
|
export const UserDetail: React.FC = () => {
|
||||||
|
const { id } = useParams<{ id: string }>();
|
||||||
|
const [user, setUser] = useState<User | undefined>();
|
||||||
|
const [attendances, setAttendances] = useState<Attendance[]>([]);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [currentPage, setCurrentPage] = useState(1);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (id) {
|
||||||
|
setLoading(true);
|
||||||
|
|
||||||
|
const loadData = async () => {
|
||||||
|
try {
|
||||||
|
const u = await getUserById(id);
|
||||||
|
setUser(u);
|
||||||
|
|
||||||
|
if (u) {
|
||||||
|
const data = await getAttendances(CURRENT_TENANT_ID, {
|
||||||
|
userId: id,
|
||||||
|
dateRange: { start: new Date(0), end: new Date() } // All time
|
||||||
|
});
|
||||||
|
setAttendances(data);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error loading user details", error);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
loadData();
|
||||||
|
}
|
||||||
|
}, [id]);
|
||||||
|
|
||||||
|
const totalPages = Math.ceil(attendances.length / ITEMS_PER_PAGE);
|
||||||
|
|
||||||
|
const currentData = useMemo(() => {
|
||||||
|
const start = (currentPage - 1) * ITEMS_PER_PAGE;
|
||||||
|
return attendances.slice(start, start + ITEMS_PER_PAGE);
|
||||||
|
}, [attendances, currentPage]);
|
||||||
|
|
||||||
|
const handlePageChange = (newPage: number) => {
|
||||||
|
if (newPage >= 1 && newPage <= totalPages) {
|
||||||
|
setCurrentPage(newPage);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
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';
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
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 (!loading && !user) return <div className="p-8 text-slate-500">Usuário não encontrado</div>;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-8 max-w-7xl mx-auto">
|
||||||
|
{/* 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">
|
||||||
|
<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" />
|
||||||
|
<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">
|
||||||
|
<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>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</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>
|
||||||
|
<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">
|
||||||
|
{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">
|
||||||
|
{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>
|
||||||
|
|
||||||
|
{loading ? (
|
||||||
|
<div className="p-12 text-center text-slate-400">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">
|
||||||
|
<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>
|
||||||
|
<th className="px-6 py-4 font-medium text-center">Nota</th>
|
||||||
|
<th className="px-6 py-4 font-medium text-center">T. Resp.</th>
|
||||||
|
<th className="px-6 py-4 font-medium text-right">Ação</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody className="divide-y divide-slate-100 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>
|
||||||
|
</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="flex items-center gap-1"><MessageSquare size={10} /> {att.origin}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
<td className="px-6 py-4 text-center">
|
||||||
|
<span className={`inline-flex px-2.5 py-0.5 rounded-full text-xs font-semibold border ${getStageBadgeColor(att.funnel_stage)}`}>
|
||||||
|
{att.funnel_stage}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td className="px-6 py-4 text-center">
|
||||||
|
<span className={`inline-flex items-center justify-center w-8 h-8 rounded-lg font-bold text-sm ${getScoreColor(att.score)}`}>
|
||||||
|
{att.score}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td className="px-6 py-4 text-center text-slate-600">
|
||||||
|
<div className="flex items-center justify-center gap-1">
|
||||||
|
<Clock size={14} className="text-slate-400" />
|
||||||
|
{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"
|
||||||
|
title="Ver Detalhes"
|
||||||
|
>
|
||||||
|
<Eye size={18} />
|
||||||
|
</Link>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Pagination Footer */}
|
||||||
|
{totalPages > 1 && (
|
||||||
|
<div className="px-6 py-4 border-t border-slate-100 flex items-center justify-between bg-slate-50/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"
|
||||||
|
>
|
||||||
|
<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>
|
||||||
|
<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"
|
||||||
|
>
|
||||||
|
Próximo <ChevronRight size={16} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
207
pages/UserProfile.tsx
Normal file
207
pages/UserProfile.tsx
Normal file
@@ -0,0 +1,207 @@
|
|||||||
|
import React, { useState, useEffect } from 'react';
|
||||||
|
import { Camera, Save, Mail, User as UserIcon, Building, Shield, Loader2, CheckCircle2 } from 'lucide-react';
|
||||||
|
import { USERS } from '../constants';
|
||||||
|
import { User } from '../types';
|
||||||
|
|
||||||
|
export const UserProfile: React.FC = () => {
|
||||||
|
// Simulating logged-in user state
|
||||||
|
const [user, setUser] = useState<User | null>(null);
|
||||||
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
|
const [isSuccess, setIsSuccess] = useState(false);
|
||||||
|
|
||||||
|
// Form State
|
||||||
|
const [name, setName] = useState('');
|
||||||
|
const [bio, setBio] = useState('');
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
// Simulate fetching user data
|
||||||
|
const currentUser = USERS[0];
|
||||||
|
setUser(currentUser);
|
||||||
|
setName(currentUser.name);
|
||||||
|
setBio(currentUser.bio || '');
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleSubmit = (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setIsLoading(true);
|
||||||
|
setIsSuccess(false);
|
||||||
|
|
||||||
|
// Simulate API call
|
||||||
|
setTimeout(() => {
|
||||||
|
setIsLoading(false);
|
||||||
|
setIsSuccess(true);
|
||||||
|
// In a real app, we would update the user context/store here
|
||||||
|
setTimeout(() => setIsSuccess(false), 3000);
|
||||||
|
}, 1500);
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!user) return <div className="p-8 text-center text-slate-500">Carregando perfil...</div>;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="max-w-4xl mx-auto space-y-6 pb-12">
|
||||||
|
<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>
|
||||||
|
</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} 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">
|
||||||
|
<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>
|
||||||
|
|
||||||
|
<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>
|
||||||
|
<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' : 'Vendas Beta'}
|
||||||
|
</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 bg-green-500"></div>
|
||||||
|
Ativo
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-3 text-sm text-slate-600">
|
||||||
|
<Building size={14} />
|
||||||
|
Fasto Corp (Organização)
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 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>
|
||||||
|
{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">
|
||||||
|
<CheckCircle2 size={16} /> Salvo com sucesso
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<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">
|
||||||
|
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" />
|
||||||
|
</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"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label htmlFor="email" className="block text-sm font-medium text-slate-700">
|
||||||
|
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" />
|
||||||
|
</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"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-slate-400 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">
|
||||||
|
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" />
|
||||||
|
</div>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
id="role"
|
||||||
|
value={user.role.charAt(0).toUpperCase() + user.role.slice(1)}
|
||||||
|
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"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label htmlFor="bio" className="block text-sm font-medium text-slate-700">
|
||||||
|
Bio / Descrição
|
||||||
|
</label>
|
||||||
|
<textarea
|
||||||
|
id="bio"
|
||||||
|
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"
|
||||||
|
placeholder="Escreva uma breve descrição sobre você..."
|
||||||
|
/>
|
||||||
|
<p className="text-xs text-slate-400 text-right">{bio.length}/500 caracteres</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="pt-4 flex items-center justify-end border-t border-slate-100 mt-6">
|
||||||
|
<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"
|
||||||
|
>
|
||||||
|
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"
|
||||||
|
>
|
||||||
|
{isLoading ? (
|
||||||
|
<>
|
||||||
|
<Loader2 className="animate-spin h-4 w-4" /> Salvando...
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<Save size={16} /> Salvar Alterações
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
68
services/dataService.ts
Normal file
68
services/dataService.ts
Normal file
@@ -0,0 +1,68 @@
|
|||||||
|
|
||||||
|
import { Attendance, DashboardFilter, User } from '../types';
|
||||||
|
|
||||||
|
// URL do Backend que criamos (backend/index.js)
|
||||||
|
// Certifique-se de rodar o backend com 'node backend/index.js'
|
||||||
|
const API_URL = 'http://localhost:3001/api';
|
||||||
|
|
||||||
|
export const getAttendances = async (tenantId: string, filter: DashboardFilter): Promise<Attendance[]> => {
|
||||||
|
try {
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
params.append('tenantId', tenantId);
|
||||||
|
|
||||||
|
if (filter.dateRange.start) params.append('startDate', filter.dateRange.start.toISOString());
|
||||||
|
if (filter.dateRange.end) params.append('endDate', filter.dateRange.end.toISOString());
|
||||||
|
|
||||||
|
if (filter.userId && filter.userId !== 'all') params.append('userId', filter.userId);
|
||||||
|
if (filter.teamId && filter.teamId !== 'all') params.append('teamId', filter.teamId);
|
||||||
|
|
||||||
|
const response = await fetch(`${API_URL}/attendances?${params.toString()}`);
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error('Falha ao buscar atendimentos do servidor');
|
||||||
|
}
|
||||||
|
|
||||||
|
return await response.json();
|
||||||
|
} catch (error) {
|
||||||
|
console.error("API Error (getAttendances):", error);
|
||||||
|
// Fallback vazio ou lançar erro para a UI tratar
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getUsers = async (tenantId: string): Promise<User[]> => {
|
||||||
|
try {
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
if (tenantId !== 'all') params.append('tenantId', tenantId);
|
||||||
|
|
||||||
|
const response = await fetch(`${API_URL}/users?${params.toString()}`);
|
||||||
|
if (!response.ok) throw new Error('Falha ao buscar usuários');
|
||||||
|
|
||||||
|
return await response.json();
|
||||||
|
} catch (error) {
|
||||||
|
console.error("API Error (getUsers):", error);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getUserById = async (id: string): Promise<User | undefined> => {
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${API_URL}/users/${id}`);
|
||||||
|
if (!response.ok) return undefined;
|
||||||
|
return await response.json();
|
||||||
|
} catch (error) {
|
||||||
|
console.error("API Error (getUserById):", error);
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getAttendanceById = async (id: string): Promise<Attendance | undefined> => {
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${API_URL}/attendances/${id}`);
|
||||||
|
if (!response.ok) return undefined;
|
||||||
|
return await response.json();
|
||||||
|
} catch (error) {
|
||||||
|
console.error("API Error (getAttendanceById):", error);
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
};
|
||||||
29
tsconfig.json
Normal file
29
tsconfig.json
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2022",
|
||||||
|
"experimentalDecorators": true,
|
||||||
|
"useDefineForClassFields": false,
|
||||||
|
"module": "ESNext",
|
||||||
|
"lib": [
|
||||||
|
"ES2022",
|
||||||
|
"DOM",
|
||||||
|
"DOM.Iterable"
|
||||||
|
],
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"types": [
|
||||||
|
"node"
|
||||||
|
],
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"isolatedModules": true,
|
||||||
|
"moduleDetection": "force",
|
||||||
|
"allowJs": true,
|
||||||
|
"jsx": "react-jsx",
|
||||||
|
"paths": {
|
||||||
|
"@/*": [
|
||||||
|
"./*"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"allowImportingTsExtensions": true,
|
||||||
|
"noEmit": true
|
||||||
|
}
|
||||||
|
}
|
||||||
62
types.ts
Normal file
62
types.ts
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
|
||||||
|
export enum FunnelStage {
|
||||||
|
NO_CONTACT = 'Sem atendimento',
|
||||||
|
IDENTIFICATION = 'Identificação',
|
||||||
|
NEGOTIATION = 'Negociação',
|
||||||
|
WON = 'Ganhos',
|
||||||
|
LOST = 'Perdidos',
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface User {
|
||||||
|
id: string;
|
||||||
|
tenant_id: string;
|
||||||
|
name: string;
|
||||||
|
email: string;
|
||||||
|
avatar_url: string;
|
||||||
|
role: 'super_admin' | 'admin' | 'manager' | 'agent';
|
||||||
|
team_id: string;
|
||||||
|
bio?: string;
|
||||||
|
status: 'active' | 'inactive';
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Attendance {
|
||||||
|
id: string;
|
||||||
|
tenant_id: string;
|
||||||
|
user_id: string;
|
||||||
|
created_at: string; // ISO Date
|
||||||
|
summary: string;
|
||||||
|
attention_points: string[];
|
||||||
|
improvement_points: string[];
|
||||||
|
score: number; // 0-100
|
||||||
|
first_response_time_min: number;
|
||||||
|
handling_time_min: number;
|
||||||
|
funnel_stage: FunnelStage;
|
||||||
|
origin: 'WhatsApp' | 'Instagram' | 'Website' | 'LinkedIn' | 'Referral';
|
||||||
|
product_requested: string;
|
||||||
|
product_sold?: string;
|
||||||
|
converted: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Tenant {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
logo_url?: string;
|
||||||
|
// Extended fields for Super Admin
|
||||||
|
slug?: string;
|
||||||
|
admin_email?: string;
|
||||||
|
status?: 'active' | 'inactive' | 'trial';
|
||||||
|
user_count?: number;
|
||||||
|
attendance_count?: number;
|
||||||
|
created_at?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DateRange {
|
||||||
|
start: Date;
|
||||||
|
end: Date;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DashboardFilter {
|
||||||
|
dateRange: DateRange;
|
||||||
|
userId?: string;
|
||||||
|
teamId?: string;
|
||||||
|
}
|
||||||
23
vite.config.ts
Normal file
23
vite.config.ts
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
import path from 'path';
|
||||||
|
import { defineConfig, loadEnv } from 'vite';
|
||||||
|
import react from '@vitejs/plugin-react';
|
||||||
|
|
||||||
|
export default defineConfig(({ mode }) => {
|
||||||
|
const env = loadEnv(mode, '.', '');
|
||||||
|
return {
|
||||||
|
server: {
|
||||||
|
port: 3000,
|
||||||
|
host: '0.0.0.0',
|
||||||
|
},
|
||||||
|
plugins: [react()],
|
||||||
|
define: {
|
||||||
|
'process.env.API_KEY': JSON.stringify(env.GEMINI_API_KEY),
|
||||||
|
'process.env.GEMINI_API_KEY': JSON.stringify(env.GEMINI_API_KEY)
|
||||||
|
},
|
||||||
|
resolve: {
|
||||||
|
alias: {
|
||||||
|
'@': path.resolve(__dirname, '.'),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user