Compare commits

..

23 Commits

Author SHA1 Message Date
Jose Selesan
0f62a13246 fix(analysis): compute variation for oldest month in 12-month table
The last row of the monthly variation table (oldest month of the rolling
window) always showed only the inflation value: the window started exactly
at that month, so there was no previous month to compare against, the
variation was null and the currency cells rendered '--' (hiding the prices
too).

- Backend: fetch 13 months (12 displayed + 1 base) so the oldest displayed
  month gets its previous month; bump cache key to monthly-last-v3.
- Backend: fix external fallback filter comparing a full date against a
  month key ('2026-10-14' > '2026-10' is always true), which silently
  dropped the most recent month whenever it was missing from the DB.
  Now filters by month key only.
- Backend: normalize subtractMonths to the 1st of the target month to avoid
  month shifts; skip external quotes without a buy value.
- Frontend: compute variations over the 13 months and render the last 12;
  show the current price when a variation is unavailable so no row is blank.
- Add regression tests for the window size and the external fallback.
2026-10-14 12:05:27 -03:00
Jose Selesan
28e1a732e0 feat(analysis): add monthly pattern analysis feature with chart and API integration 2026-09-14 16:41:21 -03:00
Jose Selesan
f2c26c266c fix: peak hours analysis uses all historical data
Remove date range filtering from peak-hours endpoint so the
analysis considers all available data in the database, not just
the last 30 days.
2026-08-28 13:31:30 -03:00
Jose Selesan
0998d64cbb feat: add BELO peak hour analysis chart
- New backend endpoint GET /quotes/:type/peak-hours
- Groups daily price data by hour to find peak frequency
- Bar chart showing how often each hour is the daily peak
- Only displayed for BELO currency in analysis page
2026-08-28 12:05:43 -03:00
Jose Selesan
2fe8198c41 fix(analysis): use last business day of previous month for 'Vs. mes anterior' card 2026-08-28 11:46:41 -03:00
Jose Selesan
1fee87a4ce fix(analysis): use compound inflation calculation instead of linear sum 2026-08-27 12:52:48 -03:00
Jose Selesan
d24f3ce872 feat(analysis): add 12-month summary row with total variation and accumulated inflation 2026-08-27 11:56:02 -03:00
Jose Selesan
b78fcbc0e9 fix(quotes): add logging + parallel fetch for external API diagnostics 2026-08-27 11:51:21 -03:00
Jose Selesan
d8aed4970c feat(analysis): bold month names for DB-sourced data, regular for external 2026-08-27 11:37:43 -03:00
Jose Selesan
28f9dea7ba feat(analysis): rolling 12-month table with external API fallback
- monthly-last endpoint now returns last 12 months (rolling)
- For months without DB data, fetches from ArgentinaDatos API
- Casa mapping: BELO=cripto, BLUE=blue, BNA=oficial
- DB data takes priority over external API data
2026-08-27 11:33:45 -03:00
Jose Selesan
873fd63ea4 style(analysis): use full month names in variation table 2026-08-27 11:16:39 -03:00
Jose Selesan
88fa05d5b8 style(analysis): show raw values inline instead of below percentage 2026-08-27 10:37:04 -03:00
Jose Selesan
f9e0267c94 feat(analysis): show raw values ( → ) below each variation 2026-08-27 10:34:33 -03:00
Jose Selesan
0c634bbc8b fix(analysis): don't skip any months for inflation, just check if data exists 2026-08-27 10:22:13 -03:00
Jose Selesan
e32131d32e fix(analysis): only skip inflation for current month, not last complete month
The last complete month's inflation is usually available by the 14th of the
current month. Previously July was always skipped even though data exists.
2026-08-27 10:21:39 -03:00
Jose Selesan
66ab56b46a feat(analysis): add monthly variation table with inflation comparison
- New backend endpoint GET /api/quotes/monthly-last
- MonthlyVariationTable component with BELO/Blue/Oficial % changes
- Inflation data from ArgentinaDatos API with 24h cache
- Visual indicators: green if beats inflation, red if below
- Responsive: cards on mobile, table on desktop
2026-08-27 10:13:56 -03:00
Jose Selesan
a6e95f0c05 fix(analysis): pad comparison chart Y domain to 20% around the range 2026-08-20 14:38:57 -03:00
Jose Selesan
48c4c892cd feat(analysis): add comparison chart of buy price for the 3 quotes 2026-08-20 14:33:39 -03:00
Jose Selesan
31dae446af feat(telegram): add /blu and /oficial commands and main menu 2026-08-20 14:22:56 -03:00
Jose Selesan
96f6b26a76 feat(telegram): add /belo command with current quote and daily progress 2026-08-20 14:17:31 -03:00
Jose Selesan
0407a79e1e Updated Telegram notification 2026-08-05 13:56:52 -03:00
Jose Selesan
4784242a35 Added estimaded salary to dashboard 2026-07-22 12:31:58 -03:00
09f00aa3b9 Merge pull request 'feat/payment-wallets' (#5) from feat/payment-wallets into main
Reviewed-on: #5
2026-06-17 14:11:30 +00:00
23 changed files with 2710 additions and 106 deletions

View File

@@ -0,0 +1,13 @@
-- CreateTable
CREATE TABLE "settings" (
"key" TEXT NOT NULL,
"value" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "settings_pkey" PRIMARY KEY ("key")
);
-- Seed
INSERT INTO "settings" ("key", "value", "createdAt", "updatedAt")
VALUES ('salary_multiplier', '4500', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP);

View File

@@ -0,0 +1,26 @@
-- CreateEnum
CREATE TYPE "PriceDirection" AS ENUM ('MAX', 'MIN');
-- CreateTable
CREATE TABLE "telegram_daily_price_notifications" (
"id" TEXT NOT NULL,
"date" TIMESTAMP(3) NOT NULL,
"quoteType" "QuoteType" NOT NULL,
"direction" "PriceDirection" NOT NULL,
"value" MONEY NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "telegram_daily_price_notifications_pkey" PRIMARY KEY ("id")
);
-- Migrate existing max records (if any)
INSERT INTO "telegram_daily_price_notifications" ("id", "date", "quoteType", "direction", "value", "createdAt", "updatedAt")
SELECT "id", "date", "quoteType", 'MAX'::"PriceDirection", "maxValue", "createdAt", "updatedAt"
FROM "telegram_daily_max_notifications";
-- CreateIndex
CREATE UNIQUE INDEX "telegram_daily_price_notifications_date_quoteType_direction_key" ON "telegram_daily_price_notifications"("date", "quoteType", "direction");
-- DropTable
DROP TABLE "telegram_daily_max_notifications";

View File

@@ -79,16 +79,22 @@ model TelegramChat {
@@map("telegram_chats")
}
model TelegramDailyMaxNotification {
enum PriceDirection {
MAX
MIN
}
model TelegramDailyPriceNotification {
id String @id @default(cuid())
date DateTime
quoteType QuoteType
maxValue Decimal @db.Money
direction PriceDirection
value Decimal @db.Money
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@unique([date, quoteType])
@@map("telegram_daily_max_notifications")
@@unique([date, quoteType, direction])
@@map("telegram_daily_price_notifications")
}
enum QuoteType {
@@ -122,6 +128,15 @@ model QuoteHistory {
@@map("quotes_history")
}
model Setting {
key String @id
value String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@map("settings")
}
// Expenses
enum PaymentStatus {

View File

@@ -11,6 +11,7 @@ import { startExpenseJob } from "./modules/expenses/expense.job";
import expensesRouter from "./modules/expenses/expenses.routes";
import { startQuoteJob } from "./modules/quotes/quote.job";
import quotesRouter from "./modules/quotes/quotes.routes";
import settingsRouter from "./modules/settings/settings.routes";
import telegramRouter from "./modules/telegram/telegram.router";
import walletsRouter from "./modules/wallets/wallets.routes";
@@ -32,6 +33,7 @@ app.use("/api/*", async (c, next) => {
});
app.route("/api/quotes", quotesRouter);
app.route("/api/settings", settingsRouter);
app.route("/api", expensesRouter);
app.route("/api/telegram", telegramRouter);
app.route("/api/wallets", walletsRouter);

View File

@@ -1,9 +1,24 @@
import { Bot } from "grammy";
import type { Context } from "grammy";
import { Bot, InlineKeyboard } from "grammy";
import type { QuoteType } from "../generated/prisma/client";
import type { QuoteStatus } from "../modules/telegram/telegram.service";
import {
formatPrice,
formatTime,
getQuoteStatus,
isChatValidated,
validateCode,
} from "../modules/telegram/telegram.service";
import { logger } from "./logger";
import { validateCode } from "../modules/telegram/telegram.service";
const token = process.env.BOT_TOKEN;
const QUOTE_COMMANDS = {
BELO: { label: "BELO · USDC/ARS", icon: "💰" },
BLUE: { label: "Dólar Blue", icon: "💵" },
BNA: { label: "Dólar Oficial", icon: "🏦" },
} as const satisfies Record<QuoteType, { label: string; icon: string }>;
let botInstance: Bot | null = null;
let botUsername: string | null = null;
@@ -15,6 +30,54 @@ export function getBotUsername(): string | null {
return botUsername;
}
function buildQuoteMessage(type: QuoteType, status: QuoteStatus): string {
const { label, icon } = QUOTE_COMMANDS[type];
const progress = Math.round(status.progressPercentage ?? 0);
return [
`${icon} <b>${label}</b>`,
"",
`Compra: <b>$${formatPrice(status.buy)}</b>`,
`Venta: <b>$${formatPrice(status.sell)}</b>`,
"",
`Mínimo del día: $${formatPrice(status.minBuy)}`,
`Máximo del día: $${formatPrice(status.maxBuy)}`,
`Avance del día: <b>${progress}%</b>`,
"",
`🕐 ${formatTime(status.timeStamp)}`,
].join("\n");
}
async function replyQuote(ctx: Context, type: QuoteType): Promise<void> {
const chatId = ctx.chat?.id;
if (!chatId) return;
const validated = await isChatValidated(BigInt(chatId));
if (!validated) {
await ctx.reply(
"🔒 Tu cuenta no está conectada. Enviá /menu para ver cómo conectarla.",
);
return;
}
const status = await getQuoteStatus(type);
if (!status) {
await ctx.reply(
`❌ No hay datos de ${QUOTE_COMMANDS[type].label} disponibles todavía.`,
);
return;
}
await ctx.reply(buildQuoteMessage(type, status), { parse_mode: "HTML" });
}
function mainMenu(): InlineKeyboard {
return new InlineKeyboard()
.text(`${QUOTE_COMMANDS.BELO.icon} BELO`, "quote:BELO")
.text(`${QUOTE_COMMANDS.BLUE.icon} Blue`, "quote:BLUE")
.row()
.text(`${QUOTE_COMMANDS.BNA.icon} Oficial`, "quote:BNA");
}
export async function startBot(): Promise<void> {
if (!token) {
logger.warn("BOT_TOKEN not set, Telegram bot not started");
@@ -25,9 +88,38 @@ export async function startBot(): Promise<void> {
const bot = new Bot(token);
bot.command("start", async (ctx) => {
const validated = await isChatValidated(BigInt(ctx.chat.id));
if (validated) {
await ctx.reply("👋 ¡Hola! Seleccioná una cotización:", {
reply_markup: mainMenu(),
});
} else {
await ctx.reply(
"🔗 Enviá el código de verificación que aparece en la Configuración de la app para conectar tu cuenta de Telegram.\n\nUna vez conectado, recibirás notificaciones cuando BELO alcance el máximo del día.",
"🔗 Enviá el código de verificación que aparece en la Configuración de la app para conectar tu cuenta de Telegram.\n\nUna vez conectado, recibirás notificaciones cuando BELO alcance el máximo del día y podrás consultar las cotizaciones con /menu.",
);
}
});
bot.command("menu", async (ctx) => {
await ctx.reply("📊 <b>Menú</b>\n\nElegí una cotización:", {
parse_mode: "HTML",
reply_markup: mainMenu(),
});
});
bot.command("belo", (ctx) => replyQuote(ctx, "BELO"));
bot.command("blu", (ctx) => replyQuote(ctx, "BLUE"));
bot.command("oficial", (ctx) => replyQuote(ctx, "BNA"));
bot.on("callback_query:data", async (ctx) => {
const [cmd, rawType] = ctx.callbackQuery.data.split(":");
if (cmd !== "quote") return;
const type = rawType as QuoteType;
if (!QUOTE_COMMANDS[type]) return;
await replyQuote(ctx, type);
await ctx.answerCallbackQuery();
});
bot.on("message:text", async (ctx) => {
@@ -36,7 +128,9 @@ export async function startBot(): Promise<void> {
const success = await validateCode(BigInt(ctx.chat.id), text);
if (success) {
await ctx.reply("✅ ¡Conectado! Recibirás notificaciones de BELO aquí.");
await ctx.reply(
"✅ ¡Conectado! Recibirás notificaciones de BELO aquí.",
);
} else {
await ctx.reply("❌ Código inválido o ya utilizado.");
}
@@ -45,6 +139,13 @@ export async function startBot(): Promise<void> {
const botInfo = await bot.api.getMe();
botUsername = botInfo.username;
await bot.api.setMyCommands([
{ command: "menu", description: "Mostrar menú principal" },
{ command: "belo", description: "Cotización de BELO (USDC/ARS)" },
{ command: "blu", description: "Cotización del dólar blue" },
{ command: "oficial", description: "Cotización del dólar oficial" },
]);
bot.start();
botInstance = bot;

View File

@@ -0,0 +1,189 @@
import type { Context } from "hono";
import { cache } from "../../../lib/cache";
import { prisma } from "../../../lib/prisma";
type MonthlyLastRow = {
month: string;
type: string;
buy: number;
source: "db" | "external";
};
type ExternalQuote = {
casa: string;
fecha: string;
compra: number;
venta: number;
};
const CASA_MAP: Record<string, string> = {
BELO: "cripto",
BLUE: "blue",
BNA: "oficial",
};
const TYPES = ["BELO", "BLUE", "BNA"] as const;
function getMonthKey(date: Date): string {
const y = date.getFullYear();
const m = String(date.getMonth() + 1).padStart(2, "0");
return `${y}-${m}`;
}
function subtractMonths(date: Date, months: number): Date {
// Normalizamos al día 1 del mes destino para evitar corrimientos cuando el
// día actual no existe en ese mes (ej. 31/03 - 1 mes => 03/03).
return new Date(date.getFullYear(), date.getMonth() - months, 1);
}
// La tabla muestra 12 meses, pero traemos un mes extra al principio para poder
// calcular la variación del mes más antiguo mostrado (necesita su mes previo).
const DISPLAY_MONTHS = 12;
export async function getMonthlyLast(c: Context) {
const cacheKey = "quotes:monthly-last-v3";
const cached = cache.get(cacheKey);
if (cached) return c.json(cached);
const today = new Date();
const currentMonthKey = getMonthKey(today);
const startMonth = subtractMonths(today, DISPLAY_MONTHS);
const startDate = new Date(
startMonth.getFullYear(),
startMonth.getMonth(),
1,
);
const endDate = new Date(today.getFullYear(), today.getMonth() + 1, 1);
const dbRows = await prisma.$queryRaw<
Array<{
month: string;
type: string;
buy: number;
}>
>`
SELECT
TO_CHAR(DATE_TRUNC('month', "timeStamp"), 'YYYY-MM') AS month,
"type"::text,
(ARRAY_AGG(buy ORDER BY "timeStamp" DESC))[1]::numeric::float8 AS buy
FROM "quotes_history"
WHERE "timeStamp" >= ${startDate}::timestamptz
AND "timeStamp" < ${endDate}::timestamptz
GROUP BY DATE_TRUNC('month', "timeStamp"), "type"
ORDER BY month ASC
`;
const dbMap = new Map<string, Map<string, number>>();
for (const row of dbRows) {
if (!dbMap.has(row.month)) dbMap.set(row.month, new Map());
dbMap.get(row.month)?.set(row.type, row.buy);
}
const expectedMonths: string[] = [];
let cursor = new Date(startMonth.getFullYear(), startMonth.getMonth(), 1);
while (getMonthKey(cursor) <= currentMonthKey) {
expectedMonths.push(getMonthKey(cursor));
cursor = new Date(cursor.getFullYear(), cursor.getMonth() + 1, 1);
}
const missingByType = new Map<string, string[]>();
for (const type of TYPES) {
const missing = expectedMonths.filter((m) => !dbMap.get(m)?.has(type));
if (missing.length > 0) missingByType.set(type, missing);
}
if (missingByType.size === 0) {
const result: MonthlyLastRow[] = [];
for (const month of expectedMonths) {
for (const type of TYPES) {
const buy = dbMap.get(month)?.get(type);
if (buy !== undefined) {
result.push({ month, type, buy, source: "db" });
}
}
}
cache.set(cacheKey, result, 300);
return c.json(result);
}
const neededMonths = new Set<string>();
for (const months of missingByType.values()) {
for (const m of months) neededMonths.add(m);
}
const externalData = new Map<string, Map<string, number>>();
const fetches = Object.entries(CASA_MAP).map(async ([type, casa]) => {
if (!missingByType.has(type)) return;
try {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 30_000);
const res = await fetch(
`https://api.argentinadatos.com/v1/cotizaciones/dolares/${casa}`,
{ signal: controller.signal },
);
clearTimeout(timeout);
if (!res.ok) {
console.error(`[monthlyLast] ${casa} responded ${res.status}`);
return;
}
const quotes: ExternalQuote[] = await res.json();
const monthLast = new Map<string, { fecha: string; compra: number }>();
for (const q of quotes) {
if (q.compra === null || q.compra === undefined) continue;
// Comparamos por clave de mes ("YYYY-MM"), nunca la fecha completa
// contra la clave: "2026-10-14" > "2026-10" siempre es true y
// descartaría el mes más reciente.
const fecha = q.fecha.slice(0, 10);
const monthKey = fecha.slice(0, 7);
if (!neededMonths.has(monthKey)) continue;
const existing = monthLast.get(monthKey);
if (!existing || fecha > existing.fecha) {
monthLast.set(monthKey, { fecha, compra: q.compra });
}
}
const typeMap = new Map<string, number>();
for (const [month, data] of monthLast) {
typeMap.set(month, data.compra);
}
externalData.set(type, typeMap);
console.error(
`[monthlyLast] ${casa}: fetched ${quotes.length} quotes, ${monthLast.size} months`,
);
} catch (e) {
console.error(`[monthlyLast] ${casa} fetch failed:`, e);
}
});
await Promise.all(fetches);
const result: MonthlyLastRow[] = [];
for (const month of expectedMonths) {
for (const type of TYPES) {
const dbBuy = dbMap.get(month)?.get(type);
if (dbBuy !== undefined) {
result.push({ month, type, buy: dbBuy, source: "db" });
continue;
}
const extBuy = externalData.get(type)?.get(month);
if (extBuy !== undefined) {
result.push({ month, type, buy: extBuy, source: "external" });
}
}
}
console.error(
`[monthlyLast] result: ${result.length} rows, months: ${[...new Set(result.map((r) => r.month))].sort().join(", ")}`,
);
cache.set(cacheKey, result, 300);
return c.json(result);
}

View File

@@ -0,0 +1,122 @@
import type { Context } from "hono";
import { cache } from "../../../lib/cache";
import { prisma } from "../../../lib/prisma";
const VALID_TYPES = ["BLUE", "BNA", "BELO"] as const;
const ONE_HOUR = 60 * 60 * 1000;
export async function getMonthlyPattern(c: Context) {
const rawType = c.req.param("type")?.toUpperCase();
if (!VALID_TYPES.includes(rawType as (typeof VALID_TYPES)[number])) {
return c.json(
{
error: `Invalid quote type. Must be one of: ${VALID_TYPES.join(", ")}`,
},
400,
);
}
const cacheKey = `quotes:monthly-pattern:${rawType}`;
const cached = cache.get(cacheKey);
if (cached) return c.json(cached);
const rows = await prisma.$queryRaw<
Array<{
day: number;
months: number;
avgBuy: number;
avgSell: number;
avgBuyPosition: number | null;
avgSellPosition: number | null;
minBuyDays: number;
maxBuyDays: number;
minSellDays: number;
maxSellDays: number;
}>
>`
WITH monthly AS (
SELECT
DATE_TRUNC('month', "timeStamp")::date AS month,
MIN(buy::numeric) AS min_buy,
MAX(buy::numeric) AS max_buy,
MIN(sell::numeric) AS min_sell,
MAX(sell::numeric) AS max_sell
FROM "quotes_history"
WHERE "type" = ${rawType}::"QuoteType"
AND "timeStamp" < DATE_TRUNC('month', NOW())
GROUP BY DATE_TRUNC('month', "timeStamp")
),
daily AS (
SELECT
DATE_TRUNC('month', "timeStamp")::date AS month,
EXTRACT(DAY FROM "timeStamp")::int AS day,
AVG(buy::numeric) AS avg_buy,
AVG(sell::numeric) AS avg_sell,
MIN(buy::numeric) AS day_min_buy,
MAX(buy::numeric) AS day_max_buy,
MIN(sell::numeric) AS day_min_sell,
MAX(sell::numeric) AS day_max_sell
FROM "quotes_history"
WHERE "type" = ${rawType}::"QuoteType"
AND "timeStamp" < DATE_TRUNC('month', NOW())
GROUP BY
DATE_TRUNC('month', "timeStamp"),
EXTRACT(DAY FROM "timeStamp")
)
SELECT
d.day,
COUNT(*)::int AS months,
AVG(d.avg_buy)::float8 AS "avgBuy",
AVG(d.avg_sell)::float8 AS "avgSell",
AVG(
CASE WHEN m.max_buy > m.min_buy
THEN (d.avg_buy - m.min_buy) / (m.max_buy - m.min_buy)
END
)::float8 AS "avgBuyPosition",
AVG(
CASE WHEN m.max_sell > m.min_sell
THEN (d.avg_sell - m.min_sell) / (m.max_sell - m.min_sell)
END
)::float8 AS "avgSellPosition",
COUNT(*) FILTER (WHERE d.day_min_buy = m.min_buy)::int AS "minBuyDays",
COUNT(*) FILTER (WHERE d.day_max_buy = m.max_buy)::int AS "maxBuyDays",
COUNT(*) FILTER (WHERE d.day_min_sell = m.min_sell)::int AS "minSellDays",
COUNT(*) FILTER (WHERE d.day_max_sell = m.max_sell)::int AS "maxSellDays"
FROM daily d
JOIN monthly m ON m.month = d.month
GROUP BY d.day
ORDER BY d.day ASC
`;
const totalMonths = await prisma.$queryRaw<Array<{ count: number }>>`
SELECT COUNT(*)::int AS count
FROM (
SELECT DATE_TRUNC('month', "timeStamp")::date AS month
FROM "quotes_history"
WHERE "type" = ${rawType}::"QuoteType"
AND "timeStamp" < DATE_TRUNC('month', NOW())
GROUP BY DATE_TRUNC('month', "timeStamp")
) AS months
`;
const response = {
type: rawType,
totalMonths: totalMonths[0]?.count ?? 0,
days: rows.map((r) => ({
day: r.day,
months: r.months,
avgBuy: r.avgBuy,
avgSell: r.avgSell,
avgBuyPosition: r.avgBuyPosition,
avgSellPosition: r.avgSellPosition,
minBuyDays: r.minBuyDays,
maxBuyDays: r.maxBuyDays,
minSellDays: r.minSellDays,
maxSellDays: r.maxSellDays,
})),
};
cache.set(cacheKey, response, ONE_HOUR);
return c.json(response);
}

View File

@@ -0,0 +1,76 @@
import type { Context } from "hono";
import type { QuoteType } from "../../../generated/prisma/client";
import { cache } from "../../../lib/cache";
import { prisma } from "../../../lib/prisma";
const VALID_TYPES = ["BLUE", "BNA", "BELO"] as const;
export async function getPeakHours(c: Context) {
const rawType = c.req.param("type")?.toUpperCase();
if (!VALID_TYPES.includes(rawType as (typeof VALID_TYPES)[number])) {
return c.json(
{
error: `Invalid quote type. Must be one of: ${VALID_TYPES.join(", ")}`,
},
400,
);
}
const cacheKey = `quotes:peak-hours:${rawType}`;
const cached = cache.get(cacheKey);
if (cached) return c.json(cached);
const result = await prisma.$queryRaw<
Array<{
hour: number;
frequency: number;
avg_peak_buy: number;
min_peak_buy: number;
max_peak_buy: number;
}>
>`
WITH daily_peaks AS (
SELECT
DATE("timeStamp") AS day,
EXTRACT(HOUR FROM "timeStamp")::int AS peak_hour,
buy::numeric AS peak_buy,
ROW_NUMBER() OVER (
PARTITION BY DATE("timeStamp")
ORDER BY buy::numeric DESC
) AS rn
FROM "quotes_history"
WHERE "type" = ${rawType}::"QuoteType"
)
SELECT
peak_hour AS hour,
COUNT(*)::int AS frequency,
AVG(peak_buy)::float8 AS avg_peak_buy,
MIN(peak_buy)::float8 AS min_peak_buy,
MAX(peak_buy)::float8 AS max_peak_buy
FROM daily_peaks
WHERE rn = 1
GROUP BY peak_hour
ORDER BY peak_hour ASC
`;
const totalDays = await prisma.$queryRaw<Array<{ count: number }>>`
SELECT COUNT(DISTINCT DATE("timeStamp"))::int AS count
FROM "quotes_history"
WHERE "type" = ${rawType}::"QuoteType"
`;
const response = {
totalDays: totalDays[0]?.count ?? 0,
peaks: result.map((r) => ({
hour: r.hour,
frequency: r.frequency,
avgPeakBuy: r.avg_peak_buy,
minPeakBuy: r.min_peak_buy,
maxPeakBuy: r.max_peak_buy,
})),
};
cache.set(cacheKey, response);
return c.json(response);
}

View File

@@ -1,7 +1,7 @@
import cron from "node-cron";
import { eventBus } from "../../lib/event-bus";
import { logger } from "../../lib/logger";
import { checkAndNotifyBeloMax } from "../telegram/telegram.service";
import { checkAndNotifyBelo } from "../telegram/telegram.service";
import { processBeloQuote } from "./belo.service";
import { processBlueQuote } from "./blue.service";
import { processBnaQuote } from "./bna.service";
@@ -14,7 +14,7 @@ async function safeProcess(
await fn();
logger.info(`${name} quote processed successfully`);
if (name === "BELO") {
await checkAndNotifyBeloMax();
await checkAndNotifyBelo();
}
} catch (error) {
logger.error(error, `Error processing ${name} quote`);

View File

@@ -4,15 +4,21 @@ import { getCurrentQuotes } from "./handlers/getCurrentQuotes";
import { getDailyMinMax } from "./handlers/getDailyMinMax";
import { getDailyQuotes } from "./handlers/getDailyQuotes";
import { getHistoricalMinMax } from "./handlers/getHistoricalMinMax";
import { getMonthlyLast } from "./handlers/getMonthlyLast";
import { getMonthlyPattern } from "./handlers/getMonthlyPattern";
import { getPeakHours } from "./handlers/getPeakHours";
import { getQuoteHistory } from "./handlers/getQuoteHistory";
import { quoteEvents } from "./handlers/quoteEvents";
const app = new Hono();
app.get("/", getCurrentQuotes);
app.get("/monthly-last", getMonthlyLast);
app.get("/:type/history", getQuoteHistory);
app.get("/:type/daily", getDailyQuotes);
app.get("/:type/min-max", getDailyMinMax);
app.get("/:type/peak-hours", getPeakHours);
app.get("/:type/monthly-pattern", getMonthlyPattern);
app.get("/:type/historical/min-max", getHistoricalMinMax);
app.get("/fetch", fetchQuotes);
app.get("/events", quoteEvents);

View File

@@ -0,0 +1,29 @@
import type { Context } from "hono";
import { cache } from "../../lib/cache";
import { prisma } from "../../lib/prisma";
export async function getSettings(c: Context) {
const cached = cache.get("settings:all");
if (cached) return c.json(cached);
const settings = await prisma.setting.findMany();
cache.set("settings:all", settings, 60_000);
return c.json(settings);
}
export async function updateSetting(c: Context) {
const body = await c.req.json<{ key: string; value: string }>();
if (!body.key || body.value === undefined) {
return c.json({ error: "key and value are required" }, 400);
}
const setting = await prisma.setting.upsert({
where: { key: body.key },
update: { value: body.value },
create: { key: body.key, value: body.value },
});
cache.invalidateByPrefix("settings:");
return c.json(setting);
}

View File

@@ -0,0 +1,9 @@
import { Hono } from "hono";
import { getSettings, updateSetting } from "./settings.handler";
const app = new Hono();
app.get("/", getSettings);
app.put("/", updateSetting);
export default app;

View File

@@ -1,6 +1,7 @@
import crypto from "crypto";
import { prisma } from "../../lib/prisma";
import type { QuoteType } from "../../generated/prisma/client";
import { logger } from "../../lib/logger";
import { prisma } from "../../lib/prisma";
import { getBot, getBotUsername } from "../../lib/telegram";
function generateRandomCode(): string {
@@ -13,7 +14,7 @@ function generateRandomCode(): string {
return code;
}
function formatPrice(price: number): string {
export function formatPrice(price: number): string {
return price.toLocaleString("es-AR", {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
@@ -72,7 +73,93 @@ export async function getTelegramStatus(): Promise<{
};
}
export async function checkAndNotifyBeloMax(): Promise<void> {
export function formatTime(date: Date): string {
const artOffset = -3;
const artMs = date.getTime() + artOffset * 3600000;
const artDate = new Date(artMs);
return artDate.toLocaleTimeString("es-AR", {
hour: "2-digit",
minute: "2-digit",
hour12: false,
timeZone: "UTC",
});
}
async function checkAndNotifyBound({
chatId,
direction,
currentValue,
quoteTime,
todayStart,
}: {
chatId: string | bigint;
direction: "MAX" | "MIN";
currentValue: number;
quoteTime: Date;
todayStart: Date;
}): Promise<void> {
const bot = getBot();
if (!bot) return;
const isMax = direction === "MAX";
const lastNotified = await prisma.telegramDailyPriceNotification.findUnique({
where: {
date_quoteType_direction: {
date: todayStart,
quoteType: "BELO",
direction,
},
},
});
const lastNotifiedValue = lastNotified
? Number(lastNotified.value)
: isMax
? 0
: Number.POSITIVE_INFINITY;
const shouldNotify = isMax
? currentValue > lastNotifiedValue
: currentValue < lastNotifiedValue;
if (!shouldNotify) return;
const formattedPrice = formatPrice(currentValue);
const time = formatTime(quoteTime);
const icon = isMax ? "🟢📈" : "🔴📉";
const word = isMax ? "máximo" : "mínimo";
const message = `${icon} BELO alcanzó el ${word} del día a las ${time}, cotización actual es de $${formattedPrice}`;
try {
await bot.api.sendMessage(Number(chatId), message);
await prisma.telegramDailyPriceNotification.upsert({
where: {
date_quoteType_direction: {
date: todayStart,
quoteType: "BELO",
direction,
},
},
create: {
date: todayStart,
quoteType: "BELO",
direction,
value: currentValue,
},
update: {
value: currentValue,
},
});
logger.info(`Telegram BELO ${word} notification sent: $${formattedPrice}`);
} catch (error) {
logger.error(error, `Failed to send Telegram BELO ${word} notification`);
}
}
export async function checkAndNotifyBelo(): Promise<void> {
const chat = await prisma.telegramChat.findFirst({
where: { validatedAt: { not: null } },
orderBy: { validatedAt: "desc" },
@@ -84,7 +171,7 @@ export async function checkAndNotifyBeloMax(): Promise<void> {
if (!bot) return;
const now = new Date();
const artHour = ((now.getUTCHours() - 3) % 24 + 24) % 24;
const artHour = (((now.getUTCHours() - 3) % 24) + 24) % 24;
if (artHour < 8 || artHour >= 20) return;
const currentQuote = await prisma.quote.findFirst({
@@ -106,46 +193,93 @@ export async function checkAndNotifyBeloMax(): Promise<void> {
),
);
const lastNotified = await prisma.telegramDailyMaxNotification.findUnique({
where: {
date_quoteType: {
date: todayStart,
quoteType: "BELO",
},
},
await checkAndNotifyBound({
chatId: chat.chatId,
direction: "MAX",
currentValue: currentBuy,
quoteTime: currentQuote.timeStamp,
todayStart,
});
const lastNotifiedValue = lastNotified ? Number(lastNotified.maxValue) : 0;
if (currentBuy <= lastNotifiedValue) return;
const formattedPrice = formatPrice(currentBuy);
const message = `BELO alcanzó el máximo del día, la cotización actual es de $${formattedPrice}`;
try {
await bot.api.sendMessage(Number(chat.chatId), message);
await prisma.telegramDailyMaxNotification.upsert({
where: {
date_quoteType: {
date: todayStart,
quoteType: "BELO",
},
},
create: {
date: todayStart,
quoteType: "BELO",
maxValue: currentBuy,
},
update: {
maxValue: currentBuy,
},
await checkAndNotifyBound({
chatId: chat.chatId,
direction: "MIN",
currentValue: currentBuy,
quoteTime: currentQuote.timeStamp,
todayStart,
});
}
logger.info(
`Telegram BELO max notification sent: $${formattedPrice}`,
export interface QuoteStatus {
buy: number;
sell: number;
timeStamp: Date;
minBuy: number;
maxBuy: number;
minSell: number;
maxSell: number;
progressPercentage: number | null;
}
export async function getQuoteStatus(
type: QuoteType,
): Promise<QuoteStatus | null> {
const currentQuote = await prisma.quote.findFirst({
where: { type },
orderBy: { timeStamp: "desc" },
});
if (!currentQuote) return null;
const now = new Date();
const artOffset = -3;
const artMs = now.getTime() + artOffset * 3600000;
const artDate = new Date(artMs);
const todayStart = new Date(
Date.UTC(
artDate.getUTCFullYear(),
artDate.getUTCMonth(),
artDate.getUTCDate(),
),
);
} catch (error) {
logger.error(error, "Failed to send Telegram BELO max notification");
const agg = await prisma.quoteHistory.aggregate({
where: {
type,
timeStamp: { gte: todayStart },
},
_min: { buy: true, sell: true },
_max: { buy: true, sell: true },
});
const currentBuy = Number(currentQuote.buy);
const minBuy = Number(agg._min.buy ?? currentQuote.buy);
const maxBuy = Number(agg._max.buy ?? currentQuote.buy);
let progressPercentage: number | null = null;
if (maxBuy > minBuy) {
progressPercentage = Math.min(
100,
Math.max(0, ((currentBuy - minBuy) / (maxBuy - minBuy)) * 100),
);
} else {
progressPercentage = 100;
}
return {
buy: currentBuy,
sell: Number(currentQuote.sell),
timeStamp: currentQuote.timeStamp,
minBuy,
maxBuy,
minSell: Number(agg._min.sell ?? currentQuote.sell),
maxSell: Number(agg._max.sell ?? currentQuote.sell),
progressPercentage,
};
}
export async function isChatValidated(chatId: bigint): Promise<boolean> {
const chat = await prisma.telegramChat.findFirst({
where: { chatId, validatedAt: { not: null } },
});
return chat !== null;
}

View File

@@ -0,0 +1,143 @@
import {
afterEach,
beforeEach,
describe,
expect,
mock,
setSystemTime,
test,
} from "bun:test";
import type { Context } from "hono";
const mockQueryRaw = mock();
mock.module("../src/lib/prisma", () => ({
prisma: { $queryRaw: mockQueryRaw },
}));
const { getMonthlyLast } = await import(
"../src/modules/quotes/handlers/getMonthlyLast"
);
const { cache } = await import("../src/lib/cache");
type Row = { month: string; type: string; buy: number };
const originalFetch = globalThis.fetch;
function fakeCasaData(casa: string): unknown[] {
// Un único día por mes, cubriendo de 2025-10 a 2026-10.
const 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",
];
return months.map((m, i) => ({
casa,
fecha: `${m}-15`,
compra: 1000 + i,
venta: 1010 + i,
}));
}
function mockExternalApi() {
globalThis.fetch = mock(async (url: string | URL) => {
const casa = String(url).split("/").pop() ?? "";
return {
ok: true,
status: 200,
json: async () => fakeCasaData(casa),
} as unknown as Response;
}) as unknown as typeof fetch;
}
const context = { json: (data: unknown) => data } as unknown as Context;
beforeEach(() => {
mockQueryRaw.mockClear();
cache.clear();
setSystemTime(new Date("2026-10-14T12:00:00Z"));
});
afterEach(() => {
globalThis.fetch = originalFetch;
setSystemTime();
});
describe("getMonthlyLast", () => {
test("trae 13 meses (12 a mostrar + 1 base) y no descarta el mes en curso del fallback externo", async () => {
mockQueryRaw.mockResolvedValue([]);
mockExternalApi();
const rows = (await getMonthlyLast(context)) as Row[];
const months = [...new Set(rows.map((r) => r.month))].sort();
expect(months).toEqual([
"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
// reciente nunca llegaba desde la API externa.
expect(rows).toContainEqual({
month: "2026-10",
type: "BELO",
buy: 1012,
source: "external",
});
});
test("usa la DB cuando el dato existe y no pega a la API externa", async () => {
const dbRows: Row[] = [];
const 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"]) {
dbRows.push({ month, type, buy: 500 });
}
}
mockQueryRaw.mockResolvedValue(dbRows);
const fetchMock = mock();
globalThis.fetch = fetchMock as unknown as typeof fetch;
const rows = (await getMonthlyLast(context)) as Row[];
expect(fetchMock).not.toHaveBeenCalled();
expect(rows.every((r) => r.source === "db")).toBe(true);
expect(rows).toHaveLength(13 * 3);
});
});

View File

@@ -1,5 +1,5 @@
import { Link, useNavigate } from "@tanstack/react-router";
import { subDays } from "date-fns";
import { subDays, subMonths } from "date-fns";
import { ArrowLeft } from "lucide-react";
import { useMemo, useState } from "react";
import {
@@ -13,7 +13,17 @@ import {
YAxis,
} from "recharts";
import { DatePicker } from "@/components/ui/date-picker";
import { useDailyQuotes, useHistoricalMinMax, useQuotes } from "@/lib/queries";
import {
useDailyQuotes,
useHistoricalMinMax,
useMonthlyLast,
useMonthlyPattern,
usePeakHours,
useQuotes,
} from "@/lib/queries";
import { MonthlyVariationTable } from "./components/MonthlyVariationTable";
import { MonthPatternChart } from "./components/MonthPatternChart";
import { PeakHoursChart } from "./components/PeakHoursChart";
const CURRENCIES = ["BELO", "BLUE", "BNA"] as const;
@@ -67,21 +77,37 @@ export function AnalysisPage({ currency }: { currency: string }) {
endDateStr,
);
const { data: beloDaily, isLoading: beloLoading } = useDailyQuotes(
"BELO",
startDateStr,
endDateStr,
);
const { data: blueDaily, isLoading: blueLoading } = useDailyQuotes(
"BLUE",
startDateStr,
endDateStr,
);
const { data: bnaDaily, isLoading: bnaLoading } = useDailyQuotes(
"BNA",
startDateStr,
endDateStr,
);
const yesterday = subDays(today, 1);
const yesterdayStr = formatDate(yesterday);
const firstOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
const firstOfMonthStr = formatDate(firstOfMonth);
const { data: yesterdayQuote } = useDailyQuotes(
currency,
yesterdayStr,
yesterdayStr,
);
const { data: firstDayQuote } = useDailyQuotes(
currency,
firstOfMonthStr,
firstOfMonthStr,
);
const { data: monthlyLastData } = useMonthlyLast();
const { data: peakHoursData, isLoading: peakHoursLoading } =
usePeakHours("BELO");
const { data: monthlyPatternData, isLoading: monthlyPatternLoading } =
useMonthlyPattern("BELO");
const chartData = useMemo(() => {
if (!daily) return [];
@@ -91,6 +117,47 @@ export function AnalysisPage({ currency }: { currency: string }) {
}));
}, [daily]);
const comparisonData = useMemo(() => {
const map = new Map<
string,
{ date: string; BELO?: number; BLUE?: number; BNA?: number }
>();
const add = (
rows: { date: string; buy: number }[] | undefined,
key: "BELO" | "BLUE" | "BNA",
) => {
rows?.forEach((d) => {
const entry = map.get(d.date) ?? { date: d.date };
entry[key] = d.buy;
map.set(d.date, entry);
});
};
add(beloDaily, "BELO");
add(blueDaily, "BLUE");
add(bnaDaily, "BNA");
return [...map.values()]
.sort((a, b) => a.date.localeCompare(b.date))
.map(({ date, ...rest }) => ({ date: formatShortDate(date), ...rest }));
}, [beloDaily, blueDaily, bnaDaily]);
const comparisonDomain = useMemo(() => {
if (comparisonData.length === 0) return [0, 0] as [number, number];
let min = Infinity;
let max = -Infinity;
for (const d of comparisonData) {
for (const key of ["BELO", "BLUE", "BNA"] as const) {
const value = d[key];
if (value === undefined) continue;
if (value < min) min = value;
if (value > max) max = value;
}
}
if (!Number.isFinite(min) || !Number.isFinite(max))
return [0, 0] as [number, number];
const range = max - min;
return [min - range * 0.2, max + range * 0.2] as [number, number];
}, [comparisonData]);
const { yDomain, minBuyValue, maxBuyValue, avgBuyValue } = useMemo(() => {
if (chartData.length === 0)
return {
@@ -126,11 +193,21 @@ export function AnalysisPage({ currency }: { currency: string }) {
? (prevDayDiff / yesterdayBuy) * 100
: null;
const firstMonthBuy = firstDayQuote?.[0]?.buy ?? null;
const monthDiff = firstMonthBuy !== null ? currentBuy - firstMonthBuy : null;
const previousMonthBuy = useMemo(() => {
if (!monthlyLastData || monthlyLastData.length === 0) return null;
const prevMonth = subMonths(today, 1);
const prevMonthKey = `${prevMonth.getFullYear()}-${String(prevMonth.getMonth() + 1).padStart(2, "0")}`;
const entry = monthlyLastData.find(
(e) => e.month === prevMonthKey && e.type === currency,
);
return entry?.buy ?? null;
}, [monthlyLastData, currency, today]);
const monthDiff =
previousMonthBuy !== null ? currentBuy - previousMonthBuy : null;
const monthPct =
monthDiff !== null && firstMonthBuy !== null && firstMonthBuy !== 0
? (monthDiff / firstMonthBuy) * 100
monthDiff !== null && previousMonthBuy !== null && previousMonthBuy !== 0
? (monthDiff / previousMonthBuy) * 100
: null;
const backTo = currency === "BELO" ? "/quotes/belo" : "/quotes";
@@ -178,7 +255,10 @@ export function AnalysisPage({ currency }: { currency: string }) {
key={c}
type="button"
onClick={() =>
navigate({ to: "/quotes/analysis/$currency", params: { currency: c } })
navigate({
to: "/quotes/analysis/$currency",
params: { currency: c },
})
}
className={`px-3 py-1 text-xs rounded-md transition-colors cursor-pointer ${
currency === c
@@ -244,9 +324,7 @@ export function AnalysisPage({ currency }: { currency: string }) {
<VariationValue value={prevDayDiff} pct={prevDayPct} />
</div>
<div className="rounded-lg border p-4">
<p className="text-sm text-muted-foreground mb-2">
Vs. primer día del mes
</p>
<p className="text-sm text-muted-foreground mb-2">Vs. mes anterior</p>
<VariationValue value={monthDiff} pct={monthPct} />
</div>
</div>
@@ -402,6 +480,155 @@ export function AnalysisPage({ currency }: { currency: string }) {
</>
)}
</div>
<div className="rounded-lg border p-4">
<h2 className="text-sm font-medium mb-4">
Precio de compra por cotización
</h2>
{beloLoading || blueLoading || bnaLoading ? (
<div className="flex items-center justify-center h-64 text-muted-foreground">
Cargando...
</div>
) : comparisonData.length === 0 ? (
<div className="flex items-center justify-center h-64 text-muted-foreground">
Sin datos para este período
</div>
) : (
<>
<div className="h-64">
<ResponsiveContainer width="100%" height="100%">
<LineChart data={comparisonData}>
<CartesianGrid
strokeDasharray="3 3"
className="stroke-border"
/>
<XAxis
dataKey="date"
tick={{ fontSize: 11 }}
className="text-muted-foreground"
interval="preserveStartEnd"
/>
<YAxis
tick={{ fontSize: 11 }}
className="text-muted-foreground"
tickFormatter={(v: number) =>
`$${priceFormatter.format(v)}`
}
width={80}
domain={comparisonDomain}
/>
<Tooltip
formatter={(value: unknown, name: unknown) => [
`$${priceFormatter.format(Number(value))}`,
CURRENCY_LABELS[String(name)] ?? String(name),
]}
labelFormatter={(label: unknown) => `Fecha: ${label}`}
contentStyle={{
backgroundColor: "var(--card)",
border: "1px solid var(--border)",
borderRadius: "var(--radius)",
fontSize: 13,
}}
/>
<Line
type="linear"
dataKey="BELO"
name="BELO"
stroke="var(--chart-1)"
strokeWidth={2}
dot={false}
activeDot={{ r: 4 }}
isAnimationActive={false}
/>
<Line
type="linear"
dataKey="BLUE"
name="BLUE"
stroke="var(--chart-2)"
strokeWidth={2}
dot={false}
activeDot={{ r: 4 }}
isAnimationActive={false}
/>
<Line
type="linear"
dataKey="BNA"
name="BNA"
stroke="var(--chart-4)"
strokeWidth={2}
dot={false}
activeDot={{ r: 4 }}
isAnimationActive={false}
/>
</LineChart>
</ResponsiveContainer>
</div>
<div className="flex items-center justify-center gap-4 mt-3">
<div className="flex items-center gap-1.5">
<span
className="size-2.5 rounded-full"
style={{ backgroundColor: "var(--chart-1)" }}
/>
<span className="text-xs text-muted-foreground">BELO</span>
</div>
<div className="flex items-center gap-1.5">
<span
className="size-2.5 rounded-full"
style={{ backgroundColor: "var(--chart-2)" }}
/>
<span className="text-xs text-muted-foreground">
Dólar Blue
</span>
</div>
<div className="flex items-center gap-1.5">
<span
className="size-2.5 rounded-full"
style={{ backgroundColor: "var(--chart-4)" }}
/>
<span className="text-xs text-muted-foreground">
Dólar Oficial
</span>
</div>
</div>
</>
)}
</div>
<div className="rounded-lg border p-4">
<h2 className="text-sm font-medium mb-4">
Variación mensual vs. inflación
</h2>
<MonthlyVariationTable />
</div>
{currency === "BELO" && (
<>
<div className="rounded-lg border p-4">
<h2 className="text-sm font-medium mb-4">
Análisis de pico horario
</h2>
<p className="text-xs text-muted-foreground mb-4">
Frecuencia con la que cada hora del día fue el momento de mayor
precio de compra dentro de cada día.
</p>
<PeakHoursChart data={peakHoursData} isLoading={peakHoursLoading} />
</div>
<div className="rounded-lg border p-4">
<h2 className="text-sm font-medium mb-4">Patrón mensual</h2>
<p className="text-xs text-muted-foreground mb-4">
Posición del precio dentro de cada mes (0% = mínimo del mes, 100%
= máximo), promediada entre los meses completos disponibles. Se
excluye la tendencia inflacionaria para comparar momentos del mes.
</p>
<MonthPatternChart
data={monthlyPatternData}
isLoading={monthlyPatternLoading}
/>
</div>
</>
)}
</div>
);
}

View File

@@ -0,0 +1,293 @@
import { useMemo, useState } from "react";
import {
Bar,
BarChart,
CartesianGrid,
Cell,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from "recharts";
import type { MonthlyPatternResponse } from "@/lib/api";
import { cn } from "@/lib/utils";
const priceFormatter = new Intl.NumberFormat("es-AR", {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
});
type Mode = "sell" | "buy";
type ChartEntry = {
day: number;
months: number;
position: number;
avgPrice: number;
recommended: boolean;
};
export function MonthPatternChart({
data,
isLoading,
}: {
data: MonthlyPatternResponse | undefined;
isLoading: boolean;
}) {
const [mode, setMode] = useState<Mode>("sell");
const { chartData, totalMonths, bestSellDay, bestBuyDay, minCoverage } =
useMemo(() => {
const totalMonths = data?.totalMonths ?? 0;
const allDays = data?.days ?? [];
const byDay = new Map(allDays.map((d) => [d.day, d]));
const minCoverage = Math.max(3, Math.ceil(totalMonths * 0.5));
const eligible = allDays.filter((d) => d.months >= minCoverage);
let bestSellDay: number | null = null;
let bestSellPosition = -Infinity;
for (const d of eligible) {
const pos = d.avgBuyPosition ?? null;
if (pos !== null && pos > bestSellPosition) {
bestSellPosition = pos;
bestSellDay = d.day;
}
}
let bestBuyDay: number | null = null;
let bestBuyPosition = Infinity;
for (const d of eligible) {
const pos = d.avgSellPosition ?? null;
if (pos !== null && pos < bestBuyPosition) {
bestBuyPosition = pos;
bestBuyDay = d.day;
}
}
const recommended = mode === "sell" ? bestSellDay : bestBuyDay;
const chartData: ChartEntry[] = Array.from({ length: 31 }, (_, i) => {
const day = i + 1;
const found = byDay.get(day);
const position =
mode === "sell"
? (found?.avgBuyPosition ?? 0)
: (found?.avgSellPosition ?? 0);
return {
day,
months: found?.months ?? 0,
position,
avgPrice:
mode === "sell" ? (found?.avgBuy ?? 0) : (found?.avgSell ?? 0),
recommended: recommended !== null && day === recommended,
};
});
return {
chartData,
totalMonths,
bestSellDay,
bestBuyDay,
minCoverage,
};
}, [data, mode]);
if (isLoading) {
return (
<div className="flex items-center justify-center h-64 text-muted-foreground text-sm">
Cargando datos del patrón mensual...
</div>
);
}
if (totalMonths === 0 || chartData.every((d) => d.months === 0)) {
return (
<div className="flex items-center justify-center h-64 text-muted-foreground text-sm">
Sin suficiente historial. Se necesitan al menos 2 meses completos de
datos.
</div>
);
}
return (
<div className="space-y-4">
<div className="grid gap-4 md:grid-cols-3">
<div className="rounded-lg border p-4">
<p className="text-sm text-muted-foreground mb-1">
Mejor día para vender USDC
</p>
<p className="text-2xl font-bold">
{bestSellDay !== null ? `Día ${bestSellDay}` : "Sin datos"}
</p>
<p className="text-xs text-muted-foreground mt-0.5">
Precio de compra más alto del mes
</p>
</div>
<div className="rounded-lg border p-4">
<p className="text-sm text-muted-foreground mb-1">
Mejor día para comprar USDC
</p>
<p className="text-2xl font-bold">
{bestBuyDay !== null ? `Día ${bestBuyDay}` : "Sin datos"}
</p>
<p className="text-xs text-muted-foreground mt-0.5">
Precio de venta más bajo del mes
</p>
</div>
<div className="rounded-lg border p-4">
<p className="text-sm text-muted-foreground mb-1">Meses analizados</p>
<p className="text-2xl font-bold tabular-nums">{totalMonths}</p>
<p className="text-xs text-muted-foreground mt-0.5">
Mínimo de cobertura por día: {minCoverage} meses
</p>
</div>
</div>
<div className="flex items-center gap-2">
<div className="flex items-center gap-1 rounded-lg border p-0.5">
<button
type="button"
onClick={() => setMode("sell")}
className={cn(
"px-3 py-1 text-xs rounded-md transition-colors cursor-pointer",
mode === "sell"
? "bg-primary text-primary-foreground"
: "text-muted-foreground hover:text-foreground",
)}
>
Vender USDC (compra)
</button>
<button
type="button"
onClick={() => setMode("buy")}
className={cn(
"px-3 py-1 text-xs rounded-md transition-colors cursor-pointer",
mode === "buy"
? "bg-primary text-primary-foreground"
: "text-muted-foreground hover:text-foreground",
)}
>
Comprar USDC (venta)
</button>
</div>
<p className="text-xs text-muted-foreground">
Posición promedio dentro del mes (0% = mínimo, 100% = máximo)
</p>
</div>
<div className="h-64">
<ResponsiveContainer width="100%" height="100%">
<BarChart data={chartData}>
<CartesianGrid
strokeDasharray="3 3"
className="stroke-border"
vertical={false}
/>
<XAxis
dataKey="day"
tick={{ fontSize: 10 }}
className="text-muted-foreground"
interval={2}
/>
<YAxis
tick={{ fontSize: 11 }}
className="text-muted-foreground"
domain={[0, 1]}
tickFormatter={(v: number) => `${Math.round(v * 100)}%`}
label={{
value: "Posición en el mes",
angle: -90,
position: "insideLeft",
offset: 10,
style: { fontSize: 11, fill: "hsl(var(--muted-foreground))" },
}}
/>
<Tooltip
cursor={{ fill: "hsl(var(--muted) / 0.3)" }}
content={({ active, payload }) => {
if (!active || !payload?.length) return null;
const d = payload[0].payload as ChartEntry;
return (
<div
className="rounded-lg border bg-card p-3 text-sm shadow-sm"
style={{ minWidth: 180 }}
>
<p className="font-semibold mb-1">Día {d.day}</p>
<div className="space-y-0.5 text-muted-foreground">
<p>
Posición:{" "}
<span className="font-medium text-foreground">
{Math.round(d.position * 100)}%
</span>
</p>
{d.avgPrice > 0 && (
<p>
Precio promedio:{" "}
<span className="font-medium text-foreground">
${priceFormatter.format(d.avgPrice)}
</span>
</p>
)}
<p>
Con datos en:{" "}
<span className="font-medium text-foreground">
{d.months} meses
</span>
</p>
{d.recommended && (
<p className="text-emerald-500 font-medium">
Día recomendado
</p>
)}
</div>
</div>
);
}}
/>
<Bar
dataKey="position"
radius={[4, 4, 0, 0]}
isAnimationActive={false}
>
{chartData.map((entry) => (
<Cell
key={entry.day}
fill={
entry.recommended
? mode === "sell"
? "var(--chart-1)"
: "var(--chart-2)"
: "hsl(var(--muted-foreground) / 0.25)"
}
fillOpacity={entry.months === 0 ? 0.4 : 1}
/>
))}
</Bar>
</BarChart>
</ResponsiveContainer>
</div>
<div className="flex items-center justify-center gap-4">
<div className="flex items-center gap-1.5">
<span
className="size-2.5 rounded-full"
style={{ backgroundColor: "var(--chart-1)" }}
/>
<span className="text-xs text-muted-foreground">
Mejor día para vender USDC
</span>
</div>
<div className="flex items-center gap-1.5">
<span
className="size-2.5 rounded-full"
style={{ backgroundColor: "var(--chart-2)" }}
/>
<span className="text-xs text-muted-foreground">
Mejor día para comprar USDC
</span>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,505 @@
import { ArrowDown, ArrowRight, ArrowUp, TrendingUp } from "lucide-react";
import { useMemo } from "react";
import { useInflation, useMonthlyLast } from "@/lib/queries";
type MonthKey = string;
type CurrencyValues = {
variation: number | null;
prev: number | null;
current: number | null;
};
type MonthRow = {
month: MonthKey;
label: string;
fromDb: boolean;
BELO: CurrencyValues;
BLUE: CurrencyValues;
BNA: CurrencyValues;
inflation: number | null;
};
const MONTH_NAMES = [
"Enero",
"Febrero",
"Marzo",
"Abril",
"Mayo",
"Junio",
"Julio",
"Agosto",
"Septiembre",
"Octubre",
"Noviembre",
"Diciembre",
];
// La ventana trae 12 meses a mostrar + 1 mes "base" al inicio, que se usa para
// calcular la variación del mes más antiguo mostrado.
const DISPLAY_MONTHS = 12;
function formatMonth(monthKey: string): string {
const [y, m] = monthKey.split("-");
return `${MONTH_NAMES[Number(m) - 1]} ${y}`;
}
function formatPct(value: number): string {
const sign = value >= 0 ? "+" : "";
return `${sign}${value.toFixed(1)}%`;
}
const priceFormatter = new Intl.NumberFormat("es-AR", {
minimumFractionDigits: 0,
maximumFractionDigits: 0,
});
function formatPrice(value: number): string {
return `$${priceFormatter.format(value)}`;
}
function TotalVariation({
variation,
inflation,
}: {
variation: number | null;
inflation: number | null;
}) {
if (variation === null) {
return (
<span className="text-xs text-muted-foreground inline-flex items-center gap-1">
--
</span>
);
}
return (
<span
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 ? (
<ArrowUp className="size-3" />
) : (
<ArrowDown className="size-3" />
)}
{formatPct(variation)}
</span>
);
}
function VariationIndicator({
variation,
inflation,
prev,
current,
}: {
variation: number | null;
inflation: number | null;
prev: number | null;
current: number | null;
}) {
if (variation === null) {
return (
<span className="text-xs text-muted-foreground inline-flex items-center gap-1">
<ArrowRight className="size-3" />
--
{current !== null && (
<span className="text-[10px] tabular-nums">
{formatPrice(current)}
</span>
)}
</span>
);
}
const indicator = (
<span
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 ? (
<ArrowUp className="size-3" />
) : (
<ArrowDown className="size-3" />
)}
{formatPct(variation)}
</span>
);
if (prev !== null && current !== null) {
return (
<span className="inline-flex items-center gap-1.5">
{indicator}
<span className="text-[10px] text-muted-foreground tabular-nums">
{formatPrice(prev)} → {formatPrice(current)}
</span>
</span>
);
}
return indicator;
}
export function MonthlyVariationTable() {
const { data: monthlyData, isLoading: monthlyLoading } = useMonthlyLast();
const { data: inflationData, isLoading: inflationLoading } = useInflation();
const rows = useMemo<MonthRow[]>(() => {
if (!monthlyData || monthlyData.length === 0) return [];
const monthsMap = new Map<
MonthKey,
{
BELO: number | null;
BLUE: number | null;
BNA: number | null;
dbTypes: Set<string>;
}
>();
for (const entry of monthlyData) {
const existing = monthsMap.get(entry.month) ?? {
BELO: null,
BLUE: null,
BNA: null,
dbTypes: new Set(),
};
if (entry.type === "BELO") existing.BELO = entry.buy;
if (entry.type === "BLUE") existing.BLUE = entry.buy;
if (entry.type === "BNA") existing.BNA = entry.buy;
if (entry.source === "db") existing.dbTypes.add(entry.type);
monthsMap.set(entry.month, existing);
}
const inflationMap = new Map<MonthKey, number>();
if (inflationData) {
for (const inf of inflationData) {
const monthKey = inf.fecha.slice(0, 7);
inflationMap.set(monthKey, inf.valor);
}
}
const sortedMonths = [...monthsMap.keys()].sort();
const calcVariation = (
currentVal: number | null,
prevVal: number | null,
): number | null => {
if (currentVal === null || prevVal === null || prevVal === 0) return null;
return ((currentVal - prevVal) / prevVal) * 100;
};
const allRows = sortedMonths.map((month, i) => {
const prev = i > 0 ? sortedMonths[i - 1] : null;
const current = monthsMap.get(month);
const prevData = prev ? monthsMap.get(prev) : null;
const beloVar = calcVariation(
current?.BELO ?? null,
prevData?.BELO ?? null,
);
const blueVar = calcVariation(
current?.BLUE ?? null,
prevData?.BLUE ?? null,
);
const bnaVar = calcVariation(current?.BNA ?? null, prevData?.BNA ?? null);
let inflation: number | null = null;
inflation = inflationMap.get(month) ?? null;
return {
month,
label: formatMonth(month),
fromDb: (current?.dbTypes.size ?? 0) > 0,
BELO: {
variation: beloVar,
prev: prevData?.BELO ?? null,
current: current?.BELO ?? null,
},
BLUE: {
variation: blueVar,
prev: prevData?.BLUE ?? null,
current: current?.BLUE ?? null,
},
BNA: {
variation: bnaVar,
prev: prevData?.BNA ?? null,
current: current?.BNA ?? null,
},
inflation,
};
});
// Descartamos el mes base (el más antiguo) del render: ya cumplió su
// función como mes previo para calcular la variación del primero mostrado.
return allRows.slice(-DISPLAY_MONTHS).reverse();
}, [monthlyData, inflationData]);
const summary = useMemo(() => {
if (rows.length < 2) return null;
const oldest = rows[rows.length - 1];
const newest = rows[0];
const totalVariation = (
first: number | null,
last: number | null,
): number | null => {
if (first === null || last === null || first === 0) return null;
return ((last - first) / first) * 100;
};
const accumulatedInflation = rows.reduce<number | null>((acc, row) => {
if (row.inflation === null) return acc;
const factor = 1 + row.inflation / 100;
return (acc ?? 1) * factor;
}, null);
return {
BELO: totalVariation(oldest.BELO.current, newest.BELO.current),
BLUE: totalVariation(oldest.BLUE.current, newest.BLUE.current),
BNA: totalVariation(oldest.BNA.current, newest.BNA.current),
inflation:
accumulatedInflation !== null ? (accumulatedInflation - 1) * 100 : null,
period: `${oldest.label} – ${newest.label}`,
};
}, [rows]);
const isLoading = monthlyLoading || inflationLoading;
if (isLoading) {
return (
<div className="flex items-center justify-center h-32 text-muted-foreground text-sm">
Cargando datos mensuales...
</div>
);
}
if (rows.length === 0) {
return (
<div className="flex items-center justify-center h-32 text-muted-foreground text-sm">
Sin datos mensuales disponibles
</div>
);
}
return (
<>
<div className="space-y-2 sm:hidden">
{rows.map((row) => (
<div
key={row.month}
className="rounded-lg border bg-card p-3 text-sm"
>
<div className="flex items-center justify-between mb-2">
<span className={row.fromDb ? "font-semibold" : "font-normal"}>
{row.label}
</span>
{row.inflation !== null ? (
<span className="text-xs text-muted-foreground tabular-nums inline-flex items-center gap-1">
<TrendingUp className="size-3" />
{formatPct(row.inflation)} inflación
</span>
) : (
<span className="text-xs text-muted-foreground">
Sin inflación
</span>
)}
</div>
<div className="grid grid-cols-3 gap-2">
<div>
<p className="text-[10px] text-muted-foreground mb-0.5">BELO</p>
<VariationIndicator
variation={row.BELO.variation}
inflation={row.inflation}
prev={row.BELO.prev}
current={row.BELO.current}
/>
</div>
<div>
<p className="text-[10px] text-muted-foreground mb-0.5">Blue</p>
<VariationIndicator
variation={row.BLUE.variation}
inflation={row.inflation}
prev={row.BLUE.prev}
current={row.BLUE.current}
/>
</div>
<div>
<p className="text-[10px] text-muted-foreground mb-0.5">
Oficial
</p>
<VariationIndicator
variation={row.BNA.variation}
inflation={row.inflation}
prev={row.BNA.prev}
current={row.BNA.current}
/>
</div>
</div>
</div>
))}
{summary && (
<div className="rounded-lg border bg-muted/50 p-3 text-sm">
<div className="flex items-center justify-between mb-2">
<span className="font-semibold">Total 12 meses</span>
{summary.inflation !== null ? (
<span className="text-xs text-muted-foreground tabular-nums inline-flex items-center gap-1">
<TrendingUp className="size-3" />
{formatPct(summary.inflation)} inflación
</span>
) : (
<span className="text-xs text-muted-foreground">
Sin inflación
</span>
)}
</div>
<div className="grid grid-cols-3 gap-2">
<div>
<p className="text-[10px] text-muted-foreground mb-0.5">BELO</p>
<TotalVariation
variation={summary.BELO}
inflation={summary.inflation}
/>
</div>
<div>
<p className="text-[10px] text-muted-foreground mb-0.5">Blue</p>
<TotalVariation
variation={summary.BLUE}
inflation={summary.inflation}
/>
</div>
<div>
<p className="text-[10px] text-muted-foreground mb-0.5">
Oficial
</p>
<TotalVariation
variation={summary.BNA}
inflation={summary.inflation}
/>
</div>
</div>
</div>
)}
</div>
<div className="hidden overflow-x-auto rounded-lg border sm:block">
<table className="w-full text-sm">
<thead>
<tr className="border-b bg-muted/50">
<th className="px-3 py-2 text-left text-xs font-medium text-muted-foreground">
Mes
</th>
<th className="px-3 py-2 text-right text-xs font-medium text-muted-foreground">
BELO
</th>
<th className="px-3 py-2 text-right text-xs font-medium text-muted-foreground">
Blue
</th>
<th className="px-3 py-2 text-right text-xs font-medium text-muted-foreground">
Oficial
</th>
<th className="px-3 py-2 text-right text-xs font-medium text-muted-foreground">
Inflación
</th>
</tr>
</thead>
<tbody>
{rows.map((row) => (
<tr
key={row.month}
className="border-b last:border-0 hover:bg-muted/30"
>
<td
className={`px-3 py-2.5 ${row.fromDb ? "font-semibold" : "font-normal"}`}
>
{row.label}
</td>
<td className="px-3 py-2.5 text-right">
<VariationIndicator
variation={row.BELO.variation}
inflation={row.inflation}
prev={row.BELO.prev}
current={row.BELO.current}
/>
</td>
<td className="px-3 py-2.5 text-right">
<VariationIndicator
variation={row.BLUE.variation}
inflation={row.inflation}
prev={row.BLUE.prev}
current={row.BLUE.current}
/>
</td>
<td className="px-3 py-2.5 text-right">
<VariationIndicator
variation={row.BNA.variation}
inflation={row.inflation}
prev={row.BNA.prev}
current={row.BNA.current}
/>
</td>
<td className="px-3 py-2.5 text-right">
{row.inflation !== null ? (
<span className="text-xs text-muted-foreground tabular-nums">
{formatPct(row.inflation)}
</span>
) : (
<span className="text-xs text-muted-foreground">--</span>
)}
</td>
</tr>
))}
{summary && (
<tr className="border-t-2 bg-muted/50 font-medium">
<td className="px-3 py-2.5 text-xs">Total 12 meses</td>
<td className="px-3 py-2.5 text-right">
<TotalVariation
variation={summary.BELO}
inflation={summary.inflation}
/>
</td>
<td className="px-3 py-2.5 text-right">
<TotalVariation
variation={summary.BLUE}
inflation={summary.inflation}
/>
</td>
<td className="px-3 py-2.5 text-right">
<TotalVariation
variation={summary.BNA}
inflation={summary.inflation}
/>
</td>
<td className="px-3 py-2.5 text-right">
{summary.inflation !== null ? (
<span className="text-xs font-medium tabular-nums">
{formatPct(summary.inflation)}
</span>
) : (
<span className="text-xs text-muted-foreground">--</span>
)}
</td>
</tr>
)}
</tbody>
</table>
</div>
</>
);
}

View File

@@ -0,0 +1,184 @@
import { useMemo } from "react";
import {
Bar,
BarChart,
CartesianGrid,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from "recharts";
import type { PeakHoursResponse } from "@/lib/api";
const priceFormatter = new Intl.NumberFormat("es-AR", {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
});
type ChartEntry = {
hour: string;
frequency: number;
avgPeakBuy: number;
minPeakBuy: number;
maxPeakBuy: number;
isPeak: boolean;
};
export function PeakHoursChart({
data,
isLoading,
}: {
data: PeakHoursResponse | undefined;
isLoading: boolean;
}) {
const { chartData, peakHour, totalDays } = useMemo(() => {
if (!data || data.peaks.length === 0) {
return { chartData: [], peakHour: null, totalDays: 0 };
}
const maxFreq = Math.max(...data.peaks.map((p) => p.frequency));
const allHours: ChartEntry[] = Array.from({ length: 24 }, (_, i) => {
const found = data.peaks.find((p) => p.hour === i);
return {
hour: `${String(i).padStart(2, "0")}hs`,
frequency: found?.frequency ?? 0,
avgPeakBuy: found?.avgPeakBuy ?? 0,
minPeakBuy: found?.minPeakBuy ?? 0,
maxPeakBuy: found?.maxPeakBuy ?? 0,
isPeak: found?.frequency === maxFreq && found !== undefined,
};
});
const peak = data.peaks.find((p) => p.frequency === maxFreq);
return {
chartData: allHours,
peakHour: peak ?? null,
totalDays: data.totalDays,
};
}, [data]);
if (isLoading) {
return (
<div className="flex items-center justify-center h-64 text-muted-foreground text-sm">
Cargando datos de pico horario...
</div>
);
}
if (chartData.length === 0 || totalDays === 0) {
return (
<div className="flex items-center justify-center h-64 text-muted-foreground text-sm">
Sin datos de pico horario disponibles
</div>
);
}
return (
<div>
{peakHour && (
<div className="mb-4 flex items-center gap-2 text-sm">
<span className="text-muted-foreground">
El pico más frecuente ocurre a las{" "}
<span className="font-semibold text-foreground">
{String(peakHour.hour).padStart(2, "0")}hs
</span>{" "}
({peakHour.frequency} de {totalDays} días) con un promedio de{" "}
<span className="font-semibold text-foreground">
${priceFormatter.format(peakHour.avgPeakBuy)}
</span>
</span>
</div>
)}
<div className="h-64">
<ResponsiveContainer width="100%" height="100%">
<BarChart data={chartData}>
<CartesianGrid
strokeDasharray="3 3"
className="stroke-border"
vertical={false}
/>
<XAxis
dataKey="hour"
tick={{ fontSize: 10 }}
className="text-muted-foreground"
interval={2}
/>
<YAxis
tick={{ fontSize: 11 }}
className="text-muted-foreground"
allowDecimals={false}
label={{
value: "Frecuencia",
angle: -90,
position: "insideLeft",
offset: 10,
style: { fontSize: 11, fill: "hsl(var(--muted-foreground))" },
}}
/>
<Tooltip
cursor={{ fill: "hsl(var(--muted) / 0.3)" }}
content={({ active, payload }) => {
if (!active || !payload?.length) return null;
const d = payload[0].payload as ChartEntry;
return (
<div
className="rounded-lg border bg-card p-3 text-sm shadow-sm"
style={{ minWidth: 180 }}
>
<p className="font-semibold mb-1">{d.hour}</p>
<div className="space-y-0.5 text-muted-foreground">
<p>
Veces pico:{" "}
<span className="font-medium text-foreground">
{d.frequency}
</span>
</p>
{d.frequency > 0 && (
<>
<p>
Precio promedio:{" "}
<span className="font-medium text-foreground">
${priceFormatter.format(d.avgPeakBuy)}
</span>
</p>
<p>
Rango:{" "}
<span className="font-medium text-foreground">
${priceFormatter.format(d.minPeakBuy)} – $
{priceFormatter.format(d.maxPeakBuy)}
</span>
</p>
</>
)}
</div>
</div>
);
}}
/>
<Bar
dataKey="frequency"
name="Frecuencia"
radius={[4, 4, 0, 0]}
isAnimationActive={false}
fill="var(--chart-2)"
/>
</BarChart>
</ResponsiveContainer>
</div>
<div className="flex items-center justify-center gap-4 mt-3">
<div className="flex items-center gap-1.5">
<span
className="size-2.5 rounded-full"
style={{ backgroundColor: "var(--chart-2)" }}
/>
<span className="text-xs text-muted-foreground">
Frecuencia de pico por hora
</span>
</div>
</div>
</div>
);
}

View File

@@ -9,9 +9,9 @@ import {
import type { Quote } from "@/lib/api";
import {
useFetchQuotes,
useMonthlyPayedTotal,
useMonthlyTotals,
useQuotes,
useSettings,
useWallets,
} from "@/lib/queries";
import { RelativeTime } from "@/lib/time";
@@ -131,15 +131,15 @@ export function DashboardPage() {
const bna = quotes?.find((q) => q.type === "BNA");
const now = new Date();
const { data: monthlyExpenses } = useMonthlyPayedTotal(
now.getFullYear(),
now.getMonth() + 1,
);
const { data: monthlyTotals } = useMonthlyTotals(
now.getFullYear(),
now.getMonth() + 1,
);
const { data: settings } = useSettings();
const salaryMultiplier =
settings?.find((s) => s.key === "salary_multiplier")?.value ?? "4500";
const isFetching = isLoading || isPending;
const { data: wallets } = useWallets();
@@ -173,9 +173,12 @@ export function DashboardPage() {
</p>
</div>
<div className="rounded-lg border p-4">
<p className="text-sm text-muted-foreground">Gastos del mes</p>
<p className="text-sm text-muted-foreground">Sueldo</p>
<p className="text-2xl font-bold">
${priceFormatter.format(monthlyExpenses?.total ?? 0)}
$
{priceFormatter.format(
(belo ? Number(belo.buy) : 0) * Number(salaryMultiplier),
)}
</p>
</div>
<QuoteCard
@@ -202,12 +205,11 @@ export function DashboardPage() {
<h2 className="text-lg font-semibold">Billeteras</h2>
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
{wallets.map((w) => (
<div
key={w.id}
className="rounded-lg border p-4"
>
<div key={w.id} className="rounded-lg border p-4">
<p className="text-sm text-muted-foreground">{w.name}</p>
<p className="text-sm text-muted-foreground/60 text-xs">{w.currency}</p>
<p className="text-sm text-muted-foreground/60 text-xs">
{w.currency}
</p>
<p className="text-2xl font-bold tabular-nums mt-1">
{walletBalanceFormatter.format(w.balance)}
</p>

View File

@@ -45,6 +45,38 @@ export type HistoricalMinMax = {
maxBuyDate: string | null;
};
export type PeakHour = {
hour: number;
frequency: number;
avgPeakBuy: number;
minPeakBuy: number;
maxPeakBuy: number;
};
export type PeakHoursResponse = {
totalDays: number;
peaks: PeakHour[];
};
export type MonthPatternDay = {
day: number;
months: number;
avgBuy: number;
avgSell: number;
avgBuyPosition: number | null;
avgSellPosition: number | null;
minBuyDays: number;
maxBuyDays: number;
minSellDays: number;
maxSellDays: number;
};
export type MonthlyPatternResponse = {
type: string;
totalMonths: number;
days: MonthPatternDay[];
};
async function fetcher<T>(url: string): Promise<T> {
const res = await fetch(url, { credentials: "include" });
if (!res.ok) {
@@ -109,6 +141,41 @@ export function getHistoricalMinMax(type: string): Promise<HistoricalMinMax> {
return fetcher<HistoricalMinMax>(`/api/quotes/${type}/historical/min-max`);
}
export function getPeakHours(type: string): Promise<PeakHoursResponse> {
return fetcher<PeakHoursResponse>(`/api/quotes/${type}/peak-hours`);
}
export function getMonthlyPattern(
type: string,
): Promise<MonthlyPatternResponse> {
return fetcher<MonthlyPatternResponse>(`/api/quotes/${type}/monthly-pattern`);
}
export type MonthlyLast = {
month: string;
type: "BELO" | "BLUE" | "BNA";
buy: number;
source: "db" | "external";
};
export function getMonthlyLast(): Promise<MonthlyLast[]> {
return fetcher<MonthlyLast[]>("/api/quotes/monthly-last");
}
export type InflationMonth = {
fecha: string;
valor: number;
};
export function getInflation(): Promise<InflationMonth[]> {
return fetch(
"https://api.argentinadatos.com/v1/finanzas/indices/inflacion",
).then((r) => {
if (!r.ok) throw new Error(`Inflation API error: ${r.status}`);
return r.json();
});
}
// Expenses
export type PeriodicExpense = {
@@ -339,7 +406,12 @@ export type Wallet = {
export type WalletMovement = {
id: number;
walletId: number;
type: "DEPOSIT" | "WITHDRAWAL" | "TRANSFER_IN" | "TRANSFER_OUT" | "ADJUSTMENT";
type:
| "DEPOSIT"
| "WITHDRAWAL"
| "TRANSFER_IN"
| "TRANSFER_OUT"
| "ADJUSTMENT";
amount: number;
description: string | null;
referenceWalletId: number | null;
@@ -390,10 +462,7 @@ export function deleteWallet(id: number): Promise<void> {
return mutator<void>(`/api/wallets/${id}`, "DELETE");
}
export function depositWallet(
id: number,
data: DepositInput,
): Promise<Wallet> {
export function depositWallet(id: number, data: DepositInput): Promise<Wallet> {
return mutator<Wallet>(`/api/wallets/${id}/deposit`, "POST", data);
}
@@ -418,9 +487,7 @@ export function setDefaultWallet(id: number): Promise<Wallet> {
return mutator<Wallet>(`/api/wallets/${id}/default`, "PUT");
}
export function getWalletMovements(
id: number,
): Promise<WalletMovement[]> {
export function getWalletMovements(id: number): Promise<WalletMovement[]> {
return fetcher<WalletMovement[]>(`/api/wallets/${id}/movements`);
}
@@ -447,6 +514,21 @@ export function getWalletMovementsFiltered(
);
}
// Settings
export type Setting = {
key: string;
value: string;
};
export function getSettings(): Promise<Setting[]> {
return fetcher<Setting[]>("/api/settings");
}
export function updateSetting(key: string, value: string): Promise<Setting> {
return mutator<Setting>("/api/settings", "PUT", { key, value });
}
// Telegram
export type TelegramStatus = {

View File

@@ -6,47 +6,53 @@ import {
} from "@tanstack/react-query";
import {
type AdjustBalanceInput,
adjustBalance as adjustBalanceApi,
type CreateNonPeriodicExpenseInput,
type CreatePeriodicExpenseInput,
type CreateWalletInput,
type DepositInput,
type TransferInput,
type WalletMovementsFilter,
createNonPeriodicExpense as createNonPeriodicExpenseApi,
createPeriodicExpense as createPeriodicExpenseApi,
createWallet as createWalletApi,
type DepositInput,
deletePeriodicExpense as deletePeriodicExpenseApi,
deleteWallet as deleteWalletApi,
depositWallet as depositWalletApi,
adjustBalance as adjustBalanceApi,
fetchQuotes,
generateMonthlyExpense as generateMonthlyExpenseApi,
generateTelegramCode,
getDailyMinMax,
getDailyQuotes,
getExpenses,
generateTelegramCode,
getHistoricalMinMax,
getInflation,
getMonthlyLast,
getMonthlyPattern,
getMonthlyPayedTotal,
getMonthlyTotals,
getPeakHours,
getPendingUpcomingExpenses,
getPeriodicExpenses,
getQuoteHistory,
getQuotes,
getSettings,
getTelegramStatus,
getTotalPending,
getWalletMovements,
getWalletMovementsFiltered,
getWallets,
setDefaultWallet as setDefaultWalletApi,
importExpenses,
importPeriodicExpenses,
type PayExpenseInput,
payExpense as payExpenseApi,
setDefaultWallet as setDefaultWalletApi,
type TransferInput,
transferWallet as transferWalletApi,
type UpdateExpenseInput,
updateExpense as updateExpenseApi,
updatePeriodicExpense as updatePeriodicExpenseApi,
createWallet as createWalletApi,
updateSetting as updateSettingApi,
updateWallet as updateWalletApi,
deleteWallet as deleteWalletApi,
transferWallet as transferWalletApi,
type WalletMovementsFilter,
} from "./api";
export const quoteKeys = {
@@ -59,6 +65,8 @@ export const quoteKeys = {
["quotes", type, "daily", startDate, endDate] as const,
historicalMinMax: (type: string) =>
["quotes", type, "historicalMinMax"] as const,
peakHours: (type: string) => ["quotes", type, "peakHours"] as const,
monthlyPattern: (type: string) => ["quotes", type, "monthlyPattern"] as const,
};
export function useQuotes() {
@@ -128,6 +136,38 @@ export function useHistoricalMinMax(type: string) {
});
}
export function usePeakHours(type: string) {
return useQuery({
queryKey: quoteKeys.peakHours(type),
queryFn: () => getPeakHours(type),
staleTime: 30_000,
});
}
export function useMonthlyPattern(type: string) {
return useQuery({
queryKey: quoteKeys.monthlyPattern(type),
queryFn: () => getMonthlyPattern(type),
staleTime: 30_000,
});
}
export function useMonthlyLast() {
return useQuery({
queryKey: ["quotes", "monthlyLast"] as const,
queryFn: getMonthlyLast,
staleTime: 60_000,
});
}
export function useInflation() {
return useQuery({
queryKey: ["inflation"] as const,
queryFn: getInflation,
staleTime: 86_400_000,
});
}
// Expenses
export const expenseKeys = {
@@ -422,6 +462,31 @@ export function useWalletMovementsFiltered(filter: WalletMovementsFilter) {
});
}
// Settings
export const settingKeys = {
all: ["settings"] as const,
};
export function useSettings() {
return useQuery({
queryKey: settingKeys.all,
queryFn: getSettings,
staleTime: 60_000,
});
}
export function useUpdateSetting() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({ key, value }: { key: string; value: string }) =>
updateSettingApi(key, value),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: settingKeys.all });
},
});
}
// Telegram
export function useTelegramStatus() {

View File

@@ -1,12 +1,14 @@
import { createFileRoute } from "@tanstack/react-router";
import { Check, Copy, RefreshCw } from "lucide-react";
import { useState } from "react";
import { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { useAuth } from "@/lib/auth-context";
import {
useGenerateTelegramCode,
useSettings,
useTelegramStatus,
useUpdateSetting,
} from "@/lib/queries";
export const Route = createFileRoute("/_authenticated/settings")({
@@ -126,11 +128,79 @@ function SettingsPage() {
<hr className="border-border" />
<SalaryMultiplierSection />
<TelegramSection />
</div>
);
}
function SalaryMultiplierSection() {
const { data: settings, isLoading } = useSettings();
const updateSetting = useUpdateSetting();
const current =
settings?.find((s) => s.key === "salary_multiplier")?.value ?? "4500";
const [localValue, setLocalValue] = useState(current);
const [success, setSuccess] = useState(false);
useEffect(() => {
if (settings) {
const val = settings.find((s) => s.key === "salary_multiplier")?.value;
if (val) setLocalValue(val);
}
}, [settings]);
async function handleSave() {
setSuccess(false);
await updateSetting.mutateAsync({
key: "salary_multiplier",
value: localValue,
});
setSuccess(true);
setTimeout(() => setSuccess(false), 2000);
}
return (
<div className="space-y-4">
<div>
<h2 className="text-lg font-semibold tracking-tight">
Multiplicador de sueldo
</h2>
<p className="text-sm text-muted-foreground">
Valor para calcular el sueldo (Sueldo = BELO bid x este valor)
</p>
</div>
{isLoading ? (
<p className="text-sm text-muted-foreground">Cargando...</p>
) : (
<div className="space-y-3">
<div className="flex items-center gap-2">
<Input
type="number"
value={localValue}
onChange={(e) => setLocalValue(e.target.value)}
className="w-32"
/>
<Button
type="button"
onClick={handleSave}
disabled={updateSetting.isPending || localValue === current}
>
{updateSetting.isPending ? "Guardando..." : "Guardar"}
</Button>
</div>
{success && (
<p className="text-sm text-emerald-600">
Multiplicador actualizado correctamente
</p>
)}
</div>
)}
</div>
);
}
function TelegramSection() {
const { data: status, isLoading } = useTelegramStatus();
const {

311
pnpm-lock.yaml generated Normal file
View File

@@ -0,0 +1,311 @@
lockfileVersion: '9.0'
settings:
autoInstallPeers: true
excludeLinksFromLockfile: false
importers:
.:
dependencies:
'@noble/ciphers':
specifier: ^2.2.0
version: 2.4.0
devDependencies:
'@biomejs/biome':
specifier: ^2.4.16
version: 2.5.10
concurrently:
specifier: ^9.1.0
version: 9.2.4
packages:
'@biomejs/biome@2.5.10':
resolution: {integrity: sha512-WRKXARA3kTuiV5sxqTpobJ/I0MVd4vk3pOL6wnp5az4LntFIhWTj1RWZq3DI9PCEN3lXcqy7p5aqUHzvq8AXyQ==}
engines: {node: '>=14.21.3'}
hasBin: true
'@biomejs/cli-darwin-arm64@2.5.10':
resolution: {integrity: sha512-ItCrxKK6SXVT6flYs0qIuBd4AA3TTTl4d66Re6YI2FuGZnN85NmuYNzkiTJUyYw8qBLv69L5zTUB6uyWd++h3Q==}
engines: {node: '>=14.21.3'}
cpu: [arm64]
os: [darwin]
'@biomejs/cli-darwin-x64@2.5.10':
resolution: {integrity: sha512-yLsPU9pAmtChXDu8vhKAzErqe+LeeYuwuUB2FZMkRitsmdodxsYRa9KHrFispsUHzzOu+9HB3nP/TQxyia+Sjw==}
engines: {node: '>=14.21.3'}
cpu: [x64]
os: [darwin]
'@biomejs/cli-linux-arm64-musl@2.5.10':
resolution: {integrity: sha512-t1QAKZwQJRB4dvgJSgFiQ4BNfNPChg69BNonz854qLVxnjT3UvDzQg9mbkTJRu35ZqU0Rw10A73J8Urgbg2RPw==}
engines: {node: '>=14.21.3'}
cpu: [arm64]
os: [linux]
libc: [musl]
'@biomejs/cli-linux-arm64@2.5.10':
resolution: {integrity: sha512-VG8uQW/86a1roLaIFvtIbEigxIdzdJ190oGyg1tV7VYeQtOS+x10sflk7WbuXgw91EtZX5DlIIIej1YqkNLlcg==}
engines: {node: '>=14.21.3'}
cpu: [arm64]
os: [linux]
libc: [glibc]
'@biomejs/cli-linux-x64-musl@2.5.10':
resolution: {integrity: sha512-pgDDqp9JybHm2I0KRgzN6i4+lt8xu4iqxUwLzglUMmOmyRTU1AYBGKzh9sNMOtIjah7xoWvKHlLVetvyifzoiQ==}
engines: {node: '>=14.21.3'}
cpu: [x64]
os: [linux]
libc: [musl]
'@biomejs/cli-linux-x64@2.5.10':
resolution: {integrity: sha512-4O6T0eq2heoHZN0a9UX+rWQoxXEBaKf+lRi2hbsGlHneUz9BWXM76nEWMK7Eeq8gzMxR1khQB6BFpAASpeXqGg==}
engines: {node: '>=14.21.3'}
cpu: [x64]
os: [linux]
libc: [glibc]
'@biomejs/cli-win32-arm64@2.5.10':
resolution: {integrity: sha512-pxAbxduPO4xq/Cvgaa2lOrs9BB0hEXmmDqfMNP4ZOffGOkUrD1/QGw9UAMpFQpX2P8MqTIIRuQKcmetum4Oa6A==}
engines: {node: '>=14.21.3'}
cpu: [arm64]
os: [win32]
'@biomejs/cli-win32-x64@2.5.10':
resolution: {integrity: sha512-M+2dgBsl3lXRiTfgPVc2p3anS4Tocojke4rzFLScZ2Y/wmF+36dRb1iHCLiyGqOzQGyTplZH1HnEYviiAqi3nA==}
engines: {node: '>=14.21.3'}
cpu: [x64]
os: [win32]
'@noble/ciphers@2.4.0':
resolution: {integrity: sha512-AnjFn0Jv92laAkvMrghlFZq4qQCIN/4DxFV/eooqtC2YTjB7kBeLMS2T9KJX4Dn+ZVXLOwK0lSgqDtx9gvxtiw==}
engines: {node: '>= 20.19.0'}
ansi-regex@5.0.1:
resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==}
engines: {node: '>=8'}
ansi-styles@4.3.0:
resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==}
engines: {node: '>=8'}
chalk@4.1.2:
resolution: {integrity: sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==}
engines: {node: '>=10'}
cliui@8.0.1:
resolution: {integrity: sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==}
engines: {node: '>=12'}
color-convert@2.0.1:
resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==}
engines: {node: '>=7.0.0'}
color-name@1.1.4:
resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==}
concurrently@9.2.4:
resolution: {integrity: sha512-TZ0CEhyzvFjgtAvHTusDMgj7wNdihCh7LLLrzdUOXIhdlnL2JBBGA9eJxR24rtqgmdjh3OA3hrN1rCHj6HM8qA==}
engines: {node: '>=18'}
hasBin: true
emoji-regex@8.0.0:
resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==}
escalade@3.2.0:
resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==}
engines: {node: '>=6'}
get-caller-file@2.0.5:
resolution: {integrity: sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==}
engines: {node: 6.* || 8.* || >= 10.*}
has-flag@4.0.0:
resolution: {integrity: sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==}
engines: {node: '>=8'}
is-fullwidth-code-point@3.0.0:
resolution: {integrity: sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==}
engines: {node: '>=8'}
require-directory@2.1.1:
resolution: {integrity: sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==}
engines: {node: '>=0.10.0'}
rxjs@7.8.2:
resolution: {integrity: sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==}
shell-quote@1.9.0:
resolution: {integrity: sha512-Iov+JwFv/2HcTpcwNMKd8+IWNb8tboQJNQTkAY/LLVK7gGH9jy+LGkVqPxfekHl+yMmiqXszdGWXgkfml7hjqA==}
engines: {node: '>= 0.4'}
string-width@4.2.3:
resolution: {integrity: sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==}
engines: {node: '>=8'}
strip-ansi@6.0.1:
resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==}
engines: {node: '>=8'}
supports-color@7.2.0:
resolution: {integrity: sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==}
engines: {node: '>=8'}
supports-color@8.1.1:
resolution: {integrity: sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==}
engines: {node: '>=10'}
tree-kill@1.2.2:
resolution: {integrity: sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==}
hasBin: true
tslib@2.8.1:
resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==}
wrap-ansi@7.0.0:
resolution: {integrity: sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==}
engines: {node: '>=10'}
y18n@5.0.8:
resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==}
engines: {node: '>=10'}
yargs-parser@21.1.1:
resolution: {integrity: sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==}
engines: {node: '>=12'}
yargs@17.7.2:
resolution: {integrity: sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==}
engines: {node: '>=12'}
snapshots:
'@biomejs/biome@2.5.10':
optionalDependencies:
'@biomejs/cli-darwin-arm64': 2.5.10
'@biomejs/cli-darwin-x64': 2.5.10
'@biomejs/cli-linux-arm64': 2.5.10
'@biomejs/cli-linux-arm64-musl': 2.5.10
'@biomejs/cli-linux-x64': 2.5.10
'@biomejs/cli-linux-x64-musl': 2.5.10
'@biomejs/cli-win32-arm64': 2.5.10
'@biomejs/cli-win32-x64': 2.5.10
'@biomejs/cli-darwin-arm64@2.5.10':
optional: true
'@biomejs/cli-darwin-x64@2.5.10':
optional: true
'@biomejs/cli-linux-arm64-musl@2.5.10':
optional: true
'@biomejs/cli-linux-arm64@2.5.10':
optional: true
'@biomejs/cli-linux-x64-musl@2.5.10':
optional: true
'@biomejs/cli-linux-x64@2.5.10':
optional: true
'@biomejs/cli-win32-arm64@2.5.10':
optional: true
'@biomejs/cli-win32-x64@2.5.10':
optional: true
'@noble/ciphers@2.4.0': {}
ansi-regex@5.0.1: {}
ansi-styles@4.3.0:
dependencies:
color-convert: 2.0.1
chalk@4.1.2:
dependencies:
ansi-styles: 4.3.0
supports-color: 7.2.0
cliui@8.0.1:
dependencies:
string-width: 4.2.3
strip-ansi: 6.0.1
wrap-ansi: 7.0.0
color-convert@2.0.1:
dependencies:
color-name: 1.1.4
color-name@1.1.4: {}
concurrently@9.2.4:
dependencies:
chalk: 4.1.2
rxjs: 7.8.2
shell-quote: 1.9.0
supports-color: 8.1.1
tree-kill: 1.2.2
yargs: 17.7.2
emoji-regex@8.0.0: {}
escalade@3.2.0: {}
get-caller-file@2.0.5: {}
has-flag@4.0.0: {}
is-fullwidth-code-point@3.0.0: {}
require-directory@2.1.1: {}
rxjs@7.8.2:
dependencies:
tslib: 2.8.1
shell-quote@1.9.0: {}
string-width@4.2.3:
dependencies:
emoji-regex: 8.0.0
is-fullwidth-code-point: 3.0.0
strip-ansi: 6.0.1
strip-ansi@6.0.1:
dependencies:
ansi-regex: 5.0.1
supports-color@7.2.0:
dependencies:
has-flag: 4.0.0
supports-color@8.1.1:
dependencies:
has-flag: 4.0.0
tree-kill@1.2.2: {}
tslib@2.8.1: {}
wrap-ansi@7.0.0:
dependencies:
ansi-styles: 4.3.0
string-width: 4.2.3
strip-ansi: 6.0.1
y18n@5.0.8: {}
yargs-parser@21.1.1: {}
yargs@17.7.2:
dependencies:
cliui: 8.0.1
escalade: 3.2.0
get-caller-file: 2.0.5
require-directory: 2.1.1
string-width: 4.2.3
y18n: 5.0.8
yargs-parser: 21.1.1