<commit_before>
// Load the Shift model
var Shift = require('../models/shiftModel');
var Template = require('../models/templateModel');
var moment = require('moment');
var mongoose = require('mongoose');
var ObjectID = require('mongodb').ObjectID;

// Get options from config file
var config = require('../config');

// Check if shifts have been created for the current week
exports.checkShifts = function (req, res, next) {
  var query = getFriday(moment());
  Shift.find(query, function (err1, results1) {
    if (err1) {console.log(err1);}
    // If there are no shifts for this week, create them
    if (!results1.length) {
      Template.findOne({}, null, {sort: {version: -1}}, function (err2, results2) {
        if (err2) {console.log(err2);}
        if (!results2) {console.log("No templates were found. Please create a template first");}
        Template.find({version: results2.version}, function (err3, results3) {
          var i, j, k, l, m;
          for (i = 0; i < results3.length; i++) {
            j = results3[i].nSpots; k = results3[i].nExec;
            Shift.create({date: query.date, index: results3[i].index, time: results3[i].time, nVol: (j-k), nExec: k}, function (err4, results4) {
              if (err4) {console.log(err4);}
            });
          }
          console.log("Creating new shifts for this Friday");
        });
      });
    }
  });
  return next();
};

exports.getShifts = function (req, res, next) {
  // http://mongoosejs.com/docs/populate.html
  var query = getFriday(moment());
  var shifts = Shift.find(query).populate({path: 'Vol', select: '_id firstName lastNameInitial profilePicture'}).populate({path: 'Exec', select: '_id firstName lastNameInitial profilePicture'}).exec(function (err, results) {
    if (err) {console.log(err)}
    res.json(results);
  });
};

exports.volunteer = function (req, res, next) {
  console.log("req.body was", req.body);
  var shiftID = req.body.shiftID;
  // Just quit if the ObjectID isn't valid
  if (!mongoose.Types.ObjectId.isValid(shiftID)) {
    console.log("shiftID was invalid");
    return next;
  }
  // Quit if shifts aren't open
  if (!shouldWrite()) {
    console.log("shouldWrite was false (exiting)");
    return next;
  }
  var rightNow = moment();
  var query = getFriday(rightNow);
  query.Vol = [];
  query.Vol[0] = req.user._id;
  console.log(query);
  // Check if the volunteer already has a shift this week
  Shift.findOne(query, function (err, result) {
    if (err) {console.log(err);}
    console.log("result was", result);
    if (!result) {
      // Check that there actually is a spot available
      Shift.findOne({"_id": ObjectID(shiftID)}, function (err0, result0) {
        var nVolNow = result0.Vol.length;
        if (nVolNow < result0.nVol) {
          var uQuery = getFriday(rightNow); // Ensure shift is for this week
          uQuery["_id"] = ObjectID(shiftID);
          Shift.update(uQuery, {$push:{"Vol":req.user._id}}, function (err1, results1) {
            if (err1) {console.log(err1)};
            console.log(results1);
          });
        } else {
          console.log("No more volunteering spots left");
        }
      });
    }
  });
  return next;
};

function getFriday(now) {
  if (now.day() < 5 && now.day() > 0) {
    query = {"date" : now.day(5).startOf('day').toDate()};
  } else if (now.day() === 5) {
    query = {"date" : now.startOf('day').toDate()};
  } else if (now.day() === 6 || now.day() === 0) {
    query = {"date" : now.day(-2).startOf('day').toDate()};
  } else {
    console.log("Could not interpret day of week in checkShifts. Had now.day() = ", now.day());
    return;
  }
	return query;
};

function shouldWrite() {<commit_msg>Fix redirect after adding shift, fix #5<commit_after>
// Load the Shift model
var Shift = require('../models/shiftModel');
var Template = require('../models/templateModel');
var moment = require('moment');
var mongoose = require('mongoose');
var ObjectID = require('mongodb').ObjectID;

// Get options from config file
var config = require('../config');

// Check if shifts have been created for the current week
exports.checkShifts = function (req, res, next) {
  var query = getFriday(moment());
  Shift.find(query, function (err1, results1) {
    if (err1) {return console.log(err1);}
    // If there are no shifts for this week, create them
    if (!results1.length) {
      Template.findOne({}, null, {sort: {version: -1}}, function (err2, results2) {
        if (err2) {return console.log(err2);}
        if (!results2) {return console.log("No templates were found. Please create a template first");}
        Template.find({version: results2.version}, function (err3, results3) {
          var i, j, k, l, m;
          for (i = 0; i < results3.length; i++) {
            j = results3[i].nSpots; k = results3[i].nExec;
            Shift.create({date: query.date, index: results3[i].index, time: results3[i].time, nVol: (j-k), nExec: k}, function (err4, results4) {
              if (err4) {return console.log(err4);}
            });
          }
          console.log("Creating new shifts for this Friday");
        });
      });
    }
  });
  return next();
};

exports.getShifts = function (req, res, next) {
  // http://mongoosejs.com/docs/populate.html
  var query = getFriday(moment());
  var shifts = Shift.find(query).populate({path: 'Vol', select: '_id firstName lastNameInitial profilePicture'}).populate({path: 'Exec', select: '_id firstName lastNameInitial profilePicture'}).exec(function (err, results) {
    if (err) {return console.log(err)}
    res.json(results);
  });
};

exports.volunteer = function (req, res, next) {
  var shiftID = req.body.shiftID;
  // Just quit if the ObjectID isn't valid
  if (!mongoose.Types.ObjectId.isValid(shiftID)) {
    console.log("shiftID was invalid");
    return next;
  }
  // Quit if shifts aren't open
  if (!shouldWrite()) {
    console.log("shouldWrite was false (exiting)");
    return next;
  }
  var rightNow = moment();
  var query = getFriday(rightNow);
  query.Vol = [];
  query.Vol[0] = req.user._id;
  // Check if the volunteer already has a shift this week
  Shift.findOne(query, function (err, result) {
    if (err) {return console.log(err);}
    if (!result) {
      // Check that there actually is a spot available
      Shift.findOne({"_id": ObjectID(shiftID)}, function (err0, result0) {
        var nVolNow = result0.Vol.length;
        if (nVolNow < result0.nVol) {
          var uQuery = getFriday(rightNow); // Ensure shift is for this week
          uQuery["_id"] = ObjectID(shiftID);
          Shift.update(uQuery, {$push:{"Vol":req.user._id}}, function (err1, results1) {
            if (err1) {return console.log(err1)};
            console.log("Added shift", results1);
          });
        } else {
          console.log("No more volunteering spots left");
        }
      });
    }
  });
  return next();
};

function getFriday(now) {
  if (now.day() < 5 && now.day() > 0) {
    query = {"date" : now.day(5).startOf('day').toDate()};
  } else if (now.day() === 5) {
    query = {"date" : now.startOf('day').toDate()};
  } else if (now.day() === 6 || now.day() === 0) {
    query = {"date" : now.day(-2).startOf('day').toDate()};
  } else {
    console.log("Could not interpret day of week in checkShifts. Had now.day() = ", now.day());
    return;
  }
	return query;
};

function shouldWrite() {
{'fraction_non_alphanumeric': 0.1673895364597452, 'fraction_numerical': 0.011249661154784494, 'mean_word_length': 2.9629430719656282, 'pattern_counts': {'":': 4, '<': 9, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2088879', 'n_tokens_mistral': 2405, 'n_tokens_neox': 2366, 'n_words': 652}