<commit_before>var Patient       = require('../app/models/patient_profile');
var PendingReq    = require('../app/models/pending_req');
var Agent         = require('../app/models/agent_profile');
var Doctor        = require('../app/models/doctor_profile');
var Post          = require('../app/models/post');
var Reply         = require('../app/models/reply');
var DoctorReview  = require('../app/models/doctor_review')
var mongoose      = require('mongoose');
var sentiment     = require('sentiment')

module.exports = function(app, passport) {

// normal routes ===============================================================

    //reply to post
    app.post('/replypost/:id', isLoggedIn, function(req, res) {
        var reply = new Reply();
        reply.user_id      = req.user.id;
        reply.mainThreadID = req.params.id;
        reply.postDate     = new Date();
        reply.content      = req.param('content');
        reply.save();
        console.log(reply);
        Post.findOne({_id: req.params.id}, function (err, post) {
            if (err) {
            }
            ;
            post.reply.push(reply);
            post.save();
        });

        res.redirect('/viewpost/'+ req.params.id);

    });

    //submit new post
    app.post('/newpost', isLoggedIn, function(req, res) {
        var post = new Post();
        post.user_id    = req.user.id;
        post.postTitle  = req.param('title');
        post.postType   = req.param('postType');
        post.postDate   = new Date();
        post.content    = req.param('content');
        post.save();
        res.redirect('/forum');

    });

    //edit new post
    app.get('/newpost', isLoggedIn, function(req, res) {
        res.render('newpost.ejs', {

        });
    });

    //view post
    app.get('/viewpost/:id', function(req, res) {

        Post.findOne({_id: req.params.id}, function (err, post) {
            if (err) {
            }
            ;
            res.render('viewpost.ejs', {
                post: post
            });
        });

    });

    // construct forum
    app.get('/forum', function(req, res) {

        Post.find({},function (err, posts) {
            if (err) {
            }
            ;
            res.render('forum.ejs', {
                posts: posts
            });
        });

    });

    // patient submit request
    app.post('/app_request', isLoggedIn, function(req, res) {
        var request = new PendingReq();
        var final = []
        var average = []

        request.status          = 0;
        request.patient_id      = req.user.id;
        request.modifiedDate    = new Date();
        request.appDate         = new Date(req.param('element_1_3'),req.param('element_1_1'),req.param('element_1_2'));
        request.insurance       = req.param('insurance');
        request.specialty       = req.param('specialty');
        request.city            = req.param('city');
        request.zipcode         = req.param('zipcode');
        request.infor           = req.param('infor');

        request.reason          = req.param('reason');
        request.address         = req.param('address');
        request.department      = req.param('department');
        request.review_name     =[];
        request.review_star     =[];
        request.review_bussiness_id       =[];
        request.review_address  =[];
        DoctorReview.find({'value.city':req.param('city')},function (err,docs){
            if(err){
                console.log("Problemmmmmmmmmmmmmmmm")
            }
            var length = docs.length;

            for ( var i = 0; i < length; i++) {
                final.push ([]);
                var length1 = docs[i].value.texts.length;
                for (var j = 0; j < length1; j++) {
                    sentiment(
                        docs[i].value.texts[j].text
                        , function (err, result) {
                            record= result.score;
                        });
                    final[i].push(record)
                }
                var sum = eval(final[i].join('+')), avg = sum / final[i].length;
                request.review_name.push(docs[i].value.name);
                request.review_star.push(avg);
                request.review_address.push(docs[i].value.full_address);
                request.review_bussiness_id.push(docs[i]._id);
            }
            request.save();

        });

        console.log(request.appDate);

        request.save();

        res.redirect('/app');
    });

    // patient request appointment, doctor respond to request
    app.get('/app', isLoggedIn, function(req, res) {
        if(req.user.local.userType == "patient"){
            res.render('patient_app_request.ejs');
        }else if(req.user.local.userType == "doctor"){
            PendingReq.find({"doctor_id": req.user.id}, function (err, item) {
                res.render('doc_app_request.ejs', {
                    item: item,
                    user: req.user
                });
            });
        }

    });

    // patient view appointment
    app.get('/viewapp', isLoggedIn, function(req, res) {

        if(req.user.local.userType == "patient"){
            PendingReq.find({"patient_id": req.user.id}, function (err, item) {
                res.render('patient_app_view.ejs', {
                    item: item,
                    user: req.user
                });
            });
/*
                DoctorReview.find({"value.categories": req.specialty}, function (err, review) {
                    res.render('patient_app_view.ejs', {
                        review: review
                    });
 });
*/

        }else if(req.user.local.userType == "doctor"){
            PendingReq.find({"doctor_id": req.user.id}, function (err, item) {
                res.render('doc_app_view.ejs', {
                    item: item,
                    user: req.user
                });
            });
        };

    });

	// show the home page (will also have our login links)
	app.get('/', function(req, res) {
		res.render('index.ejs');
	});

	// PROFILE SECTION =========================
	app.get('/modifyprofile', isLoggedIn, function(req, res) {
        if(req.user.local.userType == "doctor"){
            res.render('modify_doc_profile.ejs', {
                user : req.user
            });

        }else{
            res.render('modify_profile.ejs', {
                user : req.user
            });
        }
	});

    //create new profile when sign up or modify profile
    app.post('/profile', isLoggedIn, function(req, res) {
        if(req.user.local.userType == "patient"){
            Patient.findOne(req.user.id, function(err, user) {
                // if there are any errors, return the error
                if (err)
                    return done(err);

                // if no user is found, return the message
                if (!user){
                    //console.log("ininin");
                    var patient = new Patient();
                    patient.user_id = req.user.id;
                    patient.firstName = req.param('firstName');
                    patient.lastName = req.param('lastName');
                    patient.address = req.param('address');
                    patient.phone = req.param('phone');
                    patient.email = req.param('email');
                    patient.save();
                }
                else{
                    Patient.update({user_id:req.user.id},{firstName: req.param('firstName'), lastName:req.param('lastName'),
                    address:req.param('address'), phone:req.param('phone')}).exec();

                };
            });

        };
        if(req.user.local.userType == "agent"){
            Agent.findOne(req.user.id, function(err, user) {
                // if there are any errors, return the error
                if (err)
                    return done(err);

                // if no user is found, return the message
                if (!user){
                    var agent = new Agent();
                    agent.user_id = req.user.id;
                    agent.firstName = req.param('firstName');
                    agent.lastName = req.param('lastName');
                    agent.address = req.param('address');
                    agent.phone = req.param('phone');
                    agent.email = req.param('email');
                    agent.save();
                }
                else{
                    Agent.update({user_id:req.user.id},{firstName: req.param('firstName'), lastName:req.param('lastName'),
                        address:req.param('address'), phone:req.param('phone')}).exec();

                };
            });

        };
        if(req.user.local.userType == "doctor"){
            Doctor.findOne(req.user.id, function(err, user) {
                // if there are any errors, return the error
                if (err)
                    return done(err);

                // if no user is found, return the message
                if (!user){
                    var doctor = new Doctor();
                    doctor.user_id = req.user.id;
                    doctor.firstName = req.param('firstName');
                    doctor.lastName = req.param('lastName');
                    doctor.address = req.param('address');
                    doctor.phone = req.param('phone');
                    doctor.email = req.param('email');
                    doctor.department = req.param('department');
                    doctor.save();
                }
                else{
                    Doctor.update({user_id:req.user.id},{firstName: req.param('firstName'), lastName:req.param('lastName'),
                        address:req.param('address'), phone:req.param('phone'), department : req.param('department'), email: req.param('email')}).exec();

                };
            });

        };
        res.redirect('/profile');
    });

    app.get('/profile', isLoggedIn, function(req, res) {

        if(req.user.local.userType == "doctor"){

            Doctor.findOne(req.user.id, function(err, doc) {
                res.render('view_doc_profile.ejs', {
                    user : req.user,
                    person  : doc
                });
            });

        }else if(req.user.local.userType == "patient"){
            Patient.findOne(req.user.id, function(err, pat) {
                res.render('view_general_profile.ejs', {
                    user    : req.user,
                    person  : pat
                });
            });

        }else{
            Agent.findOne(req.user.id, function(err, agent) {
                res.render('view_general_profile.ejs', {
                    user    : req.user,
                    person  : agent
                });
            });
        }

    });

	// LOGOUT ==============================
	app.get('/logout', function(req, res) {
		req.logout();
		res.redirect('/');

	});

// =============================================================================
// AUTHENTICATE (FIRST LOGIN) ==================================================
// =============================================================================

	// locally --------------------------------
		// LOGIN ===============================
		// show the login form
		app.get('/login', function(req, res) {
			res.render('login.ejs', { message: req.flash('loginMessage') });
		});

		// process the login form
		app.post('/login', passport.authenticate('local-login', {
			successRedirect : '/profile', // redirect to the secure profile section
			failureRedirect : '/login', // redirect back to the signup page if there is an error
			failureFlash : true // allow flash messages
		}));

		// SIGNUP =================================
		// show the signup form
		app.get('/signup', function(req, res) {
			res.render('signup.ejs', { message: req.flash('signupMessage') });
		});

		// process the signup form
		app.post('/signup', passport.authenticate('local-signup', {
			successRedirect : '/modifyprofile', // redirect to the secure profile section
			failureRedirect : '/signup', // redirect back to the signup page if there is an error
			failureFlash : true // allow flash messages
		}));

// =============================================================================
// AUTHORIZE (ALREADY LOGGED IN / CONNECTING OTHER SOCIAL ACCOUNT) =============
// =============================================================================

	// locally --------------------------------
		app.get('/connect/local', function(req, res) {
			res.render('connect-local.ejs', { message: req.flash('loginMessage') });
		});
		app.post('/connect/local', passport.authenticate('local-signup', {
			successRedirect : '/profile', // redirect to the secure profile section
			failureRedirect : '/connect/local', // redirect back to the signup page if there is an error
			failureFlash : true // allow flash messages
		}));

};

// route middleware to ensure user is logged in
function isLoggedIn(req, res, next) {
	if (req.isAuthenticated())
		return next();

	res.redirect('/');
}
<commit_msg>profile bug fix<commit_after>var Patient       = require('../app/models/patient_profile');
var PendingReq    = require('../app/models/pending_req');
var Agent         = require('../app/models/agent_profile');
var Doctor        = require('../app/models/doctor_profile');
var Post          = require('../app/models/post');
var Reply         = require('../app/models/reply');
var DoctorReview  = require('../app/models/doctor_review')
var mongoose      = require('mongoose');
var sentiment     = require('sentiment')

module.exports = function(app, passport) {

// normal routes ===============================================================

    //reply to post
    app.post('/replypost/:id', isLoggedIn, function(req, res) {
        var reply = new Reply();
        reply.user_id      = req.user.id;
        reply.mainThreadID = req.params.id;
        reply.postDate     = new Date();
        reply.content      = req.param('content');
        reply.save();
        console.log(reply);
        Post.findOne({_id: req.params.id}, function (err, post) {
            if (err) {
            }
            ;
            post.reply.push(reply);
            post.save();
        });

        res.redirect('/viewpost/'+ req.params.id);

    });

    //submit new post
    app.post('/newpost', isLoggedIn, function(req, res) {
        var post = new Post();
        post.user_id    = req.user.id;
        post.postTitle  = req.param('title');
        post.postType   = req.param('postType');
        post.postDate   = new Date();
        post.content    = req.param('content');
        post.save();
        res.redirect('/forum');

    });

    //edit new post
    app.get('/newpost', isLoggedIn, function(req, res) {
        res.render('newpost.ejs', {

        });
    });

    //view post
    app.get('/viewpost/:id', function(req, res) {

        Post.findOne({_id: req.params.id}, function (err, post) {
            if (err) {
            }
            ;
            res.render('viewpost.ejs', {
                post: post
            });
        });

    });

    // construct forum
    app.get('/forum', function(req, res) {

        Post.find({},function (err, posts) {
            if (err) {
            }
            ;
            res.render('forum.ejs', {
                posts: posts
            });
        });

    });

    // patient submit request
    app.post('/app_request', isLoggedIn, function(req, res) {
        var request = new PendingReq();
        var final = []
        var average = []

        request.status          = 0;
        request.patient_id      = req.user.id;
        request.modifiedDate    = new Date();
        request.appDate         = new Date(req.param('element_1_3'),req.param('element_1_1'),req.param('element_1_2'));
        request.insurance       = req.param('insurance');
        request.specialty       = req.param('specialty');
        request.city            = req.param('city');
        request.zipcode         = req.param('zipcode');
        request.infor           = req.param('infor');

        request.reason          = req.param('reason');
        request.address         = req.param('address');
        request.department      = req.param('department');
        request.review_name     =[];
        request.review_star     =[];
        request.review_bussiness_id       =[];
        request.review_address  =[];
        DoctorReview.find({'value.city':req.param('city')},function (err,docs){
            if(err){
                console.log("Problemmmmmmmmmmmmmmmm")
            }
            var length = docs.length;

            for ( var i = 0; i < length; i++) {
                final.push ([]);
                var length1 = docs[i].value.texts.length;
                for (var j = 0; j < length1; j++) {
                    sentiment(
                        docs[i].value.texts[j].text
                        , function (err, result) {
                            record= result.score;
                        });
                    final[i].push(record)
                }
                var sum = eval(final[i].join('+')), avg = sum / final[i].length;
                request.review_name.push(docs[i].value.name);
                request.review_star.push(avg);
                request.review_address.push(docs[i].value.full_address);
                request.review_bussiness_id.push(docs[i]._id);
            }
            request.save();

        });

        console.log(request.appDate);

        request.save();

        res.redirect('/app');
    });

    // patient request appointment, doctor respond to request
    app.get('/app', isLoggedIn, function(req, res) {
        if(req.user.local.userType == "patient"){
            res.render('patient_app_request.ejs');
        }else if(req.user.local.userType == "doctor"){
            PendingReq.find({"doctor_id": req.user.id}, function (err, item) {
                res.render('doc_app_request.ejs', {
                    item: item,
                    user: req.user
                });
            });
        }

    });

    // patient view appointment
    app.get('/viewapp', isLoggedIn, function(req, res) {

        if(req.user.local.userType == "patient"){
            PendingReq.find({"patient_id": req.user.id}, function (err, item) {
                res.render('patient_app_view.ejs', {
                    item: item,
                    user: req.user
                });
            });
/*
                DoctorReview.find({"value.categories": req.specialty}, function (err, review) {
                    res.render('patient_app_view.ejs', {
                        review: review
                    });
 });
*/

        }else if(req.user.local.userType == "doctor"){
            PendingReq.find({"doctor_id": req.user.id}, function (err, item) {
                res.render('doc_app_view.ejs', {
                    item: item,
                    user: req.user
                });
            });
        };

    });

	// show the home page (will also have our login links)
	app.get('/', function(req, res) {
		res.render('index.ejs');
	});

	// PROFILE SECTION =========================
	app.get('/modifyprofile', isLoggedIn, function(req, res) {
        if(req.user.local.userType == "doctor"){
            res.render('modify_doc_profile.ejs', {
                user : req.user
            });

        }else{
            res.render('modify_profile.ejs', {
                user : req.user
            });
        }
	});

    //create new profile when sign up or modify profile
    app.post('/profile', isLoggedIn, function(req, res) {
        if(req.user.local.userType == "patient"){
            Patient.findOne({user_id: req.user.id}, function(err, user) {
                // if there are any errors, return the error
                if (err)
                    return done(err);

                // if no user is found, return the message
                if (!user){
                    console.log("1111111");
                    var patient = new Patient();
                    patient.user_id = req.user.id;
                    patient.firstName = req.param('firstName');
                    patient.lastName = req.param('lastName');
                    patient.address = req.param('address');
                    patient.phone = req.param('phone');
                    patient.email = req.param('email');
                    patient.save();
                }
                else{
                    console.log("22222");
                    Patient.update({user_id:req.user.id},{firstName: req.param('firstName'), lastName:req.param('lastName'),
                    address:req.param('address'), phone:req.param('phone')}).exec();

                };
            });

        };
        if(req.user.local.userType == "agent"){
            Agent.findOne(req.user.id, function(err, user) {
                // if there are any errors, return the error
                if (err)
                    return done(err);

                // if no user is found, return the message
                if (!user){
                    var agent = new Agent();
                    agent.user_id = req.user.id;
                    agent.firstName = req.param('firstName');
                    agent.lastName = req.param('lastName');
                    agent.address = req.param('address');
                    agent.phone = req.param('phone');
                    agent.email = req.param('email');
                    agent.save();
                }
                else{
                    Agent.update({user_id:req.user.id},{firstName: req.param('firstName'), lastName:req.param('lastName'),
                        address:req.param('address'), phone:req.param('phone')}).exec();

                };
            });

        };
        if(req.user.local.userType == "doctor"){
            Doctor.findOne(req.user.id, function(err, user) {
                // if there are any errors, return the error
                if (err)
                    return done(err);

                // if no user is found, return the message
                if (!user){
                    var doctor = new Doctor();
                    doctor.user_id = req.user.id;
                    doctor.firstName = req.param('firstName');
                    doctor.lastName = req.param('lastName');
                    doctor.address = req.param('address');
                    doctor.phone = req.param('phone');
                    doctor.email = req.param('email');
                    doctor.department = req.param('department');
                    doctor.save();
                }
                else{
                    Doctor.update({user_id:req.user.id},{firstName: req.param('firstName'), lastName:req.param('lastName'),
                        address:req.param('address'), phone:req.param('phone'), department : req.param('department'), email: req.param('email')}).exec();

                };
            });

        };
        res.redirect('/profile');
    });

    app.get('/profile', isLoggedIn, function(req, res) {

        if(req.user.local.userType == "doctor"){

            Doctor.findOne({user_id: req.user.id}, function(err, doc) {
                res.render('view_doc_profile.ejs', {
                    user : req.user,
                    person  : doc
                });
            });

        }else if(req.user.local.userType == "patient"){
            Patient.findOne({user_id: req.user.id}, function(err, pat) {
                res.render('view_general_profile.ejs', {
                    user    : req.user,
                    person  : pat
                });
            });

        }else{
            Agent.findOne({user_id: req.user.id}, function(err, agent) {
                res.render('view_general_profile.ejs', {
                    user    : req.user,
                    person  : agent
                });
            });
        }

    });

	// LOGOUT ==============================
	app.get('/logout', function(req, res) {
		req.logout();
		res.redirect('/');

	});

// =============================================================================
// AUTHENTICATE (FIRST LOGIN) ==================================================
// =============================================================================

	// locally --------------------------------
		// LOGIN ===============================
		// show the login form
		app.get('/login', function(req, res) {
			res.render('login.ejs', { message: req.flash('loginMessage') });
		});

		// process the login form
		app.post('/login', passport.authenticate('local-login', {
			successRedirect : '/profile', // redirect to the secure profile section
			failureRedirect : '/login', // redirect back to the signup page if there is an error
			failureFlash : true // allow flash messages
		}));

		// SIGNUP =================================
		// show the signup form
		app.get('/signup', function(req, res) {
			res.render('signup.ejs', { message: req.flash('signupMessage') });
		});

		// process the signup form
		app.post('/signup', passport.authenticate('local-signup', {
			successRedirect : '/modifyprofile', // redirect to the secure profile section
			failureRedirect : '/signup', // redirect back to the signup page if there is an error
			failureFlash : true // allow flash messages
		}));

// =============================================================================
// AUTHORIZE (ALREADY LOGGED IN / CONNECTING OTHER SOCIAL ACCOUNT) =============
// =============================================================================

	// locally --------------------------------
		app.get('/connect/local', function(req, res) {
			res.render('connect-local.ejs', { message: req.flash('loginMessage') });
		});
		app.post('/connect/local', passport.authenticate('local-signup', {
			successRedirect : '/profile', // redirect to the secure profile section
			failureRedirect : '/connect/local', // redirect back to the signup page if there is an error
			failureFlash : true // allow flash messages
		}));

};

// route middleware to ensure user is logged in
function isLoggedIn(req, res, next) {
	if (req.isAuthenticated())
		return next();

	res.redirect('/');
}
<|endoftext|>


<commit_before>/*
 MIT License http://www.opensource.org/licenses/mit-license.php
 Author Daniel Tschinder @danez
 */
var nextIdent = 0;

function PathChunkPlugin(options) {
  this.chunkName = options.name;
  this.filenameTemplate = options.filename;
  this.ignore = options.ignore || [];
  this.ident = __filename + (nextIdent++);

  if (!this.chunkName) {
    throw new Error('Supplying a name is mandatory for path-chunk-webpack-plugin');
  }

  if (!Array.isArray(this.ignore)) {
    this.ignore = [this.ignore];
  }

  if (typeof options.test === 'function') {
    this.test = options.test;
  } else if (typeof options.test === 'string') {
    this.test = function (userRequest) { return userRequest.indexOf(options.test) >= 0; };
  } else if (options.test instanceof RegExp) {
    this.test = options.test.test;
  } else {
    throw new Error('Invalid test supplied to path-chunk-webpack-plugin');
  }
}

module.exports = PathChunkPlugin;
PathChunkPlugin.prototype.apply = function (compiler) {
  var filenameTemplate = this.filenameTemplate;
  var chunkName = this.chunkName;
  var ident = this.ident;
  var ignore = this.ignore;
  var isModuleMatching = this.test;

  compiler.plugin('compilation', function (compilation) {
    compilation.plugin('optimize-chunks', function (chunks) {
      // only optimize once
      if (compilation[ident]) return;
      compilation[ident] = true;

      var pathChunk = chunks.find(function (chunk) {
        return chunk.name === chunkName;
      });

      if (!pathChunk) {
        pathChunk = this.addChunk(chunkName);
        pathChunk.initial = pathChunk.entry = true;
      }

      var usedChunks = chunks.filter(function (chunk) {
        return chunk !== pathChunk;
      });

      var commonModules = [];
      var addCommonModule = function (module) {
        if (!module.userRequest) return;

        for (var i in ignore) {
          if (module.userRequest.indexOf(ignore[i]) >= 0) return;
        }
        if (commonModules.indexOf(module) < 0 && isModuleMatching(module.userRequest)) {
          commonModules.push(module);
        }
      };

      usedChunks.forEach(function (chunk) {
        chunk.modules.forEach(addCommonModule);
        chunk.parents = [pathChunk];
        pathChunk.chunks.push(chunk);
        if (chunk.entry) {
          chunk.entry = false;
        }
      });

      commonModules.forEach(function (module) {
        usedChunks.forEach(module.removeChunk);
        pathChunk.addModule(module);
        module.addChunk(pathChunk);
      });

      if (filenameTemplate) {
        pathChunk.filenameTemplate = filenameTemplate;
      }

      this.restartApplyPlugins();
    });
  });
};
<commit_msg>fix(plugin): Bind removeChunk to correct scope<commit_after>/*
 MIT License http://www.opensource.org/licenses/mit-license.php
 Author Daniel Tschinder @danez
 */
var nextIdent = 0;

function PathChunkPlugin(options) {
  this.chunkName = options.name;
  this.filenameTemplate = options.filename;
  this.ignore = options.ignore || [];
  this.ident = __filename + (nextIdent++);

  if (!this.chunkName) {
    throw new Error('Supplying a name is mandatory for path-chunk-webpack-plugin');
  }

  if (!Array.isArray(this.ignore)) {
    this.ignore = [this.ignore];
  }

  if (typeof options.test === 'function') {
    this.test = options.test;
  } else if (typeof options.test === 'string') {
    this.test = function (userRequest) { return userRequest.indexOf(options.test) >= 0; };
  } else if (options.test instanceof RegExp) {
    this.test = options.test.test;
  } else {
    throw new Error('Invalid test supplied to path-chunk-webpack-plugin');
  }
}

module.exports = PathChunkPlugin;
PathChunkPlugin.prototype.apply = function (compiler) {
  var filenameTemplate = this.filenameTemplate;
  var chunkName = this.chunkName;
  var ident = this.ident;
  var ignore = this.ignore;
  var isModuleMatching = this.test;

  compiler.plugin('compilation', function (compilation) {
    compilation.plugin('optimize-chunks', function (chunks) {
      // only optimize once
      if (compilation[ident]) return;
      compilation[ident] = true;

      var pathChunk = chunks.find(function (chunk) {
        return chunk.name === chunkName;
      });

      if (!pathChunk) {
        pathChunk = this.addChunk(chunkName);
        pathChunk.initial = pathChunk.entry = true;
      }

      var usedChunks = chunks.filter(function (chunk) {
        return chunk !== pathChunk;
      });

      var commonModules = [];
      var addCommonModule = function (module) {
        if (!module.userRequest) return;

        for (var i in ignore) {
          if (module.userRequest.indexOf(ignore[i]) >= 0) return;
        }
        if (commonModules.indexOf(module) < 0 && isModuleMatching(module.userRequest)) {
          commonModules.push(module);
        }
      };

      usedChunks.forEach(function (chunk) {
        chunk.modules.forEach(addCommonModule);
        chunk.parents = [pathChunk];
        pathChunk.chunks.push(chunk);
        if (chunk.entry) {
          chunk.entry = false;
        }
      });

      commonModules.forEach(function (module) {
        usedChunks.forEach(module.removeChunk.bind(module));
        pathChunk.addModule(module);
        module.addChunk(pathChunk);
      });

      if (filenameTemplate) {
        pathChunk.filenameTemplate = filenameTemplate;
      }

      this.restartApplyPlugins();
    });
  });
};
<|endoftext|>


<commit_before>// stamper-test.js
//
// Test the stamper module
//
// Copyright 2012, StatusNet Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

var assert = require('assert'),
    vows = require('vows');

vows.describe('stamper module interface').addBatch({
    'When we require the stamper module': {
        topic: function() {
            return require('../lib/stamper');
        },
        'it works': function(stamper) {
            assert.isObject(stamper);
        },
        'and we get its Stamper export': {
            topic: function(stamper) {
                return stamper.Stamper;
            },
            'it exists': function(Stamper) {
                assert.isObject(Stamper);
            },
            'it has a stamp() method': function(Stamper) {
                assert.isFunction(Stamper.stamp);
            },
            'it has an unstamp() method': function(Stamper) {
                assert.isFunction(Stamper.unstamp);
            },
            'and we make a timestamp with no argument': {
                topic: function(Stamper) {
                    return Stamper.stamp();
                },
                'it works': function(ts) {
                    assert.isString(ts);
                },
                'it looks correct': function(ts) {
                    assert.match(ts, /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z/);
                }
            },
            'and we make a timestamp with a date argument': {
                topic: function(Stamper) {
                    var d = new Date(2000, 1, 1, 12, 34, 56);
                    return Stamper.stamp(d);
                },
                'it works': function(ts) {
                    assert.isString(ts);
                },
                'it looks correct': function(ts) {
                    assert.match(ts, /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z/);
                },
                'it contains our date': function(ts) {
                    assert.equal(ts, '2000-01-01T12:34:56Z');
                }
            },
            'and we unstamp a timestamp': {
                topic: function(Stamper) {
                    var ts = '1968-10-14T13:32:12Z';
                    return Stamper.unstamp(ts);
                },
                'it works': function(dt) {
                    assert.isObject(dt);
                    assert.instanceOf(dt, Date);
                },
                'its properties are correct': function(dt) {
                    assert.equal(dt.getUTCFullYear(), 1968);
                    assert.equal(dt.getUTCMonth(), 10);
                    assert.equal(dt.getUTCDate(), 14);
                    assert.equal(dt.getUTCHours(), 13);
                    assert.equal(dt.getUTCMinutes(), 32);
                    assert.equal(dt.getUTCSeconds(), 12);
                }
            }
        }
    }
})['export'](module);
<commit_msg>UTC() for Date<commit_after>// stamper-test.js
//
// Test the stamper module
//
// Copyright 2012, StatusNet Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

var assert = require('assert'),
    vows = require('vows');

vows.describe('stamper module interface').addBatch({
    'When we require the stamper module': {
        topic: function() {
            return require('../lib/stamper');
        },
        'it works': function(stamper) {
            assert.isObject(stamper);
        },
        'and we get its Stamper export': {
            topic: function(stamper) {
                return stamper.Stamper;
            },
            'it exists': function(Stamper) {
                assert.isObject(Stamper);
            },
            'it has a stamp() method': function(Stamper) {
                assert.isFunction(Stamper.stamp);
            },
            'it has an unstamp() method': function(Stamper) {
                assert.isFunction(Stamper.unstamp);
            },
            'and we make a timestamp with no argument': {
                topic: function(Stamper) {
                    return Stamper.stamp();
                },
                'it works': function(ts) {
                    assert.isString(ts);
                },
                'it looks correct': function(ts) {
                    assert.match(ts, /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/);
                }
            },
            'and we make a timestamp with a date argument': {
                topic: function(Stamper) {
                    var d = Date.UTC(2000, 1, 1, 12, 34, 56);
                    return Stamper.stamp(d);
                },
                'it works': function(ts) {
                    assert.isString(ts);
                },
                'it looks correct': function(ts) {
                    assert.match(ts, /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/);
                },
                'it contains our date': function(ts) {
                    assert.equal(ts, '2000-01-01T12:34:56');
                }
            },
            'and we unstamp a timestamp': {
                topic: function(Stamper) {
                    var ts = '1968-10-14T13:32:12Z';
                    return Stamper.unstamp(ts);
                },
                'it works': function(dt) {
                    assert.isObject(dt);
                    assert.instanceOf(dt, Date);
                },
                'its properties are correct': function(dt) {
                    assert.equal(dt.getUTCFullYear(), 1968);
                    assert.equal(dt.getUTCMonth(), 10);
                    assert.equal(dt.getUTCDate(), 14);
                    assert.equal(dt.getUTCHours(), 13);
                    assert.equal(dt.getUTCMinutes(), 32);
                    assert.equal(dt.getUTCSeconds(), 12);
                }
            }
        }
    }
})['export'](module);
<|endoftext|>


<commit_before>// #/logging
sammy.get
(
    /^#\/(logging)$/,
    function( context )
    {
        var content_element = $( '#content' );

        content_element
            .html( '

' );

        $.ajax
        (
            {
                url : 'logging.json',
                dataType : 'json',
                context : $( '#logging', content_element ),
                beforeSend : function( xhr, settings )
                {
                    this
                        .html( '
Loading ...
' );
                },
                success : function( response, text_status, xhr )
                {
                    var logger = response.logger;

                    var loglevel = '
' + "\n";
                    loglevel += '%effective_level%' + "\n";
                    loglevel += '
' + "\n";

                    for( var key in response.levels )
                    {
                        var level = response.levels[key].esc();
                        loglevel += '
' + level + '
' + "\n";
                    }

                    loglevel += '
UNSET
' + "\n";
                    loglevel += '
' + "\n";
                    loglevel += '
';

                    var logger_tree = function( filter )
                    {
                        var logger_content = '';
                        var filter_regex = new RegExp( '^' + filter + '\\.\\w+$' );

                        for( var logger_name in logger )
                        {
                            var continue_matcher = false;

                            if( !filter )
                            {
                                continue_matcher = logger_name.indexOf( '.' ) !== -1;
                            }
                            else
                            {
                                continue_matcher = !logger_name.match( filter_regex );
                            }

                            if( continue_matcher )
                            {
                                continue;
                            }

                            var has_logger_instance = !!logger[logger_name];

                            var classes = [];

                            has_logger_instance
                                ? classes.push( 'active' )
                                : classes.push( 'inactive' );

                            logger_content += '
';
                            logger_content += ' ';
                            logger_content += '' + "\n" +
                                                logger_name.split( '.' ).pop().esc() + "\n" +
                                              '';

                            logger_content += loglevel
                                                .replace
                                                (
                                                    /%class%/g,
                                                    classes.join( ' ' )
                                                )
                                                .replace
                                                (
                                                    /%effective_level%/g,
                                                    has_logger_instance
                                                        ? logger[logger_name].effective_level
                                                        : 'null'
                                                );

                            var child_logger_content = logger_tree( logger_name );
                            if( child_logger_content )
                            {
                                logger_content += '
';
                                logger_content += child_logger_content;
                                logger_content += '
';
                            }

                            logger_content += '
';
                        }

                        return logger_content;
                    }

                    var logger_content = logger_tree( null );

                    this
                        .html( '
' + logger_content + '
' );

                    $( 'li:last-child', this )
                        .addClass( 'jstree-last' );

                    $( '.loglevel', this )
                        .each
                        (
                            function( index, element )
                            {
                                var element = $( element );
                                var effective_level = $( '.effective_level span', element ).text();

                                element
                                    .css( 'z-index', 800 - index );

                                $( 'ul .' + effective_level, element )
                                    .addClass( 'selected' );
                            }
                        );

                    $( '.trigger', this )
                        .die( 'click' )
                        .live
                        (
                            'click',
                            function( event )
                            {
                                $( '.loglevel', $( this ).parents( 'li' ).first() ).first()
                                    .trigger( 'toggle' );
                            }
                        );

                    $( '.loglevel', this )
                        .die( 'toggle')
                        .live
                        (
                            'toggle',
                            function( event )
                            {
                                $( this )
                                    .toggleClass( 'open' );
                            }
                        );
                },
                error : function( xhr, text_status, error_thrown)
                {
                },
                complete : function( xhr, text_status )
                {
                }
            }
        );
    }
);<commit_msg>SOLR-3208: adding a note that the logging is just a stub...<commit_after>// #/logging
sammy.get
(
    /^#\/(logging)$/,
    function( context )
    {
        var content_element = $( '#content' );

        content_element
            .html( '

' );

        $.ajax
        (
            {
                url : 'logging.json',
                dataType : 'json',
                context : $( '#logging', content_element ),
                beforeSend : function( xhr, settings )
                {
                    this
                        .html( '
Loading ...
' );
                },
                success : function( response, text_status, xhr )
                {
                    var logger = response.logger;

                    var loglevel = '
' + "\n";
                    loglevel += '%effective_level%' + "\n";
                    loglevel += '
' + "\n";

                    for( var key in response.levels )
                    {
                        var level = response.levels[key].esc();
                        loglevel += '
' + level + '
' + "\n";
                    }

                    loglevel += '
UNSET
' + "\n";
                    loglevel += '
' + "\n";
                    loglevel += '
';

                    var logger_tree = function( filter )
                    {
                        var logger_content = '';
                        var filter_regex = new RegExp( '^' + filter + '\\.\\w+$' );

                        for( var logger_name in logger )
                        {
                            var continue_matcher = false;

                            if( !filter )
                            {
                                continue_matcher = logger_name.indexOf( '.' ) !== -1;
                            }
                            else
                            {
                                continue_matcher = !logger_name.match( filter_regex );
                            }

                            if( continue_matcher )
                            {
                                continue;
                            }

                            var has_logger_instance = !!logger[logger_name];

                            var classes = [];

                            has_logger_instance
                                ? classes.push( 'active' )
                                : classes.push( 'inactive' );

                            logger_content += '
';
                            logger_content += ' ';
                            logger_content += '' + "\n" +
                                                logger_name.split( '.' ).pop().esc() + "\n" +
                                              '';

                            logger_content += loglevel
                                                .replace
                                                (
                                                    /%class%/g,
                                                    classes.join( ' ' )
                                                )
                                                .replace
                                                (
                                                    /%effective_level%/g,
                                                    has_logger_instance
                                                        ? logger[logger_name].effective_level
                                                        : 'null'
                                                );

                            var child_logger_content = logger_tree( logger_name );
                            if( child_logger_content )
                            {
                                logger_content += '
';
                                logger_content += child_logger_content;
                                logger_content += '
';
                            }

                            logger_content += '
';
                        }

                        return logger_content;
                    }

                    var logger_content = logger_tree( null );

                    var warn = '
TODO, this is not yet implemented.  For now, use the old logging UI

'

                    this.html( warn + '
' + logger_content + '
' );

                    $( 'li:last-child', this )
                        .addClass( 'jstree-last' );

                    $( '.loglevel', this )
                        .each
                        (
                            function( index, element )
                            {
                                var element = $( element );
                                var effective_level = $( '.effective_level span', element ).text();

                                element
                                    .css( 'z-index', 800 - index );

                                $( 'ul .' + effective_level, element )
                                    .addClass( 'selected' );
                            }
                        );

                    $( '.trigger', this )
                        .die( 'click' )
                        .live
                        (
                            'click',
                            function( event )
                            {
                                $( '.loglevel', $( this ).parents( 'li' ).first() ).first()
                                    .trigger( 'toggle' );
                            }
                        );

                    $( '.loglevel', this )
                        .die( 'toggle')
                        .live
                        (
                            'toggle',
                            function( event )
                            {
                                $( this )
                                    .toggleClass( 'open' );
                            }
                        );
                },
                error : function( xhr, text_status, error_thrown)
                {
                },
                complete : function( xhr, text_status )
                {
                }
            }
        );
    }
);<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var session = require('./session');

router.use(function (req, res, next) {

  // Store common vars
  res.locals.data = {};

  // expose session data to templates
  res.locals.data = req.session.data;
  res.locals.query = req.query

  //console.log('query', req.query);
  //console.log('headers', req.headers);

  if (req.session.data && req.session.data.userName) {
    next();
  } else {
    if (req.originalUrl.match(/^\/login$/) ||
        req.originalUrl.match(/^\/send-login$/) ||
        req.originalUrl.match(/^\/$/) ||
        req.originalUrl.match(/^\/create_account/)) {
      next();
    } else {
      res.redirect('/login');
    }
  }
});

router.get('/', function (req, res) {
  req.session.regenerate(function(err) {
    req.session.query = req.query;
    res.render('index');
  });
});

// Branching

// Question for questions/eligibility/index.html
router.get('/create_account/enter_details', function (req, res) {

  // get the answer from the query string (eg. ?existing_account="yes")
  var existing_account = req.query.existing_account;

  if (existing_account == "yes" ){

    // if users is DOES have account
//    res.redirect("/create_account/search_for_existing_account" + res.locals.formQuery);

  } else {

    // if users is does NOT have account
    res.render('create_account/enter_details.html');

  }

});

router.get(
  '/manage_data/upload_new_dataset',
  function (req, res) {
    req.session.data.newSet = {};
    res.redirect('upload_new_dataset/title_summary');
  }
);

router.post('/manage_data/upload_new_dataset/file_upload', function (req, res) {
  req.session.data.newSet = collectFormData(req, req.session.data.newSet);
  res.render('manage_data/upload_new_dataset/file_upload.html');
});

router.post('/manage_data/upload_new_dataset/themes_auto', function (req, res) {
  req.session.data.newSet = collectFormData(req, req.session.data.newSet);
  req.session.data.newSet.themes = ['Business and economy', 'Environment'];
  res.render('manage_data/upload_new_dataset/themes_auto.html');
});

router.post('/manage_data/upload_new_dataset/themes_confirm',
  function (req, res) {
    req.session.data.newSet = collectFormData(req, req.session.data.newSet);
    res.render('manage_data/upload_new_dataset/themes_confirm.html');
  }
);

router.post('/manage_data/upload_new_dataset/geo', function (req, res) {
  req.session.data.newSet = collectFormData(req, req.session.data.newSet);
  res.render('manage_data/upload_new_dataset/geo.html');
});

router.post(
  '/manage_data/upload_new_dataset/update_frequency',
  function (req, res) {
    req.session.data.newSet = collectFormData(req, req.session.data.newSet);
    res.render('manage_data/upload_new_dataset/update_frequency.html');
  }
);

router.post('/manage_data/upload_new_dataset/check', function (req, res) {
  req.session.data.newSet = collectFormData(req, req.session.data.newSet);
  res.render('manage_data/upload_new_dataset/check.html');
});

/* === Dataset management === */

router.get('/datasets/edit/:index', function (req, res) {
  var datasetToEdit = req.session.data.sets[req.params.index];
  res.render(
    'manage_data/edit_dataset/index.html',
    { index: req.params.index, dataset: datasetToEdit }
  );
});

router.get('/datasets/delete/:index', function (req, res) {
  req.session.data.sets.splice(req.params.index, 1);
  res.redirect('/datasets?deleted=1');
});

router.post('/datasets', function (req, res) {
  req.session.data.newSet = collectFormData(req, req.session.data.newSet);
  console.log('unshift');
  req.session.data.sets.unshift(req.session.data.newSet);
  req.session.data.newSet = {};
  latestSet = req.session.data.sets[0];

  res.render(
    'datasets/index.html',
    { query: req.query, status: latestSet.status }
  );
});

/* === Data file management === */

router.post('/manage_data/upload_new_dataset/datafiles', function (req, res) {
  req.session.data.newSet = collectFormData(req, req.session.data.newSet);
  res.render('manage_data/upload_new_dataset/datafiles.html');
});

router.get(
  '/manage_data/upload_new_dataset/datafiles/edit/:index',
  function (req, res) {
    var datasetFile = req.session.data.newSet.files[req.params.index];
    res.render('manage_data/upload_new_dataset/file_upload.html');
  }
);

router.get(
  '/manage_data/upload_new_dataset/datafiles/delete/:index',
  function (req, res) {
    req.session.data.newSet.files.splice(req.params.index, 1);
    res.redirect('/manage_data/upload_new_dataset/datafiles');
  }
);

/* ============================ */

// Check if we've got to this page but user actually selected harvest
router.get('/menu', function (req, res) {
  res.redirect(req.query.goto);
});

router.post('/manage_data/upload_new_dataset/licence', function (req, res) {
  req.session.data.newSet = collectFormData(req, req.session.data.newSet);
  if (req.session.data.newSet === 'http://justice.gov.uk/test-data') {
    res.redirect('/manage_data/upload_new_dataset/file_upload?error=1')
  } else {
    res.render('manage_data/upload_new_dataset/licence.html');
  }
});

router.post('/manage_data/upload_new_dataset/publish', function (req, res) {
  req.session.data.newSet = collectFormData(req, req.session.data.newSet);
  res.redirect(307, '/datasets?newset=1');
});

router.post(
  '/manage_data/upload_new_dataset/want_notifications',
  function (req, res) {
    delete req.session.data.newSet.notify;
    req.session.data.newSet = collectFormData(req, req.session.data.newSet);
    if (req.session.data.newSet.frequency !== 'none'
        && !req.session.data.newSet.notify) {
      res.redirect('/manage_data/upload_new_dataset/want_notifications');
    } else {
      res.redirect('/manage_data/upload_new_dataset/check');
    }
  }
);

router.post('/manage_data/upload_new_dataset/frequency_routing',
  function(req, res) {
    req.session.data.newSet = collectFormData(req, req.session.data.newSet);
    queryString = req.query.change ? '?change=1' : '';
    switch (req.session.data.newSet.frequency) {
      case 'week':
        res.redirect('/manage_data/upload_new_dataset/period_week' + queryString);
        break;
      case 'month':
        res.redirect('/manage_data/upload_new_dataset/period_month' + queryString);
        break;
      case 'quarter':
        res.redirect('/manage_data/upload_new_dataset/period_quarter' + queryString);
        break;
      case 'year':
        res.redirect('/manage_data/upload_new_dataset/period_year' + queryString);
        break;
      default:
        if (req.query.change) {
          res.redirect('/manage_data/upload_new_dataset/check');
        } else {
          res.redirect('/manage_data/upload_new_dataset/file_upload');
        }
        break;
    }
  }
);

router.post('/datasets/edit/edit_submit', function(req, res) {
  req.session.data.sets[req.body.index] =
    collectFormData(req, req.session.data.sets[req.body.index]);
  res.redirect('/datasets?modified=1');
});

router.post('/send-login', function (req, res) {
  if (req.body.email == 'a@b.c' && req.body.password == 'foobar') {
    req.session.data = { userName: req.body.email };
    req.session.data.sets = session.initialDataSets();
    res.redirect('/dashboard');
  }
});

router.get('/logout', function (req, res) {
  req.session.destroy(function(err) {
    res.redirect('/');
  });
})

module.exports = router;

function collectFormData(req, dataset) {

  if (req.body['title-dataset']) {
    dataset.title = req.body['title-dataset'];
  }
  if (req.body['summary-dataset']) {
    dataset.summary = req.body['summary-dataset'];
  }
  if (req.body['file-url']) {
    if (!dataset.files) dataset.files = [];
    dataset.files.push({
      url: req.body['file-url'],
      title: req.body['file-title']
    });
  }
  if (req.body['licence']) {
    dataset.licence = req.body['licence'];
  }
  if (req.body['other-licence']) {
    dataset.otherLicence = req.body['other-licence'];
  }
  if (req.body['themes']) {
    var themes = req.body['themes'];
    dataset.themes = typeof themes === 'string' ? [themes] : themes;
  }
  if (req.body['geo']) {
    var geo = req.body['geo'];
    dataset.geo = typeof geo === 'string' ? [geo] : geo;
  }
  if (req.body['other-geo']) {
    dataset.otherGeo = req.body['other-geo'];
  }
  if (req.body['frequency']) {
    dataset.frequency = req.body['frequency'];
  }
  if (req.body['start-day']) {
    dataset.startDay = req.body['start-day'];
  }
  if (req.body['start-month']) {
    dataset.startMonth = req.body['start-month'];
  }
  if (req.body['start-year']) {
    dataset.startYear = req.body['start-year'];
  }
  if (req.body['end-day']) {
    dataset.endDay = req.body['end-day'];
  }
  if (req.body['end-month']) {
    dataset.endMonth = req.body['end-month'];
  }
  if (req.body['end-year']) {
    dataset.endYear = req.body['end-year'];
  }
  if (req.body['period-month']) {
    dataset.periodMonth = req.body['period-month'];
  }
  if (req.body['period-year']) {
    dataset.periodYear = req.body['period-year'];
  }
  if (req.body['period-quarter']) {
    dataset.periodQuarter = req.body['period-quarter'];
  }
  if (req.body['notify']) {
    dataset.notify = req.body['notify'];
  }
  if (req.body['status']) {
    dataset.status = req.body['status'];
  }

  console.log(dataset);

  return dataset;
}
<commit_msg>Fix fake error functionality<commit_after>var express = require('express');
var router = express.Router();
var session = require('./session');

router.use(function (req, res, next) {

  // Store common vars
  res.locals.data = {};

  // expose session data to templates
  res.locals.data = req.session.data;
  res.locals.query = req.query

  //console.log('query', req.query);
  //console.log('headers', req.headers);

  if (req.session.data && req.session.data.userName) {
    next();
  } else {
    if (req.originalUrl.match(/^\/login$/) ||
        req.originalUrl.match(/^\/send-login$/) ||
        req.originalUrl.match(/^\/$/) ||
        req.originalUrl.match(/^\/create_account/)) {
      next();
    } else {
      res.redirect('/login');
    }
  }
});

router.get('/', function (req, res) {
  req.session.regenerate(function(err) {
    req.session.query = req.query;
    res.render('index');
  });
});

// Branching

// Question for questions/eligibility/index.html
router.get('/create_account/enter_details', function (req, res) {

  // get the answer from the query string (eg. ?existing_account="yes")
  var existing_account = req.query.existing_account;

  if (existing_account == "yes" ){

    // if users is DOES have account
//    res.redirect("/create_account/search_for_existing_account" + res.locals.formQuery);

  } else {

    // if users is does NOT have account
    res.render('create_account/enter_details.html');

  }

});

router.get(
  '/manage_data/upload_new_dataset',
  function (req, res) {
    req.session.data.newSet = {};
    res.redirect('upload_new_dataset/title_summary');
  }
);

router.post('/manage_data/upload_new_dataset/file_upload', function (req, res) {
  req.session.data.newSet = collectFormData(req, req.session.data.newSet);
  res.render('manage_data/upload_new_dataset/file_upload.html');
});

router.post('/manage_data/upload_new_dataset/themes_auto', function (req, res) {
  req.session.data.newSet = collectFormData(req, req.session.data.newSet);
  req.session.data.newSet.themes = ['Business and economy', 'Environment'];
  res.render('manage_data/upload_new_dataset/themes_auto.html');
});

router.post('/manage_data/upload_new_dataset/themes_confirm',
  function (req, res) {
    req.session.data.newSet = collectFormData(req, req.session.data.newSet);
    res.render('manage_data/upload_new_dataset/themes_confirm.html');
  }
);

router.post('/manage_data/upload_new_dataset/geo', function (req, res) {
  req.session.data.newSet = collectFormData(req, req.session.data.newSet);
  res.render('manage_data/upload_new_dataset/geo.html');
});

router.post(
  '/manage_data/upload_new_dataset/update_frequency',
  function (req, res) {
    req.session.data.newSet = collectFormData(req, req.session.data.newSet);
    res.render('manage_data/upload_new_dataset/update_frequency.html');
  }
);

router.post('/manage_data/upload_new_dataset/check', function (req, res) {
  req.session.data.newSet = collectFormData(req, req.session.data.newSet);
  res.render('manage_data/upload_new_dataset/check.html');
});

/* === Dataset management === */

router.get('/datasets/edit/:index', function (req, res) {
  var datasetToEdit = req.session.data.sets[req.params.index];
  res.render(
    'manage_data/edit_dataset/index.html',
    { index: req.params.index, dataset: datasetToEdit }
  );
});

router.get('/datasets/delete/:index', function (req, res) {
  req.session.data.sets.splice(req.params.index, 1);
  res.redirect('/datasets?deleted=1');
});

router.post('/datasets', function (req, res) {
  req.session.data.newSet = collectFormData(req, req.session.data.newSet);
  console.log('unshift');
  req.session.data.sets.unshift(req.session.data.newSet);
  req.session.data.newSet = {};
  latestSet = req.session.data.sets[0];

  res.render(
    'datasets/index.html',
    { query: req.query, status: latestSet.status }
  );
});

/* === Data file management === */

router.post('/manage_data/upload_new_dataset/datafiles', function (req, res) {
  if (req.body['file-url'].indexOf('invalid') !== -1) {
    res.redirect('/manage_data/upload_new_dataset/file_upload?error=1')
  } else {
    req.session.data.newSet = collectFormData(req, req.session.data.newSet);
    res.render('manage_data/upload_new_dataset/datafiles.html');
  }
});

router.get(
  '/manage_data/upload_new_dataset/datafiles/edit/:index',
  function (req, res) {
    var datasetFile = req.session.data.newSet.files[req.params.index];
    res.render('manage_data/upload_new_dataset/file_upload.html');
  }
);

router.get(
  '/manage_data/upload_new_dataset/datafiles/delete/:index',
  function (req, res) {
    req.session.data.newSet.files.splice(req.params.index, 1);
    res.redirect('/manage_data/upload_new_dataset/datafiles');
  }
);

/* ============================ */

// Check if we've got to this page but user actually selected harvest
router.get('/menu', function (req, res) {
  res.redirect(req.query.goto);
});

router.post('/manage_data/upload_new_dataset/licence', function (req, res) {
  req.session.data.newSet = collectFormData(req, req.session.data.newSet);
  res.render('manage_data/upload_new_dataset/licence.html');
});

router.post('/manage_data/upload_new_dataset/publish', function (req, res) {
  req.session.data.newSet = collectFormData(req, req.session.data.newSet);
  res.redirect(307, '/datasets?newset=1');
});

router.post(
  '/manage_data/upload_new_dataset/want_notifications',
  function (req, res) {
    delete req.session.data.newSet.notify;
    req.session.data.newSet = collectFormData(req, req.session.data.newSet);
    if (req.session.data.newSet.frequency !== 'none'
        && !req.session.data.newSet.notify) {
      res.redirect('/manage_data/upload_new_dataset/want_notifications');
    } else {
      res.redirect('/manage_data/upload_new_dataset/check');
    }
  }
);

router.post('/manage_data/upload_new_dataset/frequency_routing',
  function(req, res) {
    req.session.data.newSet = collectFormData(req, req.session.data.newSet);
    queryString = req.query.change ? '?change=1' : '';
    switch (req.session.data.newSet.frequency) {
      case 'week':
        res.redirect('/manage_data/upload_new_dataset/period_week' + queryString);
        break;
      case 'month':
        res.redirect('/manage_data/upload_new_dataset/period_month' + queryString);
        break;
      case 'quarter':
        res.redirect('/manage_data/upload_new_dataset/period_quarter' + queryString);
        break;
      case 'year':
        res.redirect('/manage_data/upload_new_dataset/period_year' + queryString);
        break;
      default:
        if (req.query.change) {
          res.redirect('/manage_data/upload_new_dataset/check');
        } else {
          res.redirect('/manage_data/upload_new_dataset/file_upload');
        }
        break;
    }
  }
);

router.post('/datasets/edit/edit_submit', function(req, res) {
  req.session.data.sets[req.body.index] =
    collectFormData(req, req.session.data.sets[req.body.index]);
  res.redirect('/datasets?modified=1');
});

router.post('/send-login', function (req, res) {
  if (req.body.email == 'a@b.c' && req.body.password == 'foobar') {
    req.session.data = { userName: req.body.email };
    req.session.data.sets = session.initialDataSets();
    res.redirect('/dashboard');
  }
});

router.get('/logout', function (req, res) {
  req.session.destroy(function(err) {
    res.redirect('/');
  });
})

module.exports = router;

function collectFormData(req, dataset) {

  if (req.body['title-dataset']) {
    dataset.title = req.body['title-dataset'];
  }
  if (req.body['summary-dataset']) {
    dataset.summary = req.body['summary-dataset'];
  }
  if (req.body['file-url']) {
    if (!dataset.files) dataset.files = [];
    dataset.files.push({
      url: req.body['file-url'],
      title: req.body['file-title']
    });
  }
  if (req.body['licence']) {
    dataset.licence = req.body['licence'];
  }
  if (req.body['other-licence']) {
    dataset.otherLicence = req.body['other-licence'];
  }
  if (req.body['themes']) {
    var themes = req.body['themes'];
    dataset.themes = typeof themes === 'string' ? [themes] : themes;
  }
  if (req.body['geo']) {
    var geo = req.body['geo'];
    dataset.geo = typeof geo === 'string' ? [geo] : geo;
  }
  if (req.body['other-geo']) {
    dataset.otherGeo = req.body['other-geo'];
  }
  if (req.body['frequency']) {
    dataset.frequency = req.body['frequency'];
  }
  if (req.body['start-day']) {
    dataset.startDay = req.body['start-day'];
  }
  if (req.body['start-month']) {
    dataset.startMonth = req.body['start-month'];
  }
  if (req.body['start-year']) {
    dataset.startYear = req.body['start-year'];
  }
  if (req.body['end-day']) {
    dataset.endDay = req.body['end-day'];
  }
  if (req.body['end-month']) {
    dataset.endMonth = req.body['end-month'];
  }
  if (req.body['end-year']) {
    dataset.endYear = req.body['end-year'];
  }
  if (req.body['period-month']) {
    dataset.periodMonth = req.body['period-month'];
  }
  if (req.body['period-year']) {
    dataset.periodYear = req.body['period-year'];
  }
  if (req.body['period-quarter']) {
    dataset.periodQuarter = req.body['period-quarter'];
  }
  if (req.body['notify']) {
    dataset.notify = req.body['notify'];
  }
  if (req.body['status']) {
    dataset.status = req.body['status'];
  }

  console.log(dataset);

  return dataset;
}
<|endoftext|>


<commit_before>var emojis = require('emojilib')
var clipboard = require('clipboard')
var ipc = require('ipc')
var index = buildIndex(emojis)
var searchInput = document.querySelector('.js-search')

// todo
// - up/down/left/right key navigation
// - pagination?

searchInput.focus()
searchInput.addEventListener('input', function (evt) {
  search(this.value)
})

document.addEventListener('keyup', function (evt) {
  if (evt.keyCode === 13 && evt.target.className === "code") {
    // on enter: copy data and exit
    if (evt.shiftKey) {
      var data = evt.target.dataset.char
    } else {
      var data = evt.target.value
    }
    clipboard.writeText(data)

    ipc.send('abort')
  } else if (evt.keyCode === 191) {
    // on `/`: focus on the search field
    searchInput.select()
  } else if (evt.keyCode === 27) {
    // on escape: exit
    ipc.send('abort')
  }
})

document.addEventListener('keypress', function (evt) {
  // if typing while navigatin, just type into the search box!
  var word = isWord(evt.charCode)
  if (word && evt.target.className === "code") {
    searchInput.focus()
    searchInput.value = word
  }
})

function search (query) {
  var results = (Object.keys(index).filter(function matchQuery (keyword) {
    return keyword.match(query)
  })).map(function(keyword) {
    return index[keyword]
  }).join().split(',').filter(function filterUniqueResults (emoji, pos, arr) {
    return emoji && arr.indexOf(emoji) === pos
  }).map(function generateMarkup (name) {
    var unicode = (emojis[name]['char'] || '--')
    var result = '
' + unicode + ''
    result += '<input readonly type="text" data-char="' + unicode + '" class="code" value=":' + name + ':">
'
    return result
  }).join('')

  document.querySelector('.js-outcome').innerHTML = results
}

function buildIndex (emojis) {
  var keywords = {}
  Object.keys(emojis).map(function (name) {
    var words = emojis[name]["keywords"]
    words.push(name)
    words.push(emojis[name]["category"])

    words.forEach(function(word) {
      if (keywords[word] && keywords[word].indexOf(name) < 0) {
        keywords[word].push(name)
      } else {
        keywords[word] = [name]
      }
    })
  })
  return keywords
}

function isWord (charCode) {
  var word = String.fromCharCode(charCode).match(/\w/)
  return !!word ? word : false
}<commit_msg>👋 implement key navigation<commit_after>var emojis = require('emojilib')
var clipboard = require('clipboard')
var ipc = require('ipc')
var index = buildIndex(emojis)
var searchInput = document.querySelector('.js-search')
var directions = {
  37: "left",
  38: "up",
  39: "right",
  40: "down"
}

// todo
// - pagination?

searchInput.focus()
searchInput.addEventListener('input', function (evt) {
  search(this.value)
})

document.addEventListener('keyup', function (evt) {
  if (evt.target.className === "code") {
    if (evt.keyCode === 13) {
      // on enter: copy data and exit
      if (evt.shiftKey) {
        var data = evt.target.dataset.char
      } else {
        var data = evt.target.value
      }
      clipboard.writeText(data)

      ipc.send('abort')
    } else if (Object.keys(directions).indexOf(evt.keyCode.toString()) >= 0) {
      // on navigation, navigate
      jumpto(directions[evt.keyCode])
    }
  } else if (evt.keyCode === 191) {
    // on `/`: focus on the search field
    searchInput.select()
  } else if (evt.keyCode === 27) {
    // on escape: exit
    ipc.send('abort')
  }
})

document.addEventListener('keypress', function (evt) {
  // if typing while navigatin, just type into the search box!
  var word = isWord(evt.charCode)
  if (word && evt.target.className === "code") {
    searchInput.focus()
    searchInput.value = word
  }
})

function search (query) {
  var results = (Object.keys(index).filter(function matchQuery (keyword) {
    return keyword.match(query)
  })).map(function(keyword) {
    return index[keyword]
  }).join().split(',').filter(function filterUniqueResults (emoji, pos, arr) {
    return emoji && arr.indexOf(emoji) === pos
  }).map(function generateMarkup (name) {
    var unicode = (emojis[name]['char'] || '--')
    var result = '
' + unicode + ''
    result += '<input readonly type="text" data-char="' + unicode + '" class="code" value=":' + name + ':">
'
    return result
  }).join('')

  document.querySelector('.js-outcome').innerHTML = results
}

function buildIndex (emojis) {
  var keywords = {}
  Object.keys(emojis).map(function (name) {
    var words = emojis[name]["keywords"]
    words.push(name)
    words.push(emojis[name]["category"])

    words.forEach(function(word) {
      if (keywords[word] && keywords[word].indexOf(name) < 0) {
        keywords[word].push(name)
      } else {
        keywords[word] = [name]
      }
    })
  })
  return keywords
}

function isWord (charCode) {
  var word = String.fromCharCode(charCode).match(/\w/)
  return !!word ? word : false
}

function jumpto (direction) {
  var all = document.getElementsByClassName('code')
  var focusedElement = document.querySelector('.code:focus')
  var nodeIndex = Array.prototype.indexOf.call(all, focusedElement)
  var resultPerRow = 3

  if (direction === 'up') {
    var newTarget = nodeIndex - 3
  } else if (direction === 'down') {
    var newTarget = nodeIndex + 3
  } else if (direction === 'left') {
    if ((nodeIndex+1)%3 === 1) {
      var newTarget = nodeIndex + 2
    } else {
      var newTarget = nodeIndex - 1
    }
  } else if (direction === 'right') {
    if ((nodeIndex+1)%3 === 0) {
      var newTarget = nodeIndex - 2
    } else {
      var newTarget = nodeIndex + 1
    }
  }

  if (newTarget < 0) newTarget = 0
  if (newTarget >= all.length - 1) newTarget = all.length - 1
  all[newTarget].focus()
}
<|endoftext|>


<commit_before>var Strategy=require('../lib/index.js');

describe('Strategy Tests', function () {
  var onshapeStrategy;
  beforeEach(function() {
    onshapeStrategy = new Strategy({
      clientID: 'AClientID',
      clientSecret: 'TheClientSecret',
      callbackURL: 'http://example.com/oauthCallback',
      userAgent: 'TheUserAgent'
      }, function() {});
  });

  it('should be able to construct the Onshape strategy', function() {

    expect(onshapeStrategy.name).toEqual('onshape');
  });

  it('should fetch the user profile', function() {
    var done = jasmine.createSpy('done');
    spyOn(onshapeStrategy._oauth2, 'get').and.callFake(function(url, token, cb) {
      var response = {id: 'AUserId', name: 'User Name',html_url: 'http://example.com', email: 'user@example.com'};
      cb(null, JSON.stringify(response));
    });
    onshapeStrategy.userProfile('AnAccessToken', done);
    expect(onshapeStrategy._oauth2.get).toHaveBeenCalledWith(jasmine.any(String), 'AnAccessToken', jasmine.any(Function));
    expect(done).toHaveBeenCalledWith(null, {
      provider: 'onshape',
      id: 'AUserId',
      displayName: 'User Name',
      profileUrl: 'http://example.com',
      emails: [{value: 'user@example.com'}],
      _raw: jasmine.any(String),
      _json: jasmine.any(Object)
    });
  });

  it('should handle an error when fetching the user profile', function() {
    var done = jasmine.createSpy('done');
    spyOn(onshapeStrategy._oauth2, 'get').and.callFake(function(url, token, cb) {
      cb('An Error occured', null);
    });
    onshapeStrategy.userProfile('AnAccessToken', done);
    expect(onshapeStrategy._oauth2.get).toHaveBeenCalledWith(jasmine.any(String), 'AnAccessToken', jasmine.any(Function));
    expect(done.calls.mostRecent().args[0].message).toEqual( 'Failed to fetch user profile' );
    expect(done.calls.mostRecent().args[0].name).toEqual( 'InternalOAuthError' );
    expect(done.calls.mostRecent().args[0].oauthError).toEqual( 'An Error occured' );
  });

  it('should handle an error when deserializing the user profile', function() {
    var done = jasmine.createSpy('done');
    spyOn(onshapeStrategy._oauth2, 'get').and.callFake(function(url, token, cb) {
      cb(null, 'A Text String');
    });
    onshapeStrategy.userProfile('AnAccessToken', done);
    expect(onshapeStrategy._oauth2.get).toHaveBeenCalledWith(jasmine.any(String), 'AnAccessToken', jasmine.any(Function));
    expect(done.calls.mostRecent().args[0].message).toEqual('Failed to parse user profile');
  });
});
<commit_msg>fixed jasmine tests for update<commit_after>var Strategy=require('../lib/index.js');

describe('Strategy Tests', function () {
  var onshapeStrategy;
  beforeEach(function() {
    onshapeStrategy = new Strategy({
      clientID: 'AClientID',
      clientSecret: 'TheClientSecret',
      callbackURL: 'http://example.com/oauthCallback',
      userAgent: 'TheUserAgent'
      }, function() {});
  });

  it('should be able to construct the Onshape strategy', function() {

    expect(onshapeStrategy.name).toEqual('onshape');
  });

  it('should fetch the user profile', function() {
    var done = jasmine.createSpy('done');
    spyOn(onshapeStrategy._oauth2, 'get').andCallFake(function(url, token, cb) {
      var response = {id: 'AUserId', name: 'User Name',html_url: 'http://example.com', email: 'user@example.com'};
      cb(null, JSON.stringify(response));
    });
    onshapeStrategy.userProfile('AnAccessToken', done);
    expect(onshapeStrategy._oauth2.get).toHaveBeenCalledWith(jasmine.any(String), 'AnAccessToken', jasmine.any(Function));
    expect(done).toHaveBeenCalledWith(null, {
      provider: 'onshape',
      id: 'AUserId',
      displayName: 'User Name',
      profileUrl: 'http://example.com',
      emails: [{value: 'user@example.com'}],
      _raw: jasmine.any(String),
      _json: jasmine.any(Object)
    });
  });

  it('should handle an error when fetching the user profile', function() {
    var done = jasmine.createSpy('done');
    spyOn(onshapeStrategy._oauth2, 'get').andCallFake(function(url, token, cb) {
      cb('An Error occured', null);
    });
    onshapeStrategy.userProfile('AnAccessToken', done);
    expect(onshapeStrategy._oauth2.get).toHaveBeenCalledWith(jasmine.any(String), 'AnAccessToken', jasmine.any(Function));
    var recentCallArgs = done.mostRecentCall.args[0];
    expect(recentCallArgs.message).toEqual( 'Failed to fetch user profile' );
    expect(recentCallArgs.name).toEqual( 'InternalOAuthError' );
    expect(recentCallArgs.oauthError).toEqual( 'An Error occured' );
  });

  it('should handle an error when deserializing the user profile', function() {
    var done = jasmine.createSpy('done');
    spyOn(onshapeStrategy._oauth2, 'get').andCallFake(function(url, token, cb) {
      cb(null, 'A Text String');
    });
    onshapeStrategy.userProfile('AnAccessToken', done);
    expect(onshapeStrategy._oauth2.get).toHaveBeenCalledWith(jasmine.any(String), 'AnAccessToken', jasmine.any(Function));
    expect(done.mostRecentCall.args[0].message).toEqual('Failed to parse user profile');
  });
});
<|endoftext|>