From 86d7e2d25a70f1dbbff92ccebfc3b0a6bb5f03cd Mon Sep 17 00:00:00 2001 From: Akki meena Date: Wed, 23 Jul 2025 15:54:31 +0530 Subject: [PATCH 1/3] Initial code upload. --- controllers/account.controller.js | 298 +++++ controllers/budget.controller.js | 100 ++ controllers/category.controller.js | 139 +++ controllers/log-activity.controller.js | 22 + controllers/record-list.controller.js | 156 +++ database/db.js | 16 + index.js | 0 model/account.model.js | 26 + model/budget.model.js | 19 + model/category.model.js | 17 + model/log.model.js | 19 + model/record-list.model.js | 49 + model/user.model.js | 23 + package-lock.json | 1489 ++++++++++++++++++++++++ package.json | 21 + routes/account.route.js | 15 + routes/budget.route.js | 12 + routes/category.route.js | 12 + routes/log.route.js | 9 + routes/record-list.route.js | 16 + server.js | 34 + utials/log.activity.js | 18 + 22 files changed, 2510 insertions(+) create mode 100644 controllers/account.controller.js create mode 100644 controllers/budget.controller.js create mode 100644 controllers/category.controller.js create mode 100644 controllers/log-activity.controller.js create mode 100644 controllers/record-list.controller.js create mode 100644 database/db.js create mode 100644 index.js create mode 100644 model/account.model.js create mode 100644 model/budget.model.js create mode 100644 model/category.model.js create mode 100644 model/log.model.js create mode 100644 model/record-list.model.js create mode 100644 model/user.model.js create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 routes/account.route.js create mode 100644 routes/budget.route.js create mode 100644 routes/category.route.js create mode 100644 routes/log.route.js create mode 100644 routes/record-list.route.js create mode 100644 server.js create mode 100644 utials/log.activity.js diff --git a/controllers/account.controller.js b/controllers/account.controller.js new file mode 100644 index 0000000..4749c37 --- /dev/null +++ b/controllers/account.controller.js @@ -0,0 +1,298 @@ +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') + + +//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' }) + } + } + catch (error) { + console.error('Faiiled to Fatch Accounts', error.message); + return res.status(500).json({ + success: false, message: 'something went wrong! please try again' + }) + } +} + +//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', }); + } +}; + + +//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(); + } + } + 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.' + }); + } +}; + + +// 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' }); + } +}; + + +// 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 + } + await oldFromAccount.save(); + 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' }); + } +}; + +//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 }) + } + } + catch (error) { + console.log(error); + return res.status(500).json({ success: false, message: 'something went wrong! please try again.' }) + } +} + + +//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) { + await RecordList.findByIdAndDelete(recordId); + 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}`; + await record.save(); + message += `transaction record updated by: ${user.username}`; + } + } + //if user have no record exists and new Amount more then 0 create record + else if (!recordId && newAmount > 0) { + const createdRecord = await RecordList.create({ + amount: newAmount, + type: 'income', + account: account._id, + addNote: `Account "${name}" updated with initial amount ₹${newAmount}`, + isInitialEntry: true + }); + account.recordId = createdRecord._id; + await account.save(); + message += `Initial transaction record created)`; + } + 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' }); + } +}; + + +module.exports = { getAllAccount, addNewAccount, getAccountById, deleteAccount, transferAmount, updateAccount, updateTransferAmount }; \ No newline at end of file diff --git a/controllers/budget.controller.js b/controllers/budget.controller.js new file mode 100644 index 0000000..5b47da4 --- /dev/null +++ b/controllers/budget.controller.js @@ -0,0 +1,100 @@ +const Budget = require('../model/budget.model'); +const User = require('../model/user.model'); +const Log = require('../model/log.model'); +const Category = require('../model/category.model'); + + + +//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' }) + } +} + + +//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 + }); + + 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' }); + } +}; + + + +//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' }); + } +}; + + +//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 }) + } + catch (error) { + console.error(error); + return res.status(500).json({ success: false, message: 'something went wrong! please try again' }) + + } +} + +module.exports = { getAllBudget, addNewBudget, updateBudget, deleteBudget }; diff --git a/controllers/category.controller.js b/controllers/category.controller.js new file mode 100644 index 0000000..bb61dee --- /dev/null +++ b/controllers/category.controller.js @@ -0,0 +1,139 @@ +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'); + + +//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' }) + } + } + catch (error) { + console.log(err); + return res.state(500).json({ success: false, message: 'Something went wrong! please try again' }) + } +} +//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' }) + } + } + catch (error) { + return res.status(500).json({ + success: false, + message: 'Something went wrong! please try again' + }) + } +} +//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.' }); + } +}; + + +//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' }) + } +} + +//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 }) + } + } + catch (error) { + console.log(error); + return res.status(500).json({ success: false, message: "something went wrong! please try again" }) + } +} + +module.exports = { getAllCategory, addNewCategory, updateCategory, deleteCategory, getCategoryById } \ No newline at end of file diff --git a/controllers/log-activity.controller.js b/controllers/log-activity.controller.js new file mode 100644 index 0000000..4cce4dc --- /dev/null +++ b/controllers/log-activity.controller.js @@ -0,0 +1,22 @@ +const Log = require('../model/log.model') + +//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' }); + } +} + + +module.exports = { getAllLogs } + + diff --git a/controllers/record-list.controller.js b/controllers/record-list.controller.js new file mode 100644 index 0000000..08c14f9 --- /dev/null +++ b/controllers/record-list.controller.js @@ -0,0 +1,156 @@ +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') + + +//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' }) + } + } + catch (err) { + console.log(err); + return res.status(500).json({ success: false, message: 'Internal Server Error' }) + } +} + +// 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' }) + } + } + catch (err) { + console.log(err); + return res.status(500).json({ success: false, message: 'something went worng.! please try again' }) + } +} + + +//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' }) + } +} + +//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 }) + } + 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.' }); + } +}; + + +//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 }); + } + catch (err) { + console.log(err); + return res.status(500).json({ success: false, message: 'something went worng.! please try again' }) + } +} + + +module.exports = { getAllRecord, addNewRecord, deleteRecord, getRecordById, updateRecord } + + + diff --git a/database/db.js b/database/db.js new file mode 100644 index 0000000..c5c64b8 --- /dev/null +++ b/database/db.js @@ -0,0 +1,16 @@ +const mongoose = require('mongoose'); + + +const ConnectToDB = async () => { + + mongoose.connect(process.env.MONGO_URI) + try { + + console.log('MongoDb Connected Successful....') + } + catch (error) { + console.error('Failed To Connect Datebase...',error) + } +} + +module.exports = ConnectToDB; \ No newline at end of file diff --git a/index.js b/index.js new file mode 100644 index 0000000..e69de29 diff --git a/model/account.model.js b/model/account.model.js new file mode 100644 index 0000000..8c4ca3e --- /dev/null +++ b/model/account.model.js @@ -0,0 +1,26 @@ +const mongoose = require('mongoose') + +const AccountSchema = new mongoose.Schema({ + name: { + type: String, + required: true, + + }, + amount: { + type: Number, + required: true, + default: 0, + }, + type: { + type: String, + default: 'income' + }, + recordId: { + type: mongoose.Schema.Types.ObjectId, + ref: 'RecordList', + default: null + } + +}, { timestamps: true }) + +module.exports = mongoose.model('Account', AccountSchema); \ No newline at end of file diff --git a/model/budget.model.js b/model/budget.model.js new file mode 100644 index 0000000..8a0f767 --- /dev/null +++ b/model/budget.model.js @@ -0,0 +1,19 @@ +const mongoose = require('mongoose'); +const BUdgetSchema = new mongoose.Schema({ + category: { + type: mongoose.Schema.Types.ObjectId, + ref: 'Category', + required: true, + }, + limit: { + type: Number, + required: true, + }, + date: { + type: Date, + default: Date.now, + } + +}, { timestamps: true }); + +module.exports = mongoose.model('Budget', BUdgetSchema); \ No newline at end of file diff --git a/model/category.model.js b/model/category.model.js new file mode 100644 index 0000000..4aa3329 --- /dev/null +++ b/model/category.model.js @@ -0,0 +1,17 @@ +const mongoose = require('mongoose'); + +//category schema +const CategorySchema = new mongoose.Schema({ + name: { + type: String, + required: true, + }, + + type: { + type: String, + enum: ['income', 'expense'], + required: true, + } + +}, {timestamps: true}) +module.exports = mongoose.model('Category',CategorySchema) \ No newline at end of file diff --git a/model/log.model.js b/model/log.model.js new file mode 100644 index 0000000..79e5cde --- /dev/null +++ b/model/log.model.js @@ -0,0 +1,19 @@ +const mongoose = require('mongoose'); + +const LogSchema = new mongoose.Schema({ + userId: { + type: mongoose.Schema.Types.ObjectId, + ref: 'User', + required: true, + }, + message: { + type: String, + required: true, + }, + date: { + type: Date, + default: Date.now, + } +}); + +module.exports = mongoose.model('Log', LogSchema) \ No newline at end of file diff --git a/model/record-list.model.js b/model/record-list.model.js new file mode 100644 index 0000000..04257d8 --- /dev/null +++ b/model/record-list.model.js @@ -0,0 +1,49 @@ +const mongoose = require('mongoose'); + +const RecordListSchema = new mongoose.Schema({ + addNote: { + type: String, + }, + amount: { + type: Number, + required: true, + }, + type: { + type: String, + enum: ['income', 'expense', 'transfer'], + required: true, + }, + category: { + type: mongoose.Schema.Types.ObjectId, + ref: 'Category', + }, + account: { + type: mongoose.Schema.Types.ObjectId, + ref: 'Account', + required: true + }, + date: { + type: Date, + default: Date.now, + }, + isInitialEntry: { + type : Boolean, + default: false, + }, + isTransfer: { + type: Boolean, + default: false, + }, + fromAccount: { + type: mongoose.Schema.Types.ObjectId, + ref: 'Account' + }, + toAccount: { + type: mongoose.Schema.Types.ObjectId, + ref: 'Account' + } + +}, { timestamps: true }) + + +module.exports = mongoose.model('RecordList', RecordListSchema); \ No newline at end of file diff --git a/model/user.model.js b/model/user.model.js new file mode 100644 index 0000000..309ffbf --- /dev/null +++ b/model/user.model.js @@ -0,0 +1,23 @@ +const mongoose = require('mongoose'); + +const UserSchema = new mongoose.Schema({ + username: { + type: String, + required: true, + }, + email: { + type: String, + required: true, + }, + phone: { + type: String, + required: true, + }, + password: { + type: String, + required: true + } + +}, {timestamps: true}) + +module.exports = mongoose.model('User', UserSchema) \ No newline at end of file diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..e37b5f9 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,1489 @@ +{ + "name": "backend", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "backend", + "version": "1.0.0", + "license": "ISC", + "dependencies": { + "cors": "^2.8.5", + "dotenv": "^16.5.0", + "express": "^5.1.0", + "jsonwebtoken": "^9.0.2", + "mongoose": "^8.16.0", + "nodemon": "^3.1.10" + } + }, + "node_modules/@mongodb-js/saslprep": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@mongodb-js/saslprep/-/saslprep-1.3.0.tgz", + "integrity": "sha512-zlayKCsIjYb7/IdfqxorK5+xUMyi4vOKcFy10wKJYc63NSdKI8mNME+uJqfatkPmOSMMUiojrL58IePKBm3gvQ==", + "license": "MIT", + "dependencies": { + "sparse-bitfield": "^3.0.3" + } + }, + "node_modules/@types/webidl-conversions": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/@types/webidl-conversions/-/webidl-conversions-7.0.3.tgz", + "integrity": "sha512-CiJJvcRtIgzadHCYXw7dqEnMNRjhGZlYK05Mj9OyktqV8uVT8fD2BFOB7S1uwBE3Kj2Z+4UyPmFw/Ixgw/LAlA==", + "license": "MIT" + }, + "node_modules/@types/whatwg-url": { + "version": "11.0.5", + "resolved": "https://registry.npmjs.org/@types/whatwg-url/-/whatwg-url-11.0.5.tgz", + "integrity": "sha512-coYR071JRaHa+xoEvvYqvnIHaVqaYrLPbsufM9BF63HkwI5Lgmy2QR8Q5K/lYDYo5AK82wOvSOS0UsLTpTG7uQ==", + "license": "MIT", + "dependencies": { + "@types/webidl-conversions": "*" + } + }, + "node_modules/accepts": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", + "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", + "license": "MIT", + "dependencies": { + "mime-types": "^3.0.0", + "negotiator": "^1.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/anymatch": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", + "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", + "license": "ISC", + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "license": "MIT" + }, + "node_modules/binary-extensions": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz", + "integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==", + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/body-parser": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.2.0.tgz", + "integrity": "sha512-02qvAaxv8tp7fBa/mw1ga98OGm+eCbqzJOKoRt70sLmfEEi+jyBYVTDGfCL/k06/4EMk/z01gCe7HoCH/f2LTg==", + "license": "MIT", + "dependencies": { + "bytes": "^3.1.2", + "content-type": "^1.0.5", + "debug": "^4.4.0", + "http-errors": "^2.0.0", + "iconv-lite": "^0.6.3", + "on-finished": "^2.4.1", + "qs": "^6.14.0", + "raw-body": "^3.0.0", + "type-is": "^2.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/brace-expansion": { + "version": "1.1.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz", + "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/braces": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "license": "MIT", + "dependencies": { + "fill-range": "^7.1.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/bson": { + "version": "6.10.4", + "resolved": "https://registry.npmjs.org/bson/-/bson-6.10.4.tgz", + "integrity": "sha512-WIsKqkSC0ABoBJuT1LEX+2HEvNmNKKgnTAyd0fL8qzK4SH2i9NXg+t08YtdZp/V9IZ33cxe3iV4yM0qg8lMQng==", + "license": "Apache-2.0", + "engines": { + "node": ">=16.20.1" + } + }, + "node_modules/buffer-equal-constant-time": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", + "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==", + "license": "BSD-3-Clause" + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/chokidar": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", + "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", + "license": "MIT", + "dependencies": { + "anymatch": "~3.1.2", + "braces": "~3.0.2", + "glob-parent": "~5.1.2", + "is-binary-path": "~2.1.0", + "is-glob": "~4.0.1", + "normalize-path": "~3.0.0", + "readdirp": "~3.6.0" + }, + "engines": { + "node": ">= 8.10.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + } + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "license": "MIT" + }, + "node_modules/content-disposition": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.0.0.tgz", + "integrity": "sha512-Au9nRL8VNUut/XSzbQA38+M78dzP4D+eqg3gfJHMIHHYa3bg067xj1KxMUWj+VULbiZMowKngFFbKczUrNJ1mg==", + "license": "MIT", + "dependencies": { + "safe-buffer": "5.2.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", + "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", + "license": "MIT", + "engines": { + "node": ">=6.6.0" + } + }, + "node_modules/cors": { + "version": "2.8.5", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz", + "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==", + "license": "MIT", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/debug": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.1.tgz", + "integrity": "sha512-KcKCqiftBJcZr++7ykoDIEwSa3XWowTfNPo92BYxjXiyYEVrUQh2aLyhxBCwww+heortUFxEJYcRzosstTEBYQ==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/dotenv": { + "version": "16.5.0", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.5.0.tgz", + "integrity": "sha512-m/C+AwOAr9/W1UOIZUo232ejMNnJAJtYQjUbHoNTBNTJSvqzzDh7vnrei3o3r3m9blf6ZoDkvcw0VmozNRFJxg==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ecdsa-sig-formatter": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", + "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", + "license": "Apache-2.0", + "dependencies": { + "safe-buffer": "^5.0.1" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/express/-/express-5.1.0.tgz", + "integrity": "sha512-DT9ck5YIRU+8GYzzU5kT3eHGA5iL+1Zd0EutOmTE9Dtk+Tvuzd23VBU+ec7HPNSTxXYO55gPV/hq4pSBJDjFpA==", + "license": "MIT", + "dependencies": { + "accepts": "^2.0.0", + "body-parser": "^2.2.0", + "content-disposition": "^1.0.0", + "content-type": "^1.0.5", + "cookie": "^0.7.1", + "cookie-signature": "^1.2.1", + "debug": "^4.4.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "finalhandler": "^2.1.0", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "merge-descriptors": "^2.0.0", + "mime-types": "^3.0.0", + "on-finished": "^2.4.1", + "once": "^1.4.0", + "parseurl": "^1.3.3", + "proxy-addr": "^2.0.7", + "qs": "^6.14.0", + "range-parser": "^1.2.1", + "router": "^2.2.0", + "send": "^1.1.0", + "serve-static": "^2.2.0", + "statuses": "^2.0.1", + "type-is": "^2.0.1", + "vary": "^1.1.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/fill-range": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "license": "MIT", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/finalhandler": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.0.tgz", + "integrity": "sha512-/t88Ty3d5JWQbWYgaOGCCYfXRwV1+be02WqYYlL6h0lEiUAMPM8o8qKGO01YIkOHzka2up08wvgYD0mDiI+q3Q==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "on-finished": "^2.4.1", + "parseurl": "^1.3.3", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", + "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/http-errors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", + "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", + "license": "MIT", + "dependencies": { + "depd": "2.0.0", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/http-errors/node_modules/statuses": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/iconv-lite": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", + "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/ignore-by-default": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/ignore-by-default/-/ignore-by-default-1.0.1.tgz", + "integrity": "sha512-Ius2VYcGNk7T90CppJqcIkS5ooHUZyIQK+ClZfMfMNFEF9VSE73Fq+906u/CWu92x4gzZMWOwfFYckPObzdEbA==", + "license": "ISC" + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-binary-path": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", + "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", + "license": "MIT", + "dependencies": { + "binary-extensions": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "license": "MIT", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/is-promise": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", + "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", + "license": "MIT" + }, + "node_modules/jsonwebtoken": { + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.2.tgz", + "integrity": "sha512-PRp66vJ865SSqOlgqS8hujT5U4AOgMfhrwYIuIhfKaoSCZcirrmASQr8CX7cUg+RMih+hgznrjp99o+W4pJLHQ==", + "license": "MIT", + "dependencies": { + "jws": "^3.2.2", + "lodash.includes": "^4.3.0", + "lodash.isboolean": "^3.0.3", + "lodash.isinteger": "^4.0.4", + "lodash.isnumber": "^3.0.3", + "lodash.isplainobject": "^4.0.6", + "lodash.isstring": "^4.0.1", + "lodash.once": "^4.0.0", + "ms": "^2.1.1", + "semver": "^7.5.4" + }, + "engines": { + "node": ">=12", + "npm": ">=6" + } + }, + "node_modules/jwa": { + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-1.4.2.tgz", + "integrity": "sha512-eeH5JO+21J78qMvTIDdBXidBd6nG2kZjg5Ohz/1fpa28Z4CcsWUzJ1ZZyFq/3z3N17aZy+ZuBoHljASbL1WfOw==", + "license": "MIT", + "dependencies": { + "buffer-equal-constant-time": "^1.0.1", + "ecdsa-sig-formatter": "1.0.11", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/jws": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/jws/-/jws-3.2.2.tgz", + "integrity": "sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA==", + "license": "MIT", + "dependencies": { + "jwa": "^1.4.1", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/kareem": { + "version": "2.6.3", + "resolved": "https://registry.npmjs.org/kareem/-/kareem-2.6.3.tgz", + "integrity": "sha512-C3iHfuGUXK2u8/ipq9LfjFfXFxAZMQJJq7vLS45r3D9Y2xQ/m4S8zaR4zMLFWh9AsNPXmcFfUDhTEO8UIC/V6Q==", + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/lodash.includes": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz", + "integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==", + "license": "MIT" + }, + "node_modules/lodash.isboolean": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz", + "integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==", + "license": "MIT" + }, + "node_modules/lodash.isinteger": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz", + "integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==", + "license": "MIT" + }, + "node_modules/lodash.isnumber": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz", + "integrity": "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw==", + "license": "MIT" + }, + "node_modules/lodash.isplainobject": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", + "integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==", + "license": "MIT" + }, + "node_modules/lodash.isstring": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz", + "integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==", + "license": "MIT" + }, + "node_modules/lodash.once": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz", + "integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==", + "license": "MIT" + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz", + "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/memory-pager": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/memory-pager/-/memory-pager-1.5.0.tgz", + "integrity": "sha512-ZS4Bp4r/Zoeq6+NLJpP+0Zzm0pR8whtGPf1XExKLJBAczGMnSi3It14OiNCStjQjM6NU1okjQGSxgEZN8eBYKg==", + "license": "MIT" + }, + "node_modules/merge-descriptors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", + "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.1.tgz", + "integrity": "sha512-xRc4oEhT6eaBpU1XF7AjpOFD+xQmXNB5OVKwp4tqCuBpHLS/ZbBDrc07mYTDqVMg6PfxUjjNp85O6Cd2Z/5HWA==", + "license": "MIT", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/mongodb": { + "version": "6.17.0", + "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-6.17.0.tgz", + "integrity": "sha512-neerUzg/8U26cgruLysKEjJvoNSXhyID3RvzvdcpsIi2COYM3FS3o9nlH7fxFtefTb942dX3W9i37oPfCVj4wA==", + "license": "Apache-2.0", + "dependencies": { + "@mongodb-js/saslprep": "^1.1.9", + "bson": "^6.10.4", + "mongodb-connection-string-url": "^3.0.0" + }, + "engines": { + "node": ">=16.20.1" + }, + "peerDependencies": { + "@aws-sdk/credential-providers": "^3.188.0", + "@mongodb-js/zstd": "^1.1.0 || ^2.0.0", + "gcp-metadata": "^5.2.0", + "kerberos": "^2.0.1", + "mongodb-client-encryption": ">=6.0.0 <7", + "snappy": "^7.2.2", + "socks": "^2.7.1" + }, + "peerDependenciesMeta": { + "@aws-sdk/credential-providers": { + "optional": true + }, + "@mongodb-js/zstd": { + "optional": true + }, + "gcp-metadata": { + "optional": true + }, + "kerberos": { + "optional": true + }, + "mongodb-client-encryption": { + "optional": true + }, + "snappy": { + "optional": true + }, + "socks": { + "optional": true + } + } + }, + "node_modules/mongodb-connection-string-url": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/mongodb-connection-string-url/-/mongodb-connection-string-url-3.0.2.tgz", + "integrity": "sha512-rMO7CGo/9BFwyZABcKAWL8UJwH/Kc2x0g72uhDWzG48URRax5TCIcJ7Rc3RZqffZzO/Gwff/jyKwCU9TN8gehA==", + "license": "Apache-2.0", + "dependencies": { + "@types/whatwg-url": "^11.0.2", + "whatwg-url": "^14.1.0 || ^13.0.0" + } + }, + "node_modules/mongoose": { + "version": "8.16.0", + "resolved": "https://registry.npmjs.org/mongoose/-/mongoose-8.16.0.tgz", + "integrity": "sha512-gLuAZsbwY0PHjrvfuXvUkUq9tXjyAjN3ioXph5Y6Seu7/Uo8xJaM+rrMbL/x34K4T3UTgtXRyfoq1YU16qKyIw==", + "license": "MIT", + "dependencies": { + "bson": "^6.10.4", + "kareem": "2.6.3", + "mongodb": "~6.17.0", + "mpath": "0.9.0", + "mquery": "5.0.0", + "ms": "2.1.3", + "sift": "17.1.3" + }, + "engines": { + "node": ">=16.20.1" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/mongoose" + } + }, + "node_modules/mpath": { + "version": "0.9.0", + "resolved": "https://registry.npmjs.org/mpath/-/mpath-0.9.0.tgz", + "integrity": "sha512-ikJRQTk8hw5DEoFVxHG1Gn9T/xcjtdnOKIU1JTmGjZZlg9LST2mBLmcX3/ICIbgJydT2GOc15RnNy5mHmzfSew==", + "license": "MIT", + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/mquery": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/mquery/-/mquery-5.0.0.tgz", + "integrity": "sha512-iQMncpmEK8R8ncT8HJGsGc9Dsp8xcgYMVSbs5jgnm1lFHTZqMJTUWTDx1LBO8+mK3tPNZWFLBghQEIOULSTHZg==", + "license": "MIT", + "dependencies": { + "debug": "4.x" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/negotiator": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz", + "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/nodemon": { + "version": "3.1.10", + "resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.1.10.tgz", + "integrity": "sha512-WDjw3pJ0/0jMFmyNDp3gvY2YizjLmmOUQo6DEBY+JgdvW/yQ9mEeSw6H5ythl5Ny2ytb7f9C2nIbjSxMNzbJXw==", + "license": "MIT", + "dependencies": { + "chokidar": "^3.5.2", + "debug": "^4", + "ignore-by-default": "^1.0.1", + "minimatch": "^3.1.2", + "pstree.remy": "^1.1.8", + "semver": "^7.5.3", + "simple-update-notifier": "^2.0.0", + "supports-color": "^5.5.0", + "touch": "^3.1.0", + "undefsafe": "^2.0.5" + }, + "bin": { + "nodemon": "bin/nodemon.js" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/nodemon" + } + }, + "node_modules/normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-to-regexp": { + "version": "8.2.0", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.2.0.tgz", + "integrity": "sha512-TdrF7fW9Rphjq4RjrW0Kp2AW0Ahwu9sRGTkS6bvDi0SCwZlEZYmcfDbEsTz8RVk0EHIS/Vd1bv3JhG+1xZuAyQ==", + "license": "MIT", + "engines": { + "node": ">=16" + } + }, + "node_modules/picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/pstree.remy": { + "version": "1.1.8", + "resolved": "https://registry.npmjs.org/pstree.remy/-/pstree.remy-1.1.8.tgz", + "integrity": "sha512-77DZwxQmxKnu3aR542U+X8FypNzbfJ+C5XQDk3uWjWxn6151aIMGthWYRXTqT1E5oJvg+ljaa2OJi+VfvCOQ8w==", + "license": "MIT" + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/qs": { + "version": "6.14.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.0.tgz", + "integrity": "sha512-YWWTjgABSKcvs/nWBi9PycY/JiPJqOD4JA6o9Sej2AtvSGarXxKC3OQSk4pAarbdQlKAh5D4FCQkJNkW+GAn3w==", + "license": "BSD-3-Clause", + "dependencies": { + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.0.tgz", + "integrity": "sha512-RmkhL8CAyCRPXCE28MMH0z2PNWQBNk2Q09ZdxM9IOOXwxwZbN+qbWaatPkdkWIKL2ZVDImrN/pK5HTRz2PcS4g==", + "license": "MIT", + "dependencies": { + "bytes": "3.1.2", + "http-errors": "2.0.0", + "iconv-lite": "0.6.3", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/readdirp": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", + "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", + "license": "MIT", + "dependencies": { + "picomatch": "^2.2.1" + }, + "engines": { + "node": ">=8.10.0" + } + }, + "node_modules/router": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", + "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "depd": "^2.0.0", + "is-promise": "^4.0.0", + "parseurl": "^1.3.3", + "path-to-regexp": "^8.0.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/semver": { + "version": "7.7.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.2.tgz", + "integrity": "sha512-RF0Fw+rO5AMf9MAyaRXI4AV0Ulj5lMHqVxxdSgiVbixSCXoEmmX/jk0CuJw4+3SqroYO9VoUh+HcuJivvtJemA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/send": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/send/-/send-1.2.0.tgz", + "integrity": "sha512-uaW0WwXKpL9blXE2o0bRhoL2EGXIrZxQ2ZQ4mgcfoBxdFmQold+qWsD2jLrfZ0trjKL6vOw0j//eAwcALFjKSw==", + "license": "MIT", + "dependencies": { + "debug": "^4.3.5", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "mime-types": "^3.0.1", + "ms": "^2.1.3", + "on-finished": "^2.4.1", + "range-parser": "^1.2.1", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/serve-static": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.0.tgz", + "integrity": "sha512-61g9pCh0Vnh7IutZjtLGGpTA355+OPn2TyDv/6ivP2h/AdAVX9azsoxmg2/M6nZeQZNYBEwIcsne1mJd9oQItQ==", + "license": "MIT", + "dependencies": { + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "parseurl": "^1.3.3", + "send": "^1.2.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/side-channel": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", + "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3", + "side-channel-list": "^1.0.0", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz", + "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/sift": { + "version": "17.1.3", + "resolved": "https://registry.npmjs.org/sift/-/sift-17.1.3.tgz", + "integrity": "sha512-Rtlj66/b0ICeFzYTuNvX/EF1igRbbnGSvEyT79McoZa/DeGhMyC5pWKOEsZKnpkqtSeovd5FL/bjHWC3CIIvCQ==", + "license": "MIT" + }, + "node_modules/simple-update-notifier": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/simple-update-notifier/-/simple-update-notifier-2.0.0.tgz", + "integrity": "sha512-a2B9Y0KlNXl9u/vsW6sTIu9vGEpfKu2wRV6l1H3XEas/0gUIzGzBoP/IouTcUQbm9JWZLH3COxyn03TYlFax6w==", + "license": "MIT", + "dependencies": { + "semver": "^7.5.3" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/sparse-bitfield": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/sparse-bitfield/-/sparse-bitfield-3.0.3.tgz", + "integrity": "sha512-kvzhi7vqKTfkh0PZU+2D2PIllw2ymqJKujUcyPMd9Y75Nv4nPbGJZXNhxsgdQab2BmlDct1YnfQCguEvHr7VsQ==", + "license": "MIT", + "dependencies": { + "memory-pager": "^1.0.2" + } + }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "license": "MIT", + "dependencies": { + "has-flag": "^3.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "license": "MIT", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/touch": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/touch/-/touch-3.1.1.tgz", + "integrity": "sha512-r0eojU4bI8MnHr8c5bNo7lJDdI2qXlWWJk6a9EAFG7vbhTjElYhBVS3/miuE0uOuoLdb8Mc/rVfsmm6eo5o9GA==", + "license": "ISC", + "bin": { + "nodetouch": "bin/nodetouch.js" + } + }, + "node_modules/tr46": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-5.1.1.tgz", + "integrity": "sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==", + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/type-is": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.0.1.tgz", + "integrity": "sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw==", + "license": "MIT", + "dependencies": { + "content-type": "^1.0.5", + "media-typer": "^1.1.0", + "mime-types": "^3.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/undefsafe": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/undefsafe/-/undefsafe-2.0.5.tgz", + "integrity": "sha512-WxONCrssBM8TSPRqN5EmsjVrsv4A8X12J4ArBiiayv3DyyG3ZlIg6yysuuSYdZsVz3TKcTg2fd//Ujd4CHV1iA==", + "license": "MIT" + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/webidl-conversions": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz", + "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + } + }, + "node_modules/whatwg-url": { + "version": "14.2.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-14.2.0.tgz", + "integrity": "sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==", + "license": "MIT", + "dependencies": { + "tr46": "^5.1.0", + "webidl-conversions": "^7.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC" + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..e8e5383 --- /dev/null +++ b/package.json @@ -0,0 +1,21 @@ +{ + "name": "backend", + "version": "1.0.0", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1", + "start": "nodemon server.js" + }, + "keywords": [], + "author": "", + "license": "ISC", + "description": "", + "dependencies": { + "cors": "^2.8.5", + "dotenv": "^16.5.0", + "express": "^5.1.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 new file mode 100644 index 0000000..c300ed1 --- /dev/null +++ b/routes/account.route.js @@ -0,0 +1,15 @@ +const express = require('express'); +const router= express.Router(); +const {getAllAccount, getAccountById, addNewAccount, updateAccount, deleteAccount, transferAmount, updateTransferAmount} = 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) + + +module.exports = router; \ No newline at end of file diff --git a/routes/budget.route.js b/routes/budget.route.js new file mode 100644 index 0000000..33f9505 --- /dev/null +++ b/routes/budget.route.js @@ -0,0 +1,12 @@ +const express = require('express'); +const router= express.Router(); +const {getAllBudget, addNewBudget, updateBudget,deleteBudget} = 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) + +module.exports = router; \ No newline at end of file diff --git a/routes/category.route.js b/routes/category.route.js new file mode 100644 index 0000000..5df3f02 --- /dev/null +++ b/routes/category.route.js @@ -0,0 +1,12 @@ +const {getAllCategory, addNewCategory, updateCategory, deleteCategory, getCategoryById} = 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 ); + +module.exports = router; \ No newline at end of file diff --git a/routes/log.route.js b/routes/log.route.js new file mode 100644 index 0000000..8a6e643 --- /dev/null +++ b/routes/log.route.js @@ -0,0 +1,9 @@ +const express= require('express'); +const router = express.Router(); +const {getAllLogs} = require('../controllers/log-activity.controller'); + + +router.get('/getAllLogs', getAllLogs); + + +module.exports = router; \ No newline at end of file diff --git a/routes/record-list.route.js b/routes/record-list.route.js new file mode 100644 index 0000000..7319490 --- /dev/null +++ b/routes/record-list.route.js @@ -0,0 +1,16 @@ + +const {getAllRecord, addNewRecord, deleteRecord, getRecordById, updateRecord} = 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); + + + +module.exports = router; \ No newline at end of file diff --git a/server.js b/server.js new file mode 100644 index 0000000..7268b8a --- /dev/null +++ b/server.js @@ -0,0 +1,34 @@ +const express = require('express'); +const connectToDB = require('./database/db'); +const cors= require('cors') +require('dotenv').config(); +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'); + + +app.use(express.json()); + +app.use(cors({origin: ['http://localhost:4200']})) + +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.listen(PORT, ()=>{ + console.log(`server running on http://loalhost:${PORT}`) +}) \ No newline at end of file diff --git a/utials/log.activity.js b/utials/log.activity.js new file mode 100644 index 0000000..f8e5409 --- /dev/null +++ b/utials/log.activity.js @@ -0,0 +1,18 @@ +// 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}; From b5107d839d2d3ed3e6792ca3d53627b214a1c41f Mon Sep 17 00:00:00 2001 From: Akki meena Date: Tue, 29 Jul 2025 11:38:31 +0530 Subject: [PATCH 2/3] fix global Error handling and create a seprate log file --- controllers/account.controller.js | 455 +++++++++++-------------- controllers/budget.controller.js | 130 +++---- controllers/category.controller.js | 190 ++++------- controllers/log-activity.controller.js | 24 +- controllers/record-list.controller.js | 222 +++++------- database/db.js | 12 +- middleware/errorHandler.js | 13 + model/budget.model.js | 4 +- model/category.model.js | 1 - package-lock.json | 8 + package.json | 2 + server.js | 45 ++- utials/apiError.js | 11 + utials/asyncHandler.js | 11 + utials/log.activity.js | 18 - utials/log.js | 15 + 16 files changed, 506 insertions(+), 655 deletions(-) create mode 100644 middleware/errorHandler.js create mode 100644 utials/apiError.js create mode 100644 utials/asyncHandler.js delete mode 100644 utials/log.activity.js create mode 100644 utials/log.js diff --git a/controllers/account.controller.js b/controllers/account.controller.js index 4749c37..b655ab5 100644 --- a/controllers/account.controller.js +++ b/controllers/account.controller.js @@ -1,298 +1,227 @@ 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 getAllAccount = asyncHandler(async (req, res) => { + const account = await Account.find({}).populate('recordId'); + if (account.length === 0) { + throw new ApiError(404, 'No account found') } - 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 Fetch Successfully', data: account }); +}); //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', }); +const addNewAccount = 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(); - } +const deleteAccount = 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 transferAmount = 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 - } - await oldFromAccount.save(); - 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.!.' }); - } +const updateTransferAmount = 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; + } + if (oldToAccount) { + oldToAccount.amount -= record.amount + } + await oldFromAccount.save(); + await oldToAccount.save(); + //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'); + } + if (newFromAccount.amount < amount) { + throw new ApiError(400,'Insufficient Amount.!') + } - newFromAccount.amount -= amount, - newToAccount.amount += amount - await newFromAccount.save(); - await newToAccount.save(); + 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 getAccountById = asyncHandler(async (req, res) => { + const getAccountById = req.params.id; + const getAccountDetailsById = await Account.findById(getAccountById); + if (!getAccountDetailsById) { + throw new ApiError(404,'Account not Found'); + } + res.status(200).json({ success: true, message: 'Account Details Fetch Successful', data: getAccountDetailsById }); - // 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' }); - } -}; -//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 }) - } +//update account and adjust account balance after updation +const updateAccount = asyncHandler(async (req, res) => { + const { accountId, recordId, name, amount } = req.body; + if (!accountId || !name || amount == null) { + throw new ApiError(400,'All fields are required'); } - catch (error) { - console.log(error); - return res.status(500).json({ success: false, message: 'something went wrong! please try again.' }) + //find account byId + const account = await Account.findById(accountId); + if (!account) { + throw new ApiError(404,'Account not found'); } -} - - -//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' }); + 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) { + await RecordList.findByIdAndDelete(recordId); + account.recordId = null; + await account.save(); } - //find account byId - const account = await Account.findById(accountId); - if (!account) { - return res.status(404).json({ success: false, message: 'Account not found' }); + } + 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}`; + await record.save(); + message += `transaction record updated`; } - const oldAmount = account.amount; - const newAmount = amount; - const currentAmount = newAmount - oldAmount; - //Update Account Name and Amount - account.name = name; - account.amount = newAmount; + } + //if user have no record exists and new Amount more then 0 create record + else if (!recordId && newAmount > 0) { + const createdRecord = await RecordList.create({ + amount: newAmount, + type: 'income', + account: account._id, + addNote: `Account "${name}" updated with initial amount ₹${newAmount}`, + isInitialEntry: true + }); + account.recordId = createdRecord._id; 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) { - await RecordList.findByIdAndDelete(recordId); - 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}`; - await record.save(); - message += `transaction record updated by: ${user.username}`; - } - } - //if user have no record exists and new Amount more then 0 create record - else if (!recordId && newAmount > 0) { - const createdRecord = await RecordList.create({ - amount: newAmount, - type: 'income', - account: account._id, - addNote: `Account "${name}" updated with initial amount ₹${newAmount}`, - isInitialEntry: true - }); - account.recordId = createdRecord._id; - await account.save(); - message += `Initial transaction record created)`; - } - 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 createLog(`Initial transaction record created with ₹${newAmount}`); + res.status(200).json({ success: true, message: 'Account and Transaction updated successfully', data: account }); +}); module.exports = { getAllAccount, addNewAccount, getAccountById, deleteAccount, transferAmount, updateAccount, updateTransferAmount }; \ No newline at end of file diff --git a/controllers/budget.controller.js b/controllers/budget.controller.js index 5b47da4..6e8c45a 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 getAllBudget = asyncHandler(async (req, res) => { + const getBudget = await Budget.find({}); + if (getBudget.length === 0) { + throw new ApiError(404,'Budget not found'); } -} - + res.status(200).json({ success: true, message: 'All Budget Fatch Success', data: getBudget }); +}); //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 - }); - - 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 addNewBudget = asyncHandler(async (req, res) => { + const { categoryId, limit, date } = req.body; + if (!categoryId || !limit) { + throw new ApiError(400,'All Fields are required'); } -}; + + 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 updateBudget = 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 deleteBudget = 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 }; diff --git a/controllers/category.controller.js b/controllers/category.controller.js index bb61dee..4d07366 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' }) - } +const getAllCategory = asyncHandler(async (req, res) => { + const allCategory = await Category.find({}); + if (allCategory.length === 0) { + throw new ApiError(404, 'Category not found'); } - 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 Category Fatch Successfully', data: allCategory }) + +}); //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 addNewCategory = 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 updateCategory = 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 deleteCategory = 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 getCategoryById = 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 diff --git a/controllers/log-activity.controller.js b/controllers/log-activity.controller.js index 4cce4dc..0e76e24 100644 --- a/controllers/log-activity.controller.js +++ b/controllers/log-activity.controller.js @@ -1,20 +1,16 @@ -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 getAllLogs = asyncHandler(async (req, res) => { + const getAllLogs = await Log.find({}).populate('userId').sort({date: -1}); + if (getAllLogs.length === 0) { + throw new ApiError(404,'Logs not found') } -} + res.status(200).json({ success: true, message: 'Logs Fetch Successfully', data: getAllLogs }); + +}); module.exports = { getAllLogs } diff --git a/controllers/record-list.controller.js b/controllers/record-list.controller.js index 08c14f9..be94174 100644 --- a/controllers/record-list.controller.js +++ b/controllers/record-list.controller.js @@ -1,153 +1,119 @@ 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' }) - } - } - catch (err) { - console.log(err); - return res.status(500).json({ success: false, message: 'Internal Server Error' }) +const getAllRecord = asyncHandler(async (req, res) => { + const getTransaction = await RecordList.find({}).sort({ date: -1 }); + if (getTransaction.length === 0) { + throw new ApiError(404, 'No transaction found'); + } -} + return res.status(200).json({ success: true, message: 'All Transaction Record Fetch Successfully', data: getTransaction }) + +}); // 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 addNewRecord = 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 }) - } +const getRecordById = 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') } - catch (error) { - console.log(error); - return res.status(500).json({ success: false, message: 'something went worng.! please try again' }) - } -} + 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 deleteRecord = 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 updateRecord = 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 } 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..b1e71bf --- /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; 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/server.js b/server.js index 975bbff..5c3462c 100644 --- a/server.js +++ b/server.js @@ -1,40 +1,37 @@ 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 category = require('./routes/category.route'); +const account = require('./routes/account.route'); +const record = require('./routes/record-list.route'); +const log = require('./routes/log.route'); +const budget = 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/category', category); +app.use('/api/account', account); +app.use('/api/record', record); +app.use('/api/log', log); +app.use('/api/budget', budget) -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; diff --git a/utials/apiError.js b/utials/apiError.js new file mode 100644 index 0000000..c217577 --- /dev/null +++ b/utials/apiError.js @@ -0,0 +1,11 @@ +class ApiError extends Error { + constructor(statusCode, message) { + super(message); + this.statusCode = statusCode; + this.status = statusCode >= 400 && statusCode < 500 ? 'fail' : '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; From ababe21b014254a69c0969f61977e95d60387542 Mon Sep 17 00:00:00 2001 From: Akki meena Date: Fri, 1 Aug 2025 17:59:58 +0530 Subject: [PATCH 3/3] correct endpoints name --- controllers/account.controller.js | 147 +++++++++++++------------ controllers/budget.controller.js | 36 +++--- controllers/category.controller.js | 22 ++-- controllers/log-activity.controller.js | 12 +- controllers/record-list.controller.js | 24 ++-- middleware/errorHandler.js | 2 +- routes/account.route.js | 16 +-- routes/budget.route.js | 10 +- routes/category.route.js | 12 +- routes/log.route.js | 4 +- routes/record-list.route.js | 12 +- server.js | 22 ++-- utials/apiError.js | 6 +- 13 files changed, 164 insertions(+), 161 deletions(-) diff --git a/controllers/account.controller.js b/controllers/account.controller.js index b655ab5..a4de796 100644 --- a/controllers/account.controller.js +++ b/controllers/account.controller.js @@ -6,19 +6,22 @@ const ApiError = require('../utials/apiError'); //getAllAccounts -const getAllAccount = asyncHandler(async (req, res) => { - const account = await Account.find({}).populate('recordId'); - if (account.length === 0) { - throw new ApiError(404, 'No account found') +const fetchAllAccounts = asyncHandler(async (req, res) => { + const accounts = await Account.find({}).populate('recordId'); + if (accounts.length === 0) { + return res.status(204).send() } - res.status(200).json({ success: true, message: 'All Accounts Fetch Successfully', data: account }); + res.status(200).json({ success: true, message: 'All Accounts Fetched Successfully', data: accounts }); }); + + + //create New account -const addNewAccount = asyncHandler(async (req, res) => { +const createAccount = asyncHandler(async (req, res) => { const { name, amount, type } = req.body; if (!name) { - throw new ApiError(400,'Account name is required'); + throw new ApiError(400, 'Account name is required'); } const newCreatedAccount = await Account.create({ name, amount: 0, type }); if (amount && amount > 0) { @@ -37,12 +40,12 @@ const addNewAccount = asyncHandler(async (req, res) => { }); -//deleteAccount from account list -const deleteAccount = asyncHandler(async (req, res) => { +//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') + throw new ApiError(404, 'Account not found') } //find all transaction of transfer amount const transferAmount = await RecordList.find({ toAccount: accountId, isTransfer: true }); @@ -69,21 +72,21 @@ const deleteAccount = asyncHandler(async (req, res) => { // transfer amount from one account to another -const transferAmount = asyncHandler(async (req, res) => { +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') + 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.') + 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'); + throw new ApiError(404, 'Account not found'); } if (fromAccount.amount < amount) { - throw new ApiError(400,'Insufficient Amount.!'); + throw new ApiError(400, 'Insufficient Amount.!'); } //amount transfer fromAccount.amount -= amount; @@ -107,37 +110,39 @@ const transferAmount = asyncHandler(async (req, res) => { // Update an existing transfer transaction records -const updateTransferAmount = asyncHandler(async (req, res) => { +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'); + throw new ApiError(400, 'invalid transfer Amount'); } if (fromAccountId === toAccountId) { - throw new ApiError(400,'Both Accounts cannot be the same'); + 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'); + 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 + oldToAccount.amount -= record.amount; + await oldToAccount.save(); } - await oldFromAccount.save(); - await oldToAccount.save(); + + //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'); + throw new ApiError(404, 'Account not found'); } if (newFromAccount.amount < amount) { - throw new ApiError(400,'Insufficient Amount.!') + throw new ApiError(400, 'Insufficient Amount.!') } newFromAccount.amount -= amount, @@ -158,70 +163,70 @@ const updateTransferAmount = asyncHandler(async (req, res) => { }); //Fetch accountDetails by AccountId -const getAccountById = asyncHandler(async (req, res) => { - const getAccountById = req.params.id; - const getAccountDetailsById = await Account.findById(getAccountById); - if (!getAccountDetailsById) { - throw new ApiError(404,'Account not Found'); +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: getAccountDetailsById }); + res.status(200).json({ success: true, message: 'Account Details Fetch Successful', data: fetchAccountDetailsById }); }); //update account and adjust account balance after updation -const updateAccount = asyncHandler(async (req, res) => { +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'); + throw new ApiError(400, 'All fields are required'); } - //find account byId const account = await Account.findById(accountId); if (!account) { - throw new ApiError(404,'Account not found'); + throw new ApiError(404, 'Account not found'); } - const oldAmount = account.amount; - const newAmount = amount; - const currentAmount = newAmount - oldAmount; - //Update Account Name and Amount + let message = ''; 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) { + message = `Account "${name}" updated.`; + if (recordId) { const record = await RecordList.findById(recordId); if (record && record.isInitialEntry) { - await RecordList.findByIdAndDelete(recordId); - account.recordId = null; - await account.save(); + const oldInitialAmount = record.amount; + if (amount === 0) { + await RecordList.findByIdAndDelete(recordId); + const remaining = account.amount - oldInitialAmount; + account.amount = remaining; + account.recordId = null; + 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(); + + account.amount = remaining + amount; + message += ` Initial amount changed from ₹${oldInitialAmount} to ₹${amount}.`; + } + } else { + throw new ApiError(400, 'Invalid initial entry'); } - } - 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}`; - await record.save(); - message += `transaction record updated`; + + } else { + if (amount > 0) { + const createdRecord = await RecordList.create({ + amount, + type: 'income', + account: account._id, + addNote: `Initial amount set to ₹${amount}`, + isInitialEntry: true, + }); + account.amount += amount; + account.recordId = createdRecord._id; + message += ` Initial record created with ₹${amount}.`; } } - //if user have no record exists and new Amount more then 0 create record - else if (!recordId && newAmount > 0) { - const createdRecord = await RecordList.create({ - amount: newAmount, - type: 'income', - account: account._id, - addNote: `Account "${name}" updated with initial amount ₹${newAmount}`, - isInitialEntry: true - }); - account.recordId = createdRecord._id; - await account.save(); - } - await createLog(`Initial transaction record created with ₹${newAmount}`); - res.status(200).json({ success: true, message: 'Account and Transaction updated successfully', data: account }); + 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 6e8c45a..4010133 100644 --- a/controllers/budget.controller.js +++ b/controllers/budget.controller.js @@ -8,25 +8,25 @@ const ApiError = require('../utials/apiError'); //find all budget -const getAllBudget = asyncHandler(async (req, res) => { - const getBudget = await Budget.find({}); - if (getBudget.length === 0) { - throw new ApiError(404,'Budget not found'); +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 Budget Fatch Success', data: getBudget }); + res.status(200).json({ success: true, message: 'All Budgets Fatched Successfully', data: budgets }); }); //set Budget with selected category -const addNewBudget = asyncHandler(async (req, res) => { +const createBudget = asyncHandler(async (req, res) => { const { categoryId, limit, date } = req.body; if (!categoryId || !limit) { - throw new ApiError(400,'All Fields are required'); + throw new ApiError(400, 'All Fields are required'); + } + + const category = await Category.findById(categoryId); + if (!category) { + throw new ApiError(404, 'Category not found'); } - - const category = await Category.findById(categoryId); - if(!category) { - throw new ApiError(404,'Category not found'); - } const budget = await Budget.create({ category: categoryId, @@ -39,32 +39,32 @@ const addNewBudget = asyncHandler(async (req, res) => { //Update budget by ID -const updateBudget = asyncHandler(async (req, res) => { +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'); + throw new ApiError(400, 'limit is required'); } const updatedBudget = await Budget.findByIdAndUpdate(getCurrentBudget, budgetUpdateFormData, { new: true } ); if (!updatedBudget) { - throw new ApiError(404,'Budget not found'); + throw new ApiError(404, 'Budget not found'); } await createLog(`update budget with new limit ${updatedBudget.limit}`) res.status(200).json({ success: true, message: 'Budget updated successfully', data: updatedBudget }); }); //deleted budget -const deleteBudget = asyncHandler(async (req, res) => { +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'); + 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 4d07366..ad72b4d 100644 --- a/controllers/category.controller.js +++ b/controllers/category.controller.js @@ -7,17 +7,17 @@ const createLog = require('../utials/log'); const ApiError = require('../utials/apiError'); -//getAll Category -const getAllCategory = asyncHandler(async (req, res) => { - const allCategory = await Category.find({}); - if (allCategory.length === 0) { - throw new ApiError(404, '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(); } - res.status(200).json({ success: true, message: 'All Category Fatch Successfully', data: allCategory }) + res.status(200).json({ success: true, message: 'All Categories Fatched Successfully', data: categories }) }); //create new Catgeory -const addNewCategory = asyncHandler(async (req, res) => { +const createCategory = asyncHandler(async (req, res) => { const { name, type } = req.body; if (!name || !type) { throw new ApiError(400, 'All Fields are required'); @@ -35,7 +35,7 @@ const addNewCategory = asyncHandler(async (req, res) => { }); //update categoryByid -const updateCategory = asyncHandler(async (req, res) => { +const updateCategoryDetails = asyncHandler(async (req, res) => { const categoryUpdateFormData = req.body; const getCurrentCategoryById = req.params.id; const updateCategory = await Category.findByIdAndUpdate(getCurrentCategoryById, categoryUpdateFormData, { new: true }); @@ -49,7 +49,7 @@ const updateCategory = asyncHandler(async (req, res) => { //delete Category -const deleteCategory = asyncHandler(async (req, res) => { +const deleteCategoryById = asyncHandler(async (req, res) => { const categoryId = req.params.id; const category = await Category.findByIdAndDelete(categoryId); if (!category) { @@ -80,7 +80,7 @@ const deleteCategory = asyncHandler(async (req, res) => { //getcategory BY Id -const getCategoryById = asyncHandler(async (req, res) => { +const fetchCategoryById = asyncHandler(async (req, res) => { const getCategoryById = req.params.id; const getCategoryDetailsById = await Category.findById(getCategoryById); if (!getCategoryDetailsById) { @@ -90,4 +90,4 @@ const getCategoryById = asyncHandler(async (req, res) => { }); -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 0e76e24..5bf3619 100644 --- a/controllers/log-activity.controller.js +++ b/controllers/log-activity.controller.js @@ -3,16 +3,16 @@ const asyncHandler = require('../utials/asyncHandler'); const ApiError = require('../utials/apiError'); //get All activity logs -const getAllLogs = asyncHandler(async (req, res) => { - const getAllLogs = await Log.find({}).populate('userId').sort({date: -1}); - if (getAllLogs.length === 0) { - throw new ApiError(404,'Logs not found') +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: 'Logs Fetch Successfully', data: getAllLogs }); + 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 be94174..6827a87 100644 --- a/controllers/record-list.controller.js +++ b/controllers/record-list.controller.js @@ -4,19 +4,18 @@ const asyncHandler = require('../utials/asyncHandler'); const createLog = require('../utials/log'); const ApiError = require('../utials/apiError'); -//fatch all Records -const getAllRecord = asyncHandler(async (req, res) => { - const getTransaction = await RecordList.find({}).sort({ date: -1 }); - if (getTransaction.length === 0) { - throw new ApiError(404, 'No transaction 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(); } - return res.status(200).json({ success: true, message: 'All Transaction Record Fetch Successfully', data: getTransaction }) + return res.status(200).json({ success: true, message: 'All Transaction Record Fetched Successfully', data: transactions }) }); // create new Transaction Records -const addNewRecord = asyncHandler(async (req, res) => { +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"); @@ -44,18 +43,17 @@ const addNewRecord = asyncHandler(async (req, res) => { //getRecordDetails byId -const getRecordById = asyncHandler(async (req, res) => { +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 = asyncHandler(async (req, res) => { +const deleteRecordById = asyncHandler(async (req, res) => { const record = await RecordList.findById(req.params.id); if (!record) { throw new ApiError(404, 'Transaction Record not found'); @@ -92,7 +90,7 @@ const deleteRecord = asyncHandler(async (req, res) => { //update Records Details -const updateRecord = asyncHandler(async (req, res) => { +const updateRecordDetails = asyncHandler(async (req, res) => { const recordUpdateFormData = req.body; const recordId = req.params.id; const getRecordDetails = await RecordList.findById(recordId); @@ -116,7 +114,7 @@ const updateRecord = asyncHandler(async (req, res) => { }); -module.exports = { getAllRecord, addNewRecord, deleteRecord, getRecordById, updateRecord } +module.exports = { fetchAllRecords, createRecord, fetchTransactionRecordById, deleteRecordById, updateRecordDetails } diff --git a/middleware/errorHandler.js b/middleware/errorHandler.js index b1e71bf..f35d8d0 100644 --- a/middleware/errorHandler.js +++ b/middleware/errorHandler.js @@ -10,4 +10,4 @@ const errorHandler = (err, req, res, next) => { res.status(statusCode).json(errorResponse); }; -module.exports = errorHandler; +module.exports = errorHandler; \ No newline at end of file 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 5c3462c..f88c0ba 100644 --- a/server.js +++ b/server.js @@ -7,11 +7,11 @@ require('dotenv').config(); const app = express(); //route -const category = require('./routes/category.route'); -const account = require('./routes/account.route'); -const record = require('./routes/record-list.route'); -const log = require('./routes/log.route'); -const budget = require('./routes/budget.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; @@ -22,11 +22,11 @@ const PORT = process.env.PORT || 3000; connectToDB(); -app.use('/api/category', category); -app.use('/api/account', account); -app.use('/api/record', record); -app.use('/api/log', log); -app.use('/api/budget', budget) +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.use(errorHandler); @@ -35,4 +35,4 @@ app.listen(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 index c217577..f32f900 100644 --- a/utials/apiError.js +++ b/utials/apiError.js @@ -1,10 +1,10 @@ class ApiError extends Error { - constructor(statusCode, message) { + constructor(statusCode, message,error) { super(message); this.statusCode = statusCode; this.status = statusCode >= 400 && statusCode < 500 ? 'fail' : 'error'; - this.isOperational = true; - + this.error = error; + this.isOperational = true; Error.captureStackTrace(this, this.constructor); } }