Use Tiny compositions for purchase planning
All checks were successful
Build and Deploy / build-and-deploy (push) Successful in 2m41s

This commit is contained in:
Cauê Faleiros
2026-08-03 10:22:39 -03:00
parent 1a3fed3dda
commit e993bfdaf3
11 changed files with 544 additions and 40 deletions

View File

@@ -7,8 +7,8 @@ import DateRangePicker from '../components/DateRangePicker';
import SkuPlanningModal from '../components/SkuPlanningModal';
import ProductTypeBadge from '../components/ProductTypeBadge';
import RefreshStatus from '../components/RefreshStatus';
import type { CutProductOverride, CuttingSettings, DateRange, ProductComposition, ProductDetailsAnalytics } from '../types';
import { fetchCuttingSettings, fetchProductComposition, fetchProductDetailsAnalytics, saveCuttingSettings } from '../dataService';
import type { CutProductOverride, CuttingSettings, DateRange, ProductComposition, ProductDetailsAnalytics, StockData } from '../types';
import { fetchCuttingSettings, fetchProductComposition, fetchProductDetailsAnalytics, fetchStock, saveCuttingSettings } from '../dataService';
import { parseProductName } from '../productParsing';
import { formatColorLabel } from '../displayFormatters';
import { averageRecentValues, formatDateBucketLabel, formatDateBucketLongLabel, getAutoDateBucket, getMovingAverageWindow, getRangeDayCount, getDateBucketKey, type DateBucket } from '../chartUtils';
@@ -132,6 +132,7 @@ const ProductDetails = () => {
}>();
const [details, setDetails] = useState<ProductDetailsAnalytics | null>(null);
const [composition, setComposition] = useState<ProductComposition | null>(null);
const [materialStock, setMaterialStock] = useState<StockData[]>([]);
const [isCompositionLoading, setIsCompositionLoading] = useState(true);
const [isLoading, setIsLoading] = useState(true);
const [chartMetric, setChartMetric] = useState<ProductChartMetric>('quantity');
@@ -171,14 +172,16 @@ const ProductDetails = () => {
setIsLoading(true);
setIsCompositionLoading(true);
const [productDetails, productComposition] = await Promise.all([
const [productDetails, productComposition, stock] = await Promise.all([
fetchProductDetailsAnalytics(id, dateRange),
fetchProductComposition(id)
fetchProductComposition(id),
fetchStock()
]);
if (isMounted) {
setDetails(productDetails);
setComposition(productComposition);
setMaterialStock(stock);
setIsLoading(false);
setIsCompositionLoading(false);
}
@@ -331,6 +334,35 @@ const ProductDetails = () => {
: formatDateBucketLongLabel(selectedProductPoint.date, dateBucket)
: '';
const maxVariantQuantity = Math.max(...variantBreakdown.map(variant => variant.quantitySold), 0);
const normalizeMaterialKey = (value: string) => value
.normalize('NFD')
.replace(/[\u0300-\u036f]/g, '')
.replace(/\s+/g, ' ')
.trim()
.toUpperCase();
const materialPlan = (composition?.components || []).map(component => {
const candidates = new Set([
component.componentTinyId,
component.componentSku,
component.productId || '',
component.componentName
].map(normalizeMaterialKey).filter(Boolean));
const stockMatch = materialStock.find(item => (
candidates.has(normalizeMaterialKey(item.produto_id)) || candidates.has(normalizeMaterialKey(item.nome))
));
const availableStock = stockMatch ? getPlanningStock(stockMatch.saldo) : null;
const requiredForPeriod = totalSold * component.quantityPerUnit;
const productionCapacity = availableStock === null || component.quantityPerUnit <= 0
? null
: Math.floor(availableStock / component.quantityPerUnit);
const periodCoverage = requiredForPeriod > 0 && availableStock !== null
? (availableStock / requiredForPeriod) * periodDays
: null;
return { component, availableStock, requiredForPeriod, productionCapacity, periodCoverage };
});
const blockingMaterial = materialPlan
.filter(item => item.productionCapacity !== null)
.sort((a, b) => (a.productionCapacity || 0) - (b.productionCapacity || 0))[0];
return (
<div className="space-y-6">
@@ -414,12 +446,23 @@ const ProductDetails = () => {
</div>
<section className="bg-white dark:bg-dark-card border border-zinc-200 dark:border-dark-border rounded-2xl p-6 shadow-sm">
<div className="mb-5">
<h3 className="text-lg font-bold text-zinc-900 dark:text-dark-text">Composição</h3>
{composition && (
<p className="mt-1 text-sm font-medium text-zinc-500 dark:text-dark-muted">
Para produzir 1 UN de {composition.finishedProductSku || productInfo.id}
</p>
<div className="mb-5 flex flex-col gap-3 md:flex-row md:items-end md:justify-between">
<div>
<h3 className="text-lg font-bold text-zinc-900 dark:text-dark-text">Composição</h3>
{composition && (
<p className="mt-1 text-sm font-medium text-zinc-500 dark:text-dark-muted">
Necessidade para as {formatNumber(totalSold)} un. vendidas no período e saldo atual do Tiny.
</p>
)}
</div>
{blockingMaterial && (
<div className={`rounded-xl border px-3 py-2 text-xs font-bold ${
(blockingMaterial.productionCapacity || 0) < totalSold
? 'border-red-400/30 bg-red-400/10 text-red-300'
: 'border-emerald-400/30 bg-emerald-400/10 text-emerald-300'
}`}>
Limitante: {blockingMaterial.component.componentName} · {formatNumber(blockingMaterial.productionCapacity || 0)} un. possíveis
</div>
)}
</div>
{isCompositionLoading ? (
@@ -434,17 +477,20 @@ const ProductDetails = () => {
</div>
) : (
<div className="overflow-x-auto rounded-xl border border-dark-border">
<table className="w-full min-w-[640px] text-left text-sm">
<table className="w-full min-w-[920px] text-left text-sm">
<thead className="bg-dark-input/60 text-[10px] font-bold uppercase tracking-widest text-dark-muted">
<tr>
<th className="px-4 py-3">Produto / insumo</th>
<th className="px-4 py-3">SKU</th>
<th className="px-4 py-3 text-right">Quantidade por unidade</th>
<th className="px-4 py-3">Unidade</th>
<th className="px-4 py-3 text-right">Necessário no período</th>
<th className="px-4 py-3 text-right">Estoque Tiny</th>
<th className="px-4 py-3 text-right">Cobertura</th>
</tr>
</thead>
<tbody className="divide-y divide-dark-border">
{composition.components.map(component => (
{materialPlan.map(({ component, requiredForPeriod, availableStock, productionCapacity, periodCoverage }) => (
<tr key={component.id} className="text-dark-text">
<td className="px-4 py-3 font-semibold">
{component.productId ? (
@@ -456,6 +502,13 @@ const ProductDetails = () => {
<td className="px-4 py-3 font-mono text-xs text-dark-muted">{component.componentSku || '—'}</td>
<td className="px-4 py-3 text-right font-semibold">{formatNumber(component.quantityPerUnit)}</td>
<td className="px-4 py-3 text-dark-muted">{component.unit || '—'}</td>
<td className="px-4 py-3 text-right font-semibold">{formatNumber(requiredForPeriod)} {component.unit || ''}</td>
<td className="px-4 py-3 text-right font-semibold">{availableStock === null ? 'Sem vínculo' : `${formatNumber(availableStock)} ${component.unit || ''}`}</td>
<td className={`px-4 py-3 text-right font-bold ${availableStock === null || (productionCapacity || 0) < totalSold ? 'text-red-300' : 'text-emerald-300'}`}>
{availableStock === null
? 'Revisar link'
: `${formatNumber(productionCapacity || 0)} un. · ${periodCoverage === null ? '-' : `${formatNumber(periodCoverage)} dias`}`}
</td>
</tr>
))}
</tbody>