Add native cutting plan page
This commit is contained in:
@@ -9,6 +9,7 @@ const Products = React.lazy(() => import('./pages/Products'));
|
|||||||
const ProductDetails = React.lazy(() => import('./pages/ProductDetails'));
|
const ProductDetails = React.lazy(() => import('./pages/ProductDetails'));
|
||||||
const ProductGroupDetails = React.lazy(() => import('./pages/ProductGroupDetails'));
|
const ProductGroupDetails = React.lazy(() => import('./pages/ProductGroupDetails'));
|
||||||
const Replenishment = React.lazy(() => import('./pages/Replenishment'));
|
const Replenishment = React.lazy(() => import('./pages/Replenishment'));
|
||||||
|
const Cutting = React.lazy(() => import('./pages/Cutting'));
|
||||||
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'));
|
||||||
@@ -50,6 +51,7 @@ function App() {
|
|||||||
<Route path="products/groups/:groupKey" element={<ProductGroupDetails />} />
|
<Route path="products/groups/:groupKey" element={<ProductGroupDetails />} />
|
||||||
<Route path="products/:id" element={<ProductDetails />} />
|
<Route path="products/:id" element={<ProductDetails />} />
|
||||||
<Route path="replenishment" element={<Replenishment />} />
|
<Route path="replenishment" element={<Replenishment />} />
|
||||||
|
<Route path="cutting" element={<Cutting />} />
|
||||||
<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 />} />
|
||||||
|
|||||||
64
src/analytics/cutting.test.ts
Normal file
64
src/analytics/cutting.test.ts
Normal file
@@ -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>): 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);
|
||||||
|
});
|
||||||
199
src/analytics/cutting.ts
Normal file
199
src/analytics/cutting.ts
Normal file
@@ -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<string, number> = {}
|
||||||
|
): CutPlan => {
|
||||||
|
const rangeDays = getRangeDays(dateRange);
|
||||||
|
|
||||||
|
const rows = products.map<CutPlanSkuRow>(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<CutFamilyKey, CutPlanSkuRow[]>();
|
||||||
|
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<CutPlanFamilySummary>(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
|
||||||
|
}
|
||||||
|
};
|
||||||
|
};
|
||||||
@@ -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, 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 type { DateRange, OrderData } from '../types';
|
||||||
import { isSuperAdmin, logout } from '../dataService';
|
import { isSuperAdmin, logout } from '../dataService';
|
||||||
import { rangeForLastDays } from '../dateRanges';
|
import { rangeForLastDays } from '../dateRanges';
|
||||||
@@ -63,6 +63,7 @@ const Layout = () => {
|
|||||||
{ 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: ShoppingCart },
|
{ name: 'Reposição', href: '/replenishment', icon: ShoppingCart },
|
||||||
|
{ name: 'Corte', href: '/cutting', icon: Scissors },
|
||||||
{ 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 },
|
||||||
|
|||||||
475
src/pages/Cutting.tsx
Normal file
475
src/pages/Cutting.tsx
Normal file
@@ -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<CutIssue, string> = {
|
||||||
|
missing_family_rule: 'Sem família',
|
||||||
|
missing_color: 'Sem cor',
|
||||||
|
missing_size: 'Sem tamanho'
|
||||||
|
};
|
||||||
|
|
||||||
|
const familyStyles: Record<CutFamilyKey, string> = {
|
||||||
|
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 = () => (
|
||||||
|
<div className="overflow-hidden rounded-2xl border border-dark-border bg-dark-card shadow-sm" aria-label="Carregando plano de corte">
|
||||||
|
<div className="border-b border-dark-border p-4">
|
||||||
|
<div className="grid grid-cols-[120px_1.4fr_130px_110px_110px_120px_130px_130px_110px] gap-6">
|
||||||
|
{[0, 1, 2, 3, 4, 5, 6, 7, 8].map(item => <div key={item} className="skeleton h-3" />)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="divide-y divide-dark-border">
|
||||||
|
{[0, 1, 2, 3, 4, 5, 6, 7].map(row => (
|
||||||
|
<div key={row} className="grid grid-cols-[120px_1.4fr_130px_110px_110px_120px_130px_130px_110px] gap-6 px-6 py-4">
|
||||||
|
{[0, 1, 2, 3, 4, 5, 6, 7, 8].map(item => <div key={item} className="skeleton h-4" />)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
|
const Cutting = () => {
|
||||||
|
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 [targetCoverageDays, setTargetCoverageDays] = useState(30);
|
||||||
|
const [familyFilter, setFamilyFilter] = useState<CutFamilyKey | 'all'>('all');
|
||||||
|
const [cutFilter, setCutFilter] = useState<CutFilter>('need');
|
||||||
|
const [sortBy, setSortBy] = useState<CutSort>('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 <span className="text-xs font-bold text-emerald-300">OK</span>;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<span className="inline-flex items-center gap-1.5 rounded-full border border-amber-400/30 bg-amber-400/10 px-2.5 py-1 text-xs font-bold text-amber-300">
|
||||||
|
<AlertTriangle className="h-3.5 w-3.5" />
|
||||||
|
{row.issues.map(issue => issueLabels[issue]).join(', ')}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
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="mb-2 text-2xl font-bold text-zinc-900 dark:text-dark-text">Plano de Corte</h1>
|
||||||
|
<p className="font-medium text-zinc-500 dark:text-dark-muted">
|
||||||
|
Necessidade por família, cor e tamanho calculada com vendas, estoque e cobertura alvo.
|
||||||
|
</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
|
||||||
|
type="button"
|
||||||
|
onClick={exportRows}
|
||||||
|
className="flex items-center justify-center gap-2 rounded-xl border border-dark-border bg-dark-card px-4 py-2.5 text-sm font-medium text-dark-text shadow-sm transition-colors hover:border-brand-primary 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">Unidades a cortar</p>
|
||||||
|
<p className="mt-2 text-3xl font-bold text-red-300">{formatNumber(cutPlan.summary.suggestedCutQuantity)}</p>
|
||||||
|
<p className="mt-1 text-xs font-semibold text-dark-muted">{formatNumber(cutPlan.summary.skuCount)} SKUs com necessidade</p>
|
||||||
|
</div>
|
||||||
|
<div className="rounded-xl border border-red-400/25 bg-red-400/10 p-3 text-red-300">
|
||||||
|
<Scissors 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">Famílias</p>
|
||||||
|
<p className="mt-2 text-3xl font-bold text-dark-text">{formatNumber(cutPlan.summary.familiesWithNeed)}</p>
|
||||||
|
<p className="mt-1 text-xs font-semibold text-dark-muted">Com necessidade no período</p>
|
||||||
|
</div>
|
||||||
|
<div className="rounded-xl border border-brand-primary/25 bg-brand-primary/10 p-3 text-brand-primary">
|
||||||
|
<Layers3 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">Cores / tamanhos</p>
|
||||||
|
<p className="mt-2 text-3xl font-bold text-sky-300">
|
||||||
|
{formatNumber(cutPlan.summary.colorsWithNeed)} / {formatNumber(cutPlan.summary.sizesWithNeed)}
|
||||||
|
</p>
|
||||||
|
<p className="mt-1 text-xs font-semibold text-dark-muted">Com corte sugerido</p>
|
||||||
|
</div>
|
||||||
|
<div className="rounded-xl border border-sky-400/25 bg-sky-400/10 p-3 text-sky-300">
|
||||||
|
<Palette 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">Pendências</p>
|
||||||
|
<p className="mt-2 text-3xl font-bold text-amber-300">{formatNumber(cutPlan.summary.rowsWithIssues)}</p>
|
||||||
|
<p className="mt-1 text-xs font-semibold text-dark-muted">Sem família, cor ou tamanho</p>
|
||||||
|
</div>
|
||||||
|
<div className="rounded-xl border border-amber-400/25 bg-amber-400/10 p-3 text-amber-300">
|
||||||
|
<AlertTriangle className="h-5 w-5" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{!!cutPlan.familySummaries.length && (
|
||||||
|
<div className="grid grid-cols-1 gap-4 xl:grid-cols-4">
|
||||||
|
{cutPlan.familySummaries.map(summary => (
|
||||||
|
<div key={summary.family.key} className="rounded-2xl border border-dark-border bg-dark-card p-4 shadow-sm">
|
||||||
|
<div className="flex items-start justify-between gap-3">
|
||||||
|
<div>
|
||||||
|
<span className={`inline-flex rounded-full border px-2.5 py-1 text-xs font-bold ${familyStyles[summary.family.key]}`}>
|
||||||
|
{summary.family.materialLabel}
|
||||||
|
</span>
|
||||||
|
<h3 className="mt-3 text-sm font-bold text-dark-text">{summary.family.label}</h3>
|
||||||
|
</div>
|
||||||
|
<Scissors className="h-5 w-5 text-dark-muted" />
|
||||||
|
</div>
|
||||||
|
<p className="mt-4 text-2xl font-bold text-dark-text">{formatNumber(summary.suggestedCutQuantity)} un.</p>
|
||||||
|
<p className="mt-1 text-xs font-semibold text-dark-muted">
|
||||||
|
{formatNumber(summary.skuCount)} SKUs · {formatNumber(summary.colorCount)} cores · {formatNumber(summary.sizeCount)} tamanhos
|
||||||
|
</p>
|
||||||
|
</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-[1fr_170px_170px_170px_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, ID, grupo ou cor..."
|
||||||
|
value={searchTerm}
|
||||||
|
onChange={(event) => {
|
||||||
|
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"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<select
|
||||||
|
value={targetCoverageDays}
|
||||||
|
onChange={(event) => {
|
||||||
|
setTargetCoverageDays(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:border-brand-primary focus:outline-none cursor-pointer"
|
||||||
|
aria-label="Dias de cobertura alvo"
|
||||||
|
>
|
||||||
|
{coverageTargetOptions.map(days => <option key={days} value={days}>Cobrir {days} dias</option>)}
|
||||||
|
</select>
|
||||||
|
|
||||||
|
<select
|
||||||
|
value={familyFilter}
|
||||||
|
onChange={(event) => {
|
||||||
|
setFamilyFilter(event.target.value as CutFamilyKey | 'all');
|
||||||
|
setCurrentPage(1);
|
||||||
|
}}
|
||||||
|
className="h-11 rounded-xl border border-dark-border bg-dark-input px-3 text-sm font-semibold text-dark-text focus:border-brand-primary focus:outline-none cursor-pointer"
|
||||||
|
>
|
||||||
|
{familyOptions.map(option => <option key={option.value} value={option.value}>{option.label}</option>)}
|
||||||
|
</select>
|
||||||
|
|
||||||
|
<select
|
||||||
|
value={cutFilter}
|
||||||
|
onChange={(event) => {
|
||||||
|
setCutFilter(event.target.value as CutFilter);
|
||||||
|
setCurrentPage(1);
|
||||||
|
}}
|
||||||
|
className="h-11 rounded-xl border border-dark-border bg-dark-input px-3 text-sm font-semibold text-dark-text focus:border-brand-primary focus:outline-none 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 CutSort);
|
||||||
|
setCurrentPage(1);
|
||||||
|
}}
|
||||||
|
className="h-11 rounded-xl border border-dark-border bg-dark-input px-3 text-sm font-semibold text-dark-text focus:border-brand-primary focus:outline-none 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="sold_desc">Mais vendidos</option>
|
||||||
|
<option value="name_asc">Nome A-Z</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{isLoading && products.length === 0 ? (
|
||||||
|
<CuttingSkeleton />
|
||||||
|
) : (
|
||||||
|
<div className={`overflow-hidden rounded-2xl border border-zinc-200 bg-white shadow-sm dark:border-dark-border dark:bg-dark-card ${isRefreshing ? 'refreshing-content' : ''}`} aria-busy={isRefreshing}>
|
||||||
|
<div className="overflow-x-auto">
|
||||||
|
<table className="w-full min-w-[1420px] table-fixed text-left text-sm">
|
||||||
|
<colgroup>
|
||||||
|
<col className="w-[120px]" />
|
||||||
|
<col className="w-[360px]" />
|
||||||
|
<col className="w-[150px]" />
|
||||||
|
<col className="w-[120px]" />
|
||||||
|
<col className="w-[100px]" />
|
||||||
|
<col className="w-[130px]" />
|
||||||
|
<col className="w-[110px]" />
|
||||||
|
<col className="w-[130px]" />
|
||||||
|
<col className="w-[140px]" />
|
||||||
|
<col className="w-[150px]" />
|
||||||
|
<col className="w-[110px]" />
|
||||||
|
</colgroup>
|
||||||
|
<thead className="border-b border-zinc-100 bg-zinc-50 text-zinc-500 dark:border-dark-border dark:bg-dark-header dark:text-dark-muted">
|
||||||
|
<tr>
|
||||||
|
<th className="px-6 py-4 text-[10px] font-bold uppercase tracking-wider">ID Produto</th>
|
||||||
|
<th className="px-6 py-4 text-[10px] font-bold uppercase tracking-wider">Descrição</th>
|
||||||
|
<th className="px-6 py-4 text-[10px] font-bold uppercase tracking-wider">Família</th>
|
||||||
|
<th className="px-6 py-4 text-[10px] font-bold uppercase tracking-wider">Cor</th>
|
||||||
|
<th className="px-6 py-4 text-[10px] font-bold uppercase tracking-wider">Tamanho</th>
|
||||||
|
<th className="px-6 py-4 text-[10px] font-bold uppercase tracking-wider">Demanda proj.</th>
|
||||||
|
<th className="px-6 py-4 text-[10px] font-bold uppercase tracking-wider">Estoque</th>
|
||||||
|
<th className="px-6 py-4 text-[10px] font-bold uppercase tracking-wider">Disponível</th>
|
||||||
|
<th className="px-6 py-4 text-[10px] font-bold uppercase tracking-wider">Necessidade</th>
|
||||||
|
<th className="px-6 py-4 text-[10px] font-bold uppercase tracking-wider">Pendências</th>
|
||||||
|
<th className="px-6 py-4 text-right text-[10px] font-bold uppercase tracking-wider">Ações</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody className="divide-y divide-zinc-100 dark:divide-dark-border">
|
||||||
|
{paginatedRows.map(row => (
|
||||||
|
<tr key={row.id} className="transition-colors hover:bg-zinc-50/80 dark:hover:bg-dark-input/50">
|
||||||
|
<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] font-medium text-zinc-400 dark:text-dark-muted">
|
||||||
|
Média: {formatNumber(row.dailySales, 2)} un./dia · Cobertura: {formatDays(row.daysOfCover)}
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
<td className="px-6 py-2.5">
|
||||||
|
<span className={`inline-flex whitespace-nowrap rounded-full border px-2.5 py-1 text-xs font-bold ${familyStyles[row.family.key]}`}>
|
||||||
|
{row.family.materialLabel}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td className="px-6 py-2.5">
|
||||||
|
<span className="inline-flex max-w-full items-center gap-2 rounded-full border border-sky-400/25 bg-sky-400/10 px-2.5 py-1 text-xs font-bold text-sky-300">
|
||||||
|
<Palette className="h-3.5 w-3.5 shrink-0" />
|
||||||
|
<span className="truncate">{row.color || '-'}</span>
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td className="px-6 py-2.5">
|
||||||
|
<span className="inline-flex items-center gap-1.5 rounded-full border border-emerald-400/25 bg-emerald-400/10 px-2.5 py-1 text-xs font-bold text-emerald-300">
|
||||||
|
<Ruler className="h-3.5 w-3.5" />
|
||||||
|
{row.size || '-'}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td className="px-6 py-2.5 font-bold whitespace-nowrap text-zinc-900 dark:text-dark-text">{formatNumber(row.projectedDemand, 1)} un.</td>
|
||||||
|
<td className="px-6 py-2.5 font-bold whitespace-nowrap text-zinc-900 dark:text-dark-text">{formatNumber(row.stock)} un.</td>
|
||||||
|
<td className="px-6 py-2.5 font-bold whitespace-nowrap text-zinc-900 dark:text-dark-text">
|
||||||
|
{formatNumber(row.availableQuantity)} un.
|
||||||
|
{!!row.openProductionQuantity && <span className="ml-1 text-xs text-dark-muted">incl. OP</span>}
|
||||||
|
</td>
|
||||||
|
<td className="px-6 py-2.5 whitespace-nowrap">
|
||||||
|
<span className={row.suggestedCutQuantity > 0 ? 'font-bold text-red-300' : 'font-bold text-emerald-300'}>
|
||||||
|
{formatNumber(row.suggestedCutQuantity)} un.
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td className="px-6 py-2.5">{renderIssueBadge(row)}</td>
|
||||||
|
<td className="px-4 py-2.5 text-right">
|
||||||
|
<Link
|
||||||
|
to={`/products/${row.id}`}
|
||||||
|
className="inline-flex items-center whitespace-nowrap rounded-lg bg-brand-primary/10 px-3 py-1.5 text-xs font-bold text-brand-primary transition-opacity hover:opacity-80"
|
||||||
|
>
|
||||||
|
<Package className="mr-1.5 h-3.5 w-3.5" />
|
||||||
|
Ver SKU
|
||||||
|
</Link>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{!filteredRows.length && (
|
||||||
|
<div className="px-6 py-12 text-center">
|
||||||
|
<Scissors className="mx-auto h-10 w-10 text-dark-muted" />
|
||||||
|
<p className="mt-4 text-sm font-bold text-dark-text">Nenhum item encontrado.</p>
|
||||||
|
<p className="mt-1 text-sm text-dark-muted">Ajuste a busca, família, status ou período selecionado.</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<PaginationControls
|
||||||
|
totalItems={filteredRows.length}
|
||||||
|
currentPage={safeCurrentPage}
|
||||||
|
totalPages={totalPages}
|
||||||
|
pageSize={itemsPerPage}
|
||||||
|
pageSizeOptions={[10, 20, 50, 100]}
|
||||||
|
itemLabel="SKUs"
|
||||||
|
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 Cutting;
|
||||||
Reference in New Issue
Block a user