import React, { useEffect, useState } from 'react'; import { CondoService } from '../services/mockDb'; import { PayPalScriptProvider, PayPalButtons } from "@paypal/react-paypal-js"; import { Briefcase, Calendar, CheckCircle2, AlertCircle, Eye, Paperclip, X, FileText, Download } from 'lucide-react'; import { ExtraordinaryExpense } from '../types'; export const ExtraordinaryUser: React.FC = () => { const [expenses, setExpenses] = useState([]); const [loading, setLoading] = useState(true); const [paypalClientId, setPaypalClientId] = useState(''); const [successMsg, setSuccessMsg] = useState(''); const [hasFamily, setHasFamily] = useState(true); // Details Modal State const [showDetails, setShowDetails] = useState(false); const [selectedExpense, setSelectedExpense] = useState(null); const [loadingDetails, setLoadingDetails] = useState(false); useEffect(() => { const load = async () => { try { const user = CondoService.getCurrentUser(); if (!user?.familyId) { setHasFamily(false); setLoading(false); return; } const [myExp, condo] = await Promise.all([ CondoService.getMyExpenses(), CondoService.getActiveCondo() ]); setExpenses(myExp); if (condo?.paypalClientId) setPaypalClientId(condo.paypalClientId); // Update "Last Viewed" timestamp to clear notification localStorage.setItem('lastViewedExpensesTime', Date.now().toString()); // Trigger event to update Sidebar immediately window.dispatchEvent(new Event('expenses-viewed')); } catch(e) { console.error(e); } finally { setLoading(false); } }; load(); }, []); const handlePaymentSuccess = async (expenseId: string, amount: number) => { try { await CondoService.payExpense(expenseId, amount); setSuccessMsg('Pagamento registrato con successo!'); setTimeout(() => setSuccessMsg(''), 3000); // Refresh const updated = await CondoService.getMyExpenses(); setExpenses(updated); } catch(e) { alert("Errore registrazione pagamento"); } }; const handleCardClick = async (expenseId: string) => { setLoadingDetails(true); try { // Fetch full details including attachments const fullDetails = await CondoService.getExpenseDetails(expenseId); setSelectedExpense(fullDetails); setShowDetails(true); } catch (e) { console.error(e); alert("Impossibile caricare i dettagli."); } finally { setLoadingDetails(false); } }; const openAttachment = async (expenseId: string, attId: string) => { try { const file = await CondoService.getExpenseAttachment(expenseId, attId); const win = window.open(); if (win) { if (file.fileType.startsWith('image/') || file.fileType === 'application/pdf') { win.document.write(``); } else { win.document.write(`Download ${file.fileName}`); } } } catch(e) { alert("Errore apertura file"); } }; if (loading) return
Caricamento spese...
; if (!hasFamily) { return (

Nessuna Famiglia Associata

Il tuo utente (probabilmente Admin) non è collegato ad alcuna famiglia, quindi non ci sono spese personali da mostrare.

Vai in Impostazioni > Utenti e associa il tuo account a una famiglia per testare questa vista.

); } return (

Le Mie Spese Extra

Lavori straordinari e ripartizioni

{successMsg && (
{successMsg}
)} {expenses.length === 0 ? (

Nessuna spesa straordinaria attiva.

) : (
{expenses.map(exp => { const remaining = exp.myShare.amountDue - exp.myShare.amountPaid; const isPaid = exp.myShare.status === 'PAID'; return (
handleCardClick(exp.id)} className="bg-white rounded-xl border border-slate-200 shadow-sm overflow-hidden flex flex-col cursor-pointer hover:shadow-md transition-all group" >

{exp.title}

{new Date(exp.startDate).toLocaleDateString()}

{isPaid ? 'Saldato' : 'In Sospeso'}
Quota Totale (100%) € {exp.totalAmount.toLocaleString()}
La tua quota ({exp.myShare.percentage}%) € {exp.myShare.amountDue.toFixed(2)}
Versato: € {exp.myShare.amountPaid.toFixed(2)} Restante: € {Math.max(0, remaining).toFixed(2)}
e.stopPropagation()}> {!isPaid && remaining > 0.01 && ( <> {paypalClientId ? ( { return actions.order.create({ intent: "CAPTURE", purchase_units: [{ description: `Spesa Straordinaria: ${exp.title}`, amount: { currency_code: "EUR", value: remaining.toFixed(2) } }] }); }} onApprove={(data, actions) => { if(!actions.order) return Promise.resolve(); return actions.order.capture().then(() => { handlePaymentSuccess(exp.id, remaining); }); }} /> ) : (
Pagamenti online non configurati. Contatta l'amministratore.
)} )} {isPaid && (
Nessun importo dovuto
)}
); })}
)} {/* DETAILS MODAL */} {showDetails && selectedExpense && (

{selectedExpense.title}

{selectedExpense.contractorName}

{/* Description */}

Descrizione Lavori

{selectedExpense.description}

{/* Dates & Totals */}

Inizio Lavori

{new Date(selectedExpense.startDate).toLocaleDateString()}

Totale Progetto

€ {selectedExpense.totalAmount.toLocaleString()}

{/* Items List */}

Dettaglio Voci di Spesa

{selectedExpense.items.map((item, i) => ( ))}
Descrizione Importo
{item.description} € {item.amount.toLocaleString()}
{/* Attachments */} {selectedExpense.attachments && selectedExpense.attachments.length > 0 && (

Documenti & Allegati

{selectedExpense.attachments.map(att => ( ))}
)}
)}
); };