buckets/resources/js/pages/Scenarios/Show.tsx

579 lines
33 KiB
TypeScript
Raw Normal View History

2025-12-29 23:32:05 +01:00
import { Head, Link, router } from '@inertiajs/react';
import { useState } from 'react';
2025-12-29 21:53:52 +01:00
interface Scenario {
id: string;
2025-12-29 21:53:52 +01:00
name: string;
created_at: string;
updated_at: string;
}
2025-12-29 23:32:05 +01:00
interface Bucket {
id: string;
2025-12-29 23:32:05 +01:00
name: string;
priority: number;
sort_order: number;
allocation_type: string;
allocation_value: number | null;
allocation_type_label: string;
formatted_allocation_value: string;
current_balance: number;
has_available_space: boolean;
available_space: number;
}
2025-12-31 00:02:54 +01:00
interface Stream {
id: string;
2025-12-31 00:02:54 +01:00
name: string;
type: 'income' | 'expense';
type_label: string;
amount: number;
frequency: string;
frequency_label: string;
start_date: string;
end_date: string | null;
bucket_id: string | null;
2025-12-31 00:02:54 +01:00
bucket_name: string | null;
description: string | null;
is_active: boolean;
monthly_equivalent: number;
}
interface StreamStats {
total_streams: number;
active_streams: number;
income_streams: number;
expense_streams: number;
monthly_income: number;
monthly_expenses: number;
monthly_net: number;
}
2025-12-29 21:53:52 +01:00
interface Props {
scenario: Scenario;
2026-01-01 03:18:40 +01:00
buckets: { data: Bucket[] };
streams: { data: Stream[] };
2025-12-31 00:02:54 +01:00
streamStats?: StreamStats;
2025-12-29 21:53:52 +01:00
}
2026-01-01 03:18:40 +01:00
export default function Show({ scenario, buckets, streams = { data: [] }, streamStats }: Props) {
2025-12-29 23:32:05 +01:00
const [isModalOpen, setIsModalOpen] = useState(false);
const [isSubmitting, setIsSubmitting] = useState(false);
2025-12-30 20:50:13 +01:00
const [editingBucket, setEditingBucket] = useState<Bucket | null>(null);
2025-12-29 23:32:05 +01:00
const [formData, setFormData] = useState({
name: '',
allocation_type: 'fixed_limit',
allocation_value: ''
});
2025-12-30 20:50:13 +01:00
const handleEdit = (bucket: Bucket) => {
setEditingBucket(bucket);
setFormData({
name: bucket.name,
allocation_type: bucket.allocation_type,
allocation_value: bucket.allocation_value ? bucket.allocation_value.toString() : ''
});
setIsModalOpen(true);
};
const handleDelete = async (bucket: Bucket) => {
if (!confirm(`Are you sure you want to delete "${bucket.name}"?`)) {
return;
}
try {
const response = await fetch(`/buckets/${bucket.id}`, {
method: 'DELETE',
headers: {
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '',
},
});
if (response.ok) {
router.reload({ only: ['buckets'] });
} else {
console.error('Failed to delete bucket');
}
} catch (error) {
console.error('Error deleting bucket:', error);
}
};
2025-12-29 23:32:05 +01:00
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setIsSubmitting(true);
2025-12-30 20:50:13 +01:00
const url = editingBucket
? `/buckets/${editingBucket.id}`
: `/scenarios/${scenario.id}/buckets`;
const method = editingBucket ? 'PATCH' : 'POST';
2025-12-29 23:32:05 +01:00
try {
2025-12-30 20:50:13 +01:00
const response = await fetch(url, {
method: method,
2025-12-29 23:32:05 +01:00
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '',
},
body: JSON.stringify({
name: formData.name,
allocation_type: formData.allocation_type,
2025-12-30 20:50:13 +01:00
allocation_value: formData.allocation_value ? parseFloat(formData.allocation_value) : null,
priority: editingBucket ? editingBucket.priority : undefined
2025-12-29 23:32:05 +01:00
}),
});
if (response.ok) {
setIsModalOpen(false);
setFormData({ name: '', allocation_type: 'fixed_limit', allocation_value: '' });
2025-12-30 20:50:13 +01:00
setEditingBucket(null);
2025-12-29 23:32:05 +01:00
router.reload({ only: ['buckets'] });
} else {
const errorData = await response.json();
2025-12-30 20:50:13 +01:00
console.error(`Failed to ${editingBucket ? 'update' : 'create'} bucket:`, errorData);
2025-12-29 23:32:05 +01:00
}
} catch (error) {
2025-12-30 20:50:13 +01:00
console.error(`Error ${editingBucket ? 'updating' : 'creating'} bucket:`, error);
2025-12-29 23:32:05 +01:00
} finally {
setIsSubmitting(false);
}
};
const handlePriorityChange = async (bucketId: string, direction: 'up' | 'down') => {
2026-01-01 03:18:40 +01:00
const bucket = buckets.data.find(b => b.id === bucketId);
2025-12-29 23:35:57 +01:00
if (!bucket) return;
const newPriority = direction === 'up' ? bucket.priority - 1 : bucket.priority + 1;
// Don't allow moving beyond bounds
2026-01-01 03:18:40 +01:00
if (newPriority < 1 || newPriority > buckets.data.length) return;
2025-12-29 23:35:57 +01:00
try {
const response = await fetch(`/buckets/${bucketId}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '',
},
body: JSON.stringify({
name: bucket.name,
allocation_type: bucket.allocation_type,
allocation_value: bucket.allocation_value,
priority: newPriority
}),
});
if (response.ok) {
router.reload({ only: ['buckets'] });
} else {
console.error('Failed to update bucket priority');
}
} catch (error) {
console.error('Error updating bucket priority:', error);
}
};
2025-12-29 21:53:52 +01:00
return (
<>
<Head title={scenario.name} />
<div className="min-h-screen bg-gray-50 py-8">
<div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
{/* Header */}
<div className="mb-8">
<div className="flex items-center justify-between">
<div>
<Link
href="/"
className="text-sm text-blue-600 hover:text-blue-500 mb-2 inline-flex items-center"
>
<svg className="mr-2 h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
</svg>
Back to Scenarios
</Link>
<h1 className="text-3xl font-bold text-gray-900">{scenario.name}</h1>
<p className="mt-2 text-gray-600">
Water flows through the pipeline into prioritized buckets
</p>
</div>
</div>
</div>
2025-12-29 23:32:05 +01:00
{/* Bucket Dashboard */}
<div className="space-y-6">
<div className="flex items-center justify-between">
<h2 className="text-xl font-semibold text-gray-900">Buckets</h2>
<button
2025-12-30 20:50:13 +01:00
onClick={() => {
setEditingBucket(null);
setFormData({ name: '', allocation_type: 'fixed_limit', allocation_value: '' });
setIsModalOpen(true);
}}
2025-12-29 21:53:52 +01:00
className="rounded-md bg-blue-600 px-4 py-2 text-sm font-semibold text-white hover:bg-blue-500"
>
2025-12-29 23:32:05 +01:00
+ Add Bucket
</button>
</div>
<div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
2026-01-01 03:18:40 +01:00
{buckets.data.map((bucket) => (
2025-12-29 23:32:05 +01:00
<div
key={bucket.id}
className="rounded-lg bg-white p-6 shadow transition-shadow hover:shadow-lg border-l-4 border-blue-500"
>
<div className="flex items-start justify-between">
<div className="flex-1">
<h3 className="text-lg font-semibold text-gray-900">
{bucket.name}
</h3>
<p className="text-sm text-gray-600 mt-1">
Priority {bucket.priority} {bucket.allocation_type_label}
</p>
</div>
2025-12-29 23:35:57 +01:00
<div className="flex items-center gap-1">
<button
onClick={() => handlePriorityChange(bucket.id, 'up')}
disabled={bucket.priority === 1}
className="p-1 rounded hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed"
title="Move up in priority"
>
<svg className="w-3 h-3 text-gray-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
</svg>
</button>
<button
onClick={() => handlePriorityChange(bucket.id, 'down')}
2026-01-01 03:18:40 +01:00
disabled={bucket.priority === buckets.data.length}
2025-12-29 23:35:57 +01:00
className="p-1 rounded hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed"
title="Move down in priority"
>
<svg className="w-3 h-3 text-gray-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
</svg>
</button>
<span className="rounded-full bg-blue-100 px-2.5 py-0.5 text-xs font-medium text-blue-800">
#{bucket.priority}
</span>
</div>
2025-12-29 23:32:05 +01:00
</div>
<div className="mt-4">
<div className="flex items-center justify-between">
<span className="text-sm text-gray-600">Current Balance</span>
<span className="text-lg font-semibold text-gray-900">
${bucket.current_balance.toFixed(2)}
</span>
</div>
<div className="mt-2">
<span className="text-sm text-gray-600">
Allocation: {bucket.formatted_allocation_value}
</span>
</div>
{bucket.allocation_type === 'fixed_limit' && (
<div className="mt-3">
<div className="flex justify-between text-sm">
<span>Progress</span>
<span>
${bucket.current_balance.toFixed(2)} / ${Number(bucket.allocation_value)?.toFixed(2)}
</span>
</div>
<div className="mt-1 h-2 bg-gray-200 rounded-full">
<div
className="h-2 bg-blue-600 rounded-full transition-all"
style={{
width: `${bucket.allocation_value ? Math.min((bucket.current_balance / Number(bucket.allocation_value)) * 100, 100) : 0}%`
}}
/>
</div>
</div>
)}
</div>
<div className="mt-4 flex gap-2">
2025-12-30 20:50:13 +01:00
<button
onClick={() => handleEdit(bucket)}
className="flex-1 text-sm text-blue-600 hover:text-blue-500"
>
2025-12-29 23:32:05 +01:00
Edit
</button>
2025-12-30 20:50:13 +01:00
<button
onClick={() => handleDelete(bucket)}
className="flex-1 text-sm text-red-600 hover:text-red-500"
>
2025-12-29 23:32:05 +01:00
Delete
</button>
</div>
</div>
))}
{/* Virtual Overflow Bucket (placeholder for now) */}
<div className="rounded-lg bg-gray-50 p-6 border-2 border-dashed border-gray-300">
<div className="text-center">
<div className="mx-auto h-8 w-8 text-gray-400">
<svg fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6V4m0 2a2 2 0 100 4m0-4a2 2 0 110 4m-6 8a2 2 0 100-4m0 4a2 2 0 100 4m0-4v2m0-6V4m6 6v10m6-2a2 2 0 100-4m0 4a2 2 0 100 4m0-4v2m0-6V4" />
</svg>
</div>
<h3 className="mt-2 text-sm font-medium text-gray-500">
Overflow
</h3>
<p className="text-xs text-gray-400 mt-1">
Unallocated funds
</p>
<p className="text-lg font-semibold text-gray-600 mt-2">
$0.00
</p>
</div>
</div>
</div>
2025-12-31 00:02:54 +01:00
{/* Streams Section */}
<div className="mt-8">
<div className="flex items-center justify-between mb-4">
<h2 className="text-xl font-semibold text-gray-900">Income & Expense Streams</h2>
<button
className="rounded-md bg-green-600 px-4 py-2 text-sm font-semibold text-white hover:bg-green-500"
>
+ Add Stream
</button>
</div>
{/* Stream Statistics */}
{streamStats && (
<div className="grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-4 mb-6">
<div className="bg-white overflow-hidden shadow rounded-lg">
<div className="px-4 py-5 sm:p-6">
<dt className="text-sm font-medium text-gray-500 truncate">
Monthly Income
</dt>
<dd className="mt-1 text-3xl font-semibold text-green-600">
${streamStats.monthly_income.toFixed(2)}
</dd>
</div>
</div>
<div className="bg-white overflow-hidden shadow rounded-lg">
<div className="px-4 py-5 sm:p-6">
<dt className="text-sm font-medium text-gray-500 truncate">
Monthly Expenses
</dt>
<dd className="mt-1 text-3xl font-semibold text-red-600">
${streamStats.monthly_expenses.toFixed(2)}
</dd>
</div>
</div>
<div className="bg-white overflow-hidden shadow rounded-lg">
<div className="px-4 py-5 sm:p-6">
<dt className="text-sm font-medium text-gray-500 truncate">
Net Cash Flow
</dt>
<dd className={`mt-1 text-3xl font-semibold ${streamStats.monthly_net >= 0 ? 'text-green-600' : 'text-red-600'}`}>
${streamStats.monthly_net.toFixed(2)}
</dd>
</div>
</div>
<div className="bg-white overflow-hidden shadow rounded-lg">
<div className="px-4 py-5 sm:p-6">
<dt className="text-sm font-medium text-gray-500 truncate">
Active Streams
</dt>
<dd className="mt-1 text-3xl font-semibold text-gray-900">
{streamStats.active_streams} / {streamStats.total_streams}
</dd>
</div>
</div>
</div>
)}
2026-01-01 03:18:40 +01:00
{streams.data.length === 0 ? (
2025-12-31 00:02:54 +01:00
<div className="rounded-lg bg-white p-8 text-center shadow">
<p className="text-gray-600">No streams yet. Add income or expense streams to start tracking cash flow.</p>
</div>
) : (
<div className="overflow-hidden shadow ring-1 ring-black ring-opacity-5 md:rounded-lg">
<table className="min-w-full divide-y divide-gray-300">
<thead className="bg-gray-50">
<tr>
<th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">
Name
</th>
<th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">
Type
</th>
<th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">
Amount
</th>
<th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">
Frequency
</th>
<th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">
Bucket
</th>
<th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">
Start Date
</th>
<th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">
Status
</th>
<th className="relative px-6 py-3">
<span className="sr-only">Actions</span>
</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-200 bg-white">
2026-01-01 03:18:40 +01:00
{streams.data.map((stream) => (
2025-12-31 00:02:54 +01:00
<tr key={stream.id}>
<td className="whitespace-nowrap px-6 py-4 text-sm font-medium text-gray-900">
{stream.name}
</td>
<td className="whitespace-nowrap px-6 py-4 text-sm text-gray-500">
<span className={`inline-flex rounded-full px-2 text-xs font-semibold leading-5 ${
stream.type === 'income'
? 'bg-green-100 text-green-800'
: 'bg-red-100 text-red-800'
}`}>
{stream.type_label}
</span>
</td>
<td className="whitespace-nowrap px-6 py-4 text-sm text-gray-500">
${stream.amount.toFixed(2)}
</td>
<td className="whitespace-nowrap px-6 py-4 text-sm text-gray-500">
{stream.frequency_label}
</td>
<td className="whitespace-nowrap px-6 py-4 text-sm text-gray-500">
{stream.bucket_name || '-'}
</td>
<td className="whitespace-nowrap px-6 py-4 text-sm text-gray-500">
{new Date(stream.start_date).toLocaleDateString()}
</td>
<td className="whitespace-nowrap px-6 py-4 text-sm text-gray-500">
<button
className={`inline-flex rounded-full px-2 text-xs font-semibold leading-5 ${
stream.is_active
? 'bg-green-100 text-green-800'
: 'bg-gray-100 text-gray-800'
}`}
>
{stream.is_active ? 'Active' : 'Inactive'}
</button>
</td>
<td className="relative whitespace-nowrap py-4 pl-3 pr-4 text-right text-sm font-medium sm:pr-6">
<button className="text-indigo-600 hover:text-indigo-900 mr-3">
Edit
</button>
<button className="text-red-600 hover:text-red-900">
Delete
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
2025-12-29 23:32:05 +01:00
{/* Placeholder for future features */}
<div className="rounded-lg bg-blue-50 p-6 text-center">
<h3 className="text-lg font-medium text-blue-900">
2025-12-31 00:02:54 +01:00
Coming Next: Timeline & Projections
2025-12-29 23:32:05 +01:00
</h3>
<p className="text-sm text-blue-700 mt-2">
2025-12-31 00:02:54 +01:00
Calculate projections to see your money flow through these buckets over time.
2025-12-29 23:32:05 +01:00
</p>
2025-12-29 21:53:52 +01:00
</div>
</div>
</div>
</div>
2025-12-29 23:32:05 +01:00
{/* Add Bucket Modal */}
{isModalOpen && (
<div className="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50">
<div className="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
<div className="mt-3">
2025-12-30 20:50:13 +01:00
<h3 className="text-lg font-medium text-gray-900 mb-4">{editingBucket ? 'Edit Bucket' : 'Add New Bucket'}</h3>
2025-12-29 23:32:05 +01:00
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label htmlFor="name" className="block text-sm font-medium text-gray-700">
Bucket Name
</label>
<input
type="text"
id="name"
value={formData.name}
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-gray-900"
placeholder="e.g., Travel Fund"
required
/>
</div>
<div>
<label htmlFor="allocation_type" className="block text-sm font-medium text-gray-700">
Allocation Type
</label>
<select
id="allocation_type"
value={formData.allocation_type}
onChange={(e) => setFormData({ ...formData, allocation_type: e.target.value })}
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-gray-900"
>
<option value="fixed_limit">Fixed Limit</option>
<option value="percentage">Percentage</option>
<option value="unlimited">Unlimited</option>
</select>
</div>
{formData.allocation_type !== 'unlimited' && (
<div>
<label htmlFor="allocation_value" className="block text-sm font-medium text-gray-700">
{formData.allocation_type === 'percentage' ? 'Percentage (%)' : 'Amount ($)'}
</label>
<input
type="number"
id="allocation_value"
value={formData.allocation_value}
onChange={(e) => setFormData({ ...formData, allocation_value: e.target.value })}
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-gray-900"
placeholder={formData.allocation_type === 'percentage' ? '25' : '1000'}
step={formData.allocation_type === 'percentage' ? '0.01' : '0.01'}
min={formData.allocation_type === 'percentage' ? '0.01' : '0'}
max={formData.allocation_type === 'percentage' ? '100' : undefined}
required
/>
</div>
)}
<div className="flex gap-3 pt-4">
<button
type="button"
2025-12-30 20:50:13 +01:00
onClick={() => {
setIsModalOpen(false);
setEditingBucket(null);
setFormData({ name: '', allocation_type: 'fixed_limit', allocation_value: '' });
}}
2025-12-29 23:32:05 +01:00
className="flex-1 px-4 py-2 text-sm font-medium text-gray-700 bg-gray-200 rounded-md hover:bg-gray-300"
disabled={isSubmitting}
>
Cancel
</button>
<button
type="submit"
className="flex-1 px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-md hover:bg-blue-700 disabled:opacity-50"
disabled={isSubmitting}
>
2025-12-30 20:50:13 +01:00
{isSubmitting ? (editingBucket ? 'Updating...' : 'Creating...') : (editingBucket ? 'Update Bucket' : 'Create Bucket')}
2025-12-29 23:32:05 +01:00
</button>
</div>
</form>
</div>
</div>
</div>
)}
2025-12-29 21:53:52 +01:00
</>
);
}