diff --git a/controllers/account.controller.js b/controllers/account.controller.js index 4749c37..a4de796 100644 --- a/controllers/account.controller.js +++ b/controllers/account.controller.js @@ -1,298 +1,232 @@ const Account = require('../model/account.model'); const RecordList = require('../model/record-list.model'); -const User = require('../model/user.model'); -const Log = require('../model/log.model') +const asyncHandler = require('../utials/asyncHandler'); +const createLog = require('../utials/log'); +const ApiError = require('../utials/apiError'); //getAllAccounts -const getAllAccount = async (req, res) => { - try { - const getAllAccount = await Account.find({}).populate('recordId'); - if (getAllAccount.length > 0) { - return res.status(200).json({ success: true, message: 'All Accounts Fatch Successfully', data: getAllAccount }) - } - else { - return res.status(404).json({ success: false, message: 'Accounts Not Found' }) - } +const fetchAllAccounts = asyncHandler(async (req, res) => { + const accounts = await Account.find({}).populate('recordId'); + if (accounts.length === 0) { + return res.status(204).send() } - catch (error) { - console.error('Faiiled to Fatch Accounts', error.message); - return res.status(500).json({ - success: false, message: 'something went wrong! please try again' - }) - } -} + res.status(200).json({ success: true, message: 'All Accounts Fetched Successfully', data: accounts }); +}); + + -//create New account -const addNewAccount = async (req, res) => { - try { - const { name, amount, type } = req.body; - if (!name) { - return res.status(400).json({ success: false, message: 'All fields are required' }); - } - const user = await User.findOne({}); - if (!user) { - return res.status(404).json({ success: false, message: 'User not found' }); - } - const newCreatedAccount = await Account.create({ name, amount: 0, type }); - if (amount && amount > 0) { - const createdRecord = await RecordList.create({ - amount: amount, - type: 'income', - account: newCreatedAccount._id, - addNote: `"${name}" Account Created With initial Amount ₹${amount}`, - isInitialEntry: true - }); - // created record' - await Account.findByIdAndUpdate(newCreatedAccount._id, { $inc: { amount: amount }, $set: { recordId: createdRecord._id } }); - } - const message = `Account "${newCreatedAccount.name}" Created with Initial Amount ₹${amount} By: ${user.username}.`; - await Log.create({ userId: user._id, message }); - return res.status(201).json({ success: true, message: 'Account created successfully.', data: newCreatedAccount }); - } catch (error) { - console.error(error); - return res.status(500).json({ success: false, message: 'Something went wrong..! Please try again', }); +//create New account +const createAccount = asyncHandler(async (req, res) => { + const { name, amount, type } = req.body; + if (!name) { + throw new ApiError(400, 'Account name is required'); + } + const newCreatedAccount = await Account.create({ name, amount: 0, type }); + if (amount && amount > 0) { + const createdRecord = await RecordList.create({ + amount: amount, + type: 'income', + account: newCreatedAccount._id, + addNote: `"${name}" Account Created With initial Amount ₹${amount}`, + isInitialEntry: true + }); + // created record' + await Account.findByIdAndUpdate(newCreatedAccount._id, { $inc: { amount: amount }, $set: { recordId: createdRecord._id } }); } -}; + await createLog(`Account "${newCreatedAccount.name}" Created with Initial Amount ₹${amount}`); + res.status(201).json({ success: true, message: 'Account created successfully.', data: newCreatedAccount }); +}); -//deleteAccount from account list -const deleteAccount = async (req, res) => { - try { - const accountId = req.params.id; - const deleteAccount = await Account.findById(accountId); - if (!deleteAccount) { - return res.status(404).json({ success: false, message: 'Account not found' }); - } - const user = await User.findOne({}); - if (!user) { - return res.status(404).json({ success: false, message: 'User not found' }); - } - //find all transaction of transfer amount - const transferAmount = await RecordList.find({ toAccount: accountId, isTransfer: true }); - for (const transfer of transferAmount) { - const { fromAccount } = transfer; - const getFromAccount = await Account.findById(fromAccount); - if (getFromAccount) { - const initialRecord = await RecordList.findOne({ account: getFromAccount._id, isInitialEntry: true, type: 'income' }); - if (initialRecord) { - initialRecord.amount = getFromAccount.amount; - initialRecord.addNote = `Updated Amount after Delete "${deleteAccount.name}" Account ₹${getFromAccount.amount}`; - await initialRecord.save(); - } +//remove Account from account list +const removeAccountById = asyncHandler(async (req, res) => { + const accountId = req.params.id; + const deleteAccount = await Account.findById(accountId); + if (!deleteAccount) { + throw new ApiError(404, 'Account not found') + } + //find all transaction of transfer amount + const transferAmount = await RecordList.find({ toAccount: accountId, isTransfer: true }); + for (const transfer of transferAmount) { + const { fromAccount } = transfer; + const getFromAccount = await Account.findById(fromAccount); + if (getFromAccount) { + const initialRecord = await RecordList.findOne({ account: getFromAccount._id, isInitialEntry: true, type: 'income' }); + if (initialRecord) { + initialRecord.amount = getFromAccount.amount; + initialRecord.addNote = `Updated Amount after Delete "${deleteAccount.name}" Account ₹${getFromAccount.amount}`; + await initialRecord.save(); } - await RecordList.findByIdAndDelete(transfer._id); } - await RecordList.deleteMany({ account: accountId }); - await Account.findByIdAndDelete(accountId); - const message = `"${deleteAccount.name}" Account deleted by: ${user.username}`; - await Log.create({ userId: user._id, message }); - return res.status(200).json({ success: true, message: 'Account deleted successfully. Transfer records removed, and sender records updated.', data: deleteAccount }); - - } catch (error) { - console.error('Failed to delete Account', error.message); - return res.status(500).json({ - success: false, - message: 'Something went wrong! Please try again.' - }); + await RecordList.findByIdAndDelete(transfer._id); } -}; + await RecordList.deleteMany({ account: accountId }); + await Account.findByIdAndDelete(accountId); + await createLog(`"${deleteAccount.name}" Account deleted`); + res.status(200).json({ success: true, message: 'Account deleted successfully. Transfer records removed, and records updated.', data: deleteAccount }); + + +}); // transfer amount from one account to another -const transferAmount = async (req, res) => { - try { - const { fromAccountId, toAccountId, amount } = req.body; - const user = await User.findOne({}); - if (!user) { - return res.status(404).json({ success: false, message: 'User not found' }); - } - if (!fromAccountId || !toAccountId || !amount || amount <= 0) { - return res.status(400).json({ success: false, message: 'Enter a valid Amount.! Must be grater then 0' }); - } - if (fromAccountId === toAccountId) { - return res.status(400).json({ success: false, message: 'Accounts are same choose different Account..' }); - } - const fromAccount = await Account.findById(fromAccountId); - const toAccount = await Account.findById(toAccountId); - if (!fromAccount || !toAccount) { - return res.status(404).json({ success: false, message: 'Account not Found.!!' }); - } - if (fromAccount.amount < amount) { - return res.status(400).json({ success: false, message: 'Insufficient Amount.!' }); - } - //amount transfer - fromAccount.amount -= amount; - toAccount.amount += amount; - await fromAccount.save(); - await toAccount.save(); - //create a transfer transaction record - const transferAmountRecord = await RecordList.create({ - account: fromAccount._id, - type: 'transfer', - amount, - fromAccount: fromAccount._id, - toAccount: toAccount._id, - addNote: `Transferred ₹${amount} from "${fromAccount.name}" to "${toAccount.name}" Account.`, - isTransfer: true, - }); - const message = ` Amount ₹${amount} Transfer "${fromAccount.name}" Account To "${toAccount.name}" Account. BY: ${user.username}`; - await Log.create({ userId: user._id, message }); - return res.status(200).json({ success: true, message: 'Amount Transfer Successfull', data: { fromAccount, toAccount, transferAmountRecord } }); - } catch (error) { - console.error('Transfer failed:', error.message); - return res.status(500).json({ success: false, message: 'Internal Server Error' }); +const transferAmountBetweenAccounts = asyncHandler(async (req, res) => { + const { fromAccountId, toAccountId, amount } = req.body; + if (!fromAccountId || !toAccountId || !amount || amount <= 0) { + throw new ApiError(400, 'Enter a valid Amount.! Must be greater then 0') } -}; + if (fromAccountId === toAccountId) { + throw new ApiError(400, 'Both accounts are same choose different Account.') + } + const fromAccount = await Account.findById(fromAccountId); + const toAccount = await Account.findById(toAccountId); + if (!fromAccount || !toAccount) { + throw new ApiError(404, 'Account not found'); + } + if (fromAccount.amount < amount) { + throw new ApiError(400, 'Insufficient Amount.!'); + } + //amount transfer + fromAccount.amount -= amount; + toAccount.amount += amount; + await fromAccount.save(); + await toAccount.save(); + //create a transfer transaction record + const transferAmountRecord = await RecordList.create({ + account: fromAccount._id, + type: 'transfer', + amount, + fromAccount: fromAccount._id, + toAccount: toAccount._id, + addNote: `Transferred ₹${amount} from "${fromAccount.name}" to "${toAccount.name}" Account.`, + isTransfer: true, + }); + await createLog(` Amount ₹${amount} Transfer "${fromAccount.name}" Account To "${toAccount.name}" Account.`); + res.status(200).json({ success: true, message: 'Amount Transfer Successfull', data: { fromAccount, toAccount, transferAmountRecord } }); + +}); // Update an existing transfer transaction records -const updateTransferAmount = async (req, res) => { - try { - const { fromAccountId, toAccountId, amount, recordId } = req.body; - const user = await User.findOne({}); - if (!user) { - return res.status(404).json({ success: false, message: 'User not found' }); - } - if (!recordId || !fromAccountId || !toAccountId || !amount || amount <= 0) { - return res.status(400).json({ success: false, message: 'invalid transfer Amount' }); - } - if (fromAccountId === toAccountId) { - return res.status(400).json({ success: false, message: 'both Accounts cannot be the same' }); - } - const record = await RecordList.findById(recordId); - if (!record || !record.isTransfer) { - return res.status(404).json({ success: false, message: 'Transfer record not found.' }); - } - //updated Amount after updated Transfer Transaction add back amount while updating transaction record - const oldFromAccount = await Account.findById(record.fromAccount); - const oldToAccount = await Account.findById(record.toAccount); - if (oldFromAccount) { - oldFromAccount.amount += record.amount; - } - if (oldToAccount) { - oldToAccount.amount -= record.amount - } +const updateTransferTransaction = asyncHandler(async (req, res) => { + const { fromAccountId, toAccountId, amount, recordId } = req.body; + if (!recordId || !fromAccountId || !toAccountId || !amount || amount <= 0) { + throw new ApiError(400, 'invalid transfer Amount'); + } + if (fromAccountId === toAccountId) { + throw new ApiError(400, 'Both Accounts cannot be the same'); + } + const record = await RecordList.findById(recordId); + if (!record || !record.isTransfer) { + throw new ApiError(404, 'Transfer record not found'); + } + //updated Amount after updated Transfer Transaction add back amount while updating transaction record + const oldFromAccount = await Account.findById(record.fromAccount); + const oldToAccount = await Account.findById(record.toAccount); + if (oldFromAccount) { + oldFromAccount.amount += record.amount; await oldFromAccount.save(); + } + if (oldToAccount) { + oldToAccount.amount -= record.amount; await oldToAccount.save(); - //fatch and validate Accounts - const newFromAccount = await Account.findById(fromAccountId); - const newToAccount = await Account.findById(toAccountId); - if (!newFromAccount || !newToAccount) { - return res.status(404).json({ success: false, message: 'Account not Found' }); - } - if (newFromAccount.amount < amount) { - return res.status(400).json({ success: false, message: 'Insufficient Amount.!.' }); - } - - newFromAccount.amount -= amount, - newToAccount.amount += amount - await newFromAccount.save(); - await newToAccount.save(); + } - // Update the transfer record - record.fromAccount = fromAccountId; - record.toAccount = toAccountId; - record.amount = amount; - record.account = fromAccountId; - record.addNote = `Transferred ₹${amount} from "${newFromAccount.name}" to "${newToAccount.name}" Account.`; - record.updatedAt = new Date(); - await record.save(); - const message = `Transfer updated: ₹${amount} from "${newFromAccount.name}" to "${newToAccount.name} By: ${user.username}"`; - await Log.create({ userId: user._id, message }); - return res.status(200).json({ success: true, message: 'Transfer record updated successfully.', data: record }); - } catch (error) { - console.error('Transfer update failed:', error.message); - return res.status(500).json({ success: false, message: 'Internal Server Error!. Please try again' }); + //Fetch and validate Accounts + const newFromAccount = await Account.findById(fromAccountId); + const newToAccount = await Account.findById(toAccountId); + if (!newFromAccount || !newToAccount) { + throw new ApiError(404, 'Account not found'); } -}; - -//fatch accountDetails by AccountId -const getAccountById = async (req, res) => { - try { - const getCurrentAccountById = req.params.id; - const getAccountDetailsById = await Account.findById(getCurrentAccountById); - if (!getAccountDetailsById) { - return res.status(404).json({ success: false, message: "Account Not Found" }) - } - else { - return res.status(200).json({ success: true, message: 'Account Details Fatch Successful', data: getAccountDetailsById }) - } + if (newFromAccount.amount < amount) { + throw new ApiError(400, 'Insufficient Amount.!') } - catch (error) { - console.log(error); - return res.status(500).json({ success: false, message: 'something went wrong! please try again.' }) + + newFromAccount.amount -= amount, + newToAccount.amount += amount + await newFromAccount.save(); + await newToAccount.save(); + + // Update the transfer record + record.fromAccount = fromAccountId; + record.toAccount = toAccountId; + record.amount = amount; + record.account = fromAccountId; + record.addNote = `Transferred ₹${amount} from "${newFromAccount.name}" to "${newToAccount.name}" Account.`; + record.updatedAt = new Date(); + await record.save(); + await createLog(`Transfer updated: ₹${amount} from "${newFromAccount.name}" to "${newToAccount.name}`); + res.status(200).json({ success: true, message: 'Transfer record updated successfully.', data: record }); +}); + +//Fetch accountDetails by AccountId +const fetchAccountById = asyncHandler(async (req, res) => { + const fetchAccountById = req.params.id; + const fetchAccountDetailsById = await Account.findById(fetchAccountById); + if (!fetchAccountDetailsById) { + throw new ApiError(404, 'Account not Found'); } -} + res.status(200).json({ success: true, message: 'Account Details Fetch Successful', data: fetchAccountDetailsById }); +}); -//udpate account and adjust account balance after updation -const updateAccount = async (req, res) => { - try { - const { accountId, recordId, name, amount } = req.body; - const user = await User.findOne({}); - if (!user) { - return res.status(404).json({ success: false, message: 'User not found' }); - } - if (!accountId || !name || amount == null) { - return res.status(400).json({ success: false, message: 'All fields are required' }); - } - //find account byId - const account = await Account.findById(accountId); - if (!account) { - return res.status(404).json({ success: false, message: 'Account not found' }); - } - const oldAmount = account.amount; - const newAmount = amount; - const currentAmount = newAmount - oldAmount; - //Update Account Name and Amount - account.name = name; - account.amount = newAmount; - await account.save(); - let message = `Account "${name}" updated. Amount changed from ₹${oldAmount} to ₹${newAmount}`; - ///delete transaction record Entry when updated amount equal zero - if (recordId && newAmount === 0) { - const record = await RecordList.findById(recordId); - if (record && record.isInitialEntry) { +//update account and adjust account balance after updation +const updateAccountDetails = asyncHandler(async (req, res) => { + const { accountId, recordId, name, amount } = req.body; + if (!accountId || !name || amount == null) { + throw new ApiError(400, 'All fields are required'); + } + const account = await Account.findById(accountId); + if (!account) { + throw new ApiError(404, 'Account not found'); + } + let message = ''; + account.name = name; + message = `Account "${name}" updated.`; + if (recordId) { + const record = await RecordList.findById(recordId); + if (record && record.isInitialEntry) { + const oldInitialAmount = record.amount; + if (amount === 0) { await RecordList.findByIdAndDelete(recordId); + const remaining = account.amount - oldInitialAmount; + account.amount = remaining; account.recordId = null; - await account.save(); - } - } - else if (recordId && newAmount > 0) { - const record = await RecordList.findById(recordId); - if (record && record.isInitialEntry) { - record.amount = newAmount; - record.addNote = `Account "${name}" updated with amount ₹${newAmount}`; + message += ` Initial record deleted (was ₹${oldInitialAmount}).`; + } else { + const remaining = account.amount - oldInitialAmount; + record.amount = amount; + record.addNote = `Initial amount updated to ₹${amount}`; await record.save(); - message += `transaction record updated by: ${user.username}`; + + account.amount = remaining + amount; + message += ` Initial amount changed from ₹${oldInitialAmount} to ₹${amount}.`; } + } else { + throw new ApiError(400, 'Invalid initial entry'); } - //if user have no record exists and new Amount more then 0 create record - else if (!recordId && newAmount > 0) { + + } else { + if (amount > 0) { const createdRecord = await RecordList.create({ - amount: newAmount, + amount, type: 'income', account: account._id, - addNote: `Account "${name}" updated with initial amount ₹${newAmount}`, - isInitialEntry: true + addNote: `Initial amount set to ₹${amount}`, + isInitialEntry: true, }); + account.amount += amount; account.recordId = createdRecord._id; - await account.save(); - message += `Initial transaction record created)`; + message += ` Initial record created with ₹${amount}.`; } - await Log.create({ userId: user._id, message }); - - return res.status(200).json({ success: true, message: 'Account and Transaction updated successfully', data: account }); - - } catch (err) { - console.error('Update Account Error:', err.message); - return res.status(500).json({ success: false, message: 'Something went wrong' }); } -}; - + await account.save(); + await createLog(message); + res.status(200).json({ success: true, message, data: account }); +}); -module.exports = { getAllAccount, addNewAccount, getAccountById, deleteAccount, transferAmount, updateAccount, updateTransferAmount }; \ No newline at end of file +module.exports = { fetchAllAccounts, fetchAccountById, createAccount, removeAccountById, updateAccountDetails, updateTransferTransaction, transferAmountBetweenAccounts }; \ No newline at end of file diff --git a/controllers/budget.controller.js b/controllers/budget.controller.js index 5b47da4..4010133 100644 --- a/controllers/budget.controller.js +++ b/controllers/budget.controller.js @@ -1,100 +1,70 @@ +const asyncHandler = require('../utials/asyncHandler'); const Budget = require('../model/budget.model'); -const User = require('../model/user.model'); -const Log = require('../model/log.model'); const Category = require('../model/category.model'); +const createLog = require('../utials/log'); +const ApiError = require('../utials/apiError'); + //find all budget -const getAllBudget = async (req, res) => { - try { - const Budgets = await Budget.find({}); - if (Budgets.length > 0) { - return res.status(200).json({ success: true, message: 'All Budget Fatch Success', data: Budgets }) - } - else { - return res.status(404).json({ success: false, message: 'Budget Not Found' }) - } - } - catch (error) { - console.log(error); - return res.status(500).json({ success: false, message: 'Somethng went wrong!please try again' }) +const fetchAllBudgets = asyncHandler(async (req, res) => { + const budgets = await Budget.find({}); + if (budgets.length === 0) { + return res.status(204).send(); } -} - + res.status(200).json({ success: true, message: 'All Budgets Fatched Successfully', data: budgets }); +}); //set Budget with selected category -const addNewBudget = async (req, res) => { - try { - const { categoryId, limit, date } = req.body; - const user = await User.findOne({}); - if (!categoryId || !limit) { - return res.status(400).json({ success: false, message: 'All Fields are required' }); - } - if (!user) { - return res.status(404).json({ success: false, message: 'user not found' }) - } - // Check if budget already exists for this category - const existCategoryBudget = await Budget.findOne({ category: categoryId, date }); - if (existCategoryBudget) { - existCategoryBudget.limit = limit; - await existCategoryBudget.save(); - return res.status(200).json({ success: true, message: 'Budget updated', data: existCategoryBudget }); - } - const budget = await Budget.create({ - category: categoryId, - limit, - date, - userId: user._id - }); +const createBudget = asyncHandler(async (req, res) => { + const { categoryId, limit, date } = req.body; + if (!categoryId || !limit) { + throw new ApiError(400, 'All Fields are required'); + } - await Log.create({ userId: user._id, message: `${user.username} created a new monthly budget limit ₹${limit}` }); - return res.status(201).json({ success: true, message: 'Budget created Successfully.!', data: budget }); - } catch (err) { - console.log(err); - return res.status(500).json({ success: false, message: 'Something went wrong! Please try again' }); + const category = await Category.findById(categoryId); + if (!category) { + throw new ApiError(404, 'Category not found'); } -}; + const budget = await Budget.create({ + category: categoryId, + limit, + date, + }); + await createLog(` Created a new monthly Budget for "${category.name}" category with limit ₹${limit}`); + res.status(201).json({ success: true, message: 'Budget created Successfully.!', data: budget }); +}); //Update budget by ID -const updateBudget = async (req, res) => { - try { - const budgetUpdateFormData = req.body; - const getCurrentBudget = req.params.id; - const { limit } = req.body; - if (!limit) { - return res.status(400).json({ success: false, message: 'Limit is required' }); - } - const updatedBudget = await Budget.findByIdAndUpdate(getCurrentBudget, budgetUpdateFormData, { new: true } - ); - if (!updatedBudget) { - return res.status(404).json({ success: false, message: 'Budget not found' }); - } - return res.status(200).json({ success: true, message: 'Budget updated successfully', data: updatedBudget }); - } catch (error) { - console.error(error); - return res.status(500).json({ success: false, message: 'Something went wrong' }); +const updateBudgetDetails = asyncHandler(async (req, res) => { + const budgetUpdateFormData = req.body; + const getCurrentBudget = req.params.id; + const { limit } = req.body; + if (!limit) { + throw new ApiError(400, 'limit is required'); } -}; - - -//delete -const deleteBudget = async (req, res) => { - try { - const getCurrentBudgetId = req.params.id; - const deleteBudget = await Budget.findByIdAndDelete(getCurrentBudgetId); - if (!deleteBudget) { - return res.status(404).json({ success: false, message: 'Selected ctageory budget not found' }) - } - res.status(200).json({ success: true, message: 'Category Budget Delete Success', data: deleteBudget }) + const updatedBudget = await Budget.findByIdAndUpdate(getCurrentBudget, budgetUpdateFormData, { new: true } + ); + if (!updatedBudget) { + throw new ApiError(404, 'Budget not found'); } - catch (error) { - console.error(error); - return res.status(500).json({ success: false, message: 'something went wrong! please try again' }) + await createLog(`update budget with new limit ${updatedBudget.limit}`) + res.status(200).json({ success: true, message: 'Budget updated successfully', data: updatedBudget }); +}); +//deleted budget +const deleteBudgetById = asyncHandler(async (req, res) => { + const getBudgetId = req.params.id; + const deletedBudget = await Budget.findByIdAndDelete(getBudgetId); + if (!deletedBudget) { + throw new ApiError(404, 'Budget not found'); } -} + await createLog(`deleted a monthly budget of limit ₹${deletedBudget.limit}`) + res.status(200).json({ success: true, message: 'Category Budget Delete Success', data: deletedBudget }); + +}); -module.exports = { getAllBudget, addNewBudget, updateBudget, deleteBudget }; +module.exports = { fetchAllBudgets, createBudget, deleteBudgetById, updateBudgetDetails }; diff --git a/controllers/category.controller.js b/controllers/category.controller.js index bb61dee..ad72b4d 100644 --- a/controllers/category.controller.js +++ b/controllers/category.controller.js @@ -1,139 +1,93 @@ const Category = require('../model/category.model'); const Account = require('../model/account.model'); const RecordList = require('../model/record-list.model'); -const User = require('../model/user.model'); -const Log = require('../model/log.model'); const Budget = require('../model/budget.model'); +const asyncHandler = require('../utials/asyncHandler'); +const createLog = require('../utials/log'); +const ApiError = require('../utials/apiError'); -//getAll Category -const getAllCategory = async (req, res) => { - try { - const getAllCategory = await Category.find({}); - if (getAllCategory.length > 0) { - return res.status(200).json({ success: true, message: 'All Category Fatch Successfully', data: getAllCategory }) - } - else { - return res.status(404).json({ success: false, message: 'Category Not Found' }) - } +//fetch All Categories +const fetchAllCategories = asyncHandler(async (req, res) => { + const categories = await Category.find({}); + if (categories.length === 0) { + return res.status(204).send(); } - catch (error) { - console.log(err); - return res.state(500).json({ success: false, message: 'Something went wrong! please try again' }) - } -} + res.status(200).json({ success: true, message: 'All Categories Fatched Successfully', data: categories }) + +}); //create new Catgeory -const addNewCategory = async (req, res) => { - try { - const { name, type } = req.body; - if (!name || !type) { - return res.status(404).json({ success: false, message: 'All Fields are required' }) - } - const user = await User.findOne({}); - if (!user) { - return res.status(404).json({ success: false, message: 'User not found' }); - } - const newCategoryFormData = { name, type }; - const newCreatedCategory = await Category.create(newCategoryFormData); - if (newCreatedCategory) { - const message = ` ${type} Category " ${name}" Created successful By: "${user.username}"` - await Log.create({ userId: user._id, message }); - return res.status(201).json({ success: true, message: 'Category Cretae Successful', data: newCreatedCategory }) - } - else { - return res.status(400).json({ success: false, message: 'Failed to create Category' }) - } +const createCategory = asyncHandler(async (req, res) => { + const { name, type } = req.body; + if (!name || !type) { + throw new ApiError(400, 'All Fields are required'); } - catch (error) { - return res.status(500).json({ - success: false, - message: 'Something went wrong! please try again' - }) + const newCategoryFormData = { name, type }; + const newCreatedCategory = await Category.create(newCategoryFormData); + if (newCreatedCategory) { + await createLog(` ${type} Category " ${name}" Created successful`); + return res.status(201).json({ success: true, message: 'Category Created Successful', data: newCreatedCategory }) } -} -//delete Category -const deleteCategory = async (req, res) => { - try { - const categoryId = req.params.id; - const category = await Category.findByIdAndDelete(categoryId); - const user = await User.findOne({}); - if (!user) { - return res.status(404).json({ success: false, message: 'User not found' }); - } - if (!category) { - return res.status(404).json({ success: false, message: 'Category not found' }); - } - //monthly budget also deleted when used category deleted - const deletedBudget = await Budget.findOneAndDelete({ category: categoryId }); - if (deletedBudget) { - await Log.create({ - userId: user._id, - message: `Monthly Set Budget for deleted category "${category.name}" was also Delete by ${user.username}`, - }); - } - // find all transactions selected category - const findTransactionRecords = await RecordList.find({ category: categoryId }); - for (const record of findTransactionRecords) { - const account = await Account.findById(record.account); - const updateAmount = record.type === 'income' ? -record.amount : record.amount; - if (account) { - account.amount += updateAmount; - await account.save(); - } - //Log each transaction deletion - const message = `${record.type} transaction of ₹${record.amount} (from deleted category "${category.name}") was removed by ${user.username}`; - await Log.create({ userId: user._id, message }); - await RecordList.findByIdAndDelete(record._id); - } - await Log.create({ userId: user._id, message: `${category.type} category "${category.name}" was deleted by ${user.username}` }); - return res.status(200).json({ success: true, message: 'Category deleted successfully', data: { category, deletedRecords: findTransactionRecords.length } }); - } - catch (error) { - console.error('Error deleting category:', error.message); - return res.status(500).json({ success: false, message: 'Something went wrong. Please try again.' }); - } -}; + + throw new ApiError(400, 'Failed to create Category'); +}); + //update categoryByid -const updateCategory = async (req, res) => { - try { - const categoryUpdateFormData = req.body; - const getCurrentCategoryById = req.params.id; - const updateCategory = await Category.findByIdAndUpdate(getCurrentCategoryById, categoryUpdateFormData, { new: true }); - const user = await User.findOne({}); - if (!user) { - return res.status(404).json({ success: false, message: 'User not found' }); - } - if (!updateCategory) { - return res.status(404).json({ success: false, message: 'Category Not Found' }) - } - const message = `"${updateCategory.name} " ${updateCategory.type} Category update successfully. By: "${user.username}"`; - await Log.create({ userId: user._id, message }); - return res.status(200).json({ success: true, message: 'Category Update Success', data: updateCategory }) - } - catch (error) { - console.log(error); - return res.status(500).json({ success: false, message: 'something went wrong! please try again' }) +const updateCategoryDetails = asyncHandler(async (req, res) => { + const categoryUpdateFormData = req.body; + const getCurrentCategoryById = req.params.id; + const updateCategory = await Category.findByIdAndUpdate(getCurrentCategoryById, categoryUpdateFormData, { new: true }); + if (!updateCategory) { + throw new ApiError(404, 'Category not found'); } -} + await createLog(`"${updateCategory.name} " ${updateCategory.type} Category update successfully`); + res.status(200).json({ success: true, message: 'Category Update Success', data: updateCategory }) +}); -//getcategory BY Id -const getCategoryById = async (req, res) => { - try { - const getCurrentCategoryById = req.params.id; - const getCategoryDetailsById = await Category.findById(getCurrentCategoryById); - if (!getCategoryDetailsById) { - return res.status(404).json({ success: false, message: 'category not found' }) - } - else { - return res.status(200).json({ success: true, message: 'Category Details Fatch Success..', data: getCategoryDetailsById }) + + +//delete Category +const deleteCategoryById = asyncHandler(async (req, res) => { + const categoryId = req.params.id; + const category = await Category.findByIdAndDelete(categoryId); + if (!category) { + throw new ApiError(404, 'Category not found'); + } + //monthly budget also deleted when used category deleted + const deletedBudget = await Budget.findOneAndDelete({ category: categoryId }); + if (deletedBudget) { + await createLog(`Monthly Set Budget for deleted category "${category.name}" was also Delete`); + } + // find all transactions selected category + const findTransactionRecords = await RecordList.find({ category: categoryId }); + for (const record of findTransactionRecords) { + const account = await Account.findById(record.account); + const updateAmount = record.type === 'income' ? -record.amount : record.amount; + if (account) { + account.amount += updateAmount; + await account.save(); } + //Log each transaction deletion + await createLog(`${record.type} transaction of ₹${record.amount} (from deleted category "${category.name}") was removed`) + await RecordList.findByIdAndDelete(record._id); } - catch (error) { - console.log(error); - return res.status(500).json({ success: false, message: "something went wrong! please try again" }) + await createLog(`${category.type} category "${category.name}" was deleted`) + res.status(200).json({ success: true, message: 'Category deleted successfully', data: { category, deletedRecords: findTransactionRecords.length } }); +}); + + + +//getcategory BY Id +const fetchCategoryById = asyncHandler(async (req, res) => { + const getCategoryById = req.params.id; + const getCategoryDetailsById = await Category.findById(getCategoryById); + if (!getCategoryDetailsById) { + throw new ApiError(404, 'Category not found'); } -} + res.status(200).json({ success: true, message: 'Category Details Fetch Success..', data: getCategoryDetailsById }) + +}); -module.exports = { getAllCategory, addNewCategory, updateCategory, deleteCategory, getCategoryById } \ No newline at end of file +module.exports = { fetchAllCategories, createCategory,fetchCategoryById, deleteCategoryById, updateCategoryDetails } \ No newline at end of file diff --git a/controllers/log-activity.controller.js b/controllers/log-activity.controller.js index 4cce4dc..5bf3619 100644 --- a/controllers/log-activity.controller.js +++ b/controllers/log-activity.controller.js @@ -1,22 +1,18 @@ -const Log = require('../model/log.model') +const Log = require('../model/log.model'); +const asyncHandler = require('../utials/asyncHandler'); +const ApiError = require('../utials/apiError'); //get All activity logs -const getAllLogs = async (req, res) => { - try { - const getAllLogActivity = await Log.find({}).populate('userId'); - if (getAllLogActivity.length > 0) { - return res.status(200).json({ success: true, message: 'Activity logs fetched', data: getAllLogActivity }); - } - else { - return res.status(404).json({ success: false, message: 'log activity not found' }) - } - } catch (error) { - console.error(error); - return res.status(500).json({ success: false, message: 'Error fetching logs' }); +const fetchAllLogs = asyncHandler(async (req, res) => { + const logs = await Log.find({}).populate('userId').sort({date: -1}); + if (logs.length === 0) { + return res.status(204).send(); } -} + res.status(200).json({ success: true, message: 'All Logs Fetched Successfully', data:logs }); +}); -module.exports = { getAllLogs } + +module.exports = { fetchAllLogs } diff --git a/controllers/record-list.controller.js b/controllers/record-list.controller.js index 08c14f9..6827a87 100644 --- a/controllers/record-list.controller.js +++ b/controllers/record-list.controller.js @@ -1,156 +1,120 @@ const RecordList = require('../model/record-list.model'); const Account = require('../model/account.model'); -const User = require('../model/user.model'); -const Log = require('../model/log.model') +const asyncHandler = require('../utials/asyncHandler'); +const createLog = require('../utials/log'); +const ApiError = require('../utials/apiError'); - -//fatch all Records -const getAllRecord = async (req, res) => { - try { - const getAllRecord = await RecordList.find({}); - if (getAllRecord.length > 0) { - return res.status(200).json({ success: true, message: 'All Record Fatch Success', data: getAllRecord }) - } - else { - return res.status(404).json({ success: false, message: 'No record Found' }) - } +// transaction Records +const fetchAllRecords = asyncHandler(async (req, res) => { + const transactions = await RecordList.find({}).sort({ date: -1 }); + if (transactions.length === 0) { + return res.status(204).send(); } - catch (err) { - console.log(err); - return res.status(500).json({ success: false, message: 'Internal Server Error' }) - } -} + return res.status(200).json({ success: true, message: 'All Transaction Record Fetched Successfully', data: transactions }) + +}); // create new Transaction Records -const addNewRecord = async (req, res) => { - try { - const { addNote, amount, type, account, category, date } = req.body; - if (!amount || !account) { - return res.status(400).json({ success: false, message: "All Fields are required" }) - } - const user = await User.findOne({}); - if (!user) { - return res.status(404).json({ success: false, message: 'User not found' }); - } - const newRecordFormData = { addNote, amount, type, account, category, date}; - const newCreateRecord = await RecordList.create(newRecordFormData); - - const updateAmount = type === 'income' ? amount : -amount; - await Account.findByIdAndUpdate(account, { $inc: { amount: updateAmount }}, {new: true}); - - const accountDetails = await Account.findById(account) - if(!accountDetails) { - return res.status(404).json({success: false, message: 'Account not Found'}) - } - if (newCreateRecord) { - const accountName = accountDetails.name; - const message = type === 'income' ? `An ${type} ₹${amount} has been Credit in "${accountName}"Account.By: ${user.username}` : `An ${type} of ₹${amount} has been Debit From "${accountName}" Account By: ${user.username}`; - await Log.create({ userId: user._id, message }); - return res.status(201).json({ success: true, message: 'Record Add Success', data: newCreateRecord }) - } - else { - return res.status(400).json({ success: false, message: 'Failed to Create Record' }) - } +const createRecord = asyncHandler(async (req, res) => { + const { addNote, amount, type, account, category, date } = req.body; + if (!amount || !account) { + throw new ApiError(400, "All Fields are required"); } - catch (err) { - console.log(err); - return res.status(500).json({ success: false, message: 'something went worng.! please try again' }) + const newRecordFormData = { addNote, amount, type, account, category, date }; + const newCreateRecord = await RecordList.create(newRecordFormData); + const updateAmount = type === 'income' ? amount : -amount; + await Account.findByIdAndUpdate(account, { $inc: { amount: updateAmount } }, { new: true }); + + const accountDetails = await Account.findById(account) + if (!accountDetails) { + throw new ApiError(404, 'Account not found'); + } + if (newCreateRecord) { + const accountName = accountDetails.name; + const message = type === 'income' + ? `An ${type} of ₹${amount} has been credited to the "${accountName}" account.` + : `An ${type} of ₹${amount} has been debited from the "${accountName}" account`; + await createLog(message); + return res.status(201).json({ success: true, message: 'Record Add Success', data: newCreateRecord }) } -} + throw new ApiError(400, 'Failed to Create Record'); + +}); //getRecordDetails byId -const getRecordById = async (req, res) => { - try { - const getCurrentRecordById = req.params.id; - const getRecordDetailsById = await RecordList.findById(getCurrentRecordById); - if (!getRecordDetailsById) { - return res.status(404).json({ success: false, message: "Record Details Not Found" }) - } - else { - return res.status(200).json({ success: true, message: 'Record Details Fatch Success', data: getRecordDetailsById }) - } - } - catch (error) { - console.log(error); - return res.status(500).json({ success: false, message: 'something went worng.! please try again' }) +const fetchTransactionRecordById = asyncHandler(async (req, res) => { + const recordId = req.params.id; + const record = await RecordList.findById(recordId); + if (!record) { + throw new ApiError(404, 'Record Details Not Found') } -} + return res.status(200).json({ success: true, message: 'Record Details Fetch Success', data: record }) +}); //deleteRecord and update Amount -const deleteRecord = async (req, res) => { - try { - const record = await RecordList.findById(req.params.id); - if (!record) { - return res.status(404).json({ success: false, message: 'Record not found.' }); - } - const user = await User.findOne({}); - if (!user) { - return res.status(404).json({ success: false, message: 'User not found' }); - } - //if the transaction record is transfer typr - if (record.type === 'transfer' && record.fromAccount && record.toAccount) { - const fromAccount = await Account.findById(record.fromAccount); - const toAccount = await Account.findById(record.toAccount); - if (fromAccount && toAccount) { - fromAccount.amount += record.amount; - toAccount.amount -= record.amount; - await fromAccount.save(); - await toAccount.save(); - const message = `Transfer of ₹${record.amount} from "${fromAccount.name}" to "${toAccount.name}" was deleted By: ${user.username}`; - await Log.create({ userId: user._id, message }); - } - } else { - const updateAmount = record.type === 'income' ? -record.amount : record.amount; - await Account.findByIdAndUpdate(record.account, { $inc: { amount: updateAmount } }); - const message = record.type === 'income' ? `Transaction record of income ₹${record.amount} was deleted by: ${user.username}` : `Transaction record of expense ₹${record.amount} was deleted by: ${user.username}`; - await Log.create({ userId: user._id, message }) +const deleteRecordById = asyncHandler(async (req, res) => { + const record = await RecordList.findById(req.params.id); + if (!record) { + throw new ApiError(404, 'Transaction Record not found'); + } + // transfer type + if (record.type === 'transfer' && record.fromAccount && record.toAccount) { + const fromAccount = await Account.findById(record.fromAccount); + const toAccount = await Account.findById(record.toAccount); + if (fromAccount && toAccount) { + fromAccount.amount += record.amount; + toAccount.amount -= record.amount; + + await fromAccount.save(); + await toAccount.save(); + + const message = `Transfer of ₹${record.amount} from "${fromAccount.name}" to "${toAccount.name}" was deleted`; + await createLog(message); } - await RecordList.findByIdAndDelete(req.params.id); - return res.status(200).json({ success: true, message: 'Record deleted successfully.', data: record}); - } catch (err) { - console.error('Delete record error:', err.message); - return res.status(500).json({ success: false, message: 'Something went wrong. Please try again.' }); + } else { + const updateAmount = record.type === 'income' ? -record.amount : record.amount; + await Account.findByIdAndUpdate(record.account, { + $inc: { amount: updateAmount } + }); + const message = + record.type === 'income' + ? `Transaction record of income ₹${record.amount} was deleted` + : `Transaction record of expense ₹${record.amount} was deleted`; + await createLog(message); } -}; + await RecordList.findByIdAndDelete(req.params.id); + return res.status(200).json({ success: true, message: 'Record deleted successfully.', data: record }); +}); + //update Records Details -const updateRecord = async (req, res) => { - try { - const recordUpdateFormData = req.body; - const recordId = req.params.id; - const getRecordDetails = await RecordList.findById(recordId); - if (!getRecordDetails) { - return res.status(404).json({ success: false, message: 'Record not found' }); - } - const user = await User.findOne({}); - if (!user) { - return res.status(404).json({ success: false, message: 'User not found' }); - } - const updateAmount = getRecordDetails.type === 'income' ? -getRecordDetails.amount : getRecordDetails.amount; - await Account.findByIdAndUpdate(getRecordDetails.account, { $inc: { amount: updateAmount } }); - //Update the record of type income and expense - const updatedRecord = await RecordList.findByIdAndUpdate(recordId, recordUpdateFormData, { new: true }); - if (!updatedRecord) { - return res.status(400).json({ success: false, message: 'Failed to update record' }); - } - //updated transaction record - const { type, amount, account } = updatedRecord; - const updatedAmount = type === 'income' ? amount : -amount; - await Account.findByIdAndUpdate(account, { $inc: { amount: updatedAmount } }); - const message = `Amount ₹${getRecordDetails.amount} to ₹${updatedRecord.amount} And Category Type "${getRecordDetails.type}" to "${updatedRecord.type}" Transaction Update Successfully By: ${user.username} ` - await Log.create({ userId: user._id, message }) - return res.status(200).json({ success: true, message: 'Record updated successfully', data: updatedRecord }); +const updateRecordDetails = asyncHandler(async (req, res) => { + const recordUpdateFormData = req.body; + const recordId = req.params.id; + const getRecordDetails = await RecordList.findById(recordId); + if (!getRecordDetails) { + throw new ApiError(404, 'Transaction Record not found') } - catch (err) { - console.log(err); - return res.status(500).json({ success: false, message: 'something went worng.! please try again' }) + const updateAmount = getRecordDetails.type === 'income' ? -getRecordDetails.amount : getRecordDetails.amount; + await Account.findByIdAndUpdate(getRecordDetails.account, { $inc: { amount: updateAmount } }); + //Update the record of type income and expense + const updatedRecord = await RecordList.findByIdAndUpdate(recordId, recordUpdateFormData, { new: true }); + if (!updatedRecord) { + return res.status(400).json({ success: false, message: 'Failed to update record' }); } -} + //updated transaction record + const { type, amount, account } = updatedRecord; + const updatedAmount = type === 'income' ? amount : -amount; + await Account.findByIdAndUpdate(account, { $inc: { amount: updatedAmount } }); + const message = `Amount ₹${getRecordDetails.amount} to ₹${updatedRecord.amount} And Category Type "${getRecordDetails.type}" to "${updatedRecord.type}" Transaction Update Successfully`; + await createLog(message); + return res.status(200).json({ success: true, message: 'Record updated successfully', data: updatedRecord }); +}); -module.exports = { getAllRecord, addNewRecord, deleteRecord, getRecordById, updateRecord } +module.exports = { fetchAllRecords, createRecord, fetchTransactionRecordById, deleteRecordById, updateRecordDetails } diff --git a/database/db.js b/database/db.js index c5c64b8..dc9b2c5 100644 --- a/database/db.js +++ b/database/db.js @@ -1,15 +1,13 @@ const mongoose = require('mongoose'); - -const ConnectToDB = async () => { - - mongoose.connect(process.env.MONGO_URI) +const ConnectToDB = async () => { try { - - console.log('MongoDb Connected Successful....') + const conn = await mongoose.connect(process.env.MONGO_URI) + console.log(`Database Connected: ${conn.connection.host} (${conn.connection.name})`); } catch (error) { - console.error('Failed To Connect Datebase...',error) + console.error('Failed To Connect Database...', error); + process.exit(1); } } diff --git a/middleware/errorHandler.js b/middleware/errorHandler.js new file mode 100644 index 0000000..f35d8d0 --- /dev/null +++ b/middleware/errorHandler.js @@ -0,0 +1,13 @@ +const errorHandler = (err, req, res, next) => { + if (res.headersSent) { + return next(err); + } + const statusCode = err.statusCode || 500; + const errorResponse = { + success: false, + message: err.message || 'Something went wrong!', + }; + res.status(statusCode).json(errorResponse); +}; + +module.exports = errorHandler; \ No newline at end of file diff --git a/model/budget.model.js b/model/budget.model.js index 8a0f767..3475f27 100644 --- a/model/budget.model.js +++ b/model/budget.model.js @@ -1,5 +1,5 @@ const mongoose = require('mongoose'); -const BUdgetSchema = new mongoose.Schema({ +const BudgetSchema = new mongoose.Schema({ category: { type: mongoose.Schema.Types.ObjectId, ref: 'Category', @@ -16,4 +16,4 @@ const BUdgetSchema = new mongoose.Schema({ }, { timestamps: true }); -module.exports = mongoose.model('Budget', BUdgetSchema); \ No newline at end of file +module.exports = mongoose.model('Budget', BudgetSchema); \ No newline at end of file diff --git a/model/category.model.js b/model/category.model.js index 4aa3329..7b392d5 100644 --- a/model/category.model.js +++ b/model/category.model.js @@ -1,6 +1,5 @@ const mongoose = require('mongoose'); -//category schema const CategorySchema = new mongoose.Schema({ name: { type: String, diff --git a/package-lock.json b/package-lock.json index e37b5f9..c7efe6f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,9 +9,11 @@ "version": "1.0.0", "license": "ISC", "dependencies": { + "body-parser": "^2.2.0", "cors": "^2.8.5", "dotenv": "^16.5.0", "express": "^5.1.0", + "express-async-handler": "^1.2.0", "jsonwebtoken": "^9.0.2", "mongoose": "^8.16.0", "nodemon": "^3.1.10" @@ -425,6 +427,12 @@ "url": "https://opencollective.com/express" } }, + "node_modules/express-async-handler": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/express-async-handler/-/express-async-handler-1.2.0.tgz", + "integrity": "sha512-rCSVtPXRmQSW8rmik/AIb2P0op6l7r1fMW538yyvTMltCO4xQEWMmobfrIxN2V1/mVrgxB8Az3reYF6yUZw37w==", + "license": "MIT" + }, "node_modules/fill-range": { "version": "7.1.1", "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", diff --git a/package.json b/package.json index c023adb..41e5c5b 100644 --- a/package.json +++ b/package.json @@ -12,9 +12,11 @@ "license": "ISC", "description": "", "dependencies": { + "body-parser": "^2.2.0", "cors": "^2.8.5", "dotenv": "^16.5.0", "express": "^5.1.0", + "express-async-handler": "^1.2.0", "jsonwebtoken": "^9.0.2", "mongoose": "^8.16.0", "nodemon": "^3.1.10" diff --git a/routes/account.route.js b/routes/account.route.js index c300ed1..808b3f8 100644 --- a/routes/account.route.js +++ b/routes/account.route.js @@ -1,15 +1,15 @@ const express = require('express'); const router= express.Router(); -const {getAllAccount, getAccountById, addNewAccount, updateAccount, deleteAccount, transferAmount, updateTransferAmount} = require('../controllers/account.controller'); +const {fetchAllAccounts, fetchAccountById, createAccount, removeAccountById, updateAccountDetails, transferAmountBetweenAccounts, updateTransferTransaction} = require('../controllers/account.controller'); //acount related routes here -router.get('/getAllAccount', getAllAccount); -router.get('get/:id',getAccountById ) -router.post('/addAccount', addNewAccount); -router.put('/updateAccount',updateAccount); -router.delete('/deleteAccount/:id', deleteAccount); -router.post('/transferAmount', transferAmount); -router.put('/updateTransferAmount', updateTransferAmount) +router.get('/', fetchAllAccounts); +router.get('/:id',fetchAccountById ) +router.post('/', createAccount); +router.put('/:id',updateAccountDetails); +router.delete('/:id', removeAccountById); +router.post('/transfer', transferAmountBetweenAccounts); +router.put('/transfer/:id', updateTransferTransaction) module.exports = router; \ No newline at end of file diff --git a/routes/budget.route.js b/routes/budget.route.js index 33f9505..39aa4d2 100644 --- a/routes/budget.route.js +++ b/routes/budget.route.js @@ -1,12 +1,12 @@ const express = require('express'); const router= express.Router(); -const {getAllBudget, addNewBudget, updateBudget,deleteBudget} = require('../controllers/budget.controller'); +const {fetchAllBudgets,createBudget, deleteBudgetById, updateBudgetDetails } = require('../controllers/budget.controller'); //budget related routes here -router.post('/addNewBudget', addNewBudget); -router.get('/getAllBudget', getAllBudget); -router.delete('/deleteBudget/:id', deleteBudget); -router.put('/updateBudget/:id', updateBudget) +router.get('/', fetchAllBudgets); +router.post('/', createBudget); +router.delete('/:id',deleteBudgetById); +router.put('/:id', updateBudgetDetails) module.exports = router; \ No newline at end of file diff --git a/routes/category.route.js b/routes/category.route.js index 5df3f02..fb9a74a 100644 --- a/routes/category.route.js +++ b/routes/category.route.js @@ -1,12 +1,12 @@ -const {getAllCategory, addNewCategory, updateCategory, deleteCategory, getCategoryById} = require('../controllers/category.controller') +const {fetchAllCategories, fetchCategoryById, createCategory, deleteCategoryById, updateCategoryDetails} = require('../controllers/category.controller') const express = require('express'); const router= express.Router() //category related routes here -router.get('/getAllCategory', getAllCategory); -router.get('/getcategoryById/:id', getCategoryById) -router.post('/addCategory',addNewCategory); -router.delete('/deleteCategory/:id', deleteCategory); -router.put('/updateCategory/:id',updateCategory ); +router.get('/', fetchAllCategories); +router.get('/:id', fetchCategoryById) +router.post('/', createCategory); +router.delete('/:id', deleteCategoryById); +router.put('/:id', updateCategoryDetails ); module.exports = router; \ No newline at end of file diff --git a/routes/log.route.js b/routes/log.route.js index 8a6e643..2f49535 100644 --- a/routes/log.route.js +++ b/routes/log.route.js @@ -1,9 +1,9 @@ const express= require('express'); const router = express.Router(); -const {getAllLogs} = require('../controllers/log-activity.controller'); +const {fetchAllLogs} = require('../controllers/log-activity.controller'); -router.get('/getAllLogs', getAllLogs); +router.get('/', fetchAllLogs); module.exports = router; \ No newline at end of file diff --git a/routes/record-list.route.js b/routes/record-list.route.js index 7319490..eba737e 100644 --- a/routes/record-list.route.js +++ b/routes/record-list.route.js @@ -1,15 +1,15 @@ -const {getAllRecord, addNewRecord, deleteRecord, getRecordById, updateRecord} = require('../controllers/record-list.controller'); +const {fetchAllRecords, createRecord, fetchTransactionRecordById, updateRecordDetails, deleteRecordById} = require('../controllers/record-list.controller'); const express = require('express'); const router =express.Router(); // transaction records routes realated routes here -router.get('/getAllRecord', getAllRecord); -router.post('/addNewRecord', addNewRecord); -router.get('/get/:id',getRecordById ) -router.delete('/deleteRecord/:id', deleteRecord); -router.put('/updateRecord/:id', updateRecord); +router.get('/', fetchAllRecords); +router.post('/', createRecord); +router.get('/:id', fetchTransactionRecordById ) +router.delete('/:id', deleteRecordById); +router.put('/:id', updateRecordDetails); diff --git a/server.js b/server.js index 975bbff..f88c0ba 100644 --- a/server.js +++ b/server.js @@ -1,41 +1,38 @@ const express = require('express'); const connectToDB = require('./database/db'); -const cors= require('cors'); +const bodyParser = require('body-parser'); +const errorHandler = require('./middleware/errorHandler') +const cors = require('cors') require('dotenv').config(); -const app = express(); +const app = express(); -//category route -const categoryRoutes = require('./routes/category.route'); -//account routes -const accountRoutes = require('./routes/account.route'); - -const recordRoutes =require('./routes/record-list.route'); -const logRoutes = require('./routes/log.route'); -const budgetRoutes = require('./routes/budget.route'); +//route +const categories = require('./routes/category.route'); +const accounts = require('./routes/account.route'); +const records = require('./routes/record-list.route'); +const logs = require('./routes/log.route'); +const budgets= require('./routes/budget.route'); +const allowOrigin = process.env.ORIGIN_URL; app.use(express.json()); - -const allowedOrigins = ['http://localhost:4200']; -if (process.env.CORS_ORIGIN) { - allowedOrigins.push(process.env.CORS_ORIGIN); -} -app.use(cors({ origin: allowedOrigins })); - +app.use(cors({ origin: [allowOrigin], credentials: true })) +app.use(bodyParser.urlencoded({ extended: true })) const PORT = process.env.PORT || 3000; connectToDB(); -app.use('/api/category', categoryRoutes); -app.use('/api/account',accountRoutes ); -app.use('/api/record', recordRoutes); -app.use('/api/log', logRoutes); -app.use('/api/budget', budgetRoutes) +app.use('/api/categories',categories); +app.use('/api/accounts', accounts); +app.use('/api/records', records); +app.use('/api/logs', logs); +app.use('/api/budgets', budgets) -app.listen(PORT, ()=>{ - console.log(`server running on port ${PORT}`) +app.use(errorHandler); +app.listen(PORT, () => { + console.log(`server running on port ${PORT}`) }) module.exports = app; -// This is the main entry point for the Express application, setting up routes and middleware. \ No newline at end of file +// This is the main entry point for the Express application, setting up routes and middleware. diff --git a/utials/apiError.js b/utials/apiError.js new file mode 100644 index 0000000..f32f900 --- /dev/null +++ b/utials/apiError.js @@ -0,0 +1,11 @@ +class ApiError extends Error { + constructor(statusCode, message,error) { + super(message); + this.statusCode = statusCode; + this.status = statusCode >= 400 && statusCode < 500 ? 'fail' : 'error'; + this.error = error; + this.isOperational = true; + Error.captureStackTrace(this, this.constructor); + } +} +module.exports = ApiError; diff --git a/utials/asyncHandler.js b/utials/asyncHandler.js new file mode 100644 index 0000000..321718c --- /dev/null +++ b/utials/asyncHandler.js @@ -0,0 +1,11 @@ +const asyncHandler = (fn) => { + return async (req, res, next) => { + try { + await fn(req, res, next); + } catch (error) { + next(error); + } + }; +}; + +module.exports = asyncHandler; diff --git a/utials/log.activity.js b/utials/log.activity.js deleted file mode 100644 index f8e5409..0000000 --- a/utials/log.activity.js +++ /dev/null @@ -1,18 +0,0 @@ -// const Log = require('../model/log.model'); -// const User = require('../model/user.model'); - -// const createLog = async (message) => { -// try { -// const user = await User.findOne({}); -// if (!user) { -// return res.status(404).json({success: false, message: 'User Not Found'}) -// return; -// } -// const log = new Log({ userId: user._id, message }); -// await log.save(); -// } catch (error) { -// console.error(' Logging failed:', error.message); -// } -// }; - -// module.exports = {createLog}; diff --git a/utials/log.js b/utials/log.js new file mode 100644 index 0000000..3491d7f --- /dev/null +++ b/utials/log.js @@ -0,0 +1,15 @@ +const User = require('../model/user.model'); +const Log = require('../model/log.model'); +const ApiError = require('../utials/apiError'); + + +const createLog = async (message) => { + const user = await User.findOne(); + if (!user) { + throw new ApiError(404, 'User not found'); + } + const logMessage = `${message} By: ${user.username}`; + await Log.create({ userId: user._id, message: logMessage }); +}; + +module.exports = createLog;