feat(dashboard): painel Sandra — aprovações, pedidos do dia, inativos por rep (C8)

GET /dashboard/supervisor com fila de aprovações, KPIs do dia vs semana
anterior e top 3 reps com mais clientes inativos. SandraPainel com polling
30s. Rota / role-aware: rep → RafaelPainel, supervisor/manager → SandraPainel.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-05-28 00:40:08 +00:00
parent 6028bf1ba9
commit 36103eaa87
6 changed files with 454 additions and 5 deletions

View File

@@ -1,6 +1,6 @@
import { Controller, Get } from '@nestjs/common';
import { ClsService } from 'nestjs-cls';
import type { RepDashboard } from '@sar/api-interface';
import type { RepDashboard, SupervisorDashboard } from '@sar/api-interface';
import type { WorkspaceClsStore } from '../workspace/workspace.types';
import { DashboardService } from './dashboard.service';
@@ -15,4 +15,9 @@ export class DashboardController {
repDashboard(): Promise<RepDashboard> {
return this.dashboard.repDashboard(this.cls.get('userId') ?? '');
}
@Get('supervisor')
supervisorDashboard(): Promise<SupervisorDashboard> {
return this.dashboard.supervisorDashboard();
}
}

View File

@@ -1,7 +1,7 @@
import { Injectable } from '@nestjs/common';
import { ClsService } from 'nestjs-cls';
import { OrderStatus } from '@prisma/client';
import type { RepDashboard } from '@sar/api-interface';
import type { RepDashboard, SupervisorDashboard } from '@sar/api-interface';
import type { WorkspaceClsStore } from '../workspace/workspace.types';
@Injectable()
@@ -106,4 +106,78 @@ export class DashboardService {
syncedAt: now.toISOString(),
};
}
async supervisorDashboard(): Promise<SupervisorDashboard> {
const prisma = this.cls.get('prisma');
const now = new Date();
// Fila de aprovações — mais antigos primeiro
const approvalQueue = await prisma.order.findMany({
where: { deletedAt: null, status: OrderStatus.pending_approval },
include: { client: { select: { name: true } } },
orderBy: { issuedAt: 'asc' },
take: 50,
});
// Pedidos do dia (hoje, meia-noite até agora)
const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());
const todayOrders = await prisma.order.findMany({
where: {
deletedAt: null,
status: { not: OrderStatus.cancelled },
issuedAt: { gte: todayStart },
},
});
// Mesmo dia da semana passada (comparativo)
const lastWeekStart = new Date(todayStart.getTime() - 7 * 24 * 60 * 60 * 1000);
const lastWeekEnd = new Date(lastWeekStart.getTime() + 24 * 60 * 60 * 1000 - 1);
const lastWeekOrders = await prisma.order.findMany({
where: {
deletedAt: null,
status: { not: OrderStatus.cancelled },
issuedAt: { gte: lastWeekStart, lte: lastWeekEnd },
},
});
// Inativos por rep — top 3 reps com mais clientes inativos (>30 dias)
const thirtyDaysAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
const inativosPorRep = await prisma.client.groupBy({
by: ['repId'],
where: {
deletedAt: null,
OR: [{ lastOrderAt: null }, { lastOrderAt: { lt: thirtyDaysAgo } }],
},
_count: { id: true },
orderBy: { _count: { id: 'desc' } },
take: 3,
});
const mapOrder = (o: (typeof approvalQueue)[number]) => ({
id: o.id,
number: o.number,
clientId: o.clientId,
clientName: o.client.name,
repId: o.repId,
status: o.status,
total: String(o.total),
discountPct: String(o.discountPct),
issuedAt: o.issuedAt.toISOString(),
});
return {
approvalQueue: approvalQueue.map(mapOrder),
pedidosDia: {
count: todayOrders.length,
total: todayOrders.reduce((s, o) => s + Number(o.total), 0),
countSemanaAnterior: lastWeekOrders.length,
totalSemanaAnterior: lastWeekOrders.reduce((s, o) => s + Number(o.total), 0),
},
inativosPorRep: inativosPorRep.map((r) => ({
repId: r.repId,
inativosCount: r._count.id,
})),
syncedAt: now.toISOString(),
};
}
}

View File

@@ -0,0 +1,316 @@
import { Badge, Card, Col, Flex, Row, Skeleton, Space, Table, Tag, Typography } from 'antd';
import type { TableColumnsType } from 'antd';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {
faCheckCircle,
faCircleExclamation,
faClipboardList,
} from '@fortawesome/free-solid-svg-icons';
import { Link } from '@tanstack/react-router';
import type { OrderSummary } from '@sar/api-interface';
import { useSupervisorDashboard } from '../../lib/queries/dashboard';
const { Title, Text } = Typography;
function fmt(v: number): string {
return v.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' });
}
function hoursWaiting(issuedAt: string): number {
return Math.floor((Date.now() - new Date(issuedAt).getTime()) / 3_600_000);
}
function delta(current: number, previous: number): { label: string; positive: boolean } | null {
if (previous === 0) return null;
const pct = Math.round(((current - previous) / previous) * 100);
return { label: `${pct >= 0 ? '+' : ''}${pct}% vs semana passada`, positive: pct >= 0 };
}
function today(): string {
return new Date().toLocaleDateString('pt-BR', { weekday: 'long', day: 'numeric', month: 'long' });
}
const queueColumns: TableColumnsType<OrderSummary> = [
{
title: 'Pedido',
dataIndex: 'number',
width: 120,
render: (num: string, row: OrderSummary) => (
<Link to="/pedidos/$id" params={{ id: row.id }}>
{num}
</Link>
),
},
{ title: 'Rep', dataIndex: 'repId', width: 120, ellipsis: true },
{ title: 'Cliente', dataIndex: 'clientName', ellipsis: true },
{
title: 'Total',
dataIndex: 'total',
width: 130,
align: 'right',
render: (v: string) => fmt(Number(v)),
},
{
title: 'Aguardando',
dataIndex: 'issuedAt',
width: 120,
render: (v: string) => {
const h = hoursWaiting(v);
return <Tag color={h > 2 ? 'red' : 'orange'}>{h}h</Tag>;
},
},
{
title: '',
width: 90,
render: (_: unknown, row: OrderSummary) => (
<Link to="/pedidos/$id" params={{ id: row.id }}>
<Tag color="blue" style={{ cursor: 'pointer' }}>
Analisar
</Tag>
</Link>
),
},
];
export function SandraPainel() {
const { data, isLoading } = useSupervisorDashboard();
if (isLoading || !data) {
return (
<Flex vertical gap={24} style={{ maxWidth: 1280, margin: '0 auto' }}>
<Skeleton active paragraph={{ rows: 1 }} />
<Row gutter={[24, 24]}>
{[1, 2, 3].map((i) => (
<Col key={i} xs={24} md={8}>
<Skeleton active />
</Col>
))}
</Row>
</Flex>
);
}
const { approvalQueue, pedidosDia, inativosPorRep, syncedAt } = data;
const urgentCount = approvalQueue.filter((o) => hoursWaiting(o.issuedAt) > 2).length;
const countDelta = delta(pedidosDia.count, pedidosDia.countSemanaAnterior);
const totalDelta = delta(pedidosDia.total, pedidosDia.totalSemanaAnterior);
return (
<Flex vertical gap={24} style={{ maxWidth: 1280, margin: '0 auto' }}>
{/* Saudação */}
<Flex vertical gap={4}>
<Title level={2} style={{ margin: 0 }}>
Bom dia, Sandra
</Title>
<Text type="secondary" style={{ fontSize: 'var(--text-lg)' }}>
{today()}
{urgentCount > 0 && (
<>
{' '}
·{' '}
<span style={{ color: '#cf1322' }}>
{urgentCount} aprovação{urgentCount > 1 ? 'ões' : ''} urgente
{urgentCount > 1 ? 's' : ''}
</span>
</>
)}
</Text>
</Flex>
{/* KPIs */}
<Row gutter={[24, 24]}>
<Col xs={24} md={8}>
<Card>
<Space direction="vertical" size={4}>
<Text type="secondary" style={{ fontSize: 'var(--text-sm)' }}>
APROVAÇÕES PENDENTES
</Text>
<Flex align="center" gap={8}>
<Title level={3} style={{ margin: 0 }} className="tabular-nums">
{approvalQueue.length}
</Title>
{urgentCount > 0 && (
<Badge
count={urgentCount}
style={{ backgroundColor: '#cf1322' }}
title={`${urgentCount} urgente(s) — mais de 2h`}
/>
)}
</Flex>
<Link to="/aprovacoes">
<Text style={{ fontSize: 'var(--text-sm)', color: 'var(--jcs-blue)' }}>
Ver fila completa
</Text>
</Link>
</Space>
</Card>
</Col>
<Col xs={24} md={8}>
<Card>
<Space direction="vertical" size={4}>
<Text type="secondary" style={{ fontSize: 'var(--text-sm)' }}>
PEDIDOS HOJE
</Text>
<Title level={3} style={{ margin: 0 }} className="tabular-nums">
{pedidosDia.count}
</Title>
{countDelta && (
<Text
style={{
fontSize: 'var(--text-sm)',
color: countDelta.positive ? 'var(--green)' : '#cf1322',
}}
>
{countDelta.label}
</Text>
)}
</Space>
</Card>
</Col>
<Col xs={24} md={8}>
<Card>
<Space direction="vertical" size={4}>
<Text type="secondary" style={{ fontSize: 'var(--text-sm)' }}>
VALOR HOJE
</Text>
<Title level={3} style={{ margin: 0 }} className="tabular-nums">
{fmt(pedidosDia.total)}
</Title>
{totalDelta && (
<Text
style={{
fontSize: 'var(--text-sm)',
color: totalDelta.positive ? 'var(--green)' : '#cf1322',
}}
>
{totalDelta.label}
</Text>
)}
</Space>
</Card>
</Col>
</Row>
{/* Fila de aprovações + Inativos por rep */}
<Row gutter={[24, 24]}>
<Col xs={24} lg={16}>
<Card
title={
<Space>
<FontAwesomeIcon icon={faCheckCircle} style={{ color: 'var(--jcs-blue)' }} />
Fila de Aprovações
{approvalQueue.length > 0 && (
<Badge
count={approvalQueue.length}
style={{ backgroundColor: 'var(--jcs-blue)' }}
/>
)}
</Space>
}
extra={<Link to="/aprovacoes">Ver todas</Link>}
>
<Table<OrderSummary>
rowKey="id"
columns={queueColumns}
dataSource={approvalQueue.slice(0, 8)}
pagination={false}
size="small"
rowClassName={(row) => (hoursWaiting(row.issuedAt) > 2 ? 'row-urgent' : '')}
locale={{ emptyText: 'Nenhum pedido aguardando aprovação.' }}
/>
<style>{`.row-urgent td { background: #fff1f0 !important; }`}</style>
</Card>
</Col>
<Col xs={24} lg={8}>
<Card
title={
<Space>
<FontAwesomeIcon icon={faCircleExclamation} style={{ color: 'var(--orange)' }} />
Inativos por Rep
</Space>
}
extra={
<Text type="secondary" style={{ fontSize: 'var(--text-xs)' }}>
sem compra +30 dias
</Text>
}
>
{inativosPorRep.length === 0 ? (
<Text type="secondary">Nenhum inativo no momento.</Text>
) : (
<Flex vertical gap={12}>
{inativosPorRep.map((r) => (
<Flex
key={r.repId}
justify="space-between"
align="center"
style={{
padding: 'var(--space-sm) var(--space-md)',
borderRadius: 12,
background: 'var(--bg-surface-alt)',
}}
>
<Space direction="vertical" size={0}>
<Text strong>{r.repId}</Text>
</Space>
<Tag
color={r.inativosCount >= 3 ? 'orange' : 'default'}
className="tabular-nums"
>
{r.inativosCount} cliente{r.inativosCount > 1 ? 's' : ''}
</Tag>
</Flex>
))}
</Flex>
)}
</Card>
<Card
style={{ marginTop: 24 }}
title={
<Space>
<FontAwesomeIcon icon={faClipboardList} style={{ color: 'var(--jcs-blue)' }} />
Pedidos de Hoje
</Space>
}
>
<Flex vertical gap={8}>
<Flex justify="space-between">
<Text type="secondary">Total de pedidos</Text>
<Text strong className="tabular-nums">
{pedidosDia.count}
</Text>
</Flex>
<Flex justify="space-between">
<Text type="secondary">Valor consolidado</Text>
<Text strong className="tabular-nums">
{fmt(pedidosDia.total)}
</Text>
</Flex>
{pedidosDia.countSemanaAnterior > 0 && (
<Flex justify="space-between">
<Text type="secondary">Semana passada</Text>
<Text type="secondary" className="tabular-nums">
{pedidosDia.countSemanaAnterior} · {fmt(pedidosDia.totalSemanaAnterior)}
</Text>
</Flex>
)}
</Flex>
</Card>
</Col>
</Row>
<Flex justify="space-between" style={{ paddingTop: 8 }}>
<Text type="secondary" style={{ fontSize: 'var(--text-xs)' }}>
SAR · Força de Vendas · Powered by JCS Sistemas
</Text>
<Text type="secondary" style={{ fontSize: 'var(--text-xs)' }}>
Sync: {new Date(syncedAt).toLocaleTimeString('pt-BR')} · atualiza a cada 30s
</Text>
</Flex>
</Flex>
);
}

View File

@@ -1,5 +1,10 @@
import { useQuery } from '@tanstack/react-query';
import { RepDashboardSchema, type RepDashboard } from '@sar/api-interface';
import {
RepDashboardSchema,
SupervisorDashboardSchema,
type RepDashboard,
type SupervisorDashboard,
} from '@sar/api-interface';
import { apiFetch } from '../api-client';
export function useRepDashboard() {
@@ -9,6 +14,18 @@ export function useRepDashboard() {
const raw = await apiFetch('/dashboard/rep');
return RepDashboardSchema.parse(raw);
},
staleTime: 5 * 60 * 1000, // 5 min
staleTime: 5 * 60 * 1000,
});
}
export function useSupervisorDashboard() {
return useQuery<SupervisorDashboard>({
queryKey: ['dashboard', 'supervisor'],
queryFn: async () => {
const raw = await apiFetch('/dashboard/supervisor');
return SupervisorDashboardSchema.parse(raw);
},
staleTime: 30 * 1000, // 30s — simula near-real-time até C6 (SSE)
refetchInterval: 30 * 1000,
});
}

View File

@@ -7,6 +7,24 @@ import { OrdersPage } from '../cockpits/rafael/OrdersPage';
import { OrderDetailPage } from '../cockpits/rafael/OrderDetailPage';
import { NewOrderPage } from '../cockpits/rafael/NewOrderPage';
import { ApprovalQueuePage } from '../cockpits/sandra/ApprovalQueuePage';
import { SandraPainel } from '../cockpits/sandra/SandraPainel';
import { authStore } from './auth-store';
function getRoleFromToken(): string {
const token = authStore.get();
if (!token) return 'rep';
try {
const payload = JSON.parse(atob(token.split('.')[1] ?? ''));
return (payload.role as string) ?? 'rep';
} catch {
return 'rep';
}
}
function HomeRoute() {
const role = getRoleFromToken();
return role === 'supervisor' || role === 'manager' ? <SandraPainel /> : <RafaelPainel />;
}
const rootRoute = createRootRoute({
component: () => (
@@ -19,7 +37,7 @@ const rootRoute = createRootRoute({
const indexRoute = createRoute({
getParentRoute: () => rootRoute,
path: '/',
component: RafaelPainel,
component: HomeRoute,
});
const rafaelRoute = createRoute({