<commit_before>const express = require('express');
const router = express.Router();
const User = require('../models/user');
const Item = require('../models/item');
const Tip = require('../models/tip');
const Forum = require('../models/forum');
const handlebars = require('handlebars');
const helpers = require('handlebars-helpers')({
  handlebars: handlebars
});
const mongoose = require('mongoose');

// GET Homepage
router.get('/', (req, res) => {
  Item
  .find({})
  .limit(10)
  .exec((err, items) => {
    let itemArray = [];
    items.forEach(function(item) {
      itemArray.push(item);
    });
    res.render('index', {
      items: itemArray
    });
  });
});

// GET FORUM - place for discussion
router.get('/forum', ensureAuthenticated, (req, res) => {
  Forum.find({}, (err, forum) => {
    if(err) {
      req.flag('error_msg', 'There was an error.');
      res.redirect('/');
    }
    res.render('forum', {
      forum: forum
    });
  })
  .catch((err) => {
    req.flag('error_msg', 'There was an error.');
    res.redirect('/');
  });
});

// POST FORUM - add suggestions
router.post('/suggestions', ensureAuthenticated, (req, res) => {
  const content = req.body.content;
  const userId = req.user._id;
  const subject = req.body.subject;

  // Validate
  req.checkBody('subject', 'Subject is required').notEmpty();
  req.checkBody('content', 'Content is required').notEmpty();


  const errors = req.validationErrors();
  if(errors) {
    res.render('forum', {
      errors: errors
    });
  } else {
    User.findById({_id: userId}, (err, user) => {

      const newSuggestion = new Forum({
        userId: userId,
        content: content,
        userName: user.name,
        subject: subject
      });

      newSuggestion.save(function(err) {
        if(err) {
          req.flash('error_msg', 'There was an error');
          res.redirect('/forum');
        }
        console.log("Successfully saved new suggestion");
      });

      req.flash('success_msg', 'Successfully saved new suggestion!');
      console.log("Successfully saved new suggestion");
      res.redirect('/forum');
    }).
    catch((err) => {
      req.flash('error_msg', 'There was an error');
      res.redirect('/forum');
    });
  }
});



// GET DASHBOARD - current user's
router.get('/dashboard', ensureAuthenticated, (req, res) => {
  const id = req.user._id;
  // declare variables
  // find info by user
  User.findById({_id: id}, (err, user) => {
    // get user data;
    let tipsId = user.tipIdArray;
    let bookmarks = user.itemIdArray;
    let bookmarkData = [];
    // search for tipsdata
    Tip.find({_id: {$in: tipsId}}, (err, tipsData) => {
      if(err) {
        console.error('There was an error: ' + err);
        res.render('dashboard', {
          user: user
        });
      }
      return tipsData;
    })
    .then((tipsData) => {
      Item.find({_id: {$in: bookmarks}}, (err, items) =>{
        if(err) {
          console.log('Item not found');
          res.render('dashboard', {
            user: user,
            tips: tipsData
          });
        }
        return items
      }).then((items)=> {
        bookmarkData = items;
        req.flash('success_msg', 'dashboard loaded');
        res.render('dashboard', {
          user: user,
          tips: tipsData,
          bookmarks: bookmarkData
        }); // end of render
      });// end of Item.find()
    }); // end of first then()
  }) // end of User.findById
  .catch((err) => {
    console.error('There was an error finding user info');
    res.render('dashboard', user);
  }) // end of catch
});

// POST - Query item
router.post('/search', (req, res) => {
  let query = req.body.item;
  Item
  .find({itemName: query})
  .exec()
  .then(function(itemData) {
    if(itemData[0] === undefined) {
      req.flash('error_msg', 'Item does not exist.');
      res.redirect('/');
    }
    Tip.find({'_id': { $in: itemData[0].tipIdArray}}, function(err, tipsData) {
      if(err) {
        console.log('Item not found');
        res.redirect('/dashboard');
      }
      res.render('item', {
        _id: itemData[0]._id,
        itemName: itemData[0].itemName,
        imgSrc: itemData[0].imgSrc,
        shortDescription: itemData[0].shortDescription,
        tips: tipsData
      }); // end of render
    }); // end of Tip.find()
  })// end of then()
  .catch( (err) => {
    req.flash('error_msg', 'Error searching for item');
    res.redirect('/');
  });
});// end of router.post()

// GET - Individual item page
router.get('/items/:itemid', ensureAuthenticated, (req, res) => {
  const itemId = req.params.itemid;
  Item.findById({_id: itemId}, function(err, item) {
    if(err) {
      req.flag('error_msg', "Item not found.");
      res.redirect('/dashboard');
    };
    let itemTipArray = item.tipIdArray;
    let tipResults;
    Tip.find({_id: {$in: itemTipArray} }, (err, results) => {
      if(err) {
        req.flash('error_msg', 'There was an error');
        res.redirect('/');
      }
      tipResults = results;
      res.render('item', {<commit_msg>fixed search query - now working<commit_after>const express = require('express');
const router = express.Router();
const User = require('../models/user');
const Item = require('../models/item');
const Tip = require('../models/tip');
const Forum = require('../models/forum');
const handlebars = require('handlebars');
const helpers = require('handlebars-helpers')({
  handlebars: handlebars
});
const mongoose = require('mongoose');

// GET Homepage
router.get('/', (req, res) => {
  Item
  .find({})
  .limit(10)
  .exec((err, items) => {
    let itemArray = [];
    items.forEach(function(item) {
      itemArray.push(item);
    });
    res.render('index', {
      items: itemArray
    });
  });
});

// GET FORUM - place for discussion
router.get('/forum', ensureAuthenticated, (req, res) => {
  Forum.find({}, (err, forum) => {
    if(err) {
      req.flag('error_msg', 'There was an error.');
      res.redirect('/');
    }
    res.render('forum', {
      forum: forum
    });
  })
  .catch((err) => {
    req.flag('error_msg', 'There was an error.');
    res.redirect('/');
  });
});

// POST FORUM - add suggestions
router.post('/suggestions', ensureAuthenticated, (req, res) => {
  const content = req.body.content;
  const userId = req.user._id;
  const subject = req.body.subject;

  // Validate
  req.checkBody('subject', 'Subject is required').notEmpty();
  req.checkBody('content', 'Content is required').notEmpty();


  const errors = req.validationErrors();
  if(errors) {
    res.render('forum', {
      errors: errors
    });
  } else {
    User.findById({_id: userId}, (err, user) => {

      const newSuggestion = new Forum({
        userId: userId,
        content: content,
        userName: user.name,
        subject: subject
      });

      newSuggestion.save(function(err) {
        if(err) {
          req.flash('error_msg', 'There was an error');
          res.redirect('/forum');
        }
        console.log("Successfully saved new suggestion");
      });

      req.flash('success_msg', 'Successfully saved new suggestion!');
      console.log("Successfully saved new suggestion");
      res.redirect('/forum');
    }).
    catch((err) => {
      req.flash('error_msg', 'There was an error');
      res.redirect('/forum');
    });
  }
});



// GET DASHBOARD - current user's
router.get('/dashboard', ensureAuthenticated, (req, res) => {
  const id = req.user._id;
  // declare variables
  // find info by user
  User.findById({_id: id}, (err, user) => {
    // get user data;
    let tipsId = user.tipIdArray;
    let bookmarks = user.itemIdArray;
    let bookmarkData = [];
    // search for tipsdata
    Tip.find({_id: {$in: tipsId}}, (err, tipsData) => {
      if(err) {
        console.error('There was an error: ' + err);
        res.render('dashboard', {
          user: user
        });
      }
      return tipsData;
    })
    .then((tipsData) => {
      Item.find({_id: {$in: bookmarks}}, (err, items) =>{
        if(err) {
          console.log('Item not found');
          res.render('dashboard', {
            user: user,
            tips: tipsData
          });
        }
        return items
      }).then((items)=> {
        bookmarkData = items;
        req.flash('success_msg', 'dashboard loaded');
        res.render('dashboard', {
          user: user,
          tips: tipsData,
          bookmarks: bookmarkData
        }); // end of render
      });// end of Item.find()
    }); // end of first then()
  }) // end of User.findById
  .catch((err) => {
    console.error('There was an error finding user info');
    res.render('dashboard', user);
  }) // end of catch
});

// POST - Query item
router.post('/search', (req, res) => {
  let query = req.body.item;
  console.log(query);
  Item
  .find({itemName: query})
  .exec()
  .then(function(itemData) {
    if(itemData[0] === undefined) {
      req.flash('error_msg', 'Item does not exist.');
      res.redirect('/');
    }
    console.log(itemData[0].tipIdArray);
    let itemInfo = itemData[0];
    Tip.find({'_id': {$in: itemData[0].tipIdArray}}, function(err, tipsData) {
      if(err) {
        console.log('Item not found');
        res.redirect('/dashboard');
      }
      res.render('item', {
        item: itemInfo,
        tipData: tipsData
      }); // end of render
    }); // end of Tip.find()
  })// end of then()
  .catch( (err) => {
    req.flash('error_msg', 'Error searching for item');
    res.redirect('/');
  });
});// end of router.post()

// GET - Individual item page
router.get('/items/:itemid', ensureAuthenticated, (req, res) => {
  const itemId = req.params.itemid;
  Item.findById({_id: itemId}, function(err, item) {
    if(err) {
      req.flag('error_msg', "Item not found.");
      res.redirect('/dashboard');
    };
    let itemTipArray = item.tipIdArray;
    let tipResults;
    Tip.find({_id: {$in: itemTipArray} }, (err, results) => {
      if(err) {
        req.flash('error_msg', 'There was an error');
        res.redirect('/');
      }
      tipResults = results;
      res.render('item', {
{'fraction_non_alphanumeric': 0.18142206377500494, 'fraction_numerical': 0.0013864131511190335, 'mean_word_length': 2.476419965576592, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 41, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2173121', 'n_tokens_mistral': 3193, 'n_tokens_neox': 3197, 'n_words': 733}