Skip to content

Commit

Permalink
fix: search friend query and weekly expense comparision
Browse files Browse the repository at this point in the history
  • Loading branch information
krishkalaria12 committed Jul 7, 2024
1 parent a80ced8 commit d79c44d
Show file tree
Hide file tree
Showing 6 changed files with 99 additions and 72 deletions.
2 changes: 1 addition & 1 deletion src/actions/friend.actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export const getAllFriends = async (): Promise<{ friends: Friend[], pendingReque
};

export const searchFriend = async (query: string): Promise<Friend[]> => {
const response = await axios.get(`/api/friendship/search-friend?q=${query}`);
const response = await axios.get(`/api/friendship/search-friend?query=${query}`);
return response.data.data;
};

Expand Down
146 changes: 83 additions & 63 deletions src/app/api/expense/get-expense-by-comparison/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,40 +12,59 @@ export async function GET(request: Request){
const { has, sessionClaims } = auth();

if (!has) {
return Response.json(
createError(
"Unauthorized", 401, false
)
return new Response(
JSON.stringify(createError("Unauthorized", 401, false)),
{ status: 401 }
);
}

const userId = (sessionClaims?.mongoId as { mongoId: string })?.mongoId;

if (!isValidObjectId(userId)) {
return Response.json(createError("Unauthorized", 401, false));
return new Response(JSON.stringify(createError("Unauthorized", 401, false)), { status: 401 });
}

const today = new Date();

// Calculate the start and end dates for the present week
const startOfWeek = new Date(today);
startOfWeek.setDate(today.getDate() - today.getDay()); // Adjust to the start of the week (Sunday)
startOfWeek.setDate(today.getDate() - today.getDay());
startOfWeek.setHours(0, 0, 0, 0); // Set to the start of the day

const endOfWeek = new Date(today);
endOfWeek.setDate(today.getDate() + (6 - today.getDay())); // Adjust to the end of the week (Saturday)
endOfWeek.setDate(today.getDate() + (6 - today.getDay()));
endOfWeek.setHours(23, 59, 59, 999); // Set to the end of the day

// Calculate the start and end dates for the past week
const startOfPastWeek = new Date(startOfWeek);
startOfPastWeek.setDate(startOfWeek.getDate() - 7);

const endOfPastWeek = new Date(endOfWeek);
endOfPastWeek.setDate(endOfWeek.getDate() - 7);

// Calculate the start and end dates for the present month
const startOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
startOfMonth.setHours(0, 0, 0, 0);

const endOfMonth = new Date(today.getFullYear(), today.getMonth() + 1, 0);
endOfMonth.setHours(23, 59, 59, 999);

// Calculate the start and end dates for the previous month
const startOfPreviousMonth = new Date(today.getFullYear(), today.getMonth() - 1, 1);
startOfPreviousMonth.setHours(0, 0, 0, 0);

const endOfPreviousMonth = new Date(today.getFullYear(), today.getMonth(), 0);
endOfPreviousMonth.setHours(23, 59, 59, 999);

// Logging the calculated dates for debugging
console.log("Start of Week:", startOfWeek);
console.log("End of Week:", endOfWeek);
console.log("Start of Past Week:", startOfPastWeek);
console.log("End of Past Week:", endOfPastWeek);
console.log("Start of Month:", startOfMonth);
console.log("End of Month:", endOfMonth);
console.log("Start of Previous Month:", startOfPreviousMonth);
console.log("End of Previous Month:", endOfPreviousMonth);

// Calculate expenses for the present week
const weekExpense = await calculateExpense(userId, startOfWeek, endOfWeek);
Expand Down Expand Up @@ -79,75 +98,76 @@ export async function GET(request: Request){
totalExpenseAmount: monthExpense // Assuming total expense amount is calculated for the present month
};

return Response.json(
createResponse(
"Expense Calculated Successfully", 200, true, data
)
return new Response(
JSON.stringify(createResponse("Expense Calculated Successfully", 200, true, data)),
{ status: 200 }
);

} catch (error) {
console.log(error);
return Response.json(
createError(
"Internal Server Error", 200, false, error
)
console.error("Error while fetching expense data:", error);
return new Response(
JSON.stringify(createError("Internal Server Error", 500, false, error)),
{ status: 500 }
);
}
}

const calculateOverallExpense = async (userId: string) => {
const expenseAggregate = await Expense.aggregate([
{
$match: {
owner: new mongoose.Types.ObjectId(userId)
}
},
{
$group: {
_id: null,
totalExpense: { $sum: "$amount" }
}
},
{
$project: {
_id: 0,
totalExpense: 1
}
}
]);
const expenseAggregate = await Expense.aggregate([
{
$match: {
owner: new mongoose.Types.ObjectId(userId)
}
},
{
$group: {
_id: null,
totalExpense: { $sum: "$amount" }
}
},
{
$project: {
_id: 0,
totalExpense: 1
}
}
]);

return expenseAggregate.length > 0 ? expenseAggregate[0].totalExpense : 0;
return expenseAggregate.length > 0 ? expenseAggregate[0].totalExpense : 0;
};

const calculateExpense = async (userId: string, startDate: string | number | Date, endDate: string | number | Date) => {
const expenseAggregate = await Expense.aggregate([
{
$match: {
owner: new mongoose.Types.ObjectId(userId),
createdAt: { $gte: new Date(startDate), $lte: new Date(endDate) }
}
},
{
$group: {
_id: null,
totalExpense: { $sum: { $toInt: "$amount" } } // Convert amount to integer for aggregation
}
},
{
$project: {
_id: 0,
totalExpense: 1
}
}
]);
const calculateExpense = async (userId: string, startDate: Date, endDate: Date) => {
console.log(`Calculating expense from ${startDate} to ${endDate}`);
const expenseAggregate = await Expense.aggregate([
{
$match: {
owner: new mongoose.Types.ObjectId(userId),
createdAt: { $gte: startDate, $lte: endDate }
}
},
{
$group: {
_id: null,
totalExpense: { $sum: "$amount" }
}
},
{
$project: {
_id: 0,
totalExpense: 1
}
}
]);

return expenseAggregate.length > 0 ? expenseAggregate[0].totalExpense : 0;
console.log(`Expense from ${startDate} to ${endDate}:`, expenseAggregate);
return expenseAggregate.length > 0 ? expenseAggregate[0].totalExpense : 0;
};

// Function to calculate percentage comparison between two expense amounts
const calculatePercentageComparison = (currentExpense: number, previousExpense: number) => {
if (previousExpense === 0) {
return 100;
}
return ((currentExpense - previousExpense) / previousExpense) * 100;
};
if (previousExpense === 0) {
return "+100%"; // If there's no expense in the previous period, return +100% increase
}
const percentage = ((currentExpense - previousExpense) / previousExpense) * 100;
return `${percentage >= 0 ? "+" : ""}${percentage.toFixed(2)}%`;
};
2 changes: 1 addition & 1 deletion src/app/api/friendship/search-friend/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export async function GET(request: Request) {
try {
const url = new URL(request.url);
const query = url.searchParams.get("query");

const { has, sessionClaims } = auth();
const userId = (sessionClaims?.mongoId as { mongoId: string })?.mongoId;

Expand Down
1 change: 1 addition & 0 deletions src/app/expense/AddExpense.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ export const AddExpense: React.FC = () => {
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['expenses'] });
queryClient.invalidateQueries({ queryKey: ['expense-comparison'] });
queryClient.invalidateQueries({ queryKey: ['expenseData'] });
toast({
title: "Expense added successfully",
description: "You've successfully added an expense",
Expand Down
16 changes: 11 additions & 5 deletions src/app/expense/ExpenseComparison.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,12 @@ import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle }
import { ExpenseComparison as ExpenseComparisonType } from "@/types";

const ExpenseComparison: React.FC<{ data: ExpenseComparisonType }> = ({ data }) => {
const weekPercentage = parseFloat(data.percentageComparison.week);
const monthPercentage = parseFloat(data.percentageComparison.month);

const valueForWeek = weekPercentage > 0 ? weekPercentage : 0;
const valueForMonth = monthPercentage > 0 ? monthPercentage : 0;

return (
<>
<Card x-chunk="dashboard-05-chunk-1">
Expand All @@ -12,11 +18,11 @@ const ExpenseComparison: React.FC<{ data: ExpenseComparisonType }> = ({ data })
</CardHeader>
<CardContent>
<div className="text-xs text-muted-foreground">
+{data.percentageComparison.week.toFixed(2)}% from last week
{data.percentageComparison.week} from last week
</div>
</CardContent>
<CardFooter>
<Progress value={data.percentageComparison.week} aria-label={`${data.percentageComparison.week}% increase`} />
<Progress value={valueForWeek} aria-label={`${data.percentageComparison.week}% increase`} />
</CardFooter>
</Card>
<Card x-chunk="dashboard-05-chunk-2">
Expand All @@ -26,11 +32,11 @@ const ExpenseComparison: React.FC<{ data: ExpenseComparisonType }> = ({ data })
</CardHeader>
<CardContent>
<div className="text-xs text-muted-foreground">
+{data.percentageComparison.month}% from last month
{data.percentageComparison.month} from last month
</div>
</CardContent>
<CardFooter>
<Progress value={data.percentageComparison.month} aria-label={`${data.percentageComparison.month}% increase`} />
<Progress value={valueForMonth} aria-label={`${data.percentageComparison.month}% increase`} />
</CardFooter>
</Card>
<Card x-chunk="dashboard-05-chunk-3">
Expand All @@ -40,7 +46,7 @@ const ExpenseComparison: React.FC<{ data: ExpenseComparisonType }> = ({ data })
</CardHeader>
<CardContent>
<p className="text-base text-gray-500">
&quot;Frugality is not about depriving yourself of things you want, but about being mindful of the things you need&quot;
&#34;Frugality is not about depriving yourself of things you want, but about being mindful of the things you need&#34;
</p>
</CardContent>
</Card>
Expand Down
4 changes: 2 additions & 2 deletions src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ export interface ExpenseComparison {
weekExpense: number;
monthExpense: number;
percentageComparison: {
week: number;
month: number;
week: string;
month: string;
};
overallExpenseAmount: number;
}
Expand Down

0 comments on commit d79c44d

Please sign in to comment.