Compare commits

..

2 Commits

Author SHA1 Message Date
Cauê Faleiros
56cff262ab Add grouped replenishment analysis
All checks were successful
Build and Deploy / build-and-deploy (push) Successful in 2m1s
2026-07-07 09:59:07 -03:00
Cauê Faleiros
e0c71de3eb Add replenishment needs view 2026-07-07 09:48:39 -03:00
6 changed files with 639 additions and 3 deletions

View File

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

View File

@@ -1,6 +1,6 @@
import { useState, useEffect } from 'react';
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 { isSuperAdmin, logout } from '../dataService';
import { rangeForLastDays } from '../dateRanges';
@@ -62,6 +62,7 @@ const Layout = () => {
const appNavigation = [
{ name: 'Dashboard', href: '/graph', icon: LayoutDashboard },
{ name: 'Produtos', href: '/products', icon: Package },
{ name: 'Reposição', href: '/replenishment', icon: PackagePlus },
{ name: 'Ordens de Produção', href: '/production-orders', icon: ClipboardList },
{ name: 'Clientes', href: '/clients', icon: Users },
{ name: 'RFV', href: '/rfm', icon: Grid3X3 },

View File

@@ -6,6 +6,7 @@ import DateRangePicker from '../components/DateRangePicker';
import RefreshStatus from '../components/RefreshStatus';
import type { DateRange, ProductDetailsAnalytics } from '../types';
import { fetchProductDetailsAnalytics } from '../dataService';
import { parseProductName } from '../productParsing';
const CHART_GRID_COLOR = 'var(--chart-grid)';
const CHART_AXIS_COLOR = 'var(--chart-axis)';
@@ -351,13 +352,26 @@ const ProductDetails = () => {
<div className="space-y-3">
{variantBreakdown.map(variant => {
const width = maxVariantQuantity ? Math.max(4, (variant.quantitySold / maxVariantQuantity) * 100) : 0;
const metadata = parseProductName(variant.name);
return (
<div key={variant.id} className="rounded-xl border border-dark-border bg-dark-input/45 p-4">
<div className="flex flex-col gap-2 md:flex-row md:items-start md:justify-between">
<div className="min-w-0">
<div className="truncate text-sm font-bold text-dark-text">{variant.name}</div>
<div className="mt-1 text-[11px] font-medium text-dark-muted">#{variant.id}</div>
<div className="mt-1 flex flex-wrap items-center gap-2 text-[11px] font-medium text-dark-muted">
<span>#{variant.id}</span>
{metadata.color && (
<span className="rounded-full border border-sky-400/25 bg-sky-400/10 px-2 py-0.5 font-bold text-sky-300">
{metadata.color}
</span>
)}
{metadata.size && (
<span className="rounded-full border border-emerald-400/25 bg-emerald-400/10 px-2 py-0.5 font-bold text-emerald-300">
Tam. {metadata.size}
</span>
)}
</div>
</div>
<div className="flex shrink-0 gap-5 text-right text-xs">
<div>

View File

@@ -1,6 +1,6 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { Link, useOutletContext } from 'react-router-dom';
import { Download, Filter, Package, PackageCheck, Search, TrendingDown, TrendingUp, X } from 'lucide-react';
import { Download, Filter, Package, PackageCheck, PackagePlus, Search, TrendingDown, TrendingUp, X } from 'lucide-react';
import PaginationControls from '../components/PaginationControls';
import RefreshStatus from '../components/RefreshStatus';
import type { DateRange, ProductAnalyticsItem } from '../types';
@@ -569,6 +569,15 @@ const Products = () => {
)}
</div>
<Link
to="/replenishment?status=need&view=group"
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="Ver necessidade de reposição"
>
<PackagePlus size={16} className="text-brand-primary" />
<span className="hidden sm:inline">Reposição</span>
</Link>
<button
onClick={() => {
const exportData = productsData.map(product => ({

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

@@ -0,0 +1,573 @@
import { useEffect, useMemo, useState } from 'react';
import { Link, useOutletContext, useSearchParams } 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';
import { parseProductName, sortProductSizes } from '../productParsing';
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 ReplenishmentView = 'sku' | 'group';
type ReplenishmentRow = ProductAnalyticsItem & {
dailySales: number;
projectedDemand: number;
suggestedQuantity: number;
daysOfCover: number | null;
status: ReplenishmentStatus;
statusLabel: string;
baseName: string;
color: string;
size: string;
productIds: string[];
productCount: number;
sizes: 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 [searchParams] = useSearchParams();
const [products, setProducts] = useState<ProductAnalyticsItem[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [searchTerm, setSearchTerm] = useState('');
const [horizonDays, setHorizonDays] = useState(30);
const [statusFilter, setStatusFilter] = useState<ReplenishmentFilter>(() => {
const filter = searchParams.get('status') as ReplenishmentFilter | null;
return filter && filterOptions.some(option => option.value === filter) ? filter : 'need';
});
const [sortBy, setSortBy] = useState<ReplenishmentSort>('need_desc');
const [viewMode, setViewMode] = useState<ReplenishmentView>(() => searchParams.get('view') === 'group' ? 'group' : 'sku');
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 = product.stock <= 0
? 'no_stock'
: dailySales <= 0
? 'no_sales'
: suggestedQuantity > 0
? 'need'
: 'covered';
const metadata = parseProductName(product.name);
return {
...product,
dailySales,
projectedDemand,
suggestedQuantity,
daysOfCover,
status,
statusLabel: statusStyles[status].label,
baseName: metadata.baseName,
color: metadata.color,
size: metadata.size,
productIds: [product.id],
productCount: 1,
sizes: metadata.size ? [metadata.size] : []
};
});
}, [dateRange, horizonDays, products]);
const groupedRows = useMemo<ReplenishmentRow[]>(() => {
const groups = new Map<string, ReplenishmentRow[]>();
allRows.forEach(row => {
const key = `${row.baseName.toLowerCase()}::${row.color.toLowerCase()}`;
const group = groups.get(key) || [];
group.push(row);
groups.set(key, group);
});
return Array.from(groups.values()).map(group => {
const first = group[0];
const quantitySold = group.reduce((total, row) => total + row.quantitySold, 0);
const revenue = group.reduce((total, row) => total + row.revenue, 0);
const stock = group.reduce((total, row) => total + row.stock, 0);
const dailySales = group.reduce((total, row) => total + row.dailySales, 0);
const projectedDemand = group.reduce((total, row) => total + row.projectedDemand, 0);
const suggestedQuantity = group.reduce((total, row) => total + row.suggestedQuantity, 0);
const orderLineCount = group.reduce((total, row) => total + row.orderLineCount, 0);
const daysOfCover = dailySales > 0 ? stock / dailySales : null;
const status: ReplenishmentStatus = stock <= 0
? 'no_stock'
: dailySales <= 0
? 'no_sales'
: suggestedQuantity > 0
? 'need'
: 'covered';
const sizes = sortProductSizes(Array.from(new Set(group.flatMap(row => row.sizes))));
const productIds = group.map(row => row.id);
const name = first.color ? `${first.baseName} · ${first.color}` : first.baseName;
return {
...first,
id: productIds[0],
name,
quantitySold,
revenue,
stock,
orderLineCount,
dailySales,
projectedDemand,
suggestedQuantity,
daysOfCover,
status,
statusLabel: statusStyles[status].label,
productIds,
productCount: group.length,
sizes,
lastPrice: group.length ? revenue / Math.max(1, quantitySold) : first.lastPrice
};
});
}, [allRows]);
const activeRows = viewMode === 'group' ? groupedRows : allRows;
const filteredRows = useMemo(() => {
const normalizedSearch = searchTerm.trim().toLowerCase();
const searchedRows = normalizedSearch
? activeRows.filter(row =>
row.name.toLowerCase().includes(normalizedSearch) ||
row.id.toLowerCase().includes(normalizedSearch) ||
row.productIds.some(id => id.toLowerCase().includes(normalizedSearch))
)
: activeRows;
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;
}
});
}, [activeRows, 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 = activeRows.filter(row => row.suggestedQuantity > 0);
const totalSuggestedQuantity = needRows.reduce((total, row) => total + row.suggestedQuantity, 0);
const projectedDemand = activeRows.reduce((total, row) => total + row.projectedDemand, 0);
const totalStock = activeRows.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 => ({
'Tipo': viewMode === 'group' ? 'Grupo' : 'SKU',
'ID Produto': viewMode === 'group' ? row.productIds.join(' | ') : row.id,
'Descricao': row.name,
'Cor': row.color,
'Tamanhos': row.sizes.join(' | '),
'SKUs': row.productCount,
'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">
{viewMode === 'group' ? 'Grupos' : 'SKUs'} 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">{viewMode === 'group' ? 'Grupos cobertos' : 'Produtos cobertos'}</p>
<p className="mt-2 text-3xl font-bold text-emerald-300">{formatNumber(activeRows.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 xl:grid-cols-[auto_1fr_160px_180px_190px]">
<div className="inline-flex rounded-xl border border-dark-border bg-dark-input p-1">
{[
{ key: 'sku' as const, label: 'SKU' },
{ key: 'group' as const, label: 'Grupo' }
].map(view => (
<button
key={view.key}
type="button"
onClick={() => {
setViewMode(view.key);
setCurrentPage(1);
}}
className={`rounded-lg px-4 py-2 text-sm font-bold transition-colors cursor-pointer ${
viewMode === view.key
? 'bg-brand-primary text-brand-contrast'
: 'text-dark-muted hover:bg-dark-card hover:text-dark-text'
}`}
>
{view.label}
</button>
))}
</div>
<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-[1320px] table-fixed text-left text-sm">
<colgroup>
<col className="w-[120px]" />
<col className="w-[390px]" />
<col className="w-[130px]" />
<col className="w-[140px]" />
<col className="w-[120px]" />
<col className="w-[150px]" />
<col className="w-[130px]" />
<col className="w-[140px]" />
</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]">{viewMode === 'group' ? 'SKUs' : 'ID Produto'}</th>
<th className="px-6 py-4 font-bold uppercase tracking-wider text-[10px]">{viewMode === 'group' ? 'Grupo / cor' : '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">
{viewMode === 'group' ? `${row.productCount} SKUs` : `#${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">
{viewMode === 'group' && row.sizes.length ? `Tamanhos: ${row.sizes.join(', ')} · ` : ''}
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"
>
{viewMode === 'group' ? 'Ver líder' : '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;

37
src/productParsing.ts Normal file
View File

@@ -0,0 +1,37 @@
const sizeOrder = ['2', '4', '6', '8', '10', '12', '14', '16', 'PP', 'P', 'M', 'G', 'GG', 'XG', 'G1', 'G2', 'G3', 'G4', 'G5'];
const sizeSet = new Set(sizeOrder);
export const normalizeProductText = (value: string) => value.replace(/\s+/g, ' ').trim();
export const sortProductSizes = (sizes: string[]) => [...sizes].sort((a, b) => {
const indexA = sizeOrder.indexOf(a);
const indexB = sizeOrder.indexOf(b);
if (indexA !== -1 || indexB !== -1) {
return (indexA === -1 ? Number.MAX_SAFE_INTEGER : indexA) - (indexB === -1 ? Number.MAX_SAFE_INTEGER : indexB);
}
return a.localeCompare(b, 'pt-BR');
});
export const parseProductName = (name: string) => {
const cleanName = normalizeProductText(name);
const explicitSizeMatch = cleanName.match(/\bTAMANHO\s*-?\s*([A-Z0-9]+)\b/i);
const trailingTokenMatch = cleanName.match(/(?:\s+-\s+|\s)([A-Z0-9]+)$/i);
const trailingToken = trailingTokenMatch?.[1]?.toUpperCase() || '';
const size = (explicitSizeMatch?.[1] || (sizeSet.has(trailingToken) ? trailingToken : '')).toUpperCase();
const colorMatch = cleanName.match(/\bCOR\s+(.+?)(?:\s+TAMANHO|\s+-\s+[A-Z0-9]+$|$)/i);
const color = normalizeProductText(colorMatch?.[1] || '');
let baseName = cleanName
.replace(/\bCOR\s+.+?(?:\s+TAMANHO\s*-?\s*[A-Z0-9]+|\s+-\s+[A-Z0-9]+$|$)/i, '')
.replace(/\bTAMANHO\s*-?\s*[A-Z0-9]+\b/i, '')
.replace(/\s+-\s*[A-Z0-9]+$/i, '');
baseName = normalizeProductText(baseName.replace(/\s+-\s*$/g, ''));
return {
baseName: baseName || cleanName,
color,
size
};
};