Compare commits

...

26 Commits

Author SHA1 Message Date
Julien Froidefond
8a4f6d31b8 feat: enhance tooltip and global styles for improved visibility; implement custom tooltip rendering in CategoryTrendChart and enforce opacity settings in globals.css for Radix Portal and Recharts tooltips
All checks were successful
Deploy with Docker Compose / deploy (push) Successful in 4m7s
2025-12-23 12:28:13 +01:00
Julien Froidefond
804b0f0aad feat: add sidebar-opaque color variable and update Sidebar component styling; enhance visual consistency by applying new background color to the sidebar 2025-12-23 12:15:49 +01:00
Julien Froidefond
f295e86fc2 refactor: improve code formatting and consistency in StatisticsPage and TopExpensesList components; standardize quotation marks and enhance readability across various sections
All checks were successful
Deploy with Docker Compose / deploy (push) Successful in 2m57s
2025-12-23 11:49:31 +01:00
Julien Froidefond
c57daa9cc8 refactor: standardize quotation marks in pnpm-lock.yaml and improve code formatting across various components; enhance readability and maintain consistency in code style 2025-12-23 11:42:02 +01:00
Julien Froidefond
01c1f25de2 feat: add transaction statistics to TransactionsPage; implement reconciled and categorized percentage calculations, enhance card layout, and update UI components for improved data presentation
All checks were successful
Deploy with Docker Compose / deploy (push) Successful in 2m11s
2025-12-23 11:27:06 +01:00
Julien Froidefond
9de7d1a467 feat: enhance tooltip functionality in BalanceLineChart; implement custom content rendering for improved data presentation and user interaction, including dynamic styling and formatting of displayed values
All checks were successful
Deploy with Docker Compose / deploy (push) Successful in 2m4s
2025-12-23 11:14:07 +01:00
Julien Froidefond
407486a109 feat: implement top expenses categorization and enhance UI with tabs; display top 10 expenses per top 5 parent categories, improving data organization and user navigation in the statistics page 2025-12-23 11:07:15 +01:00
Julien Froidefond
e0597b0dcb feat: update theme management across the application; change default theme to 'light', disable system theme option, and add ThemeCard component in settings for enhanced user customization
All checks were successful
Deploy with Docker Compose / deploy (push) Successful in 2m23s
2025-12-23 07:59:33 +01:00
Julien Froidefond
b2eac21bdf refactor: clean up imports and improve code consistency across various components; remove unused imports in page.tsx, add missing imports in categories page, and standardize formatting in hooks and chart components
All checks were successful
Deploy with Docker Compose / deploy (push) Successful in 1m30s
2025-12-22 08:46:59 +01:00
Julien Froidefond
7c3f522531 feat: refine Sidebar component layout and styling; adjust padding, spacing, and button styles for improved visual consistency and user experience 2025-12-22 08:45:41 +01:00
Julien Froidefond
4f13134ef0 feat: enhance global styles and component themes with new semantic colors; integrate ThemeProvider for improved theme management and update color usage across various components for consistency 2025-12-22 08:40:25 +01:00
Julien Froidefond
6c14484636 feat: introduce customizable background options with new gradient and solid color styles; integrate BackgroundProvider and BackgroundCard components for enhanced user experience in settings and layout
All checks were successful
Deploy with Docker Compose / deploy (push) Successful in 1m52s
2025-12-21 13:43:16 +01:00
Julien Froidefond
2452e30a0f feat: enhance card components across the application with consistent hover effects and improved layout; update spacing in categories page for better visual hierarchy
All checks were successful
Deploy with Docker Compose / deploy (push) Successful in 2m5s
2025-12-21 13:38:59 +01:00
Julien Froidefond
b3ae6059ca feat: improve MonthlyChart and transaction data formatting; dynamically adjust X-axis intervals and enhance month label presentation for better readability 2025-12-21 13:35:49 +01:00
Julien Froidefond
6f78dca1f0 feat: refine card styles and interactions across the dashboard; adjust glassmorphism effects, enhance texture for statistic cards, and improve layout for account filter component 2025-12-21 13:33:23 +01:00
Julien Froidefond
c4707e5511 feat: update fintech card styles with modern design enhancements; add subtle texture effects and adjust gradient backgrounds for improved visual appeal in overview and statistics cards
All checks were successful
Deploy with Docker Compose / deploy (push) Successful in 1m52s
2025-12-21 13:29:43 +01:00
Julien Froidefond
2887a6a750 feat: enhance Sidebar and TransactionTable components with improved accessibility and layout adjustments; add SheetTitle for navigation context and refine padding and width for better responsiveness 2025-12-21 13:25:27 +01:00
Julien Froidefond
82e27524b5 feat: enhance TransactionsPage with total count and amount display; update CategoryCard and ParentCategoryRow to link to transaction filters by category; implement localStorage for transaction period preference
All checks were successful
Deploy with Docker Compose / deploy (push) Successful in 1m57s
2025-12-21 08:33:19 +01:00
Julien Froidefond
8b62cd8385 feat: add account and category filter functionality to TransactionsPage; implement hooks for filtering transactions based on selected accounts and categories 2025-12-21 08:29:10 +01:00
Julien Froidefond
a01345c1fb feat: implement category breakdown by parent in dashboard; enhance chart data handling to include totals for parent categories 2025-12-21 08:26:01 +01:00
Julien Froidefond
c358845033 feat: implement localStorage persistence for user preferences in categories, statistics, transactions, and sidebar components; enhance UI with collapsible elements and improved layout 2025-12-21 08:24:04 +01:00
Julien Froidefond
b3e99a15d2 refactor: optimize TransactionsPage component by removing fullscreen functionality and stabilizing transactions reference with useMemo; clean up unused imports 2025-12-21 08:17:33 +01:00
Julien Froidefond
dbcf8e7abd refactor: update grid layout for transactions and overview cards; adjust chart dimensions and axis properties for improved responsiveness
All checks were successful
Deploy with Docker Compose / deploy (push) Successful in 1m56s
2025-12-21 07:42:09 +01:00
Julien Froidefond
55f0e5c625 feat: enhance category filter functionality to include child categories in selection and deselection; update transaction page to expand selected categories based on parent-child relationships 2025-12-21 07:38:57 +01:00
Julien Froidefond
b4dace0673 feat: enhance transactions page with total amount and count display; integrate collapsible statistics card and update chart data handling 2025-12-21 07:35:35 +01:00
Julien Froidefond
aa2c656c00 feat: integrate monthly chart with collapsible feature in transactions page; update transaction period to default to last 3 months 2025-12-21 07:31:29 +01:00
79 changed files with 8201 additions and 3251 deletions

View File

@@ -134,7 +134,11 @@ export default function AccountsPage() {
// Convert accountsWithStats to regular accounts for compatibility
const accounts = accountsWithStats.map(
({ transactionCount: _transactionCount, calculatedBalance: _calculatedBalance, ...account }) => account,
({
transactionCount: _transactionCount,
calculatedBalance: _calculatedBalance,
...account
}) => account,
);
const formatCurrency = (amount: number) => {
@@ -165,10 +169,11 @@ export default function AccountsPage() {
// Calculer le balance à partir du solde total et du solde initial
// balance = totalBalance - initialBalance
const balance = formData.totalBalance - formData.initialBalance;
// Convertir "folder-root" en null
const folderId = formData.folderId === "folder-root" ? null : formData.folderId;
const folderId =
formData.folderId === "folder-root" ? null : formData.folderId;
const updatedAccount = {
...editingAccount,
name: formData.name,
@@ -325,10 +330,10 @@ export default function AccountsPage() {
const result = await response.json();
invalidateAllAccountQueries(queryClient);
// Réinitialiser la sélection
setSelectedAccounts(new Set());
// Afficher un message de succès
alert(
`Fusion réussie ! ${result.transactionCount} transactions déplacées vers le compte de destination.`,
@@ -384,7 +389,16 @@ export default function AccountsPage() {
// Update cache directly
queryClient.setQueryData(
["accounts-with-stats"],
(old: Array<Account & { transactionCount: number; calculatedBalance: number }> | undefined) => {
(
old:
| Array<
Account & {
transactionCount: number;
calculatedBalance: number;
}
>
| undefined,
) => {
if (!old) return old;
return old.map((a) => (a.id === accountId ? updatedAccount : a));
},
@@ -564,25 +578,27 @@ export default function AccountsPage() {
(f: FolderType) => f.id === account.folderId,
);
const accountWithStats = accountsWithStats.find(
(a) => a.id === account.id,
);
return (
<AccountCard
key={account.id}
account={account}
folder={folder}
transactionCount={getTransactionCount(account.id)}
calculatedBalance={accountWithStats?.calculatedBalance}
onEdit={handleEdit}
onDelete={handleDelete}
formatCurrency={formatCurrency}
isSelected={selectedAccounts.has(account.id)}
onSelect={toggleSelectAccount}
draggableId={`account-${account.id}`}
compact={isCompactView}
/>
);
const accountWithStats = accountsWithStats.find(
(a) => a.id === account.id,
);
return (
<AccountCard
key={account.id}
account={account}
folder={folder}
transactionCount={getTransactionCount(account.id)}
calculatedBalance={
accountWithStats?.calculatedBalance
}
onEdit={handleEdit}
onDelete={handleDelete}
formatCurrency={formatCurrency}
isSelected={selectedAccounts.has(account.id)}
onSelect={toggleSelectAccount}
draggableId={`account-${account.id}`}
compact={isCompactView}
/>
);
})}
</div>
</FolderDropZone>
@@ -694,7 +710,9 @@ export default function AccountsPage() {
account={account}
folder={accountFolder}
transactionCount={getTransactionCount(account.id)}
calculatedBalance={accountWithStats?.calculatedBalance}
calculatedBalance={
accountWithStats?.calculatedBalance
}
onEdit={handleEdit}
onDelete={handleDelete}
formatCurrency={formatCurrency}

View File

@@ -126,4 +126,3 @@ export async function POST(request: NextRequest) {
);
}
}

View File

@@ -66,4 +66,3 @@ export async function POST(request: NextRequest) {
return NextResponse.json({ error: errorMessage }, { status: 500 });
}
}

View File

@@ -11,6 +11,7 @@ import {
import { useBankingMetadata, useCategoryStats } from "@/lib/hooks";
import { useQueryClient } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import {
Dialog,
DialogContent,
@@ -29,6 +30,7 @@ import {
} from "@/lib/store-db";
import type { Category, Transaction } from "@/lib/types";
import { invalidateAllCategoryQueries } from "@/lib/cache-utils";
import { useLocalStorage } from "@/hooks/use-local-storage";
interface RecategorizationResult {
transaction: Transaction;
@@ -58,6 +60,12 @@ export default function CategoriesPage() {
const [isRecatDialogOpen, setIsRecatDialogOpen] = useState(false);
const [isRecategorizing, setIsRecategorizing] = useState(false);
// Persister l'état "tout déplier" dans le localStorage
const [expandAllByDefault, setExpandAllByDefault] = useLocalStorage(
"categories-expand-all-by-default",
true,
);
// Organiser les catégories par parent
const { parentCategories, childrenByParent, orphanCategories } =
useMemo(() => {
@@ -97,13 +105,19 @@ export default function CategoriesPage() {
};
}, [metadata?.categories]);
// Initialiser tous les parents comme ouverts
// Initialiser tous les parents selon la préférence sauvegardée
useEffect(() => {
if (parentCategories.length > 0 && expandedParents.size === 0) {
setExpandedParents(new Set(parentCategories.map((p: Category) => p.id)));
if (expandAllByDefault) {
setExpandedParents(
new Set(parentCategories.map((p: Category) => p.id)),
);
} else {
setExpandedParents(new Set());
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [parentCategories.length]);
}, [parentCategories.length, expandAllByDefault]);
const refresh = useCallback(() => {
invalidateAllCategoryQueries(queryClient);
@@ -162,10 +176,12 @@ export default function CategoriesPage() {
const expandAll = () => {
setExpandedParents(new Set(parentCategories.map((p: Category) => p.id)));
setExpandAllByDefault(true);
};
const collapseAll = () => {
setExpandedParents(new Set());
setExpandAllByDefault(false);
};
const allExpanded =
@@ -338,7 +354,7 @@ export default function CategoriesPage() {
onToggleAll={allExpanded ? collapseAll : expandAll}
/>
<div className="space-y-1">
<div className="space-y-3 md:space-y-4">
{filteredParentCategories.map((parent: Category) => {
const allChildren = childrenByParent[parent.id] || [];
const children = searchQuery.trim()
@@ -374,8 +390,8 @@ export default function CategoriesPage() {
})}
{orphanCategories.length > 0 && (
<div className="border rounded-lg bg-card">
<div className="px-3 py-2 border-b">
<Card className="card-hover">
<div className="px-3 py-2 border-b border-border">
<span className="text-sm font-medium text-muted-foreground">
Catégories non classées ({orphanCategories.length})
</span>
@@ -392,7 +408,7 @@ export default function CategoriesPage() {
/>
))}
</div>
</div>
</Card>
)}
</div>

File diff suppressed because it is too large Load Diff

View File

@@ -4,6 +4,8 @@ import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
import { AuthSessionProvider } from "@/components/providers/session-provider";
import { QueryProvider } from "@/components/providers/query-provider";
import { BackgroundProvider } from "@/components/providers/background-provider";
import { ThemeProvider } from "@/components/theme-provider";
const _geist = Geist({ subsets: ["latin"] });
const _geistMono = Geist_Mono({ subsets: ["latin"] });
@@ -21,11 +23,19 @@ export default function RootLayout({
children: React.ReactNode;
}>) {
return (
<html lang="fr">
<html lang="fr" suppressHydrationWarning>
<body className="font-sans antialiased">
<QueryProvider>
<AuthSessionProvider>{children}</AuthSessionProvider>
</QueryProvider>
<ThemeProvider
attribute="class"
defaultTheme="light"
enableSystem={false}
disableTransitionOnChange
>
<BackgroundProvider />
<QueryProvider>
<AuthSessionProvider>{children}</AuthSessionProvider>
</QueryProvider>
</ThemeProvider>
</body>
</html>
);

View File

@@ -48,7 +48,7 @@ export default function LoginPage() {
return (
<div className="min-h-screen flex items-center justify-center bg-[var(--background)] p-4 page-background">
<Card className="w-full max-w-md page-content">
<Card className="w-full max-w-md page-content card-hover">
<CardHeader className="space-y-1">
<div className="flex items-center justify-center mb-4">
<Lock className="w-12 h-12 text-[var(--primary)]" />

View File

@@ -8,7 +8,6 @@ import { AccountsSummary } from "@/components/dashboard/accounts-summary";
import { CategoryBreakdown } from "@/components/dashboard/category-breakdown";
import { OFXImportDialog } from "@/components/import/ofx-import-dialog";
import { AccountFilterCombobox } from "@/components/ui/account-filter-combobox";
import { Card, CardContent } from "@/components/ui/card";
import { useBankingData } from "@/lib/hooks";
import { Button } from "@/components/ui/button";
import { Upload } from "lucide-react";
@@ -60,18 +59,16 @@ export default function DashboardPage() {
}
/>
<Card className="mb-6 card-hover">
<CardContent className="px-5 py-5 sm:px-6 sm:py-6">
<AccountFilterCombobox
accounts={data.accounts}
folders={data.folders}
value={selectedAccounts}
onChange={setSelectedAccounts}
className="w-full md:w-[320px]"
filteredTransactions={data.transactions}
/>
</CardContent>
</Card>
<div className="mb-6">
<AccountFilterCombobox
accounts={data.accounts}
folders={data.folders}
value={selectedAccounts}
onChange={setSelectedAccounts}
className="w-full md:w-[320px]"
filteredTransactions={data.transactions}
/>
</div>
<OverviewCards data={filteredData} />

View File

@@ -36,20 +36,17 @@ export default function RulesPage() {
const { data: metadata, isLoading: isLoadingMetadata } = useBankingMetadata();
// Fetch uncategorized transactions only
const {
data: transactionsData,
isLoading: isLoadingTransactions,
invalidate: invalidateTransactions,
} = useTransactions(
{
limit: 10000, // Large limit to get all uncategorized
offset: 0,
includeUncategorized: true,
},
!!metadata,
);
const { data: transactionsData, isLoading: isLoadingTransactions } =
useTransactions(
{
limit: 10000, // Large limit to get all uncategorized
offset: 0,
includeUncategorized: true,
},
!!metadata,
);
const refresh = useCallback(() => {
const _refresh = useCallback(() => {
invalidateAllTransactionQueries(queryClient);
invalidateAllCategoryQueries(queryClient);
}, [queryClient]);

View File

@@ -9,6 +9,8 @@ import {
BackupCard,
PasswordCard,
ReconcileDateRangeCard,
BackgroundCard,
ThemeCard,
} from "@/components/settings";
import { useBankingData } from "@/lib/hooks";
import type { BankingData } from "@/lib/types";
@@ -126,6 +128,10 @@ export default function SettingsPage() {
<PasswordCard />
<ThemeCard />
<BackgroundCard />
<ReconcileDateRangeCard />
<DangerZoneCard

View File

@@ -1,6 +1,6 @@
"use client";
import { useState, useMemo } from "react";
import { useState, useMemo, useEffect } from "react";
import { PageLayout, LoadingState, PageHeader } from "@/components/layout";
import {
StatsSummaryCards,
@@ -46,6 +46,7 @@ import { Button } from "@/components/ui/button";
import { format } from "date-fns";
import { fr } from "date-fns/locale";
import { useIsMobile } from "@/hooks/use-mobile";
import { useLocalStorage } from "@/hooks/use-local-storage";
import type { Account, Category } from "@/lib/types";
type Period = "1month" | "3months" | "6months" | "12months" | "custom" | "all";
@@ -54,21 +55,65 @@ export default function StatisticsPage() {
const { data, isLoading } = useBankingData();
const isMobile = useIsMobile();
const [sheetOpen, setSheetOpen] = useState(false);
const [period, setPeriod] = useState<Period>("6months");
const [selectedAccounts, setSelectedAccounts] = useState<string[]>(["all"]);
const [selectedCategories, setSelectedCategories] = useState<string[]>([
"all",
]);
// Persister les filtres dans le localStorage
const [period, setPeriod] = useLocalStorage<Period>(
"statistics-period",
"6months"
);
const [selectedAccounts, setSelectedAccounts] = useLocalStorage<string[]>(
"statistics-selected-accounts",
["all"]
);
const [selectedCategories, setSelectedCategories] = useLocalStorage<string[]>(
"statistics-selected-categories",
["all"]
);
const [excludeInternalTransfers, setExcludeInternalTransfers] =
useState(true);
const [customStartDate, setCustomStartDate] = useState<Date | undefined>(
undefined,
useLocalStorage("statistics-exclude-internal-transfers", true);
// Pour les dates, on stocke les ISO strings et on les convertit
const [customStartDateISO, setCustomStartDateISO] = useLocalStorage<
string | null
>("statistics-custom-start-date", null);
const [customEndDateISO, setCustomEndDateISO] = useLocalStorage<
string | null
>("statistics-custom-end-date", null);
// Convertir les ISO strings en Date
const customStartDate = useMemo(
() => (customStartDateISO ? new Date(customStartDateISO) : undefined),
[customStartDateISO]
);
const [customEndDate, setCustomEndDate] = useState<Date | undefined>(
undefined,
const customEndDate = useMemo(
() => (customEndDateISO ? new Date(customEndDateISO) : undefined),
[customEndDateISO]
);
// Fonctions pour mettre à jour les dates avec persistance
const setCustomStartDate = (date: Date | undefined) => {
setCustomStartDateISO(date ? date.toISOString() : null);
};
const setCustomEndDate = (date: Date | undefined) => {
setCustomEndDateISO(date ? date.toISOString() : null);
};
const [isCustomDatePickerOpen, setIsCustomDatePickerOpen] = useState(false);
// Nettoyer les dates personnalisées quand on change de période (sauf si on passe à "custom")
useEffect(() => {
if (period !== "custom" && (customStartDateISO || customEndDateISO)) {
setCustomStartDateISO(null);
setCustomEndDateISO(null);
}
}, [
period,
customStartDateISO,
customEndDateISO,
setCustomStartDateISO,
setCustomEndDateISO,
]);
// Get start date based on period
const startDate = useMemo(() => {
const now = new Date();
@@ -100,7 +145,7 @@ export default function StatisticsPage() {
const internalTransferCategory = useMemo(() => {
if (!data) return null;
return data.categories.find(
(c) => c.name.toLowerCase() === "virement interne",
(c) => c.name.toLowerCase() === "virement interne"
);
}, [data]);
@@ -216,7 +261,7 @@ export default function StatisticsPage() {
// Filter by accounts
if (!selectedAccounts.includes("all")) {
transactions = transactions.filter((t) =>
selectedAccounts.includes(t.accountId),
selectedAccounts.includes(t.accountId)
);
}
@@ -226,7 +271,7 @@ export default function StatisticsPage() {
transactions = transactions.filter((t) => !t.categoryId);
} else {
transactions = transactions.filter(
(t) => t.categoryId && selectedCategories.includes(t.categoryId),
(t) => t.categoryId && selectedCategories.includes(t.categoryId)
);
}
}
@@ -234,7 +279,7 @@ export default function StatisticsPage() {
// Exclude "Virement interne" category if checkbox is checked
if (excludeInternalTransfers && internalTransferCategory) {
transactions = transactions.filter(
(t) => t.categoryId !== internalTransferCategory.id,
(t) => t.categoryId !== internalTransferCategory.id
);
}
@@ -307,7 +352,7 @@ export default function StatisticsPage() {
});
const categoryChartDataByParent = Array.from(
categoryTotalsByParent.entries(),
categoryTotalsByParent.entries()
)
.map(([groupId, total]) => {
const category = data.categories.find((c) => c.id === groupId);
@@ -321,22 +366,53 @@ export default function StatisticsPage() {
})
.sort((a, b) => b.value - a.value);
// Top expenses - deduplicate by ID and sort by amount (most negative first)
// Top expenses by top parent categories - deduplicate by ID
const uniqueTransactions = Array.from(
new Map(transactions.map((t) => [t.id, t])).values(),
new Map(transactions.map((t) => [t.id, t])).values()
);
const topExpenses = uniqueTransactions
.filter((t) => t.amount < 0)
.sort((a, b) => {
// Sort by amount (most negative first)
if (a.amount !== b.amount) {
return a.amount - b.amount;
}
// If same amount, sort by date (most recent first) for stable sorting
return new Date(b.date).getTime() - new Date(a.date).getTime();
})
const expenses = uniqueTransactions.filter((t) => t.amount < 0);
// Get top 5 parent categories by total expenses
const topParentCategories = Array.from(categoryTotalsByParent.entries())
.map(([groupId, total]) => ({
groupId: groupId === "uncategorized" ? null : groupId,
total,
}))
.sort((a, b) => b.total - a.total)
.slice(0, 5);
// Get top 10 expenses per top parent category (from all its subcategories)
const topExpensesByCategory = topParentCategories.map(({ groupId }) => {
const categoryExpenses = expenses
.filter((t) => {
if (groupId === null) {
return !t.categoryId;
}
// Check if transaction belongs to this parent category or its subcategories
const category = data.categories.find((c) => c.id === t.categoryId);
if (!category) {
return false;
}
// Use parent category ID if exists, otherwise use the category itself
const transactionGroupId = category.parentId || category.id;
return transactionGroupId === groupId;
})
.sort((a, b) => {
// Sort by amount (most negative first)
if (a.amount !== b.amount) {
return a.amount - b.amount;
}
// If same amount, sort by date (most recent first) for stable sorting
return new Date(b.date).getTime() - new Date(a.date).getTime();
})
.slice(0, 10);
return {
categoryId: groupId,
expenses: categoryExpenses,
};
});
// Summary
const totalIncome = transactions
.filter((t) => t.amount >= 0)
@@ -349,7 +425,7 @@ export default function StatisticsPage() {
// Balance evolution - Aggregated (using filtered transactions)
const sortedFilteredTransactions = [...transactions].sort(
(a, b) => new Date(a.date).getTime() - new Date(b.date).getTime(),
(a, b) => new Date(a.date).getTime() - new Date(b.date).getTime()
);
// Calculate starting balance: initialBalance + transactions before startDate
@@ -361,7 +437,7 @@ export default function StatisticsPage() {
// Start with initial balances
runningBalance = accountsToUse.reduce(
(sum, acc) => sum + (acc.initialBalance || 0),
0,
0
);
// Add all transactions before the start date for these accounts
@@ -398,7 +474,7 @@ export default function StatisticsPage() {
});
const aggregatedBalanceData = Array.from(
aggregatedBalanceByDate.entries(),
aggregatedBalanceByDate.entries()
).map(([date, balance]) => ({
date: new Date(date).toLocaleDateString("fr-FR", {
day: "2-digit",
@@ -614,13 +690,14 @@ export default function StatisticsPage() {
monthlyChartData,
categoryChartData,
categoryChartDataByParent,
topExpenses,
topExpensesByCategory,
totalIncome,
totalExpenses,
avgMonthlyExpenses,
aggregatedBalanceData,
perAccountBalanceData,
transactionCount: transactions.length,
transactions, // Toutes les transactions filtrées pour le graphique
savingsTrendData,
categoryTrendData,
categoryTrendDataByParent,
@@ -855,7 +932,7 @@ export default function StatisticsPage() {
onRemoveAccount={(id) => {
const newAccounts = selectedAccounts.filter((a) => a !== id);
setSelectedAccounts(
newAccounts.length > 0 ? newAccounts : ["all"],
newAccounts.length > 0 ? newAccounts : ["all"]
);
}}
onClearAccounts={() => setSelectedAccounts(["all"])}
@@ -863,7 +940,7 @@ export default function StatisticsPage() {
onRemoveCategory={(id) => {
const newCategories = selectedCategories.filter((c) => c !== id);
setSelectedCategories(
newCategories.length > 0 ? newCategories : ["all"],
newCategories.length > 0 ? newCategories : ["all"]
);
}}
onClearCategories={() => setSelectedCategories(["all"])}
@@ -961,7 +1038,11 @@ export default function StatisticsPage() {
selected={customStartDate}
onSelect={(date) => {
setCustomStartDate(date);
if (date && customEndDate && date > customEndDate) {
if (
date &&
customEndDate &&
date > customEndDate
) {
setCustomEndDate(undefined);
}
}}
@@ -1001,26 +1082,26 @@ export default function StatisticsPage() {
</div>
{customStartDate && customEndDate && (
<div className="flex gap-2 pt-2 border-t px-3 pb-3">
<Button
variant="outline"
size="sm"
className="flex-1"
onClick={() => {
setCustomStartDate(undefined);
setCustomEndDate(undefined);
}}
>
Réinitialiser
</Button>
<Button
size="sm"
className="flex-1"
onClick={() => setIsCustomDatePickerOpen(false)}
>
Valider
</Button>
</div>
)}
<Button
variant="outline"
size="sm"
className="flex-1"
onClick={() => {
setCustomStartDate(undefined);
setCustomEndDate(undefined);
}}
>
Réinitialiser
</Button>
<Button
size="sm"
className="flex-1"
onClick={() => setIsCustomDatePickerOpen(false)}
>
Valider
</Button>
</div>
)}
</PopoverContent>
</Popover>
)}
@@ -1049,17 +1130,17 @@ export default function StatisticsPage() {
onRemoveAccount={(id) => {
const newAccounts = selectedAccounts.filter((a) => a !== id);
setSelectedAccounts(
newAccounts.length > 0 ? newAccounts : ["all"],
newAccounts.length > 0 ? newAccounts : ["all"]
);
}}
onClearAccounts={() => setSelectedAccounts(["all"])}
selectedCategories={selectedCategories}
onRemoveCategory={(id) => {
const newCategories = selectedCategories.filter(
(c) => c !== id,
(c) => c !== id
);
setSelectedCategories(
newCategories.length > 0 ? newCategories : ["all"],
newCategories.length > 0 ? newCategories : ["all"]
);
}}
onClearCategories={() => setSelectedCategories(["all"])}
@@ -1161,9 +1242,10 @@ export default function StatisticsPage() {
</div>
<div className="mt-4 md:mt-6">
<TopExpensesList
expenses={stats.topExpenses}
expensesByCategory={stats.topExpensesByCategory}
categories={data.categories}
formatCurrency={formatCurrency}
allTransactions={stats.transactions}
/>
</div>
</section>
@@ -1209,7 +1291,7 @@ function ActiveFilters({
const selectedAccs = accounts.filter((a) => selectedAccounts.includes(a.id));
const selectedCats = categories.filter((c) =>
selectedCategories.includes(c.id),
selectedCategories.includes(c.id)
);
const isUncategorized = selectedCategories.includes("uncategorized");

View File

@@ -1,8 +1,16 @@
"use client";
import { useCallback } from "react";
import { useCallback, useMemo } from "react";
import { PageLayout, PageHeader } from "@/components/layout";
import { RefreshCw } from "lucide-react";
import {
RefreshCw,
Receipt,
Euro,
ChevronDown,
ChevronUp,
CheckCircle2,
Tag,
} from "lucide-react";
import {
TransactionFilters,
TransactionBulkActions,
@@ -13,12 +21,23 @@ import {
} from "@/components/transactions";
import { RuleCreateDialog } from "@/components/rules";
import { OFXImportDialog } from "@/components/import/ofx-import-dialog";
import { MonthlyChart } from "@/components/statistics";
import { useQueryClient } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible";
import { Upload } from "lucide-react";
import { useTransactionsPage } from "@/hooks/use-transactions-page";
import { useTransactionMutations } from "@/hooks/use-transaction-mutations";
import { useTransactionRules } from "@/hooks/use-transaction-rules";
import { useTransactionsChartData } from "@/hooks/use-transactions-chart-data";
import { useTransactionsForAccountFilter } from "@/hooks/use-transactions-for-account-filter";
import { useTransactionsForCategoryFilter } from "@/hooks/use-transactions-for-category-filter";
import { useLocalStorage } from "@/hooks/use-local-storage";
export default function TransactionsPage() {
const queryClient = useQueryClient();
@@ -88,6 +107,45 @@ export default function TransactionsPage() {
metadata,
});
// Chart data
const {
monthlyData,
isLoading: isLoadingChart,
totalAmount: chartTotalAmount,
totalCount: chartTotalCount,
transactions: chartTransactions,
} = useTransactionsChartData({
selectedAccounts,
selectedCategories,
period,
customStartDate,
customEndDate,
showReconciled,
searchQuery,
});
// Transactions for account filter (filtered by categories, period, search, reconciled - NOT by accounts)
const { transactions: transactionsForAccountFilter } =
useTransactionsForAccountFilter({
selectedCategories,
period,
customStartDate,
customEndDate,
showReconciled,
searchQuery,
});
// Transactions for category filter (filtered by accounts, period, search, reconciled - NOT by categories)
const { transactions: transactionsForCategoryFilter } =
useTransactionsForCategoryFilter({
selectedAccounts,
period,
customStartDate,
customEndDate,
showReconciled,
searchQuery,
});
const invalidateAll = useCallback(() => {
invalidateTransactions();
queryClient.invalidateQueries({ queryKey: ["banking-metadata"] });
@@ -109,7 +167,11 @@ export default function TransactionsPage() {
[handleBulkSetCategory, selectedTransactions, clearSelection],
);
const filteredTransactions = transactionsData?.transactions || [];
// Stabilize transactions reference to prevent unnecessary re-renders
const filteredTransactions = useMemo(
() => transactionsData?.transactions || [],
[transactionsData?.transactions],
);
const totalTransactions = transactionsData?.total || 0;
const hasMore = transactionsData?.hasMore || false;
const uncategorizedCount = transactionsData?.uncategorizedCount || 0;
@@ -118,10 +180,32 @@ export default function TransactionsPage() {
? Math.round((uncategorizedCount / totalTransactions) * 100)
: 0;
// For filter comboboxes, we'll use empty arrays for now
// They can be enhanced later with separate queries if needed
const transactionsForAccountFilter: never[] = [];
const transactionsForCategoryFilter: never[] = [];
// Use total from chart data (all filtered transactions) or fallback to paginated data
const totalAmount = chartTotalAmount ?? 0;
const displayTotalCount = chartTotalCount ?? totalTransactions;
// Calculate percentages from chart transactions (all filtered transactions)
const reconciledPercent = useMemo(() => {
if (chartTransactions.length === 0) return "0.00";
const reconciledCount = chartTransactions.filter(
(t) => t.isReconciled,
).length;
return ((reconciledCount / chartTransactions.length) * 100).toFixed(2);
}, [chartTransactions]);
const categorizedPercent = useMemo(() => {
if (chartTransactions.length === 0) return "0.00";
const categorizedCount = chartTransactions.filter(
(t) => t.categoryId !== null,
).length;
return ((categorizedCount / chartTransactions.length) * 100).toFixed(2);
}, [chartTransactions]);
// Persist statistics collapsed state in localStorage
const [isStatsExpanded, setIsStatsExpanded] = useLocalStorage(
"transactions-stats-expanded",
true,
);
// Early return for loading state - prevents sidebar flash
if (isLoadingMetadata || !metadata) {
@@ -179,6 +263,143 @@ export default function TransactionsPage() {
transactionsForCategoryFilter={transactionsForCategoryFilter}
/>
{(!isLoadingChart || !isLoadingTransactions) && (
<Card className="mb-6 card-hover">
<Collapsible open={isStatsExpanded} onOpenChange={setIsStatsExpanded}>
<CardHeader className="flex flex-row items-center justify-between space-y-0 py-3 px-6">
<CardTitle className="text-base font-semibold">
Statistiques
{!isStatsExpanded && (
<span className="ml-3 text-sm font-normal text-muted-foreground">
{displayTotalCount} opération
{displayTotalCount > 1 ? "s" : ""} {" "}
{formatCurrency(totalAmount)}
</span>
)}
</CardTitle>
<CollapsibleTrigger asChild>
<Button variant="ghost" size="sm" className="h-8">
{isStatsExpanded ? (
<>
<ChevronUp className="w-4 h-4 mr-1" />
Réduire
</>
) : (
<>
<ChevronDown className="w-4 h-4 mr-1" />
Afficher
</>
)}
</Button>
</CollapsibleTrigger>
</CardHeader>
<CollapsibleContent>
<CardContent className="pt-0">
{/* Summary cards */}
{!isLoadingTransactions && (
<div className="grid gap-4 grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 mb-6">
<Card className="card-hover">
<CardContent className="pt-6">
<div className="flex items-center justify-between">
<div>
<p className="text-sm font-medium text-muted-foreground">
Nombre de transactions
</p>
<p className="text-2xl font-bold mt-1">
{displayTotalCount}
</p>
</div>
<Receipt
className="w-8 h-8"
style={{ color: "var(--gray)" }}
/>
</div>
</CardContent>
</Card>
<Card className="card-hover">
<CardContent className="pt-6">
<div className="flex items-center justify-between">
<div>
<p className="text-sm font-medium text-muted-foreground">
Total
</p>
<p
className={`text-2xl font-bold mt-1 ${
totalAmount >= 0
? "text-emerald-600"
: "text-red-600"
}`}
>
{formatCurrency(totalAmount)}
</p>
</div>
<Euro
className={`w-8 h-8 ${
totalAmount >= 0
? "text-emerald-600"
: "text-red-600"
}`}
/>
</div>
</CardContent>
</Card>
<Card className="card-hover">
<CardContent className="pt-6">
<div className="flex items-center justify-between">
<div>
<p className="text-sm font-medium text-muted-foreground">
Pointé
</p>
<p className="text-2xl font-bold mt-1 text-primary">
{reconciledPercent}%
</p>
</div>
<CheckCircle2 className="w-8 h-8 text-primary" />
</div>
</CardContent>
</Card>
<Card className="card-hover">
<CardContent className="pt-6">
<div className="flex items-center justify-between">
<div>
<p className="text-sm font-medium text-muted-foreground">
Catégorisé
</p>
<p
className="text-2xl font-bold mt-1"
style={{ color: "var(--blue)" }}
>
{categorizedPercent}%
</p>
</div>
<Tag
className="w-8 h-8"
style={{ color: "var(--blue)" }}
/>
</div>
</CardContent>
</Card>
</div>
)}
{/* Chart */}
{!isLoadingChart && monthlyData.length > 0 && (
<MonthlyChart
data={monthlyData}
formatCurrency={formatCurrency}
collapsible={false}
showDots={
period !== "all" &&
(period === "12months" || monthlyData.length <= 12)
}
/>
)}
</CardContent>
</CollapsibleContent>
</Collapsible>
</Card>
)}
<TransactionBulkActions
selectedCount={selectedTransactions.size}
categories={metadata.categories}

View File

@@ -55,7 +55,8 @@ export function AccountCard({
const isMobile = useIsMobile();
const Icon = accountTypeIcons[account.type];
const realBalance = getAccountBalance(account);
const hasBalanceDifference = calculatedBalance !== undefined &&
const hasBalanceDifference =
calculatedBalance !== undefined &&
Math.abs(account.balance - calculatedBalance) > 0.01;
const {
@@ -188,7 +189,7 @@ export function AccountCard({
? "text-base"
: "text-xl",
!compact && !isMobile && "mb-1.5",
realBalance >= 0 ? "text-emerald-600" : "text-red-600",
realBalance >= 0 ? "text-success" : "text-destructive",
)}
>
{formatCurrency(realBalance)}
@@ -200,7 +201,8 @@ export function AccountCard({
</span>
{hasBalanceDifference && (
<span className="text-xs text-destructive font-semibold">
(diff: {formatCurrency(account.balance - calculatedBalance)})
(diff: {formatCurrency(account.balance - calculatedBalance)}
)
</span>
)}
</div>

View File

@@ -137,7 +137,8 @@ export function AccountEditDialog({
placeholder="0.00"
/>
<p className="text-xs text-muted-foreground">
Solde de départ pour équilibrer le compte. Le balance sera calculé automatiquement (solde total - solde initial).
Solde de départ pour équilibrer le compte. Le balance sera calculé
automatiquement (solde total - solde initial).
</p>
</div>
<div className="space-y-2">

View File

@@ -54,7 +54,11 @@ export function AccountMergeSelectDialog({
}
const handleMerge = async () => {
if (!sourceAccountId || !targetAccountId || sourceAccountId === targetAccountId) {
if (
!sourceAccountId ||
!targetAccountId ||
sourceAccountId === targetAccountId
) {
return;
}
@@ -105,13 +109,20 @@ export function AccountMergeSelectDialog({
<div className="space-y-3">
<Label>Compte à conserver (destination)</Label>
<RadioGroup value={targetAccountId} onValueChange={setTargetAccountId}>
<RadioGroup
value={targetAccountId}
onValueChange={setTargetAccountId}
>
{selectedAccounts.map((account) => (
<div
key={account.id}
className="flex items-start space-x-3 rounded-lg border p-3 hover:bg-accent"
>
<RadioGroupItem value={account.id} id={account.id} className="mt-1" />
<RadioGroupItem
value={account.id}
id={account.id}
className="mt-1"
/>
<Label
htmlFor={account.id}
className="flex-1 cursor-pointer space-y-1"
@@ -120,7 +131,9 @@ export function AccountMergeSelectDialog({
<div className="text-xs text-muted-foreground space-y-0.5">
<div>Numéro: {account.accountNumber}</div>
<div>Bank ID: {account.bankId}</div>
<div>Solde: {formatCurrency(getAccountBalance(account))}</div>
<div>
Solde: {formatCurrency(getAccountBalance(account))}
</div>
</div>
</Label>
</div>
@@ -133,9 +146,9 @@ export function AccountMergeSelectDialog({
<AlertTriangle className="h-4 w-4" />
<AlertDescription>
<strong>Attention :</strong> Toutes les transactions du compte "
{sourceAccount.name}" seront déplacées vers "{targetAccount.name}". Le
compte "{sourceAccount.name}" sera supprimé après la fusion. Cette
action est irréversible.
{sourceAccount.name}" seront déplacées vers "
{targetAccount.name}". Le compte "{sourceAccount.name}" sera
supprimé après la fusion. Cette action est irréversible.
</AlertDescription>
</Alert>
)}
@@ -153,4 +166,3 @@ export function AccountMergeSelectDialog({
</Dialog>
);
}

View File

@@ -1,5 +1,6 @@
"use client";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { CategoryIcon } from "@/components/ui/category-icon";
@@ -37,7 +38,13 @@ export function CategoryCard({
size={isMobile ? 10 : 12}
/>
</div>
<span className="text-xs md:text-sm truncate">{category.name}</span>
<Link
href={`/transactions?categoryIds=${category.id}`}
className="text-xs md:text-sm truncate hover:underline"
onClick={(e) => e.stopPropagation()}
>
{category.name}
</Link>
{!isMobile && (
<span className="text-xs md:text-sm text-muted-foreground shrink-0">
{stats.count} opération{stats.count > 1 ? "s" : ""} {" "}

View File

@@ -1,5 +1,6 @@
"use client";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
@@ -12,6 +13,7 @@ import {
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible";
import { Card } from "@/components/ui/card";
import { CategoryIcon } from "@/components/ui/category-icon";
import {
Plus,
@@ -53,7 +55,7 @@ export function ParentCategoryRow({
const isMobile = useIsMobile();
return (
<div className="border rounded-lg bg-card">
<Card className="card-hover">
<Collapsible open={isExpanded} onOpenChange={onToggleExpanded}>
<div className="flex items-center justify-between px-2 md:px-3 py-1.5 md:py-2">
<CollapsibleTrigger asChild>
@@ -73,9 +75,13 @@ export function ParentCategoryRow({
size={isMobile ? 10 : 14}
/>
</div>
<span className="font-medium text-xs md:text-sm truncate">
<Link
href={`/transactions?categoryIds=${parent.id}`}
className="font-medium text-xs md:text-sm truncate hover:underline"
onClick={(e) => e.stopPropagation()}
>
{parent.name}
</span>
</Link>
{!isMobile && (
<span className="text-xs md:text-sm text-muted-foreground shrink-0">
{children.length} {stats.count} opération
@@ -119,7 +125,7 @@ export function ParentCategoryRow({
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => onDelete(parent.id)}
className="text-red-600"
className="text-destructive"
>
<Trash2 className="w-4 h-4 mr-2" />
Supprimer
@@ -150,6 +156,6 @@ export function ParentCategoryRow({
)}
</CollapsibleContent>
</Collapsible>
</div>
</Card>
);
}

View File

@@ -89,7 +89,7 @@ export function AccountsSummary({ data }: AccountsSummaryProps) {
<span
className={cn(
"text-xs font-semibold tabular-nums ml-auto",
folderTotal >= 0 ? "text-emerald-600" : "text-red-600",
folderTotal >= 0 ? "text-success" : "text-destructive",
)}
>
{formatCurrency(folderTotal)}
@@ -130,9 +130,7 @@ export function AccountsSummary({ data }: AccountsSummaryProps) {
<span
className={cn(
"font-bold tabular-nums text-base",
realBalance >= 0
? "text-emerald-600 dark:text-emerald-400"
: "text-red-600 dark:text-red-400",
realBalance >= 0 ? "text-success" : "text-destructive",
)}
>
{formatCurrency(realBalance)}
@@ -204,7 +202,7 @@ export function AccountsSummary({ data }: AccountsSummaryProps) {
<span
className={cn(
"text-xs font-semibold tabular-nums ml-auto",
orphanTotal >= 0 ? "text-emerald-600" : "text-red-600",
orphanTotal >= 0 ? "text-success" : "text-destructive",
)}
>
{formatCurrency(orphanTotal)}
@@ -245,8 +243,8 @@ export function AccountsSummary({ data }: AccountsSummaryProps) {
className={cn(
"font-bold tabular-nums text-base",
realBalance >= 0
? "text-emerald-600 dark:text-emerald-400"
: "text-red-600 dark:text-red-400",
? "text-success"
: "text-destructive",
)}
>
{formatCurrency(realBalance)}

View File

@@ -36,10 +36,43 @@ export function CategoryBreakdown({ data }: CategoryBreakdownProps) {
value: total,
color: category?.color || "#94a3b8",
icon: category?.icon || "HelpCircle",
categoryId: categoryId === "uncategorized" ? null : categoryId,
};
})
.sort((a, b) => b.value - a.value)
.slice(0, 6);
.sort((a, b) => b.value - a.value);
// Category breakdown grouped by parent
const categoryTotalsByParent = new Map<string, number>();
monthExpenses.forEach((t) => {
const category = data.categories.find((c) => c.id === t.categoryId);
// Use parent category ID if exists, otherwise use the category itself
let groupId: string;
if (!category) {
groupId = "uncategorized";
} else if (category.parentId) {
groupId = category.parentId;
} else {
// Category is a parent itself
groupId = category.id;
}
const current = categoryTotalsByParent.get(groupId) || 0;
categoryTotalsByParent.set(groupId, current + Math.abs(t.amount));
});
const chartDataByParent: CategoryChartData[] = Array.from(
categoryTotalsByParent.entries(),
)
.map(([groupId, total]) => {
const category = data.categories.find((c) => c.id === groupId);
return {
name: category?.name || "Non catégorisé",
value: total,
color: category?.color || "#94a3b8",
icon: category?.icon || "HelpCircle",
categoryId: groupId === "uncategorized" ? null : groupId,
};
})
.sort((a, b) => b.value - a.value);
const formatCurrency = (value: number) => {
return new Intl.NumberFormat("fr-FR", {
@@ -51,6 +84,8 @@ export function CategoryBreakdown({ data }: CategoryBreakdownProps) {
return (
<CategoryPieChart
data={chartData}
dataByParent={chartDataByParent}
categories={data.categories}
formatCurrency={formatCurrency}
title="Dépenses par catégorie"
height={250}

View File

@@ -19,7 +19,7 @@ interface OverviewCardsProps {
export function OverviewCards({ data }: OverviewCardsProps) {
const totalBalance = data.accounts.reduce(
(sum, acc) => sum + getAccountBalance(acc),
0
0,
);
const thisMonth = new Date();
@@ -27,7 +27,7 @@ export function OverviewCards({ data }: OverviewCardsProps) {
const thisMonthStr = thisMonth.toISOString().slice(0, 7);
const monthTransactions = data.transactions.filter((t) =>
t.date.startsWith(thisMonthStr)
t.date.startsWith(thisMonthStr),
);
const income = monthTransactions
@@ -41,13 +41,13 @@ export function OverviewCards({ data }: OverviewCardsProps) {
const reconciled = data.transactions.filter((t) => t.isReconciled).length;
const total = data.transactions.length;
const reconciledPercent =
total > 0 ? Math.round((reconciled / total) * 100) : 0;
total > 0 ? ((reconciled / total) * 100).toFixed(2) : "0.00";
const categorized = data.transactions.filter(
(t) => t.categoryId !== null
(t) => t.categoryId !== null,
).length;
const categorizedPercent =
total > 0 ? Math.round((categorized / total) * 100) : 0;
total > 0 ? ((categorized / total) * 100).toFixed(2) : "0.00";
const formatCurrency = (amount: number) => {
return new Intl.NumberFormat("fr-FR", {
@@ -57,47 +57,53 @@ export function OverviewCards({ data }: OverviewCardsProps) {
};
return (
<div className="grid gap-4 sm:gap-6 grid-cols-2 lg:grid-cols-5">
<div className="grid gap-4 sm:gap-6 grid-cols-1 sm:grid-cols-2 lg:grid-cols-5">
<Card className="stat-card-gradient-1 card-hover group relative overflow-hidden">
<CardHeader className="flex flex-row items-start justify-between space-y-0 pb-4 px-6 pt-6 sm:px-7 sm:pt-7 lg:px-5 lg:pt-5 relative z-10">
<CardTitle className="text-xs font-bold text-muted-foreground/70 leading-tight uppercase tracking-widest">
{/* Icône en arrière-plan */}
<div className="absolute bottom-2 right-2 opacity-[0.04] z-0 pointer-events-none">
<Wallet
className="h-20 w-20 sm:h-24 sm:w-24 md:h-28 md:w-28 text-primary"
strokeWidth={1}
/>
</div>
<CardHeader className="flex flex-row items-start justify-between space-y-0 pb-3 px-5 pt-5 sm:px-6 sm:pt-6 relative z-10">
<CardTitle className="text-[10px] sm:text-xs font-semibold text-muted-foreground/80 leading-tight uppercase tracking-wider flex-1 min-w-0">
Solde Total
</CardTitle>
<div className="rounded-2xl bg-gradient-to-br from-primary/30 via-primary/20 to-primary/10 p-3 shrink-0 shadow-lg shadow-primary/20">
<Wallet className="h-5 w-5 text-primary" />
</div>
</CardHeader>
<CardContent className="px-6 pb-6 sm:px-7 sm:pb-7 lg:px-5 lg:pb-5 pt-0 relative z-10">
<CardContent className="px-5 pb-5 sm:px-6 sm:pb-6 pt-0 relative z-10">
<div
className={cn(
"text-2xl sm:text-3xl md:text-3xl lg:text-xl xl:text-xl font-black tracking-tight mb-4 leading-none break-words",
totalBalance >= 0
? "text-emerald-600 dark:text-emerald-400"
: "text-red-600 dark:text-red-400"
"text-2xl sm:text-3xl md:text-3xl lg:text-2xl xl:text-3xl font-black tracking-tight mb-3 leading-tight break-words",
totalBalance >= 0 ? "text-success" : "text-destructive",
)}
>
{formatCurrency(totalBalance)}
</div>
<p className="text-xs sm:text-sm font-semibold text-muted-foreground/60">
<p className="text-xs sm:text-sm font-medium text-muted-foreground/70">
{data.accounts.length} compte{data.accounts.length > 1 ? "s" : ""}
</p>
</CardContent>
</Card>
<Card className="stat-card-gradient-2 card-hover group relative overflow-hidden">
<CardHeader className="flex flex-row items-start justify-between space-y-0 pb-4 px-6 pt-6 sm:px-7 sm:pt-7 lg:px-5 lg:pt-5 relative z-10">
<CardTitle className="text-xs font-bold text-muted-foreground/70 leading-tight uppercase tracking-widest">
{/* Icône en arrière-plan */}
<div className="absolute bottom-2 right-2 opacity-[0.04] z-0 pointer-events-none">
<TrendingUp
className="h-20 w-20 sm:h-24 sm:w-24 md:h-28 md:w-28 text-success"
strokeWidth={1}
/>
</div>
<CardHeader className="flex flex-row items-start justify-between space-y-0 pb-3 px-5 pt-5 sm:px-6 sm:pt-6 relative z-10">
<CardTitle className="text-[10px] sm:text-xs font-semibold text-muted-foreground/80 leading-tight uppercase tracking-wider flex-1 min-w-0">
Revenus du mois
</CardTitle>
<div className="rounded-2xl bg-gradient-to-br from-success/30 via-success/20 to-success/10 p-3 shrink-0 shadow-lg shadow-success/20">
<TrendingUp className="h-5 w-5 text-success" />
</div>
</CardHeader>
<CardContent className="px-6 pb-6 sm:px-7 sm:pb-7 lg:px-5 lg:pb-5 pt-0 relative z-10">
<div className="text-2xl sm:text-3xl md:text-3xl lg:text-xl xl:text-xl font-black tracking-tight text-success mb-4 leading-none break-words">
<CardContent className="px-5 pb-5 sm:px-6 sm:pb-6 pt-0 relative z-10">
<div className="text-2xl sm:text-3xl md:text-3xl lg:text-2xl xl:text-3xl font-black tracking-tight text-success mb-3 leading-tight break-words">
{formatCurrency(income)}
</div>
<p className="text-xs sm:text-sm font-semibold text-muted-foreground/60">
<p className="text-xs sm:text-sm font-medium text-muted-foreground/70">
{monthTransactions.filter((t) => t.amount > 0).length} opération
{monthTransactions.filter((t) => t.amount > 0).length > 1
? "s"
@@ -107,19 +113,23 @@ export function OverviewCards({ data }: OverviewCardsProps) {
</Card>
<Card className="stat-card-gradient-3 card-hover group relative overflow-hidden">
<CardHeader className="flex flex-row items-start justify-between space-y-0 pb-4 px-6 pt-6 sm:px-7 sm:pt-7 lg:px-5 lg:pt-5 relative z-10">
<CardTitle className="text-xs font-bold text-muted-foreground/70 leading-tight uppercase tracking-widest">
{/* Icône en arrière-plan */}
<div className="absolute bottom-2 right-2 opacity-[0.04] z-0 pointer-events-none">
<TrendingDown
className="h-20 w-20 sm:h-24 sm:w-24 md:h-28 md:w-28 text-destructive"
strokeWidth={1}
/>
</div>
<CardHeader className="flex flex-row items-start justify-between space-y-0 pb-3 px-5 pt-5 sm:px-6 sm:pt-6 relative z-10">
<CardTitle className="text-[10px] sm:text-xs font-semibold text-muted-foreground/80 leading-tight uppercase tracking-wider flex-1 min-w-0">
Dépenses du mois
</CardTitle>
<div className="rounded-2xl bg-gradient-to-br from-destructive/30 via-destructive/20 to-destructive/10 p-3 shrink-0 shadow-lg shadow-destructive/20">
<TrendingDown className="h-5 w-5 text-destructive" />
</div>
</CardHeader>
<CardContent className="px-6 pb-6 sm:px-7 sm:pb-7 lg:px-5 lg:pb-5 pt-0 relative z-10">
<div className="text-2xl sm:text-3xl md:text-3xl lg:text-xl xl:text-xl font-black tracking-tight text-destructive mb-4 leading-none break-words">
<CardContent className="px-5 pb-5 sm:px-6 sm:pb-6 pt-0 relative z-10">
<div className="text-2xl sm:text-3xl md:text-3xl lg:text-2xl xl:text-3xl font-black tracking-tight text-destructive mb-3 leading-tight break-words">
{formatCurrency(expenses)}
</div>
<p className="text-xs sm:text-sm font-semibold text-muted-foreground/60">
<p className="text-xs sm:text-sm font-medium text-muted-foreground/70">
{monthTransactions.filter((t) => t.amount < 0).length} opération
{monthTransactions.filter((t) => t.amount < 0).length > 1
? "s"
@@ -129,38 +139,46 @@ export function OverviewCards({ data }: OverviewCardsProps) {
</Card>
<Card className="stat-card-gradient-4 card-hover group relative overflow-hidden">
<CardHeader className="flex flex-row items-start justify-between space-y-0 pb-4 px-6 pt-6 sm:px-7 sm:pt-7 lg:px-5 lg:pt-5 relative z-10">
<CardTitle className="text-xs font-bold text-muted-foreground/70 leading-tight uppercase tracking-widest">
{/* Icône en arrière-plan */}
<div className="absolute bottom-2 right-2 opacity-[0.04] z-0 pointer-events-none">
<CreditCard
className="h-20 w-20 sm:h-24 sm:w-24 md:h-28 md:w-28 text-chart-4"
strokeWidth={1}
/>
</div>
<CardHeader className="flex flex-row items-start justify-between space-y-0 pb-3 px-5 pt-5 sm:px-6 sm:pt-6 relative z-10">
<CardTitle className="text-[10px] sm:text-xs font-semibold text-muted-foreground/80 leading-tight uppercase tracking-wider flex-1 min-w-0">
Pointage
</CardTitle>
<div className="rounded-2xl bg-gradient-to-br from-chart-4/30 via-chart-4/20 to-chart-4/10 p-3 shrink-0 shadow-lg shadow-chart-4/20">
<CreditCard className="h-5 w-5 text-chart-4" />
</div>
</CardHeader>
<CardContent className="px-6 pb-6 sm:px-7 sm:pb-7 lg:px-5 lg:pb-5 pt-0 relative z-10">
<div className="text-2xl sm:text-3xl md:text-3xl lg:text-xl xl:text-xl font-black tracking-tight mb-4 leading-none break-words">
<CardContent className="px-5 pb-5 sm:px-6 sm:pb-6 pt-0 relative z-10">
<div className="text-2xl sm:text-3xl md:text-3xl lg:text-2xl xl:text-3xl font-black tracking-tight mb-3 leading-tight break-words">
{reconciledPercent}%
</div>
<p className="text-xs sm:text-sm font-semibold text-muted-foreground/60">
<p className="text-xs sm:text-sm font-medium text-muted-foreground/70">
{reconciled} / {total} opérations pointées
</p>
</CardContent>
</Card>
<Card className="stat-card-gradient-5 card-hover group relative overflow-hidden">
<CardHeader className="flex flex-row items-start justify-between space-y-0 pb-4 px-6 pt-6 sm:px-7 sm:pt-7 lg:px-5 lg:pt-5 relative z-10">
<CardTitle className="text-xs font-bold text-muted-foreground/70 leading-tight uppercase tracking-widest">
{/* Icône en arrière-plan */}
<div className="absolute bottom-2 right-2 opacity-[0.04] z-0 pointer-events-none">
<Tag
className="h-20 w-20 sm:h-24 sm:w-24 md:h-28 md:w-28 text-chart-5"
strokeWidth={1}
/>
</div>
<CardHeader className="flex flex-row items-start justify-between space-y-0 pb-3 px-5 pt-5 sm:px-6 sm:pt-6 relative z-10">
<CardTitle className="text-[10px] sm:text-xs font-semibold text-muted-foreground/80 leading-tight uppercase tracking-wider flex-1 min-w-0">
Catégorisation
</CardTitle>
<div className="rounded-2xl bg-gradient-to-br from-chart-5/30 via-chart-5/20 to-chart-5/10 p-3 shrink-0 shadow-lg shadow-chart-5/20">
<Tag className="h-5 w-5 text-chart-5" />
</div>
</CardHeader>
<CardContent className="px-6 pb-6 sm:px-7 sm:pb-7 lg:px-5 lg:pb-5 pt-0 relative z-10">
<div className="text-2xl sm:text-3xl md:text-3xl lg:text-xl xl:text-xl font-black tracking-tight mb-4 leading-none break-words">
<CardContent className="px-5 pb-5 sm:px-6 sm:pb-6 pt-0 relative z-10">
<div className="text-2xl sm:text-3xl md:text-3xl lg:text-2xl xl:text-3xl font-black tracking-tight mb-3 leading-tight break-words">
{categorizedPercent}%
</div>
<p className="text-xs sm:text-sm font-semibold text-muted-foreground/60">
<p className="text-xs sm:text-sm font-medium text-muted-foreground/70">
{categorized} / {total} opérations catégorisées
</p>
</CardContent>

View File

@@ -61,13 +61,13 @@ export function RecentTransactions({ data }: RecentTransactionsProps) {
}
return (
<Card className="card-hover">
<CardHeader className="pb-5">
<Card className="card-hover relative overflow-hidden">
<CardHeader className="pb-5 relative z-10">
<CardTitle className="text-lg md:text-xl font-black tracking-tight">
Transactions récentes
</CardTitle>
</CardHeader>
<CardContent className="px-5 md:px-6">
<CardContent className="px-5 md:px-6 relative z-10">
<div className="space-y-3">
{recentTransactions.map((transaction) => {
const category = getCategory(transaction.categoryId);
@@ -88,8 +88,8 @@ export function RecentTransactions({ data }: RecentTransactionsProps) {
className={cn(
"font-black tabular-nums text-sm md:text-base shrink-0 md:hidden",
transaction.amount >= 0
? "text-emerald-600 dark:text-emerald-400"
: "text-red-600 dark:text-red-400"
? "text-success"
: "text-destructive",
)}
>
{transaction.amount >= 0 ? "+" : ""}
@@ -130,8 +130,8 @@ export function RecentTransactions({ data }: RecentTransactionsProps) {
className={cn(
"font-black tabular-nums text-base md:text-lg shrink-0 hidden md:block leading-tight",
transaction.amount >= 0
? "text-emerald-600 dark:text-emerald-400"
: "text-red-600 dark:text-red-400"
? "text-success"
: "text-destructive",
)}
>
{transaction.amount >= 0 ? "+" : ""}

View File

@@ -1,6 +1,5 @@
"use client";
import { useState } from "react";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { signOut } from "next-auth/react";
@@ -19,8 +18,9 @@ import {
LogOut,
} from "lucide-react";
import { toast } from "sonner";
import { Sheet, SheetContent } from "@/components/ui/sheet";
import { Sheet, SheetContent, SheetTitle } from "@/components/ui/sheet";
import { useIsMobile } from "@/hooks/use-mobile";
import { useLocalStorage } from "@/hooks/use-local-storage";
const navItems = [
{ href: "/", label: "Tableau de bord", icon: LayoutDashboard },
@@ -77,25 +77,27 @@ function SidebarContent({
</div>
)}
<nav className={cn("flex-1 space-y-2", collapsed ? "p-2" : "p-4")}>
<nav className={cn("flex-1 pt-2", collapsed ? "p-2" : "p-4")}>
{navItems.map((item) => {
const isActive = pathname === item.href;
return (
<Link key={item.href} href={item.href} onClick={handleLinkClick}>
<Link
key={item.href}
href={item.href}
onClick={handleLinkClick}
className="block mb-2 first:mt-0"
>
<Button
variant={isActive ? "secondary" : "ghost"}
className={cn(
"w-full justify-start gap-4 h-12 rounded-2xl",
"w-full justify-start gap-3 h-12 rounded-2xl px-3",
isActive &&
"bg-gradient-to-r from-primary/15 via-primary/10 to-primary/5 border-2 border-primary/30 shadow-lg shadow-primary/10 backdrop-blur-sm",
collapsed && "justify-center px-2 w-12 mx-auto",
)}
>
<item.icon
className={cn(
"w-5 h-5 shrink-0",
isActive && "text-primary",
)}
className={cn("w-5 h-5 shrink-0", isActive && "text-primary")}
/>
{!collapsed && (
<span
@@ -115,15 +117,15 @@ function SidebarContent({
<div
className={cn(
"border-t border-border/30 space-y-2",
"border-t border-border/30 pt-2",
collapsed ? "p-2" : "p-4",
)}
>
<Link href="/settings" onClick={handleLinkClick}>
<Link href="/settings" onClick={handleLinkClick} className="block mb-2">
<Button
variant="ghost"
className={cn(
"w-full justify-start gap-4 h-12 rounded-2xl",
"w-full justify-start gap-3 h-12 rounded-2xl px-3",
collapsed && "justify-center px-2 w-12 mx-auto",
)}
>
@@ -137,7 +139,7 @@ function SidebarContent({
variant="ghost"
onClick={handleSignOut}
className={cn(
"w-full justify-start gap-4 h-12 rounded-2xl",
"w-full justify-start gap-3 h-12 rounded-2xl px-3 mb-2",
"text-destructive",
collapsed && "justify-center px-2 w-12 mx-auto",
)}
@@ -158,13 +160,18 @@ interface SidebarProps {
}
export function Sidebar({ open, onOpenChange }: SidebarProps) {
const [collapsed, setCollapsed] = useState(false);
const [collapsed, setCollapsed] = useLocalStorage("sidebar-collapsed", false);
const isMobile = useIsMobile();
if (isMobile) {
return (
<Sheet open={open} onOpenChange={onOpenChange}>
<SheetContent side="left" className="w-64 p-0">
<SheetContent
side="left"
className="w-64 p-0 text-sidebar-foreground border-sidebar-border"
style={{ backgroundColor: 'var(--sidebar-opaque)' }}
>
<SheetTitle className="sr-only">Navigation</SheetTitle>
<div className="flex flex-col h-full">
<SidebarContent
showHeader
@@ -179,7 +186,7 @@ export function Sidebar({ open, onOpenChange }: SidebarProps) {
return (
<aside
className={cn(
"hidden md:flex flex-col h-screen glass border-r border-border",
"hidden md:flex flex-col h-screen bg-sidebar text-sidebar-foreground border-r border-sidebar-border",
"backdrop-blur-xl",
collapsed ? "w-16" : "w-64",
)}
@@ -204,10 +211,7 @@ export function Sidebar({ open, onOpenChange }: SidebarProps) {
variant="ghost"
size="icon"
onClick={() => setCollapsed(!collapsed)}
className={cn(
"rounded-xl",
collapsed ? "" : "ml-auto",
)}
className={cn("rounded-xl", collapsed ? "" : "ml-auto")}
>
{collapsed ? (
<ChevronRight className="w-5 h-5" />

View File

@@ -74,7 +74,7 @@ export function DraggableAccountItem({
<span
className={cn(
"text-sm tabular-nums",
realBalance >= 0 ? "text-emerald-600" : "text-red-600",
realBalance >= 0 ? "text-success" : "text-destructive",
)}
>
{formatCurrency(realBalance)}

View File

@@ -120,7 +120,7 @@ export function DraggableFolderItem({
<span
className={cn(
"text-sm font-semibold tabular-nums",
folderTotal >= 0 ? "text-emerald-600" : "text-red-600",
folderTotal >= 0 ? "text-success" : "text-destructive",
)}
>
{formatCurrency(folderTotal)}
@@ -145,7 +145,7 @@ export function DraggableFolderItem({
{folder.id !== "folder-root" && (
<DropdownMenuItem
onClick={() => onDelete(folder.id)}
className="text-red-600"
className="text-destructive"
>
<Trash2 className="w-4 h-4 mr-2" />
Supprimer

View File

@@ -505,9 +505,9 @@ export function OFXImportDialog({
{importResults.map((result, i) => (
<div key={i} className="flex items-center gap-2">
{result.error ? (
<AlertCircle className="w-4 h-4 text-red-500 flex-shrink-0" />
<AlertCircle className="w-4 h-4 text-destructive flex-shrink-0" />
) : (
<CheckCircle2 className="w-4 h-4 text-emerald-500 flex-shrink-0" />
<CheckCircle2 className="w-4 h-4 text-success flex-shrink-0" />
)}
<span className="truncate">{result.fileName}</span>
{!result.error && (
@@ -524,16 +524,16 @@ export function OFXImportDialog({
{step === "success" && (
<div className="py-4">
<CheckCircle2 className="w-16 h-16 mx-auto mb-4 text-emerald-600" />
<CheckCircle2 className="w-16 h-16 mx-auto mb-4 text-success" />
{importResults.length > 1 && (
<div className="max-h-48 overflow-auto space-y-1 text-sm mb-4 border rounded-lg p-2">
{importResults.map((result, i) => (
<div key={i} className="flex items-center gap-2 py-1">
{result.error ? (
<AlertCircle className="w-4 h-4 text-red-500 flex-shrink-0" />
<AlertCircle className="w-4 h-4 text-destructive flex-shrink-0" />
) : (
<CheckCircle2 className="w-4 h-4 text-emerald-500 flex-shrink-0" />
<CheckCircle2 className="w-4 h-4 text-success flex-shrink-0" />
)}
<div className="flex-1 min-w-0">
<p className="truncate font-medium">
@@ -544,7 +544,7 @@ export function OFXImportDialog({
</p>
</div>
{result.error ? (
<span className="text-xs text-red-500 flex-shrink-0">
<span className="text-xs text-destructive flex-shrink-0">
{result.error}
</span>
) : (
@@ -559,7 +559,7 @@ export function OFXImportDialog({
)}
{errorCount > 0 && (
<p className="text-sm text-red-600 mb-4 text-center">
<p className="text-sm text-destructive mb-4 text-center">
{errorCount} fichier{errorCount > 1 ? "s" : ""} en erreur
</p>
)}
@@ -572,7 +572,7 @@ export function OFXImportDialog({
{step === "error" && (
<div className="text-center py-4">
<AlertCircle className="w-16 h-16 mx-auto mb-4 text-red-600" />
<AlertCircle className="w-16 h-16 mx-auto mb-4 text-destructive" />
<Button onClick={() => setStep("upload")}>Réessayer</Button>
</div>
)}

View File

@@ -1,6 +1,6 @@
"use client";
import { ReactNode } from "react";
import { ReactNode, useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { Menu } from "lucide-react";
import { useSidebarContext } from "@/components/layout/sidebar-context";
@@ -21,6 +21,30 @@ export function PageHeader({
}: PageHeaderProps) {
const { setOpen } = useSidebarContext();
const isMobile = useIsMobile();
const [textColor, setTextColor] = useState("var(--foreground)");
useEffect(() => {
const checkDarkBackground = () => {
const pageBackground = document.querySelector(".page-background");
if (pageBackground?.classList.contains("bg-solid-dark")) {
setTextColor("#f5f5f5");
} else {
setTextColor("var(--foreground)");
}
};
checkDarkBackground();
const observer = new MutationObserver(checkDarkBackground);
const pageBackground = document.querySelector(".page-background");
if (pageBackground) {
observer.observe(pageBackground, {
attributes: true,
attributeFilter: ["class"],
});
}
return () => observer.disconnect();
}, []);
return (
<div className="flex flex-col gap-4 mb-2">
@@ -37,7 +61,13 @@ export function PageHeader({
)}
<div className="flex-1 min-w-0">
<div className="flex items-start justify-between gap-2 mb-2">
<h1 className="text-2xl md:text-4xl lg:text-5xl font-black text-foreground tracking-tight leading-tight flex-1 min-w-0">
<h1
className="text-2xl md:text-4xl lg:text-5xl font-black tracking-tight leading-tight flex-1 min-w-0"
style={{
color: textColor,
WebkitTextFillColor: textColor,
}}
>
{title}
</h1>
{rightContent && <div className="shrink-0">{rightContent}</div>}

View File

@@ -15,10 +15,10 @@ export function PageLayout({ children }: PageLayoutProps) {
<SidebarContext.Provider
value={{ open: sidebarOpen, setOpen: setSidebarOpen }}
>
<div className="flex h-screen bg-background overflow-hidden page-background">
<div className="flex h-screen bg-background overflow-hidden page-background bg-default">
<Sidebar open={sidebarOpen} onOpenChange={setSidebarOpen} />
<main className="flex-1 overflow-auto overflow-x-hidden page-content">
<div className="p-6 md:p-8 lg:p-10 space-y-6 md:space-y-8 max-w-full">
<div className="p-3 md:p-8 lg:p-10 space-y-4 md:space-y-8 max-w-full">
{children}
</div>
</main>

View File

@@ -0,0 +1,89 @@
"use client";
import { useEffect } from "react";
interface BackgroundSettings {
type: string;
customImageUrl?: string;
}
export function BackgroundProvider() {
useEffect(() => {
const applyBackground = () => {
try {
const pageBackground = document.querySelector(
".page-background",
) as HTMLElement;
if (!pageBackground) return;
const stored = localStorage.getItem("background-settings");
const settings: BackgroundSettings = stored
? JSON.parse(stored)
: { type: "default" };
// Retirer toutes les classes de fond
pageBackground.classList.remove(
"bg-default",
"bg-gradient-blue",
"bg-gradient-purple",
"bg-gradient-green",
"bg-gradient-orange",
"bg-solid-light",
"bg-solid-dark",
"bg-custom-image",
);
const root = document.documentElement;
if (settings.type === "custom-image" && settings.customImageUrl) {
pageBackground.classList.add("bg-custom-image");
root.style.setProperty(
"--custom-background-image",
`url(${settings.customImageUrl})`,
);
} else {
pageBackground.classList.add(`bg-${settings.type || "default"}`);
root.style.removeProperty("--custom-background-image");
}
} catch (error) {
console.error("Error applying background:", error);
}
};
// Appliquer immédiatement
applyBackground();
// Observer pour les changements de DOM (si le page-background est ajouté plus tard)
const observer = new MutationObserver(() => {
applyBackground();
});
observer.observe(document.body, {
childList: true,
subtree: true,
});
// Écouter les changements dans localStorage (autres onglets)
const handleStorageChange = (e: StorageEvent) => {
if (e.key === "background-settings") {
applyBackground();
}
};
// Écouter les événements personnalisés (même onglet)
const handleBackgroundChanged = () => {
applyBackground();
};
window.addEventListener("storage", handleStorageChange);
window.addEventListener("background-changed", handleBackgroundChanged);
return () => {
observer.disconnect();
window.removeEventListener("storage", handleStorageChange);
window.removeEventListener("background-changed", handleBackgroundChanged);
};
}, []);
return null;
}

View File

@@ -133,7 +133,7 @@ export function RuleCreateDialog({
catégorisées.
</p>
{existingCategory && (
<div className="flex items-center gap-2 text-xs text-amber-600 dark:text-amber-400">
<div className="flex items-center gap-2 text-xs text-warning">
<AlertCircle className="h-3 w-3" />
<span>
Ce mot-clé existe déjà dans &quot;{existingCategory.name}

View File

@@ -5,6 +5,7 @@ import { ChevronDown, ChevronRight, Plus, Tag } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { CategoryCombobox } from "@/components/ui/category-combobox";
import { Card } from "@/components/ui/card";
import { useIsMobile } from "@/hooks/use-mobile";
import { cn } from "@/lib/utils";
import type { Transaction, Category } from "@/lib/types";
@@ -54,7 +55,7 @@ export function RuleGroupCard({
};
return (
<div className="border border-border rounded-lg bg-card overflow-hidden">
<Card className="card-hover overflow-hidden">
{/* Header */}
<div
className="flex flex-col md:flex-row md:items-center gap-2 md:gap-3 p-3 md:p-4 cursor-pointer hover:bg-accent/5"
@@ -247,6 +248,6 @@ export function RuleGroupCard({
)}
</div>
)}
</div>
</Card>
);
}

View File

@@ -0,0 +1,326 @@
"use client";
import { useState, useEffect, useMemo } from "react";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Image, X } from "lucide-react";
import { useLocalStorage } from "@/hooks/use-local-storage";
import { cn } from "@/lib/utils";
type BackgroundType =
| "default"
| "gradient-blue"
| "gradient-purple"
| "gradient-green"
| "gradient-orange"
| "solid-light"
| "solid-dark"
| "custom-image";
interface BackgroundSettings {
type: BackgroundType;
customImageUrl?: string;
}
const DEFAULT_BACKGROUNDS: Array<{
value: BackgroundType;
label: string;
preview: string;
description?: string;
}> = [
{
value: "default",
label: "Neutre",
preview:
"linear-gradient(135deg, oklch(0.985 0 0) 0%, oklch(0.97 0.005 260) 50%, oklch(0.985 0 0) 100%)",
description: "Fond neutre et élégant",
},
{
value: "gradient-blue",
label: "Océan",
preview:
"linear-gradient(135deg, oklch(0.95 0.03 230) 0%, oklch(0.88 0.08 225) 50%, oklch(0.78 0.12 220) 100%)",
description: "Dégradé bleu apaisant",
},
{
value: "gradient-purple",
label: "Améthyste",
preview:
"linear-gradient(135deg, oklch(0.95 0.04 300) 0%, oklch(0.88 0.1 295) 50%, oklch(0.78 0.15 290) 100%)",
description: "Dégradé violet sophistiqué",
},
{
value: "gradient-green",
label: "Forêt",
preview:
"linear-gradient(135deg, oklch(0.95 0.04 160) 0%, oklch(0.88 0.1 155) 50%, oklch(0.78 0.14 150) 100%)",
description: "Dégradé vert naturel",
},
{
value: "gradient-orange",
label: "Aurore",
preview:
"linear-gradient(135deg, oklch(0.97 0.03 80) 0%, oklch(0.92 0.08 60) 50%, oklch(0.85 0.14 45) 100%)",
description: "Dégradé orange chaleureux",
},
{
value: "solid-light",
label: "Lumineux",
preview:
"linear-gradient(135deg, oklch(1 0 0) 0%, oklch(0.98 0.005 260) 100%)",
description: "Fond blanc épuré",
},
{
value: "solid-dark",
label: "Minuit",
preview:
"linear-gradient(135deg, oklch(0.18 0.02 260) 0%, oklch(0.08 0.015 250) 100%)",
description: "Fond sombre immersif",
},
];
export function BackgroundCard() {
const [backgroundSettings, setBackgroundSettings] =
useLocalStorage<BackgroundSettings>("background-settings", {
type: "default",
});
const currentSettings = useMemo<BackgroundSettings>(
() => backgroundSettings || { type: "default" },
[backgroundSettings],
);
const [customImageUrl, setCustomImageUrl] = useState(
currentSettings.customImageUrl || "",
);
const [showCustomInput, setShowCustomInput] = useState(
currentSettings.type === "custom-image",
);
// Synchroniser customImageUrl avec les settings
useEffect(() => {
if (
currentSettings.type === "custom-image" &&
currentSettings.customImageUrl
) {
setCustomImageUrl(currentSettings.customImageUrl);
}
}, [currentSettings]);
const applyBackground = (settings: BackgroundSettings) => {
const root = document.documentElement;
const pageBackground = document.querySelector(
".page-background",
) as HTMLElement;
if (!pageBackground) return;
// Retirer toutes les classes de fond
pageBackground.classList.remove(
"bg-default",
"bg-gradient-blue",
"bg-gradient-purple",
"bg-gradient-green",
"bg-gradient-orange",
"bg-solid-light",
"bg-solid-dark",
"bg-custom-image",
);
if (settings.type === "custom-image" && settings.customImageUrl) {
pageBackground.classList.add("bg-custom-image");
root.style.setProperty(
"--custom-background-image",
`url(${settings.customImageUrl})`,
);
} else {
pageBackground.classList.add(`bg-${settings.type || "default"}`);
root.style.removeProperty("--custom-background-image");
}
// Déclencher un événement personnalisé pour notifier les autres composants
window.dispatchEvent(
new CustomEvent("background-changed", { detail: settings }),
);
};
const handleBackgroundChange = (type: BackgroundType) => {
if (type === "custom-image") {
setShowCustomInput(true);
if (customImageUrl.trim()) {
const newSettings: BackgroundSettings = {
type,
customImageUrl: customImageUrl.trim(),
};
setBackgroundSettings(newSettings);
applyBackground(newSettings);
} else {
const newSettings: BackgroundSettings = { type };
setBackgroundSettings(newSettings);
}
} else {
setShowCustomInput(false);
const newSettings: BackgroundSettings = { type };
setBackgroundSettings(newSettings);
applyBackground(newSettings);
}
};
const handleCustomImageSubmit = () => {
if (customImageUrl.trim()) {
const newSettings: BackgroundSettings = {
type: "custom-image",
customImageUrl: customImageUrl.trim(),
};
setBackgroundSettings(newSettings);
applyBackground(newSettings);
}
};
const handleRemoveCustomImage = () => {
setCustomImageUrl("");
setShowCustomInput(false);
const newSettings: BackgroundSettings = { type: "default" };
setBackgroundSettings(newSettings);
applyBackground(newSettings);
};
// Appliquer le fond au chargement et quand il change
useEffect(() => {
if (typeof window !== "undefined") {
applyBackground(currentSettings);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [currentSettings.type, currentSettings.customImageUrl]);
return (
<Card className="card-hover">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Image className="w-5 h-5" />
Fond du site
</CardTitle>
<CardDescription>
Personnalisez l'apparence du fond de l'application
</CardDescription>
</CardHeader>
<CardContent className="space-y-6">
<RadioGroup
value={currentSettings.type}
onValueChange={(value) =>
handleBackgroundChange(value as BackgroundType)
}
>
<div className="grid grid-cols-2 md:grid-cols-3 gap-3">
{DEFAULT_BACKGROUNDS.map((bg) => (
<label
key={bg.value}
htmlFor={`bg-${bg.value}`}
className={cn(
"relative flex flex-col items-center justify-center p-4 rounded-lg border-2 cursor-pointer transition-all",
currentSettings.type === bg.value
? "border-primary bg-primary/5"
: "border-border hover:border-primary/50",
)}
>
<RadioGroupItem
value={bg.value}
id={`bg-${bg.value}`}
className="sr-only"
/>
<div
className="w-full h-16 rounded-md mb-2 border border-border/50"
style={{ background: bg.preview }}
/>
<span className="text-xs font-medium text-center">
{bg.label}
</span>
</label>
))}
<label
htmlFor="bg-custom-image"
className={cn(
"relative flex flex-col items-center justify-center p-4 rounded-lg border-2 cursor-pointer transition-all",
currentSettings.type === "custom-image"
? "border-primary bg-primary/5"
: "border-border hover:border-primary/50",
)}
>
<RadioGroupItem
value="custom-image"
id="bg-custom-image"
className="sr-only"
/>
<div className="w-full h-16 rounded-md mb-2 border border-border/50 bg-muted flex items-center justify-center">
<Image className="w-6 h-6 text-muted-foreground" />
</div>
<span className="text-xs font-medium text-center">
Image personnalisée
</span>
</label>
</div>
</RadioGroup>
{showCustomInput && (
<div className="space-y-3 p-4 rounded-lg bg-muted/30 border border-border">
<div className="space-y-2">
<Label htmlFor="custom-image-url">URL de l'image</Label>
<div className="flex gap-2">
<Input
id="custom-image-url"
type="url"
placeholder="https://example.com/image.jpg"
value={customImageUrl}
onChange={(e) => setCustomImageUrl(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") {
handleCustomImageSubmit();
}
}}
/>
{customImageUrl && (
<Button
variant="outline"
size="icon"
onClick={handleRemoveCustomImage}
>
<X className="w-4 h-4" />
</Button>
)}
</div>
</div>
<Button
onClick={handleCustomImageSubmit}
disabled={!customImageUrl.trim()}
>
Appliquer l'image
</Button>
{currentSettings.type === "custom-image" &&
currentSettings.customImageUrl && (
<div className="mt-3">
<div className="text-xs text-muted-foreground mb-2">
Aperçu :
</div>
<div
className="w-full h-32 rounded-md border border-border bg-cover bg-center bg-no-repeat"
style={{
backgroundImage: `url(${currentSettings.customImageUrl})`,
}}
/>
</div>
)}
</div>
)}
</CardContent>
</Card>
);
}

View File

@@ -59,9 +59,9 @@ export function DangerZoneCard({
}
};
return (
<Card className="border-red-200">
<Card className="border-destructive/30 card-hover">
<CardHeader>
<CardTitle className="flex items-center gap-2 text-red-600">
<CardTitle className="flex items-center gap-2 text-destructive">
<Trash2 className="w-5 h-5" />
Zone dangereuse
</CardTitle>

View File

@@ -4,3 +4,5 @@ export { OFXInfoCard } from "./ofx-info-card";
export { BackupCard } from "./backup-card";
export { PasswordCard } from "./password-card";
export { ReconcileDateRangeCard } from "./reconcile-date-range-card";
export { BackgroundCard } from "./background-card";
export { ThemeCard } from "./theme-card";

View File

@@ -45,11 +45,12 @@ export function ReconcileDateRangeCard() {
setIsReconciling(true);
try {
const endDateStr = format(endDate, "yyyy-MM-dd");
const body: { endDate: string; startDate?: string; reconciled: boolean } = {
endDate: endDateStr,
reconciled: true,
};
const body: { endDate: string; startDate?: string; reconciled: boolean } =
{
endDate: endDateStr,
reconciled: true,
};
if (startDate) {
body.startDate = format(startDate, "yyyy-MM-dd");
}
@@ -69,7 +70,7 @@ export function ReconcileDateRangeCard() {
}
const result = await response.json();
// Invalider toutes les requêtes de transactions pour rafraîchir les données
invalidateAllTransactionQueries(queryClient);
@@ -118,7 +119,7 @@ export function ReconcileDateRangeCard() {
<>
{startDate ? (
<>
{format(startDate, "PPP", { locale: fr})} -{" "}
{format(startDate, "PPP", { locale: fr })} -{" "}
{format(endDate, "PPP", { locale: fr })}
</>
) : (
@@ -134,7 +135,10 @@ export function ReconcileDateRangeCard() {
<div className="p-3 flex gap-4">
<div className="space-y-2">
<label className="text-sm font-medium">
Date de début <span className="text-xs text-muted-foreground">(optionnel)</span>
Date de début{" "}
<span className="text-xs text-muted-foreground">
(optionnel)
</span>
</label>
<div className="scale-90 origin-top-left">
<CalendarComponent
@@ -233,8 +237,8 @@ export function ReconcileDateRangeCard() {
) : (
<>jusqu'au {format(endDate, "PPP", { locale: fr })}</>
)}{" "}
comme pointées. Seules les opérations non encore pointées seront
modifiées.
comme pointées. Seules les opérations non encore pointées
seront modifiées.
</>
)}
</AlertDialogDescription>
@@ -257,4 +261,3 @@ export function ReconcileDateRangeCard() {
</Card>
);
}

View File

@@ -0,0 +1,93 @@
"use client";
import { useTheme } from "next-themes";
import { useEffect, useState } from "react";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Moon, Sun } from "lucide-react";
import { cn } from "@/lib/utils";
const THEMES = [
{
value: "light",
label: "Clair",
icon: Sun,
description: "Thème clair",
},
{
value: "dark",
label: "Sombre",
icon: Moon,
description: "Thème sombre",
},
] as const;
export function ThemeCard() {
const { theme, setTheme } = useTheme();
const [mounted, setMounted] = useState(false);
// Éviter le flash de contenu non stylé
useEffect(() => {
setMounted(true);
}, []);
if (!mounted) {
return null;
}
const currentTheme = theme || "light";
return (
<Card className="card-hover">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Moon className="w-5 h-5" />
Thème
</CardTitle>
<CardDescription>
Choisissez le thème d'affichage de l'application
</CardDescription>
</CardHeader>
<CardContent>
<RadioGroup
value={currentTheme}
onValueChange={(value) => setTheme(value)}
>
<div className="grid grid-cols-2 gap-3">
{THEMES.map((themeOption) => {
const Icon = themeOption.icon;
return (
<label
key={themeOption.value}
htmlFor={`theme-${themeOption.value}`}
className={cn(
"relative flex flex-col items-center justify-center p-4 rounded-lg border-2 cursor-pointer transition-all",
currentTheme === themeOption.value
? "border-primary bg-primary/5"
: "border-border hover:border-primary/50",
)}
>
<RadioGroupItem
value={themeOption.value}
id={`theme-${themeOption.value}`}
className="sr-only"
/>
<Icon className="w-6 h-6 mb-2" />
<span className="text-sm font-medium">
{themeOption.label}
</span>
</label>
);
})}
</div>
</RadioGroup>
</CardContent>
</Card>
);
}

View File

@@ -57,7 +57,7 @@ export function BalanceLineChart({
};
return (
<Card>
<Card className="card-hover">
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle>Évolution du solde</CardTitle>
<div className="flex gap-1">
@@ -103,11 +103,38 @@ export function BalanceLineChart({
tick={{ fill: "var(--muted-foreground)" }}
/>
<Tooltip
formatter={(value: number) => formatCurrency(value)}
contentStyle={{
backgroundColor: "var(--card)",
border: "1px solid var(--border)",
borderRadius: "8px",
content={({ active, payload }) => {
if (!active || !payload?.length) return null;
return (
<div
className="px-3 py-2 rounded-lg shadow-lg"
style={{
backgroundColor: "var(--popover)",
border: "1px solid var(--border)",
opacity: 1,
backdropFilter: "blur(8px)",
}}
>
{payload.map((entry, index) => (
<div
key={`tooltip-${index}`}
className="flex items-center gap-2"
style={{ color: entry.color }}
>
<div
className="w-3 h-3 rounded-full"
style={{ backgroundColor: entry.color }}
/>
<span className="text-sm font-medium">
{entry.name}:
</span>
<span className="text-sm font-semibold">
{formatCurrency(entry.value as number)}
</span>
</div>
))}
</div>
);
}}
/>
{mode === "aggregated" ? (

View File

@@ -31,10 +31,18 @@ export function CategoryBarChart({
const displayData = data.slice(0, maxItems).reverse(); // Reverse pour avoir le plus grand en haut
// Custom tick component for clickable labels
const CustomYAxisTick = ({ x, y, payload }: any) => {
const CustomYAxisTick = ({
x,
y,
payload,
}: {
x: number;
y: number;
payload: { value: string };
}) => {
const categoryName = payload.value;
const item = displayData.find((d) => d.name === categoryName);
if (!item) {
return (
<text
@@ -73,7 +81,7 @@ export function CategoryBarChart({
};
return (
<Card>
<Card className="card-hover">
<CardHeader>
<CardTitle>{title}</CardTitle>
</CardHeader>
@@ -154,3 +162,5 @@ export function CategoryBarChart({
</Card>
);
}
// Find the Card component in this file

View File

@@ -51,7 +51,7 @@ export function CategoryPieChart({
const currentData = isExpanded ? baseData : baseData.slice(0, maxItems);
return (
<Card>
<Card className="card-hover">
<CardHeader className="flex flex-col md:flex-row md:items-center md:justify-between space-y-2 md:space-y-0 pb-2">
<CardTitle className="text-sm md:text-base">{title}</CardTitle>
<div className="flex flex-col md:flex-row gap-2 w-full md:w-auto">

View File

@@ -96,7 +96,7 @@ export function CategoryTrendChart({
};
return (
<Card>
<Card className="card-hover">
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle>Évolution des dépenses par catégorie</CardTitle>
<div className="flex gap-2">
@@ -166,11 +166,67 @@ export function CategoryTrendChart({
tick={{ fill: "var(--muted-foreground)" }}
/>
<Tooltip
formatter={(value: number) => formatCurrency(value)}
contentStyle={{
backgroundColor: "var(--card)",
border: "1px solid var(--border)",
borderRadius: "8px",
content={({ active, payload, label }) => {
if (!active || !payload?.length) return null;
// Filtrer seulement les catégories qui ont une valeur
const entriesWithValue = payload.filter(
(entry) => entry.value !== undefined && entry.value !== null && Number(entry.value) !== 0
);
if (entriesWithValue.length === 0) return null;
return (
<div
className="px-2.5 py-2 rounded-lg shadow-lg"
style={{
backgroundColor: "var(--background)",
border: "1px solid var(--border)",
opacity: 1,
}}
>
<div className="text-xs font-medium text-foreground mb-1.5 pb-1 border-b border-border/50">
{label}
</div>
<div className="space-y-1">
{entriesWithValue.map((entry, index) => {
const categoryId = entry.dataKey as string;
const categoryInfo = getCategoryInfo(categoryId);
const categoryName = getCategoryName(categoryId);
const value = entry.value as number;
return (
<div
key={`tooltip-${categoryId}-${index}`}
className="flex items-center gap-1.5"
>
{categoryInfo ? (
<CategoryIcon
icon={categoryInfo.icon}
color={categoryInfo.color}
size={12}
/>
) : (
<div
className="w-3 h-3 rounded-full shrink-0"
style={{ backgroundColor: "#94a3b8" }}
/>
)}
<span className="text-xs text-foreground flex-1 min-w-0 truncate">
{categoryName}
</span>
<span className="text-xs font-semibold text-foreground tabular-nums whitespace-nowrap">
{formatCurrency(value)}
</span>
</div>
);
})}
</div>
</div>
);
}}
wrapperStyle={{
opacity: 1,
}}
/>
<Legend
@@ -179,8 +235,9 @@ export function CategoryTrendChart({
const allCategoryIds = Array.from(categoryTotals.keys());
return (
<div className="flex flex-wrap justify-center gap-x-4 gap-y-1 mt-2">
{allCategoryIds.map((categoryId) => {
<div className="max-h-[60px] overflow-y-auto overflow-x-hidden pr-2 mt-2">
<div className="flex flex-wrap justify-center gap-x-4 gap-y-1">
{allCategoryIds.map((categoryId) => {
const categoryInfo = getCategoryInfo(categoryId);
const categoryName = getCategoryName(categoryId);
if (!categoryInfo && categoryId !== "uncategorized")
@@ -233,6 +290,7 @@ export function CategoryTrendChart({
</button>
);
})}
</div>
</div>
);
}}
@@ -259,6 +317,7 @@ export function CategoryTrendChart({
strokeWidth={isSelected ? 2 : 1}
strokeOpacity={isSelected ? 1 : 0.3}
dot={false}
connectNulls={true}
hide={!isSelected && selectedCategories.length > 0}
/>
);

View File

@@ -28,7 +28,7 @@ export function IncomeExpenseTrendChart({
formatCurrency,
}: IncomeExpenseTrendChartProps) {
return (
<Card>
<Card className="card-hover">
<CardHeader>
<CardTitle>Tendances revenus et dépenses</CardTitle>
</CardHeader>

View File

@@ -1,9 +1,12 @@
"use client";
import { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { ChevronDown, ChevronUp } from "lucide-react";
import {
BarChart,
Bar,
LineChart,
Line,
XAxis,
YAxis,
CartesianGrid,
@@ -11,6 +14,11 @@ import {
ResponsiveContainer,
Legend,
} from "recharts";
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible";
interface MonthlyChartData {
month: string;
@@ -22,54 +30,147 @@ interface MonthlyChartData {
interface MonthlyChartProps {
data: MonthlyChartData[];
formatCurrency: (amount: number) => string;
collapsible?: boolean;
defaultExpanded?: boolean;
showDots?: boolean;
}
export function MonthlyChart({ data, formatCurrency }: MonthlyChartProps) {
export function MonthlyChart({
data,
formatCurrency,
collapsible = false,
defaultExpanded = true,
showDots = true,
}: MonthlyChartProps) {
const [isExpanded, setIsExpanded] = useState(defaultExpanded);
// Calculer l'intervalle dynamiquement selon le nombre de données
const getXAxisInterval = () => {
if (data.length <= 6) return 0; // Afficher tous les labels pour 6 mois ou moins
if (data.length <= 12) return 1; // Afficher un label sur deux pour 7-12 mois
return Math.floor(data.length / 12); // Pour plus de 12 mois, afficher environ 12 labels
};
// Formater les labels de manière plus compacte
const formatMonthLabel = (month: string) => {
// Format: "janv. 24" -> "janv 24" (enlever le point)
return month.replace(".", "");
};
const chartContent = (
<>
{data.length > 0 ? (
<div className="h-[400px] sm:h-[300px]">
<ResponsiveContainer width="100%" height="100%">
<LineChart
data={data}
margin={{
left: 0,
right: 10,
top: 10,
bottom: data.length > 6 ? 80 : 60,
}}
>
<CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
<XAxis
dataKey="month"
className="text-xs"
angle={data.length > 6 ? -45 : 0}
textAnchor={data.length > 6 ? "end" : "middle"}
height={data.length > 6 ? 80 : 60}
interval={getXAxisInterval()}
tickFormatter={formatMonthLabel}
tick={{ fontSize: 11 }}
/>
<YAxis
className="text-xs"
width={60}
tickFormatter={(v) => {
// Format compact pour les grandes valeurs
if (Math.abs(v) >= 1000) {
return `${(v / 1000).toFixed(1)}k€`;
}
return `${v.toFixed(0)}`;
}}
tick={{ fill: "var(--muted-foreground)" }}
/>
<Tooltip
formatter={(value: number) => formatCurrency(value)}
labelFormatter={(label) => label}
contentStyle={{
backgroundColor: "var(--card)",
border: "1px solid var(--border)",
borderRadius: "8px",
}}
/>
<Legend />
<Line
type="monotone"
dataKey="revenus"
name="Revenus"
stroke="#22c55e"
strokeWidth={2}
dot={showDots ? { fill: "#22c55e", r: 4 } : false}
activeDot={showDots ? { r: 6 } : false}
/>
<Line
type="monotone"
dataKey="depenses"
name="Dépenses"
stroke="#ef4444"
strokeWidth={2}
dot={showDots ? { fill: "#ef4444", r: 4 } : false}
activeDot={showDots ? { r: 6 } : false}
/>
</LineChart>
</ResponsiveContainer>
</div>
) : (
<div className="h-[400px] sm:h-[300px] flex items-center justify-center text-muted-foreground">
Pas de données pour cette période
</div>
)}
</>
);
if (!collapsible) {
return (
<Card className="card-hover">
<CardHeader>
<CardTitle>Revenus vs Dépenses par mois</CardTitle>
</CardHeader>
<CardContent>{chartContent}</CardContent>
</Card>
);
}
return (
<Card>
<CardHeader>
<CardTitle>Revenus vs Dépenses par mois</CardTitle>
</CardHeader>
<CardContent>
{data.length > 0 ? (
<div className="h-[300px]">
<ResponsiveContainer width="100%" height="100%">
<BarChart data={data}>
<CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
<XAxis dataKey="month" className="text-xs" />
<YAxis
className="text-xs"
width={80}
tickFormatter={(v) => {
// Format compact pour les grandes valeurs
if (Math.abs(v) >= 1000) {
return `${(v / 1000).toFixed(1)}k€`;
}
return `${Math.round(v)}`;
}}
tick={{ fill: "var(--muted-foreground)" }}
/>
<Tooltip
formatter={(value: number) => formatCurrency(value)}
labelFormatter={(label) => label}
contentStyle={{
backgroundColor: "var(--card)",
border: "1px solid var(--border)",
borderRadius: "8px",
}}
/>
<Legend />
<Bar dataKey="revenus" fill="#22c55e" radius={[4, 4, 0, 0]} />
<Bar dataKey="depenses" fill="#ef4444" radius={[4, 4, 0, 0]} />
</BarChart>
</ResponsiveContainer>
</div>
) : (
<div className="h-[300px] flex items-center justify-center text-muted-foreground">
Pas de données pour cette période
</div>
)}
</CardContent>
<Card className="card-hover">
<Collapsible open={isExpanded} onOpenChange={setIsExpanded}>
<CardHeader className="flex flex-row items-center justify-between space-y-0 py-3 px-6">
<CardTitle className="text-base font-semibold">
Revenus vs Dépenses par mois
</CardTitle>
<CollapsibleTrigger asChild>
<Button variant="ghost" size="sm" className="h-8">
{isExpanded ? (
<>
<ChevronUp className="w-4 h-4 mr-1" />
Réduire
</>
) : (
<>
<ChevronDown className="w-4 h-4 mr-1" />
Afficher
</>
)}
</Button>
</CollapsibleTrigger>
</CardHeader>
<CollapsibleContent>
<CardContent className="pt-0">{chartContent}</CardContent>
</CollapsibleContent>
</Collapsible>
</Card>
);
}

View File

@@ -31,18 +31,18 @@ export function SavingsTrendChart({
const isPositive = latestSavings >= 0;
return (
<Card>
<Card className="card-hover">
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle>Évolution des économies</CardTitle>
<div className="flex items-center gap-2">
{isPositive ? (
<TrendingUp className="w-4 h-4 text-emerald-600" />
<TrendingUp className="w-4 h-4 text-success" />
) : (
<TrendingDown className="w-4 h-4 text-red-600" />
<TrendingDown className="w-4 h-4 text-destructive" />
)}
<span
className={`text-sm font-semibold ${
isPositive ? "text-emerald-600" : "text-red-600"
isPositive ? "text-success" : "text-destructive"
}`}
>
{formatCurrency(latestSavings)}

View File

@@ -21,59 +21,86 @@ export function StatsSummaryCards({
return (
<div className="grid gap-3 md:gap-4 grid-cols-2 md:grid-cols-4">
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-xs md:text-sm font-medium text-muted-foreground flex items-center gap-1.5 md:gap-2">
<TrendingUp className="w-3 h-3 md:w-4 md:h-4 text-emerald-600" />
<Card className="stat-card-textured relative overflow-hidden">
{/* Icône en arrière-plan */}
<div className="absolute bottom-2 right-2 opacity-[0.04] z-0 pointer-events-none">
<TrendingUp
className="h-16 w-16 md:h-20 md:w-20 text-success"
strokeWidth={1}
/>
</div>
<CardHeader className="pb-3 px-5 pt-5 relative z-10">
<CardTitle className="text-[10px] md:text-xs font-semibold text-muted-foreground/80 uppercase tracking-wider">
Total Revenus
</CardTitle>
</CardHeader>
<CardContent>
<div className="text-lg md:text-2xl font-bold text-emerald-600">
<CardContent className="px-5 pb-5 pt-0 relative z-10">
<div className="text-xl md:text-2xl font-black text-success tracking-tight">
{formatCurrency(totalIncome)}
</div>
</CardContent>
</Card>
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-xs md:text-sm font-medium text-muted-foreground flex items-center gap-1.5 md:gap-2">
<TrendingDown className="w-3 h-3 md:w-4 md:h-4 text-red-600" />
<Card className="stat-card-textured relative overflow-hidden">
{/* Icône en arrière-plan */}
<div className="absolute bottom-2 right-2 opacity-[0.04] z-0 pointer-events-none">
<TrendingDown
className="h-16 w-16 md:h-20 md:w-20 text-destructive"
strokeWidth={1}
/>
</div>
<CardHeader className="pb-3 px-5 pt-5 relative z-10">
<CardTitle className="text-[10px] md:text-xs font-semibold text-muted-foreground/80 uppercase tracking-wider">
Total Dépenses
</CardTitle>
</CardHeader>
<CardContent>
<div className="text-lg md:text-2xl font-bold text-red-600">
<CardContent className="px-5 pb-5 pt-0 relative z-10">
<div className="text-xl md:text-2xl font-black text-destructive tracking-tight">
{formatCurrency(totalExpenses)}
</div>
</CardContent>
</Card>
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-xs md:text-sm font-medium text-muted-foreground flex items-center gap-1.5 md:gap-2">
<ArrowRight className="w-3 h-3 md:w-4 md:h-4" />
<Card className="stat-card-textured relative overflow-hidden">
{/* Icône en arrière-plan */}
<div className="absolute bottom-2 right-2 opacity-[0.04] z-0 pointer-events-none">
<ArrowRight
className="h-16 w-16 md:h-20 md:w-20 text-muted-foreground/40"
strokeWidth={1}
/>
</div>
<CardHeader className="pb-3 px-5 pt-5 relative z-10">
<CardTitle className="text-[10px] md:text-xs font-semibold text-muted-foreground/80 uppercase tracking-wider">
Moyenne mensuelle
</CardTitle>
</CardHeader>
<CardContent>
<div className="text-lg md:text-2xl font-bold">
<CardContent className="px-5 pb-5 pt-0 relative z-10">
<div className="text-xl md:text-2xl font-black tracking-tight">
{formatCurrency(avgMonthlyExpenses)}
</div>
</CardContent>
</Card>
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-xs md:text-sm font-medium text-muted-foreground">
<Card className="stat-card-textured relative overflow-hidden">
{/* Icône en arrière-plan */}
<div className="absolute bottom-2 right-2 opacity-[0.04] z-0 pointer-events-none">
<div
className={cn(
"h-16 w-16 md:h-20 md:w-20 rounded-full border-2",
savings >= 0 ? "border-success" : "border-destructive",
)}
/>
</div>
<CardHeader className="pb-3 px-5 pt-5 relative z-10">
<CardTitle className="text-[10px] md:text-xs font-semibold text-muted-foreground/80 uppercase tracking-wider">
Économies
</CardTitle>
</CardHeader>
<CardContent>
<CardContent className="px-5 pb-5 pt-0 relative z-10">
<div
className={cn(
"text-lg md:text-2xl font-bold",
savings >= 0 ? "text-emerald-600" : "text-red-600",
"text-xl md:text-2xl font-black tracking-tight",
savings >= 0 ? "text-success" : "text-destructive",
)}
>
{formatCurrency(savings)}

View File

@@ -1,89 +1,468 @@
"use client";
import { useState, useMemo, useEffect } from "react";
import Link from "next/link";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { CategoryIcon } from "@/components/ui/category-icon";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
import { Button } from "@/components/ui/button";
import { useIsMobile } from "@/hooks/use-mobile";
import {
BarChart,
Bar,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
ResponsiveContainer,
} from "recharts";
import { List, ListOrdered } from "lucide-react";
import type { Transaction, Category } from "@/lib/types";
interface TopExpensesListProps {
expenses: Transaction[];
expensesByCategory: Array<{
categoryId: string | null;
expenses: Transaction[];
}>;
categories: Category[];
formatCurrency: (amount: number) => string;
allTransactions?: Transaction[]; // Toutes les transactions filtrées pour calculer toutes les dépenses
}
export function TopExpensesList({
expenses,
expensesByCategory,
categories,
formatCurrency,
allTransactions = [],
}: TopExpensesListProps) {
const isMobile = useIsMobile();
const [showAllExpenses, setShowAllExpenses] = useState(false);
// Filtrer les catégories qui ont des dépenses
const categoriesWithExpenses = expensesByCategory.filter(
(group) => group.expenses.length > 0,
);
const hasExpenses = categoriesWithExpenses.length > 0;
// Déterminer la valeur par défaut du premier onglet
const defaultTabValue =
categoriesWithExpenses.length > 0
? categoriesWithExpenses[0].categoryId || "uncategorized"
: "";
const [activeTab, setActiveTab] = useState<string>(() => defaultTabValue);
// Mettre à jour activeTab quand defaultTabValue change ou si activeTab est invalide
useEffect(() => {
if (!defaultTabValue) return;
// Vérifier si activeTab correspond à une catégorie valide
const isValidTab = categoriesWithExpenses.some(
(group) => (group.categoryId || "uncategorized") === activeTab,
);
// Si activeTab est vide ou invalide, utiliser defaultTabValue
if (!activeTab || !isValidTab) {
setActiveTab(defaultTabValue);
}
}, [defaultTabValue, categoriesWithExpenses, activeTab]);
// Calculer les données du graphique pour la catégorie active
const chartData = useMemo(() => {
if (!hasExpenses) return [];
// Utiliser activeTab ou defaultTabValue comme fallback
const currentTab = activeTab || defaultTabValue;
if (!currentTab) return [];
const activeCategoryGroup = categoriesWithExpenses.find(
(group) => (group.categoryId || "uncategorized") === currentTab,
);
if (!activeCategoryGroup) {
return [];
}
// Si showAllExpenses est activé et qu'on a toutes les transactions, utiliser toutes les dépenses de la catégorie
let expenses: Transaction[];
if (showAllExpenses && allTransactions.length > 0) {
// Filtrer toutes les transactions pour obtenir toutes les dépenses de cette catégorie parente
const categoryId = activeCategoryGroup.categoryId;
expenses = allTransactions
.filter((t) => t.amount < 0) // Seulement les dépenses
.filter((t) => {
if (categoryId === null) {
return !t.categoryId;
}
// Vérifier si la transaction appartient à cette catégorie parente ou ses sous-catégories
const category = categories.find((c) => c.id === t.categoryId);
if (!category) {
return false;
}
const transactionGroupId = category.parentId || category.id;
return transactionGroupId === categoryId;
});
} else {
// Utiliser seulement les top 10
expenses = activeCategoryGroup.expenses;
}
if (expenses.length === 0) {
return [];
}
// Grouper les dépenses par période
// Si moins de 30 jours, groupe par jour
// Si moins de 6 mois, groupe par semaine
// Sinon groupe par mois
const sortedExpenses = [...expenses].sort(
(a, b) => new Date(a.date).getTime() - new Date(b.date).getTime(),
);
if (sortedExpenses.length === 0) return [];
const firstDate = new Date(sortedExpenses[0].date);
const lastDate = new Date(
sortedExpenses[sortedExpenses.length - 1].date,
);
const daysDiff =
(lastDate.getTime() - firstDate.getTime()) / (1000 * 60 * 60 * 24);
let groupBy: "day" | "week" | "month";
if (daysDiff <= 30) {
groupBy = "day";
} else if (daysDiff <= 180) {
groupBy = "week";
} else {
groupBy = "month";
}
// Fonction helper pour obtenir la clé de période d'une date
const getPeriodKey = (date: Date): { key: string; dateKey: string } => {
if (groupBy === "day") {
return {
key: date.toLocaleDateString("fr-FR", {
day: "2-digit",
month: "short",
}),
dateKey: date.toISOString().substring(0, 10), // YYYY-MM-DD
};
} else if (groupBy === "week") {
// Semaine commençant le lundi
const weekStart = new Date(date);
const day = weekStart.getDay();
const diff = weekStart.getDate() - day + (day === 0 ? -6 : 1);
weekStart.setDate(diff);
return {
key: `Sem. ${weekStart.toLocaleDateString("fr-FR", {
day: "2-digit",
month: "short",
})}`,
dateKey: weekStart.toISOString().substring(0, 10), // YYYY-MM-DD
};
} else {
return {
key: date.toLocaleDateString("fr-FR", {
month: "short",
year: "numeric",
}),
dateKey: `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}`, // YYYY-MM
};
}
};
// Grouper les dépenses par période
const groupedData = new Map<
string,
{ total: number; dateKey: string }
>();
sortedExpenses.forEach((expense) => {
const date = new Date(expense.date);
const { key, dateKey } = getPeriodKey(date);
const current = groupedData.get(key);
if (current) {
current.total += Math.abs(expense.amount);
} else {
groupedData.set(key, {
total: Math.abs(expense.amount),
dateKey,
});
}
});
// Générer toutes les périodes entre la première et la dernière date
const allPeriodsMap = new Map<
string,
{ period: string; montant: number; dateKey: string }
>();
const currentDate = new Date(firstDate);
const endDate = new Date(lastDate);
// Normaliser les dates selon le type de groupement
if (groupBy === "day") {
currentDate.setHours(0, 0, 0, 0);
endDate.setHours(23, 59, 59, 999);
} else if (groupBy === "week") {
// Début de la semaine de la première date
const day = currentDate.getDay();
const diff = currentDate.getDate() - day + (day === 0 ? -6 : 1);
currentDate.setDate(diff);
currentDate.setHours(0, 0, 0, 0);
// Début de la semaine de la dernière date (pour la boucle)
const lastDay = endDate.getDay();
const lastDiff = endDate.getDate() - lastDay + (lastDay === 0 ? -6 : 1);
endDate.setDate(lastDiff);
endDate.setHours(0, 0, 0, 0);
} else {
// Mois : premier jour du mois
currentDate.setDate(1);
currentDate.setHours(0, 0, 0, 0);
endDate.setDate(1);
endDate.setHours(0, 0, 0, 0);
}
while (currentDate <= endDate) {
const { key, dateKey } = getPeriodKey(currentDate);
const existingData = groupedData.get(key);
// Utiliser dateKey comme clé unique pour éviter les doublons
if (!allPeriodsMap.has(dateKey)) {
allPeriodsMap.set(dateKey, {
period: key,
montant: existingData ? Math.round(existingData.total) : 0,
dateKey,
});
}
// Passer à la période suivante
if (groupBy === "day") {
currentDate.setDate(currentDate.getDate() + 1);
} else if (groupBy === "week") {
currentDate.setDate(currentDate.getDate() + 7);
} else {
// Mois suivant
currentDate.setMonth(currentDate.getMonth() + 1);
}
}
return Array.from(allPeriodsMap.values()) .sort((a, b) =>
a.dateKey.localeCompare(b.dateKey),
);
}, [
hasExpenses,
categoriesWithExpenses,
activeTab,
defaultTabValue,
showAllExpenses,
allTransactions,
categories,
]);
return (
<Card>
<Card className="card-hover">
<CardHeader>
<CardTitle className="text-sm md:text-base">Top 5 dépenses</CardTitle>
<CardTitle className="text-sm md:text-base">
Top 10 dépenses par top 5 catégories parentes
</CardTitle>
</CardHeader>
<CardContent>
{expenses.length > 0 ? (
<div className="space-y-3 md:space-y-4">
{expenses.map((expense, index) => {
const category = categories.find(
(c) => c.id === expense.categoryId,
);
{hasExpenses ? (
<Tabs
defaultValue={defaultTabValue}
value={activeTab || defaultTabValue}
onValueChange={setActiveTab}
className="w-full"
>
<TabsList className="w-full flex-wrap h-auto p-1 mb-4">
{categoriesWithExpenses.map(({ categoryId, expenses }) => {
const category = categoryId
? categories.find((c) => c.id === categoryId)
: null;
const tabValue = categoryId || "uncategorized";
return (
<TabsTrigger
key={tabValue}
value={tabValue}
className="flex items-center gap-1.5 md:gap-2 text-xs md:text-sm"
>
{category && (
<CategoryIcon
icon={category.icon}
color={category.color}
size={isMobile ? 12 : 14}
/>
)}
<span className="truncate max-w-[100px] md:max-w-none">
{category?.name || "Non catégorisé"}
</span>
</TabsTrigger>
);
})}
</TabsList>
{categoriesWithExpenses.map(({ categoryId, expenses }) => {
const category = categoryId
? categories.find((c) => c.id === categoryId)
: null;
const tabValue = categoryId || "uncategorized";
return (
<div
key={expense.id}
className="flex items-start gap-2 md:gap-3"
>
<div className="w-6 h-6 md:w-8 md:h-8 rounded-full bg-muted flex items-center justify-center text-xs md:text-sm font-semibold shrink-0">
{index + 1}
</div>
<div className="flex-1 min-w-0">
<div className="flex items-start justify-between gap-2 mb-1">
<p className="font-medium text-xs md:text-sm truncate flex-1">
{expense.description}
</p>
<div className="text-red-600 font-semibold tabular-nums text-xs md:text-sm shrink-0">
{formatCurrency(expense.amount)}
</div>
</div>
<div className="flex items-center gap-1.5 md:gap-2 flex-wrap">
<span className="text-[10px] md:text-xs text-muted-foreground">
{new Date(expense.date).toLocaleDateString("fr-FR")}
</span>
{category && (
<Link
href={`/transactions?categoryIds=${category.id}`}
className="inline-block"
>
<Badge
variant="secondary"
className="text-[10px] md:text-xs px-1.5 md:px-2 py-0.5 inline-flex items-center gap-1 shrink-0 hover:opacity-80 transition-opacity cursor-pointer"
style={{
backgroundColor: `${category.color}20`,
color: category.color,
borderColor: `${category.color}30`,
}}
>
<CategoryIcon
icon={category.icon}
color={category.color}
size={isMobile ? 8 : 10}
/>
<span className="truncate max-w-[120px] md:max-w-none">
{category.name}
<TabsContent key={tabValue} value={tabValue}>
<div className="space-y-2 md:space-y-3">
{expenses.map((expense, index) => (
<div
key={expense.id}
className="flex items-start gap-2 md:gap-3"
>
<div className="w-5 h-5 md:w-6 md:h-6 rounded-full bg-muted flex items-center justify-center text-[10px] md:text-xs font-semibold shrink-0">
{index + 1}
</div>
<div className="flex-1 min-w-0">
<div className="flex items-start justify-between gap-2 mb-1">
<p className="font-medium text-xs md:text-sm truncate flex-1">
{expense.description}
</p>
<div className="text-destructive font-semibold tabular-nums text-xs md:text-sm shrink-0">
{formatCurrency(expense.amount)}
</div>
</div>
<div className="flex items-center gap-1.5 md:gap-2 flex-wrap">
<span className="text-[10px] md:text-xs text-muted-foreground">
{new Date(expense.date).toLocaleDateString(
"fr-FR",
)}
</span>
</Badge>
</Link>
)}
</div>
{expense.categoryId &&
(() => {
const expenseCategory = categories.find(
(c) => c.id === expense.categoryId,
);
// Afficher seulement si c'est une sous-catégorie (a un parentId)
if (expenseCategory?.parentId) {
return (
<Link
href={`/transactions?categoryIds=${expenseCategory.id}`}
className="inline-block"
>
<Badge
variant="secondary"
className="text-[10px] md:text-xs px-1.5 md:px-2 py-0.5 inline-flex items-center gap-1 shrink-0 hover:opacity-80 transition-opacity cursor-pointer"
style={{
backgroundColor: `${expenseCategory.color}20`,
color: expenseCategory.color,
borderColor: `${expenseCategory.color}30`,
}}
>
<CategoryIcon
icon={expenseCategory.icon}
color={expenseCategory.color}
size={isMobile ? 8 : 10}
/>
<span className="truncate max-w-[100px] md:max-w-none">
{expenseCategory.name}
</span>
</Badge>
</Link>
);
}
return null;
})()}
</div>
</div>
</div>
))}
</div>
</TabsContent>
);
})}
{/* Graphique d'évolution temporelle */}
{chartData.length > 0 && (() => {
const currentTab = activeTab || defaultTabValue;
const activeCategoryGroup = categoriesWithExpenses.find(
(group) => (group.categoryId || "uncategorized") === currentTab,
);
const activeCategory = activeCategoryGroup?.categoryId
? categories.find((c) => c.id === activeCategoryGroup.categoryId)
: null;
const barColor = activeCategory?.color || "var(--destructive)";
return (
<div className="mt-6 pt-6 border-t border-border">
<div className="flex items-center justify-between mb-4">
<h3 className="text-sm font-semibold">
Évolution des dépenses dans le temps
</h3>
{allTransactions.length > 0 && (
<Button
variant="outline"
size="sm"
onClick={() => setShowAllExpenses(!showAllExpenses)}
className="text-xs"
>
{showAllExpenses ? (
<>
<ListOrdered className="w-3 h-3 mr-1.5" />
Top 10 seulement
</>
) : (
<>
<List className="w-3 h-3 mr-1.5" />
Voir toutes les dépenses
</>
)}
</Button>
)}
</div>
<div className="h-[250px]">
<ResponsiveContainer width="100%" height="100%">
<BarChart data={chartData}>
<CartesianGrid
strokeDasharray="3 3"
className="stroke-muted"
/>
<XAxis
dataKey="period"
className="text-xs"
interval="preserveStartEnd"
angle={-45}
textAnchor="end"
height={60}
/>
<YAxis
className="text-xs"
width={80}
tickFormatter={(v) => {
if (Math.abs(v) >= 1000) {
return `${(v / 1000).toFixed(1)}k€`;
}
return `${Math.round(v)}`;
}}
tick={{ fill: "var(--muted-foreground)" }}
/>
<Tooltip
formatter={(value: number) => formatCurrency(value)}
contentStyle={{
backgroundColor: "var(--card)",
border: "1px solid var(--border)",
borderRadius: "8px",
}}
/>
<Bar
dataKey="montant"
fill={barColor}
radius={[4, 4, 0, 0]}
/>
</BarChart>
</ResponsiveContainer>
</div>
</div>
);
})}
</div>
})()}
</Tabs>
) : (
<div className="h-[200px] flex items-center justify-center text-muted-foreground text-xs md:text-sm">
Pas de dépenses pour cette période

View File

@@ -33,7 +33,7 @@ export function YearOverYearChart({
previousYearLabel = "Année précédente",
}: YearOverYearChartProps) {
return (
<Card>
<Card className="card-hover">
<CardHeader>
<CardTitle>Comparaison année sur année</CardTitle>
</CardHeader>

View File

@@ -245,26 +245,26 @@ export function TransactionFilters({
</div>
{customStartDate && customEndDate && (
<div className="flex gap-2 pt-2 border-t px-3 pb-3">
<Button
variant="outline"
size="sm"
className="flex-1"
onClick={() => {
onCustomStartDateChange(undefined);
onCustomEndDateChange(undefined);
}}
>
Réinitialiser
</Button>
<Button
size="sm"
className="flex-1"
onClick={() => onCustomDatePickerOpenChange(false)}
>
Valider
</Button>
</div>
)}
<Button
variant="outline"
size="sm"
className="flex-1"
onClick={() => {
onCustomStartDateChange(undefined);
onCustomEndDateChange(undefined);
}}
>
Réinitialiser
</Button>
<Button
size="sm"
className="flex-1"
onClick={() => onCustomDatePickerOpenChange(false)}
>
Valider
</Button>
</div>
)}
</PopoverContent>
</Popover>
)}

View File

@@ -155,7 +155,7 @@ export function TransactionTable({
const parentRef = useRef<HTMLDivElement>(null);
const isMobile = useIsMobile();
const MOBILE_ROW_HEIGHT = 120;
const MOBILE_ROW_HEIGHT = 140;
const virtualizer = useVirtualizer({
count: transactions.length,
@@ -227,17 +227,17 @@ export function TransactionTable({
);
return (
<Card className="overflow-hidden">
<CardContent className="p-0">
<Card className="overflow-hidden w-full card-hover">
<CardContent className="p-0 w-full">
{transactions.length === 0 ? (
<div className="flex flex-col items-center justify-center py-12">
<p className="text-muted-foreground">Aucune transaction trouvée</p>
</div>
) : isMobile ? (
<div className="divide-y divide-border">
<div className="divide-y divide-border w-full">
<div
ref={parentRef}
className="overflow-auto"
className="overflow-auto w-full"
style={{ height: "calc(100vh - 200px)", minHeight: "600px" }}
>
<div
@@ -278,30 +278,31 @@ export function TransactionTable({
}
}}
className={cn(
"p-4 space-y-3 hover:bg-muted/50 cursor-pointer border-b border-border",
"p-4 md:p-4 space-y-3 hover:bg-muted/50 cursor-pointer border-b border-border",
transaction.isReconciled && "bg-emerald-500/5",
isFocused && "bg-primary/10 ring-1 ring-primary/30",
isDuplicate && "shadow-sm",
)}
>
<div className="flex items-start justify-between gap-2">
<div className="flex items-start gap-3 flex-1 min-w-0">
<div className="flex items-start justify-between gap-3">
<div className="flex items-start gap-0 md:gap-3 flex-1 min-w-0">
<Checkbox
checked={selectedTransactions.has(transaction.id)}
onCheckedChange={() => {
onToggleSelectTransaction(transaction.id);
}}
onClick={(e) => e.stopPropagation()}
className="mt-0.5 hidden md:flex"
/>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<p className="font-medium text-xs md:text-sm truncate">
<p className="font-medium text-sm md:text-sm truncate leading-tight">
{transaction.description}
</p>
{isDuplicate && (
<Tooltip delayDuration={200}>
<TooltipTrigger asChild>
<AlertTriangle className="h-3 w-3 md:h-4 md:w-4 text-[var(--warning)] shrink-0" />
<AlertTriangle className="h-4 w-4 md:h-4 md:w-4 text-[var(--warning)] shrink-0" />
</TooltipTrigger>
<TooltipContent>
<p>
@@ -312,7 +313,7 @@ export function TransactionTable({
)}
</div>
{transaction.memo && (
<p className="text-[10px] md:text-xs text-muted-foreground truncate mt-1">
<p className="text-xs md:text-xs text-muted-foreground truncate mt-1.5">
{transaction.memo}
</p>
)}
@@ -320,10 +321,10 @@ export function TransactionTable({
</div>
<div
className={cn(
"font-semibold tabular-nums text-sm md:text-base shrink-0",
"font-semibold tabular-nums text-base md:text-base shrink-0",
transaction.amount >= 0
? "text-emerald-600"
: "text-red-600",
? "text-success"
: "text-destructive",
)}
>
{transaction.amount >= 0 ? "+" : ""}
@@ -331,18 +332,18 @@ export function TransactionTable({
</div>
</div>
<div className="flex items-center gap-2 md:gap-3 flex-wrap">
<span className="text-[10px] md:text-xs text-muted-foreground">
<div className="flex items-center gap-2.5 md:gap-3 flex-wrap">
<span className="text-xs md:text-xs text-muted-foreground">
{formatDate(transaction.date)}
</span>
{account && (
<span className="text-[10px] md:text-xs text-muted-foreground">
<span className="text-xs md:text-xs text-muted-foreground">
{account.name}
</span>
)}
<div
onClick={(e) => e.stopPropagation()}
className="flex-1 relative"
className="flex-1 relative min-w-[120px]"
>
{updatingTransactionIds.has(transaction.id) && (
<div className="absolute inset-0 flex items-center justify-center bg-background/50 z-10 rounded">
@@ -370,9 +371,9 @@ export function TransactionTable({
<Button
variant="ghost"
size="icon"
className="h-8 w-8 shrink-0"
className="h-9 w-9 shrink-0"
>
<MoreVertical className="w-4 h-4" />
<MoreVertical className="w-5 h-5" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
@@ -397,7 +398,7 @@ export function TransactionTable({
onDelete(transaction.id);
}
}}
className="text-red-600 focus:text-red-600"
className="text-destructive focus:text-destructive"
>
<Trash2 className="w-4 h-4 mr-2" />
Supprimer
@@ -446,7 +447,7 @@ export function TransactionTable({
<div className="p-3 text-sm font-medium text-muted-foreground">
Compte
</div>
<div className="p-3 text-sm font-medium text-muted-foreground">
<div className="p-3 text-sm font-medium text-muted-foreground text-center">
Catégorie
</div>
<div className="p-3 text-right">
@@ -464,7 +465,7 @@ export function TransactionTable({
<div className="p-3"></div>
</div>
</div>
{/* Body virtualisé */}
{/* Body virtualisé ou non selon le mode */}
<div
ref={parentRef}
className="overflow-auto"
@@ -552,7 +553,7 @@ export function TransactionTable({
{account?.name || "-"}
</div>
<div
className="p-3 relative"
className="p-3 relative flex items-center justify-center"
onClick={(e) => e.stopPropagation()}
>
{updatingTransactionIds.has(transaction.id) && (
@@ -575,8 +576,8 @@ export function TransactionTable({
className={cn(
"p-3 text-right font-semibold tabular-nums",
transaction.amount >= 0
? "text-emerald-600"
: "text-red-600",
? "text-success"
: "text-destructive",
)}
>
{transaction.amount >= 0 ? "+" : ""}
@@ -591,7 +592,7 @@ export function TransactionTable({
className="p-1 hover:bg-muted rounded"
>
{transaction.isReconciled ? (
<CheckCircle2 className="w-5 h-5 text-emerald-600" />
<CheckCircle2 className="w-5 h-5 text-success" />
) : (
<Circle className="w-5 h-5 text-muted-foreground" />
)}
@@ -649,7 +650,7 @@ export function TransactionTable({
onDelete(transaction.id);
}
}}
className="text-red-600 focus:text-red-600"
className="text-destructive focus:text-destructive"
>
<Trash2 className="w-4 h-4 mr-2" />
Supprimer

View File

@@ -5,7 +5,7 @@ import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
const badgeVariants = cva(
"inline-flex items-center justify-center rounded-md border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",
"inline-flex items-center justify-center rounded-md border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/30 aria-invalid:border-destructive overflow-hidden",
{
variants: {
variant: {
@@ -14,7 +14,7 @@ const badgeVariants = cva(
secondary:
"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
destructive:
"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
"border-transparent bg-destructive text-destructive-foreground [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/30",
outline:
"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
},

View File

@@ -5,16 +5,16 @@ import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-xl text-sm font-semibold disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-xl text-sm font-semibold disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/30 aria-invalid:border-destructive",
{
variants: {
variant: {
default:
"bg-gradient-to-r from-primary via-primary/95 to-primary/90 text-primary-foreground shadow-xl shadow-primary/30 backdrop-blur-sm border border-primary/20",
destructive:
"bg-gradient-to-r from-destructive via-destructive/95 to-destructive/90 text-white shadow-xl shadow-destructive/30 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 backdrop-blur-sm border border-destructive/20",
"bg-gradient-to-r from-destructive via-destructive/95 to-destructive/90 text-destructive-foreground shadow-xl shadow-destructive/30 focus-visible:ring-destructive/30 backdrop-blur-sm border border-destructive/20",
outline:
"border-2 bg-background/95 backdrop-blur-md shadow-md dark:bg-input/40 dark:border-input",
"border-2 bg-background/95 backdrop-blur-md shadow-md border-border",
secondary:
"bg-gradient-to-r from-secondary via-secondary/95 to-secondary/90 text-secondary-foreground backdrop-blur-sm",
ghost: "backdrop-blur-sm",
@@ -33,7 +33,7 @@ const buttonVariants = cva(
variant: "default",
size: "default",
},
}
},
);
function Button({

View File

@@ -201,7 +201,7 @@ function CalendarDayButton({
data-range-end={modifiers.range_end}
data-range-middle={modifiers.range_middle}
className={cn(
"data-[selected-single=true]:bg-primary data-[selected-single=true]:text-primary-foreground data-[range-middle=true]:bg-accent data-[range-middle=true]:text-accent-foreground data-[range-start=true]:bg-primary data-[range-start=true]:text-primary-foreground data-[range-end=true]:bg-primary data-[range-end=true]:text-primary-foreground group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-ring/50 dark:hover:text-accent-foreground flex aspect-square size-auto w-full min-w-(--cell-size) flex-col gap-1 leading-none font-normal group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:ring-[3px] data-[range-end=true]:rounded-md data-[range-end=true]:rounded-r-md data-[range-middle=true]:rounded-none data-[range-start=true]:rounded-md data-[range-start=true]:rounded-l-md [&>span]:text-xs [&>span]:opacity-70",
"data-[selected-single=true]:bg-primary data-[selected-single=true]:text-primary-foreground data-[range-middle=true]:bg-accent data-[range-middle=true]:text-accent-foreground data-[range-start=true]:bg-primary data-[range-start=true]:text-primary-foreground data-[range-end=true]:bg-primary data-[range-end=true]:text-primary-foreground group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-ring/50 hover:text-accent-foreground flex aspect-square size-auto w-full min-w-(--cell-size) flex-col gap-1 leading-none font-normal group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:ring-[3px] data-[range-end=true]:rounded-md data-[range-end=true]:rounded-r-md data-[range-middle=true]:rounded-none data-[range-start=true]:rounded-md data-[range-start=true]:rounded-l-md [&>span]:text-xs [&>span]:opacity-70",
defaultClassNames.day,
className,
)}

View File

@@ -87,21 +87,55 @@ export function CategoryFilterCombobox({
return;
}
// Check if this is a parent category
const isParentCategory = parentCategories.some((p) => p.id === newValue);
const childCategories = isParentCategory
? childrenByParent[newValue] || []
: [];
// Category selection - toggle
let newSelection: string[];
if (isAll || isUncategorized) {
// Start fresh with just this category
newSelection = [newValue];
// Start fresh with this category and its children (if parent)
if (isParentCategory && childCategories.length > 0) {
newSelection = [newValue, ...childCategories.map((child) => child.id)];
} else {
newSelection = [newValue];
}
} else if (value.includes(newValue)) {
// Remove category
newSelection = value.filter((v) => v !== newValue);
// Remove category and its children (if parent)
if (isParentCategory && childCategories.length > 0) {
const childIds = childCategories.map((child) => child.id);
newSelection = value.filter(
(v) => v !== newValue && !childIds.includes(v),
);
} else {
newSelection = value.filter((v) => v !== newValue);
}
if (newSelection.length === 0) {
newSelection = ["all"];
}
} else {
// Add category
newSelection = [...value, newValue];
// Add category and its children (if parent)
if (isParentCategory && childCategories.length > 0) {
const childIds = childCategories.map((child) => child.id);
newSelection = [
...value.filter((v) => !childIds.includes(v)), // Remove any existing children
newValue,
...childIds,
];
} else {
// Check if this child's parent is already selected
const category = categories.find((c) => c.id === newValue);
if (category?.parentId && value.includes(category.parentId)) {
// Parent is selected, so we're adding a child - keep parent
newSelection = [...value, newValue];
} else {
// Regular add
newSelection = [...value, newValue];
}
}
}
onChange(newSelection);

View File

@@ -14,7 +14,7 @@ function Checkbox({
<CheckboxPrimitive.Root
data-slot="checkbox"
className={cn(
"peer border-input dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
"peer border-input bg-input data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/30 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
className,
)}
{...props}

View File

@@ -126,7 +126,7 @@ function ContextMenuItem({
data-inset={inset}
data-variant={variant}
className={cn(
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/15 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}

View File

@@ -60,7 +60,7 @@ function DialogContent({
<DialogPrimitive.Content
data-slot="dialog-content"
className={cn(
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 flex flex-col w-full max-w-[calc(100%-2rem)] max-h-[calc(100vh-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 overflow-y-auto sm:max-w-lg",
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 flex flex-col w-full max-w-[calc(100%-2rem)] max-h-[calc(100vh-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 overflow-y-auto sm:max-w-lg",
className,
)}
{...props}

View File

@@ -76,7 +76,7 @@ function DropdownMenuItem({
data-inset={inset}
data-variant={variant}
className={cn(
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/15 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}

View File

@@ -117,7 +117,7 @@ function FieldLabel({
className={cn(
"group/field-label peer/field-label flex w-fit gap-2 leading-snug group-data-[disabled=true]/field:opacity-50",
"has-[>[data-slot=field]]:w-full has-[>[data-slot=field]]:flex-col has-[>[data-slot=field]]:rounded-md has-[>[data-slot=field]]:border [&>*]:data-[slot=field]:p-4",
"has-data-[state=checked]:bg-primary/5 has-data-[state=checked]:border-primary dark:has-data-[state=checked]:bg-primary/10",
"has-data-[state=checked]:bg-primary/8 has-data-[state=checked]:border-primary",
className,
)}
{...props}

View File

@@ -13,7 +13,7 @@ function InputGroup({ className, ...props }: React.ComponentProps<"div">) {
data-slot="input-group"
role="group"
className={cn(
"group/input-group border-input dark:bg-input/30 relative flex w-full items-center rounded-md border shadow-xs transition-[color,box-shadow] outline-none",
"group/input-group border-input bg-input relative flex w-full items-center rounded-md border shadow-xs outline-none",
"h-9 has-[>textarea]:h-auto",
// Variants based on alignment.
@@ -26,7 +26,7 @@ function InputGroup({ className, ...props }: React.ComponentProps<"div">) {
"has-[[data-slot=input-group-control]:focus-visible]:border-ring has-[[data-slot=input-group-control]:focus-visible]:ring-ring/50 has-[[data-slot=input-group-control]:focus-visible]:ring-[3px]",
// Error state.
"has-[[data-slot][aria-invalid=true]]:ring-destructive/20 has-[[data-slot][aria-invalid=true]]:border-destructive dark:has-[[data-slot][aria-invalid=true]]:ring-destructive/40",
"has-[[data-slot][aria-invalid=true]]:ring-destructive/30 has-[[data-slot][aria-invalid=true]]:border-destructive",
className,
)}
@@ -135,7 +135,7 @@ function InputGroupInput({
<Input
data-slot="input-group-control"
className={cn(
"flex-1 rounded-none border-0 bg-transparent shadow-none focus-visible:ring-0 dark:bg-transparent",
"flex-1 rounded-none border-0 bg-transparent shadow-none focus-visible:ring-0",
className,
)}
{...props}
@@ -151,7 +151,7 @@ function InputGroupTextarea({
<Textarea
data-slot="input-group-control"
className={cn(
"flex-1 resize-none rounded-none border-0 bg-transparent py-3 shadow-none focus-visible:ring-0 dark:bg-transparent",
"flex-1 resize-none rounded-none border-0 bg-transparent py-3 shadow-none focus-visible:ring-0",
className,
)}
{...props}

View File

@@ -51,7 +51,7 @@ function InputOTPSlot({
data-slot="input-otp-slot"
data-active={isActive}
className={cn(
"data-[active=true]:border-ring data-[active=true]:ring-ring/50 data-[active=true]:aria-invalid:ring-destructive/20 dark:data-[active=true]:aria-invalid:ring-destructive/40 aria-invalid:border-destructive data-[active=true]:aria-invalid:border-destructive dark:bg-input/30 border-input relative flex h-9 w-9 items-center justify-center border-y border-r text-sm shadow-xs transition-all outline-none first:rounded-l-md first:border-l last:rounded-r-md data-[active=true]:z-10 data-[active=true]:ring-[3px]",
"data-[active=true]:border-ring data-[active=true]:ring-ring/50 data-[active=true]:aria-invalid:ring-destructive/30 aria-invalid:border-destructive data-[active=true]:aria-invalid:border-destructive bg-input border-input relative flex h-9 w-9 items-center justify-center border-y border-r text-sm shadow-xs outline-none first:rounded-l-md first:border-l last:rounded-r-md data-[active=true]:z-10 data-[active=true]:ring-[3px]",
className,
)}
{...props}

View File

@@ -9,13 +9,13 @@ function Input({ className, type, ...props }: React.ComponentProps<"input">) {
data-slot="input"
className={cn(
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground",
"dark:bg-input/40 border-input h-9 w-full min-w-0 rounded-lg border bg-background/50 backdrop-blur-sm px-3 py-1 text-base",
"shadow-sm transition-all duration-200 outline-none",
"bg-input border-border h-9 w-full min-w-0 rounded-lg border backdrop-blur-sm px-3 py-1 text-base",
"shadow-sm outline-none",
"file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium",
"disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
"focus-visible:border-primary/50 focus-visible:ring-primary/20 focus-visible:ring-[3px] focus-visible:shadow-md focus-visible:shadow-primary/10",
"hover:border-primary/30 hover:shadow-sm",
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
"aria-invalid:ring-destructive/30 aria-invalid:border-destructive",
className,
)}
{...props}

View File

@@ -7,7 +7,7 @@ function Kbd({ className, ...props }: React.ComponentProps<"kbd">) {
className={cn(
"bg-muted w-fit text-muted-foreground pointer-events-none inline-flex h-5 min-w-5 items-center justify-center gap-1 rounded-sm px-1 font-sans text-xs font-medium select-none",
"[&_svg:not([class*='size-'])]:size-3",
"[[data-slot=tooltip-content]_&]:bg-background/20 [[data-slot=tooltip-content]_&]:text-background dark:[[data-slot=tooltip-content]_&]:bg-background/10",
"[[data-slot=tooltip-content]_&]:bg-background/15 [[data-slot=tooltip-content]_&]:text-background",
className,
)}
{...props}

View File

@@ -103,7 +103,7 @@ function MenubarItem({
data-inset={inset}
data-variant={variant}
className={cn(
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/15 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}

View File

@@ -27,7 +27,7 @@ function RadioGroupItem({
<RadioGroupPrimitive.Item
data-slot="radio-group-item"
className={cn(
"border-input text-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 aspect-square size-4 shrink-0 rounded-full border shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
"border-input text-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/30 aria-invalid:border-destructive bg-input aspect-square size-4 shrink-0 rounded-full border shadow-xs outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
className,
)}
{...props}

View File

@@ -37,7 +37,7 @@ function SelectTrigger({
data-slot="select-trigger"
data-size={size}
className={cn(
"border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
"border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/30 aria-invalid:border-destructive bg-input hover:bg-input/80 flex w-fit items-center justify-between gap-2 rounded-md border px-3 py-2 text-sm whitespace-nowrap shadow-xs outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}

View File

@@ -4,11 +4,11 @@ import { useTheme } from "next-themes";
import { Toaster as Sonner, ToasterProps } from "sonner";
const Toaster = ({ ...props }: ToasterProps) => {
const { theme = "system" } = useTheme();
const { theme = "light" } = useTheme();
return (
<Sonner
theme={theme as ToasterProps["theme"]}
theme={theme === "system" ? "dark" : (theme as ToasterProps["theme"])}
className="toaster group"
style={
{

View File

@@ -13,7 +13,7 @@ function Switch({
<SwitchPrimitive.Root
data-slot="switch"
className={cn(
"peer data-[state=checked]:bg-primary data-[state=unchecked]:bg-input focus-visible:border-ring focus-visible:ring-ring/50 dark:data-[state=unchecked]:bg-input/80 inline-flex h-[1.15rem] w-8 shrink-0 items-center rounded-full border border-transparent shadow-xs transition-all outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
"peer data-[state=checked]:bg-primary data-[state=unchecked]:bg-input focus-visible:border-ring focus-visible:ring-ring/50 inline-flex h-[1.15rem] w-8 shrink-0 items-center rounded-full border border-transparent shadow-xs outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
className,
)}
{...props}
@@ -21,7 +21,7 @@ function Switch({
<SwitchPrimitive.Thumb
data-slot="switch-thumb"
className={
"bg-background dark:data-[state=unchecked]:bg-foreground dark:data-[state=checked]:bg-primary-foreground pointer-events-none block size-4 rounded-full ring-0 transition-transform data-[state=checked]:translate-x-[calc(100%-2px)] data-[state=unchecked]:translate-x-0"
"bg-primary-foreground pointer-events-none block size-4 rounded-full ring-0 data-[state=checked]:translate-x-[calc(100%-2px)] data-[state=unchecked]:translate-x-0"
}
/>
</SwitchPrimitive.Root>

View File

@@ -42,7 +42,7 @@ function TabsTrigger({
<TabsPrimitive.Trigger
data-slot="tabs-trigger"
className={cn(
"data-[state=active]:bg-background dark:data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:shadow-sm [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
"data-[state=active]:bg-background data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring data-[state=active]:border-input text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:shadow-sm [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}

View File

@@ -8,11 +8,11 @@ function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
data-slot="textarea"
className={cn(
"border-input placeholder:text-muted-foreground",
"dark:bg-input/40 flex field-sizing-content min-h-16 w-full rounded-lg border bg-background/50 backdrop-blur-sm px-3 py-2 text-base",
"shadow-sm transition-all duration-200 outline-none",
"bg-input flex field-sizing-content min-h-16 w-full rounded-lg border backdrop-blur-sm px-3 py-2 text-base",
"shadow-sm outline-none",
"focus-visible:border-primary/50 focus-visible:ring-primary/20 focus-visible:ring-[3px] focus-visible:shadow-md focus-visible:shadow-primary/10",
"hover:border-primary/30 hover:shadow-sm",
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
"aria-invalid:ring-destructive/30 aria-invalid:border-destructive",
"disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
className,
)}

View File

@@ -7,7 +7,7 @@ import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
const toggleVariants = cva(
"inline-flex items-center justify-center gap-2 rounded-md text-sm font-medium hover:bg-muted hover:text-muted-foreground disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 [&_svg]:shrink-0 focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] outline-none transition-[color,box-shadow] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive whitespace-nowrap",
"inline-flex items-center justify-center gap-2 rounded-md text-sm font-medium hover:bg-muted hover:text-muted-foreground disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 [&_svg]:shrink-0 focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] outline-none aria-invalid:ring-destructive/30 aria-invalid:border-destructive whitespace-nowrap",
{
variants: {
variant: {

View File

@@ -0,0 +1,44 @@
"use client";
import { useState } from "react";
/**
* Hook pour gérer la persistance d'une valeur dans le localStorage
*/
export function useLocalStorage<T>(
key: string,
initialValue: T,
): [T, (value: T | ((val: T) => T)) => void] {
// État pour stocker la valeur
const [storedValue, setStoredValue] = useState<T>(() => {
if (typeof window === "undefined") {
return initialValue;
}
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
console.error(`Error reading localStorage key "${key}":`, error);
return initialValue;
}
});
// Fonction pour mettre à jour la valeur
const setValue = (value: T | ((val: T) => T)) => {
try {
// Permet d'utiliser une fonction comme setState
const valueToStore =
value instanceof Function ? value(storedValue) : value;
setStoredValue(valueToStore);
if (typeof window !== "undefined") {
window.localStorage.setItem(key, JSON.stringify(valueToStore));
}
} catch (error) {
console.error(`Error setting localStorage key "${key}":`, error);
}
};
return [storedValue, setValue];
}

View File

@@ -0,0 +1,328 @@
"use client";
import { useMemo } from "react";
import { useTransactions } from "@/lib/hooks";
import { useBankingMetadata } from "@/lib/hooks";
import type { TransactionsPaginatedParams } from "@/services/banking.service";
import type { Account } from "@/lib/types";
interface BalanceChartDataPoint {
date: string;
[key: string]: string | number;
}
interface UseTransactionsBalanceChartParams {
selectedAccounts: string[];
selectedCategories: string[];
period: "1month" | "3months" | "6months" | "12months" | "custom" | "all";
customStartDate?: Date;
customEndDate?: Date;
showReconciled: string;
searchQuery: string;
}
export function useTransactionsBalanceChart({
selectedAccounts,
selectedCategories,
period,
customStartDate,
customEndDate,
showReconciled,
searchQuery,
}: UseTransactionsBalanceChartParams) {
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)
const chartParams = useMemo<TransactionsPaginatedParams>(() => {
const params: TransactionsPaginatedParams = {
limit: 10000, // Large limit to get all transactions
offset: 0,
sortField: "date",
sortOrder: "asc", // Ascending for balance calculation
};
if (startDate && period !== "all") {
params.startDate = startDate.toISOString().split("T")[0];
}
if (endDate) {
params.endDate = endDate.toISOString().split("T")[0];
}
if (!selectedAccounts.includes("all")) {
params.accountIds = selectedAccounts;
}
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,
selectedAccounts,
selectedCategories,
searchQuery,
showReconciled,
period,
]);
// Build params for fetching transactions before startDate (for initial balance)
const beforeStartDateParams = useMemo<TransactionsPaginatedParams>(() => {
if (period === "all" || !startDate) {
return { limit: 0, offset: 0 }; // Don't fetch if no start date
}
const params: TransactionsPaginatedParams = {
limit: 10000,
offset: 0,
sortField: "date",
sortOrder: "asc",
endDate: new Date(startDate.getTime() - 1).toISOString().split("T")[0], // Day before startDate
};
if (!selectedAccounts.includes("all")) {
params.accountIds = selectedAccounts;
}
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,
selectedAccounts,
selectedCategories,
searchQuery,
showReconciled,
period,
]);
// Fetch transactions before startDate for initial balance calculation
const { data: beforeStartDateData } = useTransactions(
beforeStartDateParams,
!!metadata && period !== "all" && !!startDate,
);
// Fetch all filtered transactions for chart
const { data: transactionsData, isLoading } = useTransactions(
chartParams,
!!metadata,
);
// Calculate balance chart data
const chartData = useMemo(() => {
if (!transactionsData || !metadata) {
return {
aggregatedData: [],
perAccountData: [],
};
}
const transactions = transactionsData.transactions;
const accounts = metadata.accounts;
// Sort transactions by date
const sortedTransactions = [...transactions].sort(
(a, b) => new Date(a.date).getTime() - new Date(b.date).getTime(),
);
// Calculate starting balance: initialBalance + transactions before startDate
let runningBalance = 0;
const accountsToUse = selectedAccounts.includes("all")
? accounts
: accounts.filter((acc: Account) => selectedAccounts.includes(acc.id));
// Start with initial balances
runningBalance = accountsToUse.reduce(
(sum: number, acc: Account) => sum + (acc.initialBalance || 0),
0,
);
// Add transactions before startDate if we have them
if (beforeStartDateData?.transactions) {
const beforeStartTransactions = beforeStartDateData.transactions.filter(
(t) => {
const transactionDate = new Date(t.date);
return transactionDate < startDate;
},
);
beforeStartTransactions.forEach((t) => {
runningBalance += t.amount;
});
}
const aggregatedBalanceByDate = new Map<string, number>();
// Calculate balance evolution
sortedTransactions.forEach((t) => {
runningBalance += t.amount;
aggregatedBalanceByDate.set(t.date, runningBalance);
});
const aggregatedBalanceData: BalanceChartDataPoint[] = Array.from(
aggregatedBalanceByDate.entries(),
).map(([date, balance]) => ({
date: new Date(date).toLocaleDateString("fr-FR", {
day: "2-digit",
month: "short",
year: "numeric",
}),
solde: Math.round(balance),
}));
// Per account balance calculation
const accountBalances = new Map<string, Map<string, number>>();
accounts.forEach((account: Account) => {
accountBalances.set(account.id, new Map());
});
// Calculate running balance per account
const accountRunningBalances = new Map<string, number>();
accounts.forEach((account: Account) => {
accountRunningBalances.set(account.id, account.initialBalance || 0);
});
// Add transactions before startDate per account
if (beforeStartDateData?.transactions) {
const beforeStartTransactions = beforeStartDateData.transactions.filter(
(t) => {
const transactionDate = new Date(t.date);
return transactionDate < startDate;
},
);
beforeStartTransactions.forEach((t) => {
const currentBalance = accountRunningBalances.get(t.accountId) || 0;
accountRunningBalances.set(t.accountId, currentBalance + t.amount);
});
}
// Filter transactions by account if needed
const transactionsForAccounts = selectedAccounts.includes("all")
? sortedTransactions
: sortedTransactions.filter((t) =>
selectedAccounts.includes(t.accountId),
);
transactionsForAccounts.forEach((t) => {
const currentBalance = accountRunningBalances.get(t.accountId) || 0;
const newBalance = currentBalance + t.amount;
accountRunningBalances.set(t.accountId, newBalance);
const accountDates = accountBalances.get(t.accountId);
if (accountDates) {
accountDates.set(t.date, newBalance);
}
});
// Merge all dates and create data points
const allDates = new Set<string>();
accountBalances.forEach((dates) => {
dates.forEach((_, date) => allDates.add(date));
});
const sortedDates = Array.from(allDates).sort();
const lastBalances = new Map<string, number>();
accounts.forEach((account: Account) => {
// Start with initial balance + transactions before startDate
let accountStartingBalance = account.initialBalance || 0;
if (beforeStartDateData?.transactions) {
const beforeStartTransactions = beforeStartDateData.transactions.filter(
(t) => {
const transactionDate = new Date(t.date);
return transactionDate < startDate && t.accountId === account.id;
},
);
beforeStartTransactions.forEach((t) => {
accountStartingBalance += t.amount;
});
}
lastBalances.set(account.id, accountStartingBalance);
});
const perAccountBalanceData: BalanceChartDataPoint[] = sortedDates.map(
(date) => {
const point: BalanceChartDataPoint = {
date: new Date(date).toLocaleDateString("fr-FR", {
day: "2-digit",
month: "short",
year: "numeric",
}),
};
accounts.forEach((account: Account) => {
const accountDates = accountBalances.get(account.id);
if (accountDates?.has(date)) {
lastBalances.set(account.id, accountDates.get(date)!);
}
point[account.id] = Math.round(lastBalances.get(account.id) || 0);
});
return point;
},
);
return {
aggregatedData: aggregatedBalanceData,
perAccountData: perAccountBalanceData,
};
}, [
transactionsData,
beforeStartDateData,
metadata,
selectedAccounts,
startDate,
]);
return {
aggregatedData: chartData.aggregatedData,
perAccountData: chartData.perAccountData,
accounts: metadata?.accounts || [],
isLoading,
};
}

View File

@@ -0,0 +1,224 @@
"use client";
import { useMemo } from "react";
import { useTransactions } from "@/lib/hooks";
import { useBankingMetadata } from "@/lib/hooks";
import type { TransactionsPaginatedParams } from "@/services/banking.service";
import type { Category } from "@/lib/types";
interface MonthlyChartData {
month: string;
revenus: number;
depenses: number;
solde: number;
}
interface CategoryChartData {
name: string;
value: number;
color: string;
icon: string;
categoryId: string | null;
}
interface UseTransactionsChartDataParams {
selectedAccounts: string[];
selectedCategories: string[];
period: "1month" | "3months" | "6months" | "12months" | "custom" | "all";
customStartDate?: Date;
customEndDate?: Date;
showReconciled: string;
searchQuery: string;
}
export function useTransactionsChartData({
selectedAccounts,
selectedCategories,
period,
customStartDate,
customEndDate,
showReconciled,
searchQuery,
}: UseTransactionsChartDataParams) {
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)
const chartParams = useMemo<TransactionsPaginatedParams>(() => {
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];
}
if (!selectedAccounts.includes("all")) {
params.accountIds = selectedAccounts;
}
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,
selectedAccounts,
selectedCategories,
searchQuery,
showReconciled,
period,
]);
// Fetch all filtered transactions for chart
const { data: transactionsData, isLoading } = useTransactions(
chartParams,
!!metadata,
);
// Calculate monthly chart data
const monthlyData = useMemo(() => {
if (!transactionsData || !metadata) {
return [];
}
const transactions = transactionsData.transactions;
// Monthly breakdown
const monthlyMap = new Map<string, { income: number; expenses: number }>();
transactions.forEach((t) => {
const monthKey = t.date.substring(0, 7);
const current = monthlyMap.get(monthKey) || { income: 0, expenses: 0 };
if (t.amount >= 0) {
current.income += t.amount;
} else {
current.expenses += Math.abs(t.amount);
}
monthlyMap.set(monthKey, current);
});
// Format months with year: use short format for better readability
const sortedMonths = Array.from(monthlyMap.entries()).sort((a, b) =>
a[0].localeCompare(b[0]),
);
const monthlyChartData: MonthlyChartData[] = sortedMonths.map(
([monthKey, values]) => {
const date = new Date(monthKey + "-01");
// Format: "janv. 24" instead of "janv. 2024" for compactness
const monthLabel = date.toLocaleDateString("fr-FR", {
month: "short",
});
const yearShort = date.getFullYear().toString().slice(-2);
return {
month: `${monthLabel} ${yearShort}`,
revenus: values.income,
depenses: values.expenses,
solde: values.income - values.expenses,
};
},
);
return monthlyChartData;
}, [transactionsData, metadata]);
// Calculate category chart data (expenses only)
const categoryData = useMemo(() => {
if (!transactionsData || !metadata) {
return [];
}
const transactions = transactionsData.transactions;
const categoryTotals = new Map<string, number>();
transactions
.filter((t) => t.amount < 0)
.forEach((t) => {
const catId = t.categoryId || "uncategorized";
const current = categoryTotals.get(catId) || 0;
categoryTotals.set(catId, current + Math.abs(t.amount));
});
const categoryChartData: CategoryChartData[] = Array.from(
categoryTotals.entries(),
)
.map(([categoryId, total]) => {
const category = metadata.categories.find(
(c: Category) => c.id === categoryId,
);
return {
name: category?.name || "Non catégorisé",
value: Math.round(total),
color: category?.color || "#94a3b8",
icon: category?.icon || "HelpCircle",
categoryId: categoryId === "uncategorized" ? null : categoryId,
};
})
.sort((a, b) => b.value - a.value);
return categoryChartData;
}, [transactionsData, metadata]);
// Calculate total amount and count from all filtered transactions
const totalAmount = useMemo(() => {
if (!transactionsData) return 0;
return transactionsData.transactions.reduce((sum, t) => sum + t.amount, 0);
}, [transactionsData]);
const totalCount = useMemo(() => {
return transactionsData?.total || 0;
}, [transactionsData?.total]);
return {
monthlyData,
categoryData,
isLoading,
totalAmount,
totalCount,
transactions: transactionsData?.transactions || [],
};
}

View File

@@ -0,0 +1,108 @@
"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<TransactionsPaginatedParams>(() => {
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,
};
}

View File

@@ -0,0 +1,104 @@
"use client";
import { useMemo } from "react";
import { useTransactions } from "@/lib/hooks";
import { useBankingMetadata } from "@/lib/hooks";
import type { TransactionsPaginatedParams } from "@/services/banking.service";
interface UseTransactionsForCategoryFilterParams {
selectedAccounts: string[];
period: "1month" | "3months" | "6months" | "12months" | "custom" | "all";
customStartDate?: Date;
customEndDate?: Date;
showReconciled: string;
searchQuery: string;
}
/**
* Hook to fetch transactions filtered by accounts, period, search, reconciled
* but NOT by categories. Used for displaying transaction counts in category filter.
*/
export function useTransactionsForCategoryFilter({
selectedAccounts,
period,
customStartDate,
customEndDate,
showReconciled,
searchQuery,
}: UseTransactionsForCategoryFilterParams) {
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 category filter)
const filterParams = useMemo<TransactionsPaginatedParams>(() => {
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];
}
if (!selectedAccounts.includes("all")) {
params.accountIds = selectedAccounts;
}
// NOTE: We intentionally don't filter by categories here
if (searchQuery) {
params.search = searchQuery;
}
if (showReconciled !== "all") {
params.isReconciled = showReconciled === "reconciled";
}
return params;
}, [
startDate,
endDate,
selectedAccounts,
searchQuery,
showReconciled,
period,
]);
// Fetch all filtered transactions (without category filter)
const { data: transactionsData, isLoading } = useTransactions(
filterParams,
!!metadata,
);
return {
transactions: transactionsData?.transactions || [],
isLoading,
};
}

View File

@@ -7,7 +7,9 @@ import {
useTransactions,
useDuplicateIds,
} from "@/lib/hooks";
import { useLocalStorage } from "@/hooks/use-local-storage";
import type { TransactionsPaginatedParams } from "@/services/banking.service";
import type { Category } from "@/lib/types";
type SortField = "date" | "amount" | "description";
type SortOrder = "asc" | "desc";
@@ -29,7 +31,10 @@ export function useTransactionsPage() {
"all",
]);
const [showReconciled, setShowReconciled] = useState<string>("all");
const [period, setPeriod] = useState<Period>("all");
const [period, setPeriod] = useLocalStorage<Period>(
"transactions-period",
"3months",
);
const [customStartDate, setCustomStartDate] = useState<Date | undefined>(
undefined,
);
@@ -73,16 +78,36 @@ export function useTransactionsPage() {
useEffect(() => {
const categoryIdsParam = searchParams.get("categoryIds");
const includeUncategorizedParam = searchParams.get("includeUncategorized");
if (categoryIdsParam) {
if (categoryIdsParam && metadata) {
const categoryIds = categoryIdsParam.split(",");
setSelectedCategories(categoryIds);
// Expand parent categories to include their children
const expandedCategoryIds = new Set<string>(categoryIds);
categoryIds.forEach((categoryId) => {
// Check if this is a parent category
const category = metadata.categories.find(
(c: Category) => c.id === categoryId,
);
if (category && category.parentId === null) {
// Find all children of this parent
const children = metadata.categories.filter(
(c: Category) => c.parentId === categoryId,
);
children.forEach((child: Category) => {
expandedCategoryIds.add(child.id);
});
}
});
setSelectedCategories(Array.from(expandedCategoryIds));
setPage(0);
} else if (includeUncategorizedParam === "true") {
setSelectedCategories(["uncategorized"]);
setPage(0);
}
}, [searchParams]);
}, [searchParams, metadata]);
// Calculate start date based on period
const startDate = useMemo(() => {
@@ -183,15 +208,18 @@ export function useTransactionsPage() {
setPage(0);
}, []);
const handlePeriodChange = useCallback((p: Period) => {
setPeriod(p);
setPage(0);
if (p !== "custom") {
setIsCustomDatePickerOpen(false);
} else {
setIsCustomDatePickerOpen(true);
}
}, []);
const handlePeriodChange = useCallback(
(p: Period) => {
setPeriod(p);
setPage(0);
if (p !== "custom") {
setIsCustomDatePickerOpen(false);
} else {
setIsCustomDatePickerOpen(true);
}
},
[setPeriod],
);
const handleCustomStartDateChange = useCallback((date: Date | undefined) => {
setCustomStartDate(date);

6735
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@@ -4,8 +4,12 @@ async function main() {
const accountNumbers = process.argv.slice(2);
if (accountNumbers.length === 0) {
console.error("Usage: tsx scripts/fix-account-balances.ts <accountNumber1> [accountNumber2] ...");
console.error("Exemple: tsx scripts/fix-account-balances.ts 0748461N022 7555880857A");
console.error(
"Usage: tsx scripts/fix-account-balances.ts <accountNumber1> [accountNumber2] ...",
);
console.error(
"Exemple: tsx scripts/fix-account-balances.ts 0748461N022 7555880857A",
);
process.exit(1);
}
@@ -47,7 +51,9 @@ async function main() {
console.log(` Balance calculée: ${calculatedBalance}`);
if (Math.abs(account.balance - calculatedBalance) > 0.01) {
console.log(`\n⚠ Différence détectée: ${Math.abs(account.balance - calculatedBalance).toFixed(2)}`);
console.log(
`\n⚠ Différence détectée: ${Math.abs(account.balance - calculatedBalance).toFixed(2)}`,
);
console.log(`Mise à jour du solde...`);
await prisma.account.update({
@@ -68,9 +74,7 @@ async function main() {
await prisma.$disconnect();
}
main()
.catch((e) => {
console.error("Erreur:", e);
process.exit(1);
});
main().catch((e) => {
console.error("Erreur:", e);
process.exit(1);
});

View File

@@ -4,7 +4,9 @@ async function main() {
const accountNumber = process.argv[2];
if (!accountNumber) {
console.error("Usage: tsx scripts/merge-duplicate-accounts.ts <accountNumber>");
console.error(
"Usage: tsx scripts/merge-duplicate-accounts.ts <accountNumber>",
);
process.exit(1);
}
@@ -52,11 +54,19 @@ async function main() {
// Le compte avec bankId numérique (pas "FR") est le bon - le garder comme principal
// Si pas de bankId numérique, garder le plus récent
const primaryAccount = accounts.find(acc => acc.bankId !== "FR" && acc.bankId !== "") || accounts[0];
const accountsToMerge = accounts.filter(acc => acc.id !== primaryAccount.id);
const primaryAccount =
accounts.find((acc) => acc.bankId !== "FR" && acc.bankId !== "") ||
accounts[0];
const accountsToMerge = accounts.filter(
(acc) => acc.id !== primaryAccount.id,
);
console.log(`\nCompte principal (conservé): ${primaryAccount.id} (bankId: ${primaryAccount.bankId})`);
console.log(`Comptes à fusionner: ${accountsToMerge.map((a) => `${a.id} (bankId: ${a.bankId})`).join(", ")}\n`);
console.log(
`\nCompte principal (conservé): ${primaryAccount.id} (bankId: ${primaryAccount.bankId})`,
);
console.log(
`Comptes à fusionner: ${accountsToMerge.map((a) => `${a.id} (bankId: ${a.bankId})`).join(", ")}\n`,
);
// Calculer l'initialBalance total (somme des initialBalance)
const totalInitialBalance = accounts.reduce(
@@ -111,7 +121,9 @@ async function main() {
0,
);
console.log(`Balance calculée à partir des transactions: ${calculatedBalance}`);
console.log(
`Balance calculée à partir des transactions: ${calculatedBalance}`,
);
// Mettre à jour la balance du compte principal
// Garder le bankId du compte principal (celui qui est correct)
@@ -125,12 +137,14 @@ async function main() {
// Garder le bankId du compte principal (le bon)
bankId: primaryAccount.bankId,
// Garder le dernier import le plus récent parmi tous les comptes
lastImport:
accounts.reduce((latest, acc) => {
lastImport: accounts.reduce(
(latest, acc) => {
if (!acc.lastImport) return latest;
if (!latest) return acc.lastImport;
return acc.lastImport > latest ? acc.lastImport : latest;
}, null as string | null),
},
null as string | null,
),
},
});
@@ -152,7 +166,9 @@ async function main() {
if (finalAccount) {
console.log(`\nVérification finale:`);
console.log(` - Transactions dans le compte: ${finalAccount.transactions.length}`);
console.log(
` - Transactions dans le compte: ${finalAccount.transactions.length}`,
);
console.log(` - Balance: ${finalAccount.balance}`);
console.log(` - Bank ID: ${finalAccount.bankId}`);
}
@@ -160,9 +176,7 @@ async function main() {
await prisma.$disconnect();
}
main()
.catch((e) => {
console.error("Erreur:", e);
process.exit(1);
});
main().catch((e) => {
console.error("Erreur:", e);
process.exit(1);
});

View File

@@ -396,7 +396,9 @@ export const bankingService = {
});
return accounts.map(
(a): Account & { transactionCount: number; calculatedBalance: number } => ({
(
a,
): Account & { transactionCount: number; calculatedBalance: number } => ({
id: a.id,
name: a.name,
bankId: a.bankId,

View File

@@ -1,125 +0,0 @@
@import "tailwindcss";
@import "tw-animate-css";
@custom-variant dark (&:is(.dark *));
:root {
--background: oklch(1 0 0);
--foreground: oklch(0.145 0 0);
--card: oklch(1 0 0);
--card-foreground: oklch(0.145 0 0);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.145 0 0);
--primary: oklch(0.205 0 0);
--primary-foreground: oklch(0.985 0 0);
--secondary: oklch(0.97 0 0);
--secondary-foreground: oklch(0.205 0 0);
--muted: oklch(0.97 0 0);
--muted-foreground: oklch(0.556 0 0);
--accent: oklch(0.97 0 0);
--accent-foreground: oklch(0.205 0 0);
--destructive: oklch(0.577 0.245 27.325);
--destructive-foreground: oklch(0.577 0.245 27.325);
--border: oklch(0.922 0 0);
--input: oklch(0.922 0 0);
--ring: oklch(0.708 0 0);
--chart-1: oklch(0.646 0.222 41.116);
--chart-2: oklch(0.6 0.118 184.704);
--chart-3: oklch(0.398 0.07 227.392);
--chart-4: oklch(0.828 0.189 84.429);
--chart-5: oklch(0.769 0.188 70.08);
--radius: 0.625rem;
--sidebar: oklch(0.985 0 0);
--sidebar-foreground: oklch(0.145 0 0);
--sidebar-primary: oklch(0.205 0 0);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.97 0 0);
--sidebar-accent-foreground: oklch(0.205 0 0);
--sidebar-border: oklch(0.922 0 0);
--sidebar-ring: oklch(0.708 0 0);
}
.dark {
--background: oklch(0.145 0 0);
--foreground: oklch(0.985 0 0);
--card: oklch(0.145 0 0);
--card-foreground: oklch(0.985 0 0);
--popover: oklch(0.145 0 0);
--popover-foreground: oklch(0.985 0 0);
--primary: oklch(0.985 0 0);
--primary-foreground: oklch(0.205 0 0);
--secondary: oklch(0.269 0 0);
--secondary-foreground: oklch(0.985 0 0);
--muted: oklch(0.269 0 0);
--muted-foreground: oklch(0.708 0 0);
--accent: oklch(0.269 0 0);
--accent-foreground: oklch(0.985 0 0);
--destructive: oklch(0.396 0.141 25.723);
--destructive-foreground: oklch(0.637 0.237 25.331);
--border: oklch(0.269 0 0);
--input: oklch(0.269 0 0);
--ring: oklch(0.439 0 0);
--chart-1: oklch(0.488 0.243 264.376);
--chart-2: oklch(0.696 0.17 162.48);
--chart-3: oklch(0.769 0.188 70.08);
--chart-4: oklch(0.627 0.265 303.9);
--chart-5: oklch(0.645 0.246 16.439);
--sidebar: oklch(0.205 0 0);
--sidebar-foreground: oklch(0.985 0 0);
--sidebar-primary: oklch(0.488 0.243 264.376);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.269 0 0);
--sidebar-accent-foreground: oklch(0.985 0 0);
--sidebar-border: oklch(0.269 0 0);
--sidebar-ring: oklch(0.439 0 0);
}
@theme inline {
--font-sans: "Geist", "Geist Fallback";
--font-mono: "Geist Mono", "Geist Mono Fallback";
--color-background: var(--background);
--color-foreground: var(--foreground);
--color-card: var(--card);
--color-card-foreground: var(--card-foreground);
--color-popover: var(--popover);
--color-popover-foreground: var(--popover-foreground);
--color-primary: var(--primary);
--color-primary-foreground: var(--primary-foreground);
--color-secondary: var(--secondary);
--color-secondary-foreground: var(--secondary-foreground);
--color-muted: var(--muted);
--color-muted-foreground: var(--muted-foreground);
--color-accent: var(--accent);
--color-accent-foreground: var(--accent-foreground);
--color-destructive: var(--destructive);
--color-destructive-foreground: var(--destructive-foreground);
--color-border: var(--border);
--color-input: var(--input);
--color-ring: var(--ring);
--color-chart-1: var(--chart-1);
--color-chart-2: var(--chart-2);
--color-chart-3: var(--chart-3);
--color-chart-4: var(--chart-4);
--color-chart-5: var(--chart-5);
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
--color-sidebar: var(--sidebar);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-ring: var(--sidebar-ring);
}
@layer base {
* {
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground;
}
}