Skip to content

Commit

Permalink
Bulk delete transaction inside the account table functionality is added
Browse files Browse the repository at this point in the history
  • Loading branch information
Priyanshu9898 committed Dec 30, 2024
1 parent b7e4ee6 commit 49fcaae
Show file tree
Hide file tree
Showing 4 changed files with 101 additions and 37 deletions.
77 changes: 77 additions & 0 deletions actions/Account.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
"use server";

import { DB } from "@/lib/prisma";
import { auth } from "@clerk/nextjs/server";
import { Decimal } from "@prisma/client/runtime/library";
import { revalidatePath } from "next/cache";

/* eslint-disable @typescript-eslint/no-explicit-any */

Expand Down Expand Up @@ -60,3 +64,76 @@ export async function getAccountDetails(acccountId: string) {
console.error(error?.message);
}
}

export async function BulkDeleteTransaction(selectedIds: string[]) {
try {
const { userId } = await auth();

if (!userId) {
throw new Error("Unauthorized!!");
}

// Get accounts
const user = await DB.user.findUnique({
where: {
clerkUserId: userId,
},
});

if (!user) {
throw new Error("User not found");
}

const transactions = await DB.transaction.findMany({
where: {
id: { in: selectedIds },
userId: user.id,
},
});

const accountBalanceChanges = transactions.reduce<{
[key: string]: Decimal;
}>((acc, transaction) => {
const change =
transaction.type === "EXPENSE"
? transaction.amount
: transaction.amount.negated();
acc[transaction.accountId] = (
acc[transaction.accountId] || new Decimal(0)
).plus(change);
return acc;
}, {});

// Delete transactions and update account balances in a transaction
await DB.$transaction(async (tx) => {
// Delete transactions
await tx.transaction.deleteMany({
where: {
id: { in: selectedIds },
userId: user.id,
},
});

// Update account balances
for (const [accountId, balanceChange] of Object.entries(
accountBalanceChanges
)) {
await tx.account.update({
where: { id: accountId },
data: {
balance: {
increment: balanceChange,
},
},
});
}
});

revalidatePath("/dashboard");
revalidatePath("/account/[id]");

return { success: true };
} catch (error: any) {
console.error(error?.message);
}
}
32 changes: 7 additions & 25 deletions app/(main)/account/[id]/page.tsx
Original file line number Diff line number Diff line change
@@ -1,40 +1,24 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
"// app/account/[id]/page.tsx";

export const dynamic = "force-dynamic";

import { Suspense } from "react";
import { BarLoader } from "react-spinners";
import { notFound } from "next/navigation";
import { getAccountDetails } from "@/actions/Account";
import TransactionTable from "../_components/TransactionTable";
import { Account } from "@/types";

// Define the Account interface
interface Account {
id: string;
name: string;
type: string;
balance: number;
_count: {
transactions: number;
};
transactions: any[];
}
export default async function AccountPage({ params }: { params: any }) {
const accountId = await params;

const AccountPage = async ({ params }: { params: { id: string } }) => {
const parameters = await params;
const accountId = parameters.id;
const id = accountId.id;

const accountData: Account | null = await getAccountDetails(accountId);
const accountData: Account | null = await getAccountDetails(id);

if (!accountData) {
notFound();
}

const { transactions, ...account } = accountData;

console.log(transactions);

return (
<div className="container mx-auto py-8 px-5">
<div className="space-y-8 px-5">
Expand All @@ -43,7 +27,7 @@ const AccountPage = async ({ params }: { params: { id: string } }) => {
<h1 className="text-3xl sm:text-5xl font-bold tracking-tight text-transparent bg-clip-text bg-gradient-to-r from-sky-500 to-blue-600 capitalize">
{account.name}
</h1>
<p className="text-muted-foreground ">
<p className="text-muted-foreground">
{account.type.charAt(0) + account.type.slice(1).toLowerCase()}{" "}
Account
</p>
Expand Down Expand Up @@ -79,6 +63,4 @@ const AccountPage = async ({ params }: { params: { id: string } }) => {
</div>
</div>
);
};

export default AccountPage;
}
17 changes: 5 additions & 12 deletions app/(main)/account/_components/TransactionTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ import { categoryColors } from "@/data/categories";
import { BarLoader } from "react-spinners";
import { useRouter } from "next/navigation";
import { Transaction } from "@/types";
import { BulkDeleteTransaction } from "@/actions/Account";

// Constants
const ITEMS_PER_PAGE = 10;
Expand Down Expand Up @@ -197,25 +198,17 @@ const TransactionTable: React.FC<TransactionTableProps> = ({
try {
setDeleteLoading(true);

// Replace with your API endpoint for deleting transactions
const response = await fetch("/api/transactions/bulk-delete", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ ids: selectedIds }),
});
const deleteTransaction = await BulkDeleteTransaction(selectedIds);

if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.message || "Failed to delete transactions.");
if (!deleteTransaction?.success) {
throw new Error("Failed to delete transactions.");
}

toast.success(
`Deleted ${selectedIds.length} transaction(s) successfully.`
);
setSelectedIds([]);
router.refresh(); // Refresh the page to reflect changes
// router.refresh(); // Refresh the page to reflect changes
} catch (error: any) {
console.error("Error deleting transactions:", error);
toast.error(error.message || "Something went wrong!");
Expand Down
12 changes: 12 additions & 0 deletions types/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import {
AccountType,
RecurringInterval,
Expand Down Expand Up @@ -32,3 +33,14 @@ export interface Transaction {
recurringInterval?: RecurringInterval;
nextRecurringDate?: Date;
}

export interface Account {
id: string;
name: string;
type: string;
balance: number;
_count: {
transactions: number;
};
transactions: any[];
}

0 comments on commit 49fcaae

Please sign in to comment.