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
1 change: 1 addition & 0 deletions .env.sample
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
VITE_API_URL= # Base URL for your API, e.g., http://localhost:5000/api
3 changes: 3 additions & 0 deletions Backend/.env.sample
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
MONGODB_URL="" # Your MongoDB connection instance.JWT_SECRET=123
JWT_SECRET= # Your JWT secret key
Frontend_URL= # URL of your frontend application, e.g., http://localhost:5173
29 changes: 29 additions & 0 deletions Backend/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
const express = require('express');
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const goals = require('./routes/goals');
const transactions = require('./routes/transactions.js');
const cors = require('cors');
const { urlencoded } = require('express');
dotenv.config();


const app = express();
app.use(express.json());
app.use(cors({
origin: process.env.FRONTEND_URL,
credentials: true,
}));
app.use(urlencoded({ extended: true }));


mongoose.connect(process.env.MONGODB_URL)
.then(() => console.log('MongoDB connected'))
.catch(err => console.error(err));

app.use('/api/auth', require('./routes/auth'));
app.use('/api/goals', goals);
app.use('/api/transactions', transactions);

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
15 changes: 15 additions & 0 deletions Backend/middleware/auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const jwt = require('jsonwebtoken');
const User = require('../models/User.js');

module.exports = async (req, res, next) => {
const token = req.header('Authorization')?.split(' ')[1];
if (!token) return res.status(401).json({ msg: 'No token, authorization denied' });

try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = await User.findById(decoded.id).select('-password');
next();
} catch (err) {
res.status(401).json({ msg: 'Token is not valid' });
}
};
66 changes: 66 additions & 0 deletions Backend/models/Goal.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
const mongoose = require('mongoose');

const goalSchema = new mongoose.Schema({
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true
},
name: {
type: String,
required: true,
trim: true,
maxlength: 100
},
targetAmount: {
type: Number,
required: true,
min: 0.01
},
currentAmount: {
type: Number,
default: 0,
min: 0
},
isCompleted: {
type: Boolean,
default: false
},
completedAt: {
type: Date,
default: null
}
}, {
timestamps: true
});

// Virtual to calculate progress percentage
goalSchema.virtual('progressPercentage').get(function() {
return Math.min((this.currentAmount / this.targetAmount) * 100, 100);
});

// Virtual to calculate remaining amount
goalSchema.virtual('remainingAmount').get(function() {
return Math.max(this.targetAmount - this.currentAmount, 0);
});

// Middleware to update completion status
goalSchema.pre('save', function(next) {
if (this.currentAmount >= this.targetAmount && !this.isCompleted) {
this.isCompleted = true;
this.completedAt = new Date();
} else if (this.currentAmount < this.targetAmount && this.isCompleted) {
this.isCompleted = false;
this.completedAt = null;
}
next();
});

// Include virtuals when converting to JSON
goalSchema.set('toJSON', { virtuals: true });
goalSchema.set('toObject', { virtuals: true });

// Index for better query performance
goalSchema.index({ userId: 1, createdAt: -1 });

module.exports = mongoose.model('Goal', goalSchema);
48 changes: 48 additions & 0 deletions Backend/models/Transaction.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// models/Transaction.js
const mongoose = require('mongoose');

const transactionSchema = new mongoose.Schema({
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true
},
amount: {
type: Number,
required: true,
min: 0
},
category: {
type: String,
required: true,
trim: true
},
type: {
type: String,
required: true,
enum: ['Income', 'Expense']
},
date: {
type: Date,
required: true,
default: Date.now
},
note: {
type: String,
trim: true,
default: ''
},
goalId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Goal',
default: null
}
}, {
timestamps: true
});

// Index for better query performance
transactionSchema.index({ userId: 1, date: -1 });
transactionSchema.index({ userId: 1, goalId: 1 });

module.exports = mongoose.model('Transaction', transactionSchema);
20 changes: 20 additions & 0 deletions Backend/models/User.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');

const UserSchema = new mongoose.Schema({
name: String,
email: { type: String, required: true, unique: true },
password: { type: String, required: true }
});

UserSchema.pre('save', async function(next) {
if (!this.isModified('password')) return next();
this.password = await bcrypt.hash(this.password, 10);
next();
});

UserSchema.methods.comparePassword = async function(password) {
return await bcrypt.compare(password, this.password);
};

module.exports = mongoose.model('User', UserSchema);
Loading