Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const dotenv = require('dotenv');
- dotenv.config();
- const express = require('express');
- const incomeRoute = express.Router();
- const knex = require('../knex/knex');
- const income = knex('income');
- const passport = require('passport');
- require('../middleware/passport')(passport);
- incomeRoute.use(function timeLog (req, res, next) {
- let timeStamp = new Date().toString();
- console.log(`Request received at incomeRoute on: ${timeStamp}`);
- next();
- });
- // verify user is authenticated before accessing data
- let authenticate = (req, res, next) => {
- if(req.isAuthenticated()) {
- return next();
- }
- res.status(403).send('You are not logged in. You will be redirected to login.');
- }
- incomeRoute.get('/', (req, res) => {
- let userid = req.user[0]['userid'];
- income.where({
- userid: userid
- }).orderBy('transactionid', 'desc').then((data, err) => {
- return err? console.log(err) : res.send(data);
- }).catch((err) => {
- console.log(err);
- })
- });
- incomeRoute.post('/create', (req, res) => {
- // let userid = req.user[0]['userid'];
- let userid = req.body.userid;
- let amount = req.body.amount;
- let employer = req.body.employer;
- let datereceived = req.body.datereceived;
- let tax = amount * 0.15;
- income.where({
- userid: userid
- }).select('transactionid', 'taxytd')
- .orderBy('transactionid', 'desc')
- .then((data) => {
- let taxytd = data[0]['taxytd']; // Set taxytd param to be used in existingData function
- return data === undefined || data.length === 0 ? noExistingIncome() : existingData(taxytd);
- }).catch((err) => {
- console.log(err);
- });
- let noExistingIncome = () => {
- income.insert({
- userid: userid,
- amount: amount,
- employer: employer,
- datereceived: datereceived,
- tax: tax,
- taxytd: tax
- }).then((data) => {
- res.send('Data successfully entered');
- }).catch((err) => {
- console.log(err);
- res.send('There was an issue while creating this data. Please try again');
- });
- };
- let existingData = (taxytd) => {
- /*
- While using income.insert({...}), it will fail on the second data submission w/ an error of NaN for taxytd.
- It is unclear as to why this happens at this time however the below function works correctly when using it as knex.insert({...}).into('income')
- */
- let newTaxYtd = Number(taxytd) + Number(tax);
- knex.insert({
- userid: userid,
- amount: amount,
- employer: employer,
- datereceived: datereceived,
- tax: tax,
- taxytd: newTaxYtd
- }).into('income').then((data) => {
- res.send('Data successfully entered');
- }).catch((err) => {
- console.log(err);
- res.send('There was an issue while creating this data. Please try again');
- });
- }
- });
- module.exports = incomeRoute;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement