Compare commits

...

3 Commits

Author SHA1 Message Date
Jose Selesan
d156a2a8a4 fix(analysis): mark sub-inflation growth orange and show 12 inflation months
Reserve red for negative variations across all currency columns and the total row. Show the last 12 months with inflation data plus the trailing months without it, and compute the accumulated inflation and total variation over the same 12-month window. Extend the monthly-last backend window to 15 months.
2026-11-19 15:29:11 -03:00
Jose Selesan
e5382670a5 fix(web): cache hashed assets immutably and never cache the SPA shell
Hash-named assets under /assets can be cached for a year with immutable,
but index.html must not be cached. Otherwise a previously cached shell
keeps loading the old bundle after a deploy, masking frontend fixes (e.g.
the monthly variation table still rendering the old extra blank row).
2026-10-14 12:44:09 -03:00
Jose Selesan
15c77c07cf fix(lint): resolve Biome errors and migrate config
- migrate biome.json to schema 2.5.10 (preset instead of recommended)
- apply safe fixes: formatting, import organization, unused imports/vars
- use node:crypto import protocol
- drop unused catch bindings
- a11y: associate labels with controls via htmlFor/id (add optional id to
  DatePicker), hide decorative SVGs from AT, and replace the custom
  role="checkbox" button with a native checkbox input
- remove unnecessary pageSize dependency from useMemo
2026-10-14 12:44:07 -03:00
31 changed files with 304 additions and 261 deletions

View File

@@ -38,8 +38,28 @@ app.route("/api", expensesRouter);
app.route("/api/telegram", telegramRouter); app.route("/api/telegram", telegramRouter);
app.route("/api/wallets", walletsRouter); app.route("/api/wallets", walletsRouter);
app.use("/assets/*", serveStatic({ root: "./web" })); // Los assets incluyen un hash en el nombre, así que se pueden cachear para
app.get("*", serveStatic({ path: "./web/index.html" })); // siempre. El index.html no debe cachearse: referencia los assets con hash y,
// si queda cacheado, el navegador sigue sirviendo el bundle viejo después de
// un deploy (por eso una nueva versión no se ve hasta un hard refresh).
app.use(
"/assets/*",
serveStatic({
root: "./web",
onFound: (_path, c) => {
c.header("Cache-Control", "public, max-age=31536000, immutable");
},
}),
);
app.get(
"*",
serveStatic({
path: "./web/index.html",
onFound: (_path, c) => {
c.header("Cache-Control", "no-cache");
},
}),
);
eventBus.on("quotes-updated", () => { eventBus.on("quotes-updated", () => {
cache.invalidateByPrefix("quotes:"); cache.invalidateByPrefix("quotes:");

View File

@@ -1,5 +1,9 @@
import { z } from "zod"; import { z } from "zod";
import { PaymentStatus, QuoteType, type Prisma } from "../../generated/prisma/client"; import {
PaymentStatus,
type Prisma,
QuoteType,
} from "../../generated/prisma/client";
import { cache } from "../../lib/cache"; import { cache } from "../../lib/cache";
import { prisma } from "../../lib/prisma"; import { prisma } from "../../lib/prisma";
import { roundTo } from "../../lib/utils"; import { roundTo } from "../../lib/utils";
@@ -87,7 +91,10 @@ export async function getBeloSellPriceForDate(
paymentDate.getUTCFullYear(), paymentDate.getUTCFullYear(),
paymentDate.getUTCMonth(), paymentDate.getUTCMonth(),
paymentDate.getUTCDate(), paymentDate.getUTCDate(),
17, 0, 0, 0, 17,
0,
0,
0,
), ),
); );
@@ -240,7 +247,9 @@ export async function createNonPeriodicExpense(
const isUSDC = wallet.currency === "USDC"; const isUSDC = wallet.currency === "USDC";
if (isUSDC && !data.usdcConversionRate) { if (isUSDC && !data.usdcConversionRate) {
throw new Error("La tasa de conversión es obligatoria para billeteras USDC"); throw new Error(
"La tasa de conversión es obligatoria para billeteras USDC",
);
} }
const belo = isUSDC ? null : await getBeloSellPriceForDate(dueDate); const belo = isUSDC ? null : await getBeloSellPriceForDate(dueDate);
@@ -313,12 +322,15 @@ export async function payExpense(
const isUSDC = wallet.currency === "USDC"; const isUSDC = wallet.currency === "USDC";
if (isUSDC && !data.usdcConversionRate) { if (isUSDC && !data.usdcConversionRate) {
throw new Error("La tasa de conversión es obligatoria para billeteras USDC"); throw new Error(
"La tasa de conversión es obligatoria para billeteras USDC",
);
} }
const belo = isUSDC ? null : await getBeloSellPriceForDate(paymentDate); const belo = isUSDC ? null : await getBeloSellPriceForDate(paymentDate);
const movementAmount = isUSDC && data.usdcConversionRate const movementAmount =
isUSDC && data.usdcConversionRate
? -roundTo(data.amountPayed / data.usdcConversionRate, 4) ? -roundTo(data.amountPayed / data.usdcConversionRate, 4)
: -data.amountPayed; : -data.amountPayed;
@@ -331,7 +343,10 @@ export async function payExpense(
if (isUSDC && data.usdcConversionRate) { if (isUSDC && data.usdcConversionRate) {
expenseUpdateData.beloPrice = data.usdcConversionRate; expenseUpdateData.beloPrice = data.usdcConversionRate;
expenseUpdateData.usdcEquivalent = roundTo(data.amountPayed / data.usdcConversionRate, 6); expenseUpdateData.usdcEquivalent = roundTo(
data.amountPayed / data.usdcConversionRate,
6,
);
} else if (belo !== null) { } else if (belo !== null) {
expenseUpdateData.beloPrice = belo; expenseUpdateData.beloPrice = belo;
expenseUpdateData.usdcEquivalent = roundTo(data.amountPayed / belo, 6); expenseUpdateData.usdcEquivalent = roundTo(data.amountPayed / belo, 6);
@@ -405,11 +420,16 @@ export async function updateExpense(
updateData.paymentDate = new Date(data.paymentDate); updateData.paymentDate = new Date(data.paymentDate);
} }
const resolvedPaymentDate = updateData.paymentDate instanceof Date const resolvedPaymentDate =
updateData.paymentDate instanceof Date
? updateData.paymentDate ? updateData.paymentDate
: (existing.paymentDate ?? undefined); : (existing.paymentDate ?? undefined);
const amountPayed = updateData.amountPayed ?? existing.amountPayed; const amountPayed = updateData.amountPayed ?? existing.amountPayed;
if (resolvedPaymentDate && amountPayed !== undefined && amountPayed !== null) { if (
resolvedPaymentDate &&
amountPayed !== undefined &&
amountPayed !== null
) {
const belo = await getBeloSellPriceForDate(resolvedPaymentDate); const belo = await getBeloSellPriceForDate(resolvedPaymentDate);
if (belo !== null) { if (belo !== null) {
updateData.beloPrice = belo; updateData.beloPrice = belo;
@@ -424,7 +444,8 @@ export async function updateExpense(
const oldPayed = existing.amountPayed const oldPayed = existing.amountPayed
? Number(existing.amountPayed) ? Number(existing.amountPayed)
: Number(existing.amount); : Number(existing.amount);
const newPayed = data.amountPayed !== undefined const newPayed =
data.amountPayed !== undefined
? Number(data.amountPayed) ? Number(data.amountPayed)
: Number(data.amount); : Number(data.amount);

View File

@@ -36,18 +36,20 @@ function subtractMonths(date: Date, months: number): Date {
return new Date(date.getFullYear(), date.getMonth() - months, 1); return new Date(date.getFullYear(), date.getMonth() - months, 1);
} }
// La tabla muestra 12 meses, pero traemos un mes extra al principio para poder // La tabla compara 12 meses con dato de inflación. El mes actual y, a veces,
// calcular la variación del mes más antiguo mostrado (necesita su mes previo). // el anterior todavía no tienen inflación publicada, así que sumamos esos 2
const DISPLAY_MONTHS = 12; // meses y uno más al inicio como base para calcular la variación del mes más
// antiguo mostrado. El rango es inclusivo, por eso se resta 1 al mes actual.
const TOTAL_MONTHS = 15;
export async function getMonthlyLast(c: Context) { export async function getMonthlyLast(c: Context) {
const cacheKey = "quotes:monthly-last-v3"; const cacheKey = "quotes:monthly-last-v4";
const cached = cache.get(cacheKey); const cached = cache.get(cacheKey);
if (cached) return c.json(cached); if (cached) return c.json(cached);
const today = new Date(); const today = new Date();
const currentMonthKey = getMonthKey(today); const currentMonthKey = getMonthKey(today);
const startMonth = subtractMonths(today, DISPLAY_MONTHS); const startMonth = subtractMonths(today, TOTAL_MONTHS - 1);
const startDate = new Date( const startDate = new Date(
startMonth.getFullYear(), startMonth.getFullYear(),

View File

@@ -1,5 +1,4 @@
import type { Context } from "hono"; import type { Context } from "hono";
import type { QuoteType } from "../../../generated/prisma/client";
import { cache } from "../../../lib/cache"; import { cache } from "../../../lib/cache";
import { prisma } from "../../../lib/prisma"; import { prisma } from "../../../lib/prisma";

View File

@@ -5,7 +5,7 @@ export async function generateCodeHandler(c: Context) {
try { try {
const result = await generateCode(); const result = await generateCode();
return c.json(result); return c.json(result);
} catch (error) { } catch {
return c.json({ error: "Failed to generate code" }, 500); return c.json({ error: "Failed to generate code" }, 500);
} }
} }
@@ -14,7 +14,7 @@ export async function telegramStatusHandler(c: Context) {
try { try {
const status = await getTelegramStatus(); const status = await getTelegramStatus();
return c.json(status); return c.json(status);
} catch (error) { } catch {
return c.json({ connected: false, botUsername: null }, 500); return c.json({ connected: false, botUsername: null }, 500);
} }
} }

View File

@@ -1,4 +1,4 @@
import crypto from "crypto"; import crypto from "node:crypto";
import type { QuoteType } from "../../generated/prisma/client"; import type { QuoteType } from "../../generated/prisma/client";
import { logger } from "../../lib/logger"; import { logger } from "../../lib/logger";
import { prisma } from "../../lib/prisma"; import { prisma } from "../../lib/prisma";

View File

@@ -1,8 +1,5 @@
import type { Context } from "hono"; import type { Context } from "hono";
import { import { adjustBalance, adjustBalanceSchema } from "../wallets.service";
adjustBalance,
adjustBalanceSchema,
} from "../wallets.service";
export async function adjustBalanceHandler(c: Context) { export async function adjustBalanceHandler(c: Context) {
const id = Number(c.req.param("id")); const id = Number(c.req.param("id"));

View File

@@ -1,8 +1,5 @@
import type { Context } from "hono"; import type { Context } from "hono";
import { import { createWallet, createWalletSchema } from "../wallets.service";
createWallet,
createWalletSchema,
} from "../wallets.service";
export async function createWalletHandler(c: Context) { export async function createWalletHandler(c: Context) {
const body = await c.req.json(); const body = await c.req.json();

View File

@@ -1,8 +1,5 @@
import type { Context } from "hono"; import type { Context } from "hono";
import { import { depositSchema, depositWallet } from "../wallets.service";
depositWallet,
depositSchema,
} from "../wallets.service";
export async function depositWalletHandler(c: Context) { export async function depositWalletHandler(c: Context) {
const id = Number(c.req.param("id")); const id = Number(c.req.param("id"));

View File

@@ -1,8 +1,5 @@
import type { Context } from "hono"; import type { Context } from "hono";
import { import { transferSchema, transferWallet } from "../wallets.service";
transferSchema,
transferWallet,
} from "../wallets.service";
export async function transferWalletHandler(c: Context) { export async function transferWalletHandler(c: Context) {
const body = await c.req.json(); const body = await c.req.json();

View File

@@ -1,8 +1,5 @@
import type { Context } from "hono"; import type { Context } from "hono";
import { import { updateWallet, updateWalletSchema } from "../wallets.service";
updateWallet,
updateWalletSchema,
} from "../wallets.service";
export async function updateWalletHandler(c: Context) { export async function updateWalletHandler(c: Context) {
const id = Number(c.req.param("id")); const id = Number(c.req.param("id"));

View File

@@ -6,9 +6,9 @@ import { depositWalletHandler } from "./handlers/depositWallet";
import { listAllMovementsHandler } from "./handlers/listAllMovements"; import { listAllMovementsHandler } from "./handlers/listAllMovements";
import { listMovementsHandler } from "./handlers/listMovements"; import { listMovementsHandler } from "./handlers/listMovements";
import { listWalletsHandler } from "./handlers/listWallets"; import { listWalletsHandler } from "./handlers/listWallets";
import { setDefaultWalletHandler } from "./handlers/setDefaultWallet";
import { transferWalletHandler } from "./handlers/transferWallet"; import { transferWalletHandler } from "./handlers/transferWallet";
import { updateWalletHandler } from "./handlers/updateWallet"; import { updateWalletHandler } from "./handlers/updateWallet";
import { setDefaultWalletHandler } from "./handlers/setDefaultWallet";
const app = new Hono(); const app = new Hono();

View File

@@ -1,7 +1,6 @@
import { z } from "zod"; import { z } from "zod";
import { Prisma } from "../../generated/prisma/client";
import { prisma } from "../../lib/prisma";
import { cache } from "../../lib/cache"; import { cache } from "../../lib/cache";
import { prisma } from "../../lib/prisma";
export const createWalletSchema = z.object({ export const createWalletSchema = z.object({
name: z.string().min(1).max(100), name: z.string().min(1).max(100),
@@ -80,7 +79,9 @@ export async function updateWallet(id: number, input: UpdateWalletInput) {
export async function deleteWallet(id: number) { export async function deleteWallet(id: number) {
const wallet = await prisma.wallet.findUniqueOrThrow({ where: { id } }); const wallet = await prisma.wallet.findUniqueOrThrow({ where: { id } });
if (Number(wallet.balance) !== 0) { if (Number(wallet.balance) !== 0) {
throw new Error("No se puede eliminar una billetera con saldo distinto de cero"); throw new Error(
"No se puede eliminar una billetera con saldo distinto de cero",
);
} }
await prisma.walletMovement.deleteMany({ where: { walletId: id } }); await prisma.walletMovement.deleteMany({ where: { walletId: id } });
await prisma.wallet.delete({ where: { id } }); await prisma.wallet.delete({ where: { id } });
@@ -182,7 +183,9 @@ export async function setDefaultWallet(walletId: number) {
data: { isDefault: true }, data: { isDefault: true },
}), }),
]); ]);
const wallet = await prisma.wallet.findUniqueOrThrow({ where: { id: walletId } }); const wallet = await prisma.wallet.findUniqueOrThrow({
where: { id: walletId },
});
return { ...wallet, balance: Number(wallet.balance) }; return { ...wallet, balance: Number(wallet.balance) };
} }

View File

@@ -800,7 +800,6 @@ describe("payExpense with BELO", () => {
amountPayed: null, amountPayed: null,
paymentDate: null, paymentDate: null,
}; };
const paymentDate = new Date("2026-06-10T00:00:00.000Z");
const wallet = { id: 1, balance: 100000, currency: "ARS" }; const wallet = { id: 1, balance: 100000, currency: "ARS" };
mockPrisma.expense.findUniqueOrThrow.mockResolvedValueOnce(expense); mockPrisma.expense.findUniqueOrThrow.mockResolvedValueOnce(expense);
mockWalletFindUnique.mockResolvedValueOnce(wallet); mockWalletFindUnique.mockResolvedValueOnce(wallet);
@@ -884,8 +883,7 @@ describe("createNonPeriodicExpense with BELO", () => {
}) })
.mockResolvedValueOnce(null); .mockResolvedValueOnce(null);
mockPrisma.expense.create.mockImplementationOnce( mockPrisma.expense.create.mockImplementationOnce(async ({ data }) => ({
async ({ data }) => ({
id: 1, id: 1,
description: data.description, description: data.description,
amount: data.amount, amount: data.amount,
@@ -893,8 +891,7 @@ describe("createNonPeriodicExpense with BELO", () => {
status: PaymentStatus.PAYED, status: PaymentStatus.PAYED,
beloPrice: data.beloPrice, beloPrice: data.beloPrice,
usdcEquivalent: data.usdcEquivalent, usdcEquivalent: data.usdcEquivalent,
}), }));
);
mockWalletUpdate.mockResolvedValueOnce({ ...wallet, balance: 70000 }); mockWalletUpdate.mockResolvedValueOnce({ ...wallet, balance: 70000 });
mockMovementCreate.mockResolvedValueOnce({ id: 1 }); mockMovementCreate.mockResolvedValueOnce({ id: 1 });
@@ -916,15 +913,13 @@ describe("createNonPeriodicExpense with BELO", () => {
.mockResolvedValueOnce(null) .mockResolvedValueOnce(null)
.mockResolvedValueOnce(null); .mockResolvedValueOnce(null);
mockPrisma.expense.create.mockImplementationOnce( mockPrisma.expense.create.mockImplementationOnce(async ({ data }) => ({
async ({ data }) => ({
id: 1, id: 1,
description: data.description, description: data.description,
amount: data.amount, amount: data.amount,
amountPayed: data.amountPayed, amountPayed: data.amountPayed,
status: PaymentStatus.PAYED, status: PaymentStatus.PAYED,
}), }));
);
mockWalletUpdate.mockResolvedValueOnce({ ...wallet, balance: 97500 }); mockWalletUpdate.mockResolvedValueOnce({ ...wallet, balance: 97500 });
mockMovementCreate.mockResolvedValueOnce({ id: 1 }); mockMovementCreate.mockResolvedValueOnce({ id: 1 });

View File

@@ -24,9 +24,10 @@ type Row = { month: string; type: string; buy: number };
const originalFetch = globalThis.fetch; const originalFetch = globalThis.fetch;
function fakeCasaData(casa: string): unknown[] { // 12 meses con inflación + 2 aún sin dato + 1 mes base, de 2025-08 a 2026-10.
// Un único día por mes, cubriendo de 2025-10 a 2026-10. const MONTHS = [
const months = [ "2025-08",
"2025-09",
"2025-10", "2025-10",
"2025-11", "2025-11",
"2025-12", "2025-12",
@@ -40,8 +41,11 @@ function fakeCasaData(casa: string): unknown[] {
"2026-08", "2026-08",
"2026-09", "2026-09",
"2026-10", "2026-10",
]; ];
return months.map((m, i) => ({
function fakeCasaData(casa: string): unknown[] {
// Un único día por mes.
return MONTHS.map((m, i) => ({
casa, casa,
fecha: `${m}-15`, fecha: `${m}-15`,
compra: 1000 + i, compra: 1000 + i,
@@ -74,57 +78,28 @@ afterEach(() => {
}); });
describe("getMonthlyLast", () => { describe("getMonthlyLast", () => {
test("trae 13 meses (12 a mostrar + 1 base) y no descarta el mes en curso del fallback externo", async () => { test("trae 15 meses (12 con inflación + 2 sin dato + 1 base) y no descarta el mes en curso del fallback externo", async () => {
mockQueryRaw.mockResolvedValue([]); mockQueryRaw.mockResolvedValue([]);
mockExternalApi(); mockExternalApi();
const rows = (await getMonthlyLast(context)) as Row[]; const rows = (await getMonthlyLast(context)) as Row[];
const months = [...new Set(rows.map((r) => r.month))].sort(); const months = [...new Set(rows.map((r) => r.month))].sort();
expect(months).toEqual([ expect(months).toEqual(MONTHS);
"2025-10",
"2025-11",
"2025-12",
"2026-01",
"2026-02",
"2026-03",
"2026-04",
"2026-05",
"2026-06",
"2026-07",
"2026-08",
"2026-09",
"2026-10",
]);
// Regresión: "2026-10-14" > "2026-10" siempre daba true y el mes más // Regresión: "2026-10-14" > "2026-10" siempre daba true y el mes más
// reciente nunca llegaba desde la API externa. // reciente nunca llegaba desde la API externa.
expect(rows).toContainEqual({ expect(rows).toContainEqual({
month: "2026-10", month: "2026-10",
type: "BELO", type: "BELO",
buy: 1012, buy: 1014,
source: "external", source: "external",
}); });
}); });
test("usa la DB cuando el dato existe y no pega a la API externa", async () => { test("usa la DB cuando el dato existe y no pega a la API externa", async () => {
const dbRows: Row[] = []; const dbRows: Row[] = [];
const months = [ for (const month of MONTHS) {
"2025-10",
"2025-11",
"2025-12",
"2026-01",
"2026-02",
"2026-03",
"2026-04",
"2026-05",
"2026-06",
"2026-07",
"2026-08",
"2026-09",
"2026-10",
];
for (const month of months) {
for (const type of ["BELO", "BLUE", "BNA"]) { for (const type of ["BELO", "BLUE", "BNA"]) {
dbRows.push({ month, type, buy: 500 }); dbRows.push({ month, type, buy: 500 });
} }
@@ -138,6 +113,6 @@ describe("getMonthlyLast", () => {
expect(fetchMock).not.toHaveBeenCalled(); expect(fetchMock).not.toHaveBeenCalled();
expect(rows.every((r) => r.source === "db")).toBe(true); expect(rows.every((r) => r.source === "db")).toBe(true);
expect(rows).toHaveLength(13 * 3); expect(rows).toHaveLength(MONTHS.length * 3);
}); });
}); });

View File

@@ -8,16 +8,19 @@ function TelegramIcon(props: { className?: string }) {
fill="currentColor" fill="currentColor"
className={props.className} className={props.className}
xmlns="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg"
aria-hidden="true"
focusable="false"
> >
<path d="M11.944 0A12 12 0 0 0 0 12a12 12 0 0 0 12 12 12 12 0 0 0 12-12A12 12 0 0 0 12 0a12 12 0 0 0-.056 0zm4.962 7.224c.1-.002.321.023.465.14a.506.506 0 0 1 .171.325c.016.093.036.306.02.472-.18 1.898-.962 6.502-1.36 8.627-.168.9-.499 1.201-.82 1.23-.696.065-1.225-.46-1.9-.902-1.056-.693-1.653-1.124-2.678-1.8-1.185-.78-.417-1.21.258-1.91.177-.184 3.247-2.977 3.307-3.23.007-.032.014-.15-.056-.212s-.174-.041-.249-.024c-.106.024-1.793 1.14-5.061 3.345-.48.33-.913.49-1.302.48-.428-.008-1.252-.241-1.865-.44-.752-.245-1.349-.374-1.297-.789.027-.216.325-.437.893-.663 3.498-1.524 5.83-2.529 6.998-3.014 3.332-1.386 4.025-1.627 4.476-1.635z" /> <path d="M11.944 0A12 12 0 0 0 0 12a12 12 0 0 0 12 12 12 12 0 0 0 12-12A12 12 0 0 0 12 0a12 12 0 0 0-.056 0zm4.962 7.224c.1-.002.321.023.465.14a.506.506 0 0 1 .171.325c.016.093.036.306.02.472-.18 1.898-.962 6.502-1.36 8.627-.168.9-.499 1.201-.82 1.23-.696.065-1.225-.46-1.9-.902-1.056-.693-1.653-1.124-2.678-1.8-1.185-.78-.417-1.21.258-1.91.177-.184 3.247-2.977 3.307-3.23.007-.032.014-.15-.056-.212s-.174-.041-.249-.024c-.106.024-1.793 1.14-5.061 3.345-.48.33-.913.49-1.302.48-.428-.008-1.252-.241-1.865-.44-.752-.245-1.349-.374-1.297-.789.027-.216.325-.437.893-.663 3.498-1.524 5.83-2.529 6.998-3.014 3.332-1.386 4.025-1.627 4.476-1.635z" />
</svg> </svg>
); );
} }
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { useAuth } from "@/lib/auth-context"; import { useAuth } from "@/lib/auth-context";
import { useTelegramStatus } from "@/lib/queries";
import { useSseStatus } from "@/lib/sse-context"; import { useSseStatus } from "@/lib/sse-context";
import { useTheme } from "@/lib/theme"; import { useTheme } from "@/lib/theme";
import { useTelegramStatus } from "@/lib/queries";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
interface HeaderProps { interface HeaderProps {
@@ -82,7 +85,11 @@ export function Header({ onMenuClick }: HeaderProps) {
? "text-emerald-500 hover:text-emerald-400" ? "text-emerald-500 hover:text-emerald-400"
: "text-muted-foreground hover:text-foreground", : "text-muted-foreground hover:text-foreground",
)} )}
title={telegramStatus?.connected ? "Telegram conectado" : "Conectar Telegram"} title={
telegramStatus?.connected
? "Telegram conectado"
: "Conectar Telegram"
}
> >
<TelegramIcon className="size-4" /> <TelegramIcon className="size-4" />
</Link> </Link>

View File

@@ -14,12 +14,14 @@ import {
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
interface DatePickerProps { interface DatePickerProps {
id?: string;
value: Date | undefined; value: Date | undefined;
onChange: (date: Date | undefined) => void; onChange: (date: Date | undefined) => void;
placeholder?: string; placeholder?: string;
} }
export function DatePicker({ export function DatePicker({
id,
value, value,
onChange, onChange,
placeholder = "Seleccionar fecha", placeholder = "Seleccionar fecha",
@@ -30,6 +32,7 @@ export function DatePicker({
<Popover open={open} onOpenChange={setOpen}> <Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild> <PopoverTrigger asChild>
<Button <Button
id={id}
variant="outline" variant="outline"
className={cn( className={cn(
"h-8 w-full justify-start gap-2 px-2.5 font-normal", "h-8 w-full justify-start gap-2 px-2.5 font-normal",

View File

@@ -35,9 +35,10 @@ const MONTH_NAMES = [
"Diciembre", "Diciembre",
]; ];
// La ventana trae 12 meses a mostrar + 1 mes "base" al inicio, que se usa para // Comparamos 12 meses con dato de inflación. El backend además trae hasta 2
// meses sin dato (el actual y el anterior) y 1 mes "base" al inicio para
// calcular la variación del mes más antiguo mostrado. // calcular la variación del mes más antiguo mostrado.
const DISPLAY_MONTHS = 12; const INFLATION_MONTHS = 12;
function formatMonth(monthKey: string): string { function formatMonth(monthKey: string): string {
const [y, m] = monthKey.split("-"); const [y, m] = monthKey.split("-");
@@ -58,6 +59,44 @@ function formatPrice(value: number): string {
return `$${priceFormatter.format(value)}`; return `$${priceFormatter.format(value)}`;
} }
type VariationTone = "positive" | "orange" | "negative";
// El rojo queda reservado a las caídas: crecer por debajo de la inflación es
// naranja, empatarla o superarla es verde.
function getVariationTone(
variation: number,
inflation: number | null,
): VariationTone {
if (variation < 0) return "negative";
if (inflation !== null && variation < inflation) return "orange";
return "positive";
}
const PLAIN_TONE_CLASSES: Record<VariationTone, string> = {
positive: "text-emerald-500",
orange: "text-orange-500",
negative: "text-red-500",
};
const COMPARED_TONE_CLASSES: Record<VariationTone, string> = {
positive:
"bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400 px-1.5 py-0.5 rounded",
orange:
"bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400 px-1.5 py-0.5 rounded",
negative:
"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400 px-1.5 py-0.5 rounded",
};
function getVariationClassName(
variation: number,
inflation: number | null,
): string {
const tone = getVariationTone(variation, inflation);
const toneClasses =
inflation !== null ? COMPARED_TONE_CLASSES[tone] : PLAIN_TONE_CLASSES[tone];
return `text-xs font-medium inline-flex items-center gap-1 tabular-nums ${toneClasses}`;
}
function TotalVariation({ function TotalVariation({
variation, variation,
inflation, inflation,
@@ -74,17 +113,7 @@ function TotalVariation({
} }
return ( return (
<span <span className={getVariationClassName(variation, inflation)}>
className={`text-xs font-medium inline-flex items-center gap-1 tabular-nums ${
inflation !== null
? variation > inflation
? "bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400 px-1.5 py-0.5 rounded"
: "bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400 px-1.5 py-0.5 rounded"
: variation >= 0
? "text-emerald-500"
: "text-red-500"
}`}
>
{variation >= 0 ? ( {variation >= 0 ? (
<ArrowUp className="size-3" /> <ArrowUp className="size-3" />
) : ( ) : (
@@ -121,17 +150,7 @@ function VariationIndicator({
} }
const indicator = ( const indicator = (
<span <span className={getVariationClassName(variation, inflation)}>
className={`text-xs font-medium inline-flex items-center gap-1 tabular-nums ${
inflation !== null
? variation > inflation
? "bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400 px-1.5 py-0.5 rounded"
: "bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400 px-1.5 py-0.5 rounded"
: variation >= 0
? "text-emerald-500"
: "text-red-500"
}`}
>
{variation >= 0 ? ( {variation >= 0 ? (
<ArrowUp className="size-3" /> <ArrowUp className="size-3" />
) : ( ) : (
@@ -219,8 +238,7 @@ export function MonthlyVariationTable() {
); );
const bnaVar = calcVariation(current?.BNA ?? null, prevData?.BNA ?? null); const bnaVar = calcVariation(current?.BNA ?? null, prevData?.BNA ?? null);
let inflation: number | null = null; const inflation: number | null = inflationMap.get(month) ?? null;
inflation = inflationMap.get(month) ?? null;
return { return {
month, month,
@@ -245,16 +263,27 @@ export function MonthlyVariationTable() {
}; };
}); });
// Descartamos el mes base (el más antiguo) del render: ya cumplió su // Mostramos los últimos 12 meses con dato de inflación y, desde el más
// función como mes previo para calcular la variación del primero mostrado. // antiguo de ellos hacia adelante, también los meses aún sin dato (el
return allRows.slice(-DISPLAY_MONTHS).reverse(); // actual y a veces el anterior). El mes inmediatamente anterior al primero
// visible se conserva fuera del render solo como base de su variación.
const monthsWithInflation = allRows.filter((row) => row.inflation !== null);
const firstVisibleIndex = Math.max(
0,
monthsWithInflation.length - INFLATION_MONTHS,
);
const firstVisibleMonth = monthsWithInflation[firstVisibleIndex]?.month;
if (!firstVisibleMonth) return [];
return allRows.filter((row) => row.month >= firstVisibleMonth).reverse();
}, [monthlyData, inflationData]); }, [monthlyData, inflationData]);
const summary = useMemo(() => { const summary = useMemo(() => {
if (rows.length < 2) return null; const inflationRows = rows.filter((row) => row.inflation !== null);
if (inflationRows.length < 2) return null;
const oldest = rows[rows.length - 1]; const oldest = inflationRows[inflationRows.length - 1];
const newest = rows[0]; const newest = inflationRows[0];
const totalVariation = ( const totalVariation = (
first: number | null, first: number | null,
@@ -264,18 +293,15 @@ export function MonthlyVariationTable() {
return ((last - first) / first) * 100; return ((last - first) / first) * 100;
}; };
const accumulatedInflation = rows.reduce<number | null>((acc, row) => { const accumulatedInflation = inflationRows.reduce<number>((acc, row) => {
if (row.inflation === null) return acc; return acc * (1 + (row.inflation ?? 0) / 100);
const factor = 1 + row.inflation / 100; }, 1);
return (acc ?? 1) * factor;
}, null);
return { return {
BELO: totalVariation(oldest.BELO.current, newest.BELO.current), BELO: totalVariation(oldest.BELO.current, newest.BELO.current),
BLUE: totalVariation(oldest.BLUE.current, newest.BLUE.current), BLUE: totalVariation(oldest.BLUE.current, newest.BLUE.current),
BNA: totalVariation(oldest.BNA.current, newest.BNA.current), BNA: totalVariation(oldest.BNA.current, newest.BNA.current),
inflation: inflation: (accumulatedInflation - 1) * 100,
accumulatedInflation !== null ? (accumulatedInflation - 1) * 100 : null,
period: `${oldest.label} – ${newest.label}`, period: `${oldest.label} – ${newest.label}`,
}; };
}, [rows]); }, [rows]);

View File

@@ -1,4 +1,5 @@
import { zodResolver } from "@hookform/resolvers/zod"; import { zodResolver } from "@hookform/resolvers/zod";
import { Check } from "lucide-react";
import { useEffect, useRef } from "react"; import { useEffect, useRef } from "react";
import { Controller, useForm, useWatch } from "react-hook-form"; import { Controller, useForm, useWatch } from "react-hook-form";
import { z } from "zod"; import { z } from "zod";
@@ -17,7 +18,10 @@ import { useExpensesContext } from "../ExpensesProvider";
const editSchema = z.object({ const editSchema = z.object({
amount: z.number().positive("El monto debe ser mayor a 0"), amount: z.number().positive("El monto debe ser mayor a 0"),
dueDate: z.date({ message: "La fecha es obligatoria" }), dueDate: z.date({ message: "La fecha es obligatoria" }),
amountPayed: z.number().positive("El monto pagado debe ser mayor a 0").optional(), amountPayed: z
.number()
.positive("El monto pagado debe ser mayor a 0")
.optional(),
paymentDate: z.date().optional(), paymentDate: z.date().optional(),
markAsPending: z.boolean(), markAsPending: z.boolean(),
}); });
@@ -107,8 +111,8 @@ export function EditExpenseDialog({
await updateExpense(expense.id, { await updateExpense(expense.id, {
amount: data.amount, amount: data.amount,
dueDate: data.dueDate.toISOString(), dueDate: data.dueDate.toISOString(),
amountPayed: data.amountPayed!, amountPayed: data.amountPayed,
paymentDate: data.paymentDate!.toISOString(), paymentDate: data.paymentDate?.toISOString(),
}); });
} else { } else {
await updateExpense(expense.id, { await updateExpense(expense.id, {
@@ -193,7 +197,10 @@ export function EditExpenseDialog({
{!markAsPending && ( {!markAsPending && (
<> <>
<div className="flex flex-col gap-1.5"> <div className="flex flex-col gap-1.5">
<label htmlFor="amountPayed" className="text-sm font-medium"> <label
htmlFor="amountPayed"
className="text-sm font-medium"
>
Monto pagado Monto pagado
</label> </label>
<input <input
@@ -214,9 +221,7 @@ export function EditExpenseDialog({
</div> </div>
<div className="flex flex-col gap-1.5"> <div className="flex flex-col gap-1.5">
<span className="text-sm font-medium"> <span className="text-sm font-medium">Fecha de pago</span>
Fecha de pago
</span>
<Controller <Controller
control={control} control={control}
name="paymentDate" name="paymentDate"
@@ -237,40 +242,32 @@ export function EditExpenseDialog({
</> </>
)} )}
<label className="flex items-center gap-2 text-sm cursor-pointer"> <label
htmlFor="mark-as-pending"
className="flex items-center gap-2 text-sm cursor-pointer"
>
<Controller <Controller
control={control} control={control}
name="markAsPending" name="markAsPending"
render={({ field }) => ( render={({ field }) => (
<button <>
type="button" <input
role="checkbox" id="mark-as-pending"
aria-checked={field.value} type="checkbox"
onClick={() => field.onChange(!field.value)} checked={field.value}
className={ onChange={(e) => field.onChange(e.target.checked)}
field.value className="peer sr-only"
? "flex size-4 shrink-0 items-center justify-center rounded-[4px] bg-primary text-primary-foreground ring-offset-background transition-colors"
: "flex size-4 shrink-0 items-center justify-center rounded-[4px] border border-input bg-background ring-offset-background transition-colors hover:border-ring"
}
>
{field.value && (
<svg
width="10"
height="10"
viewBox="0 0 10 10"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M2 5.5L4 7.5L8 3"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
/> />
</svg> <span
)} className={`flex size-4 shrink-0 items-center justify-center rounded-[4px] ring-offset-background transition-colors peer-focus-visible:ring-3 peer-focus-visible:ring-ring/50 ${
</button> field.value
? "bg-primary text-primary-foreground"
: "border border-input bg-background hover:border-ring"
}`}
>
{field.value && <Check className="size-3" />}
</span>
</>
)} )}
/> />
<span>Marcar como pendiente</span> <span>Marcar como pendiente</span>

View File

@@ -18,8 +18,8 @@ import {
SelectTrigger, SelectTrigger,
SelectValue, SelectValue,
} from "@/components/ui/select"; } from "@/components/ui/select";
import { useExpensesContext } from "../ExpensesProvider";
import { useQuotes, useWallets } from "@/lib/queries"; import { useQuotes, useWallets } from "@/lib/queries";
import { useExpensesContext } from "../ExpensesProvider";
const newExpenseSchema = z.object({ const newExpenseSchema = z.object({
description: z description: z
@@ -175,7 +175,9 @@ export function NewExpenseDialog({
</div> </div>
<div className="flex flex-col gap-1.5"> <div className="flex flex-col gap-1.5">
<label className="text-sm font-medium">Billetera</label> <label htmlFor="expense-wallet" className="text-sm font-medium">
Billetera
</label>
<Controller <Controller
control={control} control={control}
name="walletId" name="walletId"
@@ -184,7 +186,7 @@ export function NewExpenseDialog({
value={field.value ? String(field.value) : ""} value={field.value ? String(field.value) : ""}
onValueChange={(v) => field.onChange(Number(v))} onValueChange={(v) => field.onChange(Number(v))}
> >
<SelectTrigger className="h-8 w-full"> <SelectTrigger id="expense-wallet" className="h-8 w-full">
<SelectValue placeholder="Seleccionar billetera" /> <SelectValue placeholder="Seleccionar billetera" />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>

View File

@@ -19,8 +19,8 @@ import {
SelectValue, SelectValue,
} from "@/components/ui/select"; } from "@/components/ui/select";
import type { Expense } from "@/lib/api"; import type { Expense } from "@/lib/api";
import { useExpensesContext } from "../ExpensesProvider";
import { useQuotes, useWallets } from "@/lib/queries"; import { useQuotes, useWallets } from "@/lib/queries";
import { useExpensesContext } from "../ExpensesProvider";
const paySchema = z.object({ const paySchema = z.object({
amountPayed: z.number().positive("El monto debe ser mayor a 0"), amountPayed: z.number().positive("El monto debe ser mayor a 0"),
@@ -194,7 +194,9 @@ export function PayExpenseDialog({
</div> </div>
<div className="flex flex-col gap-1.5"> <div className="flex flex-col gap-1.5">
<label className="text-sm font-medium">Billetera</label> <label htmlFor="pay-expense-wallet" className="text-sm font-medium">
Billetera
</label>
<Controller <Controller
control={control} control={control}
name="walletId" name="walletId"
@@ -203,7 +205,7 @@ export function PayExpenseDialog({
value={field.value ? String(field.value) : ""} value={field.value ? String(field.value) : ""}
onValueChange={(v) => field.onChange(Number(v))} onValueChange={(v) => field.onChange(Number(v))}
> >
<SelectTrigger className="h-8 w-full"> <SelectTrigger id="pay-expense-wallet" className="h-8 w-full">
<SelectValue placeholder="Seleccionar billetera" /> <SelectValue placeholder="Seleccionar billetera" />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>

View File

@@ -1,12 +1,13 @@
"use client"; "use client";
import { useSearch } from "@tanstack/react-router";
import { import {
type ColumnDef, type ColumnDef,
flexRender, flexRender,
getCoreRowModel, getCoreRowModel,
useReactTable, useReactTable,
} from "@tanstack/react-table"; } from "@tanstack/react-table";
import { subMonths, startOfMonth } from "date-fns"; import { startOfMonth, subMonths } from "date-fns";
import { import {
ChevronsLeftIcon, ChevronsLeftIcon,
ChevronsRightIcon, ChevronsRightIcon,
@@ -14,7 +15,6 @@ import {
SkipForwardIcon, SkipForwardIcon,
} from "lucide-react"; } from "lucide-react";
import { useMemo, useState } from "react"; import { useMemo, useState } from "react";
import { useSearch } from "@tanstack/react-router";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { DatePicker } from "@/components/ui/date-picker"; import { DatePicker } from "@/components/ui/date-picker";
import { import {
@@ -40,6 +40,8 @@ const amountFormatter = new Intl.NumberFormat("es-AR", {
maximumFractionDigits: 4, maximumFractionDigits: 4,
}); });
const PAGE_SIZE = 20;
const dateFormatter = new Intl.DateTimeFormat("es-AR", { const dateFormatter = new Intl.DateTimeFormat("es-AR", {
day: "2-digit", day: "2-digit",
month: "2-digit", month: "2-digit",
@@ -60,8 +62,7 @@ function TypeBadge({ type }: { type: string }) {
const styles: Record<string, string> = { const styles: Record<string, string> = {
DEPOSIT: DEPOSIT:
"bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400", "bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400",
WITHDRAWAL: WITHDRAWAL: "bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400",
"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400",
TRANSFER_IN: TRANSFER_IN:
"bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400", "bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400",
TRANSFER_OUT: TRANSFER_OUT:
@@ -97,7 +98,6 @@ export function WalletMovementsPage() {
const [endDate, setEndDate] = useState<Date | undefined>(today); const [endDate, setEndDate] = useState<Date | undefined>(today);
const [page, setPage] = useState(1); const [page, setPage] = useState(1);
const pageSize = 20;
const filter: WalletMovementsFilter = useMemo( const filter: WalletMovementsFilter = useMemo(
() => ({ () => ({
@@ -105,9 +105,9 @@ export function WalletMovementsPage() {
startDate: startDate?.toISOString(), startDate: startDate?.toISOString(),
endDate: endDate?.toISOString(), endDate: endDate?.toISOString(),
page, page,
pageSize, pageSize: PAGE_SIZE,
}), }),
[walletId, startDate, endDate, page, pageSize], [walletId, startDate, endDate, page],
); );
const { data: result, isLoading } = useWalletMovementsFiltered(filter); const { data: result, isLoading } = useWalletMovementsFiltered(filter);
@@ -142,9 +142,7 @@ export function WalletMovementsPage() {
header: "Billetera", header: "Billetera",
id: "walletName", id: "walletName",
cell: ({ row }) => { cell: ({ row }) => {
const w = wallets?.find( const w = wallets?.find((w) => w.id === row.original.walletId);
(w) => w.id === row.original.walletId,
);
return w ? ( return w ? (
<span className="text-xs text-muted-foreground">{w.name}</span> <span className="text-xs text-muted-foreground">{w.name}</span>
) : null; ) : null;
@@ -192,13 +190,13 @@ export function WalletMovementsPage() {
getCoreRowModel: getCoreRowModel(), getCoreRowModel: getCoreRowModel(),
}); });
const totalPages = Math.max(1, Math.ceil(total / pageSize)); const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE));
const GROUP_SIZE = 3; const GROUP_SIZE = 3;
const currentGroup = Math.floor((page - 1) / GROUP_SIZE); const currentGroup = Math.floor((page - 1) / GROUP_SIZE);
const startPage = currentGroup * GROUP_SIZE + 1; const startPage = currentGroup * GROUP_SIZE + 1;
const endPage = Math.min(startPage + GROUP_SIZE - 1, totalPages); const endPage = Math.min(startPage + GROUP_SIZE - 1, totalPages);
const firstItem = total === 0 ? 0 : (page - 1) * pageSize + 1; const firstItem = total === 0 ? 0 : (page - 1) * PAGE_SIZE + 1;
const lastItem = Math.min(page * pageSize, total); const lastItem = Math.min(page * PAGE_SIZE, total);
const mobilePagination = const mobilePagination =
total > 0 ? ( total > 0 ? (
@@ -233,7 +231,10 @@ export function WalletMovementsPage() {
<div className="flex flex-wrap items-end gap-3"> <div className="flex flex-wrap items-end gap-3">
<div className="flex flex-col gap-1.5"> <div className="flex flex-col gap-1.5">
<label className="text-xs font-medium text-muted-foreground"> <label
htmlFor="filter-wallet"
className="text-xs font-medium text-muted-foreground"
>
Billetera Billetera
</label> </label>
<Select <Select
@@ -243,13 +244,11 @@ export function WalletMovementsPage() {
setPage(1); setPage(1);
}} }}
> >
<SelectTrigger className="h-8 w-44"> <SelectTrigger id="filter-wallet" className="h-8 w-44">
<SelectValue placeholder="Todas las billeteras" /> <SelectValue placeholder="Todas las billeteras" />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
<SelectItem value="all"> <SelectItem value="all">Todas las billeteras</SelectItem>
Todas las billeteras
</SelectItem>
{wallets?.map((w: Wallet) => ( {wallets?.map((w: Wallet) => (
<SelectItem key={w.id} value={String(w.id)}> <SelectItem key={w.id} value={String(w.id)}>
{w.name} ({w.currency}) {w.name} ({w.currency})
@@ -260,10 +259,14 @@ export function WalletMovementsPage() {
</div> </div>
<div className="flex flex-col gap-1.5"> <div className="flex flex-col gap-1.5">
<label className="text-xs font-medium text-muted-foreground"> <label
htmlFor="filter-start-date"
className="text-xs font-medium text-muted-foreground"
>
Desde Desde
</label> </label>
<DatePicker <DatePicker
id="filter-start-date"
value={startDate} value={startDate}
onChange={(d) => { onChange={(d) => {
setStartDate(d); setStartDate(d);
@@ -274,10 +277,14 @@ export function WalletMovementsPage() {
</div> </div>
<div className="flex flex-col gap-1.5"> <div className="flex flex-col gap-1.5">
<label className="text-xs font-medium text-muted-foreground"> <label
htmlFor="filter-end-date"
className="text-xs font-medium text-muted-foreground"
>
Hasta Hasta
</label> </label>
<DatePicker <DatePicker
id="filter-end-date"
value={endDate} value={endDate}
onChange={(d) => { onChange={(d) => {
setEndDate(d); setEndDate(d);

View File

@@ -1,8 +1,8 @@
import { useState } from "react";
import { Plus } from "lucide-react"; import { Plus } from "lucide-react";
import { useState } from "react";
import { useWallets } from "@/lib/queries"; import { useWallets } from "@/lib/queries";
import { WalletCard } from "./components/WalletCard";
import { CreateWalletDialog } from "./components/CreateWalletDialog"; import { CreateWalletDialog } from "./components/CreateWalletDialog";
import { WalletCard } from "./components/WalletCard";
export function WalletsPage() { export function WalletsPage() {
const { data: wallets, isLoading } = useWallets(); const { data: wallets, isLoading } = useWallets();

View File

@@ -9,8 +9,8 @@ import {
ResponsiveDialogHeader, ResponsiveDialogHeader,
ResponsiveDialogTitle, ResponsiveDialogTitle,
} from "@/components/ui/responsive-dialog"; } from "@/components/ui/responsive-dialog";
import { useAdjustBalance } from "@/lib/queries";
import type { Wallet } from "@/lib/api"; import type { Wallet } from "@/lib/api";
import { useAdjustBalance } from "@/lib/queries";
const adjustSchema = z.object({ const adjustSchema = z.object({
newBalance: z.number().min(0, "El saldo no puede ser negativo"), newBalance: z.number().min(0, "El saldo no puede ser negativo"),

View File

@@ -9,8 +9,8 @@ import {
ResponsiveDialogHeader, ResponsiveDialogHeader,
ResponsiveDialogTitle, ResponsiveDialogTitle,
} from "@/components/ui/responsive-dialog"; } from "@/components/ui/responsive-dialog";
import { useDepositWallet } from "@/lib/queries";
import type { Wallet } from "@/lib/api"; import type { Wallet } from "@/lib/api";
import { useDepositWallet } from "@/lib/queries";
const depositSchema = z.object({ const depositSchema = z.object({
amount: z.number().positive("El monto debe ser mayor a 0"), amount: z.number().positive("El monto debe ser mayor a 0"),

View File

@@ -16,8 +16,8 @@ import {
SelectTrigger, SelectTrigger,
SelectValue, SelectValue,
} from "@/components/ui/select"; } from "@/components/ui/select";
import { useUpdateWallet } from "@/lib/queries";
import type { Wallet } from "@/lib/api"; import type { Wallet } from "@/lib/api";
import { useUpdateWallet } from "@/lib/queries";
const editWalletSchema = z.object({ const editWalletSchema = z.object({
name: z.string().min(1, "El nombre es obligatorio").max(100), name: z.string().min(1, "El nombre es obligatorio").max(100),
@@ -128,11 +128,7 @@ export function EditWalletDialog({
> >
Cancelar Cancelar
</Button> </Button>
<Button <Button type="submit" form="edit-wallet-form" disabled={isSubmitting}>
type="submit"
form="edit-wallet-form"
disabled={isSubmitting}
>
Guardar Guardar
</Button> </Button>
</ResponsiveDialogFooter> </ResponsiveDialogFooter>

View File

@@ -16,8 +16,8 @@ import {
SelectTrigger, SelectTrigger,
SelectValue, SelectValue,
} from "@/components/ui/select"; } from "@/components/ui/select";
import { useTransferWallet, useWallets } from "@/lib/queries";
import type { Wallet } from "@/lib/api"; import type { Wallet } from "@/lib/api";
import { useTransferWallet, useWallets } from "@/lib/queries";
const transferSchema = z.object({ const transferSchema = z.object({
toWalletId: z.number().positive("Seleccioná una billetera destino"), toWalletId: z.number().positive("Seleccioná una billetera destino"),
@@ -42,8 +42,7 @@ export function TransferDialog({
const { data: wallets } = useWallets(); const { data: wallets } = useWallets();
const transfer = useTransferWallet(); const transfer = useTransferWallet();
const otherWallets = const otherWallets = wallets?.filter((w) => w.id !== sourceWallet.id) ?? [];
wallets?.filter((w) => w.id !== sourceWallet.id) ?? [];
const { const {
register, register,
@@ -96,7 +95,9 @@ export function TransferDialog({
className="flex flex-col gap-4" className="flex flex-col gap-4"
> >
<div className="flex flex-col gap-1.5"> <div className="flex flex-col gap-1.5">
<label className="text-sm font-medium">Billetera destino</label> <label htmlFor="transfer-to-wallet" className="text-sm font-medium">
Billetera destino
</label>
<Controller <Controller
control={control} control={control}
name="toWalletId" name="toWalletId"
@@ -105,7 +106,7 @@ export function TransferDialog({
value={field.value ? String(field.value) : ""} value={field.value ? String(field.value) : ""}
onValueChange={(v) => field.onChange(Number(v))} onValueChange={(v) => field.onChange(Number(v))}
> >
<SelectTrigger className="h-8"> <SelectTrigger id="transfer-to-wallet" className="h-8">
<SelectValue placeholder="Seleccionar destino" /> <SelectValue placeholder="Seleccionar destino" />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
@@ -126,10 +127,7 @@ export function TransferDialog({
</div> </div>
<div className="flex flex-col gap-1.5"> <div className="flex flex-col gap-1.5">
<label <label htmlFor="transfer-outgoing" className="text-sm font-medium">
htmlFor="transfer-outgoing"
className="text-sm font-medium"
>
Monto saliente (de {sourceWallet.name}) Monto saliente (de {sourceWallet.name})
</label> </label>
<input <input
@@ -149,10 +147,7 @@ export function TransferDialog({
</div> </div>
<div className="flex flex-col gap-1.5"> <div className="flex flex-col gap-1.5">
<label <label htmlFor="transfer-incoming" className="text-sm font-medium">
htmlFor="transfer-incoming"
className="text-sm font-medium"
>
Monto entrante (en destino) Monto entrante (en destino)
</label> </label>
<input <input

View File

@@ -1,4 +1,4 @@
import { useState } from "react"; import { useNavigate } from "@tanstack/react-router";
import { import {
ArrowDownToLine, ArrowDownToLine,
ArrowLeftRight, ArrowLeftRight,
@@ -7,7 +7,7 @@ import {
PencilLine, PencilLine,
Star, Star,
} from "lucide-react"; } from "lucide-react";
import { useNavigate } from "@tanstack/react-router"; import { useState } from "react";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { import {
Tooltip, Tooltip,
@@ -17,10 +17,10 @@ import {
} from "@/components/ui/tooltip"; } from "@/components/ui/tooltip";
import type { Wallet } from "@/lib/api"; import type { Wallet } from "@/lib/api";
import { useSetDefaultWallet } from "@/lib/queries"; import { useSetDefaultWallet } from "@/lib/queries";
import { DepositDialog } from "./DepositDialog";
import { AdjustBalanceDialog } from "./AdjustBalanceDialog"; import { AdjustBalanceDialog } from "./AdjustBalanceDialog";
import { TransferDialog } from "./TransferDialog"; import { DepositDialog } from "./DepositDialog";
import { EditWalletDialog } from "./EditWalletDialog"; import { EditWalletDialog } from "./EditWalletDialog";
import { TransferDialog } from "./TransferDialog";
const balanceFormatter = new Intl.NumberFormat("es-AR", { const balanceFormatter = new Intl.NumberFormat("es-AR", {
minimumFractionDigits: 2, minimumFractionDigits: 2,
@@ -148,7 +148,10 @@ export function WalletCard({ wallet }: WalletCardProps) {
size="icon" size="icon"
className="size-8" className="size-8"
onClick={() => onClick={() =>
navigate({ to: "/wallets/movements", search: { walletId: wallet.id } }) navigate({
to: "/wallets/movements",
search: { walletId: wallet.id },
})
} }
> >
<History className="size-4" /> <History className="size-4" />

View File

@@ -1,11 +1,11 @@
import { useWalletMovements } from "@/lib/queries";
import type { Wallet } from "@/lib/api";
import { import {
ResponsiveDialog, ResponsiveDialog,
ResponsiveDialogContent, ResponsiveDialogContent,
ResponsiveDialogHeader, ResponsiveDialogHeader,
ResponsiveDialogTitle, ResponsiveDialogTitle,
} from "@/components/ui/responsive-dialog"; } from "@/components/ui/responsive-dialog";
import type { Wallet } from "@/lib/api";
import { useWalletMovements } from "@/lib/queries";
const amountFormatter = new Intl.NumberFormat("es-AR", { const amountFormatter = new Intl.NumberFormat("es-AR", {
minimumFractionDigits: 2, minimumFractionDigits: 2,
@@ -62,7 +62,9 @@ export function WalletMovementsDialog({
className="flex items-center justify-between rounded-md p-2 text-sm hover:bg-muted/50" className="flex items-center justify-between rounded-md p-2 text-sm hover:bg-muted/50"
> >
<div className="flex flex-col"> <div className="flex flex-col">
<span className="font-medium">{typeLabels[m.type] ?? m.type}</span> <span className="font-medium">
{typeLabels[m.type] ?? m.type}
</span>
{m.description && ( {m.description && (
<span className="text-xs text-muted-foreground"> <span className="text-xs text-muted-foreground">
{m.description} {m.description}

View File

@@ -2,6 +2,9 @@ import { createFileRoute, redirect } from "@tanstack/react-router";
export const Route = createFileRoute("/_authenticated/quotes/belo/analysis")({ export const Route = createFileRoute("/_authenticated/quotes/belo/analysis")({
loader: () => { loader: () => {
throw redirect({ to: "/quotes/analysis/$currency", params: { currency: "BELO" } }); throw redirect({
to: "/quotes/analysis/$currency",
params: { currency: "BELO" },
});
}, },
}); });

View File

@@ -1,5 +1,5 @@
{ {
"$schema": "https://biomejs.dev/schemas/2.4.16/schema.json", "$schema": "https://biomejs.dev/schemas/2.5.10/schema.json",
"vcs": { "vcs": {
"enabled": true, "enabled": true,
"clientKind": "git", "clientKind": "git",
@@ -21,7 +21,7 @@
"linter": { "linter": {
"enabled": true, "enabled": true,
"rules": { "rules": {
"recommended": true "preset": "recommended"
} }
}, },
"javascript": { "javascript": {