Route SKU actions to focused editors

This commit is contained in:
Cauê Faleiros
2026-07-14 13:24:25 -03:00
parent bc05fb4504
commit 63efb47e77
4 changed files with 116 additions and 43 deletions

View File

@@ -12,3 +12,15 @@ export const buildSkuEditPath = ({ sku, name = '', color = '', size = '' }: SkuE
if (size) params.set('size', size);
return `/registrations?${params.toString()}`;
};
export const buildCuttingSkuConfigPath = ({ sku }: Pick<SkuEditParams, 'sku'>) => {
const params = new URLSearchParams({ config: 'corrections', sku });
return `/cutting?${params.toString()}`;
};
export const buildConsumptionReferencePath = ({ sku, name = '', color = '' }: Omit<SkuEditParams, 'size'>) => {
const params = new URLSearchParams({ tab: 'references', sku });
if (name) params.set('name', name);
if (color) params.set('color', color);
return `/registrations?${params.toString()}`;
};

View File

@@ -1,11 +1,11 @@
import { useEffect, useMemo, useState } from 'react';
import { Link, useOutletContext } from 'react-router-dom';
import { Link, useOutletContext, useSearchParams } from 'react-router-dom';
import { AlertTriangle, ArrowLeft, ClipboardList, Download, Eye, Layers3, Palette, Pencil, RotateCcw, Ruler, Save as SaveIcon, Scissors, Search, Settings2, X } from 'lucide-react';
import DateRangePicker from '../components/DateRangePicker';
import PaginationControls from '../components/PaginationControls';
import ProductColorBadge from '../components/ProductColorBadge';
import RefreshStatus from '../components/RefreshStatus';
import { buildSkuEditPath } from '../catalogLinks';
import { buildCuttingSkuConfigPath } from '../catalogLinks';
import { CUT_FAMILY_RULES, buildCutPlan, buildOpenProductionByProductId, type CutFamilyKey, type CutIssue, type CutPlanSkuRow, type CutProductOverride } from '../analytics/cutting';
import { exportToCSV, fetchCuttingSettings, fetchProductAnalytics, fetchProductionOrders, saveCuttingSettings } from '../dataService';
import type { CuttingSettings, DateRange, ProductAnalyticsItem, ProductionOrderItem } from '../types';
@@ -117,6 +117,7 @@ const Cutting = () => {
dateRange: DateRange,
setDateRange: (range: DateRange) => void
}>();
const [searchParams] = useSearchParams();
const [products, setProducts] = useState<ProductAnalyticsItem[]>([]);
const [productionOrders, setProductionOrders] = useState<ProductionOrderItem[]>([]);
const [isLoading, setIsLoading] = useState(true);
@@ -134,6 +135,8 @@ const Cutting = () => {
const [correctionPage, setCorrectionPage] = useState(1);
const [currentPage, setCurrentPage] = useState(1);
const [itemsPerPage, setItemsPerPage] = useState(10);
const cutConfigSection = searchParams.get('config');
const targetCorrectionSku = (searchParams.get('sku') || '').trim();
useEffect(() => {
let isMounted = true;
@@ -249,13 +252,20 @@ const Cutting = () => {
(correctionIssueFilter === 'all' || row.issues.includes(correctionIssueFilter))
));
return [...rows].sort((a, b) => {
const sortedRows = [...rows].sort((a, b) => {
if (b.suggestedCutQuantity !== a.suggestedCutQuantity) {
return b.suggestedCutQuantity - a.suggestedCutQuantity;
}
return a.name.localeCompare(b.name, 'pt-BR');
});
}, [correctionIssueFilter, cutPlan.rows]);
if (!targetCorrectionSku) return sortedRows;
const targetRow = cutPlan.rows.find(row => row.id.toLowerCase() === targetCorrectionSku.toLowerCase());
if (!targetRow) return sortedRows;
return [targetRow, ...sortedRows.filter(row => row.id !== targetRow.id)];
}, [correctionIssueFilter, cutPlan.rows, targetCorrectionSku]);
const correctionItemsPerPage = 12;
const correctionTotalPages = Math.ceil(correctionRows.length / correctionItemsPerPage);
const safeCorrectionPage = Math.min(correctionPage, correctionTotalPages || 1);
@@ -264,6 +274,20 @@ const Cutting = () => {
const configuredYieldCount = CUT_FAMILY_RULES.filter(rule => cuttingSettings.familyYields[rule.key]).length;
const productOverrideCount = Object.keys(cuttingSettings.productOverrides).length;
useEffect(() => {
if (cutConfigSection !== 'corrections' || !targetCorrectionSku) return;
const correctionIndex = correctionRows.findIndex(row => row.id.toLowerCase() === targetCorrectionSku.toLowerCase());
queueMicrotask(() => {
setIsSettingsOpen(true);
setSettingsSection('corrections');
setCorrectionIssueFilter('all');
if (correctionIndex >= 0) {
setCorrectionPage(Math.floor(correctionIndex / correctionItemsPerPage) + 1);
}
});
}, [correctionItemsPerPage, correctionRows, cutConfigSection, targetCorrectionSku]);
useEffect(() => {
if (!isSettingsOpen) return undefined;
@@ -586,8 +610,12 @@ const Cutting = () => {
<div className="divide-y divide-dark-border">
{paginatedCorrectionRows.map(row => {
const override = cuttingSettings.productOverrides[row.id] || {};
const isTargetRow = targetCorrectionSku.toLowerCase() === row.id.toLowerCase();
return (
<div key={row.id} className="grid grid-cols-[120px_1.4fr_150px_150px_120px_80px] items-center gap-3 px-4 py-3">
<div
key={row.id}
className={`grid grid-cols-[120px_1.4fr_150px_150px_120px_80px] items-center gap-3 px-4 py-3 ${isTargetRow ? 'bg-brand-primary/10 ring-1 ring-inset ring-brand-primary/35' : ''}`}
>
<span className="font-mono text-[11px] text-dark-muted">#{row.id}</span>
<div className="min-w-0">
<div className="truncate text-xs font-bold text-dark-text" title={row.name}>{row.name}</div>
@@ -948,10 +976,10 @@ const Cutting = () => {
<td className="px-4 py-2.5 text-right">
<div className="flex justify-end gap-2">
<Link
to={buildSkuEditPath({ sku: row.id, name: row.name, color: row.color, size: row.size })}
to={buildCuttingSkuConfigPath({ sku: row.id })}
className="inline-flex h-8 w-8 items-center justify-center rounded-lg bg-dark-input text-dark-text transition-colors hover:bg-dark-border"
title={`Editar SKU ${row.id}`}
aria-label={`Editar SKU ${row.id}`}
title={`Configurar corte do SKU ${row.id}`}
aria-label={`Configurar corte do SKU ${row.id}`}
>
<Pencil className="h-3.5 w-3.5" />
</Link>

View File

@@ -146,7 +146,7 @@ const Registrations = () => {
const sku = (searchParams.get('sku') || '').trim();
if (!sku && !(requestedTab === 'products' || requestedTab === 'categories' || requestedTab === 'references')) return;
const prefillKey = `${sku}|${searchParams.get('name') || ''}|${catalog.products.length}`;
const prefillKey = `${requestedTab || ''}|${sku}|${searchParams.get('name') || ''}|${searchParams.get('color') || ''}|${catalog.products.length}`;
if (appliedSkuPrefillRef.current === prefillKey) return;
appliedSkuPrefillRef.current = prefillKey;
@@ -158,10 +158,22 @@ const Registrations = () => {
if (!sku) return;
const existingProduct = catalog.products.find(product => product.sku.toLowerCase() === sku.toLowerCase());
setActiveTab('products');
setProductFilter('all');
setStatus('idle');
if (requestedTab === 'references' && existingProduct) {
setActiveTab('references');
setReferenceForm(current => ({
...current,
productId: String(existingProduct.id),
color: searchParams.get('color') || existingProduct.color || current.color
}));
setFeedback(`Criando referência de consumo para SKU ${existingProduct.sku}.`);
return;
}
setActiveTab('products');
if (existingProduct) {
setProductForm({
type: existingProduct.type,
@@ -189,7 +201,11 @@ const Registrations = () => {
color: searchParams.get('color') || '',
sizes: requestedSize ? [requestedSize] : defaultProductForm.sizes
});
setFeedback(`Novo cadastro para SKU ${sku}.`);
setFeedback(
requestedTab === 'references'
? `Cadastre o SKU ${sku} antes de criar a referência de consumo.`
: `Novo cadastro para SKU ${sku}.`
);
});
}, [catalog.products, searchParams]);

View File

@@ -11,6 +11,7 @@ import {
Download,
Link as LinkIcon,
Package,
Pencil,
RefreshCw,
Repeat2,
Ruler,
@@ -21,6 +22,7 @@ import {
Trash2,
Warehouse,
} from 'lucide-react';
import { buildConsumptionReferencePath } from '../catalogLinks';
import { adjustSupplyLotInventory, approveSupplyReceipt, consumeSupplyLotForProduction, createSupplyFabricPlan, createSupplyReceipt, deleteSupplyFabricPlan, deleteSupplyReceipt, fetchSupplySummary } from '../dataService';
import type { SupplyFabricPlan, SupplyLot, SupplyMovement, SupplyPurchaseNeed, SupplyReceipt, SupplySummary } from '../types';
@@ -1246,15 +1248,29 @@ const PurchaseNeedsScreen = () => {
<span>Cobertura</span>
</div>
<div className="divide-y divide-dark-border">
{visibleNeeds.map(need => (
{visibleNeeds.map(need => {
const referenceProduct = need.products?.[0];
return (
<div key={need.material} className="grid grid-cols-1 gap-3 bg-dark-card px-4 py-4 lg:grid-cols-[1.3fr_110px_110px_110px_110px_110px] lg:items-center">
<div>
<p className="text-sm font-bold text-dark-text">{need.material}</p>
<p className="mt-1 text-xs font-semibold text-dark-muted">
<div className="mt-1 flex flex-wrap items-center gap-2">
<p className="text-xs font-semibold text-dark-muted">
{need.missingReference
? 'Cadastre produto/material em Cadastros > Referência de Consumo'
: `${(need.colors.length ? need.colors.join(', ') : 'Todas as cores')} · ${(need.suppliers.length ? need.suppliers.join(', ') : 'Sem fornecedor')}`}
</p>
{need.missingReference && referenceProduct ? (
<RouterLink
to={buildConsumptionReferencePath({ sku: referenceProduct.productId, name: referenceProduct.name })}
className="inline-flex h-7 w-7 items-center justify-center rounded-lg bg-dark-input text-dark-text transition-colors hover:bg-dark-border"
title={`Cadastrar referência do SKU ${referenceProduct.productId}`}
aria-label={`Cadastrar referência do SKU ${referenceProduct.productId}`}
>
<Pencil className="h-3.5 w-3.5" />
</RouterLink>
) : null}
</div>
{need.products?.length ? (
<p className="mt-1 text-xs font-semibold text-dark-muted">
{need.products.slice(0, 2).map(product => product.productId).join(', ')}
@@ -1278,7 +1294,8 @@ const PurchaseNeedsScreen = () => {
{need.missingReference ? 'Sem referência' : purchaseStatusLabels[need.status]}
</span>
</div>
))}
);
})}
</div>
</div>
) : (