Add OP-aware cutting planning

This commit is contained in:
Cauê Faleiros
2026-07-07 15:11:42 -03:00
parent f451c3df63
commit d1220fdd3f
4 changed files with 261 additions and 36 deletions

View File

@@ -1,8 +1,8 @@
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import test from 'node:test'; import test from 'node:test';
import { buildCutPlan, classifyCutFamily } from './cutting.ts'; import { buildCutPlan, buildOpenProductionByProductId, classifyCutFamily } from './cutting.ts';
import type { DateRange, ProductAnalyticsItem } from '../types.ts'; import type { DateRange, ProductAnalyticsItem, ProductionOrderItem } from '../types.ts';
const range: DateRange = { const range: DateRange = {
start: new Date(2026, 6, 1), start: new Date(2026, 6, 1),
@@ -22,6 +22,26 @@ const product = (overrides: Partial<ProductAnalyticsItem>): ProductAnalyticsItem
...overrides ...overrides
}); });
const productionOrder = (overrides: Partial<ProductionOrderItem>): ProductionOrderItem => ({
id: 1,
tinyId: '',
number: 'OP-1',
status: 'in_progress',
statusLabel: 'Em andamento',
orderReference: '',
issueDate: '2026-07-01',
expectedDate: '2026-07-15',
productSku: '',
productDescription: 'BASE LISA CAMISETA COR PRETO TAMANHO - M',
quantity: 40,
unit: 'UN',
integrationStatus: '',
markers: [],
createdAt: null,
updatedAt: null,
...overrides
});
test('classifyCutFamily maps known product bases to internal cut families', () => { test('classifyCutFamily maps known product bases to internal cut families', () => {
assert.equal(classifyCutFamily('BASE LISA CAMISETA').key, 'BLCS'); assert.equal(classifyCutFamily('BASE LISA CAMISETA').key, 'BLCS');
assert.equal(classifyCutFamily('BASE LISA CAMISETA OVER').key, 'BLOS'); assert.equal(classifyCutFamily('BASE LISA CAMISETA OVER').key, 'BLOS');
@@ -37,6 +57,8 @@ test('buildCutPlan calculates projected cut need from sales pace and stock', ()
assert.equal(row.projectedDemand, 140); assert.equal(row.projectedDemand, 140);
assert.equal(row.availableQuantity, 20); assert.equal(row.availableQuantity, 20);
assert.equal(row.suggestedCutQuantity, 120); assert.equal(row.suggestedCutQuantity, 120);
assert.equal(row.estimatedRolls, null);
assert.deepEqual(row.issues, ['missing_yield_rule']);
assert.equal(plan.summary.suggestedCutQuantity, 120); assert.equal(plan.summary.suggestedCutQuantity, 120);
}); });
@@ -48,6 +70,20 @@ test('buildCutPlan subtracts open production quantity from suggested cut need',
assert.equal(row.suggestedCutQuantity, 20); assert.equal(row.suggestedCutQuantity, 20);
}); });
test('buildOpenProductionByProductId matches open OPs by SKU and normalized product variant', () => {
const products = [
product({ id: 'SKU-1' }),
product({ id: 'SKU-2', name: 'BASE LISA CAMISETA COR BRANCO TAMANHO - G' })
];
const totals = buildOpenProductionByProductId(products, [
productionOrder({ productSku: 'SKU-1', productDescription: '', quantity: 10 }),
productionOrder({ productSku: '', productDescription: 'Base Lisa Camiseta Cor Branco Tamanho - G', quantity: 20 }),
productionOrder({ productSku: 'SKU-1', status: 'finished', quantity: 999 })
]);
assert.deepEqual(totals, { 'SKU-1': 10, 'SKU-2': 20 });
});
test('buildCutPlan marks products that cannot be planned cleanly for cutting', () => { test('buildCutPlan marks products that cannot be planned cleanly for cutting', () => {
const plan = buildCutPlan([ const plan = buildCutPlan([
product({ product({

View File

@@ -1,14 +1,15 @@
import type { DateRange, ProductAnalyticsItem } from '../types'; import type { DateRange, ProductAnalyticsItem, ProductionOrderItem } from '../types';
import { parseProductName, sortProductSizes } from '../productParsing.ts'; import { normalizeProductText, parseProductName, sortProductSizes } from '../productParsing.ts';
export type CutFamilyKey = 'BLCS' | 'BLOS' | 'BLMC' | 'BLPM' | 'OUTROS'; export type CutFamilyKey = 'BLCS' | 'BLOS' | 'BLMC' | 'BLPM' | 'OUTROS';
export type CutIssue = 'missing_family_rule' | 'missing_color' | 'missing_size'; export type CutIssue = 'missing_family_rule' | 'missing_color' | 'missing_size' | 'missing_yield_rule';
export interface CutFamilyRule { export interface CutFamilyRule {
key: CutFamilyKey; key: CutFamilyKey;
label: string; label: string;
materialLabel: string; materialLabel: string;
keywords: string[]; keywords: string[];
unitsPerRoll: number | null;
} }
export interface CutPlanSkuRow extends ProductAnalyticsItem { export interface CutPlanSkuRow extends ProductAnalyticsItem {
@@ -21,6 +22,7 @@ export interface CutPlanSkuRow extends ProductAnalyticsItem {
openProductionQuantity: number; openProductionQuantity: number;
availableQuantity: number; availableQuantity: number;
suggestedCutQuantity: number; suggestedCutQuantity: number;
estimatedRolls: number | null;
daysOfCover: number | null; daysOfCover: number | null;
issues: CutIssue[]; issues: CutIssue[];
} }
@@ -34,6 +36,7 @@ export interface CutPlanFamilySummary {
stock: number; stock: number;
projectedDemand: number; projectedDemand: number;
suggestedCutQuantity: number; suggestedCutQuantity: number;
estimatedRolls: number | null;
} }
export interface CutPlanSummary { export interface CutPlanSummary {
@@ -45,7 +48,9 @@ export interface CutPlanSummary {
totalStock: number; totalStock: number;
projectedDemand: number; projectedDemand: number;
suggestedCutQuantity: number; suggestedCutQuantity: number;
estimatedRolls: number | null;
rowsWithIssues: number; rowsWithIssues: number;
openProductionQuantity: number;
} }
export interface CutPlan { export interface CutPlan {
@@ -60,25 +65,29 @@ export const CUT_FAMILY_RULES: CutFamilyRule[] = [
key: 'BLPM', key: 'BLPM',
label: 'Moletom', label: 'Moletom',
materialLabel: 'BLPM', materialLabel: 'BLPM',
keywords: ['MOLETOM'] keywords: ['MOLETOM'],
unitsPerRoll: null
}, },
{ {
key: 'BLOS', key: 'BLOS',
label: 'Camiseta over', label: 'Camiseta over',
materialLabel: 'BLOS', materialLabel: 'BLOS',
keywords: ['OVER'] keywords: ['OVER'],
unitsPerRoll: null
}, },
{ {
key: 'BLMC', key: 'BLMC',
label: 'Camiseta infantil', label: 'Camiseta infantil',
materialLabel: 'BLMC', materialLabel: 'BLMC',
keywords: ['INFANTIL', 'KIDS'] keywords: ['INFANTIL', 'KIDS'],
unitsPerRoll: null
}, },
{ {
key: 'BLCS', key: 'BLCS',
label: 'Camiseta regular', label: 'Camiseta regular',
materialLabel: 'BLCS', materialLabel: 'BLCS',
keywords: ['CAMISETA'] keywords: ['CAMISETA'],
unitsPerRoll: null
} }
]; ];
@@ -86,7 +95,8 @@ export const OUTROS_RULE: CutFamilyRule = {
key: 'OUTROS', key: 'OUTROS',
label: 'Sem regra', label: 'Sem regra',
materialLabel: 'Pendente', materialLabel: 'Pendente',
keywords: [] keywords: [],
unitsPerRoll: null
}; };
export const getRangeDays = (range: DateRange) => { export const getRangeDays = (range: DateRange) => {
@@ -111,6 +121,59 @@ export const classifyCutFamily = (baseName: string): CutFamilyRule => {
)) || OUTROS_RULE; )) || OUTROS_RULE;
}; };
const normalizeMatchText = (value: string) => normalizeProductText(value)
.normalize('NFD')
.replace(/\p{Diacritic}/gu, '')
.toLowerCase();
const isOpenProductionOrder = (order: ProductionOrderItem) => (
order.status === 'open' ||
order.status === 'in_progress' ||
['em aberto', 'aberta', 'andamento', 'em andamento'].includes(normalizeMatchText(order.status))
);
export const buildOpenProductionByProductId = (
products: ProductAnalyticsItem[],
productionOrders: ProductionOrderItem[]
): Record<string, number> => {
const productById = new Map(products.map(product => [product.id, product]));
const productByName = new Map(products.map(product => [normalizeMatchText(product.name), product]));
const productsByVariantKey = new Map<string, ProductAnalyticsItem>();
products.forEach(product => {
const metadata = parseProductName(product.name);
const key = [
normalizeMatchText(metadata.baseName),
normalizeMatchText(metadata.color),
normalizeMatchText(metadata.size)
].join('::');
productsByVariantKey.set(key, product);
});
return productionOrders.reduce<Record<string, number>>((totals, order) => {
if (!isOpenProductionOrder(order)) return totals;
const skuMatch = order.productSku ? productById.get(order.productSku) : undefined;
const nameMatch = order.productDescription ? productByName.get(normalizeMatchText(order.productDescription)) : undefined;
let product = skuMatch || nameMatch;
if (!product && order.productDescription) {
const metadata = parseProductName(order.productDescription);
const key = [
normalizeMatchText(metadata.baseName),
normalizeMatchText(metadata.color),
normalizeMatchText(metadata.size)
].join('::');
product = productsByVariantKey.get(key);
}
if (!product) return totals;
totals[product.id] = (totals[product.id] || 0) + order.quantity;
return totals;
}, {});
};
export const buildCutPlan = ( export const buildCutPlan = (
products: ProductAnalyticsItem[], products: ProductAnalyticsItem[],
dateRange: DateRange, dateRange: DateRange,
@@ -127,12 +190,16 @@ export const buildCutPlan = (
const openProductionQuantity = openProductionByProductId[product.id] || 0; const openProductionQuantity = openProductionByProductId[product.id] || 0;
const availableQuantity = product.stock + openProductionQuantity; const availableQuantity = product.stock + openProductionQuantity;
const suggestedCutQuantity = Math.max(0, Math.ceil(projectedDemand - availableQuantity)); const suggestedCutQuantity = Math.max(0, Math.ceil(projectedDemand - availableQuantity));
const estimatedRolls = family.unitsPerRoll && suggestedCutQuantity > 0
? Math.ceil(suggestedCutQuantity / family.unitsPerRoll)
: null;
const daysOfCover = dailySales > 0 ? availableQuantity / dailySales : null; const daysOfCover = dailySales > 0 ? availableQuantity / dailySales : null;
const issues: CutIssue[] = []; const issues: CutIssue[] = [];
if (family.key === 'OUTROS') issues.push('missing_family_rule'); if (family.key === 'OUTROS') issues.push('missing_family_rule');
if (!metadata.color) issues.push('missing_color'); if (!metadata.color) issues.push('missing_color');
if (!metadata.size) issues.push('missing_size'); if (!metadata.size) issues.push('missing_size');
if (suggestedCutQuantity > 0 && family.key !== 'OUTROS' && !family.unitsPerRoll) issues.push('missing_yield_rule');
return { return {
...product, ...product,
@@ -145,6 +212,7 @@ export const buildCutPlan = (
openProductionQuantity, openProductionQuantity,
availableQuantity, availableQuantity,
suggestedCutQuantity, suggestedCutQuantity,
estimatedRolls,
daysOfCover, daysOfCover,
issues issues
}; };
@@ -172,7 +240,10 @@ export const buildCutPlan = (
quantitySold: group.reduce((total, row) => total + row.quantitySold, 0), quantitySold: group.reduce((total, row) => total + row.quantitySold, 0),
stock: group.reduce((total, row) => total + row.stock, 0), stock: group.reduce((total, row) => total + row.stock, 0),
projectedDemand: group.reduce((total, row) => total + row.projectedDemand, 0), projectedDemand: group.reduce((total, row) => total + row.projectedDemand, 0),
suggestedCutQuantity: group.reduce((total, row) => total + row.suggestedCutQuantity, 0) suggestedCutQuantity: group.reduce((total, row) => total + row.suggestedCutQuantity, 0),
estimatedRolls: group.some(row => row.estimatedRolls === null)
? null
: group.reduce((total, row) => total + (row.estimatedRolls || 0), 0)
}; };
}) })
.sort((a, b) => b.suggestedCutQuantity - a.suggestedCutQuantity); .sort((a, b) => b.suggestedCutQuantity - a.suggestedCutQuantity);
@@ -193,7 +264,11 @@ export const buildCutPlan = (
totalStock: needRows.reduce((total, row) => total + row.stock, 0), totalStock: needRows.reduce((total, row) => total + row.stock, 0),
projectedDemand: needRows.reduce((total, row) => total + row.projectedDemand, 0), projectedDemand: needRows.reduce((total, row) => total + row.projectedDemand, 0),
suggestedCutQuantity: needRows.reduce((total, row) => total + row.suggestedCutQuantity, 0), suggestedCutQuantity: needRows.reduce((total, row) => total + row.suggestedCutQuantity, 0),
rowsWithIssues: needRows.filter(row => row.issues.length > 0).length estimatedRolls: needRows.some(row => row.estimatedRolls === null)
? null
: needRows.reduce((total, row) => total + (row.estimatedRolls || 0), 0),
rowsWithIssues: needRows.filter(row => row.issues.length > 0).length,
openProductionQuantity: needRows.reduce((total, row) => total + row.openProductionQuantity, 0)
} }
}; };
}; };

View File

@@ -1,12 +1,12 @@
import { useEffect, useMemo, useState } from 'react'; import { useEffect, useMemo, useState } from 'react';
import { Link, useOutletContext } from 'react-router-dom'; import { Link, useOutletContext } from 'react-router-dom';
import { AlertTriangle, Download, Layers3, Package, Palette, Ruler, Scissors, Search } from 'lucide-react'; import { AlertTriangle, ClipboardList, Download, Layers3, Package, Palette, Ruler, Scissors, Search } from 'lucide-react';
import DateRangePicker from '../components/DateRangePicker'; import DateRangePicker from '../components/DateRangePicker';
import PaginationControls from '../components/PaginationControls'; import PaginationControls from '../components/PaginationControls';
import RefreshStatus from '../components/RefreshStatus'; import RefreshStatus from '../components/RefreshStatus';
import { CUT_FAMILY_RULES, buildCutPlan, type CutFamilyKey, type CutIssue, type CutPlanSkuRow } from '../analytics/cutting'; import { CUT_FAMILY_RULES, buildCutPlan, buildOpenProductionByProductId, type CutFamilyKey, type CutIssue, type CutPlanSkuRow } from '../analytics/cutting';
import { exportToCSV, fetchProductAnalytics } from '../dataService'; import { exportToCSV, fetchProductAnalytics, fetchProductionOrders } from '../dataService';
import type { DateRange, ProductAnalyticsItem } from '../types'; import type { DateRange, ProductAnalyticsItem, ProductionOrderItem } from '../types';
type CutFilter = 'need' | 'all' | 'issues' | 'covered'; type CutFilter = 'need' | 'all' | 'issues' | 'covered';
type CutSort = 'need_desc' | 'need_asc' | 'demand_desc' | 'stock_asc' | 'sold_desc' | 'name_asc'; type CutSort = 'need_desc' | 'need_asc' | 'demand_desc' | 'stock_asc' | 'sold_desc' | 'name_asc';
@@ -28,7 +28,15 @@ const filterOptions: Array<{ value: CutFilter; label: string }> = [
const issueLabels: Record<CutIssue, string> = { const issueLabels: Record<CutIssue, string> = {
missing_family_rule: 'Sem família', missing_family_rule: 'Sem família',
missing_color: 'Sem cor', missing_color: 'Sem cor',
missing_size: 'Sem tamanho' missing_size: 'Sem tamanho',
missing_yield_rule: 'Sem rendimento'
};
const issueHelp: Record<CutIssue, string> = {
missing_family_rule: 'Produto não caiu em BLCS, BLOS, BLMC ou BLPM.',
missing_color: 'Nome do produto não tem uma cor clara para montar matriz de corte.',
missing_size: 'Nome do produto não tem tamanho claro para montar matriz de corte.',
missing_yield_rule: 'Família reconhecida, mas ainda falta cadastrar unidades por rolo.'
}; };
const familyStyles: Record<CutFamilyKey, string> = { const familyStyles: Record<CutFamilyKey, string> = {
@@ -49,6 +57,11 @@ const formatDays = (value: number | null) => {
return `${formatNumber(value, value < 10 ? 1 : 0)} dias`; return `${formatNumber(value, value < 10 ? 1 : 0)} dias`;
}; };
const allProductionOrdersRange = {
start: new Date(2000, 0, 1),
end: new Date(2100, 11, 31)
};
const CuttingSkeleton = () => ( 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="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="border-b border-dark-border p-4">
@@ -72,6 +85,7 @@ const Cutting = () => {
setDateRange: (range: DateRange) => void setDateRange: (range: DateRange) => void
}>(); }>();
const [products, setProducts] = useState<ProductAnalyticsItem[]>([]); const [products, setProducts] = useState<ProductAnalyticsItem[]>([]);
const [productionOrders, setProductionOrders] = useState<ProductionOrderItem[]>([]);
const [isLoading, setIsLoading] = useState(true); const [isLoading, setIsLoading] = useState(true);
const [searchTerm, setSearchTerm] = useState(''); const [searchTerm, setSearchTerm] = useState('');
const [targetCoverageDays, setTargetCoverageDays] = useState(30); const [targetCoverageDays, setTargetCoverageDays] = useState(30);
@@ -86,9 +100,13 @@ const Cutting = () => {
const loadProducts = async () => { const loadProducts = async () => {
setIsLoading(true); setIsLoading(true);
const data = await fetchProductAnalytics(dateRange); const [productData, productionOrderData] = await Promise.all([
fetchProductAnalytics(dateRange),
fetchProductionOrders(allProductionOrdersRange)
]);
if (isMounted) { if (isMounted) {
setProducts(data); setProducts(productData);
setProductionOrders(productionOrderData.orders);
setIsLoading(false); setIsLoading(false);
} }
}; };
@@ -100,7 +118,23 @@ const Cutting = () => {
}; };
}, [dateRange]); }, [dateRange]);
const cutPlan = useMemo(() => buildCutPlan(products, dateRange, targetCoverageDays), [dateRange, products, targetCoverageDays]); const openProductionByProductId = useMemo(
() => buildOpenProductionByProductId(products, productionOrders),
[products, productionOrders]
);
const cutPlan = useMemo(
() => buildCutPlan(products, dateRange, targetCoverageDays, openProductionByProductId),
[dateRange, openProductionByProductId, products, targetCoverageDays]
);
const issueSummaries = useMemo(() => {
const counts = new Map<CutIssue, number>();
cutPlan.needRows.forEach(row => {
row.issues.forEach(issue => counts.set(issue, (counts.get(issue) || 0) + 1));
});
return Array.from(counts.entries()).map(([issue, count]) => ({ issue, count }));
}, [cutPlan.needRows]);
const filteredRows = useMemo(() => { const filteredRows = useMemo(() => {
const normalizedSearch = searchTerm.trim().toLowerCase(); const normalizedSearch = searchTerm.trim().toLowerCase();
@@ -159,6 +193,8 @@ const Cutting = () => {
'OP aberta': row.openProductionQuantity, 'OP aberta': row.openProductionQuantity,
'Disponível': row.availableQuantity, 'Disponível': row.availableQuantity,
'Necessidade corte': row.suggestedCutQuantity, 'Necessidade corte': row.suggestedCutQuantity,
'Rendimento un/rolo': row.family.unitsPerRoll || '',
'Rolos estimados': row.estimatedRolls || '',
'Cobertura': row.daysOfCover === null ? '' : row.daysOfCover.toFixed(1).replace('.', ','), 'Cobertura': row.daysOfCover === null ? '' : row.daysOfCover.toFixed(1).replace('.', ','),
'Pendências': row.issues.map(issue => issueLabels[issue]).join(' | ') 'Pendências': row.issues.map(issue => issueLabels[issue]).join(' | ')
})), `plano_corte_${new Date().toISOString().split('T')[0]}.csv`); })), `plano_corte_${new Date().toISOString().split('T')[0]}.csv`);
@@ -229,7 +265,9 @@ const Cutting = () => {
<div> <div>
<p className="text-xs font-bold uppercase tracking-widest text-dark-muted">Famílias</p> <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-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> <p className="mt-1 text-xs font-semibold text-dark-muted">
{cutPlan.summary.estimatedRolls === null ? 'Rolos pendentes de rendimento' : `${formatNumber(cutPlan.summary.estimatedRolls)} rolos estimados`}
</p>
</div> </div>
<div className="rounded-xl border border-brand-primary/25 bg-brand-primary/10 p-3 text-brand-primary"> <div className="rounded-xl border border-brand-primary/25 bg-brand-primary/10 p-3 text-brand-primary">
<Layers3 className="h-5 w-5" /> <Layers3 className="h-5 w-5" />
@@ -255,17 +293,52 @@ const Cutting = () => {
<div className="rounded-2xl border border-dark-border bg-dark-card p-5 shadow-sm"> <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 className="flex items-start justify-between gap-4">
<div> <div>
<p className="text-xs font-bold uppercase tracking-widest text-dark-muted">Pendências</p> <p className="text-xs font-bold uppercase tracking-widest text-dark-muted">OP aberta</p>
<p className="mt-2 text-3xl font-bold text-amber-300">{formatNumber(cutPlan.summary.rowsWithIssues)}</p> <p className="mt-2 text-3xl font-bold text-amber-300">{formatNumber(cutPlan.summary.openProductionQuantity)}</p>
<p className="mt-1 text-xs font-semibold text-dark-muted">Sem família, cor ou tamanho</p> <p className="mt-1 text-xs font-semibold text-dark-muted">Unidades abatidas quando match</p>
</div> </div>
<div className="rounded-xl border border-amber-400/25 bg-amber-400/10 p-3 text-amber-300"> <div className="rounded-xl border border-amber-400/25 bg-amber-400/10 p-3 text-amber-300">
<AlertTriangle className="h-5 w-5" /> <ClipboardList className="h-5 w-5" />
</div> </div>
</div> </div>
</div> </div>
</div> </div>
{!!issueSummaries.length && (
<div className="rounded-2xl border border-amber-400/20 bg-amber-400/5 p-4 shadow-sm">
<div className="mb-4 flex items-start justify-between gap-4">
<div>
<h2 className="text-sm font-bold text-amber-200">Pendências para fechar o Corte</h2>
<p className="mt-1 text-xs font-semibold text-dark-muted">
Estes pontos substituem as correções manuais que antes ficavam espalhadas no Excel.
</p>
</div>
<span className="rounded-full border border-amber-400/30 bg-amber-400/10 px-3 py-1 text-xs font-bold text-amber-300">
{formatNumber(cutPlan.summary.rowsWithIssues)} SKUs
</span>
</div>
<div className="grid grid-cols-1 gap-3 md:grid-cols-4">
{issueSummaries.map(summary => (
<button
key={summary.issue}
type="button"
onClick={() => {
setCutFilter('issues');
setCurrentPage(1);
}}
className="rounded-xl border border-dark-border bg-dark-card p-3 text-left transition-colors hover:border-amber-400/50 cursor-pointer"
>
<div className="flex items-center justify-between gap-3">
<span className="text-xs font-bold text-dark-text">{issueLabels[summary.issue]}</span>
<span className="text-sm font-bold text-amber-300">{formatNumber(summary.count)}</span>
</div>
<p className="mt-2 text-[11px] font-medium leading-relaxed text-dark-muted">{issueHelp[summary.issue]}</p>
</button>
))}
</div>
</div>
)}
{!!cutPlan.familySummaries.length && ( {!!cutPlan.familySummaries.length && (
<div className="grid grid-cols-1 gap-4 xl:grid-cols-4"> <div className="grid grid-cols-1 gap-4 xl:grid-cols-4">
{cutPlan.familySummaries.map(summary => ( {cutPlan.familySummaries.map(summary => (
@@ -281,7 +354,7 @@ const Cutting = () => {
</div> </div>
<p className="mt-4 text-2xl font-bold text-dark-text">{formatNumber(summary.suggestedCutQuantity)} un.</p> <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"> <p className="mt-1 text-xs font-semibold text-dark-muted">
{formatNumber(summary.skuCount)} SKUs · {formatNumber(summary.colorCount)} cores · {formatNumber(summary.sizeCount)} tamanhos {formatNumber(summary.skuCount)} SKUs · {formatNumber(summary.colorCount)} cores · {summary.estimatedRolls === null ? 'sem rendimento' : `${formatNumber(summary.estimatedRolls)} rolos`}
</p> </p>
</div> </div>
))} ))}
@@ -370,6 +443,7 @@ const Cutting = () => {
<col className="w-[110px]" /> <col className="w-[110px]" />
<col className="w-[130px]" /> <col className="w-[130px]" />
<col className="w-[140px]" /> <col className="w-[140px]" />
<col className="w-[120px]" />
<col className="w-[150px]" /> <col className="w-[150px]" />
<col className="w-[110px]" /> <col className="w-[110px]" />
</colgroup> </colgroup>
@@ -384,6 +458,7 @@ const Cutting = () => {
<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">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">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">Necessidade</th>
<th className="px-6 py-4 text-[10px] font-bold uppercase tracking-wider">Rolos</th>
<th className="px-6 py-4 text-[10px] font-bold uppercase tracking-wider">Pendências</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> <th className="px-6 py-4 text-right text-[10px] font-bold uppercase tracking-wider">Ações</th>
</tr> </tr>
@@ -426,6 +501,9 @@ const Cutting = () => {
{formatNumber(row.suggestedCutQuantity)} un. {formatNumber(row.suggestedCutQuantity)} un.
</span> </span>
</td> </td>
<td className="px-6 py-2.5 font-bold whitespace-nowrap text-zinc-900 dark:text-dark-text">
{row.estimatedRolls === null ? '-' : formatNumber(row.estimatedRolls)}
</td>
<td className="px-6 py-2.5">{renderIssueBadge(row)}</td> <td className="px-6 py-2.5">{renderIssueBadge(row)}</td>
<td className="px-4 py-2.5 text-right"> <td className="px-4 py-2.5 text-right">
<Link <Link

View File

@@ -4,8 +4,9 @@ import { AlertTriangle, CheckCircle2, Download, Package, Search, TrendingUp } fr
import DateRangePicker from '../components/DateRangePicker'; import DateRangePicker from '../components/DateRangePicker';
import PaginationControls from '../components/PaginationControls'; import PaginationControls from '../components/PaginationControls';
import RefreshStatus from '../components/RefreshStatus'; import RefreshStatus from '../components/RefreshStatus';
import type { DateRange, ProductAnalyticsItem } from '../types'; import { buildOpenProductionByProductId } from '../analytics/cutting';
import { exportToCSV, fetchProductAnalytics } from '../dataService'; import type { DateRange, ProductAnalyticsItem, ProductionOrderItem } from '../types';
import { exportToCSV, fetchProductAnalytics, fetchProductionOrders } from '../dataService';
import { parseProductName, sortProductSizes } from '../productParsing'; import { parseProductName, sortProductSizes } from '../productParsing';
type ReplenishmentStatus = 'need' | 'covered' | 'no_sales' | 'no_stock'; type ReplenishmentStatus = 'need' | 'covered' | 'no_sales' | 'no_stock';
@@ -17,6 +18,8 @@ type ReplenishmentRow = ProductAnalyticsItem & {
dailySales: number; dailySales: number;
projectedDemand: number; projectedDemand: number;
suggestedQuantity: number; suggestedQuantity: number;
openProductionQuantity: number;
availableQuantity: number;
daysOfCover: number | null; daysOfCover: number | null;
status: ReplenishmentStatus; status: ReplenishmentStatus;
statusLabel: string; statusLabel: string;
@@ -79,6 +82,11 @@ const getRangeDays = (range: DateRange) => {
return Math.max(1, Math.round((end.getTime() - start.getTime()) / 86_400_000) + 1); return Math.max(1, Math.round((end.getTime() - start.getTime()) / 86_400_000) + 1);
}; };
const allProductionOrdersRange = {
start: new Date(2000, 0, 1),
end: new Date(2100, 11, 31)
};
const ReplenishmentSkeleton = () => ( 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="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="border-b border-zinc-100 p-4 dark:border-dark-border">
@@ -115,6 +123,7 @@ const Replenishment = () => {
}>(); }>();
const [searchParams] = useSearchParams(); const [searchParams] = useSearchParams();
const [products, setProducts] = useState<ProductAnalyticsItem[]>([]); const [products, setProducts] = useState<ProductAnalyticsItem[]>([]);
const [productionOrders, setProductionOrders] = useState<ProductionOrderItem[]>([]);
const [isLoading, setIsLoading] = useState(true); const [isLoading, setIsLoading] = useState(true);
const [searchTerm, setSearchTerm] = useState(''); const [searchTerm, setSearchTerm] = useState('');
const [statusFilter, setStatusFilter] = useState<ReplenishmentFilter>(() => { const [statusFilter, setStatusFilter] = useState<ReplenishmentFilter>(() => {
@@ -132,10 +141,14 @@ const Replenishment = () => {
const loadProducts = async () => { const loadProducts = async () => {
setIsLoading(true); setIsLoading(true);
const data = await fetchProductAnalytics(dateRange); const [productData, productionOrderData] = await Promise.all([
fetchProductAnalytics(dateRange),
fetchProductionOrders(allProductionOrdersRange)
]);
if (isMounted) { if (isMounted) {
setProducts(data); setProducts(productData);
setProductionOrders(productionOrderData.orders);
setIsLoading(false); setIsLoading(false);
} }
}; };
@@ -147,16 +160,23 @@ const Replenishment = () => {
}; };
}, [dateRange]); }, [dateRange]);
const openProductionByProductId = useMemo(
() => buildOpenProductionByProductId(products, productionOrders),
[products, productionOrders]
);
const allRows = useMemo<ReplenishmentRow[]>(() => { const allRows = useMemo<ReplenishmentRow[]>(() => {
const rangeDays = getRangeDays(dateRange); const rangeDays = getRangeDays(dateRange);
return products.map(product => { return products.map(product => {
const dailySales = product.quantitySold / rangeDays; const dailySales = product.quantitySold / rangeDays;
const projectedDemand = dailySales * targetCoverageDays; const projectedDemand = dailySales * targetCoverageDays;
const rawNeed = projectedDemand - product.stock; const openProductionQuantity = openProductionByProductId[product.id] || 0;
const availableQuantity = product.stock + openProductionQuantity;
const rawNeed = projectedDemand - availableQuantity;
const suggestedQuantity = Math.max(0, Math.ceil(rawNeed)); const suggestedQuantity = Math.max(0, Math.ceil(rawNeed));
const daysOfCover = dailySales > 0 ? product.stock / dailySales : null; const daysOfCover = dailySales > 0 ? availableQuantity / dailySales : null;
const status: ReplenishmentStatus = product.stock <= 0 const status: ReplenishmentStatus = availableQuantity <= 0
? 'no_stock' ? 'no_stock'
: dailySales <= 0 : dailySales <= 0
? 'no_sales' ? 'no_sales'
@@ -171,6 +191,8 @@ const Replenishment = () => {
dailySales, dailySales,
projectedDemand, projectedDemand,
suggestedQuantity, suggestedQuantity,
openProductionQuantity,
availableQuantity,
daysOfCover, daysOfCover,
status, status,
statusLabel: statusStyles[status].label, statusLabel: statusStyles[status].label,
@@ -182,7 +204,7 @@ const Replenishment = () => {
sizes: metadata.size ? [metadata.size] : [] sizes: metadata.size ? [metadata.size] : []
}; };
}); });
}, [dateRange, products, targetCoverageDays]); }, [dateRange, openProductionByProductId, products, targetCoverageDays]);
const groupedRows = useMemo<ReplenishmentRow[]>(() => { const groupedRows = useMemo<ReplenishmentRow[]>(() => {
const groups = new Map<string, ReplenishmentRow[]>(); const groups = new Map<string, ReplenishmentRow[]>();
@@ -199,12 +221,14 @@ const Replenishment = () => {
const quantitySold = group.reduce((total, row) => total + row.quantitySold, 0); const quantitySold = group.reduce((total, row) => total + row.quantitySold, 0);
const revenue = group.reduce((total, row) => total + row.revenue, 0); const revenue = group.reduce((total, row) => total + row.revenue, 0);
const stock = group.reduce((total, row) => total + row.stock, 0); const stock = group.reduce((total, row) => total + row.stock, 0);
const openProductionQuantity = group.reduce((total, row) => total + row.openProductionQuantity, 0);
const availableQuantity = group.reduce((total, row) => total + row.availableQuantity, 0);
const dailySales = group.reduce((total, row) => total + row.dailySales, 0); const dailySales = group.reduce((total, row) => total + row.dailySales, 0);
const projectedDemand = group.reduce((total, row) => total + row.projectedDemand, 0); const projectedDemand = group.reduce((total, row) => total + row.projectedDemand, 0);
const suggestedQuantity = group.reduce((total, row) => total + row.suggestedQuantity, 0); const suggestedQuantity = group.reduce((total, row) => total + row.suggestedQuantity, 0);
const orderLineCount = group.reduce((total, row) => total + row.orderLineCount, 0); const orderLineCount = group.reduce((total, row) => total + row.orderLineCount, 0);
const daysOfCover = dailySales > 0 ? stock / dailySales : null; const daysOfCover = dailySales > 0 ? availableQuantity / dailySales : null;
const status: ReplenishmentStatus = stock <= 0 const status: ReplenishmentStatus = availableQuantity <= 0
? 'no_stock' ? 'no_stock'
: dailySales <= 0 : dailySales <= 0
? 'no_sales' ? 'no_sales'
@@ -222,6 +246,8 @@ const Replenishment = () => {
quantitySold, quantitySold,
revenue, revenue,
stock, stock,
openProductionQuantity,
availableQuantity,
orderLineCount, orderLineCount,
dailySales, dailySales,
projectedDemand, projectedDemand,
@@ -317,6 +343,8 @@ const Replenishment = () => {
'Media Diaria': row.dailySales.toFixed(2).replace('.', ','), 'Media Diaria': row.dailySales.toFixed(2).replace('.', ','),
'Demanda Projetada': row.projectedDemand.toFixed(2).replace('.', ','), 'Demanda Projetada': row.projectedDemand.toFixed(2).replace('.', ','),
'Estoque Atual': row.stock, 'Estoque Atual': row.stock,
'OP Aberta': row.openProductionQuantity,
'Disponivel': row.availableQuantity,
'Cobertura Atual': row.daysOfCover === null ? '' : row.daysOfCover.toFixed(1).replace('.', ','), 'Cobertura Atual': row.daysOfCover === null ? '' : row.daysOfCover.toFixed(1).replace('.', ','),
'Sugestao Reposicao': row.suggestedQuantity 'Sugestao Reposicao': row.suggestedQuantity
})); }));
@@ -481,6 +509,7 @@ const Replenishment = () => {
<colgroup> <colgroup>
<col className="w-[120px]" /> <col className="w-[120px]" />
<col className="w-[390px]" /> <col className="w-[390px]" />
<col className="w-[120px]" />
<col className="w-[130px]" /> <col className="w-[130px]" />
<col className="w-[140px]" /> <col className="w-[140px]" />
<col className="w-[120px]" /> <col className="w-[120px]" />
@@ -495,6 +524,7 @@ const Replenishment = () => {
<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]">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]">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]">Estoque</th>
<th className="px-6 py-4 font-bold uppercase tracking-wider text-[10px]">Disponível</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]">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]">Cobertura</th>
<th className="px-6 py-4 font-bold uppercase tracking-wider text-[10px] text-right">Ações</th> <th className="px-6 py-4 font-bold uppercase tracking-wider text-[10px] text-right">Ações</th>
@@ -524,6 +554,12 @@ const Replenishment = () => {
</td> </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.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 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="font-bold text-zinc-900 dark:text-dark-text">{formatNumber(row.availableQuantity)} un.</span>
{!!row.openProductionQuantity && (
<span className="ml-1 text-xs font-semibold text-dark-muted">OP {formatNumber(row.openProductionQuantity)}</span>
)}
</td>
<td className="px-6 py-2.5 whitespace-nowrap"> <td className="px-6 py-2.5 whitespace-nowrap">
<span className={row.suggestedQuantity > 0 ? 'font-bold text-red-300' : 'font-bold text-emerald-300'}> <span className={row.suggestedQuantity > 0 ? 'font-bold text-red-300' : 'font-bold text-emerald-300'}>
{formatNumber(row.suggestedQuantity)} un. {formatNumber(row.suggestedQuantity)} un.