Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,8 @@ class TransactionController {
const transaction = await this.transactionService.addTransaction({ ...req.body, userId: user.id });
res.status(201).json(transaction);
} catch (err: unknown) {
console.error("Error adding transaction:", (err as Error).message); // ← add this

res.status(500).json({ error: (err as Error).message });
}
}
Expand Down
15 changes: 15 additions & 0 deletions Backend/src/BusinessLogic_Layer/controllers/vis.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,21 @@ class VisController {
}
}
//=================================================================================================
//updates

async getIncomeBySource(req: Request & { user?: JwtPayload }, res: Response): Promise<void> {
try {
const userId = req.user?.id;
if (!userId) {
res.status(401).json({ error: "Sorry Unauthorized :(" });
return;
}

const incomeSources = await this.visService.getIncomeBySource(userId);
res.status(200).json({ incomeSources });
} catch (error: any) {
res.status(500).json({ error: error.message });
}
}
}
export default VisController;
2 changes: 2 additions & 0 deletions Backend/src/BusinessLogic_Layer/routes/vis.routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ router.get('/spent-in-last-30-days', authenticateToken, (req, res) => visControl
//=================================================================================================
router.get('/spent-in-last-12-months', authenticateToken, (req, res) => visController.getSpentLast12Months(req, res));
//=================================================================================================
//updates
router.get('/income-by-source', authenticateToken, (req, res) => visController.getIncomeBySource(req, res));

export default router;

33 changes: 33 additions & 0 deletions Backend/src/BusinessLogic_Layer/services/vis.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,4 +122,37 @@ export class VisService {
return transactions.reduce((sum, t) => sum + t.amount, 0);
}
//=================================================================================================
//updates

async getIncomeBySource(userId: string): Promise<{ category: string; total: number }[]> {
if (!userId) throw new Error("User ID is required");

const result = await Transaction.aggregate([
{ $match: { userId: new mongoose.Types.ObjectId(userId), type: "income" } },
{
$lookup: {
from: "categories",
localField: "category",
foreignField: "_id",
as: "categoryInfo"
}
},
{ $unwind: "$categoryInfo" },
{
$group: {
_id: "$categoryInfo.category",
total: { $sum: "$amount" }
}
},
{
$project: {
category: "$_id",
total: 1,
_id: 0
}
}
]);

return result;
}
}
2 changes: 1 addition & 1 deletion Backend/src/Database_Layer/configdb.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import mongoose from 'mongoose';
//dotenv.config();

// Get the database URL from environment variables
const dbURI: string = 'mongodb+srv://MRB:MARBN12@cluster0.83945.mongodb.net/financeTracker';
const dbURI: string = 'mongodb+srv://MRB:Radwa234@cluster0.83945.mongodb.net/financeTracker';

// Database connection function
const connectDB = async (): Promise<void> => {
Expand Down
20 changes: 10 additions & 10 deletions Frontend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions Frontend/src/components/AddTransaction.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ const AddTransaction: React.FC = () => {
if (name === 'category') {
const selectedCategory = categories.find((cat) => cat._id === value);
setFormData({ ...formData, category: selectedCategory });
}else if (name === 'amount') {
// convert to number to avoid issues like "Infinity124124"
setFormData({ ...formData, amount: Number(value) });
} else {
setFormData({ ...formData, [name]: value });
}
Expand Down
96 changes: 96 additions & 0 deletions Frontend/src/components/IncomeBar.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import React, { useEffect, useState } from 'react';
import { visService } from '../services/card.service'; // assuming this service is in place
import { Bar } from 'react-chartjs-2';
import { Chart as ChartJS, CategoryScale, LinearScale, BarElement, Tooltip, Legend, ChartOptions, TooltipItem } from 'chart.js';
import '../styles/IncomeBar.css'

// Registering required chart.js components
ChartJS.register(CategoryScale, LinearScale, BarElement, Tooltip, Legend);

const IncomeBar: React.FC = () => {
const [incomeData, setIncomeData] = useState<{ category: string; total: number }[]>([]);
const [loading, setLoading] = useState<boolean>(true);
const [error, setError] = useState<string>('');

useEffect(() => {
const fetchIncomeBySource = async () => {
try {
// Assuming `visService.getIncomeBySource` is correctly implemented to fetch the data
const response = await visService.getIncomeBySource();
setIncomeData(response);
} catch (err: any) {
setError('Failed to fetch income data');
console.error(err);
} finally {
setLoading(false);
}
};

fetchIncomeBySource();
}, []);

const chartData = {
labels: incomeData.map(item => item.category), // Categories on the X-axis
datasets: [
{
label: 'Income by Source',
data: incomeData.map(item => item.total), // Total income for each category
backgroundColor: '#36A2EB', // Color for the bars
borderColor: '#36A2EB',
borderWidth: 1,
},
],
};

// Explicitly type chartOptions as ChartOptions<'bar'>
const chartOptions: ChartOptions<'bar'> = {
responsive: true,
plugins: {
legend: {
position: 'top', // Valid values: 'top', 'right', 'bottom', 'left', 'center'
},
tooltip: {
callbacks: {
label: (context: TooltipItem<'bar'>) => {
const value = context.raw as number; // Cast value to a number
return `$${value.toFixed(2)}`; // Display value as currency
},
},
},
},
scales: {
x: {
title: {
display: true,
text: 'Income Source',
},
},
y: {
title: {
display: true,
text: 'Total Income ($)',
},
beginAtZero: true, // Ensures the y-axis starts at zero
},
},
};

if (loading) {
return <div>Loading income data...</div>;
}

if (error) {
return <div>{error}</div>;
}

return (
<div className="income-bar-container">
<h2>Income by Source</h2>
<div className="bar-chart">
<Bar data={chartData} options={chartOptions} />
</div>
</div>
);
};

export default IncomeBar;
6 changes: 6 additions & 0 deletions Frontend/src/pages/DashboardPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import '../styles/dashbored.css';
import { visService } from "../services/card.service";
import { Transaction } from '../types/transaction';
import { transactionsService } from '../services/transactions.service';
import IncomeBar from '../components/IncomeBar';

import { Chart as ChartJS, ArcElement, Tooltip, Legend, CategoryScale, LinearScale, PointElement, LineElement } from 'chart.js';
import { Pie, Line } from 'react-chartjs-2';
Expand Down Expand Up @@ -171,6 +172,11 @@ const DashboardPage: React.FC = () => {
<h3>Income vs Expenses</h3>
{totalIncomeAndExpenses ? <Pie data={pieData} /> : <p>Loading Chart...</p>}
</div>
<div className="income-bar">
{/* <h3>Income by Source</h3> */}
{/* Use IncomeBar component, no need for incomeData or chartData */}
<IncomeBar />
</div>
<div className="cards-section">
<h3>Your Financial Highlights</h3>
<div className="cards-container">
Expand Down
9 changes: 9 additions & 0 deletions Frontend/src/services/card.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,4 +52,13 @@ async getMaxExpense( queryParams: Record<string, any> = {}): Promise<number> {
console.log(response);
return response.data.maxExpense;
},

//updates

// Fetch income data by source
async getIncomeBySource() {
const response = await api.get('/income-by-source');
console.log(response);
return response.data.incomeSources; // Assuming incomeSources is an array of { category, total }
},
};
57 changes: 57 additions & 0 deletions Frontend/src/styles/IncomeBar.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
Container for the bar chart
.income-bar-container {
width: 100%;
padding: 20px;
background: #f9f9f9;
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
margin: 20px 0;
text-align: center;
}

.income-bar-container h2 {
font-size: 1.5rem;
color: #333;
margin-bottom: 20px;
font-family: 'Arial', sans-serif;
font-weight: 600;
}

/* The bar chart styling */
.bar-chart {
position: relative;
width: 100%;
max-width: 800px;
margin: 0 auto;
}

.chartjs-render-monitor {
background: linear-gradient(45deg, #ff66b2, #9b59b6); /* Pink to Purple Gradient */
border-radius: 8px;
padding: 20px;
}

.chart-container {
position: relative;
}

/* Tooltip styling */
.chartjs-tooltip {
background-color: rgba(0, 0, 0, 0.8);
color: white;
font-size: 14px;
padding: 10px;
border-radius: 5px;
}

/* Responsive behavior */
@media (max-width: 768px) {
.income-bar-container {
padding: 15px;
}

.bar-chart {
width: 90%;
}
}

2 changes: 2 additions & 0 deletions Frontend/src/styles/dashbored.css
Original file line number Diff line number Diff line change
Expand Up @@ -210,4 +210,6 @@ html, body {
}

}



6 changes: 2 additions & 4 deletions Frontend/test-results/.last-run.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
{
"status": "failed",
"failedTests": [
"ba0db3d088059a45db0d-20bc3e21613bb8009c6a"
]
"status": "passed",
"failedTests": []
}