<commit_before>var express = require('express');
var bodyParser = require('body-parser');
var Facility = require('../models/facility');
var Field = require('../models/field');
var FieldSize = require('../models/fieldSize');
var async = require('async');
var Verify = require('./verify');

var router = express.Router();
router.use(bodyParser.json());

//#################################################################################################
//#################################################################################################
router.route('/')

//get all facilities:
.get(function(req, res, next) {
    Facility.find(req.query)
        .sort({ name: 'asc' })
        .populate('club_affiliation')
        .populate({
             path: 'fields',
             model: 'Field',
             populate: {
               path: 'size',
               model: 'FieldSize'
             }
          })
        .populate('closures')
        .exec(function(err, facilities) {
            if(err) throw err;
            res.json(facilities);
    });
})

//add a new facility to the system:
.post(Verify.verifyOrdinaryUser, function(req, res, next) {
    Facility.create(req.body, function(err, facility) {
        if(err) return next(err);
        console.log("New facility created");
        res.json(facility);
    });
})

.delete(Verify.verifyOrdinaryUser, function(req, res, next) {
    Facility.remove({}, function(err, facilities) {
        if(err) return next(err);
        console.log("Removed: \n" + facilities);
        res.json("All facilities removed.");
    });
});

//#################################################################################################
//#################################################################################################
router.route('/:facilityId')

///GET facility by ID
.get(Verify.verifyOrdinaryUser, function(req, res, next) {
    Facility.findById(req.params.facilityId)
        .populate('club_affiliation')
        .populate({
             path: 'fields',
             model: 'Field',
             populate: {
               path: 'size',
               model: 'FieldSize'
             }
          })
        .populate('closures')
        .exec(function(err, facility) {
            if(err) throw err;
            res.json(facility);
    });
})

//PUT update facility by ID
.put(Verify.verifyOrdinaryUser, function(req, res, next) {
    Facility.findByIdAndUpdate(req.params.facilityId, {$set: req.body}, {new: true})
        .exec(function(err, facility) {
            if(err) throw err;
            res.json(facility);
    });
})

///DELETE facility by ID
.delete(Verify.verifyOrdinaryUser, function(req, res, next) {
    Facility.findById(req.params.facilityId)
        .exec(function(err, facility) {
            if(err) throw err;
            facility.remove();
            res.json("Successfully removed facility " + facility.name);
    });
});

//#################################################################################################
//#################################################################################################
router.route('/addField/:facilityId/:fieldId')

///PUT add a field to a facility by ID
.put(Verify.verifyOrdinaryUser, function(req, res, next) {
    async.waterfall(
        [
            function(callback) {
                Facility.findById(req.params.facilityId)
                    .populate('club_affiliation')
                    .populate({
                         path: 'fields',
                         model: 'Field',
                         populate: {
                           path: 'size',
                           model: 'FieldSize'
                         }
                      })
                    .populate('closures')
                    .exec(function(err, facility) {
                        if(err) throw err;
                        callback(null, facility);
                });

            },
            function(facility, callback) {
                //add the facility id to the field and save the field:
                Field.findByIdAndUpdate(req.params.fieldId, {$set: {facility: facility._id}}, {new: true})
                    .exec(function(err, field) {
                        if(err) throw err;
                        callback(null, facility, field);
                });
            },
            function(facility, field, callback) {
                console.log("attempting to put field: " + field);
                console.log("into facility: " + facility);
                //now, push the field into the facility and save it.
                facility.fields.push(field);
                facility.save()
                    .then(function(facility) {
                    console.log("Successfully saved " + facility);
                    callback(null, facility);
                },function(errResponse) {
                    console.log("Here is where it all falls down " + errResponse);
                });
            }
        ],
        function(err, facility) {
            if(err) return next(err);
            res.json(facility);
        }
    )
});

//#################################################################################################
//#################################################################################################
router.route('/closeFacility/:facilityId/:closureId')

///PUT close this facility and all of its fields based on the facility closure
.put(Verify.verifyOrdinaryUser, function(req, res, next) {

    async.waterfall(
        [
            function(callback) {
                Facility.findById(req.params.facilityId)
                    .populate('club_affiliation')
                    .populate({
                         path: 'fields',
                         model: 'Field',
                         populate: {
                           path: 'size',
                           model: 'FieldSize'
                         }
                      })
                    .populate('closures')
                    .exec(function(err, facility) {
                        if(err) throw err;
                        callback(null, facility);
                });
            },
            function(facility, callback) {
                var count = facility.fields.length;
                var flds = facility.fields;
                var newFields = [];

                console.log("will now update " + count + " fields");

                async.forEach(flds, function(fld, callback) {
                    Field.findById(fld._id)
                        .exec(function(err, field) {
                            if(err) throw err;
                            field.closures.push(req.params.closureId);
                            field.save(function(err, field) {
                                if(err) return next(err);
                                newFields.push(field);
                                callback();
                            });
                    });
                }, function(err) {
                    if (err) return next(err);
                    facility.fields = newFields;
                    callback(null, facility);
                });
            },
            function(facility, callback) {
                facility.closures.push(req.params.closureId);
                facility.save(function(err, facility) {
                    if(err) return next(err);
                    callback(null, facility);
                })
            }
        ],
        function(err, facility) {
            res.json(facility);
        }
    )
});

//#################################################################################################
//#################################################################################################
router.route('/deleteAllClosures/:facilityId')

///PUT remove all closures for this facility and all of its fields
.put(Verify.verifyOrdinaryUser, function(req, res, next) {

    async.waterfall(
        [
            function(callback) {
                Facility.findById(req.params.facilityId)
                    .populate('club_affiliation')
                    .populate({
                         path: 'fields',
                         model: 'Field',
                         populate: {
                           path: 'size',
                           model: 'FieldSize'
                         }
                      })
                    .populate('closures')
                    .exec(function(err, facility) {
                        if(err) throw err;
                        callback(null, facility);
                });
            },
            function(facility, callback) {
                var count = facility.fields.length;
                var flds = facility.fields;
                var newFields = [];

                console.log("will now update " + count + " fields");

                async.forEach(flds, function(fld, callback) {
                    Field.findById(fld._id)
                        .exec(function(err, field) {
                            if(err) throw err;
                            field.closures = [];
                            field.save(function(err, field) {
                                if(err) return next(err);
                                newFields.push(field);
                                callback();
                            });
                    });
                }, function(err) {
                    if (err) return next(err);
                    facility.fields = newFields;
                    callback(null, facility);
                });
            },
            function(facility, callback) {
                facility.closures = [];
                facility.save(function(err, facility) {
                    if(err) return next(err);
                    callback(null, facility);
                })
            }
        ],
        function(err, facility) {
            res.json(facility);
        }
    )
});

//#################################################################################################
//#################################################################################################
router.route('/openFacility/:facilityId')

///PUT open all of this facility's fields
.put(Verify.verifyOrdinaryUser, function(req, res, next) {
    //first, get all closures for this facility, find any that have a start time less than current and an end time greater than current.
    //if so, change end time to current.
    async.waterfall(
        [
            function(callback) {
                Facility.findById(req.params.facilityId)
                    .populate('club_affiliation')
                    .populate({
                         path: 'fields',
                         model: 'Field',
                         populate: {
                           path: 'size',
                           model: 'FieldSize'
                         }
                      })
                    .populate('closures')
                    .exec(function(err, facility) {
                        if(err) throw err;
                        var now = new Date().getTime();
                        //iterate through any closures, find any that are current, and change their end time to current time
                        console.log("Facility has " + facility.closures.length + " closures");
                        for(var i = 0; i < facility.closures.length; i++) {
                            console.log("for first closure, comparing start time of " + facility.closures[i].start + " and end time of " + facility.closures[i].end + " with current time: " + now);
                            if(facility.closures[i].start < now && facility.closures[i].end > now) {
                                console.log("Closure is current, changing end time from " + facility.closures[i].end + " to " + now);
                                facility.closures[i].end = now;
                            }
                        }
                        callback(null, facility);
                });
            },
            function(facility, callback) {
                //now grab all fields for the facility and do the same:
                var count = facility.fields.length;
                var flds = facility.fields;
                var newFields = [];

                console.log("will now update " + count + " fields");

                async.forEach(flds, function(fld, callback) {
                    Field.findById(fld._id)
                        .exec(function(err, field) {
                            if(err) throw err;
                            var now = new Date().getTime();
                            //iterate through any closures, find any that are current, and change their end time to current time
                            console.log("Field has " + field.closures.length + " closures");
                            for(var i = 0; i < field.closures.length; i++) {
                                console.log("for first closure, comparing start time of " + field.closures[i].start + " and end time of " + field.closures[i].end + " with current time: " + now);
                                if(field.closures[i].start < now && field.closures[i].end > now) {
                                    console.log("Closure is current, changing end time from " + field.closures[i].end + " to " + now);
                                    field.closures[i].end = now;
                                }
                            }
                            field.save(function(err, field) {
                                if(err) return next(err);
                                newFields.push(field);
                                callback();
                            });
                    });
                }, function(err) {
                    if (err) return next(err);
                    facility.fields = newFields;
                    callback(null, facility);
                });
            },
            function(facility, callback) {
                facility.save(function(err, facility) {
                    if(err) return next(err);
                    callback(null, facility);
                })
            }
        ],
        function(err, facility) {
            res.json(facility);
        }
    )
});

module.exports = router;<commit_msg>corrections to openFacility route<commit_after>var express = require('express');
var bodyParser = require('body-parser');
var Facility = require('../models/facility');
var Field = require('../models/field');
var Closure = require('../models/closure');
var FieldSize = require('../models/fieldSize');
var async = require('async');
var Verify = require('./verify');

var router = express.Router();
router.use(bodyParser.json());

//#################################################################################################
//#################################################################################################
router.route('/')

//get all facilities:
.get(function(req, res, next) {
    Facility.find(req.query)
        .sort({ name: 'asc' })
        .populate('club_affiliation')
        .populate({
             path: 'fields',
             model: 'Field',
             populate: {
               path: 'size',
               model: 'FieldSize'
             }
          })
        .populate('closures')
        .exec(function(err, facilities) {
            if(err) throw err;
            res.json(facilities);
    });
})

//add a new facility to the system:
.post(Verify.verifyOrdinaryUser, function(req, res, next) {
    Facility.create(req.body, function(err, facility) {
        if(err) return next(err);
        console.log("New facility created");
        res.json(facility);
    });
})

.delete(Verify.verifyOrdinaryUser, function(req, res, next) {
    Facility.remove({}, function(err, facilities) {
        if(err) return next(err);
        console.log("Removed: \n" + facilities);
        res.json("All facilities removed.");
    });
});

//#################################################################################################
//#################################################################################################
router.route('/:facilityId')

///GET facility by ID
.get(Verify.verifyOrdinaryUser, function(req, res, next) {
    Facility.findById(req.params.facilityId)
        .populate('club_affiliation')
        .populate({
             path: 'fields',
             model: 'Field',
             populate: {
               path: 'size',
               model: 'FieldSize'
             }
          })
        .populate('closures')
        .exec(function(err, facility) {
            if(err) throw err;
            res.json(facility);
    });
})

//PUT update facility by ID
.put(Verify.verifyOrdinaryUser, function(req, res, next) {
    Facility.findByIdAndUpdate(req.params.facilityId, {$set: req.body}, {new: true})
        .exec(function(err, facility) {
            if(err) throw err;
            res.json(facility);
    });
})

///DELETE facility by ID
.delete(Verify.verifyOrdinaryUser, function(req, res, next) {
    Facility.findById(req.params.facilityId)
        .exec(function(err, facility) {
            if(err) throw err;
            facility.remove();
            res.json("Successfully removed facility " + facility.name);
    });
});

//#################################################################################################
//#################################################################################################
router.route('/addField/:facilityId/:fieldId')

///PUT add a field to a facility by ID
.put(Verify.verifyOrdinaryUser, function(req, res, next) {
    async.waterfall(
        [
            function(callback) {
                Facility.findById(req.params.facilityId)
                    .populate('club_affiliation')
                    .populate({
                         path: 'fields',
                         model: 'Field',
                         populate: {
                           path: 'size',
                           model: 'FieldSize'
                         }
                      })
                    .populate('closures')
                    .exec(function(err, facility) {
                        if(err) throw err;
                        callback(null, facility);
                });

            },
            function(facility, callback) {
                //add the facility id to the field and save the field:
                Field.findByIdAndUpdate(req.params.fieldId, {$set: {facility: facility._id}}, {new: true})
                    .exec(function(err, field) {
                        if(err) throw err;
                        callback(null, facility, field);
                });
            },
            function(facility, field, callback) {
                console.log("attempting to put field: " + field);
                console.log("into facility: " + facility);
                //now, push the field into the facility and save it.
                facility.fields.push(field);
                facility.save()
                    .then(function(facility) {
                    console.log("Successfully saved " + facility);
                    callback(null, facility);
                },function(errResponse) {
                    console.log("Here is where it all falls down " + errResponse);
                });
            }
        ],
        function(err, facility) {
            if(err) return next(err);
            res.json(facility);
        }
    )
});

//#################################################################################################
//#################################################################################################
router.route('/closeFacility/:facilityId/:closureId')

///PUT close this facility and all of its fields based on the facility closure
.put(Verify.verifyOrdinaryUser, function(req, res, next) {

    async.waterfall(
        [
            function(callback) {
                Facility.findById(req.params.facilityId)
                    .populate('club_affiliation')
                    .populate({
                         path: 'fields',
                         model: 'Field',
                         populate: {
                           path: 'size',
                           model: 'FieldSize'
                         }
                      })
                    .populate('closures')
                    .exec(function(err, facility) {
                        if(err) throw err;
                        callback(null, facility);
                });
            },
            function(facility, callback) {
                var count = facility.fields.length;
                var flds = facility.fields;
                var newFields = [];

                console.log("will now update " + count + " fields");

                async.forEach(flds, function(fld, callback) {
                    Field.findById(fld._id)
                        .exec(function(err, field) {
                            if(err) throw err;
                            field.closures.push(req.params.closureId);
                            field.save(function(err, field) {
                                if(err) return next(err);
                                newFields.push(field);
                                callback();
                            });
                    });
                }, function(err) {
                    if (err) return next(err);
                    facility.fields = newFields;
                    callback(null, facility);
                });
            },
            function(facility, callback) {
                facility.closures.push(req.params.closureId);
                facility.save(function(err, facility) {
                    if(err) return next(err);
                    callback(null, facility);
                })
            }
        ],
        function(err, facility) {
            res.json(facility);
        }
    )
});

//#################################################################################################
//#################################################################################################
router.route('/deleteAllClosures/:facilityId')

///PUT remove all closures for this facility and all of its fields
.put(Verify.verifyOrdinaryUser, function(req, res, next) {

    async.waterfall(
        [
            function(callback) {
                Facility.findById(req.params.facilityId)
                    .populate('club_affiliation')
                    .populate({
                         path: 'fields',
                         model: 'Field',
                         populate: {
                           path: 'size',
                           model: 'FieldSize'
                         }
                      })
                    .populate('closures')
                    .exec(function(err, facility) {
                        if(err) throw err;
                        callback(null, facility);
                });
            },
            function(facility, callback) {
                var count = facility.fields.length;
                var flds = facility.fields;
                var newFields = [];

                console.log("will now update " + count + " fields");

                async.forEach(flds, function(fld, callback) {
                    Field.findById(fld._id)
                        .exec(function(err, field) {
                            if(err) throw err;
                            field.closures = [];
                            field.save(function(err, field) {
                                if(err) return next(err);
                                newFields.push(field);
                                callback();
                            });
                    });
                }, function(err) {
                    if (err) return next(err);
                    facility.fields = newFields;
                    callback(null, facility);
                });
            },
            function(facility, callback) {
                facility.closures = [];
                facility.save(function(err, facility) {
                    if(err) return next(err);
                    callback(null, facility);
                })
            }
        ],
        function(err, facility) {
            res.json(facility);
        }
    )
});

//#################################################################################################
//#################################################################################################
router.route('/openFacility/:facilityId')

///PUT open all of this facility's fields
.put(Verify.verifyOrdinaryUser, function(req, res, next) {
    //first, get all closures for this facility, find any that have a start time less than current and an end time greater than current.
    //if so, change end time to current.
    async.waterfall(
        [
            function(callback) {
                Facility.findById(req.params.facilityId)
                    .populate('club_affiliation')
                    .populate({
                         path: 'fields',
                         model: 'Field',
                         populate: {
                           path: 'size',
                           model: 'FieldSize'
                         }
                      })
                    .populate('closures')
                    .exec(function(err, facility) {
                        if(err) throw err;
                        var now = new Date().getTime();
                        var affectedClosureIds = [];
                        //iterate through any closures, find any that are current, add them to an array
                        console.log("Facility has " + facility.closures.length + " closures");
                        for(var i = 0; i < facility.closures.length; i++) {
                            console.log("for first closure, comparing start time of " + facility.closures[i].start + " and end time of " + facility.closures[i].end + " with current time: " + now);
                            if(facility.closures[i].start < now && facility.closures[i].end > now) {
                                console.log("Closure is current, changing end time from " + facility.closures[i].end + " to " + now);
                                affectedClosureIds.push(facility.closures[i]._id);
                            }
                        }
                        callback(null, facility, affectedClosureIds);
                });
            },
            function(facility, affectedClosures, callback) {
                //now grab all fields for the facility and do the same:
                var count = affectedClosures.length;

                console.log("will now update " + count + " closures");

                async.forEach(affectedClosures, function(closure, callback) {
                    Closure.findById(closure)
                        .exec(function(err, clos) {
                            if(err) throw err;
                            var now = new Date().getTime();
                            clos.end = now;
                            clos.save(function(err, closure) {
                                if(err) return next(err);
                                callback();
                            });
                    });
                }, function(err) {
                    if (err) return next(err);
                    callback(null, facility);
                });
            },
            function(facility, callback) {
                facility.save(function(err, facility) {
                    if(err) return next(err);
                    callback(null, facility);
                })
            }
        ],
        function(err, facility) {
            res.json(facility);
        }
    )
});

module.exports = router;<|endoftext|>


<commit_before>var express = require('express');
var bodyParser = require('body-parser');
var Facility = require('../models/facility');
var Field = require('../models/field');
var FieldSize = require('../models/fieldSize');
var async = require('async');
var Verify = require('./verify');

var router = express.Router();
router.use(bodyParser.json());

//#################################################################################################
//#################################################################################################
router.route('/')

//get all facilities:
.get(function(req, res) {
    Facility.find({})
        .populate('club_affiliation')
        .populate({
             path: 'fields',
             model: 'Field',
             populate: {
               path: 'size',
               model: 'FieldSize'
             }
          })
        .exec(function(err, facilities) {
            if(err) throw err;
            res.json(facilities);
    });
})

//add a new facility to the system:
.post(Verify.verifyOrdinaryUser, function(req, res, next) {
    Facility.create(req.body, function(err, facility) {
        if(err) return next(err);
        console.log("New facility created");
        res.json(facility);
    });
})

.delete(Verify.verifyOrdinaryUser, function(req, res, next) {
    Facility.remove({}, function(err, facilities) {
        if(err) return next(err);
        console.log("Removed: \n" + facilities);
        res.json("All facilities removed.");
    });
});

//#################################################################################################
//#################################################################################################
router.route('/:facilityId')

///GET facility by ID
.get(Verify.verifyOrdinaryUser, function(req, res) {
    Facility.findById(req.params.facilityId)
        .populate('club_affiliation')
        .populate({
             path: 'fields',
             model: 'Field',
             populate: {
               path: 'size',
               model: 'FieldSize'
             }
          })
        .exec(function(err, facility) {
            if(err) throw err;
            res.json(facility);
    });
})

//PUT update facility by ID
.put(Verify.verifyOrdinaryUser, function(req, res) {
    Facility.findByIdAndUpdate(req.params.facilityId, {$set: req.body}, {new: true})
        .exec(function(err, facility) {
            if(err) throw err;
            res.json(facility);
    });
})

///DELETE facility by ID
.delete(Verify.verifyOrdinaryUser, function(req, res) {
    Facility.findById(req.params.facilityId)
        .exec(function(err, facility) {
            if(err) throw err;
            facility.remove();
            res.json("Successfully removed facility " + facility.name);
    });
});

//#################################################################################################
//#################################################################################################
router.route('/addField/:facilityId/:fieldId')

///POST add a field to a facility by ID
.post(Verify.verifyOrdinaryUser, function(req, res, next) {
    async.waterfall(
        [
            function(callback) {
                Facility.findById(req.params.facilityId)
                    .populate('club_affiliation')
                    .populate({
                         path: 'fields',
                         model: 'Field',
                         populate: {
                           path: 'size',
                           model: 'FieldSize'
                         }
                      })
                    .exec(function(err, facility) {
                        if(err) throw err;
                        callback(null, facility);
                });

            },
            function(facility, callback) {
                //add the facility id to the field and save the field:
                Field.findByIdAndUpdate(req.params.fieldId, {$set: {facility: facility._id}}, {new: true})
                    .exec(function(err, field) {
                        if(err) throw err;
                        callback(null, facility, field);
                });
            },
            function(facility, field, callback) {
                console.log("attempting to put field: " + field);
                console.log("into facility: " + facility);
                //now, push the field into the facility and save it.
                facility.fields.push(field);
                facility.save()
                    .then(function(facility) {
                    console.log("Successfully saved " + facility);
                    callback(null, facility);
                },function(errResponse) {
                    console.log("Here is where it all falls down " + errResponse);
                });
            }
        ],
        function(err, facility) {
            if(err) return next(err);
            res.json(facility);
        }
    )
});

//#################################################################################################
//#################################################################################################
router.route('/closeFields/:facilityId')

///POST close all of this facility's fields based on the facility closure
.post(Verify.verifyOrdinaryUser, function(req, res, next) {

    async.waterfall(
        [
            function(callback) {
                Facility.findById(req.params.facilityId)
                    .populate('club_affiliation')
                    .populate({
                         path: 'fields',
                         model: 'Field',
                         populate: {
                           path: 'size',
                           model: 'FieldSize'
                         }
                      })
                    .exec(function(err, facility) {
                        if(err) throw err;
                        callback(null, facility);
                });
            },
            function(facility, callback) {
                var count = facility.fields.length;
                var flds = facility.fields;
                var newFields = [];

                console.log("will now update " + count + " fields");

                async.forEach(flds, function(fld, callback) {
                    Field.findByIdAndUpdate(fld._id,
                            {$set:
                                {
                                    closure: facility.closure,
                                    closure_type: facility.closure_type,
                                    close_start: facility.close_start,
                                    close_end: facility.close_end
                                }
                             }, {new: true})
                        .exec(function(err, field) {
                            if(err) throw err;
                            newFields.push(field);
                            callback();
                    });
                }, function(err) {
                    if (err) return next(err);
                    callback(null, newFields);
                });
            }
        ],
        function(err, facility) {
            res.json(facility);
        }
    )
});

module.exports = router;<commit_msg>modified /facilities/closeFields to /facilities/closeFacility, added /openFacility<commit_after>var express = require('express');
var bodyParser = require('body-parser');
var Facility = require('../models/facility');
var Field = require('../models/field');
var FieldSize = require('../models/fieldSize');
var async = require('async');
var Verify = require('./verify');

var router = express.Router();
router.use(bodyParser.json());

//#################################################################################################
//#################################################################################################
router.route('/')

//get all facilities:
.get(function(req, res) {
    Facility.find({})
        .populate('club_affiliation')
        .populate({
             path: 'fields',
             model: 'Field',
             populate: {
               path: 'size',
               model: 'FieldSize'
             }
          })
        .exec(function(err, facilities) {
            if(err) throw err;
            res.json(facilities);
    });
})

//add a new facility to the system:
.post(Verify.verifyOrdinaryUser, function(req, res, next) {
    Facility.create(req.body, function(err, facility) {
        if(err) return next(err);
        console.log("New facility created");
        res.json(facility);
    });
})

.delete(Verify.verifyOrdinaryUser, function(req, res, next) {
    Facility.remove({}, function(err, facilities) {
        if(err) return next(err);
        console.log("Removed: \n" + facilities);
        res.json("All facilities removed.");
    });
});

//#################################################################################################
//#################################################################################################
router.route('/:facilityId')

///GET facility by ID
.get(Verify.verifyOrdinaryUser, function(req, res) {
    Facility.findById(req.params.facilityId)
        .populate('club_affiliation')
        .populate({
             path: 'fields',
             model: 'Field',
             populate: {
               path: 'size',
               model: 'FieldSize'
             }
          })
        .exec(function(err, facility) {
            if(err) throw err;
            res.json(facility);
    });
})

//PUT update facility by ID
.put(Verify.verifyOrdinaryUser, function(req, res) {
    Facility.findByIdAndUpdate(req.params.facilityId, {$set: req.body}, {new: true})
        .exec(function(err, facility) {
            if(err) throw err;
            res.json(facility);
    });
})

///DELETE facility by ID
.delete(Verify.verifyOrdinaryUser, function(req, res) {
    Facility.findById(req.params.facilityId)
        .exec(function(err, facility) {
            if(err) throw err;
            facility.remove();
            res.json("Successfully removed facility " + facility.name);
    });
});

//#################################################################################################
//#################################################################################################
router.route('/addField/:facilityId/:fieldId')

///POST add a field to a facility by ID
.post(Verify.verifyOrdinaryUser, function(req, res, next) {
    async.waterfall(
        [
            function(callback) {
                Facility.findById(req.params.facilityId)
                    .populate('club_affiliation')
                    .populate({
                         path: 'fields',
                         model: 'Field',
                         populate: {
                           path: 'size',
                           model: 'FieldSize'
                         }
                      })
                    .exec(function(err, facility) {
                        if(err) throw err;
                        callback(null, facility);
                });

            },
            function(facility, callback) {
                //add the facility id to the field and save the field:
                Field.findByIdAndUpdate(req.params.fieldId, {$set: {facility: facility._id}}, {new: true})
                    .exec(function(err, field) {
                        if(err) throw err;
                        callback(null, facility, field);
                });
            },
            function(facility, field, callback) {
                console.log("attempting to put field: " + field);
                console.log("into facility: " + facility);
                //now, push the field into the facility and save it.
                facility.fields.push(field);
                facility.save()
                    .then(function(facility) {
                    console.log("Successfully saved " + facility);
                    callback(null, facility);
                },function(errResponse) {
                    console.log("Here is where it all falls down " + errResponse);
                });
            }
        ],
        function(err, facility) {
            if(err) return next(err);
            res.json(facility);
        }
    )
});

//#################################################################################################
//#################################################################################################
router.route('/closeFacility/:facilityId')

///PUT close this facility and all of its fields based on the facility closure
.put(Verify.verifyOrdinaryUser, function(req, res, next) {

    async.waterfall(
        [
            function(callback) {
                Facility.findByIdAndUpdate(req.params.facilityId, {$set: req.body}, {new: true})
                    .populate('club_affiliation')
                    .populate({
                         path: 'fields',
                         model: 'Field',
                         populate: {
                           path: 'size',
                           model: 'FieldSize'
                         }
                      })
                    .exec(function(err, facility) {
                        if(err) throw err;
                        callback(null, facility);
                });
            },
            function(facility, callback) {
                var count = facility.fields.length;
                var flds = facility.fields;
                var newFields = [];

                console.log("will now update " + count + " fields");

                async.forEach(flds, function(fld, callback) {
                    Field.findByIdAndUpdate(fld._id,
                            {$set:
                                {
                                    closure: facility.closure,
                                    closure_type: facility.closure_type,
                                    close_start: facility.close_start,
                                    close_end: facility.close_end
                                }
                             }, {new: true})
                        .exec(function(err, field) {
                            if(err) throw err;
                            newFields.push(field);
                            callback();
                    });
                }, function(err) {
                    if (err) return next(err);
                    facility.fields = newFields;
                    callback(null, facility);
                });
            }
        ],
        function(err, facility) {
            res.json(facility);
        }
    )
});

//#################################################################################################
//#################################################################################################
router.route('/openFacility/:facilityId')

///PUT open all of this facility's fields
.put(Verify.verifyOrdinaryUser, function(req, res, next) {

    async.waterfall(
        [
            function(callback) {
                Facility.findByIdAndUpdate(req.params.facilityId, {$set:
                                {
                                    closure: false,
                                    closure_type: "",
                                    close_start: 0,
                                    close_end: 0
                                }
                             }, {new: true})
                    .populate('club_affiliation')
                    .populate({
                         path: 'fields',
                         model: 'Field',
                         populate: {
                           path: 'size',
                           model: 'FieldSize'
                         }
                      })
                    .exec(function(err, facility) {
                        if(err) throw err;
                        callback(null, facility);
                });
            },
            function(facility, callback) {
                var count = facility.fields.length;
                var flds = facility.fields;
                var newFields = [];

                console.log("will now update " + count + " fields");

                async.forEach(flds, function(fld, callback) {
                    Field.findByIdAndUpdate(fld._id,
                            {$set:
                                {
                                    closure: false,
                                    closure_type: "",
                                    close_start: 0,
                                    close_end: 0
                                }
                             }, {new: true})
                        .exec(function(err, field) {
                            if(err) throw err;
                            newFields.push(field);
                            callback();
                    });
                }, function(err) {
                    if (err) return next(err);
                    facility.fields = newFields;
                    callback(null, facility);
                });
            }
        ],
        function(err, facility) {
            res.json(facility);
        }
    )
});

module.exports = router;<|endoftext|>


<commit_before>var setlistVisualizer = (function(){
	'use strict';

	var width = 900,
		height = 400,
		verticalPadding = 60,
		horizontalPadding = 30,
		datePrefix = "2014-08-13T",
		dateSuffix = ":00+0200";

	function getDate(timeString) {
		return new Date(timeString+dateSuffix);
	}

	function timeToNumber(timeString){
		var hours = parseInt(timeString.split(":")[0], 10) +
					(parseInt(timeString.split(":")[1])/60);
		var yPos = Math.floor(Math.pow(hours, 5)/10000);
		console.log("yPos: "+ yPos);
		return yPos;
	}

	var chart = function(selection){
		selection.each(function(data) {

			// stage names for ordinal scale
			// and earlierst- and latest play times
			var stageNames = [],
				earlierstTime = data.stages[0].bands[0].from,
				latestTime = data.stages[0].bands[0].until;

			data.stages.forEach(function(stage, i){
				stageNames.push(stage.stage);
				stage.bands.forEach(function(band, j){
					if(band.from < earlierstTime) {
						earlierstTime = band.from;
					}
					if(band.until > latestTime) {
						latestTime = band.until;
					}
				});
			});
			console.log("stages: "+stageNames);
			console.log("earlierstTime: "+earlierstTime);
			console.log("latestTime: "+latestTime);

			var minDate = getDate(earlierstTime),
				maxDate = getDate(latestTime);

			// scales and axis
			var yScale = d3.time.scale()
								.domain([minDate, maxDate])
								.range([1, height]),

				xScale = d3.scale.ordinal()
								.domain(stageNames)
								.rangeBands([1, width]),

				yAxis = d3.svg.axis()
								.scale(yScale)
								.orient("left")
								.ticks(d3.time.hours, 2)
								.tickFormat(d3.time.format('%H:%M')),

				xAxis = d3.svg.axis()
								.scale(xScale)
								.orient('top');

			var getPositionX = function(stage){
				return xScale(stage.stage);

			}, getPositionY = function(d){
				console.log( "y date: "+ getDate(d.from) );
				console.log( "y scale: "+ yScale(getDate(d.from)) );
				return yScale(getDate(d.from));

			}, getWidth = function (d) {
				return xScale.rangeBand();

			}, getHeight = function (d) {
				var dateFrom = getDate(d.from),
				dateUntil = getDate(d.until);
				return yScale(dateUntil.getTime()) - yScale(dateFrom.getTime());

			}, calcForegroundColor = function(backgroundColor){
				var rgb = backgroundColor.match(/.{1,2}/g),
					brightness = calcBrightness(rgb[0], rgb[1], rgb[2]);

				console.log(backgroundColor +": "+rgb+" : "+brightness);
				return (brightness < 130) ? '#FFF' : '#000';

			}, calcBrightness = function(r, g, b){
				r = parseInt(r, 16);
				g = parseInt(g, 16);
				b = parseInt(b, 16);
				return Math.sqrt(
					r * r * 0.299 +
					g * g * 0.587 +
					b * b * 0.114);

			}, getFill = function(d){
				var hexColor = Math.floor(Math.random()*16777215).toString(16);
				d.textColor = calcForegroundColor(hexColor); // precalc
				return '#'+hexColor;

			}, getTextColor = function(d){
				return d.textColor; // get precalc value
			};

			// svg container
			var svg = selection.append("svg")
				.attr("width", width + verticalPadding*2)
				.attr("height", height + horizontalPadding*2)
				.style("border", "1px solid black");

			// axis group
			var yAxisGroup = svg.append("g")
								.attr('class', 'yaxis axis')
								.attr(
									"transform",
									"translate("+verticalPadding+","+horizontalPadding+")"
								)
								.call(yAxis),

				xAxisGroup = yAxisGroup.append('g')
								.attr('class', 'xaxis axis')
								.call(xAxis);

			// stages
			data.stages.forEach(function(stage, i){
				console.log(stage);

				// band slots
				var slots = yAxisGroup.selectAll(".slot")
								.data(stage.bands)
								.enter()
								.append("g")
								.attr('class', 'slot')
								.attr("transform",
									function(d, i) {
										return "translate("+
											getPositionX(stage)+
											","+
											getPositionY(d)+
											")";
									});

				var rectangle = slots.append("rect")
					.transition().duration(500)
					.attr("width", getWidth)
					.attr("height", getHeight)
					.style("fill", getFill);

				slots.append("text")
					.attr('class', 'bandname')
					.attr('dx', 10)
					.attr('dy', 18)
					.attr('fill', getTextColor)
					.text(function(d) { return d.band; });
			});
			console.log("/stages");
		});
	};

	return chart;
})();<commit_msg>more cleanup<commit_after>var setlistVisualizer = (function(){
	'use strict';

	var width = 900,
		height = 400,
		verticalPadding = 60,
		horizontalPadding = 30,
		datePrefix = "2014-08-13T",
		dateSuffix = ":00+0200";

	function getDate(timeString) {
		return new Date(timeString+dateSuffix);
	}

	function timeToNumber(timeString){
		var hours = parseInt(timeString.split(":")[0], 10) +
					(parseInt(timeString.split(":")[1])/60);
		var yPos = Math.floor(Math.pow(hours, 5)/10000);
		console.log("yPos: "+ yPos);
		return yPos;
	}

	var drawChart = function(data, selection){
		// stage names for ordinal scale
		// and earlierst- and latest play times
		var stageNames = [],
			earlierstTime = data.stages[0].bands[0].from,
			latestTime = data.stages[0].bands[0].until;

		data.stages.forEach(function(stage, i){
			stageNames.push(stage.stage);
			stage.bands.forEach(function(band, j){
				if(band.from < earlierstTime) {
					earlierstTime = band.from;
				}
				if(band.until > latestTime) {
					latestTime = band.until;
				}
			});
		});
		console.log("stages: "+stageNames);
		console.log("earlierstTime: "+earlierstTime);
		console.log("latestTime: "+latestTime);

		var minDate = getDate(earlierstTime),
			maxDate = getDate(latestTime);

		// scales and axis
		var yScale = d3.time.scale()
							.domain([minDate, maxDate])
							.range([1, height]),

			xScale = d3.scale.ordinal()
							.domain(stageNames)
							.rangeBands([1, width]),

			yAxis = d3.svg.axis()
							.scale(yScale)
							.orient("left")
							.ticks(d3.time.hours, 2)
							.tickFormat(d3.time.format('%H:%M')),

			xAxis = d3.svg.axis()
							.scale(xScale)
							.orient('top');

		var getPositionX = function(stage){
			return xScale(stage.stage);

		}, getPositionY = function(d){
			return yScale(getDate(d.from));

		}, getWidth = function (d) {
			return xScale.rangeBand();

		}, getHeight = function (d) {
			var dateFrom = getDate(d.from),
			dateUntil = getDate(d.until);
			return yScale(dateUntil.getTime()) - yScale(dateFrom.getTime());

		}, calcForegroundColor = function(backgroundColor){
			var rgb = backgroundColor.match(/.{1,2}/g),
				brightness = calcBrightness(rgb[0], rgb[1], rgb[2]);

			//console.log(backgroundColor +": "+rgb+" : "+brightness);
			return (brightness < 130) ? '#FFF' : '#000';

		}, calcBrightness = function(r, g, b){
			r = parseInt(r, 16);
			g = parseInt(g, 16);
			b = parseInt(b, 16);
			return Math.sqrt(
				r * r * 0.299 +
				g * g * 0.587 +
				b * b * 0.114);

		}, getFill = function(d){
			var hexColor = Math.floor(Math.random()*16777215).toString(16);
			d.textColor = calcForegroundColor(hexColor); // precalc
			return '#'+hexColor;

		}, getTextColor = function(d){
			return d.textColor; // get precalc value
		};

		// svg container
		var svg = selection.append("svg")
			.attr("width", width + verticalPadding*2)
			.attr("height", height + horizontalPadding*2)
			.style("border", "1px solid black");

		// axis group
		var yAxisGroup = svg.append("g")
							.attr('class', 'yaxis axis')
							.attr(
								"transform",
								"translate("+verticalPadding+","+horizontalPadding+")"
							)
							.call(yAxis),

			xAxisGroup = yAxisGroup.append('g')
							.attr('class', 'xaxis axis')
							.call(xAxis);

		// stages
		data.stages.forEach(function(stage, i){
			console.log(stage);

			// band slots
			var slots = yAxisGroup.selectAll(".slot")
							.data(stage.bands)
							.enter()
							.append("g")
							.attr('class', 'slot')
							.attr("transform",
								function(d, i) {
									return "translate("+
										getPositionX(stage)+
										","+
										getPositionY(d)+
										")";
								});

			var rectangle = slots.append("rect")
				.transition().duration(500)
				.attr("width", getWidth)
				.attr("height", getHeight)
				.style("fill", getFill);

			slots.append("text")
				.attr('class', 'bandname')
				.attr('dx', 10)
				.attr('dy', 18)
				.attr('fill', getTextColor)
				.text(function(d) { return d.band; });
		});
		console.log("/stages");
	};

	/**
	 * public chart exposure
	 * @param  {Object} selection a dom selection
	 */
	var chart = function(selection){
		selection.each(function(data){
			drawChart(data, selection);
		});
	};

	return chart;
})();<|endoftext|>


<commit_before>var expect = require('chai').expect;
var request = require('supertest')('http://localhost:5000');
var db = require('../database');
var users = db.get('users');
var posts = db.get('posts');

describe('API', function () {
  var testuser;
  var otheruser;
  before(function () {
    users.findOne({apiKey: 'thetestuserapikey'}, function (err, doc) {
      testuser = doc;
    });
    users.findOne({apiKey: 'theotheruserapikey'}, function (err, doc) {
      otheruser = doc;
    });
  });

  describe('Authentication', function () {
    it('should allow access without api key', function (done) {
      request.get('/').expect(200, done);
    });
    it('should not allow access with an invalid api key', function (done) {
      request.get('/?api_key=notavalidapikey').expect(403, done);
    });
    it('should allow access with api key via GET parameter api_key', function (done) {
      request.get('/?api_key=thetestuserapikey').expect(200, done);
    });
    it('should allow access with api key via GET parameter apiKey', function (done) {
      request.get('/?apiKey=thetestuserapikey').expect(200, done);
    });

    it('should redirect /auth/google to Google oAuth2', function (done) {
      request.get('/auth/google').expect(302, function (err, res) {
        expect(res.header['location']).to.match(/^https:\/\/accounts.google.com\/o\/oauth2\/auth/);
        done(err);
      });
    });
    it('should redirect /auth/facebook to Facebook oAuth2', function (done) {
      request.get('/auth/facebook').expect(302, function (err, res) {
        expect(res.header['location']).to.match(/^https:\/\/www.facebook.com\/dialog\/oauth/);
        done(err);
      });
    });
//    it('should redirect /auth/twitter to Twitter oAuth1'); //, function (done) {
//      request.get('/auth/twitter').expect(302, function (err, res) {
//        expect(res.header['location']).to.match(/^https:\/\/www.twitter.com\//);
//        done(err);
//      })
//    })
  });

  describe('/posts', function () {
    it('should create a new post and return it on POST', function (done) {
      request.post('/posts/?apiKey=thetestuserapikey').send({
        lat: 13,
        long: 37,
        message: 'Testmessage'
      }).expect(200, function (err, res) {
        var post = res.body;
        expect(post.user).to.equal(testuser._id.toString());
        expect(post.lat).to.equal(13);
        expect(post.long).to.equal(37);
        expect(post.message).to.equal('Testmessage');
        expect(post._id).to.exist;
        done(err);
      });
    });
    it('should not create a new post with missing parameter "lat" on POST', function (done) {
      request.post('/posts/?apiKey=thetestuserapikey').send({
        long: 37,
        message: 'Testmessage'
      }).expect(400, done);
    });
    it('should not create a new post with missing parameter "long" on POST', function (done) {
      request.post('/posts/?apiKey=thetestuserapikey').send({
        lat: 13,
        message: 'Testmessage'
      }).expect(400, done)
    });
    it('should not create a new post with missing parameter "message" on POST', function (done) {
      request.post('/posts/?apiKey=thetestuserapikey').send({
        lat: 13,
        long: 37
      }).expect(400, done);
    });
    it('should not create a new post with parameter "lat" bigger than 90', function (done) {
      request.post('/posts/?apiKey=thetestuserapikey').send({
        lat: 90.1,
        long: 37,
        message: 'Testmessage'
      }).expect(400, done);
    });
    it('should not create a new post with parameter "lat" smaller than -90', function (done) {
      request.post('/posts/?apiKey=thetestuserapikey').send({
        lat: -90.1,
        long: 37,
        message: 'Testmessage'
      }).expect(400, done);
    });
    it('should not create a new post with parameter "long" bigger than 180', function (done) {
      request.post('/posts/?apiKey=thetestuserapikey').send({
        lat: 13,
        long: 180.1,
        message: 'Testmessage'
      }).expect(400, done);
    });
    it('should not create a new post with parameter "long" smaller than -180', function (done) {
      request.post('/posts/?apiKey=thetestuserapikey').send({
        lat: 13,
        long: -180.1,
        message: 'Testmessage'
      }).expect(400, done);
    });
    it('should not create a new post without an api key', function (done) {
      request.post('/posts/').send({
        lat: 13,
        long: 37,
        message: 'Testmessage'
      }).expect(403, done);
    });
  });
  describe('/posts/:id', function () {
    var my_post_id;
    var other_post_id;
    before(function (done) {
      request.post('/posts/?apiKey=thetestuserapikey').send({
        lat: 42,
        long: 21,
        message: 'Testmessage'
      }).end(function (err, res) {
        if (err) {
          done(err);
        } else {
          my_post_id = res.body._id;
          request.post('/posts/?apiKey=theotheruserapikey').send({
            lat: 47,
            long: 11,
            message: 'Testmessage'
          }).end(function (err, res) {
            other_post_id = res.body._id;
            done(err);
          });
        }
      });
    });

    it('should delete own posts on HTTP DELETE /posts/:id', function (done) {
//      console.log(my_post_id);
//      console.log(other_post_id);
      request.delete('/posts/' + my_post_id + '?apiKey=thetestuserapikey').expect(204, function (err, res) {
        if (err) {
          done(err);
        } else {
          posts.findOne({'_id': my_post_id}, function (err, doc) {
            expect(doc).to.not.exist;
            done(err);
          });
        }
      });
    });
    it('should forbid deleting foreign posts on HTTP DELETE /posts/:id', function (done) {
      request.delete('/posts/' + other_post_id + '?apiKey=thetestuserapikey').expect(403, function (err, res) {
        if (err) {
          done(err);
        } else {
          posts.findOne({'_id': other_post_id}, function (err, doc) {
            expect(doc).to.exist;
            done(err);
          });
        }
      });
    });
    it('should forbid deleting posts on HTTP DELETE /posts/:id without api key', function (done) {
      request.delete('/posts/' + other_post_id).expect(403, function (err, res) {
        if (err) {
          done(err);
        } else {
          posts.findOne({'_id': other_post_id}, function (err, doc) {
            expect(doc).to.exist;
            done(err);
          });
        }
      });
    });
    it('should return a post on HTTP GET /posts/:id with api key', function (done) {
      request.get('/posts/' + other_post_id + '?apiKey=thetestuserapikey').expect(200, function (err, res) {
        var post = res.body;
        expect(post.lat).to.equal(47);
        expect(post.long).to.equal(11);
        expect(post.message).to.equal('Testmessage');
        expect(post._id).to.exist;
        expect(post.user).to.equal(otheruser._id.toString());
        expect(post.relevance).to.be.a('number');
        done(err);
      });
    });
    it('should return a post on HTTP GET /posts/:id without api key', function (done) {
      request.get('/posts/' + other_post_id).expect(200, function (err, res) {
        var post = res.body;
        expect(post.lat).to.equal(47);
        expect(post.long).to.equal(11);
        expect(post.message).to.equal('Testmessage');
        expect(post._id).to.exist;
        expect(post.user).to.equal(otheruser._id.toString());
        expect(post.relevance).to.be.a('number');
        done(err);
      });
    });
    it('should return 404 when using HTTP GET /posts/:id with an unkown id with api key', function (done) {
      request.get('/posts/deadbeef?apiKey=thetestuserapikey').expect(404, done);
    });
    it('should return 404 when using HTTP GET /posts/:id with an unkown id without api key', function (done) {
      request.get('/posts/deadbeef').expect(404, done);
    });
    it('should return 400 when using HTTP GET /posts/:id with an invalid id with api key', function (done) {
      request.get('/posts/valid_ids_may_only_be_hex_numbers?apiKey=thetestuserapikey').expect(400, done);
    });
    it('should return 400 when using HTTP GET /posts/:id with an invalid id without api key', function (done) {
      request.get('/posts/valid_ids_may_only_be_hex_numbers').expect(400, done);
    });
  });
});<commit_msg>Restructured tests.<commit_after>var expect = require('chai').expect;
var request = require('supertest')('http://localhost:5000');
var db = require('../database');
var users = db.get('users');
var posts = db.get('posts');

describe('API', function () {
  var testuser;
  var otheruser;
  before(function () {
    users.findOne({apiKey: 'thetestuserapikey'}, function (err, doc) {
      testuser = doc;
    });
    users.findOne({apiKey: 'theotheruserapikey'}, function (err, doc) {
      otheruser = doc;
    });
  });

  describe('Authentication', function () {
    it('should allow access without api key', function (done) {
      request.get('/').expect(200, done);
    });
    it('should not allow access with an invalid api key', function (done) {
      request.get('/?api_key=notavalidapikey').expect(403, done);
    });
    it('should allow access with api key via GET parameter api_key', function (done) {
      request.get('/?api_key=thetestuserapikey').expect(200, done);
    });
    it('should allow access with api key via GET parameter apiKey', function (done) {
      request.get('/?apiKey=thetestuserapikey').expect(200, done);
    });
    it('should redirect /auth/google to Google oAuth2', function (done) {
      request.get('/auth/google').expect(302, function (err, res) {
        expect(res.header['location']).to.match(/^https:\/\/accounts.google.com\/o\/oauth2\/auth/);
        done(err);
      });
    });
    it('should redirect /auth/facebook to Facebook oAuth2', function (done) {
      request.get('/auth/facebook').expect(302, function (err, res) {
        expect(res.header['location']).to.match(/^https:\/\/www.facebook.com\/dialog\/oauth/);
        done(err);
      });
    });
  });

  describe('/posts', function () {
    describe('HTTP GET', function () {
      describe('without API key', function () {
        it('should return 200 OK', function (done) {
          request.get('/posts/').expect(200, done);
        });
      });
      describe('with API key', function () {
        it('should return 200 OK', function (done) {
          request.get('/posts/?apiKey=thetestuserapikey').expect(200, done);
        });
      });
    });
    describe('HTTP POST', function () {
      describe('without API key', function () {
        it('should return 403 FORBIDDEN', function (done) {
          request.post('/posts/').send({
            lat: 13,
            long: 37,
            message: 'Testmessage'
          }).expect(403, done);
        });
        it('should return 403 FORBIDDEN with missing parameter "lat"', function (done) {
          request.post('/posts/').send({
            long: 37,
            message: 'Testmessage'
          }).expect(403, done);
        });
        it('should return 403 FORBIDDEN with missing parameter "long"', function (done) {
          request.post('/posts/').send({
            lat: 13,
            message: 'Testmessage'
          }).expect(403, done)
        });
        it('should return 403 FORBIDDEN with missing parameter "message"', function (done) {
          request.post('/posts/').send({
            lat: 13,
            long: 37
          }).expect(403, done);
        });
        it('should return 403 FORBIDDEN with parameter "lat" bigger than 90', function (done) {
          request.post('/posts/').send({
            lat: 90.1,
            long: 37,
            message: 'Testmessage'
          }).expect(403, done);
        });
        it('should return 403 FORBIDDEN with parameter "lat" smaller than -90', function (done) {
          request.post('/posts/').send({
            lat: -90.1,
            long: 37,
            message: 'Testmessage'
          }).expect(403, done);
        });
        it('should return 403 FORBIDDEN with parameter "long" bigger than 180', function (done) {
          request.post('/posts/').send({
            lat: 13,
            long: 180.1,
            message: 'Testmessage'
          }).expect(403, done);
        });
        it('should return 403 FORBIDDEN with parameter "long" smaller than -180', function (done) {
          request.post('/posts/').send({
            lat: 13,
            long: -180.1,
            message: 'Testmessage'
          }).expect(403, done);
        });
      });
      describe('with API key', function () {
        it('should return 200 OK when creating a new post and return the post', function (done) {
          request.post('/posts/?apiKey=thetestuserapikey').send({
            lat: 13,
            long: 37,
            message: 'Testmessage'
          }).expect(200, function (err, res) {
            var post = res.body;
            expect(post.user).to.equal(testuser._id.toString());
            expect(post.lat).to.equal(13);
            expect(post.long).to.equal(37);
            expect(post.message).to.equal('Testmessage');
            expect(post._id).to.exist;
            done(err);
          });
        });
        it('should return 400 BAD REQUEST with missing parameter "lat"', function (done) {
          request.post('/posts/?apiKey=thetestuserapikey').send({
            long: 37,
            message: 'Testmessage'
          }).expect(400, done);
        });
        it('should return 400 BAD REQUEST with missing parameter "long"', function (done) {
          request.post('/posts/?apiKey=thetestuserapikey').send({
            lat: 13,
            message: 'Testmessage'
          }).expect(400, done)
        });
        it('should return 400 BAD REQUEST with missing parameter "message"', function (done) {
          request.post('/posts/?apiKey=thetestuserapikey').send({
            lat: 13,
            long: 37
          }).expect(400, done);
        });
        it('should return 400 BAD REQUEST with parameter "lat" bigger than 90', function (done) {
          request.post('/posts/?apiKey=thetestuserapikey').send({
            lat: 90.1,
            long: 37,
            message: 'Testmessage'
          }).expect(400, done);
        });
        it('should return 400 BAD REQUEST with parameter "lat" smaller than -90', function (done) {
          request.post('/posts/?apiKey=thetestuserapikey').send({
            lat: -90.1,
            long: 37,
            message: 'Testmessage'
          }).expect(400, done);
        });
        it('should return 400 BAD REQUEST with parameter "long" bigger than 180', function (done) {
          request.post('/posts/?apiKey=thetestuserapikey').send({
            lat: 13,
            long: 180.1,
            message: 'Testmessage'
          }).expect(400, done);
        });
        it('should return 400 BAD REQUEST with parameter "long" smaller than -180', function (done) {
          request.post('/posts/?apiKey=thetestuserapikey').send({
            lat: 13,
            long: -180.1,
            message: 'Testmessage'
          }).expect(400, done);
        });
      });
    });
  });
  describe('/posts/:id', function () {
    var my_post_id;
    var other_post_id;
    before(function (done) {
      request.post('/posts/?apiKey=thetestuserapikey').send({
        lat: 42,
        long: 21,
        message: 'Testmessage'
      }).end(function (err, res) {
        if (err) {
          done(err);
        } else {
          my_post_id = res.body._id;
          request.post('/posts/?apiKey=theotheruserapikey').send({
            lat: 47,
            long: 11,
            message: 'Testmessage'
          }).end(function (err, res) {
            other_post_id = res.body._id;
            done(err);
          });
        }
      });
    });

    describe('HTTP GET', function () {
      describe('without API key', function () {
        it('should return 200 OK and the correct post', function (done) {
          request.get('/posts/' + other_post_id).expect(200, function (err, res) {
            var post = res.body;
            expect(post.lat).to.equal(47);
            expect(post.long).to.equal(11);
            expect(post.message).to.equal('Testmessage');
            expect(post._id).to.exist;
            expect(post.user).to.equal(otheruser._id.toString());
            expect(post.relevance).to.be.a('number');
            done(err);
          });
        });
        it('should return 404 NOT FOUND with an unkown post id', function (done) {
          request.get('/posts/deadbeef').expect(404, done);
        });
        it('should return 400 BAD REQUEST with an invalid post id', function (done) {
          request.get('/posts/valid_ids_may_only_be_hex_numbers').expect(400, done);
        });
      });
      describe('with API key', function () {
        it('should return 200 OK and the correct post', function (done) {
          request.get('/posts/' + other_post_id + '?apiKey=thetestuserapikey').expect(200, function (err, res) {
            var post = res.body;
            expect(post.lat).to.equal(47);
            expect(post.long).to.equal(11);
            expect(post.message).to.equal('Testmessage');
            expect(post._id).to.exist;
            expect(post.user).to.equal(otheruser._id.toString());
            expect(post.relevance).to.be.a('number');
            done(err);
          });
        });
        it('should return 404 NOT FOUND with an unkown post id', function (done) {
          request.get('/posts/deadbeef?apiKey=thetestuserapikey').expect(404, done);
        });
        it('should return 400 BAD REQUEST with an invalid post id', function (done) {
          request.get('/posts/valid_ids_may_only_be_hex_numbers?apiKey=thetestuserapikey').expect(400, done);
        });
      });
    });
    describe('HTTP POST', function () {
    });
    describe('HTTP DELETE', function () {
      describe('without API key', function () {
        it('should return 403 FORBIDDEN when trying to delete a post', function (done) {
          request.delete('/posts/' + other_post_id).expect(403, function (err, res) {
            if (err) {
              done(err);
            } else {
              posts.findOne({'_id': other_post_id}, function (err, doc) {
                expect(doc).to.exist;
                done(err);
              });
            }
          });
        });
        it('should return 403 FORBIDDEN when trying to delete an unkown post id', function (done) {
          request.delete('/posts/deadbeef').expect(403, done);
        });
        it('should return 403 FORBIDDEN when trying to delete an invalid post id', function (done) {
          request.delete('/posts/valid_ids_may_only_be_hex_numbers').expect(403, done);
        });
      });
      describe('with API key', function () {
        it('should return 204 NO CONTENT when deleting an own post', function (done) {
          request.delete('/posts/' + my_post_id + '?apiKey=thetestuserapikey').expect(204, function (err, res) {
            if (err) {
              done(err);
            } else {
              posts.findOne({'_id': my_post_id}, function (err, doc) {
                expect(doc).to.not.exist;
                done(err);
              });
            }
          });
        });
        it('should return 403 FORBIDDEN when trying to delete a foreign post', function (done) {
          request.delete('/posts/' + other_post_id + '?apiKey=thetestuserapikey').expect(403, function (err, res) {
            if (err) {
              done(err);
            } else {
              posts.findOne({'_id': other_post_id}, function (err, doc) {
                expect(doc).to.exist;
                done(err);
              });
            }
          });
        });
        it('should return 404 NOT FOUND when trying to delete an unkown post id', function (done) {
          request.delete('/posts/deadbeef?apiKey=thetestuserapikey').expect(404, done);
        });
        it('should return 400 BAD REQUEST when trying to delete an invalid post id', function (done) {
          request.delete('/posts/valid_ids_may_only_be_hex_numbers?apiKey=thetestuserapikey').expect(400, done);
        });
      });
    });
  });
});<|endoftext|>


<commit_before>Array.prototype.last = function() {return this[this.length-1];}

var projects = new Lawnchair({adaptor: 'air', table: "projects"});

$(document).ready(function() {
  listProjects();

  var target = document.getElementById('watchtarget');
  target.addEventListener("dragenter", dragEnterHandler);
  target.addEventListener("dragover", dragOverHandler);
  target.addEventListener("drop", dropHandler);

  $('.option.add').click(createProjectBySelectingDirectory);

  $('#nuke').click(function(){
    projects.nuke();
    listProjects();
  });
});

function listProjects(){
  $('.projects').empty();
  projects.all(function(project){
    if(project){
      appendProjectToProjectsList(project);
    }
  });
  $('.project .select.input').click(selectInputBySelectingDirectory);
  $('.project .select.output').click(selectOutputBySelectingDirectory);
  $('.project .delete').click(deleteProject);

  $('.project .play').live('click', toggleWatch);
  $('.project .stop').live('click', toggleWatch);

  $('.project .source').click(function() {
    $(this).parents('.project').children('.config').toggle();
  });
}

function startWatch(inputPath, outputPath) {
  air.trace("started watching..." + inputPath);
}

function stopWatch() {
  air.trace("stopped watching.");
}

function toggleWatch(evnt) {
  key = $(this).parents('.project:first').attr('data-key');
  thing = $(this);
  projects.get(key, function(project) {
    if(thing.hasClass("play")) {
      startWatch(project.inputPath, project.outputPath);
      thing.html("Stop");
    } else {
      stopWatch();
      thing.html("Play");
    }
    thing.toggleClass("play");
    thing.toggleClass("stop");
  });
  return false;
}

// function playProject() {
//   projects.get(key, function(project) {
//     startWatch(project.inputPath, project.outputPath);
//   });
//   $(this).removeClass("play");
//   $(this).addClass("stop");
//   $('.project .stop').click(stopProject);
//   $(this).html("stop");
//   return false;
// }
//
// function stopProject() {
//   key = $(this).parents('.project:first').attr('data-key');
//   projects.get(key, function(project) {
//     stopWatch();
//   });
//   $(this).removeClass("stop");
//   $(this).addClass("play");
//   $('.project .play').click(playProject);
//   $(this).html("play");
//   return false;
// }

function deleteProject() {
  key = $(this).parents('.project:first').attr('data-key');
  projects.get(key, function(project) {
    projects.remove(project);
  });
  listProjects();
  return false;
}

function selectOutputBySelectingDirectory() {
  key = $(this).parents('.project:first').attr('data-key');
  config = $(this).siblings('span');
  browseDirectories(function(evnt){
    projects.get(key, function(project) {
      project.outputPath = evnt.target.nativePath;
      projects.save(project);
    });
    config.html(evnt.target.nativePath);
  });
  return false;
}

function selectInputBySelectingDirectory() {
  key = $(this).parents('.project:first').attr('data-key');
  config = $(this).siblings('span');
  browseDirectories(function(evnt){
    projects.get(key, function(project) {
      project.inputPath = evnt.target.nativePath;
      projects.save(project);
    });
    config.html(evnt.target.nativePath);
  });
  return false;
}

function createProjectBySelectingDirectory() {
  browseDirectories(createProjectFromFolder);
}

function browseDirectories(callback) {
  var directory = air.File.documentsDirectory;
  try
  {
    directory.browseForDirectory("Select Directory");
    directory.addEventListener(air.Event.SELECT, callback);
  }
  catch (error)
  {
    air.trace("Failed:", error.message)
  }
}

function createProjectFromFolder(evnt) {
  createProject(evnt.target.nativePath.replace(/\/$/, '').split('/').last(), evnt.target.nativePath, "");
}

function createProject(name, inputPath, outputPath) {
  projects.save({
    name: name,
    inputPath: inputPath,
    outputPath: outputPath
  });
  listProjects();
  $('.projects .project').last().children('.config').toggle();
}

function appendProjectToProjectsList(project) {
  $.tmpl($("#project-template"), project).appendTo(".projects");
}

function dragEnterHandler(evnt) {
  evnt.preventDefault();
}

function dragOverHandler(evnt){
  evnt.preventDefault();
}

function dropHandler(evnt){
  evnt.preventDefault();
  createProject(evnt.dataTransfer.getData("text/uri-list").replace(/\/$/, '').split('/').last(), "", "");
}

function onOutputData()
{
  //air.trace("Got: ", process.standardOutput.readUTFBytes(process.standardOutput.bytesAvailable));
}

function onErrorData(evnt)
{
  //air.trace("ERROR -", process.standardError.readUTFBytes(process.standardError.bytesAvailable));
}

function onExit(evnt)
{
  //air.trace("Process exited with ", evnt.exitCode);
}

function onIOError(evnt)
{
  //air.trace(evnt.toString());
}

// $(document).ready(function(){
//   air.trace($("#m").length);
//   $("#m").click(function(){
//      var nativeProcessStartupInfo = new air.NativeProcessStartupInfo();
//      var file = air.File.applicationDirectory.resolvePath("vendor/jruby-1.6.0.RC2/bin/jruby");
//      nativeProcessStartupInfo.executable = file;
//
//      var processArgs = new air.Vector["<String>"]();
//      processArgs.push("--version");
//      nativeProcessStartupInfo.arguments = processArgs;
//
//      process = new air.NativeProcess();
//      process.addEventListener(air.ProgressEvent.STANDARD_OUTPUT_DATA, dataHandler);
//     process.addEventListener(air.ProgressEvent.STANDARD_ERROR_DATA, dataHandler);
//      process.start(nativeProcessStartupInfo);
//
//       var bytes = new air.ByteArray();
//      function dataHandler(evnt) {
//        process.standardOutput.readBytes(bytes, 0, process.standardOutput.bytesAvailable);
//        alert(bytes.toString());
//        air.trace(bytes.toString());
//       // $("body").append(bytes.toString());
//      }
//   });
// });
<commit_msg>changed click bindings to use live<commit_after>Array.prototype.last = function() {return this[this.length-1];}

var projects = new Lawnchair({adaptor: 'air', table: "projects"});

$(document).ready(function() {
  listProjects();

  var target = document.getElementById('watchtarget');
  target.addEventListener("dragenter", dragEnterHandler);
  target.addEventListener("dragover", dragOverHandler);
  target.addEventListener("drop", dropHandler);

  $('.option.add').click(createProjectBySelectingDirectory);
  $('.project .play').live('click', toggleWatch);
  $('.project .stop').live('click', toggleWatch);
  $('.project .select.input').live('click', selectInputBySelectingDirectory);
  $('.project .select.output').live('click', selectOutputBySelectingDirectory);
  $('.project .delete').live('click', deleteProject);

  $('.project .source').live('click', function() {
    $(this).parents('.project').children('.config').toggle();
  });

  $('#nuke').click(function(){
    projects.nuke();
    listProjects();
  });
});

function listProjects(){
  $('.projects').empty();
  projects.all(function(project){
    if(project){
      appendProjectToProjectsList(project);
    }
  });
}

function startWatch(inputPath, outputPath) {
  air.trace("started watching..." + inputPath);
}

function stopWatch() {
  air.trace("stopped watching.");
}

function toggleWatch(evnt) {
  key = $(this).parents('.project:first').attr('data-key');
  thing = $(this);
  projects.get(key, function(project) {
    if(thing.hasClass("play")) {
      startWatch(project.inputPath, project.outputPath);
      thing.html("Stop");
    } else {
      stopWatch();
      thing.html("Play");
    }
    thing.toggleClass("play");
    thing.toggleClass("stop");
  });
  return false;
}

function deleteProject() {
  key = $(this).parents('.project:first').attr('data-key');
  projects.get(key, function(project) {
    projects.remove(project);
  });
  listProjects();
  return false;
}

function selectOutputBySelectingDirectory() {
  key = $(this).parents('.project:first').attr('data-key');
  config = $(this).siblings('span');
  browseDirectories(function(evnt){
    projects.get(key, function(project) {
      project.outputPath = evnt.target.nativePath;
      projects.save(project);
    });
    config.html(evnt.target.nativePath);
  });
  return false;
}

function selectInputBySelectingDirectory() {
  key = $(this).parents('.project:first').attr('data-key');
  config = $(this).siblings('span');
  browseDirectories(function(evnt){
    projects.get(key, function(project) {
      project.inputPath = evnt.target.nativePath;
      projects.save(project);
    });
    config.html(evnt.target.nativePath);
  });
  return false;
}

function createProjectBySelectingDirectory() {
  browseDirectories(createProjectFromFolder);
}

function browseDirectories(callback) {
  var directory = air.File.documentsDirectory;
  try
  {
    directory.browseForDirectory("Select Directory");
    directory.addEventListener(air.Event.SELECT, callback);
  }
  catch (error)
  {
    air.trace("Failed:", error.message)
  }
}

function createProjectFromFolder(evnt) {
  createProject(evnt.target.nativePath.replace(/\/$/, '').split('/').last(), evnt.target.nativePath, "");
}

function createProject(name, inputPath, outputPath) {
  projects.save({
    name: name,
    inputPath: inputPath,
    outputPath: outputPath
  });
  listProjects();
  $('.projects .project').last().children('.config').toggle();
}

function appendProjectToProjectsList(project) {
  $.tmpl($("#project-template"), project).appendTo(".projects");
}

function dragEnterHandler(evnt) {
  evnt.preventDefault();
}

function dragOverHandler(evnt){
  evnt.preventDefault();
}

function dropHandler(evnt){
  evnt.preventDefault();
  createProject(evnt.dataTransfer.getData("text/uri-list").replace(/\/$/, '').split('/').last(), "", "");
}

function onOutputData()
{
  //air.trace("Got: ", process.standardOutput.readUTFBytes(process.standardOutput.bytesAvailable));
}

function onErrorData(evnt)
{
  //air.trace("ERROR -", process.standardError.readUTFBytes(process.standardError.bytesAvailable));
}

function onExit(evnt)
{
  //air.trace("Process exited with ", evnt.exitCode);
}

function onIOError(evnt)
{
  //air.trace(evnt.toString());
}

// $(document).ready(function(){
//   air.trace($("#m").length);
//   $("#m").click(function(){
//      var nativeProcessStartupInfo = new air.NativeProcessStartupInfo();
//      var file = air.File.applicationDirectory.resolvePath("vendor/jruby-1.6.0.RC2/bin/jruby");
//      nativeProcessStartupInfo.executable = file;
//
//      var processArgs = new air.Vector["<String>"]();
//      processArgs.push("--version");
//      nativeProcessStartupInfo.arguments = processArgs;
//
//      process = new air.NativeProcess();
//      process.addEventListener(air.ProgressEvent.STANDARD_OUTPUT_DATA, dataHandler);
//     process.addEventListener(air.ProgressEvent.STANDARD_ERROR_DATA, dataHandler);
//      process.start(nativeProcessStartupInfo);
//
//       var bytes = new air.ByteArray();
//      function dataHandler(evnt) {
//        process.standardOutput.readBytes(bytes, 0, process.standardOutput.bytesAvailable);
//        alert(bytes.toString());
//        air.trace(bytes.toString());
//       // $("body").append(bytes.toString());
//      }
//   });
// });
<|endoftext|>


<commit_before>// File name: mongotests.js
// Date: 03/04/2017
// Programmer: Jim Medlock
//
// Routes containing native Mongo tests.

const config = require('../config');
const express = require('express');
const mongodb = require('mongodb');
const router = express.Router();

const hlog = require('../util/htmllog');

// Establish a mongo connection using settings from the config.js file
const mongoUri = `mongodb://${config.db.host}/${config.db.name}`;
const mongoClient = mongodb.MongoClient;

// -------------------------------------------------------------
// Express Route Definitions
// -------------------------------------------------------------

// Route - Retrieve all documents from the database.
//         http://localhost:3000/mongo/findall
router.get('/findall', (request, response) => {
  const log = new hlog.HtmlLog();
  let accountsDb = null;
  let collection = null;
  log.addEntry('
Mongo Test
');
  log.addEntry('
Execution Log:
');
  log.addEntry('Entered /mongo/findall...');
  mongoClient.connect(mongoUri)
  .then((db) => {
    accountsDb = db;
    collection = accountsDb.collection('accounts');
    log.addEntry('Successfully connected to MongoDB');
    return collection.count();
  })
  .then((count) => {
    log.addEntry(`Existing record count: ${count}`);
    return collection.find();
  })
  .then((cursor) => {
    cursor.each((error, anAccount) => {
      if (anAccount === null) {
        log.writeLog('normal', response, 'Findall test successfully completed');
        return;
      }
      log.addEntry(`Account: account_no:${anAccount.account_no}
        owner_fname:${anAccount.owner_fname}
        owner_mi:${anAccount.owner_mi}
        owner_lname:${anAccount.owner_lname}`);
    });
    accountsDb.close();
  })
  .catch((error) => {
    log.addEntry(`Unable to establish connection to MongoDB. Error: ${error}`);
    log.addEntry(`MongoUri: ${mongoUri}`);
    log.writeLog('error', response);
  });
});

// Route - Retrieve specific documents from the database via a complex query.
//         http://localhost:3000/mongo/simplequery
router.get('/simplequery', (request, response) => {
  const log = new hlog.HtmlLog();
  let accountsDb = null;
  let collection = null;
  log.addEntry('
Mongo Test
');
  log.addEntry('
Execution Log:
');
  log.addEntry('Entered /mongo/simplequery...');
  mongoClient.connect(mongoUri)
  .then((db) => {
    accountsDb = db;
    collection = accountsDb.collection('accounts');
    log.addEntry('Successfully connected to MongoDB');
    return collection.count();
  })
  .then((count) => {
    log.addEntry(`Existing record count: ${count}`);
    return collection.find({ owner_fname: 'Roger' });
  })
  .then((cursor) => {
    cursor.each((error, anAccount) => {
      if (anAccount === null) {
        log.writeLog('normal', response,
          'Simplequery test successfully completed');
        return;
      }
      log.addEntry(`Account: account_no:${anAccount.account_no}
        owner_fname:${anAccount.owner_fname}
        owner_mi:${anAccount.owner_mi}
        owner_lname:${anAccount.owner_lname}`);
    });
    accountsDb.close();
  })
  .catch((error) => {
    log.addEntry(`Unable to establish connection to MongoDB. Error: ${error}`);
    log.addEntry(`MongoUri: ${mongoUri}`);
    log.writeLog('error', response);
  });
});

module.exports = router;
<commit_msg>updated mongotests/simplequery to match functionality of mongoose/simplequery<commit_after>// File name: mongotests.js
// Date: 03/04/2017
// Programmer: Jim Medlock
//
// Routes containing native Mongo tests.

const config = require('../config');
const express = require('express');
const mongodb = require('mongodb');
const router = express.Router();

const hlog = require('../util/htmllog');

// Establish a mongo connection using settings from the config.js file
const mongoUri = `mongodb://${config.db.host}/${config.db.name}`;
const mongoClient = mongodb.MongoClient;

// -------------------------------------------------------------
// Express Route Definitions
// -------------------------------------------------------------

// Route - Retrieve all documents from the database.
//         http://localhost:3000/mongo/findall
router.get('/findall', (request, response) => {
  const log = new hlog.HtmlLog();
  let accountsDb = null;
  let collection = null;
  log.addEntry('
Mongo Test
');
  log.addEntry('
Execution Log:
');
  log.addEntry('Entered /mongo/findall...');
  mongoClient.connect(mongoUri)
  .then((db) => {
    accountsDb = db;
    collection = accountsDb.collection('accounts');
    log.addEntry('Successfully connected to MongoDB');
    return collection.count();
  })
  .then((count) => {
    log.addEntry(`Existing record count: ${count}`);
    return collection.find();
  })
  .then((cursor) => {
    cursor.each((error, anAccount) => {
      if (anAccount === null) {
        log.writeLog('normal', response, 'Findall test successfully completed');
        return;
      }
      log.addEntry(`Account: account_no:${anAccount.account_no}
        owner_fname:${anAccount.owner_fname}
        owner_mi:${anAccount.owner_mi}
        owner_lname:${anAccount.owner_lname}`);
    });
    accountsDb.close();
  })
  .catch((error) => {
    log.addEntry(`Unable to establish connection to MongoDB. Error: ${error}`);
    log.addEntry(`MongoUri: ${mongoUri}`);
    log.writeLog('error', response);
  });
});

// Route - Retrieve specific documents from the database via a complex query.
//         http://localhost:3000/mongo/simplequery
router.get('/simplequery', (request, response) => {
  const log = new hlog.HtmlLog();
  let accountsDb = null;
  let collection = null;
  log.addEntry('
Mongo Test
');
  log.addEntry('
Execution Log:
');
  log.addEntry('Entered /mongo/simplequery...');
  mongoClient.connect(mongoUri)
  .then((db) => {
    accountsDb = db;
    collection = accountsDb.collection('accounts');
    log.addEntry('Successfully connected to MongoDB');
    return collection.count();
  })
  .then((count) => {
    log.addEntry(`Existing record count: ${count}`);
    return collection.find({ owner_fname: { $eq: 'Roger' } });
  })
  .then((cursor) => {
    return cursor.sort({ owner_lname: 1 });
  })
  .then((cursor) => {
    cursor.each((error, anAccount) => {
      if (anAccount === null) {
        log.writeLog('normal', response,
          'Simplequery test successfully completed');
        return;
      }
      log.addEntry(`Account: account_no:${anAccount.account_no}
        owner_fname:${anAccount.owner_fname}
        owner_mi:${anAccount.owner_mi}
        owner_lname:${anAccount.owner_lname}`);
    });
    accountsDb.close();
  })
  .catch((error) => {
    log.addEntry(`Unable to establish connection to MongoDB. Error: ${error}`);
    log.addEntry(`MongoUri: ${mongoUri}`);
    log.writeLog('error', response);
  });
});

module.exports = router;
<|endoftext|>