"use client"; import { useMemo } from "react"; import { useTransactions } from "@/lib/hooks"; import { useBankingMetadata } from "@/lib/hooks"; import type { TransactionsPaginatedParams } from "@/services/banking.service"; interface UseTransactionsForAccountFilterParams { selectedCategories: string[]; period: "1month" | "3months" | "6months" | "12months" | "custom" | "all"; customStartDate?: Date; customEndDate?: Date; showReconciled: string; searchQuery: string; } /** * Hook to fetch transactions filtered by categories, period, search, reconciled * but NOT by accounts. Used for displaying account totals in account filter. */ export function useTransactionsForAccountFilter({ selectedCategories, period, customStartDate, customEndDate, showReconciled, searchQuery, }: UseTransactionsForAccountFilterParams) { const { data: metadata } = useBankingMetadata(); // Calculate start date based on period const startDate = useMemo(() => { const now = new Date(); switch (period) { case "1month": return new Date(now.getFullYear(), now.getMonth() - 1, 1); case "3months": return new Date(now.getFullYear(), now.getMonth() - 3, 1); case "6months": return new Date(now.getFullYear(), now.getMonth() - 6, 1); case "12months": return new Date(now.getFullYear(), now.getMonth() - 12, 1); case "custom": return customStartDate || new Date(0); default: return new Date(0); } }, [period, customStartDate]); // Calculate end date (only for custom period) const endDate = useMemo(() => { if (period === "custom" && customEndDate) { return customEndDate; } return undefined; }, [period, customEndDate]); // Build params for fetching all transactions (no pagination, no account filter) const filterParams = useMemo(() => { const params: TransactionsPaginatedParams = { limit: 10000, // Large limit to get all transactions offset: 0, sortField: "date", sortOrder: "asc", }; if (startDate && period !== "all") { params.startDate = startDate.toISOString().split("T")[0]; } if (endDate) { params.endDate = endDate.toISOString().split("T")[0]; } // NOTE: We intentionally don't filter by accounts here if (!selectedCategories.includes("all")) { if (selectedCategories.includes("uncategorized")) { params.includeUncategorized = true; } else { params.categoryIds = selectedCategories; } } if (searchQuery) { params.search = searchQuery; } if (showReconciled !== "all") { params.isReconciled = showReconciled === "reconciled"; } return params; }, [ startDate, endDate, selectedCategories, searchQuery, showReconciled, period, ]); // Fetch all filtered transactions (without account filter) const { data: transactionsData, isLoading } = useTransactions( filterParams, !!metadata, ); return { transactions: transactionsData?.transactions || [], isLoading, }; }