mirror of
https://github.com/escalante29/WealthySmart.git
synced 2026-07-17 12:28:48 +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).
|
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 3 — Frontend Data Layer & Feedback ⏳ NOT STARTED
|
||||||
|
|
||||||
## Phase 4 — UX, Trust & Features ⏳ NOT STARTED
|
## Phase 4 — UX, Trust & Features ⏳ NOT STARTED
|
||||||
|
|||||||
@@ -19,6 +19,7 @@
|
|||||||
"@fontsource-variable/ibm-plex-sans": "^5.2.8",
|
"@fontsource-variable/ibm-plex-sans": "^5.2.8",
|
||||||
"@fontsource-variable/noto-sans": "^5.2.10",
|
"@fontsource-variable/noto-sans": "^5.2.10",
|
||||||
"@hono/node-server": "^1.14.4",
|
"@hono/node-server": "^1.14.4",
|
||||||
|
"@tanstack/react-query": "^5.101.0",
|
||||||
"@tanstack/react-table": "^8.21.3",
|
"@tanstack/react-table": "^8.21.3",
|
||||||
"class-variance-authority": "^0.7.1",
|
"class-variance-authority": "^0.7.1",
|
||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
@@ -30,6 +31,7 @@
|
|||||||
"react-router-dom": "^7.6.0",
|
"react-router-dom": "^7.6.0",
|
||||||
"recharts": "^3.8.1",
|
"recharts": "^3.8.1",
|
||||||
"rxjs": "^7.8.1",
|
"rxjs": "^7.8.1",
|
||||||
|
"sonner": "^2.0.7",
|
||||||
"tailwind-merge": "^3.5.0",
|
"tailwind-merge": "^3.5.0",
|
||||||
"tsx": "^4.19.4",
|
"tsx": "^4.19.4",
|
||||||
"tw-animate-css": "^1.4.0"
|
"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':
|
'@hono/node-server':
|
||||||
specifier: ^1.14.4
|
specifier: ^1.14.4
|
||||||
version: 1.19.14(hono@4.12.15)
|
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':
|
'@tanstack/react-table':
|
||||||
specifier: ^8.21.3
|
specifier: ^8.21.3
|
||||||
version: 8.21.3(react-dom@19.2.5(react@19.2.5))(react@19.2.5)
|
version: 8.21.3(react-dom@19.2.5(react@19.2.5))(react@19.2.5)
|
||||||
@@ -65,6 +68,9 @@ importers:
|
|||||||
rxjs:
|
rxjs:
|
||||||
specifier: ^7.8.1
|
specifier: ^7.8.1
|
||||||
version: 7.8.2
|
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:
|
tailwind-merge:
|
||||||
specifier: ^3.5.0
|
specifier: ^3.5.0
|
||||||
version: 3.5.0
|
version: 3.5.0
|
||||||
@@ -1606,6 +1612,14 @@ packages:
|
|||||||
resolution: {integrity: sha512-ZNQ1bIL6eUXVKdic0tiImvBVkWrg/IoSK6VIacTrO3d3HAGnd70qFJNJagR/YOJIOw4EKGWnodwpYZkN1pWuVQ==}
|
resolution: {integrity: sha512-ZNQ1bIL6eUXVKdic0tiImvBVkWrg/IoSK6VIacTrO3d3HAGnd70qFJNJagR/YOJIOw4EKGWnodwpYZkN1pWuVQ==}
|
||||||
engines: {node: '>=18'}
|
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':
|
'@tanstack/react-table@8.21.3':
|
||||||
resolution: {integrity: sha512-5nNMTSETP4ykGegmVkhjcS8tTLW6Vl4axfEGQN3v0zdHYbK4UfoqfPChclTrJ4EoK9QynqAu9oUf8VEmrpZ5Ww==}
|
resolution: {integrity: sha512-5nNMTSETP4ykGegmVkhjcS8tTLW6Vl4axfEGQN3v0zdHYbK4UfoqfPChclTrJ4EoK9QynqAu9oUf8VEmrpZ5Ww==}
|
||||||
engines: {node: '>=12'}
|
engines: {node: '>=12'}
|
||||||
@@ -3852,6 +3866,12 @@ packages:
|
|||||||
sonic-boom@4.2.1:
|
sonic-boom@4.2.1:
|
||||||
resolution: {integrity: sha512-w6AxtubXa2wTXAUsZMMWERrsIRAdrK0Sc+FUytWvYAhBJLyuI4llrMIC1DtlNSdI99EI86KZum2MMq3EAZlF9Q==}
|
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:
|
source-map-js@1.2.1:
|
||||||
resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==}
|
resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==}
|
||||||
engines: {node: '>=0.10.0'}
|
engines: {node: '>=0.10.0'}
|
||||||
@@ -5705,6 +5725,13 @@ snapshots:
|
|||||||
'@tanstack/devtools-event-client': 0.4.3
|
'@tanstack/devtools-event-client': 0.4.3
|
||||||
'@tanstack/store': 0.9.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)':
|
'@tanstack/react-table@8.21.3(react-dom@19.2.5(react@19.2.5))(react@19.2.5)':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@tanstack/table-core': 8.21.3
|
'@tanstack/table-core': 8.21.3
|
||||||
@@ -8634,6 +8661,11 @@ snapshots:
|
|||||||
dependencies:
|
dependencies:
|
||||||
atomic-sleep: 1.0.0
|
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: {}
|
source-map-js@1.2.1: {}
|
||||||
|
|
||||||
space-separated-tokens@1.1.5: {}
|
space-separated-tokens@1.1.5: {}
|
||||||
|
|||||||
@@ -382,7 +382,10 @@ app.all("/api/copilotkit/*", async (c) => {
|
|||||||
headers: outbound.headers,
|
headers: outbound.headers,
|
||||||
body: JSON.stringify({ ...body, messages: paired }),
|
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;
|
return;
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,8 +1,19 @@
|
|||||||
import { BrowserRouter, Routes, Route, Navigate } from "react-router-dom";
|
import { BrowserRouter, Routes, Route, Navigate } from "react-router-dom";
|
||||||
import { CopilotKit } from "@copilotkit/react-core";
|
import { CopilotKit } from "@copilotkit/react-core";
|
||||||
|
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||||
|
import { Toaster } from "sonner";
|
||||||
import { AuthProvider, useAuth } from "./AuthContext";
|
import { AuthProvider, useAuth } from "./AuthContext";
|
||||||
import { ThemeProvider } from "./contexts/theme-context";
|
import { ThemeProvider } from "./contexts/theme-context";
|
||||||
import { PrivacyProvider } from "./contexts/privacy-context";
|
import { PrivacyProvider } from "./contexts/privacy-context";
|
||||||
|
|
||||||
|
const queryClient = new QueryClient({
|
||||||
|
defaultOptions: {
|
||||||
|
queries: {
|
||||||
|
staleTime: 30_000,
|
||||||
|
retry: 1,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
import Layout from "./components/Layout";
|
import Layout from "./components/Layout";
|
||||||
import LoginPage from "./pages/Login";
|
import LoginPage from "./pages/Login";
|
||||||
import Asistente from "./pages/Asistente";
|
import Asistente from "./pages/Asistente";
|
||||||
@@ -58,9 +69,12 @@ export default function App() {
|
|||||||
<ThemeProvider>
|
<ThemeProvider>
|
||||||
<PrivacyProvider>
|
<PrivacyProvider>
|
||||||
<AuthProvider>
|
<AuthProvider>
|
||||||
|
<QueryClientProvider client={queryClient}>
|
||||||
<CopilotKit runtimeUrl="/api/copilotkit" agent="wealthysmart" a2ui={{}}>
|
<CopilotKit runtimeUrl="/api/copilotkit" agent="wealthysmart" a2ui={{}}>
|
||||||
<AppRoutes />
|
<AppRoutes />
|
||||||
|
<Toaster richColors position="top-right" closeButton />
|
||||||
</CopilotKit>
|
</CopilotKit>
|
||||||
|
</QueryClientProvider>
|
||||||
</AuthProvider>
|
</AuthProvider>
|
||||||
</PrivacyProvider>
|
</PrivacyProvider>
|
||||||
</ThemeProvider>
|
</ThemeProvider>
|
||||||
|
|||||||
@@ -20,12 +20,27 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
|||||||
const [isLoading, setIsLoading] = useState(true);
|
const [isLoading, setIsLoading] = useState(true);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
// Probe auth state by hitting a protected endpoint.
|
// Probe auth state by hitting a protected endpoint. An HTTP status is an
|
||||||
// If the ws_token cookie is valid, the server returns 200; else 401.
|
// authoritative answer (200 = in, 401 = out); a thrown fetch is a NETWORK
|
||||||
fetch("/api/v1/auth/me", { credentials: "include" })
|
// failure and must not log the user out — retry once before giving up.
|
||||||
.then((r) => setAuthenticated(r.ok))
|
let cancelled = false;
|
||||||
.catch(() => setAuthenticated(false))
|
const probe = () => fetch("/api/v1/auth/me", { credentials: "include" });
|
||||||
.finally(() => setIsLoading(false));
|
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 () => {
|
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,
|
Banknote,
|
||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
|
|
||||||
|
import { toast } from 'sonner';
|
||||||
|
|
||||||
import api, { type Transaction } from '@/lib/api';
|
import api, { type Transaction } from '@/lib/api';
|
||||||
import TransactionModal from './TransactionModal';
|
import TransactionModal from './TransactionModal';
|
||||||
import ConfirmDialog from './ConfirmDialog';
|
import ConfirmDialog from './ConfirmDialog';
|
||||||
@@ -66,8 +68,11 @@ export default function TransactionList({
|
|||||||
setDeleting(true);
|
setDeleting(true);
|
||||||
try {
|
try {
|
||||||
await api.delete(`/transactions/${deleteId}`);
|
await api.delete(`/transactions/${deleteId}`);
|
||||||
|
toast.success('Transacción eliminada');
|
||||||
setDeleteId(null);
|
setDeleteId(null);
|
||||||
onRefresh();
|
onRefresh();
|
||||||
|
} catch {
|
||||||
|
toast.error('No se pudo eliminar la transacción');
|
||||||
} finally {
|
} finally {
|
||||||
setDeleting(false);
|
setDeleting(false);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useState } from 'react';
|
||||||
|
import { toast } from 'sonner';
|
||||||
|
|
||||||
import api, { type Category, type Transaction } from '@/lib/api';
|
import api, { type Category, type Transaction } from '@/lib/api';
|
||||||
import { formatLocalDatetime } from '@/lib/format';
|
import { formatLocalDatetime } from '@/lib/format';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
@@ -92,12 +94,18 @@ export default function TransactionModal({ transaction, source, onClose, onSaved
|
|||||||
} else {
|
} else {
|
||||||
await api.post('/transactions/', payload);
|
await api.post('/transactions/', payload);
|
||||||
}
|
}
|
||||||
|
toast.success(transaction ? 'Transacción actualizada' : 'Transacción creada');
|
||||||
onSaved();
|
onSaved();
|
||||||
onClose();
|
onClose();
|
||||||
} catch (err: any) {
|
} catch (err) {
|
||||||
if (err.response?.status === 409) {
|
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.');
|
setError('Duplicate transaction: a transaction with this reference already exists.');
|
||||||
} else {
|
} else {
|
||||||
|
setError('No se pudo guardar la transacción.');
|
||||||
console.error(err);
|
console.error(err);
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import ConfirmDialog from '@/components/ConfirmDialog';
|
||||||
import { useState, useRef, useEffect } from 'react';
|
import { useState, useRef, useEffect } from 'react';
|
||||||
import { Pencil } from 'lucide-react';
|
import { Pencil } from 'lucide-react';
|
||||||
|
|
||||||
@@ -42,6 +43,7 @@ export default function YearlyOverview({
|
|||||||
const currentMonth = new Date().getMonth() + 1;
|
const currentMonth = new Date().getMonth() + 1;
|
||||||
const currentYear = new Date().getFullYear();
|
const currentYear = new Date().getFullYear();
|
||||||
const [editingMonth, setEditingMonth] = useState<number | null>(null);
|
const [editingMonth, setEditingMonth] = useState<number | null>(null);
|
||||||
|
const [confirmClearMonth, setConfirmClearMonth] = useState<number | null>(null);
|
||||||
const [editValue, setEditValue] = useState('');
|
const [editValue, setEditValue] = useState('');
|
||||||
const inputRef = useRef<HTMLInputElement>(null);
|
const inputRef = useRef<HTMLInputElement>(null);
|
||||||
|
|
||||||
@@ -61,7 +63,16 @@ export default function YearlyOverview({
|
|||||||
if (editingMonth === null) return;
|
if (editingMonth === null) return;
|
||||||
const trimmed = editValue.trim();
|
const trimmed = editValue.trim();
|
||||||
if (trimmed === '') {
|
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 {
|
} else {
|
||||||
const num = parseFloat(trimmed);
|
const num = parseFloat(trimmed);
|
||||||
if (!isNaN(num)) {
|
if (!isNaN(num)) {
|
||||||
@@ -71,6 +82,12 @@ export default function YearlyOverview({
|
|||||||
setEditingMonth(null);
|
setEditingMonth(null);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleConfirmClear = async () => {
|
||||||
|
if (confirmClearMonth === null) return;
|
||||||
|
await onClearOverride(confirmClearMonth);
|
||||||
|
setConfirmClearMonth(null);
|
||||||
|
};
|
||||||
|
|
||||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||||
if (e.key === 'Enter') {
|
if (e.key === 'Enter') {
|
||||||
handleSave();
|
handleSave();
|
||||||
@@ -202,6 +219,15 @@ export default function YearlyOverview({
|
|||||||
})}
|
})}
|
||||||
</TableBody>
|
</TableBody>
|
||||||
</Table>
|
</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>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,11 +8,10 @@ const PrivacyContext = createContext<{
|
|||||||
}>({ privacyMode: false, togglePrivacy: () => {} });
|
}>({ privacyMode: false, togglePrivacy: () => {} });
|
||||||
|
|
||||||
export function PrivacyProvider({ children }: { children: ReactNode }) {
|
export function PrivacyProvider({ children }: { children: ReactNode }) {
|
||||||
const [privacyMode, setPrivacyMode] = useState<boolean>(false);
|
// Lazy initializer: sensitive values must never flash unmasked on reload.
|
||||||
|
const [privacyMode, setPrivacyMode] = useState<boolean>(
|
||||||
useEffect(() => {
|
() => localStorage.getItem("privacyMode") === "true",
|
||||||
setPrivacyMode(localStorage.getItem("privacyMode") === "true");
|
);
|
||||||
}, []);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
document.documentElement.classList.toggle("privacy", privacyMode);
|
document.documentElement.classList.toggle("privacy", privacyMode);
|
||||||
|
|||||||
@@ -10,18 +10,15 @@ const ThemeContext = createContext<{
|
|||||||
}>({ theme: "dark", toggleTheme: () => {} });
|
}>({ theme: "dark", toggleTheme: () => {} });
|
||||||
|
|
||||||
export function ThemeProvider({ children }: { children: ReactNode }) {
|
export function ThemeProvider({ children }: { children: ReactNode }) {
|
||||||
const [theme, setTheme] = useState<Theme>("dark");
|
// Lazy initializer: resolving the theme before first paint avoids the
|
||||||
|
// flash of wrong theme an effect-based init caused.
|
||||||
// Initialize once on mount (localStorage + prefers-color-scheme).
|
const [theme, setTheme] = useState<Theme>(() => {
|
||||||
useEffect(() => {
|
|
||||||
const saved = localStorage.getItem("theme") as Theme | null;
|
const saved = localStorage.getItem("theme") as Theme | null;
|
||||||
const initial: Theme = saved
|
if (saved) return saved;
|
||||||
? saved
|
return window.matchMedia("(prefers-color-scheme: dark)").matches
|
||||||
: window.matchMedia("(prefers-color-scheme: dark)").matches
|
|
||||||
? "dark"
|
? "dark"
|
||||||
: "light";
|
: "light";
|
||||||
setTheme(initial);
|
});
|
||||||
}, []);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
document.documentElement.classList.toggle("dark", theme === "dark");
|
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 {
|
import {
|
||||||
type YearlyProjection,
|
|
||||||
type MonthlyDetail,
|
|
||||||
type RecurringItem,
|
|
||||||
type RecurringItemCreate,
|
type RecurringItemCreate,
|
||||||
type RecurringItemUpdate,
|
type RecurringItemUpdate,
|
||||||
getYearlyProjection,
|
getYearlyProjection,
|
||||||
@@ -15,89 +14,90 @@ import {
|
|||||||
deleteBalanceOverride,
|
deleteBalanceOverride,
|
||||||
} from '@/lib/api';
|
} 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) {
|
export function useBudget(initialYear: number) {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
const [year, setYear] = useState(initialYear);
|
const [year, setYear] = useState(initialYear);
|
||||||
const [selectedMonth, setSelectedMonth] = useState<number>(new Date().getMonth() + 1);
|
const [selectedMonth, setSelectedMonth] = useState<number>(
|
||||||
const [projection, setProjection] = useState<YearlyProjection | null>(null);
|
new Date().getMonth() + 1,
|
||||||
const [monthDetail, setMonthDetail] = useState<MonthlyDetail | null>(null);
|
);
|
||||||
const [recurringItems, setRecurringItems] = useState<RecurringItem[]>([]);
|
|
||||||
const [loading, setLoading] = useState(true);
|
|
||||||
const [monthLoading, setMonthLoading] = useState(false);
|
|
||||||
|
|
||||||
const fetchProjection = useCallback(async () => {
|
const projectionQ = useQuery({
|
||||||
setLoading(true);
|
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 {
|
try {
|
||||||
const { data } = await getYearlyProjection(year);
|
await action();
|
||||||
setProjection(data);
|
} catch (err) {
|
||||||
} finally {
|
toast.error(failure);
|
||||||
setLoading(false);
|
throw err;
|
||||||
}
|
}
|
||||||
}, [year]);
|
toast.success(success);
|
||||||
|
await invalidate();
|
||||||
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();
|
|
||||||
};
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
year,
|
year,
|
||||||
setYear,
|
setYear,
|
||||||
selectedMonth,
|
selectedMonth,
|
||||||
setSelectedMonth,
|
setSelectedMonth,
|
||||||
projection,
|
projection: projectionQ.data ?? null,
|
||||||
monthDetail,
|
monthDetail: monthDetailQ.data ?? null,
|
||||||
recurringItems,
|
recurringItems: recurringQ.data ?? [],
|
||||||
loading,
|
loading: projectionQ.isPending,
|
||||||
monthLoading,
|
monthLoading: monthDetailQ.isFetching,
|
||||||
addItem,
|
error: projectionQ.error ?? monthDetailQ.error ?? recurringQ.error ?? null,
|
||||||
updateItem,
|
addItem: (data: RecurringItemCreate) =>
|
||||||
deleteItem,
|
mutateWithToast(
|
||||||
saveBalanceOverride,
|
() => createRecurringItem(data),
|
||||||
clearBalanceOverride,
|
'Item recurrente creado',
|
||||||
refresh: () => Promise.all([fetchProjection(), fetchMonthDetail(), fetchRecurringItems()]),
|
'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 {
|
interface RequestConfig {
|
||||||
params?: Record<string, string | number | boolean | undefined>;
|
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>(
|
async function request<T>(
|
||||||
method: string,
|
method: string,
|
||||||
url: string,
|
url: string,
|
||||||
@@ -38,11 +43,17 @@ async function request<T>(
|
|||||||
fetchBody = JSON.stringify(body);
|
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, {
|
const res = await fetch(fullUrl, {
|
||||||
method,
|
method,
|
||||||
headers,
|
headers,
|
||||||
body: fetchBody,
|
body: fetchBody,
|
||||||
credentials: "same-origin",
|
credentials: "same-origin",
|
||||||
|
signal,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (res.status === 401) {
|
if (res.status === 401) {
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { useEffect, useState } from 'react';
|
import { useState } from 'react';
|
||||||
|
import { useQuery } from '@tanstack/react-query';
|
||||||
import {
|
import {
|
||||||
PieChart,
|
PieChart,
|
||||||
Pie,
|
Pie,
|
||||||
@@ -13,6 +14,7 @@ import {
|
|||||||
import { BarChart3 } from 'lucide-react';
|
import { BarChart3 } from 'lucide-react';
|
||||||
|
|
||||||
import api from '@/lib/api';
|
import api from '@/lib/api';
|
||||||
|
import ErrorState from '@/components/ErrorState';
|
||||||
import BillingCycleSelector from '@/components/BillingCycleSelector';
|
import BillingCycleSelector from '@/components/BillingCycleSelector';
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||||
import {
|
import {
|
||||||
@@ -70,29 +72,43 @@ const dailyChartConfig = {
|
|||||||
|
|
||||||
export default function Analytics() {
|
export default function Analytics() {
|
||||||
const [cycle, setCycle] = useState<{ year: number; month: number } | null>(null);
|
const [cycle, setCycle] = useState<{ year: number; month: number } | null>(null);
|
||||||
const [byCategory, setByCategory] = useState<CategorySpending[]>([]);
|
const cycleParams: Record<string, string> = cycle
|
||||||
const [trend, setTrend] = useState<MonthlyTrend[]>([]);
|
? { cycle_year: String(cycle.year), cycle_month: String(cycle.month) }
|
||||||
const [daily, setDaily] = useState<DailySpending[]>([]);
|
: {};
|
||||||
|
|
||||||
useEffect(() => {
|
const byCategoryQ = useQuery({
|
||||||
const params: Record<string, string> = {};
|
queryKey: ['analytics', 'by-category', cycle],
|
||||||
if (cycle) {
|
queryFn: ({ signal }) =>
|
||||||
params.cycle_year = String(cycle.year);
|
api
|
||||||
params.cycle_month = String(cycle.month);
|
.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([
|
const byCategory = byCategoryQ.data ?? [];
|
||||||
api.get<CategorySpending[]>('/analytics/by-category', { params }),
|
const trend = trendQ.data ?? [];
|
||||||
api.get<MonthlyTrend[]>('/analytics/monthly-trend'),
|
const daily = dailyQ.data ?? [];
|
||||||
api.get<DailySpending[]>('/analytics/daily-spending', { params }),
|
const anyError = byCategoryQ.isError || trendQ.isError || dailyQ.isError;
|
||||||
])
|
const retryAll = () => {
|
||||||
.then(([catRes, trendRes, dailyRes]) => {
|
byCategoryQ.refetch();
|
||||||
setByCategory(catRes.data);
|
trendQ.refetch();
|
||||||
setTrend(trendRes.data);
|
dailyQ.refetch();
|
||||||
setDaily(dailyRes.data);
|
};
|
||||||
})
|
|
||||||
.catch(console.error);
|
|
||||||
}, [cycle]);
|
|
||||||
|
|
||||||
// Build dynamic chart config for pie chart
|
// Build dynamic chart config for pie chart
|
||||||
const pieChartConfig = byCategory.reduce<ChartConfig>((acc, cat, i) => {
|
const pieChartConfig = byCategory.reduce<ChartConfig>((acc, cat, i) => {
|
||||||
@@ -116,6 +132,13 @@ export default function Analytics() {
|
|||||||
<BillingCycleSelector value={cycle} onChange={setCycle} />
|
<BillingCycleSelector value={cycle} onChange={setCycle} />
|
||||||
</div>
|
</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">
|
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||||
{/* Spending by Category - Donut */}
|
{/* Spending by Category - Donut */}
|
||||||
<Card>
|
<Card>
|
||||||
|
|||||||
@@ -1,10 +1,13 @@
|
|||||||
import { useState, useEffect, useCallback } from 'react';
|
import { useState, useCallback } from 'react';
|
||||||
import { ChevronLeft, ChevronRight, Calculator } from 'lucide-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 api, { type Transaction } from '@/lib/api';
|
||||||
import { useBudget } from '@/hooks/useBudget';
|
import { useBudget } from '@/hooks/useBudget';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||||
|
import ErrorState from '@/components/ErrorState';
|
||||||
import MonthlyDetail from '@/components/budget/MonthlyDetail';
|
import MonthlyDetail from '@/components/budget/MonthlyDetail';
|
||||||
import RecurringItemsManager from '@/components/budget/RecurringItemsManager';
|
import RecurringItemsManager from '@/components/budget/RecurringItemsManager';
|
||||||
import TransactionList from '@/components/TransactionList';
|
import TransactionList from '@/components/TransactionList';
|
||||||
@@ -27,28 +30,25 @@ export default function Budget() {
|
|||||||
monthDetail,
|
monthDetail,
|
||||||
recurringItems,
|
recurringItems,
|
||||||
monthLoading,
|
monthLoading,
|
||||||
|
error: budgetError,
|
||||||
addItem,
|
addItem,
|
||||||
updateItem,
|
updateItem,
|
||||||
deleteItem,
|
deleteItem,
|
||||||
refresh,
|
refresh,
|
||||||
} = useBudget(currentYear);
|
} = useBudget(currentYear);
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
const [subTab, setSubTab] = useState<'detail' | 'transactions'>('detail');
|
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 [txSearch, setTxSearch] = useState('');
|
||||||
const [txSource, setTxSource] = useState<'CREDIT_CARD' | 'CASH_AND_TRANSFER'>('CREDIT_CARD');
|
const [txSource, setTxSource] = useState<'CREDIT_CARD' | 'CASH_AND_TRANSFER'>('CREDIT_CARD');
|
||||||
|
|
||||||
const fetchTransactions = useCallback(async () => {
|
const txQuery = useQuery({
|
||||||
setTxLoading(true);
|
queryKey: ['transactions', 'budget', year, selectedMonth, txSource, txSearch],
|
||||||
try {
|
queryFn: async ({ signal }) => {
|
||||||
const params: Record<string, string | number | boolean | undefined> = {
|
const params: Record<string, string | number | boolean | undefined> = {
|
||||||
search: txSearch || undefined,
|
search: txSearch || undefined,
|
||||||
limit: 200,
|
limit: 200,
|
||||||
};
|
};
|
||||||
|
|
||||||
if (txSource === 'CREDIT_CARD') {
|
if (txSource === 'CREDIT_CARD') {
|
||||||
params.source = 'CREDIT_CARD';
|
params.source = 'CREDIT_CARD';
|
||||||
// Credit card: billing cycle that ends around the 18th of selectedMonth
|
// Credit card: billing cycle that ends around the 18th of selectedMonth
|
||||||
@@ -66,33 +66,41 @@ export default function Budget() {
|
|||||||
params.start_date = startDate;
|
params.start_date = startDate;
|
||||||
params.end_date = endDate;
|
params.end_date = endDate;
|
||||||
}
|
}
|
||||||
|
const { data } = await api.get<Transaction[]>('/transactions/', { params, signal });
|
||||||
const { data } = await api.get<Transaction[]>('/transactions/', { params });
|
|
||||||
const INCOME_TYPES = ['DEPOSITO', 'SALARY'];
|
const INCOME_TYPES = ['DEPOSITO', 'SALARY'];
|
||||||
const filtered = data.filter((tx) => !INCOME_TYPES.includes(tx.transaction_type));
|
return data.filter((tx) => !INCOME_TYPES.includes(tx.transaction_type));
|
||||||
setTransactions(filtered);
|
},
|
||||||
} finally {
|
placeholderData: (prev) => prev,
|
||||||
setTxLoading(false);
|
});
|
||||||
}
|
const transactions = txQuery.data ?? [];
|
||||||
}, [year, selectedMonth, txSource, txSearch]);
|
|
||||||
|
const invalidateTransactionsAndBudget = useCallback(() => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['transactions'] });
|
||||||
|
refresh();
|
||||||
|
}, [queryClient, refresh]);
|
||||||
|
|
||||||
const handleToggleDeferred = useCallback(async (tx: Transaction) => {
|
const handleToggleDeferred = useCallback(async (tx: Transaction) => {
|
||||||
|
try {
|
||||||
await api.patch(`/transactions/${tx.id}`, {
|
await api.patch(`/transactions/${tx.id}`, {
|
||||||
deferred_to_next_cycle: !tx.deferred_to_next_cycle,
|
deferred_to_next_cycle: !tx.deferred_to_next_cycle,
|
||||||
});
|
});
|
||||||
fetchTransactions();
|
toast.success(
|
||||||
refresh();
|
tx.deferred_to_next_cycle
|
||||||
}, [fetchTransactions, refresh]);
|
? '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(() => {
|
const handleNavigateToTransactions = useCallback(() => {
|
||||||
setTxSource('CASH_AND_TRANSFER');
|
setTxSource('CASH_AND_TRANSFER');
|
||||||
setSubTab('transactions');
|
setSubTab('transactions');
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
fetchTransactions();
|
|
||||||
}, [fetchTransactions]);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
{/* Header */}
|
{/* Header */}
|
||||||
@@ -154,11 +162,15 @@ export default function Budget() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<TabsContent value="detail" className="space-y-6 mt-4">
|
<TabsContent value="detail" className="space-y-6 mt-4">
|
||||||
|
{budgetError ? (
|
||||||
|
<ErrorState onRetry={refresh} />
|
||||||
|
) : (
|
||||||
<MonthlyDetail
|
<MonthlyDetail
|
||||||
detail={monthDetail}
|
detail={monthDetail}
|
||||||
loading={monthLoading || !monthDetail}
|
loading={monthLoading || !monthDetail}
|
||||||
onNavigateToTransactions={handleNavigateToTransactions}
|
onNavigateToTransactions={handleNavigateToTransactions}
|
||||||
/>
|
/>
|
||||||
|
)}
|
||||||
</TabsContent>
|
</TabsContent>
|
||||||
|
|
||||||
<TabsContent value="transactions" className="space-y-3 mt-4">
|
<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>
|
<TabsTrigger value="CASH_AND_TRANSFER">Efectivo y Transferencias</TabsTrigger>
|
||||||
</TabsList>
|
</TabsList>
|
||||||
</Tabs>
|
</Tabs>
|
||||||
|
{txQuery.isError ? (
|
||||||
|
<ErrorState
|
||||||
|
message="No se pudieron cargar las transacciones"
|
||||||
|
onRetry={() => txQuery.refetch()}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
<TransactionList
|
<TransactionList
|
||||||
transactions={transactions}
|
transactions={transactions}
|
||||||
loading={txLoading}
|
loading={txQuery.isPending}
|
||||||
source={txSource === 'CREDIT_CARD' ? 'CREDIT_CARD' : 'CASH'}
|
source={txSource === 'CREDIT_CARD' ? 'CREDIT_CARD' : 'CASH'}
|
||||||
search={txSearch}
|
search={txSearch}
|
||||||
onSearchChange={setTxSearch}
|
onSearchChange={setTxSearch}
|
||||||
onRefresh={() => {
|
onRefresh={invalidateTransactionsAndBudget}
|
||||||
fetchTransactions();
|
|
||||||
refresh();
|
|
||||||
}}
|
|
||||||
showCategory={txSource === 'CREDIT_CARD'}
|
showCategory={txSource === 'CREDIT_CARD'}
|
||||||
showSourceIcon={txSource === 'CASH_AND_TRANSFER'}
|
showSourceIcon={txSource === 'CASH_AND_TRANSFER'}
|
||||||
emptyMessage={`Sin transacciones de ${txSource === 'CREDIT_CARD' ? 'tarjeta' : 'efectivo o transferencia'} en ${MONTH_NAMES[selectedMonth]}`}
|
emptyMessage={`Sin transacciones de ${txSource === 'CREDIT_CARD' ? 'tarjeta' : 'efectivo o transferencia'} en ${MONTH_NAMES[selectedMonth]}`}
|
||||||
onToggleDeferred={txSource === 'CREDIT_CARD' ? handleToggleDeferred : undefined}
|
onToggleDeferred={txSource === 'CREDIT_CARD' ? handleToggleDeferred : undefined}
|
||||||
/>
|
/>
|
||||||
|
)}
|
||||||
</TabsContent>
|
</TabsContent>
|
||||||
</Tabs>
|
</Tabs>
|
||||||
</TabsContent>
|
</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 {
|
import {
|
||||||
LineChart,
|
LineChart,
|
||||||
Line,
|
Line,
|
||||||
@@ -238,9 +240,9 @@ function ChartTooltipContent({
|
|||||||
|
|
||||||
// ─── Main Component ───────────────────────────────────────────────────────────
|
// ─── Main Component ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
const EMPTY_SNAPSHOTS: PensionSnapshot[] = [];
|
||||||
|
|
||||||
export default function Pensions() {
|
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 [visibleFunds, setVisibleFunds] = useState<Set<FundKey>>(new Set(FUND_KEYS));
|
||||||
const [projections, setProjections] = useState<Record<FundKey, ProjectionState>>({
|
const [projections, setProjections] = useState<Record<FundKey, ProjectionState>>({
|
||||||
FCL: { contribution: 150_000, rate: 7.5, targetAge: 35 },
|
FCL: { contribution: 150_000, rate: 7.5, targetAge: 35 },
|
||||||
@@ -254,22 +256,22 @@ export default function Pensions() {
|
|||||||
const [showManualEntry, setShowManualEntry] = useState(false);
|
const [showManualEntry, setShowManualEntry] = useState(false);
|
||||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||||
|
|
||||||
const loadData = useCallback(async () => {
|
const pensionQ = useQuery({
|
||||||
try {
|
queryKey: ['pensions'],
|
||||||
|
queryFn: async () => {
|
||||||
const [summaryRes, snapshotsRes] = await Promise.all([
|
const [summaryRes, snapshotsRes] = await Promise.all([
|
||||||
getPensionFundSummary(),
|
getPensionFundSummary(),
|
||||||
getPensionSnapshots(),
|
getPensionSnapshots(),
|
||||||
]);
|
]);
|
||||||
setFundSummary(summaryRes.data);
|
return { summary: summaryRes.data, snapshots: snapshotsRes.data };
|
||||||
setAllSnapshots(snapshotsRes.data);
|
},
|
||||||
} catch {
|
});
|
||||||
// API not available or no data yet — use defaults
|
const fundSummary = pensionQ.data?.summary ?? EMPTY_SNAPSHOTS;
|
||||||
}
|
const allSnapshots = pensionQ.data?.snapshots ?? EMPTY_SNAPSHOTS;
|
||||||
}, []);
|
const loadData = useCallback(async () => {
|
||||||
|
await pensionQ.refetch();
|
||||||
useEffect(() => {
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
loadData();
|
}, [pensionQ.refetch]);
|
||||||
}, [loadData]);
|
|
||||||
|
|
||||||
const FUNDS = useMemo(() => applySnapshots(fundSummary), [fundSummary]);
|
const FUNDS = useMemo(() => applySnapshots(fundSummary), [fundSummary]);
|
||||||
|
|
||||||
@@ -392,6 +394,12 @@ export default function Pensions() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-8">
|
<div className="space-y-8">
|
||||||
|
{pensionQ.isError && (
|
||||||
|
<ErrorState
|
||||||
|
message="No se pudieron cargar los datos de pensiones"
|
||||||
|
onRetry={() => pensionQ.refetch()}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
{/* ── Page Header ─────────────────────────────────────────────────── */}
|
{/* ── Page Header ─────────────────────────────────────────────────── */}
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
<div className="w-10 h-10 rounded-lg bg-primary/10 flex items-center justify-center">
|
<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 && (
|
{uploadResult.snapshots.length > 0 && (
|
||||||
<div className="space-y-1 pt-1">
|
<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">
|
<div key={snap.id} className="flex items-center justify-between text-xs">
|
||||||
<span className="text-muted-foreground">
|
<span className="text-muted-foreground">
|
||||||
{snap.fund} · {new Date(snap.period_start).toLocaleDateString('es-CR', { month: 'short', year: '2-digit' })}
|
{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>
|
<span data-sensitive className="font-mono font-medium">{formatCRC(snap.saldo_final)}</span>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
|
{uploadResult.snapshots.length > 10 && (
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
… y {uploadResult.snapshots.length - 10} más
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { formatAmount } from '@/lib/format';
|
|||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Card, CardContent } from '@/components/ui/card';
|
import { Card, CardContent } from '@/components/ui/card';
|
||||||
|
import ErrorState from '@/components/ErrorState';
|
||||||
import YearlyOverview from '@/components/budget/YearlyOverview';
|
import YearlyOverview from '@/components/budget/YearlyOverview';
|
||||||
|
|
||||||
const MIN_YEAR = 2026;
|
const MIN_YEAR = 2026;
|
||||||
@@ -19,6 +20,8 @@ export default function Proyecciones() {
|
|||||||
setSelectedMonth,
|
setSelectedMonth,
|
||||||
projection,
|
projection,
|
||||||
loading,
|
loading,
|
||||||
|
error,
|
||||||
|
refresh,
|
||||||
saveBalanceOverride,
|
saveBalanceOverride,
|
||||||
clearBalanceOverride,
|
clearBalanceOverride,
|
||||||
} = useBudget(currentYear);
|
} = useBudget(currentYear);
|
||||||
@@ -89,6 +92,9 @@ export default function Proyecciones() {
|
|||||||
) : projection ? (
|
) : projection ? (
|
||||||
<Card>
|
<Card>
|
||||||
<CardContent className="p-0">
|
<CardContent className="p-0">
|
||||||
|
{error ? (
|
||||||
|
<ErrorState onRetry={refresh} />
|
||||||
|
) : (
|
||||||
<YearlyOverview
|
<YearlyOverview
|
||||||
months={projection.months}
|
months={projection.months}
|
||||||
selectedMonth={0}
|
selectedMonth={0}
|
||||||
@@ -104,6 +110,7 @@ export default function Proyecciones() {
|
|||||||
await clearBalanceOverride(year, month);
|
await clearBalanceOverride(year, month);
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
)}
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
) : null}
|
) : 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 { type ColumnDef } from '@tanstack/react-table';
|
||||||
import { Landmark, RefreshCw, Hash, CalendarDays, Banknote } from 'lucide-react';
|
import { Landmark, RefreshCw, Hash, CalendarDays, Banknote } from 'lucide-react';
|
||||||
|
|
||||||
import { type Transaction, type SalariosSummary, getSalarios, getSalariosSummary } from '@/lib/api';
|
import { type Transaction, type SalariosSummary, getSalarios, getSalariosSummary } from '@/lib/api';
|
||||||
import { formatAmount, formatDate } from '@/lib/format';
|
import { formatAmount, formatDate } from '@/lib/format';
|
||||||
|
import ErrorState from '@/components/ErrorState';
|
||||||
import { DataTable } from '@/components/ui/data-table';
|
import { DataTable } from '@/components/ui/data-table';
|
||||||
import { DataTableColumnHeader } from '@/components/ui/data-table-column-header';
|
import { DataTableColumnHeader } from '@/components/ui/data-table-column-header';
|
||||||
import { Card, CardContent } from '@/components/ui/card';
|
import { Card, CardContent } from '@/components/ui/card';
|
||||||
@@ -11,27 +13,20 @@ import { Button } from '@/components/ui/button';
|
|||||||
import { Badge } from '@/components/ui/badge';
|
import { Badge } from '@/components/ui/badge';
|
||||||
|
|
||||||
export default function Salarios() {
|
export default function Salarios() {
|
||||||
const [deposits, setDeposits] = useState<Transaction[]>([]);
|
const query = useQuery({
|
||||||
const [summary, setSummary] = useState<SalariosSummary | null>(null);
|
queryKey: ['salarios'],
|
||||||
const [loading, setLoading] = useState(true);
|
queryFn: async () => {
|
||||||
|
|
||||||
const fetchData = async () => {
|
|
||||||
setLoading(true);
|
|
||||||
try {
|
|
||||||
const [depRes, sumRes] = await Promise.all([
|
const [depRes, sumRes] = await Promise.all([
|
||||||
getSalarios({ limit: 500 }),
|
getSalarios({ limit: 500 }),
|
||||||
getSalariosSummary(),
|
getSalariosSummary(),
|
||||||
]);
|
]);
|
||||||
setDeposits(depRes.data);
|
return { deposits: depRes.data, summary: sumRes.data };
|
||||||
setSummary(sumRes.data);
|
},
|
||||||
} catch (e) {
|
});
|
||||||
console.error(e);
|
const deposits = query.data?.deposits ?? [];
|
||||||
} finally {
|
const summary = query.data?.summary ?? null;
|
||||||
setLoading(false);
|
const loading = query.isFetching;
|
||||||
}
|
const fetchData = () => query.refetch();
|
||||||
};
|
|
||||||
|
|
||||||
useEffect(() => { fetchData(); }, []);
|
|
||||||
|
|
||||||
const columns = useMemo<ColumnDef<Transaction, unknown>[]>(
|
const columns = useMemo<ColumnDef<Transaction, unknown>[]>(
|
||||||
() => [
|
() => [
|
||||||
@@ -146,6 +141,12 @@ export default function Salarios() {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Data table */}
|
{/* Data table */}
|
||||||
|
{query.isError ? (
|
||||||
|
<ErrorState
|
||||||
|
message="No se pudieron cargar los salarios"
|
||||||
|
onRetry={fetchData}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
<Card>
|
<Card>
|
||||||
<CardContent className="p-0">
|
<CardContent className="p-0">
|
||||||
<DataTable
|
<DataTable
|
||||||
@@ -158,6 +159,7 @@ export default function Salarios() {
|
|||||||
/>
|
/>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
)}
|
||||||
</div>
|
</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 {
|
import {
|
||||||
BarChart,
|
BarChart,
|
||||||
Bar,
|
Bar,
|
||||||
@@ -179,10 +181,10 @@ function ChartTooltipContent({
|
|||||||
|
|
||||||
// ─── Main Component ──────────────────────────────────────────────────────────
|
// ─── Main Component ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
const EMPTY_RECEIPTS: MunicipalReceipt[] = [];
|
||||||
|
const EMPTY_READINGS: WaterMeterReading[] = [];
|
||||||
|
|
||||||
export default function ServiciosMunicipales() {
|
export default function ServiciosMunicipales() {
|
||||||
const [receipts, setReceipts] = useState<MunicipalReceipt[]>([]);
|
|
||||||
const [waterReadings, setWaterReadings] = useState<WaterMeterReading[]>([]);
|
|
||||||
const [loading, setLoading] = useState(true);
|
|
||||||
|
|
||||||
// Chart visibility state
|
// Chart visibility state
|
||||||
const [hiddenMeters, setHiddenMeters] = useState<Set<string>>(new Set());
|
const [hiddenMeters, setHiddenMeters] = useState<Set<string>>(new Set());
|
||||||
@@ -195,25 +197,23 @@ export default function ServiciosMunicipales() {
|
|||||||
const [uploadResults, setUploadResults] = useState<MunicipalReceiptUploadResult[]>([]);
|
const [uploadResults, setUploadResults] = useState<MunicipalReceiptUploadResult[]>([]);
|
||||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||||
|
|
||||||
const loadData = useCallback(async () => {
|
const municipalQ = useQuery({
|
||||||
setLoading(true);
|
queryKey: ['municipal'],
|
||||||
try {
|
queryFn: async () => {
|
||||||
const [receiptsRes, waterRes] = await Promise.all([
|
const [receiptsRes, waterRes] = await Promise.all([
|
||||||
getMunicipalReceipts(),
|
getMunicipalReceipts(),
|
||||||
getWaterConsumption(24),
|
getWaterConsumption(24),
|
||||||
]);
|
]);
|
||||||
setReceipts(receiptsRes.data);
|
return { receipts: receiptsRes.data, water: waterRes.data };
|
||||||
setWaterReadings(waterRes.data);
|
},
|
||||||
} catch {
|
});
|
||||||
// API not available yet
|
const receipts = municipalQ.data?.receipts ?? EMPTY_RECEIPTS;
|
||||||
} finally {
|
const waterReadings = municipalQ.data?.water ?? EMPTY_READINGS;
|
||||||
setLoading(false);
|
const loading = municipalQ.isPending;
|
||||||
}
|
const loadData = useCallback(async () => {
|
||||||
}, []);
|
await municipalQ.refetch();
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
useEffect(() => {
|
}, [municipalQ.refetch]);
|
||||||
loadData();
|
|
||||||
}, [loadData]);
|
|
||||||
|
|
||||||
// Derived data
|
// Derived data
|
||||||
const chartData = useMemo(() => buildChartData(waterReadings), [waterReadings]);
|
const chartData = useMemo(() => buildChartData(waterReadings), [waterReadings]);
|
||||||
@@ -291,6 +291,12 @@ export default function ServiciosMunicipales() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-8">
|
<div className="space-y-8">
|
||||||
|
{municipalQ.isError && (
|
||||||
|
<ErrorState
|
||||||
|
message="No se pudieron cargar los recibos municipales"
|
||||||
|
onRetry={() => municipalQ.refetch()}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
{/* ── Page Header ─────────────────────────────────────────────────── */}
|
{/* ── Page Header ─────────────────────────────────────────────────── */}
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
<div className="w-10 h-10 rounded-lg bg-primary/10 flex items-center justify-center">
|
<div className="w-10 h-10 rounded-lg bg-primary/10 flex items-center justify-center">
|
||||||
|
|||||||
Reference in New Issue
Block a user