feat(expenses): add monthly totals and pagination support for expenses

This commit is contained in:
Jose Selesan
2026-05-29 10:59:40 -03:00
parent e1786f7384
commit 4b17940134
12 changed files with 410 additions and 57 deletions

View File

@@ -0,0 +1,129 @@
import * as React from "react"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { ChevronLeftIcon, ChevronRightIcon, MoreHorizontalIcon } from "lucide-react"
function Pagination({ className, ...props }: React.ComponentProps<"nav">) {
return (
<nav
role="navigation"
aria-label="pagination"
data-slot="pagination"
className={cn("mx-auto flex w-full justify-center", className)}
{...props}
/>
)
}
function PaginationContent({
className,
...props
}: React.ComponentProps<"ul">) {
return (
<ul
data-slot="pagination-content"
className={cn("flex items-center gap-0.5", className)}
{...props}
/>
)
}
function PaginationItem({ ...props }: React.ComponentProps<"li">) {
return <li data-slot="pagination-item" {...props} />
}
type PaginationLinkProps = {
isActive?: boolean
} & Pick<React.ComponentProps<typeof Button>, "size"> &
React.ComponentProps<"a">
function PaginationLink({
className,
isActive,
size = "icon",
...props
}: PaginationLinkProps) {
return (
<Button
asChild
variant={isActive ? "outline" : "ghost"}
size={size}
className={cn(className)}
>
<a
aria-current={isActive ? "page" : undefined}
data-slot="pagination-link"
data-active={isActive}
{...props}
/>
</Button>
)
}
function PaginationPrevious({
className,
text = "Previous",
...props
}: React.ComponentProps<typeof PaginationLink> & { text?: string }) {
return (
<PaginationLink
aria-label="Go to previous page"
size="default"
className={cn("pl-1.5!", className)}
{...props}
>
<ChevronLeftIcon data-icon="inline-start" />
<span className="hidden sm:block">{text}</span>
</PaginationLink>
)
}
function PaginationNext({
className,
text = "Next",
...props
}: React.ComponentProps<typeof PaginationLink> & { text?: string }) {
return (
<PaginationLink
aria-label="Go to next page"
size="default"
className={cn("pr-1.5!", className)}
{...props}
>
<span className="hidden sm:block">{text}</span>
<ChevronRightIcon data-icon="inline-end" />
</PaginationLink>
)
}
function PaginationEllipsis({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
aria-hidden
data-slot="pagination-ellipsis"
className={cn(
"flex size-8 items-center justify-center [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
<MoreHorizontalIcon
/>
<span className="sr-only">More pages</span>
</span>
)
}
export {
Pagination,
PaginationContent,
PaginationEllipsis,
PaginationItem,
PaginationLink,
PaginationNext,
PaginationPrevious,
}

View File

@@ -1,7 +1,7 @@
import { Minus, RefreshCw, TrendingDown, TrendingUp } from "lucide-react";
import { RelativeTime } from "@/lib/time";
import type { Quote } from "@/lib/api";
import { useQuotes, useFetchQuotes } from "@/lib/queries";
import { useQuotes, useFetchQuotes, useMonthlyPayedTotal } from "@/lib/queries";
import { useNavigate } from "@tanstack/react-router";
import {
Tooltip,
@@ -101,6 +101,9 @@ export function DashboardPage() {
const belo = quotes?.find((q) => q.type === "BELO");
const blue = quotes?.find((q) => q.type === "BLUE");
const now = new Date();
const { data: monthlyExpenses } = useMonthlyPayedTotal(now.getFullYear(), now.getMonth() + 1);
const isFetching = isLoading || isPending;
return (
@@ -124,7 +127,7 @@ export function DashboardPage() {
</div>
<div className="rounded-lg border p-4">
<p className="text-sm text-muted-foreground">Gastos del mes</p>
<p className="text-2xl font-bold">$0.00</p>
<p className="text-2xl font-bold">${priceFormatter.format(monthlyExpenses?.total ?? 0)}</p>
</div>
<QuoteCard quote={belo} title="BELO" to="/quotes/belo" variant="minimal" />
<QuoteCard quote={blue} title="BLUE" variant="minimal" />

View File

@@ -8,6 +8,7 @@ import {
useExpenses,
useCreateNonPeriodicExpense,
usePayExpense,
useMonthlyTotals,
} from "@/lib/queries";
import type {
PeriodicExpense,
@@ -15,16 +16,24 @@ import type {
CreatePeriodicExpenseInput,
CreateNonPeriodicExpenseInput,
PayExpenseInput,
PaginatedResponse,
MonthlyTotals,
} from "@/lib/api";
interface ExpensesContextValue {
periodicExpenses: PeriodicExpense[];
isLoadingPeriodic: boolean;
expenses: Expense[];
expenses: PaginatedResponse<Expense>;
isLoadingExpenses: boolean;
statusFilter: string;
setStatusFilter: (status: string) => void;
page: number;
setPage: (page: number) => void;
pageSize: number;
monthlyTotals: MonthlyTotals | undefined;
isLoadingTotals: boolean;
createPeriodicExpense: (data: CreatePeriodicExpenseInput) => Promise<PeriodicExpense>;
updatePeriodicExpense: (id: number, data: CreatePeriodicExpenseInput) => Promise<void>;
@@ -38,9 +47,15 @@ const ExpensesContext = createContext<ExpensesContextValue | null>(null);
export function ExpensesProvider({ children }: { children: ReactNode }) {
const [statusFilter, setStatusFilter] = useState("PENDING");
const [page, setPage] = useState(1);
const pageSize = 10;
const { data: periodicExpenses = [], isLoading: isLoadingPeriodic } = usePeriodicExpenses();
const { data: expenses = [], isLoading: isLoadingExpenses } = useExpenses(statusFilter);
const { data: expenses = { data: [], total: 0, page: 1, pageSize: 10 }, isLoading: isLoadingExpenses } =
useExpenses(statusFilter, page, pageSize);
const now = new Date();
const { data: monthlyTotals, isLoading: isLoadingTotals } = useMonthlyTotals(now.getFullYear(), now.getMonth() + 1);
const createPeriodicMutation = useCreatePeriodicExpense();
const updatePeriodicMutation = useUpdatePeriodicExpense();
@@ -100,6 +115,11 @@ export function ExpensesProvider({ children }: { children: ReactNode }) {
isLoadingExpenses,
statusFilter,
setStatusFilter,
page,
setPage,
pageSize,
monthlyTotals,
isLoadingTotals,
createPeriodicExpense,
updatePeriodicExpense: updatePeriodicExpenseFn,
deletePeriodicExpense: deletePeriodicExpenseFn,

View File

@@ -7,8 +7,23 @@ import { Button } from "@/components/ui/button";
import { Plus } from "lucide-react";
import type { Expense } from "@/lib/api";
const priceFormatter = new Intl.NumberFormat("es-AR", {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
});
export function ExpensesTabContent() {
const { expenses, isLoadingExpenses, statusFilter, setStatusFilter } = useExpensesContext();
const {
expenses,
isLoadingExpenses,
statusFilter,
setStatusFilter,
page,
setPage,
pageSize,
monthlyTotals,
isLoadingTotals,
} = useExpensesContext();
const [payDialogExpense, setPayDialogExpense] = useState<Expense | null>(null);
const [newExpenseOpen, setNewExpenseOpen] = useState(false);
@@ -28,7 +43,7 @@ export function ExpensesTabContent() {
key={f.value}
variant={statusFilter === f.value ? "default" : "outline"}
size="xs"
onClick={() => setStatusFilter(f.value)}
onClick={() => { setStatusFilter(f.value); setPage(1); }}
>
{f.label}
</Button>
@@ -43,9 +58,35 @@ export function ExpensesTabContent() {
{isLoadingExpenses ? (
<p className="text-sm text-muted-foreground">Cargando...</p>
) : (
<ExpensesTable data={expenses} onPay={setPayDialogExpense} />
<ExpensesTable
data={expenses.data}
onPay={setPayDialogExpense}
page={expenses.page}
total={expenses.total}
pageSize={expenses.pageSize}
onPageChange={setPage}
/>
)}
<div className="grid gap-4 sm:grid-cols-2">
<div className="rounded-lg border p-4">
<p className="text-sm text-muted-foreground">Total Pagado</p>
<p className="text-2xl font-bold tabular-nums">
{isLoadingTotals
? "..."
: `$${priceFormatter.format(monthlyTotals?.payed ?? 0)}`}
</p>
</div>
<div className="rounded-lg border p-4">
<p className="text-sm text-muted-foreground">Total Pendiente</p>
<p className="text-2xl font-bold tabular-nums">
{isLoadingTotals
? "..."
: `$${priceFormatter.format(monthlyTotals?.pending ?? 0)}`}
</p>
</div>
</div>
<PayExpenseDialog
expense={payDialogExpense}
open={payDialogExpense !== null}

View File

@@ -8,13 +8,25 @@ import {
import type { Expense } from "@/lib/api";
import { Button } from "@/components/ui/button";
import { CircleDollarSign } from "lucide-react";
import {
Pagination,
PaginationContent,
PaginationItem,
PaginationLink,
PaginationNext,
PaginationPrevious,
} from "@/components/ui/pagination";
interface ExpensesTableProps {
data: Expense[];
onPay: (expense: Expense) => void;
page: number;
total: number;
pageSize: number;
onPageChange: (page: number) => void;
}
export function ExpensesTable({ data, onPay }: ExpensesTableProps) {
export function ExpensesTable({ data, onPay, page, total, pageSize, onPageChange }: ExpensesTableProps) {
const columns = useMemo<ColumnDef<Expense>[]>(
() => [
{
@@ -101,42 +113,78 @@ export function ExpensesTable({ data, onPay }: ExpensesTableProps) {
getCoreRowModel: getCoreRowModel(),
});
const totalPages = Math.max(1, Math.ceil(total / pageSize));
return (
<div className="overflow-x-auto rounded-lg border">
<table className="w-full text-sm">
<thead>
{table.getHeaderGroups().map((headerGroup) => (
<tr key={headerGroup.id} className="border-b bg-muted/50">
{headerGroup.headers.map((header) => (
<th
key={header.id}
className="px-3 py-2 text-left text-xs font-medium text-muted-foreground"
>
{flexRender(header.column.columnDef.header, header.getContext())}
</th>
))}
</tr>
))}
</thead>
<tbody>
{table.getRowModel().rows.map((row) => (
<tr key={row.id} className="border-b last:border-0 hover:bg-muted/30">
{row.getVisibleCells().map((cell) => (
<td key={cell.id} className="px-3 py-2.5">
{flexRender(cell.column.columnDef.cell, cell.getContext())}
<div className="space-y-4">
<div className="overflow-x-auto rounded-lg border">
<table className="w-full text-sm">
<thead>
{table.getHeaderGroups().map((headerGroup) => (
<tr key={headerGroup.id} className="border-b bg-muted/50">
{headerGroup.headers.map((header) => (
<th
key={header.id}
className="px-3 py-2 text-left text-xs font-medium text-muted-foreground"
>
{flexRender(header.column.columnDef.header, header.getContext())}
</th>
))}
</tr>
))}
</thead>
<tbody>
{table.getRowModel().rows.map((row) => (
<tr key={row.id} className="border-b last:border-0 hover:bg-muted/30">
{row.getVisibleCells().map((cell) => (
<td key={cell.id} className="px-3 py-2.5">
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</td>
))}
</tr>
))}
{table.getRowModel().rows.length === 0 && (
<tr>
<td colSpan={columns.length} className="px-3 py-8 text-center text-sm text-muted-foreground">
No hay gastos para mostrar.
</td>
))}
</tr>
))}
{table.getRowModel().rows.length === 0 && (
<tr>
<td colSpan={columns.length} className="px-3 py-8 text-center text-sm text-muted-foreground">
No hay gastos para mostrar.
</td>
</tr>
)}
</tbody>
</table>
</tr>
)}
</tbody>
</table>
</div>
{totalPages > 1 && (
<Pagination>
<PaginationContent>
<PaginationItem>
<PaginationPrevious
onClick={(e) => { e.preventDefault(); if (page > 1) onPageChange(page - 1); }}
href="#"
className={page <= 1 ? "pointer-events-none opacity-50" : ""}
/>
</PaginationItem>
{Array.from({ length: totalPages }, (_, i) => i + 1).map((p) => (
<PaginationItem key={p}>
<PaginationLink
isActive={p === page}
onClick={(e) => { e.preventDefault(); onPageChange(p); }}
href="#"
>
{p}
</PaginationLink>
</PaginationItem>
))}
<PaginationItem>
<PaginationNext
onClick={(e) => { e.preventDefault(); if (page < totalPages) onPageChange(page + 1); }}
href="#"
className={page >= totalPages ? "pointer-events-none opacity-50" : ""}
/>
</PaginationItem>
</PaginationContent>
</Pagination>
)}
</div>
);
}

View File

@@ -158,9 +158,41 @@ export function generateMonthlyExpense(id: number): Promise<Expense> {
return mutator<Expense>(`/api/periodic-expenses/${id}/generate-month`, "POST");
}
export function getExpenses(status?: string): Promise<Expense[]> {
const params = status ? `?status=${status}` : "";
return fetcher<Expense[]>(`/api/expenses${params}`);
export type MonthlyExpensesTotal = { total: number };
export function getMonthlyPayedTotal(year?: number, month?: number): Promise<MonthlyExpensesTotal> {
const params = new URLSearchParams();
if (year) params.set("year", String(year));
if (month) params.set("month", String(month));
return fetcher<MonthlyExpensesTotal>(`/api/expenses/monthly-total?${params}`);
}
export type PaginatedResponse<T> = {
data: T[];
total: number;
page: number;
pageSize: number;
};
export type MonthlyTotals = {
payed: number;
pending: number;
};
export function getExpenses(status?: string, page?: number, pageSize?: number): Promise<PaginatedResponse<Expense>> {
const params = new URLSearchParams();
if (status) params.set("status", status);
if (page) params.set("page", String(page));
if (pageSize) params.set("pageSize", String(pageSize));
const qs = params.toString();
return fetcher<PaginatedResponse<Expense>>(`/api/expenses${qs ? `?${qs}` : ""}`);
}
export function getMonthlyTotals(year?: number, month?: number): Promise<MonthlyTotals> {
const params = new URLSearchParams();
if (year) params.set("year", String(year));
if (month) params.set("month", String(month));
return fetcher<MonthlyTotals>(`/api/expenses/totals?${params}`);
}
export function createNonPeriodicExpense(data: CreateNonPeriodicExpenseInput): Promise<Expense> {

View File

@@ -7,6 +7,8 @@ import {
generateMonthlyExpense as generateMonthlyExpenseApi,
getExpenses, createNonPeriodicExpense as createNonPeriodicExpenseApi,
payExpense as payExpenseApi,
getMonthlyPayedTotal,
getMonthlyTotals,
type CreatePeriodicExpenseInput, type CreateNonPeriodicExpenseInput, type PayExpenseInput,
} from "./api";
@@ -72,7 +74,10 @@ export function useDailyQuotes(type: string, startDate: string, endDate: string)
export const expenseKeys = {
periodic: ["periodic-expenses"] as const,
all: ["expenses"] as const,
byStatus: (status: string) => ["expenses", status] as const,
byStatus: (status: string, page: number, pageSize: number) =>
["expenses", status, page, pageSize] as const,
monthlyTotal: (year: number, month: number) => ["expenses", "monthly-total", year, month] as const,
monthlyTotals: (year: number, month: number) => ["expenses", "totals", year, month] as const,
};
export function usePeriodicExpenses() {
@@ -123,10 +128,24 @@ export function useGenerateMonthlyExpense() {
});
}
export function useExpenses(status: string) {
export function useExpenses(status: string, page: number = 1, pageSize: number = 10) {
return useQuery({
queryKey: expenseKeys.byStatus(status),
queryFn: () => getExpenses(status === "all" ? undefined : status),
queryKey: expenseKeys.byStatus(status, page, pageSize),
queryFn: () => getExpenses(status === "all" ? undefined : status, page, pageSize),
});
}
export function useMonthlyTotals(year: number, month: number) {
return useQuery({
queryKey: expenseKeys.monthlyTotals(year, month),
queryFn: () => getMonthlyTotals(year, month),
});
}
export function useMonthlyPayedTotal(year: number, month: number) {
return useQuery({
queryKey: expenseKeys.monthlyTotal(year, month),
queryFn: () => getMonthlyPayedTotal(year, month),
});
}