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

637 lines
34 KiB
TypeScript

import { Head, router } from '@inertiajs/react';
import { Settings } from 'lucide-react';
import { useRef, useState } from 'react';
import BucketCard from '@/components/BucketCard';
import DistributionLines from '@/components/DistributionLines';
import InlineEditInput from '@/components/InlineEditInput';
import InlineEditSelect from '@/components/InlineEditSelect';
import SettingsPanel from '@/components/SettingsPanel';
import { csrfToken } from '@/lib/utils';
import { type Bucket, type DistributionPreview, type Scenario } from '@/types';
interface Props {
scenario: Scenario;
buckets: { data: Bucket[] };
}
const bucketTypeOptions = [
{ value: 'need', label: 'Need' },
{ value: 'want', label: 'Want' },
];
const allocationTypeOptions = [
{ value: 'fixed_limit', label: 'Fixed Limit' },
{ value: 'percentage', label: 'Percentage' },
];
const centsToDollars = (cents: number): number => cents / 100;
const dollarsToCents = (dollars: number): number => Math.round(dollars * 100);
const basisPointsToPercent = (bp: number): number => bp / 100;
const percentToBasisPoints = (pct: number): number => Math.round(pct * 100);
const patchBucket = async (bucketId: string, data: Record<string, unknown>): Promise<void> => {
const response = await fetch(`/buckets/${bucketId}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': csrfToken(),
},
body: JSON.stringify(data),
});
if (!response.ok) {
throw new Error('Failed to update bucket');
}
router.reload({ only: ['buckets'] });
};
const defaultFormData = {
name: '',
type: 'need' as Bucket['type'],
allocation_type: 'fixed_limit',
allocation_value: '',
buffer_multiplier: '0',
buffer_mode: 'preset' as 'preset' | 'custom',
};
export default function Show({ scenario, buckets }: Props) {
const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
const [editingBucket, setEditingBucket] = useState<Bucket | null>(null);
const [isSettingsOpen, setIsSettingsOpen] = useState(false);
const [isSubmitting, setIsSubmitting] = useState(false);
const [formData, setFormData] = useState({ ...defaultFormData });
const [incomeAmount, setIncomeAmount] = useState('');
const [distribution, setDistribution] = useState<DistributionPreview | null>(null);
const [isDistributing, setIsDistributing] = useState(false);
const [isSaving, setIsSaving] = useState(false);
const [distributionError, setDistributionError] = useState<string | null>(null);
const containerRef = useRef<HTMLDivElement>(null);
const incomeRef = useRef<HTMLDivElement>(null);
const bucketRefs = useRef<Map<string, HTMLElement>>(new Map());
const handleDistribute = async () => {
const dollars = parseFloat(incomeAmount);
if (!dollars || dollars <= 0) return;
setIsDistributing(true);
setDistributionError(null);
try {
const response = await fetch(`/scenarios/${scenario.id}/projections/preview`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': csrfToken(),
},
body: JSON.stringify({ amount: dollarsToCents(dollars) }),
});
if (response.ok) {
setDistribution(await response.json());
} else {
setDistributionError('DISTRIBUTION FAILED');
}
} catch (error) {
setDistributionError('CONNECTION ERROR');
} finally {
setIsDistributing(false);
}
};
const handleSaveDistribution = async () => {
const dollars = parseFloat(incomeAmount);
if (!dollars || dollars <= 0 || !distribution) return;
setIsSaving(true);
setDistributionError(null);
try {
const response = await fetch(`/scenarios/${scenario.id}/projections/apply`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': csrfToken(),
},
body: JSON.stringify({ amount: dollarsToCents(dollars) }),
});
if (response.ok) {
setDistribution(null);
setIncomeAmount('');
router.reload({ only: ['buckets'] });
} else {
setDistributionError('SAVE FAILED');
}
} catch (error) {
setDistributionError('CONNECTION ERROR');
} finally {
setIsSaving(false);
}
};
const handleIncomeChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setIncomeAmount(e.target.value);
setDistribution(null);
setDistributionError(null);
};
const openCreateModal = () => {
setFormData({ ...defaultFormData });
setIsCreateModalOpen(true);
};
const handleDelete = async (bucket: Bucket) => {
if (!confirm(`Delete "${bucket.name}"?`)) return;
try {
const response = await fetch(`/buckets/${bucket.id}`, {
method: 'DELETE',
headers: { 'X-CSRF-TOKEN': csrfToken() },
});
if (response.ok) {
setEditingBucket(null);
router.reload({ only: ['buckets'] });
}
} catch (error) {
console.error('Error deleting bucket:', error);
}
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setIsSubmitting(true);
try {
const response = await fetch(`/scenarios/${scenario.id}/buckets`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': csrfToken(),
},
body: JSON.stringify({
name: formData.name,
type: formData.type,
allocation_type: formData.allocation_type,
allocation_value: formData.allocation_value
? (formData.allocation_type === 'percentage'
? percentToBasisPoints(parseFloat(formData.allocation_value))
: dollarsToCents(parseFloat(formData.allocation_value)))
: null,
buffer_multiplier: formData.allocation_type === 'fixed_limit' ? parseFloat(formData.buffer_multiplier) || 0 : 0,
}),
});
if (response.ok) {
setIsCreateModalOpen(false);
setFormData({ ...defaultFormData });
router.reload({ only: ['buckets'] });
} else {
const errorData = await response.json();
console.error('Failed to create bucket:', errorData);
}
} catch (error) {
console.error('Error creating bucket:', error);
} finally {
setIsSubmitting(false);
}
};
const handlePriorityChange = async (bucketId: string, direction: 'up' | 'down') => {
const bucket = buckets.data.find(b => b.id === bucketId);
if (!bucket) return;
const newPriority = direction === 'up' ? bucket.priority - 1 : bucket.priority + 1;
if (newPriority < 1 || newPriority > buckets.data.length) return;
try {
await patchBucket(bucketId, { priority: newPriority });
} catch (error) {
console.error('Error updating bucket priority:', error);
}
};
return (
<>
<Head title={scenario.name} />
<div className="min-h-screen bg-background p-8">
<div className="mx-auto max-w-6xl">
{/* Header */}
<div className="mb-8 flex items-center justify-between border-b border-red-500/40 pb-4">
<h1 className="text-2xl font-bold font-mono uppercase tracking-wider text-red-500">
BUCKETS
</h1>
<button
onClick={() => setIsSettingsOpen(!isSettingsOpen)}
className="p-2 text-red-500/60 hover:text-red-500 transition-colors"
title="Settings"
>
<Settings className="w-5 h-5" />
</button>
</div>
<div
className="overflow-hidden transition-all duration-300 ease-in-out"
style={{ maxHeight: isSettingsOpen ? '500px' : '0', opacity: isSettingsOpen ? 1 : 0 }}
>
<SettingsPanel onOpenChange={setIsSettingsOpen} />
</div>
{/* Buckets + Distribution + Income */}
<div ref={containerRef} className="relative flex items-start gap-0">
{/* Left: Buckets */}
<div className="w-2/5 shrink-0 space-y-4">
<div className="flex items-center justify-between">
<h2 className="text-sm font-mono font-bold tracking-wider uppercase text-red-500/60">
BUCKETS
</h2>
<button
onClick={openCreateModal}
className="border-2 border-red-500 bg-black px-3 py-1 text-xs font-mono font-bold uppercase tracking-wider text-red-500 hover:bg-red-500 hover:text-black transition-colors"
>
+ ADD
</button>
</div>
{buckets.data.length === 0 ? (
<div className="border-4 border-red-500 bg-black p-8 text-center glow-red">
<p className="text-red-500 font-mono uppercase tracking-wider mb-4">
NO BUCKETS CONFIGURED
</p>
<p className="text-red-500/60 font-mono text-sm mb-6">
Income flows through your pipeline into prioritized buckets.
</p>
<button
onClick={openCreateModal}
className="border-2 border-red-500 bg-black px-6 py-3 font-mono font-bold uppercase tracking-wider text-red-500 hover:bg-red-500 hover:text-black transition-colors"
>
CREATE FIRST BUCKET
</button>
</div>
) : (
<div className="space-y-6 px-4">
{buckets.data.map((bucket) => (
<button
key={bucket.id}
type="button"
ref={(el) => {
if (el) bucketRefs.current.set(bucket.id, el);
else bucketRefs.current.delete(bucket.id);
}}
onClick={() => setEditingBucket(bucket)}
className="w-full border-4 border-red-500 bg-black glow-red transition-all text-left hover:border-red-400 cursor-pointer"
>
<BucketCard
bucket={bucket}
projectedAmount={distribution?.allocations.find(a => a.bucket_id === bucket.id)?.allocated_amount}
/>
</button>
))}
</div>
)}
</div>
{/* Middle: Connector area (SVG lines render here) */}
<div className="flex-1" />
{distribution && (
<DistributionLines
distribution={distribution}
bucketRefs={bucketRefs}
containerRef={containerRef}
incomeRef={incomeRef}
/>
)}
{/* Right: Income */}
<div ref={incomeRef} className="w-1/5 shrink-0 self-center">
<div className="flex items-center justify-center border-b border-red-500/40 pb-2 mb-6">
<h2 className="text-sm font-mono font-bold tracking-wider uppercase text-red-500/60">
INCOME
</h2>
</div>
<div className="text-center space-y-4">
<input
type="number"
value={incomeAmount}
onChange={handleIncomeChange}
className="w-48 bg-black border-2 border-red-500/50 px-4 py-2 text-center font-digital text-2xl text-red-500 focus:border-red-500 focus:outline-none"
placeholder="0"
min="0"
step="0.01"
/>
<button
onClick={handleDistribute}
disabled={!incomeAmount || parseFloat(incomeAmount) <= 0 || isDistributing}
className="block mx-auto border-2 border-red-500 bg-black px-6 py-2 text-xs font-mono font-bold uppercase tracking-wider text-red-500 hover:bg-red-500 hover:text-black transition-colors disabled:opacity-30 disabled:cursor-not-allowed"
>
{isDistributing ? 'CALCULATING...' : 'DISTRIBUTE'}
</button>
{distribution && (
<button
onClick={handleSaveDistribution}
disabled={isSaving}
className="block mx-auto border-2 border-red-500 bg-red-500 px-6 py-2 text-xs font-mono font-bold uppercase tracking-wider text-black hover:bg-red-400 transition-colors disabled:opacity-50"
>
{isSaving ? 'SAVING...' : 'SAVE'}
</button>
)}
{distributionError && (
<p className="text-red-500 font-mono text-xs uppercase tracking-wider">
{distributionError}
</p>
)}
</div>
</div>
</div>
</div>
</div>
{/* Create Bucket Modal */}
{isCreateModalOpen && (
<div className="fixed inset-0 bg-black/80 overflow-y-auto h-full w-full z-50 flex items-start justify-center pt-20">
<div className="border-4 border-red-500 bg-black p-8 w-96 glow-red">
<h3 className="text-lg font-mono font-bold uppercase tracking-wider text-red-500 mb-6">
ADD BUCKET
</h3>
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label htmlFor="name" className="block text-xs font-mono uppercase text-red-500/60 mb-1">
NAME
</label>
<input
type="text"
id="name"
value={formData.name}
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
className="w-full bg-black border-2 border-red-500/50 px-3 py-2 text-red-500 font-mono focus:border-red-500 focus:outline-none"
placeholder="e.g., Travel Fund"
required
/>
</div>
<div>
<label htmlFor="type" className="block text-xs font-mono uppercase text-red-500/60 mb-1">
TYPE
</label>
<select
id="type"
value={formData.type}
onChange={(e) => setFormData({ ...formData, type: e.target.value as Bucket['type'] })}
className="w-full bg-black border-2 border-red-500/50 px-3 py-2 text-red-500 font-mono focus:border-red-500 focus:outline-none"
>
<option value="need">Need</option>
<option value="want">Want</option>
</select>
</div>
<div>
<label htmlFor="allocation_type" className="block text-xs font-mono uppercase text-red-500/60 mb-1">
ALLOCATION TYPE
</label>
<select
id="allocation_type"
value={formData.allocation_type}
onChange={(e) => setFormData({ ...formData, allocation_type: e.target.value })}
className="w-full bg-black border-2 border-red-500/50 px-3 py-2 text-red-500 font-mono focus:border-red-500 focus:outline-none"
>
<option value="fixed_limit">Fixed Limit</option>
<option value="percentage">Percentage</option>
</select>
</div>
{formData.allocation_type !== 'unlimited' && (
<div>
<label htmlFor="allocation_value" className="block text-xs font-mono uppercase text-red-500/60 mb-1">
{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="w-full bg-black border-2 border-red-500/50 px-3 py-2 text-red-500 font-mono font-digital focus:border-red-500 focus:outline-none"
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>
)}
{formData.allocation_type === 'fixed_limit' && (
<div>
<label htmlFor="buffer_preset" className="block text-xs font-mono uppercase text-red-500/60 mb-1">
BUFFER
</label>
<select
id="buffer_preset"
value={formData.buffer_mode === 'custom' ? 'custom' : formData.buffer_multiplier}
onChange={(e) => {
if (e.target.value === 'custom') {
setFormData({ ...formData, buffer_mode: 'custom' });
} else {
setFormData({ ...formData, buffer_multiplier: e.target.value, buffer_mode: 'preset' });
}
}}
className="w-full bg-black border-2 border-red-500/50 px-3 py-2 text-red-500 font-mono focus:border-red-500 focus:outline-none"
>
<option value="0">None</option>
<option value="0.5">0.5x (50% extra)</option>
<option value="1">1x (100% extra)</option>
<option value="1.5">1.5x (150% extra)</option>
<option value="2">2x (200% extra)</option>
<option value="custom">Custom</option>
</select>
{formData.buffer_mode === 'custom' && (
<input
type="number"
id="buffer_multiplier"
value={formData.buffer_multiplier}
onChange={(e) => setFormData({ ...formData, buffer_multiplier: e.target.value })}
className="mt-2 w-full bg-black border-2 border-red-500/50 px-3 py-2 text-red-500 font-mono font-digital focus:border-red-500 focus:outline-none"
placeholder="e.g., 0.75"
step="0.01"
min="0"
/>
)}
</div>
)}
<div className="flex gap-3 pt-4">
<button
type="button"
onClick={() => {
setIsCreateModalOpen(false);
setFormData({ ...defaultFormData });
}}
className="flex-1 border-2 border-red-500/50 bg-black px-4 py-2 text-sm font-mono uppercase text-red-500/60 hover:border-red-500 hover:text-red-500 transition-colors"
disabled={isSubmitting}
>
CANCEL
</button>
<button
type="submit"
className="flex-1 border-2 border-red-500 bg-red-500 px-4 py-2 text-sm font-mono font-bold uppercase text-black hover:bg-red-400 transition-colors disabled:opacity-50"
disabled={isSubmitting}
>
{isSubmitting ? 'CREATING...' : 'CREATE'}
</button>
</div>
</form>
</div>
</div>
)}
{/* Edit Bucket Modal */}
{editingBucket && (
<div
className="fixed inset-0 bg-black/80 overflow-y-auto h-full w-full z-50 flex items-start justify-center pt-20"
onClick={(e) => { if (e.target === e.currentTarget) setEditingBucket(null); }}
>
<div className="border-4 border-red-500 bg-black p-8 w-96 glow-red">
<div className="flex items-center justify-between mb-6">
<h3 className="text-lg font-mono font-bold uppercase tracking-wider text-red-500">
EDIT BUCKET
</h3>
<button
onClick={() => setEditingBucket(null)}
className="text-red-500/60 hover:text-red-500 font-mono text-sm transition-colors"
>
CLOSE
</button>
</div>
<div className="space-y-4">
{/* Name */}
<div className="flex items-center justify-between">
<span className="text-xs font-mono uppercase text-red-500/60">NAME</span>
<InlineEditInput
type="text"
value={editingBucket.name}
onSave={(val) => patchBucket(editingBucket.id, { name: val })}
className="text-red-500 font-mono font-bold"
/>
</div>
{/* Type */}
<div className="flex items-center justify-between">
<span className="text-xs font-mono uppercase text-red-500/60">TYPE</span>
<InlineEditSelect
value={editingBucket.type}
options={bucketTypeOptions}
onSave={(val) => patchBucket(editingBucket.id, { type: val })}
displayLabel={editingBucket.type_label}
disabled={editingBucket.type === 'overflow'}
className="text-red-500 font-mono"
/>
</div>
{/* Allocation Type */}
<div className="flex items-center justify-between">
<span className="text-xs font-mono uppercase text-red-500/60">ALLOCATION</span>
<InlineEditSelect
value={editingBucket.allocation_type}
options={allocationTypeOptions}
onSave={(val) => patchBucket(editingBucket.id, { allocation_type: val, allocation_value: null })}
displayLabel={editingBucket.allocation_type_label}
disabled={editingBucket.type === 'overflow'}
className="text-red-500 font-mono"
/>
</div>
{/* Allocation Value */}
{editingBucket.allocation_type !== 'unlimited' && (
<div className="flex items-center justify-between">
<span className="text-xs font-mono uppercase text-red-500/60">VALUE</span>
<span className="font-digital text-red-500">
{editingBucket.allocation_type === 'fixed_limit' ? (
<InlineEditInput
value={centsToDollars(editingBucket.allocation_value ?? 0)}
onSave={(val) => patchBucket(editingBucket.id, { allocation_value: dollarsToCents(val) })}
formatDisplay={(v) => `$${v.toFixed(2)}`}
min={0}
step="0.01"
/>
) : (
<InlineEditInput
value={basisPointsToPercent(editingBucket.allocation_value ?? 0)}
onSave={(val) => patchBucket(editingBucket.id, { allocation_value: percentToBasisPoints(val) })}
formatDisplay={(v) => `${v.toFixed(2)}%`}
min={0}
step="0.01"
/>
)}
</span>
</div>
)}
{/* Current Balance */}
<div className="flex items-center justify-between">
<span className="text-xs font-mono uppercase text-red-500/60">CURRENT</span>
<InlineEditInput
value={centsToDollars(editingBucket.starting_amount)}
onSave={(val) => patchBucket(editingBucket.id, { starting_amount: dollarsToCents(val) })}
formatDisplay={(v) => `$${v.toFixed(2)}`}
min={0}
step="0.01"
className="font-digital text-red-500"
/>
</div>
{/* Buffer */}
{editingBucket.allocation_type === 'fixed_limit' && (
<div className="flex items-center justify-between">
<span className="text-xs font-mono uppercase text-red-500/60">BUFFER</span>
<InlineEditInput
value={editingBucket.buffer_multiplier}
onSave={(val) => patchBucket(editingBucket.id, { buffer_multiplier: val })}
formatDisplay={(v) => v > 0 ? `${v}x` : 'NONE'}
min={0}
step="0.01"
className="font-digital text-red-500"
/>
</div>
)}
{/* Priority */}
<div className="flex items-center justify-between">
<span className="text-xs font-mono uppercase text-red-500/60">PRIORITY</span>
<div className="flex items-center gap-2">
<button
onClick={() => handlePriorityChange(editingBucket.id, 'up')}
disabled={editingBucket.priority === 1}
className="px-2 py-1 border border-red-500/50 text-red-500 font-mono text-xs hover:bg-red-500/20 disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
>
UP
</button>
<span className="font-digital text-red-500">#{editingBucket.priority}</span>
<button
onClick={() => handlePriorityChange(editingBucket.id, 'down')}
disabled={editingBucket.priority === buckets.data.length}
className="px-2 py-1 border border-red-500/50 text-red-500 font-mono text-xs hover:bg-red-500/20 disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
>
DOWN
</button>
</div>
</div>
{/* Delete */}
{editingBucket.type !== 'overflow' && (
<div className="pt-4 border-t border-red-500/20">
<button
onClick={() => handleDelete(editingBucket)}
className="text-red-500/40 text-xs font-mono uppercase hover:text-red-500 transition-colors"
>
DELETE BUCKET
</button>
</div>
)}
</div>
</div>
</div>
)}
</>
);
}