import React, { useState } from 'react'; import { Book, Plus, Trash2, CheckCircle, XCircle, DollarSign, Package, Users, ChevronRight, Search, AlertCircle, Save, X, RefreshCw, Edit } from 'lucide-react'; import { SchoolData, Handout, HandoutDelivery, Class, Student } from '../types'; import { dbService } from '../services/dbService'; import { useDialog } from '../DialogContext'; import { supabase, isSupabaseConfigured } from '../services/supabase'; interface HandoutsProps { data: SchoolData; updateData: (newData: Partial) => void; } const Handouts: React.FC = ({ data, updateData }) => { const { showAlert, showConfirm } = useDialog(); const [showAddHandout, setShowAddHandout] = useState(false); const [isClosing, setIsClosing] = useState(false); const [selectedClass, setSelectedClass] = useState(null); const [selectedStudent, setSelectedStudent] = useState(null); const [searchTerm, setSearchTerm] = useState(''); const [activeTab, setActiveTab] = useState<'classes' | 'individual'>('classes'); const [isSyncing, setIsSyncing] = useState(false); const [editingHandoutId, setEditingHandoutId] = useState(null); const closeModal = () => { setIsClosing(true); setTimeout(() => { setShowAddHandout(false); setSelectedClass(null); setSelectedStudent(null); setIsClosing(false); setEditingHandoutId(null); setNewHandout({ name: '', price: 0 }); }, 400); }; // Sync Asaas payments on mount React.useEffect(() => { syncAsaasPayments(); }, []); // Auto-sync handout payment status with Finance payments React.useEffect(() => { if (!data.payments || !data.handoutDeliveries) return; const currentDeliveries = data.handoutDeliveries; const currentPayments = data.payments; const currentHandouts = data.handouts || []; const updatedDeliveries = currentDeliveries.map(delivery => { if (delivery.paymentStatus === 'pending') { const handout = currentHandouts.find(h => h.id === delivery.handoutId); const isPaidInFinance = currentPayments.some(p => p.studentId === delivery.studentId && p.status === 'paid' && ( (delivery.asaasPaymentId && p.asaasPaymentId === delivery.asaasPaymentId) || (handout && p.description && p.description.includes(handout.name)) ) ); if (isPaidInFinance) { return { ...delivery, paymentStatus: 'paid' as const, paymentDate: delivery.paymentDate || new Date().toISOString() }; } } return delivery; }); const hasChanges = updatedDeliveries.some((d, i) => d.paymentStatus !== currentDeliveries[i].paymentStatus); if (hasChanges) { updateData({ handoutDeliveries: updatedDeliveries }); dbService.saveData({ ...data, handoutDeliveries: updatedDeliveries }); } }, [data.payments, data.handoutDeliveries, data.handouts, updateData, data]); // Sincronização automática removida conforme pedido const syncAsaasPayments = () => { // Função desativada para manter compatibilidade com render e evitar erros de referência }; // Form state for new handout const [newHandout, setNewHandout] = useState>({ name: '', price: 0, description: '', finePercentage: 0, interestPercentage: 0 }); const handouts = data.handouts || []; const deliveries = data.handoutDeliveries || []; const classes = data.classes || []; const students = data.students || []; const handleAddHandout = () => { if (!newHandout.name || newHandout.price === undefined) { showAlert('Erro', 'Por favor, preencha o nome e o preço da apostila.', 'error'); return; } let updatedHandouts: Handout[]; if (editingHandoutId) { updatedHandouts = handouts.map(h => h.id === editingHandoutId ? { ...h, name: newHandout.name!, price: newHandout.price!, description: newHandout.description, finePercentage: newHandout.finePercentage || 0, interestPercentage: newHandout.interestPercentage || 0 } : h ); showAlert('Sucesso', 'Apostila atualizada com sucesso!', 'success'); } else { const handout: Handout = { id: crypto.randomUUID(), name: newHandout.name, price: newHandout.price, description: newHandout.description, finePercentage: newHandout.finePercentage || 0, interestPercentage: newHandout.interestPercentage || 0 }; updatedHandouts = [...handouts, handout]; showAlert('Sucesso', 'Apostila adicionada com sucesso!', 'success'); } updateData({ handouts: updatedHandouts }); dbService.saveData({ ...data, handouts: updatedHandouts }); setNewHandout({ name: '', price: 0, description: '', finePercentage: 0, interestPercentage: 0 }); setShowAddHandout(false); setEditingHandoutId(null); }; const handleEditHandout = (handout: Handout) => { setNewHandout({ name: handout.name, price: handout.price, description: handout.description || '', finePercentage: handout.finePercentage || 0, interestPercentage: handout.interestPercentage || 0 }); setEditingHandoutId(handout.id); setShowAddHandout(true); }; const handleDeleteHandout = (id: string) => { showConfirm( 'Excluir Apostila', 'Tem certeza que deseja excluir esta apostila? Isso removerá todos os registros de entrega vinculados.', () => { const updatedHandouts = handouts.filter(h => h.id !== id); const updatedDeliveries = deliveries.filter(d => d.handoutId !== id); updateData({ handouts: updatedHandouts, handoutDeliveries: updatedDeliveries }); dbService.saveData({ ...data, handouts: updatedHandouts, handoutDeliveries: updatedDeliveries }); } ); }; const toggleDeliveryStatus = (studentId: string, handoutId: string) => { const existing = deliveries.find(d => d.studentId === studentId && d.handoutId === handoutId); let updatedDeliveries: HandoutDelivery[]; if (existing) { updatedDeliveries = deliveries.map(d => (d.studentId === studentId && d.handoutId === handoutId) ? { ...d, deliveryStatus: d.deliveryStatus === 'delivered' ? 'pending' : 'delivered', deliveryDate: d.deliveryStatus === 'delivered' ? undefined : new Date().toISOString() } : d ); } else { updatedDeliveries = [ ...deliveries, { id: crypto.randomUUID(), studentId, handoutId, deliveryStatus: 'delivered', paymentStatus: 'pending', deliveryDate: new Date().toISOString() } ]; } updateData({ handoutDeliveries: updatedDeliveries }); dbService.saveData({ ...data, handoutDeliveries: updatedDeliveries }); }; const togglePaymentStatus = (studentId: string, handoutId: string) => { const existing = deliveries.find(d => d.studentId === studentId && d.handoutId === handoutId); let updatedDeliveries: HandoutDelivery[]; if (existing) { updatedDeliveries = deliveries.map(d => (d.studentId === studentId && d.handoutId === handoutId) ? { ...d, paymentStatus: d.paymentStatus === 'paid' ? 'pending' : 'paid', paymentDate: d.paymentStatus === 'paid' ? undefined : new Date().toISOString() } : d ); } else { updatedDeliveries = [ ...deliveries, { id: crypto.randomUUID(), studentId, handoutId, deliveryStatus: 'pending', paymentStatus: 'paid', paymentDate: new Date().toISOString() } ]; } updateData({ handoutDeliveries: updatedDeliveries }); dbService.saveData({ ...data, handoutDeliveries: updatedDeliveries }); }; const getStudentDelivery = (studentId: string, handoutId: string) => { return deliveries.find(d => d.studentId === studentId && d.handoutId === handoutId); }; const filteredClasses = classes.filter(c => (c.name || '').toLowerCase().includes((searchTerm || '').toLowerCase()) ); const filteredStudents = students.filter(s => (s.name || '').toLowerCase().includes((searchTerm || '').toLowerCase()) || (s.cpf || '').includes(searchTerm || '') ); return (

Gestão de Apostilas

Cadastre livros e gerencie entregas e pagamentos.

{/* Handouts List */}

Apostilas Cadastradas

{handouts.map(handout => (

{handout.name}

{handout.description || 'Sem descrição'}

R$ {handout.price.toFixed(2)}

))} {handouts.length === 0 && (
Nenhuma apostila cadastrada.
)}
{/* Management Tabs */}
setSearchTerm(e.target.value)} />
{activeTab === 'classes' ? (
{filteredClasses.map(cls => ( ))} {filteredClasses.length === 0 && (
Nenhuma turma encontrada.
)}
) : (
{filteredStudents.map(student => ( ))} {filteredStudents.length === 0 && (
Nenhum aluno encontrado.
)}
)}
{/* Add Handout Modal */} {showAddHandout && (

{editingHandoutId ? 'Editar Apostila' : 'Nova Apostila'}

Cadastre e configure os dados do material.

setNewHandout({...newHandout, name: e.target.value})} />
setNewHandout({...newHandout, price: parseFloat(e.target.value)})} />
setNewHandout({...newHandout, finePercentage: parseFloat(e.target.value)})} />
setNewHandout({...newHandout, interestPercentage: parseFloat(e.target.value)})} />