feat: implement bulk account deletion and enhance account management with folder organization and drag-and-drop functionality

This commit is contained in:
Julien Froidefond
2025-11-30 12:00:29 +01:00
parent d663fbcbd0
commit c26ba9ddc6
16 changed files with 1188 additions and 261 deletions

View File

@@ -2,11 +2,15 @@
import { useState } from "react";
import { PageLayout, LoadingState, PageHeader } from "@/components/layout";
import { AccountCard, AccountEditDialog } from "@/components/accounts";
import {
AccountCard,
AccountEditDialog,
AccountBulkActions,
} from "@/components/accounts";
import { useBankingData } from "@/lib/hooks";
import { updateAccount, deleteAccount } from "@/lib/store-db";
import { Card, CardContent } from "@/components/ui/card";
import { Building2 } from "lucide-react";
import { Building2, Folder } from "lucide-react";
import type { Account } from "@/lib/types";
import { cn } from "@/lib/utils";
@@ -14,6 +18,9 @@ export default function AccountsPage() {
const { data, isLoading, refresh } = useBankingData();
const [editingAccount, setEditingAccount] = useState<Account | null>(null);
const [isDialogOpen, setIsDialogOpen] = useState(false);
const [selectedAccounts, setSelectedAccounts] = useState<Set<string>>(
new Set(),
);
const [formData, setFormData] = useState({
name: "",
type: "CHECKING" as Account["type"],
@@ -76,12 +83,69 @@ export default function AccountsPage() {
}
};
const handleBulkDelete = async () => {
const count = selectedAccounts.size;
if (
!confirm(
`Supprimer ${count} compte${count > 1 ? "s" : ""} et toutes leurs transactions ?`,
)
)
return;
try {
const ids = Array.from(selectedAccounts);
const response = await fetch(
`/api/banking/accounts?ids=${ids.join(",")}`,
{
method: "DELETE",
},
);
if (!response.ok) {
throw new Error("Failed to delete accounts");
}
setSelectedAccounts(new Set());
refresh();
} catch (error) {
console.error("Error deleting accounts:", error);
alert("Erreur lors de la suppression des comptes");
}
};
const toggleSelectAccount = (accountId: string, selected: boolean) => {
const newSelected = new Set(selectedAccounts);
if (selected) {
newSelected.add(accountId);
} else {
newSelected.delete(accountId);
}
setSelectedAccounts(newSelected);
};
const getTransactionCount = (accountId: string) => {
return data.transactions.filter((t) => t.accountId === accountId).length;
};
const totalBalance = data.accounts.reduce((sum, a) => sum + a.balance, 0);
// Grouper les comptes par folder
const accountsByFolder = data.accounts.reduce(
(acc, account) => {
const folderId = account.folderId || "no-folder";
if (!acc[folderId]) {
acc[folderId] = [];
}
acc[folderId].push(account);
return acc;
},
{} as Record<string, Account[]>,
);
// Obtenir les folders racine (sans parent) et les trier par nom
const rootFolders = data.folders
.filter((f) => !f.parentId)
.sort((a, b) => a.name.localeCompare(b.name));
return (
<PageLayout>
<PageHeader
@@ -114,23 +178,110 @@ export default function AccountsPage() {
</CardContent>
</Card>
) : (
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
{data.accounts.map((account) => {
const folder = data.folders.find((f) => f.id === account.folderId);
<>
<AccountBulkActions
selectedCount={selectedAccounts.size}
onDelete={handleBulkDelete}
/>
<div className="space-y-6">
{/* Afficher d'abord les comptes sans dossier */}
{accountsByFolder["no-folder"] &&
accountsByFolder["no-folder"].length > 0 && (
<div>
<div className="flex items-center gap-2 mb-4">
<Folder className="w-5 h-5 text-muted-foreground" />
<h2 className="text-lg font-semibold">Sans dossier</h2>
<span className="text-sm text-muted-foreground">
({accountsByFolder["no-folder"].length})
</span>
</div>
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
{accountsByFolder["no-folder"].map((account) => {
const folder = data.folders.find(
(f) => f.id === account.folderId,
);
return (
<AccountCard
key={account.id}
account={account}
folder={folder}
transactionCount={getTransactionCount(account.id)}
onEdit={handleEdit}
onDelete={handleDelete}
formatCurrency={formatCurrency}
/>
);
})}
</div>
return (
<AccountCard
key={account.id}
account={account}
folder={folder}
transactionCount={getTransactionCount(account.id)}
onEdit={handleEdit}
onDelete={handleDelete}
formatCurrency={formatCurrency}
isSelected={selectedAccounts.has(account.id)}
onSelect={toggleSelectAccount}
/>
);
})}
</div>
</div>
)}
{/* Afficher les comptes groupés par folder */}
{rootFolders.map((folder) => {
const folderAccounts = accountsByFolder[folder.id] || [];
if (folderAccounts.length === 0) return null;
const folderBalance = folderAccounts.reduce(
(sum, a) => sum + a.balance,
0,
);
return (
<div key={folder.id}>
<div className="flex items-center gap-2 mb-4">
<div
className="w-5 h-5 rounded flex items-center justify-center"
style={{ backgroundColor: `${folder.color}20` }}
>
<Folder
className="w-4 h-4"
style={{ color: folder.color }}
/>
</div>
<h2 className="text-lg font-semibold">{folder.name}</h2>
<span className="text-sm text-muted-foreground">
({folderAccounts.length})
</span>
<span
className={cn(
"text-sm font-semibold tabular-nums ml-auto",
folderBalance >= 0
? "text-emerald-600"
: "text-red-600",
)}
>
{formatCurrency(folderBalance)}
</span>
</div>
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
{folderAccounts.map((account) => {
const accountFolder = data.folders.find(
(f) => f.id === account.folderId,
);
return (
<AccountCard
key={account.id}
account={account}
folder={accountFolder}
transactionCount={getTransactionCount(account.id)}
onEdit={handleEdit}
onDelete={handleDelete}
formatCurrency={formatCurrency}
isSelected={selectedAccounts.has(account.id)}
onSelect={toggleSelectAccount}
/>
);
})}
</div>
</div>
);
})}
</div>
</>
)}
<AccountEditDialog

View File

@@ -44,6 +44,20 @@ export async function DELETE(request: Request) {
try {
const { searchParams } = new URL(request.url);
const id = searchParams.get("id");
const ids = searchParams.get("ids");
if (ids) {
// Multiple deletion
const accountIds = ids.split(",").filter(Boolean);
if (accountIds.length === 0) {
return NextResponse.json(
{ error: "At least one account ID is required" },
{ status: 400 },
);
}
await accountService.deleteMany(accountIds);
return NextResponse.json({ success: true, count: accountIds.length });
}
if (!id) {
return NextResponse.json(

View File

@@ -1,6 +1,17 @@
"use client";
import { useState } from "react";
import {
DndContext,
DragEndEvent,
DragOverlay,
DragStartEvent,
PointerSensor,
useSensor,
useSensors,
closestCenter,
} from "@dnd-kit/core";
import { SortableContext, verticalListSortingStrategy } from "@dnd-kit/sortable";
import { PageLayout, LoadingState, PageHeader } from "@/components/layout";
import {
FolderTreeItem,
@@ -28,6 +39,7 @@ export default function FoldersPage() {
parentId: "folder-root" as string | null,
color: "#6366f1",
});
const [activeId, setActiveId] = useState<string | null>(null);
// Account editing state
const [isAccountDialogOpen, setIsAccountDialogOpen] = useState(false);
@@ -38,6 +50,14 @@ export default function FoldersPage() {
folderId: "folder-root",
});
const sensors = useSensors(
useSensor(PointerSensor, {
activationConstraint: {
distance: 8,
},
})
);
if (isLoading || !data) {
return <LoadingState />;
}
@@ -144,6 +164,87 @@ export default function FoldersPage() {
}
};
const handleDragStart = (event: DragStartEvent) => {
setActiveId(event.active.id as string);
};
const handleDragEnd = async (event: DragEndEvent) => {
const { active, over } = event;
setActiveId(null);
if (!over || active.id === over.id) return;
const activeId = active.id as string;
const overId = over.id as string;
// Déplacer un compte vers un dossier
if (activeId.startsWith("account-")) {
const accountId = activeId.replace("account-", "");
let targetFolderId: string | null = null;
if (overId.startsWith("folder-")) {
const folderId = overId.replace("folder-", "");
targetFolderId = folderId === "folder-root" ? null : folderId;
} else if (overId.startsWith("account-")) {
// Déplacer vers le dossier du compte cible
const targetAccountId = overId.replace("account-", "");
const targetAccount = data.accounts.find((a) => a.id === targetAccountId);
if (targetAccount) {
targetFolderId = targetAccount.folderId;
}
}
if (targetFolderId !== undefined) {
try {
const account = data.accounts.find((a) => a.id === accountId);
if (account) {
await updateAccount({
...account,
folderId: targetFolderId,
});
refresh();
}
} catch (error) {
console.error("Error moving account:", error);
alert("Erreur lors du déplacement du compte");
}
}
}
// Déplacer un dossier vers un autre dossier (changer le parent)
if (activeId.startsWith("folder-") && overId.startsWith("folder-")) {
const folderId = activeId.replace("folder-", "");
const targetFolderId = overId.replace("folder-", "");
// Empêcher de déplacer un dossier dans lui-même ou ses enfants
const folder = data.folders.find((f) => f.id === folderId);
if (!folder) return;
const isDescendant = (parentId: string, childId: string): boolean => {
const child = data.folders.find((f) => f.id === childId);
if (!child || !child.parentId) return false;
if (child.parentId === parentId) return true;
return isDescendant(parentId, child.parentId);
};
if (folderId === targetFolderId || isDescendant(folderId, targetFolderId)) {
return; // Ne pas permettre de déplacer un dossier dans lui-même ou ses descendants
}
try {
const newParentId = targetFolderId === "folder-root" ? null : targetFolderId;
await updateFolder({
...folder,
parentId: newParentId,
});
refresh();
} catch (error) {
console.error("Error moving folder:", error);
alert("Erreur lors du déplacement du dossier");
}
}
};
return (
<PageLayout>
<PageHeader
@@ -162,21 +263,55 @@ export default function FoldersPage() {
<CardTitle>Arborescence des comptes</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-1">
{rootFolders.map((folder) => (
<FolderTreeItem
key={folder.id}
folder={folder}
accounts={data.accounts}
allFolders={data.folders}
level={0}
onEdit={handleEdit}
onDelete={handleDelete}
onEditAccount={handleEditAccount}
formatCurrency={formatCurrency}
/>
))}
</div>
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
onDragStart={handleDragStart}
onDragEnd={handleDragEnd}
>
<SortableContext
items={[
...rootFolders.map((f) => `folder-${f.id}`),
...data.accounts.map((a) => `account-${a.id}`),
]}
strategy={verticalListSortingStrategy}
>
<div className="space-y-1">
{rootFolders.map((folder) => (
<FolderTreeItem
key={folder.id}
folder={folder}
accounts={data.accounts}
allFolders={data.folders}
level={0}
onEdit={handleEdit}
onDelete={handleDelete}
onEditAccount={handleEditAccount}
formatCurrency={formatCurrency}
/>
))}
</div>
</SortableContext>
<DragOverlay>
{activeId ? (
<div className="opacity-50">
{activeId.startsWith("account-") ? (
<div className="p-2 bg-muted rounded">
{data.accounts.find(
(a) => a.id === activeId.replace("account-", "")
)?.name || ""}
</div>
) : (
<div className="p-2 bg-muted rounded">
{data.folders.find(
(f) => f.id === activeId.replace("folder-", "")
)?.name || ""}
</div>
)}
</div>
) : null}
</DragOverlay>
</DndContext>
</CardContent>
</Card>