<commit_before>var _          = require('underscore'),
    fs         = require('fs');
    async      = require('async'),
    ejs        = require('ejs');

//var cache = require('memory-cache');

var Preferences = require('./../config/Preferences.js'),
    Utility     = require('./../modules/Utility.js'),
    User        = require('./../modules/user.js'),
    db          = require('./../modules/db.js'),
    autoAssign  = require('./../modules/autoAssign.js');

module.exports = {
    get: function(req, res) {
        User.permissionControl(req, res, 10);

        var lastInfo = ['',''];
        try {
            var readFile = fs.readFileSync(__dirname + Preferences.path_last_upload_info); //see the last upload time & user
            lastInfo = readFile.toString().split('&');
        } catch(e) {}
         res.render('upload', {app: req.app, lastUploadTime: lastInfo[0], lastUploadUser: lastInfo[1]});
    },
    post: function(req, res) {
        User.permissionControl(req, res, 10);

        var today, twoWeeksLater;
        today = new Date();
        today.setHours(0,0,0,0);
        twoWeeksLater = new Date((new Date()).getTime() + 2 * 7 * 24 * 60 * 60 * 1000);
        twoWeeksLater.setHours(23,59,59,999);

        db.events.find({'start': {$gte: today, $lt: twoWeeksLater}}, function(err, events) {
            if (err || !events) {
                console.log(req.url);
                console.log("No events found" + err);
            } else {
                // events loaded. let's check for every event

                    var parser = require('xml2json');
                    console.log('Upload and saving progress started');
                    //you should check if it's an xml file
                    try {
                        // Freshly uploaded XML and last.xml are read
                            var xml = fs.readFileSync(req.files.myFile.path),
                                last = fs.readFileSync(__dirname + Preferences.path_last_xml);
                        // Both XML files are parsed
                            xml = parser.toJson(xml, {
                                object: true,
                                trim: true,
                                arrayNotation: true
                            }).CopyofIMSforExport.Data;
                            last = parser.toJson(last, {
                                object: true,
                                trim: true,
                                arrayNotation: true
                            }).CopyofIMSforExport.Data;
                            if(last === "0" || last === 0) {last = [];} //this is only for the first setup of spec on any machine

                        var whatToChange = { update: [], add: [], remove: events };
                        console.log(xml.length + ' events in the new XML file');
                        console.log(last.length + ' events in the last XML file');
                        // Parsed XML files are compared according to their unique ID's, event by event
                        xml.forEach(function(xmlEntry) {
                            //try to find an object with the same unique ID
                            var entryInLast = _.findWhere(last, {
                                'Service_x0020_Order_x0020_Detail_x0020_ID': xmlEntry.Service_x0020_Order_x0020_Detail_x0020_ID
                            });
                            if (!_.isUndefined(entryInLast)) { //if exists, then compare if they are the same
                                if(!_.isEqual(xmlEntry, entryInLast)) {
                                    whatToChange.update.push(xmlEntry); //if they are the same, store to update later
                                }
                            } else { //if it doesn't exist in the last.xml, then store it to add later.
                                whatToChange.add.push(xmlEntry);
                            }
                            /*
                            find the event with the same XMLid, delete that event from the array
                            the remaining events are apparently deleted from EMS
                            */
                            whatToChange.remove = _.reject(whatToChange.remove, function(el) { return el.XMLid === xmlEntry.Service_x0020_Order_x0020_Detail_x0020_ID; });
                        });
                        //should write a part that distinguishes new events and updated events.
                        var process = function(data) {
                            var bookingDate = data.Booking_x0020_Date.split(" ")[0],
                                reservedStart = new Date(Date.parse(bookingDate + ' ' + data.Reserved_x0020_Start)),
                                reservedEnd = new Date(Date.parse(bookingDate + ' ' + data.Reserved_x0020_End)),
                                eventStart = new Date(Date.parse(bookingDate + ' ' + data.Event_x0020_Start)),
                                eventEnd = new Date(Date.parse(bookingDate + ' ' + data.Event_x0020_End)),
                                desc;

                            if(data.Category === 'A/V Services') {
                                desc = data.Resource;
                            } else {
                                desc = data.Notes;
                            }

                            if(_.isObject(desc)) {desc = '';} //if it's an object rather than a string, make it a blank string

                            var cancelled = false;
                            if (data.Booking_x0020_Status == 'Cancelled') {
                                cancelled = true;
                            }
                            var video = false;
                            ['video','recording'].forEach(function(word) {
                                if(String(data.Notes).indexOf(word) != -1) {
                                    video = true;
                                }
                            });
                            return {
                                XMLid: data.Service_x0020_Order_x0020_Detail_x0020_ID,
                                title: req.app.locals.fixParantheses(data.Event_x0020_Name),
                                desc:  req.app.locals.fixParantheses(desc),
                                loc:   req.app.locals.fixParantheses(data.Room_x0020_Description),
                                start: reservedStart,
                                end:   reservedEnd,
                                'eventStart': eventStart,
                                'eventEnd':   eventEnd,
                                'cancelled':  cancelled,
                                techMustStay: true,
                                'audio': false,
                                'video':  video,
                                customer: {
                                    'name':  req.app.locals.fixParantheses(data.Customer),
                                    'phone': data.Customer_x0020_Phone_x0020_1,
                                }
                            };
                        };

                        var cleanSheet = function(data) { //these are for the new events to be added.
                            data.inventory = [];
                            data.notes = [];
                            data.shifts = [];
                            data.staffNeeded = 1;
                            return data;
                        };

                        whatToChange.update = whatToChange.update.map(process);
                        whatToChange.add = whatToChange.add.map(process).map(cleanSheet).map(autoAssign);

                        var changeNumbers = {add:0, update:0, remove: 0},
                            parallel = [],
                            whatToReport = {update:[], remove: whatToChange.remove};
                        //push update functions in an array, in order to have a final callback function to end response after the async.parallel process
                        whatToChange.add.forEach(function(event) {
                            parallel.push(function(callback) {
                                                    db.events.save(event, function(err, saved) {
                                                        if (err || !saved) {
                                                            console.log("New event is not saved");
                                                        } else {
                                                            changeNumbers.add++;
                                                            callback();
                                                        }
                                                    });
                                                });
                        });

                        whatToChange.update.forEach(function(event) {
                            parallel.push(function(callback) {
                                                    db.events.findAndModify({
                                                        query: {XMLid: event.XMLid},
                                                        update: {$set: event },
                                                        new: true
                                                    },
                                                    function(err, updated) {
                                                        if (err || !updated) {
                                                            console.log("Event could not be updated: " + err);
                                                            console.log(event.title);
                                                        } else {
                                                            changeNumbers.update++;
                                                            whatToReport.update.push(updated);
                                                            callback();
                                                        }
                                                    });
                                                });
                        });

                        whatToChange.remove.forEach(function(event) { //events removed from EMS detected, now delete them from db
                            parallel.push(function(callback) {
                                                    db.events.remove(
                                                        {XMLid: event.XMLid},
                                                        function(err, removed) {
                                                            if (err || !removed) {
                                                                console.log("Event could not be removed:" + err);
                                                                console.log(event.title);
                                                            } else {
                                                                changeNumbers.remove++;
                                                                callback();
                                                            }
                                                        });
                                                });
                        });

                        async.parallel(parallel, function() {
                            console.log("Upload and saving progress ended successfully");
                            res.writeHead(200);
                            res.write(changeNumbers.add + ' events added, ' + changeNumbers.update + ' updated and ' + changeNumbers.remove + ' removed, upload and saving progress ended successfully.');
                            res.end();
                            // delete the old last.xml file and rename the new uploaded file as last.xml
                            (function(path) {
                                fs.unlink(__dirname + Preferences.path_last_xml, function(err) {
                                    if (err) {
                                        console.log(err);
                                        return false;
                                    }
                                    console.log('Old last.xml file successfully deleted');
                                    fs.rename(path, __dirname + Preferences.path_last_xml, function(err) {
                                        if (err) throw err;
                                        console.log('Uploaded file renamed to last.xml');
                                    });
                                });
                            })(req.files.myFile.path);
                            reportUpdate(whatToReport, req); //send messages to the staff and managers
                            fs.writeFileSync(__dirname + Preferences.path_last_upload_info, (new Date() + '&' + User.getUser(req))); //store the last upload time & user
                        });
                    } catch (err) {
                        // delete the newly uploaded file because there is no need to store it
                        if(!_.isUndefined(req.files)) { //if there is actually a file, then delete it
                            (function(path) {
                                console.log(path);
                                fs.unlink(path, function(err) {
                                    if (err) {
                                        console.log(err);
                                        return false;
                                    }
                                    console.log('File with error successfully deleted');
                                });
                            })(req.files.myFile.path);
                        } else {
                            console.log('There is no file uploaded.');
                        }
                        console.log(err);
                        //res.writeHead(400);
                        res.end();
                        return false;
                    }

                // first db query and if else, and other functions end
            }
        });
    }
};

//this will send messages to the managers and the people who are registered in those events
//gonna be hoisted
function reportUpdate(whatToReport, req) {
    if(whatToReport.update.length < 1 && whatToReport.remove.length < 1) {return false;} //don't send any mail if there is no change
    //not using a function for e-mail sending because we need to close the connection after all stuff

    // create reusable transport method (opens pool of SMTP connections)
    var smtpTransport = Utility.smtpTransport();
    //we have an object {update:[], remove:[]}, and the update array has the these events
    var whatToSend = {},
        parallel = [];
    whatToReport.update.forEach(function(event) {
        parallel.push(function(callback) {
            event.shifts.forEach(function(shift) {
                if(_.isUndefined(whatToSend[shift.staff])) { whatToSend[shift.staff] = {remove:[], update:[]}; }
                whatToSend[shift.staff].update.push({'event': event, 'shift': shift}); //this is the structure of the array elements, be careful
            });
            callback();
        });
    });
    whatToReport.remove.forEach(function(event) {
        parallel.push(function(callback) {
            event.shifts.forEach(function(shift) {
                if(_.isUndefined(whatToSend[shift.staff])) { whatToSend[shift.staff] = {remove:[], update:[]}; }
                whatToSend[shift.staff].remove.push({'event': event, 'shift': shift}); //this is the structure of the array elements, be careful
            });
            callback();
        });
    });
    async.parallel(parallel, function() {
        //now we have a complete whatToSend object, so we can start to send notifications

        _.each(whatToSend, function(items, user) {
            var staffMailOptions = {
                from: Preferences.mail.fromString,
                to: user + "@wesleyan.edu",
                subject: "Updated Event for " + user + " (IMPORTANT)",
            };

            staffMailOptions.html = ejs.render(fs.readFileSync(__dirname + '/../views/mail/normalUpdate.ejs', 'utf8'), {'app': req.app, 'items': items});

            smtpTransport.sendMail(staffMailOptions, function(error, response) {
                if (error) {
                    console.log(error);
                } else {
                    //console.log("Message sent: " + response.message);
                }
            });
        });

    }); //end of async.parallel

    //now it's time to report all updates to the managers (all staff with level 10), with whatToReport

        //var managerList = _.where(cache.get('storeStaff'), {level:10});
        var managerList = Preferences.managerEmails;

            managerMailOptions = {
                    from: Preferences.mail.fromString,
                    subject: "General Event Update Report (IMPORTANT)",
                };

        managerMailOptions.html = ejs.render(fs.readFileSync(__dirname + '/../views/mail/managerUpdate.ejs', 'utf8'), {'app': req.app, 'items': whatToReport});
        managerList.forEach(function (manager) {
            managerMailOptions.to = manager.username + "@wesleyan.edu";
            smtpTransport.sendMail(managerMailOptions, function(error, response) {
                    if (error) {
                        console.log(error);
                    } else {
                        //console.log("Message sent: " + response.message);
                    }
                });
        });

    //smtpTransport.close(); //this should wait for the callbacks to end
} //end of reportUpdate
<commit_msg>date range calculated in upload<commit_after>var _          = require('underscore'),
    fs         = require('fs');
    async      = require('async'),
    ejs        = require('ejs');

//var cache = require('memory-cache');

var Preferences = require('./../config/Preferences.js'),
    Utility     = require('./../modules/Utility.js'),
    User        = require('./../modules/user.js'),
    db          = require('./../modules/db.js'),
    autoAssign  = require('./../modules/autoAssign.js');

module.exports = {
    get: function(req, res) {
        User.permissionControl(req, res, 10);

        var lastInfo = ['',''];
        try {
            var readFile = fs.readFileSync(__dirname + Preferences.path_last_upload_info); //see the last upload time & user
            lastInfo = readFile.toString().split('&');
        } catch(e) {}
         res.render('upload', {app: req.app, lastUploadTime: lastInfo[0], lastUploadUser: lastInfo[1]});
    },
    post: function(req, res) {
        User.permissionControl(req, res, 10);

        var today, twoWeeksLater;
        today = new Date();
        today.setHours(0,0,0,0);
        twoWeeksLater = new Date((new Date()).getTime() + 2 * 7 * 24 * 60 * 60 * 1000);
        twoWeeksLater.setHours(23,59,59,999);

        db.events.find({'start': {$gte: today, $lt: twoWeeksLater}}, function(err, events) {
            if (err || !events) {
                console.log(req.url);
                console.log("No events found" + err);
            } else {
                // events loaded. let's check for every event

                    var parser = require('xml2json');
                    console.log('Upload and saving progress started');
                    //you should check if it's an xml file
                    try {
                        // Freshly uploaded XML and last.xml are read
                            var xml = fs.readFileSync(req.files.myFile.path),
                                last = fs.readFileSync(__dirname + Preferences.path_last_xml);
                        // Both XML files are parsed
                            xml = parser.toJson(xml, {
                                object: true,
                                trim: true,
                                arrayNotation: true
                            }).CopyofIMSforExport.Data;

                            // calculate the start and end dates for the event list
                            /*
                            var dates = xml.map(function(event) {
                                return new Date(Date.parse(bookingDate + ' ' + data.Reserved_x0020_Start));
                            });
                            dates = _.sortBy(dates, function(date) {
                                return date.getTime();
                            });
                            dates = {
                                first: _(dates).first(),
                                last: _(dates).last()
                            };
                            */

                            last = parser.toJson(last, {
                                object: true,
                                trim: true,
                                arrayNotation: true
                            }).CopyofIMSforExport.Data;
                            if(last === "0" || last === 0) {last = [];} //this is only for the first setup of spec on any machine

                        var whatToChange = { update: [], add: [], remove: events };
                        console.log(xml.length + ' events in the new XML file');
                        console.log(last.length + ' events in the last XML file');
                        // Parsed XML files are compared according to their unique ID's, event by event
                        xml.forEach(function(xmlEntry) {
                            //try to find an object with the same unique ID
                            var entryInLast = _.findWhere(last, {
                                'Service_x0020_Order_x0020_Detail_x0020_ID': xmlEntry.Service_x0020_Order_x0020_Detail_x0020_ID
                            });
                            if (!_.isUndefined(entryInLast)) { //if exists, then compare if they are the same
                                if(!_.isEqual(xmlEntry, entryInLast)) {
                                    whatToChange.update.push(xmlEntry); //if they are the same, store to update later
                                }
                            } else { //if it doesn't exist in the last.xml, then store it to add later.
                                whatToChange.add.push(xmlEntry);
                            }
                            /*
                            find the event with the same XMLid, delete that event from the array
                            the remaining events are apparently deleted from EMS
                            */
                            whatToChange.remove = _.reject(whatToChange.remove, function(el) { return el.XMLid === xmlEntry.Service_x0020_Order_x0020_Detail_x0020_ID; });
                        });
                        //should write a part that distinguishes new events and updated events.
                        var process = function(data) {
                            var bookingDate = data.Booking_x0020_Date.split(" ")[0],
                                reservedStart = new Date(Date.parse(bookingDate + ' ' + data.Reserved_x0020_Start)),
                                reservedEnd = new Date(Date.parse(bookingDate + ' ' + data.Reserved_x0020_End)),
                                eventStart = new Date(Date.parse(bookingDate + ' ' + data.Event_x0020_Start)),
                                eventEnd = new Date(Date.parse(bookingDate + ' ' + data.Event_x0020_End)),
                                desc;

                            if(data.Category === 'A/V Services') {
                                desc = data.Resource;
                            } else {
                                desc = data.Notes;
                            }

                            if(_.isObject(desc)) {desc = '';} //if it's an object rather than a string, make it a blank string

                            var cancelled = false;
                            if (data.Booking_x0020_Status == 'Cancelled') {
                                cancelled = true;
                            }
                            var video = false;
                            ['video','recording'].forEach(function(word) {
                                if(String(data.Notes).indexOf(word) != -1) {
                                    video = true;
                                }
                            });
                            return {
                                XMLid: data.Service_x0020_Order_x0020_Detail_x0020_ID,
                                title: req.app.locals.fixParantheses(data.Event_x0020_Name),
                                desc:  req.app.locals.fixParantheses(desc),
                                loc:   req.app.locals.fixParantheses(data.Room_x0020_Description),
                                start: reservedStart,
                                end:   reservedEnd,
                                'eventStart': eventStart,
                                'eventEnd':   eventEnd,
                                'cancelled':  cancelled,
                                techMustStay: true,
                                'audio': false,
                                'video':  video,
                                customer: {
                                    'name':  req.app.locals.fixParantheses(data.Customer),
                                    'phone': data.Customer_x0020_Phone_x0020_1,
                                }
                            };
                        };

                        var cleanSheet = function(data) { //these are for the new events to be added.
                            data.inventory = [];
                            data.notes = [];
                            data.shifts = [];
                            data.staffNeeded = 1;
                            return data;
                        };

                        whatToChange.update = whatToChange.update.map(process);
                        whatToChange.add = whatToChange.add.map(process).map(cleanSheet).map(autoAssign);

                        var changeNumbers = {add:0, update:0, remove: 0},
                            parallel = [],
                            whatToReport = {update:[], remove: whatToChange.remove};
                        //push update functions in an array, in order to have a final callback function to end response after the async.parallel process
                        whatToChange.add.forEach(function(event) {
                            parallel.push(function(callback) {
                                                    db.events.save(event, function(err, saved) {
                                                        if (err || !saved) {
                                                            console.log("New event is not saved");
                                                        } else {
                                                            changeNumbers.add++;
                                                            callback();
                                                        }
                                                    });
                                                });
                        });

                        whatToChange.update.forEach(function(event) {
                            parallel.push(function(callback) {
                                                    db.events.findAndModify({
                                                        query: {XMLid: event.XMLid},
                                                        update: {$set: event },
                                                        new: true
                                                    },
                                                    function(err, updated) {
                                                        if (err || !updated) {
                                                            console.log("Event could not be updated: " + err);
                                                            console.log(event.title);
                                                        } else {
                                                            changeNumbers.update++;
                                                            whatToReport.update.push(updated);
                                                            callback();
                                                        }
                                                    });
                                                });
                        });

                        whatToChange.remove.forEach(function(event) { //events removed from EMS detected, now delete them from db
                            parallel.push(function(callback) {
                                                    db.events.remove(
                                                        {XMLid: event.XMLid},
                                                        function(err, removed) {
                                                            if (err || !removed) {
                                                                console.log("Event could not be removed:" + err);
                                                                console.log(event.title);
                                                            } else {
                                                                changeNumbers.remove++;
                                                                callback();
                                                            }
                                                        });
                                                });
                        });

                        async.parallel(parallel, function() {
                            console.log("Upload and saving progress ended successfully");
                            res.writeHead(200);
                            res.write(changeNumbers.add + ' events added, ' + changeNumbers.update + ' updated and ' + changeNumbers.remove + ' removed, upload and saving progress ended successfully.');
                            res.end();
                            // delete the old last.xml file and rename the new uploaded file as last.xml
                            (function(path) {
                                fs.unlink(__dirname + Preferences.path_last_xml, function(err) {
                                    if (err) {
                                        console.log(err);
                                        return false;
                                    }
                                    console.log('Old last.xml file successfully deleted');
                                    fs.rename(path, __dirname + Preferences.path_last_xml, function(err) {
                                        if (err) throw err;
                                        console.log('Uploaded file renamed to last.xml');
                                    });
                                });
                            })(req.files.myFile.path);
                            reportUpdate(whatToReport, req); //send messages to the staff and managers
                            fs.writeFileSync(__dirname + Preferences.path_last_upload_info, (new Date() + '&' + User.getUser(req))); //store the last upload time & user
                        });
                    } catch (err) {
                        // delete the newly uploaded file because there is no need to store it
                        if(!_.isUndefined(req.files)) { //if there is actually a file, then delete it
                            (function(path) {
                                console.log(path);
                                fs.unlink(path, function(err) {
                                    if (err) {
                                        console.log(err);
                                        return false;
                                    }
                                    console.log('File with error successfully deleted');
                                });
                            })(req.files.myFile.path);
                        } else {
                            console.log('There is no file uploaded.');
                        }
                        console.log(err);
                        //res.writeHead(400);
                        res.end();
                        return false;
                    }

                // first db query and if else, and other functions end
            }
        });
    }
};

//this will send messages to the managers and the people who are registered in those events
//gonna be hoisted
function reportUpdate(whatToReport, req) {
    if(whatToReport.update.length < 1 && whatToReport.remove.length < 1) {return false;} //don't send any mail if there is no change
    //not using a function for e-mail sending because we need to close the connection after all stuff

    // create reusable transport method (opens pool of SMTP connections)
    var smtpTransport = Utility.smtpTransport();
    //we have an object {update:[], remove:[]}, and the update array has the these events
    var whatToSend = {},
        parallel = [];
    whatToReport.update.forEach(function(event) {
        parallel.push(function(callback) {
            event.shifts.forEach(function(shift) {
                if(_.isUndefined(whatToSend[shift.staff])) { whatToSend[shift.staff] = {remove:[], update:[]}; }
                whatToSend[shift.staff].update.push({'event': event, 'shift': shift}); //this is the structure of the array elements, be careful
            });
            callback();
        });
    });
    whatToReport.remove.forEach(function(event) {
        parallel.push(function(callback) {
            event.shifts.forEach(function(shift) {
                if(_.isUndefined(whatToSend[shift.staff])) { whatToSend[shift.staff] = {remove:[], update:[]}; }
                whatToSend[shift.staff].remove.push({'event': event, 'shift': shift}); //this is the structure of the array elements, be careful
            });
            callback();
        });
    });
    async.parallel(parallel, function() {
        //now we have a complete whatToSend object, so we can start to send notifications

        _.each(whatToSend, function(items, user) {
            var staffMailOptions = {
                from: Preferences.mail.fromString,
                to: user + "@wesleyan.edu",
                subject: "Updated Event for " + user + " (IMPORTANT)",
            };

            staffMailOptions.html = ejs.render(fs.readFileSync(__dirname + '/../views/mail/normalUpdate.ejs', 'utf8'), {'app': req.app, 'items': items});

            smtpTransport.sendMail(staffMailOptions, function(error, response) {
                if (error) {
                    console.log(error);
                } else {
                    //console.log("Message sent: " + response.message);
                }
            });
        });

    }); //end of async.parallel

    //now it's time to report all updates to the managers (all staff with level 10), with whatToReport

        //var managerList = _.where(cache.get('storeStaff'), {level:10});
        var managerList = Preferences.managerEmails;

            managerMailOptions = {
                    from: Preferences.mail.fromString,
                    subject: "General Event Update Report (IMPORTANT)",
                };

        managerMailOptions.html = ejs.render(fs.readFileSync(__dirname + '/../views/mail/managerUpdate.ejs', 'utf8'), {'app': req.app, 'items': whatToReport});
        managerList.forEach(function (manager) {
            managerMailOptions.to = manager.username + "@wesleyan.edu";
            smtpTransport.sendMail(managerMailOptions, function(error, response) {
                    if (error) {
                        console.log(error);
                    } else {
                        //console.log("Message sent: " + response.message);
                    }
                });
        });

    //smtpTransport.close(); //this should wait for the callbacks to end
} //end of reportUpdate
<|endoftext|>


<commit_before>var mongoose = require('mongoose');
var uuid = require('node-uuid');
var express = require('express');
var Item = require(__dirname + '/../models/item');
var ItemDetail = require(__dirname + '/../models/itemDetail');
var User = require(__dirname + '/../models/user');

var itemRouter = module.exports = express.Router();

// This route gets the details on an item.
// Call this route with the detailId of any posted item.
// GET /item/{itemDetailId}
itemRouter.get('/:item_id', function(req, res)
{
	ItemDetail.findById(req.params.item_id, function(err, item) {
		if (!item) res.status(404).json({msg: 'Item doesn\'t exist.'});
		else res.json(item);
	})
});

// This is the update endpoint.
// PUT /item/{itemDetailId}
itemRouter.put('/:item_id', function(req, res)
{
	ItemDetail.findById(req.params.item_id, function(err, itemDetail) {
		if (err) res.send(err);
		else if (!itemDetail) res.status(404).json({ msg: 'Item doesn\'t exist.' });
		else
		{
			Item.findOne({'linkId': itemDetail.linkId}, function(err, item)
			{
				if (!item)
				{
					res.status(404).json({ msg: 'Item doesn\'t exist.' });
					return;
				}

				if (req.body.title)
				{
					itemDetail.title = req.body.title;
					item.title = req.body.title;
				}
				if (req.body.description) itemDetail.description = req.body.description;
				if (req.body.askingPrice)
				{
					itemDetail.askingPrice = req.body.askingPrice;
					item.askingPrice = req.body.askingPrice;
				}
				if (req.body.postDate) {
					  itemDetail.postDate = req.body.postDate;
					  item.postDate = req.body.postDate;
				}
				if (req.body.displayPhoto) item.displayPhoto = req.body.displayPhoto;
				if (req.body.morePhotos)  itemDetail.morePhotos = req.body.morePhotos;
				if (req.body.preferredMethodOfContact) itemDetail.preferredMethodOfContact = req.body.preferredMethodOfContact;

				itemDetail.save(function(err) {
					if (err) res.send(err);
					else
					{
						item.save(function(err)
						{
							if (err)
								res.send(err);

							else
								res.status(200).json({ msg: 'Item detail updated.'});

						})
					}
				});
			});
		}
	});
});

itemRouter.delete('/:item_id', function(req, res) {
	ItemDetail.remove({
		_id: req.params.item_id
	}, function(err, itemDetail) {
		if (err) res.send(err);

		res.json({ msg: 'Item detail deleted.'});

		Item.findOne({'linkId': itemDetail.linkId }, function(err, item) {

			if (!item) console.log('Couldn\'t find item to delete.');

			item.remove({ _id: item._id}, function(err, item) {
				if (err) res.send(err);

				// res.json({ msg: 'Item deleted.'});
			});
		});
	});
});

// This route gets all lightweight items.
// This would eventually be built out for searching.
itemRouter.get('/', function(req, res) {
	Item.find(function(err, items){
		if (err) res.send(err);

		res.json(items);
	});
});

// Used to create an item advertisement.
// Successfully calling this route will create an itemDetail and a searchable truncated item.
itemRouter.post('/', function(req, res) {

	User.findOne({'username': req.body.sellerUserName}, function(err, foundUser) {
		if (err) res.send(err);

		var dateOfPost = Date.now(); // Get the date at the time of post.

		var linkId = uuid.v4(); // Use this ID to link

		// Create the detailed post.
		var itemDetail = new ItemDetail();
		itemDetail.title = req.body.title;
		itemDetail.linkId = linkId;
		itemDetail.displayPhoto = req.body.displayPhoto;
		itemDetail.description = req.body.description;
		itemDetail.askingPrice = req.body.askingPrice;
		itemDetail.postDate = dateOfPost;
		itemDetail.sellerUserName = req.body.sellerUserName;
		itemDetail.sellerRating = foundUser.sellerRating;
		itemDetail.sellerTransHistory = 0; // Was an empty string.
		itemDetail.sellerAverageResponse = foundUser.averageResponseInMinutes;
		itemDetail.sellerOtherItems = foundUser.itemsForSale;
		itemDetail.latitude = foundUser.locationLng;
		itemDetail.longitude = foundUser.locationLat;
		itemDetail.morePhotos = req.body.morePhotos;
		itemDetail.noOfInquiries = 0; // Starts at zero at the time of posting.
		itemDetail.preferredMethodOfContact = req.body.preferredMethodOfContact;

		itemDetail.save(function(err)
		{
			if (err) res.send(err);

				res.status(201).json({ msg: 'Item created with ID' + itemDetail._id });
		});

		// Create the light-weight version for searching that links to the details.
		var item = new Item();
		item.detailId = itemDetail._id; // Keeping detail ID for fast lookup.
		item.linkId = linkId; // We can index on the linkId once we create the index on the DB.
		item.title = req.body.title;
		item.displayPhoto = req.body.displayPhoto;
		item.askingPrice = req.body.askingPrice;
		item.postDate = dateOfPost;
		item.userName = req.body.userName;
		item.sellerRating = req.body.sellerRating;

		item.save(function(err)
		{
			if (err) res.send(err);
		});

		foundUser.itemsForSale ++;
		foundUser.save(function(err){
			// if (err) res.send(err); // I'm not sure if this will cause a problem if the response is already sent.
		});
	});
});
<commit_msg>Added DELETE endpoint for...deletions.<commit_after>var mongoose = require('mongoose');
var uuid = require('node-uuid');
var express = require('express');
var Item = require(__dirname + '/../models/item');
var ItemDetail = require(__dirname + '/../models/itemDetail');
var User = require(__dirname + '/../models/user');

var itemRouter = module.exports = express.Router();

// This route gets the details on an item.
// Call this route with the detailId of any posted item.
// GET /item/{itemDetailId}
itemRouter.get('/:item_id', function(req, res)
{
	ItemDetail.findById(req.params.item_id, function(err, item) {
		if (!item) res.status(404).json({msg: 'Item doesn\'t exist.'});
		else res.json(item);
	});
});

// This is the update endpoint.
// PUT /item/{itemDetailId}
itemRouter.put('/:item_id', function(req, res)
{
	ItemDetail.findById(req.params.item_id, function(err, itemDetail) {
		if (err) res.send(err);
		else if (!itemDetail) res.status(404).json({ msg: 'Item doesn\'t exist.' });
		else
		{
			Item.findOne({'linkId': itemDetail.linkId}, function(err, item)
			{
				if (!item)
				{
					res.status(404).json({ msg: 'Item doesn\'t exist.' });
					return;
				}

				if (req.body.title)
				{
					itemDetail.title = req.body.title;
					item.title = req.body.title;
				}
				if (req.body.description) itemDetail.description = req.body.description;
				if (req.body.askingPrice)
				{
					itemDetail.askingPrice = req.body.askingPrice;
					item.askingPrice = req.body.askingPrice;
				}
				if (req.body.postDate) {
					  itemDetail.postDate = req.body.postDate;
					  item.postDate = req.body.postDate;
				}
				if (req.body.displayPhoto) item.displayPhoto = req.body.displayPhoto;
				if (req.body.morePhotos)  itemDetail.morePhotos = req.body.morePhotos;
				if (req.body.preferredMethodOfContact) itemDetail.preferredMethodOfContact = req.body.preferredMethodOfContact;

				itemDetail.save(function(err) {
					if (err) res.send(err);
					else
					{
						item.save(function(err)
						{
							if (err)
								res.send(err);

							else
								res.status(200).json({ msg: 'Item detail updated.'});

						})
					}
				});
			});
		}
	});
});

// DELETE /item/{detailId}
itemRouter.delete('/:item_id', function(req, res) {
	ItemDetail.findById(req.params.item_id, function(err, itemDetail) {
		if (!itemDetail) res.status(404).json({msg: 'Item doesn\'t exist.'});
		else if (err) res.send(err);
		else {
			Item.findOne({'linkId': itemDetail.linkId }, function(err, item) {
				if (!item) res.status(404).json({ msg: 'Item not found.'});
				else if (err) res.send(err);
				else {
					Item.remove({ _id: item._id}, function(err, item) {
						if (err) res.send(err);
						else
						{
							ItemDetail.remove({ _id: req.params.item_id}, function(err, itemDetail){
								if (err) res.send(err);

								res.json({ msg: 'Item deleted.'});
							})
						}
					});
				}
			});
		}
	});
});

// This route gets all lightweight items.
// This would eventually be built out for searching.
itemRouter.get('/', function(req, res) {
	Item.find(function(err, items){
		if (err) res.send(err);

		res.json(items);
	});
});

// Used to create an item advertisement.
// Successfully calling this route will create an itemDetail and a searchable truncated item.
itemRouter.post('/', function(req, res) {

	User.findOne({'username': req.body.sellerUserName}, function(err, foundUser) {
		if (!foundUser) res.status(404).json({ msg: 'User doesn\'t exist.' });
		else if (err) res.send(err);
		else
		{

			var dateOfPost = Date.now(); // Get the date at the time of post.

			var linkId = uuid.v4(); // Use this ID to link

			// Create the detailed post.
			var itemDetail = new ItemDetail();
			itemDetail.title = req.body.title;
			itemDetail.linkId = linkId;
			itemDetail.displayPhoto = req.body.displayPhoto;
			itemDetail.description = req.body.description;
			itemDetail.askingPrice = req.body.askingPrice;
			itemDetail.postDate = dateOfPost;
			itemDetail.sellerUserName = req.body.sellerUserName;
			itemDetail.sellerRating = foundUser.sellerRating;
			itemDetail.sellerTransHistory = 0; // Was an empty string.
			itemDetail.sellerAverageResponse = foundUser.averageResponseInMinutes;
			itemDetail.sellerOtherItems = foundUser.itemsForSale;
			itemDetail.latitude = foundUser.locationLng;
			itemDetail.longitude = foundUser.locationLat;
			itemDetail.morePhotos = req.body.morePhotos;
			itemDetail.noOfInquiries = 0; // Starts at zero at the time of posting.
			itemDetail.preferredMethodOfContact = req.body.preferredMethodOfContact;

			itemDetail.save(function(err)
			{
				if (err) res.send(err);

					res.status(201).json({ msg: 'Item created with ID ' + itemDetail._id });
			});

			// Create the light-weight version for searching that links to the details.
			var item = new Item();
			item.detailId = itemDetail._id; // Keeping detail ID for fast lookup.
			item.linkId = linkId; // We can index on the linkId once we create the index on the DB.
			item.title = req.body.title;
			item.displayPhoto = req.body.displayPhoto;
			item.askingPrice = req.body.askingPrice;
			item.postDate = dateOfPost;
			item.userName = req.body.userName;
			item.sellerRating = req.body.sellerRating;

			item.save(function(err)
			{
				if (err) res.send(err);
			});

			foundUser.itemsForSale ++;
			foundUser.save(function(err){
				// if (err) res.send(err); // I'm not sure if this will cause a problem if the response is already sent.
			});
		}
	});
});
<|endoftext|>


<commit_before>/**
 * This file contains the common middleware used by your routes.
 *
 * Extend or replace these functions as your application requires.
 *
 * This structure is not enforced, and just a starting point. If
 * you have more middleware you may want to group it as separate
 * modules in your project's /lib directory.
 */

var _ = require('underscore');

var keystone = require('keystone');

/**
	Initialises the standard view locals

	The included layout depends on the navLinks array to generate
	the navigation in the header, you may wish to change this array
	or replace it with your own templates / logic.
*/

exports.initLocals = function(req, res, next) {

	var locals = res.locals;

	locals.navLinks = [
		{ label: '\xDCber Uns',		key: 'aboutus',		href: '/aboutus' },
		{ label: 'Galerie',		key: 'gallery',		href: '/gallery' },
		{ label: 'Kontakt',		key: 'contact',		href: '/contact' }
	];

	locals.user = req.user;

	if(req.user && req.user.canAccessKeystone){
		keystone.list('Enquiry').model.count().exec(function(err, c) {
			locals.pendingEnquiries = c;
			next();
		});
	}
	else {
		next();
	}
};

/**
	Fetches and clears the flashMessages before a view is rendered
*/

exports.flashMessages = function(req, res, next) {

	var flashMessages = {
		info: req.flash('info'),
		success: req.flash('success'),
		warning: req.flash('warning'),
		error: req.flash('error')
	};

	res.locals.messages = _.any(flashMessages, function(msgs) { return msgs.length; }) ? flashMessages : false;

	next();

};

/**
	Prevents people from accessing protected pages when they're not signed in
 */

exports.requireUser = function(req, res, next) {

	if (!req.user) {
		req.flash('error', 'Please sign in to access this page.');
		res.redirect('/keystone/signin');
	} else {
		next();
	}

};
<commit_msg>adding events to main navigation<commit_after>/**
 * This file contains the common middleware used by your routes.
 *
 * Extend or replace these functions as your application requires.
 *
 * This structure is not enforced, and just a starting point. If
 * you have more middleware you may want to group it as separate
 * modules in your project's /lib directory.
 */

var _ = require('underscore');

var keystone = require('keystone');

/**
	Initialises the standard view locals

	The included layout depends on the navLinks array to generate
	the navigation in the header, you may wish to change this array
	or replace it with your own templates / logic.
*/

exports.initLocals = function(req, res, next) {

	var locals = res.locals;

	locals.navLinks = [
		{ label: '\xDCber Uns',		key: 'aboutus',		href: '/aboutus' },
		{ label: 'Events',		key: 'events',		href: '/events' },
		{ label: 'Galerie',		key: 'gallery',		href: '/gallery' },
		{ label: 'Kontakt',		key: 'contact',		href: '/contact' }
	];

	locals.user = req.user;

	if(req.user && req.user.canAccessKeystone){
		keystone.list('Enquiry').model.count().exec(function(err, c) {
			locals.pendingEnquiries = c;
			next();
		});
	}
	else {
		next();
	}
};

/**
	Fetches and clears the flashMessages before a view is rendered
*/

exports.flashMessages = function(req, res, next) {

	var flashMessages = {
		info: req.flash('info'),
		success: req.flash('success'),
		warning: req.flash('warning'),
		error: req.flash('error')
	};

	res.locals.messages = _.any(flashMessages, function(msgs) { return msgs.length; }) ? flashMessages : false;

	next();

};

/**
	Prevents people from accessing protected pages when they're not signed in
 */

exports.requireUser = function(req, res, next) {

	if (!req.user) {
		req.flash('error', 'Please sign in to access this page.');
		res.redirect('/keystone/signin');
	} else {
		next();
	}

};
<|endoftext|>


<commit_before>(function () {
  'use strict';

  module.exports = function (gulp, plugins, config) {
    return function () {
      var source = gulp.src([config.patternsPath + '/**/*.scss', config.templatesPath + '/scss/**/*.scss'])
        .pipe(plugins.plumber({ errorHandler: plugins.notify.onError('Error: <%= error.message %>') }))
        .pipe(plugins.sourcemaps.init())
        .pipe(plugins.sass())
        .pipe(plugins.autoprefixer({
          browsers: ['last 5 Chrome versions',
                     'last 5 Firefox versions',
                     'Safari >= 9',
                     'ie >= 9',
                     'Edge >= 1',
                     'iOS >= 8',
                     'Android >= 4.4']
        }))
        .pipe(plugins.postcss([plugins.postcssFlexibility()]))
      ;

      var max = source.pipe(plugins.clone())
        .pipe(plugins.sourcemaps.write('.', { sourceRoot: null }))
        .pipe(gulp.dest(config.buildCssPath))
      ;

      var min = source.pipe(plugins.clone())
        .pipe(plugins.sourcemaps.init())
        .pipe(plugins.rename({ suffix: '.min' }))
        .pipe(plugins.postcss([plugins.cssnano()]))
        .pipe(plugins.size(config.sizeOptions))
        .pipe(plugins.sourcemaps.write('.', { sourceRoot: null }))
        .pipe(gulp.dest(config.buildCssPath))
        .pipe(plugins.browserSync.stream({ match: '**/*.css' }))
      ;

      return plugins.mergeStream(max, min);
    };
  };
})();
<commit_msg>feat(Build): Extend Autoprefixer browser support.<commit_after>(function () {
  'use strict';

  module.exports = function (gulp, plugins, config) {
    return function () {
      var source = gulp.src([config.patternsPath + '/**/*.scss', config.templatesPath + '/scss/**/*.scss'])
        .pipe(plugins.plumber({ errorHandler: plugins.notify.onError('Error: <%= error.message %>') }))
        .pipe(plugins.sourcemaps.init())
        .pipe(plugins.sass())
        .pipe(plugins.autoprefixer({
          browsers: ['last 10 Chrome versions',
                     'last 10 Firefox versions',
                     'Safari >= 9',
                     'ie >= 9',
                     'Edge >= 1',
                     'iOS >= 8',
                     'Android >= 4.4']
        }))
        .pipe(plugins.postcss([plugins.postcssFlexibility()]))
      ;

      var max = source.pipe(plugins.clone())
        .pipe(plugins.sourcemaps.write('.', { sourceRoot: null }))
        .pipe(gulp.dest(config.buildCssPath))
      ;

      var min = source.pipe(plugins.clone())
        .pipe(plugins.sourcemaps.init())
        .pipe(plugins.rename({ suffix: '.min' }))
        .pipe(plugins.postcss([plugins.cssnano()]))
        .pipe(plugins.size(config.sizeOptions))
        .pipe(plugins.sourcemaps.write('.', { sourceRoot: null }))
        .pipe(gulp.dest(config.buildCssPath))
        .pipe(plugins.browserSync.stream({ match: '**/*.css' }))
      ;

      return plugins.mergeStream(max, min);
    };
  };
})();
<|endoftext|>


<commit_before>/**
 * Created by Nicolas on 3/19/2016.
 */
var express = require('express');
var router = express.Router();
var async = require('async');
var Property = require('../models/property');
var RoomType = require('../models/roomType');
var User = require('../models/user');

/* GET properties listing. */
router.get('/', function(req, res) {
    // get all the properties
    Property.find({}, function(err, properties) {
        if (err) {
            res.status(500);
            res.send();
        } else {
            res.send(properties);
        }
    });
});

router.get('/:property_id', function(req, res){
    var property_id = req.params.property_id;
    Property.findById(property_id).populate('user').exec(function(err, property) {
        if(!property) {
            res.status(404);
            res.send();
        } else {
            res.send(property);
        }

    });
});

router.get('/user/:user_id', function(req, res){
    var user_id = req.params.user_id;
    Property.find({'user':user_id}, function(err, properties) {
        if(!properties) {
            res.status(404);
            res.send();
        } else {
            res.send(properties);
        }

    });
});

router.post('/', function(req, res) {
    data = req.body;
    var user_id = data.user_id;
    User.findById(user_id, function(err,user) {
        if(!user) {
            res.status(404);
            res.send();
        } else {
            var property = new Property({
                name: data.name,
                addressLine1: data.addressLine1,
                addressLine2: data.addressLine2,
                zipCode: data.zipCode,
                city: data.city,
                user:user
            });

            property.save(function(err) {
                if(err){
                    res.status(400);
                    res.send();
                } else {
                    property.user = property.user._id;
                    console.log(property.user);
                    res.send(property);
                }
            });
        }
    });

});

router.delete('/:property_id', function(req, res) {
    var property_id = req.params.property_id;
    Property.findById(property_id, function(err, property) {
        if(!property){
            res.status(404);
        } else {
            property.remove(function(err) {
                if(err){
                    res.status(500);
                } else {
                    res.status(201);
                }
            });
        }
        res.send();
    });

});

module.exports = router;<commit_msg>added put on properties<commit_after>/**
 * Created by Nicolas on 3/19/2016.
 */
var express = require('express');
var router = express.Router();
var async = require('async');
var Property = require('../models/property');
var RoomType = require('../models/roomType');
var User = require('../models/user');

/* GET properties listing. */
router.get('/', function(req, res) {
    // get all the properties
    Property.find({}, function(err, properties) {
        if (err) {
            res.status(500);
            res.send();
        } else {
            res.send(properties);
        }
    });
});

router.get('/:property_id', function(req, res){
    var property_id = req.params.property_id;
    Property.findById(property_id, function(err, property) {
        if(!property) {
            res.status(404);
            res.send();
        } else {
            res.send(property);
        }

    });
});

router.get('/user/:user_id', function(req, res){
    var user_id = req.params.user_id;
    Property.find({'user':user_id}, function(err, properties) {
        if(!properties) {
            res.status(404);
            res.send();
        } else {
            res.send(properties);
        }

    });
});

router.post('/', function(req, res) {
    data = req.body;
    var user_id = data.user_id;
    User.findById(user_id, function(err,user) {
        if(!user) {
            res.status(404);
            res.send();
        } else {
            var property = new Property({
                name: data.name,
                addressLine1: data.addressLine1,
                addressLine2: data.addressLine2,
                zipCode: data.zipCode,
                city: data.city,
                user:user
            });

            property.save(function(err) {
                if(err){
                    res.status(400);
                    res.send();
                } else {
                    property.user = property.user._id;
                    res.send(property);
                }
            });
        }
    });

});

router.put('/', function (req,res) {
    data = req.body;
    var property_id = data.property_id;
    Property.findById(property_id,function(err,property) {
        if(!property) {
            res.status(404);
            res.send();
        } else {
            property.name = data.name;
            property.addressLine1 = data.addressLine1;
            property.addressLine2 = data.addressLine2;
            property.city = data.city;
            property.zip = data.zip;

            property.save(function (err) {
                if (err) {
                    res.status(500);
                    res.send();
                } else {
                    res.send(property);
                }
            })
        }
    });
});

router.delete('/:property_id', function(req, res) {
    var property_id = req.params.property_id;
    Property.findById(property_id, function(err, property) {
        if(!property){
            res.status(404);
        } else {
            property.remove(function(err) {
                if(err){
                    res.status(500);
                } else {
                    res.status(201);
                }
            });
        }
        res.send();
    });

});

module.exports = router;<|endoftext|>


<commit_before>var keystone = require('keystone');

exports = module.exports = function (req, res) {

	var view = new keystone.View(req, res);
	var locals = res.locals;

    // locals.section is used to set the currently selected
    // item in the header navigation.
	locals.section = 'home';

	view.on('init', function (next) {

		keystone.list('Project').model.count({ type: 'project' }, function (err, count) {
			if (err) {
				locals.projects_count = 0;
			} else {
				locals.projects_count = count;
			}
			keystone.list('Project').model.count({ type: 'workshop' }, function (err, count) {
				if (err) {
					locals.workshops_count = 0;
				} else {
					locals.workshops_count = count;
				}
				keystone.list('Project').model.count({ type: 'event' }, function (err, count) {
					if (err) {
						locals.events_count = 0;
					} else {
						locals.events_count = count;
					}
					keystone.list('User').model.count(function (err, count) {
						if (err) {
							locals.members_count = 0;
						} else {
							locals.members_cVount = count;
						}
						var q = keystone.list('Project').model.find().where('state', 'completed').sort('-publishedDate');

						q.exec(function (err, results) {
							locals.projects = results;
							next();
						});
					});
				});
			});
		});
	});

    // Render the view
	view.render('home');
};
<commit_msg>Added limit 4<commit_after>var keystone = require('keystone');

exports = module.exports = function (req, res) {

	var view = new keystone.View(req, res);
	var locals = res.locals;

    // locals.section is used to set the currently selected
    // item in the header navigation.
	locals.section = 'home';

	view.on('init', function (next) {

		keystone.list('Project').model.count({ type: 'project' }, function (err, count) {
			if (err) {
				locals.projects_count = 0;
			} else {
				locals.projects_count = count;
			}
			keystone.list('Project').model.count({ type: 'workshop' }, function (err, count) {
				if (err) {
					locals.workshops_count = 0;
				} else {
					locals.workshops_count = count;
				}
				keystone.list('Project').model.count({ type: 'event' }, function (err, count) {
					if (err) {
						locals.events_count = 0;
					} else {
						locals.events_count = count;
					}
					keystone.list('User').model.count(function (err, count) {
						if (err) {
							locals.members_count = 0;
						} else {
							locals.members_cVount = count;
						}
						var q = keystone.list('Project').model.find().where('state', 'completed').sort('-publishedDate').limit(4);

						q.exec(function (err, results) {
							locals.projects = results;
							next();
						});
					});
				});
			});
		});
	});

    // Render the view
	view.render('home');
};
<|endoftext|>


<commit_before>/* global prettyPrint */
(function($) {
	"use strict";

	var $window = $(window),
		$kssMenu = $(".kss___nav"),
		$kssMenuItems = $kssMenu.find(".kss___nav__item"),
		$kssMenuActiveItem = $kssMenuItems.eq($kssMenu.data("kss-activemenuindex")),
		$kssMenuSub = $(".kss___navSub"),
		$kssMenuSubItems = $kssMenuSub.find(".kss___navSub__item"),
		$kssContentWrapper = $('.kss___contentWrapper'),
		kssMenuStickyClass = "kss___nav--sticky",
		kssMenuSubActiveClass = "kss___navSub__item--active",
		kssMenuOffset = $kssMenu.offset().top,
		urlHash = window.location.hash,
		scrollBuffer = false,

		scrollSpy = function () {
			var scrollTop = $window.scrollTop(),
				$kssMenuSubAnchors = $kssMenuSub.find("a"),
				currentTargetHash,
				activeIndex;

			// Get the new index for the new active subMenuItem.
			$kssMenuSubAnchors.each(function (index) {
				var anchorHash = $(this).attr("href"),
					$anchorTarget = $(anchorHash.replace(/\./g, "\\.")),
					offsetTop = $anchorTarget.offset().top,
					offsetBottom = offsetTop + $anchorTarget.outerHeight(true);

				if (offsetTop <= scrollTop && scrollTop < offsetBottom) {
					activeIndex = index;
					currentTargetHash = anchorHash;
				}
			});

			// Set the active class on the subMenuItem.
			$kssMenuSubItems.removeClass(kssMenuSubActiveClass);
			if (typeof activeIndex !== "undefined") {
				$kssMenuSubItems.eq(activeIndex).addClass(kssMenuSubActiveClass);
				if(urlHash !== currentTargetHash) {
					history.replaceState(null, null, currentTargetHash);
					urlHash = currentTargetHash;
				}
			} else if(scrollTop < $($kssMenuSubAnchors.eq(0).attr("href").replace(/\./g, "\\.")).offset().top) {
				$kssMenuSubItems.eq(0).addClass(kssMenuSubActiveClass);
			}

			// Validate if the sideNav should be sticky or not.
			if(scrollTop > kssMenuOffset) {
				$kssMenu.addClass(kssMenuStickyClass);
			} else {
				$kssMenu.removeClass(kssMenuStickyClass);
			}
		},
		formatTemplate = function() {
			$('.kss-box').each(function(index, elem) {
				var $this = $(elem),
					isPureCodeMarker = '<!= isPureCode !>',
					boxHtml = $this.html(),
					isPureCode = boxHtml.search(isPureCodeMarker);

				if(isPureCode > 1) {
					$this.html(boxHtml.replace(isPureCodeMarker, '')).parent().addClass('kss___hideExamples');
				}
			});
		};

	// Add the active class for the current item in the sideMenu.
	$kssMenuActiveItem.addClass("kss___nav__item--active");

	// Format the template.
	formatTemplate();

	if ($kssMenuSub.length) {
		// Add the menu depth classes for each item.
		$kssMenuSubItems.each(function(index, elem) {
			var $this = $(elem),
				$referenceNum = $this.find('.kss___navSub__item__ref'),
				depth = $referenceNum.html().split('.').length;
			$this.addClass('kss___navSub__item--' + depth);
		});

		// Append the subMenu of the current item into the sideMenu.
		$kssMenuSub.appendTo(".kss___nav__item--active");

		// Set the active class on the current item.
		scrollSpy();
		$window.on("scroll", function() {
			if (!scrollBuffer) {
				scrollBuffer = setTimeout(function () {
					scrollSpy();
					scrollBuffer = false;
				}, 60);
			}
		});
	}

	// Set the height of the sideNav as a min-height on the contentWrapper.
	$kssContentWrapper.css("min-height", $kssMenu.height());

	// Ensure code blocks are highlighted properly...
	$('pre>code').addClass('prettyprint');
	prettyPrint();
})(jQuery);
<commit_msg>[MISC] Create an initialize fn for the styleguide js code<commit_after>/* global prettyPrint */
(function($) {
	"use strict";

	var $window = $(window),
		$kssMenu = $(".kss___nav"),
		$kssMenuItems = $kssMenu.find(".kss___nav__item"),
		$kssMenuActiveItem = $kssMenuItems.eq($kssMenu.data("kss-activemenuindex")),
		$kssMenuSub = $(".kss___navSub"),
		$kssMenuSubItems = $kssMenuSub.find(".kss___navSub__item"),
		$kssContentWrapper = $('.kss___contentWrapper'),
		kssMenuStickyClass = "kss___nav--sticky",
		kssMenuSubActiveClass = "kss___navSub__item--active",
		kssMenuOffset = $kssMenu.offset().top,
		urlHash = window.location.hash,
		scrollBuffer = false,

		init = function() {
			// Add the active class for the current item in the sideMenu.
			$kssMenuActiveItem.addClass("kss___nav__item--active");

			// Format the template.
			formatTemplate();

			if ($kssMenuSub.length) {
				// Add the menu depth classes for each item.
				$kssMenuSubItems.each(function(index, elem) {
					var $this = $(elem),
						$referenceNum = $this.find('.kss___navSub__item__ref'),
						depth = $referenceNum.html().split('.').length;
					$this.addClass('kss___navSub__item--' + depth);
				});

				// Append the subMenu of the current item into the sideMenu.
				$kssMenuSub.appendTo(".kss___nav__item--active");

				// Set the active class on the current item.
				scrollSpy();
				$window.on("scroll", function() {
					if (!scrollBuffer) {
						scrollBuffer = setTimeout(function () {
							scrollSpy();
							scrollBuffer = false;
						}, 60);
					}
				});
			}

			// Set the height of the sideNav as a min-height on the contentWrapper.
			$kssContentWrapper.css("min-height", $kssMenu.height());

			// Ensure code blocks are highlighted properly...
			$('pre>code').addClass('prettyprint');
			prettyPrint();
		},

		scrollSpy = function () {
			var scrollTop = $window.scrollTop(),
				$kssMenuSubAnchors = $kssMenuSub.find("a"),
				currentTargetHash,
				activeIndex;

			// Get the new index for the new active subMenuItem.
			$kssMenuSubAnchors.each(function (index) {
				var anchorHash = $(this).attr("href"),
					$anchorTarget = $(anchorHash.replace(/\./g, "\\.")),
					offsetTop = $anchorTarget.offset().top,
					offsetBottom = offsetTop + $anchorTarget.outerHeight(true);

				if (offsetTop <= scrollTop && scrollTop < offsetBottom) {
					activeIndex = index;
					currentTargetHash = anchorHash;
				}
			});

			// Set the active class on the subMenuItem.
			$kssMenuSubItems.removeClass(kssMenuSubActiveClass);
			if (typeof activeIndex !== "undefined") {
				$kssMenuSubItems.eq(activeIndex).addClass(kssMenuSubActiveClass);
				if(urlHash !== currentTargetHash) {
					history.replaceState(null, null, currentTargetHash);
					urlHash = currentTargetHash;
				}
			} else if(scrollTop < $($kssMenuSubAnchors.eq(0).attr("href").replace(/\./g, "\\.")).offset().top) {
				$kssMenuSubItems.eq(0).addClass(kssMenuSubActiveClass);
			}

			// Validate if the sideNav should be sticky or not.
			if(scrollTop > kssMenuOffset) {
				$kssMenu.addClass(kssMenuStickyClass);
			} else {
				$kssMenu.removeClass(kssMenuStickyClass);
			}
		},
		formatTemplate = function() {
			$('.kss-box').each(function(index, elem) {
				var $this = $(elem),
					isPureCodeMarker = '<!= isPureCode !>',
					boxHtml = $this.html(),
					isPureCode = boxHtml.search(isPureCodeMarker);

				if(isPureCode > 1) {
					$this.html(boxHtml.replace(isPureCodeMarker, '')).parent().addClass('kss___hideExamples');
				}
			});
		};

	init();

})(jQuery);
<|endoftext|>


<commit_before><commit_msg>build-unicode.js: added script to generate the unicode character for each icon<commit_after><|endoftext|>


<commit_before>import React, { Component } from 'react'

import globalConfig from '../../config'

import { fetchLocation, fetchOrganization } from '../../core/firebaseRestAPI'

import Layout from '../../components/Layout'
import Loading from '../../components/Loading'
import Location from '../../components/Location'

export default class LocationPage extends Component {
  constructor(props) {
    super(props)
    this.state = {
      location: null,
      organization: null,
    }
  }

  componentDidMount() {
    const match = this.props.route.pattern.exec(window.location.pathname)
    const locationId = match[1]

    fetchLocation(locationId)
      .then(location => {
        this.setState({ location })
      })
    fetchOrganization(location.organizationId)
      .then(organization => {
        this.setState({ organization })
      })
  }

  componentDidUpdate() {
    const { location } = this.state
    document.title = location ? location.name : globalConfig.title
  }

  render() {
    const { location, organization } = this.state

    return (
      <Layout>
        {(location && organization) ?
          <Location location={location} organization={organization} /> :
          <Loading />
        }
      </Layout>
    )
  }
}
<commit_msg>Load orgs inside location promise<commit_after>import React, { Component } from 'react'

import globalConfig from '../../config'

import { fetchLocation, fetchOrganization } from '../../core/firebaseRestAPI'

import Layout from '../../components/Layout'
import Loading from '../../components/Loading'
import Location from '../../components/Location'

export default class LocationPage extends Component {
  constructor(props) {
    super(props)
    this.state = {
      location: null,
      organization: null,
    }
  }

  componentDidMount() {
    const match = this.props.route.pattern.exec(window.location.pathname)
    const locationId = match[1]

    fetchLocation(locationId)
      .then(location => {
        this.setState({ location })
        fetchOrganization(location.organizationId)
          .then(organization => {
            this.setState({ organization })
          })
      })
  }

  componentDidUpdate() {
    const { location } = this.state
    document.title = location ? location.name : globalConfig.title
  }

  render() {
    const { location, organization } = this.state

    return (
      <Layout>
        {(location && organization) ?
          <Location location={location} organization={organization} /> :
          <Loading />
        }
      </Layout>
    )
  }
}
<|endoftext|>


<commit_before>/*global jake */
var async = require('async'),
    build = require('./lib/build'),
    cssTestRunner = require('./lib/css-test-runner'),
    glob = require('glob'),
    growl = require('growl'),
    packageGenerator = require('./lib/package-generator'),
    server = require('./lib/server'),
    sourceMap = require('./lib/source-map'),
    testRunner = require('./lib/test-runner'),
    wrench = require('wrench');

exports.build = function(options) {
  options.lumbarFile = options.lumbarFile || exports.lumbarFile;
  build.build(options);
};
exports.startServer = function(options) {
  options.projectDir = exports.projectDir;
  options.forceCORS = exports.forceCORS;
  return server.start(options);
};
exports.watch = function(server, mocks, test, compiled) {
  glob.sync('build/dev').forEach(wrench.rmdirSyncRecursive);

  var run;
  exports.startServer({
    test: test,
    proxy: server,
    mocks: mocks,
    data: function() {
      if (run) {
        return;
      }
      run = true;

      exports.build({
        dir: 'build/dev',
        sourceMap: true,
        watch: true,
        compiled: compiled,
        server: exports.buildServer,
        complete: function(code) {
          process.exit(code);
        }
      });
    },
    complete: function(code) {
      process.exit(code);
    }
  });
};

desc('The default task. Executes init');
task('default', ['lumbar'], function() {});

desc('Process all lumbar modules.');
task('lumbar', [], function() {
  exports.build({
    dir: 'build/dev',
    sourceMap: true,
    server: exports.buildServer,
    complete: function(code) {
      if (code) {
        console.error('Build failed with code ' + code);
        process.exit(code);
      } else {
        complete();
      }
    }
  });
}, true);

desc('Watches for build changes without a server instance.');
task('lumbar-watch', [], function() {
  exports.build({
    dir: 'build/dev',
    sourceMap: true,
    watch: true,
    server: exports.buildServer,
    complete: function(code) {
      process.exit(code);
    }
  });
}, true);

desc('Builds production packages');
task('release', [], function(prefix, pkg, branch) {
  prefix = prefix || 'phoenix';

  exports.build({
    dir: 'build/' + prefix,
    package: pkg,
    minimize: true,
    server: exports.buildServer,
    removeTests: true,
    sourceMap: 'build/source-map/' + prefix,
    configFile: './config/production.json',
    complete: function(code) {
      if (code) {
        process.exit(code);
      } else {
        if (exports.generatePackage) {
          packageGenerator.generate('./package.json', branch, 'build/' + prefix + '/package.json', function(err) {
            if (err) {
              throw err;
            }
            complete();
          });
        } else {
          complete();
        }
      }
    }
  });
});

desc('Cleans any generated content out of the application');
task('clean', [], function() {
  glob.sync('build').forEach(wrench.rmdirSyncRecursive);
});

desc('Builds the app in production test mode.');
task('heroku-test', [], function() {
  exports.build({
    dir: 'build/test',
    minimize: true,
    configFile: './config/production.json',
    complete: complete
  });
}, true);

desc('Initializes the file change watcher for stylus scripts');
task('watch', [], function(server, mocks) {
  exports.watch((exports.serverName || function() {}).apply(exports, arguments), mocks);
});

desc('Starts up the server in normal mode');
task('start', [], function(server, mocks) {
  exports.startServer({proxy: exports.serverName.apply(exports, arguments), mocks: mocks});
});

desc('Testing');
task('test-runner', [], function(webOnly, xunit) {
  var options = {
    projectDir: exports.projectDir,
    forceCORS: exports.forceCORS,
    testPlatforms: exports.testPlatforms,
    mochaTests: exports.mochaTests,
    webOnly: webOnly,
    xunit: xunit
  };
  testRunner.run(options);
});

desc('Testing');
task('css-test-runner', [], function(webOnly) {
  var options = {
    projectDir: exports.projectDir,
    forceCORS: exports.forceCORS,
    testPlatforms: exports.testPlatforms,
    webOnly: webOnly
  };
  cssTestRunner.run(options);
});

desc('Runs both builds and tests in response to watch changes.');
task('test-watch', [], function(server, mocks) {
  var queue = async.queue(function(task, callback) { task(callback); }, 1);
  exports.watch((exports.serverName || function() {}).apply(exports, arguments), mocks, true, function(module) {
    var options = {
      projectDir: exports.projectDir,
      forceCORS: exports.forceCORS,
      testPlatforms: exports.testPlatforms,
      mochaTests: exports.mochaTests,
      webOnly: true,
      module: module,
    };
    queue.push(function(callback) {
      // Cleanup any junk content that we might have
      sourceMap.reset();

      testRunner.run(options, function(code) {
        if (code) {
          growl('Test ' + module + ' failed: ' + code, { title: 'Test Failed', sticky: true });
        }
        callback();
      });
    });
  });
});

desc('Testing');
task('test', ['lumbar', 'test-runner'], function() {});
desc('Testing');
task('css-test', ['lumbar', 'css-test-runner'], function() {});

task('test-xunit', ['lumbar'], function() {
  jake.Task['test-runner'].invoke(undefined, true);
});
<commit_msg>Allow custom devdir<commit_after>/*global jake */
var async = require('async'),
    build = require('./lib/build'),
    cssTestRunner = require('./lib/css-test-runner'),
    glob = require('glob'),
    growl = require('growl'),
    packageGenerator = require('./lib/package-generator'),
    server = require('./lib/server'),
    sourceMap = require('./lib/source-map'),
    testRunner = require('./lib/test-runner'),
    wrench = require('wrench');

exports.devDir = 'build/dev';

exports.build = function(options) {
  options.lumbarFile = options.lumbarFile || exports.lumbarFile;
  build.build(options);
};
exports.startServer = function(options) {
  options.projectDir = exports.projectDir;
  options.forceCORS = exports.forceCORS;
  return server.start(options);
};
exports.watch = function(server, mocks, test, compiled) {
  glob.sync(exports.devDir).forEach(wrench.rmdirSyncRecursive);

  var run;
  exports.startServer({
    test: test,
    proxy: server,
    mocks: mocks,
    data: function() {
      if (run) {
        return;
      }
      run = true;

      exports.build({
        dir: exports.devDir,
        sourceMap: true,
        watch: true,
        compiled: compiled,
        server: exports.buildServer,
        complete: function(code) {
          process.exit(code);
        }
      });
    },
    complete: function(code) {
      process.exit(code);
    }
  });
};

desc('The default task. Executes init');
task('default', ['lumbar'], function() {});

desc('Process all lumbar modules.');
task('lumbar', [], function() {
  exports.build({
    dir: exports.devDir,
    sourceMap: true,
    server: exports.buildServer,
    complete: function(code) {
      if (code) {
        console.error('Build failed with code ' + code);
        process.exit(code);
      } else {
        complete();
      }
    }
  });
}, true);

desc('Watches for build changes without a server instance.');
task('lumbar-watch', [], function() {
  exports.build({
    dir: exports.devDir,
    sourceMap: true,
    watch: true,
    server: exports.buildServer,
    complete: function(code) {
      process.exit(code);
    }
  });
}, true);

desc('Builds production packages');
task('release', [], function(prefix, pkg, branch) {
  prefix = prefix || 'phoenix';

  exports.build({
    dir: 'build/' + prefix,
    package: pkg,
    minimize: true,
    server: exports.buildServer,
    removeTests: true,
    sourceMap: 'build/source-map/' + prefix,
    configFile: './config/production.json',
    complete: function(code) {
      if (code) {
        process.exit(code);
      } else {
        if (exports.generatePackage) {
          packageGenerator.generate('./package.json', branch, 'build/' + prefix + '/package.json', function(err) {
            if (err) {
              throw err;
            }
            complete();
          });
        } else {
          complete();
        }
      }
    }
  });
});

desc('Cleans any generated content out of the application');
task('clean', [], function() {
  glob.sync('build').forEach(wrench.rmdirSyncRecursive);
});

desc('Builds the app in production test mode.');
task('heroku-test', [], function() {
  exports.build({
    dir: 'build/test',
    minimize: true,
    configFile: './config/production.json',
    complete: complete
  });
}, true);

desc('Initializes the file change watcher for stylus scripts');
task('watch', [], function(server, mocks) {
  exports.watch((exports.serverName || function() {}).apply(exports, arguments), mocks);
});

desc('Starts up the server in normal mode');
task('start', [], function(server, mocks) {
  exports.startServer({proxy: exports.serverName.apply(exports, arguments), mocks: mocks});
});

desc('Testing');
task('test-runner', [], function(webOnly, xunit) {
  var options = {
    projectDir: exports.projectDir,
    forceCORS: exports.forceCORS,
    testPlatforms: exports.testPlatforms,
    mochaTests: exports.mochaTests,
    webOnly: webOnly,
    xunit: xunit
  };
  testRunner.run(options);
});

desc('Testing');
task('css-test-runner', [], function(webOnly) {
  var options = {
    projectDir: exports.projectDir,
    forceCORS: exports.forceCORS,
    testPlatforms: exports.testPlatforms,
    webOnly: webOnly
  };
  cssTestRunner.run(options);
});

desc('Runs both builds and tests in response to watch changes.');
task('test-watch', [], function(server, mocks) {
  var queue = async.queue(function(task, callback) { task(callback); }, 1);
  exports.watch((exports.serverName || function() {}).apply(exports, arguments), mocks, true, function(module) {
    var options = {
      projectDir: exports.projectDir,
      forceCORS: exports.forceCORS,
      testPlatforms: exports.testPlatforms,
      mochaTests: exports.mochaTests,
      webOnly: true,
      module: module,
    };
    queue.push(function(callback) {
      // Cleanup any junk content that we might have
      sourceMap.reset();

      testRunner.run(options, function(code) {
        if (code) {
          growl('Test ' + module + ' failed: ' + code, { title: 'Test Failed', sticky: true });
        }
        callback();
      });
    });
  });
});

desc('Testing');
task('test', ['lumbar', 'test-runner'], function() {});
desc('Testing');
task('css-test', ['lumbar', 'css-test-runner'], function() {});

task('test-xunit', ['lumbar'], function() {
  jake.Task['test-runner'].invoke(undefined, true);
});
<|endoftext|>