mirror of
https://github.com/escalante29/WealthySmart.git
synced 2026-07-17 10:28:47 +02:00
Compare commits
5 Commits
396c492f27
...
cdfa4ad90a
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cdfa4ad90a | ||
|
|
b5bb2e8562 | ||
|
|
2a68a05ffd | ||
|
|
7a1733bf7e | ||
|
|
65dffdac06 |
@@ -98,6 +98,51 @@ Completed 2026-06-10.
|
||||
|
||||
Tests: 55 → **69** (new: model serialization, agent tools, upload validation).
|
||||
|
||||
**Production verification (2026-06-10, deploy after CI test gate):** boot logs show
|
||||
both migrations applied in order; `alembic_version = 7884505b16b3`;
|
||||
`transaction.amount` is `numeric(15,2)`; FK rules live (`SET NULL`×2, `CASCADE`);
|
||||
data intact through the type change (238 transactions, sum unchanged); live API
|
||||
emits amounts as JSON numbers.
|
||||
|
||||
---
|
||||
|
||||
## Phase 3 — Frontend Data Layer & Feedback ✅ DONE (3.4 deferred)
|
||||
|
||||
Completed 2026-06-10.
|
||||
|
||||
| Plan item | Status | Commit |
|
||||
|---|---|---|
|
||||
| 3.1 TanStack Query: provider, api timeout/signal, useBudget, Budget | ✅ | `65dffda` |
|
||||
| 3.1 All remaining pages on queries with ErrorState+retry | ✅ | `7a1733b` |
|
||||
| 3.2 Sonner toasts on every mutation; confirm on override clear | ✅ | (toasts) |
|
||||
| 3.3 Auth probe: network failure ≠ logged out (retry once) | ✅ | (auth) |
|
||||
| 3.5 Lazy context init, CK repair logging, upload-result cap | ✅ | (auth/pages) |
|
||||
| 3.4 OpenAPI type generation | ⏸ **deferred** | — |
|
||||
|
||||
**What changed for the user:** every page now shows an explicit error panel with
|
||||
a Reintentar button when the API fails (previously: silent empty charts/tables);
|
||||
every mutation (transaction save/delete, deferred toggle, recurring items,
|
||||
balance overrides) confirms success or failure with a toast; month navigation
|
||||
keeps the previous month visible while loading; rapid filter/month changes can
|
||||
no longer paint stale results (request cancellation); all requests time out at
|
||||
30s instead of hanging; clearing a balance override asks for confirmation; the
|
||||
privacy mask and theme no longer flash wrong on reload; a transient network
|
||||
blip at app start no longer kicks an authenticated user to the login page.
|
||||
|
||||
**Architecture:** TanStack Query with `staleTime` 30s and one retry;
|
||||
`['budget']`, `['transactions']`, `['analytics']`, `['salarios']`,
|
||||
`['pensions']`, `['municipal']` key families; mutations invalidate their family.
|
||||
`useBudget` keeps its original return shape so consumers didn't churn.
|
||||
|
||||
**3.4 (OpenAPI type generation) deferred to its own pass:** it needs the backend
|
||||
`response_model` sweep (ARCH-16) first and touches every endpoint plus the
|
||||
api.ts type exports — a separate, mechanical change with its own verification.
|
||||
The hand-written types are currently accurate (typecheck is green against real
|
||||
responses). Revisit after Phase 4's backend endpoints land.
|
||||
|
||||
**Closed as already-handled during implementation:** FE-04 (the Pensions ROI
|
||||
fallback already guarded `len >= 2`).
|
||||
|
||||
## Phase 3 — Frontend Data Layer & Feedback ⏳ NOT STARTED
|
||||
|
||||
## Phase 4 — UX, Trust & Features ⏳ NOT STARTED
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
"@fontsource-variable/ibm-plex-sans": "^5.2.8",
|
||||
"@fontsource-variable/noto-sans": "^5.2.10",
|
||||
"@hono/node-server": "^1.14.4",
|
||||
"@tanstack/react-query": "^5.101.0",
|
||||
"@tanstack/react-table": "^8.21.3",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
@@ -30,6 +31,7 @@
|
||||
"react-router-dom": "^7.6.0",
|
||||
"recharts": "^3.8.1",
|
||||
"rxjs": "^7.8.1",
|
||||
"sonner": "^2.0.7",
|
||||
"tailwind-merge": "^3.5.0",
|
||||
"tsx": "^4.19.4",
|
||||
"tw-animate-css": "^1.4.0"
|
||||
|
||||
32
frontend/pnpm-lock.yaml
generated
32
frontend/pnpm-lock.yaml
generated
@@ -32,6 +32,9 @@ importers:
|
||||
'@hono/node-server':
|
||||
specifier: ^1.14.4
|
||||
version: 1.19.14(hono@4.12.15)
|
||||
'@tanstack/react-query':
|
||||
specifier: ^5.101.0
|
||||
version: 5.101.0(react@19.2.5)
|
||||
'@tanstack/react-table':
|
||||
specifier: ^8.21.3
|
||||
version: 8.21.3(react-dom@19.2.5(react@19.2.5))(react@19.2.5)
|
||||
@@ -65,6 +68,9 @@ importers:
|
||||
rxjs:
|
||||
specifier: ^7.8.1
|
||||
version: 7.8.2
|
||||
sonner:
|
||||
specifier: ^2.0.7
|
||||
version: 2.0.7(react-dom@19.2.5(react@19.2.5))(react@19.2.5)
|
||||
tailwind-merge:
|
||||
specifier: ^3.5.0
|
||||
version: 3.5.0
|
||||
@@ -1606,6 +1612,14 @@ packages:
|
||||
resolution: {integrity: sha512-ZNQ1bIL6eUXVKdic0tiImvBVkWrg/IoSK6VIacTrO3d3HAGnd70qFJNJagR/YOJIOw4EKGWnodwpYZkN1pWuVQ==}
|
||||
engines: {node: '>=18'}
|
||||
|
||||
'@tanstack/query-core@5.101.0':
|
||||
resolution: {integrity: sha512-cQetA74EB+seWySv1TTKr828TnP0u39m6LykwDXIo84SNortpDkp30TMEjkqtYCNP9c40uT/iwl6MLiufEt0Ow==}
|
||||
|
||||
'@tanstack/react-query@5.101.0':
|
||||
resolution: {integrity: sha512-rLlJXSpkqfizLWgkR5+eLeIk0MvTx/meEIR7LRjxic+qxiQP8zVjq7BqQkiCMNLQBlLfuOLqqr6KO5GtrDlmSg==}
|
||||
peerDependencies:
|
||||
react: ^18 || ^19
|
||||
|
||||
'@tanstack/react-table@8.21.3':
|
||||
resolution: {integrity: sha512-5nNMTSETP4ykGegmVkhjcS8tTLW6Vl4axfEGQN3v0zdHYbK4UfoqfPChclTrJ4EoK9QynqAu9oUf8VEmrpZ5Ww==}
|
||||
engines: {node: '>=12'}
|
||||
@@ -3852,6 +3866,12 @@ packages:
|
||||
sonic-boom@4.2.1:
|
||||
resolution: {integrity: sha512-w6AxtubXa2wTXAUsZMMWERrsIRAdrK0Sc+FUytWvYAhBJLyuI4llrMIC1DtlNSdI99EI86KZum2MMq3EAZlF9Q==}
|
||||
|
||||
sonner@2.0.7:
|
||||
resolution: {integrity: sha512-W6ZN4p58k8aDKA4XPcx2hpIQXBRAgyiWVkYhT7CvK6D3iAu7xjvVyhQHg2/iaKJZ1XVJ4r7XuwGL+WGEK37i9w==}
|
||||
peerDependencies:
|
||||
react: ^18.0.0 || ^19.0.0 || ^19.0.0-rc
|
||||
react-dom: ^18.0.0 || ^19.0.0 || ^19.0.0-rc
|
||||
|
||||
source-map-js@1.2.1:
|
||||
resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==}
|
||||
engines: {node: '>=0.10.0'}
|
||||
@@ -5705,6 +5725,13 @@ snapshots:
|
||||
'@tanstack/devtools-event-client': 0.4.3
|
||||
'@tanstack/store': 0.9.3
|
||||
|
||||
'@tanstack/query-core@5.101.0': {}
|
||||
|
||||
'@tanstack/react-query@5.101.0(react@19.2.5)':
|
||||
dependencies:
|
||||
'@tanstack/query-core': 5.101.0
|
||||
react: 19.2.5
|
||||
|
||||
'@tanstack/react-table@8.21.3(react-dom@19.2.5(react@19.2.5))(react@19.2.5)':
|
||||
dependencies:
|
||||
'@tanstack/table-core': 8.21.3
|
||||
@@ -8634,6 +8661,11 @@ snapshots:
|
||||
dependencies:
|
||||
atomic-sleep: 1.0.0
|
||||
|
||||
sonner@2.0.7(react-dom@19.2.5(react@19.2.5))(react@19.2.5):
|
||||
dependencies:
|
||||
react: 19.2.5
|
||||
react-dom: 19.2.5(react@19.2.5)
|
||||
|
||||
source-map-js@1.2.1: {}
|
||||
|
||||
space-separated-tokens@1.1.5: {}
|
||||
|
||||
@@ -382,7 +382,10 @@ app.all("/api/copilotkit/*", async (c) => {
|
||||
headers: outbound.headers,
|
||||
body: JSON.stringify({ ...body, messages: paired }),
|
||||
});
|
||||
} catch {
|
||||
} catch (err) {
|
||||
// Skipping the repair is survivable; doing it silently is not —
|
||||
// orphan tool calls then fail downstream with no trace of why.
|
||||
console.error("[copilotkit] orphan-tool-call repair skipped:", err);
|
||||
return;
|
||||
}
|
||||
},
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -20,12 +20,27 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
// Probe auth state by hitting a protected endpoint.
|
||||
// If the ws_token cookie is valid, the server returns 200; else 401.
|
||||
fetch("/api/v1/auth/me", { credentials: "include" })
|
||||
.then((r) => setAuthenticated(r.ok))
|
||||
.catch(() => setAuthenticated(false))
|
||||
.finally(() => setIsLoading(false));
|
||||
// Probe auth state by hitting a protected endpoint. An HTTP status is an
|
||||
// authoritative answer (200 = in, 401 = out); a thrown fetch is a NETWORK
|
||||
// failure and must not log the user out — retry once before giving up.
|
||||
let cancelled = false;
|
||||
const probe = () => fetch("/api/v1/auth/me", { credentials: "include" });
|
||||
probe()
|
||||
.catch(() => new Promise((r) => setTimeout(r, 1500)).then(probe))
|
||||
.then((r) => {
|
||||
if (!cancelled) setAuthenticated((r as Response).ok);
|
||||
})
|
||||
.catch(() => {
|
||||
// Network still down: leave unauthenticated but log the real cause.
|
||||
console.warn("Auth probe failed twice (network) — backend unreachable");
|
||||
if (!cancelled) setAuthenticated(false);
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setIsLoading(false);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const logout = async () => {
|
||||
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -11,6 +11,8 @@ import {
|
||||
Banknote,
|
||||
} from 'lucide-react';
|
||||
|
||||
import { toast } from 'sonner';
|
||||
|
||||
import api, { type Transaction } from '@/lib/api';
|
||||
import TransactionModal from './TransactionModal';
|
||||
import ConfirmDialog from './ConfirmDialog';
|
||||
@@ -66,8 +68,11 @@ export default function TransactionList({
|
||||
setDeleting(true);
|
||||
try {
|
||||
await api.delete(`/transactions/${deleteId}`);
|
||||
toast.success('Transacción eliminada');
|
||||
setDeleteId(null);
|
||||
onRefresh();
|
||||
} catch {
|
||||
toast.error('No se pudo eliminar la transacción');
|
||||
} finally {
|
||||
setDeleting(false);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
import api, { type Category, type Transaction } from '@/lib/api';
|
||||
import { formatLocalDatetime } from '@/lib/format';
|
||||
import { Button } from '@/components/ui/button';
|
||||
@@ -92,12 +94,18 @@ export default function TransactionModal({ transaction, source, onClose, onSaved
|
||||
} else {
|
||||
await api.post('/transactions/', payload);
|
||||
}
|
||||
toast.success(transaction ? 'Transacción actualizada' : 'Transacción creada');
|
||||
onSaved();
|
||||
onClose();
|
||||
} catch (err: any) {
|
||||
if (err.response?.status === 409) {
|
||||
} catch (err) {
|
||||
const status =
|
||||
err && typeof err === 'object' && 'response' in err
|
||||
? (err as { response: { status: number } }).response.status
|
||||
: null;
|
||||
if (status === 409) {
|
||||
setError('Duplicate transaction: a transaction with this reference already exists.');
|
||||
} else {
|
||||
setError('No se pudo guardar la transacción.');
|
||||
console.error(err);
|
||||
}
|
||||
} finally {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import ConfirmDialog from '@/components/ConfirmDialog';
|
||||
import { useState, useRef, useEffect } from 'react';
|
||||
import { Pencil } from 'lucide-react';
|
||||
|
||||
@@ -42,6 +43,7 @@ export default function YearlyOverview({
|
||||
const currentMonth = new Date().getMonth() + 1;
|
||||
const currentYear = new Date().getFullYear();
|
||||
const [editingMonth, setEditingMonth] = useState<number | null>(null);
|
||||
const [confirmClearMonth, setConfirmClearMonth] = useState<number | null>(null);
|
||||
const [editValue, setEditValue] = useState('');
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
@@ -61,7 +63,16 @@ export default function YearlyOverview({
|
||||
if (editingMonth === null) return;
|
||||
const trimmed = editValue.trim();
|
||||
if (trimmed === '') {
|
||||
await onClearOverride(editingMonth);
|
||||
// Clearing an override is destructive — confirm first (it changes the
|
||||
// cumulative chain for every following month).
|
||||
const hadOverride = months.find(
|
||||
(m) => m.month === editingMonth,
|
||||
)?.balance_overridden;
|
||||
if (hadOverride) {
|
||||
setConfirmClearMonth(editingMonth);
|
||||
setEditingMonth(null);
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
const num = parseFloat(trimmed);
|
||||
if (!isNaN(num)) {
|
||||
@@ -71,6 +82,12 @@ export default function YearlyOverview({
|
||||
setEditingMonth(null);
|
||||
};
|
||||
|
||||
const handleConfirmClear = async () => {
|
||||
if (confirmClearMonth === null) return;
|
||||
await onClearOverride(confirmClearMonth);
|
||||
setConfirmClearMonth(null);
|
||||
};
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (e.key === 'Enter') {
|
||||
handleSave();
|
||||
@@ -202,6 +219,15 @@ export default function YearlyOverview({
|
||||
})}
|
||||
</TableBody>
|
||||
</Table>
|
||||
{confirmClearMonth !== null && (
|
||||
<ConfirmDialog
|
||||
title="Eliminar ajuste de balance"
|
||||
message={`El balance de ${MONTH_NAMES[confirmClearMonth] ?? confirmClearMonth} volverá al valor calculado y los meses siguientes se recalcularán.`}
|
||||
confirmLabel="Eliminar ajuste"
|
||||
onConfirm={handleConfirmClear}
|
||||
onCancel={() => setConfirmClearMonth(null)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -8,11 +8,10 @@ const PrivacyContext = createContext<{
|
||||
}>({ privacyMode: false, togglePrivacy: () => {} });
|
||||
|
||||
export function PrivacyProvider({ children }: { children: ReactNode }) {
|
||||
const [privacyMode, setPrivacyMode] = useState<boolean>(false);
|
||||
|
||||
useEffect(() => {
|
||||
setPrivacyMode(localStorage.getItem("privacyMode") === "true");
|
||||
}, []);
|
||||
// Lazy initializer: sensitive values must never flash unmasked on reload.
|
||||
const [privacyMode, setPrivacyMode] = useState<boolean>(
|
||||
() => localStorage.getItem("privacyMode") === "true",
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
document.documentElement.classList.toggle("privacy", privacyMode);
|
||||
|
||||
@@ -10,18 +10,15 @@ const ThemeContext = createContext<{
|
||||
}>({ theme: "dark", toggleTheme: () => {} });
|
||||
|
||||
export function ThemeProvider({ children }: { children: ReactNode }) {
|
||||
const [theme, setTheme] = useState<Theme>("dark");
|
||||
|
||||
// Initialize once on mount (localStorage + prefers-color-scheme).
|
||||
useEffect(() => {
|
||||
// Lazy initializer: resolving the theme before first paint avoids the
|
||||
// flash of wrong theme an effect-based init caused.
|
||||
const [theme, setTheme] = useState<Theme>(() => {
|
||||
const saved = localStorage.getItem("theme") as Theme | null;
|
||||
const initial: Theme = saved
|
||||
? saved
|
||||
: window.matchMedia("(prefers-color-scheme: dark)").matches
|
||||
? "dark"
|
||||
: "light";
|
||||
setTheme(initial);
|
||||
}, []);
|
||||
if (saved) return saved;
|
||||
return window.matchMedia("(prefers-color-scheme: dark)").matches
|
||||
? "dark"
|
||||
: "light";
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
document.documentElement.classList.toggle("dark", theme === "dark");
|
||||
|
||||
@@ -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,4 +1,5 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useState } from 'react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import {
|
||||
PieChart,
|
||||
Pie,
|
||||
@@ -13,6 +14,7 @@ import {
|
||||
import { BarChart3 } from 'lucide-react';
|
||||
|
||||
import api from '@/lib/api';
|
||||
import ErrorState from '@/components/ErrorState';
|
||||
import BillingCycleSelector from '@/components/BillingCycleSelector';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import {
|
||||
@@ -70,29 +72,43 @@ const dailyChartConfig = {
|
||||
|
||||
export default function Analytics() {
|
||||
const [cycle, setCycle] = useState<{ year: number; month: number } | null>(null);
|
||||
const [byCategory, setByCategory] = useState<CategorySpending[]>([]);
|
||||
const [trend, setTrend] = useState<MonthlyTrend[]>([]);
|
||||
const [daily, setDaily] = useState<DailySpending[]>([]);
|
||||
const cycleParams: Record<string, string> = cycle
|
||||
? { cycle_year: String(cycle.year), cycle_month: String(cycle.month) }
|
||||
: {};
|
||||
|
||||
useEffect(() => {
|
||||
const params: Record<string, string> = {};
|
||||
if (cycle) {
|
||||
params.cycle_year = String(cycle.year);
|
||||
params.cycle_month = String(cycle.month);
|
||||
}
|
||||
const byCategoryQ = useQuery({
|
||||
queryKey: ['analytics', 'by-category', cycle],
|
||||
queryFn: ({ signal }) =>
|
||||
api
|
||||
.get<CategorySpending[]>('/analytics/by-category', { params: cycleParams, signal })
|
||||
.then((r) => r.data),
|
||||
placeholderData: (prev) => prev,
|
||||
});
|
||||
// The trend endpoint ignores the cycle filter — keep it on its own key so
|
||||
// changing cycles doesn't refetch it.
|
||||
const trendQ = useQuery({
|
||||
queryKey: ['analytics', 'trend'],
|
||||
queryFn: ({ signal }) =>
|
||||
api.get<MonthlyTrend[]>('/analytics/monthly-trend', { signal }).then((r) => r.data),
|
||||
});
|
||||
const dailyQ = useQuery({
|
||||
queryKey: ['analytics', 'daily', cycle],
|
||||
queryFn: ({ signal }) =>
|
||||
api
|
||||
.get<DailySpending[]>('/analytics/daily-spending', { params: cycleParams, signal })
|
||||
.then((r) => r.data),
|
||||
placeholderData: (prev) => prev,
|
||||
});
|
||||
|
||||
Promise.all([
|
||||
api.get<CategorySpending[]>('/analytics/by-category', { params }),
|
||||
api.get<MonthlyTrend[]>('/analytics/monthly-trend'),
|
||||
api.get<DailySpending[]>('/analytics/daily-spending', { params }),
|
||||
])
|
||||
.then(([catRes, trendRes, dailyRes]) => {
|
||||
setByCategory(catRes.data);
|
||||
setTrend(trendRes.data);
|
||||
setDaily(dailyRes.data);
|
||||
})
|
||||
.catch(console.error);
|
||||
}, [cycle]);
|
||||
const byCategory = byCategoryQ.data ?? [];
|
||||
const trend = trendQ.data ?? [];
|
||||
const daily = dailyQ.data ?? [];
|
||||
const anyError = byCategoryQ.isError || trendQ.isError || dailyQ.isError;
|
||||
const retryAll = () => {
|
||||
byCategoryQ.refetch();
|
||||
trendQ.refetch();
|
||||
dailyQ.refetch();
|
||||
};
|
||||
|
||||
// Build dynamic chart config for pie chart
|
||||
const pieChartConfig = byCategory.reduce<ChartConfig>((acc, cat, i) => {
|
||||
@@ -116,6 +132,13 @@ export default function Analytics() {
|
||||
<BillingCycleSelector value={cycle} onChange={setCycle} />
|
||||
</div>
|
||||
|
||||
{anyError && (
|
||||
<ErrorState
|
||||
message="No se pudieron cargar los datos de analytics"
|
||||
onRetry={retryAll}
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
{/* Spending by Category - Donut */}
|
||||
<Card>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { useState, useEffect, useMemo, useCallback, useRef } from 'react';
|
||||
import { useState, useMemo, useCallback, useRef } from 'react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import ErrorState from '@/components/ErrorState';
|
||||
import {
|
||||
LineChart,
|
||||
Line,
|
||||
@@ -238,9 +240,9 @@ function ChartTooltipContent({
|
||||
|
||||
// ─── Main Component ───────────────────────────────────────────────────────────
|
||||
|
||||
const EMPTY_SNAPSHOTS: PensionSnapshot[] = [];
|
||||
|
||||
export default function Pensions() {
|
||||
const [fundSummary, setFundSummary] = useState<PensionSnapshot[]>([]);
|
||||
const [allSnapshots, setAllSnapshots] = useState<PensionSnapshot[]>([]);
|
||||
const [visibleFunds, setVisibleFunds] = useState<Set<FundKey>>(new Set(FUND_KEYS));
|
||||
const [projections, setProjections] = useState<Record<FundKey, ProjectionState>>({
|
||||
FCL: { contribution: 150_000, rate: 7.5, targetAge: 35 },
|
||||
@@ -254,22 +256,22 @@ export default function Pensions() {
|
||||
const [showManualEntry, setShowManualEntry] = useState(false);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const loadData = useCallback(async () => {
|
||||
try {
|
||||
const pensionQ = useQuery({
|
||||
queryKey: ['pensions'],
|
||||
queryFn: async () => {
|
||||
const [summaryRes, snapshotsRes] = await Promise.all([
|
||||
getPensionFundSummary(),
|
||||
getPensionSnapshots(),
|
||||
]);
|
||||
setFundSummary(summaryRes.data);
|
||||
setAllSnapshots(snapshotsRes.data);
|
||||
} catch {
|
||||
// API not available or no data yet — use defaults
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
loadData();
|
||||
}, [loadData]);
|
||||
return { summary: summaryRes.data, snapshots: snapshotsRes.data };
|
||||
},
|
||||
});
|
||||
const fundSummary = pensionQ.data?.summary ?? EMPTY_SNAPSHOTS;
|
||||
const allSnapshots = pensionQ.data?.snapshots ?? EMPTY_SNAPSHOTS;
|
||||
const loadData = useCallback(async () => {
|
||||
await pensionQ.refetch();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [pensionQ.refetch]);
|
||||
|
||||
const FUNDS = useMemo(() => applySnapshots(fundSummary), [fundSummary]);
|
||||
|
||||
@@ -392,6 +394,12 @@ export default function Pensions() {
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
{pensionQ.isError && (
|
||||
<ErrorState
|
||||
message="No se pudieron cargar los datos de pensiones"
|
||||
onRetry={() => pensionQ.refetch()}
|
||||
/>
|
||||
)}
|
||||
{/* ── Page Header ─────────────────────────────────────────────────── */}
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-10 h-10 rounded-lg bg-primary/10 flex items-center justify-center">
|
||||
@@ -849,7 +857,7 @@ export default function Pensions() {
|
||||
))}
|
||||
{uploadResult.snapshots.length > 0 && (
|
||||
<div className="space-y-1 pt-1">
|
||||
{uploadResult.snapshots.map((snap) => (
|
||||
{uploadResult.snapshots.slice(0, 10).map((snap) => (
|
||||
<div key={snap.id} className="flex items-center justify-between text-xs">
|
||||
<span className="text-muted-foreground">
|
||||
{snap.fund} · {new Date(snap.period_start).toLocaleDateString('es-CR', { month: 'short', year: '2-digit' })}
|
||||
@@ -859,6 +867,11 @@ export default function Pensions() {
|
||||
<span data-sensitive className="font-mono font-medium">{formatCRC(snap.saldo_final)}</span>
|
||||
</div>
|
||||
))}
|
||||
{uploadResult.snapshots.length > 10 && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
… y {uploadResult.snapshots.length - 10} más
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -6,6 +6,7 @@ import { formatAmount } from '@/lib/format';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import ErrorState from '@/components/ErrorState';
|
||||
import YearlyOverview from '@/components/budget/YearlyOverview';
|
||||
|
||||
const MIN_YEAR = 2026;
|
||||
@@ -19,6 +20,8 @@ export default function Proyecciones() {
|
||||
setSelectedMonth,
|
||||
projection,
|
||||
loading,
|
||||
error,
|
||||
refresh,
|
||||
saveBalanceOverride,
|
||||
clearBalanceOverride,
|
||||
} = useBudget(currentYear);
|
||||
@@ -89,7 +92,10 @@ export default function Proyecciones() {
|
||||
) : projection ? (
|
||||
<Card>
|
||||
<CardContent className="p-0">
|
||||
<YearlyOverview
|
||||
{error ? (
|
||||
<ErrorState onRetry={refresh} />
|
||||
) : (
|
||||
<YearlyOverview
|
||||
months={projection.months}
|
||||
selectedMonth={0}
|
||||
year={year}
|
||||
@@ -104,6 +110,7 @@ export default function Proyecciones() {
|
||||
await clearBalanceOverride(year, month);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : null}
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useMemo } from 'react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { type ColumnDef } from '@tanstack/react-table';
|
||||
import { Landmark, RefreshCw, Hash, CalendarDays, Banknote } from 'lucide-react';
|
||||
|
||||
import { type Transaction, type SalariosSummary, getSalarios, getSalariosSummary } from '@/lib/api';
|
||||
import { formatAmount, formatDate } from '@/lib/format';
|
||||
import ErrorState from '@/components/ErrorState';
|
||||
import { DataTable } from '@/components/ui/data-table';
|
||||
import { DataTableColumnHeader } from '@/components/ui/data-table-column-header';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
@@ -11,27 +13,20 @@ import { Button } from '@/components/ui/button';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
|
||||
export default function Salarios() {
|
||||
const [deposits, setDeposits] = useState<Transaction[]>([]);
|
||||
const [summary, setSummary] = useState<SalariosSummary | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const fetchData = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const query = useQuery({
|
||||
queryKey: ['salarios'],
|
||||
queryFn: async () => {
|
||||
const [depRes, sumRes] = await Promise.all([
|
||||
getSalarios({ limit: 500 }),
|
||||
getSalariosSummary(),
|
||||
]);
|
||||
setDeposits(depRes.data);
|
||||
setSummary(sumRes.data);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => { fetchData(); }, []);
|
||||
return { deposits: depRes.data, summary: sumRes.data };
|
||||
},
|
||||
});
|
||||
const deposits = query.data?.deposits ?? [];
|
||||
const summary = query.data?.summary ?? null;
|
||||
const loading = query.isFetching;
|
||||
const fetchData = () => query.refetch();
|
||||
|
||||
const columns = useMemo<ColumnDef<Transaction, unknown>[]>(
|
||||
() => [
|
||||
@@ -146,18 +141,25 @@ export default function Salarios() {
|
||||
)}
|
||||
|
||||
{/* Data table */}
|
||||
<Card>
|
||||
<CardContent className="p-0">
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={deposits}
|
||||
pagination
|
||||
pageSize={25}
|
||||
initialSorting={[{ id: 'date', desc: true }]}
|
||||
emptyMessage="No hay depósitos registrados aún."
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
{query.isError ? (
|
||||
<ErrorState
|
||||
message="No se pudieron cargar los salarios"
|
||||
onRetry={fetchData}
|
||||
/>
|
||||
) : (
|
||||
<Card>
|
||||
<CardContent className="p-0">
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={deposits}
|
||||
pagination
|
||||
pageSize={25}
|
||||
initialSorting={[{ id: 'date', desc: true }]}
|
||||
emptyMessage="No hay depósitos registrados aún."
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { useState, useEffect, useCallback, useRef, useMemo } from 'react';
|
||||
import { useState, useCallback, useRef, useMemo } from 'react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import ErrorState from '@/components/ErrorState';
|
||||
import {
|
||||
BarChart,
|
||||
Bar,
|
||||
@@ -179,10 +181,10 @@ function ChartTooltipContent({
|
||||
|
||||
// ─── Main Component ──────────────────────────────────────────────────────────
|
||||
|
||||
const EMPTY_RECEIPTS: MunicipalReceipt[] = [];
|
||||
const EMPTY_READINGS: WaterMeterReading[] = [];
|
||||
|
||||
export default function ServiciosMunicipales() {
|
||||
const [receipts, setReceipts] = useState<MunicipalReceipt[]>([]);
|
||||
const [waterReadings, setWaterReadings] = useState<WaterMeterReading[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
// Chart visibility state
|
||||
const [hiddenMeters, setHiddenMeters] = useState<Set<string>>(new Set());
|
||||
@@ -195,25 +197,23 @@ export default function ServiciosMunicipales() {
|
||||
const [uploadResults, setUploadResults] = useState<MunicipalReceiptUploadResult[]>([]);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const loadData = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const municipalQ = useQuery({
|
||||
queryKey: ['municipal'],
|
||||
queryFn: async () => {
|
||||
const [receiptsRes, waterRes] = await Promise.all([
|
||||
getMunicipalReceipts(),
|
||||
getWaterConsumption(24),
|
||||
]);
|
||||
setReceipts(receiptsRes.data);
|
||||
setWaterReadings(waterRes.data);
|
||||
} catch {
|
||||
// API not available yet
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
loadData();
|
||||
}, [loadData]);
|
||||
return { receipts: receiptsRes.data, water: waterRes.data };
|
||||
},
|
||||
});
|
||||
const receipts = municipalQ.data?.receipts ?? EMPTY_RECEIPTS;
|
||||
const waterReadings = municipalQ.data?.water ?? EMPTY_READINGS;
|
||||
const loading = municipalQ.isPending;
|
||||
const loadData = useCallback(async () => {
|
||||
await municipalQ.refetch();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [municipalQ.refetch]);
|
||||
|
||||
// Derived data
|
||||
const chartData = useMemo(() => buildChartData(waterReadings), [waterReadings]);
|
||||
@@ -291,6 +291,12 @@ export default function ServiciosMunicipales() {
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
{municipalQ.isError && (
|
||||
<ErrorState
|
||||
message="No se pudieron cargar los recibos municipales"
|
||||
onRetry={() => municipalQ.refetch()}
|
||||
/>
|
||||
)}
|
||||
{/* ── Page Header ─────────────────────────────────────────────────── */}
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-10 h-10 rounded-lg bg-primary/10 flex items-center justify-center">
|
||||
|
||||
Reference in New Issue
Block a user