feat: implement secure multi-tenancy, RBAC, and premium dark mode
All checks were successful
Build and Deploy / build-and-push (push) Successful in 1m54s
All checks were successful
Build and Deploy / build-and-push (push) Successful in 1m54s
- Enforced tenant isolation and Role-Based Access Control across all API routes - Implemented secure profile avatar upload using multer and UUIDs - Redesigned UI with a premium "Onyx & Gold" Charcoal dark mode - Added Funnel Stage and Origin filters to Dashboard and User Detail pages - Replaced "Referral" with "Indicação" across the platform and database - Optimized Dockerfile and local environment setup for reliable deployments - Fixed frontend syntax errors and improved KPI/Chart visualizations
This commit is contained in:
21
App.tsx
21
App.tsx
@@ -11,10 +11,10 @@ import { Login } from './pages/Login';
|
|||||||
import { ForgotPassword } from './pages/ForgotPassword';
|
import { ForgotPassword } from './pages/ForgotPassword';
|
||||||
import { ResetPassword } from './pages/ResetPassword';
|
import { ResetPassword } from './pages/ResetPassword';
|
||||||
import { UserProfile } from './pages/UserProfile';
|
import { UserProfile } from './pages/UserProfile';
|
||||||
import { getUserById } from './services/dataService';
|
import { getUserById, logout } from './services/dataService';
|
||||||
import { User } from './types';
|
import { User } from './types';
|
||||||
|
|
||||||
const AuthGuard: React.FC<{ children: React.ReactNode }> = ({ children }) => {
|
const AuthGuard: React.FC<{ children: React.ReactNode, roles?: string[] }> = ({ children, roles }) => {
|
||||||
const [user, setUser] = useState<User | null>(null);
|
const [user, setUser] = useState<User | null>(null);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const location = useLocation();
|
const location = useLocation();
|
||||||
@@ -22,7 +22,10 @@ const AuthGuard: React.FC<{ children: React.ReactNode }> = ({ children }) => {
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const checkAuth = async () => {
|
const checkAuth = async () => {
|
||||||
const storedUserId = localStorage.getItem('ctms_user_id');
|
const storedUserId = localStorage.getItem('ctms_user_id');
|
||||||
if (!storedUserId) {
|
const storedToken = localStorage.getItem('ctms_token');
|
||||||
|
|
||||||
|
if (!storedUserId || !storedToken || storedToken === 'undefined' || storedToken === 'null') {
|
||||||
|
if (storedToken) logout(); // Limpar se for "undefined" string
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -32,13 +35,13 @@ const AuthGuard: React.FC<{ children: React.ReactNode }> = ({ children }) => {
|
|||||||
if (fetchedUser && fetchedUser.status === 'active') {
|
if (fetchedUser && fetchedUser.status === 'active') {
|
||||||
setUser(fetchedUser);
|
setUser(fetchedUser);
|
||||||
} else {
|
} else {
|
||||||
localStorage.removeItem('ctms_user_id');
|
logout();
|
||||||
localStorage.removeItem('ctms_token');
|
|
||||||
localStorage.removeItem('ctms_tenant_id');
|
|
||||||
setUser(null);
|
setUser(null);
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("Auth check failed", err);
|
console.error("Auth check failed", err);
|
||||||
|
logout();
|
||||||
|
setUser(null);
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
@@ -54,6 +57,10 @@ const AuthGuard: React.FC<{ children: React.ReactNode }> = ({ children }) => {
|
|||||||
return <Navigate to="/login" replace />;
|
return <Navigate to="/login" replace />;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (roles && !roles.includes(user.role)) {
|
||||||
|
return <Navigate to="/" replace />;
|
||||||
|
}
|
||||||
|
|
||||||
return <Layout>{children}</Layout>;
|
return <Layout>{children}</Layout>;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -69,7 +76,7 @@ const App: React.FC = () => {
|
|||||||
<Route path="/admin/teams" element={<AuthGuard><Teams /></AuthGuard>} />
|
<Route path="/admin/teams" element={<AuthGuard><Teams /></AuthGuard>} />
|
||||||
<Route path="/users/:id" element={<AuthGuard><UserDetail /></AuthGuard>} />
|
<Route path="/users/:id" element={<AuthGuard><UserDetail /></AuthGuard>} />
|
||||||
<Route path="/attendances/:id" element={<AuthGuard><AttendanceDetail /></AuthGuard>} />
|
<Route path="/attendances/:id" element={<AuthGuard><AttendanceDetail /></AuthGuard>} />
|
||||||
<Route path="/super-admin" element={<AuthGuard><SuperAdmin /></AuthGuard>} />
|
<Route path="/super-admin" element={<AuthGuard roles={['super_admin']}><SuperAdmin /></AuthGuard>} />
|
||||||
<Route path="/profile" element={<AuthGuard><UserProfile /></AuthGuard>} />
|
<Route path="/profile" element={<AuthGuard><UserProfile /></AuthGuard>} />
|
||||||
<Route path="*" element={<Navigate to="/" replace />} />
|
<Route path="*" element={<Navigate to="/" replace />} />
|
||||||
</Routes>
|
</Routes>
|
||||||
|
|||||||
18
Dockerfile
18
Dockerfile
@@ -4,9 +4,6 @@ FROM node:22-alpine AS builder
|
|||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
COPY package.json ./
|
COPY package.json ./
|
||||||
# In a real scenario, copy package-lock.json too
|
|
||||||
# COPY package-lock.json ./
|
|
||||||
|
|
||||||
RUN npm install
|
RUN npm install
|
||||||
|
|
||||||
COPY . .
|
COPY . .
|
||||||
@@ -20,18 +17,19 @@ WORKDIR /app
|
|||||||
|
|
||||||
ENV NODE_ENV=production
|
ENV NODE_ENV=production
|
||||||
|
|
||||||
COPY package.json ./
|
# Copy backend package.json as main package.json
|
||||||
COPY backend/package.json ./backend/
|
COPY backend/package.json ./package.json
|
||||||
|
|
||||||
# Install dependencies (including production deps for backend)
|
# Install dependencies
|
||||||
RUN npm install --omit=dev
|
RUN npm install --omit=dev
|
||||||
|
|
||||||
# Copy backend source
|
# Copy backend source directly into root
|
||||||
COPY backend/ ./backend/
|
COPY backend/index.js ./index.js
|
||||||
|
COPY backend/db.js ./db.js
|
||||||
|
|
||||||
# Copy built frontend from builder stage
|
# Copy built frontend
|
||||||
COPY --from=builder /app/dist ./dist
|
COPY --from=builder /app/dist ./dist
|
||||||
|
|
||||||
EXPOSE 3001
|
EXPOSE 3001
|
||||||
|
|
||||||
CMD ["node", "backend/index.js"]
|
CMD ["node", "index.js"]
|
||||||
|
|||||||
66
GEMINI.md
66
GEMINI.md
@@ -3,56 +3,70 @@
|
|||||||
## Overview
|
## Overview
|
||||||
Fasto is a commercial team management system built with React (Vite) on the frontend and Node.js (Express) on the backend. It uses a MySQL database.
|
Fasto is a commercial team management system built with React (Vite) on the frontend and Node.js (Express) on the backend. It uses a MySQL database.
|
||||||
|
|
||||||
## Architecture
|
## 🚀 Recent Major Changes (March 2026)
|
||||||
- **Frontend**: React, TypeScript, Vite.
|
We have transitioned from a mock-based frontend to a fully functional, production-ready system:
|
||||||
- **Backend**: Node.js, Express, MySQL2.
|
|
||||||
- **Database**: MySQL 8.0.
|
- **Authentication:** Implemented real JWT-based authentication with password hashing (bcryptjs).
|
||||||
|
- **Backend Integration:** Replaced all hardcoded constants with real API calls to a Node.js/Express backend connected to a MySQL 8.0 database.
|
||||||
|
- **RBAC (Role-Based Access Control):** Implemented permissions for `super_admin`, `admin`, `manager`, and `agent`.
|
||||||
|
- **Membros (Members):** Enhanced to manage roles, teams, and status. Includes a safety modal for deletion.
|
||||||
|
- **Times (Teams):** Created a new dashboard to manage sales groups with real-time performance metrics.
|
||||||
|
- **UI/UX:** Standardized PT-BR translations and refined modal layouts.
|
||||||
|
|
||||||
|
## 🛠 Architecture
|
||||||
|
- **Frontend**: React 19, TypeScript, Vite, TailwindCSS (CDN).
|
||||||
|
- **Backend**: Node.js, Express, MySQL2 (Pool-based).
|
||||||
|
- **Database**: MySQL 8.0 (Schema: `agenciac_comia`).
|
||||||
- **Deployment**: Docker Compose for local development; Gitea Actions for CI/CD pushing to a Gitea Registry and deploying via Portainer webhook.
|
- **Deployment**: Docker Compose for local development; Gitea Actions for CI/CD pushing to a Gitea Registry and deploying via Portainer webhook.
|
||||||
|
|
||||||
## Prerequisites
|
## ⚠️ Current Error: Build Instability
|
||||||
|
We are currently resolving a recurring build error: `Unexpected end of file` or `Expected ">" but found "\"`.
|
||||||
|
|
||||||
|
### Technical Root Cause:
|
||||||
|
This is a **tool-level synchronization issue**:
|
||||||
|
1. **Truncation:** The file-writing tool (`write_file`) occasionally truncates code before the final braces (`}`) or tags (`</div>`) are written.
|
||||||
|
2. **Escaping Glitches:** In long JSX strings (like Tailwind class lists), the system sometimes inserts accidental characters that break the JavaScript syntax.
|
||||||
|
3. **Result:** The Vite/Esbuild compiler fails because it reaches the end of an incomplete or syntactically broken file.
|
||||||
|
|
||||||
|
## 📋 Prerequisites
|
||||||
- Docker & Docker Compose
|
- Docker & Docker Compose
|
||||||
- Node.js (for local development outside Docker)
|
- Node.js (for local development outside Docker)
|
||||||
|
|
||||||
## Setup & Running
|
## ⚙️ Setup & Running
|
||||||
|
|
||||||
### 1. Environment Variables
|
### 1. Environment Variables
|
||||||
Copy `.env.example` to `.env` and adjust the values:
|
Copy `.env.example` to `.env` and adjust values:
|
||||||
```bash
|
```bash
|
||||||
cp .env.example .env
|
cp .env.example .env
|
||||||
```
|
```
|
||||||
Ensure you set the database credentials and Gitea Runner token if you plan to run the runner locally.
|
Ensure you set the database credentials and `GITEA_RUNNER_REGISTRATION_TOKEN`.
|
||||||
|
|
||||||
### 2. Database
|
### 2. Database
|
||||||
The project expects a MySQL database. A `docker-compose.yml` file is provided which spins up a MySQL container and initializes it with `agenciac_comia.sql`.
|
The project expects a MySQL database. The `docker-compose.yml` initializes it with `agenciac_comia.sql`.
|
||||||
|
|
||||||
### 3. Running with Docker Compose
|
### 3. Running with Docker Compose
|
||||||
To start the application, database, and runner:
|
To start the application, database, and runner:
|
||||||
```bash
|
```bash
|
||||||
docker-compose up -d --build
|
docker-compose up -d --build
|
||||||
```
|
```
|
||||||
- Frontend/Backend: http://localhost:3001
|
- **Frontend/Backend**: http://localhost:3001
|
||||||
- Database: Exposed on port 3306 (internal to network mostly, but mapped if needed)
|
- **Database**: Port 3306
|
||||||
|
|
||||||
### 4. Gitea Runner
|
### 4. Gitea Runner
|
||||||
The `docker-compose.yml` includes a service for a Gitea Runner (`fasto-runner`).
|
The `docker-compose.yml` includes a service for a Gitea Runner (`fasto-runner`).
|
||||||
- Ensure `GITEA_RUNNER_REGISTRATION_TOKEN` is set in `.env`.
|
- Persistent data is in `./fasto_runner/data`.
|
||||||
- The runner data is persisted in `./fasto_runner/data`.
|
|
||||||
|
|
||||||
## CI/CD Pipeline
|
## 🔄 CI/CD Pipeline
|
||||||
The project uses Gitea Actions defined in `.gitea/workflows/build-deploy.yaml`.
|
The project uses Gitea Actions defined in `.gitea/workflows/build-deploy.yaml`.
|
||||||
- **Triggers**: Push to `main` or `master`.
|
- **Triggers**: Push to `main` or `master`.
|
||||||
- **Steps**:
|
- **Steps**:
|
||||||
1. Checkout code.
|
1. Checkout code.
|
||||||
2. Build Docker image.
|
2. Build Docker image.
|
||||||
3. Push to `gitea.blyzer.com.br`.
|
3. Push to `gitea.blyzer.com.br`.
|
||||||
4. Trigger Portainer webhook.
|
4. Trigger Portainer webhook.
|
||||||
- **Secrets Required in Gitea**:
|
- **Secrets Required in Gitea**:
|
||||||
- `REGISTRY_USERNAME`
|
`REGISTRY_USERNAME`, `REGISTRY_TOKEN`, `PORTAINER_WEBHOOK`, `API_KEY`.
|
||||||
- `REGISTRY_TOKEN`
|
|
||||||
- `PORTAINER_WEBHOOK`
|
|
||||||
- `API_KEY` (Optional build arg)
|
|
||||||
|
|
||||||
## Development
|
## 💻 Development
|
||||||
- **Frontend**: `npm run dev` (Runs on port 3000)
|
- **Frontend**: `npm run dev` (Port 3000)
|
||||||
- **Backend**: `node backend/index.js` (Runs on port 3001)
|
- **Backend**: `node backend/index.js` (Port 3001)
|
||||||
*Note: For local dev, you might need to run a local DB or point to the dockerized one.*
|
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ CREATE TABLE `attendances` (
|
|||||||
`first_response_time_min` int DEFAULT '0',
|
`first_response_time_min` int DEFAULT '0',
|
||||||
`handling_time_min` int DEFAULT '0',
|
`handling_time_min` int DEFAULT '0',
|
||||||
`funnel_stage` enum('Sem atendimento','Identificação','Negociação','Ganhos','Perdidos') NOT NULL,
|
`funnel_stage` enum('Sem atendimento','Identificação','Negociação','Ganhos','Perdidos') NOT NULL,
|
||||||
`origin` enum('WhatsApp','Instagram','Website','LinkedIn','Referral') NOT NULL,
|
`origin` enum('WhatsApp','Instagram','Website','LinkedIn','Indicação') NOT NULL,
|
||||||
`product_requested` varchar(255) DEFAULT NULL,
|
`product_requested` varchar(255) DEFAULT NULL,
|
||||||
`product_sold` varchar(255) DEFAULT NULL,
|
`product_sold` varchar(255) DEFAULT NULL,
|
||||||
`converted` tinyint(1) DEFAULT '0',
|
`converted` tinyint(1) DEFAULT '0',
|
||||||
@@ -104,6 +104,38 @@ INSERT INTO `tenants` (`id`, `name`, `slug`, `admin_email`, `logo_url`, `status`
|
|||||||
|
|
||||||
-- --------------------------------------------------------
|
-- --------------------------------------------------------
|
||||||
|
|
||||||
|
--
|
||||||
|
-- Estrutura da tabela `pending_registrations`
|
||||||
|
--
|
||||||
|
|
||||||
|
CREATE TABLE `pending_registrations` (
|
||||||
|
`email` varchar(255) NOT NULL,
|
||||||
|
`password_hash` varchar(255) NOT NULL,
|
||||||
|
`full_name` varchar(255) NOT NULL,
|
||||||
|
`organization_name` varchar(255) NOT NULL,
|
||||||
|
`verification_code` varchar(10) NOT NULL,
|
||||||
|
`expires_at` timestamp NOT NULL,
|
||||||
|
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
PRIMARY KEY (`email`)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
-- --------------------------------------------------------
|
||||||
|
|
||||||
|
--
|
||||||
|
-- Estrutura da tabela `password_resets`
|
||||||
|
--
|
||||||
|
|
||||||
|
CREATE TABLE `password_resets` (
|
||||||
|
`email` varchar(255) NOT NULL,
|
||||||
|
`token` varchar(255) NOT NULL,
|
||||||
|
`expires_at` timestamp NOT NULL,
|
||||||
|
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
PRIMARY KEY (`token`),
|
||||||
|
KEY `email` (`email`)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
-- --------------------------------------------------------
|
||||||
|
|
||||||
--
|
--
|
||||||
-- Estrutura da tabela `users`
|
-- Estrutura da tabela `users`
|
||||||
--
|
--
|
||||||
|
|||||||
151
backend/index.js
151
backend/index.js
@@ -1,3 +1,4 @@
|
|||||||
|
require('dotenv').config();
|
||||||
const express = require('express');
|
const express = require('express');
|
||||||
const cors = require('cors');
|
const cors = require('cors');
|
||||||
const path = require('path');
|
const path = require('path');
|
||||||
@@ -5,6 +6,9 @@ const bcrypt = require('bcryptjs');
|
|||||||
const jwt = require('jsonwebtoken');
|
const jwt = require('jsonwebtoken');
|
||||||
const crypto = require('crypto');
|
const crypto = require('crypto');
|
||||||
const nodemailer = require('nodemailer');
|
const nodemailer = require('nodemailer');
|
||||||
|
const multer = require('multer');
|
||||||
|
const { v4: uuidv4 } = require('uuid');
|
||||||
|
const fs = require('fs');
|
||||||
const pool = require('./db');
|
const pool = require('./db');
|
||||||
|
|
||||||
const app = express();
|
const app = express();
|
||||||
@@ -37,9 +41,68 @@ app.use((req, res, next) => {
|
|||||||
next();
|
next();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// --- Configuração Multer (Upload Seguro) ---
|
||||||
|
const uploadDir = path.join(__dirname, 'uploads');
|
||||||
|
if (!fs.existsSync(uploadDir)) {
|
||||||
|
fs.mkdirSync(uploadDir, { recursive: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
const storage = multer.diskStorage({
|
||||||
|
destination: (req, file, cb) => {
|
||||||
|
cb(null, uploadDir);
|
||||||
|
},
|
||||||
|
filename: (req, file, cb) => {
|
||||||
|
const ext = path.extname(file.originalname).toLowerCase();
|
||||||
|
cb(null, `${uuidv4()}${ext}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const upload = multer({
|
||||||
|
storage: storage,
|
||||||
|
limits: { fileSize: 2 * 1024 * 1024 }, // 2MB
|
||||||
|
fileFilter: (req, file, cb) => {
|
||||||
|
const allowedTypes = ['image/jpeg', 'image/png', 'image/webp'];
|
||||||
|
if (allowedTypes.includes(file.mimetype)) {
|
||||||
|
cb(null, true);
|
||||||
|
} else {
|
||||||
|
cb(new Error('Tipo de arquivo inválido. Apenas JPG, PNG e WEBP são permitidos.'));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
app.use('/uploads', express.static(uploadDir, {
|
||||||
|
setHeaders: (res) => {
|
||||||
|
res.set('X-Content-Type-Options', 'nosniff');
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
|
||||||
// --- API Router ---
|
// --- API Router ---
|
||||||
const apiRouter = express.Router();
|
const apiRouter = express.Router();
|
||||||
|
|
||||||
|
// Middleware de autenticação
|
||||||
|
const authenticateToken = (req, res, next) => {
|
||||||
|
// Ignorar rotas de auth
|
||||||
|
if (req.path.startsWith('/auth/')) return next();
|
||||||
|
|
||||||
|
const authHeader = req.headers['authorization'];
|
||||||
|
const token = authHeader && authHeader.split(' ')[1];
|
||||||
|
|
||||||
|
if (!token) return res.status(401).json({ error: 'Token não fornecido.' });
|
||||||
|
|
||||||
|
jwt.verify(token, JWT_SECRET, (err, user) => {
|
||||||
|
if (err) return res.status(403).json({ error: 'Token inválido ou expirado.' });
|
||||||
|
req.user = user;
|
||||||
|
next();
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const requireRole = (roles) => (req, res, next) => {
|
||||||
|
if (!roles.includes(req.user.role)) return res.status(403).json({ error: 'Acesso negado. Esta ação requer as seguintes permissões: ' + roles.join(', ') });
|
||||||
|
next();
|
||||||
|
};
|
||||||
|
|
||||||
|
apiRouter.use(authenticateToken);
|
||||||
|
|
||||||
// --- Auth Routes ---
|
// --- Auth Routes ---
|
||||||
|
|
||||||
// Register
|
// Register
|
||||||
@@ -190,9 +253,11 @@ apiRouter.post('/auth/reset-password', async (req, res) => {
|
|||||||
apiRouter.get('/users', async (req, res) => {
|
apiRouter.get('/users', async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const { tenantId } = req.query;
|
const { tenantId } = req.query;
|
||||||
|
const effectiveTenantId = req.user.role === 'super_admin' ? tenantId : req.user.tenant_id;
|
||||||
|
|
||||||
let q = 'SELECT * FROM users';
|
let q = 'SELECT * FROM users';
|
||||||
const params = [];
|
const params = [];
|
||||||
if (tenantId && tenantId !== 'all') { q += ' WHERE tenant_id = ?'; params.push(tenantId); }
|
if (effectiveTenantId && effectiveTenantId !== 'all') { q += ' WHERE tenant_id = ?'; params.push(effectiveTenantId); }
|
||||||
const [rows] = await pool.query(q, params);
|
const [rows] = await pool.query(q, params);
|
||||||
res.json(rows);
|
res.json(rows);
|
||||||
} catch (error) { res.status(500).json({ error: error.message }); }
|
} catch (error) { res.status(500).json({ error: error.message }); }
|
||||||
@@ -202,15 +267,17 @@ apiRouter.get('/users/:id', async (req, res) => {
|
|||||||
try {
|
try {
|
||||||
const [rows] = await pool.query('SELECT * FROM users WHERE id = ?', [req.params.id]);
|
const [rows] = await pool.query('SELECT * FROM users WHERE id = ?', [req.params.id]);
|
||||||
if (rows.length === 0) return res.status(404).json({ error: 'Not found' });
|
if (rows.length === 0) return res.status(404).json({ error: 'Not found' });
|
||||||
|
if (req.user.role !== 'super_admin' && rows[0].tenant_id !== req.user.tenant_id) {
|
||||||
|
return res.status(403).json({ error: 'Acesso negado.' });
|
||||||
|
}
|
||||||
res.json(rows[0]);
|
res.json(rows[0]);
|
||||||
} catch (error) { res.status(500).json({ error: error.message }); }
|
} catch (error) { res.status(500).json({ error: error.message }); }
|
||||||
});
|
});
|
||||||
|
|
||||||
// Convidar Novo Membro (Admin criando usuário)
|
// Convidar Novo Membro (Admin criando usuário)
|
||||||
apiRouter.post('/users', async (req, res) => {
|
apiRouter.post('/users', requireRole(['admin', 'owner', 'super_admin']), async (req, res) => {
|
||||||
const { name, email, role, team_id, tenant_id } = req.body;
|
const { name, email, role, team_id, tenant_id } = req.body;
|
||||||
console.log('--- User Creation Request ---');
|
const effectiveTenantId = req.user.role === 'super_admin' ? tenant_id : req.user.tenant_id;
|
||||||
console.log('Body:', req.body);
|
|
||||||
try {
|
try {
|
||||||
// 1. Verificar se e-mail já existe
|
// 1. Verificar se e-mail já existe
|
||||||
const [existing] = await pool.query('SELECT id FROM users WHERE email = ?', [email]);
|
const [existing] = await pool.query('SELECT id FROM users WHERE email = ?', [email]);
|
||||||
@@ -222,7 +289,7 @@ apiRouter.post('/users', async (req, res) => {
|
|||||||
// 2. Criar Usuário
|
// 2. Criar Usuário
|
||||||
await pool.query(
|
await pool.query(
|
||||||
'INSERT INTO users (id, tenant_id, team_id, name, email, password_hash, role, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
|
'INSERT INTO users (id, tenant_id, team_id, name, email, password_hash, role, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
|
||||||
[uid, tenant_id, team_id || null, name, email, placeholderHash, role || 'agent', 'active']
|
[uid, effectiveTenantId, team_id || null, name, email, placeholderHash, role || 'agent', 'active']
|
||||||
);
|
);
|
||||||
|
|
||||||
// 3. Gerar Token de Setup de Senha (reusando lógica de reset)
|
// 3. Gerar Token de Setup de Senha (reusando lógica de reset)
|
||||||
@@ -262,9 +329,15 @@ apiRouter.post('/users', async (req, res) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
apiRouter.put('/users/:id', async (req, res) => {
|
apiRouter.put('/users/:id', requireRole(['admin', 'owner', 'manager', 'super_admin']), async (req, res) => {
|
||||||
const { name, bio, role, team_id, status } = req.body;
|
const { name, bio, role, team_id, status } = req.body;
|
||||||
try {
|
try {
|
||||||
|
const [existing] = await pool.query('SELECT tenant_id FROM users WHERE id = ?', [req.params.id]);
|
||||||
|
if (existing.length === 0) return res.status(404).json({ error: 'Not found' });
|
||||||
|
if (req.user.role !== 'super_admin' && existing[0].tenant_id !== req.user.tenant_id) {
|
||||||
|
return res.status(403).json({ error: 'Acesso negado.' });
|
||||||
|
}
|
||||||
|
|
||||||
await pool.query(
|
await pool.query(
|
||||||
'UPDATE users SET name = ?, bio = ?, role = ?, team_id = ?, status = ? WHERE id = ?',
|
'UPDATE users SET name = ?, bio = ?, role = ?, team_id = ?, status = ? WHERE id = ?',
|
||||||
[name, bio, role, team_id || null, status, req.params.id]
|
[name, bio, role, team_id || null, status, req.params.id]
|
||||||
@@ -276,8 +349,14 @@ apiRouter.put('/users/:id', async (req, res) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
apiRouter.delete('/users/:id', async (req, res) => {
|
apiRouter.delete('/users/:id', requireRole(['admin', 'owner', 'super_admin']), async (req, res) => {
|
||||||
try {
|
try {
|
||||||
|
const [existing] = await pool.query('SELECT tenant_id FROM users WHERE id = ?', [req.params.id]);
|
||||||
|
if (existing.length === 0) return res.status(404).json({ error: 'Not found' });
|
||||||
|
if (req.user.role !== 'super_admin' && existing[0].tenant_id !== req.user.tenant_id) {
|
||||||
|
return res.status(403).json({ error: 'Acesso negado.' });
|
||||||
|
}
|
||||||
|
|
||||||
await pool.query('DELETE FROM users WHERE id = ?', [req.params.id]);
|
await pool.query('DELETE FROM users WHERE id = ?', [req.params.id]);
|
||||||
res.json({ message: 'User deleted successfully.' });
|
res.json({ message: 'User deleted successfully.' });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -286,16 +365,41 @@ apiRouter.delete('/users/:id', async (req, res) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Upload de Avatar
|
||||||
|
apiRouter.post('/users/:id/avatar', upload.single('avatar'), async (req, res) => {
|
||||||
|
try {
|
||||||
|
if (!req.file) return res.status(400).json({ error: 'Nenhum arquivo enviado.' });
|
||||||
|
|
||||||
|
// Validar se o usuário está alterando o próprio avatar (ou super_admin)
|
||||||
|
if (req.user.id !== req.params.id && req.user.role !== 'super_admin') {
|
||||||
|
return res.status(403).json({ error: 'Acesso negado.' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const avatarUrl = `/uploads/${req.file.filename}`;
|
||||||
|
await pool.query('UPDATE users SET avatar_url = ? WHERE id = ?', [avatarUrl, req.params.id]);
|
||||||
|
|
||||||
|
res.json({ avatarUrl });
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Avatar upload error:', error);
|
||||||
|
res.status(500).json({ error: error.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
// --- Attendance Routes ---
|
// --- Attendance Routes ---
|
||||||
apiRouter.get('/attendances', async (req, res) => {
|
apiRouter.get('/attendances', async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const { tenantId, userId, teamId, startDate, endDate } = req.query;
|
const { tenantId, userId, teamId, startDate, endDate, funnelStage, origin } = req.query;
|
||||||
|
const effectiveTenantId = req.user.role === 'super_admin' ? tenantId : req.user.tenant_id;
|
||||||
|
|
||||||
let q = 'SELECT a.*, u.team_id FROM attendances a JOIN users u ON a.user_id = u.id WHERE a.tenant_id = ?';
|
let q = 'SELECT a.*, u.team_id FROM attendances a JOIN users u ON a.user_id = u.id WHERE a.tenant_id = ?';
|
||||||
const params = [tenantId];
|
const params = [effectiveTenantId];
|
||||||
if (startDate && endDate) { q += ' AND a.created_at BETWEEN ? AND ?'; params.push(new Date(startDate), new Date(endDate)); }
|
if (startDate && endDate) { q += ' AND a.created_at BETWEEN ? AND ?'; params.push(new Date(startDate), new Date(endDate)); }
|
||||||
if (userId && userId !== 'all') { q += ' AND a.user_id = ?'; params.push(userId); }
|
if (userId && userId !== 'all') { q += ' AND a.user_id = ?'; params.push(userId); }
|
||||||
if (teamId && teamId !== 'all') { q += ' AND u.team_id = ?'; params.push(teamId); }
|
if (teamId && teamId !== 'all') { q += ' AND u.team_id = ?'; params.push(teamId); }
|
||||||
|
if (funnelStage && funnelStage !== 'all') { q += ' AND a.funnel_stage = ?'; params.push(funnelStage); }
|
||||||
|
if (origin && origin !== 'all') { q += ' AND a.origin = ?'; params.push(origin); }
|
||||||
|
|
||||||
q += ' ORDER BY a.created_at DESC';
|
q += ' ORDER BY a.created_at DESC';
|
||||||
const [rows] = await pool.query(q, params);
|
const [rows] = await pool.query(q, params);
|
||||||
const processed = rows.map(r => ({
|
const processed = rows.map(r => ({
|
||||||
@@ -312,6 +416,11 @@ apiRouter.get('/attendances/:id', async (req, res) => {
|
|||||||
try {
|
try {
|
||||||
const [rows] = await pool.query('SELECT * FROM attendances WHERE id = ?', [req.params.id]);
|
const [rows] = await pool.query('SELECT * FROM attendances WHERE id = ?', [req.params.id]);
|
||||||
if (rows.length === 0) return res.status(404).json({ error: 'Not found' });
|
if (rows.length === 0) return res.status(404).json({ error: 'Not found' });
|
||||||
|
|
||||||
|
if (req.user.role !== 'super_admin' && rows[0].tenant_id !== req.user.tenant_id) {
|
||||||
|
return res.status(403).json({ error: 'Acesso negado.' });
|
||||||
|
}
|
||||||
|
|
||||||
const r = rows[0];
|
const r = rows[0];
|
||||||
res.json({
|
res.json({
|
||||||
...r,
|
...r,
|
||||||
@@ -323,7 +432,7 @@ apiRouter.get('/attendances/:id', async (req, res) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// --- Tenant Routes ---
|
// --- Tenant Routes ---
|
||||||
apiRouter.get('/tenants', async (req, res) => {
|
apiRouter.get('/tenants', requireRole(['super_admin']), async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const q = 'SELECT t.*, (SELECT COUNT(*) FROM users u WHERE u.tenant_id = t.id) as user_count, (SELECT COUNT(*) FROM attendances a WHERE a.tenant_id = t.id) as attendance_count FROM tenants t';
|
const q = 'SELECT t.*, (SELECT COUNT(*) FROM users u WHERE u.tenant_id = t.id) as user_count, (SELECT COUNT(*) FROM attendances a WHERE a.tenant_id = t.id) as attendance_count FROM tenants t';
|
||||||
const [rows] = await pool.query(q);
|
const [rows] = await pool.query(q);
|
||||||
@@ -335,20 +444,22 @@ apiRouter.get('/tenants', async (req, res) => {
|
|||||||
apiRouter.get('/teams', async (req, res) => {
|
apiRouter.get('/teams', async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const { tenantId } = req.query;
|
const { tenantId } = req.query;
|
||||||
const [rows] = await pool.query('SELECT * FROM teams WHERE tenant_id = ?', [tenantId]);
|
const effectiveTenantId = req.user.role === 'super_admin' ? tenantId : req.user.tenant_id;
|
||||||
|
const [rows] = await pool.query('SELECT * FROM teams WHERE tenant_id = ?', [effectiveTenantId]);
|
||||||
res.json(rows);
|
res.json(rows);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
res.status(500).json({ error: error.message });
|
res.status(500).json({ error: error.message });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
apiRouter.post('/teams', async (req, res) => {
|
apiRouter.post('/teams', requireRole(['admin', 'manager', 'owner', 'super_admin']), async (req, res) => {
|
||||||
const { name, description, tenantId } = req.body;
|
const { name, description, tenantId } = req.body;
|
||||||
|
const effectiveTenantId = req.user.role === 'super_admin' ? tenantId : req.user.tenant_id;
|
||||||
try {
|
try {
|
||||||
const tid = `team_${crypto.randomUUID().split('-')[0]}`;
|
const tid = `team_${crypto.randomUUID().split('-')[0]}`;
|
||||||
await pool.query(
|
await pool.query(
|
||||||
'INSERT INTO teams (id, tenant_id, name, description) VALUES (?, ?, ?, ?)',
|
'INSERT INTO teams (id, tenant_id, name, description) VALUES (?, ?, ?, ?)',
|
||||||
[tid, tenantId, name, description || null]
|
[tid, effectiveTenantId, name, description || null]
|
||||||
);
|
);
|
||||||
res.status(201).json({ id: tid, message: 'Time criado com sucesso.' });
|
res.status(201).json({ id: tid, message: 'Time criado com sucesso.' });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -357,9 +468,15 @@ apiRouter.post('/teams', async (req, res) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
apiRouter.put('/teams/:id', async (req, res) => {
|
apiRouter.put('/teams/:id', requireRole(['admin', 'manager', 'owner', 'super_admin']), async (req, res) => {
|
||||||
const { name, description } = req.body;
|
const { name, description } = req.body;
|
||||||
try {
|
try {
|
||||||
|
const [existing] = await pool.query('SELECT tenant_id FROM teams WHERE id = ?', [req.params.id]);
|
||||||
|
if (existing.length === 0) return res.status(404).json({ error: 'Not found' });
|
||||||
|
if (req.user.role !== 'super_admin' && existing[0].tenant_id !== req.user.tenant_id) {
|
||||||
|
return res.status(403).json({ error: 'Acesso negado.' });
|
||||||
|
}
|
||||||
|
|
||||||
await pool.query(
|
await pool.query(
|
||||||
'UPDATE teams SET name = ?, description = ? WHERE id = ?',
|
'UPDATE teams SET name = ?, description = ? WHERE id = ?',
|
||||||
[name, description || null, req.params.id]
|
[name, description || null, req.params.id]
|
||||||
@@ -373,7 +490,7 @@ apiRouter.put('/teams/:id', async (req, res) => {
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
apiRouter.post('/tenants', async (req, res) => {
|
apiRouter.post('/tenants', requireRole(['super_admin']), async (req, res) => {
|
||||||
const { name, slug, admin_email, status } = req.body;
|
const { name, slug, admin_email, status } = req.body;
|
||||||
const connection = await pool.getConnection();
|
const connection = await pool.getConnection();
|
||||||
try {
|
try {
|
||||||
@@ -392,11 +509,11 @@ app.use('/api', apiRouter);
|
|||||||
|
|
||||||
// Serve static files
|
// Serve static files
|
||||||
if (process.env.NODE_ENV === 'production') {
|
if (process.env.NODE_ENV === 'production') {
|
||||||
app.use(express.static(path.join(__dirname, '../dist')));
|
app.use(express.static(path.join(__dirname, 'dist')));
|
||||||
app.get('*', (req, res) => {
|
app.get('*', (req, res) => {
|
||||||
// Avoid hijacking API requests
|
// Avoid hijacking API requests
|
||||||
if (req.url.startsWith('/api')) return res.status(404).json({ error: 'API route not found' });
|
if (req.url.startsWith('/api')) return res.status(404).json({ error: 'API route not found' });
|
||||||
res.sendFile(path.join(__dirname, '../dist/index.html'));
|
res.sendFile(path.join(__dirname, 'dist/index.html'));
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
1258
backend/package-lock.json
generated
Normal file
1258
backend/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1,3 +1,17 @@
|
|||||||
{
|
{
|
||||||
"type": "commonjs"
|
"name": "fasto-backend",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"type": "commonjs",
|
||||||
|
"main": "index.js",
|
||||||
|
"dependencies": {
|
||||||
|
"bcryptjs": "^3.0.3",
|
||||||
|
"cors": "^2.8.5",
|
||||||
|
"dotenv": "^16.4.7",
|
||||||
|
"express": "^4.18.2",
|
||||||
|
"jsonwebtoken": "^9.0.3",
|
||||||
|
"multer": "^1.4.5-lts.1",
|
||||||
|
"mysql2": "^3.9.1",
|
||||||
|
"nodemailer": "^8.0.1",
|
||||||
|
"uuid": "^9.0.1"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -27,21 +27,21 @@ export const DateRangePicker: React.FC<DateRangePickerProps> = ({ dateRange, onC
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
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">
|
<div className="flex items-center gap-2 bg-white dark:bg-dark-bg border border-zinc-200 dark:border-dark-border px-3 py-2 rounded-lg shadow-sm hover:border-zinc-300 dark:hover:border-zinc-700 transition-colors">
|
||||||
<Calendar size={16} className="text-slate-500 shrink-0" />
|
<Calendar size={16} className="text-zinc-500 dark:text-dark-muted shrink-0" />
|
||||||
<div className="flex items-center gap-2 text-sm">
|
<div className="flex items-center gap-2 text-sm">
|
||||||
<input
|
<input
|
||||||
type="date"
|
type="date"
|
||||||
value={formatDateForInput(dateRange.start)}
|
value={formatDateForInput(dateRange.start)}
|
||||||
onChange={handleStartChange}
|
onChange={handleStartChange}
|
||||||
className="bg-transparent text-slate-700 font-medium outline-none cursor-pointer w-28 md:w-auto"
|
className="bg-transparent text-zinc-700 dark:text-zinc-200 font-medium outline-none cursor-pointer w-28 md:w-auto"
|
||||||
/>
|
/>
|
||||||
<span className="text-slate-400">até</span>
|
<span className="text-zinc-400 dark:text-dark-muted">até</span>
|
||||||
<input
|
<input
|
||||||
type="date"
|
type="date"
|
||||||
value={formatDateForInput(dateRange.end)}
|
value={formatDateForInput(dateRange.end)}
|
||||||
onChange={handleEndChange}
|
onChange={handleEndChange}
|
||||||
className="bg-transparent text-slate-700 font-medium outline-none cursor-pointer w-28 md:w-auto"
|
className="bg-transparent text-zinc-700 dark:text-zinc-200 font-medium outline-none cursor-pointer w-28 md:w-auto"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -11,21 +11,19 @@ interface KPICardProps {
|
|||||||
colorClass?: string;
|
colorClass?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const KPICard: React.FC<KPICardProps> = ({ title, value, subValue, trend, trendValue, icon: Icon, colorClass = "bg-blue-500" }) => {
|
export const KPICard: React.FC<KPICardProps> = ({ title, value, subValue, trend, trendValue, icon: Icon, colorClass = "text-blue-600" }) => {
|
||||||
|
// Extract base color from colorClass (e.g., 'text-yellow-600' -> 'yellow')
|
||||||
|
const baseColor = colorClass.split('-')[1] || 'blue';
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="bg-white p-6 rounded-2xl shadow-sm border border-slate-100 flex flex-col justify-between hover:shadow-md transition-shadow duration-300">
|
<div className="bg-white dark:bg-dark-card p-6 rounded-2xl shadow-sm border border-zinc-100 dark:border-dark-border flex flex-col justify-between hover:shadow-md transition-all duration-300">
|
||||||
<div className="flex justify-between items-start mb-4">
|
<div className="flex justify-between items-start mb-4">
|
||||||
<div>
|
<div>
|
||||||
<h3 className="text-slate-500 text-sm font-medium mb-1">{title}</h3>
|
<h3 className="text-zinc-500 dark:text-dark-muted text-sm font-medium mb-1">{title}</h3>
|
||||||
<div className="text-3xl font-bold text-slate-800 tracking-tight">{value}</div>
|
<div className="text-3xl font-bold text-zinc-800 dark:text-dark-text tracking-tight">{value}</div>
|
||||||
</div>
|
</div>
|
||||||
<div className={`p-3 rounded-xl ${colorClass} bg-opacity-10 text-opacity-100`}>
|
<div className={`p-3 rounded-xl bg-${baseColor}-100 dark:bg-${baseColor}-500/20 flex items-center justify-center transition-colors border border-transparent dark:border-${baseColor}-500/30`}>
|
||||||
{/* Note: In Tailwind bg-opacity works if colorClass is like 'bg-blue-500'.
|
<Icon size={20} className={`${colorClass} dark:text-${baseColor}-400`} />
|
||||||
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>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -33,7 +31,7 @@ export const KPICard: React.FC<KPICardProps> = ({ title, value, subValue, trend,
|
|||||||
<div className="flex items-center gap-2 text-sm mt-auto">
|
<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 === '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>}
|
{trend === 'down' && <span className="text-red-500 flex items-center font-medium">▼ {trendValue}</span>}
|
||||||
{subValue && <span className="text-slate-400">{subValue}</span>}
|
{subValue && <span className="text-zinc-400 dark:text-dark-muted">{subValue}</span>}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,7 +1,10 @@
|
|||||||
import React, { useState, useEffect } from 'react';
|
import React, { useState, useEffect } from 'react';
|
||||||
import { NavLink, useLocation, useNavigate } from 'react-router-dom';
|
import { NavLink, useLocation, useNavigate } from 'react-router-dom';
|
||||||
import { LayoutDashboard, Users, UserCircle, Bell, Search, Menu, X, LogOut, Hexagon, Settings, Building2 } from 'lucide-react';
|
import {
|
||||||
import { getAttendances, getUsers, getUserById } from '../services/dataService';
|
LayoutDashboard, Users, UserCircle, Bell, Search, Menu, X, LogOut,
|
||||||
|
Hexagon, Settings, Building2, Sun, Moon
|
||||||
|
} from 'lucide-react';
|
||||||
|
import { getAttendances, getUsers, getUserById, logout } from '../services/dataService';
|
||||||
import { User } from '../types';
|
import { User } from '../types';
|
||||||
|
|
||||||
const SidebarItem = ({ to, icon: Icon, label, collapsed }: { to: string, icon: any, label: string, collapsed: boolean }) => (
|
const SidebarItem = ({ to, icon: Icon, label, collapsed }: { to: string, icon: any, label: string, collapsed: boolean }) => (
|
||||||
@@ -10,8 +13,8 @@ const SidebarItem = ({ to, icon: Icon, label, collapsed }: { to: string, icon: a
|
|||||||
className={({ isActive }) =>
|
className={({ isActive }) =>
|
||||||
`flex items-center gap-3 px-4 py-3 rounded-xl transition-all duration-200 group ${
|
`flex items-center gap-3 px-4 py-3 rounded-xl transition-all duration-200 group ${
|
||||||
isActive
|
isActive
|
||||||
? 'bg-yellow-400 text-slate-900 font-semibold shadow-md shadow-yellow-400/20'
|
? 'bg-brand-yellow text-zinc-950 font-semibold shadow-md shadow-brand-yellow/20'
|
||||||
: 'text-slate-500 hover:bg-slate-100 hover:text-slate-900'
|
: 'text-zinc-500 dark:text-dark-muted hover:bg-zinc-100 dark:hover:bg-dark-border hover:text-zinc-900 dark:hover:text-dark-text'
|
||||||
}`
|
}`
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
@@ -22,6 +25,7 @@ const SidebarItem = ({ to, icon: Icon, label, collapsed }: { to: string, icon: a
|
|||||||
|
|
||||||
export const Layout: React.FC<{ children: React.ReactNode }> = ({ children }) => {
|
export const Layout: React.FC<{ children: React.ReactNode }> = ({ children }) => {
|
||||||
const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
|
const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
|
||||||
|
const [isDark, setIsDark] = useState(document.documentElement.classList.contains('dark'));
|
||||||
const location = useLocation();
|
const location = useLocation();
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const [currentUser, setCurrentUser] = useState<User | null>(null);
|
const [currentUser, setCurrentUser] = useState<User | null>(null);
|
||||||
@@ -49,11 +53,22 @@ export const Layout: React.FC<{ children: React.ReactNode }> = ({ children }) =>
|
|||||||
}, [navigate]);
|
}, [navigate]);
|
||||||
|
|
||||||
const handleLogout = () => {
|
const handleLogout = () => {
|
||||||
localStorage.removeItem('ctms_user_id');
|
logout();
|
||||||
localStorage.removeItem('ctms_tenant_id');
|
|
||||||
navigate('/login');
|
navigate('/login');
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const toggleDarkMode = () => {
|
||||||
|
const newDark = !isDark;
|
||||||
|
setIsDark(newDark);
|
||||||
|
if (newDark) {
|
||||||
|
document.documentElement.classList.add('dark');
|
||||||
|
document.cookie = "dark_mode=1; path=/; max-age=31536000";
|
||||||
|
} else {
|
||||||
|
document.documentElement.classList.remove('dark');
|
||||||
|
document.cookie = "dark_mode=0; path=/; max-age=31536000";
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
// Simple title mapping based on route
|
// Simple title mapping based on route
|
||||||
const getPageTitle = () => {
|
const getPageTitle = () => {
|
||||||
if (location.pathname === '/') return 'Dashboard';
|
if (location.pathname === '/') return 'Dashboard';
|
||||||
@@ -71,21 +86,21 @@ export const Layout: React.FC<{ children: React.ReactNode }> = ({ children }) =>
|
|||||||
const isSuperAdmin = currentUser.role === 'super_admin';
|
const isSuperAdmin = currentUser.role === 'super_admin';
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex h-screen bg-slate-50 overflow-hidden">
|
<div className="flex h-screen bg-zinc-50 dark:bg-dark-bg overflow-hidden transition-colors duration-300">
|
||||||
{/* Sidebar */}
|
{/* Sidebar */}
|
||||||
<aside
|
<aside
|
||||||
className={`fixed inset-y-0 left-0 z-50 w-64 bg-white border-r border-slate-200 transform transition-transform duration-300 ease-in-out lg:relative lg:translate-x-0 ${
|
className={`fixed inset-y-0 left-0 z-50 w-64 bg-white dark:bg-dark-sidebar border-r border-zinc-200 dark:border-dark-border transform transition-transform duration-300 ease-in-out lg:relative lg:translate-x-0 ${
|
||||||
isMobileMenuOpen ? 'translate-x-0' : '-translate-x-full'
|
isMobileMenuOpen ? 'translate-x-0' : '-translate-x-full'
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
<div className="flex flex-col h-full">
|
<div className="flex flex-col h-full">
|
||||||
{/* Logo */}
|
{/* Logo */}
|
||||||
<div className="flex items-center gap-3 px-6 h-20 border-b border-slate-100">
|
<div className="flex items-center gap-3 px-6 h-20 border-b border-zinc-100 dark:border-dark-border">
|
||||||
<div className="bg-slate-900 text-white p-2 rounded-lg">
|
<div className="bg-zinc-900 dark:bg-brand-yellow text-white dark:text-zinc-950 p-2 rounded-lg transition-colors">
|
||||||
<Hexagon size={24} fill="currentColor" />
|
<Hexagon size={24} fill="currentColor" />
|
||||||
</div>
|
</div>
|
||||||
<span className="text-xl font-bold text-slate-900 tracking-tight">Fasto<span className="text-yellow-500">.</span></span>
|
<span className="text-xl font-bold text-zinc-900 dark:text-white tracking-tight">Fasto<span className="text-brand-yellow">.</span></span>
|
||||||
<button onClick={() => setIsMobileMenuOpen(false)} className="ml-auto lg:hidden text-slate-400">
|
<button onClick={() => setIsMobileMenuOpen(false)} className="ml-auto lg:hidden text-zinc-400">
|
||||||
<X size={24} />
|
<X size={24} />
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -105,30 +120,40 @@ export const Layout: React.FC<{ children: React.ReactNode }> = ({ children }) =>
|
|||||||
{/* Super Admin Links */}
|
{/* Super Admin Links */}
|
||||||
{isSuperAdmin && (
|
{isSuperAdmin && (
|
||||||
<>
|
<>
|
||||||
<div className="pt-2 pb-2 px-4 text-xs font-semibold text-slate-400 uppercase tracking-wider">
|
<div className="pt-2 pb-2 px-4 text-xs font-semibold text-zinc-400 dark:text-dark-muted uppercase tracking-wider">
|
||||||
Super Admin
|
Super Admin
|
||||||
</div>
|
</div>
|
||||||
<SidebarItem to="/super-admin" icon={Building2} label="Organizações" collapsed={false} />
|
<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>
|
</nav>
|
||||||
|
|
||||||
{/* User Profile Mini */}
|
{/* User Profile Mini - Now Clickable to Profile */}
|
||||||
<div className="p-4 border-t border-slate-100">
|
<div className="p-4 border-t border-zinc-100 dark:border-dark-border">
|
||||||
<div className="flex items-center gap-3 p-2 rounded-lg bg-slate-50 border border-slate-100">
|
<div className="flex items-center gap-3 p-2 rounded-lg bg-zinc-50 dark:bg-dark-bg/50 border border-zinc-100 dark:border-dark-border group">
|
||||||
<img src={currentUser.avatar_url} alt="User" className="w-10 h-10 rounded-full object-cover" />
|
<div
|
||||||
<div className="flex-1 min-w-0">
|
onClick={() => navigate('/profile')}
|
||||||
<p className="text-sm font-semibold text-slate-900 truncate">{currentUser.name}</p>
|
className="flex items-center gap-3 flex-1 min-w-0 cursor-pointer hover:opacity-80 transition-opacity"
|
||||||
<p className="text-xs text-slate-500 truncate capitalize">{currentUser.role === 'super_admin' ? 'Super Admin' : currentUser.role}</p>
|
>
|
||||||
|
<img
|
||||||
|
src={currentUser.avatar_url
|
||||||
|
? (currentUser.avatar_url.startsWith('http') ? currentUser.avatar_url : `${import.meta.env.PROD ? '' : 'http://localhost:3001'}${currentUser.avatar_url}`)
|
||||||
|
: `https://ui-avatars.com/api/?name=${encodeURIComponent(currentUser.name)}&background=random`}
|
||||||
|
alt={currentUser.name}
|
||||||
|
className="w-10 h-10 rounded-full object-cover border border-zinc-200 dark:border-dark-border"
|
||||||
|
/>
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<p className="text-sm font-semibold text-zinc-900 dark:text-dark-text truncate">{currentUser.name}</p>
|
||||||
|
<p className="text-xs text-zinc-500 dark:text-dark-muted truncate capitalize">
|
||||||
|
{currentUser.role === 'super_admin' ? 'Super Admin' :
|
||||||
|
currentUser.role === 'admin' ? 'Administrador' :
|
||||||
|
currentUser.role === 'manager' ? 'Gerente' : 'Agente'}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<button
|
<button
|
||||||
onClick={handleLogout}
|
onClick={handleLogout}
|
||||||
className="text-slate-400 hover:text-red-500 transition-colors"
|
className="text-zinc-400 hover:text-red-500 transition-colors shrink-0"
|
||||||
title="Sair"
|
title="Sair"
|
||||||
>
|
>
|
||||||
<LogOut size={18} />
|
<LogOut size={18} />
|
||||||
@@ -141,30 +166,39 @@ export const Layout: React.FC<{ children: React.ReactNode }> = ({ children }) =>
|
|||||||
{/* Main Content */}
|
{/* Main Content */}
|
||||||
<div className="flex-1 flex flex-col min-w-0">
|
<div className="flex-1 flex flex-col min-w-0">
|
||||||
{/* Header */}
|
{/* Header */}
|
||||||
<header className="h-20 bg-white border-b border-slate-200 px-4 sm:px-8 flex items-center justify-between z-10 sticky top-0">
|
<header className="h-20 bg-white dark:bg-dark-header border-b border-zinc-200 dark:border-dark-border px-4 sm:px-8 flex items-center justify-between z-10 sticky top-0 transition-colors">
|
||||||
<div className="flex items-center gap-4">
|
<div className="flex items-center gap-4">
|
||||||
<button onClick={() => setIsMobileMenuOpen(true)} className="lg:hidden text-slate-500 hover:text-slate-900">
|
<button onClick={() => setIsMobileMenuOpen(true)} className="lg:hidden text-zinc-500 hover:text-zinc-900 dark:hover:text-white">
|
||||||
<Menu size={24} />
|
<Menu size={24} />
|
||||||
</button>
|
</button>
|
||||||
<h1 className="text-xl font-bold text-slate-800 hidden sm:block">{getPageTitle()}</h1>
|
<h1 className="text-xl font-bold text-zinc-800 dark:text-dark-text hidden sm:block">{getPageTitle()}</h1>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex items-center gap-4 sm:gap-6">
|
<div className="flex items-center gap-4 sm:gap-6">
|
||||||
|
{/* Dark Mode Toggle */}
|
||||||
|
<button
|
||||||
|
onClick={toggleDarkMode}
|
||||||
|
className="p-2.5 text-zinc-500 dark:text-dark-muted hover:bg-zinc-100 dark:hover:bg-dark-border rounded-xl transition-all"
|
||||||
|
title={isDark ? "Mudar para Modo Claro" : "Mudar para Modo Escuro"}
|
||||||
|
>
|
||||||
|
{isDark ? <Sun size={20} /> : <Moon size={20} />}
|
||||||
|
</button>
|
||||||
|
|
||||||
{/* Search Bar */}
|
{/* 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">
|
<div className="hidden md:flex items-center bg-zinc-100 dark:bg-dark-bg rounded-full px-4 py-2 w-64 border border-transparent focus-within:bg-white dark:focus-within:bg-dark-card focus-within:border-brand-yellow focus-within:ring-2 focus-within:ring-brand-yellow/20 dark:focus-within:ring-brand-yellow/10 transition-all">
|
||||||
<Search size={18} className="text-slate-400" />
|
<Search size={18} className="text-zinc-400 dark:text-dark-muted" />
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
placeholder="Buscar..."
|
placeholder="Buscar..."
|
||||||
className="bg-transparent border-none outline-none text-sm ml-2 w-full text-slate-700 placeholder-slate-400"
|
className="bg-transparent border-none outline-none text-sm ml-2 w-full text-zinc-700 dark:text-dark-text placeholder-zinc-400 dark:placeholder-dark-muted"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Notifications */}
|
{/* Notifications */}
|
||||||
<div className="relative">
|
<div className="relative">
|
||||||
<button className="p-2 text-slate-500 hover:bg-slate-100 rounded-full relative transition-colors">
|
<button className="p-2 text-zinc-500 dark:text-dark-muted hover:bg-zinc-100 dark:hover:bg-dark-border rounded-full relative transition-colors">
|
||||||
<Bell size={20} />
|
<Bell size={20} />
|
||||||
<span className="absolute top-1.5 right-2 w-2.5 h-2.5 bg-yellow-400 rounded-full border-2 border-white"></span>
|
<span className="absolute top-1.5 right-2 w-2.5 h-2.5 bg-brand-yellow rounded-full border-2 border-white dark:border-dark-header"></span>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -179,7 +213,7 @@ export const Layout: React.FC<{ children: React.ReactNode }> = ({ children }) =>
|
|||||||
{/* Overlay for mobile */}
|
{/* Overlay for mobile */}
|
||||||
{isMobileMenuOpen && (
|
{isMobileMenuOpen && (
|
||||||
<div
|
<div
|
||||||
className="fixed inset-0 bg-slate-900/50 z-40 lg:hidden"
|
className="fixed inset-0 bg-zinc-950/50 z-40 lg:hidden"
|
||||||
onClick={() => setIsMobileMenuOpen(false)}
|
onClick={() => setIsMobileMenuOpen(false)}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -14,29 +14,29 @@ interface ProductListsProps {
|
|||||||
|
|
||||||
export const ProductLists: React.FC<ProductListsProps> = ({ requested, sold }) => {
|
export const ProductLists: React.FC<ProductListsProps> = ({ requested, sold }) => {
|
||||||
const ListSection = ({ title, icon: Icon, data, color }: { title: string, icon: any, data: ProductStat[], color: string }) => (
|
const ListSection = ({ title, icon: Icon, data, color }: { title: string, icon: any, data: ProductStat[], color: string }) => (
|
||||||
<div className="bg-white p-6 rounded-2xl shadow-sm border border-slate-100 flex-1">
|
<div className="bg-white dark:bg-dark-card p-6 rounded-2xl shadow-sm border border-zinc-100 dark:border-dark-border flex-1 transition-colors">
|
||||||
<div className="flex items-center gap-2 mb-4">
|
<div className="flex items-center gap-2 mb-4">
|
||||||
<div className={`p-2 rounded-lg ${color === 'blue' ? 'bg-blue-100 text-blue-600' : 'bg-green-100 text-green-600'}`}>
|
<div className={`p-2 rounded-lg ${color === 'blue' ? 'bg-blue-100 dark:bg-blue-950/50 text-blue-600 dark:text-blue-400' : 'bg-green-100 dark:bg-green-950/50 text-green-600 dark:text-green-400'}`}>
|
||||||
<Icon size={18} />
|
<Icon size={18} />
|
||||||
</div>
|
</div>
|
||||||
<h3 className="font-bold text-slate-800">{title}</h3>
|
<h3 className="font-bold text-zinc-800 dark:text-dark-text">{title}</h3>
|
||||||
</div>
|
</div>
|
||||||
<ul className="space-y-4">
|
<ul className="space-y-4">
|
||||||
{data.map((item, idx) => (
|
{data.map((item, idx) => (
|
||||||
<li key={idx} className="flex items-center justify-between group">
|
<li key={idx} className="flex items-center justify-between group">
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
<span className={`flex items-center justify-center w-6 h-6 rounded-full text-xs font-bold ${idx < 3 ? 'bg-slate-800 text-white' : 'bg-slate-100 text-slate-500'}`}>
|
<span className={`flex items-center justify-center w-6 h-6 rounded-full text-xs font-bold ${idx < 3 ? 'bg-zinc-800 dark:bg-brand-yellow text-white dark:text-zinc-950' : 'bg-zinc-100 dark:bg-dark-bg text-zinc-500 dark:text-dark-muted'}`}>
|
||||||
{idx + 1}
|
{idx + 1}
|
||||||
</span>
|
</span>
|
||||||
<span className="text-sm font-medium text-slate-700 group-hover:text-slate-900">{item.name}</span>
|
<span className="text-sm font-medium text-zinc-700 dark:text-zinc-300 group-hover:text-zinc-900 dark:group-hover:text-dark-text">{item.name}</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="text-right">
|
<div className="text-right">
|
||||||
<span className="text-sm font-bold text-slate-900 block">{item.count}</span>
|
<span className="text-sm font-bold text-zinc-900 dark:text-zinc-100 block">{item.count}</span>
|
||||||
<span className="text-[10px] text-slate-400">{item.percentage}%</span>
|
<span className="text-[10px] text-zinc-400 dark:text-dark-muted">{item.percentage}%</span>
|
||||||
</div>
|
</div>
|
||||||
</li>
|
</li>
|
||||||
))}
|
))}
|
||||||
{data.length === 0 && <li className="text-sm text-slate-400 italic">Nenhum dado disponível.</li>}
|
{data.length === 0 && <li className="text-sm text-zinc-400 dark:text-dark-muted italic">Nenhum dado disponível.</li>}
|
||||||
</ul>
|
</ul>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -15,14 +15,12 @@ interface SellersTableProps {
|
|||||||
data: SellerStat[];
|
data: SellerStat[];
|
||||||
}
|
}
|
||||||
|
|
||||||
type SortKey = keyof SellerStat | 'name'; // 'name' is inside user object
|
|
||||||
|
|
||||||
export const SellersTable: React.FC<SellersTableProps> = ({ data }) => {
|
export const SellersTable: React.FC<SellersTableProps> = ({ data }) => {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const [sortKey, setSortKey] = useState<SortKey>('conversionRate');
|
const [sortKey, setSortKey] = useState<keyof SellerStat>('total');
|
||||||
const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('desc');
|
const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('desc');
|
||||||
|
|
||||||
const handleSort = (key: SortKey) => {
|
const handleSort = (key: keyof SellerStat) => {
|
||||||
if (sortKey === key) {
|
if (sortKey === key) {
|
||||||
setSortDirection(prev => prev === 'asc' ? 'desc' : 'asc');
|
setSortDirection(prev => prev === 'asc' ? 'desc' : 'asc');
|
||||||
} else {
|
} else {
|
||||||
@@ -33,111 +31,123 @@ export const SellersTable: React.FC<SellersTableProps> = ({ data }) => {
|
|||||||
|
|
||||||
const sortedData = useMemo(() => {
|
const sortedData = useMemo(() => {
|
||||||
return [...data].sort((a, b) => {
|
return [...data].sort((a, b) => {
|
||||||
let aValue: any = a[sortKey as keyof SellerStat];
|
const aVal = a[sortKey];
|
||||||
let bValue: any = b[sortKey as keyof SellerStat];
|
const bVal = b[sortKey];
|
||||||
|
|
||||||
if (sortKey === 'name') {
|
if (typeof aVal === 'string' && typeof bVal === 'string') {
|
||||||
aValue = a.user.name;
|
return sortDirection === 'asc'
|
||||||
bValue = b.user.name;
|
? aVal.localeCompare(bVal)
|
||||||
} else {
|
: bVal.localeCompare(aVal);
|
||||||
// Convert strings like "85.5" to numbers for sorting
|
}
|
||||||
aValue = parseFloat(aValue as string);
|
|
||||||
bValue = parseFloat(bValue as string);
|
if (typeof aVal === 'number' && typeof bVal === 'number') {
|
||||||
|
return sortDirection === 'asc' ? aVal - bVal : bVal - aVal;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle user object (sort by name)
|
||||||
|
if (sortKey === 'user') {
|
||||||
|
return sortDirection === 'asc'
|
||||||
|
? a.user.name.localeCompare(b.user.name)
|
||||||
|
: b.user.name.localeCompare(a.user.name);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (aValue < bValue) return sortDirection === 'asc' ? -1 : 1;
|
|
||||||
if (aValue > bValue) return sortDirection === 'asc' ? 1 : -1;
|
|
||||||
return 0;
|
return 0;
|
||||||
});
|
});
|
||||||
}, [data, sortKey, sortDirection]);
|
}, [data, sortKey, sortDirection]);
|
||||||
|
|
||||||
const SortIcon = ({ column }: { column: SortKey }) => {
|
const SortIcon = ({ column }: { column: string }) => {
|
||||||
if (sortKey !== column) return <ChevronsUpDown size={14} className="text-slate-300" />;
|
if (sortKey !== column) return <ChevronsUpDown size={14} className="text-zinc-300 dark:text-dark-muted" />;
|
||||||
return sortDirection === 'asc' ? <ChevronUp size={14} className="text-blue-500" /> : <ChevronDown size={14} className="text-blue-500" />;
|
return sortDirection === 'asc' ? <ChevronUp size={14} className="text-brand-yellow" /> : <ChevronDown size={14} className="text-brand-yellow" />;
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="bg-white rounded-2xl shadow-sm border border-slate-100 overflow-hidden">
|
<div className="bg-white dark:bg-dark-card rounded-2xl shadow-sm border border-zinc-100 dark:border-dark-border overflow-hidden transition-colors">
|
||||||
<div className="px-6 py-5 border-b border-slate-100 flex justify-between items-center">
|
<div className="px-6 py-5 border-b border-zinc-100 dark:border-dark-border flex justify-between items-center">
|
||||||
<h3 className="font-bold text-slate-800">Ranking de Vendedores</h3>
|
<h3 className="font-bold text-zinc-800 dark:text-dark-text">Ranking de Vendedores</h3>
|
||||||
</div>
|
</div>
|
||||||
<div className="overflow-x-auto">
|
<div className="overflow-x-auto">
|
||||||
<table className="w-full text-left border-collapse">
|
<table className="w-full text-left border-collapse">
|
||||||
<thead>
|
<thead>
|
||||||
<tr className="bg-slate-50/50 text-slate-500 text-xs uppercase tracking-wider">
|
<tr className="bg-zinc-50/50 dark:bg-dark-bg/50 text-zinc-500 dark:text-dark-muted text-xs uppercase tracking-wider">
|
||||||
<th
|
<th
|
||||||
className="px-6 py-4 font-semibold cursor-pointer hover:bg-slate-50 select-none"
|
className="px-6 py-4 font-semibold cursor-pointer hover:bg-zinc-50 dark:hover:bg-dark-border select-none"
|
||||||
onClick={() => handleSort('name')}
|
onClick={() => handleSort('user')}
|
||||||
>
|
>
|
||||||
<div className="flex items-center gap-2">Usuário <SortIcon column="name" /></div>
|
<div className="flex items-center gap-2">Usuário <SortIcon column="user" /></div>
|
||||||
</th>
|
</th>
|
||||||
<th
|
<th
|
||||||
className="px-6 py-4 font-semibold text-center cursor-pointer hover:bg-slate-50 select-none"
|
className="px-6 py-4 font-semibold text-center cursor-pointer hover:bg-zinc-50 dark:hover:bg-dark-border select-none"
|
||||||
onClick={() => handleSort('total')}
|
onClick={() => handleSort('total')}
|
||||||
>
|
>
|
||||||
<div className="flex items-center justify-center gap-2">Atendimentos <SortIcon column="total" /></div>
|
<div className="flex items-center justify-center gap-2">Atendimentos <SortIcon column="total" /></div>
|
||||||
</th>
|
</th>
|
||||||
<th
|
<th
|
||||||
className="px-6 py-4 font-semibold text-center cursor-pointer hover:bg-slate-50 select-none"
|
className="px-6 py-4 font-semibold text-center cursor-pointer hover:bg-zinc-50 dark:hover:bg-dark-border select-none"
|
||||||
onClick={() => handleSort('avgScore')}
|
onClick={() => handleSort('avgScore')}
|
||||||
>
|
>
|
||||||
<div className="flex items-center justify-center gap-2">Nota Média <SortIcon column="avgScore" /></div>
|
<div className="flex items-center justify-center gap-2">Nota Média <SortIcon column="avgScore" /></div>
|
||||||
</th>
|
</th>
|
||||||
<th
|
<th
|
||||||
className="px-6 py-4 font-semibold text-center cursor-pointer hover:bg-slate-50 select-none"
|
className="px-6 py-4 font-semibold text-center cursor-pointer hover:bg-zinc-50 dark:hover:bg-dark-border select-none"
|
||||||
onClick={() => handleSort('responseTime')}
|
onClick={() => handleSort('responseTime')}
|
||||||
>
|
>
|
||||||
<div className="flex items-center justify-center gap-2">Tempo Resp. <SortIcon column="responseTime" /></div>
|
<div className="flex items-center justify-center gap-2">Tempo Resp. <SortIcon column="responseTime" /></div>
|
||||||
</th>
|
</th>
|
||||||
<th
|
<th
|
||||||
className="px-6 py-4 font-semibold text-center cursor-pointer hover:bg-slate-50 select-none"
|
className="px-6 py-4 font-semibold text-center cursor-pointer hover:bg-zinc-50 dark:hover:bg-dark-border select-none"
|
||||||
onClick={() => handleSort('conversionRate')}
|
onClick={() => handleSort('conversionRate')}
|
||||||
>
|
>
|
||||||
<div className="flex items-center justify-center gap-2">Conversão <SortIcon column="conversionRate" /></div>
|
<div className="flex items-center justify-center gap-2">Conversão <SortIcon column="conversionRate" /></div>
|
||||||
</th>
|
</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody className="divide-y divide-slate-100">
|
<tbody className="divide-y divide-zinc-100 dark:divide-dark-border">
|
||||||
{sortedData.map((item, idx) => (
|
{sortedData.map((item, idx) => (
|
||||||
<tr
|
<tr
|
||||||
key={item.user.id}
|
key={item.user.id}
|
||||||
className="hover:bg-blue-50/30 transition-colors cursor-pointer group"
|
className="hover:bg-yellow-50/10 dark:hover:bg-yellow-400/5 transition-colors cursor-pointer group"
|
||||||
onClick={() => navigate(`/users/${item.user.id}`)}
|
onClick={() => navigate(`/users/${item.user.id}`)}
|
||||||
>
|
>
|
||||||
<td className="px-6 py-4">
|
<td className="px-6 py-4">
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
<span className="text-xs text-slate-400 font-mono w-4">#{idx + 1}</span>
|
<span className="text-xs text-zinc-400 dark:text-dark-muted 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" />
|
<img
|
||||||
|
src={item.user.avatar_url
|
||||||
|
? (item.user.avatar_url.startsWith('http') ? item.user.avatar_url : `${import.meta.env.PROD ? '' : 'http://localhost:3001'}${item.user.avatar_url}`)
|
||||||
|
: `https://ui-avatars.com/api/?name=${encodeURIComponent(item.user.name)}&background=random`}
|
||||||
|
alt=""
|
||||||
|
className="w-9 h-9 rounded-full object-cover border border-zinc-200 dark:border-dark-border"
|
||||||
|
/>
|
||||||
<div>
|
<div>
|
||||||
<div className="font-semibold text-slate-900 group-hover:text-blue-600 transition-colors">{item.user.name}</div>
|
<div className="font-semibold text-zinc-900 dark:text-dark-text group-hover:text-yellow-600 dark:group-hover:text-brand-yellow transition-colors">{item.user.name}</div>
|
||||||
<div className="text-xs text-slate-500">{item.user.email}</div>
|
<div className="text-xs text-zinc-500 dark:text-dark-muted">{item.user.email}</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</td>
|
</td>
|
||||||
<td className="px-6 py-4 text-center text-slate-600 font-medium">
|
<td className="px-6 py-4 text-center text-zinc-600 dark:text-dark-text font-medium">
|
||||||
{item.total}
|
{item.total}
|
||||||
</td>
|
</td>
|
||||||
<td className="px-6 py-4 text-center">
|
<td className="px-6 py-4 text-center">
|
||||||
<span className={`inline-flex px-2 py-1 rounded-full text-xs font-bold ${parseFloat(item.avgScore) >= 80 ? 'bg-green-100 text-green-700' : parseFloat(item.avgScore) >= 60 ? 'bg-yellow-100 text-yellow-700' : 'bg-red-100 text-red-700'}`}>
|
<span className={`inline-flex px-2 py-1 rounded-full text-xs font-bold ${parseFloat(item.avgScore) >= 80 ? 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400' : parseFloat(item.avgScore) >= 60 ? 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400' : 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400'}`}>
|
||||||
{item.avgScore}
|
{item.avgScore}
|
||||||
</span>
|
</span>
|
||||||
</td>
|
</td>
|
||||||
<td className="px-6 py-4 text-center text-slate-600 text-sm">
|
<td className="px-6 py-4 text-center text-zinc-600 dark:text-dark-text text-sm">
|
||||||
{item.responseTime} min
|
{item.responseTime} min
|
||||||
</td>
|
</td>
|
||||||
<td className="px-6 py-4 text-center">
|
<td className="px-6 py-4 text-center">
|
||||||
<div className="flex items-center justify-center gap-2">
|
<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="w-16 bg-zinc-100 dark:bg-dark-bg rounded-full h-1.5 overflow-hidden border dark:border-dark-border">
|
||||||
<div className="bg-blue-500 h-1.5 rounded-full" style={{ width: `${item.conversionRate}%` }}></div>
|
<div className="bg-brand-yellow h-1.5 rounded-full" style={{ width: `${item.conversionRate}%` }}></div>
|
||||||
</div>
|
</div>
|
||||||
<span className="text-xs font-semibold text-slate-700">{item.conversionRate}%</span>
|
<span className="text-xs font-semibold text-zinc-700 dark:text-dark-text">{item.conversionRate}%</span>
|
||||||
</div>
|
</div>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
))}
|
||||||
{sortedData.length === 0 && (
|
{sortedData.length === 0 && (
|
||||||
<tr>
|
<tr>
|
||||||
<td colSpan={5} className="px-6 py-8 text-center text-slate-400 italic">Nenhum dado disponível para o período selecionado.</td>
|
<td colSpan={5} className="px-6 py-8 text-center text-zinc-400 dark:text-dark-muted italic">Nenhum dado disponível para o período selecionado.</td>
|
||||||
</tr>
|
</tr>
|
||||||
)}
|
)}
|
||||||
</tbody>
|
</tbody>
|
||||||
|
|||||||
39
constants.ts
39
constants.ts
@@ -111,7 +111,7 @@ export const USERS: User[] = [
|
|||||||
];
|
];
|
||||||
|
|
||||||
const generateMockAttendances = (count: number): Attendance[] => {
|
const generateMockAttendances = (count: number): Attendance[] => {
|
||||||
const origins = ['WhatsApp', 'Instagram', 'Website', 'LinkedIn', 'Referral'] as const;
|
const origins = ['WhatsApp', 'Instagram', 'Website', 'LinkedIn', 'Indicação'] as const;
|
||||||
const stages = Object.values(FunnelStage);
|
const stages = Object.values(FunnelStage);
|
||||||
const products = ['Plano Premium', 'Plano Básico', 'Suíte Enterprise', 'Consultoria'];
|
const products = ['Plano Premium', 'Plano Básico', 'Suíte Enterprise', 'Consultoria'];
|
||||||
|
|
||||||
@@ -163,9 +163,36 @@ export const MOCK_ATTENDANCES = generateMockAttendances(300);
|
|||||||
// Visual Constants
|
// Visual Constants
|
||||||
export const COLORS = {
|
export const COLORS = {
|
||||||
primary: '#facc15', // Yellow-400
|
primary: '#facc15', // Yellow-400
|
||||||
secondary: '#1e293b', // Slate-800
|
secondary: '#18181b', // Zinc-900
|
||||||
success: '#22c55e',
|
success: '#10b981', // Emerald-500
|
||||||
warning: '#f59e0b',
|
warning: '#f59e0b', // Amber-500
|
||||||
danger: '#ef4444',
|
danger: '#ef4444', // Red-500
|
||||||
charts: ['#3b82f6', '#10b981', '#6366f1', '#f59e0b', '#ec4899', '#8b5cf6'],
|
|
||||||
|
// Prettier, modern SaaS palette for general charts
|
||||||
|
charts: [
|
||||||
|
'#818cf8', // Soft Indigo
|
||||||
|
'#4ade80', // Soft Emerald
|
||||||
|
'#fb923c', // Soft Orange
|
||||||
|
'#22d3ee', // Soft Cyan
|
||||||
|
'#f472b6', // Soft Pink
|
||||||
|
'#a78bfa' // Soft Violet
|
||||||
|
],
|
||||||
|
|
||||||
|
// Brand-specific colors for Lead Origins
|
||||||
|
origins: {
|
||||||
|
'WhatsApp': '#25D366',
|
||||||
|
'Instagram': '#E4405F',
|
||||||
|
'LinkedIn': '#0077B5',
|
||||||
|
'Website': '#f87171', // Coral Red (Distinct from LinkedIn blue)
|
||||||
|
'Indicação': '#f59e0b'
|
||||||
|
},
|
||||||
|
|
||||||
|
// Semantic palette for Funnel Stages
|
||||||
|
funnel: {
|
||||||
|
'Sem atendimento': '#64748b', // Slate-500
|
||||||
|
'Identificação': '#818cf8', // Indigo-400
|
||||||
|
'Negociação': '#fb923c', // Orange-400
|
||||||
|
'Ganhos': '#10b981', // Emerald-500
|
||||||
|
'Perdidos': '#f87171' // Red-400
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -18,7 +18,9 @@ services:
|
|||||||
- MAIL_FROM=${MAIL_FROM}
|
- MAIL_FROM=${MAIL_FROM}
|
||||||
volumes:
|
volumes:
|
||||||
- ./dist:/app/dist # Map local build to container
|
- ./dist:/app/dist # Map local build to container
|
||||||
- ./backend:/app/backend # Map backend source to container
|
- ./backend/index.js:/app/index.js
|
||||||
|
- ./backend/db.js:/app/db.js
|
||||||
|
command: ["node", "index.js"]
|
||||||
depends_on:
|
depends_on:
|
||||||
- db
|
- db
|
||||||
|
|
||||||
|
|||||||
36
index.html
36
index.html
@@ -5,11 +5,43 @@
|
|||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<title>Fasto | Management</title>
|
<title>Fasto | Management</title>
|
||||||
<script src="https://cdn.tailwindcss.com"></script>
|
<script src="https://cdn.tailwindcss.com"></script>
|
||||||
|
<script>
|
||||||
|
tailwind.config = {
|
||||||
|
darkMode: 'class',
|
||||||
|
theme: {
|
||||||
|
extend: {
|
||||||
|
colors: {
|
||||||
|
brand: {
|
||||||
|
yellow: '#facc15'
|
||||||
|
},
|
||||||
|
dark: {
|
||||||
|
bg: '#0a0a0a', // Deep Charcoal (Not pure black)
|
||||||
|
card: '#141414', // Elevated surface
|
||||||
|
header: '#141414',
|
||||||
|
sidebar: '#141414',
|
||||||
|
border: '#222222', // Subtle border
|
||||||
|
input: '#1a1a1a',
|
||||||
|
text: '#ededed', // High contrast off-white
|
||||||
|
muted: '#888888' // Muted gray
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check for theme in cookie or system preference
|
||||||
|
const isDark = document.cookie.split('; ').find(row => row.startsWith('dark_mode='))?.split('=')[1] === '1';
|
||||||
|
if (isDark) {
|
||||||
|
document.documentElement.classList.add('dark');
|
||||||
|
}
|
||||||
|
</script>
|
||||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
|
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
|
||||||
<style>
|
<style>
|
||||||
body { font-family: 'Inter', sans-serif; background-color: #f8fafc; }
|
body { font-family: 'Inter', sans-serif; transition: background-color 0.3s ease; }
|
||||||
|
.dark body { background-color: #0a0a0a; color: #ededed; }
|
||||||
::-webkit-scrollbar { width: 6px; height: 6px; }
|
::-webkit-scrollbar { width: 6px; height: 6px; }
|
||||||
::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 3px; }
|
::-webkit-scrollbar-thumb { background: #d4d4d8; border-radius: 3px; }
|
||||||
|
.dark ::-webkit-scrollbar-thumb { background: #333333; }
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
|
|||||||
131
package-lock.json
generated
131
package-lock.json
generated
@@ -13,18 +13,21 @@
|
|||||||
"express": "^4.18.2",
|
"express": "^4.18.2",
|
||||||
"jsonwebtoken": "^9.0.3",
|
"jsonwebtoken": "^9.0.3",
|
||||||
"lucide-react": "^0.574.0",
|
"lucide-react": "^0.574.0",
|
||||||
|
"multer": "^2.1.0",
|
||||||
"mysql2": "^3.9.1",
|
"mysql2": "^3.9.1",
|
||||||
"nodemailer": "^8.0.1",
|
"nodemailer": "^8.0.1",
|
||||||
"react": "^19.2.4",
|
"react": "^19.2.4",
|
||||||
"react-dom": "^19.2.4",
|
"react-dom": "^19.2.4",
|
||||||
"react-router-dom": "^7.13.0",
|
"react-router-dom": "^7.13.0",
|
||||||
"recharts": "^3.7.0"
|
"recharts": "^3.7.0",
|
||||||
|
"uuid": "^13.0.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/bcryptjs": "^2.4.6",
|
"@types/bcryptjs": "^2.4.6",
|
||||||
"@types/jsonwebtoken": "^9.0.10",
|
"@types/jsonwebtoken": "^9.0.10",
|
||||||
"@types/node": "^22.14.0",
|
"@types/node": "^22.14.0",
|
||||||
"@vitejs/plugin-react": "^5.0.0",
|
"@vitejs/plugin-react": "^5.0.0",
|
||||||
|
"dotenv": "^17.3.1",
|
||||||
"typescript": "~5.8.2",
|
"typescript": "~5.8.2",
|
||||||
"vite": "^6.2.0"
|
"vite": "^6.2.0"
|
||||||
}
|
}
|
||||||
@@ -1397,6 +1400,12 @@
|
|||||||
"node": ">= 0.6"
|
"node": ">= 0.6"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/append-field": {
|
||||||
|
"version": "1.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/append-field/-/append-field-1.0.0.tgz",
|
||||||
|
"integrity": "sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/array-flatten": {
|
"node_modules/array-flatten": {
|
||||||
"version": "1.1.1",
|
"version": "1.1.1",
|
||||||
"resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",
|
"resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",
|
||||||
@@ -1513,6 +1522,23 @@
|
|||||||
"integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==",
|
"integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==",
|
||||||
"license": "BSD-3-Clause"
|
"license": "BSD-3-Clause"
|
||||||
},
|
},
|
||||||
|
"node_modules/buffer-from": {
|
||||||
|
"version": "1.1.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
|
||||||
|
"integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/busboy": {
|
||||||
|
"version": "1.6.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz",
|
||||||
|
"integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==",
|
||||||
|
"dependencies": {
|
||||||
|
"streamsearch": "^1.1.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=10.16.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/bytes": {
|
"node_modules/bytes": {
|
||||||
"version": "3.1.2",
|
"version": "3.1.2",
|
||||||
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
|
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
|
||||||
@@ -1581,6 +1607,21 @@
|
|||||||
"node": ">=6"
|
"node": ">=6"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/concat-stream": {
|
||||||
|
"version": "2.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-2.0.0.tgz",
|
||||||
|
"integrity": "sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A==",
|
||||||
|
"engines": [
|
||||||
|
"node >= 6.0"
|
||||||
|
],
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"buffer-from": "^1.0.0",
|
||||||
|
"inherits": "^2.0.3",
|
||||||
|
"readable-stream": "^3.0.2",
|
||||||
|
"typedarray": "^0.0.6"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/content-disposition": {
|
"node_modules/content-disposition": {
|
||||||
"version": "0.5.4",
|
"version": "0.5.4",
|
||||||
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz",
|
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz",
|
||||||
@@ -1814,6 +1855,19 @@
|
|||||||
"npm": "1.2.8000 || >= 1.4.16"
|
"npm": "1.2.8000 || >= 1.4.16"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/dotenv": {
|
||||||
|
"version": "17.3.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.3.1.tgz",
|
||||||
|
"integrity": "sha512-IO8C/dzEb6O3F9/twg6ZLXz164a2fhTnEWb95H23Dm4OuN+92NmEAlTrupP9VW6Jm3sO26tQlqyvyi4CsnY9GA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "BSD-2-Clause",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=12"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://dotenvx.com"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/dunder-proto": {
|
"node_modules/dunder-proto": {
|
||||||
"version": "1.0.1",
|
"version": "1.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
|
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
|
||||||
@@ -2535,6 +2589,25 @@
|
|||||||
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
|
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/multer": {
|
||||||
|
"version": "2.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/multer/-/multer-2.1.0.tgz",
|
||||||
|
"integrity": "sha512-TBm6j41rxNohqawsxlsWsNNh/VdV4QFXcBvRcPhXaA05EZ79z0qJ2bQFpync6JBoHTeNY5Q1JpG7AlTjdlfAEA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"append-field": "^1.0.0",
|
||||||
|
"busboy": "^1.6.0",
|
||||||
|
"concat-stream": "^2.0.0",
|
||||||
|
"type-is": "^1.6.18"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 10.16.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"type": "opencollective",
|
||||||
|
"url": "https://opencollective.com/express"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/mysql2": {
|
"node_modules/mysql2": {
|
||||||
"version": "3.18.1",
|
"version": "3.18.1",
|
||||||
"resolved": "https://registry.npmjs.org/mysql2/-/mysql2-3.18.1.tgz",
|
"resolved": "https://registry.npmjs.org/mysql2/-/mysql2-3.18.1.tgz",
|
||||||
@@ -2890,6 +2963,20 @@
|
|||||||
"url": "https://opencollective.com/express"
|
"url": "https://opencollective.com/express"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/readable-stream": {
|
||||||
|
"version": "3.6.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
|
||||||
|
"integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"inherits": "^2.0.3",
|
||||||
|
"string_decoder": "^1.1.1",
|
||||||
|
"util-deprecate": "^1.0.1"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 6"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/recharts": {
|
"node_modules/recharts": {
|
||||||
"version": "3.7.0",
|
"version": "3.7.0",
|
||||||
"resolved": "https://registry.npmjs.org/recharts/-/recharts-3.7.0.tgz",
|
"resolved": "https://registry.npmjs.org/recharts/-/recharts-3.7.0.tgz",
|
||||||
@@ -3200,6 +3287,23 @@
|
|||||||
"node": ">= 0.8"
|
"node": ">= 0.8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/streamsearch": {
|
||||||
|
"version": "1.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz",
|
||||||
|
"integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=10.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/string_decoder": {
|
||||||
|
"version": "1.3.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
|
||||||
|
"integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"safe-buffer": "~5.2.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/tiny-invariant": {
|
"node_modules/tiny-invariant": {
|
||||||
"version": "1.3.3",
|
"version": "1.3.3",
|
||||||
"resolved": "https://registry.npmjs.org/tiny-invariant/-/tiny-invariant-1.3.3.tgz",
|
"resolved": "https://registry.npmjs.org/tiny-invariant/-/tiny-invariant-1.3.3.tgz",
|
||||||
@@ -3245,6 +3349,12 @@
|
|||||||
"node": ">= 0.6"
|
"node": ">= 0.6"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/typedarray": {
|
||||||
|
"version": "0.0.6",
|
||||||
|
"resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz",
|
||||||
|
"integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/typescript": {
|
"node_modules/typescript": {
|
||||||
"version": "5.8.3",
|
"version": "5.8.3",
|
||||||
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.8.3.tgz",
|
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.8.3.tgz",
|
||||||
@@ -3314,6 +3424,12 @@
|
|||||||
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
|
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/util-deprecate": {
|
||||||
|
"version": "1.0.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
|
||||||
|
"integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/utils-merge": {
|
"node_modules/utils-merge": {
|
||||||
"version": "1.0.1",
|
"version": "1.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
|
"resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
|
||||||
@@ -3323,6 +3439,19 @@
|
|||||||
"node": ">= 0.4.0"
|
"node": ">= 0.4.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/uuid": {
|
||||||
|
"version": "13.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/uuid/-/uuid-13.0.0.tgz",
|
||||||
|
"integrity": "sha512-XQegIaBTVUjSHliKqcnFqYypAd4S+WCYt5NIeRs6w/UAry7z8Y9j5ZwRRL4kzq9U3sD6v+85er9FvkEaBpji2w==",
|
||||||
|
"funding": [
|
||||||
|
"https://github.com/sponsors/broofa",
|
||||||
|
"https://github.com/sponsors/ctavan"
|
||||||
|
],
|
||||||
|
"license": "MIT",
|
||||||
|
"bin": {
|
||||||
|
"uuid": "dist-node/bin/uuid"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/vary": {
|
"node_modules/vary": {
|
||||||
"version": "1.1.2",
|
"version": "1.1.2",
|
||||||
"resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
|
"resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
|
||||||
|
|||||||
@@ -14,18 +14,21 @@
|
|||||||
"express": "^4.18.2",
|
"express": "^4.18.2",
|
||||||
"jsonwebtoken": "^9.0.3",
|
"jsonwebtoken": "^9.0.3",
|
||||||
"lucide-react": "^0.574.0",
|
"lucide-react": "^0.574.0",
|
||||||
|
"multer": "^2.1.0",
|
||||||
"mysql2": "^3.9.1",
|
"mysql2": "^3.9.1",
|
||||||
"nodemailer": "^8.0.1",
|
"nodemailer": "^8.0.1",
|
||||||
"react": "^19.2.4",
|
"react": "^19.2.4",
|
||||||
"react-dom": "^19.2.4",
|
"react-dom": "^19.2.4",
|
||||||
"react-router-dom": "^7.13.0",
|
"react-router-dom": "^7.13.0",
|
||||||
"recharts": "^3.7.0"
|
"recharts": "^3.7.0",
|
||||||
|
"uuid": "^13.0.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/bcryptjs": "^2.4.6",
|
"@types/bcryptjs": "^2.4.6",
|
||||||
"@types/jsonwebtoken": "^9.0.10",
|
"@types/jsonwebtoken": "^9.0.10",
|
||||||
"@types/node": "^22.14.0",
|
"@types/node": "^22.14.0",
|
||||||
"@vitejs/plugin-react": "^5.0.0",
|
"@vitejs/plugin-react": "^5.0.0",
|
||||||
|
"dotenv": "^17.3.1",
|
||||||
"typescript": "~5.8.2",
|
"typescript": "~5.8.2",
|
||||||
"vite": "^6.2.0"
|
"vite": "^6.2.0"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,14 +31,14 @@ export const AttendanceDetail: React.FC = () => {
|
|||||||
loadData();
|
loadData();
|
||||||
}, [id]);
|
}, [id]);
|
||||||
|
|
||||||
if (loading) return <div className="p-12 text-center text-slate-400">Carregando detalhes...</div>;
|
if (loading) return <div className="p-12 text-center text-zinc-400 dark:text-dark-muted transition-colors">Carregando detalhes...</div>;
|
||||||
if (!data) return <div className="p-12 text-center text-slate-500">Registro de atendimento não encontrado</div>;
|
if (!data) return <div className="p-12 text-center text-zinc-500 dark:text-dark-muted transition-colors">Registro de atendimento não encontrado</div>;
|
||||||
|
|
||||||
const getStageColor = (stage: FunnelStage) => {
|
const getStageColor = (stage: FunnelStage) => {
|
||||||
switch (stage) {
|
switch (stage) {
|
||||||
case FunnelStage.WON: return 'text-green-700 bg-green-50 border-green-200';
|
case FunnelStage.WON: return 'text-green-700 bg-green-50 border-green-200 dark:text-green-400 dark:bg-green-900/30 dark:border-green-800';
|
||||||
case FunnelStage.LOST: return 'text-red-700 bg-red-50 border-red-200';
|
case FunnelStage.LOST: return 'text-red-700 bg-red-50 border-red-200 dark:text-red-400 dark:bg-red-900/30 dark:border-red-800';
|
||||||
default: return 'text-blue-700 bg-blue-50 border-blue-200';
|
default: return 'text-blue-700 bg-blue-50 border-blue-200 dark:text-blue-400 dark:bg-blue-900/30 dark:border-blue-800';
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -48,51 +48,59 @@ export const AttendanceDetail: React.FC = () => {
|
|||||||
return 'text-red-500';
|
return 'text-red-500';
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const backendUrl = import.meta.env.PROD ? '' : 'http://localhost:3001';
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="max-w-5xl mx-auto space-y-6">
|
<div className="max-w-5xl mx-auto space-y-6 transition-colors duration-300">
|
||||||
{/* Top Nav & Context */}
|
{/* Top Nav & Context */}
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<Link
|
<Link
|
||||||
to={`/users/${data.user_id}`}
|
to={`/users/${data.user_id}`}
|
||||||
className="flex items-center gap-2 text-slate-500 hover:text-slate-900 transition-colors text-sm font-medium"
|
className="flex items-center gap-2 text-zinc-500 dark:text-dark-muted hover:text-zinc-900 dark:hover:text-dark-text transition-colors text-sm font-medium"
|
||||||
>
|
>
|
||||||
<ArrowLeft size={16} /> Voltar para Histórico
|
<ArrowLeft size={16} /> Voltar para Histórico
|
||||||
</Link>
|
</Link>
|
||||||
<div className="text-sm text-slate-400 font-mono">ID: {data.id}</div>
|
<div className="text-sm text-zinc-400 dark:text-dark-muted font-mono">ID: {data.id}</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Hero Header */}
|
{/* Hero Header */}
|
||||||
<div className="bg-white rounded-2xl border border-slate-200 shadow-sm p-6 md:p-8">
|
<div className="bg-white dark:bg-dark-card rounded-2xl border border-zinc-200 dark:border-dark-border shadow-sm p-6 md:p-8 transition-colors">
|
||||||
<div className="flex flex-col md:flex-row justify-between gap-6">
|
<div className="flex flex-col md:flex-row justify-between gap-6">
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<div className="flex flex-wrap items-center gap-3">
|
<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)}`}>
|
<span className={`px-3 py-1 rounded-full text-xs font-bold uppercase tracking-wide border ${getStageColor(data.funnel_stage)}`}>
|
||||||
{data.funnel_stage}
|
{data.funnel_stage}
|
||||||
</span>
|
</span>
|
||||||
<span className="flex items-center gap-1.5 text-slate-500 text-sm">
|
<span className="flex items-center gap-1.5 text-zinc-500 dark:text-dark-muted text-sm">
|
||||||
<Calendar size={14} /> {new Date(data.created_at).toLocaleString('pt-BR')}
|
<Calendar size={14} /> {new Date(data.created_at).toLocaleString('pt-BR')}
|
||||||
</span>
|
</span>
|
||||||
<span className="flex items-center gap-1.5 text-slate-500 text-sm">
|
<span className="flex items-center gap-1.5 text-zinc-500 dark:text-dark-muted text-sm">
|
||||||
<MessageSquare size={14} /> {data.origin}
|
<MessageSquare size={14} /> {data.origin}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<h1 className="text-2xl md:text-3xl font-bold text-slate-900 leading-tight">
|
<h1 className="text-2xl md:text-3xl font-bold text-zinc-900 dark:text-dark-text leading-tight">
|
||||||
{data.summary}
|
{data.summary}
|
||||||
</h1>
|
</h1>
|
||||||
{agent && (
|
{agent && (
|
||||||
<div className="flex items-center gap-3 pt-2">
|
<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" />
|
<img
|
||||||
<span className="text-sm font-medium text-slate-700">Agente: <span className="text-slate-900">{agent.name}</span></span>
|
src={agent.avatar_url
|
||||||
|
? (agent.avatar_url.startsWith('http') ? agent.avatar_url : `${backendUrl}${agent.avatar_url}`)
|
||||||
|
: `https://ui-avatars.com/api/?name=${encodeURIComponent(agent.name)}&background=random`}
|
||||||
|
alt=""
|
||||||
|
className="w-8 h-8 rounded-full border border-zinc-200 dark:border-dark-border object-cover"
|
||||||
|
/>
|
||||||
|
<span className="text-sm font-medium text-zinc-700 dark:text-zinc-300">Agente: <span className="text-zinc-900 dark:text-zinc-100">{agent.name}</span></span>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex flex-col items-center justify-center min-w-[140px] p-6 bg-slate-50 rounded-xl border border-slate-100">
|
<div className="flex flex-col items-center justify-center min-w-[140px] p-6 bg-zinc-50 dark:bg-dark-bg/50 rounded-xl border border-zinc-100 dark:border-dark-border">
|
||||||
<span className="text-xs font-bold text-slate-400 uppercase tracking-wider mb-1">Nota de Qualidade</span>
|
<span className="text-xs font-bold text-zinc-400 dark:text-dark-muted uppercase tracking-wider mb-1">Nota de Qualidade</span>
|
||||||
<div className={`text-5xl font-black ${getScoreColor(data.score)}`}>
|
<div className={`text-5xl font-black ${getScoreColor(data.score)}`}>
|
||||||
{data.score}
|
{data.score}
|
||||||
</div>
|
</div>
|
||||||
<span className="text-xs font-medium text-slate-400 mt-1">de 100</span>
|
<span className="text-xs font-medium text-zinc-400 dark:text-dark-muted mt-1">de 100</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -104,13 +112,13 @@ export const AttendanceDetail: React.FC = () => {
|
|||||||
<div className="lg:col-span-2 space-y-6">
|
<div className="lg:col-span-2 space-y-6">
|
||||||
|
|
||||||
{/* Summary / Transcript Stub */}
|
{/* Summary / Transcript Stub */}
|
||||||
<div className="bg-white rounded-xl border border-slate-200 shadow-sm p-6">
|
<div className="bg-white dark:bg-dark-card rounded-xl border border-zinc-200 dark:border-dark-border shadow-sm p-6">
|
||||||
<h3 className="text-base font-bold text-slate-900 mb-4 flex items-center gap-2">
|
<h3 className="text-base font-bold text-zinc-900 dark:text-dark-text mb-4 flex items-center gap-2">
|
||||||
<MessageSquare size={18} className="text-slate-400" />
|
<MessageSquare size={18} className="text-zinc-400 dark:text-dark-muted" />
|
||||||
Resumo da Interação
|
Resumo da Interação
|
||||||
</h3>
|
</h3>
|
||||||
<p className="text-slate-600 leading-relaxed text-sm">
|
<p className="text-zinc-600 dark:text-zinc-300 leading-relaxed text-sm">
|
||||||
{data.summary} O cliente perguntou sobre detalhes específicos relacionados ao <span className="font-medium text-slate-800">{data.product_requested}</span>.
|
{data.summary} O cliente perguntou sobre detalhes específicos relacionados ao <span className="font-medium text-zinc-800 dark:text-zinc-100">{data.product_requested}</span>.
|
||||||
As discussões envolveram níveis de preços, prazos de implementação e potenciais descontos por volume.
|
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'}.
|
A interação foi concluída com {data.converted ? 'uma venda realizada' : 'o cliente pedindo mais tempo para decidir'}.
|
||||||
</p>
|
</p>
|
||||||
@@ -119,45 +127,45 @@ export const AttendanceDetail: React.FC = () => {
|
|||||||
{/* Feedback Section */}
|
{/* Feedback Section */}
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||||
{/* Points of Attention */}
|
{/* Points of Attention */}
|
||||||
<div className="bg-white rounded-xl border border-red-100 shadow-sm overflow-hidden">
|
<div className="bg-white dark:bg-dark-card rounded-xl border border-red-100 dark:border-red-900/20 shadow-sm overflow-hidden">
|
||||||
<div className="px-5 py-3 bg-red-50/50 border-b border-red-100 flex items-center gap-2">
|
<div className="px-5 py-3 bg-red-50/50 dark:bg-red-900/20 border-b border-red-100 dark:border-red-900/30 flex items-center gap-2">
|
||||||
<AlertCircle size={18} className="text-red-500" />
|
<AlertCircle size={18} className="text-red-500 dark:text-red-400" />
|
||||||
<h3 className="font-bold text-red-900 text-sm">Pontos de Atenção</h3>
|
<h3 className="font-bold text-red-900 dark:text-red-300 text-sm">Pontos de Atenção</h3>
|
||||||
</div>
|
</div>
|
||||||
<div className="p-5">
|
<div className="p-5">
|
||||||
{data.attention_points && data.attention_points.length > 0 ? (
|
{data.attention_points && data.attention_points.length > 0 ? (
|
||||||
<ul className="space-y-3">
|
<ul className="space-y-3">
|
||||||
{data.attention_points.map((pt, idx) => (
|
{data.attention_points.map((pt, idx) => (
|
||||||
<li key={idx} className="flex gap-3 text-sm text-slate-700">
|
<li key={idx} className="flex gap-3 text-sm text-zinc-700 dark:text-zinc-300">
|
||||||
<span className="mt-1.5 w-1.5 h-1.5 rounded-full bg-red-400 shrink-0" />
|
<span className="mt-1.5 w-1.5 h-1.5 rounded-full bg-red-400 shrink-0" />
|
||||||
{pt}
|
{pt}
|
||||||
</li>
|
</li>
|
||||||
))}
|
))}
|
||||||
</ul>
|
</ul>
|
||||||
) : (
|
) : (
|
||||||
<p className="text-sm text-slate-400 italic">Nenhum problema detectado.</p>
|
<p className="text-sm text-zinc-400 dark:text-dark-muted italic">Nenhum problema detectado.</p>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Points of Improvement */}
|
{/* Points of Improvement */}
|
||||||
<div className="bg-white rounded-xl border border-blue-100 shadow-sm overflow-hidden">
|
<div className="bg-white dark:bg-dark-card rounded-xl border border-blue-100 dark:border-blue-900/20 shadow-sm overflow-hidden">
|
||||||
<div className="px-5 py-3 bg-blue-50/50 border-b border-blue-100 flex items-center gap-2">
|
<div className="px-5 py-3 bg-blue-50/50 dark:bg-blue-900/20 border-b border-blue-100 dark:border-blue-900/30 flex items-center gap-2">
|
||||||
<CheckCircle2 size={18} className="text-blue-500" />
|
<CheckCircle2 size={18} className="text-blue-500 dark:text-blue-400" />
|
||||||
<h3 className="font-bold text-blue-900 text-sm">Dicas de Melhoria</h3>
|
<h3 className="font-bold text-blue-900 dark:text-blue-300 text-sm">Dicas de Melhoria</h3>
|
||||||
</div>
|
</div>
|
||||||
<div className="p-5">
|
<div className="p-5">
|
||||||
{data.improvement_points && data.improvement_points.length > 0 ? (
|
{data.improvement_points && data.improvement_points.length > 0 ? (
|
||||||
<ul className="space-y-3">
|
<ul className="space-y-3">
|
||||||
{data.improvement_points.map((pt, idx) => (
|
{data.improvement_points.map((pt, idx) => (
|
||||||
<li key={idx} className="flex gap-3 text-sm text-slate-700">
|
<li key={idx} className="flex gap-3 text-sm text-zinc-700 dark:text-zinc-300">
|
||||||
<span className="mt-1.5 w-1.5 h-1.5 rounded-full bg-blue-400 shrink-0" />
|
<span className="mt-1.5 w-1.5 h-1.5 rounded-full bg-red-400 shrink-0" />
|
||||||
{pt}
|
{pt}
|
||||||
</li>
|
</li>
|
||||||
))}
|
))}
|
||||||
</ul>
|
</ul>
|
||||||
) : (
|
) : (
|
||||||
<p className="text-sm text-slate-400 italic">Continue o bom trabalho!</p>
|
<p className="text-sm text-zinc-400 dark:text-dark-muted italic">Continue o bom trabalho!</p>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -166,49 +174,49 @@ export const AttendanceDetail: React.FC = () => {
|
|||||||
|
|
||||||
{/* Right Column: Metadata & Metrics */}
|
{/* Right Column: Metadata & Metrics */}
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<div className="bg-white rounded-xl border border-slate-200 shadow-sm p-5">
|
<div className="bg-white dark:bg-dark-card rounded-xl border border-zinc-200 dark:border-dark-border shadow-sm p-5 transition-colors">
|
||||||
<h3 className="text-xs font-bold text-slate-400 uppercase tracking-wider mb-4">Métricas de Performance</h3>
|
<h3 className="text-xs font-bold text-zinc-400 dark:text-dark-muted uppercase tracking-wider mb-4">Métricas de Performance</h3>
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<div className="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
|
<div className="flex justify-between items-center p-3 bg-zinc-50 dark:bg-dark-bg/50 rounded-lg">
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
<div className="p-2 bg-white rounded-md border border-slate-100 text-blue-500"><Clock size={16} /></div>
|
<div className="p-2 bg-white dark:bg-dark-card rounded-md border border-zinc-100 dark:border-dark-border text-blue-500 dark:text-blue-400"><Clock size={16} /></div>
|
||||||
<span className="text-sm font-medium text-slate-600">Primeira Resposta</span>
|
<span className="text-sm font-medium text-zinc-600 dark:text-zinc-400">Primeira Resposta</span>
|
||||||
</div>
|
</div>
|
||||||
<span className="text-sm font-bold text-slate-900">{data.first_response_time_min} min</span>
|
<span className="text-sm font-bold text-zinc-900 dark:text-zinc-100">{data.first_response_time_min} min</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
|
<div className="flex justify-between items-center p-3 bg-zinc-50 dark:bg-dark-bg/50 rounded-lg">
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
<div className="p-2 bg-white rounded-md border border-slate-100 text-purple-500"><TrendingUp size={16} /></div>
|
<div className="p-2 bg-white dark:bg-dark-card rounded-md border border-zinc-100 dark:border-dark-border text-purple-500 dark:text-purple-400"><TrendingUp size={16} /></div>
|
||||||
<span className="text-sm font-medium text-slate-600">Tempo Atendimento</span>
|
<span className="text-sm font-medium text-zinc-600 dark:text-zinc-400">Tempo Atendimento</span>
|
||||||
</div>
|
</div>
|
||||||
<span className="text-sm font-bold text-slate-900">{data.handling_time_min} min</span>
|
<span className="text-sm font-bold text-zinc-900 dark:text-zinc-100">{data.handling_time_min} min</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="bg-white rounded-xl border border-slate-200 shadow-sm p-5">
|
<div className="bg-white dark:bg-dark-card rounded-xl border border-zinc-200 dark:border-dark-border shadow-sm p-5 transition-colors">
|
||||||
<h3 className="text-xs font-bold text-slate-400 uppercase tracking-wider mb-4">Contexto de Vendas</h3>
|
<h3 className="text-xs font-bold text-zinc-400 dark:text-dark-muted uppercase tracking-wider mb-4">Contexto de Vendas</h3>
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<div className="space-y-1">
|
<div className="space-y-1">
|
||||||
<span className="text-xs text-slate-500 font-medium">Produto Solicitado</span>
|
<span className="text-xs text-zinc-500 dark:text-dark-muted font-medium">Produto Solicitado</span>
|
||||||
<div className="flex items-center gap-2 font-semibold text-slate-800">
|
<div className="flex items-center gap-2 font-semibold text-zinc-800 dark:text-zinc-100">
|
||||||
<ShoppingBag size={16} className="text-slate-400" /> {data.product_requested}
|
<ShoppingBag size={16} className="text-zinc-400 dark:text-dark-muted" /> {data.product_requested}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="h-px bg-slate-100 my-2" />
|
<div className="h-px bg-zinc-100 dark:bg-dark-border my-2" />
|
||||||
|
|
||||||
<div className="space-y-1">
|
<div className="space-y-1">
|
||||||
<span className="text-xs text-slate-500 font-medium">Desfecho</span>
|
<span className="text-xs text-zinc-500 dark:text-dark-muted font-medium">Desfecho</span>
|
||||||
{data.converted ? (
|
{data.converted ? (
|
||||||
<div className="flex items-center gap-2 text-green-600 font-bold bg-green-50 px-3 py-2 rounded-lg border border-green-100">
|
<div className="flex items-center gap-2 text-green-600 dark:text-green-400 font-bold bg-green-50 dark:bg-green-900/20 px-3 py-2 rounded-lg border border-green-100 dark:border-green-900/30">
|
||||||
<Award size={18} /> Venda Fechada
|
<Award size={18} /> Venda Fechada
|
||||||
{data.product_sold && <span className="text-green-800 text-xs font-normal ml-auto">{data.product_sold}</span>}
|
{data.product_sold && <span className="text-green-800 dark:text-green-200 text-xs font-normal ml-auto">{data.product_sold}</span>}
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<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="flex items-center gap-2 text-zinc-500 dark:text-dark-muted font-medium bg-zinc-50 dark:bg-dark-bg/50 px-3 py-2 rounded-lg border border-zinc-100 dark:border-dark-border">
|
||||||
<div className="w-2 h-2 rounded-full bg-slate-400" /> Não Convertido
|
<div className="w-2 h-2 rounded-full bg-zinc-400 dark:bg-zinc-600" /> Não Convertido
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import {
|
|||||||
import {
|
import {
|
||||||
Users, Clock, Phone, TrendingUp, Filter
|
Users, Clock, Phone, TrendingUp, Filter
|
||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
import { getAttendances, getUsers, getTeams } from '../services/dataService';
|
import { getAttendances, getUsers, getTeams, getUserById } from '../services/dataService';
|
||||||
import { COLORS } from '../constants';
|
import { COLORS } from '../constants';
|
||||||
import { Attendance, DashboardFilter, FunnelStage, User } from '../types';
|
import { Attendance, DashboardFilter, FunnelStage, User } from '../types';
|
||||||
import { KPICard } from '../components/KPICard';
|
import { KPICard } from '../components/KPICard';
|
||||||
@@ -27,6 +27,7 @@ export const Dashboard: React.FC = () => {
|
|||||||
const [data, setData] = useState<Attendance[]>([]);
|
const [data, setData] = useState<Attendance[]>([]);
|
||||||
const [users, setUsers] = useState<User[]>([]);
|
const [users, setUsers] = useState<User[]>([]);
|
||||||
const [teams, setTeams] = useState<any[]>([]);
|
const [teams, setTeams] = useState<any[]>([]);
|
||||||
|
const [currentUser, setCurrentUser] = useState<User | null>(null);
|
||||||
|
|
||||||
const [filters, setFilters] = useState<DashboardFilter>({
|
const [filters, setFilters] = useState<DashboardFilter>({
|
||||||
dateRange: {
|
dateRange: {
|
||||||
@@ -35,6 +36,8 @@ export const Dashboard: React.FC = () => {
|
|||||||
},
|
},
|
||||||
userId: 'all',
|
userId: 'all',
|
||||||
teamId: 'all',
|
teamId: 'all',
|
||||||
|
funnelStage: 'all',
|
||||||
|
origin: 'all',
|
||||||
});
|
});
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -42,18 +45,21 @@ export const Dashboard: React.FC = () => {
|
|||||||
setLoading(true);
|
setLoading(true);
|
||||||
try {
|
try {
|
||||||
const tenantId = localStorage.getItem('ctms_tenant_id');
|
const tenantId = localStorage.getItem('ctms_tenant_id');
|
||||||
|
const storedUserId = localStorage.getItem('ctms_user_id');
|
||||||
if (!tenantId) return;
|
if (!tenantId) return;
|
||||||
|
|
||||||
// Fetch users, attendances and teams in parallel
|
// Fetch users, attendances, teams and current user in parallel
|
||||||
const [fetchedUsers, fetchedData, fetchedTeams] = await Promise.all([
|
const [fetchedUsers, fetchedData, fetchedTeams, me] = await Promise.all([
|
||||||
getUsers(tenantId),
|
getUsers(tenantId),
|
||||||
getAttendances(tenantId, filters),
|
getAttendances(tenantId, filters),
|
||||||
getTeams(tenantId)
|
getTeams(tenantId),
|
||||||
|
storedUserId ? getUserById(storedUserId) : null
|
||||||
]);
|
]);
|
||||||
|
|
||||||
setUsers(fetchedUsers);
|
setUsers(fetchedUsers);
|
||||||
setData(fetchedData);
|
setData(fetchedData);
|
||||||
setTeams(fetchedTeams);
|
setTeams(fetchedTeams);
|
||||||
|
if (me) setCurrentUser(me);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Error loading dashboard data:", error);
|
console.error("Error loading dashboard data:", error);
|
||||||
} finally {
|
} finally {
|
||||||
@@ -164,41 +170,73 @@ export const Dashboard: React.FC = () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
if (loading && data.length === 0) {
|
if (loading && data.length === 0) {
|
||||||
return <div className="flex h-full items-center justify-center text-slate-400 p-12">Carregando Dashboard...</div>;
|
return <div className="flex h-full items-center justify-center text-zinc-400 dark:text-dark-muted p-12">Carregando Dashboard...</div>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const isAdmin = currentUser?.role === 'admin' || currentUser?.role === 'super_admin' || currentUser?.role === 'manager';
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6 pb-8">
|
<div className="space-y-6 pb-8 transition-colors duration-300">
|
||||||
{/* Filters Bar */}
|
{/* 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="bg-white dark:bg-dark-card p-4 rounded-xl shadow-sm border border-zinc-100 dark:border-dark-border flex flex-col gap-4">
|
||||||
<div className="flex items-center gap-2 text-slate-500 font-medium">
|
<div className="flex flex-col md:flex-row gap-4 items-center justify-between">
|
||||||
<Filter size={18} />
|
<div className="flex items-center gap-2 text-zinc-500 dark:text-dark-muted font-medium">
|
||||||
<span className="hidden md:inline">Filtros:</span>
|
<Filter size={18} />
|
||||||
</div>
|
<span>Filtros:</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div className="flex flex-wrap items-center gap-3 w-full md:w-auto">
|
<div className="flex flex-wrap items-center gap-3 w-full md:w-auto">
|
||||||
<DateRangePicker
|
<DateRangePicker
|
||||||
dateRange={filters.dateRange}
|
dateRange={filters.dateRange}
|
||||||
onChange={(range) => handleFilterChange('dateRange', range)}
|
onChange={(range) => handleFilterChange('dateRange', range)}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<select
|
{isAdmin && (
|
||||||
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}
|
<select
|
||||||
onChange={(e) => handleFilterChange('userId', e.target.value)}
|
className="bg-zinc-50 dark:bg-dark-bg border border-zinc-200 dark:border-dark-border px-3 py-2 rounded-lg text-sm text-zinc-700 dark:text-zinc-200 outline-none focus:ring-2 focus:ring-brand-yellow/20 cursor-pointer hover:border-zinc-300 dark:hover:border-dark-border transition-all"
|
||||||
>
|
value={filters.userId}
|
||||||
<option value="all">Todos Usuários</option>
|
onChange={(e) => handleFilterChange('userId', e.target.value)}
|
||||||
{users.map(u => <option key={u.id} value={u.id}>{u.name}</option>)}
|
>
|
||||||
</select>
|
<option value="all">Todos Usuários</option>
|
||||||
|
{users.map(u => <option key={u.id} value={u.id}>{u.name}</option>)}
|
||||||
|
</select>
|
||||||
|
|
||||||
<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"
|
className="bg-zinc-50 dark:bg-dark-bg border border-zinc-200 dark:border-dark-border px-3 py-2 rounded-lg text-sm text-zinc-700 dark:text-zinc-200 outline-none focus:ring-2 focus:ring-brand-yellow/20 cursor-pointer hover:border-zinc-300 dark:hover:border-dark-border transition-all"
|
||||||
value={filters.teamId}
|
value={filters.teamId}
|
||||||
onChange={(e) => handleFilterChange('teamId', e.target.value)}
|
onChange={(e) => handleFilterChange('teamId', e.target.value)}
|
||||||
>
|
>
|
||||||
<option value="all">Todas Equipes</option>
|
<option value="all">Todas Equipes</option>
|
||||||
{teams.map(t => <option key={t.id} value={t.id}>{t.name}</option>)}
|
{teams.map(t => <option key={t.id} value={t.id}>{t.name}</option>)}
|
||||||
</select>
|
</select>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<select
|
||||||
|
className="bg-zinc-50 dark:bg-dark-bg border border-zinc-200 dark:border-dark-border px-3 py-2 rounded-lg text-sm text-zinc-700 dark:text-zinc-200 outline-none focus:ring-2 focus:ring-brand-yellow/20 cursor-pointer hover:border-zinc-300 dark:hover:border-dark-border transition-all"
|
||||||
|
value={filters.funnelStage}
|
||||||
|
onChange={(e) => handleFilterChange('funnelStage', e.target.value)}
|
||||||
|
>
|
||||||
|
<option value="all">Todas Etapas</option>
|
||||||
|
{Object.values(FunnelStage).map(stage => (
|
||||||
|
<option key={stage} value={stage}>{stage}</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
|
||||||
|
<select
|
||||||
|
className="bg-zinc-50 dark:bg-dark-bg border border-zinc-200 dark:border-dark-border px-3 py-2 rounded-lg text-sm text-zinc-700 dark:text-zinc-200 outline-none focus:ring-2 focus:ring-brand-yellow/20 cursor-pointer hover:border-zinc-300 dark:hover:border-dark-border transition-all"
|
||||||
|
value={filters.origin}
|
||||||
|
onChange={(e) => handleFilterChange('origin', e.target.value)}
|
||||||
|
>
|
||||||
|
<option value="all">Todas Origens</option>
|
||||||
|
<option value="WhatsApp">WhatsApp</option>
|
||||||
|
<option value="Instagram">Instagram</option>
|
||||||
|
<option value="Website">Website</option>
|
||||||
|
<option value="LinkedIn">LinkedIn</option>
|
||||||
|
<option value="Indicação">Indicação</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -210,7 +248,7 @@ export const Dashboard: React.FC = () => {
|
|||||||
trend="up"
|
trend="up"
|
||||||
trendValue="12%"
|
trendValue="12%"
|
||||||
icon={Users}
|
icon={Users}
|
||||||
colorClass="text-blue-600"
|
colorClass="text-yellow-600"
|
||||||
/>
|
/>
|
||||||
<KPICard
|
<KPICard
|
||||||
title="Nota Média Qualidade"
|
title="Nota Média Qualidade"
|
||||||
@@ -219,7 +257,7 @@ export const Dashboard: React.FC = () => {
|
|||||||
trend={Number(avgScore) > 75 ? 'up' : 'down'}
|
trend={Number(avgScore) > 75 ? 'up' : 'down'}
|
||||||
trendValue="2.1"
|
trendValue="2.1"
|
||||||
icon={TrendingUp}
|
icon={TrendingUp}
|
||||||
colorClass="text-purple-600"
|
colorClass="text-zinc-600"
|
||||||
/>
|
/>
|
||||||
<KPICard
|
<KPICard
|
||||||
title="Média 1ª Resposta"
|
title="Média 1ª Resposta"
|
||||||
@@ -241,8 +279,8 @@ export const Dashboard: React.FC = () => {
|
|||||||
{/* Charts Section */}
|
{/* Charts Section */}
|
||||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
||||||
{/* Funnel Chart */}
|
{/* Funnel Chart */}
|
||||||
<div className="lg:col-span-2 bg-white p-6 rounded-2xl shadow-sm border border-slate-100 min-h-[400px]">
|
<div className="lg:col-span-2 bg-white dark:bg-dark-card p-6 rounded-2xl shadow-sm border border-zinc-100 dark:border-dark-border min-h-[400px]">
|
||||||
<h3 className="text-lg font-bold text-slate-800 mb-6">Funil de Vendas</h3>
|
<h3 className="text-lg font-bold text-zinc-800 dark:text-dark-text mb-6">Funil de Vendas</h3>
|
||||||
<div className="h-[300px] w-full">
|
<div className="h-[300px] w-full">
|
||||||
<ResponsiveContainer width="100%" height="100%">
|
<ResponsiveContainer width="100%" height="100%">
|
||||||
<BarChart
|
<BarChart
|
||||||
@@ -251,23 +289,35 @@ export const Dashboard: React.FC = () => {
|
|||||||
margin={{ top: 5, right: 30, left: 40, bottom: 5 }}
|
margin={{ top: 5, right: 30, left: 40, bottom: 5 }}
|
||||||
barSize={32}
|
barSize={32}
|
||||||
>
|
>
|
||||||
<CartesianGrid strokeDasharray="3 3" horizontal={true} vertical={false} stroke="#f1f5f9" />
|
<CartesianGrid strokeDasharray="3 3" horizontal={true} vertical={false} stroke="#f1f5f9" className="dark:opacity-5" />
|
||||||
<XAxis type="number" hide />
|
<XAxis type="number" hide />
|
||||||
<YAxis
|
<YAxis
|
||||||
dataKey="name"
|
dataKey="name"
|
||||||
type="category"
|
type="category"
|
||||||
width={120}
|
width={120}
|
||||||
tick={{fill: '#475569', fontSize: 13, fontWeight: 500}}
|
tick={{fill: '#71717a', fontSize: 13, fontWeight: 500}}
|
||||||
|
className="dark:fill-dark-muted"
|
||||||
tickLine={false}
|
tickLine={false}
|
||||||
axisLine={false}
|
axisLine={false}
|
||||||
/>
|
/>
|
||||||
<Tooltip
|
<Tooltip
|
||||||
cursor={{fill: '#f8fafc'}}
|
cursor={{fill: '#f8fafc', opacity: 0.05}}
|
||||||
contentStyle={{ borderRadius: '12px', border: 'none', boxShadow: '0 10px 15px -3px rgb(0 0 0 / 0.1)' }}
|
formatter={(value: any) => [value, 'Quantidade']}
|
||||||
|
contentStyle={{
|
||||||
|
borderRadius: '12px',
|
||||||
|
border: 'none',
|
||||||
|
boxShadow: '0 10px 15px -3px rgb(0 0 0 / 0.1)',
|
||||||
|
backgroundColor: '#1a1a1a',
|
||||||
|
color: '#ededed'
|
||||||
|
}}
|
||||||
|
itemStyle={{ color: '#ededed' }}
|
||||||
/>
|
/>
|
||||||
<Bar dataKey="value" radius={[0, 6, 6, 0]}>
|
<Bar dataKey="value" radius={[0, 6, 6, 0]}>
|
||||||
{funnelData.map((entry, index) => (
|
{funnelData.map((entry, index) => (
|
||||||
<Cell key={`cell-${index}`} fill={COLORS.charts[index % COLORS.charts.length]} />
|
<Cell
|
||||||
|
key={`cell-${index}`}
|
||||||
|
fill={COLORS.funnel[entry.name as keyof typeof COLORS.funnel] || '#cbd5e1'}
|
||||||
|
/>
|
||||||
))}
|
))}
|
||||||
</Bar>
|
</Bar>
|
||||||
</BarChart>
|
</BarChart>
|
||||||
@@ -276,8 +326,8 @@ export const Dashboard: React.FC = () => {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Origin Pie Chart */}
|
{/* Origin Pie Chart */}
|
||||||
<div className="bg-white p-6 rounded-2xl shadow-sm border border-slate-100 min-h-[400px] flex flex-col">
|
<div className="bg-white dark:bg-dark-card p-6 rounded-2xl shadow-sm border border-zinc-100 dark:border-dark-border min-h-[400px] flex flex-col">
|
||||||
<h3 className="text-lg font-bold text-slate-800 mb-2">Origem dos Leads</h3>
|
<h3 className="text-lg font-bold text-zinc-800 dark:text-dark-text mb-2">Origem dos Leads</h3>
|
||||||
<div className="flex-1 min-h-0">
|
<div className="flex-1 min-h-0">
|
||||||
<ResponsiveContainer width="100%" height="100%">
|
<ResponsiveContainer width="100%" height="100%">
|
||||||
<PieChart>
|
<PieChart>
|
||||||
@@ -292,10 +342,22 @@ export const Dashboard: React.FC = () => {
|
|||||||
stroke="none"
|
stroke="none"
|
||||||
>
|
>
|
||||||
{originData.map((entry, index) => (
|
{originData.map((entry, index) => (
|
||||||
<Cell key={`cell-${index}`} fill={COLORS.charts[index % COLORS.charts.length]} />
|
<Cell
|
||||||
|
key={`cell-${index}`}
|
||||||
|
fill={COLORS.origins[entry.name as keyof typeof COLORS.origins] || COLORS.charts[index % COLORS.charts.length]}
|
||||||
|
/>
|
||||||
))}
|
))}
|
||||||
</Pie>
|
</Pie>
|
||||||
<Tooltip contentStyle={{ borderRadius: '12px' }} />
|
<Tooltip
|
||||||
|
formatter={(value: any) => [value, 'Leads']}
|
||||||
|
contentStyle={{
|
||||||
|
borderRadius: '12px',
|
||||||
|
backgroundColor: '#1a1a1a',
|
||||||
|
border: 'none',
|
||||||
|
color: '#ededed'
|
||||||
|
}}
|
||||||
|
itemStyle={{ color: '#ededed' }}
|
||||||
|
/>
|
||||||
<Legend
|
<Legend
|
||||||
verticalAlign="bottom"
|
verticalAlign="bottom"
|
||||||
height={80}
|
height={80}
|
||||||
|
|||||||
@@ -4,10 +4,10 @@ import { Hexagon, Mail, ArrowRight, Loader2, ArrowLeft, CheckCircle2 } from 'luc
|
|||||||
import { forgotPassword } from '../services/dataService';
|
import { forgotPassword } from '../services/dataService';
|
||||||
|
|
||||||
export const ForgotPassword: React.FC = () => {
|
export const ForgotPassword: React.FC = () => {
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
|
||||||
const [email, setEmail] = useState('');
|
const [email, setEmail] = useState('');
|
||||||
const [error, setError] = useState('');
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
const [isSuccess, setIsSuccess] = useState(false);
|
const [isSuccess, setIsSuccess] = useState(false);
|
||||||
|
const [error, setError] = useState('');
|
||||||
|
|
||||||
const handleSubmit = async (e: React.FormEvent) => {
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
@@ -18,117 +18,97 @@ export const ForgotPassword: React.FC = () => {
|
|||||||
await forgotPassword(email);
|
await forgotPassword(email);
|
||||||
setIsSuccess(true);
|
setIsSuccess(true);
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
setError(err.message || 'Erro ao processar solicitação.');
|
setError(err.message || 'Erro ao enviar e-mail de recuperação.');
|
||||||
} finally {
|
} finally {
|
||||||
setIsLoading(false);
|
setIsLoading(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-slate-50 flex flex-col justify-center py-12 sm:px-6 lg:px-8">
|
<div className="min-h-screen bg-zinc-50 dark:bg-dark-bg flex flex-col justify-center py-12 sm:px-6 lg:px-8 transition-colors duration-300">
|
||||||
<div className="sm:mx-auto sm:w-full sm:max-w-md">
|
<div className="sm:mx-auto sm:w-full sm:max-w-md">
|
||||||
<div className="flex justify-center items-center gap-2 text-slate-900">
|
<div className="flex justify-center items-center gap-2 text-zinc-900 dark:text-zinc-50">
|
||||||
<div className="bg-slate-900 text-white p-2 rounded-lg">
|
<div className="bg-zinc-900 dark:bg-brand-yellow text-white dark:text-zinc-950 p-2 rounded-lg transition-colors">
|
||||||
<Hexagon size={28} fill="currentColor" />
|
<Hexagon size={32} fill="currentColor" />
|
||||||
</div>
|
</div>
|
||||||
<span className="text-3xl font-bold tracking-tight">Fasto<span className="text-yellow-500">.</span></span>
|
<span className="text-3xl font-bold tracking-tight">Fasto<span className="text-brand-yellow">.</span></span>
|
||||||
</div>
|
</div>
|
||||||
<h2 className="mt-6 text-center text-3xl font-bold tracking-tight text-slate-900">
|
<h2 className="mt-6 text-center text-3xl font-bold tracking-tight text-zinc-900 dark:text-zinc-50">
|
||||||
Recupere sua senha
|
Recupere sua senha
|
||||||
</h2>
|
</h2>
|
||||||
<p className="mt-2 text-center text-sm text-slate-600">
|
<p className="mt-2 text-center text-sm text-zinc-600 dark:text-dark-muted">
|
||||||
Digite seu e-mail e enviaremos as instruções.
|
Enviaremos um link de redefinição para o seu e-mail.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="mt-8 sm:mx-auto sm:w-full sm:max-w-md">
|
<div className="mt-8 sm:mx-auto sm:w-full sm:max-w-md">
|
||||||
<div className="bg-white py-8 px-4 shadow-xl shadow-slate-200/50 rounded-2xl sm:px-10 border border-slate-100">
|
<div className="bg-white dark:bg-dark-card py-8 px-4 shadow-xl rounded-2xl sm:px-10 border border-zinc-100 dark:border-dark-border transition-colors">
|
||||||
|
|
||||||
{isSuccess ? (
|
{isSuccess ? (
|
||||||
<div className="text-center space-y-4 py-4">
|
<div className="text-center py-4 space-y-4 animate-in fade-in zoom-in duration-300">
|
||||||
<div className="flex justify-center">
|
<div className="mx-auto flex items-center justify-center h-12 w-12 rounded-full bg-green-100 dark:bg-green-900/30 text-green-600 dark:text-green-400">
|
||||||
<div className="bg-green-100 p-3 rounded-full text-green-600">
|
<CheckCircle2 size={24} />
|
||||||
<CheckCircle2 size={32} />
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
<h3 className="text-lg font-bold text-slate-900">E-mail enviado!</h3>
|
<h3 className="text-lg font-bold text-zinc-900 dark:text-zinc-50">E-mail enviado!</h3>
|
||||||
<p className="text-sm text-slate-600">
|
<p className="text-sm text-zinc-600 dark:text-dark-muted">
|
||||||
Se o e-mail <strong>{email}</strong> estiver cadastrado, você receberá um link em instantes.
|
Verifique sua caixa de entrada (e a pasta de spam) para as instruções.
|
||||||
</p>
|
</p>
|
||||||
<div className="pt-4">
|
<div className="pt-4">
|
||||||
<Link to="/login" className="text-blue-600 font-medium hover:underline flex items-center justify-center gap-2">
|
<Link to="/login" className="text-brand-yellow font-bold hover:text-yellow-600 flex items-center justify-center gap-2 transition-colors">
|
||||||
<ArrowLeft size={16} /> Voltar para o login
|
<ArrowLeft size={18} /> Voltar para o login
|
||||||
</Link>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<form className="space-y-6" onSubmit={handleSubmit}>
|
<form className="space-y-6" onSubmit={handleSubmit}>
|
||||||
<div>
|
|
||||||
<label htmlFor="email" className="block text-sm font-medium text-slate-700">
|
|
||||||
Endereço de e-mail
|
|
||||||
</label>
|
|
||||||
<div className="mt-1 relative rounded-md shadow-sm">
|
|
||||||
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
|
|
||||||
<Mail className="h-5 w-5 text-slate-400" />
|
|
||||||
</div>
|
|
||||||
<input
|
|
||||||
id="email"
|
|
||||||
name="email"
|
|
||||||
type="email"
|
|
||||||
required
|
|
||||||
value={email}
|
|
||||||
onChange={(e) => setEmail(e.target.value)}
|
|
||||||
className="block w-full pl-10 pr-3 py-2 border border-slate-300 rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-blue-100 focus:border-blue-500 sm:text-sm transition-all"
|
|
||||||
placeholder="voce@empresa.com"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{error && (
|
{error && (
|
||||||
<div className="text-red-500 text-sm font-medium text-center">
|
<div className="bg-red-50 dark:bg-red-900/20 border border-red-100 dark:border-red-900/30 p-3 rounded-lg text-red-600 dark:text-red-400 text-sm">
|
||||||
{error}
|
{error}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label htmlFor="email" className="block text-sm font-medium text-zinc-700 dark:text-zinc-300">
|
||||||
|
Seu E-mail
|
||||||
|
</label>
|
||||||
|
<div className="mt-1 relative">
|
||||||
|
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
|
||||||
|
<Mail className="h-5 w-5 text-zinc-400 dark:text-dark-muted" />
|
||||||
|
</div>
|
||||||
|
<input
|
||||||
|
id="email"
|
||||||
|
type="email"
|
||||||
|
required
|
||||||
|
value={email}
|
||||||
|
onChange={(e) => setEmail(e.target.value)}
|
||||||
|
className="block w-full pl-10 pr-3 py-2 border border-zinc-300 dark:border-dark-border rounded-lg bg-white dark:bg-dark-input text-zinc-900 dark:text-zinc-100 placeholder-zinc-400 dark:placeholder-zinc-600 focus:ring-brand-yellow/20 focus:border-brand-yellow sm:text-sm transition-all"
|
||||||
|
placeholder="seu@email.com"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<button
|
<button
|
||||||
type="submit"
|
type="submit"
|
||||||
disabled={isLoading}
|
disabled={isLoading}
|
||||||
className="w-full flex justify-center items-center gap-2 py-2.5 px-4 border border-transparent rounded-lg shadow-sm text-sm font-semibold text-white bg-slate-900 hover:bg-slate-800 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-slate-900 transition-all"
|
className="w-full flex justify-center items-center gap-2 py-2.5 px-4 border border-transparent rounded-lg shadow-sm text-sm font-bold text-zinc-950 bg-brand-yellow hover:bg-yellow-500 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-brand-yellow transition-all disabled:opacity-70"
|
||||||
>
|
>
|
||||||
{isLoading ? (
|
{isLoading ? (
|
||||||
<>
|
<Loader2 className="animate-spin h-5 w-5" />
|
||||||
<Loader2 className="animate-spin h-4 w-4" />
|
|
||||||
Enviando...
|
|
||||||
</>
|
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
Enviar Instruções <ArrowRight className="h-4 w-4" />
|
Enviar Link <ArrowRight size={18} />
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="text-center">
|
<div className="text-center">
|
||||||
<Link to="/login" className="text-sm text-slate-500 hover:text-slate-800 flex items-center justify-center gap-1">
|
<Link to="/login" className="text-sm text-zinc-500 dark:text-dark-muted hover:text-zinc-800 dark:hover:text-zinc-200 flex items-center justify-center gap-1 transition-colors">
|
||||||
<ArrowLeft size={14} /> Voltar para o login
|
<ArrowLeft size={14} /> Voltar para o login
|
||||||
</Link>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<div className="mt-6">
|
|
||||||
<div className="relative">
|
|
||||||
<div className="absolute inset-0 flex items-center">
|
|
||||||
<div className="w-full border-t border-slate-200" />
|
|
||||||
</div>
|
|
||||||
<div className="relative flex justify-center text-sm">
|
|
||||||
<span className="px-2 bg-white text-slate-500 text-xs">
|
|
||||||
Desenvolvido por <a href="https://blyzer.com.br" target="_blank" rel="noopener noreferrer" className="text-blue-600 hover:underline">Blyzer</a>
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
148
pages/Login.tsx
148
pages/Login.tsx
@@ -1,7 +1,7 @@
|
|||||||
import React, { useState } from 'react';
|
import React, { useState } from 'react';
|
||||||
import { useNavigate, Link } from 'react-router-dom';
|
import { useNavigate, Link } from 'react-router-dom';
|
||||||
import { Hexagon, Lock, Mail, ArrowRight, Loader2, Eye, EyeOff, AlertCircle } from 'lucide-react';
|
import { Hexagon, Lock, Mail, ArrowRight, Loader2, Eye, EyeOff, AlertCircle } from 'lucide-react';
|
||||||
import { login } from '../services/dataService';
|
import { login, logout } from '../services/dataService';
|
||||||
|
|
||||||
export const Login: React.FC = () => {
|
export const Login: React.FC = () => {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
@@ -12,23 +12,17 @@ export const Login: React.FC = () => {
|
|||||||
const [error, setError] = useState('');
|
const [error, setError] = useState('');
|
||||||
const [emailError, setEmailError] = useState('');
|
const [emailError, setEmailError] = useState('');
|
||||||
|
|
||||||
const validateEmail = (value: string) => {
|
const validateEmail = (val: string) => {
|
||||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
setEmail(val);
|
||||||
if (!value) {
|
if (!val) {
|
||||||
setEmailError('');
|
setEmailError('E-mail é obrigatório');
|
||||||
} else if (!emailRegex.test(value)) {
|
} else if (!/\S+@\S+\.\S+/.test(val)) {
|
||||||
setEmailError('Por favor, insira um e-mail válido.');
|
setEmailError('E-mail inválido');
|
||||||
} else {
|
} else {
|
||||||
setEmailError('');
|
setEmailError('');
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleEmailChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
|
||||||
const value = e.target.value;
|
|
||||||
setEmail(value);
|
|
||||||
validateEmail(value);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleLogin = async (e: React.FormEvent) => {
|
const handleLogin = async (e: React.FormEvent) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
if (emailError) return;
|
if (emailError) return;
|
||||||
@@ -36,52 +30,59 @@ export const Login: React.FC = () => {
|
|||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
setError('');
|
setError('');
|
||||||
|
|
||||||
|
logout();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const data = await login({ email, password });
|
const data = await login({ email, password });
|
||||||
|
|
||||||
localStorage.setItem('ctms_token', data.token);
|
|
||||||
localStorage.setItem('ctms_user_id', data.user.id);
|
|
||||||
localStorage.setItem('ctms_tenant_id', data.user.tenant_id || '');
|
|
||||||
|
|
||||||
setIsLoading(false);
|
setIsLoading(false);
|
||||||
|
|
||||||
if (data.user.role === 'super_admin') {
|
if (data.user.role === 'super_admin') {
|
||||||
navigate('/super-admin');
|
navigate('/super-admin');
|
||||||
} else {
|
} else {
|
||||||
navigate('/');
|
navigate('/');
|
||||||
}
|
}
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
console.error("Login error:", err);
|
|
||||||
setIsLoading(false);
|
setIsLoading(false);
|
||||||
setError(err.message || 'E-mail ou senha incorretos.');
|
setError(err.message || 'Erro ao fazer login. Verifique suas credenciais.');
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-slate-50 flex flex-col justify-center py-12 sm:px-6 lg:px-8">
|
<div className="min-h-screen bg-zinc-50 dark:bg-dark-bg flex flex-col justify-center py-12 sm:px-6 lg:px-8 transition-colors duration-300">
|
||||||
<div className="sm:mx-auto sm:w-full sm:max-w-md">
|
<div className="sm:mx-auto sm:w-full sm:max-w-md">
|
||||||
<div className="flex justify-center items-center gap-2 text-slate-900">
|
<div className="flex justify-center items-center gap-2 text-zinc-900 dark:text-zinc-50">
|
||||||
<div className="bg-slate-900 text-white p-2 rounded-lg">
|
<div className="bg-zinc-900 dark:bg-brand-yellow text-white dark:text-zinc-950 p-2 rounded-lg transition-colors">
|
||||||
<Hexagon size={28} fill="currentColor" />
|
<Hexagon size={32} fill="currentColor" />
|
||||||
</div>
|
</div>
|
||||||
<span className="text-3xl font-bold tracking-tight">Fasto<span className="text-yellow-500">.</span></span>
|
<span className="text-3xl font-bold tracking-tight">Fasto<span className="text-brand-yellow">.</span></span>
|
||||||
</div>
|
</div>
|
||||||
<h2 className="mt-6 text-center text-3xl font-bold tracking-tight text-slate-900">
|
<h2 className="mt-6 text-center text-3xl font-bold tracking-tight text-zinc-900 dark:text-zinc-50">
|
||||||
Acesse sua conta
|
Acesse sua conta
|
||||||
</h2>
|
</h2>
|
||||||
|
<p className="mt-2 text-center text-sm text-zinc-600 dark:text-dark-muted">
|
||||||
|
Ou{' '}
|
||||||
|
<Link to="/register" className="font-medium text-brand-yellow hover:text-yellow-600">
|
||||||
|
registre sua nova organização
|
||||||
|
</Link>
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="mt-8 sm:mx-auto sm:w-full sm:max-w-md">
|
<div className="mt-8 sm:mx-auto sm:w-full sm:max-w-md">
|
||||||
<div className="bg-white py-8 px-4 shadow-xl shadow-slate-200/50 rounded-2xl sm:px-10 border border-slate-100">
|
<div className="bg-white dark:bg-dark-card py-8 px-4 shadow-xl shadow-zinc-200/50 dark:shadow-none rounded-2xl sm:px-10 border border-zinc-100 dark:border-dark-border transition-colors">
|
||||||
|
|
||||||
<form className="space-y-6" onSubmit={handleLogin}>
|
<form className="space-y-6" onSubmit={handleLogin}>
|
||||||
|
{error && (
|
||||||
|
<div className="bg-red-50 dark:bg-red-900/20 border border-red-100 dark:border-red-900/30 p-3 rounded-lg flex items-center gap-2 text-red-600 dark:text-red-400 text-sm animate-in fade-in slide-in-from-top-1">
|
||||||
|
<AlertCircle size={18} />
|
||||||
|
{error}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<label htmlFor="email" className="block text-sm font-medium text-slate-700">
|
<label htmlFor="email" className="block text-sm font-medium text-zinc-700 dark:text-zinc-300">
|
||||||
Endereço de e-mail
|
Endereço de E-mail
|
||||||
</label>
|
</label>
|
||||||
<div className="mt-1 relative rounded-md shadow-sm">
|
<div className="mt-1 relative">
|
||||||
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
|
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
|
||||||
<Mail className={`h-5 w-5 ${emailError ? 'text-red-400' : 'text-slate-400'}`} />
|
<Mail className="h-5 w-5 text-zinc-400 dark:text-dark-muted" />
|
||||||
</div>
|
</div>
|
||||||
<input
|
<input
|
||||||
id="email"
|
id="email"
|
||||||
@@ -90,29 +91,28 @@ export const Login: React.FC = () => {
|
|||||||
autoComplete="email"
|
autoComplete="email"
|
||||||
required
|
required
|
||||||
value={email}
|
value={email}
|
||||||
onChange={handleEmailChange}
|
onChange={(e) => validateEmail(e.target.value)}
|
||||||
className={`block w-full pl-10 pr-3 py-2 border rounded-lg leading-5 bg-white placeholder-slate-400 focus:outline-none focus:ring-2 transition-all sm:text-sm ${
|
className={`block w-full pl-10 pr-3 py-2 border ${emailError ? 'border-red-300 focus:ring-red-100 focus:border-red-500' : 'border-zinc-300 dark:border-dark-border focus:ring-brand-yellow/20 focus:border-brand-yellow'} rounded-lg bg-white dark:bg-dark-input text-zinc-900 dark:text-zinc-100 placeholder-zinc-400 dark:placeholder-zinc-600 sm:text-sm transition-all`}
|
||||||
emailError
|
placeholder="seu@email.com"
|
||||||
? 'border-red-300 focus:ring-red-100 focus:border-red-500'
|
|
||||||
: 'border-slate-300 focus:ring-blue-100 focus:border-blue-500'
|
|
||||||
}`}
|
|
||||||
placeholder="voce@empresa.com"
|
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
{emailError && (
|
{emailError && <p className="mt-1 text-xs text-red-500">{emailError}</p>}
|
||||||
<p className="mt-1.5 text-xs text-red-500 font-medium flex items-center gap-1">
|
|
||||||
<AlertCircle size={12} /> {emailError}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<label htmlFor="password" senior-admin-password className="block text-sm font-medium text-slate-700">
|
<div className="flex items-center justify-between">
|
||||||
Senha
|
<label htmlFor="password" senior-admin-password className="block text-sm font-medium text-zinc-700 dark:text-zinc-300">
|
||||||
</label>
|
Senha
|
||||||
<div className="mt-1 relative rounded-md shadow-sm">
|
</label>
|
||||||
|
<div className="text-sm">
|
||||||
|
<Link to="/forgot-password" size="14" className="font-medium text-brand-yellow hover:text-yellow-600 transition-colors">
|
||||||
|
Esqueceu a senha?
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="mt-1 relative">
|
||||||
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
|
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
|
||||||
<Lock className="h-5 w-5 text-slate-400" />
|
<Lock className="h-5 w-5 text-zinc-400 dark:text-dark-muted" />
|
||||||
</div>
|
</div>
|
||||||
<input
|
<input
|
||||||
id="password"
|
id="password"
|
||||||
@@ -122,74 +122,46 @@ export const Login: React.FC = () => {
|
|||||||
required
|
required
|
||||||
value={password}
|
value={password}
|
||||||
onChange={(e) => setPassword(e.target.value)}
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
className="block w-full pl-10 pr-10 py-2 border border-slate-300 rounded-lg leading-5 bg-white placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-100 focus:border-blue-500 sm:text-sm transition-all"
|
className="block w-full pl-10 pr-10 py-2 border border-zinc-300 dark:border-dark-border rounded-lg bg-white dark:bg-dark-input text-zinc-900 dark:text-zinc-100 placeholder-zinc-400 dark:placeholder-zinc-600 sm:text-sm focus:ring-brand-yellow/20 focus:border-brand-yellow transition-all"
|
||||||
placeholder="••••••••"
|
placeholder="••••••••"
|
||||||
/>
|
/>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
|
className="absolute inset-y-0 right-0 pr-3 flex items-center text-zinc-400 hover:text-zinc-600 dark:hover:text-zinc-200 transition-colors"
|
||||||
onClick={() => setShowPassword(!showPassword)}
|
onClick={() => setShowPassword(!showPassword)}
|
||||||
className="absolute inset-y-0 right-0 pr-3 flex items-center text-slate-400 hover:text-slate-600 transition-colors"
|
|
||||||
>
|
>
|
||||||
{showPassword ? <EyeOff size={18} /> : <Eye size={18} />}
|
{showPassword ? <EyeOff size={18} /> : <Eye size={18} />}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{error && (
|
|
||||||
<div className="bg-red-50 border border-red-100 text-red-600 px-4 py-3 rounded-xl text-sm font-medium flex items-center gap-2 animate-in fade-in slide-in-from-top-2 duration-200">
|
|
||||||
<AlertCircle size={18} className="shrink-0" />
|
|
||||||
{error}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<div className="flex items-center">
|
|
||||||
<input
|
|
||||||
id="remember-me"
|
|
||||||
name="remember-me"
|
|
||||||
type="checkbox"
|
|
||||||
className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-slate-300 rounded"
|
|
||||||
/>
|
|
||||||
<label htmlFor="remember-me" className="ml-2 block text-sm text-slate-900">
|
|
||||||
Lembrar de mim
|
|
||||||
</label>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="text-sm">
|
|
||||||
<Link to="/forgot-password" title="Recuperar Senha" className="font-medium text-blue-600 hover:text-blue-500">
|
|
||||||
Esqueceu sua senha?
|
|
||||||
</Link>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<button
|
<button
|
||||||
type="submit"
|
type="submit"
|
||||||
disabled={isLoading || !!emailError || !email}
|
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"
|
className="w-full flex justify-center items-center gap-2 py-2.5 px-4 border border-transparent rounded-lg shadow-sm text-sm font-bold text-zinc-950 bg-brand-yellow hover:bg-yellow-500 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-brand-yellow transition-all disabled:opacity-70"
|
||||||
>
|
>
|
||||||
{isLoading ? (
|
{isLoading ? (
|
||||||
<>
|
<>
|
||||||
<Loader2 className="animate-spin h-4 w-4" />
|
<Loader2 className="animate-spin h-5 w-5" /> Entrando...
|
||||||
Entrando...
|
|
||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
Entrar <ArrowRight className="h-4 w-4" />
|
Entrar <ArrowRight size={18} />
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
<div className="mt-6">
|
<div className="mt-8">
|
||||||
<div className="relative">
|
<div className="relative">
|
||||||
<div className="absolute inset-0 flex items-center">
|
<div className="absolute inset-0 flex items-center">
|
||||||
<div className="w-full border-t border-slate-200" />
|
<div className="w-full border-t border-zinc-200 dark:border-dark-border" />
|
||||||
</div>
|
</div>
|
||||||
<div className="relative flex justify-center text-sm">
|
<div className="relative flex justify-center text-sm">
|
||||||
<span className="px-2 bg-white text-slate-500 text-xs">
|
<span className="px-2 bg-white dark:bg-dark-card text-zinc-500 dark:text-dark-muted text-xs uppercase tracking-widest font-bold transition-colors">
|
||||||
Desenvolvido por <a href="https://blyzer.com.br" target="_blank" rel="noopener noreferrer" className="text-blue-600 hover:underline">Blyzer</a>
|
Powered by <a href="https://blyzer.com.br" target="_blank" rel="noopener noreferrer" className="text-brand-yellow hover:underline">Blyzer</a>
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -22,156 +22,87 @@ export const Register: React.FC = () => {
|
|||||||
try {
|
try {
|
||||||
const success = await register(formData);
|
const success = await register(formData);
|
||||||
if (success) {
|
if (success) {
|
||||||
// Save email to localStorage for the verification step
|
navigate('/login', { state: { message: 'Conta criada! Verifique seu e-mail para o código de ativação.' } });
|
||||||
localStorage.setItem('pending_verify_email', formData.email);
|
|
||||||
navigate('/verify');
|
|
||||||
}
|
}
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
setError(err.message || 'Erro ao realizar registro.');
|
setError(err.message || 'Erro ao criar conta.');
|
||||||
} finally {
|
} finally {
|
||||||
setIsLoading(false);
|
setIsLoading(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-slate-50 flex flex-col justify-center py-12 sm:px-6 lg:px-8">
|
<div className="min-h-screen bg-zinc-50 dark:bg-dark-bg flex flex-col justify-center py-12 sm:px-6 lg:px-8 transition-colors duration-300">
|
||||||
<div className="sm:mx-auto sm:w-full sm:max-w-md">
|
<div className="sm:mx-auto sm:w-full sm:max-w-md">
|
||||||
<div className="flex justify-center items-center gap-2 text-slate-900">
|
<div className="flex justify-center items-center gap-2 text-zinc-900 dark:text-zinc-50">
|
||||||
<div className="bg-slate-900 text-white p-2 rounded-lg">
|
<div className="bg-zinc-900 dark:bg-brand-yellow text-white dark:text-zinc-950 p-2 rounded-lg transition-colors">
|
||||||
<Hexagon size={28} fill="currentColor" />
|
<Hexagon size={32} fill="currentColor" />
|
||||||
</div>
|
</div>
|
||||||
<span className="text-3xl font-bold tracking-tight">Fasto<span className="text-yellow-500">.</span></span>
|
<span className="text-3xl font-bold tracking-tight">Fasto<span className="text-brand-yellow">.</span></span>
|
||||||
</div>
|
</div>
|
||||||
<h2 className="mt-6 text-center text-3xl font-bold tracking-tight text-slate-900">
|
<h2 className="mt-6 text-center text-3xl font-bold tracking-tight text-zinc-900 dark:text-zinc-50">
|
||||||
Crie sua conta
|
Crie sua organização
|
||||||
</h2>
|
</h2>
|
||||||
<p className="mt-2 text-center text-sm text-slate-600">
|
|
||||||
Já tem uma conta? <Link to="/login" className="font-medium text-blue-600 hover:text-blue-500">Faça login agora</Link>
|
|
||||||
</p>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="mt-8 sm:mx-auto sm:w-full sm:max-w-md">
|
<div className="mt-8 sm:mx-auto sm:w-full sm:max-w-md">
|
||||||
<div className="bg-white py-8 px-4 shadow-xl shadow-slate-200/50 rounded-2xl sm:px-10 border border-slate-100">
|
<div className="bg-white dark:bg-dark-card py-8 px-4 shadow-xl shadow-zinc-200/50 dark:shadow-none rounded-2xl sm:px-10 border border-zinc-100 dark:border-dark-border transition-colors">
|
||||||
|
|
||||||
<form className="space-y-5" onSubmit={handleRegister}>
|
<form className="space-y-5" onSubmit={handleRegister}>
|
||||||
<div>
|
|
||||||
<label htmlFor="name" className="block text-sm font-medium text-slate-700">
|
|
||||||
Nome Completo
|
|
||||||
</label>
|
|
||||||
<div className="mt-1 relative rounded-md shadow-sm">
|
|
||||||
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
|
|
||||||
<User className="h-5 w-5 text-slate-400" />
|
|
||||||
</div>
|
|
||||||
<input
|
|
||||||
id="name"
|
|
||||||
type="text"
|
|
||||||
required
|
|
||||||
value={formData.name}
|
|
||||||
onChange={(e) => setFormData({...formData, name: e.target.value})}
|
|
||||||
className="block w-full pl-10 pr-3 py-2 border border-slate-300 rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-blue-100 focus:border-blue-500 sm:text-sm"
|
|
||||||
placeholder="Seu nome"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<label htmlFor="organization" className="block text-sm font-medium text-slate-700">
|
|
||||||
Nome da Organização
|
|
||||||
</label>
|
|
||||||
<div className="mt-1 relative rounded-md shadow-sm">
|
|
||||||
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
|
|
||||||
<Building className="h-5 w-5 text-slate-400" />
|
|
||||||
</div>
|
|
||||||
<input
|
|
||||||
id="organization"
|
|
||||||
type="text"
|
|
||||||
required
|
|
||||||
value={formData.organizationName}
|
|
||||||
onChange={(e) => setFormData({...formData, organizationName: e.target.value})}
|
|
||||||
className="block w-full pl-10 pr-3 py-2 border border-slate-300 rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-blue-100 focus:border-blue-500 sm:text-sm"
|
|
||||||
placeholder="Ex: Minha Empresa"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<label htmlFor="email" className="block text-sm font-medium text-slate-700">
|
|
||||||
Endereço de e-mail
|
|
||||||
</label>
|
|
||||||
<div className="mt-1 relative rounded-md shadow-sm">
|
|
||||||
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
|
|
||||||
<Mail className="h-5 w-5 text-slate-400" />
|
|
||||||
</div>
|
|
||||||
<input
|
|
||||||
id="email"
|
|
||||||
type="email"
|
|
||||||
autoComplete="email"
|
|
||||||
required
|
|
||||||
value={formData.email}
|
|
||||||
onChange={(e) => setFormData({...formData, email: e.target.value})}
|
|
||||||
className="block w-full pl-10 pr-3 py-2 border border-slate-300 rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-blue-100 focus:border-blue-500 sm:text-sm"
|
|
||||||
placeholder="voce@empresa.com"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<label htmlFor="password" senior-admin-password className="block text-sm font-medium text-slate-700">
|
|
||||||
Senha
|
|
||||||
</label>
|
|
||||||
<div className="mt-1 relative rounded-md shadow-sm">
|
|
||||||
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
|
|
||||||
<Lock className="h-5 w-5 text-slate-400" />
|
|
||||||
</div>
|
|
||||||
<input
|
|
||||||
id="password"
|
|
||||||
type="password"
|
|
||||||
required
|
|
||||||
value={formData.password}
|
|
||||||
onChange={(e) => setFormData({...formData, password: e.target.value})}
|
|
||||||
className="block w-full pl-10 pr-3 py-2 border border-slate-300 rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-blue-100 focus:border-blue-500 sm:text-sm"
|
|
||||||
placeholder="••••••••"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{error && (
|
{error && (
|
||||||
<div className="text-red-500 text-sm font-medium text-center">
|
<div className="bg-red-50 dark:bg-red-900/20 border border-red-100 dark:border-red-900/30 p-3 rounded-lg text-red-600 dark:text-red-400 text-sm">
|
||||||
{error}
|
{error}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<button
|
<label htmlFor="name" className="block text-sm font-medium text-zinc-700 dark:text-zinc-300">Seu Nome</label>
|
||||||
type="submit"
|
<div className="mt-1 relative">
|
||||||
disabled={isLoading}
|
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
|
||||||
className="w-full flex justify-center items-center gap-2 py-2.5 px-4 border border-transparent rounded-lg shadow-sm text-sm font-semibold text-white bg-slate-900 hover:bg-slate-800 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-slate-900 transition-all"
|
<User className="h-5 w-5 text-zinc-400 dark:text-dark-muted" />
|
||||||
>
|
</div>
|
||||||
{isLoading ? (
|
<input type="text" required value={formData.name} onChange={e => setFormData({...formData, name: e.target.value})} className="block w-full pl-10 pr-3 py-2 border border-zinc-300 dark:border-dark-border rounded-lg bg-white dark:bg-dark-input text-zinc-900 dark:text-zinc-100 placeholder-zinc-400 dark:placeholder-zinc-600 focus:ring-brand-yellow/20 focus:border-brand-yellow sm:text-sm transition-all" placeholder="Nome Completo" />
|
||||||
<>
|
</div>
|
||||||
<Loader2 className="animate-spin h-4 w-4" />
|
</div>
|
||||||
Criando conta...
|
|
||||||
</>
|
<div>
|
||||||
) : (
|
<label htmlFor="organization" className="block text-sm font-medium text-zinc-700 dark:text-zinc-300">Nome da Organização</label>
|
||||||
<>
|
<div className="mt-1 relative">
|
||||||
Registrar <ArrowRight className="h-4 w-4" />
|
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
|
||||||
</>
|
<Building className="h-5 w-5 text-zinc-400 dark:text-dark-muted" />
|
||||||
)}
|
</div>
|
||||||
|
<input type="text" required value={formData.organizationName} onChange={e => setFormData({...formData, organizationName: e.target.value})} className="block w-full pl-10 pr-3 py-2 border border-zinc-300 dark:border-dark-border rounded-lg bg-white dark:bg-dark-input text-zinc-900 dark:text-zinc-100 placeholder-zinc-400 dark:placeholder-zinc-600 focus:ring-brand-yellow/20 focus:border-brand-yellow sm:text-sm transition-all" placeholder="Ex: Minha Empresa" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label htmlFor="email" className="block text-sm font-medium text-zinc-700 dark:text-zinc-300">E-mail Corporativo</label>
|
||||||
|
<div className="mt-1 relative">
|
||||||
|
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
|
||||||
|
<Mail className="h-5 w-5 text-zinc-400 dark:text-dark-muted" />
|
||||||
|
</div>
|
||||||
|
<input type="email" required value={formData.email} onChange={e => setFormData({...formData, email: e.target.value})} className="block w-full pl-10 pr-3 py-2 border border-zinc-300 dark:border-dark-border rounded-lg bg-white dark:bg-dark-input text-zinc-900 dark:text-zinc-100 placeholder-zinc-400 dark:placeholder-zinc-600 focus:ring-brand-yellow/20 focus:border-brand-yellow sm:text-sm transition-all" placeholder="seu@email.com" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label htmlFor="password" senior-admin-password className="block text-sm font-medium text-zinc-700 dark:text-zinc-300">Senha</label>
|
||||||
|
<div className="mt-1 relative">
|
||||||
|
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
|
||||||
|
<Lock className="h-5 w-5 text-zinc-400 dark:text-dark-muted" />
|
||||||
|
</div>
|
||||||
|
<input type="password" required value={formData.password} onChange={e => setFormData({...formData, password: e.target.value})} className="block w-full pl-10 pr-3 py-2 border border-zinc-300 dark:border-dark-border rounded-lg bg-white dark:bg-dark-input text-zinc-900 dark:text-zinc-100 placeholder-zinc-400 dark:placeholder-zinc-600 focus:ring-brand-yellow/20 focus:border-brand-yellow sm:text-sm transition-all" placeholder="••••••••" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<button type="submit" disabled={isLoading} className="w-full flex justify-center items-center gap-2 py-2.5 px-4 border border-transparent rounded-lg shadow-sm text-sm font-bold text-zinc-950 bg-brand-yellow hover:bg-yellow-500 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-brand-yellow transition-all disabled:opacity-70">
|
||||||
|
{isLoading ? <Loader2 className="animate-spin h-5 w-5" /> : <>Criar Conta <ArrowRight size={18} /></>}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
<div className="mt-6">
|
<div className="mt-6 text-center">
|
||||||
<div className="relative">
|
<Link to="/login" className="text-sm font-medium text-brand-yellow hover:text-yellow-600">Já possui uma conta? Entre aqui</Link>
|
||||||
<div className="absolute inset-0 flex items-center">
|
|
||||||
<div className="w-full border-t border-slate-200" />
|
|
||||||
</div>
|
|
||||||
<div className="relative flex justify-center text-sm">
|
|
||||||
<span className="px-2 bg-white text-slate-500 text-xs">
|
|
||||||
Desenvolvido por <a href="https://blyzer.com.br" target="_blank" rel="noopener noreferrer" className="text-blue-600 hover:underline">Blyzer</a>
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -6,22 +6,14 @@ import { resetPassword } from '../services/dataService';
|
|||||||
export const ResetPassword: React.FC = () => {
|
export const ResetPassword: React.FC = () => {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const location = useLocation();
|
const location = useLocation();
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
const query = new URLSearchParams(location.search);
|
||||||
const [password, setPassword] = useState('');
|
const token = query.get('token') || '';
|
||||||
const [confirmPassword, setPasswordConfirm] = useState('');
|
|
||||||
const [error, setError] = useState('');
|
|
||||||
const [isSuccess, setIsSuccess] = useState(false);
|
|
||||||
const [token, setToken] = useState('');
|
|
||||||
|
|
||||||
useEffect(() => {
|
const [password, setPassword] = useState('');
|
||||||
const params = new URLSearchParams(location.search);
|
const [confirmPassword, setConfirmPassword] = useState('');
|
||||||
const t = params.get('token');
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
if (!t) {
|
const [isSuccess, setIsSuccess] = useState(false);
|
||||||
setError('Token de recuperação ausente.');
|
const [error, setError] = useState('');
|
||||||
} else {
|
|
||||||
setToken(t);
|
|
||||||
}
|
|
||||||
}, [location]);
|
|
||||||
|
|
||||||
const handleSubmit = async (e: React.FormEvent) => {
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
@@ -34,137 +26,108 @@ export const ResetPassword: React.FC = () => {
|
|||||||
setError('');
|
setError('');
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await resetPassword(password, token);
|
await resetPassword(token, password);
|
||||||
setIsSuccess(true);
|
setIsSuccess(true);
|
||||||
setTimeout(() => navigate('/login'), 3000);
|
setTimeout(() => navigate('/login'), 3000);
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
setError(err.message || 'Erro ao redefinir senha.');
|
setError(err.message || 'Erro ao redefinir senha. O link pode estar expirado.');
|
||||||
} finally {
|
} finally {
|
||||||
setIsLoading(false);
|
setIsLoading(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-slate-50 flex flex-col justify-center py-12 sm:px-6 lg:px-8">
|
<div className="min-h-screen bg-zinc-50 dark:bg-dark-bg flex flex-col justify-center py-12 sm:px-6 lg:px-8 transition-colors duration-300">
|
||||||
<div className="sm:mx-auto sm:w-full sm:max-w-md">
|
<div className="sm:mx-auto sm:w-full sm:max-w-md">
|
||||||
<div className="flex justify-center items-center gap-2 text-slate-900">
|
<div className="flex justify-center items-center gap-2 text-zinc-900 dark:text-zinc-50">
|
||||||
<div className="bg-slate-900 text-white p-2 rounded-lg">
|
<div className="bg-zinc-900 dark:bg-brand-yellow text-white dark:text-zinc-950 p-2 rounded-lg transition-colors">
|
||||||
<Hexagon size={28} fill="currentColor" />
|
<Hexagon size={32} fill="currentColor" />
|
||||||
</div>
|
</div>
|
||||||
<span className="text-3xl font-bold tracking-tight">Fasto<span className="text-yellow-500">.</span></span>
|
<span className="text-3xl font-bold tracking-tight">Fasto<span className="text-brand-yellow">.</span></span>
|
||||||
</div>
|
</div>
|
||||||
<h2 className="mt-6 text-center text-3xl font-bold tracking-tight text-slate-900">
|
<h2 className="mt-6 text-center text-3xl font-bold tracking-tight text-zinc-900 dark:text-zinc-50">
|
||||||
Nova senha
|
Crie uma nova senha
|
||||||
</h2>
|
</h2>
|
||||||
<p className="mt-2 text-center text-sm text-slate-600">
|
|
||||||
Escolha uma senha forte para sua segurança.
|
|
||||||
</p>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="mt-8 sm:mx-auto sm:w-full sm:max-w-md">
|
<div className="mt-8 sm:mx-auto sm:w-full sm:max-w-md">
|
||||||
<div className="bg-white py-8 px-4 shadow-xl shadow-slate-200/50 rounded-2xl sm:px-10 border border-slate-100">
|
<div className="bg-white dark:bg-dark-card py-8 px-4 shadow-xl rounded-2xl sm:px-10 border border-zinc-100 dark:border-dark-border transition-colors">
|
||||||
|
|
||||||
{isSuccess ? (
|
{isSuccess ? (
|
||||||
<div className="text-center space-y-4 py-4">
|
<div className="text-center py-4 space-y-4 animate-in fade-in zoom-in duration-300">
|
||||||
<div className="flex justify-center">
|
<div className="mx-auto flex items-center justify-center h-12 w-12 rounded-full bg-green-100 dark:bg-green-900/30 text-green-600 dark:text-green-400">
|
||||||
<div className="bg-green-100 p-3 rounded-full text-green-600">
|
<CheckCircle2 size={24} />
|
||||||
<CheckCircle2 size={32} />
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
<h3 className="text-lg font-bold text-slate-900">Sucesso!</h3>
|
<h3 className="text-lg font-bold text-zinc-900 dark:text-zinc-50">Senha alterada!</h3>
|
||||||
<p className="text-sm text-slate-600">
|
<p className="text-sm text-zinc-600 dark:text-dark-muted">
|
||||||
Sua senha foi redefinida. Redirecionando para o login...
|
Sua senha foi redefinida com sucesso. Redirecionando para o login...
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<form className="space-y-5" onSubmit={handleSubmit}>
|
<form className="space-y-6" onSubmit={handleSubmit}>
|
||||||
{!token && (
|
|
||||||
<div className="bg-red-50 text-red-600 p-3 rounded-lg text-sm flex items-center gap-2">
|
|
||||||
<AlertCircle size={18} /> Link inválido ou expirado.
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<label htmlFor="password" senior-admin-password className="block text-sm font-medium text-slate-700">
|
|
||||||
Nova Senha
|
|
||||||
</label>
|
|
||||||
<div className="mt-1 relative rounded-md shadow-sm">
|
|
||||||
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
|
|
||||||
<Lock className="h-5 w-5 text-slate-400" />
|
|
||||||
</div>
|
|
||||||
<input
|
|
||||||
id="password"
|
|
||||||
type="password"
|
|
||||||
required
|
|
||||||
disabled={!token}
|
|
||||||
value={password}
|
|
||||||
onChange={(e) => setPassword(e.target.value)}
|
|
||||||
className="block w-full pl-10 pr-3 py-2 border border-slate-300 rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-blue-100 focus:border-blue-500 sm:text-sm transition-all"
|
|
||||||
placeholder="••••••••"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<label htmlFor="confirmPassword" senior-admin-password className="block text-sm font-medium text-slate-700">
|
|
||||||
Confirmar Nova Senha
|
|
||||||
</label>
|
|
||||||
<div className="mt-1 relative rounded-md shadow-sm">
|
|
||||||
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
|
|
||||||
<Lock className="h-5 w-5 text-slate-400" />
|
|
||||||
</div>
|
|
||||||
<input
|
|
||||||
id="confirmPassword"
|
|
||||||
type="password"
|
|
||||||
required
|
|
||||||
disabled={!token}
|
|
||||||
value={confirmPassword}
|
|
||||||
onChange={(e) => setPasswordConfirm(e.target.value)}
|
|
||||||
className="block w-full pl-10 pr-3 py-2 border border-slate-300 rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-blue-100 focus:border-blue-500 sm:text-sm transition-all"
|
|
||||||
placeholder="••••••••"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{error && (
|
{error && (
|
||||||
<div className="text-red-500 text-sm font-medium text-center">
|
<div className="bg-red-50 dark:bg-red-900/20 border border-red-100 dark:border-red-900/30 p-3 rounded-lg flex items-center gap-2 text-red-600 dark:text-red-400 text-sm">
|
||||||
|
<AlertCircle size={18} />
|
||||||
{error}
|
{error}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label htmlFor="password" senior-admin-password className="block text-sm font-medium text-zinc-700 dark:text-zinc-300">
|
||||||
|
Nova Senha
|
||||||
|
</label>
|
||||||
|
<div className="mt-1 relative">
|
||||||
|
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
|
||||||
|
<Lock className="h-5 w-5 text-zinc-400 dark:text-dark-muted" />
|
||||||
|
</div>
|
||||||
|
<input
|
||||||
|
id="password"
|
||||||
|
type="password"
|
||||||
|
required
|
||||||
|
value={password}
|
||||||
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
|
className="block w-full pl-10 pr-3 py-2 border border-zinc-300 dark:border-dark-border rounded-lg bg-white dark:bg-dark-input text-zinc-900 dark:text-zinc-100 placeholder-zinc-400 dark:placeholder-zinc-600 focus:ring-brand-yellow/20 focus:border-brand-yellow sm:text-sm transition-all"
|
||||||
|
placeholder="••••••••"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label htmlFor="confirmPassword" senior-admin-password className="block text-sm font-medium text-zinc-700 dark:text-zinc-300">
|
||||||
|
Confirmar Nova Senha
|
||||||
|
</label>
|
||||||
|
<div className="mt-1 relative">
|
||||||
|
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
|
||||||
|
<Lock className="h-5 w-5 text-zinc-400 dark:text-dark-muted" />
|
||||||
|
</div>
|
||||||
|
<input
|
||||||
|
id="confirmPassword"
|
||||||
|
type="password"
|
||||||
|
required
|
||||||
|
value={confirmPassword}
|
||||||
|
onChange={(e) => setConfirmPassword(e.target.value)}
|
||||||
|
className="block w-full pl-10 pr-3 py-2 border border-zinc-300 dark:border-dark-border rounded-lg bg-white dark:bg-dark-input text-zinc-900 dark:text-zinc-100 placeholder-zinc-400 dark:placeholder-zinc-600 focus:ring-brand-yellow/20 focus:border-brand-yellow sm:text-sm transition-all"
|
||||||
|
placeholder="••••••••"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<button
|
<button
|
||||||
type="submit"
|
type="submit"
|
||||||
disabled={isLoading || !token}
|
disabled={isLoading}
|
||||||
className="w-full flex justify-center items-center gap-2 py-2.5 px-4 border border-transparent rounded-lg shadow-sm text-sm font-semibold text-white bg-slate-900 hover:bg-slate-800 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-slate-900 transition-all disabled:opacity-50"
|
className="w-full flex justify-center items-center gap-2 py-2.5 px-4 border border-transparent rounded-lg shadow-sm text-sm font-bold text-zinc-950 bg-brand-yellow hover:bg-yellow-500 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-brand-yellow transition-all disabled:opacity-50"
|
||||||
>
|
>
|
||||||
{isLoading ? (
|
{isLoading ? (
|
||||||
<>
|
<Loader2 className="animate-spin h-5 w-5" />
|
||||||
<Loader2 className="animate-spin h-4 w-4" />
|
|
||||||
Alterando...
|
|
||||||
</>
|
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
Redefinir Senha <ArrowRight className="h-4 w-4" />
|
Redefinir Senha <ArrowRight size={18} />
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<div className="mt-6">
|
|
||||||
<div className="relative">
|
|
||||||
<div className="absolute inset-0 flex items-center">
|
|
||||||
<div className="w-full border-t border-slate-200" />
|
|
||||||
</div>
|
|
||||||
<div className="relative flex justify-center text-sm">
|
|
||||||
<span className="px-2 bg-white text-slate-500 text-xs">
|
|
||||||
Desenvolvido por <a href="https://blyzer.com.br" target="_blank" rel="noopener noreferrer" className="text-blue-600 hover:underline">Blyzer</a>
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -20,11 +20,9 @@ export const SuperAdmin: React.FC = () => {
|
|||||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||||
const [editingTenant, setEditingTenant] = useState<Tenant | null>(null);
|
const [editingTenant, setEditingTenant] = useState<Tenant | null>(null);
|
||||||
|
|
||||||
// Sorting State
|
|
||||||
const [sortKey, setSortKey] = useState<keyof Tenant>('created_at');
|
const [sortKey, setSortKey] = useState<keyof Tenant>('created_at');
|
||||||
const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('desc');
|
const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('desc');
|
||||||
|
|
||||||
// Load Tenants from API
|
|
||||||
const loadTenants = async () => {
|
const loadTenants = async () => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
const data = await getTenants();
|
const data = await getTenants();
|
||||||
@@ -36,16 +34,12 @@ export const SuperAdmin: React.FC = () => {
|
|||||||
loadTenants();
|
loadTenants();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
// --- Metrics ---
|
|
||||||
const totalTenants = tenants.length;
|
const totalTenants = tenants.length;
|
||||||
const totalUsersGlobal = tenants.reduce((acc, t) => acc + (t.user_count || 0), 0);
|
const totalUsersGlobal = tenants.reduce((acc, t) => acc + (t.user_count || 0), 0);
|
||||||
const totalAttendancesGlobal = tenants.reduce((acc, t) => acc + (t.attendance_count || 0), 0);
|
const totalAttendancesGlobal = tenants.reduce((acc, t) => acc + (t.attendance_count || 0), 0);
|
||||||
|
|
||||||
// --- Data Filtering & Sorting ---
|
|
||||||
const filteredTenants = useMemo(() => {
|
const filteredTenants = useMemo(() => {
|
||||||
let data = tenants;
|
let data = tenants;
|
||||||
|
|
||||||
// Search
|
|
||||||
if (searchQuery) {
|
if (searchQuery) {
|
||||||
const q = searchQuery.toLowerCase();
|
const q = searchQuery.toLowerCase();
|
||||||
data = data.filter(t =>
|
data = data.filter(t =>
|
||||||
@@ -54,27 +48,20 @@ export const SuperAdmin: React.FC = () => {
|
|||||||
t.slug?.toLowerCase().includes(q)
|
t.slug?.toLowerCase().includes(q)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Tenant Filter (Select)
|
|
||||||
if (selectedTenantId !== 'all') {
|
if (selectedTenantId !== 'all') {
|
||||||
data = data.filter(t => t.id === selectedTenantId);
|
data = data.filter(t => t.id === selectedTenantId);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Sort
|
|
||||||
return [...data].sort((a, b) => {
|
return [...data].sort((a, b) => {
|
||||||
const aVal = a[sortKey];
|
const aVal = a[sortKey];
|
||||||
const bVal = b[sortKey];
|
const bVal = b[sortKey];
|
||||||
|
|
||||||
if (aVal === undefined) return 1;
|
if (aVal === undefined) return 1;
|
||||||
if (bVal === undefined) return -1;
|
if (bVal === undefined) return -1;
|
||||||
|
|
||||||
if (aVal < bVal) return sortDirection === 'asc' ? -1 : 1;
|
if (aVal < bVal) return sortDirection === 'asc' ? -1 : 1;
|
||||||
if (aVal > bVal) return sortDirection === 'asc' ? 1 : -1;
|
if (aVal > bVal) return sortDirection === 'asc' ? 1 : -1;
|
||||||
return 0;
|
return 0;
|
||||||
});
|
});
|
||||||
}, [tenants, searchQuery, selectedTenantId, sortKey, sortDirection]);
|
}, [tenants, searchQuery, selectedTenantId, sortKey, sortDirection]);
|
||||||
|
|
||||||
// --- Handlers ---
|
|
||||||
const handleSort = (key: keyof Tenant) => {
|
const handleSort = (key: keyof Tenant) => {
|
||||||
if (sortKey === key) {
|
if (sortKey === key) {
|
||||||
setSortDirection(prev => prev === 'asc' ? 'desc' : 'asc');
|
setSortDirection(prev => prev === 'asc' ? 'desc' : 'asc');
|
||||||
@@ -98,286 +85,162 @@ export const SuperAdmin: React.FC = () => {
|
|||||||
const handleSaveTenant = async (e: React.FormEvent) => {
|
const handleSaveTenant = async (e: React.FormEvent) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
const form = e.target as HTMLFormElement;
|
const form = e.target as HTMLFormElement;
|
||||||
|
|
||||||
const name = (form.elements.namedItem('name') as HTMLInputElement).value;
|
const name = (form.elements.namedItem('name') as HTMLInputElement).value;
|
||||||
const slug = (form.elements.namedItem('slug') as HTMLInputElement).value;
|
const slug = (form.elements.namedItem('slug') as HTMLInputElement).value;
|
||||||
const admin_email = (form.elements.namedItem('admin_email') as HTMLInputElement).value;
|
const admin_email = (form.elements.namedItem('admin_email') as HTMLInputElement).value;
|
||||||
const status = (form.elements.namedItem('status') as HTMLSelectElement).value;
|
const status = (form.elements.namedItem('status') as HTMLSelectElement).value;
|
||||||
|
|
||||||
const success = await createTenant({ name, slug, admin_email, status });
|
const success = await createTenant({ name, slug, admin_email, status });
|
||||||
|
|
||||||
if (success) {
|
if (success) {
|
||||||
setIsModalOpen(false);
|
setIsModalOpen(false);
|
||||||
setEditingTenant(null);
|
setEditingTenant(null);
|
||||||
loadTenants(); // Reload list
|
loadTenants();
|
||||||
alert('Organização salva com sucesso!');
|
alert('Organização salva com sucesso!');
|
||||||
} else {
|
} else {
|
||||||
alert('Erro ao salvar organização. Verifique o console.');
|
alert('Erro ao salvar organização.');
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- Helper Components ---
|
|
||||||
const SortIcon = ({ column }: { column: keyof Tenant }) => {
|
const SortIcon = ({ column }: { column: keyof Tenant }) => {
|
||||||
if (sortKey !== column) return <ChevronsUpDown size={14} className="text-slate-300" />;
|
if (sortKey !== column) return <ChevronsUpDown size={14} className="text-zinc-300 dark:text-dark-muted" />;
|
||||||
return sortDirection === 'asc' ? <ChevronUp size={14} className="text-blue-500" /> : <ChevronDown size={14} className="text-blue-500" />;
|
return sortDirection === 'asc' ? <ChevronUp size={14} className="text-brand-yellow" /> : <ChevronDown size={14} className="text-brand-yellow" />;
|
||||||
};
|
};
|
||||||
|
|
||||||
const StatusBadge = ({ status }: { status?: string }) => {
|
const StatusBadge = ({ status }: { status?: string }) => {
|
||||||
const styles = {
|
const styles = {
|
||||||
active: 'bg-green-100 text-green-700 border-green-200',
|
active: 'bg-green-100 text-green-700 border-green-200 dark:bg-green-900/30 dark:text-green-400 dark:border-green-800',
|
||||||
inactive: 'bg-slate-100 text-slate-700 border-slate-200',
|
inactive: 'bg-zinc-100 text-zinc-700 border-zinc-200 dark:bg-dark-input dark:text-dark-muted dark:border-dark-border',
|
||||||
trial: 'bg-purple-100 text-purple-700 border-purple-200',
|
trial: 'bg-purple-100 text-purple-700 border-purple-200 dark:bg-purple-900/30 dark:text-purple-400 dark:border-purple-800',
|
||||||
};
|
};
|
||||||
const style = styles[status as keyof typeof styles] || styles.inactive;
|
const style = styles[status as keyof typeof styles] || styles.inactive;
|
||||||
|
let label = status === 'active' ? 'Ativo' : status === 'inactive' ? 'Inativo' : status === 'trial' ? 'Teste' : 'Desconhecido';
|
||||||
let label = status || 'Desconhecido';
|
return <span className={`px-2.5 py-0.5 rounded-full text-xs font-semibold border capitalize ${style}`}>{label}</span>;
|
||||||
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 (
|
return (
|
||||||
<div className="space-y-8 max-w-7xl mx-auto pb-8">
|
<div className="space-y-8 max-w-7xl mx-auto pb-8 transition-colors duration-300">
|
||||||
{/* Header */}
|
|
||||||
<div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
|
<div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-2xl font-bold text-slate-900 tracking-tight">Painel Super Admin</h1>
|
<h1 className="text-2xl font-bold text-zinc-900 dark:text-zinc-50 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>
|
<p className="text-zinc-500 dark:text-dark-muted text-sm">Gerencie organizações e visualize estatísticas globais.</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>
|
||||||
|
<button onClick={() => { setEditingTenant(null); setIsModalOpen(true); }} className="bg-zinc-900 dark:bg-brand-yellow text-white dark:text-zinc-950 px-4 py-2 rounded-lg text-sm font-bold hover:opacity-90 transition-all shadow-sm">
|
||||||
|
<Plus size={16} /> Adicionar Organização
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
{/* KPI Cards */}
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
|
||||||
|
<KPICard title="Total de Organizações" value={totalTenants} icon={Building2} colorClass="text-blue-600" trend="up" trendValue="+1 este mês" />
|
||||||
|
<KPICard title="Total de Usuários" value={totalUsersGlobal} icon={Users} colorClass="text-purple-600" subValue="Em todas as organizações" />
|
||||||
|
<KPICard title="Total de Atendimentos" value={totalAttendancesGlobal.toLocaleString()} icon={MessageSquare} colorClass="text-green-600" trend="up" trendValue="+12%" />
|
||||||
|
</div>
|
||||||
|
|
||||||
{/* KPI Cards */}
|
<div className="bg-white dark:bg-dark-card p-4 rounded-xl border border-zinc-200 dark:border-dark-border shadow-sm flex flex-col md:flex-row gap-4 justify-between items-center transition-colors">
|
||||||
<div className="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">
|
<div className="flex items-center gap-3 w-full md:w-auto">
|
||||||
<DateRangePicker dateRange={dateRange} onChange={setDateRange} />
|
<DateRangePicker dateRange={dateRange} onChange={setDateRange} />
|
||||||
|
<div className="h-8 w-px bg-zinc-200 dark:bg-dark-border hidden md:block" />
|
||||||
<div className="h-8 w-px bg-slate-200 hidden md:block" />
|
<select className="bg-zinc-50 dark:bg-dark-bg border border-zinc-200 dark:border-dark-border px-3 py-2 rounded-lg text-sm text-zinc-700 dark:text-zinc-200 outline-none focus:ring-2 focus:ring-brand-yellow/20 cursor-pointer hover:border-zinc-300 dark:hover:border-dark-border w-full md:w-48 transition-all" value={selectedTenantId} onChange={(e) => setSelectedTenantId(e.target.value)}>
|
||||||
|
|
||||||
<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>
|
<option value="all">Todas Organizações</option>
|
||||||
{tenants.map(t => <option key={t.id} value={t.id}>{t.name}</option>)}
|
{tenants.map(t => <option key={t.id} value={t.id}>{t.name}</option>)}
|
||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="relative w-full md:w-64">
|
<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" />
|
<Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-zinc-400 dark:text-dark-muted" />
|
||||||
<input
|
<input type="text" placeholder="Buscar organizações..." value={searchQuery} onChange={(e) => setSearchQuery(e.target.value)} className="w-full pl-9 pr-4 py-2 bg-zinc-50 dark:bg-dark-bg border border-zinc-200 dark:border-dark-border rounded-lg text-sm text-zinc-900 dark:text-zinc-100 outline-none focus:ring-2 focus:ring-brand-yellow/20 transition-all" />
|
||||||
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>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Tenants Table */}
|
<div className="bg-white dark:bg-dark-card border border-zinc-200 dark:border-dark-border rounded-xl shadow-sm overflow-hidden transition-colors">
|
||||||
<div className="bg-white border border-slate-200 rounded-xl shadow-sm overflow-hidden">
|
|
||||||
<div className="overflow-x-auto">
|
<div className="overflow-x-auto">
|
||||||
<table className="w-full text-left border-collapse">
|
<table className="w-full text-left border-collapse">
|
||||||
<thead>
|
<thead>
|
||||||
<tr className="bg-slate-50/50 text-slate-500 text-xs uppercase tracking-wider border-b border-slate-100">
|
<tr className="bg-zinc-50/50 dark:bg-dark-bg/50 text-zinc-500 dark:text-dark-muted text-xs uppercase tracking-wider border-b border-zinc-100 dark:border-dark-border">
|
||||||
<th className="px-6 py-4 font-semibold cursor-pointer hover:bg-slate-50 select-none" onClick={() => handleSort('name')}>
|
<th className="px-6 py-4 font-semibold cursor-pointer hover:bg-zinc-50 dark:hover:bg-dark-border select-none" onClick={() => handleSort('name')}>
|
||||||
<div className="flex items-center gap-2">Organização <SortIcon column="name" /></div>
|
<div className="flex items-center gap-2">Organização <SortIcon column="name" /></div>
|
||||||
</th>
|
</th>
|
||||||
<th className="px-6 py-4 font-semibold">Slug</th>
|
<th className="px-6 py-4 font-semibold">Slug</th>
|
||||||
<th className="px-6 py-4 font-semibold cursor-pointer hover:bg-slate-50 select-none" onClick={() => handleSort('status')}>
|
<th className="px-6 py-4 font-semibold cursor-pointer hover:bg-zinc-50 dark:hover:bg-dark-border select-none" onClick={() => handleSort('status')}>
|
||||||
<div className="flex items-center gap-2">Status <SortIcon column="status" /></div>
|
<div className="flex items-center gap-2">Status <SortIcon column="status" /></div>
|
||||||
</th>
|
</th>
|
||||||
<th className="px-6 py-4 font-semibold text-center cursor-pointer hover:bg-slate-50 select-none" onClick={() => handleSort('user_count')}>
|
<th className="px-6 py-4 font-semibold text-center cursor-pointer hover:bg-zinc-50 dark:hover:bg-dark-border select-none" onClick={() => handleSort('user_count')}>
|
||||||
<div className="flex items-center justify-center gap-2">Usuários <SortIcon column="user_count" /></div>
|
<div className="flex items-center justify-center gap-2">Usuários <SortIcon column="user_count" /></div>
|
||||||
</th>
|
</th>
|
||||||
<th className="px-6 py-4 font-semibold text-center cursor-pointer hover:bg-slate-50 select-none" onClick={() => handleSort('attendance_count')}>
|
<th className="px-6 py-4 font-semibold text-center cursor-pointer hover:bg-zinc-50 dark:hover:bg-dark-border select-none" onClick={() => handleSort('attendance_count')}>
|
||||||
<div className="flex items-center justify-center gap-2">Atendimentos <SortIcon column="attendance_count" /></div>
|
<div className="flex items-center justify-center gap-2">Atendimentos <SortIcon column="attendance_count" /></div>
|
||||||
</th>
|
</th>
|
||||||
<th className="px-6 py-4 font-semibold text-right">Ações</th>
|
<th className="px-6 py-4 font-semibold text-right">Ações</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody className="divide-y divide-slate-100 text-sm">
|
<tbody className="divide-y divide-zinc-100 dark:divide-dark-border text-sm">
|
||||||
{filteredTenants.map((tenant) => (
|
{filteredTenants.map((tenant) => (
|
||||||
<tr key={tenant.id} className="hover:bg-slate-50/50 transition-colors group">
|
<tr key={tenant.id} className="hover:bg-zinc-50/50 dark:hover:bg-zinc-800/50 transition-colors group">
|
||||||
<td className="px-6 py-4">
|
<td className="px-6 py-4">
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
<div className="w-10 h-10 rounded-lg bg-slate-100 flex items-center justify-center text-slate-400 font-bold border border-slate-200">
|
<div className="w-10 h-10 rounded-lg bg-zinc-100 dark:bg-dark-bg flex items-center justify-center text-zinc-400 dark:text-dark-muted font-bold border border-zinc-200 dark:border-dark-border">
|
||||||
{tenant.logo_url ? <img src={tenant.logo_url} className="w-full h-full object-cover rounded-lg" alt="" /> : <Building2 size={20} />}
|
{tenant.logo_url ? <img src={tenant.logo_url} className="w-full h-full object-cover rounded-lg" alt="" /> : <Building2 size={20} />}
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<div className="font-semibold text-slate-900">{tenant.name}</div>
|
<div className="font-semibold text-zinc-900 dark:text-zinc-100">{tenant.name}</div>
|
||||||
<div className="text-xs text-slate-500">{tenant.admin_email}</div>
|
<div className="text-xs text-zinc-500 dark:text-dark-muted">{tenant.admin_email}</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</td>
|
</td>
|
||||||
<td className="px-6 py-4 text-slate-600 font-mono text-xs">
|
<td className="px-6 py-4 text-zinc-600 dark:text-dark-muted font-mono text-xs">{tenant.slug}</td>
|
||||||
{tenant.slug}
|
<td className="px-6 py-4"><StatusBadge status={tenant.status} /></td>
|
||||||
</td>
|
<td className="px-6 py-4 text-center font-medium text-zinc-700 dark:text-zinc-300">{tenant.user_count}</td>
|
||||||
<td className="px-6 py-4">
|
<td className="px-6 py-4 text-center font-medium text-zinc-700 dark:text-zinc-300">{tenant.attendance_count?.toLocaleString()}</td>
|
||||||
<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">
|
<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">
|
<div className="flex items-center justify-end gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
|
||||||
<button
|
<button onClick={() => handleEdit(tenant)} className="p-2 text-zinc-400 hover:text-brand-yellow hover:bg-zinc-50 dark:hover:bg-dark-bg rounded-lg transition-colors"><Edit size={16} /></button>
|
||||||
onClick={() => handleEdit(tenant)}
|
<button onClick={() => handleDelete(tenant.id)} className="p-2 text-zinc-400 hover:text-red-600 hover:bg-red-50 dark:hover:bg-red-900/30 rounded-lg transition-colors"><Trash2 size={16} /></button>
|
||||||
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>
|
</div>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</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>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
|
<div className="px-6 py-4 border-t border-zinc-100 dark:border-dark-border bg-zinc-50/30 dark:bg-dark-bg/30 text-xs text-zinc-500 dark:text-dark-muted flex justify-between items-center transition-colors">
|
||||||
{/* 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>
|
<span>Mostrando {filteredTenants.length} de {tenants.length} organizações</span>
|
||||||
<div className="flex gap-2">
|
<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 dark:border-dark-border rounded bg-white dark:bg-dark-card disabled:opacity-50">Ant</button>
|
||||||
<button disabled className="px-3 py-1 border rounded bg-white disabled:opacity-50">Próx</button>
|
<button disabled className="px-3 py-1 border dark:border-dark-border rounded bg-white dark:bg-dark-card disabled:opacity-50">Próx</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Add/Edit Modal */}
|
|
||||||
{isModalOpen && (
|
{isModalOpen && (
|
||||||
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/50 backdrop-blur-sm">
|
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-zinc-950/80 backdrop-blur-sm">
|
||||||
<div className="bg-white rounded-xl shadow-xl w-full max-w-lg overflow-hidden animate-in fade-in zoom-in duration-200">
|
<div className="bg-white dark:bg-dark-card rounded-xl shadow-xl w-full max-w-lg overflow-hidden animate-in fade-in zoom-in duration-200 border border-transparent dark:border-dark-border transition-colors">
|
||||||
<div className="px-6 py-4 border-b border-slate-100 flex justify-between items-center bg-slate-50/50">
|
<div className="px-6 py-4 border-b border-zinc-100 dark:border-dark-border flex justify-between items-center bg-zinc-50/50 dark:bg-dark-bg/50">
|
||||||
<h3 className="font-bold text-slate-900">{editingTenant ? 'Editar Organização' : 'Adicionar Nova Organização'}</h3>
|
<h3 className="font-bold text-zinc-900 dark:text-zinc-50">{editingTenant ? 'Editar Organização' : 'Adicionar Nova Organização'}</h3>
|
||||||
<button onClick={() => setIsModalOpen(false)} className="text-slate-400 hover:text-slate-600">
|
<button onClick={() => setIsModalOpen(false)} className="text-zinc-400 hover:text-zinc-600 dark:hover:text-zinc-300"><X size={20} /></button>
|
||||||
<X size={20} />
|
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<form onSubmit={handleSaveTenant} className="p-6 space-y-4">
|
<form onSubmit={handleSaveTenant} className="p-6 space-y-4">
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<label className="text-sm font-medium text-slate-700">Nome da Organização</label>
|
<label className="text-sm font-medium text-zinc-700 dark:text-zinc-300">Nome da Organização</label>
|
||||||
<input
|
<input type="text" name="name" defaultValue={editingTenant?.name} className="w-full px-3 py-2 bg-zinc-50 dark:bg-dark-bg border border-zinc-200 dark:border-dark-border rounded-lg text-sm text-zinc-900 dark:text-zinc-100 focus:ring-2 focus:ring-brand-yellow/20 outline-none transition-all" required />
|
||||||
type="text"
|
|
||||||
name="name"
|
|
||||||
defaultValue={editingTenant?.name}
|
|
||||||
className="w-full px-3 py-2 bg-slate-50 border border-slate-200 rounded-lg text-sm focus:ring-2 focus:ring-blue-100 outline-none"
|
|
||||||
placeholder="ex. Acme Corp"
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="grid grid-cols-2 gap-4">
|
<div className="grid grid-cols-2 gap-4">
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<label className="text-sm font-medium text-slate-700">Slug</label>
|
<label className="text-sm font-medium text-zinc-700 dark:text-zinc-300">Slug</label>
|
||||||
<input
|
<input type="text" name="slug" defaultValue={editingTenant?.slug} className="w-full px-3 py-2 bg-zinc-50 dark:bg-dark-bg border border-zinc-200 dark:border-dark-border rounded-lg text-sm text-zinc-900 dark:text-zinc-100 focus:ring-2 focus:ring-brand-yellow/20 outline-none transition-all" />
|
||||||
type="text"
|
|
||||||
name="slug"
|
|
||||||
defaultValue={editingTenant?.slug}
|
|
||||||
className="w-full px-3 py-2 bg-slate-50 border border-slate-200 rounded-lg text-sm focus:ring-2 focus:ring-blue-100 outline-none"
|
|
||||||
placeholder="ex. acme-corp"
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<label className="text-sm font-medium text-slate-700">Status</label>
|
<label className="text-sm font-medium text-zinc-700 dark:text-zinc-300">Status</label>
|
||||||
<select
|
<select name="status" defaultValue={editingTenant?.status || 'active'} className="w-full px-3 py-2 bg-zinc-50 dark:bg-dark-bg border border-zinc-200 dark:border-dark-border rounded-lg text-sm text-zinc-900 dark:text-zinc-100 outline-none transition-all">
|
||||||
name="status"
|
|
||||||
defaultValue={editingTenant?.status || 'active'}
|
|
||||||
className="w-full px-3 py-2 bg-slate-50 border border-slate-200 rounded-lg text-sm focus:ring-2 focus:ring-blue-100 outline-none"
|
|
||||||
>
|
|
||||||
<option value="active">Ativo</option>
|
<option value="active">Ativo</option>
|
||||||
<option value="inactive">Inativo</option>
|
<option value="inactive">Inativo</option>
|
||||||
<option value="trial">Teste</option>
|
<option value="trial">Teste</option>
|
||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<label className="text-sm font-medium text-slate-700">E-mail do Admin</label>
|
<label className="text-sm font-medium text-zinc-700 dark:text-zinc-300">E-mail do Admin</label>
|
||||||
<input
|
<input type="email" name="admin_email" defaultValue={editingTenant?.admin_email} className="w-full px-3 py-2 bg-zinc-50 dark:bg-dark-bg border border-zinc-200 dark:border-dark-border rounded-lg text-sm text-zinc-900 dark:text-zinc-100 focus:ring-2 focus:ring-brand-yellow/20 outline-none transition-all" required />
|
||||||
type="email"
|
|
||||||
name="admin_email"
|
|
||||||
defaultValue={editingTenant?.admin_email}
|
|
||||||
className="w-full px-3 py-2 bg-slate-50 border border-slate-200 rounded-lg text-sm focus:ring-2 focus:ring-blue-100 outline-none"
|
|
||||||
placeholder="admin@empresa.com"
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
|
<div className="pt-4 flex justify-end gap-3 border-t dark:border-dark-border mt-6">
|
||||||
<div className="pt-4 flex justify-end gap-3">
|
<button type="button" onClick={() => setIsModalOpen(false)} className="px-4 py-2 text-zinc-600 dark:text-zinc-400 hover:bg-zinc-100 dark:hover:bg-dark-border rounded-lg text-sm font-medium transition-colors">Cancelar</button>
|
||||||
<button
|
<button type="submit" className="px-4 py-2 bg-zinc-900 dark:bg-brand-yellow text-white dark:text-zinc-950 rounded-lg text-sm font-bold hover:opacity-90 transition-all shadow-sm">{editingTenant ? 'Salvar Alterações' : 'Criar Organização'}</button>
|
||||||
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>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import React, { useState, useEffect } from 'react';
|
import React, { useState, useEffect } from 'react';
|
||||||
import { Users, Plus, Mail, Search, X, Edit, Trash2, Loader2, CheckCircle2, AlertCircle, AlertTriangle } from 'lucide-react';
|
import { Users, Plus, Mail, Search, X, Edit, Trash2, Loader2, AlertTriangle } from 'lucide-react';
|
||||||
import { getUsers, getTeams, createMember, deleteUser, updateUser, getUserById } from '../services/dataService';
|
import { getUsers, getTeams, createMember, deleteUser, updateUser, getUserById } from '../services/dataService';
|
||||||
import { User } from '../types';
|
import { User } from '../types';
|
||||||
|
|
||||||
@@ -15,7 +15,13 @@ export const TeamManagement: React.FC = () => {
|
|||||||
const [userToDelete, setUserToDelete] = useState<User | null>(null);
|
const [userToDelete, setUserToDelete] = useState<User | null>(null);
|
||||||
const [deleteConfirmName, setDeleteConfirmName] = useState('');
|
const [deleteConfirmName, setDeleteConfirmName] = useState('');
|
||||||
const [editingUser, setEditingUser] = useState<User | null>(null);
|
const [editingUser, setEditingUser] = useState<User | null>(null);
|
||||||
const [formData, setFormData] = useState({ name: '', email: '', role: 'agent' as any, team_id: '', status: 'active' as any });
|
const [formData, setFormData] = useState({
|
||||||
|
name: '',
|
||||||
|
email: '',
|
||||||
|
role: 'agent' as any,
|
||||||
|
team_id: '',
|
||||||
|
status: 'active' as any
|
||||||
|
});
|
||||||
|
|
||||||
const loadData = async () => {
|
const loadData = async () => {
|
||||||
const tid = localStorage.getItem('ctms_tenant_id');
|
const tid = localStorage.getItem('ctms_tenant_id');
|
||||||
@@ -37,9 +43,11 @@ export const TeamManagement: React.FC = () => {
|
|||||||
setIsSaving(true);
|
setIsSaving(true);
|
||||||
try {
|
try {
|
||||||
const tid = localStorage.getItem('ctms_tenant_id') || '';
|
const tid = localStorage.getItem('ctms_tenant_id') || '';
|
||||||
const success = editingUser ? await updateUser(editingUser.id, formData) : await createMember({ ...formData, tenant_id: tid });
|
const success = editingUser
|
||||||
|
? await updateUser(editingUser.id, formData)
|
||||||
|
: await createMember({ ...formData, tenant_id: tid });
|
||||||
if (success) { setIsModalOpen(false); loadData(); }
|
if (success) { setIsModalOpen(false); loadData(); }
|
||||||
} catch (err) { console.error(err); } finally { setIsSaving(false); }
|
} catch (err) { alert('Erro ao salvar'); } finally { setIsSaving(false); }
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleConfirmDelete = async () => {
|
const handleConfirmDelete = async () => {
|
||||||
@@ -47,89 +55,143 @@ export const TeamManagement: React.FC = () => {
|
|||||||
setIsSaving(true);
|
setIsSaving(true);
|
||||||
try {
|
try {
|
||||||
if (await deleteUser(userToDelete.id)) { setIsDeleteModalOpen(false); loadData(); }
|
if (await deleteUser(userToDelete.id)) { setIsDeleteModalOpen(false); loadData(); }
|
||||||
} catch (err) { console.error(err); } finally { setIsSaving(false); }
|
} catch (err) { alert('Erro ao excluir'); } finally { setIsSaving(false); }
|
||||||
};
|
};
|
||||||
|
|
||||||
if (loading && users.length === 0) return <div className="flex h-screen items-center justify-center text-slate-400">Carregando...</div>;
|
if (loading && users.length === 0) return <div className="flex h-screen items-center justify-center text-zinc-400 dark:text-dark-muted transition-colors">Carregando...</div>;
|
||||||
|
|
||||||
const canManage = currentUser?.role === 'admin' || currentUser?.role === 'super_admin';
|
const canManage = currentUser?.role === 'admin' || currentUser?.role === 'super_admin';
|
||||||
const filtered = users.filter(u => u.name.toLowerCase().includes(searchTerm.toLowerCase()) || u.email.toLowerCase().includes(searchTerm.toLowerCase()));
|
const filtered = users.filter(u => u.name.toLowerCase().includes(searchTerm.toLowerCase()) || u.email.toLowerCase().includes(searchTerm.toLowerCase()));
|
||||||
|
|
||||||
|
const getRoleLabel = (role: string) => {
|
||||||
|
if (role === 'admin') return 'Admin';
|
||||||
|
if (role === 'manager') return 'Gerente';
|
||||||
|
return 'Agente';
|
||||||
|
};
|
||||||
|
|
||||||
const getRoleBadge = (role: string) => {
|
const getRoleBadge = (role: string) => {
|
||||||
switch (role) {
|
switch (role) {
|
||||||
case 'admin': return 'bg-purple-100 text-purple-700 border-purple-200';
|
case 'admin': return 'bg-purple-100 text-purple-700 border-purple-200 dark:bg-purple-900/30 dark:text-purple-400 dark:border-purple-800';
|
||||||
case 'manager': return 'bg-blue-100 text-blue-700 border-blue-200';
|
case 'manager': return 'bg-blue-100 text-blue-700 border-blue-200 dark:bg-blue-900/30 dark:text-blue-400 dark:border-blue-800';
|
||||||
default: return 'bg-slate-100 text-slate-700 border-slate-200';
|
default: return 'bg-zinc-100 text-zinc-700 border-zinc-200 dark:bg-dark-input dark:text-dark-muted dark:border-dark-border';
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-8 max-w-7xl mx-auto pb-12">
|
<div className="space-y-8 max-w-7xl mx-auto pb-12 transition-colors duration-300">
|
||||||
<div className="flex justify-between items-center">
|
<div className="flex justify-between items-center">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-2xl font-bold text-slate-900 tracking-tight">Membros</h1>
|
<h1 className="text-2xl font-bold text-zinc-900 dark:text-dark-text tracking-tight">Membros</h1>
|
||||||
<p className="text-slate-500 text-sm">Gerencie os acessos da sua organização.</p>
|
<p className="text-zinc-500 dark:text-dark-muted text-sm">Visualize e gerencie as funções dos membros da sua organização.</p>
|
||||||
</div>
|
</div>
|
||||||
{canManage && (
|
{canManage && (
|
||||||
<button onClick={() => { setEditingUser(null); setFormData({name:'', email:'', role:'agent', team_id:'', status:'active'}); setIsModalOpen(true); }} className="bg-slate-900 text-white px-4 py-2 rounded-lg flex items-center gap-2 text-sm font-bold shadow-sm">
|
<button onClick={() => { setEditingUser(null); setFormData({name:'', email:'', role:'agent', team_id:'', status:'active'}); setIsModalOpen(true); }} className="bg-zinc-900 dark:bg-brand-yellow text-white dark:text-zinc-950 px-4 py-2 rounded-lg flex items-center gap-2 text-sm font-bold shadow-sm hover:opacity-90 transition-all">
|
||||||
<Plus size={16} /> Adicionar Membro
|
<Plus size={16} /> Adicionar Membro
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="bg-white border border-slate-200 rounded-xl shadow-sm overflow-hidden">
|
<div className="bg-white dark:bg-dark-card border border-zinc-200 dark:border-dark-border rounded-xl shadow-sm overflow-hidden">
|
||||||
<div className="p-4 border-b border-slate-100 bg-slate-50/30">
|
<div className="p-4 border-b border-zinc-100 dark:border-dark-border bg-zinc-50 dark:bg-dark-bg/50">
|
||||||
<input type="text" placeholder="Buscar membros..." value={searchTerm} onChange={e => setSearchTerm(e.target.value)} className="w-full max-w-md border border-slate-200 p-2 rounded-lg text-sm outline-none" />
|
<div className="relative max-w-md">
|
||||||
|
<Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-zinc-400 dark:text-dark-muted" />
|
||||||
|
<input type="text" placeholder="Buscar membros..." value={searchTerm} onChange={e => setSearchTerm(e.target.value)} className="w-full pl-9 pr-4 py-2 bg-white dark:bg-dark-bg border border-zinc-200 dark:border-dark-border rounded-lg text-sm text-zinc-900 dark:text-dark-text outline-none focus:ring-2 focus:ring-brand-yellow/20 transition-all" />
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<table className="w-full text-left">
|
<div className="overflow-x-auto">
|
||||||
<thead className="bg-slate-50/50 text-slate-500 text-xs uppercase font-bold border-b">
|
<table className="w-full text-left">
|
||||||
<tr>
|
<thead>
|
||||||
<th className="px-6 py-4">Usuário</th>
|
<tr className="bg-zinc-50 dark:bg-dark-bg/50 text-zinc-500 dark:text-dark-muted text-xs uppercase font-bold border-b dark:border-dark-border">
|
||||||
<th className="px-6 py-4">Função</th>
|
<th className="px-6 py-4">Usuário</th>
|
||||||
<th className="px-6 py-4">Time</th>
|
<th className="px-6 py-4">Função</th>
|
||||||
<th className="px-6 py-4">Status</th>
|
<th className="px-6 py-4">Time</th>
|
||||||
{canManage && <th className="px-6 py-4 text-right">Ações</th>}
|
<th className="px-6 py-4">Status</th>
|
||||||
</tr>
|
{canManage && <th className="px-6 py-4 text-right">Ações</th>}
|
||||||
</thead>
|
|
||||||
<tbody className="divide-y text-sm">
|
|
||||||
{filtered.map(user => (
|
|
||||||
<tr key={user.id} className="hover:bg-slate-50 group">
|
|
||||||
<td className="px-6 py-4">
|
|
||||||
<div className="flex items-center gap-3">
|
|
||||||
<img src={`https://ui-avatars.com/api/?name=${encodeURIComponent(user.name)}&background=random`} alt="" className="w-8 h-8 rounded-full" />
|
|
||||||
<div><div className="font-bold text-slate-900">{user.name}</div><div className="text-xs text-slate-500">{user.email}</div></div>
|
|
||||||
</div>
|
|
||||||
</td>
|
|
||||||
<td className="px-6 py-4"><span className={`px-2.5 py-0.5 rounded-full text-xs font-bold border capitalize ${getRoleBadge(user.role)}`}>{user.role}</span></td>
|
|
||||||
<td className="px-6 py-4 text-slate-600">{teams.find(t => t.id === user.team_id)?.name || '-'}</td>
|
|
||||||
<td className="px-6 py-4"><span className={`px-2 py-0.5 rounded-full text-xs font-bold ${user.status === 'active' ? 'bg-green-100 text-green-700' : 'bg-slate-100 text-slate-500'}`}>{user.status}</span></td>
|
|
||||||
{canManage && (
|
|
||||||
<td className="px-6 py-4 text-right flex justify-end gap-2 opacity-0 group-hover:opacity-100">
|
|
||||||
<button onClick={() => { setEditingUser(user); setFormData({name:user.name, email:user.email, role:user.role as any, team_id:user.team_id||'', status:user.status as any}); setIsModalOpen(true); }} className="p-1 hover:text-blue-600"><Edit size={16} /></button>
|
|
||||||
<button onClick={() => { setUserToDelete(user); setDeleteConfirmName(''); setIsDeleteModalOpen(true); }} className="p-1 hover:text-red-600"><Trash2 size={16} /></button>
|
|
||||||
</td>
|
|
||||||
)}
|
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
</thead>
|
||||||
</tbody>
|
<tbody className="divide-y dark:divide-dark-border text-sm">
|
||||||
</table>
|
{filtered.map(user => (
|
||||||
|
<tr key={user.id} className="hover:bg-zinc-50 dark:hover:bg-dark-border/50 transition-colors group">
|
||||||
|
<td className="px-6 py-4">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<div className="relative">
|
||||||
|
<img
|
||||||
|
src={user.avatar_url
|
||||||
|
? (user.avatar_url.startsWith('http') ? user.avatar_url : `${import.meta.env.PROD ? '' : 'http://localhost:3001'}${user.avatar_url}`)
|
||||||
|
: `https://ui-avatars.com/api/?name=${encodeURIComponent(user.name)}&background=random`}
|
||||||
|
alt=""
|
||||||
|
className="w-10 h-10 rounded-full border border-zinc-200 dark:border-dark-border object-cover"
|
||||||
|
/>
|
||||||
|
<span className={`absolute bottom-0 right-0 w-2.5 h-2.5 rounded-full border-2 border-white dark:border-dark-card ${user.status === 'active' ? 'bg-green-500' : 'bg-zinc-300 dark:bg-zinc-600'}`}></span>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div className="font-bold text-zinc-900 dark:text-dark-text">{user.name}</div>
|
||||||
|
<div className="text-xs text-zinc-500 dark:text-dark-muted">{user.email}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
<td className="px-6 py-4">
|
||||||
|
<span className={`px-2.5 py-0.5 rounded-full text-xs font-bold border capitalize ${getRoleBadge(user.role)}`}>{getRoleLabel(user.role)}</span>
|
||||||
|
</td>
|
||||||
|
<td className="px-6 py-4 text-zinc-600 dark:text-zinc-300 font-medium">{teams.find(t => t.id === user.team_id)?.name || '-'}</td>
|
||||||
|
<td className="px-6 py-4">
|
||||||
|
<span className={`px-2 py-0.5 rounded-full text-xs font-bold border ${user.status === 'active' ? 'bg-green-100 text-green-700 border-green-200 dark:bg-green-900/30 dark:text-green-400 dark:border-green-800' : 'bg-zinc-100 text-zinc-500 border-zinc-200 dark:bg-dark-input dark:text-dark-muted dark:border-dark-border'}`}>{user.status === 'active' ? 'Ativo' : 'Inativo'}</span>
|
||||||
|
</td>
|
||||||
|
{canManage && (
|
||||||
|
<td className="px-6 py-4 text-right">
|
||||||
|
<div className="flex justify-end gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
|
||||||
|
<button onClick={() => { setEditingUser(user); setFormData({name:user.name, email:user.email, role:user.role as any, team_id:user.team_id||'', status:user.status as any}); setIsModalOpen(true); }} className="p-2 hover:bg-zinc-100 dark:hover:bg-dark-border text-zinc-400 hover:text-zinc-900 dark:hover:text-dark-text rounded-lg transition-colors"><Edit size={16} /></button>
|
||||||
|
<button onClick={() => { setUserToDelete(user); setDeleteConfirmName(''); setIsDeleteModalOpen(true); }} className="p-2 hover:bg-red-50 dark:hover:bg-red-900/30 text-zinc-400 hover:text-red-600 dark:hover:text-red-400 rounded-lg transition-colors"><Trash2 size={16} /></button>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
)}
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{isModalOpen && (
|
{isModalOpen && (
|
||||||
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm">
|
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-zinc-950/80 backdrop-blur-sm">
|
||||||
<div className="bg-white rounded-2xl p-6 w-full max-w-md shadow-xl">
|
<div className="bg-white dark:bg-dark-card rounded-2xl p-8 w-full max-w-lg shadow-2xl animate-in zoom-in duration-200 transition-colors border border-transparent dark:border-dark-border">
|
||||||
<h3 className="text-lg font-bold mb-4">{editingUser ? 'Editar' : 'Novo'} Membro</h3>
|
<h3 className="text-xl font-bold text-zinc-900 dark:text-dark-text mb-6">{editingUser ? 'Editar Usuário' : 'Novo Membro'}</h3>
|
||||||
<form onSubmit={handleSave} className="space-y-4">
|
<form onSubmit={handleSave} className="space-y-5">
|
||||||
<div><label className="text-xs font-bold text-slate-500 block mb-1">NOME</label><input type="text" value={formData.name} onChange={e => setFormData({...formData, name:e.target.value})} className="w-full border p-2 rounded-lg" required /></div>
|
<div>
|
||||||
<div><label className="text-xs font-bold text-slate-500 block mb-1">E-MAIL</label><input type="email" value={formData.email} onChange={e => setFormData({...formData, email:e.target.value})} className="w-full border p-2 rounded-lg" disabled={!!editingUser} required /></div>
|
<label className="text-xs font-bold text-zinc-500 dark:text-dark-muted uppercase mb-1 block">Nome Completo</label>
|
||||||
<div className="grid grid-cols-2 gap-4">
|
<input type="text" value={formData.name} onChange={e => setFormData({...formData, name:e.target.value})} className="w-full bg-white dark:bg-dark-input border border-zinc-200 dark:border-dark-border p-3 rounded-lg text-sm text-zinc-900 dark:text-dark-text outline-none focus:ring-2 focus:ring-brand-yellow/20" required />
|
||||||
<div><label className="text-xs font-bold text-slate-500 block mb-1">FUNÇÃO</label><select value={formData.role} onChange={e => setFormData({...formData, role: e.target.value as any})} className="w-full border p-2 rounded-lg"><option value="agent">Agente</option><option value="manager">Gerente</option><option value="admin">Admin</option></select></div>
|
|
||||||
<div><label className="text-xs font-bold text-slate-500 block mb-1">TIME</label><select value={formData.team_id} onChange={e => setFormData({...formData, team_id: e.target.value})} className="w-full border p-2 rounded-lg"><option value="">Nenhum</option>{teams.map(t => <option key={t.id} value={t.id}>{t.name}</option>)}</select></div>
|
|
||||||
</div>
|
</div>
|
||||||
<div><label className="text-xs font-bold text-slate-500 block mb-1">STATUS</label><select value={formData.status} onChange={e => setFormData({...formData, status: e.target.value as any})} className="w-full border p-2 rounded-lg"><option value="active">Ativo</option><option value="inactive">Inativo</option></select></div>
|
<div>
|
||||||
<div className="flex justify-end gap-2 pt-4">
|
<label className="text-xs font-bold text-zinc-500 dark:text-dark-muted uppercase mb-1 block">E-mail</label>
|
||||||
<button type="button" onClick={() => setIsModalOpen(false)} className="px-4 py-2">Cancelar</button>
|
<input type="email" value={formData.email} onChange={e => setFormData({...formData, email:e.target.value})} className="w-full bg-white dark:bg-dark-input border border-zinc-200 dark:border-dark-border p-3 rounded-lg text-sm text-zinc-900 dark:text-dark-text disabled:bg-zinc-50 dark:disabled:bg-dark-bg/50 dark:disabled:text-dark-muted" disabled={!!editingUser} required />
|
||||||
<button type="submit" className="bg-slate-900 text-white px-6 py-2 rounded-lg font-bold">{isSaving ? '...' : 'Salvar'}</button>
|
</div>
|
||||||
|
<div className="grid grid-cols-2 gap-4">
|
||||||
|
<div>
|
||||||
|
<label className="text-xs font-bold text-zinc-500 dark:text-dark-muted uppercase mb-1 block">Função</label>
|
||||||
|
<select value={formData.role} onChange={e => setFormData({...formData, role: e.target.value as any})} className="w-full bg-white dark:bg-dark-input border border-zinc-200 dark:border-dark-border p-3 rounded-lg text-sm text-zinc-900 dark:text-dark-text">
|
||||||
|
<option value="agent">Agente</option>
|
||||||
|
<option value="manager">Gerente</option>
|
||||||
|
<option value="admin">Admin</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="text-xs font-bold text-zinc-500 dark:text-dark-muted uppercase mb-1 block">Time</label>
|
||||||
|
<select value={formData.team_id} onChange={e => setFormData({...formData, team_id: e.target.value})} className="w-full bg-white dark:bg-dark-input border border-zinc-200 dark:border-dark-border p-3 rounded-lg text-sm text-zinc-900 dark:text-dark-text">
|
||||||
|
<option value="">Nenhum</option>
|
||||||
|
{teams.map(t => <option key={t.id} value={t.id}>{t.name}</option>)}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="text-xs font-bold text-zinc-500 dark:text-dark-muted uppercase mb-1 block">Status</label>
|
||||||
|
<select value={formData.status} onChange={e => setFormData({...formData, status: e.target.value as any})} className="w-full bg-white dark:bg-dark-input border border-zinc-200 dark:border-dark-border p-3 rounded-lg text-sm text-zinc-900 dark:text-dark-text">
|
||||||
|
<option value="active">Ativo</option>
|
||||||
|
<option value="inactive">Inativo</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div className="flex justify-end gap-3 pt-6 border-t dark:border-dark-border mt-6">
|
||||||
|
<button type="button" onClick={() => setIsModalOpen(false)} className="px-6 py-2.5 text-sm font-medium text-zinc-500 dark:text-dark-muted hover:bg-zinc-100 dark:hover:bg-dark-border rounded-lg transition-colors">Cancelar</button>
|
||||||
|
<button type="submit" disabled={isSaving} className="bg-zinc-900 dark:bg-brand-yellow text-white dark:text-zinc-950 px-8 py-2.5 rounded-lg text-sm font-bold flex items-center gap-2 hover:opacity-90 transition-all">{isSaving ? <Loader2 className="animate-spin" size={16} /> : 'Salvar Alterações'}</button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
@@ -137,13 +199,15 @@ export const TeamManagement: React.FC = () => {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{isDeleteModalOpen && userToDelete && (
|
{isDeleteModalOpen && userToDelete && (
|
||||||
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50">
|
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-zinc-950/80 backdrop-blur-sm">
|
||||||
<div className="bg-white rounded-2xl p-6 w-full max-w-md">
|
<div className="bg-white dark:bg-dark-card rounded-2xl p-8 w-full max-w-md shadow-xl animate-in zoom-in duration-200 text-center transition-colors border border-transparent dark:border-dark-border">
|
||||||
<h3 className="text-lg font-bold mb-2">Excluir {userToDelete.name}?</h3>
|
<div className="w-16 h-16 bg-red-100 dark:bg-red-900/30 text-red-600 dark:text-red-400 rounded-full flex items-center justify-center mx-auto mb-4"><AlertTriangle size={32} /></div>
|
||||||
<input type="text" value={deleteConfirmName} onChange={e => setDeleteConfirmName(e.target.value)} className="w-full border-2 p-2 rounded-lg mb-4 text-center font-bold" placeholder="Digite o nome para confirmar" />
|
<h3 className="text-xl font-bold text-zinc-900 dark:text-dark-text mb-2">Excluir {userToDelete.name}?</h3>
|
||||||
<div className="flex gap-2">
|
<p className="text-sm text-zinc-500 dark:text-dark-muted mb-8 leading-relaxed">Esta ação é <strong>permanente</strong>. Para confirmar, digite o nome completo dele abaixo:</p>
|
||||||
<button onClick={() => setIsDeleteModalOpen(false)} className="flex-1 py-2">Cancelar</button>
|
<input type="text" value={deleteConfirmName} onChange={e => setDeleteConfirmName(e.target.value)} className="w-full bg-white dark:bg-dark-input border-2 border-red-50 dark:border-red-900/20 p-3 rounded-xl mb-8 text-center font-bold text-base text-zinc-900 dark:text-dark-text outline-none focus:ring-2 focus:ring-red-100 dark:focus:ring-red-900/40 transition-all" placeholder="Nome completo" />
|
||||||
<button onClick={handleConfirmDelete} disabled={deleteConfirmName !== userToDelete.name} className="flex-1 py-2 bg-red-600 text-white rounded-lg">Excluir</button>
|
<div className="flex gap-3">
|
||||||
|
<button onClick={() => setIsDeleteModalOpen(false)} className="flex-1 py-3 text-sm font-bold text-zinc-500 dark:text-dark-muted hover:bg-zinc-100 dark:hover:bg-dark-border rounded-lg border border-zinc-100 dark:border-dark-border transition-colors">Cancelar</button>
|
||||||
|
<button onClick={handleConfirmDelete} disabled={isSaving || deleteConfirmName !== userToDelete.name} className="flex-1 py-3 text-sm font-bold bg-red-600 text-white rounded-lg disabled:opacity-50 shadow-lg shadow-red-200 dark:shadow-none transition-all hover:bg-red-700">Excluir para sempre</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import React, { useState, useEffect, useMemo } from 'react';
|
import React, { useState, useEffect, useMemo } from 'react';
|
||||||
import { Building2, Users, Plus, Search, Target, ArrowUpRight, Loader2, CheckCircle2, AlertCircle, Edit2, X } from 'lucide-react';
|
import { Building2, Users, Plus, Search, Target, ArrowUpRight, Loader2, Edit2, X } from 'lucide-react';
|
||||||
import { getTeams, getUsers, getAttendances, createTeam, updateTeam } from '../services/dataService';
|
import { getTeams, getUsers, getAttendances, createTeam, updateTeam } from '../services/dataService';
|
||||||
import { User, Attendance } from '../types';
|
import { User, Attendance } from '../types';
|
||||||
|
|
||||||
@@ -11,15 +11,8 @@ export const Teams: React.FC = () => {
|
|||||||
const [isSaving, setIsSaving] = useState(false);
|
const [isSaving, setIsSaving] = useState(false);
|
||||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||||
const [editingTeam, setEditingTeam] = useState<any | null>(null);
|
const [editingTeam, setEditingTeam] = useState<any | null>(null);
|
||||||
const [searchTerm, setSearchTerm] = useState('');
|
|
||||||
const [toast, setToast] = useState<{message: string, type: 'success' | 'error'} | null>(null);
|
|
||||||
const [formData, setFormData] = useState({ name: '', description: '' });
|
const [formData, setFormData] = useState({ name: '', description: '' });
|
||||||
|
|
||||||
const showToast = (message: string, type: 'success' | 'error') => {
|
|
||||||
setToast({ message, type });
|
|
||||||
setTimeout(() => setToast(null), 4000);
|
|
||||||
};
|
|
||||||
|
|
||||||
const loadData = async () => {
|
const loadData = async () => {
|
||||||
const tid = localStorage.getItem('ctms_tenant_id');
|
const tid = localStorage.getItem('ctms_tenant_id');
|
||||||
if (!tid) return;
|
if (!tid) return;
|
||||||
@@ -41,77 +34,84 @@ export const Teams: React.FC = () => {
|
|||||||
const ta = attendances.filter(a => tu.some(u => u.id === a.user_id));
|
const ta = attendances.filter(a => tu.some(u => u.id === a.user_id));
|
||||||
const wins = ta.filter(a => a.converted).length;
|
const wins = ta.filter(a => a.converted).length;
|
||||||
const rate = ta.length > 0 ? (wins / ta.length) * 100 : 0;
|
const rate = ta.length > 0 ? (wins / ta.length) * 100 : 0;
|
||||||
return { ...t, memberCount: tu.length, leads: ta.length, rate: rate.toFixed(1) };
|
return { ...t, memberCount: tu.length, rate: rate.toFixed(1) };
|
||||||
}), [teams, users, attendances]);
|
}), [teams, users, attendances]);
|
||||||
|
|
||||||
const filtered = stats.filter(t => t.name.toLowerCase().includes(searchTerm.toLowerCase()));
|
|
||||||
|
|
||||||
const handleSave = async (e: React.FormEvent) => {
|
const handleSave = async (e: React.FormEvent) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
setIsSaving(true);
|
setIsSaving(true);
|
||||||
try {
|
try {
|
||||||
const tid = localStorage.getItem('ctms_tenant_id') || '';
|
const tid = localStorage.getItem('ctms_tenant_id') || '';
|
||||||
if (editingTeam) {
|
const success = editingTeam
|
||||||
if (await updateTeam(editingTeam.id, formData)) { showToast('Atualizado!', 'success'); setIsModalOpen(false); loadData(); }
|
? await updateTeam(editingTeam.id, formData)
|
||||||
} else {
|
: await createTeam({ ...formData, tenantId: tid });
|
||||||
if (await createTeam({ ...formData, tenantId: tid })) { showToast('Criado!', 'success'); setIsModalOpen(false); loadData(); }
|
if (success) { setIsModalOpen(false); loadData(); }
|
||||||
}
|
} catch (err) { alert('Erro ao salvar'); } finally { setIsSaving(false); }
|
||||||
} catch (e) { showToast('Erro', 'error'); } finally { setIsSaving(false); }
|
|
||||||
};
|
};
|
||||||
|
|
||||||
if (loading && teams.length === 0) return <div className="p-12 text-center text-slate-400">Carregando...</div>;
|
if (loading && teams.length === 0) return <div className="p-12 text-center text-zinc-400 dark:text-dark-muted transition-colors">Carregando...</div>;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-8 max-w-7xl mx-auto pb-12">
|
<div className="space-y-8 max-w-7xl mx-auto pb-12 transition-colors duration-300">
|
||||||
<div className="flex justify-between items-center">
|
<div className="flex justify-between items-center">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-2xl font-bold text-slate-900">Times</h1>
|
<h1 className="text-2xl font-bold text-zinc-900 dark:text-zinc-50 tracking-tight">Times</h1>
|
||||||
<p className="text-slate-500 text-sm">Desempenho por grupo.</p>
|
<p className="text-zinc-500 dark:text-dark-muted text-sm">Visualize o desempenho e gerencie seus grupos de vendas.</p>
|
||||||
</div>
|
</div>
|
||||||
<button onClick={() => { setEditingTeam(null); setFormData({name:'', description:''}); setIsModalOpen(true); }} className="bg-slate-900 text-white px-4 py-2 rounded-lg flex items-center gap-2 text-sm font-bold">
|
<button onClick={() => { setEditingTeam(null); setFormData({name:'', description:''}); setIsModalOpen(true); }} className="bg-zinc-900 dark:bg-brand-yellow text-white dark:text-zinc-950 px-4 py-2 rounded-lg flex items-center gap-2 text-sm font-bold shadow-sm hover:opacity-90 transition-all">
|
||||||
<Plus size={16} /> Novo Time
|
<Plus size={16} /> Novo Time
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
|
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||||
{filtered.map(t => (
|
{stats.map(t => (
|
||||||
<div key={t.id} className="bg-white rounded-2xl border border-slate-200 p-6 shadow-sm group">
|
<div key={t.id} className="bg-white dark:bg-dark-card rounded-2xl border border-zinc-200 dark:border-dark-border p-6 shadow-sm group hover:shadow-md transition-all">
|
||||||
<div className="flex justify-between mb-4">
|
<div className="flex justify-between mb-6">
|
||||||
<div className="p-3 bg-blue-50 text-blue-600 rounded-xl"><Building2 size={24} /></div>
|
<div className="p-3 bg-zinc-50 dark:bg-dark-bg text-zinc-600 dark:text-dark-muted rounded-xl border border-zinc-100 dark:border-dark-border"><Building2 size={24} /></div>
|
||||||
<button onClick={() => { setEditingTeam(t); setFormData({name:t.name, description:t.description||''}); setIsModalOpen(true); }} className="text-slate-400 hover:text-blue-600 opacity-0 group-hover:opacity-100 transition-opacity"><Edit2 size={18} /></button>
|
<button onClick={() => { setEditingTeam(t); setFormData({name:t.name, description:t.description||''}); setIsModalOpen(true); }} className="text-zinc-400 dark:text-dark-muted hover:text-zinc-900 dark:hover:text-dark-text opacity-0 group-hover:opacity-100 p-2 rounded-lg hover:bg-zinc-50 dark:hover:bg-dark-bg transition-all"><Edit2 size={18} /></button>
|
||||||
</div>
|
</div>
|
||||||
<h3 className="font-bold text-slate-900">{t.name}</h3>
|
<h3 className="text-lg font-bold text-zinc-900 dark:text-zinc-50 mb-1">{t.name}</h3>
|
||||||
<p className="text-sm text-slate-500 mb-4">{t.description || 'Sem descrição'}</p>
|
<p className="text-sm text-zinc-500 dark:text-dark-muted mb-6 h-10 line-clamp-2">{t.description || 'Sem descrição definida.'}</p>
|
||||||
<div className="grid grid-cols-2 gap-4 pt-4 border-t text-sm">
|
<div className="grid grid-cols-2 gap-4 pt-6 border-t border-zinc-50 dark:border-dark-border text-sm">
|
||||||
<div><span className="text-slate-400 block text-xs font-bold uppercase">Membros</span><strong>{t.memberCount}</strong></div>
|
<div className="space-y-1">
|
||||||
<div><span className="text-slate-400 block text-xs font-bold uppercase">Conversão</span><strong className="text-blue-600">{t.rate}%</strong></div>
|
<span className="text-zinc-400 dark:text-dark-muted block text-[10px] font-bold uppercase tracking-wider">Membros</span>
|
||||||
|
<strong className="text-lg text-zinc-800 dark:text-zinc-200">{t.memberCount}</strong>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-1 text-right">
|
||||||
|
<span className="text-zinc-400 dark:text-dark-muted block text-[10px] font-bold uppercase tracking-wider">Conversão</span>
|
||||||
|
<strong className="text-lg text-brand-yellow">{t.rate}%</strong>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{isModalOpen && (
|
{isModalOpen && (
|
||||||
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/50 backdrop-blur-sm">
|
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-zinc-950/80 backdrop-blur-sm">
|
||||||
<div className="bg-white rounded-2xl p-6 w-full max-w-md">
|
<div className="bg-white dark:bg-dark-card rounded-2xl p-8 w-full max-w-md shadow-2xl animate-in zoom-in duration-200 transition-colors border border-transparent dark:border-dark-border">
|
||||||
<h3 className="text-lg font-bold mb-4">{editingTeam ? 'Editar' : 'Novo'} Time</h3>
|
<div className="flex justify-between items-center mb-6 pb-4 border-b border-zinc-100 dark:border-dark-border">
|
||||||
<form onSubmit={handleSave} className="space-y-4">
|
<h3 className="text-xl font-bold text-zinc-900 dark:text-zinc-50">{editingTeam ? 'Editar Time' : 'Novo Time'}</h3>
|
||||||
<input type="text" placeholder="Nome" value={formData.name} onChange={e => setFormData({...formData, name:e.target.value})} className="w-full border p-2 rounded-lg" required />
|
<button onClick={() => setIsModalOpen(false)} className="text-zinc-400 hover:text-zinc-600 dark:hover:text-zinc-300 transition-colors"><X size={20} /></button>
|
||||||
<textarea placeholder="Descrição" value={formData.description} onChange={e => setFormData({...formData, description:e.target.value})} className="w-full border p-2 rounded-lg resize-none" rows={3} />
|
</div>
|
||||||
<div className="flex justify-end gap-2">
|
<form onSubmit={handleSave} className="space-y-5">
|
||||||
<button type="button" onClick={() => setIsModalOpen(false)} className="px-4 py-2 text-slate-500">Cancelar</button>
|
<div>
|
||||||
<button type="submit" disabled={isSaving} className="bg-slate-900 text-white px-6 py-2 rounded-lg font-bold">{isSaving ? '...' : 'Salvar'}</button>
|
<label className="text-xs font-bold text-zinc-500 dark:text-dark-muted uppercase mb-1.5 block tracking-wider">Nome do Time</label>
|
||||||
|
<input type="text" placeholder="Ex: Vendas Sul" value={formData.name} onChange={e => setFormData({...formData, name:e.target.value})} className="w-full bg-white dark:bg-dark-input border border-zinc-200 dark:border-dark-border p-3 rounded-lg text-sm text-zinc-900 dark:text-zinc-100 outline-none focus:ring-2 focus:ring-brand-yellow/20 transition-all" required />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="text-xs font-bold text-zinc-500 dark:text-dark-muted uppercase mb-1.5 block tracking-wider">Descrição</label>
|
||||||
|
<textarea placeholder="Breve descrição..." value={formData.description} onChange={e => setFormData({...formData, description:e.target.value})} className="w-full bg-white dark:bg-dark-input border border-zinc-200 dark:border-dark-border p-3 rounded-lg text-sm text-zinc-900 dark:text-zinc-100 resize-none h-28 outline-none focus:ring-2 focus:ring-brand-yellow/20 transition-all" />
|
||||||
|
</div>
|
||||||
|
<div className="flex justify-end gap-3 pt-6 border-t dark:border-dark-border mt-6">
|
||||||
|
<button type="button" onClick={() => setIsModalOpen(false)} className="px-6 py-2.5 text-sm font-medium text-zinc-500 dark:text-dark-muted hover:bg-zinc-100 dark:hover:bg-dark-bg rounded-lg transition-colors">Cancelar</button>
|
||||||
|
<button type="submit" disabled={isSaving} className="bg-zinc-900 dark:bg-brand-yellow text-white dark:text-zinc-950 px-8 py-2.5 rounded-lg text-sm font-bold shadow-lg transition-all hover:opacity-90">
|
||||||
|
{isSaving ? <Loader2 className="animate-spin" size={16} /> : 'Salvar Time'}
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{toast && (
|
|
||||||
<div className="fixed bottom-8 right-8 z-[100] flex items-center gap-3 px-6 py-4 rounded-2xl shadow-2xl bg-white border border-slate-100">
|
|
||||||
<CheckCircle2 className="text-green-500" size={20} />
|
|
||||||
<span className="font-bold text-sm text-slate-700">{toast.message}</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import React, { useEffect, useState, useMemo } from 'react';
|
import React, { useEffect, useState, useMemo } from 'react';
|
||||||
import { useParams, Link } from 'react-router-dom';
|
import { useParams, Link } from 'react-router-dom';
|
||||||
import { getAttendances, getUserById } from '../services/dataService';
|
import { getAttendances, getUserById } from '../services/dataService';
|
||||||
import { Attendance, User, FunnelStage } from '../types';
|
import { Attendance, User, FunnelStage, DashboardFilter } from '../types';
|
||||||
import { ArrowLeft, Mail, Phone, Clock, MessageSquare, ChevronLeft, ChevronRight, Eye } from 'lucide-react';
|
import { ArrowLeft, Mail, Phone, Clock, MessageSquare, ChevronLeft, ChevronRight, Eye, Filter } from 'lucide-react';
|
||||||
|
|
||||||
const ITEMS_PER_PAGE = 10;
|
const ITEMS_PER_PAGE = 10;
|
||||||
|
|
||||||
@@ -12,6 +12,12 @@ export const UserDetail: React.FC = () => {
|
|||||||
const [attendances, setAttendances] = useState<Attendance[]>([]);
|
const [attendances, setAttendances] = useState<Attendance[]>([]);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [currentPage, setCurrentPage] = useState(1);
|
const [currentPage, setCurrentPage] = useState(1);
|
||||||
|
const [filters, setFilters] = useState<DashboardFilter>({
|
||||||
|
dateRange: { start: new Date(0), end: new Date() },
|
||||||
|
userId: id,
|
||||||
|
funnelStage: 'all',
|
||||||
|
origin: 'all'
|
||||||
|
});
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (id) {
|
if (id) {
|
||||||
@@ -25,8 +31,8 @@ export const UserDetail: React.FC = () => {
|
|||||||
|
|
||||||
if (u && tenantId) {
|
if (u && tenantId) {
|
||||||
const data = await getAttendances(tenantId, {
|
const data = await getAttendances(tenantId, {
|
||||||
userId: id,
|
...filters,
|
||||||
dateRange: { start: new Date(0), end: new Date() } // All time
|
userId: id
|
||||||
});
|
});
|
||||||
setAttendances(data);
|
setAttendances(data);
|
||||||
}
|
}
|
||||||
@@ -39,7 +45,12 @@ export const UserDetail: React.FC = () => {
|
|||||||
|
|
||||||
loadData();
|
loadData();
|
||||||
}
|
}
|
||||||
}, [id]);
|
}, [id, filters]);
|
||||||
|
|
||||||
|
const handleFilterChange = (key: keyof DashboardFilter, value: any) => {
|
||||||
|
setFilters(prev => ({ ...prev, [key]: value }));
|
||||||
|
setCurrentPage(1); // Reset pagination on filter change
|
||||||
|
};
|
||||||
|
|
||||||
const totalPages = Math.ceil(attendances.length / ITEMS_PER_PAGE);
|
const totalPages = Math.ceil(attendances.length / ITEMS_PER_PAGE);
|
||||||
|
|
||||||
@@ -56,38 +67,46 @@ export const UserDetail: React.FC = () => {
|
|||||||
|
|
||||||
const getStageBadgeColor = (stage: FunnelStage) => {
|
const getStageBadgeColor = (stage: FunnelStage) => {
|
||||||
switch (stage) {
|
switch (stage) {
|
||||||
case FunnelStage.WON: return 'bg-green-100 text-green-700 border-green-200';
|
case FunnelStage.WON: return 'bg-green-100 text-green-700 border-green-200 dark:bg-green-900/30 dark:text-green-400 dark:border-green-800';
|
||||||
case FunnelStage.LOST: return 'bg-red-100 text-red-700 border-red-200';
|
case FunnelStage.LOST: return 'bg-red-100 text-red-700 border-red-200 dark:bg-red-900/30 dark:text-red-400 dark:border-red-800';
|
||||||
case FunnelStage.NEGOTIATION: return 'bg-blue-100 text-blue-700 border-blue-200';
|
case FunnelStage.NEGOTIATION: return 'bg-blue-100 text-blue-700 border-blue-200 dark:bg-blue-900/30 dark:text-blue-400 dark:border-blue-800';
|
||||||
case FunnelStage.IDENTIFICATION: return 'bg-yellow-100 text-yellow-700 border-yellow-200';
|
case FunnelStage.IDENTIFICATION: return 'bg-yellow-100 text-yellow-700 border-yellow-200 dark:bg-yellow-900/30 dark:text-yellow-400 dark:border-yellow-800';
|
||||||
default: return 'bg-slate-100 text-slate-700 border-slate-200';
|
default: return 'bg-zinc-100 text-zinc-700 border-zinc-200 dark:bg-zinc-800 dark:text-zinc-300 dark:border-zinc-700';
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const getScoreColor = (score: number) => {
|
const getScoreColor = (score: number) => {
|
||||||
if (score >= 80) return 'text-green-600 bg-green-50';
|
if (score >= 80) return 'text-green-600 bg-green-50 dark:bg-green-900/20 dark:text-green-400';
|
||||||
if (score >= 60) return 'text-yellow-600 bg-yellow-50';
|
if (score >= 60) return 'text-yellow-600 bg-yellow-50 dark:bg-yellow-900/20 dark:text-yellow-400';
|
||||||
return 'text-red-600 bg-red-50';
|
return 'text-red-600 bg-red-50 dark:bg-red-900/20 dark:text-red-400';
|
||||||
};
|
};
|
||||||
|
|
||||||
if (!loading && !user) return <div className="p-8 text-slate-500">Usuário não encontrado</div>;
|
if (!loading && !user) return <div className="p-8 text-zinc-500 dark:text-dark-muted transition-colors">Usuário não encontrado</div>;
|
||||||
|
|
||||||
|
const backendUrl = import.meta.env.PROD ? '' : 'http://localhost:3001';
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-8 max-w-7xl mx-auto">
|
<div className="space-y-8 max-w-7xl mx-auto transition-colors duration-300">
|
||||||
{/* Header Section */}
|
{/* Header Section */}
|
||||||
<div className="flex flex-col md:flex-row gap-6 items-start md:items-center justify-between">
|
<div className="flex flex-col md:flex-row gap-6 items-start md:items-center justify-between">
|
||||||
<div className="flex items-center gap-4">
|
<div className="flex items-center gap-4">
|
||||||
<Link to="/" className="p-2.5 bg-white border border-slate-200 rounded-lg text-slate-500 hover:bg-slate-50 hover:text-slate-900 transition-colors shadow-sm">
|
<Link to="/" className="p-2.5 bg-white dark:bg-dark-card border border-zinc-200 dark:border-dark-border rounded-lg text-zinc-500 dark:text-dark-muted hover:bg-zinc-50 dark:hover:bg-zinc-800 hover:text-zinc-900 dark:hover:text-dark-text transition-all shadow-sm">
|
||||||
<ArrowLeft size={18} />
|
<ArrowLeft size={18} />
|
||||||
</Link>
|
</Link>
|
||||||
{user && (
|
{user && (
|
||||||
<div className="flex items-center gap-4">
|
<div className="flex items-center gap-4">
|
||||||
<img src={user.avatar_url} alt={user.name} className="w-16 h-16 rounded-full border-2 border-white shadow-md object-cover" />
|
<img
|
||||||
|
src={user.avatar_url
|
||||||
|
? (user.avatar_url.startsWith('http') ? user.avatar_url : `${backendUrl}${user.avatar_url}`)
|
||||||
|
: `https://ui-avatars.com/api/?name=${encodeURIComponent(user.name)}&background=random`}
|
||||||
|
alt={user.name}
|
||||||
|
className="w-16 h-16 rounded-full border-2 border-white dark:border-dark-border shadow-md object-cover"
|
||||||
|
/>
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-2xl font-bold text-slate-900 tracking-tight">{user.name}</h1>
|
<h1 className="text-2xl font-bold text-zinc-900 dark:text-dark-text tracking-tight">{user.name}</h1>
|
||||||
<div className="flex items-center gap-3 text-sm text-slate-500 mt-1">
|
<div className="flex items-center gap-3 text-sm text-zinc-500 dark:text-dark-muted mt-1">
|
||||||
<span className="flex items-center gap-1.5"><Mail size={14} /> {user.email}</span>
|
<span className="flex items-center gap-1.5"><Mail size={14} /> {user.email}</span>
|
||||||
<span className="bg-slate-100 text-slate-600 px-2 py-0.5 rounded text-xs font-semibold uppercase">{user.role}</span>
|
<span className="bg-zinc-100 dark:bg-dark-bg text-zinc-600 dark:text-dark-muted px-2 py-0.5 rounded text-xs font-semibold uppercase">{user.role}</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -95,40 +114,72 @@ export const UserDetail: React.FC = () => {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Filters Section */}
|
||||||
|
<div className="bg-white dark:bg-dark-card p-4 rounded-xl border border-zinc-200 dark:border-dark-border shadow-sm flex flex-wrap items-center gap-4">
|
||||||
|
<div className="flex items-center gap-2 text-zinc-500 dark:text-dark-muted font-medium mr-2">
|
||||||
|
<Filter size={18} />
|
||||||
|
<span>Filtros:</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<select
|
||||||
|
className="bg-zinc-50 dark:bg-dark-bg border border-zinc-200 dark:border-dark-border px-3 py-2 rounded-lg text-sm text-zinc-700 dark:text-zinc-200 outline-none focus:ring-2 focus:ring-brand-yellow/20 cursor-pointer hover:border-zinc-300 dark:hover:border-zinc-700 transition-all"
|
||||||
|
value={filters.funnelStage}
|
||||||
|
onChange={(e) => handleFilterChange('funnelStage', e.target.value)}
|
||||||
|
>
|
||||||
|
<option value="all">Todas Etapas</option>
|
||||||
|
{Object.values(FunnelStage).map(stage => (
|
||||||
|
<option key={stage} value={stage}>{stage}</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
|
||||||
|
<select
|
||||||
|
className="bg-zinc-50 dark:bg-dark-bg border border-zinc-200 dark:border-dark-border px-3 py-2 rounded-lg text-sm text-zinc-700 dark:text-zinc-200 outline-none focus:ring-2 focus:ring-brand-yellow/20 cursor-pointer hover:border-zinc-300 dark:hover:border-zinc-700 transition-all"
|
||||||
|
value={filters.origin}
|
||||||
|
onChange={(e) => handleFilterChange('origin', e.target.value)}
|
||||||
|
>
|
||||||
|
<option value="all">Todas Origens</option>
|
||||||
|
<option value="WhatsApp">WhatsApp</option>
|
||||||
|
<option value="Instagram">Instagram</option>
|
||||||
|
<option value="Website">Website</option>
|
||||||
|
<option value="LinkedIn">LinkedIn</option>
|
||||||
|
<option value="Indicação">Indicação</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
{/* KPI Cards */}
|
{/* KPI Cards */}
|
||||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
|
<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="bg-white dark:bg-dark-card p-6 rounded-xl border border-zinc-200 dark:border-dark-border shadow-sm transition-colors">
|
||||||
<div className="text-sm font-medium text-slate-500 mb-2">Total de Interações</div>
|
<div className="text-sm font-medium text-zinc-500 dark:text-dark-muted mb-2">Total de Interações</div>
|
||||||
<div className="text-3xl font-bold text-slate-900">{attendances.length}</div>
|
<div className="text-3xl font-bold text-zinc-900 dark:text-dark-text">{attendances.length}</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="bg-white p-6 rounded-xl border border-slate-200 shadow-sm">
|
<div className="bg-white dark:bg-dark-card p-6 rounded-xl border border-zinc-200 dark:border-dark-border shadow-sm transition-colors">
|
||||||
<div className="text-sm font-medium text-slate-500 mb-2">Taxa de Conversão</div>
|
<div className="text-sm font-medium text-zinc-500 dark:text-dark-muted mb-2">Taxa de Conversão</div>
|
||||||
<div className="text-3xl font-bold text-blue-600">
|
<div className="text-3xl font-bold text-brand-yellow">
|
||||||
{attendances.length ? ((attendances.filter(a => a.converted).length / attendances.length) * 100).toFixed(1) : 0}%
|
{attendances.length ? ((attendances.filter(a => a.converted).length / attendances.length) * 100).toFixed(1) : 0}%
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="bg-white p-6 rounded-xl border border-slate-200 shadow-sm">
|
<div className="bg-white dark:bg-dark-card p-6 rounded-xl border border-zinc-200 dark:border-dark-border shadow-sm transition-colors">
|
||||||
<div className="text-sm font-medium text-slate-500 mb-2">Nota Média</div>
|
<div className="text-sm font-medium text-zinc-500 dark:text-dark-muted mb-2">Nota Média</div>
|
||||||
<div className="text-3xl font-bold text-yellow-500">
|
<div className="text-3xl font-bold text-zinc-800 dark:text-zinc-100">
|
||||||
{attendances.length ? (attendances.reduce((acc, c) => acc + c.score, 0) / attendances.length).toFixed(1) : 0}
|
{attendances.length ? (attendances.reduce((acc, c) => acc + c.score, 0) / attendances.length).toFixed(1) : 0}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Attendance Table */}
|
{/* Attendance Table */}
|
||||||
<div className="bg-white border border-slate-200 rounded-xl shadow-sm overflow-hidden flex flex-col">
|
<div className="bg-white dark:bg-dark-card border border-zinc-200 dark:border-dark-border rounded-xl shadow-sm overflow-hidden flex flex-col transition-colors">
|
||||||
<div className="px-6 py-4 border-b border-slate-100 flex justify-between items-center bg-slate-50/50">
|
<div className="px-6 py-4 border-b border-zinc-100 dark:border-zinc-800 flex justify-between items-center bg-zinc-50/50 dark:bg-dark-bg/50">
|
||||||
<h2 className="font-semibold text-slate-900">Histórico de Atendimentos</h2>
|
<h2 className="font-semibold text-zinc-900 dark:text-zinc-100">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>
|
<span className="text-xs text-zinc-500 dark:text-dark-muted font-medium bg-zinc-200/50 dark:bg-zinc-800 px-2 py-1 rounded transition-colors">Página {currentPage} de {totalPages || 1}</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{loading ? (
|
{loading ? (
|
||||||
<div className="p-12 text-center text-slate-400">Carregando registros...</div>
|
<div className="p-12 text-center text-zinc-400 dark:text-dark-muted">Carregando registros...</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="overflow-x-auto">
|
<div className="overflow-x-auto">
|
||||||
<table className="w-full text-left border-collapse">
|
<table className="w-full text-left border-collapse">
|
||||||
<thead>
|
<thead>
|
||||||
<tr className="border-b border-slate-100 text-xs uppercase text-slate-500 bg-slate-50/30">
|
<tr className="border-b border-zinc-100 dark:border-zinc-800 text-xs uppercase text-zinc-500 dark:text-dark-muted bg-zinc-50/30 dark:bg-dark-bg/30">
|
||||||
<th className="px-6 py-4 font-medium">Data / Hora</th>
|
<th className="px-6 py-4 font-medium">Data / Hora</th>
|
||||||
<th className="px-6 py-4 font-medium w-1/3">Resumo</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">Etapa</th>
|
||||||
@@ -137,17 +188,17 @@ export const UserDetail: React.FC = () => {
|
|||||||
<th className="px-6 py-4 font-medium text-right">Ação</th>
|
<th className="px-6 py-4 font-medium text-right">Ação</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody className="divide-y divide-slate-100 text-sm">
|
<tbody className="divide-y divide-zinc-100 dark:divide-zinc-800 text-sm">
|
||||||
{currentData.map(att => (
|
{currentData.map(att => (
|
||||||
<tr key={att.id} className="hover:bg-slate-50/80 transition-colors group">
|
<tr key={att.id} className="hover:bg-zinc-50/80 dark:hover:bg-zinc-800/50 transition-colors group">
|
||||||
<td className="px-6 py-4 text-slate-600 whitespace-nowrap">
|
<td className="px-6 py-4 text-zinc-600 dark:text-zinc-300 whitespace-nowrap">
|
||||||
<div className="font-medium text-slate-900">{new Date(att.created_at).toLocaleDateString()}</div>
|
<div className="font-medium text-zinc-900 dark:text-zinc-100">{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>
|
<div className="text-xs text-zinc-400 dark:text-dark-muted">{new Date(att.created_at).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'})}</div>
|
||||||
</td>
|
</td>
|
||||||
<td className="px-6 py-4">
|
<td className="px-6 py-4">
|
||||||
<div className="flex flex-col">
|
<div className="flex flex-col">
|
||||||
<span className="text-slate-800 line-clamp-1 font-medium mb-1">{att.summary}</span>
|
<span className="text-zinc-800 dark:text-zinc-200 line-clamp-1 font-medium mb-1">{att.summary}</span>
|
||||||
<div className="flex items-center gap-2 text-xs text-slate-500">
|
<div className="flex items-center gap-2 text-xs text-zinc-500 dark:text-dark-muted">
|
||||||
<span className="flex items-center gap-1"><MessageSquare size={10} /> {att.origin}</span>
|
<span className="flex items-center gap-1"><MessageSquare size={10} /> {att.origin}</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -162,16 +213,16 @@ export const UserDetail: React.FC = () => {
|
|||||||
{att.score}
|
{att.score}
|
||||||
</span>
|
</span>
|
||||||
</td>
|
</td>
|
||||||
<td className="px-6 py-4 text-center text-slate-600">
|
<td className="px-6 py-4 text-center text-zinc-600 dark:text-zinc-300">
|
||||||
<div className="flex items-center justify-center gap-1">
|
<div className="flex items-center justify-center gap-1">
|
||||||
<Clock size={14} className="text-slate-400" />
|
<Clock size={14} className="text-zinc-400 dark:text-dark-muted" />
|
||||||
{att.first_response_time_min}m
|
{att.first_response_time_min}m
|
||||||
</div>
|
</div>
|
||||||
</td>
|
</td>
|
||||||
<td className="px-6 py-4 text-right">
|
<td className="px-6 py-4 text-right">
|
||||||
<Link
|
<Link
|
||||||
to={`/attendances/${att.id}`}
|
to={`/attendances/${att.id}`}
|
||||||
className="inline-flex items-center justify-center p-2 rounded-lg text-slate-400 hover:text-blue-600 hover:bg-blue-50 transition-all"
|
className="inline-flex items-center justify-center p-2 rounded-lg text-zinc-400 dark:text-dark-muted hover:text-brand-yellow hover:bg-zinc-100 dark:hover:bg-zinc-800 transition-all"
|
||||||
title="Ver Detalhes"
|
title="Ver Detalhes"
|
||||||
>
|
>
|
||||||
<Eye size={18} />
|
<Eye size={18} />
|
||||||
@@ -186,21 +237,21 @@ export const UserDetail: React.FC = () => {
|
|||||||
|
|
||||||
{/* Pagination Footer */}
|
{/* Pagination Footer */}
|
||||||
{totalPages > 1 && (
|
{totalPages > 1 && (
|
||||||
<div className="px-6 py-4 border-t border-slate-100 flex items-center justify-between bg-slate-50/30">
|
<div className="px-6 py-4 border-t border-zinc-100 dark:border-zinc-800 flex items-center justify-between bg-zinc-50/30 dark:bg-dark-bg/30">
|
||||||
<button
|
<button
|
||||||
onClick={() => handlePageChange(currentPage - 1)}
|
onClick={() => handlePageChange(currentPage - 1)}
|
||||||
disabled={currentPage === 1}
|
disabled={currentPage === 1}
|
||||||
className="flex items-center gap-1 px-3 py-2 text-sm font-medium text-slate-600 bg-white border border-slate-200 rounded-lg hover:bg-slate-50 disabled:opacity-50 disabled:cursor-not-allowed transition-all shadow-sm"
|
className="flex items-center gap-1 px-3 py-2 text-sm font-medium text-zinc-600 dark:text-dark-text bg-white dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700 rounded-lg hover:bg-zinc-50 dark:hover:bg-zinc-700 disabled:opacity-50 disabled:cursor-not-allowed transition-all shadow-sm"
|
||||||
>
|
>
|
||||||
<ChevronLeft size={16} /> Anterior
|
<ChevronLeft size={16} /> Anterior
|
||||||
</button>
|
</button>
|
||||||
<div className="text-sm text-slate-500">
|
<div className="text-sm text-zinc-500 dark:text-dark-muted">
|
||||||
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}
|
Mostrando <span className="font-medium text-zinc-900 dark:text-zinc-100">{((currentPage - 1) * ITEMS_PER_PAGE) + 1}</span> a <span className="font-medium text-zinc-900 dark:text-zinc-100">{Math.min(currentPage * ITEMS_PER_PAGE, attendances.length)}</span> de {attendances.length}
|
||||||
</div>
|
</div>
|
||||||
<button
|
<button
|
||||||
onClick={() => handlePageChange(currentPage + 1)}
|
onClick={() => handlePageChange(currentPage + 1)}
|
||||||
disabled={currentPage === totalPages}
|
disabled={currentPage === totalPages}
|
||||||
className="flex items-center gap-1 px-3 py-2 text-sm font-medium text-slate-600 bg-white border border-slate-200 rounded-lg hover:bg-slate-50 disabled:opacity-50 disabled:cursor-not-allowed transition-all shadow-sm"
|
className="flex items-center gap-1 px-3 py-2 text-sm font-medium text-zinc-600 dark:text-dark-text bg-white dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700 rounded-lg hover:bg-zinc-50 dark:hover:bg-zinc-700 disabled:opacity-50 disabled:cursor-not-allowed transition-all shadow-sm"
|
||||||
>
|
>
|
||||||
Próximo <ChevronRight size={16} />
|
Próximo <ChevronRight size={16} />
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import React, { useState, useEffect } from 'react';
|
import React, { useState, useEffect, useRef } from 'react';
|
||||||
import { Camera, Save, Mail, User as UserIcon, Building, Shield, Loader2, CheckCircle2 } from 'lucide-react';
|
import { Camera, Save, Mail, User as UserIcon, Building, Shield, Loader2, CheckCircle2 } from 'lucide-react';
|
||||||
import { getUserById, getTenants, updateUser } from '../services/dataService';
|
import { getUserById, getTenants, updateUser, uploadAvatar } from '../services/dataService';
|
||||||
import { User, Tenant } from '../types';
|
import { User, Tenant } from '../types';
|
||||||
|
|
||||||
export const UserProfile: React.FC = () => {
|
export const UserProfile: React.FC = () => {
|
||||||
@@ -8,6 +8,8 @@ export const UserProfile: React.FC = () => {
|
|||||||
const [tenant, setTenant] = useState<Tenant | null>(null);
|
const [tenant, setTenant] = useState<Tenant | null>(null);
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
const [isSuccess, setIsSuccess] = useState(false);
|
const [isSuccess, setIsSuccess] = useState(false);
|
||||||
|
const [isUploading, setIsUploading] = useState(false);
|
||||||
|
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||||
|
|
||||||
const [name, setName] = useState('');
|
const [name, setName] = useState('');
|
||||||
const [bio, setBio] = useState('');
|
const [bio, setBio] = useState('');
|
||||||
@@ -38,6 +40,36 @@ export const UserProfile: React.FC = () => {
|
|||||||
fetchUserAndTenant();
|
fetchUserAndTenant();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
const handleAvatarClick = () => {
|
||||||
|
fileInputRef.current?.click();
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
|
const file = e.target.files?.[0];
|
||||||
|
if (!file || !user) return;
|
||||||
|
|
||||||
|
if (file.size > 2 * 1024 * 1024) {
|
||||||
|
alert('Arquivo muito grande. Máximo de 2MB.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setIsUploading(true);
|
||||||
|
try {
|
||||||
|
const newUrl = await uploadAvatar(user.id, file);
|
||||||
|
if (newUrl) {
|
||||||
|
setUser({ ...user, avatar_url: newUrl });
|
||||||
|
window.location.reload();
|
||||||
|
} else {
|
||||||
|
alert('Erro ao fazer upload da imagem.');
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error(err);
|
||||||
|
alert('Erro ao conectar ao servidor.');
|
||||||
|
} finally {
|
||||||
|
setIsUploading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const handleSubmit = async (e: React.FormEvent) => {
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
if (!user) return;
|
if (!user) return;
|
||||||
@@ -49,7 +81,6 @@ export const UserProfile: React.FC = () => {
|
|||||||
const success = await updateUser(user.id, { name, bio });
|
const success = await updateUser(user.id, { name, bio });
|
||||||
if (success) {
|
if (success) {
|
||||||
setIsSuccess(true);
|
setIsSuccess(true);
|
||||||
// Update local state
|
|
||||||
setUser({ ...user, name, bio });
|
setUser({ ...user, name, bio });
|
||||||
setTimeout(() => setIsSuccess(false), 3000);
|
setTimeout(() => setIsSuccess(false), 3000);
|
||||||
} else {
|
} else {
|
||||||
@@ -63,53 +94,69 @@ export const UserProfile: React.FC = () => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
if (!user) return <div className="p-8 text-center text-slate-500">Carregando perfil...</div>;
|
if (!user) return <div className="p-8 text-center text-zinc-500 dark:text-zinc-400 transition-colors">Carregando perfil...</div>;
|
||||||
|
|
||||||
|
const backendUrl = import.meta.env.PROD ? '' : 'http://localhost:3001';
|
||||||
|
const displayAvatar = user.avatar_url
|
||||||
|
? (user.avatar_url.startsWith('http') ? user.avatar_url : `${backendUrl}${user.avatar_url}`)
|
||||||
|
: `https://ui-avatars.com/api/?name=${encodeURIComponent(user.name)}&background=random`;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="max-w-4xl mx-auto space-y-6 pb-12">
|
<div className="max-w-4xl mx-auto space-y-6 pb-12 transition-colors duration-300">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-2xl font-bold text-slate-900 tracking-tight">Meu Perfil</h1>
|
<h1 className="text-2xl font-bold text-zinc-900 dark:text-zinc-50 tracking-tight">Meu Perfil</h1>
|
||||||
<p className="text-slate-500 text-sm">Gerencie suas informações pessoais e preferências.</p>
|
<p className="text-zinc-500 dark:text-zinc-400 text-sm">Gerencie suas informações pessoais e preferências.</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-8">
|
<div className="grid grid-cols-1 md:grid-cols-3 gap-8">
|
||||||
{/* Left Column: Avatar & Basic Info */}
|
{/* Left Column: Avatar & Basic Info */}
|
||||||
<div className="md:col-span-1 space-y-6">
|
<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="bg-white dark:bg-zinc-900 p-6 rounded-2xl shadow-sm border border-zinc-200 dark:border-zinc-800 flex flex-col items-center text-center">
|
||||||
<div className="relative group cursor-pointer">
|
<input
|
||||||
<div className="w-32 h-32 rounded-full overflow-hidden border-4 border-slate-50 shadow-sm">
|
type="file"
|
||||||
<img src={user.avatar_url || `https://ui-avatars.com/api/?name=${encodeURIComponent(user.name)}&background=random`} alt={user.name} className="w-full h-full object-cover" />
|
ref={fileInputRef}
|
||||||
|
onChange={handleFileChange}
|
||||||
|
accept="image/jpeg,image/png,image/webp"
|
||||||
|
className="hidden"
|
||||||
|
/>
|
||||||
|
<div className="relative group cursor-pointer" onClick={handleAvatarClick}>
|
||||||
|
<div className="w-32 h-32 rounded-full overflow-hidden border-4 border-zinc-50 dark:border-zinc-800 shadow-sm bg-zinc-100 dark:bg-zinc-800 flex items-center justify-center">
|
||||||
|
{isUploading ? (
|
||||||
|
<Loader2 className="animate-spin text-zinc-400 dark:text-zinc-500" size={32} />
|
||||||
|
) : (
|
||||||
|
<img src={displayAvatar} alt={user.name} className="w-full h-full object-cover" />
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
<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">
|
<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} />
|
<Camera className="text-white" size={28} />
|
||||||
</div>
|
</div>
|
||||||
<button className="absolute bottom-0 right-2 bg-white text-slate-600 p-2 rounded-full shadow-md border border-slate-100 hover:text-blue-600 transition-colors">
|
<button className="absolute bottom-0 right-2 bg-white dark:bg-zinc-800 text-zinc-600 dark:text-zinc-400 p-2 rounded-full shadow-md border border-zinc-100 dark:border-zinc-700 hover:text-yellow-500 dark:hover:text-yellow-400 transition-colors">
|
||||||
<Camera size={16} />
|
<Camera size={16} />
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<h2 className="mt-4 text-lg font-bold text-slate-900">{user.name}</h2>
|
<h2 className="mt-4 text-lg font-bold text-zinc-900 dark:text-zinc-100">{user.name}</h2>
|
||||||
<p className="text-slate-500 text-sm">{user.email}</p>
|
<p className="text-zinc-500 dark:text-zinc-400 text-sm">{user.email}</p>
|
||||||
|
|
||||||
<div className="mt-4 flex flex-wrap justify-center gap-2">
|
<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">
|
<span className="px-3 py-1 bg-purple-100 text-purple-700 rounded-full text-xs font-semibold capitalize border border-purple-200 dark:bg-purple-900/30 dark:text-purple-400 dark:border-purple-800">
|
||||||
{user.role}
|
{user.role === 'admin' ? 'Admin' : user.role === 'manager' ? 'Gerente' : user.role === 'super_admin' ? 'Super Admin' : 'Agente'}
|
||||||
</span>
|
</span>
|
||||||
{user.team_id && (
|
{user.team_id && (
|
||||||
<span className="px-3 py-1 bg-blue-100 text-blue-700 rounded-full text-xs font-semibold border border-blue-200">
|
<span className="px-3 py-1 bg-blue-100 text-blue-700 rounded-full text-xs font-semibold border border-blue-200 dark:bg-blue-900/30 dark:text-blue-400 dark:border-blue-800">
|
||||||
{user.team_id === 'sales_1' ? 'Vendas Alpha' : user.team_id === 'sales_2' ? 'Vendas Beta' : user.team_id}
|
{tenant?.name ? `Time ${tenant.name}` : user.team_id}
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="bg-slate-100 rounded-xl p-4 border border-slate-200">
|
<div className="bg-zinc-100 dark:bg-zinc-900 rounded-xl p-4 border border-zinc-200 dark:border-zinc-800">
|
||||||
<h3 className="text-xs font-bold text-slate-500 uppercase tracking-wider mb-3">Status da Conta</h3>
|
<h3 className="text-xs font-bold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider mb-3">Status da Conta</h3>
|
||||||
<div className="flex items-center gap-3 text-sm text-slate-600 mb-2">
|
<div className="flex items-center gap-3 text-sm text-zinc-600 dark:text-zinc-300 mb-2">
|
||||||
<div className={`w-2 h-2 rounded-full ${user.status === 'active' ? 'bg-green-500' : 'bg-slate-400'}`}></div>
|
<div className={`w-2 h-2 rounded-full ${user.status === 'active' ? 'bg-green-500' : 'bg-zinc-400'}`}></div>
|
||||||
{user.status === 'active' ? 'Ativo' : 'Inativo'}
|
{user.status === 'active' ? 'Ativo' : 'Inativo'}
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center gap-3 text-sm text-slate-600">
|
<div className="flex items-center gap-3 text-sm text-zinc-600 dark:text-zinc-300">
|
||||||
<Building size={14} />
|
<Building size={14} />
|
||||||
{tenant?.name || 'Organização'}
|
{tenant?.name || 'Organização'}
|
||||||
</div>
|
</div>
|
||||||
@@ -118,11 +165,11 @@ export const UserProfile: React.FC = () => {
|
|||||||
|
|
||||||
{/* Right Column: Edit Form */}
|
{/* Right Column: Edit Form */}
|
||||||
<div className="md:col-span-2">
|
<div className="md:col-span-2">
|
||||||
<div className="bg-white rounded-2xl shadow-sm border border-slate-200 overflow-hidden">
|
<div className="bg-white dark:bg-zinc-900 rounded-2xl shadow-sm border border-zinc-200 dark:border-zinc-800 overflow-hidden">
|
||||||
<div className="px-6 py-4 border-b border-slate-100 bg-slate-50/50 flex justify-between items-center">
|
<div className="px-6 py-4 border-b border-zinc-100 dark:border-zinc-800 bg-zinc-50/50 dark:bg-zinc-900/50 flex justify-between items-center">
|
||||||
<h3 className="font-bold text-slate-800">Informações Pessoais</h3>
|
<h3 className="font-bold text-zinc-800 dark:text-zinc-100">Informações Pessoais</h3>
|
||||||
{isSuccess && (
|
{isSuccess && (
|
||||||
<span className="flex items-center gap-1.5 text-green-600 text-sm font-medium animate-in fade-in slide-in-from-right-4">
|
<span className="flex items-center gap-1.5 text-green-600 dark:text-green-400 text-sm font-medium animate-in fade-in slide-in-from-right-4">
|
||||||
<CheckCircle2 size={16} /> Salvo com sucesso
|
<CheckCircle2 size={16} /> Salvo com sucesso
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
@@ -131,63 +178,63 @@ export const UserProfile: React.FC = () => {
|
|||||||
<form onSubmit={handleSubmit} className="p-6 space-y-6">
|
<form onSubmit={handleSubmit} className="p-6 space-y-6">
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<label htmlFor="fullName" className="block text-sm font-medium text-slate-700">
|
<label htmlFor="fullName" className="block text-sm font-medium text-zinc-700 dark:text-zinc-300">
|
||||||
Nome Completo
|
Nome Completo
|
||||||
</label>
|
</label>
|
||||||
<div className="relative">
|
<div className="relative">
|
||||||
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
|
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
|
||||||
<UserIcon className="h-5 w-5 text-slate-400" />
|
<UserIcon className="h-5 w-5 text-zinc-400 dark:text-zinc-500" />
|
||||||
</div>
|
</div>
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
id="fullName"
|
id="fullName"
|
||||||
value={name}
|
value={name}
|
||||||
onChange={(e) => setName(e.target.value)}
|
onChange={(e) => setName(e.target.value)}
|
||||||
className="block w-full pl-10 pr-3 py-2 border border-slate-200 rounded-lg bg-white text-slate-900 placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-100 focus:border-blue-500 sm:text-sm transition-all"
|
className="block w-full pl-10 pr-3 py-2 border border-zinc-200 dark:border-zinc-800 rounded-lg bg-white dark:bg-zinc-950 text-zinc-900 dark:text-zinc-100 placeholder-zinc-400 dark:placeholder-zinc-600 focus:outline-none focus:ring-2 focus:ring-yellow-400/20 focus:border-yellow-400 transition-all sm:text-sm"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<label htmlFor="email" className="block text-sm font-medium text-slate-700">
|
<label htmlFor="email" className="block text-sm font-medium text-zinc-700 dark:text-zinc-300">
|
||||||
Endereço de E-mail
|
Endereço de E-mail
|
||||||
</label>
|
</label>
|
||||||
<div className="relative">
|
<div className="relative">
|
||||||
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
|
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
|
||||||
<Mail className="h-5 w-5 text-slate-400" />
|
<Mail className="h-5 w-5 text-zinc-400 dark:text-zinc-500" />
|
||||||
</div>
|
</div>
|
||||||
<input
|
<input
|
||||||
type="email"
|
type="email"
|
||||||
id="email"
|
id="email"
|
||||||
value={user.email}
|
value={user.email}
|
||||||
disabled
|
disabled
|
||||||
className="block w-full pl-10 pr-3 py-2 border border-slate-200 rounded-lg bg-slate-50 text-slate-500 cursor-not-allowed sm:text-sm"
|
className="block w-full pl-10 pr-3 py-2 border border-zinc-200 dark:border-zinc-800 rounded-lg bg-zinc-50 dark:bg-zinc-900/50 text-zinc-500 dark:text-zinc-500 cursor-not-allowed sm:text-sm"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<p className="text-xs text-slate-400 mt-1">Contate o admin para alterar o e-mail.</p>
|
<p className="text-xs text-zinc-400 dark:text-zinc-500 mt-1">Contate o admin para alterar o e-mail.</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<label htmlFor="role" className="block text-sm font-medium text-slate-700">
|
<label htmlFor="role" className="block text-sm font-medium text-zinc-700 dark:text-zinc-300">
|
||||||
Função e Permissões
|
Função e Permissões
|
||||||
</label>
|
</label>
|
||||||
<div className="relative">
|
<div className="relative">
|
||||||
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
|
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
|
||||||
<Shield className="h-5 w-5 text-slate-400" />
|
<Shield className="h-5 w-5 text-zinc-400 dark:text-zinc-500" />
|
||||||
</div>
|
</div>
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
id="role"
|
id="role"
|
||||||
value={user.role.charAt(0).toUpperCase() + user.role.slice(1)}
|
value={user.role === 'admin' ? 'Administrador' : user.role === 'manager' ? 'Gerente' : user.role === 'super_admin' ? 'Super Admin' : 'Agente'}
|
||||||
disabled
|
disabled
|
||||||
className="block w-full pl-10 pr-3 py-2 border border-slate-200 rounded-lg bg-slate-50 text-slate-500 cursor-not-allowed sm:text-sm"
|
className="block w-full pl-10 pr-3 py-2 border border-zinc-200 dark:border-zinc-800 rounded-lg bg-zinc-50 dark:bg-zinc-900/50 text-zinc-500 dark:text-zinc-500 cursor-not-allowed sm:text-sm"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<label htmlFor="bio" className="block text-sm font-medium text-slate-700">
|
<label htmlFor="bio" className="block text-sm font-medium text-zinc-700 dark:text-zinc-300">
|
||||||
Bio / Descrição
|
Bio / Descrição
|
||||||
</label>
|
</label>
|
||||||
<textarea
|
<textarea
|
||||||
@@ -195,27 +242,27 @@ export const UserProfile: React.FC = () => {
|
|||||||
rows={4}
|
rows={4}
|
||||||
value={bio}
|
value={bio}
|
||||||
onChange={(e) => setBio(e.target.value)}
|
onChange={(e) => setBio(e.target.value)}
|
||||||
className="block w-full p-3 border border-slate-200 rounded-lg text-slate-900 placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-100 focus:border-blue-500 sm:text-sm transition-all resize-none"
|
className="block w-full p-3 border border-zinc-200 dark:border-zinc-800 rounded-lg bg-white dark:bg-zinc-950 text-zinc-900 dark:text-zinc-100 placeholder-zinc-400 dark:placeholder-zinc-600 focus:outline-none focus:ring-2 focus:ring-yellow-400/20 focus:border-yellow-400 transition-all sm:text-sm resize-none"
|
||||||
placeholder="Escreva uma breve descrição sobre você..."
|
placeholder="Escreva uma breve descrição sobre você..."
|
||||||
/>
|
/>
|
||||||
<p className="text-xs text-slate-400 text-right">{bio.length}/500 caracteres</p>
|
<p className="text-xs text-zinc-400 dark:text-zinc-500 text-right">{bio.length}/500 caracteres</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="pt-4 flex items-center justify-end border-t border-slate-100 mt-6">
|
<div className="pt-4 flex items-center justify-end border-t border-zinc-100 dark:border-zinc-800 mt-6 transition-colors">
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
setName(user.name);
|
setName(user.name);
|
||||||
setBio(user.bio || '');
|
setBio(user.bio || '');
|
||||||
}}
|
}}
|
||||||
className="mr-3 px-4 py-2 text-sm font-medium text-slate-600 hover:text-slate-800 hover:bg-slate-50 rounded-lg transition-colors"
|
className="mr-3 px-4 py-2 text-sm font-medium text-zinc-600 dark:text-zinc-400 hover:text-zinc-800 dark:hover:text-zinc-200 hover:bg-zinc-50 dark:hover:bg-zinc-800 rounded-lg transition-colors"
|
||||||
>
|
>
|
||||||
Desfazer Alterações
|
Desfazer Alterações
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
type="submit"
|
type="submit"
|
||||||
disabled={isLoading}
|
disabled={isLoading}
|
||||||
className="flex items-center gap-2 bg-slate-900 text-white px-6 py-2 rounded-lg text-sm font-medium hover:bg-slate-800 focus:ring-2 focus:ring-offset-2 focus:ring-slate-900 transition-all disabled:opacity-70 disabled:cursor-not-allowed"
|
className="flex items-center gap-2 bg-zinc-900 dark:bg-yellow-400 text-white dark:text-zinc-950 px-6 py-2 rounded-lg text-sm font-medium hover:bg-zinc-800 dark:hover:opacity-90 focus:ring-2 focus:ring-offset-2 focus:ring-zinc-900 dark:focus:ring-yellow-400 transition-all disabled:opacity-70 disabled:cursor-not-allowed"
|
||||||
>
|
>
|
||||||
{isLoading ? (
|
{isLoading ? (
|
||||||
<>
|
<>
|
||||||
|
|||||||
@@ -1,35 +1,27 @@
|
|||||||
import React, { useState, useEffect } from 'react';
|
import React, { useState } from 'react';
|
||||||
import { useNavigate, Link } from 'react-router-dom';
|
import { useNavigate, Link, useLocation } from 'react-router-dom';
|
||||||
import { Hexagon, ShieldCheck, ArrowRight, Loader2 } from 'lucide-react';
|
import { Hexagon, ArrowRight, Loader2, AlertCircle, CheckCircle2 } from 'lucide-react';
|
||||||
import { verifyCode } from '../services/dataService';
|
import { verifyCode } from '../services/dataService';
|
||||||
|
|
||||||
export const VerifyCode: React.FC = () => {
|
export const VerifyCode: React.FC = () => {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
const location = useLocation();
|
||||||
|
const email = location.state?.email || '';
|
||||||
const [code, setCode] = useState('');
|
const [code, setCode] = useState('');
|
||||||
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
const [error, setError] = useState('');
|
const [error, setError] = useState('');
|
||||||
const [email, setEmail] = useState('');
|
|
||||||
|
|
||||||
useEffect(() => {
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
const storedEmail = localStorage.getItem('pending_verify_email');
|
|
||||||
if (!storedEmail) {
|
|
||||||
navigate('/register');
|
|
||||||
} else {
|
|
||||||
setEmail(storedEmail);
|
|
||||||
}
|
|
||||||
}, [navigate]);
|
|
||||||
|
|
||||||
const handleVerify = async (e: React.FormEvent) => {
|
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
|
if (!email) { setError('E-mail não encontrado. Tente registrar novamente.'); return; }
|
||||||
|
|
||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
setError('');
|
setError('');
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const success = await verifyCode({ email, code });
|
const success = await verifyCode({ email, code });
|
||||||
if (success) {
|
if (success) {
|
||||||
localStorage.removeItem('pending_verify_email');
|
navigate('/login', { state: { message: 'E-mail verificado com sucesso! Agora você pode entrar.' } });
|
||||||
alert('Conta verificada com sucesso! Agora você pode fazer login.');
|
|
||||||
navigate('/login');
|
|
||||||
}
|
}
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
setError(err.message || 'Código inválido ou expirado.');
|
setError(err.message || 'Código inválido ou expirado.');
|
||||||
@@ -39,28 +31,34 @@ export const VerifyCode: React.FC = () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-slate-50 flex flex-col justify-center py-12 sm:px-6 lg:px-8">
|
<div className="min-h-screen bg-zinc-50 dark:bg-dark-bg flex flex-col justify-center py-12 sm:px-6 lg:px-8 transition-colors duration-300">
|
||||||
<div className="sm:mx-auto sm:w-full sm:max-w-md">
|
<div className="sm:mx-auto sm:w-full sm:max-w-md">
|
||||||
<div className="flex justify-center items-center gap-2 text-slate-900">
|
<div className="flex justify-center items-center gap-2 text-zinc-900 dark:text-zinc-50">
|
||||||
<div className="bg-slate-900 text-white p-2 rounded-lg">
|
<div className="bg-zinc-900 dark:bg-brand-yellow text-white dark:text-zinc-950 p-2 rounded-lg transition-colors">
|
||||||
<Hexagon size={28} fill="currentColor" />
|
<Hexagon size={32} fill="currentColor" />
|
||||||
</div>
|
</div>
|
||||||
<span className="text-3xl font-bold tracking-tight">Fasto<span className="text-yellow-500">.</span></span>
|
<span className="text-3xl font-bold tracking-tight">Fasto<span className="text-brand-yellow">.</span></span>
|
||||||
</div>
|
</div>
|
||||||
<h2 className="mt-6 text-center text-3xl font-bold tracking-tight text-slate-900">
|
<h2 className="mt-6 text-center text-3xl font-bold tracking-tight text-zinc-900 dark:text-zinc-50">
|
||||||
Verifique seu e-mail
|
Verifique seu e-mail
|
||||||
</h2>
|
</h2>
|
||||||
<p className="mt-2 text-center text-sm text-slate-600 px-4">
|
<p className="mt-2 text-center text-sm text-zinc-600 dark:text-dark-muted px-4">
|
||||||
Enviamos um código de 6 dígitos para <strong>{email}</strong>. Por favor, insira-o abaixo.
|
Insira o código de 6 dígitos enviado para <span className="font-semibold text-zinc-900 dark:text-zinc-200">{email}</span>
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="mt-8 sm:mx-auto sm:w-full sm:max-w-md">
|
<div className="mt-8 sm:mx-auto sm:w-full sm:max-w-md">
|
||||||
<div className="bg-white py-8 px-4 shadow-xl shadow-slate-200/50 rounded-2xl sm:px-10 border border-slate-100">
|
<div className="bg-white dark:bg-dark-card py-8 px-4 shadow-xl rounded-2xl sm:px-10 border border-zinc-100 dark:border-dark-border transition-colors">
|
||||||
|
<form className="space-y-6" onSubmit={handleSubmit}>
|
||||||
|
{error && (
|
||||||
|
<div className="bg-red-50 dark:bg-red-900/20 border border-red-100 dark:border-red-900/30 p-3 rounded-lg text-red-600 dark:text-red-400 text-sm">
|
||||||
|
<AlertCircle size={18} />
|
||||||
|
{error}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
<form className="space-y-6" onSubmit={handleVerify}>
|
|
||||||
<div>
|
<div>
|
||||||
<label htmlFor="code" className="block text-sm font-medium text-slate-700 text-center mb-4">
|
<label htmlFor="code" className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 text-center mb-4">
|
||||||
Código de Verificação
|
Código de Verificação
|
||||||
</label>
|
</label>
|
||||||
<input
|
<input
|
||||||
@@ -69,32 +67,23 @@ export const VerifyCode: React.FC = () => {
|
|||||||
maxLength={6}
|
maxLength={6}
|
||||||
required
|
required
|
||||||
value={code}
|
value={code}
|
||||||
onChange={(e) => setCode(e.target.value.replace(/\D/g, ''))}
|
onChange={(e) => setCode(e.target.value.replace(/[^0-9]/g, ''))}
|
||||||
className="block w-full text-center text-3xl tracking-[0.5em] font-bold py-3 border border-slate-300 rounded-lg bg-slate-50 focus:outline-none focus:ring-2 focus:ring-blue-100 focus:border-blue-500 transition-all"
|
className="block w-full text-center text-3xl tracking-[0.5em] font-bold py-3 border border-zinc-300 dark:border-dark-border rounded-lg bg-zinc-50 dark:bg-dark-input text-zinc-900 dark:text-zinc-100 focus:outline-none focus:ring-2 focus:ring-brand-yellow/20 focus:border-brand-yellow transition-all"
|
||||||
placeholder="000000"
|
placeholder="000000"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{error && (
|
|
||||||
<div className="text-red-500 text-sm font-medium text-center">
|
|
||||||
{error}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<button
|
<button
|
||||||
type="submit"
|
type="submit"
|
||||||
disabled={isLoading || code.length !== 6}
|
disabled={isLoading || code.length < 6}
|
||||||
className="w-full flex justify-center items-center gap-2 py-2.5 px-4 border border-transparent rounded-lg shadow-sm text-sm font-semibold text-white bg-slate-900 hover:bg-slate-800 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-slate-900 disabled:opacity-70 disabled:cursor-not-allowed transition-all"
|
className="w-full flex justify-center items-center gap-2 py-2.5 px-4 border border-transparent rounded-lg shadow-sm text-sm font-bold text-zinc-950 bg-brand-yellow hover:bg-yellow-500 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-brand-yellow disabled:opacity-70 disabled:cursor-not-allowed transition-all"
|
||||||
>
|
>
|
||||||
{isLoading ? (
|
{isLoading ? (
|
||||||
<>
|
<Loader2 className="animate-spin h-5 w-5" />
|
||||||
<Loader2 className="animate-spin h-4 w-4" />
|
|
||||||
Verificando...
|
|
||||||
</>
|
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
Verificar Código <ShieldCheck className="h-4 w-4" />
|
Verificar Código <ArrowRight size={18} />
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</button>
|
</button>
|
||||||
@@ -103,10 +92,11 @@ export const VerifyCode: React.FC = () => {
|
|||||||
|
|
||||||
<div className="mt-6 text-center">
|
<div className="mt-6 text-center">
|
||||||
<button
|
<button
|
||||||
|
type="button"
|
||||||
|
className="text-sm font-medium text-brand-yellow hover:text-yellow-600 transition-colors"
|
||||||
onClick={() => navigate('/register')}
|
onClick={() => navigate('/register')}
|
||||||
className="text-sm text-slate-500 hover:text-slate-800"
|
|
||||||
>
|
>
|
||||||
Alterar e-mail ou voltar ao registro
|
Voltar e corrigir e-mail
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -6,6 +6,17 @@ import { Attendance, DashboardFilter, User } from '../types';
|
|||||||
// Em desenvolvimento, aponta para o localhost:3001
|
// Em desenvolvimento, aponta para o localhost:3001
|
||||||
const API_URL = import.meta.env.PROD ? '/api' : 'http://localhost:3001/api';
|
const API_URL = import.meta.env.PROD ? '/api' : 'http://localhost:3001/api';
|
||||||
|
|
||||||
|
const getHeaders = () => {
|
||||||
|
const token = localStorage.getItem('ctms_token');
|
||||||
|
// Evitar enviar "undefined" ou "null" como strings se o localStorage estiver corrompido
|
||||||
|
if (!token || token === 'undefined' || token === 'null') return { 'Content-Type': 'application/json' };
|
||||||
|
|
||||||
|
return {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Authorization': `Bearer ${token}`
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
export const getAttendances = async (tenantId: string, filter: DashboardFilter): Promise<Attendance[]> => {
|
export const getAttendances = async (tenantId: string, filter: DashboardFilter): Promise<Attendance[]> => {
|
||||||
try {
|
try {
|
||||||
const params = new URLSearchParams();
|
const params = new URLSearchParams();
|
||||||
@@ -16,8 +27,12 @@ export const getAttendances = async (tenantId: string, filter: DashboardFilter):
|
|||||||
|
|
||||||
if (filter.userId && filter.userId !== 'all') params.append('userId', filter.userId);
|
if (filter.userId && filter.userId !== 'all') params.append('userId', filter.userId);
|
||||||
if (filter.teamId && filter.teamId !== 'all') params.append('teamId', filter.teamId);
|
if (filter.teamId && filter.teamId !== 'all') params.append('teamId', filter.teamId);
|
||||||
|
if (filter.funnelStage && filter.funnelStage !== 'all') params.append('funnelStage', filter.funnelStage);
|
||||||
|
if (filter.origin && filter.origin !== 'all') params.append('origin', filter.origin);
|
||||||
|
|
||||||
const response = await fetch(`${API_URL}/attendances?${params.toString()}`);
|
const response = await fetch(`${API_URL}/attendances?${params.toString()}`, {
|
||||||
|
headers: getHeaders()
|
||||||
|
});
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
throw new Error('Falha ao buscar atendimentos do servidor');
|
throw new Error('Falha ao buscar atendimentos do servidor');
|
||||||
@@ -36,7 +51,9 @@ export const getUsers = async (tenantId: string): Promise<User[]> => {
|
|||||||
const params = new URLSearchParams();
|
const params = new URLSearchParams();
|
||||||
if (tenantId !== 'all') params.append('tenantId', tenantId);
|
if (tenantId !== 'all') params.append('tenantId', tenantId);
|
||||||
|
|
||||||
const response = await fetch(`${API_URL}/users?${params.toString()}`);
|
const response = await fetch(`${API_URL}/users?${params.toString()}`, {
|
||||||
|
headers: getHeaders()
|
||||||
|
});
|
||||||
if (!response.ok) throw new Error('Falha ao buscar usuários');
|
if (!response.ok) throw new Error('Falha ao buscar usuários');
|
||||||
|
|
||||||
return await response.json();
|
return await response.json();
|
||||||
@@ -48,7 +65,9 @@ export const getUsers = async (tenantId: string): Promise<User[]> => {
|
|||||||
|
|
||||||
export const getUserById = async (id: string): Promise<User | undefined> => {
|
export const getUserById = async (id: string): Promise<User | undefined> => {
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`${API_URL}/users/${id}`);
|
const response = await fetch(`${API_URL}/users/${id}`, {
|
||||||
|
headers: getHeaders()
|
||||||
|
});
|
||||||
if (!response.ok) return undefined;
|
if (!response.ok) return undefined;
|
||||||
|
|
||||||
const contentType = response.headers.get("content-type");
|
const contentType = response.headers.get("content-type");
|
||||||
@@ -66,7 +85,7 @@ export const updateUser = async (id: string, userData: any): Promise<boolean> =>
|
|||||||
try {
|
try {
|
||||||
const response = await fetch(`${API_URL}/users/${id}`, {
|
const response = await fetch(`${API_URL}/users/${id}`, {
|
||||||
method: 'PUT',
|
method: 'PUT',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: getHeaders(),
|
||||||
body: JSON.stringify(userData)
|
body: JSON.stringify(userData)
|
||||||
});
|
});
|
||||||
return response.ok;
|
return response.ok;
|
||||||
@@ -76,11 +95,34 @@ export const updateUser = async (id: string, userData: any): Promise<boolean> =>
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const uploadAvatar = async (id: string, file: File): Promise<string | null> => {
|
||||||
|
try {
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append('avatar', file);
|
||||||
|
|
||||||
|
const token = localStorage.getItem('ctms_token');
|
||||||
|
const response = await fetch(`${API_URL}/users/${id}/avatar`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
...(token ? { 'Authorization': `Bearer ${token}` } : {})
|
||||||
|
},
|
||||||
|
body: formData
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) throw new Error('Falha no upload');
|
||||||
|
const data = await response.json();
|
||||||
|
return data.avatarUrl;
|
||||||
|
} catch (error) {
|
||||||
|
console.error("API Error (uploadAvatar):", error);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
export const createMember = async (userData: any): Promise<boolean> => {
|
export const createMember = async (userData: any): Promise<boolean> => {
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`${API_URL}/users`, {
|
const response = await fetch(`${API_URL}/users`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: getHeaders(),
|
||||||
body: JSON.stringify(userData)
|
body: JSON.stringify(userData)
|
||||||
});
|
});
|
||||||
return response.ok;
|
return response.ok;
|
||||||
@@ -93,7 +135,8 @@ export const createMember = async (userData: any): Promise<boolean> => {
|
|||||||
export const deleteUser = async (id: string): Promise<boolean> => {
|
export const deleteUser = async (id: string): Promise<boolean> => {
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`${API_URL}/users/${id}`, {
|
const response = await fetch(`${API_URL}/users/${id}`, {
|
||||||
method: 'DELETE'
|
method: 'DELETE',
|
||||||
|
headers: getHeaders()
|
||||||
});
|
});
|
||||||
return response.ok;
|
return response.ok;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -104,7 +147,9 @@ export const deleteUser = async (id: string): Promise<boolean> => {
|
|||||||
|
|
||||||
export const getAttendanceById = async (id: string): Promise<Attendance | undefined> => {
|
export const getAttendanceById = async (id: string): Promise<Attendance | undefined> => {
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`${API_URL}/attendances/${id}`);
|
const response = await fetch(`${API_URL}/attendances/${id}`, {
|
||||||
|
headers: getHeaders()
|
||||||
|
});
|
||||||
if (!response.ok) return undefined;
|
if (!response.ok) return undefined;
|
||||||
|
|
||||||
const contentType = response.headers.get("content-type");
|
const contentType = response.headers.get("content-type");
|
||||||
@@ -120,7 +165,9 @@ export const getAttendanceById = async (id: string): Promise<Attendance | undefi
|
|||||||
|
|
||||||
export const getTenants = async (): Promise<any[]> => {
|
export const getTenants = async (): Promise<any[]> => {
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`${API_URL}/tenants`);
|
const response = await fetch(`${API_URL}/tenants`, {
|
||||||
|
headers: getHeaders()
|
||||||
|
});
|
||||||
if (!response.ok) throw new Error('Falha ao buscar tenants');
|
if (!response.ok) throw new Error('Falha ao buscar tenants');
|
||||||
|
|
||||||
const contentType = response.headers.get("content-type");
|
const contentType = response.headers.get("content-type");
|
||||||
@@ -136,7 +183,9 @@ export const getTenants = async (): Promise<any[]> => {
|
|||||||
|
|
||||||
export const getTeams = async (tenantId: string): Promise<any[]> => {
|
export const getTeams = async (tenantId: string): Promise<any[]> => {
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`${API_URL}/teams?tenantId=${tenantId}`);
|
const response = await fetch(`${API_URL}/teams?tenantId=${tenantId}`, {
|
||||||
|
headers: getHeaders()
|
||||||
|
});
|
||||||
if (!response.ok) throw new Error('Falha ao buscar equipes');
|
if (!response.ok) throw new Error('Falha ao buscar equipes');
|
||||||
return await response.json();
|
return await response.json();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -149,7 +198,7 @@ export const createTeam = async (teamData: any): Promise<boolean> => {
|
|||||||
try {
|
try {
|
||||||
const response = await fetch(`${API_URL}/teams`, {
|
const response = await fetch(`${API_URL}/teams`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: getHeaders(),
|
||||||
body: JSON.stringify(teamData)
|
body: JSON.stringify(teamData)
|
||||||
});
|
});
|
||||||
return response.ok;
|
return response.ok;
|
||||||
@@ -163,7 +212,7 @@ export const updateTeam = async (id: string, teamData: any): Promise<boolean> =>
|
|||||||
try {
|
try {
|
||||||
const response = await fetch(`${API_URL}/teams/${id}`, {
|
const response = await fetch(`${API_URL}/teams/${id}`, {
|
||||||
method: 'PUT',
|
method: 'PUT',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: getHeaders(),
|
||||||
body: JSON.stringify(teamData)
|
body: JSON.stringify(teamData)
|
||||||
});
|
});
|
||||||
return response.ok;
|
return response.ok;
|
||||||
@@ -177,7 +226,7 @@ export const createTenant = async (tenantData: any): Promise<boolean> => {
|
|||||||
try {
|
try {
|
||||||
const response = await fetch(`${API_URL}/tenants`, {
|
const response = await fetch(`${API_URL}/tenants`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: getHeaders(),
|
||||||
body: JSON.stringify(tenantData)
|
body: JSON.stringify(tenantData)
|
||||||
});
|
});
|
||||||
return response.ok;
|
return response.ok;
|
||||||
@@ -189,6 +238,12 @@ export const createTenant = async (tenantData: any): Promise<boolean> => {
|
|||||||
|
|
||||||
// --- Auth Functions ---
|
// --- Auth Functions ---
|
||||||
|
|
||||||
|
export const logout = () => {
|
||||||
|
localStorage.removeItem('ctms_token');
|
||||||
|
localStorage.removeItem('ctms_user_id');
|
||||||
|
localStorage.removeItem('ctms_tenant_id');
|
||||||
|
};
|
||||||
|
|
||||||
export const login = async (credentials: any): Promise<any> => {
|
export const login = async (credentials: any): Promise<any> => {
|
||||||
const response = await fetch(`${API_URL}/auth/login`, {
|
const response = await fetch(`${API_URL}/auth/login`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
@@ -204,7 +259,13 @@ export const login = async (credentials: any): Promise<any> => {
|
|||||||
throw new Error(error.error || 'Erro no login');
|
throw new Error(error.error || 'Erro no login');
|
||||||
}
|
}
|
||||||
|
|
||||||
return isJson ? await response.json() : null;
|
const data = isJson ? await response.json() : null;
|
||||||
|
if (data && data.token) {
|
||||||
|
localStorage.setItem('ctms_token', data.token);
|
||||||
|
localStorage.setItem('ctms_user_id', data.user.id);
|
||||||
|
localStorage.setItem('ctms_tenant_id', data.user.tenant_id || '');
|
||||||
|
}
|
||||||
|
return data;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const register = async (userData: any): Promise<boolean> => {
|
export const register = async (userData: any): Promise<boolean> => {
|
||||||
|
|||||||
@@ -11,7 +11,8 @@
|
|||||||
],
|
],
|
||||||
"skipLibCheck": true,
|
"skipLibCheck": true,
|
||||||
"types": [
|
"types": [
|
||||||
"node"
|
"node",
|
||||||
|
"vite/client"
|
||||||
],
|
],
|
||||||
"moduleResolution": "bundler",
|
"moduleResolution": "bundler",
|
||||||
"isolatedModules": true,
|
"isolatedModules": true,
|
||||||
|
|||||||
4
types.ts
4
types.ts
@@ -31,7 +31,7 @@ export interface Attendance {
|
|||||||
first_response_time_min: number;
|
first_response_time_min: number;
|
||||||
handling_time_min: number;
|
handling_time_min: number;
|
||||||
funnel_stage: FunnelStage;
|
funnel_stage: FunnelStage;
|
||||||
origin: 'WhatsApp' | 'Instagram' | 'Website' | 'LinkedIn' | 'Referral';
|
origin: 'WhatsApp' | 'Instagram' | 'Website' | 'LinkedIn' | 'Indicação';
|
||||||
product_requested: string;
|
product_requested: string;
|
||||||
product_sold?: string;
|
product_sold?: string;
|
||||||
converted: boolean;
|
converted: boolean;
|
||||||
@@ -59,4 +59,6 @@ export interface DashboardFilter {
|
|||||||
dateRange: DateRange;
|
dateRange: DateRange;
|
||||||
userId?: string;
|
userId?: string;
|
||||||
teamId?: string;
|
teamId?: string;
|
||||||
|
funnelStage?: string;
|
||||||
|
origin?: string;
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user