feat: complete UI/UX refinement, email flow updates, and deep black theme
All checks were successful
Build and Deploy / build-and-push (push) Successful in 2m18s
All checks were successful
Build and Deploy / build-and-push (push) Successful in 2m18s
- Updated all email templates to a clean light theme and changed button text to 'Finalizar Cadastro'. - Enforced a strict 15-minute expiration on all auth/reset tokens. - Created SetupAccount flow distinct from ResetPassword to capture user name during admin init. - Refined dark mode to a premium True Black (Onyx) palette using Zinc. - Fixed Dashboard KPI visibility and true period-over-period trend logic. - Enhanced TeamManagement with global tenant filtering for Super Admins. - Implemented secure User URL routing via slugs instead of raw UUIDs. - Enforced strict Agent-level RBAC for viewing attendances.
This commit is contained in:
@@ -147,6 +147,7 @@ CREATE TABLE `users` (
|
||||
`name` varchar(255) NOT NULL,
|
||||
`email` varchar(255) NOT NULL,
|
||||
`password_hash` varchar(255) NOT NULL DEFAULT 'hash_placeholder',
|
||||
`slug` varchar(255) UNIQUE DEFAULT NULL,
|
||||
`avatar_url` text,
|
||||
`role` enum('super_admin','admin','manager','agent') NOT NULL DEFAULT 'agent',
|
||||
`bio` text,
|
||||
|
||||
@@ -203,7 +203,7 @@ apiRouter.post('/auth/forgot-password', async (req, res) => {
|
||||
const [users] = await pool.query('SELECT name FROM users WHERE email = ?', [email]);
|
||||
if (users.length > 0) {
|
||||
const token = crypto.randomBytes(32).toString('hex');
|
||||
await pool.query('INSERT INTO password_resets (email, token, expires_at) VALUES (?, ?, DATE_ADD(NOW(), INTERVAL 1 HOUR))', [email, token]);
|
||||
await pool.query('INSERT INTO password_resets (email, token, expires_at) VALUES (?, ?, DATE_ADD(NOW(), INTERVAL 15 MINUTE))', [email, token]);
|
||||
const link = `${process.env.APP_URL || 'http://localhost:3001'}/#/reset-password?token=${token}`;
|
||||
|
||||
const mailOptions = {
|
||||
@@ -218,7 +218,7 @@ apiRouter.post('/auth/forgot-password', async (req, res) => {
|
||||
<div style="text-align: center; margin: 30px 0;">
|
||||
<a href="${link}" style="background-color: #0f172a; color: white; padding: 12px 24px; text-decoration: none; border-radius: 8px; font-weight: bold; display: inline-block;">Redefinir Minha Senha</a>
|
||||
</div>
|
||||
<p style="font-size: 12px; color: #94a3b8;">Este link expira em 1 hora. Se você não solicitou isso, pode ignorar este e-mail.</p>
|
||||
<p style="font-size: 12px; color: #94a3b8;">Este link expira em 15 minutos. Se você não solicitou isso, pode ignorar este e-mail.</p>
|
||||
<div style="border-top: 1px solid #f1f5f9; margin-top: 20px; padding-top: 20px; text-align: center;">
|
||||
<p style="font-size: 12px; color: #94a3b8;">Desenvolvido por <a href="https://blyzer.com.br" style="color: #3b82f6; text-decoration: none;">Blyzer</a></p>
|
||||
</div>
|
||||
@@ -236,14 +236,23 @@ apiRouter.post('/auth/forgot-password', async (req, res) => {
|
||||
|
||||
// Reset Password
|
||||
apiRouter.post('/auth/reset-password', async (req, res) => {
|
||||
const { token, password } = req.body;
|
||||
const { token, password, name } = req.body;
|
||||
try {
|
||||
const [resets] = await pool.query('SELECT email FROM password_resets WHERE token = ? AND expires_at > NOW()', [token]);
|
||||
if (resets.length === 0) return res.status(400).json({ error: 'Token inválido.' });
|
||||
if (resets.length === 0) return res.status(400).json({ error: 'Token inválido ou expirado.' });
|
||||
|
||||
const hash = await bcrypt.hash(password, 10);
|
||||
await pool.query('UPDATE users SET password_hash = ? WHERE email = ?', [hash, resets[0].email]);
|
||||
|
||||
if (name) {
|
||||
// If a name is provided (like in the initial admin setup flow), update it along with the password
|
||||
await pool.query('UPDATE users SET password_hash = ?, name = ? WHERE email = ?', [hash, name, resets[0].email]);
|
||||
} else {
|
||||
// Standard password reset, just update the hash
|
||||
await pool.query('UPDATE users SET password_hash = ? WHERE email = ?', [hash, resets[0].email]);
|
||||
}
|
||||
|
||||
await pool.query('DELETE FROM password_resets WHERE email = ?', [resets[0].email]);
|
||||
res.json({ message: 'Senha resetada.' });
|
||||
res.json({ message: 'Senha e perfil atualizados com sucesso.' });
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
@@ -263,9 +272,9 @@ apiRouter.get('/users', async (req, res) => {
|
||||
} catch (error) { res.status(500).json({ error: error.message }); }
|
||||
});
|
||||
|
||||
apiRouter.get('/users/:id', async (req, res) => {
|
||||
apiRouter.get('/users/:idOrSlug', async (req, res) => {
|
||||
try {
|
||||
const [rows] = await pool.query('SELECT * FROM users WHERE id = ?', [req.params.id]);
|
||||
const [rows] = await pool.query('SELECT * FROM users WHERE id = ? OR slug = ?', [req.params.idOrSlug, req.params.idOrSlug]);
|
||||
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.' });
|
||||
@@ -295,33 +304,32 @@ apiRouter.post('/users', requireRole(['admin', 'owner', 'super_admin']), async (
|
||||
// 3. Gerar Token de Setup de Senha (reusando lógica de reset)
|
||||
const token = crypto.randomBytes(32).toString('hex');
|
||||
await pool.query(
|
||||
'INSERT INTO password_resets (email, token, expires_at) VALUES (?, ?, DATE_ADD(NOW(), INTERVAL 24 HOUR))',
|
||||
'INSERT INTO password_resets (email, token, expires_at) VALUES (?, ?, DATE_ADD(NOW(), INTERVAL 15 MINUTE))',
|
||||
[email, token]
|
||||
);
|
||||
|
||||
// 4. Enviar E-mail de Boas-vindas
|
||||
const setupLink = `${process.env.APP_URL || 'http://localhost:3001'}/#/reset-password?token=${token}`;
|
||||
|
||||
|
||||
await transporter.sendMail({
|
||||
from: `"Fasto" <${process.env.MAIL_FROM || 'nao-responda@blyzer.com.br'}>`,
|
||||
to: email,
|
||||
subject: 'Bem-vindo ao Fasto - Crie sua senha',
|
||||
subject: 'Bem-vindo ao Fasto - Finalize seu cadastro',
|
||||
html: `
|
||||
<div style="font-family: sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #e2e8f0; border-radius: 12px;">
|
||||
<div style="font-family: sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #e2e8f0; border-radius: 12px; background: #ffffff; color: #0f172a;">
|
||||
<h2 style="color: #0f172a;">Olá, ${name}!</h2>
|
||||
<p style="color: #475569;">Você foi convidado para participar da equipe no Fasto.</p>
|
||||
<p style="color: #475569;">Clique no botão abaixo para definir sua senha e acessar sua conta:</p>
|
||||
<div style="text-align: center; margin: 30px 0;">
|
||||
<a href="${setupLink}" style="background-color: #0f172a; color: white; padding: 12px 24px; text-decoration: none; border-radius: 8px; font-weight: bold; display: inline-block;">Definir Minha Senha</a>
|
||||
<a href="${setupLink}" style="background-color: #0f172a; color: white; padding: 12px 24px; text-decoration: none; border-radius: 8px; font-weight: bold; display: inline-block;">Finalizar Cadastro</a>
|
||||
</div>
|
||||
<p style="font-size: 12px; color: #94a3b8;">Este link expira em 24 horas. Se você não esperava este convite, ignore este e-mail.</p>
|
||||
<p style="font-size: 12px; color: #94a3b8;">Este link expira em 15 minutos. Se você não esperava este convite, ignore este e-mail.</p>
|
||||
<div style="border-top: 1px solid #f1f5f9; margin-top: 20px; padding-top: 20px; text-align: center;">
|
||||
<p style="font-size: 12px; color: #94a3b8;">Desenvolvido por <a href="https://blyzer.com.br" style="color: #3b82f6; text-decoration: none;">Blyzer</a></p>
|
||||
</div>
|
||||
</div>
|
||||
`
|
||||
});
|
||||
|
||||
res.status(201).json({ id: uid, message: 'Convite enviado com sucesso.' });
|
||||
} catch (error) {
|
||||
console.error('Invite error:', error);
|
||||
@@ -406,8 +414,23 @@ apiRouter.get('/attendances', async (req, res) => {
|
||||
|
||||
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 = [effectiveTenantId];
|
||||
|
||||
if (startDate && endDate) { q += ' AND a.created_at BETWEEN ? AND ?'; params.push(new Date(startDate), new Date(endDate)); }
|
||||
if (userId && userId !== 'all') { q += ' AND a.user_id = ?'; params.push(userId); }
|
||||
|
||||
// Strict RBAC: Agents can ONLY see their own data, regardless of what they request
|
||||
if (req.user.role === 'agent') {
|
||||
q += ' AND a.user_id = ?';
|
||||
params.push(req.user.id);
|
||||
} else if (userId && userId !== 'all') {
|
||||
// check if it's a slug or id
|
||||
if (userId.startsWith('u_')) {
|
||||
q += ' AND a.user_id = ?';
|
||||
params.push(userId);
|
||||
} else {
|
||||
q += ' AND u.slug = ?';
|
||||
params.push(userId);
|
||||
}
|
||||
}
|
||||
if (teamId && teamId !== 'all') { q += ' AND u.team_id = ?'; params.push(teamId); }
|
||||
if (funnelStage && funnelStage !== 'all') { q += ' AND a.funnel_stage = ?'; params.push(funnelStage); }
|
||||
if (origin && origin !== 'all') { q += ' AND a.origin = ?'; params.push(origin); }
|
||||
@@ -525,19 +548,32 @@ apiRouter.post('/tenants', requireRole(['super_admin']), async (req, res) => {
|
||||
await connection.query('INSERT INTO users (id, tenant_id, name, email, password_hash, role) VALUES (?, ?, ?, ?, ?, ?)', [uid, tid, 'Admin', admin_email, placeholderHash, 'admin']);
|
||||
|
||||
const token = crypto.randomBytes(32).toString('hex');
|
||||
await connection.query('INSERT INTO password_resets (email, token, expires_at) VALUES (?, ?, DATE_ADD(NOW(), INTERVAL 24 HOUR))', [admin_email, token]);
|
||||
// Adicionar aos pending_registrations em vez de criar um usuário direto se quisermos que eles completem o cadastro.
|
||||
// Ou, se quisermos apenas definir a senha, mantemos o password_resets.
|
||||
// O usuário quer "like a register", então vamos enviar para uma página onde eles definem a senha.
|
||||
await connection.query('INSERT INTO password_resets (email, token, expires_at) VALUES (?, ?, DATE_ADD(NOW(), INTERVAL 15 MINUTE))', [admin_email, token]);
|
||||
|
||||
const setupLink = `${process.env.APP_URL || 'http://localhost:3001'}/#/reset-password?token=${token}`;
|
||||
await transporter.sendMail({
|
||||
from: `"Fasto" <${process.env.MAIL_FROM || 'nao-responda@blyzer.com.br'}>`,
|
||||
to: admin_email,
|
||||
subject: 'Bem-vindo ao Fasto - Crie sua senha',
|
||||
html: `<p>Você foi convidado para ser Admin. <a href="${setupLink}">Crie sua senha aqui</a>.</p>`
|
||||
subject: 'Bem-vindo ao Fasto - Conclua seu cadastro de Admin',
|
||||
html: `
|
||||
<div style="font-family: sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #e2e8f0; border-radius: 12px; background: #ffffff; color: #0f172a;">
|
||||
<h2 style="color: #0f172a;">Sua organização foi criada</h2>
|
||||
<p style="color: #475569;">Você foi definido como administrador da organização <strong>${name}</strong>.</p>
|
||||
<p style="color: #475569;">Por favor, clique no botão abaixo para definir sua senha e concluir seu cadastro.</p>
|
||||
<div style="text-align: center; margin: 30px 0;">
|
||||
<a href="${setupLink}" style="background-color: #0f172a; color: white; padding: 12px 24px; text-decoration: none; border-radius: 8px; font-weight: bold; display: inline-block;">Finalizar Cadastro</a>
|
||||
</div>
|
||||
<p style="font-size: 12px; color: #94a3b8;">Este link expira em 15 minutos.</p>
|
||||
</div>
|
||||
`
|
||||
}).catch(err => console.error("Email failed:", err));
|
||||
}
|
||||
|
||||
await connection.commit();
|
||||
res.status(201).json({ id: tid });
|
||||
res.status(201).json({ id: tid, message: 'Organização criada e convite enviado por e-mail.' });
|
||||
} catch (error) { await connection.rollback(); res.status(500).json({ error: error.message }); } finally { connection.release(); }
|
||||
});
|
||||
|
||||
@@ -592,7 +628,7 @@ const provisionSuperAdmin = async () => {
|
||||
|
||||
const token = crypto.randomBytes(32).toString('hex');
|
||||
await pool.query(
|
||||
'INSERT INTO password_resets (email, token, expires_at) VALUES (?, ?, DATE_ADD(NOW(), INTERVAL 24 HOUR))',
|
||||
'INSERT INTO password_resets (email, token, expires_at) VALUES (?, ?, DATE_ADD(NOW(), INTERVAL 15 MINUTE))',
|
||||
[email, token]
|
||||
);
|
||||
|
||||
@@ -604,13 +640,13 @@ const provisionSuperAdmin = async () => {
|
||||
to: email,
|
||||
subject: 'Conta Super Admin Criada - Fasto',
|
||||
html: `
|
||||
<div style="font-family: sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #222; border-radius: 12px; background: #0a0a0a; color: #ededed;">
|
||||
<h2 style="color: #facc15;">Conta Super Admin Gerada</h2>
|
||||
<p>Sua conta de suporte (super_admin) foi criada no Fasto.</p>
|
||||
<div style="font-family: sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #e2e8f0; border-radius: 12px; background: #ffffff; color: #0f172a;">
|
||||
<h2 style="color: #0f172a;">Conta Super Admin Gerada</h2>
|
||||
<p style="color: #475569;">Sua conta de suporte (super_admin) foi criada no Fasto.</p>
|
||||
<div style="text-align: center; margin: 30px 0;">
|
||||
<a href="${setupLink}" style="background-color: #facc15; color: #09090b; padding: 12px 24px; text-decoration: none; border-radius: 8px; font-weight: bold; display: inline-block;">Definir Senha do Super Admin</a>
|
||||
<a href="${setupLink}" style="background-color: #0f172a; color: white; padding: 12px 24px; text-decoration: none; border-radius: 8px; font-weight: bold; display: inline-block;">Finalizar Cadastro</a>
|
||||
</div>
|
||||
<p style="font-size: 12px; color: #888;">Este link expira em 24 horas.</p>
|
||||
<p style="font-size: 12px; color: #94a3b8;">Este link expira em 15 minutos.</p>
|
||||
</div>
|
||||
`
|
||||
}).catch(err => console.error("Failed to send super_admin email:", err));
|
||||
|
||||
@@ -12,9 +12,10 @@ interface KPICardProps {
|
||||
}
|
||||
|
||||
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';
|
||||
|
||||
// Extract base color from colorClass (e.g., 'text-brand-yellow' -> 'brand-yellow' or 'text-blue-600' -> 'blue-600')
|
||||
// Safer extraction:
|
||||
const baseColor = colorClass.replace('text-', '').split(' ')[0]; // gets 'brand-yellow' or 'zinc-500'
|
||||
|
||||
return (
|
||||
<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">
|
||||
@@ -22,8 +23,8 @@ export const KPICard: React.FC<KPICardProps> = ({ title, value, subValue, trend,
|
||||
<h3 className="text-zinc-500 dark:text-dark-muted text-sm font-medium mb-1">{title}</h3>
|
||||
<div className="text-3xl font-bold text-zinc-800 dark:text-dark-text tracking-tight">{value}</div>
|
||||
</div>
|
||||
<div className={`p-3 rounded-xl bg-${baseColor}-100 dark:bg-${baseColor}-500/20 flex items-center justify-center transition-colors border border-transparent dark:border-${baseColor}-500/30`}>
|
||||
<Icon size={20} className={`${colorClass} dark:text-${baseColor}-400`} />
|
||||
<div className={`p-3 rounded-xl bg-${baseColor.split('-')[0]}-100 dark:bg-zinc-800 flex items-center justify-center transition-colors border border-transparent dark:border-dark-border`}>
|
||||
<Icon size={20} className={`${colorClass} dark:text-${baseColor.split('-')[0]}-400`} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -31,6 +32,7 @@ export const KPICard: React.FC<KPICardProps> = ({ title, value, subValue, trend,
|
||||
<div className="flex items-center gap-2 text-sm mt-auto">
|
||||
{trend === 'up' && <span className="text-green-500 flex items-center font-medium">▲ {trendValue}</span>}
|
||||
{trend === 'down' && <span className="text-red-500 flex items-center font-medium">▼ {trendValue}</span>}
|
||||
{trend === 'neutral' && <span className="text-zinc-500 dark:text-dark-muted flex items-center font-medium">- {trendValue}</span>}
|
||||
{subValue && <span className="text-zinc-400 dark:text-dark-muted">{subValue}</span>}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -106,7 +106,7 @@ export const SellersTable: React.FC<SellersTableProps> = ({ data }) => {
|
||||
<tr
|
||||
key={item.user.id}
|
||||
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.slug || item.user.id}`)}
|
||||
>
|
||||
<td className="px-6 py-4">
|
||||
<div className="flex items-center gap-3">
|
||||
|
||||
@@ -2,6 +2,7 @@ services:
|
||||
app:
|
||||
build: .
|
||||
container_name: fasto-app-local
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "3001:3001"
|
||||
environment:
|
||||
@@ -27,6 +28,7 @@ services:
|
||||
db:
|
||||
image: mysql:8.0
|
||||
container_name: fasto-db-local
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
MYSQL_ROOT_PASSWORD: ${DB_PASSWORD:-root_password}
|
||||
MYSQL_DATABASE: ${DB_NAME:-agenciac_comia}
|
||||
|
||||
@@ -25,6 +25,7 @@ interface SellerStats {
|
||||
export const Dashboard: React.FC = () => {
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [data, setData] = useState<Attendance[]>([]);
|
||||
const [prevData, setPrevData] = useState<Attendance[]>([]);
|
||||
const [users, setUsers] = useState<User[]>([]);
|
||||
const [teams, setTeams] = useState<any[]>([]);
|
||||
const [currentUser, setCurrentUser] = useState<User | null>(null);
|
||||
@@ -48,16 +49,24 @@ export const Dashboard: React.FC = () => {
|
||||
const storedUserId = localStorage.getItem('ctms_user_id');
|
||||
if (!tenantId) return;
|
||||
|
||||
// Calculate previous date range for accurate period-over-period trend
|
||||
const duration = filters.dateRange.end.getTime() - filters.dateRange.start.getTime();
|
||||
const prevStart = new Date(filters.dateRange.start.getTime() - duration);
|
||||
const prevEnd = new Date(filters.dateRange.start.getTime());
|
||||
const prevFilters = { ...filters, dateRange: { start: prevStart, end: prevEnd } };
|
||||
|
||||
// Fetch users, attendances, teams and current user in parallel
|
||||
const [fetchedUsers, fetchedData, fetchedTeams, me] = await Promise.all([
|
||||
const [fetchedUsers, fetchedData, prevFetchedData, fetchedTeams, me] = await Promise.all([
|
||||
getUsers(tenantId),
|
||||
getAttendances(tenantId, filters),
|
||||
getAttendances(tenantId, prevFilters),
|
||||
getTeams(tenantId),
|
||||
storedUserId ? getUserById(storedUserId) : null
|
||||
]);
|
||||
|
||||
setUsers(fetchedUsers);
|
||||
setData(fetchedData);
|
||||
setPrevData(prevFetchedData);
|
||||
setTeams(fetchedTeams);
|
||||
if (me) setCurrentUser(me);
|
||||
} catch (error) {
|
||||
@@ -74,6 +83,48 @@ export const Dashboard: React.FC = () => {
|
||||
const avgScore = data.length > 0 ? (data.reduce((acc, curr) => acc + curr.score, 0) / data.length).toFixed(1) : "0";
|
||||
const avgResponseTime = data.length > 0 ? (data.reduce((acc, curr) => acc + curr.first_response_time_min, 0) / data.length).toFixed(0) : "0";
|
||||
const avgHandleTime = data.length > 0 ? (data.reduce((acc, curr) => acc + curr.handling_time_min, 0) / data.length).toFixed(0) : "0";
|
||||
|
||||
// --- Dynamic Trends Calculation ---
|
||||
const trends = useMemo(() => {
|
||||
if (data.length === 0 && prevData.length === 0) {
|
||||
return { leads: null, score: null, resp: null };
|
||||
}
|
||||
|
||||
const calcAvg = (arr: Attendance[], key: keyof Attendance) =>
|
||||
arr.length ? arr.reduce((acc, curr) => acc + (curr[key] as number), 0) / arr.length : 0;
|
||||
|
||||
// Leads Trend (%)
|
||||
const recentLeads = data.length;
|
||||
const prevLeads = prevData.length;
|
||||
let leadsTrend = 0;
|
||||
if (prevLeads > 0) {
|
||||
leadsTrend = ((recentLeads - prevLeads) / prevLeads) * 100;
|
||||
} else if (recentLeads > 0) {
|
||||
leadsTrend = 100;
|
||||
}
|
||||
|
||||
// Score Trend (Absolute point difference)
|
||||
const recentScore = calcAvg(data, 'score');
|
||||
const prevScore = calcAvg(prevData, 'score');
|
||||
let scoreTrend = 0;
|
||||
if (prevData.length > 0) {
|
||||
scoreTrend = recentScore - prevScore;
|
||||
} else {
|
||||
scoreTrend = recentScore;
|
||||
}
|
||||
|
||||
// Response Time Trend (%)
|
||||
const recentResp = calcAvg(data, 'first_response_time_min');
|
||||
const prevResp = calcAvg(prevData, 'first_response_time_min');
|
||||
let respTrend = 0;
|
||||
if (prevResp > 0) {
|
||||
respTrend = ((recentResp - prevResp) / prevResp) * 100;
|
||||
} else if (recentResp > 0) {
|
||||
respTrend = 100; // Time increased from 0, which is worse
|
||||
}
|
||||
|
||||
return { leads: leadsTrend, score: scoreTrend, resp: respTrend };
|
||||
}, [data, prevData]);
|
||||
|
||||
// --- Chart Data: Funnel ---
|
||||
const funnelData = useMemo(() => {
|
||||
@@ -245,25 +296,25 @@ export const Dashboard: React.FC = () => {
|
||||
<KPICard
|
||||
title="Total de Leads"
|
||||
value={totalLeads}
|
||||
trend="up"
|
||||
trendValue="12%"
|
||||
trend={trends.leads > 0 ? 'up' : trends.leads < 0 ? 'down' : 'neutral'}
|
||||
trendValue={`${Math.abs(trends.leads).toFixed(1)}%`}
|
||||
icon={Users}
|
||||
colorClass="text-yellow-600"
|
||||
colorClass="text-brand-yellow"
|
||||
/>
|
||||
<KPICard
|
||||
title="Nota Média Qualidade"
|
||||
value={avgScore}
|
||||
subValue="/ 100"
|
||||
trend={Number(avgScore) > 75 ? 'up' : 'down'}
|
||||
trendValue="2.1"
|
||||
trend={trends.score > 0 ? 'up' : trends.score < 0 ? 'down' : 'neutral'}
|
||||
trendValue={Math.abs(trends.score).toFixed(1)}
|
||||
icon={TrendingUp}
|
||||
colorClass="text-zinc-600"
|
||||
colorClass="text-zinc-500"
|
||||
/>
|
||||
<KPICard
|
||||
title="Média 1ª Resposta"
|
||||
value={`${avgResponseTime}m`}
|
||||
trend="down"
|
||||
trendValue="bom"
|
||||
trend={trends.resp < 0 ? 'up' : trends.resp > 0 ? 'down' : 'neutral'} // Faster response is better (up)
|
||||
trendValue={`${Math.abs(trends.resp).toFixed(1)}%`}
|
||||
icon={Clock}
|
||||
colorClass="text-orange-500"
|
||||
/>
|
||||
|
||||
@@ -58,12 +58,6 @@ export const Login: React.FC = () => {
|
||||
<h2 className="mt-6 text-center text-3xl font-bold tracking-tight text-zinc-900 dark:text-zinc-50">
|
||||
Acesse sua conta
|
||||
</h2>
|
||||
<p className="mt-2 text-center text-sm text-zinc-600 dark:text-dark-muted">
|
||||
Ou{' '}
|
||||
<Link to="/register" className="font-medium text-brand-yellow hover:text-yellow-600">
|
||||
registre sua nova organização
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="mt-8 sm:mx-auto sm:w-full sm:max-w-md">
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import React, { useState } from 'react';
|
||||
import { useNavigate, useLocation, Link } from 'react-router-dom';
|
||||
import { Hexagon, Lock, ArrowRight, Loader2, CheckCircle2, AlertCircle } from 'lucide-react';
|
||||
import { resetPassword } from '../services/dataService';
|
||||
@@ -26,7 +26,7 @@ export const ResetPassword: React.FC = () => {
|
||||
setError('');
|
||||
|
||||
try {
|
||||
await resetPassword(password, token);
|
||||
await resetPassword(password, token); // No name sent here
|
||||
setIsSuccess(true);
|
||||
setTimeout(() => navigate('/login'), 3000);
|
||||
} catch (err: any) {
|
||||
|
||||
156
pages/SetupAccount.tsx
Normal file
156
pages/SetupAccount.tsx
Normal file
@@ -0,0 +1,156 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { useNavigate, useLocation, Link } from 'react-router-dom';
|
||||
import { Hexagon, Lock, ArrowRight, Loader2, CheckCircle2, AlertCircle, User } from 'lucide-react';
|
||||
import { resetPassword } from '../services/dataService';
|
||||
|
||||
export const ResetPassword: React.FC = () => {
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const query = new URLSearchParams(location.search);
|
||||
const token = query.get('token') || '';
|
||||
|
||||
const [name, setName] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [confirmPassword, setConfirmPassword] = useState('');
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isSuccess, setIsSuccess] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (password !== confirmPassword) {
|
||||
setError('As senhas não coincidem.');
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
setError('');
|
||||
|
||||
try {
|
||||
await resetPassword(password, token, name);
|
||||
setIsSuccess(true);
|
||||
setTimeout(() => navigate('/login'), 3000);
|
||||
} catch (err: any) {
|
||||
setError(err.message || 'Erro ao redefinir senha. O link pode estar expirado.');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-zinc-50 dark:bg-dark-bg flex flex-col justify-center py-12 sm:px-6 lg:px-8 transition-colors duration-300">
|
||||
<div className="sm:mx-auto sm:w-full sm:max-w-md">
|
||||
<div className="flex justify-center items-center gap-2 text-zinc-900 dark:text-zinc-50">
|
||||
<div className="bg-zinc-900 dark:bg-brand-yellow text-white dark:text-zinc-950 p-2 rounded-lg transition-colors">
|
||||
<Hexagon size={32} fill="currentColor" />
|
||||
</div>
|
||||
<span className="text-3xl font-bold tracking-tight">Fasto<span className="text-brand-yellow">.</span></span>
|
||||
</div>
|
||||
<h2 className="mt-6 text-center text-3xl font-bold tracking-tight text-zinc-900 dark:text-zinc-50">
|
||||
Finalize seu cadastro
|
||||
</h2>
|
||||
</div>
|
||||
|
||||
<div className="mt-8 sm:mx-auto sm:w-full sm:max-w-md">
|
||||
<div className="bg-white dark:bg-dark-card py-8 px-4 shadow-xl rounded-2xl sm:px-10 border border-zinc-100 dark:border-dark-border transition-colors">
|
||||
{isSuccess ? (
|
||||
<div className="text-center py-4 space-y-4 animate-in fade-in zoom-in duration-300">
|
||||
<div className="mx-auto flex items-center justify-center h-12 w-12 rounded-full bg-green-100 dark:bg-green-900/30 text-green-600 dark:text-green-400">
|
||||
<CheckCircle2 size={24} />
|
||||
</div>
|
||||
<h3 className="text-lg font-bold text-zinc-900 dark:text-zinc-50">Tudo pronto!</h3>
|
||||
<p className="text-sm text-zinc-600 dark:text-dark-muted">
|
||||
Seu perfil foi atualizado com sucesso. Redirecionando para o login...
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<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 flex items-center gap-2 text-red-600 dark:text-red-400 text-sm">
|
||||
<AlertCircle size={18} />
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<label htmlFor="name" className="block text-sm font-medium text-zinc-700 dark:text-zinc-300">
|
||||
Seu Nome Completo
|
||||
</label>
|
||||
<div className="mt-1 relative">
|
||||
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
|
||||
<User className="h-5 w-5 text-zinc-400 dark:text-dark-muted" />
|
||||
</div>
|
||||
<input
|
||||
id="name"
|
||||
type="text"
|
||||
required
|
||||
value={name}
|
||||
onChange={(e) => setName(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="João da Silva"
|
||||
/>
|
||||
</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>
|
||||
<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-50"
|
||||
>
|
||||
{isLoading ? (
|
||||
<Loader2 className="animate-spin h-5 w-5" />
|
||||
) : (
|
||||
<>
|
||||
Salvar e Entrar <ArrowRight size={18} />
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -1,9 +1,9 @@
|
||||
import React, { useState, useMemo } from 'react';
|
||||
import {
|
||||
Building2, Users, MessageSquare, Plus, Search,
|
||||
Edit, Trash2, ChevronDown, ChevronUp, ChevronsUpDown, X
|
||||
Edit, Trash2, ChevronDown, ChevronUp, ChevronsUpDown, X, CheckCircle2
|
||||
} from 'lucide-react';
|
||||
import { getTenants, createTenant, deleteTenant } from '../services/dataService';
|
||||
import { getTenants, createTenant, deleteTenant, updateTenant } from '../services/dataService';
|
||||
import { Tenant } from '../types';
|
||||
import { DateRangePicker } from '../components/DateRangePicker';
|
||||
import { KPICard } from '../components/KPICard';
|
||||
@@ -91,21 +91,44 @@ export const SuperAdmin: React.FC = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const [successMessage, setSuccessMessage] = useState('');
|
||||
const [errorMessage, setErrorMessage] = useState('');
|
||||
|
||||
const handleSaveTenant = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setErrorMessage('');
|
||||
setSuccessMessage('');
|
||||
const form = e.target as HTMLFormElement;
|
||||
const name = (form.elements.namedItem('name') as HTMLInputElement).value;
|
||||
const slug = (form.elements.namedItem('slug') as HTMLInputElement).value;
|
||||
const admin_email = (form.elements.namedItem('admin_email') as HTMLInputElement).value;
|
||||
const status = (form.elements.namedItem('status') as HTMLSelectElement).value;
|
||||
const success = await createTenant({ name, slug, admin_email, status });
|
||||
if (success) {
|
||||
setIsModalOpen(false);
|
||||
setEditingTenant(null);
|
||||
loadTenants();
|
||||
alert('Organização salva com sucesso!');
|
||||
|
||||
if (editingTenant) {
|
||||
const success = await updateTenant(editingTenant.id, { name, slug, admin_email, status });
|
||||
if (success) {
|
||||
setSuccessMessage('Organização atualizada com sucesso!');
|
||||
loadTenants();
|
||||
setTimeout(() => {
|
||||
setIsModalOpen(false);
|
||||
setSuccessMessage('');
|
||||
setEditingTenant(null);
|
||||
}, 2000);
|
||||
} else {
|
||||
setErrorMessage('Erro ao atualizar organização.');
|
||||
}
|
||||
} else {
|
||||
alert('Erro ao salvar organização.');
|
||||
const result = await createTenant({ name, slug, admin_email, status });
|
||||
if (result.success) {
|
||||
setSuccessMessage(result.message || 'Organização criada com sucesso!');
|
||||
loadTenants();
|
||||
setTimeout(() => {
|
||||
setIsModalOpen(false);
|
||||
setSuccessMessage('');
|
||||
}, 3000);
|
||||
} else {
|
||||
setErrorMessage(result.message || 'Erro ao salvar organização.');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -132,7 +155,7 @@ export const SuperAdmin: React.FC = () => {
|
||||
<h1 className="text-2xl font-bold text-zinc-900 dark:text-zinc-50 tracking-tight">Painel Super Admin</h1>
|
||||
<p className="text-zinc-500 dark:text-dark-muted text-sm">Gerencie organizações e visualize estatísticas globais.</p>
|
||||
</div>
|
||||
<button onClick={() => { setEditingTenant(null); setIsModalOpen(true); }} className="bg-zinc-900 dark:bg-brand-yellow text-white dark:text-zinc-950 px-4 py-2 rounded-lg text-sm font-bold hover:opacity-90 transition-all shadow-sm">
|
||||
<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 flex items-center gap-2 whitespace-nowrap text-sm font-bold hover:opacity-90 transition-all shadow-sm">
|
||||
<Plus size={16} /> Adicionar Organização
|
||||
</button>
|
||||
</div>
|
||||
@@ -225,6 +248,16 @@ export const SuperAdmin: React.FC = () => {
|
||||
<button onClick={() => setIsModalOpen(false)} className="text-zinc-400 hover:text-zinc-600 dark:hover:text-zinc-300"><X size={20} /></button>
|
||||
</div>
|
||||
<form onSubmit={handleSaveTenant} className="p-6 space-y-4">
|
||||
{successMessage && (
|
||||
<div className="bg-green-50 dark:bg-green-900/20 border border-green-100 dark:border-green-900/30 p-3 rounded-lg flex items-center gap-2 text-green-700 dark:text-green-400 text-sm animate-in fade-in slide-in-from-top-1">
|
||||
<CheckCircle2 size={16} /> {successMessage}
|
||||
</div>
|
||||
)}
|
||||
{errorMessage && (
|
||||
<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-700 dark:text-red-400 text-sm animate-in fade-in slide-in-from-top-1">
|
||||
<X size={16} /> {errorMessage}
|
||||
</div>
|
||||
)}
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium text-zinc-700 dark:text-zinc-300">Nome da Organização</label>
|
||||
<input type="text" name="name" defaultValue={editingTenant?.name} className="w-full px-3 py-2 bg-zinc-50 dark:bg-dark-bg border border-zinc-200 dark:border-dark-border rounded-lg text-sm text-zinc-900 dark:text-zinc-100 focus:ring-2 focus:ring-brand-yellow/20 outline-none transition-all" required />
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { Users, Plus, Mail, Search, X, Edit, Trash2, Loader2, AlertTriangle } from 'lucide-react';
|
||||
import { getUsers, getTeams, createMember, deleteUser, updateUser, getUserById, getTenants } from '../services/dataService';
|
||||
import { User, Tenant } from '../types';
|
||||
@@ -12,6 +13,7 @@ export const TeamManagement: React.FC = () => {
|
||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||
const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
|
||||
const [searchTerm, setSearchTerm] = useState('');
|
||||
const [tenantFilter, setTenantFilter] = useState('all');
|
||||
const [currentUser, setCurrentUser] = useState<User | null>(null);
|
||||
const [userToDelete, setUserToDelete] = useState<User | null>(null);
|
||||
const [deleteConfirmName, setDeleteConfirmName] = useState('');
|
||||
@@ -92,7 +94,10 @@ export const TeamManagement: React.FC = () => {
|
||||
if (loading && users.length === 0) return <div className="flex h-screen items-center justify-center text-zinc-400 dark:text-dark-muted transition-colors">Carregando...</div>;
|
||||
|
||||
const canManage = currentUser?.role === 'admin' || currentUser?.role === 'super_admin';
|
||||
const filtered = users.filter(u => u.name.toLowerCase().includes(searchTerm.toLowerCase()) || u.email.toLowerCase().includes(searchTerm.toLowerCase()));
|
||||
const filtered = users.filter(u =>
|
||||
(u.name.toLowerCase().includes(searchTerm.toLowerCase()) || u.email.toLowerCase().includes(searchTerm.toLowerCase())) &&
|
||||
(tenantFilter === 'all' || u.tenant_id === tenantFilter)
|
||||
);
|
||||
|
||||
const getRoleLabel = (role: string) => {
|
||||
if (role === 'super_admin') return 'Super Admin';
|
||||
@@ -124,11 +129,21 @@ export const TeamManagement: React.FC = () => {
|
||||
</div>
|
||||
|
||||
<div className="bg-white dark:bg-dark-card border border-zinc-200 dark:border-dark-border rounded-xl shadow-sm overflow-hidden">
|
||||
<div className="p-4 border-b border-zinc-100 dark:border-dark-border bg-zinc-50 dark:bg-dark-bg/50">
|
||||
<div className="relative max-w-md">
|
||||
<div className="p-4 border-b border-zinc-100 dark:border-dark-border bg-zinc-50 dark:bg-dark-bg/50 flex flex-col sm:flex-row gap-4">
|
||||
<div className="relative flex-1 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>
|
||||
{currentUser?.role === 'super_admin' && (
|
||||
<select
|
||||
value={tenantFilter}
|
||||
onChange={e => setTenantFilter(e.target.value)}
|
||||
className="bg-white 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-dark-text outline-none focus:ring-2 focus:ring-brand-yellow/20 cursor-pointer w-full sm:w-auto transition-all"
|
||||
>
|
||||
<option value="all">Todas Organizações</option>
|
||||
{tenants.map(t => <option key={t.id} value={t.id}>{t.name}</option>)}
|
||||
</select>
|
||||
)}
|
||||
</div>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-left">
|
||||
@@ -158,7 +173,7 @@ export const TeamManagement: React.FC = () => {
|
||||
<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>
|
||||
<Link to={`/users/${user.slug || user.id}`} className="font-bold text-zinc-900 dark:text-dark-text hover:underline">{user.name}</Link>
|
||||
<div className="text-xs text-zinc-500 dark:text-dark-muted">{user.email}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -3,6 +3,7 @@ import { useParams, Link } from 'react-router-dom';
|
||||
import { getAttendances, getUserById } from '../services/dataService';
|
||||
import { Attendance, User, FunnelStage, DashboardFilter } from '../types';
|
||||
import { ArrowLeft, Mail, Phone, Clock, MessageSquare, ChevronLeft, ChevronRight, Eye, Filter } from 'lucide-react';
|
||||
import { DateRangePicker } from '../components/DateRangePicker';
|
||||
|
||||
const ITEMS_PER_PAGE = 10;
|
||||
|
||||
@@ -13,7 +14,7 @@ export const UserDetail: React.FC = () => {
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const [filters, setFilters] = useState<DashboardFilter>({
|
||||
dateRange: { start: new Date(0), end: new Date() },
|
||||
dateRange: { start: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000), end: new Date() },
|
||||
userId: id,
|
||||
funnelStage: 'all',
|
||||
origin: 'all'
|
||||
@@ -121,6 +122,11 @@ export const UserDetail: React.FC = () => {
|
||||
<span>Filtros:</span>
|
||||
</div>
|
||||
|
||||
<DateRangePicker
|
||||
dateRange={filters.dateRange}
|
||||
onChange={(range) => handleFilterChange('dateRange', range)}
|
||||
/>
|
||||
|
||||
<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}
|
||||
|
||||
@@ -234,17 +234,19 @@ export const updateTeam = async (id: string, teamData: any): Promise<boolean> =>
|
||||
}
|
||||
};
|
||||
|
||||
export const createTenant = async (tenantData: any): Promise<boolean> => {
|
||||
export const createTenant = async (tenantData: any): Promise<{ success: boolean; message?: string }> => {
|
||||
try {
|
||||
const response = await fetch(`${API_URL}/tenants`, {
|
||||
method: 'POST',
|
||||
headers: getHeaders(),
|
||||
body: JSON.stringify(tenantData)
|
||||
});
|
||||
return response.ok;
|
||||
} catch (error) {
|
||||
const data = await response.json().catch(() => null);
|
||||
if (!response.ok) throw new Error(data?.error || 'Erro ao criar organização');
|
||||
return { success: true, message: data?.message || 'Organização criada!' };
|
||||
} catch (error: any) {
|
||||
console.error("API Error (createTenant):", error);
|
||||
return false;
|
||||
return { success: false, message: error.message };
|
||||
}
|
||||
};
|
||||
|
||||
@@ -352,11 +354,11 @@ export const forgotPassword = async (email: string): Promise<string> => {
|
||||
return data.message;
|
||||
};
|
||||
|
||||
export const resetPassword = async (password: string, token: string): Promise<string> => {
|
||||
export const resetPassword = async (password: string, token: string, name?: string): Promise<string> => {
|
||||
const response = await fetch(`${API_URL}/auth/reset-password`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ password, token })
|
||||
body: JSON.stringify({ password, token, name })
|
||||
});
|
||||
|
||||
const contentType = response.headers.get("content-type");
|
||||
|
||||
Reference in New Issue
Block a user