mirror of
https://github.com/escalante29/WealthySmart.git
synced 2026-07-17 11:48:46 +02:00
Adopt TanStack Query: provider, timeouts, useBudget, Budget page
QueryClientProvider (30s staleTime, 1 retry) + Sonner Toaster at the root. api.ts gains AbortSignal support and a default 30s timeout (FE-24); query cancellation kills the stale-response races (FE-01, FE-03). useBudget is now queries + mutations with targeted ['budget'] invalidation and success/error toasts on every mutation (ARCH-13, UX-01); month navigation keeps the previous month visible while fetching. Budget's transaction list is a cancellable query with placeholder data; deferred-toggle gets feedback (UX-05); both panels render a shared ErrorState with retry instead of failing silently. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,8 +1,19 @@
|
||||
import { BrowserRouter, Routes, Route, Navigate } from "react-router-dom";
|
||||
import { CopilotKit } from "@copilotkit/react-core";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { Toaster } from "sonner";
|
||||
import { AuthProvider, useAuth } from "./AuthContext";
|
||||
import { ThemeProvider } from "./contexts/theme-context";
|
||||
import { PrivacyProvider } from "./contexts/privacy-context";
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
staleTime: 30_000,
|
||||
retry: 1,
|
||||
},
|
||||
},
|
||||
});
|
||||
import Layout from "./components/Layout";
|
||||
import LoginPage from "./pages/Login";
|
||||
import Asistente from "./pages/Asistente";
|
||||
@@ -58,9 +69,12 @@ export default function App() {
|
||||
<ThemeProvider>
|
||||
<PrivacyProvider>
|
||||
<AuthProvider>
|
||||
<CopilotKit runtimeUrl="/api/copilotkit" agent="wealthysmart" a2ui={{}}>
|
||||
<AppRoutes />
|
||||
</CopilotKit>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<CopilotKit runtimeUrl="/api/copilotkit" agent="wealthysmart" a2ui={{}}>
|
||||
<AppRoutes />
|
||||
<Toaster richColors position="top-right" closeButton />
|
||||
</CopilotKit>
|
||||
</QueryClientProvider>
|
||||
</AuthProvider>
|
||||
</PrivacyProvider>
|
||||
</ThemeProvider>
|
||||
|
||||
28
frontend/src/components/ErrorState.tsx
Normal file
28
frontend/src/components/ErrorState.tsx
Normal file
@@ -0,0 +1,28 @@
|
||||
import { AlertTriangle, RotateCw } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
||||
interface Props {
|
||||
message?: string;
|
||||
onRetry?: () => void;
|
||||
}
|
||||
|
||||
export default function ErrorState({
|
||||
message = 'No se pudieron cargar los datos',
|
||||
onRetry,
|
||||
}: Props) {
|
||||
return (
|
||||
<div
|
||||
role="alert"
|
||||
className="flex flex-col items-center justify-center gap-3 rounded-lg border border-destructive/40 bg-destructive/5 p-8 text-center"
|
||||
>
|
||||
<AlertTriangle className="h-6 w-6 text-destructive" aria-hidden="true" />
|
||||
<p className="text-sm text-muted-foreground">{message}</p>
|
||||
{onRetry && (
|
||||
<Button variant="outline" size="sm" onClick={onRetry}>
|
||||
<RotateCw className="mr-2 h-4 w-4" aria-hidden="true" />
|
||||
Reintentar
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,8 +1,7 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useState } from 'react';
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { toast } from 'sonner';
|
||||
import {
|
||||
type YearlyProjection,
|
||||
type MonthlyDetail,
|
||||
type RecurringItem,
|
||||
type RecurringItemCreate,
|
||||
type RecurringItemUpdate,
|
||||
getYearlyProjection,
|
||||
@@ -15,89 +14,90 @@ import {
|
||||
deleteBalanceOverride,
|
||||
} from '@/lib/api';
|
||||
|
||||
/** All budget data hangs off the ['budget', ...] key family; every mutation
|
||||
* invalidates the family so projection, month detail and items stay in sync. */
|
||||
export function useBudget(initialYear: number) {
|
||||
const queryClient = useQueryClient();
|
||||
const [year, setYear] = useState(initialYear);
|
||||
const [selectedMonth, setSelectedMonth] = useState<number>(new Date().getMonth() + 1);
|
||||
const [projection, setProjection] = useState<YearlyProjection | null>(null);
|
||||
const [monthDetail, setMonthDetail] = useState<MonthlyDetail | null>(null);
|
||||
const [recurringItems, setRecurringItems] = useState<RecurringItem[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [monthLoading, setMonthLoading] = useState(false);
|
||||
const [selectedMonth, setSelectedMonth] = useState<number>(
|
||||
new Date().getMonth() + 1,
|
||||
);
|
||||
|
||||
const fetchProjection = useCallback(async () => {
|
||||
setLoading(true);
|
||||
const projectionQ = useQuery({
|
||||
queryKey: ['budget', 'projection', year],
|
||||
queryFn: () => getYearlyProjection(year).then((r) => r.data),
|
||||
});
|
||||
|
||||
const monthDetailQ = useQuery({
|
||||
queryKey: ['budget', 'month', year, selectedMonth],
|
||||
queryFn: () => getMonthlyDetail(year, selectedMonth).then((r) => r.data),
|
||||
placeholderData: (prev) => prev, // keep last month visible while navigating
|
||||
});
|
||||
|
||||
const recurringQ = useQuery({
|
||||
queryKey: ['budget', 'recurring'],
|
||||
queryFn: () => getRecurringItems().then((r) => r.data),
|
||||
});
|
||||
|
||||
const invalidate = () =>
|
||||
queryClient.invalidateQueries({ queryKey: ['budget'] });
|
||||
|
||||
async function mutateWithToast(
|
||||
action: () => Promise<unknown>,
|
||||
success: string,
|
||||
failure: string,
|
||||
) {
|
||||
try {
|
||||
const { data } = await getYearlyProjection(year);
|
||||
setProjection(data);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
await action();
|
||||
} catch (err) {
|
||||
toast.error(failure);
|
||||
throw err;
|
||||
}
|
||||
}, [year]);
|
||||
|
||||
const fetchMonthDetail = useCallback(async () => {
|
||||
setMonthLoading(true);
|
||||
try {
|
||||
const { data } = await getMonthlyDetail(year, selectedMonth);
|
||||
setMonthDetail(data);
|
||||
} finally {
|
||||
setMonthLoading(false);
|
||||
}
|
||||
}, [year, selectedMonth]);
|
||||
|
||||
const fetchRecurringItems = useCallback(async () => {
|
||||
const { data } = await getRecurringItems();
|
||||
setRecurringItems(data);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
fetchProjection();
|
||||
fetchRecurringItems();
|
||||
}, [fetchProjection, fetchRecurringItems]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchMonthDetail();
|
||||
}, [fetchMonthDetail]);
|
||||
|
||||
const addItem = async (data: RecurringItemCreate) => {
|
||||
await createRecurringItem(data);
|
||||
await Promise.all([fetchProjection(), fetchMonthDetail(), fetchRecurringItems()]);
|
||||
};
|
||||
|
||||
const updateItem = async (id: number, data: RecurringItemUpdate) => {
|
||||
await apiUpdateItem(id, data);
|
||||
await Promise.all([fetchProjection(), fetchMonthDetail(), fetchRecurringItems()]);
|
||||
};
|
||||
|
||||
const deleteItem = async (id: number) => {
|
||||
await apiDeleteItem(id);
|
||||
await Promise.all([fetchProjection(), fetchMonthDetail(), fetchRecurringItems()]);
|
||||
};
|
||||
|
||||
const saveBalanceOverride = async (overrideYear: number, month: number, value: number) => {
|
||||
await upsertBalanceOverride(overrideYear, month, value);
|
||||
await fetchProjection();
|
||||
};
|
||||
|
||||
const clearBalanceOverride = async (overrideYear: number, month: number) => {
|
||||
await deleteBalanceOverride(overrideYear, month);
|
||||
await fetchProjection();
|
||||
};
|
||||
toast.success(success);
|
||||
await invalidate();
|
||||
}
|
||||
|
||||
return {
|
||||
year,
|
||||
setYear,
|
||||
selectedMonth,
|
||||
setSelectedMonth,
|
||||
projection,
|
||||
monthDetail,
|
||||
recurringItems,
|
||||
loading,
|
||||
monthLoading,
|
||||
addItem,
|
||||
updateItem,
|
||||
deleteItem,
|
||||
saveBalanceOverride,
|
||||
clearBalanceOverride,
|
||||
refresh: () => Promise.all([fetchProjection(), fetchMonthDetail(), fetchRecurringItems()]),
|
||||
projection: projectionQ.data ?? null,
|
||||
monthDetail: monthDetailQ.data ?? null,
|
||||
recurringItems: recurringQ.data ?? [],
|
||||
loading: projectionQ.isPending,
|
||||
monthLoading: monthDetailQ.isFetching,
|
||||
error: projectionQ.error ?? monthDetailQ.error ?? recurringQ.error ?? null,
|
||||
addItem: (data: RecurringItemCreate) =>
|
||||
mutateWithToast(
|
||||
() => createRecurringItem(data),
|
||||
'Item recurrente creado',
|
||||
'No se pudo crear el item',
|
||||
),
|
||||
updateItem: (id: number, data: RecurringItemUpdate) =>
|
||||
mutateWithToast(
|
||||
() => apiUpdateItem(id, data),
|
||||
'Item recurrente actualizado',
|
||||
'No se pudo actualizar el item',
|
||||
),
|
||||
deleteItem: (id: number) =>
|
||||
mutateWithToast(
|
||||
() => apiDeleteItem(id),
|
||||
'Item recurrente eliminado',
|
||||
'No se pudo eliminar el item',
|
||||
),
|
||||
saveBalanceOverride: (overrideYear: number, month: number, value: number) =>
|
||||
mutateWithToast(
|
||||
() => upsertBalanceOverride(overrideYear, month, value),
|
||||
'Balance ajustado',
|
||||
'No se pudo ajustar el balance',
|
||||
),
|
||||
clearBalanceOverride: (overrideYear: number, month: number) =>
|
||||
mutateWithToast(
|
||||
() => deleteBalanceOverride(overrideYear, month),
|
||||
'Ajuste de balance eliminado',
|
||||
'No se pudo eliminar el ajuste',
|
||||
),
|
||||
refresh: invalidate,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -10,8 +10,13 @@ class ApiError extends Error {
|
||||
|
||||
interface RequestConfig {
|
||||
params?: Record<string, string | number | boolean | undefined>;
|
||||
/** Caller cancellation (TanStack Query passes this); combined with the
|
||||
* default 30s timeout. */
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
const REQUEST_TIMEOUT_MS = 30_000;
|
||||
|
||||
async function request<T>(
|
||||
method: string,
|
||||
url: string,
|
||||
@@ -38,11 +43,17 @@ async function request<T>(
|
||||
fetchBody = JSON.stringify(body);
|
||||
}
|
||||
|
||||
const timeout = AbortSignal.timeout(REQUEST_TIMEOUT_MS);
|
||||
const signal = config?.signal
|
||||
? AbortSignal.any([config.signal, timeout])
|
||||
: timeout;
|
||||
|
||||
const res = await fetch(fullUrl, {
|
||||
method,
|
||||
headers,
|
||||
body: fetchBody,
|
||||
credentials: "same-origin",
|
||||
signal,
|
||||
});
|
||||
|
||||
if (res.status === 401) {
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useState, useCallback } from 'react';
|
||||
import { ChevronLeft, ChevronRight, Calculator } from 'lucide-react';
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
import api, { type Transaction } from '@/lib/api';
|
||||
import { useBudget } from '@/hooks/useBudget';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import ErrorState from '@/components/ErrorState';
|
||||
import MonthlyDetail from '@/components/budget/MonthlyDetail';
|
||||
import RecurringItemsManager from '@/components/budget/RecurringItemsManager';
|
||||
import TransactionList from '@/components/TransactionList';
|
||||
@@ -27,28 +30,25 @@ export default function Budget() {
|
||||
monthDetail,
|
||||
recurringItems,
|
||||
monthLoading,
|
||||
error: budgetError,
|
||||
addItem,
|
||||
updateItem,
|
||||
deleteItem,
|
||||
refresh,
|
||||
} = useBudget(currentYear);
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const [subTab, setSubTab] = useState<'detail' | 'transactions'>('detail');
|
||||
|
||||
// Transaction list state for the selected month
|
||||
const [transactions, setTransactions] = useState<Transaction[]>([]);
|
||||
const [txLoading, setTxLoading] = useState(false);
|
||||
const [txSearch, setTxSearch] = useState('');
|
||||
const [txSource, setTxSource] = useState<'CREDIT_CARD' | 'CASH_AND_TRANSFER'>('CREDIT_CARD');
|
||||
|
||||
const fetchTransactions = useCallback(async () => {
|
||||
setTxLoading(true);
|
||||
try {
|
||||
const txQuery = useQuery({
|
||||
queryKey: ['transactions', 'budget', year, selectedMonth, txSource, txSearch],
|
||||
queryFn: async ({ signal }) => {
|
||||
const params: Record<string, string | number | boolean | undefined> = {
|
||||
search: txSearch || undefined,
|
||||
limit: 200,
|
||||
};
|
||||
|
||||
if (txSource === 'CREDIT_CARD') {
|
||||
params.source = 'CREDIT_CARD';
|
||||
// Credit card: billing cycle that ends around the 18th of selectedMonth
|
||||
@@ -66,33 +66,41 @@ export default function Budget() {
|
||||
params.start_date = startDate;
|
||||
params.end_date = endDate;
|
||||
}
|
||||
|
||||
const { data } = await api.get<Transaction[]>('/transactions/', { params });
|
||||
const { data } = await api.get<Transaction[]>('/transactions/', { params, signal });
|
||||
const INCOME_TYPES = ['DEPOSITO', 'SALARY'];
|
||||
const filtered = data.filter((tx) => !INCOME_TYPES.includes(tx.transaction_type));
|
||||
setTransactions(filtered);
|
||||
} finally {
|
||||
setTxLoading(false);
|
||||
}
|
||||
}, [year, selectedMonth, txSource, txSearch]);
|
||||
return data.filter((tx) => !INCOME_TYPES.includes(tx.transaction_type));
|
||||
},
|
||||
placeholderData: (prev) => prev,
|
||||
});
|
||||
const transactions = txQuery.data ?? [];
|
||||
|
||||
const invalidateTransactionsAndBudget = useCallback(() => {
|
||||
queryClient.invalidateQueries({ queryKey: ['transactions'] });
|
||||
refresh();
|
||||
}, [queryClient, refresh]);
|
||||
|
||||
const handleToggleDeferred = useCallback(async (tx: Transaction) => {
|
||||
await api.patch(`/transactions/${tx.id}`, {
|
||||
deferred_to_next_cycle: !tx.deferred_to_next_cycle,
|
||||
});
|
||||
fetchTransactions();
|
||||
refresh();
|
||||
}, [fetchTransactions, refresh]);
|
||||
try {
|
||||
await api.patch(`/transactions/${tx.id}`, {
|
||||
deferred_to_next_cycle: !tx.deferred_to_next_cycle,
|
||||
});
|
||||
toast.success(
|
||||
tx.deferred_to_next_cycle
|
||||
? 'Transacción restaurada a su ciclo original'
|
||||
: 'Transacción diferida al siguiente ciclo',
|
||||
);
|
||||
} catch {
|
||||
toast.error('No se pudo actualizar la transacción');
|
||||
return;
|
||||
}
|
||||
invalidateTransactionsAndBudget();
|
||||
}, [invalidateTransactionsAndBudget]);
|
||||
|
||||
const handleNavigateToTransactions = useCallback(() => {
|
||||
setTxSource('CASH_AND_TRANSFER');
|
||||
setSubTab('transactions');
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
fetchTransactions();
|
||||
}, [fetchTransactions]);
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Header */}
|
||||
@@ -154,11 +162,15 @@ export default function Budget() {
|
||||
</div>
|
||||
|
||||
<TabsContent value="detail" className="space-y-6 mt-4">
|
||||
<MonthlyDetail
|
||||
detail={monthDetail}
|
||||
loading={monthLoading || !monthDetail}
|
||||
onNavigateToTransactions={handleNavigateToTransactions}
|
||||
/>
|
||||
{budgetError ? (
|
||||
<ErrorState onRetry={refresh} />
|
||||
) : (
|
||||
<MonthlyDetail
|
||||
detail={monthDetail}
|
||||
loading={monthLoading || !monthDetail}
|
||||
onNavigateToTransactions={handleNavigateToTransactions}
|
||||
/>
|
||||
)}
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="transactions" className="space-y-3 mt-4">
|
||||
@@ -171,21 +183,25 @@ export default function Budget() {
|
||||
<TabsTrigger value="CASH_AND_TRANSFER">Efectivo y Transferencias</TabsTrigger>
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
{txQuery.isError ? (
|
||||
<ErrorState
|
||||
message="No se pudieron cargar las transacciones"
|
||||
onRetry={() => txQuery.refetch()}
|
||||
/>
|
||||
) : (
|
||||
<TransactionList
|
||||
transactions={transactions}
|
||||
loading={txLoading}
|
||||
loading={txQuery.isPending}
|
||||
source={txSource === 'CREDIT_CARD' ? 'CREDIT_CARD' : 'CASH'}
|
||||
search={txSearch}
|
||||
onSearchChange={setTxSearch}
|
||||
onRefresh={() => {
|
||||
fetchTransactions();
|
||||
refresh();
|
||||
}}
|
||||
onRefresh={invalidateTransactionsAndBudget}
|
||||
showCategory={txSource === 'CREDIT_CARD'}
|
||||
showSourceIcon={txSource === 'CASH_AND_TRANSFER'}
|
||||
emptyMessage={`Sin transacciones de ${txSource === 'CREDIT_CARD' ? 'tarjeta' : 'efectivo o transferencia'} en ${MONTH_NAMES[selectedMonth]}`}
|
||||
onToggleDeferred={txSource === 'CREDIT_CARD' ? handleToggleDeferred : undefined}
|
||||
/>
|
||||
)}
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</TabsContent>
|
||||
|
||||
Reference in New Issue
Block a user