diff --git a/src/App.tsx b/src/App.tsx index a04ff30..ff81bee 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -9,6 +9,7 @@ const Products = React.lazy(() => import('./pages/Products')); const ProductDetails = React.lazy(() => import('./pages/ProductDetails')); const ProductGroupDetails = React.lazy(() => import('./pages/ProductGroupDetails')); const Replenishment = React.lazy(() => import('./pages/Replenishment')); +const Cutting = React.lazy(() => import('./pages/Cutting')); const ProductionOrders = React.lazy(() => import('./pages/ProductionOrders')); const Clients = React.lazy(() => import('./pages/Clients')); const ClientDetails = React.lazy(() => import('./pages/ClientDetails')); @@ -50,6 +51,7 @@ function App() { } /> } /> } /> + } /> } /> } /> } /> diff --git a/src/analytics/cutting.test.ts b/src/analytics/cutting.test.ts new file mode 100644 index 0000000..fabf705 --- /dev/null +++ b/src/analytics/cutting.test.ts @@ -0,0 +1,64 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; + +import { buildCutPlan, classifyCutFamily } from './cutting.ts'; +import type { DateRange, ProductAnalyticsItem } from '../types.ts'; + +const range: DateRange = { + start: new Date(2026, 6, 1), + end: new Date(2026, 6, 7) +}; + +const product = (overrides: Partial): ProductAnalyticsItem => ({ + id: 'SKU-1', + name: 'BASE LISA CAMISETA COR PRETO TAMANHO - M', + quantitySold: 70, + revenue: 700, + orderLineCount: 10, + lastPrice: 10, + stock: 20, + firstSaleDate: '2026-07-01', + lastSaleDate: '2026-07-07', + ...overrides +}); + +test('classifyCutFamily maps known product bases to internal cut families', () => { + assert.equal(classifyCutFamily('BASE LISA CAMISETA').key, 'BLCS'); + assert.equal(classifyCutFamily('BASE LISA CAMISETA OVER').key, 'BLOS'); + assert.equal(classifyCutFamily('BASE LISA MOLETOM CANGURU').key, 'BLPM'); + assert.equal(classifyCutFamily('BONÉ').key, 'OUTROS'); +}); + +test('buildCutPlan calculates projected cut need from sales pace and stock', () => { + const plan = buildCutPlan([product({})], range, 14); + const [row] = plan.needRows; + + assert.equal(row.dailySales, 10); + assert.equal(row.projectedDemand, 140); + assert.equal(row.availableQuantity, 20); + assert.equal(row.suggestedCutQuantity, 120); + assert.equal(plan.summary.suggestedCutQuantity, 120); +}); + +test('buildCutPlan subtracts open production quantity from suggested cut need', () => { + const plan = buildCutPlan([product({ id: 'SKU-1' })], range, 14, { 'SKU-1': 100 }); + const [row] = plan.needRows; + + assert.equal(row.availableQuantity, 120); + assert.equal(row.suggestedCutQuantity, 20); +}); + +test('buildCutPlan marks products that cannot be planned cleanly for cutting', () => { + const plan = buildCutPlan([ + product({ + id: 'SKU-2', + name: 'BONÉ PRETO', + quantitySold: 70, + stock: 0 + }) + ], range, 7); + + assert.equal(plan.needRows[0].family.key, 'OUTROS'); + assert.deepEqual(plan.needRows[0].issues, ['missing_family_rule', 'missing_color', 'missing_size']); + assert.equal(plan.summary.rowsWithIssues, 1); +}); diff --git a/src/analytics/cutting.ts b/src/analytics/cutting.ts new file mode 100644 index 0000000..7b7447a --- /dev/null +++ b/src/analytics/cutting.ts @@ -0,0 +1,199 @@ +import type { DateRange, ProductAnalyticsItem } from '../types'; +import { parseProductName, sortProductSizes } from '../productParsing.ts'; + +export type CutFamilyKey = 'BLCS' | 'BLOS' | 'BLMC' | 'BLPM' | 'OUTROS'; +export type CutIssue = 'missing_family_rule' | 'missing_color' | 'missing_size'; + +export interface CutFamilyRule { + key: CutFamilyKey; + label: string; + materialLabel: string; + keywords: string[]; +} + +export interface CutPlanSkuRow extends ProductAnalyticsItem { + family: CutFamilyRule; + baseName: string; + color: string; + size: string; + dailySales: number; + projectedDemand: number; + openProductionQuantity: number; + availableQuantity: number; + suggestedCutQuantity: number; + daysOfCover: number | null; + issues: CutIssue[]; +} + +export interface CutPlanFamilySummary { + family: CutFamilyRule; + skuCount: number; + colorCount: number; + sizeCount: number; + quantitySold: number; + stock: number; + projectedDemand: number; + suggestedCutQuantity: number; +} + +export interface CutPlanSummary { + skuCount: number; + familiesWithNeed: number; + colorsWithNeed: number; + sizesWithNeed: number; + totalSold: number; + totalStock: number; + projectedDemand: number; + suggestedCutQuantity: number; + rowsWithIssues: number; +} + +export interface CutPlan { + rows: CutPlanSkuRow[]; + needRows: CutPlanSkuRow[]; + familySummaries: CutPlanFamilySummary[]; + summary: CutPlanSummary; +} + +export const CUT_FAMILY_RULES: CutFamilyRule[] = [ + { + key: 'BLPM', + label: 'Moletom', + materialLabel: 'BLPM', + keywords: ['MOLETOM'] + }, + { + key: 'BLOS', + label: 'Camiseta over', + materialLabel: 'BLOS', + keywords: ['OVER'] + }, + { + key: 'BLMC', + label: 'Camiseta infantil', + materialLabel: 'BLMC', + keywords: ['INFANTIL', 'KIDS'] + }, + { + key: 'BLCS', + label: 'Camiseta regular', + materialLabel: 'BLCS', + keywords: ['CAMISETA'] + } +]; + +export const OUTROS_RULE: CutFamilyRule = { + key: 'OUTROS', + label: 'Sem regra', + materialLabel: 'Pendente', + keywords: [] +}; + +export 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 normalizeRuleText = (value: string) => ( + value + .normalize('NFD') + .replace(/\p{Diacritic}/gu, '') + .toUpperCase() +); + +export const classifyCutFamily = (baseName: string): CutFamilyRule => { + const normalizedName = normalizeRuleText(baseName); + return CUT_FAMILY_RULES.find(rule => ( + rule.keywords.some(keyword => normalizedName.includes(normalizeRuleText(keyword))) + )) || OUTROS_RULE; +}; + +export const buildCutPlan = ( + products: ProductAnalyticsItem[], + dateRange: DateRange, + targetCoverageDays: number, + openProductionByProductId: Record = {} +): CutPlan => { + const rangeDays = getRangeDays(dateRange); + + const rows = products.map(product => { + const metadata = parseProductName(product.name); + const family = classifyCutFamily(metadata.baseName); + const dailySales = product.quantitySold / rangeDays; + const projectedDemand = dailySales * targetCoverageDays; + const openProductionQuantity = openProductionByProductId[product.id] || 0; + const availableQuantity = product.stock + openProductionQuantity; + const suggestedCutQuantity = Math.max(0, Math.ceil(projectedDemand - availableQuantity)); + const daysOfCover = dailySales > 0 ? availableQuantity / dailySales : null; + const issues: CutIssue[] = []; + + if (family.key === 'OUTROS') issues.push('missing_family_rule'); + if (!metadata.color) issues.push('missing_color'); + if (!metadata.size) issues.push('missing_size'); + + return { + ...product, + family, + baseName: metadata.baseName, + color: metadata.color, + size: metadata.size, + dailySales, + projectedDemand, + openProductionQuantity, + availableQuantity, + suggestedCutQuantity, + daysOfCover, + issues + }; + }); + + const needRows = rows.filter(row => row.suggestedCutQuantity > 0); + const familyGroups = new Map(); + needRows.forEach(row => { + const group = familyGroups.get(row.family.key) || []; + group.push(row); + familyGroups.set(row.family.key, group); + }); + + const familySummaries = Array.from(familyGroups.values()) + .map(group => { + const first = group[0]; + const colors = new Set(group.map(row => row.color).filter(Boolean)); + const sizes = sortProductSizes(Array.from(new Set(group.map(row => row.size).filter(Boolean)))); + + return { + family: first.family, + skuCount: group.length, + colorCount: colors.size, + sizeCount: sizes.length, + quantitySold: group.reduce((total, row) => total + row.quantitySold, 0), + stock: group.reduce((total, row) => total + row.stock, 0), + projectedDemand: group.reduce((total, row) => total + row.projectedDemand, 0), + suggestedCutQuantity: group.reduce((total, row) => total + row.suggestedCutQuantity, 0) + }; + }) + .sort((a, b) => b.suggestedCutQuantity - a.suggestedCutQuantity); + + const colorsWithNeed = new Set(needRows.map(row => row.color).filter(Boolean)); + const sizesWithNeed = new Set(needRows.map(row => row.size).filter(Boolean)); + + return { + rows, + needRows, + familySummaries, + summary: { + skuCount: needRows.length, + familiesWithNeed: familySummaries.length, + colorsWithNeed: colorsWithNeed.size, + sizesWithNeed: sizesWithNeed.size, + totalSold: needRows.reduce((total, row) => total + row.quantitySold, 0), + totalStock: needRows.reduce((total, row) => total + row.stock, 0), + projectedDemand: needRows.reduce((total, row) => total + row.projectedDemand, 0), + suggestedCutQuantity: needRows.reduce((total, row) => total + row.suggestedCutQuantity, 0), + rowsWithIssues: needRows.filter(row => row.issues.length > 0).length + } + }; +}; diff --git a/src/components/Layout.tsx b/src/components/Layout.tsx index b0f0f2f..58497c7 100644 --- a/src/components/Layout.tsx +++ b/src/components/Layout.tsx @@ -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, ShoppingCart } from 'lucide-react'; +import { LayoutDashboard, Users, BarChart3, ChevronLeft, ChevronRight, Package, LogOut, Megaphone, Grid3X3, Shield, Moon, Sun, ClipboardList, ShoppingCart, Scissors } from 'lucide-react'; import type { DateRange, OrderData } from '../types'; import { isSuperAdmin, logout } from '../dataService'; import { rangeForLastDays } from '../dateRanges'; @@ -63,6 +63,7 @@ const Layout = () => { { name: 'Dashboard', href: '/graph', icon: LayoutDashboard }, { name: 'Produtos', href: '/products', icon: Package }, { name: 'Reposição', href: '/replenishment', icon: ShoppingCart }, + { name: 'Corte', href: '/cutting', icon: Scissors }, { name: 'Ordens de Produção', href: '/production-orders', icon: ClipboardList }, { name: 'Clientes', href: '/clients', icon: Users }, { name: 'RFV', href: '/rfm', icon: Grid3X3 }, diff --git a/src/pages/Cutting.tsx b/src/pages/Cutting.tsx new file mode 100644 index 0000000..df165ae --- /dev/null +++ b/src/pages/Cutting.tsx @@ -0,0 +1,475 @@ +import { useEffect, useMemo, useState } from 'react'; +import { Link, useOutletContext } from 'react-router-dom'; +import { AlertTriangle, Download, Layers3, Package, Palette, Ruler, Scissors, Search } from 'lucide-react'; +import DateRangePicker from '../components/DateRangePicker'; +import PaginationControls from '../components/PaginationControls'; +import RefreshStatus from '../components/RefreshStatus'; +import { CUT_FAMILY_RULES, buildCutPlan, type CutFamilyKey, type CutIssue, type CutPlanSkuRow } from '../analytics/cutting'; +import { exportToCSV, fetchProductAnalytics } from '../dataService'; +import type { DateRange, ProductAnalyticsItem } from '../types'; + +type CutFilter = 'need' | 'all' | 'issues' | 'covered'; +type CutSort = 'need_desc' | 'need_asc' | 'demand_desc' | 'stock_asc' | 'sold_desc' | 'name_asc'; + +const coverageTargetOptions = [7, 15, 30, 60]; +const familyOptions: Array<{ value: CutFamilyKey | 'all'; label: string }> = [ + { value: 'all', label: 'Todas famílias' }, + ...CUT_FAMILY_RULES.map(rule => ({ value: rule.key, label: `${rule.materialLabel} · ${rule.label}` })), + { value: 'OUTROS', label: 'Sem regra' } +]; + +const filterOptions: Array<{ value: CutFilter; label: string }> = [ + { value: 'need', label: 'Com necessidade' }, + { value: 'all', label: 'Todos' }, + { value: 'issues', label: 'Pendências' }, + { value: 'covered', label: 'Sem necessidade' } +]; + +const issueLabels: Record = { + missing_family_rule: 'Sem família', + missing_color: 'Sem cor', + missing_size: 'Sem tamanho' +}; + +const familyStyles: Record = { + BLCS: 'border-emerald-400/30 bg-emerald-400/10 text-emerald-300', + BLOS: 'border-sky-400/30 bg-sky-400/10 text-sky-300', + BLMC: 'border-amber-400/30 bg-amber-400/10 text-amber-300', + BLPM: 'border-purple-400/30 bg-purple-400/10 text-purple-300', + OUTROS: 'border-zinc-500/30 bg-zinc-500/10 text-zinc-300' +}; + +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 CuttingSkeleton = () => ( +
+
+
+ {[0, 1, 2, 3, 4, 5, 6, 7, 8].map(item =>
)} +
+
+
+ {[0, 1, 2, 3, 4, 5, 6, 7].map(row => ( +
+ {[0, 1, 2, 3, 4, 5, 6, 7, 8].map(item =>
)} +
+ ))} +
+
+); + +const Cutting = () => { + const { dateRange, setDateRange } = useOutletContext<{ + dateRange: DateRange, + setDateRange: (range: DateRange) => void + }>(); + const [products, setProducts] = useState([]); + const [isLoading, setIsLoading] = useState(true); + const [searchTerm, setSearchTerm] = useState(''); + const [targetCoverageDays, setTargetCoverageDays] = useState(30); + const [familyFilter, setFamilyFilter] = useState('all'); + const [cutFilter, setCutFilter] = useState('need'); + const [sortBy, setSortBy] = useState('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 cutPlan = useMemo(() => buildCutPlan(products, dateRange, targetCoverageDays), [dateRange, products, targetCoverageDays]); + + const filteredRows = useMemo(() => { + const normalizedSearch = searchTerm.trim().toLowerCase(); + const searchedRows = normalizedSearch + ? cutPlan.rows.filter(row => ( + row.name.toLowerCase().includes(normalizedSearch) || + row.id.toLowerCase().includes(normalizedSearch) || + row.baseName.toLowerCase().includes(normalizedSearch) || + row.color.toLowerCase().includes(normalizedSearch) + )) + : cutPlan.rows; + + const familyRows = familyFilter === 'all' + ? searchedRows + : searchedRows.filter(row => row.family.key === familyFilter); + + const statusRows = familyRows.filter(row => { + if (cutFilter === 'all') return true; + if (cutFilter === 'need') return row.suggestedCutQuantity > 0; + if (cutFilter === 'issues') return row.issues.length > 0; + return row.suggestedCutQuantity === 0; + }); + + return [...statusRows].sort((a, b) => { + switch (sortBy) { + case 'need_asc': return a.suggestedCutQuantity - b.suggestedCutQuantity; + case 'demand_desc': return b.projectedDemand - a.projectedDemand; + case 'stock_asc': return a.stock - b.stock; + 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.suggestedCutQuantity - a.suggestedCutQuantity; + } + }); + }, [cutFilter, cutPlan.rows, familyFilter, searchTerm, sortBy]); + + 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 exportRows = () => { + exportToCSV(filteredRows.map(row => ({ + 'ID Produto': row.id, + 'Descrição': row.name, + 'Família': row.family.label, + 'Material': row.family.materialLabel, + 'Cor': row.color, + 'Tamanho': row.size, + 'Vendido no período': row.quantitySold, + 'Média diária': row.dailySales.toFixed(2).replace('.', ','), + 'Demanda projetada': row.projectedDemand.toFixed(2).replace('.', ','), + 'Estoque': row.stock, + 'OP aberta': row.openProductionQuantity, + 'Disponível': row.availableQuantity, + 'Necessidade corte': row.suggestedCutQuantity, + 'Cobertura': row.daysOfCover === null ? '' : row.daysOfCover.toFixed(1).replace('.', ','), + 'Pendências': row.issues.map(issue => issueLabels[issue]).join(' | ') + })), `plano_corte_${new Date().toISOString().split('T')[0]}.csv`); + }; + + const renderIssueBadge = (row: CutPlanSkuRow) => { + if (!row.issues.length) { + return OK; + } + + return ( + + + {row.issues.map(issue => issueLabels[issue]).join(', ')} + + ); + }; + + return ( +
+
+
+

Plano de Corte

+

+ Necessidade por família, cor e tamanho calculada com vendas, estoque e cobertura alvo. +

+
+ +
+ { + setDateRange(range); + setCurrentPage(1); + }} + /> + + +
+
+ + + +
+
+
+
+

Unidades a cortar

+

{formatNumber(cutPlan.summary.suggestedCutQuantity)}

+

{formatNumber(cutPlan.summary.skuCount)} SKUs com necessidade

+
+
+ +
+
+
+ +
+
+
+

Famílias

+

{formatNumber(cutPlan.summary.familiesWithNeed)}

+

Com necessidade no período

+
+
+ +
+
+
+ +
+
+
+

Cores / tamanhos

+

+ {formatNumber(cutPlan.summary.colorsWithNeed)} / {formatNumber(cutPlan.summary.sizesWithNeed)} +

+

Com corte sugerido

+
+
+ +
+
+
+ +
+
+
+

Pendências

+

{formatNumber(cutPlan.summary.rowsWithIssues)}

+

Sem família, cor ou tamanho

+
+
+ +
+
+
+
+ + {!!cutPlan.familySummaries.length && ( +
+ {cutPlan.familySummaries.map(summary => ( +
+
+
+ + {summary.family.materialLabel} + +

{summary.family.label}

+
+ +
+

{formatNumber(summary.suggestedCutQuantity)} un.

+

+ {formatNumber(summary.skuCount)} SKUs · {formatNumber(summary.colorCount)} cores · {formatNumber(summary.sizeCount)} tamanhos +

+
+ ))} +
+ )} + +
+
+ + { + setSearchTerm(event.target.value); + setCurrentPage(1); + }} + className="w-full rounded-xl border border-dark-border bg-dark-input py-2.5 pl-10 pr-4 text-dark-text transition-colors hover:border-brand-primary focus:border-brand-primary focus:outline-none" + /> +
+ + + + + + + + +
+ + {isLoading && products.length === 0 ? ( + + ) : ( +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {paginatedRows.map(row => ( + + + + + + + + + + + + + + ))} + +
ID ProdutoDescriçãoFamíliaCorTamanhoDemanda proj.EstoqueDisponívelNecessidadePendênciasAções
#{row.id} +
{row.name}
+
+ Média: {formatNumber(row.dailySales, 2)} un./dia · Cobertura: {formatDays(row.daysOfCover)} +
+
+ + {row.family.materialLabel} + + + + + {row.color || '-'} + + + + + {row.size || '-'} + + {formatNumber(row.projectedDemand, 1)} un.{formatNumber(row.stock)} un. + {formatNumber(row.availableQuantity)} un. + {!!row.openProductionQuantity && incl. OP} + + 0 ? 'font-bold text-red-300' : 'font-bold text-emerald-300'}> + {formatNumber(row.suggestedCutQuantity)} un. + + {renderIssueBadge(row)} + + + Ver SKU + +
+
+ + {!filteredRows.length && ( +
+ +

Nenhum item encontrado.

+

Ajuste a busca, família, status ou período selecionado.

+
+ )} + + { + setItemsPerPage(pageSize); + setCurrentPage(1); + }} + /> +
+ )} +
+ ); +}; + +export default Cutting;