diff --git a/constants/messages.js b/constants/messages.js index 0f655aa..bfc994e 100644 --- a/constants/messages.js +++ b/constants/messages.js @@ -1,11 +1,23 @@ const messages = { - loginMessage: "User logged-in successfully", - registerMessage: "Guy, Your account has been created successfully, an otp has been sent to your email", - userExists: "User with the Phone/Email exists", - notFoundMessage: "What you seek is beyond this globe", - invalidOtp : "Invalid otp" - - -} + loginMessage: "User logged-in successfully", + registerMessage: "Guy, Your account has been created successfully, an otp has been sent to your email", + userExists: "User with the Phone/Email exists", + notFoundMessage: "What you seek is beyond this globe", + invalidOtp: "Invalid otp", + walletBalanceMessage: "wallet balance fetched successfully", + errorBalancemessage: "Error fetching wallet balance", + errorSendMoneyMessage: "invalid amount or phone", + errorSendMoneyMessageLimit: "your transfer limit has been exceeded", + sendMoneyErrorRecipientDetails: "user not found", + userWalletDetailsError: "insufficient balance. Please top-up your wallet", + receipientSuccessmessage: "Transaction completed successfully", + sendMoneyToSelfMessage:'you cannot send money to self', + errorFetchingTransactions: "Error fetching transactions from database", + dailytransactionLogMessage: "daily transaction logged successfully", + weeklytransactionLogMessage: "weekly transaction logged successfully", + monthlytransactionLogMessage: "monthly transaction logged successfully" + + +}; -module.exports = messages; \ No newline at end of file +module.exports = messages; diff --git a/controllers/sendController.js b/controllers/sendController.js deleted file mode 100644 index 2a3feb4..0000000 --- a/controllers/sendController.js +++ /dev/null @@ -1,31 +0,0 @@ -const WalletModel = require('../models/walletModel') -const { credit, getWalletBalance } = require('./walletController') - - -//User_id, wallet_id, Amount and bank needed for transaction - -const UserTopUp = async (amount, user_id, bank_id) => { - - // find bank account using bank_id - // verify user bank account has enough balance - //check account status of bank account from paystack - //if amount in bank account is less than amount for top up, something went wrong, sorry cannot complete tansaction at this point - -// credit (topUp) wallet using wallet_id with amount passed in - credit(amount, user_id, `Wallet top up from bank`) - -// debit bank using bank_id - //debit(amount, user_id, bank_id, `funds for wallet to up`) - - -} - - - -module.exports = {sendMoney} - - - -//Get user from bank table and the wallet table using the user_id -//Get the wallet+id from wallet table -//Bank_id from selected bank table \ No newline at end of file diff --git a/controllers/transactionController.js b/controllers/transactionController.js index 44eb6c4..2242196 100644 --- a/controllers/transactionController.js +++ b/controllers/transactionController.js @@ -1,198 +1,322 @@ - -const {Op} = require('sequelize'); -const transactionModel = require('../models/transactionModel'); -const {transactionTypeEnum} = require('../constants/enums'); - - - -const getTransactions = async (req, res)=>{ - - try{ - const { page } = req.query +const { Op } = require("sequelize"); +const moment = require('moment'); // require +const transactionModel = require("../models/transactionModel"); +const { TransactionTypeEnum } = require("../constants/enums"); +const {getTodaysDate} = require('../utils/helpers') +const {errorFetchingTransactions, dailytransactionLogMessage, + weeklytransactionLogMessage,monthlytransactionLogMessage} = require("../constants/messages"); +const getTransactions = async (req, res) => { + try { + const { page } = req.query; const limit = 5; - const pages = (page - 1) || 0; + const pages = page - 1 || 0; const offset = pages * limit; - const getAllTransactions = await transactionModel.findAll( - { - order:[['sn']], - limit: limit, - offset: offset, - } - ); + const getAllTransactions = await transactionModel.findAll({ + order: [["sn"]], + limit: limit, + offset: offset, + }); res.status(200).json({ - status: true, - message: 'Transaction logged successfully', - data: getAllTransactions - }); - - } catch(error){ - + status: true, + message: "Transaction logged successfully", + data: getAllTransactions, + }); + } catch (error) { res.status(500).json({ status: false, - message: error.message + message: error.message, }); - } }; -const filterTransactionsWithDate = async (req, res)=>{ - try{ + +const filterTransactionsWithDate = async (req, res) => { + try { // const {start_date, end_date} = req.body; - const {startDate, endDate} = req.query; - - if(!startDate || !endDate){ + const { startDate, endDate } = req.query; + + if (!startDate || !endDate) { res.status(404).json({ status: false, - message: 'Fill or fields' + message: "Fill or fields", }); return; - }; + } const start = new Date(startDate); const end = new Date(endDate); const getAllTransactionsViaDate = await transactionModel.findAll( { - where:{ - createdAt: {[Op.between] : [start, end]} - }, - order:[['sn']] - } - // {limit:5} - ); - if(getAllTransactionsViaDate.length < 1){ + where: { + createdAt: { [Op.between]: [start, end] }, + }, + order: [["sn"]], + } + // {limit:5} + ); + if (getAllTransactionsViaDate.length < 1) { res.status(401).json({ status: false, - message: 'No transactions during this period.' + message: "No transactions during this period.", }); return; - }; + } res.status(200).json({ - status: true, - message: 'Transaction logged successfully', - data: getAllTransactionsViaDate - }); - - } catch(error){ - console.log(error) + status: true, + message: "Transaction logged successfully", + data: getAllTransactionsViaDate, + }); + } catch (error) { + console.log(error); res.status(500).json({ status: false, - message: error.message + message: error.message, }); - } }; -const filterTransaction = async (req, res)=>{ - - try{ - - const {filter_by} = req.query; +const filterTransaction = async (req, res) => { + try { + const { filter_by } = req.query; let amount = filter_by; - if(filter_by === transactionTypeEnum.CREDIT){ + if (filter_by === transactionTypeEnum.CREDIT) { const creditTransactions = await transactionModel.findAll({ - where: { - transaction_type: transactionTypeEnum.CREDIT - }, - order:[['sn']] - }); - if(creditTransactions.length < 1){ - res.status(401).json({ - status: false, - message: 'No credit transaction.' - }); - return; - }; - res.status(200).json({ - status: true, - message: 'All credit transactions logged successfully', - data: creditTransactions + where: { + transaction_type: transactionTypeEnum.CREDIT, + }, + order: [["sn"]], + }); + if (creditTransactions.length < 1) { + res.status(401).json({ + status: false, + message: "No credit transaction.", }); - - } else if(filter_by === transactionTypeEnum.DEBIT){ + return; + } + res.status(200).json({ + status: true, + message: "All credit transactions logged successfully", + data: creditTransactions, + }); + } else if (filter_by === transactionTypeEnum.DEBIT) { const debitTransactions = await transactionModel.findAll({ where: { - transaction_type: transactionTypeEnum.DEBIT + transaction_type: transactionTypeEnum.DEBIT, }, - order:[['sn']] + order: [["sn"]], }); - if(debitTransactions.length < 1){ + if (debitTransactions.length < 1) { res.status(401).json({ status: false, - message: 'No credit transaction.' + message: "No credit transaction.", }); return; - }; + } res.status(200).json({ status: true, - message: 'All debit transactions logged successfully', - data: debitTransactions - }) - } else if(filter_by === amount){ + message: "All debit transactions logged successfully", + data: debitTransactions, + }); + } else if (filter_by === amount) { const transactionAmount = await transactionModel.findAll({ - where: { - amount: amount + amount: amount, }, - order:[['sn']] + order: [["sn"]], }); - if(transactionAmount.length < 1){ + if (transactionAmount.length < 1) { res.status(401).json({ status: false, - message: 'No transaction.' + message: "No transaction.", }); return; - }; + } res.status(200).json({ status: true, - message: 'All credit transactions logged successfully', - data: transactionAmount + message: "All credit transactions logged successfully", + data: transactionAmount, }); - - }; - - }catch(error){ + } + } catch (error) { res.status(500).json({ status: false, - message: error.message + message: error.message, }); - }; + } }; +const transactionSum = (array)=>{ + const initialValue = 0; + const sumWithInitial = array.reduce((accumulator, currentValue) => accumulator + currentValue.amount, initialValue ) + return sumWithInitial +} + +const getTrasactionAmountFromDB = async (user_id, dateDuration, transaction_type) => { + + const transactions = await transactionModel.findAll({ + attributes: [ "amount" ], + where: { + user_id: user_id, + createdAt: { + [Op.between]: dateDuration + }, + transaction_type: transaction_type + } + + }); + + return transactions; + } -const dailyTransaction = (req, res) =>{ - const {transactionType} = req.query - const {user_id} = req.body -} -const weeklyTransaction = (req, res) =>{ - const {transactionType} = req.query - const {user_id} = req.body -} -const monthlyTransaction = async(req, res) =>{ - const {transactionType} = req.query - const {user_id} = req.body + +const dailyTransaction = async (req, res) => { + const { user_id } = req.body; + + try{ + + const todayDate = [getTodaysDate(), getTodaysDate()]; + console.log(`today's date here: ${todayDate}`); + + const userCreditTransactions = await getTrasactionAmountFromDB (user_id, todayDate, TransactionTypeEnum.CREDIT); + const userDebitTransactions =await getTrasactionAmountFromDB(user_id, todayDate, TransactionTypeEnum.DEBIT); + + //[{ amount: 100 }, { amount: 200}, { amount: 300}] + + if (!userCreditTransactions ||!userDebitTransactions ) throw new Error(errorFetchingTransactions, 400); + + const creditTransactions = await transactionSum(userCreditTransactions); + + const debitTransactions = await transactionSum(userDebitTransactions); + + const totalTransactions = Number(creditTransactions + debitTransactions); + + res.status(200).json({ + status: true, + totalDailyCreditAmount: creditTransactions, + totalDailyDebitAmount: debitTransactions, + totalDailyTransactionAmount: totalTransactions, + message: dailytransactionLogMessage, + }); + +} catch (error) { + res.status(500).json({ + status: false, + message: error.message, + }); + } + + }; + +const weeklyTransaction = async (req, res) => { + const { user_id } = req.body; + + try{ + + const todayDate = getTodaysDate() + const weeklyDate = moment().subtract(7, 'days').format('YYYY-MM-DD'); + const dateRange = [weeklyDate, todayDate]; + console.log(`weeklydate here: ${weeklyDate}`); + console.log(`todaydate heree: ${todayDate}`); + + const userCreditTransactions = await getTrasactionAmountFromDB (user_id, dateRange, TransactionTypeEnum.CREDIT); + console.log(`weekly userCredits here: ${userCreditTransactions}`); + const userDebitTransactions =await getTrasactionAmountFromDB(user_id, dateRange, TransactionTypeEnum.DEBIT); + + //[{ amount: 100 }, { amount: 200}, { amount: 300}] + + if (!userCreditTransactions ||!userDebitTransactions ) throw new Error(errorFetchingTransactions, 400); + + const creditTransactions = await transactionSum(userCreditTransactions); + + const debitTransactions = await transactionSum(userDebitTransactions); + + const totalTransactions = Number(creditTransactions + debitTransactions); + + res.status(200).json({ + status: true, + totalWeeklyCreditAmount: creditTransactions, + totalWeeklyDebitAmount: debitTransactions, + totalWeeklyTransactionAmount: totalTransactions, + message: weeklytransactionLogMessage, + }); + +} catch (error) { + + res.status(500).json({ + status: false, + message: error.message, + }); + } }; -const getUserTransaction = (user_id) =>{ - return transactionModel.findAll({ - where: { - user_id : user_id - } - }) -} - -module.exports = { getTransactions, - filterTransaction, - filterTransactionsWithDate, - dailyTransaction, weeklyTransaction, monthlyTransaction +const monthlyTransaction = async (req, res) => { + const { user_id } = req.body; + + try{ + + const todayDate = getTodaysDate() + const monthlylyDate = moment().subtract(1, 'months').format('YYYY-MM-DD'); + const dateRange = [monthlylyDate, todayDate]; + console.log(`today's date here: ${todayDate}`); + console.log(`Monthlydate here: ${monthlylyDate}`); + + const userCreditTransactions = await getTrasactionAmountFromDB (user_id, dateRange, TransactionTypeEnum.CREDIT); + console.log(`monthly userCredits here: ${userCreditTransactions}`); + + const userDebitTransactions =await getTrasactionAmountFromDB(user_id, dateRange, TransactionTypeEnum.DEBIT); + + //[{ amount: 100 }, { amount: 200}, { amount: 300}] + + if (!userCreditTransactions ||!userDebitTransactions ) throw new Error(errorFetchingTransactions, 400); + + const creditTransactions = await transactionSum(userCreditTransactions); + + const debitTransactions = await transactionSum(userDebitTransactions); + + const totalTransactions = Number(creditTransactions + debitTransactions); + + res.status(200).json({ + status: true, + totalMonthlyCreditAmount: creditTransactions, + totalMonthlyDebitAmount: debitTransactions, + totalMonthlyTransactionAmount: totalTransactions, + message: monthlytransactionLogMessage + }); + +} catch (error) { + + res.status(500).json({ + status: false, + message: error.message, + }); + } }; + + +const getUserTransaction = (user_id) => { + return transactionModel.findAll({ + where: { + user_id: user_id, + }, + }); +}; + +module.exports = { + getTransactions, + filterTransaction, + filterTransactionsWithDate, + dailyTransaction, + weeklyTransaction, + monthlyTransaction +}; diff --git a/controllers/userControllers.js b/controllers/userControllers.js index 525a9dd..405f14d 100644 --- a/controllers/userControllers.js +++ b/controllers/userControllers.js @@ -69,7 +69,7 @@ const createUser = async (req, res) => { }) //give them 1000 on signup - credit(200, userID, `Wallet funding for signup credits`) + credit(700, userID, `Wallet funding for signup credits`) const _otp = generateOtp(6) const dataToInsert = { diff --git a/controllers/walletController.js b/controllers/walletController.js index 985ab9b..ba1d148 100644 --- a/controllers/walletController.js +++ b/controllers/walletController.js @@ -1,202 +1,220 @@ -const WalletModel = require('../models/walletModel') -const UserModel = require('../models/userModels') -const transactionModel = require('../models/transactionModel') -const { TransactionStatusEnum, TransactionTypeEnum } = require('../constants/enums') -const { v4: uuidv4 } = require('uuid'); -const { startPayment, completePayment } = require('../services/payment') -const messages = require('../constants/messages') +const WalletModel = require("../models/walletModel"); +const UserModel = require("../models/userModels"); +const transactionModel = require("../models/transactionModel"); +const { + TransactionStatusEnum, + TransactionTypeEnum, +} = require("../constants/enums"); +const { v4: uuidv4 } = require("uuid"); +const { startPayment, completePayment } = require("../services/payment"); +const {walletBalanceMessage, +errorBalancemessage, +errorSendMoneyMessage , +errorSendMoneyMessageLimit, +sendMoneyErrorRecipientDetails, +userWalletDetailsError , +receipientSuccessmessage,sendMoneyToSelfMessage} = require("../constants/messages"); const credit = async (amountPassed, user_id, comments) => { - const amount = Math.abs(Number(amountPassed)) - const userDetails = await getUserWallet(user_id) - const initialbalance = Number(userDetails.amount_after) - const newbalance = initialbalance + amount //amount_after - await updateWallet(user_id, initialbalance, newbalance) - transaction(TransactionTypeEnum.CREDIT,comments, amount, userDetails.user_id, TransactionStatusEnum.SUCCESS ) - return -} - -const debit = async(amountPassed, user_id, comments) => { - const amount = Math.abs(Number(amountPassed)) - const userDetails = await getUserWallet(user_id) - const initialbalance = Number(userDetails.amount_after) - if(initialbalance < amount) return false - const newbalance = initialbalance - amount //amount_after - await updateWallet(user_id, initialbalance, newbalance) - transaction(TransactionTypeEnum.DEBIT,comments, amount, userDetails.user_id, TransactionStatusEnum.SUCCESS) - return true -} - -const transaction = (type, description, amount, user_id, transaction_status) => { - return transactionModel.create({ - transaction_id: uuidv4(), - user_id: user_id, - transaction_type: type, - amount: amount, - comments: description, - transaction_status: transaction_status - }) - -} + const amount = Math.abs(Number(amountPassed)); + const userDetails = await getUserWallet(user_id); + const initialbalance = Number(userDetails.amount_after); + const newbalance = initialbalance + amount; //amount_after + await updateWallet(user_id, initialbalance, newbalance); + transaction( + TransactionTypeEnum.CREDIT, + comments, + amount, + userDetails.user_id, + TransactionStatusEnum.SUCCESS + ); + return; +}; + +const debit = async (amountPassed, user_id, comments) => { + const amount = Math.abs(Number(amountPassed)); + const userDetails = await getUserWallet(user_id); + const initialbalance = Number(userDetails.amount_after); + if (initialbalance < amount) return false; + const newbalance = initialbalance - amount; //amount_after + await updateWallet(user_id, initialbalance, newbalance); + transaction( + TransactionTypeEnum.DEBIT, + comments, + amount, + userDetails.user_id, + TransactionStatusEnum.SUCCESS + ); + return true; +}; + +const transaction = ( + type, + description, + amount, + user_id, + transaction_status +) => { + return transactionModel.create({ + transaction_id: uuidv4(), + user_id: user_id, + transaction_type: type, + amount: amount, + comments: description, + transaction_status: transaction_status, + }); +}; const getUserWallet = (user_id) => { - return WalletModel.findOne({ - where: { - user_id: user_id - } - }) -} - - - -const updateWallet = (user_id, initial, after) =>{ - return WalletModel.update({ - amount_before: initial, - amount_after: after - }, { - where: { - user_id: user_id - } - }) -} - -const startWalletFunding = async (req, res) => { - const { amount, email } = req.body - if (!amount || !email) { - res.status(400).json({ - status: false, - message: "Amount and email are required" - }) - return - } - - - - const initialiseTransaction = await startPayment(amount, email) - delete initialiseTransaction.data.data.access_code - res.status(200).json({ - status: true, - message: "Transaction initialized successfully", - data: initialiseTransaction.data.data - - }) -} - -const completeWalletFunding = async (req, res) => { - - const { reference, user_id } = req.body - if (!reference || !user_id) { - res.status(400).json({ - status: false, - message: "All fields are required" - }) - return - } - const completeTransaction = await completePayment(reference) - if (completeTransaction.data.data.status !="success") { - res.status(400).json({ - status: false, - message: "Invalid transaction reference" - }) + return WalletModel.findOne({ + where: { + user_id: user_id, + }, + }); +}; + +const updateWallet = (user_id, initial, after) => { + return WalletModel.update( + { + amount_before: initial, + amount_after: after, + }, + { + where: { + user_id: user_id, + }, } - const amountInNaira = completeTransaction.data.data.amount / 100 - const comments = `Wallet funding of ${amountInNaira} was successful` - credit(amountInNaira, user_id, comments) - res.status(200).json({ - status: true, - message: "Your Wallet has been funded successfully", - }) -} + ); +}; + +const startWalletFunding = async (req, res) => { + const { amount, email } = req.body; + if (!amount || !email) { + res.status(400).json({ + status: false, + message: "Amount and email are required", + }); + return; + } + + const initialiseTransaction = await startPayment(amount, email); + delete initialiseTransaction.data.data.access_code; + res.status(200).json({ + status: true, + message: "Transaction initialized successfully", + data: initialiseTransaction.data.data, + }); +}; + +const completeWalletFunding = async (req, res) => { + const { reference, user_id } = req.body; + if (!reference || !user_id) { + res.status(400).json({ + status: false, + message: "All fields are required", + }); + return; + } + const completeTransaction = await completePayment(reference); + if (completeTransaction.data.data.status != "success") { + res.status(400).json({ + status: false, + message: "Invalid transaction reference", + }); + } + const amountInNaira = completeTransaction.data.data.amount / 100; + const comments = `Wallet funding of ${amountInNaira} was successful`; + credit(amountInNaira, user_id, comments); + res.status(200).json({ + status: true, + message: "Your Wallet has been funded successfully", + }); +}; const getWalletBalance = async (req, res) => { - const user_id = req.params.user_id - try { - const getWallet = await getUserWallet(user_id) - const walletBalance = getWallet.amount_after - return res.json({ - status: true, - balance: walletBalance, - message: "wallet balance fetched successfully", - }) - } catch (error) { - res.status(500).json({ - status: false, - message: "Error fetching wallet balance" - }) - } -} + const user_id = req.params.user_id; + try { + const getWallet = await getUserWallet(user_id); + const walletBalance = getWallet.amount_after; + return res.json({ + status: true, + balance: walletBalance, + message: walletBalanceMessage, + }); + } catch (error) { + res.status(500).json({ + status: false, + message: errorBalancemessage, + }); + } +}; const sendMoney = async (req, res) => { - let {amount, phone, user_id} = req.body - amount = Number(amount) - if (!phone|| !amount ) - return res.json({ - status: false, - message: "amount or phone number is required" - - }) - if( amount >50000){ - return res.json({ - status: true, - message: "your transfer limit has been exceeded" - }) - } - try { - const userDetails = await getUserWallet(user_id) - const recipientDetails = await getUserWithPhone(phone) - if (!recipientDetails){ - return res.json({ - status: false, - message: "user not found" - }) - } - if (userDetails.amount_after < amount ) - return res.json({ - status:false, - message: "insufficient balance. Please top-up your wallet" - }) - const debitComments = `you have successfully tranferred ${amount} to ${recipientDetails.surname}${recipientDetails.othernames}` - await debit(amount, user_id,debitComments) - const creditComments = `your account has been credited with ${amount} from ${userDetails.othernames} ${userDetails.surname}` - await credit(amount,recipientDetails.user_id,creditComments) - return res.json({ - status: true, - message: "Transaction completed successfully", - }) - - } catch (error) { - return res.json({ - status: false, - message: error.message - }) - } -} -const getUserWithPhone = async(phone) => { - return UserModel.findOne({ - where: { - phone: phone - } + let { amount, phone, user_id } = req.body; + + try { + const minimumWithdrawal = 100; + if (!phone || !amount || isNaN(amount) || amount <= minimumWithdrawal) + throw new Error(errorSendMoneyMessage, 400); + amount = Math.abs(Number(amount)); + const maximumWithdrawal = 50000; + if (amount > maximumWithdrawal) + throw new Error(errorSendMoneyMessageLimit, 400); + + const userDetails = await getUserDetails(user_id); + const userWalletDetails = await getUserWallet(user_id); + const recipientDetails = await getUserWithPhone(phone); + if(user_id == recipientDetails.user_id) throw new Error(sendMoneyToSelfMessage, 400) + if (!recipientDetails) throw new Error(sendMoneyErrorRecipientDetails, 400); + if (userWalletDetails.amount_after < amount) + throw new Error(userWalletDetailsError, 400); + + const receipientUserID = recipientDetails.user_id; + const debitComments = `you have successfully tranferred ${amount} to ${recipientDetails.surname} ${recipientDetails.othernames}`; + await debit(amount, user_id, debitComments); + const creditComments = `your account has been credited with ${amount} from ${userDetails.surname} ${userDetails.othernames}`; + await credit(amount, receipientUserID, creditComments); + return res.json({ + status: true, + message: receipientSuccessmessage, }); -} - - -const walletBalance = async(fullname, balance, date)=>{ - const userSurname= await UserModel.surname - const userOthernames= await UserModel.othernames - fullname =userSurname + userOthernames - const userBalance = await updateWallet(user_id, initial, after) - balance = userBalance.amount_after - const presentDate = Date.now() - date = presentDate - return -} + } catch (error) { + return res.json({ + status: false, + message: error.message, + }); + } +}; +const getUserDetails = (user_id) => { + return UserModel.findOne({ + where: { + user_id: user_id, + }, + }); +}; +const getUserWithPhone = async (phone) => { + return UserModel.findOne({ + where: { + phone: phone, + }, + }); +}; + +const walletBalance = async (fullname, balance, date) => { + const userSurname = await UserModel.surname; + const userOthernames = await UserModel.othernames; + fullname = userSurname + userOthernames; + const userBalance = await updateWallet(user_id, initial, after); + balance = userBalance.amount_after; + const presentDate = Date.now(); + date = presentDate; + return; +}; module.exports = { - credit, - debit, - transaction, - startWalletFunding, - completeWalletFunding, - getWalletBalance, - sendMoney, - walletBalance - -} - + credit, + debit, + transaction, + startWalletFunding, + completeWalletFunding, + getWalletBalance, + sendMoney, + walletBalance, +}; diff --git a/models/transactionModel.js b/models/transactionModel.js index 56baed9..13c6d72 100644 --- a/models/transactionModel.js +++ b/models/transactionModel.js @@ -32,6 +32,10 @@ const Transaction = sequelize.define('transaction', { values: ['pending', 'completed', 'failed'], allowNull: false, defaultValue: 'pending' + }, + createdAt: { + field: 'createdAt', + type: Sequelize.DATEONLY } }) Transaction.removeAttribute(['id']) diff --git a/package-lock.json b/package-lock.json index dcd6f4f..ea22525 100644 --- a/package-lock.json +++ b/package-lock.json @@ -17,6 +17,7 @@ "express": "^4.18.2", "form-data": "^4.0.0", "joi": "^17.9.2", + "moment": "^2.29.4", "mysql2": "^2.3.3", "sequelize": "^6.32.1", "uuid": "^9.0.0" diff --git a/package.json b/package.json index 292754b..d88b7ad 100644 --- a/package.json +++ b/package.json @@ -26,14 +26,13 @@ "express": "^4.18.2", "form-data": "^4.0.0", "joi": "^17.9.2", + "moment": "^2.29.4", "mysql2": "^2.3.3", "sequelize": "^6.32.1", "uuid": "^9.0.0" }, "devDependencies": { - "express-routemap": "^1.6.0", "nodemon": "^2.0.22" - } } diff --git a/routes/transactionRoutes.js b/routes/transactionRoutes.js index 52f7297..454dcdb 100644 --- a/routes/transactionRoutes.js +++ b/routes/transactionRoutes.js @@ -1,8 +1,8 @@ const express = require('express') const router = express.Router() - const{dailyTransaction, weeklyTransaction, monthlyTransaction} = require('../controllers/transactionController'); - router.get('/daily', dailyTransaction); -router.get('/weekly', weeklyTransaction) -router.get('/monthly',monthlyTransaction) + const{dailyTransaction, weeklyTransaction, monthlyTransaction} = require('../controllers/transactionController'); + router.post('/daily', dailyTransaction); + router.post('/weekly', weeklyTransaction) + router.post('/monthly',monthlyTransaction) module.exports = router \ No newline at end of file diff --git a/utils/helpers.js b/utils/helpers.js index 5935a1b..78999e6 100644 --- a/utils/helpers.js +++ b/utils/helpers.js @@ -1,4 +1,5 @@ const bcrypt = require('bcrypt'); +const moment = require('moment'); // require const saltRounds = 10; const hashPassword = async (password) => { @@ -39,8 +40,28 @@ const phoneValidation = (userPhone) => { } } +// const getTodaysDate = () => { + +// const today = new Date(); +// const yyyy = today.getFullYear(); +// let mm = today.getMonth() + 1; +// // Months start at 0! +// let dd = today.getDate(); +// if (dd < 10) dd = '0' + dd; +// if (mm < 10) mm = '0' + mm; +// const formattedToday = dd + '-' + mm + '-' + yyyy; +// return formattedToday.toString(); + +// } + +const getTodaysDate = () => { + const formattedToday = moment().format('YYYY-MM-DD') + return formattedToday; + } + module.exports = { hashPassword, generateOtp, - phoneValidation + phoneValidation, + getTodaysDate } \ No newline at end of file