refactor: standardize code formatting and improve consistency across various components and API routes for enhanced readability and maintainability

This commit is contained in:
Julien Froidefond
2025-12-10 14:28:05 +01:00
parent 299a66e6ff
commit f8919b19b3
19 changed files with 152 additions and 161 deletions

View File

@@ -68,7 +68,7 @@ function FolderDropZone({
<div
ref={setNodeRef}
className={cn(
isOver && "ring-2 ring-primary ring-offset-2 rounded-lg p-2"
isOver && "ring-2 ring-primary ring-offset-2 rounded-lg p-2",
)}
>
{children}
@@ -91,7 +91,7 @@ export default function AccountsPage() {
const [editingAccount, setEditingAccount] = useState<Account | null>(null);
const [isDialogOpen, setIsDialogOpen] = useState(false);
const [selectedAccounts, setSelectedAccounts] = useState<Set<string>>(
new Set()
new Set(),
);
const [formData, setFormData] = useState({
name: "",
@@ -117,7 +117,7 @@ export default function AccountsPage() {
activationConstraint: {
distance: 8,
},
})
}),
);
if (
@@ -131,7 +131,7 @@ export default function AccountsPage() {
// Convert accountsWithStats to regular accounts for compatibility
const accounts = accountsWithStats.map(
({ transactionCount: _transactionCount, ...account }) => account
({ transactionCount: _transactionCount, ...account }) => account,
);
const formatCurrency = (amount: number) => {
@@ -191,7 +191,7 @@ export default function AccountsPage() {
const count = selectedAccounts.size;
if (
!confirm(
`Supprimer ${count} compte${count > 1 ? "s" : ""} et toutes leurs transactions ?`
`Supprimer ${count} compte${count > 1 ? "s" : ""} et toutes leurs transactions ?`,
)
)
return;
@@ -202,7 +202,7 @@ export default function AccountsPage() {
`/api/banking/accounts?ids=${ids.join(",")}`,
{
method: "DELETE",
}
},
);
if (!response.ok) {
throw new Error("Failed to delete accounts");
@@ -275,7 +275,7 @@ export default function AccountsPage() {
const handleDeleteFolder = async (folderId: string) => {
if (
!confirm(
"Supprimer ce dossier ? Les comptes seront déplacés à la racine."
"Supprimer ce dossier ? Les comptes seront déplacés à la racine.",
)
)
return;
@@ -315,7 +315,7 @@ export default function AccountsPage() {
// Déplacer vers le dossier du compte cible
const targetAccountId = overId.replace("account-", "");
const targetAccount = accountsWithStats.find(
(a) => a.id === targetAccountId
(a) => a.id === targetAccountId,
);
if (targetAccount) {
targetFolderId = targetAccount.folderId;
@@ -337,7 +337,7 @@ export default function AccountsPage() {
(old: Array<Account & { transactionCount: number }> | undefined) => {
if (!old) return old;
return old.map((a) => (a.id === accountId ? updatedAccount : a));
}
},
);
// Faire la requête en arrière-plan
@@ -362,7 +362,7 @@ export default function AccountsPage() {
const totalBalance = accounts.reduce(
(sum, a) => sum + getAccountBalance(a),
0
0,
);
// Grouper les comptes par folder
@@ -375,7 +375,7 @@ export default function AccountsPage() {
acc[folderId].push(account);
return acc;
},
{} as Record<string, Account[]>
{} as Record<string, Account[]>,
);
// Obtenir les folders racine (sans parent) et les trier par nom
@@ -429,7 +429,7 @@ export default function AccountsPage() {
className={cn(
isMobile ? "text-xl" : "text-2xl",
"font-bold",
totalBalance >= 0 ? "text-emerald-600" : "text-red-600"
totalBalance >= 0 ? "text-emerald-600" : "text-red-600",
)}
>
{isMobile && (
@@ -486,17 +486,17 @@ export default function AccountsPage() {
"text-xs sm:text-sm font-semibold tabular-nums shrink-0",
accountsByFolder["no-folder"].reduce(
(sum, a) => sum + getAccountBalance(a),
0
0,
) >= 0
? "text-emerald-600"
: "text-red-600"
: "text-red-600",
)}
>
{formatCurrency(
accountsByFolder["no-folder"].reduce(
(sum, a) => sum + getAccountBalance(a),
0
)
0,
),
)}
</span>
</div>
@@ -505,7 +505,7 @@ export default function AccountsPage() {
<div className="grid gap-2 sm:gap-3 md:gap-4 grid-cols-2 sm:grid-cols-2 lg:grid-cols-3">
{accountsByFolder["no-folder"].map((account) => {
const folder = metadata.folders.find(
(f: FolderType) => f.id === account.folderId
(f: FolderType) => f.id === account.folderId,
);
return (
@@ -533,7 +533,7 @@ export default function AccountsPage() {
const folderAccounts = accountsByFolder[folder.id] || [];
const folderBalance = folderAccounts.reduce(
(sum, a) => sum + getAccountBalance(a),
0
0,
);
return (
@@ -562,7 +562,7 @@ export default function AccountsPage() {
"text-xs sm:text-sm font-semibold tabular-nums shrink-0",
folderBalance >= 0
? "text-emerald-600"
: "text-red-600"
: "text-red-600",
)}
>
{formatCurrency(folderBalance)}
@@ -622,7 +622,7 @@ export default function AccountsPage() {
<div className="grid gap-2 sm:gap-3 md:gap-4 grid-cols-2 sm:grid-cols-2 lg:grid-cols-3">
{folderAccounts.map((account) => {
const accountFolder = metadata.folders.find(
(f: FolderType) => f.id === account.folderId
(f: FolderType) => f.id === account.folderId,
);
return (
@@ -666,7 +666,7 @@ export default function AccountsPage() {
<Card>
<CardContent className="p-4">
{accounts.find(
(a) => a.id === activeId.replace("account-", "")
(a) => a.id === activeId.replace("account-", ""),
)?.name || ""}
</CardContent>
</Card>

View File

@@ -23,7 +23,7 @@ export async function GET(request: NextRequest) {
console.error("Error fetching accounts:", error);
return NextResponse.json(
{ error: "Failed to fetch accounts" },
{ status: 500 }
{ status: 500 },
);
}
}
@@ -51,7 +51,7 @@ export async function POST(request: Request) {
console.error("Error creating account:", error);
return NextResponse.json(
{ error: "Failed to create account" },
{ status: 500 }
{ status: 500 },
);
}
}
@@ -79,7 +79,7 @@ export async function PUT(request: Request) {
console.error("Error updating account:", error);
return NextResponse.json(
{ error: "Failed to update account" },
{ status: 500 }
{ status: 500 },
);
}
}
@@ -99,7 +99,7 @@ export async function DELETE(request: Request) {
if (accountIds.length === 0) {
return NextResponse.json(
{ error: "At least one account ID is required" },
{ status: 400 }
{ status: 400 },
);
}
await accountService.deleteMany(accountIds);
@@ -116,14 +116,14 @@ export async function DELETE(request: Request) {
headers: {
"Cache-Control": "no-store",
},
}
},
);
}
if (!id) {
return NextResponse.json(
{ error: "Account ID is required" },
{ status: 400 }
{ status: 400 },
);
}
@@ -141,13 +141,13 @@ export async function DELETE(request: Request) {
headers: {
"Cache-Control": "no-store",
},
}
},
);
} catch (error) {
console.error("Error deleting account:", error);
return NextResponse.json(
{ error: "Failed to delete account" },
{ status: 500 }
{ status: 500 },
);
}
}

View File

@@ -23,7 +23,7 @@ export async function GET(request: NextRequest) {
console.error("Error fetching category stats:", error);
return NextResponse.json(
{ error: "Failed to fetch category stats" },
{ status: 500 }
{ status: 500 },
);
}
}
@@ -50,7 +50,7 @@ export async function POST(request: Request) {
console.error("Error creating category:", error);
return NextResponse.json(
{ error: "Failed to create category" },
{ status: 500 }
{ status: 500 },
);
}
}
@@ -78,7 +78,7 @@ export async function PUT(request: Request) {
console.error("Error updating category:", error);
return NextResponse.json(
{ error: "Failed to update category" },
{ status: 500 }
{ status: 500 },
);
}
}
@@ -94,7 +94,7 @@ export async function DELETE(request: Request) {
if (!id) {
return NextResponse.json(
{ error: "Category ID is required" },
{ status: 400 }
{ status: 400 },
);
}
@@ -112,13 +112,13 @@ export async function DELETE(request: Request) {
headers: {
"Cache-Control": "no-store",
},
}
},
);
} catch (error) {
console.error("Error deleting category:", error);
return NextResponse.json(
{ error: "Failed to delete category" },
{ status: 500 }
{ status: 500 },
);
}
}

View File

@@ -17,4 +17,3 @@ export async function GET() {
);
}
}

View File

@@ -23,7 +23,7 @@ export async function POST(request: Request) {
console.error("Error creating folder:", error);
return NextResponse.json(
{ error: "Failed to create folder" },
{ status: 500 }
{ status: 500 },
);
}
}
@@ -48,7 +48,7 @@ export async function PUT(request: Request) {
console.error("Error updating folder:", error);
return NextResponse.json(
{ error: "Failed to update folder" },
{ status: 500 }
{ status: 500 },
);
}
}
@@ -64,7 +64,7 @@ export async function DELETE(request: Request) {
if (!id) {
return NextResponse.json(
{ error: "Folder ID is required" },
{ status: 400 }
{ status: 400 },
);
}
@@ -79,7 +79,7 @@ export async function DELETE(request: Request) {
headers: {
"Cache-Control": "no-store",
},
}
},
);
} catch (error) {
if (error instanceof FolderNotFoundError) {
@@ -88,7 +88,7 @@ export async function DELETE(request: Request) {
console.error("Error deleting folder:", error);
return NextResponse.json(
{ error: "Failed to delete folder" },
{ status: 500 }
{ status: 500 },
);
}
}

View File

@@ -31,7 +31,7 @@ export async function POST() {
headers: {
"Cache-Control": "no-store",
},
}
},
);
} catch (error) {
console.error("Error clearing categories:", error);

View File

@@ -64,7 +64,7 @@ export async function GET(request: NextRequest) {
console.error("Error fetching transactions:", error);
return NextResponse.json(
{ error: "Failed to fetch transactions" },
{ status: 500 }
{ status: 500 },
);
}
}
@@ -90,7 +90,7 @@ export async function POST(request: Request) {
console.error("Error creating transactions:", error);
return NextResponse.json(
{ error: "Failed to create transactions" },
{ status: 500 }
{ status: 500 },
);
}
}
@@ -103,7 +103,7 @@ export async function PUT(request: Request) {
const transaction: Transaction = await request.json();
const updated = await transactionService.update(
transaction.id,
transaction
transaction,
);
// Revalider le cache des pages
@@ -120,7 +120,7 @@ export async function PUT(request: Request) {
console.error("Error updating transaction:", error);
return NextResponse.json(
{ error: "Failed to update transaction" },
{ status: 500 }
{ status: 500 },
);
}
}
@@ -136,7 +136,7 @@ export async function DELETE(request: Request) {
if (!id) {
return NextResponse.json(
{ error: "Transaction ID is required" },
{ status: 400 }
{ status: 400 },
);
}
@@ -153,7 +153,7 @@ export async function DELETE(request: Request) {
headers: {
"Cache-Control": "no-store",
},
}
},
);
} catch (error) {
console.error("Error deleting transaction:", error);

View File

@@ -42,7 +42,7 @@ export default function CategoriesPage() {
const [isDialogOpen, setIsDialogOpen] = useState(false);
const [editingCategory, setEditingCategory] = useState<Category | null>(null);
const [expandedParents, setExpandedParents] = useState<Set<string>>(
new Set()
new Set(),
);
const [formData, setFormData] = useState({
name: "",
@@ -53,7 +53,7 @@ export default function CategoriesPage() {
});
const [searchQuery, setSearchQuery] = useState("");
const [recatResults, setRecatResults] = useState<RecategorizationResult[]>(
[]
[],
);
const [isRecatDialogOpen, setIsRecatDialogOpen] = useState(false);
const [isRecategorizing, setIsRecategorizing] = useState(false);
@@ -69,7 +69,7 @@ export default function CategoriesPage() {
};
const parents = metadata.categories.filter(
(c: Category) => c.parentId === null
(c: Category) => c.parentId === null,
);
const children: Record<string, Category[]> = {};
const orphans: Category[] = [];
@@ -78,7 +78,7 @@ export default function CategoriesPage() {
.filter((c: Category) => c.parentId !== null)
.forEach((child: Category) => {
const parentExists = parents.some(
(p: Category) => p.id === child.parentId
(p: Category) => p.id === child.parentId,
);
if (parentExists) {
if (!children[child.parentId!]) {
@@ -136,7 +136,7 @@ export default function CategoriesPage() {
return { total, count };
},
[categoryStats, childrenByParent]
[categoryStats, childrenByParent],
);
if (isLoadingMetadata || !metadata || isLoadingStats || !categoryStats) {
@@ -248,7 +248,7 @@ export default function CategoriesPage() {
try {
// Fetch uncategorized transactions
const uncategorizedResponse = await fetch(
"/api/banking/transactions?limit=1000&offset=0&includeUncategorized=true"
"/api/banking/transactions?limit=1000&offset=0&includeUncategorized=true",
);
if (!uncategorizedResponse.ok) {
throw new Error("Failed to fetch uncategorized transactions");
@@ -261,11 +261,11 @@ export default function CategoriesPage() {
for (const transaction of uncategorized) {
const categoryId = autoCategorize(
transaction.description + " " + (transaction.memo || ""),
metadata.categories
metadata.categories,
);
if (categoryId) {
const category = metadata.categories.find(
(c: Category) => c.id === categoryId
(c: Category) => c.id === categoryId,
);
if (category) {
results.push({ transaction, category });
@@ -299,9 +299,9 @@ export default function CategoriesPage() {
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)),
);
}
},
);
return (
@@ -346,9 +346,9 @@ export default function CategoriesPage() {
(c) =>
c.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
c.keywords.some((k) =>
k.toLowerCase().includes(searchQuery.toLowerCase())
k.toLowerCase().includes(searchQuery.toLowerCase()),
) ||
parent.name.toLowerCase().includes(searchQuery.toLowerCase())
parent.name.toLowerCase().includes(searchQuery.toLowerCase()),
)
: allChildren;
const stats = getCategoryStats(parent.id, true);
@@ -435,7 +435,7 @@ export default function CategoriesPage() {
</p>
<p className="text-xs text-muted-foreground truncate">
{new Date(result.transaction.date).toLocaleDateString(
"fr-FR"
"fr-FR",
)}
{" • "}
{new Intl.NumberFormat("fr-FR", {

View File

@@ -46,7 +46,7 @@ export default function RulesPage() {
offset: 0,
includeUncategorized: true,
},
!!metadata
!!metadata,
);
const refresh = useCallback(() => {
@@ -58,7 +58,7 @@ export default function RulesPage() {
const [filterMinCount, setFilterMinCount] = useState(2);
const [expandedGroups, setExpandedGroups] = useState<Set<string>>(new Set());
const [selectedGroup, setSelectedGroup] = useState<TransactionGroup | null>(
null
null,
);
const [isDialogOpen, setIsDialogOpen] = useState(false);
const [isAutoCategorizing, setIsAutoCategorizing] = useState(false);
@@ -89,7 +89,7 @@ export default function RulesPage() {
totalAmount: transactions.reduce((sum, t) => sum + t.amount, 0),
suggestedKeyword: suggestKeyword(descriptions),
};
}
},
);
// Filter by search query
@@ -100,7 +100,7 @@ export default function RulesPage() {
(g) =>
g.displayName.toLowerCase().includes(query) ||
g.key.includes(query) ||
g.suggestedKeyword.toLowerCase().includes(query)
g.suggestedKeyword.toLowerCase().includes(query),
);
}
@@ -169,7 +169,7 @@ export default function RulesPage() {
// 1. Add keyword to category
const category = metadata.categories.find(
(c: { id: string }) => c.id === ruleData.categoryId
(c: { id: string }) => c.id === ruleData.categoryId,
);
if (!category) {
throw new Error("Category not found");
@@ -177,7 +177,7 @@ export default function RulesPage() {
// Check if keyword already exists
const keywordExists = category.keywords.some(
(k: string) => k.toLowerCase() === ruleData.keyword.toLowerCase()
(k: string) => k.toLowerCase() === ruleData.keyword.toLowerCase(),
);
if (!keywordExists) {
@@ -195,8 +195,8 @@ export default function RulesPage() {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ id, categoryId: ruleData.categoryId }),
})
)
}),
),
);
}
@@ -204,7 +204,7 @@ export default function RulesPage() {
invalidateAllTransactionQueries(queryClient);
invalidateAllCategoryQueries(queryClient);
},
[metadata, queryClient]
[metadata, queryClient],
);
const handleAutoCategorize = useCallback(async () => {
@@ -218,7 +218,7 @@ export default function RulesPage() {
for (const transaction of uncategorized) {
const categoryId = autoCategorize(
transaction.description + " " + (transaction.memo || ""),
metadata.categories
metadata.categories,
);
if (categoryId) {
await fetch("/api/banking/transactions", {
@@ -234,7 +234,7 @@ export default function RulesPage() {
invalidateAllTransactionQueries(queryClient);
invalidateAllCategoryQueries(queryClient);
alert(
`${categorizedCount} transaction(s) catégorisée(s) automatiquement`
`${categorizedCount} transaction(s) catégorisée(s) automatiquement`,
);
} catch (error) {
console.error("Error auto-categorizing:", error);
@@ -253,8 +253,8 @@ export default function RulesPage() {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ ...t, categoryId }),
})
)
}),
),
);
// Invalider toutes les queries liées
invalidateAllTransactionQueries(queryClient);
@@ -264,7 +264,7 @@ export default function RulesPage() {
alert("Erreur lors de la catégorisation");
}
},
[queryClient]
[queryClient],
);
if (

View File

@@ -98,7 +98,7 @@ export default function TransactionsPage() {
handleBulkReconcile(reconciled, selectedTransactions);
clearSelection();
},
[handleBulkReconcile, selectedTransactions, clearSelection]
[handleBulkReconcile, selectedTransactions, clearSelection],
);
const handleBulkSetCategoryWithClear = useCallback(
@@ -106,7 +106,7 @@ export default function TransactionsPage() {
handleBulkSetCategory(categoryId, selectedTransactions);
clearSelection();
},
[handleBulkSetCategory, selectedTransactions, clearSelection]
[handleBulkSetCategory, selectedTransactions, clearSelection],
);
const filteredTransactions = transactionsData?.transactions || [];