Connect production orders to stock movements
This commit is contained in:
@@ -1,7 +1,9 @@
|
|||||||
const express = require('express');
|
const express = require('express');
|
||||||
const { verifyToken } = require('../auth');
|
const { verifyToken } = require('../auth');
|
||||||
const {
|
const {
|
||||||
|
adjustInventoryLot,
|
||||||
approveReceipt,
|
approveReceipt,
|
||||||
|
consumeLotForProduction,
|
||||||
createFabricPlan,
|
createFabricPlan,
|
||||||
createReceipt,
|
createReceipt,
|
||||||
deleteFabricPlan,
|
deleteFabricPlan,
|
||||||
@@ -65,6 +67,22 @@ router.get('/supply/lots', verifyToken, async (req, res, next) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
router.post('/supply/lots/:id/inventory-adjustment', verifyToken, async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
res.json(await adjustInventoryLot(req.params.id, req.body || {}));
|
||||||
|
} catch (error) {
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
router.post('/supply/lots/:id/production-exit', verifyToken, async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
res.json(await consumeLotForProduction(req.params.id, req.body || {}));
|
||||||
|
} catch (error) {
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
router.get('/supply/movements', verifyToken, async (req, res, next) => {
|
router.get('/supply/movements', verifyToken, async (req, res, next) => {
|
||||||
try {
|
try {
|
||||||
res.json(await listMovements());
|
res.json(await listMovements());
|
||||||
|
|||||||
@@ -8,6 +8,12 @@ const normalizeNumber = (value) => {
|
|||||||
return Number.isFinite(number) && number > 0 ? number : null;
|
return Number.isFinite(number) && number > 0 ? number : null;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const normalizeNonNegativeNumber = (value) => {
|
||||||
|
if (value === '' || value === null || value === undefined) return null;
|
||||||
|
const number = Number(String(value).replace(',', '.'));
|
||||||
|
return Number.isFinite(number) && number >= 0 ? number : null;
|
||||||
|
};
|
||||||
|
|
||||||
const normalizeKey = (value) => normalizeText(value)
|
const normalizeKey = (value) => normalizeText(value)
|
||||||
.normalize('NFD')
|
.normalize('NFD')
|
||||||
.replace(/[\u0300-\u036f]/g, '')
|
.replace(/[\u0300-\u036f]/g, '')
|
||||||
@@ -377,8 +383,131 @@ const deleteFabricPlan = async (id) => {
|
|||||||
`, [id]);
|
`, [id]);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const updateLotQuantity = async (client, lotId, quantity) => {
|
||||||
|
const status = quantity > 0 ? 'active' : 'depleted';
|
||||||
|
const result = await client.query(`
|
||||||
|
UPDATE supply_stock_lots
|
||||||
|
SET quantity = $2,
|
||||||
|
status = $3,
|
||||||
|
updated_at = CURRENT_TIMESTAMP
|
||||||
|
WHERE id = $1
|
||||||
|
RETURNING id, receipt_id, category, product, quantity, unit, supplier, invoice, status, created_at, updated_at
|
||||||
|
`, [lotId, quantity, status]);
|
||||||
|
|
||||||
|
return mapLot(result.rows[0]);
|
||||||
|
};
|
||||||
|
|
||||||
|
const adjustInventoryLot = async (id, payload) => {
|
||||||
|
const countedQuantity = normalizeNonNegativeNumber(payload.countedQuantity);
|
||||||
|
const reason = normalizeText(payload.reason);
|
||||||
|
|
||||||
|
if (countedQuantity === null) throw createValidationError('Quantidade contada deve ser zero ou maior.');
|
||||||
|
if (!reason) throw createValidationError('Justificativa do ajuste é obrigatória.');
|
||||||
|
|
||||||
|
const client = await pool.connect();
|
||||||
|
|
||||||
|
try {
|
||||||
|
await client.query('BEGIN');
|
||||||
|
|
||||||
|
const lotResult = await client.query(`
|
||||||
|
SELECT id, receipt_id, category, product, quantity, unit, supplier, invoice, status, created_at, updated_at
|
||||||
|
FROM supply_stock_lots
|
||||||
|
WHERE id = $1
|
||||||
|
FOR UPDATE
|
||||||
|
`, [id]);
|
||||||
|
|
||||||
|
if (!lotResult.rowCount) throw createValidationError('Lote não encontrado.');
|
||||||
|
|
||||||
|
const lot = lotResult.rows[0];
|
||||||
|
const currentQuantity = Number(lot.quantity);
|
||||||
|
const difference = countedQuantity - currentQuantity;
|
||||||
|
const updatedLot = await updateLotQuantity(client, lot.id, countedQuantity);
|
||||||
|
|
||||||
|
await client.query(`
|
||||||
|
INSERT INTO supply_movements (
|
||||||
|
lot_id, type, category, product, quantity, unit, reason
|
||||||
|
)
|
||||||
|
VALUES ($1, 'inventory_adjustment', $2, $3, $4, $5, $6)
|
||||||
|
`, [
|
||||||
|
lot.id,
|
||||||
|
lot.category,
|
||||||
|
lot.product,
|
||||||
|
difference,
|
||||||
|
lot.unit,
|
||||||
|
`${reason} · sistema ${currentQuantity} ${lot.unit} · contado ${countedQuantity} ${lot.unit}`
|
||||||
|
]);
|
||||||
|
|
||||||
|
await client.query('COMMIT');
|
||||||
|
return updatedLot;
|
||||||
|
} catch (error) {
|
||||||
|
await client.query('ROLLBACK');
|
||||||
|
throw error;
|
||||||
|
} finally {
|
||||||
|
client.release();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const consumeLotForProduction = async (id, payload) => {
|
||||||
|
const quantity = normalizeNumber(payload.quantity);
|
||||||
|
const reason = normalizeText(payload.reason);
|
||||||
|
const productionOrderNumber = normalizeText(payload.productionOrderNumber);
|
||||||
|
|
||||||
|
if (!quantity) throw createValidationError('Quantidade de saída deve ser maior que zero.');
|
||||||
|
if (!productionOrderNumber && !reason) throw createValidationError('Informe a OP ou uma justificativa para a saída.');
|
||||||
|
|
||||||
|
const client = await pool.connect();
|
||||||
|
|
||||||
|
try {
|
||||||
|
await client.query('BEGIN');
|
||||||
|
|
||||||
|
const lotResult = await client.query(`
|
||||||
|
SELECT id, receipt_id, category, product, quantity, unit, supplier, invoice, status, created_at, updated_at
|
||||||
|
FROM supply_stock_lots
|
||||||
|
WHERE id = $1
|
||||||
|
FOR UPDATE
|
||||||
|
`, [id]);
|
||||||
|
|
||||||
|
if (!lotResult.rowCount) throw createValidationError('Lote não encontrado.');
|
||||||
|
|
||||||
|
const lot = lotResult.rows[0];
|
||||||
|
const currentQuantity = Number(lot.quantity);
|
||||||
|
if (lot.status !== 'active' || currentQuantity <= 0) throw createValidationError('Lote sem saldo disponível.');
|
||||||
|
if (quantity > currentQuantity) throw createValidationError('Quantidade de saída maior que o saldo do lote.');
|
||||||
|
|
||||||
|
const updatedLot = await updateLotQuantity(client, lot.id, currentQuantity - quantity);
|
||||||
|
const movementReason = [
|
||||||
|
productionOrderNumber ? `OP ${productionOrderNumber}` : '',
|
||||||
|
reason
|
||||||
|
].filter(Boolean).join(' · ');
|
||||||
|
|
||||||
|
await client.query(`
|
||||||
|
INSERT INTO supply_movements (
|
||||||
|
lot_id, type, category, product, quantity, unit, reason
|
||||||
|
)
|
||||||
|
VALUES ($1, 'production_exit', $2, $3, $4, $5, $6)
|
||||||
|
`, [
|
||||||
|
lot.id,
|
||||||
|
lot.category,
|
||||||
|
lot.product,
|
||||||
|
-quantity,
|
||||||
|
lot.unit,
|
||||||
|
movementReason || 'Saída para produção'
|
||||||
|
]);
|
||||||
|
|
||||||
|
await client.query('COMMIT');
|
||||||
|
return updatedLot;
|
||||||
|
} catch (error) {
|
||||||
|
await client.query('ROLLBACK');
|
||||||
|
throw error;
|
||||||
|
} finally {
|
||||||
|
client.release();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
|
adjustInventoryLot,
|
||||||
approveReceipt,
|
approveReceipt,
|
||||||
|
consumeLotForProduction,
|
||||||
createFabricPlan,
|
createFabricPlan,
|
||||||
createReceipt,
|
createReceipt,
|
||||||
deleteFabricPlan,
|
deleteFabricPlan,
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import type { AuthUser, CampaignPreview, CampaignProcessSummary, CampaignQueueSummary, CatalogCategory, CatalogCategoryPayload, CatalogProduct, CatalogProductPayload, CatalogSummary, ClientAnalyticsItem, ClientDetailsAnalytics, ClientFilterOptions, ClientMetadataFilters, ClientPurchasePatternAnalytics, ConsumptionReference, ConsumptionReferencePayload, CreateUserResult, CuttingSettings, DashboardAnalytics, DateRange, ManagedUser, OrderData, ProductAnalyticsItem, ProductDetailsAnalytics, ProductionOrderSummary, RfmAnalytics, StockData, SupplyFabricPlan, SupplyFabricPlanPayload, SupplyPurchaseNeed, SupplyReceipt, SupplyReceiptPayload, SupplySummary } from './types';
|
import type { AuthUser, CampaignPreview, CampaignProcessSummary, CampaignQueueSummary, CatalogCategory, CatalogCategoryPayload, CatalogProduct, CatalogProductPayload, CatalogSummary, ClientAnalyticsItem, ClientDetailsAnalytics, ClientFilterOptions, ClientMetadataFilters, ClientPurchasePatternAnalytics, ConsumptionReference, ConsumptionReferencePayload, CreateUserResult, CuttingSettings, DashboardAnalytics, DateRange, ManagedUser, OrderData, ProductAnalyticsItem, ProductDetailsAnalytics, ProductionOrderSummary, RfmAnalytics, StockData, SupplyFabricPlan, SupplyFabricPlanPayload, SupplyInventoryAdjustmentPayload, SupplyLot, SupplyProductionExitPayload, SupplyPurchaseNeed, SupplyReceipt, SupplyReceiptPayload, SupplySummary } from './types';
|
||||||
import { formatDateParam } from './dateRanges';
|
import { formatDateParam } from './dateRanges';
|
||||||
|
|
||||||
const API_URL = import.meta.env.VITE_API_URL || '/api';
|
const API_URL = import.meta.env.VITE_API_URL || '/api';
|
||||||
@@ -399,6 +399,36 @@ export const fetchSupplyPurchaseNeeds = async (): Promise<SupplyPurchaseNeed[]>
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const adjustSupplyLotInventory = async (lotId: number, payload: SupplyInventoryAdjustmentPayload): Promise<SupplyLot> => {
|
||||||
|
const response = await authFetch(`/supply/lots/${lotId}/inventory-adjustment`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(payload)
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = await response.json().catch(() => null);
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(data?.error || 'Não foi possível ajustar o inventário.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return data as SupplyLot;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const consumeSupplyLotForProduction = async (lotId: number, payload: SupplyProductionExitPayload): Promise<SupplyLot> => {
|
||||||
|
const response = await authFetch(`/supply/lots/${lotId}/production-exit`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(payload)
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = await response.json().catch(() => null);
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(data?.error || 'Não foi possível registrar a saída para produção.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return data as SupplyLot;
|
||||||
|
};
|
||||||
|
|
||||||
export const fetchDashboardAnalytics = async (dateRange: DateRange, options?: CacheOptions): Promise<DashboardAnalytics | null> => {
|
export const fetchDashboardAnalytics = async (dateRange: DateRange, options?: CacheOptions): Promise<DashboardAnalytics | null> => {
|
||||||
const path = `/analytics/dashboard?${buildDateRangeParams(dateRange).toString()}`;
|
const path = `/analytics/dashboard?${buildDateRangeParams(dateRange).toString()}`;
|
||||||
return getCachedAnalytics(path, async () => {
|
return getCachedAnalytics(path, async () => {
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
import { type FormEvent, useCallback, useEffect, useMemo, useState } from 'react';
|
||||||
import { Link, useOutletContext } from 'react-router-dom';
|
import { Link, useOutletContext } from 'react-router-dom';
|
||||||
import { ArrowLeft, CalendarDays, CheckCircle2, ClipboardList, Clock3, Download, PackageCheck, Search } from 'lucide-react';
|
import { ArrowLeft, CalendarDays, CheckCircle2, ClipboardList, Clock3, Download, PackageCheck, 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 { exportToCSV, fetchProductionOrders } from '../dataService';
|
import { consumeSupplyLotForProduction, exportToCSV, fetchProductionOrders, fetchSupplySummary } from '../dataService';
|
||||||
import type { DateRange, ProductionOrderItem, ProductionOrderStatus, ProductionOrderSummary } from '../types';
|
import type { DateRange, ProductionOrderItem, ProductionOrderStatus, ProductionOrderSummary, SupplyLot } from '../types';
|
||||||
|
|
||||||
type ProductionOrderStatusTab = 'all' | 'open' | 'in_progress' | 'finished' | 'canceled';
|
type ProductionOrderStatusTab = 'all' | 'open' | 'in_progress' | 'finished' | 'canceled';
|
||||||
|
|
||||||
@@ -117,9 +117,18 @@ const ProductionOrders = () => {
|
|||||||
const [searchTerm, setSearchTerm] = useState('');
|
const [searchTerm, setSearchTerm] = useState('');
|
||||||
const [statusFilter, setStatusFilter] = useState<ProductionOrderStatusTab>('all');
|
const [statusFilter, setStatusFilter] = useState<ProductionOrderStatusTab>('all');
|
||||||
const [summary, setSummary] = useState<ProductionOrderSummary>(emptySummary);
|
const [summary, setSummary] = useState<ProductionOrderSummary>(emptySummary);
|
||||||
|
const [supplyLots, setSupplyLots] = useState<SupplyLot[]>([]);
|
||||||
const [isLoading, setIsLoading] = useState(true);
|
const [isLoading, setIsLoading] = useState(true);
|
||||||
|
const [isSupplyBusy, setIsSupplyBusy] = useState(false);
|
||||||
|
const [supplyMessage, setSupplyMessage] = useState('');
|
||||||
const [currentPage, setCurrentPage] = useState(1);
|
const [currentPage, setCurrentPage] = useState(1);
|
||||||
const [itemsPerPage, setItemsPerPage] = useState(20);
|
const [itemsPerPage, setItemsPerPage] = useState(20);
|
||||||
|
const [exitForm, setExitForm] = useState({
|
||||||
|
orderId: '',
|
||||||
|
lotId: '',
|
||||||
|
quantity: '',
|
||||||
|
reason: '',
|
||||||
|
});
|
||||||
|
|
||||||
const loadProductionOrders = useCallback(async (options?: { force?: boolean }) => {
|
const loadProductionOrders = useCallback(async (options?: { force?: boolean }) => {
|
||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
@@ -133,9 +142,13 @@ const ProductionOrders = () => {
|
|||||||
|
|
||||||
const load = async () => {
|
const load = async () => {
|
||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
const nextSummary = await fetchProductionOrders(dateRange, { search: searchTerm });
|
const [nextSummary, nextSupplySummary] = await Promise.all([
|
||||||
|
fetchProductionOrders(dateRange, { search: searchTerm }),
|
||||||
|
fetchSupplySummary()
|
||||||
|
]);
|
||||||
if (isMounted) {
|
if (isMounted) {
|
||||||
setSummary(nextSummary);
|
setSummary(nextSummary);
|
||||||
|
setSupplyLots(nextSupplySummary.lots);
|
||||||
setIsLoading(false);
|
setIsLoading(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -177,6 +190,38 @@ const ProductionOrders = () => {
|
|||||||
void loadProductionOrders({ force: true });
|
void loadProductionOrders({ force: true });
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const refreshSupplyLots = async () => {
|
||||||
|
const supplySummary = await fetchSupplySummary();
|
||||||
|
setSupplyLots(supplySummary.lots);
|
||||||
|
};
|
||||||
|
|
||||||
|
const selectedOrder = summary.orders.find(order => `${order.id}` === exitForm.orderId);
|
||||||
|
const selectedLot = supplyLots.find(lot => `${lot.id}` === exitForm.lotId);
|
||||||
|
|
||||||
|
const handleProductionExit = async (event: FormEvent<HTMLFormElement>) => {
|
||||||
|
event.preventDefault();
|
||||||
|
const lotId = Number(exitForm.lotId);
|
||||||
|
const quantity = Number(exitForm.quantity.replace(',', '.'));
|
||||||
|
if (!lotId || !selectedOrder || !Number.isFinite(quantity) || quantity <= 0) return;
|
||||||
|
|
||||||
|
setIsSupplyBusy(true);
|
||||||
|
setSupplyMessage('');
|
||||||
|
try {
|
||||||
|
await consumeSupplyLotForProduction(lotId, {
|
||||||
|
quantity,
|
||||||
|
productionOrderNumber: selectedOrder.number || `${selectedOrder.id}`,
|
||||||
|
reason: exitForm.reason.trim() || selectedOrder.productDescription,
|
||||||
|
});
|
||||||
|
await refreshSupplyLots();
|
||||||
|
setExitForm({ orderId: '', lotId: '', quantity: '', reason: '' });
|
||||||
|
setSupplyMessage('Saída de material registrada no estoque.');
|
||||||
|
} catch (error) {
|
||||||
|
setSupplyMessage(error instanceof Error ? error.message : 'Não foi possível baixar o material.');
|
||||||
|
} finally {
|
||||||
|
setIsSupplyBusy(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const handleExport = () => {
|
const handleExport = () => {
|
||||||
const exportData = filteredOrders.map(order => ({
|
const exportData = filteredOrders.map(order => ({
|
||||||
'Numero': order.number,
|
'Numero': order.number,
|
||||||
@@ -274,6 +319,84 @@ const ProductionOrders = () => {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<form onSubmit={handleProductionExit} className="rounded-2xl border border-dark-border bg-dark-card p-5 shadow-sm">
|
||||||
|
<div className="flex flex-col gap-2 lg:flex-row lg:items-start lg:justify-between">
|
||||||
|
<div>
|
||||||
|
<h2 className="text-base font-bold text-dark-text">Baixa de material da OP</h2>
|
||||||
|
<p className="mt-1 text-sm font-semibold text-dark-muted">Consome um lote do estoque e registra a saída nas movimentações.</p>
|
||||||
|
</div>
|
||||||
|
{selectedLot && (
|
||||||
|
<span className="w-fit rounded-full border border-dark-border bg-dark-input px-2.5 py-1 text-xs font-bold text-dark-muted">
|
||||||
|
Saldo lote #{selectedLot.id}: {formatQuantity(selectedLot.quantity)} {selectedLot.unit}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="mt-4 grid grid-cols-1 gap-3 xl:grid-cols-[1.4fr_1.4fr_120px_1fr_auto]">
|
||||||
|
<label className="text-xs font-bold text-dark-muted">
|
||||||
|
Ordem de produção
|
||||||
|
<select
|
||||||
|
value={exitForm.orderId}
|
||||||
|
onChange={(event) => setExitForm(current => ({ ...current, orderId: event.target.value }))}
|
||||||
|
className="mt-1 h-10 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>
|
||||||
|
{summary.orders.filter(order => order.status !== 'finished' && order.status !== 'canceled').map(order => (
|
||||||
|
<option key={order.id} value={order.id}>
|
||||||
|
{order.number || `#${order.id}`} · {order.productDescription}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<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 h-10 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 h-10 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="text-xs font-bold text-dark-muted">
|
||||||
|
Motivo
|
||||||
|
<input
|
||||||
|
value={exitForm.reason}
|
||||||
|
onChange={(event) => setExitForm(current => ({ ...current, reason: event.target.value }))}
|
||||||
|
className="mt-1 h-10 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>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={isSupplyBusy || !supplyLots.length}
|
||||||
|
className="mt-5 inline-flex h-10 items-center justify-center gap-2 rounded-lg border border-dark-border bg-dark-input px-3 text-sm font-bold text-dark-text transition-colors hover:border-brand-primary disabled:cursor-not-allowed disabled:opacity-50"
|
||||||
|
>
|
||||||
|
<PackageCheck className="h-4 w-4 text-brand-primary" />
|
||||||
|
Baixar
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
{supplyMessage && (
|
||||||
|
<div className="mt-3 rounded-lg border border-dark-border bg-dark-input px-3 py-2 text-sm font-bold text-dark-muted">
|
||||||
|
{supplyMessage}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</form>
|
||||||
|
|
||||||
<div className="overflow-hidden rounded-2xl border border-dark-border bg-dark-card shadow-sm">
|
<div className="overflow-hidden rounded-2xl border border-dark-border bg-dark-card shadow-sm">
|
||||||
<div className="border-b border-dark-border p-5">
|
<div className="border-b border-dark-border p-5">
|
||||||
<div className="flex flex-col gap-4 xl:flex-row xl:items-center xl:justify-between">
|
<div className="flex flex-col gap-4 xl:flex-row xl:items-center xl:justify-between">
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ import {
|
|||||||
Trash2,
|
Trash2,
|
||||||
Warehouse,
|
Warehouse,
|
||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
import { approveSupplyReceipt, createSupplyFabricPlan, createSupplyReceipt, deleteSupplyFabricPlan, deleteSupplyReceipt, fetchSupplySummary } from '../dataService';
|
import { adjustSupplyLotInventory, approveSupplyReceipt, consumeSupplyLotForProduction, createSupplyFabricPlan, createSupplyReceipt, deleteSupplyFabricPlan, deleteSupplyReceipt, fetchSupplySummary } from '../dataService';
|
||||||
import type { SupplyFabricPlan, SupplyLot, SupplyMovement, SupplyPurchaseNeed, SupplyReceipt, SupplySummary } from '../types';
|
import type { SupplyFabricPlan, SupplyLot, SupplyMovement, SupplyPurchaseNeed, SupplyReceipt, SupplySummary } from '../types';
|
||||||
|
|
||||||
type InventoryTab = 'dashboard' | 'balance' | 'receipts' | 'inventory' | 'movements';
|
type InventoryTab = 'dashboard' | 'balance' | 'receipts' | 'inventory' | 'movements';
|
||||||
@@ -547,13 +547,33 @@ const ReceiptsTab = ({
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
const InventoryCountTab = ({ lots, onRefresh }: { lots: SupplyLot[]; onRefresh: () => void }) => {
|
const InventoryCountTab = ({
|
||||||
|
lots,
|
||||||
|
onAdjust,
|
||||||
|
onRefresh,
|
||||||
|
}: {
|
||||||
|
lots: SupplyLot[];
|
||||||
|
onAdjust: (lotId: number, countedQuantity: number, reason: string) => Promise<void>;
|
||||||
|
onRefresh: () => void;
|
||||||
|
}) => {
|
||||||
const [search, setSearch] = useState('');
|
const [search, setSearch] = useState('');
|
||||||
|
const [adjustments, setAdjustments] = useState<Record<number, { countedQuantity: string; reason: string }>>({});
|
||||||
const normalizedSearch = normalizeSearch(search);
|
const normalizedSearch = normalizeSearch(search);
|
||||||
const visibleLots = lots.filter(lot => (
|
const visibleLots = lots.filter(lot => (
|
||||||
!normalizedSearch || normalizeSearch(`${lot.product} ${lot.category} ${lot.supplier} ${lot.invoice} ${lot.id}`).includes(normalizedSearch)
|
!normalizedSearch || normalizeSearch(`${lot.product} ${lot.category} ${lot.supplier} ${lot.invoice} ${lot.id}`).includes(normalizedSearch)
|
||||||
));
|
));
|
||||||
|
|
||||||
|
const updateAdjustment = (lotId: number, patch: Partial<{ countedQuantity: string; reason: string }>) => {
|
||||||
|
setAdjustments(current => ({
|
||||||
|
...current,
|
||||||
|
[lotId]: {
|
||||||
|
countedQuantity: current[lotId]?.countedQuantity ?? '',
|
||||||
|
reason: current[lotId]?.reason ?? '',
|
||||||
|
...patch,
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<button
|
<button
|
||||||
@@ -587,6 +607,42 @@ const InventoryCountTab = ({ lots, onRefresh }: { lots: SupplyLot[]; onRefresh:
|
|||||||
<p className="mt-1 text-xs font-semibold text-dark-muted">{lot.category} · lote #{lot.id}</p>
|
<p className="mt-1 text-xs font-semibold text-dark-muted">{lot.category} · lote #{lot.id}</p>
|
||||||
<p className="mt-3 text-xl font-bold text-dark-text">{formatNumber(lot.quantity)} {lot.unit}</p>
|
<p className="mt-3 text-xl font-bold text-dark-text">{formatNumber(lot.quantity)} {lot.unit}</p>
|
||||||
<p className="mt-1 text-xs font-semibold text-dark-muted">{lot.supplier || 'Sem fornecedor'}</p>
|
<p className="mt-1 text-xs font-semibold text-dark-muted">{lot.supplier || 'Sem fornecedor'}</p>
|
||||||
|
<div className="mt-4 grid grid-cols-1 gap-2">
|
||||||
|
<label className="text-xs font-bold text-dark-muted">
|
||||||
|
Quantidade contada
|
||||||
|
<input
|
||||||
|
inputMode="decimal"
|
||||||
|
value={adjustments[lot.id]?.countedQuantity ?? ''}
|
||||||
|
onChange={(event) => updateAdjustment(lot.id, { countedQuantity: event.target.value })}
|
||||||
|
className={`${inputClassName} mt-1`}
|
||||||
|
placeholder={`${formatNumber(lot.quantity)} ${lot.unit}`}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label className="text-xs font-bold text-dark-muted">
|
||||||
|
Justificativa
|
||||||
|
<input
|
||||||
|
value={adjustments[lot.id]?.reason ?? ''}
|
||||||
|
onChange={(event) => updateAdjustment(lot.id, { reason: event.target.value })}
|
||||||
|
className={`${inputClassName} mt-1`}
|
||||||
|
placeholder="ex: contagem física"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={async () => {
|
||||||
|
const rawQuantity = adjustments[lot.id]?.countedQuantity ?? '';
|
||||||
|
if (!rawQuantity.trim()) return;
|
||||||
|
const nextQuantity = parseDecimal(rawQuantity);
|
||||||
|
const reason = adjustments[lot.id]?.reason.trim() ?? '';
|
||||||
|
await onAdjust(lot.id, nextQuantity, reason);
|
||||||
|
setAdjustments(current => ({ ...current, [lot.id]: { countedQuantity: '', reason: '' } }));
|
||||||
|
}}
|
||||||
|
className={buttonClassName}
|
||||||
|
>
|
||||||
|
<ClipboardCheck className="h-4 w-4" />
|
||||||
|
Ajustar lote
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
@@ -604,10 +660,91 @@ const InventoryCountTab = ({ lots, onRefresh }: { lots: SupplyLot[]; onRefresh:
|
|||||||
const movementLabels: Record<string, string> = {
|
const movementLabels: Record<string, string> = {
|
||||||
receipt: 'Entrada por recebimento',
|
receipt: 'Entrada por recebimento',
|
||||||
inventory_adjustment: 'Ajuste de inventário',
|
inventory_adjustment: 'Ajuste de inventário',
|
||||||
|
production_exit: 'Saída para produção',
|
||||||
reversal: 'Estorno',
|
reversal: 'Estorno',
|
||||||
};
|
};
|
||||||
|
|
||||||
const MovementsTab = ({ movements }: { movements: SupplyMovement[] }) => {
|
const ProductionExitPanel = ({
|
||||||
|
lots,
|
||||||
|
onConsume,
|
||||||
|
}: {
|
||||||
|
lots: SupplyLot[];
|
||||||
|
onConsume: (lotId: number, quantity: number, productionOrderNumber: string, reason: string) => Promise<void>;
|
||||||
|
}) => {
|
||||||
|
const [form, setForm] = useState({
|
||||||
|
lotId: '',
|
||||||
|
quantity: '',
|
||||||
|
productionOrderNumber: '',
|
||||||
|
reason: '',
|
||||||
|
});
|
||||||
|
|
||||||
|
const selectedLot = lots.find(lot => `${lot.id}` === form.lotId);
|
||||||
|
|
||||||
|
const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
|
||||||
|
event.preventDefault();
|
||||||
|
const lotId = Number(form.lotId);
|
||||||
|
const quantity = parseDecimal(form.quantity);
|
||||||
|
if (!lotId || quantity <= 0) return;
|
||||||
|
|
||||||
|
await onConsume(lotId, quantity, form.productionOrderNumber.trim(), form.reason.trim());
|
||||||
|
setForm({ lotId: '', quantity: '', productionOrderNumber: '', reason: '' });
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<form onSubmit={handleSubmit} className={`${panelClassName} p-5`}>
|
||||||
|
<div className="flex flex-col gap-2 md:flex-row md:items-start md:justify-between">
|
||||||
|
<div>
|
||||||
|
<h2 className="text-base font-bold text-dark-text">Saída para produção</h2>
|
||||||
|
<p className="mt-1 text-sm font-semibold text-dark-muted">Baixa material de um lote e registra movimentação ligada à OP.</p>
|
||||||
|
</div>
|
||||||
|
{selectedLot && (
|
||||||
|
<span className="w-fit rounded-full border border-dark-border bg-dark-input px-2.5 py-1 text-xs font-bold text-dark-muted">
|
||||||
|
Saldo: {formatNumber(selectedLot.quantity)} {selectedLot.unit}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="mt-4 grid grid-cols-1 gap-3 lg:grid-cols-[1.4fr_120px_160px_1fr_auto]">
|
||||||
|
<label className="text-xs font-bold text-dark-muted">
|
||||||
|
Lote
|
||||||
|
<select value={form.lotId} onChange={(event) => setForm(current => ({ ...current, lotId: event.target.value }))} className={`${inputClassName} mt-1`}>
|
||||||
|
<option value="">Selecione...</option>
|
||||||
|
{lots.map(lot => (
|
||||||
|
<option key={lot.id} value={lot.id}>
|
||||||
|
#{lot.id} · {lot.product} · {formatNumber(lot.quantity)} {lot.unit}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label className="text-xs font-bold text-dark-muted">
|
||||||
|
Quantidade
|
||||||
|
<input inputMode="decimal" value={form.quantity} onChange={(event) => setForm(current => ({ ...current, quantity: event.target.value }))} className={`${inputClassName} mt-1`} placeholder="kg" />
|
||||||
|
</label>
|
||||||
|
<label className="text-xs font-bold text-dark-muted">
|
||||||
|
OP
|
||||||
|
<input value={form.productionOrderNumber} onChange={(event) => setForm(current => ({ ...current, productionOrderNumber: event.target.value }))} className={`${inputClassName} mt-1`} placeholder="ex: OP-123" />
|
||||||
|
</label>
|
||||||
|
<label className="text-xs font-bold text-dark-muted">
|
||||||
|
Motivo
|
||||||
|
<input value={form.reason} onChange={(event) => setForm(current => ({ ...current, reason: event.target.value }))} className={`${inputClassName} mt-1`} placeholder="ex: corte BLCS" />
|
||||||
|
</label>
|
||||||
|
<button type="submit" className={`${buttonClassName} mt-5`}>
|
||||||
|
<Repeat2 className="h-4 w-4" />
|
||||||
|
Baixar
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const MovementsTab = ({
|
||||||
|
lots,
|
||||||
|
movements,
|
||||||
|
onConsume,
|
||||||
|
}: {
|
||||||
|
lots: SupplyLot[];
|
||||||
|
movements: SupplyMovement[];
|
||||||
|
onConsume: (lotId: number, quantity: number, productionOrderNumber: string, reason: string) => Promise<void>;
|
||||||
|
}) => {
|
||||||
const [search, setSearch] = useState('');
|
const [search, setSearch] = useState('');
|
||||||
const [type, setType] = useState('all');
|
const [type, setType] = useState('all');
|
||||||
const movementTypes = Array.from(new Set(movements.map(movement => movement.type))).sort();
|
const movementTypes = Array.from(new Set(movements.map(movement => movement.type))).sort();
|
||||||
@@ -620,6 +757,7 @@ const MovementsTab = ({ movements }: { movements: SupplyMovement[] }) => {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
|
<ProductionExitPanel lots={lots} onConsume={onConsume} />
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => exportCsv('movimentacoes-suprimentos.csv', visibleMovements.map(movement => ({
|
onClick={() => exportCsv('movimentacoes-suprimentos.csv', visibleMovements.map(movement => ({
|
||||||
@@ -771,8 +909,24 @@ const InventoryScreen = () => {
|
|||||||
})}
|
})}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
{activeTab === 'inventory' && <InventoryCountTab lots={summary.lots} onRefresh={loadSummary} />}
|
{activeTab === 'inventory' && (
|
||||||
{activeTab === 'movements' && <MovementsTab movements={summary.movements} />}
|
<InventoryCountTab
|
||||||
|
lots={summary.lots}
|
||||||
|
onRefresh={loadSummary}
|
||||||
|
onAdjust={(lotId, countedQuantity, reason) => runSupplyAction(async () => {
|
||||||
|
await adjustSupplyLotInventory(lotId, { countedQuantity, reason });
|
||||||
|
})}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{activeTab === 'movements' && (
|
||||||
|
<MovementsTab
|
||||||
|
lots={summary.lots}
|
||||||
|
movements={summary.movements}
|
||||||
|
onConsume={(lotId, quantity, productionOrderNumber, reason) => runSupplyAction(async () => {
|
||||||
|
await consumeSupplyLotForProduction(lotId, { quantity, productionOrderNumber, reason });
|
||||||
|
})}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
11
src/types.ts
11
src/types.ts
@@ -270,6 +270,17 @@ export type SupplyFabricPlanPayload = {
|
|||||||
priority?: string;
|
priority?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export type SupplyInventoryAdjustmentPayload = {
|
||||||
|
countedQuantity: number | string;
|
||||||
|
reason: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type SupplyProductionExitPayload = {
|
||||||
|
quantity: number | string;
|
||||||
|
productionOrderNumber?: string;
|
||||||
|
reason?: string;
|
||||||
|
};
|
||||||
|
|
||||||
export interface DateRange {
|
export interface DateRange {
|
||||||
start: Date;
|
start: Date;
|
||||||
end: Date;
|
end: Date;
|
||||||
|
|||||||
Reference in New Issue
Block a user