Reserve material lots from cut plans

This commit is contained in:
Cauê Faleiros
2026-08-25 10:55:54 -03:00
parent a226e6d9f4
commit 91f3e5e00c
8 changed files with 355 additions and 20 deletions

View File

@@ -1,4 +1,4 @@
import type { AuthUser, CampaignPreview, CampaignProcessSummary, CampaignQueueSummary, CatalogCategory, CatalogCategoryPayload, CatalogProduct, CatalogProductPayload, CatalogSummary, ClientAnalyticsItem, ClientDetailsAnalytics, ClientFilterOptions, ClientMetadataFilters, ClientPurchasePatternAnalytics, ConsumptionReference, ConsumptionReferencePayload, CreateProductionOrdersResult, CreateUserResult, CuttingSettings, DashboardAnalytics, DateRange, GraphsStockBalanceHistoryItem, GraphsStockBalancePayload, ManagedUser, OrderData, OlistRunDetails, OlistStatus, ProductAnalyticsItem, ProductComposition, ProductCompositionImportSummary, ProductCompositionPayload, ProductDetailsAnalytics, ProductionOrderExecutionPayload, ProductionOrderImportData, ProductionOrderItem, ProductionOrderPayload, ProductionOrderStatus, ProductionOrderSummary, RfmAnalytics, SellerAnalyticsItem, SellerDetailsAnalytics, StockData, SupplyFabricPlan, SupplyFabricPlanPayload, SupplyInventoryAdjustmentPayload, SupplyLot, SupplyMaterialDetailsPayload, SupplyProductionExitPayload, SupplyPurchaseNeed, SupplyReceipt, SupplyReceiptPayload, SupplySummary } from './types';
import type { AuthUser, CampaignPreview, CampaignProcessSummary, CampaignQueueSummary, CatalogCategory, CatalogCategoryPayload, CatalogProduct, CatalogProductPayload, CatalogSummary, ClientAnalyticsItem, ClientDetailsAnalytics, ClientFilterOptions, ClientMetadataFilters, ClientPurchasePatternAnalytics, ConsumptionReference, ConsumptionReferencePayload, CreateProductionOrdersResult, CreateUserResult, CutPlanLotReservationPayload, CuttingSettings, DashboardAnalytics, DateRange, GraphsStockBalanceHistoryItem, GraphsStockBalancePayload, ManagedUser, OrderData, OlistRunDetails, OlistStatus, ProductAnalyticsItem, ProductComposition, ProductCompositionImportSummary, ProductCompositionPayload, ProductDetailsAnalytics, ProductionOrderExecutionPayload, ProductionOrderImportData, ProductionOrderItem, ProductionOrderPayload, ProductionOrderStatus, ProductionOrderSummary, RfmAnalytics, SellerAnalyticsItem, SellerDetailsAnalytics, StockData, SupplyFabricPlan, SupplyFabricPlanPayload, SupplyInventoryAdjustmentPayload, SupplyLot, SupplyMaterialDetailsPayload, SupplyProductionExitPayload, SupplyPurchaseNeed, SupplyReceipt, SupplyReceiptPayload, SupplySummary } from './types';
import { formatDateParam } from './dateRanges';
const API_URL = import.meta.env.VITE_API_URL || '/api';
@@ -239,11 +239,11 @@ export const fetchProductionOrders = async (
}, options);
};
export const createProductionOrders = async (orders: ProductionOrderPayload[]): Promise<CreateProductionOrdersResult> => {
export const createProductionOrders = async (orders: ProductionOrderPayload[], lotReservations: CutPlanLotReservationPayload[] = []): Promise<CreateProductionOrdersResult> => {
const response = await authFetch('/production-orders', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ orders })
body: JSON.stringify({ orders, lotReservations })
});
if (!response.ok) throw new Error('Não foi possível criar as ordens de produção.');

View File

@@ -6,8 +6,8 @@ import PaginationControls from '../components/PaginationControls';
import ProductColorBadge from '../components/ProductColorBadge';
import RefreshStatus from '../components/RefreshStatus';
import { CUT_FAMILY_RULES, buildCutPlan, buildOpenProductionByProductId, type CutFamilyKey, type CutIssue, type CutPlanSkuRow, type CutProductOverride } from '../analytics/cutting';
import { createProductionOrders, exportToCSV, fetchCuttingSettings, fetchProductAnalytics, fetchProductCompositions, fetchProductionOrders, fetchProductionOrderImportData, fetchStock, saveCuttingSettings } from '../dataService';
import type { CuttingSettings, DateRange, ProductAnalyticsItem, ProductComposition, ProductionOrderItem, ProductionYieldRecommendation, StockData } from '../types';
import { createProductionOrders, exportToCSV, fetchCuttingSettings, fetchProductAnalytics, fetchProductCompositions, fetchProductionOrders, fetchProductionOrderImportData, fetchStock, fetchSupplySummary, saveCuttingSettings } from '../dataService';
import type { CuttingSettings, DateRange, ProductAnalyticsItem, ProductComposition, ProductionOrderItem, ProductionYieldRecommendation, StockData, SupplyLot } from '../types';
import { getPlanningStock } from '../planningStock';
type CutFilter = 'need' | 'all' | 'issues' | 'covered';
@@ -19,6 +19,7 @@ type CorrectionIssueFilter = CutProductIssue | 'all';
type SettingsSection = 'rules' | 'corrections';
type CuttingView = 'plan' | 'families' | 'issues';
type MaterialReadiness = { status: 'ready' | 'material_ready' | 'blocked' | 'missing'; blockers: string[] };
type CutMaterialRequirement = { key: string; label: string; unit: string; quantity: number };
const SETTINGS_STORAGE_KEY = 'nexstar_cutting_settings';
const coverageTargetOptions = [7, 15, 30, 60];
@@ -142,6 +143,7 @@ const Cutting = () => {
const [productionOrders, setProductionOrders] = useState<ProductionOrderItem[]>([]);
const [compositions, setCompositions] = useState<ProductComposition[]>([]);
const [materialStock, setMaterialStock] = useState<StockData[]>([]);
const [supplyLots, setSupplyLots] = useState<SupplyLot[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [searchTerm, setSearchTerm] = useState('');
const [targetCoverageDays, setTargetCoverageDays] = useState(30);
@@ -164,6 +166,7 @@ const Cutting = () => {
const [previewPage, setPreviewPage] = useState(1);
const [previewItemsPerPage, setPreviewItemsPerPage] = useState(10);
const [selectedPreviewRowIds, setSelectedPreviewRowIds] = useState<string[]>([]);
const [lotSelections, setLotSelections] = useState<Record<string, { lotId: string; quantity: string }>>({});
const [editingCutRow, setEditingCutRow] = useState<CutPlanSkuRow | null>(null);
const [quickCutEdit, setQuickCutEdit] = useState<CutProductOverride>({});
const [isQuickCutEditSaving, setIsQuickCutEditSaving] = useState(false);
@@ -213,17 +216,19 @@ const Cutting = () => {
const loadProducts = async () => {
setIsLoading(true);
const [productData, productionOrderData, compositionData, stockData] = await Promise.all([
const [productData, productionOrderData, compositionData, stockData, supplySummary] = await Promise.all([
fetchProductAnalytics(dateRange),
fetchProductionOrders(allProductionOrdersRange),
fetchProductCompositions(),
fetchStock()
fetchStock(),
fetchSupplySummary()
]);
if (isMounted) {
setProducts(productData);
setProductionOrders(productionOrderData.orders);
setCompositions(compositionData);
setMaterialStock(stockData);
setSupplyLots(supplySummary.lots);
setIsLoading(false);
}
};
@@ -245,7 +250,7 @@ const Cutting = () => {
[cuttingSettings, dateRange, openProductionByProductId, products, targetCoverageDays]
);
const materialReadinessByProductId = useMemo(() => {
const compositionsByProductId = useMemo(() => {
const compositionsById = new Map<string, ProductComposition>();
compositions.forEach(composition => {
[composition.finishedTinyProductId, composition.finishedProductSku]
@@ -253,6 +258,10 @@ const Cutting = () => {
.filter(Boolean)
.forEach(key => compositionsById.set(key, composition));
});
return compositionsById;
}, [compositions]);
const materialReadinessByProductId = useMemo(() => {
const stockIndexByKey = new Map<string, number>();
materialStock.forEach((stock, index) => {
[stock.produto_id, stock.nome].map(normalizeMaterialKey).filter(Boolean).forEach(key => stockIndexByKey.set(key, index));
@@ -262,7 +271,7 @@ const Cutting = () => {
// Shared stock is allocated to the largest current requirement first. This
// prevents every SKU from claiming the same material balance independently.
[...cutPlan.rows].sort((a, b) => b.suggestedCutQuantity - a.suggestedCutQuantity || a.name.localeCompare(b.name, 'pt-BR')).forEach(row => {
const composition = compositionsById.get(normalizeMaterialKey(row.id));
const composition = compositionsByProductId.get(normalizeMaterialKey(row.id));
if (!composition?.components.length) {
// Products without an imported composition remain eligible for cutting.
// They are excluded from material-demand calculations instead of
@@ -299,7 +308,7 @@ const Cutting = () => {
readinessByProductId.set(row.id, { status: 'ready', blockers: [] });
});
return readinessByProductId;
}, [compositions, cutPlan.rows, materialStock]);
}, [compositionsByProductId, cutPlan.rows, materialStock]);
const issueSummaries = useMemo(() => {
const counts = new Map<CutIssue, number>();
@@ -383,6 +392,43 @@ const Cutting = () => {
selectedPreviewRows.reduce((total, row) => total + row.suggestedCutQuantity, 0)
), [selectedPreviewRows]);
const cutPlanReference = useMemo(() => (
`Plano de corte ${formatDateKey(dateRange.start)} a ${formatDateKey(dateRange.end)} · ${targetCoverageDays} dias`
), [dateRange.end, dateRange.start, targetCoverageDays]);
const selectedMaterialRequirements = useMemo<CutMaterialRequirement[]>(() => {
const requirements = new Map<string, CutMaterialRequirement>();
selectedPreviewRows.forEach(row => {
const composition = compositionsByProductId.get(normalizeMaterialKey(row.id));
composition?.components
.filter(component => !isServiceComponent(component.componentName) && component.quantityPerUnit > 0)
.forEach(component => {
const key = normalizeMaterialKey(component.componentSku || component.componentTinyId || component.componentName);
if (!key) return;
const current = requirements.get(key) || {
key,
label: component.componentName,
unit: component.unit || 'UN',
quantity: 0
};
current.quantity += row.suggestedCutQuantity * component.quantityPerUnit;
requirements.set(key, current);
});
});
return Array.from(requirements.values()).sort((a, b) => a.label.localeCompare(b.label, 'pt-BR'));
}, [compositionsByProductId, selectedPreviewRows]);
const selectedLotReservations = useMemo(() => (
selectedMaterialRequirements.flatMap(requirement => {
const selection = lotSelections[requirement.key];
const lotId = Number(selection?.lotId);
const quantity = Number((selection?.quantity || '').replace(',', '.'));
return Number.isInteger(lotId) && Number.isFinite(quantity) && quantity > 0
? [{ lotId, materialKey: requirement.key, quantity, cutPlanReference }]
: [];
})
), [cutPlanReference, lotSelections, selectedMaterialRequirements]);
const previewRowsWithIssues = useMemo(() => (
selectedPreviewRows.filter(row => row.issues.length).length
), [selectedPreviewRows]);
@@ -619,6 +665,7 @@ const Cutting = () => {
setGenerationMessage('');
setPreviewPage(1);
setSelectedPreviewRowIds(rowsAvailableForOrder.map(row => row.id));
setLotSelections({});
setIsOrderPreviewOpen(true);
};
@@ -657,7 +704,7 @@ const Cutting = () => {
setGenerationMessage('');
const issueDate = formatDateKey(new Date());
const orderReference = `Plano de corte ${formatDateKey(dateRange.start)} a ${formatDateKey(dateRange.end)} · ${targetCoverageDays} dias`;
const orderReference = cutPlanReference;
try {
const result = await createProductionOrders(selectedPreviewRows.map(row => ({
@@ -669,6 +716,16 @@ const Cutting = () => {
quantity: row.suggestedCutQuantity,
unit: 'UN',
integrationStatus: 'Local',
components: (compositionsByProductId.get(normalizeMaterialKey(row.id))?.components || [])
.filter(component => component.quantityPerUnit > 0)
.map(component => ({
componentTinyId: component.componentTinyId,
componentSku: component.componentSku,
componentName: component.componentName,
quantityPerUnit: component.quantityPerUnit,
totalQuantity: row.suggestedCutQuantity * component.quantityPerUnit,
unit: component.unit
})),
markers: [
{ label: row.family.materialLabel, color: '#38bdf8' },
...(row.color ? [{ label: row.color, color: '#52DFA0' }] : []),
@@ -689,7 +746,7 @@ const Cutting = () => {
availableQuantity: row.availableQuantity,
issues: row.issues
}
})));
})), selectedLotReservations);
const refreshedOrders = await fetchProductionOrders(allProductionOrdersRange, undefined, { force: true });
setProductionOrders(refreshedOrders.orders);
@@ -898,6 +955,17 @@ const Cutting = () => {
</table>
</div>
<section className="border-t border-dark-border bg-dark-input/30 p-4">
<div className="flex flex-col gap-1 sm:flex-row sm:items-end sm:justify-between">
<div>
<h3 className="text-sm font-bold text-dark-text">Reservar lotes para este corte</h3>
<p className="mt-1 text-xs font-semibold text-dark-muted">A reserva é opcional quando o saldo vem do Tiny. Ao selecionar um lote, ela bloqueia somente o saldo disponível para outros planos; a baixa física continua na OP.</p>
</div>
<span className="text-xs font-bold text-brand-primary">{formatNumber(selectedLotReservations.length)} lote(s) reservado(s)</span>
</div>
{selectedMaterialRequirements.length ? <div className="mt-4 overflow-x-auto rounded-xl border border-dark-border bg-dark-card"><table className="w-full min-w-[760px] text-left text-xs"><thead className="bg-dark-header text-dark-muted"><tr><th className="px-3 py-2.5 font-bold">Material necessário</th><th className="px-3 py-2.5 text-right font-bold">Necessário</th><th className="px-3 py-2.5 font-bold">Lote reservado</th><th className="px-3 py-2.5 text-right font-bold">Quantidade reservada</th></tr></thead><tbody className="divide-y divide-dark-border">{selectedMaterialRequirements.map(requirement => { const selection = lotSelections[requirement.key] || { lotId: '', quantity: '' }; const lots = supplyLots.filter(lot => { const lotKey = normalizeMaterialKey(lot.product); const materialMatch = lotKey === requirement.key || lotKey === normalizeMaterialKey(requirement.label); return lot.availableQuantity > 0 && materialMatch && lot.unit.toLowerCase() === requirement.unit.toLowerCase(); }); return <tr key={requirement.key}><td className="px-3 py-3"><p className="font-bold text-dark-text">{requirement.label}</p><p className="mt-0.5 font-mono text-[10px] text-dark-muted">{requirement.key}</p></td><td className="px-3 py-3 text-right font-bold text-dark-text">{formatNumber(requirement.quantity, 4)} {requirement.unit}</td><td className="px-3 py-3"><select value={selection.lotId} onChange={(event) => setLotSelections(current => ({ ...current, [requirement.key]: { lotId: event.target.value, quantity: current[requirement.key]?.quantity || '' } }))} className="h-9 w-full min-w-[230px] rounded-lg border border-dark-border bg-dark-input px-2 text-xs font-semibold text-dark-text outline-none focus:border-brand-primary"><option value="">{lots.length ? 'Não reservar agora' : 'Sem lote compatível'}</option>{lots.map(lot => <option key={lot.id} value={lot.id}>#{lot.id} · {lot.product} · disp. {formatNumber(lot.availableQuantity, 4)} {lot.unit}</option>)}</select></td><td className="px-3 py-3"><input inputMode="decimal" value={selection.quantity} onChange={(event) => setLotSelections(current => ({ ...current, [requirement.key]: { lotId: current[requirement.key]?.lotId || '', quantity: event.target.value } }))} disabled={!selection.lotId} className="h-9 w-32 rounded-lg border border-dark-border bg-dark-input px-2 text-right text-xs font-semibold text-dark-text outline-none placeholder:text-dark-muted focus:border-brand-primary disabled:cursor-not-allowed disabled:opacity-50" placeholder={formatNumber(requirement.quantity, 4)} /></td></tr>; })}</tbody></table></div> : <p className="mt-3 rounded-xl border border-dark-border bg-dark-card px-3 py-3 text-xs font-semibold text-dark-muted">Os SKUs selecionados não possuem componentes de material sincronizados. Eles podem seguir para OP, mas não geram reserva.</p>}
</section>
<PaginationControls
totalItems={rowsAvailableForOrder.length}
currentPage={safePreviewPage}

View File

@@ -397,6 +397,11 @@ const ProductionOrders = () => {
{order.components.length ? <div className="mt-3 overflow-hidden rounded-xl border border-dark-border"><table className="w-full text-xs"><thead className="bg-dark-header text-dark-muted"><tr><th className="px-3 py-2.5 text-left font-bold">Material</th><th className="px-3 py-2.5 text-right font-bold">Por unidade</th><th className="px-3 py-2.5 text-right font-bold">Total</th></tr></thead><tbody className="divide-y divide-dark-border">{order.components.map(component => <tr key={component.id}><td className="px-3 py-3"><p className="font-bold text-dark-text">{component.componentName}</p><p className="mt-0.5 font-mono text-[10px] font-semibold text-dark-muted">{component.componentSku || 'Sem SKU'}</p></td><td className="px-3 py-3 text-right font-semibold text-dark-muted">{formatQuantity(component.quantityPerUnit)} {component.unit}</td><td className="px-3 py-3 text-right font-bold text-dark-text">{formatQuantity(component.totalQuantity)} {component.unit}</td></tr>)}</tbody></table></div> : <p className="mt-3 rounded-xl border border-dark-border bg-dark-card px-4 py-3 text-sm font-semibold text-dark-muted">Sem composição sincronizada.</p>}
</section>
{order.lotReservations.length > 0 && <section>
<h3 className="text-xs font-bold uppercase tracking-widest text-dark-muted">Lotes reservados pelo plano</h3>
<div className="mt-3 overflow-hidden rounded-xl border border-dark-border"><table className="w-full text-xs"><thead className="bg-dark-header text-dark-muted"><tr><th className="px-3 py-2.5 text-left font-bold">Lote</th><th className="px-3 py-2.5 text-left font-bold">Material</th><th className="px-3 py-2.5 text-right font-bold">Reservado</th><th className="px-3 py-2.5 text-right font-bold">Consumido</th></tr></thead><tbody className="divide-y divide-dark-border">{order.lotReservations.map(reservation => <tr key={reservation.id}><td className="px-3 py-3"><p className="font-bold text-dark-text">#{reservation.lotId}</p><p className="mt-0.5 text-[10px] font-semibold text-dark-muted">{reservation.lotSupplier || 'Sem fornecedor'}</p></td><td className="px-3 py-3"><p className="font-bold text-dark-text">{reservation.lotProduct}</p><p className="mt-0.5 font-mono text-[10px] font-semibold text-dark-muted">{reservation.materialKey}</p></td><td className="px-3 py-3 text-right font-bold text-brand-primary">{formatQuantity(reservation.quantity)} {reservation.lotUnit}</td><td className="px-3 py-3 text-right font-semibold text-dark-muted">{formatQuantity(reservation.consumedQuantity)} {reservation.lotUnit}</td></tr>)}</tbody></table></div>
</section>}
<section>
<h3 className="text-xs font-bold uppercase tracking-widest text-dark-muted">Baixa de material</h3>
{order.status === 'cutting' ? <form onSubmit={handleProductionExit} className="mt-3 rounded-xl border border-dark-border bg-dark-card p-4"><p className="text-sm font-semibold text-dark-muted">Registre uma saída somente quando o material for realmente consumido pela OP.</p><div className="mt-4 grid grid-cols-1 gap-3 sm:grid-cols-2"><label className="text-xs font-bold text-dark-muted">Lote de material<select value={exitForm.lotId} onChange={(event) => setExitForm(current => ({ ...current, lotId: event.target.value }))} className="mt-1.5 h-11 w-full rounded-lg border border-dark-border bg-dark-input px-3 text-sm font-semibold text-dark-text outline-none focus:border-brand-primary"><option value="">Selecione...</option>{supplyLots.map(lot => <option key={lot.id} value={lot.id}>#{lot.id} · {lot.product} · {formatQuantity(lot.quantity)} {lot.unit}</option>)}</select></label><label className="text-xs font-bold text-dark-muted">Quantidade<input inputMode="decimal" value={exitForm.quantity} onChange={(event) => setExitForm(current => ({ ...current, quantity: event.target.value }))} className="mt-1.5 h-11 w-full rounded-lg border border-dark-border bg-dark-input px-3 text-sm font-semibold text-dark-text outline-none placeholder:text-dark-muted focus:border-brand-primary" placeholder="kg" /></label><label className="sm:col-span-2 text-xs font-bold text-dark-muted">Motivo (opcional)<input value={exitForm.reason} onChange={(event) => setExitForm(current => ({ ...current, reason: event.target.value }))} className="mt-1.5 h-11 w-full rounded-lg border border-dark-border bg-dark-input px-3 text-sm font-semibold text-dark-text outline-none placeholder:text-dark-muted focus:border-brand-primary" placeholder="Ex.: corte do pedido" /></label></div>{selectedLot && <p className="mt-3 text-xs font-bold text-dark-muted">Saldo do lote #{selectedLot.id}: {formatQuantity(selectedLot.quantity)} {selectedLot.unit}</p>}<button type="submit" disabled={isSupplyBusy || !supplyLots.length || !exitForm.lotId || !exitForm.quantity} className="mt-4 inline-flex h-11 items-center gap-2 rounded-lg border border-brand-primary/35 bg-brand-primary/10 px-4 text-sm font-bold text-brand-primary transition-colors hover:bg-brand-primary/20 disabled:cursor-not-allowed disabled:opacity-50"><PackageCheck className="h-4 w-4" />{isSupplyBusy ? 'Registrando...' : 'Registrar baixa'}</button>{supplyMessage && <p className="mt-3 rounded-lg border border-dark-border bg-dark-input px-3 py-2 text-sm font-bold text-dark-muted">{supplyMessage}</p>}</form> : <div className="mt-3 rounded-xl border border-dark-border bg-dark-card px-4 py-3 text-sm font-semibold text-dark-muted">Altere a OP para <span className="font-bold text-amber-200">Em corte</span> antes de registrar a baixa de materiais.</div>}

View File

@@ -78,6 +78,18 @@ export interface ProductionOrderStep {
color: string;
}
export interface ProductionOrderLotReservation {
id: number;
lotId: number;
materialKey: string;
quantity: number;
consumedQuantity: number;
status: string;
lotProduct: string;
lotUnit: string;
lotSupplier: string;
}
export interface ProductionOrderItem {
id: number;
tinyId: string;
@@ -104,6 +116,7 @@ export interface ProductionOrderItem {
rejectedQuantity: number;
finishedQuantity: number | null;
qualityNotes: string;
lotReservations: ProductionOrderLotReservation[];
markers: ProductionOrderMarker[];
components: ProductionOrderComponent[];
steps: ProductionOrderStep[];
@@ -143,10 +156,25 @@ export type ProductionOrderPayload = {
quantity: number;
unit?: string;
integrationStatus?: string;
components?: Array<{
componentTinyId?: string;
componentSku?: string;
componentName: string;
quantityPerUnit: number;
totalQuantity?: number;
unit?: string;
}>;
markers?: ProductionOrderMarkerPayload[];
metadata?: Record<string, unknown>;
};
export type CutPlanLotReservationPayload = {
lotId: number;
materialKey: string;
quantity: number;
cutPlanReference?: string;
};
export type ProductionOrderExecutionPayload = {
actualCutQuantity?: number | null;
rejectedQuantity?: number | null;
@@ -395,6 +423,8 @@ export interface SupplyLot {
supplier: string;
invoice: string;
status: string;
reservedQuantity: number;
availableQuantity: number;
createdAt: string;
updatedAt: string;
}