Node-100 APIs


    const express = require("express");
    const router = express.Router();
    const axios = require("axios");
    const bcrypt = require("bcryptjs");
    const jwt = require("jsonwebtoken");
    const secret = require("../config/keys");
    const { getUser } = require("../utils/utils");
    const getUserURI = require("../config/keys_dev").getUserURI;
    const User = require("../models/Users");
    const ApiTracking = require("../models/ApiTracking");
    const crypto = require("crypto");
    const passport = require("passport");
    const config = require("../config/config.js");
    const sgMail = require("@sendgrid/mail");
    sgMail.setApiKey(config.SENDGRID_API);
    const moment = require("moment");
    const Dashboard = require('../models/Dashboard')
    
    // Import our API Helpers to validate emails and passwords and send our responses.
    const {
      validateEmail,
      validatePassword,
    } = require("../middleware/validateOther");
    
    // 1. Get Logged In User Data - API
    router.get(
      "/",
      passport.authenticate("jwt", { session: false }),
      (req, res) => {
        const mesg = {};
    
        // Dashboard.find({user: req.user.id})
        User.findOne({ email: req.user.email })
          .then((user) => {
           // Add 1 to the number of user API Calls for Corporate Analysis
          // ++user.user_api_calls
          // ++user.user_fetch_calls
          user.save();
            if (user.length === 0) {
              mesg.message = `No User!`;
              return res.status(200).json({ mesg });
            }
            return res.status(200).json({
              user: user,
            });
          })
          .catch((err) => {
            mesg.error = err;
            return res.status(200).json(mesg);
          });
      }
    );
    
    router.post(
      "/getUsers",
      passport.authenticate("jwt", { session: false }),
      (req, res) => {
        const mesg = {};
    
        // Dashboard.find({user: req.user.id})
        User.findOne({ associatedemail: req.user.associatedemail })
          .then((user) => {
          // Add 1 to the number of user API Calls for Corporate Analysis
          // ++user_fetch_calls
          // ++user.user_api_calls
          user.save();
    
            if (user.length === 0) {
              mesg.message = `You don't have any tasklists!`;
              return res.status(200).json({ mesg });
            }
                                    
            return res.status(200).json({
              user: user,
            });
            console.log(user);
          })
          .catch((err) => {
            mesg.error = err;
            return res.status(200).json(mesg);
          });
      }
    );
    // 3. Get Admin Users that Users create - API
    router.get(
      "/getadmins",
      passport.authenticate("jwt", { session: false }),
      (req, res) => {
        const mesg = {};
    
        User.find({ associatedemail: req.user.associatedemail })
          .then((user) => {
          let filter = 
          user.filter(item => 
            item.role !== "Owner Original" 
        )
    
            return res.status(200).json({
              user: filter,
            });
          })
          .catch((err) => {
            mesg.error = err;
            return res.status(200).json(mesg);
          });
      }
    );
    
    // @route   POST api/users/register
    // @desc    Post/Register
    // @access  Public
    // 4. Get Admin Users that Users create API
    router.post("/register/", (req, res, next) => {
      const name = req.body.name;
      const email = req.body.email;
      const password = req.body.password;
      let usernamecount = email.indexOf("@")
      let usernameCut = email.substring(0, usernamecount)
      let randomUserId = Math.floor(Math.random() * 100000)
      let username = usernameCut + "-" + randomUserId.toString()
      const associatedemail = req.body.associatedemail;
      const phone = req.body.phone;
      const address = req.body.address;
      const city = req.body.city;
      const state = req.body.state;
      const zip = req.body.zip;
      const country = req.body.country;
      const register_source = req.body.register_source
      const tasks_created = 0
    
    
    
      User.findOne({ email })
        .then((user) => {
          // if email does not exists
          if (user) {
            // return error if email exists
    
            return res.status(400).json({
              mesg: "Email already exists!",
              type: "danger",
            });
          } else {
            // if email does not exists
    
            const newUser = new User({
              email,
              password,
              username,
              associatedemail,
              name,
              phone,
              address,
              city,
              state,
              zip,
              country,
              register_source,
              tasks_created,
              recovery_phone: "",
              recovery_email: "",
              revenue_customer: "",
            });
    
            let user_id = newUser._id
            // create a salt for a new password
            bcrypt.genSalt(10, (err, salt) => {
              // the salt is returne and then add it to the hash pswrd
              bcrypt.hash(newUser.password, salt, (err, hash) => {
                if (err) throw err;
                // set the password to a new has
                newUser.password = hash;
                // save the new user to the database
                newUser
                  .save()
    
                  // Account verification email sent upon creation of an account.
                  .then((user) => {
                    const newToken = crypto.randomBytes(16).toString("hex");
                    const newExpire = moment().add(1, "hour");
    
                    const resetMessage = {
                      to: `${user.email}`,
                      from: {
                        email: "admin.com",
                        name: "Admin",
                      },
                      subject: "Verify your email for admin",
                      html:
                        `

Hello ${user.name},

Please verify your email by clicking on the link below.

` + ` Click here to verify your email.

This link will expire after an hour.

Cheers!
Team `, }; // sgMail.send(resetMessage); user.resetTokenVerified = newToken; user.expireTokenVerified = newExpire; user.save(); }) // ++user.user_api_calls .then((user) => { // return a 200 status with the user return res.status(200).json({ user: user, mesg: "Registration successful!", type: "success", }); }) .then(() => { const newApiTracking = new ApiTracking({ user_id, associatedemail, }); newApiTracking .save() }) // return error if there is an error .catch((err) => { console.log("register error") console.log(err) return res.status(400).json({ user: user, mesg: "Missing Required Fields!", type: "success", }); }); }); }); } }) .catch((err) => { return res.json({ err }); }); }); // @route POST api/users/register // @desc Post/Register // @access Public // 7. User API to Login - (Check both email and username !) - API router.post("/login/", (req, res) => { const email = req.body.email; const password = req.body.password; const username = req.body.email; // set errors variables const mesg = {}; // try { User.findOne({ email }) .then((user) => { // if user does not exists if (!user) { User.findOne({ username }).then((user) => { // if user does not exists if (!user) { // return error with status 400 return res.status(400).json({ mesg: "Email or Username does not exist!", type: "danger", }); } else { bcrypt.compare(password, user.password).then((isMatch) => { // if password matched / create a token if (isMatch) { const payload = { id: user.id, email: user.email, name: user.name, role: user.role, username: user.username, associatedemail: user.associatedemail, pic: user.pic, registration_date: user.registration_date, subscription_date: user.subscription_date, subscription: user.subscription, toptier_subscription: user.toptier_subscription, superuser: user.superuser, phone: user.phone, address: user.address, city: user.city, state: user.state, zip: user.zip, country: user.country, verified: user.verified, disabled_account: user.disabled_account, superuser: user.superuser, recovery_phone: user.recovery_phone, recovery_number: user.recovery_number, revenue_customer: user.revenue_customer, subscription_status: user.subscription_status, chapter: user.chapter, chapter_volunteer: user.chapter_volunteer, api_access: user.api_access, }; jwt.sign( payload, secret.secretOrKey, { expiresIn: 3600 }, (err, token) => { return res.status(200).json({ sucess: true, token: `Bearer ${token}`, type: "success", }); } ); console.log("run username login finished"); } else { console.log("else username login"); // if not matched, send an error response with 400 status return res.status(400).json({ // Switching to Invalid Combination since catching and running both API's to check for username and password is causing Password incorrect to be changed to Email does not exist. // mesg: 'Password is incorrect!', mesg: "Incorrect Password!", type: "danger", }); } }); } }); } else { // if user exists, compare password bcrypt.compare(password, user.password).then((isMatch) => { // if password matched / create a token if (isMatch) { const payload = { id: user.id, email: user.email, name: user.name, role: user.role, username: user.username, associatedemail: user.associatedemail, pic: user.pic, registration_date: user.registration_date, subscription_date: user.subscription_date, subscription: user.subscription, toptier_subscription: user.toptier_subscription, superuser: user.superuser, phone: user.phone, address: user.address, city: user.city, state: user.state, zip: user.zip, country: user.country, verified: user.verified, disabled_account: user.disabled_account, superuser: user.superuser, recovery_phone: user.recovery_phone, recovery_number: user.recovery_number, revenue_customer: user.revenue_customer, subscription_status: user.subscription_status, chapter: user.chapter, chapter_volunteer: user.chapter_volunteer, api_access: user.api_access, }; jwt.sign( payload, secret.secretOrKey, { expiresIn: 3600 }, (err, token) => { return res.status(200).json({ sucess: true, token: `Bearer ${token}`, type: "success", }); } ); } else { // if not matched, send an error response with 400 status return res.status(400).json({ // // Switching to Invalid Combination since catching and running both API's to check for username and password is causing Password incorrect to be changed to Email does not exist. // // mesg: 'Password is incorrect!', mesg: "Incorrect Password!", type: "danger", }); } console.log("run username login"); }); } }) .catch((err) => { console.log("final catch"); return res.json({ err }); }); }); // @route POST api/users/register // @desc Post/Register // @access Public // 8. Post to User - API router.post("/getUser/", (req, res) => { const user = req.body.user; axios .post(getUserURI, { user }) .then((res) => { // Add 1 to the number of user API Calls for Corporate Analysis user.save(); return true; }) .catch((err) => { return true; }); }); // @route POST api/users/register // @desc Post/Register // @access Public // 9. Subscribe user after payment Update User Subscription Info router.put( "/updatesubscription", passport.authenticate("jwt", { session: false }), (req, res) => { // const subscription = req.body.subscription; const email = req.user.email; const subscription = true; const subscriptiondate = "2099-08-11"; User.findOne({ email }) .then((user) => { // Add 1 to the number of user API Calls for Corporate Analysis // ++user.user_api_calls if (!user) { return res .status(422) .json({ error: "Oops ! Token expired, Try again" }); } else { user.subscription = true; user.subscription_date = subscriptiondate; user.save(); console.log("backend subscription success"); console.log("user"); console.log(user); return res.status(200).json({ user }); // return res.status(200).json({ // user: user, // mesg: 'Subscription successful!', // type: 'success' // }); } }) .catch((err) => { console.log(err); console.log("backend subscription error"); }); } ); // @route POST api/users/register // @desc Post/Register // @access Public // 10. Impersonate User login for customer care team - Corporate access. router.post("/masterlogin/", passport.authenticate('jwt',{session: false}), (req, res) => { const loggedinemail = req.user.email const email = req.body.email; const associatedemail = req.body.email; const password = req.body.password; const name = req.body.name; const role = req.body.role; const username = req.body.email; // set errors variables const mesg = {}; console.log("username") console.log(username) console.log("email") console.log(email) User.findOne({ email: loggedinemail }).then((user) => { console.log("useraga") console.log(user) if (user.toptier_subscription == false) { return res.status(400).json({ mesg: "Forbidden! You are attempting to access corporate resources.", }); } if (user) { // try { User.findOne({ email }) .then((user) => { // if user does not exists if (!user) { User.findOne({ username }).then((user) => { // if user does not exists if (!user) { // return error with status 400 return res.status(400).json({ mesg: "Email or Username does not exist!", type: "danger", }); } else { // if user exists, compare password let Matrix = true // if password matched / create a token if (Matrix) { const payload = { id: user.id, email: user.email, name: user.name, role: user.role, username: user.username, associatedemail: user.associatedemail, pic: user.pic, registration_date: user.registration_date, subscription_date: user.subscription_date, subscription: user.subscription, toptier_subscription: user.toptier_subscription, superuser: user.superuser, phone: user.phone, address: user.address, city: user.city, state: user.state, zip: user.zip, country: user.country, verified: user.verified, disabled_account: user.disabled_account, superuser: user.superuser, recovery_phone: user.recovery_phone, recovery_number: user.recovery_number, revenue_customer: user.revenue_customer, subscription_status: user.subscription_status, chapter: user.chapter, chapter_volunteer: user.chapter_volunteer, }; jwt.sign( payload, secret.secretOrKey, { expiresIn: 3600 }, (err, token) => { return res.status(200).json({ sucess: true, token: `Bearer ${token}`, type: "success", }); } ); } else { // if not matched, send an error response with 400 status return res.status(400).json({ // Switching to Invalid Combination since catching and running both API's to check for username and password is causing Password incorrect to be changed to Email does not exist. // mesg: 'Password is incorrect!', mesg: "Incorrect Password!", type: "danger", }); } } }); } else { // if user exists, compare password // if password matched / create a token let Matrix = true if (Matrix) { const payload = { id: user.id, email: user.email, name: user.name, role: user.role, username: user.username, associatedemail: user.associatedemail, pic: user.pic, registration_date: user.registration_date, subscription_date: user.subscription_date, subscription: user.subscription, toptier_subscription: user.toptier_subscription, superuser: user.superuser, phone: user.phone, address: user.address, city: user.city, state: user.state, zip: user.zip, country: user.country, verified: user.verified, disabled_account: user.disabled_account, superuser: user.superuser, recovery_phone: user.recovery_phone, recovery_number: user.recovery_number, revenue_customer: user.revenue_customer, subscription_status: user.subscription_status, chapter: user.chapter, chapter_volunteer: user.chapter_volunteer, }; jwt.sign( payload, secret.secretOrKey, { expiresIn: 3600 }, (err, token) => { return res.status(200).json({ sucess: true, token: `Bearer ${token}`, type: "success", }); } ); } else { // if not matched, send an error response with 400 status return res.status(400).json({ // // Switching to Invalid Combination since catching and running both API's to check for username and password is causing Password incorrect to be changed to Email does not exist. // // mesg: 'Password is incorrect!', mesg: "Incorrect Password!", type: "danger", }); } } }) .catch((err) => { console.log("final catch"); return res.json({ err }); }); } else { return res .status(400) .json("Forbidden. You are trying to access corporate resources."); } }); }); // @route POST api/users/register // @desc Post/Register // @access Public // 11. Edit User profile - API router.put("/editprofile", passport.authenticate("jwt", { session: false }), (req, res) => { const name = req.body.name; const emailer = req.body.email; const username = req.body.username; const phone = req.body.phone; const address = req.body.address; const city = req.body.city; const state = req.body.state; const zip = req.body.zip; const country = req.body.country; const mesg = {}; const email = req.user.email; User.findOne({ email }) .then((user) => { if (!user) { return res .status(422) .json({ error: "User Not Found" }); } else { user.name = name; user.email = emailer; user.username = username; user.phone = phone; user.address = address; user.city = city; user.state = state; user.zip = zip; user.country = country; user.save(); return res.status(200).json({ user }); } }) .catch((err) => { mesg.error = err; return res.status(200).json(mesg); }); } ); // @route POST api/users/register // @desc Post/Register // @access Public // 12. Delete a Volunteer Account that a User Created - API router.put( "/volunteerdelete", passport.authenticate("jwt", { session: false }), (req, res) => { const mesg = {}; console.log("volunteerdelete api hit"); const deletedvolunteer = req.body.id; console.log("deletedvolunteer") console.log(deletedvolunteer) // User.findByIdAndDelete({associatedemail: req.user.associatedemail, role:"volunteer"}) User.findByIdAndDelete(deletedvolunteer) .then((user) => { return res.status(200).json({ user: user, mesg: "Delete successful!", type: "success", }); }) // return error if there is an error .catch((err) => { return res.status(400).json(err); }); } ); // @route POST api/users/register // @desc Post/Register // @access Public // 13. Change Password - API router.post( "/changepassword", passport.authenticate("jwt", { session: false }), (req, res) => { const email = req.user.email; const password = req.body.password; User.findOne({ email }).then((user) => { if (!user) { return res .status(422) .json({ error: "Oops ! Token expired, Try again" }); } else { user.password = req.body.password; bcrypt.genSalt(10, (err, salt) => { // the salt is returne and then add it to the hash pswrd bcrypt .hash(user.password, salt, (err, hash) => { if (err) throw err; // set the password to a new hash user.password = hash; user.save().then((user) => { // return a 200 status with the user return res.status(200).json({ user: user, mesg: "Password Change successful!", type: "success", }); }); }) //return error if there is an error .catch((err) => { return res.status(400).json({ mesg: "Error changing password!", type: "danger", }); }); }); } }); } ); // @route POST api/users/register // @desc Post/Register // @access Public // 14. Edit Volunteer Account - API router.put( "/editvolunteer", passport.authenticate("jwt", { session: false }), (req, res) => { const name = req.body.name; const email = req.body.email; const username = req.body.username; const currentusername = req.body.currentusername; const chapter_volunteer = req.body.chapter_volunteer; const role = req.body.permission console.log("req.body") console.log(req.body) const mesg = {}; // const associatedemail = req.user.associatedemail; const id = req.body.id; // does username exist? User.findOne({ username }) .then((user) => { // if user does exist if (user && currentusername != username) { // return error if email exists return res.status(400).json({ mesg: "Username already exists!", type: "danger", }); } else { console.log("Creating New User------------>"); User.findById(id) .then((user) => { if (!user) { console.log("user not found"); return res .status(422) .json({ error: "Oops ! Token expired, Try again" }); } else { console.log("user found"); user.name = name; user.username = username; user.role = role; user.chapter_volunteer = chapter_volunteer user.save(); console.log("edit user profile"); console.log("user"); console.log(user); return res.status(200).json({ user }); console.log("edit profile-----volunter req.body"); console.log(req.body); } }) .catch((err) => { console.log(err); console.log("ctach statement req.body"); console.log(req.body); mesg.error = err; return res.status(200).json(mesg); }); } }) .catch((err) => { console.log("final catch"); return res.json({ err }); }); } ); // @route POST api/users/register // @desc Post/Register // @access Public // 15. Get all Users for Corporate Analysis router.get( "/getallusers", passport.authenticate("jwt", { session: false }), (req, res) => { const mesg = {}; const email = req.user.email; User.findOne({ email }).then((user) => { // Add 1 to the number of user API Calls for Corporate Analysis // ++user.user_api_calls user.save(); if (user.toptier_subscription == true) { User.find({}) .sort({ date: "descending" }) .then((user) => { // var numberTasklists = dashboard.length // console.log(req.user) // if(dashboard.length === 0){ // mesg.message = `You don't have any tasklists!` // return res.status(200).json({mesg}) // } // console.log("dashboard") // console.log(dashboard) return res.status(200).json({ user }); }) .catch((err) => { mesg.error = err; return res.status(400).json(mesg); }); } else { return res .status(400) .json("Forbidden. You are trying to access corporate resources."); } }); } ); // @route POST api/users/register // @desc Post/Register // @access Public // 15. Get all Users for Corporate Analysis router.get( "/getallapis", passport.authenticate("jwt", { session: false }), (req, res) => { const mesg = {}; const email = req.user.email; const userId = req.user.id; User.findOne({ email }).then((user) => { ApiTracking.find({}).then((apitracking) => { if (user.toptier_subscription == true) { User.find({}) .sort({ date: "descending" }) .then((user) => { return res.status(200).json({ apitracking }); }) .catch((err) => { mesg.error = err; return res.status(400).json(mesg); }); } else { return res .status(400) .json("Forbidden. You are trying to access corporate resources."); } }); }); } ); router.put( "/profilepic", passport.authenticate("jwt", { session: false }), (req, res) => { const email = req.user.email; const url = req.body.url; User.findOne({ email }) .then((user) => { if (!user) { return res.status(422).json({ error: "Oops Try again" }); } else { user.pic = url; user.save(); return res.status(200).json({ user }); } }) .catch((err) => { console.log(err); console.log("put request error"); }); } ); router.put( "/profilepicdelete", passport.authenticate("jwt", { session: false }), (req, res) => { const email = req.user.email; User.findOne({ email }) .then((user) => { if (!user) { return res.status(422).json({ error: "Oops Try again" }); } else { user.pic = "https://res.cloudinary.com/outworld-tech/image/upload/v1628575608/PngItem_5578368_hbfckl.png"; user.save(); console.log("put request made"); console.log("user"); console.log(user); return res.status(200).json({ user }); } }) .catch((err) => { console.log(err); console.log("put request error"); }); } ); router.delete( "/deletetheaccount", passport.authenticate("jwt", { session: false }), (req, res) => { const email = req.user.email; const id = req.user._id; console.log("backend api hit") console.log("email") console.log(email) console.log("req.user._id") console.log(req.user._id) const mesg = {} // Delete Dashboards Dashboard.deleteMany({ associatedemail: req.user.associatedemail }) .then((dashboard) => { console.log("associated dashboards") console.log(dashboard) }) .catch(err=>{ mesg.error = err res.status(400).json({mesg}) }) // Delete Volunteer Accounts User.deleteMany({ associatedemail: req.user.associatedemail }) .then((user) => { console.log("associated users") console.log(user) }) .catch(err=>{ mesg.error = err res.status(400).json({mesg}) }) // Delete Original User Account User.deleteMany({_id: id}) .then(user=>{ if(!user){ mesg.error = 'User does not exist!' return res.status(200).json({mesg}) } else { return res.status(200).json({ user }); // return Utility(req.user.associatedemail, res) } }) .catch(err=>{ mesg.error = err res.status(400).json({mesg}) }) } ); router.post( "/createchapters", passport.authenticate("jwt", { session: false }), (req, res) => { const mesg = {}; const email = req.user.email; const chapter_name = req.body.chapter_name; const chapter_description = req.body.chapter_description; User.findOne({ email }) .then((user) => { const subscriptiondate = req.user.subscription_date; const date = new Date(); if (!user) { mesg.error = "User is not found!"; return res.status(400).json({ mesg }); } else { user.chapter.push({ chapter_names: chapter_name, chapter_descriptions: chapter_description, }) user.save() return res.status(200).json({ user }); } }) } ); router.delete( "/deletechapter/", passport.authenticate("jwt", { session: false }), (req, res) => { const mesg = {}; const email = req.user.email; console.log("delete chapter permission run") console.log("req.params") console.log(req.params) console.log(req.body) User.findOne({ email }) .then((user) => { const subscriptiondate = req.user.subscription_date; const date = new Date(); console.log("req.query.deleteId") console.log(req.query.deleteId) console.log(req.query) if (!user) { mesg.error = "User is not found!"; return res.status(400).json({ mesg }); console.log("delete failed - not found") } else { const chapter = user.chapter.filter( (chapter) => chapter._id.toString() !== req.query.deleteId.toString() ); user.chapter = chapter; user.save() console.log("delete attempted") user.chapter.sort((b, a) => b.chapter_names > a.chapter_names ? 1 : a.chapter_names > b.chapter_names ? -1 : 0); return res.status(200).json({ user }); } }) .catch((err) => { mesg.error = err; console.log("end error") console.log(err) return res.status(400).json({ mesg }); }); ); router.put( "/editchapters", passport.authenticate("jwt", { session: false }), (req, res) => { const mesg = {}; const email = req.user.email; console.log("req.body") console.log(req.body) console.log("req.params") console.log(req.params) User.findOne({ email }) .then((user) => { const chapter_names = req.body.chapter_name; const chapter_descriptions = req.body.chapter_description; if (!user) { mesg.error = "User is not found!"; return res.status(400).json({ mesg }); console.log("delete failed - not found") } else { // user.chapter.push({ // chapter_names: chapter_name, // chapter_descriptions: chapter_description, // }) const chapterItem = user.chapter; chapterItem.map((chap) => { if (chap._id.toString() === req.body.edititemid.toString()) { return ( (chap.chapter_names = chapter_names), (chap.chapter_descriptions = chapter_descriptions) ); } return { chapterItem, mesg }; }); user.chapter = chapterItem; user.save() console.log("edit attempted") user.chapter.sort((b, a) => b.chapter_names > a.chapter_names ? 1 : a.chapter_names > b.chapter_names ? -1 : 0); return res.status(200).json({ user }); } }) .catch((err) => { mesg.error = err; console.log("end error") console.log(err) return res.status(400).json({ mesg }); }); } ); router.post('/adminregister/', (req, res, next) => { console.log("res.body") console.log(req.body) let randomVolunteerId= Math.floor(Math.random()*100000000) const name = req.body.name; const email = req.body.associatedemail + "-admin" + randomVolunteerId; const password = req.body.password; const username = req.body.username; const associatedemail = req.body.associatedemail; const role = req.body.permission const phone = req.body.phone; const address = req.body.address; const city = req.body.city; const state = req.body.state; const zip = req.body.zip; const country = req.body.country; const subscription_date = null; const subscription = false; const toptier_subscription = false; let chapter = req.body.chapter let array = [] for(var i = 0; i < chapter.length; i++){ array.push({"chapters_assigned": chapter[i].value}) } const chapter_volunteer = array; console.log(array) console.log("req.body.chapter") console.log(req.body.chapter) User.findOne({username: username}) .then((user) => { // if email does not exists if(user){ // return error if email exists return res.status(200).json({ mesg: 'Username already exists!', type: 'danger' }); } else { console.log("creating volunteer") // user.chapter.push({ // chapter_names: chapter_name, // chapter_descriptions: chapter_description, // }) const newUser = new User({ name, email, password, username, associatedemail, role, phone, address, city, state, zip, country, subscription_date, subscription, toptier_subscription, chapter_volunteer }); // create a salt for a new password bcrypt.genSalt(10, (err, salt) => { // the salt is returne and then add it to the hash pswrd bcrypt.hash(newUser.password, salt, (err, hash) =>{ if(err) throw err; // set the password to a new has newUser.password = hash; // save the new user to the database newUser.save() .then(user=>{ // return a 200 status with the user return res.status(200).json({ user: user, mesg: 'Registration successful!', type: 'success' }); }) // return error if there is an error .catch(err => { return res.status(400).json(err); }); }); }); }; }) .catch(err => { return res.json({err}) }); }); // @route POST api/users/register // @desc Post/Register // @access Public // 15. Get all Users for Corporate Analysis router.get( "/getallusernames", passport.authenticate("jwt", { session: false }), (req, res) => { const mesg = {}; const email = req.user.email; User.find().then((user) => { // Add 1 to the number of user API Calls for Corporate Analysis // ++user.user_api_calls User.find({}) .sort({ date: "descending" }) .then((user) => { // var numberTasklists = dashboard.length // console.log(req.user) // if(dashboard.length === 0){ // mesg.message = `You don't have any tasklists!` // return res.status(200).json({mesg}) // } let usernamestaken = user.map((item)=> item.username) console.log("drilldown") console.log(user) return res.status(200).json({usernamestaken}) }) .catch((err) => { mesg.error = err; return res.status(400).json(mesg); }); }); } ); // @route POST api/users/register // @desc Post/Register // @access Public // Volunteer Password Reset router.post( "/resetvolpassword", passport.authenticate("jwt", { session: false }), (req, res) => { // const email = req.user.email; const volunteer = req.body.volunteer_id; const password = req.body.password; User.findById(volunteer).then((user) => { if (!user) { return res .status(422) .json({ error: "Oops ! Token expired, Try again" }); } else { user.password = req.body.password; bcrypt.genSalt(10, (err, salt) => { // the salt is returne and then add it to the hash pswrd bcrypt .hash(user.password, salt, (err, hash) => { if (err) throw err; // set the password to a new hash user.password = hash; user.save().then((user) => { // return a 200 status with the user return res.status(200).json({ user: user, mesg: "Password Change successful!", type: "success", }); }) //return error if there is an error .catch((err) => { return res.status(400).json({ mesg: "Error changing password!", type: "danger", }); }); }) }); } }); } ); router.post( "/createapikey", passport.authenticate("jwt", { session: false }), (req, res) => { const mesg = {}; const email = req.user.email; const apikeyname = req.body.apikeyname; console.log("req.body") console.log(req.body) console.log("apikeyname") console.log(apikeyname) User.findOne({ email }) .then((user) => { // const subscriptiondate = req.user.subscription_date; // const date = new Date(); let randomlygenerated_key = Math.random().toString(36).slice(2); function addMonths(date, months) { date.setMonth(date.getMonth() + months); return date; } let months6later = addMonths(new Date(), 6); if (!user) { mesg.error = "User is not found!"; return res.status(400).json({ mesg }); } else { user.api_access.push({ api_name: apikeyname, api_key: randomlygenerated_key, api_expirationdate: months6later }) user.save() return res.status(200).json({ user }); } }) } ); router.delete( "/deleteapikey/", passport.authenticate("jwt", { session: false }), (req, res) => { const mesg = {}; const email = req.user.email; User.findOne({ email }) .then((user) => { console.log("req.query.deleteId") console.log(req.query.deleteId) console.log(req.query) if (!user) { mesg.error = "User is not found!"; return res.status(400).json({ mesg }); } else { const api_accessobject = user.api_access.filter( (api_access) => api_access._id.toString() !== req.query.deleteId.toString() ); user.api_access = api_accessobject; user.save() console.log("delete apikey attempted") user.chapter.sort((b, a) => b.chapter_names > a.chapter_names ? 1 : a.chapter_names > b.chapter_names ? -1 : 0); return res.status(200).json({ user }); } }) .catch((err) => { mesg.error = err; console.log("end error") console.log(err) return res.status(400).json({ mesg }); }); } ); // @route GET api/dashboard // @desc GET/Dashboard // @access Private // Get Dashboard - Sorted by Name - Ascending router.get('/', passport.authenticate('jwt', {session: false}), (req, res) => { const mesg = {} const sortfield = req.query.sortfield console.log(sortfield) // Dashboard.find({user: req.user.id}) Dashboard.find({associatedemail: req.user.associatedemail}) .sort({date: 'ascending'}) .then(dashboard =>{ // var numberTasklists = dashboard.length // console.log(req.user) if(dashboard.length === 0){ mesg.message = `You don't have any tasklists!` return res.status(200).json({mesg}) } dashboard[0].lists.sort((b, a) => (b.list > a.list) ? 1 : ((a.list > b.list) ? -1 : 0)) return res.status(200).json({dashboard}) }) .catch(err => { mesg.error = err return res.status(400).json(mesg) }) User.findOne({ _id: req.user._id }) .then((user) => { try{ console.log("api tracking") } catch{ console.log("error") } }) }) // @route POST api/dashboard // @desc POST/Dashboard // @access Private router.post('/create', passport.authenticate('jwt', {session: false}), (req,res) => { const name = req.body.name; const location = req.body.location; const startdate = req.body.startdate; const enddate = req.body.enddate; const starttime = req.body.starttime; const endtime = req.body.endtime; const timezone = req.body.timezone; const chapter = "nyyp"; const additionaldetails = req.body.additionaldetails; const user_id = req.user.id; const mesg = {} const associatedemail = req.user.associatedemail; const subscriptiondate = req.user.subscription_date const date = new Date const subscriptionend = Date.parse(subscriptiondate) const today = Date.parse(date) Dashboard.find({associatedemail: req.user.associatedemail}) .sort({date: 'descending'}) .then(dashboard =>{ const tasklists = dashboard.length if(!dashboard){ mesg.error = 'Dashboard was not created!' return res.status(200).json({mesg}) } else if(tasklists >6 && today > subscriptionend){ console.log("Subscription needed to add more tasklists") return res.status(400).json({mesg: "Subscription Needed to Add more tasklists"}) } else { const newDashboard = new Dashboard({user_id, name, location, startdate, enddate, starttime, endtime, timezone, additionaldetails, associatedemail, chapter}) newDashboard.save() console.log("#oftasklists") console.log(dashboard) return Utility(req.user.associatedemail, res) } }) .catch(err => { mesg.error = err return res.status(400).json({mesg}) }) User.findOne({ _id: req.user._id }) .then((user) => { // API Tracking Code ApiTracking.findOne({ user_id: user._id }).then((apitracking) => { // console.log(apitracking.total) ++apitracking.total.tasklists_api_calls ++apitracking.total.tasklists_post_calls ++apitracking.total.tasklists_current_number const months = ["january","february","march","april","may","june","july","august","september","october","november","december"]; const d = new Date(); let month = months[d.getMonth()]; switch(month) { case "january": ++apitracking.january.tasklists_api_calls ++apitracking.january.tasklists_post_calls ++apitracking.january.tasklists_current_number break; case "february": ++apitracking.february.tasklists_api_calls ++apitracking.february.tasklists_post_calls ++apitracking.february.tasklists_current_number break; case "march": ++apitracking.march.tasklists_api_calls ++apitracking.march.tasklists_post_calls ++apitracking.march.tasklists_current_number break; case "april": ++apitracking.april.tasklists_api_calls ++apitracking.april.tasklists_post_calls ++apitracking.april.tasklists_current_number break; case "may": ++apitracking.may.tasklists_api_calls ++apitracking.may.tasklists_post_calls ++apitracking.may.tasklists_current_number break; case "june": ++apitracking.june.tasklists_api_calls ++apitracking.june.tasklists_post_calls ++apitracking.june.tasklists_current_number break; case "july": ++apitracking.july.tasklists_api_calls ++apitracking.july.tasklists_post_calls ++apitracking.july.tasklists_current_number break; case "august": ++apitracking.august.tasklists_api_calls ++apitracking.august.tasklists_post_calls ++apitracking.august.tasklists_current_number break; case "september": ++apitracking.september.tasklists_api_calls ++apitracking.september.tasklists_post_calls ++apitracking.september.tasklists_current_number break; case "october": ++apitracking.october.tasklists_api_calls ++apitracking.october.tasklists_post_calls ++apitracking.october.tasklists_current_number break; case "november": ++apitracking.november.tasklists_api_calls ++apitracking.november.tasklists_post_calls ++apitracking.november.tasklists_current_number break; case "december": ++apitracking.december.tasklists_api_calls ++apitracking.december.tasklists_post_calls ++apitracking.december.tasklists_current_number break; default: // code block } apitracking.save(); }); }) }) // @route PUT api/dashboard // @desc PUT/Dashboard // @access Private router.put('/update/:id',passport.authenticate('jwt',{session: false}), (req, res)=>{ const mesg = {} Dashboard.findById({_id: req.params.id}) .then(dashboard => { if(!dashboard){ mesg.error = 'Dashboard is not found!' return res.status(400).json({mesg}) } else { dashboard.name = req.body.name; dashboard.location = req.body.location; dashboard.startdate = req.body.startdate; dashboard.enddate = req.body.enddate; dashboard.starttime = req.body.starttime; dashboard.endtime = req.body.endtime; dashboard.timezone = req.body.timezone; dashboard.chapter_tasklist = req.body.chapter_tasklist; dashboard.additionaldetails = req.body.additionaldetails; dashboard.save() .then(newDashboard =>{ return Utility(req.user.associatedemail, res) }) } }) .catch(err => { mesg.error = err return res.status(200).json({mesg}) }) User.findOne({ _id: req.user._id }) .then((user) => { // API Tracking Code ApiTracking.findOne({ user_id: user._id }).then((apitracking) => { // console.log(apitracking.total) ++apitracking.total.tasklists_api_calls ++apitracking.total.tasklists_update_calls const months = ["january","february","march","april","may","june","july","august","september","october","november","december"]; const d = new Date(); let month = months[d.getMonth()]; switch(month) { case "january": ++apitracking.january.tasklists_api_calls ++apitracking.january.tasklists_update_calls break; case "february": ++apitracking.february.tasklists_api_calls ++apitracking.february.tasklists_update_calls break; case "march": ++apitracking.march.tasklists_api_calls ++apitracking.march.tasklists_update_calls break; case "april": ++apitracking.april.tasklists_api_calls ++apitracking.april.tasklists_update_calls break; case "may": ++apitracking.may.tasklists_api_calls ++apitracking.may.tasklists_update_calls break; case "june": ++apitracking.june.tasklists_api_calls ++apitracking.june.tasklists_update_calls break; case "july": ++apitracking.july.tasklists_api_calls ++apitracking.july.tasklists_update_calls break; case "august": ++apitracking.august.tasklists_api_calls ++apitracking.august.tasklists_update_calls break; case "september": ++apitracking.september.tasklists_api_calls ++apitracking.september.tasklists_update_calls break; case "october": ++apitracking.october.tasklists_api_calls ++apitracking.october.tasklists_update_calls break; case "november": ++apitracking.november.tasklists_api_calls ++apitracking.november.tasklists_update_calls break; case "december": ++apitracking.december.tasklists_api_calls ++apitracking.december.tasklists_update_calls break; default: // code block } apitracking.save(); }); }) }) // @route DELETE api/dashboard // @desc DEL/Dashboard // @access Private router.delete('/delete/:id',passport.authenticate('jwt',{session: false}),(req,res)=>{ const id = req.params.id const mesg = {} Dashboard.findOneAndDelete({_id: id}) .then(dashboard=>{ if(!dashboard){ mesg.error = 'List is not found!' return res.status(200).json({mesg}) } else { return Utility(req.user.associatedemail, res) } }) .catch(err=>{ mesg.error = err res.status(400).json({mesg}) }) User.findOne({ _id: req.user._id }) .then((user) => { // API Tracking Code ApiTracking.findOne({ user_id: user._id }).then((apitracking) => { // console.log(apitracking.total) ++apitracking.total.tasklists_api_calls ++apitracking.total.tasklists_delete_calls --apitracking.total.tasklists_current_number const months = ["january","february","march","april","may","june","july","august","september","october","november","december"]; const d = new Date(); let month = months[d.getMonth()]; switch(month) { case "january": ++apitracking.january.tasklists_api_calls ++apitracking.january.tasklists_delete_calls --apitracking.january.tasklists_current_number break; case "february": ++apitracking.february.tasklists_api_calls ++apitracking.february.tasklists_delete_calls --apitracking.february.tasklists_current_number break; case "march": ++apitracking.march.tasklists_api_calls ++apitracking.march.tasklists_delete_calls --apitracking.march.tasklists_current_number break; case "april": ++apitracking.april.tasklists_api_calls ++apitracking.april.tasklists_delete_calls --apitracking.april.tasklists_current_number break; case "may": ++apitracking.may.tasklists_api_calls ++apitracking.may.tasklists_delete_calls --apitracking.may.tasklists_current_number break; case "june": ++apitracking.june.tasklists_api_calls ++apitracking.june.tasklists_delete_calls --apitracking.june.tasklists_current_number break; case "july": ++apitracking.july.tasklists_api_calls ++apitracking.july.tasklists_delete_calls --apitracking.july.tasklists_current_number break; case "august": ++apitracking.august.tasklists_api_calls ++apitracking.august.tasklists_delete_calls --apitracking.august.tasklists_current_number break; case "september": ++apitracking.september.tasklists_api_calls ++apitracking.september.tasklists_delete_calls --apitracking.september.tasklists_current_number break; case "october": ++apitracking.october.tasklists_api_calls ++apitracking.october.tasklists_delete_calls --apitracking.october.tasklists_current_number break; case "november": ++apitracking.november.tasklists_api_calls ++apitracking.november.tasklists_delete_calls --apitracking.november.tasklists_current_number break; case "december": ++apitracking.december.tasklists_api_calls ++apitracking.december.tasklists_delete_calls --apitracking.december.tasklists_current_number break; default: // code block } apitracking.save(); }); }); }); // API Access router.get('/apiaccess/:email/:apikey/:password', passport.authenticate('jwt', {session: false}), (req, res) => { console.log("api run") console.log(req.params) const email = req.params.email; const password = req.params.password; const apikey = req.params.apikey; User.findOne({ email }) .then((user) => { // if user does not exists if (!user) { // return error with status 400 return res.status(400).json({ mesg: "Email or Username does not exist!", type: "danger", }); } User.findOne({ email }).then((user) => { // if user does not exists if (!user) { // return error with status 400 return res.status(400).json({ mesg: "Email or Username does not exist!", type: "danger", }); } else { //Is this needed? // user.save(); bcrypt.compare(password, user.password).then((isMatch) => { // if password matched / create a token if (isMatch) { const payload = { id: user.id, email: user.email, name: user.name, role: user.role, username: user.username, associatedemail: user.associatedemail, pic: user.pic, registration_date: user.registration_date, subscription_date: user.subscription_date, subscription: user.subscription, toptier_subscription: user.toptier_subscription, superuser: user.superuser, phone: user.phone, address: user.address, city: user.city, state: user.state, zip: user.zip, country: user.country, verified: user.verified, disabled_account: user.disabled_account, superuser: user.superuser, recovery_phone: user.recovery_phone, recovery_number: user.recovery_number, revenue_customer: user.revenue_customer, subscription_status: user.subscription_status, chapter: user.chapter, chapter_volunteer: user.chapter_volunteer, api_access: user.api_access, }; jwt.sign( payload, secret.secretOrKey, { expiresIn: 3600 }, (err, token) => { // return res.status(200).json({ // sucess: true, // token: `Bearer ${token}`, // type: "success", // }); } ); let api_keys = user.api_access.map((item)=>item.api_key) console.log(api_keys) if(api_keys.includes(apikey)){ let index = api_keys.indexOf(apikey) let expiry = user.api_access.map((item)=>item.api_expirationdate) let today = new Date() if(moment(today).format("MM-DD-YYYY") > moment(expiry[index]).format("MM-DD-YYYY")){ return res.status(400).json({ // Switching to Invalid Combination since catching and running both API's to check for username and password is causing Password incorrect to be changed to Email does not exist. // mesg: 'Password is incorrect!', mesg: "API Key expired!", type: "danger", }); } Dashboard.find({associatedemail: req.user.email}) .sort({date: 'ascending'}) .then(dashboard =>{ return res.status(200).json({dashboard}) }) } else{ console.log(false) return res.status(400).json({ // Switching to Invalid Combination since catching and running both API's to check for username and password is causing Password incorrect to be changed to Email does not exist. // mesg: 'Password is incorrect!', mesg: "Expired or Invalid API Key!", type: "danger", }); } } else { console.log("incorrect password"); // if not matched, send an error response with 400 status return res.status(400).json({ // Switching to Invalid Combination since catching and running both API's to check for username and password is causing Password incorrect to be changed to Email does not exist. // mesg: 'Password is incorrect!', mesg: "Incorrect Password!", type: "danger", }); } }); } }); }) .catch((err) => { console.log("final catch"); return res.json({ err }); }); }) // @route POST api/lists/create // @desc POSTT/Lists // @access Private router.post( "/create", passport.authenticate("jwt", { session: false }), (req, res) => { const mesg = {}; let accountid = 0 console.log("create task api run"); console.log("req.body"); User.findOne({ email: req.user.associatedemail }) .then((user) => { if (!user) { return res .status(422) .json({ error: "Oops ! Token expired, Try again" }); } // double check what's happening here. accountid? else { accountid = user.tasks_created ++user.tasks_created user.save(); } }) Dashboard.find({associatedemail: req.user.associatedemail}) .sort({date: 'ascending'}) .then(alldashboards =>{ // console.log(req.body) // Dashboard.findById({ _id: req.body._id, user: req.user.id }) Dashboard.findById({ _id: req.body._id}) .then((dashboard) => { console.log("alldashboards") let accountid_arrays_tasklists = alldashboards.map((item)=>item.lists.map((item)=>item.account_id)) const all_tasklist_accountids = accountid_arrays_tasklists.flat(1); console.log(all_tasklist_accountids); let largestnumber = Math.max(...all_tasklist_accountids) let accountidsmissing_array = [] for(var i = 1; i < largestnumber; i++){ if(!all_tasklist_accountids.includes(i)){ accountidsmissing_array.push(i) } } let middleid = accountidsmissing_array[0] if(middleid == undefined){ middleid = largestnumber ++middleid } if(middleid == 0 || middleid == undefined || middleid == null || middleid < 0){ middleid = 1 } console.log("middleid") console.log(middleid) const tasks = dashboard.lists.length; const subscriptiondate = req.user.subscription_date; const date = new Date(); const subscriptionend = Date.parse(subscriptiondate); const today = Date.parse(date); if (!dashboard) { mesg.error = "Dashboard is not found!"; return res.status(400).json({ mesg }); } else { let accountids_array = dashboard.lists.map((item)=>item.account_id) let generated_accountid = 1 if(accountids_array.length == 0){ generated_accountid == 1 } else{ generated_accountid = Math.max(...accountids_array) ++generated_accountid } dashboard.lists.push({ list: req.body.list, email: req.body.email, phone: req.body.phone, tasktype: req.body.tasktype, task_details: req.body.task_details, organization: req.body.organization, table_row_number: req.body.table_row_number, seat_number: req.body.seat_number, checkedin_by: "", checkedin_by_username: "", account_id: middleid }); dashboard.save().then((dashboard) => { Dashboard.find({ associatedemail: req.user.associatedemail }) // .sort({ date: "descending" }) .then((dashboard) => { dashboard[0].lists.sort( (b, a) => (b.list > a.list ? 1 : a.list > b.list ? -1 : 0) //Name Sort // if (currentSortName == "list_a") { // dashboard[0].lists.sort((a, b) => // b.list > a.list ? 1 : a.list > b.list ? -1 : 0 // ); // } else if (currentSortName == "list_b") { // dashboard[0].lists.sort((b, a) => // b.list > a.list ? 1 : a.list > b.list ? -1 : 0 // ); // } // //Email Sort // if (currentSortName == "email_a") { // dashboard[0].lists.sort((a, b) => // b.email > a.email ? 1 : a.email > b.email ? -1 : 0 // ); // } else if (currentSortName == "email_b") { // dashboard[0].lists.sort((b, a) => // b.email > a.email ? 1 : a.email > b.email ? -1 : 0 // ); // } // //Phone Sort // if (currentSortName == "phone_a") { // dashboard[0].lists.sort((a, b) => // b.phone > a.phone ? 1 : a.phone > b.phone ? -1 : 0 // ); // } else if (currentSortName == "phone_b") { // dashboard[0].lists.sort((b, a) => // b.phone > a.phone ? 1 : a.phone > b.phone ? -1 : 0 // ); // } // //Task Type Sort // if (currentSortName == "tasktype_a") { // dashboard[0].lists.sort((a, b) => // b.tasktype > a.tasktype // ? 1 // : a.tasktype > b.tasktype // ? -1 // : 0 // ); // } else if (currentSortName == "tasktype_b") { // dashboard[0].lists.sort((b, a) => // b.tasktype > a.tasktype // ? 1 // : a.tasktype > b.tasktype // ? -1 // : 0 // ); // } // //Status Sort // if (currentSortName == "status_a") { // dashboard[0].lists.sort((a, b) => // b.status > a.status ? 1 : a.status > b.status ? -1 : 0 // ); // } else if (currentSortName == "status_b") { // dashboard[0].lists.sort((b, a) => // b.status > a.status ? 1 : a.status > b.status ? -1 : 0 // ); // } // //Organization Sort // if (currentSortName == "organization_a") { // dashboard[0].lists.sort((a, b) => // b.organization > a.organization // ? 1 // : a.organization > b.organization // ? -1 // : 0 // ); // } else if (currentSortName == "organization_b") { // dashboard[0].lists.sort((b, a) => // b.organization > a.organization // ? 1 // : a.organization > b.organization // ? -1 // : 0 // ); // } // //Table Sort // if (currentSortName == "table_row_number_a") { // dashboard[0].lists.sort((a, b) => // b.table_row_number > a.table_row_number // ? 1 // : a.table_row_number > b.table_row_number // ? -1 // : 0 // ); // } else if (currentSortName == "table_row_number_b") { // dashboard[0].lists.sort((b, a) => // b.table_row_number > a.table_row_number // ? 1 // : a.table_row_number > b.table_row_number // ? -1 // : 0 // ); // } // //Seat Sort // if (currentSortName == "seat_number_a") { // dashboard[0].lists.sort((a, b) => // b.seat_number > a.seat_number // ? 1 // : a.seat_number > b.seat_number // ? -1 // : 0 // ); // } else if (currentSortName == "seat_number_b") { // dashboard[0].lists.sort((b, a) => // b.seat_number > a.seat_number // ? 1 // : a.seat_number > b.seat_number // ? -1 // : 0 // ); // } ); if (dashboard.length === 0) { mesg.message = "You dont have any tasklists!"; return res.status(200).json({ mesg }); } else if (!dashboard) { mesg.message = "Dashboard is not found!"; return res.status(200).json({ mesg }); } return res.status(200).json({ dashboard }); }) .catch((err) => { mesg.error = err; return res.status(200).json({ mesg }); }); }); } }) .catch((err) => { mesg.error = err; return res.status(400).json({ mesg }); }); }) .catch((err) => { mesg.error = err; return res.status(400).json({ mesg }); }); } ); router.post( "/import", passport.authenticate("jwt", { session: false }), (req, res) => { const mesg = {}; Dashboard.find({associatedemail: req.user.associatedemail}) .sort({date: 'ascending'}) .then(alldashboards =>{ Dashboard.findById({ _id: req.body._id}) // Dashboard.findById({ _id: req.body._id, user: req.user.id }) .then((dashboard) => { // task_details: importedData[key].task_details, const tasks = dashboard.lists.length; const subscriptiondate = req.user.subscription_date; const date = new Date(); const subscriptionend = Date.parse(subscriptiondate); const today = Date.parse(date); if (!dashboard) { mesg.error = "Dashboard is not found!"; return res.status(400).json({ mesg }); } else { let accountid_arrays_tasklists_loop = alldashboards.map((item)=>item.lists.map((item)=>item.account_id)) let all_tasklist_accountids_loop = accountid_arrays_tasklists_loop.flat(1); for (var key in importedData) { let versatilearray = all_tasklist_accountids_loop console.log(versatilearray); let largestnumber_loop = Math.max(...versatilearray) let accountidsmissing_array_loop = [] for(let i = 1; i < largestnumber_loop; i++){ if(!versatilearray.includes(i)){ accountidsmissing_array_loop.push(i) } } let middleid_loop = accountidsmissing_array_loop[0] if(middleid_loop == undefined){ middleid_loop = largestnumber_loop ++middleid_loop } let current_generated_number = middleid_loop; if(current_generated_number == 0 || current_generated_number == undefined || current_generated_number == null || current_generated_number < 0){ current_generated_number = 1 } versatilearray.push(current_generated_number); console.log("middleid_loop"); console.log(middleid_loop); console.log("current_generated_number"); console.log(current_generated_number); dashboard.lists.push({ account_id: current_generated_number, list: importedData[key].listItem, email: importedData[key].email, phone: importedData[key].phone, tasktype: importedData[key].tasktype, organization: importedData[key].organization, table_row_number: importedData[key].table_row_number, seat_number: importedData[key].seat_number, checkedin_by: "", checkedin_by_username: "", }); } // dashboard[0].lists.sort((a, b) => // b.list > a.list ? 1 : a.list > b.list ? -1 : 0 // ); dashboard.save().then((newDashboard) => { setTimeout(() => { console.log("Delayed for 10 seconds."); return Utility(req.user.associatedemail, res); }, "5000"); }); } }) .catch((err) => { console.log("import error selected dashboard"); mesg.error = err; return res.status(400).json({ mesg }); }); }) .catch((err) => { console.log("import error all dashboards"); mesg.error = err; return res.status(400).json({ mesg }); }); } ); router.put( "/importupdate", passport.authenticate("jwt", { session: false }), (req, res) => { const mesg = {}; console.log("import api update run"); console.log("req.body._id"); console.log(req.body._id); console.log("req.body.item"); console.log(req.body.item); const importedData = req.body.item; Dashboard.find({associatedemail: req.user.associatedemail}) .sort({date: 'ascending'}) .then(alldashboards =>{ Dashboard.findById({ _id: req.body._id}) // Dashboard.findById({ _id: req.body._id, user: req.user.id }) .then((dashboard) => { console.log(importedData.length); if (!dashboard) { mesg.error = "Dashboard is not found!"; return res.status(400).json({ mesg }); } else { for (var key in importedData) { const listItem = dashboard.lists; console.log("listItem") console.log(listItem) listItem.map((list) => { if (list.account_id.toString() === importedData[key].account_id.toString()) { return ( (list.list = importedData[key].listItem), (list.email = importedData[key].email), (list.phone = importedData[key].phone), (list.tasktype = importedData[key].tasktype), (list.task_details = importedData[key].task_details), (list.organization = importedData[key].organization), (list.table_row_number = importedData[key].table_row_number), (list.seat_number = importedData[key].seat_number) ); } return { listItem, mesg }; }); dashboard.lists = listItem; } // dashboard[0].lists.sort((a, b) => // b.list > a.list ? 1 : a.list > b.list ? -1 : 0 // ); dashboard.save() return res.status(200).json({ dashboard }); // return Utility(req.user.associatedemail, res); } }) .catch((err) => { console.log("import error selected dashboard"); mesg.error = err; return res.status(400).json({ mesg }); }); }) .catch((err) => { console.log("import error all dashboards"); mesg.error = err; return res.status(400).json({ mesg }); }); } ); router.post( "/import-dynamic", passport.authenticate("jwt", { session: false }), (req, res) => { const mesg = {}; console.log("import api2 run"); console.log("req.body._id"); console.log(req.body._id); console.log("req.body.item"); console.log(req.body.item); const importedData = req.body.item; Dashboard.findById({ _id: req.body._id, user: req.user.id }) .then((dashboard) => { const tasks = dashboard.lists.length; const subscriptiondate = req.user.subscription_date; const date = new Date(); const subscriptionend = Date.parse(subscriptiondate); const today = Date.parse(date); if (!dashboard) { mesg.error = "Dashboard is not found!"; return res.status(400).json({ mesg }); } else { for (var key in importedData) { dashboard.lists.push({ list: importedData[key].name, email: importedData[key].email, phone: importedData[key].phone, tasktype: importedData[key].task, task_details: importedData[key].task_details, organization: importedData[key].organization, table_row_number: importedData[key].table_row_number, seat_number: importedData[key].seat_number, checkedin_by: "", checkedin_by_username: "", }); } dashboard.save().then((newDashboard) => { return Utility(req.user.associatedemail, res); }); } }) .catch((err) => { mesg.error = err; return res.status(400).json({ mesg }); }); User.findOne({ _id: req.user._id }).then((user) => { }); } ); // This is to check whether any imported ids not match all current accountids in the database router.get( "/importaccountids", passport.authenticate("jwt", { session: false }), (req, res) => { const mesg = {}; console.log("import api run"); Dashboard.find({ associatedemail: req.user.associatedemail }) .then((dashboard) => { console.log("dashboardaga") console.log(dashboard) console.log("accountid_arrays_tasklists 0"); let accountid_arrays_tasklists0 = dashboard.map((item)=>item.lists) console.log("accountid_arrays_tasklists 0"); console.log(accountid_arrays_tasklists0); let accountid_arrays_tasklists = dashboard.map((item)=>item.lists.map((item)=>item.account_id)) console.log("accountid_arrays_tasklists"); console.log(accountid_arrays_tasklists); const all_tasklist_accountids = accountid_arrays_tasklists.flat(1); console.log(all_tasklist_accountids); // let allids = dashboard.lists.map((item)=> item.account_id); // console.log("allids") // console.log(allids) return res.status(200).json({ all_tasklist_accountids }); }) .catch((err) => { console.log("import error"); mesg.error = err; return res.status(400).json({ mesg }); }); User.findOne({ _id: req.user._id }).then((user) => { }); } ); // @route PUT api/lists/update:id // @desc PUT/Lists // @access Private router.put( "/update/:id", passport.authenticate("jwt", { session: false }), (req, res) => { const text = req.body.text; const email = req.body.email; const phone = req.body.phone; const tasktype = req.body.tasktype; const task_details = req.body.task_details; const organization = req.body.organization; const table_row_number = req.body.table_row_number; const seat_number = req.body.seat_number; const mesg = {}; const currentSortName = req.body.currentSortName; Dashboard.findById({ _id: req.params.id }) .then((dashboard) => { if (!dashboard) { mesg.error = "List is not found!"; return res.status(400).json({ mesg }); } else { const listItem = dashboard.lists; listItem.map((list) => { if (list._id.toString() === req.body.dashId.toString()) { return ( (list.list = text), (list.email = email), (list.phone = phone), (list.tasktype = tasktype), (list.task_details = task_details), (list.organization = organization), (list.table_row_number = table_row_number), (list.seat_number = seat_number) ); } return { listItem, mesg }; }); dashboard.lists = listItem; dashboard.save() .then((dashboardList) => { Dashboard.find({ associatedemail: req.user.associatedemail }) .sort({ date: "descending" }) .then((dashboard) => { if (dashboard.length === 0) { mesg.message = "You dont have any tasklists!"; return res.status(200).json({ mesg }); } else if (!dashboard) { mesg.message = "Dashboard is not found!"; return res.status(200).json({ mesg }); } return res.status(200).json({ dashboard }); }) .catch((err) => { mesg.error = err; return res.status(200).json({ mesg }); }); }); } }) .catch((err) => { mesg.error = err; // res.status(200).json({mesg}) }); } ); // @route PUT api/lists/update:id // @desc PUT/Lists // @access Private router.put( "/updatetaskprofile/:id", passport.authenticate("jwt", { session: false }), (req, res) => { const text = req.body.text; const email = req.body.email; const phone = req.body.phone; const tasktype = req.body.tasktype; const task_details = req.body.task_details; const organization = req.body.organization; const table_row_number = req.body.table_row_number; const seat_number = req.body.seat_number; const status = req.body.status; const mesg = {}; const currentSortName = req.body.currentSortName; Dashboard.findById({ _id: req.params.id }) .then((dashboard) => { if (!dashboard) { mesg.error = "List is not found!"; return res.status(400).json({ mesg }); } else { const listItem = dashboard.lists; listItem.map((list) => { if (list._id.toString() === req.body.dashId.toString()) { return ( (list.list = text), (list.email = email), (list.phone = phone), (list.tasktype = tasktype), (list.task_details = task_details), (list.organization = organization), (list.table_row_number = table_row_number), (list.seat_number = seat_number), (list.status = status) ); } return { listItem, mesg }; }); dashboard.lists = listItem; dashboard.save().then((dashboardList) => { Dashboard.find({ associatedemail: req.user.associatedemail }) .sort({ date: "descending" }) .then((dashboard) => { dashboard[0].lists.sort((a, b) => b.list > a.list ? 1 : a.list > b.list ? -1 : 0 ); if (dashboard.length === 0) { mesg.message = "You dont have any tasklists!"; return res.status(200).json({ mesg }); } else if (!dashboard) { mesg.message = "Dashboard is not found!"; return res.status(200).json({ mesg }); } return res.status(200).json({ dashboard }); }) .catch((err) => { mesg.error = err; return res.status(200).json({ mesg }); }); }); } }) .catch((err) => { mesg.error = err; // res.status(200).json({mesg}) }); User.findOne({ _id: req.user._id }).then((user) => { }); } ); // @route PUT api/lists/updateList:id // @desc PUT/UPDATE specific list status // @access Private router.put( "/updateStatus/:id", passport.authenticate("jwt", { session: false }), (req, res) => { const mesg = {}; const currentSortName = req.body.currentSortName; Dashboard.findById({ _id: req.params.id }) .then((dashboard) => { if (!dashboard) { mesg.error = "List is not found!"; return res.status(400).json({ mesg }); } else { const listItem = dashboard.lists; listItem.map((list) => { if (list._id.toString() === req.body.listId.toString()) { return list.status === "Confirmed" ? ((list.status = "Checked In"), (list.checkedin_by = req.user.name), (list.checkedin_by_username = req.user.username) ) : list.status === "Checked In" ? ((list.status = "Confirmed"), (list.checkedin_by = ""), (list.checkedin_by_username = "") ) : null; } return { listItem, mesg }; }); dashboard.lists = listItem; dashboard.save().then((dashboardList) => { Dashboard.find({ associatedemail: req.user.associatedemail }) // .sort({ date: "descending" }) .then((dashboard) => { dashboard[0].lists.sort( (b, a) => (b.list > a.list ? 1 : a.list > b.list ? -1 : 0) ); if (dashboard.length === 0) { mesg.message = "You dont have any tasklists!"; return res.status(200).json({ mesg }); } else if (!dashboard) { mesg.message = "Dashboard is not found!"; return res.status(200).json({ mesg }); } return res.status(200).json({ dashboard }); }) .catch((err) => { mesg.error = err; return res.status(200).json({ mesg }); }); }); } }) .catch((err) => { mesg.error = err; res.status(400).json({ mesg }); }); User.findOne({ _id: req.user._id }).then((user) => { }); } ); // @route DELETE api/lists/delete:id // @desc DELETE/Lists // @access Private router.delete( "/delete/:id/:listId", passport.authenticate("jwt", { session: false }), (req, res) => { const mesg = {}; // const currentSortName = req.query.sortfield; console.log("req.params.id") console.log(req.params.id) console.log("req.params.listId") console.log(req.params.listId) Dashboard.findById({ _id: req.params.id }) .then((dashboard) => { console.log("dashboard found") console.log(dashboard) if (!dashboard) { mesg.error = "List is not found!"; return res.status(200).json({ mesg }); } else { console.log("dashboard really found") const lists = dashboard.lists.filter( (list) => list._id.toString() !== req.params.listId.toString() ); console.log("dashboard deleted") console.log("lists") dashboard.lists = lists; dashboard.save().then((dashboard) => { Dashboard.find({ associatedemail: req.user.associatedemail }) // .sort({ date: "descending" }) .then((dashboard) => { dashboard[0].lists.sort( (b, a) => (b.list > a.list ? 1 : a.list > b.list ? -1 : 0) ); if (dashboard.length === 0) { mesg.message = "You dont have any tasklists!"; return res.status(200).json({ mesg }); } else if (!dashboard) { mesg.message = "Dashboard is not found!"; return res.status(200).json({ mesg }); } return res.status(200).json({ dashboard }); }) .catch((err) => { mesg.error = err; return res.status(200).json({ mesg }); }); }); } }) .catch((err) => { mesg.error = err; res.status(400).json({ mesg }); }); } ); // @route PUT api/lists/update:id // @desc PUT/Lists // @access Private router.post( "/createtaskrelationship/:id", passport.authenticate("jwt", { session: false }), (req, res) => { const relationship = req.body.relationship; const taskid = req.body.taskid; const selectedtask = req.body.selectedtask; const relation_back = req.body.relation_back; selectedtask const id = req.params.id; const mesg = {}; Dashboard.findById({ _id: req.params.id }) .then((dashboard) => { let existingrelationship = dashboard.lists.filter((list) => list._id == selectedtask.toString())[0].relationships.filter((item)=>item.related__id == taskid) console.log("here3") console.log(existingrelationship) if (!dashboard) { mesg.error = "List is not found!"; return res.status(400).json({ mesg }); } else if (existingrelationship[0] == null) { // return res.status(400).json({ mesg }); const listItem = dashboard.lists; listItem.map((list) => { if (list._id.toString() === selectedtask.toString()) { return ( list.relationships.push({ related__id: taskid, related__type: relationship, }) ); } // return res.status(200).json({ dashboard }); }); // relationship back listItem.map((list) => { if (list._id.toString() === taskid.toString()) { console.log("attemoting relation"); return ( list.relationships.push({ related__id: selectedtask, related__type: relation_back, }) ); } // return res.status(200).json({ dashboard }); }); dashboard.lists = listItem; dashboard.save() return res.status(200).json({ mesg }); } else{ return res.status(400).json({ mesg }); } }) .catch((err) => { mesg.error = err; // res.status(200).json({mesg}) }); User.findOne({ _id: req.user._id }).then((user) => { }); } ); // @route DELETE api/lists/delete:id // @desc DELETE/Lists // @access Private router.delete( "/deletetaskrelationship/:id", passport.authenticate("jwt", { session: false }), (req, res) => { const mesg = {}; const selectedtask = req.query.selectedtask; const taskid = req.query.taskid; Dashboard.findById({ _id: req.params.id }) .then((dashboard) => { if (!dashboard) { console.log("Dashboard not found") mesg.error = "List is not found!"; return res.status(200).json({ mesg }); } else { console.log("Dashboard found") const deletingrelationship = dashboard.lists.filter( (list) => list._id.toString() == taskid.toString() ); const selected_relationship = deletingrelationship[0].relationships.filter((item)=>item.related__id != selectedtask) deletingrelationship[0].relationships = selected_relationship const deletingrelationback = dashboard.lists.filter( (list) => list._id.toString() == selectedtask.toString() ); const selected_relationship2 = deletingrelationback[0].relationships.filter((item)=>item.related__id != taskid) deletingrelationback[0].relationships = selected_relationship2 dashboard .save() .then((dashboardList) => { Dashboard.find({ associatedemail: req.user.associatedemail }) .sort({ date: "descending" }) .then((dashboard) => { //Sorting? dashboard[0].lists.sort((b, a) => b.list > a.list ? 1 : a.list > b.list ? -1 : 0 ); if (dashboard.length === 0) { mesg.message = "You dont have any tasklists!"; return res.status(200).json({ mesg }); } else if (!dashboard) { mesg.message = "Dashboard is not found!"; return res.status(200).json({ mesg }); } return res.status(200).json({ dashboard }); }) .catch((err) => { mesg.error = err; return res.status(200).json({ mesg }); }); }); } }) .catch((err) => { console.log("error") console.log(err) mesg.error = err; res.status(400).json({ mesg }); }); User.findOne({ _id: req.user._id }).then((user) => { }); } ); router.put( "/updatetaskrelationship/:id", passport.authenticate("jwt", { session: false }), (req, res) => { const editRelationship = req.body.editRelationship; console.log("updatetaskrelationshiphit") console.log(editRelationship) const id = req.params.id; const mesg = {}; Dashboard.findById({ _id: req.params.id }) .then((dashboard) => { if (!dashboard) { mesg.error = "List is not found!"; return res.status(400).json({ mesg }); } else { //Attempt3 const deletingrelationship = dashboard.lists.filter( (list) => list._id.toString() == editRelationship.taskedit_id.toString() ); const selected_relationship = deletingrelationship[0].relationships.filter((item)=>item.related__id != editRelationship.selectededit_id) deletingrelationship[0].relationships = selected_relationship const deletingrelationback = dashboard.lists.filter( (list) => list._id.toString() == editRelationship.selectededit_id.toString() ); const selected_relationship2 = deletingrelationback[0].relationships.filter((item)=>item.related__id != editRelationship.taskedit_id) deletingrelationback[0].relationships = selected_relationship2 //Attempt3 - Part2 const listItem = dashboard.lists; listItem.map((list) => { if (list._id.toString() === editRelationship.selectededit_id.toString()) { return ( list.relationships.push({ related__id: editRelationship.taskedit_id, related__type: editRelationship.relationship_type, }) ); } }); // relationship back listItem.map((list) => { if (list._id.toString() === editRelationship.taskedit_id.toString()) { console.log("attemoting relation"); return ( list.relationships.push({ related__id: editRelationship.selectededit_id, related__type: editRelationship.relation_back, }) ); } }); dashboard.lists = listItem; dashboard.save() return res.status(200).json({ dashboard }); }); } ); module.exports = router;