import React, { useState } from 'react'; import { useCRM } from '../context/CRMContext'; import { Search, ShoppingCart, Trash2, Plus, Minus, CreditCard, ChevronRight, Calculator, Package, AlertTriangle, Download, History, Store, CheckSquare, Square, UserPlus, Pencil, X, Banknote, CreditCard as CardIcon } from 'lucide-react'; import { InventoryItem, Sale, SalesChannel, Customer, PaymentMethod } from '../types'; import clsx from 'clsx'; const Sales: React.FC = () => { const { inventory, customers, registerSale, sales, importSales, updateSale, loading, addCustomer, updateProduct, isAdmin } = useCRM(); // State const [viewMode, setViewMode] = useState<'list' | 'pos'>('list'); // 'list' = Pedidos, 'pos' = Frente de Caixa // POS State const [searchTerm, setSearchTerm] = useState(''); const [cart, setCart] = useState<{ item: InventoryItem; quantity: number; price: number }[]>([]); const [selectedCustomer, setSelectedCustomer] = useState(''); const [paymentMethod, setPaymentMethod] = useState('Cash'); // New state const [isFinalizing, setIsFinalizing] = useState(false); // Import Modal State const [showImportModal, setShowImportModal] = useState(false); const [importChannel, setImportChannel] = useState('Mercado Livre'); // Quick Customer Modal const [showCustomerModal, setShowCustomerModal] = useState(false); const [newCustomer, setNewCustomer] = useState({ name: '', email: '', phone: '' }); // Quick Edit Product Modal const [editingProduct, setEditingProduct] = useState(null); const [editForm, setEditForm] = useState({ price: 0, stock: 0 }); // Filter Inventory const filteredInventory = inventory.filter(i => i.name.toLowerCase().includes(searchTerm.toLowerCase()) || i.sku.toLowerCase().includes(searchTerm.toLowerCase()) ); // Cart Actions const addToCart = (item: InventoryItem) => { const existing = cart.find(c => c.item.id === item.id); if (existing) { if (existing.quantity >= item.quantity) return; // Max stock reached setCart(cart.map(c => c.item.id === item.id ? { ...c, quantity: c.quantity + 1 } : c)); } else { if (item.quantity <= 0) return; setCart([...cart, { item, quantity: 1, price: Number(item.marketPriceBRL) || 0 }]); } }; const updateQuantity = (id: string, delta: number) => { setCart(cart.map(c => { if (c.item.id === id) { const newQty = c.quantity + delta; if (newQty <= 0) return c; // Don't remove here, need explicit remove if (newQty > c.item.quantity) return c; return { ...c, quantity: newQty }; } return c; })); }; const removeFromCart = (id: string) => { setCart(cart.filter(c => c.item.id !== id)); }; const updatePrice = (id: string, newPrice: number) => { setCart(cart.map(c => c.item.id === id ? { ...c, price: newPrice } : c)); }; // Totals const totalAmount = cart.reduce((acc, c) => acc + (c.price * c.quantity), 0); const totalItems = cart.reduce((acc, c) => acc + c.quantity, 0); const [showSuccessModal, setShowSuccessModal] = useState(false); const [lastSaleTotal, setLastSaleTotal] = useState(0); const handleFinalize = async () => { if (cart.length === 0) return; setIsFinalizing(true); const saleTotal = cart.reduce((acc, c) => acc + (c.price * c.quantity), 0); setLastSaleTotal(saleTotal); await registerSale( cart.map(c => ({ id: c.item.id, quantity: c.quantity, salePrice: c.price })), selectedCustomer || undefined, paymentMethod // Pass new arg ); setCart([]); setSelectedCustomer(''); setPaymentMethod('Cash'); // Reset setIsFinalizing(false); setShowSuccessModal(true); }; const handleNewSale = () => { setShowSuccessModal(false); }; const handlePrintReceipt = () => { alert("Impressão de Recibo iniciada... (Mock)"); // window.print(); }; const handleSendEmail = () => { const email = customers.find(c => c.id === selectedCustomer)?.email || "cliente@exemplo.com"; alert(`Comprovante enviado para ${email} (Mock)`); }; // --- IMPORT HANDLERS --- const handleImport = async () => { await importSales(importChannel); setShowImportModal(false); }; // --- QUICK ACTIONS --- const handleSaveCustomer = async () => { if (!newCustomer.name) return alert("Nome é obrigatório"); try { const created = await addCustomer({ ...newCustomer, status: 'Active', city: 'Foz do Iguaçu' } as any); if (created) { setNewCustomer({ name: '', email: '', phone: '' }); setShowCustomerModal(false); setSelectedCustomer(created.id); // Auto-select } } catch (error) { console.error(error); alert("Erro ao cadastrar cliente. Verifique o console."); } }; const handleSaveProductEdit = async () => { if (!editingProduct) return; await updateProduct(editingProduct.id, { marketPriceBRL: editForm.price, quantity: editForm.stock }); setEditingProduct(null); }; // --- UI RENDERERS --- // 1. SALES LIST VIEW const renderSalesList = () => (

Histórico de Pedidos

Gerencie vendas locais e importadas.

{sales.map(sale => ( ))}
Data / ID Canal Cliente Total Status Baixar Estoque Lançar Financeiro
{new Date(sale.date).toLocaleDateString()}
#{sale.externalId || sale.id.substring(0, 8)}
{sale.channel === 'Mercado Livre' && MeLi} {sale.channel === 'Shopee' && Shopee} {sale.channel === 'Amazon' && Amazon} {sale.channel === 'Local' && Balcão}
{sale.customerName || 'Cliente Consumidor'} R$ {sale.total.toLocaleString('pt-BR', { minimumFractionDigits: 2 })} {sale.status}
{sales.length === 0 && (

Nenhuma venda registrada

)}
{/* IMPORT MODAL */} {showImportModal && (

Importar Pedidos

Simularemos a conexão com a API do {importChannel} para buscar novos pedidos pendentes.
)}
); return (
{viewMode === 'list' ? renderSalesList() : (
{/* LEFT: POS / INVENTORY */}
{/* ... Search Bar and Grid kept as children ... */} {/* RE-INSERTING ORIGINAL POS CONTENT WRAPPED IN FRAGMENT OR DIV IF NEEDED */} {/* Search Bar */}
setSearchTerm(e.target.value)} placeholder="Buscar produto por nome ou SKU..." className="w-full bg-slate-900/50 border border-white/10 rounded-2xl py-4 pl-12 pr-4 text-white focus:border-indigo-500 outline-none transition-all placeholder:text-slate-600" />
{/* Grid */}
{filteredInventory.map(item => (
addToCart(item)} className={clsx( "p-5 rounded-[24px] border transition-all cursor-pointer group relative overflow-hidden", item.quantity === 0 ? "opacity-50 grayscale border-white/5 bg-white/5 cursor-not-allowed" : "bg-white/5 border-white/5 hover:border-indigo-500/50 hover:bg-white/10 active:scale-95" )} >
{item.sku} {item.quantity <= 3 && item.quantity > 0 && (
Baixo Estoque
)} {isAdmin && ( )}

{item.name}

Preço Venda

R$ {(Number(item.marketPriceBRL) || 0).toLocaleString('pt-BR')}

Estoque

{item.quantity}

))}
{/* RIGHT: CART / CHECKOUT */}
{/* Header */}

Carrinho

Nova Venda

{totalItems} itens
{/* Customer Select (Optional) */}
{/* Cart Items */}
{cart.length === 0 ? (

Carrinho Vazio

) : ( cart.map((c, idx) => (

{c.item.name}

{c.quantity}
R$ updatePrice(c.item.id, parseFloat(e.target.value))} className="w-full bg-black/30 border border-white/10 rounded-lg py-1.5 pl-8 pr-2 text-right text-xs font-bold text-white focus:border-indigo-500 outline-none" />
Subtotal: R$ {(c.price * c.quantity).toLocaleString('pt-BR')}
)) )}
{/* Summary & Action */}
Itens {totalItems} UN
Total Geral R$ {totalAmount.toLocaleString('pt-BR')}
{/* Payment Method Selector */}

Forma de Pagamento

{['Cash', 'Pix', 'Credit Card'].map(method => ( ))}
)} {/* SUCCESS MODAL */} {showSuccessModal && (
{/* Confetti or success decoration could go here */}

Venda Realizada!

Total processado com sucesso.

R$ {lastSaleTotal.toLocaleString('pt-BR')}
)}
); }; export default Sales;