refactor: standardize quotation marks across all files and improve code consistency

This commit is contained in:
Julien Froidefond
2025-11-27 11:40:30 +01:00
parent cc1e8c20a6
commit b2efade4d5
107 changed files with 9471 additions and 5952 deletions

View File

@@ -1,78 +1,134 @@
"use client"
"use client";
import { useState, useMemo } from "react"
import { Sidebar } from "@/components/dashboard/sidebar"
import { useBankingData } from "@/lib/hooks"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Badge } from "@/components/ui/badge"
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Plus, MoreVertical, Pencil, Trash2, RefreshCw, X, ChevronDown, ChevronRight, ChevronsUpDown, Search } from "lucide-react"
import { CategoryIcon } from "@/components/ui/category-icon"
import { autoCategorize, addCategory, updateCategory, deleteCategory } from "@/lib/store-db"
import type { Category } from "@/lib/types"
import { cn } from "@/lib/utils"
import { useState, useMemo } from "react";
import { Sidebar } from "@/components/dashboard/sidebar";
import { useBankingData } from "@/lib/hooks";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import {
Plus,
MoreVertical,
Pencil,
Trash2,
RefreshCw,
X,
ChevronDown,
ChevronRight,
ChevronsUpDown,
Search,
} from "lucide-react";
import { CategoryIcon } from "@/components/ui/category-icon";
import {
autoCategorize,
addCategory,
updateCategory,
deleteCategory,
} from "@/lib/store-db";
import type { Category } from "@/lib/types";
import { cn } from "@/lib/utils";
const categoryColors = [
"#22c55e", "#3b82f6", "#f59e0b", "#ec4899", "#ef4444",
"#8b5cf6", "#06b6d4", "#84cc16", "#f97316", "#6366f1",
"#14b8a6", "#f43f5e", "#64748b", "#0891b2", "#dc2626",
]
"#22c55e",
"#3b82f6",
"#f59e0b",
"#ec4899",
"#ef4444",
"#8b5cf6",
"#06b6d4",
"#84cc16",
"#f97316",
"#6366f1",
"#14b8a6",
"#f43f5e",
"#64748b",
"#0891b2",
"#dc2626",
];
export default function CategoriesPage() {
const { data, isLoading, refresh } = useBankingData()
const [isDialogOpen, setIsDialogOpen] = useState(false)
const [editingCategory, setEditingCategory] = useState<Category | null>(null)
const [expandedParents, setExpandedParents] = useState<Set<string>>(new Set())
const { data, isLoading, refresh } = useBankingData();
const [isDialogOpen, setIsDialogOpen] = useState(false);
const [editingCategory, setEditingCategory] = useState<Category | null>(null);
const [expandedParents, setExpandedParents] = useState<Set<string>>(
new Set(),
);
const [formData, setFormData] = useState({
name: "",
color: "#22c55e",
keywords: [] as string[],
parentId: null as string | null,
})
const [newKeyword, setNewKeyword] = useState("")
const [searchQuery, setSearchQuery] = useState("")
});
const [newKeyword, setNewKeyword] = useState("");
const [searchQuery, setSearchQuery] = useState("");
// Organiser les catégories par parent
const { parentCategories, childrenByParent, orphanCategories } = useMemo(() => {
if (!data?.categories) return { parentCategories: [], childrenByParent: {}, orphanCategories: [] }
const { parentCategories, childrenByParent, orphanCategories } =
useMemo(() => {
if (!data?.categories)
return {
parentCategories: [],
childrenByParent: {},
orphanCategories: [],
};
const parents = data.categories.filter((c) => c.parentId === null)
const children: Record<string, Category[]> = {}
const orphans: Category[] = []
const parents = data.categories.filter((c) => c.parentId === null);
const children: Record<string, Category[]> = {};
const orphans: Category[] = [];
// Grouper les enfants par parent
data.categories
.filter((c) => c.parentId !== null)
.forEach((child) => {
const parentExists = parents.some((p) => p.id === child.parentId)
if (parentExists) {
if (!children[child.parentId!]) {
children[child.parentId!] = []
// Grouper les enfants par parent
data.categories
.filter((c) => c.parentId !== null)
.forEach((child) => {
const parentExists = parents.some((p) => p.id === child.parentId);
if (parentExists) {
if (!children[child.parentId!]) {
children[child.parentId!] = [];
}
children[child.parentId!].push(child);
} else {
orphans.push(child);
}
children[child.parentId!].push(child)
} else {
orphans.push(child)
}
})
});
return {
parentCategories: parents,
childrenByParent: children,
orphanCategories: orphans,
}
}, [data?.categories])
return {
parentCategories: parents,
childrenByParent: children,
orphanCategories: orphans,
};
}, [data?.categories]);
// Initialiser tous les parents comme ouverts
useState(() => {
if (parentCategories.length > 0 && expandedParents.size === 0) {
setExpandedParents(new Set(parentCategories.map((p) => p.id)))
setExpandedParents(new Set(parentCategories.map((p) => p.id)));
}
})
});
if (isLoading || !data) {
return (
@@ -82,62 +138,75 @@ export default function CategoriesPage() {
<RefreshCw className="w-8 h-8 animate-spin text-muted-foreground" />
</main>
</div>
)
);
}
const formatCurrency = (amount: number) => {
return new Intl.NumberFormat("fr-FR", { style: "currency", currency: "EUR" }).format(amount)
}
return new Intl.NumberFormat("fr-FR", {
style: "currency",
currency: "EUR",
}).format(amount);
};
const getCategoryStats = (categoryId: string, includeChildren = false) => {
let categoryIds = [categoryId]
let categoryIds = [categoryId];
if (includeChildren && childrenByParent[categoryId]) {
categoryIds = [...categoryIds, ...childrenByParent[categoryId].map((c) => c.id)]
categoryIds = [
...categoryIds,
...childrenByParent[categoryId].map((c) => c.id),
];
}
const categoryTransactions = data.transactions.filter((t) => categoryIds.includes(t.categoryId || ""))
const total = categoryTransactions.reduce((sum, t) => sum + Math.abs(t.amount), 0)
const count = categoryTransactions.length
return { total, count }
}
const categoryTransactions = data.transactions.filter((t) =>
categoryIds.includes(t.categoryId || ""),
);
const total = categoryTransactions.reduce(
(sum, t) => sum + Math.abs(t.amount),
0,
);
const count = categoryTransactions.length;
return { total, count };
};
const toggleExpanded = (parentId: string) => {
const newExpanded = new Set(expandedParents)
const newExpanded = new Set(expandedParents);
if (newExpanded.has(parentId)) {
newExpanded.delete(parentId)
newExpanded.delete(parentId);
} else {
newExpanded.add(parentId)
newExpanded.add(parentId);
}
setExpandedParents(newExpanded)
}
setExpandedParents(newExpanded);
};
const expandAll = () => {
setExpandedParents(new Set(parentCategories.map((p) => p.id)))
}
setExpandedParents(new Set(parentCategories.map((p) => p.id)));
};
const collapseAll = () => {
setExpandedParents(new Set())
}
setExpandedParents(new Set());
};
const allExpanded = parentCategories.length > 0 && expandedParents.size === parentCategories.length
const allExpanded =
parentCategories.length > 0 &&
expandedParents.size === parentCategories.length;
const handleNewCategory = (parentId: string | null = null) => {
setEditingCategory(null)
setFormData({ name: "", color: "#22c55e", keywords: [], parentId })
setIsDialogOpen(true)
}
setEditingCategory(null);
setFormData({ name: "", color: "#22c55e", keywords: [], parentId });
setIsDialogOpen(true);
};
const handleEdit = (category: Category) => {
setEditingCategory(category)
setEditingCategory(category);
setFormData({
name: category.name,
color: category.color,
keywords: [...category.keywords],
parentId: category.parentId,
})
setIsDialogOpen(true)
}
});
setIsDialogOpen(true);
};
const handleSave = async () => {
try {
@@ -148,7 +217,7 @@ export default function CategoriesPage() {
color: formData.color,
keywords: formData.keywords,
parentId: formData.parentId,
})
});
} else {
await addCategory({
name: formData.name,
@@ -156,78 +225,88 @@ export default function CategoriesPage() {
keywords: formData.keywords,
icon: "tag",
parentId: formData.parentId,
})
});
}
refresh()
setIsDialogOpen(false)
refresh();
setIsDialogOpen(false);
} catch (error) {
console.error("Error saving category:", error)
alert("Erreur lors de la sauvegarde de la catégorie")
console.error("Error saving category:", error);
alert("Erreur lors de la sauvegarde de la catégorie");
}
}
};
const handleDelete = async (categoryId: string) => {
const hasChildren = childrenByParent[categoryId]?.length > 0
const hasChildren = childrenByParent[categoryId]?.length > 0;
const message = hasChildren
? "Cette catégorie a des sous-catégories. Supprimer quand même ?"
: "Supprimer cette catégorie ?"
if (!confirm(message)) return
: "Supprimer cette catégorie ?";
if (!confirm(message)) return;
try {
await deleteCategory(categoryId)
refresh()
await deleteCategory(categoryId);
refresh();
} catch (error) {
console.error("Error deleting category:", error)
alert("Erreur lors de la suppression de la catégorie")
console.error("Error deleting category:", error);
alert("Erreur lors de la suppression de la catégorie");
}
}
};
const addKeyword = () => {
if (newKeyword.trim() && !formData.keywords.includes(newKeyword.trim().toLowerCase())) {
if (
newKeyword.trim() &&
!formData.keywords.includes(newKeyword.trim().toLowerCase())
) {
setFormData({
...formData,
keywords: [...formData.keywords, newKeyword.trim().toLowerCase()],
})
setNewKeyword("")
});
setNewKeyword("");
}
}
};
const removeKeyword = (keyword: string) => {
setFormData({
...formData,
keywords: formData.keywords.filter((k) => k !== keyword),
})
}
});
};
const reApplyAutoCategories = async () => {
if (!confirm("Recatégoriser automatiquement les transactions non catégorisées ?")) return
if (
!confirm(
"Recatégoriser automatiquement les transactions non catégorisées ?",
)
)
return;
try {
const { updateTransaction } = await import("@/lib/store-db")
const uncategorized = data.transactions.filter((t) => !t.categoryId)
const { updateTransaction } = await import("@/lib/store-db");
const uncategorized = data.transactions.filter((t) => !t.categoryId);
for (const transaction of uncategorized) {
const categoryId = autoCategorize(
transaction.description + " " + (transaction.memo || ""),
data.categories
)
data.categories,
);
if (categoryId) {
await updateTransaction({ ...transaction, categoryId })
await updateTransaction({ ...transaction, categoryId });
}
}
refresh()
refresh();
} catch (error) {
console.error("Error re-categorizing:", error)
alert("Erreur lors de la recatégorisation")
console.error("Error re-categorizing:", error);
alert("Erreur lors de la recatégorisation");
}
}
};
const uncategorizedCount = data.transactions.filter((t) => !t.categoryId).length
const uncategorizedCount = data.transactions.filter(
(t) => !t.categoryId,
).length;
// Composant pour une carte de catégorie enfant
const ChildCategoryCard = ({ category }: { category: Category }) => {
const stats = getCategoryStats(category.id)
const stats = getCategoryStats(category.id);
return (
<div className="flex items-center justify-between py-1.5 px-2 rounded hover:bg-muted/50 transition-colors group">
@@ -236,21 +315,34 @@ export default function CategoriesPage() {
className="w-5 h-5 rounded-full flex items-center justify-center shrink-0"
style={{ backgroundColor: `${category.color}20` }}
>
<CategoryIcon icon={category.icon} color={category.color} size={12} />
<CategoryIcon
icon={category.icon}
color={category.color}
size={12}
/>
</div>
<span className="text-sm truncate">{category.name}</span>
<span className="text-sm text-muted-foreground shrink-0">
{stats.count} opération{stats.count > 1 ? "s" : ""} {formatCurrency(stats.total)}
{stats.count} opération{stats.count > 1 ? "s" : ""} {" "}
{formatCurrency(stats.total)}
</span>
{category.keywords.length > 0 && (
<Badge variant="outline" className="text-[10px] px-1.5 py-0 h-4 shrink-0">
<Badge
variant="outline"
className="text-[10px] px-1.5 py-0 h-4 shrink-0"
>
{category.keywords.length}
</Badge>
)}
</div>
<div className="flex items-center shrink-0 opacity-0 group-hover:opacity-100 transition-opacity">
<Button variant="ghost" size="icon" className="h-6 w-6" onClick={() => handleEdit(category)}>
<Button
variant="ghost"
size="icon"
className="h-6 w-6"
onClick={() => handleEdit(category)}
>
<Pencil className="w-3 h-3" />
</Button>
<Button
@@ -263,8 +355,8 @@ export default function CategoriesPage() {
</Button>
</div>
</div>
)
}
);
};
return (
<div className="flex h-screen bg-background">
@@ -277,7 +369,8 @@ export default function CategoriesPage() {
<h1 className="text-2xl font-bold text-foreground">Catégories</h1>
<p className="text-muted-foreground">
{parentCategories.length} catégories principales {" "}
{data.categories.length - parentCategories.length} sous-catégories
{data.categories.length - parentCategories.length}{" "}
sous-catégories
</p>
</div>
<div className="flex gap-2">
@@ -326,110 +419,141 @@ export default function CategoriesPage() {
<div className="space-y-1">
{parentCategories
.filter((parent) => {
if (!searchQuery.trim()) return true
const query = searchQuery.toLowerCase()
if (!searchQuery.trim()) return true;
const query = searchQuery.toLowerCase();
// Afficher si le parent matche
if (parent.name.toLowerCase().includes(query)) return true
if (parent.keywords.some((k) => k.toLowerCase().includes(query))) return true
if (parent.name.toLowerCase().includes(query)) return true;
if (
parent.keywords.some((k) => k.toLowerCase().includes(query))
)
return true;
// Ou si un enfant matche
const children = childrenByParent[parent.id] || []
const children = childrenByParent[parent.id] || [];
return children.some(
(c) =>
c.name.toLowerCase().includes(query) ||
c.keywords.some((k) => k.toLowerCase().includes(query))
)
c.keywords.some((k) => k.toLowerCase().includes(query)),
);
})
.map((parent) => {
const allChildren = childrenByParent[parent.id] || []
// Filtrer les enfants aussi si recherche active
const children = searchQuery.trim()
? allChildren.filter(
(c) =>
c.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
c.keywords.some((k) => k.toLowerCase().includes(searchQuery.toLowerCase())) ||
// Garder tous les enfants si le parent matche
parent.name.toLowerCase().includes(searchQuery.toLowerCase())
)
: allChildren
const stats = getCategoryStats(parent.id, true)
const isExpanded = expandedParents.has(parent.id) || (searchQuery.trim() !== "" && children.length > 0)
const allChildren = childrenByParent[parent.id] || [];
// Filtrer les enfants aussi si recherche active
const children = searchQuery.trim()
? allChildren.filter(
(c) =>
c.name
.toLowerCase()
.includes(searchQuery.toLowerCase()) ||
c.keywords.some((k) =>
k.toLowerCase().includes(searchQuery.toLowerCase()),
) ||
// Garder tous les enfants si le parent matche
parent.name
.toLowerCase()
.includes(searchQuery.toLowerCase()),
)
: allChildren;
const stats = getCategoryStats(parent.id, true);
const isExpanded =
expandedParents.has(parent.id) ||
(searchQuery.trim() !== "" && children.length > 0);
return (
<div key={parent.id} className="border rounded-lg bg-card">
<Collapsible open={isExpanded} onOpenChange={() => toggleExpanded(parent.id)}>
<div className="flex items-center justify-between px-3 py-2">
<CollapsibleTrigger asChild>
<button className="flex items-center gap-2 hover:opacity-80 transition-opacity flex-1 min-w-0">
{isExpanded ? (
<ChevronDown className="w-4 h-4 text-muted-foreground shrink-0" />
) : (
<ChevronRight className="w-4 h-4 text-muted-foreground shrink-0" />
)}
<div
className="w-7 h-7 rounded-full flex items-center justify-center shrink-0"
style={{ backgroundColor: `${parent.color}20` }}
>
<CategoryIcon icon={parent.icon} color={parent.color} size={14} />
</div>
<span className="font-medium text-sm truncate">{parent.name}</span>
<span className="text-sm text-muted-foreground shrink-0">
{children.length} {stats.count} opération{stats.count > 1 ? "s" : ""} {formatCurrency(stats.total)}
</span>
</button>
</CollapsibleTrigger>
<div className="flex items-center gap-1 shrink-0 ml-2">
<Button
variant="ghost"
size="icon"
className="h-7 w-7"
onClick={(e) => {
e.stopPropagation()
handleNewCategory(parent.id)
}}
>
<Plus className="w-4 h-4" />
</Button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon" className="h-7 w-7">
<MoreVertical className="w-4 h-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => handleEdit(parent)}>
<Pencil className="w-4 h-4 mr-2" />
Modifier
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => handleDelete(parent.id)}
className="text-red-600"
return (
<div key={parent.id} className="border rounded-lg bg-card">
<Collapsible
open={isExpanded}
onOpenChange={() => toggleExpanded(parent.id)}
>
<div className="flex items-center justify-between px-3 py-2">
<CollapsibleTrigger asChild>
<button className="flex items-center gap-2 hover:opacity-80 transition-opacity flex-1 min-w-0">
{isExpanded ? (
<ChevronDown className="w-4 h-4 text-muted-foreground shrink-0" />
) : (
<ChevronRight className="w-4 h-4 text-muted-foreground shrink-0" />
)}
<div
className="w-7 h-7 rounded-full flex items-center justify-center shrink-0"
style={{ backgroundColor: `${parent.color}20` }}
>
<Trash2 className="w-4 h-4 mr-2" />
Supprimer
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
<CategoryIcon
icon={parent.icon}
color={parent.color}
size={14}
/>
</div>
<span className="font-medium text-sm truncate">
{parent.name}
</span>
<span className="text-sm text-muted-foreground shrink-0">
{children.length} {stats.count} opération
{stats.count > 1 ? "s" : ""} {" "}
{formatCurrency(stats.total)}
</span>
</button>
</CollapsibleTrigger>
<CollapsibleContent>
{children.length > 0 ? (
<div className="px-3 pb-2 space-y-1 ml-6 border-l-2 border-muted ml-5">
{children.map((child) => (
<ChildCategoryCard key={child.id} category={child} />
))}
<div className="flex items-center gap-1 shrink-0 ml-2">
<Button
variant="ghost"
size="icon"
className="h-7 w-7"
onClick={(e) => {
e.stopPropagation();
handleNewCategory(parent.id);
}}
>
<Plus className="w-4 h-4" />
</Button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="icon"
className="h-7 w-7"
>
<MoreVertical className="w-4 h-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem
onClick={() => handleEdit(parent)}
>
<Pencil className="w-4 h-4 mr-2" />
Modifier
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => handleDelete(parent.id)}
className="text-red-600"
>
<Trash2 className="w-4 h-4 mr-2" />
Supprimer
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
) : (
<div className="px-3 pb-2 ml-11 text-xs text-muted-foreground italic">
Aucune sous-catégorie
</div>
)}
</CollapsibleContent>
</Collapsible>
</div>
)
})}
</div>
<CollapsibleContent>
{children.length > 0 ? (
<div className="px-3 pb-2 space-y-1 ml-6 border-l-2 border-muted ml-5">
{children.map((child) => (
<ChildCategoryCard
key={child.id}
category={child}
/>
))}
</div>
) : (
<div className="px-3 pb-2 ml-11 text-xs text-muted-foreground italic">
Aucune sous-catégorie
</div>
)}
</CollapsibleContent>
</Collapsible>
</div>
);
})}
{/* Catégories orphelines (sans parent valide) */}
{orphanCategories.length > 0 && (
@@ -465,14 +589,19 @@ export default function CategoriesPage() {
<Select
value={formData.parentId || "none"}
onValueChange={(value) =>
setFormData({ ...formData, parentId: value === "none" ? null : value })
setFormData({
...formData,
parentId: value === "none" ? null : value,
})
}
>
<SelectTrigger>
<SelectValue placeholder="Aucune (catégorie principale)" />
</SelectTrigger>
<SelectContent>
<SelectItem value="none">Aucune (catégorie principale)</SelectItem>
<SelectItem value="none">
Aucune (catégorie principale)
</SelectItem>
{parentCategories
.filter((p) => p.id !== editingCategory?.id)
.map((parent) => (
@@ -495,7 +624,9 @@ export default function CategoriesPage() {
<Label>Nom</Label>
<Input
value={formData.name}
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
onChange={(e) =>
setFormData({ ...formData, name: e.target.value })
}
placeholder="Ex: Alimentation"
/>
</div>
@@ -510,7 +641,8 @@ export default function CategoriesPage() {
onClick={() => setFormData({ ...formData, color })}
className={cn(
"w-8 h-8 rounded-full transition-transform",
formData.color === color && "ring-2 ring-offset-2 ring-primary scale-110"
formData.color === color &&
"ring-2 ring-offset-2 ring-primary scale-110",
)}
style={{ backgroundColor: color }}
/>
@@ -526,7 +658,9 @@ export default function CategoriesPage() {
value={newKeyword}
onChange={(e) => setNewKeyword(e.target.value)}
placeholder="Ajouter un mot-clé"
onKeyDown={(e) => e.key === "Enter" && (e.preventDefault(), addKeyword())}
onKeyDown={(e) =>
e.key === "Enter" && (e.preventDefault(), addKeyword())
}
/>
<Button type="button" onClick={addKeyword} size="icon">
<Plus className="w-4 h-4" />
@@ -557,5 +691,5 @@ export default function CategoriesPage() {
</DialogContent>
</Dialog>
</div>
)
);
}