diff --git a/resources/js/components/IncomeDistributionPreview.tsx b/resources/js/components/IncomeDistributionPreview.tsx index 1a576dd..ad0c00b 100644 --- a/resources/js/components/IncomeDistributionPreview.tsx +++ b/resources/js/components/IncomeDistributionPreview.tsx @@ -1,4 +1,5 @@ import { useState } from 'react'; +import { router } from '@inertiajs/react'; import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card'; import { Button } from '@/components/ui/button'; @@ -33,12 +34,15 @@ export default function IncomeDistributionPreview({ scenarioId }: IncomeDistribu const [amount, setAmount] = useState(''); const [preview, setPreview] = useState(null); const [isLoading, setIsLoading] = useState(false); + const [isApplying, setIsApplying] = useState(false); const [error, setError] = useState(null); + const [applied, setApplied] = useState(false); const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); setIsLoading(true); setError(null); + setApplied(false); const parsed = parseFloat(amount); if (isNaN(parsed) || parsed <= 0) { @@ -78,6 +82,44 @@ export default function IncomeDistributionPreview({ scenarioId }: IncomeDistribu } }; + const handleApply = async () => { + const parsed = parseFloat(amount); + if (isNaN(parsed) || parsed <= 0) return; + + setIsApplying(true); + setError(null); + + try { + const response = await fetch(`/scenarios/${scenarioId}/projections/apply`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-CSRF-TOKEN': csrfToken(), + }, + body: JSON.stringify({ amount: Math.round(parsed * 100) }), + }); + + if (!response.ok) { + let message = 'Failed to save distribution'; + try { + const data = await response.json(); + message = data.message || message; + } catch { /* non-JSON error body */ } + setError(message); + return; + } + + setPreview(null); + setAmount(''); + setApplied(true); + router.reload({ only: ['buckets'] }); + } catch { + setError('Failed to connect to server'); + } finally { + setIsApplying(false); + } + }; + return ( @@ -101,7 +143,7 @@ export default function IncomeDistributionPreview({ scenarioId }: IncomeDistribu required /> - @@ -112,6 +154,12 @@ export default function IncomeDistributionPreview({ scenarioId }: IncomeDistribu )} + {applied && ( +
+ Distribution saved successfully. Bucket balances have been updated. +
+ )} + {preview && (
{preview.allocations.length > 0 ? ( @@ -152,6 +200,16 @@ export default function IncomeDistributionPreview({ scenarioId }: IncomeDistribu ${(preview.unallocated / 100).toFixed(2)}
)} + + {preview.allocations.length > 0 && ( + + )} )}