import React, { useState, useEffect } from 'react'; import { IonContent, IonPage, IonHeader, IonToolbar, IonTitle, IonButtons, IonButton, IonIcon, IonInput, IonTextarea, IonSpinner, IonLabel, IonSelect, IonSelectOption, } from '@ionic/react'; import { chevronBackOutline } from 'ionicons/icons'; import { useHistory, useLocation } from 'react-router-dom'; import { supabase } from '../supabase'; import { useAuth } from '../contexts/AuthContext'; import { getTodayISO } from '../utils/dates'; import MoneyInput from '../components/MoneyInput'; import { parseMoney } from '../utils/money'; interface Customer { id: string; name: string; } const CreditFormPage: React.FC = () => { const history = useHistory(); const location = useLocation<{ customerId?: string }>(); const { user } = useAuth(); const [mode, setMode] = useState<'existing' | 'new'>('existing'); const [customers, setCustomers] = useState([]); const [selectedCustomerId, setSelectedCustomerId] = useState( location.state?.customerId || '' ); const [newName, setNewName] = useState(''); const [phone, setPhone] = useState(''); const [amount, setAmount] = useState(''); const [creditDate, setCreditDate] = useState(getTodayISO()); const [description, setDescription] = useState(''); const [submitting, setSubmitting] = useState(false); const [loadingCustomers, setLoadingCustomers] = useState(true); const [errors, setErrors] = useState>({}); const [message, setMessage] = useState(null); useEffect(() => { const fetchCustomers = async () => { if (!user) return; try { const { data, error } = await supabase .from('credit_customers') .select('id, name') .eq('user_id', user.id) .order('name'); if (error) throw error; setCustomers(data || []); if (!data || data.length === 0) { setMode('new'); } } catch (err) { console.error('Error fetching customers:', err); } finally { setLoadingCustomers(false); } }; fetchCustomers(); }, [user]); const validate = () => { const newErrors: Record = {}; const parsedAmount = parseMoney(amount); if (mode === 'existing' && !selectedCustomerId) { newErrors.customer = 'Please select a customer'; } if (mode === 'new' && !newName.trim()) { newErrors.name = 'Customer name is required'; } if (parsedAmount <= 0) { newErrors.amount = 'Amount must be greater than 0'; } if (!creditDate) { newErrors.date = 'Date is required'; } setErrors(newErrors); return Object.keys(newErrors).length === 0; }; const handleSave = async () => { if (!validate() || !user) return; setSubmitting(true); setMessage(null); try { let customerId = selectedCustomerId; if (mode === 'new') { const { data: newCustomer, error: customerError } = await supabase .from('credit_customers') .insert([ { user_id: user.id, name: newName.trim(), phone: phone.trim() || null, }, ]) .select() .single(); if (customerError) throw customerError; customerId = newCustomer.id; } const { error: creditError } = await supabase.from('credits').insert([ { user_id: user.id, customer_id: customerId, amount: parseMoney(amount), credit_date: creditDate, description: description.trim() || null, }, ]); if (creditError) throw creditError; history.goBack(); } catch (err: any) { console.error('Error saving credit:', err); setMessage(err.message || 'Could not save credit'); setTimeout(() => setMessage(null), 4000); } finally { setSubmitting(false); } }; return ( history.goBack()}> Add credit
{mode === 'existing' ? (
Select Customer
setSelectedCustomerId(e.detail.value)} style={{ width: '100%' }} > {customers.map((c) => ( {c.name} ))}
{errors.customer && ( {errors.customer} )}
) : ( <>
Customer Name
setNewName(e.detail.value!)} />
{errors.name && ( {errors.name} )}
Phone (optional)
setPhone(e.detail.value!)} />
)} { setAmount(val); if (errors.amount) setErrors({ ...errors, amount: '' }); }} error={errors.amount} />
Credit date
setCreditDate(e.detail.value!)} />
{errors.date && ( {errors.date} )}
Description (optional)
setDescription(e.detail.value!)} rows={4} />
{message && (
{message}
)} {submitting ? : 'Save credit'}
); }; export default CreditFormPage;