Add grouped replenishment analysis
All checks were successful
Build and Deploy / build-and-deploy (push) Successful in 2m1s

This commit is contained in:
Cauê Faleiros
2026-07-07 09:59:07 -03:00
parent e0c71de3eb
commit 56cff262ab
4 changed files with 199 additions and 30 deletions

View File

@@ -6,6 +6,7 @@ import DateRangePicker from '../components/DateRangePicker';
import RefreshStatus from '../components/RefreshStatus'; import RefreshStatus from '../components/RefreshStatus';
import type { DateRange, ProductDetailsAnalytics } from '../types'; import type { DateRange, ProductDetailsAnalytics } from '../types';
import { fetchProductDetailsAnalytics } from '../dataService'; import { fetchProductDetailsAnalytics } from '../dataService';
import { parseProductName } from '../productParsing';
const CHART_GRID_COLOR = 'var(--chart-grid)'; const CHART_GRID_COLOR = 'var(--chart-grid)';
const CHART_AXIS_COLOR = 'var(--chart-axis)'; const CHART_AXIS_COLOR = 'var(--chart-axis)';
@@ -351,13 +352,26 @@ const ProductDetails = () => {
<div className="space-y-3"> <div className="space-y-3">
{variantBreakdown.map(variant => { {variantBreakdown.map(variant => {
const width = maxVariantQuantity ? Math.max(4, (variant.quantitySold / maxVariantQuantity) * 100) : 0; const width = maxVariantQuantity ? Math.max(4, (variant.quantitySold / maxVariantQuantity) * 100) : 0;
const metadata = parseProductName(variant.name);
return ( return (
<div key={variant.id} className="rounded-xl border border-dark-border bg-dark-input/45 p-4"> <div key={variant.id} className="rounded-xl border border-dark-border bg-dark-input/45 p-4">
<div className="flex flex-col gap-2 md:flex-row md:items-start md:justify-between"> <div className="flex flex-col gap-2 md:flex-row md:items-start md:justify-between">
<div className="min-w-0"> <div className="min-w-0">
<div className="truncate text-sm font-bold text-dark-text">{variant.name}</div> <div className="truncate text-sm font-bold text-dark-text">{variant.name}</div>
<div className="mt-1 text-[11px] font-medium text-dark-muted">#{variant.id}</div> <div className="mt-1 flex flex-wrap items-center gap-2 text-[11px] font-medium text-dark-muted">
<span>#{variant.id}</span>
{metadata.color && (
<span className="rounded-full border border-sky-400/25 bg-sky-400/10 px-2 py-0.5 font-bold text-sky-300">
{metadata.color}
</span>
)}
{metadata.size && (
<span className="rounded-full border border-emerald-400/25 bg-emerald-400/10 px-2 py-0.5 font-bold text-emerald-300">
Tam. {metadata.size}
</span>
)}
</div>
</div> </div>
<div className="flex shrink-0 gap-5 text-right text-xs"> <div className="flex shrink-0 gap-5 text-right text-xs">
<div> <div>

View File

@@ -1,6 +1,6 @@
import { useEffect, useMemo, useRef, useState } from 'react'; import { useEffect, useMemo, useRef, useState } from 'react';
import { Link, useOutletContext } from 'react-router-dom'; import { Link, useOutletContext } from 'react-router-dom';
import { Download, Filter, Package, PackageCheck, Search, TrendingDown, TrendingUp, X } from 'lucide-react'; import { Download, Filter, Package, PackageCheck, PackagePlus, Search, TrendingDown, TrendingUp, X } from 'lucide-react';
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 type { DateRange, ProductAnalyticsItem } from '../types';
@@ -569,6 +569,15 @@ const Products = () => {
)} )}
</div> </div>
<Link
to="/replenishment?status=need&view=group"
className="flex items-center justify-center gap-2 bg-dark-card border border-dark-border px-4 py-2.5 rounded-xl shadow-sm hover:border-brand-primary transition-colors text-sm font-medium text-dark-text cursor-pointer"
title="Ver necessidade de reposição"
>
<PackagePlus size={16} className="text-brand-primary" />
<span className="hidden sm:inline">Reposição</span>
</Link>
<button <button
onClick={() => { onClick={() => {
const exportData = productsData.map(product => ({ const exportData = productsData.map(product => ({

View File

@@ -1,15 +1,17 @@
import { useEffect, useMemo, useState } from 'react'; import { useEffect, useMemo, useState } from 'react';
import { Link, useOutletContext } from 'react-router-dom'; import { Link, useOutletContext, useSearchParams } from 'react-router-dom';
import { AlertTriangle, CheckCircle2, Download, Package, Search, TrendingUp } from 'lucide-react'; import { AlertTriangle, CheckCircle2, Download, Package, Search, TrendingUp } 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 type { DateRange, ProductAnalyticsItem } from '../types'; import type { DateRange, ProductAnalyticsItem } from '../types';
import { exportToCSV, fetchProductAnalytics } from '../dataService'; import { exportToCSV, fetchProductAnalytics } from '../dataService';
import { parseProductName, sortProductSizes } from '../productParsing';
type ReplenishmentStatus = 'need' | 'covered' | 'no_sales' | 'no_stock'; type ReplenishmentStatus = 'need' | 'covered' | 'no_sales' | 'no_stock';
type ReplenishmentFilter = 'all' | ReplenishmentStatus; type ReplenishmentFilter = 'all' | ReplenishmentStatus;
type ReplenishmentSort = 'need_desc' | 'need_asc' | 'demand_desc' | 'stock_asc' | 'coverage_asc' | 'sold_desc' | 'name_asc'; type ReplenishmentSort = 'need_desc' | 'need_asc' | 'demand_desc' | 'stock_asc' | 'coverage_asc' | 'sold_desc' | 'name_asc';
type ReplenishmentView = 'sku' | 'group';
type ReplenishmentRow = ProductAnalyticsItem & { type ReplenishmentRow = ProductAnalyticsItem & {
dailySales: number; dailySales: number;
@@ -18,6 +20,12 @@ type ReplenishmentRow = ProductAnalyticsItem & {
daysOfCover: number | null; daysOfCover: number | null;
status: ReplenishmentStatus; status: ReplenishmentStatus;
statusLabel: string; statusLabel: string;
baseName: string;
color: string;
size: string;
productIds: string[];
productCount: number;
sizes: string[];
}; };
const horizonOptions = [7, 15, 30, 60]; const horizonOptions = [7, 15, 30, 60];
@@ -105,12 +113,17 @@ const Replenishment = () => {
dateRange: DateRange, dateRange: DateRange,
setDateRange: (range: DateRange) => void setDateRange: (range: DateRange) => void
}>(); }>();
const [searchParams] = useSearchParams();
const [products, setProducts] = useState<ProductAnalyticsItem[]>([]); const [products, setProducts] = useState<ProductAnalyticsItem[]>([]);
const [isLoading, setIsLoading] = useState(true); const [isLoading, setIsLoading] = useState(true);
const [searchTerm, setSearchTerm] = useState(''); const [searchTerm, setSearchTerm] = useState('');
const [horizonDays, setHorizonDays] = useState(30); const [horizonDays, setHorizonDays] = useState(30);
const [statusFilter, setStatusFilter] = useState<ReplenishmentFilter>('need'); const [statusFilter, setStatusFilter] = useState<ReplenishmentFilter>(() => {
const filter = searchParams.get('status') as ReplenishmentFilter | null;
return filter && filterOptions.some(option => option.value === filter) ? filter : 'need';
});
const [sortBy, setSortBy] = useState<ReplenishmentSort>('need_desc'); const [sortBy, setSortBy] = useState<ReplenishmentSort>('need_desc');
const [viewMode, setViewMode] = useState<ReplenishmentView>(() => searchParams.get('view') === 'group' ? 'group' : 'sku');
const [currentPage, setCurrentPage] = useState(1); const [currentPage, setCurrentPage] = useState(1);
const [itemsPerPage, setItemsPerPage] = useState(10); const [itemsPerPage, setItemsPerPage] = useState(10);
@@ -143,13 +156,15 @@ const Replenishment = () => {
const rawNeed = projectedDemand - product.stock; const rawNeed = projectedDemand - product.stock;
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 ? product.stock / dailySales : null;
const status: ReplenishmentStatus = dailySales <= 0 const status: ReplenishmentStatus = product.stock <= 0
? 'no_sales'
: product.stock <= 0
? 'no_stock' ? 'no_stock'
: suggestedQuantity > 0 : dailySales <= 0
? 'need' ? 'no_sales'
: 'covered'; : suggestedQuantity > 0
? 'need'
: 'covered';
const metadata = parseProductName(product.name);
return { return {
...product, ...product,
@@ -158,19 +173,81 @@ const Replenishment = () => {
suggestedQuantity, suggestedQuantity,
daysOfCover, daysOfCover,
status, status,
statusLabel: statusStyles[status].label statusLabel: statusStyles[status].label,
baseName: metadata.baseName,
color: metadata.color,
size: metadata.size,
productIds: [product.id],
productCount: 1,
sizes: metadata.size ? [metadata.size] : []
}; };
}); });
}, [dateRange, horizonDays, products]); }, [dateRange, horizonDays, products]);
const groupedRows = useMemo<ReplenishmentRow[]>(() => {
const groups = new Map<string, ReplenishmentRow[]>();
allRows.forEach(row => {
const key = `${row.baseName.toLowerCase()}::${row.color.toLowerCase()}`;
const group = groups.get(key) || [];
group.push(row);
groups.set(key, group);
});
return Array.from(groups.values()).map(group => {
const first = group[0];
const quantitySold = group.reduce((total, row) => total + row.quantitySold, 0);
const revenue = group.reduce((total, row) => total + row.revenue, 0);
const stock = group.reduce((total, row) => total + row.stock, 0);
const dailySales = group.reduce((total, row) => total + row.dailySales, 0);
const projectedDemand = group.reduce((total, row) => total + row.projectedDemand, 0);
const suggestedQuantity = group.reduce((total, row) => total + row.suggestedQuantity, 0);
const orderLineCount = group.reduce((total, row) => total + row.orderLineCount, 0);
const daysOfCover = dailySales > 0 ? stock / dailySales : null;
const status: ReplenishmentStatus = stock <= 0
? 'no_stock'
: dailySales <= 0
? 'no_sales'
: suggestedQuantity > 0
? 'need'
: 'covered';
const sizes = sortProductSizes(Array.from(new Set(group.flatMap(row => row.sizes))));
const productIds = group.map(row => row.id);
const name = first.color ? `${first.baseName} · ${first.color}` : first.baseName;
return {
...first,
id: productIds[0],
name,
quantitySold,
revenue,
stock,
orderLineCount,
dailySales,
projectedDemand,
suggestedQuantity,
daysOfCover,
status,
statusLabel: statusStyles[status].label,
productIds,
productCount: group.length,
sizes,
lastPrice: group.length ? revenue / Math.max(1, quantitySold) : first.lastPrice
};
});
}, [allRows]);
const activeRows = viewMode === 'group' ? groupedRows : allRows;
const filteredRows = useMemo(() => { const filteredRows = useMemo(() => {
const normalizedSearch = searchTerm.trim().toLowerCase(); const normalizedSearch = searchTerm.trim().toLowerCase();
const searchedRows = normalizedSearch const searchedRows = normalizedSearch
? allRows.filter(row => ? activeRows.filter(row =>
row.name.toLowerCase().includes(normalizedSearch) || row.name.toLowerCase().includes(normalizedSearch) ||
row.id.toLowerCase().includes(normalizedSearch) row.id.toLowerCase().includes(normalizedSearch) ||
row.productIds.some(id => id.toLowerCase().includes(normalizedSearch))
) )
: allRows; : activeRows;
const statusRows = statusFilter === 'all' const statusRows = statusFilter === 'all'
? searchedRows ? searchedRows
@@ -189,7 +266,7 @@ const Replenishment = () => {
return b.suggestedQuantity - a.suggestedQuantity; return b.suggestedQuantity - a.suggestedQuantity;
} }
}); });
}, [allRows, searchTerm, sortBy, statusFilter]); }, [activeRows, searchTerm, sortBy, statusFilter]);
const totalPages = Math.ceil(filteredRows.length / itemsPerPage); const totalPages = Math.ceil(filteredRows.length / itemsPerPage);
const safeCurrentPage = Math.min(currentPage, totalPages || 1); const safeCurrentPage = Math.min(currentPage, totalPages || 1);
@@ -197,10 +274,10 @@ const Replenishment = () => {
const paginatedRows = filteredRows.slice(startIndex, startIndex + itemsPerPage); const paginatedRows = filteredRows.slice(startIndex, startIndex + itemsPerPage);
const isRefreshing = isLoading && products.length > 0; const isRefreshing = isLoading && products.length > 0;
const needRows = allRows.filter(row => row.suggestedQuantity > 0); const needRows = activeRows.filter(row => row.suggestedQuantity > 0);
const totalSuggestedQuantity = needRows.reduce((total, row) => total + row.suggestedQuantity, 0); const totalSuggestedQuantity = needRows.reduce((total, row) => total + row.suggestedQuantity, 0);
const projectedDemand = allRows.reduce((total, row) => total + row.projectedDemand, 0); const projectedDemand = activeRows.reduce((total, row) => total + row.projectedDemand, 0);
const totalStock = allRows.reduce((total, row) => total + row.stock, 0); const totalStock = activeRows.reduce((total, row) => total + row.stock, 0);
return ( return (
<div className="space-y-6"> <div className="space-y-6">
@@ -224,8 +301,12 @@ const Replenishment = () => {
<button <button
onClick={() => { onClick={() => {
const exportData = filteredRows.map(row => ({ const exportData = filteredRows.map(row => ({
'ID Produto': row.id, 'Tipo': viewMode === 'group' ? 'Grupo' : 'SKU',
'ID Produto': viewMode === 'group' ? row.productIds.join(' | ') : row.id,
'Descricao': row.name, 'Descricao': row.name,
'Cor': row.color,
'Tamanhos': row.sizes.join(' | '),
'SKUs': row.productCount,
'Status': row.statusLabel, 'Status': row.statusLabel,
'Horizonte (dias)': horizonDays, 'Horizonte (dias)': horizonDays,
'Vendido no Periodo': row.quantitySold, 'Vendido no Periodo': row.quantitySold,
@@ -254,7 +335,9 @@ const Replenishment = () => {
<div> <div>
<p className="text-xs font-bold uppercase tracking-widest text-dark-muted">Produtos a repor</p> <p className="text-xs font-bold uppercase tracking-widest text-dark-muted">Produtos a repor</p>
<p className="mt-2 text-3xl font-bold text-red-300">{formatNumber(needRows.length)}</p> <p className="mt-2 text-3xl font-bold text-red-300">{formatNumber(needRows.length)}</p>
<p className="mt-1 text-xs font-semibold text-dark-muted">Com estoque abaixo da demanda projetada</p> <p className="mt-1 text-xs font-semibold text-dark-muted">
{viewMode === 'group' ? 'Grupos' : 'SKUs'} abaixo da demanda projetada
</p>
</div> </div>
<div className="rounded-xl border border-red-400/25 bg-red-400/10 p-3 text-red-300"> <div className="rounded-xl border border-red-400/25 bg-red-400/10 p-3 text-red-300">
<AlertTriangle className="h-5 w-5" /> <AlertTriangle className="h-5 w-5" />
@@ -291,8 +374,8 @@ const Replenishment = () => {
<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">Produtos cobertos</p> <p className="text-xs font-bold uppercase tracking-widest text-dark-muted">{viewMode === 'group' ? 'Grupos cobertos' : 'Produtos cobertos'}</p>
<p className="mt-2 text-3xl font-bold text-emerald-300">{formatNumber(allRows.filter(row => row.status === 'covered').length)}</p> <p className="mt-2 text-3xl font-bold text-emerald-300">{formatNumber(activeRows.filter(row => row.status === 'covered').length)}</p>
<p className="mt-1 text-xs font-semibold text-dark-muted">{formatNumber(totalStock)} unidades em estoque</p> <p className="mt-1 text-xs font-semibold text-dark-muted">{formatNumber(totalStock)} unidades em estoque</p>
</div> </div>
<div className="rounded-xl border border-emerald-400/25 bg-emerald-400/10 p-3 text-emerald-300"> <div className="rounded-xl border border-emerald-400/25 bg-emerald-400/10 p-3 text-emerald-300">
@@ -302,7 +385,30 @@ const Replenishment = () => {
</div> </div>
</div> </div>
<div className="grid grid-cols-1 gap-3 rounded-2xl border border-dark-border bg-dark-card p-4 shadow-sm lg:grid-cols-[1fr_160px_180px_190px]"> <div className="grid grid-cols-1 gap-3 rounded-2xl border border-dark-border bg-dark-card p-4 shadow-sm xl:grid-cols-[auto_1fr_160px_180px_190px]">
<div className="inline-flex rounded-xl border border-dark-border bg-dark-input p-1">
{[
{ key: 'sku' as const, label: 'SKU' },
{ key: 'group' as const, label: 'Grupo' }
].map(view => (
<button
key={view.key}
type="button"
onClick={() => {
setViewMode(view.key);
setCurrentPage(1);
}}
className={`rounded-lg px-4 py-2 text-sm font-bold transition-colors cursor-pointer ${
viewMode === view.key
? 'bg-brand-primary text-brand-contrast'
: 'text-dark-muted hover:bg-dark-card hover:text-dark-text'
}`}
>
{view.label}
</button>
))}
</div>
<div className="relative"> <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" /> <Search className="absolute left-3 top-1/2 h-5 w-5 -translate-y-1/2 text-zinc-400 dark:text-dark-muted" />
<input <input
@@ -366,21 +472,21 @@ const Replenishment = () => {
) : ( ) : (
<div className={`bg-white dark:bg-dark-card border border-zinc-200 dark:border-dark-border rounded-2xl overflow-hidden shadow-sm ${isRefreshing ? 'refreshing-content' : ''}`} aria-busy={isRefreshing}> <div className={`bg-white dark:bg-dark-card border border-zinc-200 dark:border-dark-border rounded-2xl overflow-hidden shadow-sm ${isRefreshing ? 'refreshing-content' : ''}`} aria-busy={isRefreshing}>
<div className="overflow-x-auto"> <div className="overflow-x-auto">
<table className="w-full min-w-[1240px] table-fixed text-left text-sm"> <table className="w-full min-w-[1320px] table-fixed text-left text-sm">
<colgroup> <colgroup>
<col className="w-[120px]" /> <col className="w-[120px]" />
<col className="w-[360px]" /> <col className="w-[390px]" />
<col className="w-[130px]" /> <col className="w-[130px]" />
<col className="w-[140px]" /> <col className="w-[140px]" />
<col className="w-[120px]" /> <col className="w-[120px]" />
<col className="w-[150px]" /> <col className="w-[150px]" />
<col className="w-[130px]" /> <col className="w-[130px]" />
<col className="w-[110px]" /> <col className="w-[140px]" />
</colgroup> </colgroup>
<thead className="bg-zinc-50 dark:bg-dark-header border-b border-zinc-100 dark:border-dark-border text-zinc-500 dark:text-dark-muted"> <thead className="bg-zinc-50 dark:bg-dark-header border-b border-zinc-100 dark:border-dark-border text-zinc-500 dark:text-dark-muted">
<tr> <tr>
<th className="px-6 py-4 font-bold uppercase tracking-wider text-[10px]">ID Produto</th> <th className="px-6 py-4 font-bold uppercase tracking-wider text-[10px]">{viewMode === 'group' ? 'SKUs' : 'ID Produto'}</th>
<th className="px-6 py-4 font-bold uppercase tracking-wider text-[10px]">Descrição</th> <th className="px-6 py-4 font-bold uppercase tracking-wider text-[10px]">{viewMode === 'group' ? 'Grupo / cor' : 'Descrição'}</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]">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>
@@ -395,10 +501,13 @@ const Replenishment = () => {
return ( return (
<tr key={row.id} className="hover:bg-zinc-50/80 dark:hover:bg-dark-input/50 transition-colors"> <tr key={row.id} className="hover:bg-zinc-50/80 dark:hover:bg-dark-input/50 transition-colors">
<td className="px-6 py-2.5 font-mono text-[11px] text-zinc-400 dark:text-dark-muted">#{row.id}</td> <td className="px-6 py-2.5 font-mono text-[11px] text-zinc-400 dark:text-dark-muted">
{viewMode === 'group' ? `${row.productCount} SKUs` : `#${row.id}`}
</td>
<td className="max-w-0 px-6 py-2.5"> <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="truncate font-semibold text-zinc-900 dark:text-dark-text" title={row.name}>{row.name}</div>
<div className="text-[10px] text-zinc-400 dark:text-dark-muted font-medium"> <div className="text-[10px] text-zinc-400 dark:text-dark-muted font-medium">
{viewMode === 'group' && row.sizes.length ? `Tamanhos: ${row.sizes.join(', ')} · ` : ''}
Média: {formatNumber(row.dailySales, 2)} un./dia · Vendido: {formatNumber(row.quantitySold)} un. Média: {formatNumber(row.dailySales, 2)} un./dia · Vendido: {formatNumber(row.quantitySold)} un.
</div> </div>
</td> </td>
@@ -421,7 +530,7 @@ const Replenishment = () => {
to={`/products/${row.id}`} to={`/products/${row.id}`}
className="inline-flex items-center whitespace-nowrap text-xs font-bold text-brand-primary hover:opacity-80 transition-opacity bg-brand-primary/10 px-3 py-1.5 rounded-lg cursor-pointer" className="inline-flex items-center whitespace-nowrap text-xs font-bold text-brand-primary hover:opacity-80 transition-opacity bg-brand-primary/10 px-3 py-1.5 rounded-lg cursor-pointer"
> >
Ver produto {viewMode === 'group' ? 'Ver líder' : 'Ver produto'}
</Link> </Link>
</td> </td>
</tr> </tr>

37
src/productParsing.ts Normal file
View File

@@ -0,0 +1,37 @@
const sizeOrder = ['2', '4', '6', '8', '10', '12', '14', '16', 'PP', 'P', 'M', 'G', 'GG', 'XG', 'G1', 'G2', 'G3', 'G4', 'G5'];
const sizeSet = new Set(sizeOrder);
export const normalizeProductText = (value: string) => value.replace(/\s+/g, ' ').trim();
export const sortProductSizes = (sizes: string[]) => [...sizes].sort((a, b) => {
const indexA = sizeOrder.indexOf(a);
const indexB = sizeOrder.indexOf(b);
if (indexA !== -1 || indexB !== -1) {
return (indexA === -1 ? Number.MAX_SAFE_INTEGER : indexA) - (indexB === -1 ? Number.MAX_SAFE_INTEGER : indexB);
}
return a.localeCompare(b, 'pt-BR');
});
export const parseProductName = (name: string) => {
const cleanName = normalizeProductText(name);
const explicitSizeMatch = cleanName.match(/\bTAMANHO\s*-?\s*([A-Z0-9]+)\b/i);
const trailingTokenMatch = cleanName.match(/(?:\s+-\s+|\s)([A-Z0-9]+)$/i);
const trailingToken = trailingTokenMatch?.[1]?.toUpperCase() || '';
const size = (explicitSizeMatch?.[1] || (sizeSet.has(trailingToken) ? trailingToken : '')).toUpperCase();
const colorMatch = cleanName.match(/\bCOR\s+(.+?)(?:\s+TAMANHO|\s+-\s+[A-Z0-9]+$|$)/i);
const color = normalizeProductText(colorMatch?.[1] || '');
let baseName = cleanName
.replace(/\bCOR\s+.+?(?:\s+TAMANHO\s*-?\s*[A-Z0-9]+|\s+-\s+[A-Z0-9]+$|$)/i, '')
.replace(/\bTAMANHO\s*-?\s*[A-Z0-9]+\b/i, '')
.replace(/\s+-\s*[A-Z0-9]+$/i, '');
baseName = normalizeProductText(baseName.replace(/\s+-\s*$/g, ''));
return {
baseName: baseName || cleanName,
color,
size
};
};