Add replenishment needs view

This commit is contained in:
Cauê Faleiros
2026-07-07 09:48:39 -03:00
parent 76de11f4de
commit e0c71de3eb
3 changed files with 468 additions and 1 deletions

View File

@@ -7,6 +7,7 @@ import { isAuthenticated, isSuperAdmin } from './dataService';
const Dashboard = React.lazy(() => import('./pages/Dashboard')); const Dashboard = React.lazy(() => import('./pages/Dashboard'));
const Products = React.lazy(() => import('./pages/Products')); const Products = React.lazy(() => import('./pages/Products'));
const ProductDetails = React.lazy(() => import('./pages/ProductDetails')); const ProductDetails = React.lazy(() => import('./pages/ProductDetails'));
const Replenishment = React.lazy(() => import('./pages/Replenishment'));
const ProductionOrders = React.lazy(() => import('./pages/ProductionOrders')); const ProductionOrders = React.lazy(() => import('./pages/ProductionOrders'));
const Clients = React.lazy(() => import('./pages/Clients')); const Clients = React.lazy(() => import('./pages/Clients'));
const ClientDetails = React.lazy(() => import('./pages/ClientDetails')); const ClientDetails = React.lazy(() => import('./pages/ClientDetails'));
@@ -46,6 +47,7 @@ function App() {
<Route path="graph" element={<Dashboard />} /> <Route path="graph" element={<Dashboard />} />
<Route path="products" element={<Products />} /> <Route path="products" element={<Products />} />
<Route path="products/:id" element={<ProductDetails />} /> <Route path="products/:id" element={<ProductDetails />} />
<Route path="replenishment" element={<Replenishment />} />
<Route path="stock" element={<Navigate to="/products" replace />} /> <Route path="stock" element={<Navigate to="/products" replace />} />
<Route path="stock-alerts" element={<Navigate to="/products" replace />} /> <Route path="stock-alerts" element={<Navigate to="/products" replace />} />
<Route path="production-orders" element={<ProductionOrders />} /> <Route path="production-orders" element={<ProductionOrders />} />

View File

@@ -1,6 +1,6 @@
import { useState, useEffect } from 'react'; import { useState, useEffect } from 'react';
import { Outlet, Link, useLocation } from 'react-router-dom'; import { Outlet, Link, useLocation } from 'react-router-dom';
import { LayoutDashboard, Users, BarChart3, ChevronLeft, ChevronRight, Package, LogOut, Megaphone, Grid3X3, Shield, Moon, Sun, ClipboardList } from 'lucide-react'; import { LayoutDashboard, Users, BarChart3, ChevronLeft, ChevronRight, Package, LogOut, Megaphone, Grid3X3, Shield, Moon, Sun, ClipboardList, PackagePlus } from 'lucide-react';
import type { DateRange, OrderData } from '../types'; import type { DateRange, OrderData } from '../types';
import { isSuperAdmin, logout } from '../dataService'; import { isSuperAdmin, logout } from '../dataService';
import { rangeForLastDays } from '../dateRanges'; import { rangeForLastDays } from '../dateRanges';
@@ -62,6 +62,7 @@ const Layout = () => {
const appNavigation = [ const appNavigation = [
{ name: 'Dashboard', href: '/graph', icon: LayoutDashboard }, { name: 'Dashboard', href: '/graph', icon: LayoutDashboard },
{ name: 'Produtos', href: '/products', icon: Package }, { name: 'Produtos', href: '/products', icon: Package },
{ name: 'Reposição', href: '/replenishment', icon: PackagePlus },
{ name: 'Ordens de Produção', href: '/production-orders', icon: ClipboardList }, { name: 'Ordens de Produção', href: '/production-orders', icon: ClipboardList },
{ name: 'Clientes', href: '/clients', icon: Users }, { name: 'Clientes', href: '/clients', icon: Users },
{ name: 'RFV', href: '/rfm', icon: Grid3X3 }, { name: 'RFV', href: '/rfm', icon: Grid3X3 },

464
src/pages/Replenishment.tsx Normal file
View File

@@ -0,0 +1,464 @@
import { useEffect, useMemo, useState } from 'react';
import { Link, useOutletContext } from 'react-router-dom';
import { AlertTriangle, CheckCircle2, Download, Package, Search, TrendingUp } from 'lucide-react';
import DateRangePicker from '../components/DateRangePicker';
import PaginationControls from '../components/PaginationControls';
import RefreshStatus from '../components/RefreshStatus';
import type { DateRange, ProductAnalyticsItem } from '../types';
import { exportToCSV, fetchProductAnalytics } from '../dataService';
type ReplenishmentStatus = 'need' | 'covered' | 'no_sales' | 'no_stock';
type ReplenishmentFilter = 'all' | ReplenishmentStatus;
type ReplenishmentSort = 'need_desc' | 'need_asc' | 'demand_desc' | 'stock_asc' | 'coverage_asc' | 'sold_desc' | 'name_asc';
type ReplenishmentRow = ProductAnalyticsItem & {
dailySales: number;
projectedDemand: number;
suggestedQuantity: number;
daysOfCover: number | null;
status: ReplenishmentStatus;
statusLabel: string;
};
const horizonOptions = [7, 15, 30, 60];
const statusStyles: Record<ReplenishmentStatus, { label: string; className: string; dotClass: string }> = {
need: {
label: 'Repor',
className: 'border-red-400/35 bg-red-400/10 text-red-300',
dotClass: 'bg-red-400'
},
no_stock: {
label: 'Sem estoque',
className: 'border-zinc-500/30 bg-zinc-500/10 text-zinc-300',
dotClass: 'bg-zinc-400'
},
covered: {
label: 'Coberto',
className: 'border-emerald-400/35 bg-emerald-400/10 text-emerald-300',
dotClass: 'bg-emerald-400'
},
no_sales: {
label: 'Sem venda',
className: 'border-dark-border bg-dark-input text-dark-muted',
dotClass: 'bg-dark-muted'
}
};
const filterOptions: Array<{ value: ReplenishmentFilter; label: string }> = [
{ value: 'need', label: 'Com necessidade' },
{ value: 'all', label: 'Todos' },
{ value: 'no_stock', label: 'Sem estoque' },
{ value: 'covered', label: 'Cobertos' },
{ value: 'no_sales', label: 'Sem venda' }
];
const formatNumber = (value: number, maximumFractionDigits = 0) => (
new Intl.NumberFormat('pt-BR', { maximumFractionDigits }).format(value)
);
const formatDays = (value: number | null) => {
if (value === null) return '-';
if (value > 999) return '999+ dias';
return `${formatNumber(value, value < 10 ? 1 : 0)} dias`;
};
const getRangeDays = (range: DateRange) => {
const start = new Date(range.start);
const end = new Date(range.end);
start.setHours(0, 0, 0, 0);
end.setHours(0, 0, 0, 0);
return Math.max(1, Math.round((end.getTime() - start.getTime()) / 86_400_000) + 1);
};
const ReplenishmentSkeleton = () => (
<div className="bg-white dark:bg-dark-card border border-zinc-200 dark:border-dark-border rounded-2xl overflow-hidden shadow-sm" aria-label="Carregando necessidade de reposicao">
<div className="border-b border-zinc-100 p-4 dark:border-dark-border">
<div className="grid grid-cols-[120px_1.5fr_120px_130px_120px_130px_130px_110px] gap-6">
{[0, 1, 2, 3, 4, 5, 6, 7].map(item => (
<div key={`replenishment-head-skeleton-${item}`} className="skeleton h-3" />
))}
</div>
</div>
<div className="divide-y divide-zinc-100 dark:divide-dark-border">
{[0, 1, 2, 3, 4, 5, 6, 7].map(row => (
<div key={`replenishment-row-skeleton-${row}`} className="grid grid-cols-[120px_1.5fr_120px_130px_120px_130px_130px_110px] gap-6 px-6 py-4">
<div className="skeleton h-4" />
<div>
<div className="skeleton h-4 w-4/5" />
<div className="skeleton mt-2 h-3 w-32" />
</div>
<div className="skeleton h-6 rounded-full" />
<div className="skeleton h-4" />
<div className="skeleton h-4" />
<div className="skeleton h-4" />
<div className="skeleton h-4" />
<div className="skeleton h-7 rounded-lg" />
</div>
))}
</div>
</div>
);
const Replenishment = () => {
const { dateRange, setDateRange } = useOutletContext<{
dateRange: DateRange,
setDateRange: (range: DateRange) => void
}>();
const [products, setProducts] = useState<ProductAnalyticsItem[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [searchTerm, setSearchTerm] = useState('');
const [horizonDays, setHorizonDays] = useState(30);
const [statusFilter, setStatusFilter] = useState<ReplenishmentFilter>('need');
const [sortBy, setSortBy] = useState<ReplenishmentSort>('need_desc');
const [currentPage, setCurrentPage] = useState(1);
const [itemsPerPage, setItemsPerPage] = useState(10);
useEffect(() => {
let isMounted = true;
const loadProducts = async () => {
setIsLoading(true);
const data = await fetchProductAnalytics(dateRange);
if (isMounted) {
setProducts(data);
setIsLoading(false);
}
};
void loadProducts();
return () => {
isMounted = false;
};
}, [dateRange]);
const allRows = useMemo<ReplenishmentRow[]>(() => {
const rangeDays = getRangeDays(dateRange);
return products.map(product => {
const dailySales = product.quantitySold / rangeDays;
const projectedDemand = dailySales * horizonDays;
const rawNeed = projectedDemand - product.stock;
const suggestedQuantity = Math.max(0, Math.ceil(rawNeed));
const daysOfCover = dailySales > 0 ? product.stock / dailySales : null;
const status: ReplenishmentStatus = dailySales <= 0
? 'no_sales'
: product.stock <= 0
? 'no_stock'
: suggestedQuantity > 0
? 'need'
: 'covered';
return {
...product,
dailySales,
projectedDemand,
suggestedQuantity,
daysOfCover,
status,
statusLabel: statusStyles[status].label
};
});
}, [dateRange, horizonDays, products]);
const filteredRows = useMemo(() => {
const normalizedSearch = searchTerm.trim().toLowerCase();
const searchedRows = normalizedSearch
? allRows.filter(row =>
row.name.toLowerCase().includes(normalizedSearch) ||
row.id.toLowerCase().includes(normalizedSearch)
)
: allRows;
const statusRows = statusFilter === 'all'
? searchedRows
: searchedRows.filter(row => row.status === statusFilter);
return [...statusRows].sort((a, b) => {
switch (sortBy) {
case 'need_asc': return a.suggestedQuantity - b.suggestedQuantity;
case 'demand_desc': return b.projectedDemand - a.projectedDemand;
case 'stock_asc': return a.stock - b.stock;
case 'coverage_asc': return (a.daysOfCover ?? Number.POSITIVE_INFINITY) - (b.daysOfCover ?? Number.POSITIVE_INFINITY);
case 'sold_desc': return b.quantitySold - a.quantitySold;
case 'name_asc': return a.name.localeCompare(b.name, 'pt-BR');
case 'need_desc':
default:
return b.suggestedQuantity - a.suggestedQuantity;
}
});
}, [allRows, searchTerm, sortBy, statusFilter]);
const totalPages = Math.ceil(filteredRows.length / itemsPerPage);
const safeCurrentPage = Math.min(currentPage, totalPages || 1);
const startIndex = (safeCurrentPage - 1) * itemsPerPage;
const paginatedRows = filteredRows.slice(startIndex, startIndex + itemsPerPage);
const isRefreshing = isLoading && products.length > 0;
const needRows = allRows.filter(row => row.suggestedQuantity > 0);
const totalSuggestedQuantity = needRows.reduce((total, row) => total + row.suggestedQuantity, 0);
const projectedDemand = allRows.reduce((total, row) => total + row.projectedDemand, 0);
const totalStock = allRows.reduce((total, row) => total + row.stock, 0);
return (
<div className="space-y-6">
<div className="grid grid-cols-1 gap-4 2xl:grid-cols-[minmax(520px,1fr)_auto] 2xl:items-start">
<div>
<h1 className="text-2xl font-bold mb-2 text-zinc-900 dark:text-dark-text">Necessidade de Reposição</h1>
<p className="text-zinc-500 dark:text-dark-muted font-medium">
Demanda projetada pelo ritmo de venda atual comparada com o estoque disponível.
</p>
</div>
<div className="flex flex-col gap-2 sm:flex-row sm:justify-end">
<DateRangePicker
dateRange={dateRange}
onChange={(range) => {
setDateRange(range);
setCurrentPage(1);
}}
/>
<button
onClick={() => {
const exportData = filteredRows.map(row => ({
'ID Produto': row.id,
'Descricao': row.name,
'Status': row.statusLabel,
'Horizonte (dias)': horizonDays,
'Vendido no Periodo': row.quantitySold,
'Media Diaria': row.dailySales.toFixed(2).replace('.', ','),
'Demanda Projetada': row.projectedDemand.toFixed(2).replace('.', ','),
'Estoque Atual': row.stock,
'Cobertura Atual': row.daysOfCover === null ? '' : row.daysOfCover.toFixed(1).replace('.', ','),
'Sugestao Reposicao': row.suggestedQuantity
}));
exportToCSV(exportData, `necessidade_reposicao_${new Date().toISOString().split('T')[0]}.csv`);
}}
className="flex items-center justify-center gap-2 bg-dark-card border border-dark-border px-4 py-2.5 rounded-xl shadow-sm hover:border-brand-primary transition-colors text-sm font-medium text-dark-text cursor-pointer"
title="Exportar para CSV"
>
<Download size={16} className="text-brand-primary" />
<span className="hidden sm:inline">Exportar</span>
</button>
</div>
</div>
<RefreshStatus isRefreshing={isRefreshing} />
<div className="grid grid-cols-1 gap-4 md:grid-cols-4">
<div className="rounded-2xl border border-dark-border bg-dark-card p-5 shadow-sm">
<div className="flex items-start justify-between gap-4">
<div>
<p className="text-xs font-bold uppercase tracking-widest text-dark-muted">Produtos a repor</p>
<p className="mt-2 text-3xl font-bold text-red-300">{formatNumber(needRows.length)}</p>
<p className="mt-1 text-xs font-semibold text-dark-muted">Com estoque abaixo da demanda projetada</p>
</div>
<div className="rounded-xl border border-red-400/25 bg-red-400/10 p-3 text-red-300">
<AlertTriangle className="h-5 w-5" />
</div>
</div>
</div>
<div className="rounded-2xl border border-dark-border bg-dark-card p-5 shadow-sm">
<div className="flex items-start justify-between gap-4">
<div>
<p className="text-xs font-bold uppercase tracking-widest text-dark-muted">Sugestão total</p>
<p className="mt-2 text-3xl font-bold text-dark-text">{formatNumber(totalSuggestedQuantity)}</p>
<p className="mt-1 text-xs font-semibold text-dark-muted">Unidades para cobrir {horizonDays} dias</p>
</div>
<div className="rounded-xl border border-brand-primary/25 bg-brand-primary/10 p-3 text-brand-primary">
<Package className="h-5 w-5" />
</div>
</div>
</div>
<div className="rounded-2xl border border-dark-border bg-dark-card p-5 shadow-sm">
<div className="flex items-start justify-between gap-4">
<div>
<p className="text-xs font-bold uppercase tracking-widest text-dark-muted">Demanda projetada</p>
<p className="mt-2 text-3xl font-bold text-sky-300">{formatNumber(projectedDemand)}</p>
<p className="mt-1 text-xs font-semibold text-dark-muted">Pelo ritmo do período selecionado</p>
</div>
<div className="rounded-xl border border-sky-400/25 bg-sky-400/10 p-3 text-sky-300">
<TrendingUp className="h-5 w-5" />
</div>
</div>
</div>
<div className="rounded-2xl border border-dark-border bg-dark-card p-5 shadow-sm">
<div className="flex items-start justify-between gap-4">
<div>
<p className="text-xs font-bold uppercase tracking-widest text-dark-muted">Produtos cobertos</p>
<p className="mt-2 text-3xl font-bold text-emerald-300">{formatNumber(allRows.filter(row => row.status === 'covered').length)}</p>
<p className="mt-1 text-xs font-semibold text-dark-muted">{formatNumber(totalStock)} unidades em estoque</p>
</div>
<div className="rounded-xl border border-emerald-400/25 bg-emerald-400/10 p-3 text-emerald-300">
<CheckCircle2 className="h-5 w-5" />
</div>
</div>
</div>
</div>
<div className="grid grid-cols-1 gap-3 rounded-2xl border border-dark-border bg-dark-card p-4 shadow-sm lg:grid-cols-[1fr_160px_180px_190px]">
<div className="relative">
<Search className="absolute left-3 top-1/2 h-5 w-5 -translate-y-1/2 text-zinc-400 dark:text-dark-muted" />
<input
type="text"
placeholder="Buscar por nome ou ID..."
value={searchTerm}
onChange={(event) => {
setSearchTerm(event.target.value);
setCurrentPage(1);
}}
className="w-full bg-dark-input border border-dark-border text-dark-text rounded-xl pl-10 pr-4 py-2.5 focus:outline-none focus:border-brand-primary hover:border-brand-primary transition-colors"
/>
</div>
<select
value={horizonDays}
onChange={(event) => {
setHorizonDays(Number(event.target.value));
setCurrentPage(1);
}}
className="h-11 rounded-xl border border-dark-border bg-dark-input px-3 text-sm font-semibold text-dark-text focus:outline-none focus:border-brand-primary cursor-pointer"
>
{horizonOptions.map(days => (
<option key={days} value={days}>{days} dias</option>
))}
</select>
<select
value={statusFilter}
onChange={(event) => {
setStatusFilter(event.target.value as ReplenishmentFilter);
setCurrentPage(1);
}}
className="h-11 rounded-xl border border-dark-border bg-dark-input px-3 text-sm font-semibold text-dark-text focus:outline-none focus:border-brand-primary cursor-pointer"
>
{filterOptions.map(option => (
<option key={option.value} value={option.value}>{option.label}</option>
))}
</select>
<select
value={sortBy}
onChange={(event) => {
setSortBy(event.target.value as ReplenishmentSort);
setCurrentPage(1);
}}
className="h-11 rounded-xl border border-dark-border bg-dark-input px-3 text-sm font-semibold text-dark-text focus:outline-none focus:border-brand-primary cursor-pointer"
>
<option value="need_desc">Maior necessidade</option>
<option value="need_asc">Menor necessidade</option>
<option value="demand_desc">Maior demanda projetada</option>
<option value="stock_asc">Menor estoque</option>
<option value="coverage_asc">Menor cobertura</option>
<option value="sold_desc">Mais vendidos</option>
<option value="name_asc">Nome A-Z</option>
</select>
</div>
{isLoading && products.length === 0 ? (
<ReplenishmentSkeleton />
) : (
<div className={`bg-white dark:bg-dark-card border border-zinc-200 dark:border-dark-border rounded-2xl overflow-hidden shadow-sm ${isRefreshing ? 'refreshing-content' : ''}`} aria-busy={isRefreshing}>
<div className="overflow-x-auto">
<table className="w-full min-w-[1240px] table-fixed text-left text-sm">
<colgroup>
<col className="w-[120px]" />
<col className="w-[360px]" />
<col className="w-[130px]" />
<col className="w-[140px]" />
<col className="w-[120px]" />
<col className="w-[150px]" />
<col className="w-[130px]" />
<col className="w-[110px]" />
</colgroup>
<thead className="bg-zinc-50 dark:bg-dark-header border-b border-zinc-100 dark:border-dark-border text-zinc-500 dark:text-dark-muted">
<tr>
<th className="px-6 py-4 font-bold uppercase tracking-wider text-[10px]">ID Produto</th>
<th className="px-6 py-4 font-bold uppercase tracking-wider text-[10px]">Descrição</th>
<th className="px-6 py-4 font-bold uppercase tracking-wider text-[10px]">Status</th>
<th className="px-6 py-4 font-bold uppercase tracking-wider text-[10px]">Demanda proj.</th>
<th className="px-6 py-4 font-bold uppercase tracking-wider text-[10px]">Estoque</th>
<th className="px-6 py-4 font-bold uppercase tracking-wider text-[10px]">Sugestão reposição</th>
<th className="px-6 py-4 font-bold uppercase tracking-wider text-[10px]">Cobertura</th>
<th className="px-6 py-4 font-bold uppercase tracking-wider text-[10px] text-right">Ações</th>
</tr>
</thead>
<tbody className="divide-y divide-zinc-100 dark:divide-dark-border">
{paginatedRows.map(row => {
const style = statusStyles[row.status];
return (
<tr key={row.id} className="hover:bg-zinc-50/80 dark:hover:bg-dark-input/50 transition-colors">
<td className="px-6 py-2.5 font-mono text-[11px] text-zinc-400 dark:text-dark-muted">#{row.id}</td>
<td className="max-w-0 px-6 py-2.5">
<div className="truncate font-semibold text-zinc-900 dark:text-dark-text" title={row.name}>{row.name}</div>
<div className="text-[10px] text-zinc-400 dark:text-dark-muted font-medium">
Média: {formatNumber(row.dailySales, 2)} un./dia · Vendido: {formatNumber(row.quantitySold)} un.
</div>
</td>
<td className="px-6 py-2.5">
<span className={`inline-flex items-center gap-2 whitespace-nowrap rounded-full border px-2.5 py-1 text-xs font-bold ${style.className}`}>
<span className={`h-2 w-2 rounded-full ${style.dotClass}`} />
{style.label}
</span>
</td>
<td className="px-6 py-2.5 font-bold text-zinc-900 dark:text-dark-text whitespace-nowrap">{formatNumber(row.projectedDemand, 1)} un.</td>
<td className="px-6 py-2.5 font-bold text-zinc-900 dark:text-dark-text whitespace-nowrap">{formatNumber(row.stock)} un.</td>
<td className="px-6 py-2.5 whitespace-nowrap">
<span className={row.suggestedQuantity > 0 ? 'font-bold text-red-300' : 'font-bold text-emerald-300'}>
{formatNumber(row.suggestedQuantity)} un.
</span>
</td>
<td className="px-6 py-2.5 font-bold text-zinc-900 dark:text-dark-text whitespace-nowrap">{formatDays(row.daysOfCover)}</td>
<td className="px-4 py-2.5 text-right">
<Link
to={`/products/${row.id}`}
className="inline-flex items-center whitespace-nowrap text-xs font-bold text-brand-primary hover:opacity-80 transition-opacity bg-brand-primary/10 px-3 py-1.5 rounded-lg cursor-pointer"
>
Ver produto
</Link>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
{!filteredRows.length && (
<div className="px-6 py-12 text-center">
<Package className="mx-auto h-10 w-10 text-dark-muted" />
<p className="mt-4 text-sm font-bold text-dark-text">Nenhum produto encontrado.</p>
<p className="mt-1 text-sm text-dark-muted">Ajuste os filtros, a busca ou o período selecionado.</p>
</div>
)}
<PaginationControls
totalItems={filteredRows.length}
currentPage={safeCurrentPage}
totalPages={totalPages}
pageSize={itemsPerPage}
pageSizeOptions={[10, 20, 50, 100]}
itemLabel="produtos"
pageSizeLabel="itens por página"
startIndex={startIndex}
endIndex={Math.min(startIndex + itemsPerPage, filteredRows.length)}
onPageChange={setCurrentPage}
onPageSizeChange={(pageSize) => {
setItemsPerPage(pageSize);
setCurrentPage(1);
}}
/>
</div>
)}
</div>
);
};
export default Replenishment;