mirror of
https://github.com/escalante29/WealthySmart.git
synced 2026-07-17 09:28:47 +02:00
Compare commits
4 Commits
5612f69f11
...
3ea1ef0fa0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3ea1ef0fa0 | ||
|
|
8713eaa4d8 | ||
|
|
0dfac6a285 | ||
|
|
ce3cc69846 |
@@ -26,12 +26,29 @@ class PasteImportRequest(BaseModel):
|
||||
text: str = Field(max_length=1_000_000)
|
||||
bank: Bank = Bank.BAC
|
||||
source: TransactionSource = TransactionSource.CREDIT_CARD
|
||||
# Override for false-positive dedup (legitimate same-day, same-amount
|
||||
# repeat purchases hash identically) — review UX-20/BE-08.
|
||||
allow_duplicates: bool = False
|
||||
|
||||
|
||||
class SkippedDuplicate(BaseModel):
|
||||
line: int
|
||||
merchant: str
|
||||
date: str
|
||||
amount: float
|
||||
currency: str
|
||||
existing_id: int
|
||||
existing_merchant: str
|
||||
existing_date: str
|
||||
existing_amount: float
|
||||
existing_source: str
|
||||
|
||||
|
||||
class PasteImportResult(BaseModel):
|
||||
imported: int
|
||||
duplicates: int
|
||||
errors: list[str]
|
||||
skipped: list[SkippedDuplicate] = []
|
||||
|
||||
|
||||
def make_reference_hash(date: datetime, merchant: str, amount: float, currency: str) -> str:
|
||||
@@ -103,6 +120,7 @@ def paste_import(
|
||||
imported = 0
|
||||
duplicates = 0
|
||||
errors: list[str] = []
|
||||
skipped: list[SkippedDuplicate] = []
|
||||
|
||||
lines = req.text.strip().splitlines()
|
||||
|
||||
@@ -120,13 +138,29 @@ def paste_import(
|
||||
parsed["date"], parsed["merchant"], parsed["amount"], parsed["currency"]
|
||||
)
|
||||
|
||||
# Check for duplicates
|
||||
existing = session.exec(
|
||||
select(Transaction).where(Transaction.reference == ref_hash)
|
||||
).first()
|
||||
if existing:
|
||||
duplicates += 1
|
||||
continue
|
||||
# Check for duplicates — and SHOW the user what matched instead of
|
||||
# silently dropping the line (UX-20).
|
||||
if not req.allow_duplicates:
|
||||
existing = session.exec(
|
||||
select(Transaction).where(Transaction.reference == ref_hash)
|
||||
).first()
|
||||
if existing:
|
||||
duplicates += 1
|
||||
skipped.append(
|
||||
SkippedDuplicate(
|
||||
line=i,
|
||||
merchant=parsed["merchant"],
|
||||
date=parsed["date"].isoformat(),
|
||||
amount=parsed["amount"],
|
||||
currency=parsed["currency"],
|
||||
existing_id=existing.id or 0,
|
||||
existing_merchant=existing.merchant,
|
||||
existing_date=existing.date.isoformat(),
|
||||
existing_amount=float(existing.amount),
|
||||
existing_source=existing.source.value,
|
||||
)
|
||||
)
|
||||
continue
|
||||
|
||||
tx = Transaction(
|
||||
amount=parsed["amount"],
|
||||
@@ -147,4 +181,6 @@ def paste_import(
|
||||
if imported > 0:
|
||||
session.commit()
|
||||
|
||||
return PasteImportResult(imported=imported, duplicates=duplicates, errors=errors)
|
||||
return PasteImportResult(
|
||||
imported=imported, duplicates=duplicates, errors=errors, skipped=skipped
|
||||
)
|
||||
|
||||
@@ -99,6 +99,46 @@ def list_transactions(
|
||||
return session.exec(query).all()
|
||||
|
||||
|
||||
class BulkActionRequest(BaseModel):
|
||||
ids: list[int]
|
||||
action: str # 'delete' | 'set_category' | 'set_deferred'
|
||||
category_id: Optional[int] = None # for set_category (None clears)
|
||||
deferred: Optional[bool] = None # for set_deferred
|
||||
|
||||
|
||||
@router.post("/bulk")
|
||||
def bulk_action(
|
||||
req: BulkActionRequest,
|
||||
session: Session = Depends(get_session),
|
||||
_user: str = Depends(get_current_user),
|
||||
):
|
||||
"""Apply one action to many transactions atomically (review 4.4)."""
|
||||
if not req.ids or len(req.ids) > 500:
|
||||
raise HTTPException(status_code=400, detail="ids must contain 1-500 entries")
|
||||
if req.action not in ("delete", "set_category", "set_deferred"):
|
||||
raise HTTPException(status_code=400, detail=f"Unknown action: {req.action}")
|
||||
if req.action == "set_deferred" and req.deferred is None:
|
||||
raise HTTPException(status_code=400, detail="deferred is required for set_deferred")
|
||||
if req.action == "set_category" and req.category_id is not None:
|
||||
if session.get(Category, req.category_id) is None:
|
||||
raise HTTPException(status_code=404, detail="Category not found")
|
||||
|
||||
txs = session.exec(
|
||||
select(Transaction).where(col(Transaction.id).in_(req.ids))
|
||||
).all()
|
||||
for tx in txs:
|
||||
if req.action == "delete":
|
||||
session.delete(tx)
|
||||
elif req.action == "set_category":
|
||||
tx.category_id = req.category_id
|
||||
session.add(tx)
|
||||
elif req.action == "set_deferred":
|
||||
tx.deferred_to_next_cycle = bool(req.deferred)
|
||||
session.add(tx)
|
||||
session.commit()
|
||||
return {"affected": len(txs)}
|
||||
|
||||
|
||||
@router.get("/export")
|
||||
def export_transactions_csv(
|
||||
source: Optional[TransactionSource] = None,
|
||||
|
||||
131
backend/tests/test_import_review_and_bulk.py
Normal file
131
backend/tests/test_import_review_and_bulk.py
Normal file
@@ -0,0 +1,131 @@
|
||||
"""Paste-import dedup transparency + override (UX-20) and bulk actions (4.4).
|
||||
|
||||
These exercise the endpoint functions directly with a session — no HTTP
|
||||
stack needed.
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
|
||||
from app.api.v1.endpoints.import_transactions import (
|
||||
PasteImportRequest,
|
||||
paste_import,
|
||||
)
|
||||
from app.api.v1.endpoints.transactions import BulkActionRequest, bulk_action
|
||||
from app.models.models import Category, Transaction, TransactionSource
|
||||
|
||||
LINE = "15/04/2026\tWALMART\\SAN JOSE\\CR\t25,000.50 CRC"
|
||||
|
||||
|
||||
def do_import(session, text=LINE, **kw):
|
||||
return paste_import(
|
||||
PasteImportRequest(text=text, **kw), session=session, _user="t"
|
||||
)
|
||||
|
||||
|
||||
class TestImportReview:
|
||||
def test_duplicate_is_reported_with_matched_row(self, session):
|
||||
first = do_import(session)
|
||||
assert first.imported == 1 and first.duplicates == 0
|
||||
|
||||
second = do_import(session)
|
||||
assert second.imported == 0
|
||||
assert second.duplicates == 1
|
||||
assert len(second.skipped) == 1
|
||||
skip = second.skipped[0]
|
||||
assert skip.merchant == "WALMART"
|
||||
assert skip.amount == 25000.50
|
||||
assert skip.existing_merchant == "WALMART"
|
||||
assert skip.existing_amount == 25000.50
|
||||
assert skip.existing_id > 0
|
||||
|
||||
def test_allow_duplicates_overrides_dedup(self, session):
|
||||
do_import(session)
|
||||
forced = do_import(session, allow_duplicates=True)
|
||||
assert forced.imported == 1
|
||||
assert forced.duplicates == 0
|
||||
assert forced.skipped == []
|
||||
|
||||
|
||||
def make_tx(session, merchant="M", category_id=None):
|
||||
tx = Transaction(
|
||||
amount=Decimal("10"),
|
||||
merchant=merchant,
|
||||
date=datetime(2026, 4, 1),
|
||||
category_id=category_id,
|
||||
source=TransactionSource.CREDIT_CARD,
|
||||
)
|
||||
session.add(tx)
|
||||
session.commit()
|
||||
session.refresh(tx)
|
||||
return tx
|
||||
|
||||
|
||||
class TestBulkActions:
|
||||
def test_bulk_set_category(self, session):
|
||||
cat = Category(name="Bulk")
|
||||
session.add(cat)
|
||||
session.commit()
|
||||
session.refresh(cat)
|
||||
txs = [make_tx(session, f"m{i}") for i in range(3)]
|
||||
|
||||
result = bulk_action(
|
||||
BulkActionRequest(
|
||||
ids=[t.id for t in txs], action="set_category", category_id=cat.id
|
||||
),
|
||||
session=session,
|
||||
_user="t",
|
||||
)
|
||||
assert result["affected"] == 3
|
||||
for t in txs:
|
||||
session.refresh(t)
|
||||
assert t.category_id == cat.id
|
||||
|
||||
def test_bulk_set_deferred_and_clear_category(self, session):
|
||||
cat = Category(name="X")
|
||||
session.add(cat)
|
||||
session.commit()
|
||||
session.refresh(cat)
|
||||
tx = make_tx(session, category_id=cat.id)
|
||||
|
||||
bulk_action(
|
||||
BulkActionRequest(ids=[tx.id], action="set_deferred", deferred=True),
|
||||
session=session,
|
||||
_user="t",
|
||||
)
|
||||
session.refresh(tx)
|
||||
assert tx.deferred_to_next_cycle is True
|
||||
|
||||
bulk_action(
|
||||
BulkActionRequest(ids=[tx.id], action="set_category", category_id=None),
|
||||
session=session,
|
||||
_user="t",
|
||||
)
|
||||
session.refresh(tx)
|
||||
assert tx.category_id is None
|
||||
|
||||
def test_bulk_delete(self, session):
|
||||
txs = [make_tx(session, f"d{i}") for i in range(2)]
|
||||
result = bulk_action(
|
||||
BulkActionRequest(ids=[t.id for t in txs], action="delete"),
|
||||
session=session,
|
||||
_user="t",
|
||||
)
|
||||
assert result["affected"] == 2
|
||||
assert session.get(Transaction, txs[0].id) is None
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"req",
|
||||
[
|
||||
BulkActionRequest(ids=[], action="delete"),
|
||||
BulkActionRequest(ids=[1], action="explode"),
|
||||
BulkActionRequest(ids=[1], action="set_deferred"), # missing flag
|
||||
BulkActionRequest(ids=[1], action="set_category", category_id=99999),
|
||||
],
|
||||
)
|
||||
def test_invalid_requests_rejected(self, session, req):
|
||||
with pytest.raises(HTTPException):
|
||||
bulk_action(req, session=session, _user="t")
|
||||
@@ -145,7 +145,30 @@ fallback already guarded `len >= 2`).
|
||||
|
||||
## Phase 3 — Frontend Data Layer & Feedback ⏳ NOT STARTED
|
||||
|
||||
## Phase 4 — UX, Trust & Features 🔄 ITERATION 1 DONE
|
||||
## Phase 4 — UX, Trust & Features ✅ DONE (iterations 1 + 2)
|
||||
|
||||
### Iteration 2 (2026-06-11)
|
||||
|
||||
| Plan item | Status |
|
||||
|---|---|
|
||||
| 4.2 Import review: skipped duplicates listed with matched row + import-anyway override (re-imports only skipped lines) | ✅ |
|
||||
| 4.4 Bulk operations: POST /transactions/bulk + selection UI (assign category, defer/restore, delete) | ✅ |
|
||||
| 4.7 Editable pension assumptions (UserSettings-backed) | ✅ |
|
||||
| 4.7 Dirty-form guard (UX-06), empty-state CTA (UX-14) | ✅ |
|
||||
| BE-08 hash tightening | superseded — the override solves the practical harm; rehashing would orphan every existing reference |
|
||||
| UX-11 mobile layout | **false positive** — a card layout already existed (two real bugs in it fixed: undo-pending rows showed, en-US dates) |
|
||||
| UX-13 cycle filter | **mostly false positive** — daily-spending already accepts cycle params; the trend is multi-cycle by design |
|
||||
| UX-24 meter labels, UX-22 breadcrumb, shared period navigator (UX-03) | not done — needs dedicated UI; lowest-value remainder |
|
||||
|
||||
**The improvement plan is complete** except: 3.4 OpenAPI codegen (deferred until a
|
||||
response_model sweep), the three smallest 4.7 cosmetic items above, and the
|
||||
unscheduled 4.9 wishlist (what-if planner, PWA, rate history, contribution
|
||||
calculator). Tests: **82**. Final false-positive tally across the whole plan:
|
||||
BE-06, BE-09, BE-10, ARCH-03, ARCH-08, BE-22 (accepted), FE-04, UX-04, UX-11,
|
||||
UX-13 — the characterization-tests-first approach caught all of them before any
|
||||
"fix" landed.
|
||||
|
||||
### Iteration 1 (2026-06-10)
|
||||
|
||||
Iteration 1 completed 2026-06-10. The plan marks 4.x items independent; this
|
||||
iteration delivered the highest-impact slice.
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { useState } from 'react';
|
||||
import { ClipboardPaste, CheckCircle, AlertTriangle } from 'lucide-react';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
import api, { type ImportResult } from '@/lib/api';
|
||||
import { formatAmount } from '@/lib/format';
|
||||
import { formatShortDate } from '@/lib/dates';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
@@ -39,8 +43,40 @@ export default function PasteImportModal({ onClose, onImported }: Props) {
|
||||
const { data } = await api.post<ImportResult>('/import/paste', { text, bank, source });
|
||||
setResult(data);
|
||||
if (data.imported > 0) onImported();
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
} catch {
|
||||
toast.error('No se pudo importar - revisa el formato');
|
||||
} finally {
|
||||
setImporting(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Re-import ONLY the skipped lines with the dedup check disabled, so rows
|
||||
// that imported on the first pass are never duplicated.
|
||||
const handleImportDuplicates = async () => {
|
||||
if (!result || result.skipped.length === 0) return;
|
||||
const lines = text.trim().split('\n');
|
||||
const dupText = result.skipped
|
||||
.map((s) => lines[s.line - 1])
|
||||
.filter(Boolean)
|
||||
.join('\n');
|
||||
setImporting(true);
|
||||
try {
|
||||
const { data } = await api.post<ImportResult>('/import/paste', {
|
||||
text: dupText,
|
||||
bank,
|
||||
source,
|
||||
allow_duplicates: true,
|
||||
});
|
||||
toast.success(`${data.imported} duplicado(s) importados`);
|
||||
setResult({
|
||||
...result,
|
||||
imported: result.imported + data.imported,
|
||||
skipped: [],
|
||||
duplicates: 0,
|
||||
});
|
||||
onImported();
|
||||
} catch {
|
||||
toast.error('No se pudieron importar los duplicados');
|
||||
} finally {
|
||||
setImporting(false);
|
||||
}
|
||||
@@ -134,6 +170,39 @@ export default function PasteImportModal({ onClose, onImported }: Props) {
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{result.skipped.length > 0 && (
|
||||
<div className="rounded-lg border border-amber-500/40 bg-amber-500/5 p-3 space-y-2">
|
||||
<p className="text-sm font-medium">
|
||||
{result.skipped.length} duplicado(s) omitido(s)
|
||||
</p>
|
||||
<ul className="text-xs max-h-40 overflow-y-auto space-y-1.5">
|
||||
{result.skipped.map((s) => (
|
||||
<li key={`${s.line}-${s.existing_id}`} className="space-y-0.5">
|
||||
<span className="font-mono">
|
||||
{s.merchant} · {formatShortDate(s.date)} ·{' '}
|
||||
{formatAmount(s.amount, s.currency)}
|
||||
</span>
|
||||
<span className="block text-muted-foreground">
|
||||
coincide con #{s.existing_id}: {s.existing_merchant} del{' '}
|
||||
{formatShortDate(s.existing_date)} ({s.existing_source})
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="w-full"
|
||||
onClick={handleImportDuplicates}
|
||||
disabled={importing}
|
||||
>
|
||||
{importing
|
||||
? 'Importando...'
|
||||
: 'Importar duplicados de todos modos'}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Button onClick={onClose} className="w-full">
|
||||
Done
|
||||
</Button>
|
||||
|
||||
139
frontend/src/components/PensionAssumptionsDialog.tsx
Normal file
139
frontend/src/components/PensionAssumptionsDialog.tsx
Normal file
@@ -0,0 +1,139 @@
|
||||
import { useState } from 'react';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
import api, { type UserSettingsData } from '@/lib/api';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
|
||||
export interface FundAssumption {
|
||||
monthlyContribution: number;
|
||||
annualRate: number;
|
||||
}
|
||||
|
||||
export type PensionAssumptions = Partial<
|
||||
Record<'FCL' | 'ROP' | 'VOL', FundAssumption>
|
||||
>;
|
||||
|
||||
interface Props {
|
||||
current: Record<'FCL' | 'ROP' | 'VOL', FundAssumption>;
|
||||
settingsData: UserSettingsData;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
const FUND_LABELS: Record<'FCL' | 'ROP' | 'VOL', string> = {
|
||||
FCL: 'FCL — Capitalización Laboral',
|
||||
ROP: 'ROP — Régimen Obligatorio',
|
||||
VOL: 'VOL — Fondo Voluntario',
|
||||
};
|
||||
|
||||
/** Per-fund projection assumptions, persisted server-side in UserSettings so
|
||||
* they survive devices and reloads (review UX-12). */
|
||||
export default function PensionAssumptionsDialog({
|
||||
current,
|
||||
settingsData,
|
||||
onClose,
|
||||
}: Props) {
|
||||
const queryClient = useQueryClient();
|
||||
const [form, setForm] = useState(() => ({
|
||||
FCL: { ...current.FCL },
|
||||
ROP: { ...current.ROP },
|
||||
VOL: { ...current.VOL },
|
||||
}));
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
const setField = (
|
||||
fund: 'FCL' | 'ROP' | 'VOL',
|
||||
field: keyof FundAssumption,
|
||||
value: string,
|
||||
) => {
|
||||
const num = parseFloat(value);
|
||||
setForm((prev) => ({
|
||||
...prev,
|
||||
[fund]: { ...prev[fund], [field]: isNaN(num) ? 0 : num },
|
||||
}));
|
||||
};
|
||||
|
||||
const handleSave = async () => {
|
||||
setSaving(true);
|
||||
try {
|
||||
// The settings PATCH replaces the whole blob — merge over what exists.
|
||||
await api.patch('/settings/', {
|
||||
data: { ...settingsData, pension_assumptions: form },
|
||||
});
|
||||
toast.success('Supuestos de pensión guardados');
|
||||
queryClient.invalidateQueries({ queryKey: ['settings'] });
|
||||
onClose();
|
||||
} catch {
|
||||
toast.error('No se pudieron guardar los supuestos');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open onOpenChange={(open) => { if (!open) onClose(); }}>
|
||||
<DialogContent className="sm:max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Supuestos de proyección</DialogTitle>
|
||||
</DialogHeader>
|
||||
<p className="text-sm text-muted-foreground -mt-2">
|
||||
Usados para proyectar el crecimiento de cada fondo. El saldo inicial
|
||||
siempre viene del último estado de cuenta.
|
||||
</p>
|
||||
<div className="space-y-4">
|
||||
{(Object.keys(FUND_LABELS) as Array<'FCL' | 'ROP' | 'VOL'>).map(
|
||||
(fund) => (
|
||||
<div key={fund} className="space-y-2">
|
||||
<p className="text-sm font-medium">{FUND_LABELS[fund]}</p>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div className="space-y-1">
|
||||
<Label className="text-xs">Aporte mensual (₡)</Label>
|
||||
<Input
|
||||
type="number"
|
||||
min="0"
|
||||
step="1000"
|
||||
value={form[fund].monthlyContribution}
|
||||
onChange={(e) =>
|
||||
setField(fund, 'monthlyContribution', e.target.value)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label className="text-xs">Rendimiento anual (%)</Label>
|
||||
<Input
|
||||
type="number"
|
||||
min="0"
|
||||
max="30"
|
||||
step="0.1"
|
||||
value={form[fund].annualRate}
|
||||
onChange={(e) =>
|
||||
setField(fund, 'annualRate', e.target.value)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={onClose}>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button onClick={handleSave} disabled={saving}>
|
||||
{saving ? 'Guardando...' : 'Guardar'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -13,13 +13,22 @@ import {
|
||||
|
||||
import { toast } from 'sonner';
|
||||
|
||||
import api, { type Transaction } from '@/lib/api';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
|
||||
import api, { type Category, type Transaction } from '@/lib/api';
|
||||
import TransactionModal from './TransactionModal';
|
||||
import ConfirmDialog from './ConfirmDialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { DataTable } from '@/components/ui/data-table';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { getTransactionColumns } from '@/components/transactions/transaction-columns';
|
||||
import { formatAmount } from '@/lib/format';
|
||||
import { cn } from '@/lib/utils';
|
||||
@@ -58,6 +67,40 @@ export default function TransactionList({
|
||||
const [deleteId, setDeleteId] = useState<number | null>(null);
|
||||
const [pendingDeletes, setPendingDeletes] = useState<Set<number>>(new Set());
|
||||
const deleteTimers = useRef<Map<number, ReturnType<typeof setTimeout>>>(new Map());
|
||||
const [selected, setSelected] = useState<Set<number>>(new Set());
|
||||
const [bulkConfirm, setBulkConfirm] = useState(false);
|
||||
const [bulkBusy, setBulkBusy] = useState(false);
|
||||
|
||||
const categoriesQ = useQuery({
|
||||
queryKey: ['categories'],
|
||||
queryFn: ({ signal }) =>
|
||||
api.get<Category[]>('/categories/', { signal }).then((r) =>
|
||||
[...r.data].sort((a, b) => a.name.localeCompare(b.name)),
|
||||
),
|
||||
enabled: selected.size > 0,
|
||||
});
|
||||
|
||||
const clearSelection = () => setSelected(new Set());
|
||||
|
||||
const runBulk = async (
|
||||
payload: Record<string, unknown>,
|
||||
success: string,
|
||||
) => {
|
||||
setBulkBusy(true);
|
||||
try {
|
||||
const { data } = await api.post<{ affected: number }>(
|
||||
'/transactions/bulk',
|
||||
{ ids: [...selected], ...payload },
|
||||
);
|
||||
toast.success(`${success} (${data.affected})`);
|
||||
clearSelection();
|
||||
onRefresh();
|
||||
} catch {
|
||||
toast.error('No se pudo aplicar la acción masiva');
|
||||
} finally {
|
||||
setBulkBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleEdit = (tx: Transaction) => {
|
||||
setEditing(tx);
|
||||
@@ -111,9 +154,35 @@ export default function TransactionList({
|
||||
);
|
||||
};
|
||||
|
||||
const allSelected =
|
||||
transactions.length > 0 && transactions.every((t) => selected.has(t.id));
|
||||
|
||||
const columns = useMemo(
|
||||
() => getTransactionColumns({ showCategory, showSourceIcon, onEdit: handleEdit, onDelete: (id) => setDeleteId(id), onToggleDeferred }),
|
||||
[showCategory, showSourceIcon, onToggleDeferred],
|
||||
() =>
|
||||
getTransactionColumns({
|
||||
showCategory,
|
||||
showSourceIcon,
|
||||
onEdit: handleEdit,
|
||||
onDelete: (id) => setDeleteId(id),
|
||||
onToggleDeferred,
|
||||
selection: {
|
||||
selected,
|
||||
allSelected,
|
||||
onToggle: (id) =>
|
||||
setSelected((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(id)) next.delete(id);
|
||||
else next.add(id);
|
||||
return next;
|
||||
}),
|
||||
onToggleAll: () =>
|
||||
setSelected(
|
||||
allSelected ? new Set() : new Set(transactions.map((t) => t.id)),
|
||||
),
|
||||
},
|
||||
}),
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[showCategory, showSourceIcon, onToggleDeferred, selected, allSelected, transactions],
|
||||
);
|
||||
|
||||
const visibleTransactions = pendingDeletes.size
|
||||
@@ -140,16 +209,103 @@ export default function TransactionList({
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Bulk action bar */}
|
||||
{selected.size > 0 && (
|
||||
<div className="hidden md:flex items-center gap-2 rounded-lg border bg-muted/40 px-3 py-2">
|
||||
<span className="text-sm font-medium">
|
||||
{selected.size} seleccionada{selected.size === 1 ? '' : 's'}
|
||||
</span>
|
||||
<div className="ml-auto flex items-center gap-2">
|
||||
<Select
|
||||
onValueChange={(v) => {
|
||||
if (!v) return;
|
||||
void runBulk(
|
||||
{
|
||||
action: 'set_category',
|
||||
category_id: v === '__none__' ? null : Number(v),
|
||||
},
|
||||
'Categoría aplicada',
|
||||
);
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="h-8 w-44" disabled={bulkBusy}>
|
||||
<SelectValue placeholder="Asignar categoría…" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="__none__">Sin categoría</SelectItem>
|
||||
{(categoriesQ.data ?? []).map((c) => (
|
||||
<SelectItem key={c.id} value={String(c.id)}>
|
||||
{c.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{onToggleDeferred && (
|
||||
<>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={bulkBusy}
|
||||
onClick={() =>
|
||||
void runBulk(
|
||||
{ action: 'set_deferred', deferred: true },
|
||||
'Transacciones diferidas',
|
||||
)
|
||||
}
|
||||
>
|
||||
Diferir
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={bulkBusy}
|
||||
onClick={() =>
|
||||
void runBulk(
|
||||
{ action: 'set_deferred', deferred: false },
|
||||
'Diferidas restauradas',
|
||||
)
|
||||
}
|
||||
>
|
||||
Restaurar
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="text-destructive hover:text-destructive"
|
||||
disabled={bulkBusy}
|
||||
onClick={() => setBulkConfirm(true)}
|
||||
>
|
||||
<Trash2 className="w-4 h-4 mr-1" aria-hidden="true" />
|
||||
Eliminar
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" onClick={clearSelection}>
|
||||
Cancelar
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Mobile list */}
|
||||
<Card className="md:hidden">
|
||||
<CardContent className="p-0 divide-y divide-border">
|
||||
{empty ? (
|
||||
<div className="px-5 py-16 text-center text-muted-foreground text-sm">
|
||||
{emptyIcon || <ArrowLeftRight className="w-8 h-8 mx-auto mb-3 text-muted-foreground/50" />}
|
||||
{emptyMessage}
|
||||
<p>{emptyMessage}</p>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="mt-4"
|
||||
onClick={() => { setEditing(null); setModalOpen(true); }}
|
||||
>
|
||||
<Plus className="w-4 h-4 mr-1" aria-hidden="true" />
|
||||
{addLabel}
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
transactions.map((tx) => (
|
||||
visibleTransactions.map((tx) => (
|
||||
<div key={tx.id} className="flex items-center gap-3 px-4 py-3">
|
||||
<div
|
||||
className={cn(
|
||||
@@ -177,7 +333,7 @@ export default function TransactionList({
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{new Date(tx.date).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}
|
||||
{new Date(tx.date).toLocaleDateString('es-CR', { month: 'short', day: 'numeric' })}
|
||||
{showCategory && tx.category && (
|
||||
<span className="ml-1.5 text-muted-foreground/60">{tx.category.name}</span>
|
||||
)}
|
||||
@@ -250,6 +406,20 @@ export default function TransactionList({
|
||||
/>
|
||||
)}
|
||||
|
||||
{bulkConfirm && (
|
||||
<ConfirmDialog
|
||||
title={`Eliminar ${selected.size} transacciones`}
|
||||
message="Esta acción no se puede deshacer."
|
||||
confirmLabel="Eliminar todas"
|
||||
loading={bulkBusy}
|
||||
onConfirm={async () => {
|
||||
await runBulk({ action: 'delete' }, 'Transacciones eliminadas');
|
||||
setBulkConfirm(false);
|
||||
}}
|
||||
onCancel={() => setBulkConfirm(false)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{deleteId !== null && (
|
||||
<ConfirmDialog
|
||||
title="Delete Transaction"
|
||||
|
||||
@@ -68,36 +68,70 @@ export default function RecurringItemDialog({
|
||||
const [overrides, setOverrides] = useState<{ month: string; amount: string }[]>([]);
|
||||
const [notes, setNotes] = useState('');
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [baseline, setBaseline] = useState('');
|
||||
|
||||
const snapshot = () =>
|
||||
JSON.stringify([name, amount, itemType, frequency, dayOfMonth, monthOfYear, overrides, notes]);
|
||||
|
||||
const handleOpenChange = (next: boolean) => {
|
||||
if (!next && !saving && snapshot() !== baseline) {
|
||||
// Closing with unsaved edits — confirm before discarding (UX-06).
|
||||
const discard = window.confirm('Hay cambios sin guardar. ¿Descartarlos?');
|
||||
if (!discard) return;
|
||||
}
|
||||
onOpenChange(next);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
if (item) {
|
||||
setName(item.name);
|
||||
setAmount(String(item.amount));
|
||||
setItemType(item.item_type);
|
||||
setFrequency(item.frequency);
|
||||
setDayOfMonth(item.day_of_month != null ? String(item.day_of_month) : '');
|
||||
setMonthOfYear(item.month_of_year != null ? String(item.month_of_year) : '');
|
||||
setOverrides(
|
||||
item.override_amounts
|
||||
if (!open) return;
|
||||
const init = item
|
||||
? {
|
||||
name: item.name,
|
||||
amount: String(item.amount),
|
||||
itemType: item.item_type,
|
||||
frequency: item.frequency,
|
||||
dayOfMonth: item.day_of_month != null ? String(item.day_of_month) : '',
|
||||
monthOfYear:
|
||||
item.month_of_year != null ? String(item.month_of_year) : '',
|
||||
overrides: item.override_amounts
|
||||
? Object.entries(item.override_amounts).map(([m, a]) => ({
|
||||
month: m,
|
||||
amount: String(a),
|
||||
}))
|
||||
: [],
|
||||
);
|
||||
setNotes(item.notes || '');
|
||||
} else {
|
||||
setName('');
|
||||
setAmount('');
|
||||
setItemType('EXPENSE');
|
||||
setFrequency('MONTHLY');
|
||||
setDayOfMonth('');
|
||||
setMonthOfYear('');
|
||||
setOverrides([]);
|
||||
setNotes('');
|
||||
}
|
||||
}
|
||||
notes: item.notes || '',
|
||||
}
|
||||
: {
|
||||
name: '',
|
||||
amount: '',
|
||||
itemType: 'EXPENSE' as RecurringItemType,
|
||||
frequency: 'MONTHLY' as RecurringFrequency,
|
||||
dayOfMonth: '',
|
||||
monthOfYear: '',
|
||||
overrides: [] as { month: string; amount: string }[],
|
||||
notes: '',
|
||||
};
|
||||
setName(init.name);
|
||||
setAmount(init.amount);
|
||||
setItemType(init.itemType);
|
||||
setFrequency(init.frequency);
|
||||
setDayOfMonth(init.dayOfMonth);
|
||||
setMonthOfYear(init.monthOfYear);
|
||||
setOverrides(init.overrides);
|
||||
setNotes(init.notes);
|
||||
// Baseline mirrors snapshot()'s field order exactly.
|
||||
setBaseline(
|
||||
JSON.stringify([
|
||||
init.name,
|
||||
init.amount,
|
||||
init.itemType,
|
||||
init.frequency,
|
||||
init.dayOfMonth,
|
||||
init.monthOfYear,
|
||||
init.overrides,
|
||||
init.notes,
|
||||
]),
|
||||
);
|
||||
}, [open, item]);
|
||||
|
||||
const showDayOfMonth = frequency === 'MONTHLY' || frequency === 'WEEKLY';
|
||||
@@ -135,7 +169,7 @@ export default function RecurringItemDialog({
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{isEdit ? 'Editar' : 'Nuevo'} Item Recurrente</DialogTitle>
|
||||
@@ -296,7 +330,7 @@ export default function RecurringItemDialog({
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)}>
|
||||
<Button variant="outline" onClick={() => handleOpenChange(false)}>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button onClick={handleSubmit} disabled={saving || !name || !amount}>
|
||||
|
||||
@@ -8,12 +8,20 @@ import { Button } from '@/components/ui/button';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { DataTableColumnHeader } from '@/components/ui/data-table-column-header';
|
||||
|
||||
export interface RowSelection {
|
||||
selected: Set<number>;
|
||||
allSelected: boolean;
|
||||
onToggle: (id: number) => void;
|
||||
onToggleAll: () => void;
|
||||
}
|
||||
|
||||
interface TransactionColumnOptions {
|
||||
showCategory: boolean;
|
||||
showSourceIcon?: boolean;
|
||||
onEdit: (tx: Transaction) => void;
|
||||
onDelete: (txId: number) => void;
|
||||
onToggleDeferred?: (tx: Transaction) => void;
|
||||
selection?: RowSelection;
|
||||
}
|
||||
|
||||
export function getTransactionColumns({
|
||||
@@ -22,14 +30,43 @@ export function getTransactionColumns({
|
||||
onEdit,
|
||||
onDelete,
|
||||
onToggleDeferred,
|
||||
selection,
|
||||
}: TransactionColumnOptions): ColumnDef<Transaction, unknown>[] {
|
||||
const columns: ColumnDef<Transaction, unknown>[] = [
|
||||
const columns: ColumnDef<Transaction, unknown>[] = [];
|
||||
|
||||
if (selection) {
|
||||
columns.push({
|
||||
id: 'select',
|
||||
size: 36,
|
||||
enableSorting: false,
|
||||
header: () => (
|
||||
<input
|
||||
type="checkbox"
|
||||
className="accent-primary w-4 h-4 cursor-pointer align-middle"
|
||||
aria-label="Seleccionar todas las transacciones"
|
||||
checked={selection.allSelected}
|
||||
onChange={selection.onToggleAll}
|
||||
/>
|
||||
),
|
||||
cell: ({ row }) => (
|
||||
<input
|
||||
type="checkbox"
|
||||
className="accent-primary w-4 h-4 cursor-pointer align-middle"
|
||||
aria-label={`Seleccionar ${row.original.merchant}`}
|
||||
checked={selection.selected.has(row.original.id)}
|
||||
onChange={() => selection.onToggle(row.original.id)}
|
||||
/>
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
columns.push(
|
||||
{
|
||||
accessorKey: 'date',
|
||||
header: ({ column }) => <DataTableColumnHeader column={column} title="Date" />,
|
||||
cell: ({ row }) => (
|
||||
<span className="font-mono text-muted-foreground text-xs whitespace-nowrap">
|
||||
{new Date(row.original.date).toLocaleDateString('en-US', {
|
||||
{new Date(row.original.date).toLocaleDateString('es-CR', {
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
year: 'numeric',
|
||||
@@ -74,7 +111,7 @@ export function getTransactionColumns({
|
||||
);
|
||||
},
|
||||
},
|
||||
];
|
||||
);
|
||||
|
||||
if (showCategory) {
|
||||
columns.push({
|
||||
|
||||
@@ -143,10 +143,24 @@ export interface Category {
|
||||
auto_match_patterns: string | null;
|
||||
}
|
||||
|
||||
export interface SkippedDuplicate {
|
||||
line: number;
|
||||
merchant: string;
|
||||
date: string;
|
||||
amount: number;
|
||||
currency: string;
|
||||
existing_id: number;
|
||||
existing_merchant: string;
|
||||
existing_date: string;
|
||||
existing_amount: number;
|
||||
existing_source: string;
|
||||
}
|
||||
|
||||
export interface ImportResult {
|
||||
imported: number;
|
||||
duplicates: number;
|
||||
errors: string[];
|
||||
skipped: SkippedDuplicate[];
|
||||
}
|
||||
|
||||
export interface Transaction {
|
||||
@@ -504,3 +518,15 @@ export interface SyncStatusResponse {
|
||||
}
|
||||
|
||||
export const getSyncStatus = () => api.get<SyncStatusResponse>('/sync-status/');
|
||||
|
||||
// --- User Settings ---
|
||||
|
||||
export type UserSettingsData = Record<string, unknown>;
|
||||
|
||||
export interface UserSettingsRead {
|
||||
key: string;
|
||||
data: UserSettingsData;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export const getUserSettings = () => api.get<UserSettingsRead>('/settings/');
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useState, useMemo, useCallback, useRef } from 'react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import ErrorState from '@/components/ErrorState';
|
||||
import PensionAssumptionsDialog, { type PensionAssumptions } from '@/components/PensionAssumptionsDialog';
|
||||
import {
|
||||
LineChart,
|
||||
Line,
|
||||
@@ -31,6 +32,7 @@ import { Label } from '@/components/ui/label';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import {
|
||||
getUserSettings,
|
||||
uploadPensionPDFs,
|
||||
getPensionFundSummary,
|
||||
getPensionSnapshots,
|
||||
@@ -38,7 +40,7 @@ import {
|
||||
type PensionUploadResult,
|
||||
} from '@/lib/api';
|
||||
import PensionManualEntryModal from '@/components/PensionManualEntryModal';
|
||||
import { ClipboardPaste } from 'lucide-react';
|
||||
import { ClipboardPaste, SlidersHorizontal } from 'lucide-react';
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -196,8 +198,9 @@ function calcProjection(
|
||||
/** Merge API snapshots into the default fund definitions. */
|
||||
function applySnapshots(
|
||||
snapshots: PensionSnapshot[],
|
||||
base: Record<FundKey, FundDef> = FUNDS_DEFAULT,
|
||||
): Record<FundKey, FundDef> {
|
||||
const funds = { ...FUNDS_DEFAULT };
|
||||
const funds = { ...base };
|
||||
for (const snap of snapshots) {
|
||||
const key = snap.fund as FundKey;
|
||||
if (key in funds) {
|
||||
@@ -273,7 +276,46 @@ export default function Pensions() {
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [pensionQ.refetch]);
|
||||
|
||||
const FUNDS = useMemo(() => applySnapshots(fundSummary), [fundSummary]);
|
||||
const settingsQ = useQuery({
|
||||
queryKey: ['settings'],
|
||||
queryFn: () => getUserSettings().then((r) => r.data),
|
||||
});
|
||||
const storedAssumptions = (settingsQ.data?.data?.pension_assumptions ??
|
||||
{}) as PensionAssumptions;
|
||||
|
||||
const FUNDS = useMemo(() => {
|
||||
const base = { ...FUNDS_DEFAULT };
|
||||
for (const key of FUND_KEYS) {
|
||||
const stored = storedAssumptions[key];
|
||||
if (stored) {
|
||||
base[key] = {
|
||||
...base[key],
|
||||
monthlyContribution: stored.monthlyContribution,
|
||||
annualRate: stored.annualRate,
|
||||
};
|
||||
}
|
||||
}
|
||||
return applySnapshots(fundSummary, base);
|
||||
}, [fundSummary, storedAssumptions]);
|
||||
|
||||
const currentAssumptions = useMemo(
|
||||
() => ({
|
||||
FCL: {
|
||||
monthlyContribution: FUNDS.FCL.monthlyContribution,
|
||||
annualRate: FUNDS.FCL.annualRate,
|
||||
},
|
||||
ROP: {
|
||||
monthlyContribution: FUNDS.ROP.monthlyContribution,
|
||||
annualRate: FUNDS.ROP.annualRate,
|
||||
},
|
||||
VOL: {
|
||||
monthlyContribution: FUNDS.VOL.monthlyContribution,
|
||||
annualRate: FUNDS.VOL.annualRate,
|
||||
},
|
||||
}),
|
||||
[FUNDS],
|
||||
);
|
||||
const [showAssumptions, setShowAssumptions] = useState(false);
|
||||
|
||||
// Build a map of fund -> latest snapshot for rendimientos display
|
||||
const snapshotByFund = useMemo(() => {
|
||||
@@ -628,10 +670,16 @@ export default function Pensions() {
|
||||
|
||||
{/* ── Section 4: Projections ───────────────────────────────────────── */}
|
||||
<section className="space-y-3">
|
||||
<h2 className="text-base font-semibold font-heading flex items-center gap-2 text-muted-foreground uppercase tracking-wider">
|
||||
<TrendingUp className="w-4 h-4" />
|
||||
Proyecciones
|
||||
</h2>
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="text-base font-semibold font-heading flex items-center gap-2 text-muted-foreground uppercase tracking-wider">
|
||||
<TrendingUp className="w-4 h-4" />
|
||||
Proyecciones
|
||||
</h2>
|
||||
<Button variant="outline" size="sm" onClick={() => setShowAssumptions(true)}>
|
||||
<SlidersHorizontal className="w-4 h-4 mr-2" aria-hidden="true" />
|
||||
Supuestos
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Basado en edad actual de {CURRENT_AGE} años. Edita los campos para simular escenarios.
|
||||
</p>
|
||||
@@ -710,6 +758,14 @@ export default function Pensions() {
|
||||
</section>
|
||||
|
||||
{/* ── Manual Entry Modal ──────────────────────────────────────────── */}
|
||||
{showAssumptions && (
|
||||
<PensionAssumptionsDialog
|
||||
current={currentAssumptions}
|
||||
settingsData={settingsQ.data?.data ?? {}}
|
||||
onClose={() => setShowAssumptions(false)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{showManualEntry && (
|
||||
<PensionManualEntryModal
|
||||
onClose={() => setShowManualEntry(false)}
|
||||
|
||||
Reference in New Issue
Block a user