<commit_before>var validateHTTP = require("./validateHTTP.js"),
    restify = require('restify'),
    request = require('request'),
    rand = require('csprng'),
    sha1 = require('sha1'),
    uuid = require('node-uuid'),
    neo4j = require('node-neo4j'),
    Promise = require('promise');
module.exports.creategroup = function(req, res, next) {
    if((validateHTTP.validateHTTP(req, res, next, 'users')) === true) {
        db = new neo4j('http://localhost:7474');
        console.log('NEW GROUP!');
        console.log('PUT: ' + req.params.groupname)
        console.log('FOR COMPETITION: ' + req.params.competition)
        var url = 'http://localhost:5984/groups/' + req.params.groupname;
        var competition = req.params.competition
        var groupname = req.params.groupname
        var description = req.params.description
        var groupid = 0;
        var userid = 0;
        validateHTTP.validateHTTP(req, res, next, 'users')
        var topres = res
        request.get(url, function(err, response, body) {
            if(err) {
                return next(new restify.InternalServerError('Error has occured'));
            }
            // if the document isnt found it will create it from sratch
            console.log('code' + response.statusCode)
            if(response.statusCode === 200) {
                return next(new restify.ConflictError('Group Already Created'));
            } else if(response.statusCode === 404) {
                db.cypherQuery(" MATCH (n:competition) WHERE n.name ='" + competition + "' RETURN n", function(err, result) {
                    if(err) throw err;
                    if(result.data.length == 0) {
                        return next(new restify.InternalServerError('no competition found'));
                    } else {
                        var competitionid = result.data[0]._id
                        console.log('Groupname = ' + groupname)
                        db.cypherQuery("MATCH (n:group) WHERE n.name ='" + groupname + "' RETURN n", function(err, results) {
                            if(err) throw err;
                            console.log('Group data = ' + results.data)
                            if(results.data.length == 0) {
                                db.insertNode({
                                    name: groupname,
                                    description: description
                                }, ['Group', competition], function(err, node) {
                                    if(err) throw err;
                                    // Output node properties.
                                    console.log('New neo4j node created with Groupname  = ' + node.name);
                                    groupid = node._id
                                    console.log('group id = ' + groupid)
                                    console.log('starting insert relationship')
                                    db.insertRelationship(node._id, competitionid, 'COMPETING_IN', {
                                        description: 'competiting in this competition'
                                    }, function(err, relationship) {
                                        if(err) throw err;
                                        console.log('relationship made')
                                        // Output relationship id.
                                        console.log(relationship._id);
                                        // Output relationship start_node_id.
                                        console.log(relationship._start);
                                        // Output relationship end_node_id.
                                        console.log(relationship._end);
                                        db.cypherQuery(" MATCH (n:User) WHERE n.name ='" + req.authorization.basic.username + "' RETURN n", function(err, Results) {
                                            if(err) throw err;
                                            console.log('name = ' + Results.data[0])
                                            console.log('user = ' + Results.data[0]._id)
                                            userid = Results.data[0]._id
                                            console.log('userid =' + userid)
                                            console.log(groupid)
                                            db.insertRelationship(userid, groupid, 'IN_GROUP', {
                                                description: 'Created this group'
                                            }, function(err, relationship) {
                                                if(err) throw err;
                                                console.log('relationship made')
                                                // Output relationship id.
                                                console.log(relationship._id);
                                                // Output relationship start_node_id.
                                                console.log(relationship._start);
                                                // Output relationship end_node_id.
                                                console.log(relationship._end);
                                                var d = new Date(),
                                                    date = d.toUTCString();
                                                console.log(date);
                                                var doc = {
                                                    groupname: groupname,
                                                    description: description,
                                                    date_joined: date,
                                                    last_modified: date,
                                                    createdby: req.authorization.basic.username,
                                                    grouppoints: 0,
                                                    transactions: [],
                                                    usersjoined: [req.authorization.basic.username],
                                                    competition: competition,
                                                    groupnodeid: groupid
                                                };
                                                var docStr = JSON.stringify(doc);
                                                var params = {
                                                    uri: url,
                                                    body: JSON.stringify(doc)
                                                };
                                                request.put(params, function(err, response, body) {
                                                    if(err) {
                                                        return next(new restify.InternalServerError('Cant create document'));
                                                    }
                                                    // document has been inserted into database
                                                    body = JSON.parse(body);
                                                    console.log('about to sent res')
                                                    topres.send({
                                                        Group: req.params
                                                    });
                                                    topres.end();
                                                });
                                            });
                                        });
                                    });
                                });
                            } else {
                                console.log(result.data[0])
                                return next(new restify.ConflictError('Group already created'));
                            }
                        })
                    }
                    console.log(result.data.length); // delivers an array of query results
                });
                //
            };
        });
        // if the document is found, that means the user is already created.
    }
};
module.exports.showgroup = function(req, res, next) {
    db = new neo4j('http://localhost:7474');
    console.log('GET');
    console.log('GET: ' + req.params.groupname);
    var url = 'http://localhost:5984/groups/' + req.params.groupname;
    validateHTTP.validateHTTP(req, res, next, "users")
    var topres = res
    request.get(url, function(err, response, body) {
        if(err) {
            return next(new restify.InternalServerError('Failed To Connect To Database'));
        }
        // if the document isnt found it will create it from sratch
        console.log('code' + response.statusCode)
        if(response.statusCode === 200) {
            body = JSON.parse(body);
            //res.header('ETag', body._rev);
            res.header('Last-Modified', body.last_modified);
            res.header('Accepts', 'GET');
            group = {
                id: body._id,
                groupname: body.groupname,
                description: body.description,
                last_modified: body.last_modified,
                points: body.grouppoints,
                transactions: body.transactions,
                owner: body.createdby,
                groupmemebers: body.usersjoined
            }
            console.log(group)
            console.log("Set Group data");
            res.send(group);
            console.log("sent group data");
            res.end();
        } else if(response.statusCode === 404) {
            return next(new restify.ConflictError('Group Already Created'));
        }
    });
};
module.exports.showcompetitiongroup = function(req, res, next) {
    //match (n:freshers)-[COMPETING_IN]->r return n,r
    db = new neo4j('http://localhost:7474');
    console.log('GET');
    console.log('GET COMPETITION GROUPS: ' + req.params.competition)
    var url = 'http://localhost:5984/groups/' + req.params.groupname;
    var competition = req.params.competition
    validateHTTP.validateHTTP(req, res, next)
    var topres = res
    db.cypherQuery("match (n:" + competition + ")-[COMPETING_IN]->r return labels(n),n,r", function(err, Results) {
        if(err) throw err;
        if(Results.data == 0) {
            return next(new restify.NotFoundError('Competition not found'));
        } else {
            res.send(Results.data);
            console.log("competition data sent");
            res.end();
        }
    });
};
module.exports.joinGroup = function(req, res, next) {
    var db = new neo4j('http://localhost:7474');
    console.log('PUT');
    console.log('JOIN GROUP: ' + req.params.username + ' ' + req.params.groupname)
    var url = 'http://localhost:5984/users/' + req.authorization.basic.username;
    var groupurl = 'http://localhost:5984/groups/' + req.params.groupname;
    var userid = 0,
        groupid = 0,
        groupname = req.params.groupname,
        username = req.authorization.basic.username;
    validateHTTP.validateHTTP(req, res, next, "users");
    var topres = res
    //check user exists
    request.get(url, function(err, response, body) {
        console.log("request started")
        // if user is not found will send 404 error
        if(response.statusCode == 404) {
            return next(new restify.BadRequestError('User Not Found'))
        };
        if(response.statusCode == 200) {
            body = JSON.parse(body);
            console.log('set user id')
            userid = body.nodeid;
            //check group exists
            db.cypherQuery("match n where n.name='" + groupname + "' return n", function(err, Results) {
                if(err) throw err;
                if(Results.data == 0) {
                    return next(new restify.NotFoundError('Group not found'));
                } else {
                    groupid = Results.data[0]._id
                    console.log("Group ID set");
                    var d = new Date(),
                        date = d.toUTCString();
                    console.log(date);
                    //make relationship
                    db.insertRelationship(userid, groupid, 'IN_GROUP', {
                        datejoined: date,
                    }, function(err, relationship) {
                        if(err) throw err;
                        console.log("set user");
                        res.send("relationship created @ " + date);
                        console.log("sent data");
                        res.end();
                    });
                }
            });
        };
    });
};
// rebuilding with promises and closures
module.exports.groups = (function() {
    var url = "",
        competition = "",
        groupname = "",
        description = "",
        groupid = 0,
        userid = 0,
        competitionid = "";
    return {
        createGroup: function(req, res, next) {
            console.log(req.params)
            console.log("group create started")
            console.log("POST "  + req.params.groupname )
            url = 'http://localhost:5984/groups/' + req.params.groupname
            var competition = req.params.competition;
            var groupname = req.params.groupname;
            var description = req.params.description;
            console.log(competition + " Group :"  + groupname + " Description: " + description)
            var groupid = 0;
            var userid = 0;
            getRequest(url).
            catch(function(err) {
                console.log("get request error")
                return next(new restify.InternalServerError('Error has occured'));
            }).then(function(call) {
                if(response.statusCode === 200) {
                    return next(new restify.ConflictError('Group Already Created'));
                }
            }).then(db.cypherQuery(" MATCH (n:competition) WHERE n.name ='" + competition + "' RETURN n", function(err, result) {
                if(err) throw err;
                if(result.data.length == 0) {
                    return next(new restify.InternalServerError('no competition found'));
                }
                return competitionid = result.data[0]._id
            })).then(function(i1d) {
                db.cypherQuery("MATCH (n:group) WHERE n.name ='" + groupname + "' RETURN n", function(err, results) {
                    if(err) throw err;
                    if(results.data.length == 0) {
                        return results.data
                    } else {
                        console.log(result.data[0])
                        return next(new restify.ConflictError('Group already created'));
                    }
                })
            }).then(function(data) {
                db.insertNode({
                    name: groupname,
                    description: description
                }, ['Group', competition], function(err, node) {
                    if(err) throw err;
                    // Output node properties.
                    console.log('New neo4j node created with Groupname  = ' + node.name);
                    groupid = node._id
                    console.log('group id = ' + groupid)
                    return node._id
                });
            }).then(function(nodeid) {
                db.insertRelationship(node._id, competitionid, 'COMPETING_IN', {
                    description: 'competiting in this competition'
                }, function(err, relationship) {
                    if(err) throw err;
                    console.log('relationship made')
                    // Output relationship id.
                    console.log(relationship._id);
                    // Output relationship start_node_id.
                    console.log(relationship._start);
                    // Output relationship end_node_id.
                    console.log(relationship._end);
                })
            }).then(function() {
                db.cypherQuery(" MATCH (n:User) WHERE n.name ='" + req.authorization.basic.username + "' RETURN n", function(err, Results) {
                    if(err) throw err;
                    console.log('name = ' + Results.data[0])
                    console.log('user = ' + Results.data[0]._id)
                    userid = Results.data[0]._id
                    console.log('userid =' + userid)
                    console.log(groupid)
                    return userid
                })
            }).then(function(id) {
                db.insertRelationship(userid, groupid, 'IN_GROUP', {
                    description: 'Created this group'
                }, function(err, relationship) {
                    if(err) throw err;
                    console.log('relationship made')
                    // Output relationship id.
                    console.log(relationship._id);
                    // Output relationship start_node_id.
                    console.log(relationship._start);
                    // Output relationship end_node_id.
                    console.log(relationship._end);
                })
            }).then(function() {
                var d = new Date(),
                    date = d.toUTCString();
                console.log(date);
                var doc = {
                    groupname: groupname,
                    description: description,
                    date_joined: date,
                    last_modified: date,
                    createdby: req.authorization.basic.username,
                    grouppoints: 0,
                    transactions: [],
                    usersjoined: [req.authorization.basic.username],
                    competition: competition,
                    groupnodeid: groupid
                };
                var docStr = JSON.stringify(doc);
                var params = {
                    uri: url,
                    body: JSON.stringify(doc)
                };
                return params
            }).then(function(params) {
                request.put(params, function(err, response, body) {
                    if(err) {
                        return next(new restify.InternalServerError('Cant create document'));
                    }
                    // document has been inserted into database
                    body = JSON.parse(body);
                    console.log('about to sent res')
                    res.send({
                        Group: req.params
                    });
                    res.end();
                });
            })
        },
        getRequest: function(url) {
            // set up initial get request.
            return new Promise(function(resolve, reject) {
                request.get(url, function(err, response, body) {
                    if(err) reject(err);
                    // if the document isnt found it will create it from sratch
                    console.log('code' + response.statusCode)
                    resolve({
                        response: response,
                        body: body
                    })
                })
            });
        },
        putRequest: function(params) {
            return new Promise(function(resolve, reject) {
                request.put(params, function(err, response, body) {
                    if(err) reject(err);
                    // if the document isnt found it will create it from sratch
                    console.log('code' + response.statusCode)
                    resolve({
                        response: response,
                        body: body
                    })
                })
            });
        },
        nodequery: function(query) {
            return new Promise(function(resolve, reject) {})
        }
    }
})();
module.exports.delgroup = function(req, res, next) {
    // check group exists
    // check owner is correct
    // delete relationships
    // delete couchdb
    //
    // send back success.
}<commit_msg>changed from IIFE<commit_after>var validateHTTP = require("./validateHTTP.js"),
    restify = require('restify'),
    request = require('request'),
    rand = require('csprng'),
    sha1 = require('sha1'),
    uuid = require('node-uuid'),
    neo4j = require('node-neo4j'),
    Promise = require('promise');
module.exports.creategroup = function(req, res, next) {
    if((validateHTTP.validateHTTP(req, res, next, 'users')) === true) {
        db = new neo4j('http://localhost:7474');
        console.log('NEW GROUP!');
        console.log('PUT: ' + req.params.groupname)
        console.log('FOR COMPETITION: ' + req.params.competition)
        var url = 'http://localhost:5984/groups/' + req.params.groupname;
        var competition = req.params.competition
        var groupname = req.params.groupname
        var description = req.params.description
        var groupid = 0;
        var userid = 0;
        validateHTTP.validateHTTP(req, res, next, 'users')
        var topres = res
        request.get(url, function(err, response, body) {
            if(err) {
                return next(new restify.InternalServerError('Error has occured'));
            }
            // if the document isnt found it will create it from sratch
            console.log('code' + response.statusCode)
            if(response.statusCode === 200) {
                return next(new restify.ConflictError('Group Already Created'));
            } else if(response.statusCode === 404) {
                db.cypherQuery(" MATCH (n:competition) WHERE n.name ='" + competition + "' RETURN n", function(err, result) {
                    if(err) throw err;
                    if(result.data.length == 0) {
                        return next(new restify.InternalServerError('no competition found'));
                    } else {
                        var competitionid = result.data[0]._id
                        console.log('Groupname = ' + groupname)
                        db.cypherQuery("MATCH (n:group) WHERE n.name ='" + groupname + "' RETURN n", function(err, results) {
                            if(err) throw err;
                            console.log('Group data = ' + results.data)
                            if(results.data.length == 0) {
                                db.insertNode({
                                    name: groupname,
                                    description: description
                                }, ['Group', competition], function(err, node) {
                                    if(err) throw err;
                                    // Output node properties.
                                    console.log('New neo4j node created with Groupname  = ' + node.name);
                                    groupid = node._id
                                    console.log('group id = ' + groupid)
                                    console.log('starting insert relationship')
                                    db.insertRelationship(node._id, competitionid, 'COMPETING_IN', {
                                        description: 'competiting in this competition'
                                    }, function(err, relationship) {
                                        if(err) throw err;
                                        console.log('relationship made')
                                        // Output relationship id.
                                        console.log(relationship._id);
                                        // Output relationship start_node_id.
                                        console.log(relationship._start);
                                        // Output relationship end_node_id.
                                        console.log(relationship._end);
                                        db.cypherQuery(" MATCH (n:User) WHERE n.name ='" + req.authorization.basic.username + "' RETURN n", function(err, Results) {
                                            if(err) throw err;
                                            console.log('name = ' + Results.data[0])
                                            console.log('user = ' + Results.data[0]._id)
                                            userid = Results.data[0]._id
                                            console.log('userid =' + userid)
                                            console.log(groupid)
                                            db.insertRelationship(userid, groupid, 'IN_GROUP', {
                                                description: 'Created this group'
                                            }, function(err, relationship) {
                                                if(err) throw err;
                                                console.log('relationship made')
                                                // Output relationship id.
                                                console.log(relationship._id);
                                                // Output relationship start_node_id.
                                                console.log(relationship._start);
                                                // Output relationship end_node_id.
                                                console.log(relationship._end);
                                                var d = new Date(),
                                                    date = d.toUTCString();
                                                console.log(date);
                                                var doc = {
                                                    groupname: groupname,
                                                    description: description,
                                                    date_joined: date,
                                                    last_modified: date,
                                                    createdby: req.authorization.basic.username,
                                                    grouppoints: 0,
                                                    transactions: [],
                                                    usersjoined: [req.authorization.basic.username],
                                                    competition: competition,
                                                    groupnodeid: groupid
                                                };
                                                var docStr = JSON.stringify(doc);
                                                var params = {
                                                    uri: url,
                                                    body: JSON.stringify(doc)
                                                };
                                                request.put(params, function(err, response, body) {
                                                    if(err) {
                                                        return next(new restify.InternalServerError('Cant create document'));
                                                    }
                                                    // document has been inserted into database
                                                    body = JSON.parse(body);
                                                    console.log('about to sent res')
                                                    topres.send({
                                                        Group: req.params
                                                    });
                                                    topres.end();
                                                });
                                            });
                                        });
                                    });
                                });
                            } else {
                                console.log(result.data[0])
                                return next(new restify.ConflictError('Group already created'));
                            }
                        })
                    }
                    console.log(result.data.length); // delivers an array of query results
                });
                //
            };
        });
        // if the document is found, that means the user is already created.
    }
};
module.exports.showgroup = function(req, res, next) {
    db = new neo4j('http://localhost:7474');
    console.log('GET');
    console.log('GET: ' + req.params.groupname);
    var url = 'http://localhost:5984/groups/' + req.params.groupname;
    validateHTTP.validateHTTP(req, res, next, "users")
    var topres = res
    request.get(url, function(err, response, body) {
        if(err) {
            return next(new restify.InternalServerError('Failed To Connect To Database'));
        }
        // if the document isnt found it will create it from sratch
        console.log('code' + response.statusCode)
        if(response.statusCode === 200) {
            body = JSON.parse(body);
            //res.header('ETag', body._rev);
            res.header('Last-Modified', body.last_modified);
            res.header('Accepts', 'GET');
            group = {
                id: body._id,
                groupname: body.groupname,
                description: body.description,
                last_modified: body.last_modified,
                points: body.grouppoints,
                transactions: body.transactions,
                owner: body.createdby,
                groupmemebers: body.usersjoined
            }
            console.log(group)
            console.log("Set Group data");
            res.send(group);
            console.log("sent group data");
            res.end();
        } else if(response.statusCode === 404) {
            return next(new restify.ConflictError('Group Already Created'));
        }
    });
};
module.exports.showcompetitiongroup = function(req, res, next) {
    //match (n:freshers)-[COMPETING_IN]->r return n,r
    db = new neo4j('http://localhost:7474');
    console.log('GET');
    console.log('GET COMPETITION GROUPS: ' + req.params.competition)
    var url = 'http://localhost:5984/groups/' + req.params.groupname;
    var competition = req.params.competition
    validateHTTP.validateHTTP(req, res, next)
    var topres = res
    db.cypherQuery("match (n:" + competition + ")-[COMPETING_IN]->r return labels(n),n,r", function(err, Results) {
        if(err) throw err;
        if(Results.data == 0) {
            return next(new restify.NotFoundError('Competition not found'));
        } else {
            res.send(Results.data);
            console.log("competition data sent");
            res.end();
        }
    });
};
module.exports.joinGroup = function(req, res, next) {
    var db = new neo4j('http://localhost:7474');
    console.log('PUT');
    console.log('JOIN GROUP: ' + req.params.username + ' ' + req.params.groupname)
    var url = 'http://localhost:5984/users/' + req.authorization.basic.username;
    var groupurl = 'http://localhost:5984/groups/' + req.params.groupname;
    var userid = 0,
        groupid = 0,
        groupname = req.params.groupname,
        username = req.authorization.basic.username;
    validateHTTP.validateHTTP(req, res, next, "users");
    var topres = res
    //check user exists
    request.get(url, function(err, response, body) {
        console.log("request started")
        // if user is not found will send 404 error
        if(response.statusCode == 404) {
            return next(new restify.BadRequestError('User Not Found'))
        };
        if(response.statusCode == 200) {
            body = JSON.parse(body);
            console.log('set user id')
            userid = body.nodeid;
            //check group exists
            db.cypherQuery("match n where n.name='" + groupname + "' return n", function(err, Results) {
                if(err) throw err;
                if(Results.data == 0) {
                    return next(new restify.NotFoundError('Group not found'));
                } else {
                    groupid = Results.data[0]._id
                    console.log("Group ID set");
                    var d = new Date(),
                        date = d.toUTCString();
                    console.log(date);
                    //make relationship
                    db.insertRelationship(userid, groupid, 'IN_GROUP', {
                        datejoined: date,
                    }, function(err, relationship) {
                        if(err) throw err;
                        console.log("set user");
                        res.send("relationship created @ " + date);
                        console.log("sent data");
                        res.end();
                    });
                }
            });
        };
    });
};
// rebuilding with promises and closures
module.exports.groups = function() {
    var url = "",
        competition = "",
        groupname = "",
        description = "",
        groupid = 0,
        userid = 0,
        competitionid = "";
    return {
        createGroup: function(req, res, next) {
            console.log(req.params)
            console.log("group create started")
            console.log("POST "  + req.params.groupname )
            url = 'http://localhost:5984/groups/' + req.params.groupname
            var competition = req.params.competition;
            var groupname = req.params.groupname;
            var description = req.params.description;
            console.log(competition + " Group :"  + groupname + " Description: " + description)
            var groupid = 0;
            var userid = 0;
            getRequest(url).
            catch(function(err) {
                console.log("get request error")
                return next(new restify.InternalServerError('Error has occured'));
            }).then(function(call) {
                if(response.statusCode === 200) {
                    return next(new restify.ConflictError('Group Already Created'));
                }
            }).then(db.cypherQuery(" MATCH (n:competition) WHERE n.name ='" + competition + "' RETURN n", function(err, result) {
                if(err) throw err;
                if(result.data.length == 0) {
                    return next(new restify.InternalServerError('no competition found'));
                }
                return competitionid = result.data[0]._id
            })).then(function(i1d) {
                db.cypherQuery("MATCH (n:group) WHERE n.name ='" + groupname + "' RETURN n", function(err, results) {
                    if(err) throw err;
                    if(results.data.length == 0) {
                        return results.data
                    } else {
                        console.log(result.data[0])
                        return next(new restify.ConflictError('Group already created'));
                    }
                })
            }).then(function(data) {
                db.insertNode({
                    name: groupname,
                    description: description
                }, ['Group', competition], function(err, node) {
                    if(err) throw err;
                    // Output node properties.
                    console.log('New neo4j node created with Groupname  = ' + node.name);
                    groupid = node._id
                    console.log('group id = ' + groupid)
                    return node._id
                });
            }).then(function(nodeid) {
                db.insertRelationship(node._id, competitionid, 'COMPETING_IN', {
                    description: 'competiting in this competition'
                }, function(err, relationship) {
                    if(err) throw err;
                    console.log('relationship made')
                    // Output relationship id.
                    console.log(relationship._id);
                    // Output relationship start_node_id.
                    console.log(relationship._start);
                    // Output relationship end_node_id.
                    console.log(relationship._end);
                })
            }).then(function() {
                db.cypherQuery(" MATCH (n:User) WHERE n.name ='" + req.authorization.basic.username + "' RETURN n", function(err, Results) {
                    if(err) throw err;
                    console.log('name = ' + Results.data[0])
                    console.log('user = ' + Results.data[0]._id)
                    userid = Results.data[0]._id
                    console.log('userid =' + userid)
                    console.log(groupid)
                    return userid
                })
            }).then(function(id) {
                db.insertRelationship(userid, groupid, 'IN_GROUP', {
                    description: 'Created this group'
                }, function(err, relationship) {
                    if(err) throw err;
                    console.log('relationship made')
                    // Output relationship id.
                    console.log(relationship._id);
                    // Output relationship start_node_id.
                    console.log(relationship._start);
                    // Output relationship end_node_id.
                    console.log(relationship._end);
                })
            }).then(function() {
                var d = new Date(),
                    date = d.toUTCString();
                console.log(date);
                var doc = {
                    groupname: groupname,
                    description: description,
                    date_joined: date,
                    last_modified: date,
                    createdby: req.authorization.basic.username,
                    grouppoints: 0,
                    transactions: [],
                    usersjoined: [req.authorization.basic.username],
                    competition: competition,
                    groupnodeid: groupid
                };
                var docStr = JSON.stringify(doc);
                var params = {
                    uri: url,
                    body: JSON.stringify(doc)
                };
                return params
            }).then(function(params) {
                request.put(params, function(err, response, body) {
                    if(err) {
                        return next(new restify.InternalServerError('Cant create document'));
                    }
                    // document has been inserted into database
                    body = JSON.parse(body);
                    console.log('about to sent res')
                    res.send({
                        Group: req.params
                    });
                    res.end();
                });
            })
        },
        getRequest: function(url) {
            // set up initial get request.
            return new Promise(function(resolve, reject) {
                request.get(url, function(err, response, body) {
                    if(err) reject(err);
                    // if the document isnt found it will create it from sratch
                    console.log('code' + response.statusCode)
                    resolve({
                        response: response,
                        body: body
                    })
                })
            });
        },
        putRequest: function(params) {
            return new Promise(function(resolve, reject) {
                request.put(params, function(err, response, body) {
                    if(err) reject(err);
                    // if the document isnt found it will create it from sratch
                    console.log('code' + response.statusCode)
                    resolve({
                        response: response,
                        body: body
                    })
                })
            });
        },
        nodequery: function(query) {
            return new Promise(function(resolve, reject) {})
        }
    }
}
module.exports.delgroup = function(req, res, next) {
    // check group exists
    // check owner is correct
    // delete relationships
    // delete couchdb
    //
    // send back success.
}<|endoftext|>


<commit_before>// View model for the courses page
function pageViewModel(gvm) {
    // Page specific i18n bindings
    gvm.app  = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectRapportName")}, gvm);
    gvm.title = ko.computed(function(){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("CourseTitle2");}, gvm);
    gvm.pageHeader = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("CourseTitle2");}, gvm);
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectRapportName");}, gvm);

    gvm.availableLocations = ko.observableArray([]);
    gvm.availableTrainings = ko.observableArray([]);
    gvm.availableCourses = ko.observableArray([]);

    /*Teacher*/
    gvm.availableTeacher = ko.observableArray([]);
    gvm.currentteacherid = null;
    /*teacher*/

    // Pagination i18n bindings
    gvm.addBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddBtn")}, gvm);

    gvm.codeTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("CodeTableTitle");}, gvm);
    gvm.nameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("NameTableTitle");}, gvm);
    gvm.descTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("DescTableTitle");}, gvm);
    gvm.teacherTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("TeacherTableTitle");}, gvm);
    gvm.actionTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ActionTableTitle");}, gvm);

    // The table data observable array
    gvm.tabledata = ko.observableArray([]);

    // Add data to the table
    gvm.addTableData = function(id, code, name, desc, teach) {
        // Push data
        var tblOject = {tid: id, tcode: code, tname: name, tdesc: desc, tteach:
                            function(id)
                            {
                                getTeacher(id);
                            }
                       };
        gvm.tabledata.push(tblOject);

        // Attach delete handler to delete button
        $('#removebtn-' + id).bind('click', function(event, data){
            // Delete the table item
            deleteTableItem(id, tblOject);
            event.stopPropagation();
        });

        // Attach edit handler to edit button
        $('#editbtn-' + id).bind('click', function(event, data){
            // Edit the table item
            showEditProjectTypeModal(code, name, desc, id);
            event.stopPropagation();
        });

        // Attach copy handler to copy button
        $('#copybtn-' + id).bind('click', function(event, data){
            // Delete the table item
            copyTableItem(id, tblOject);
            event.stopPropagation();
        });

        //Attach manage handler to manage competences, subcompetences and indicators to manage button
        $('#managebtn-' + id).bind('click', function(event, data) {
            //TODO
        });

        /*$('#studentbtn-' + id).bind('click', function(event, data) {
            showCoupleStudentListModal(id);
            gvm.currentprojectid = id;
            gvm.currentselectedlist = -1;
            event.stopPropagation();
            loadCoupleDropdown();
        });*/
    }

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    }
    /*
    gvm.updateDropdowns = function() {
        $.getJSON('api/teacherrapport/' + gvm.userId, function(data) {
            if(!$.isEmptyObject(data)) {
                $.each(data, function(i, item) {
                    $(".btn-teacher span:first").text(item.teacher);
                    gvm.currentteacherid = item.id;
                    gvm.updateTeacher(item.id);
                    LoadTablePage(item.currentteacherid, 1);
                });
            } else {
                gvm.updateTeacher();
            }
        });
    }*/

    gvm.updateTeacher = function(id) {
        $.getJSON('/api/getteacherrapport/' + id, function(data) {
            gvm.availableTeacher.removeAll();
            $.each(data, function(i, item) {
                console.log(item);
                gvm.availableTeacher.push(item);
                $("#teacherbtn-" + item.id).click(function(){
                    $(".btn-teacher span:first").text($(this).text());
                    gvm.currentteacherid = item.id;
                    gvm.saveLastSelectedDropdowns();
                    loadTablePage(item.id, 1);
                });
            });
        });
    }

    }

/*
 * Delete item from table given the id.
 */
function deleteTableItem(id, tblOject) {
    showYesNoModal("Bent u zeker dat u dit item wil verwijderen? \r\n Let op: verwijderde items blijven in het systeem en kunnen weer actief gezet worden door een administrator. \r\n Gelieve de administrator te contacteren om een vak definitief te verwijderen.", function(val){
        if(val){
            $.ajax({
                url: "/api/coursedelete/" + id,
                type: "DELETE",
                success: function() {
                    viewModel.tabledata.remove(tblOject);
                }
            });
        }
    });
}
/*
 * Delete item from table given the id.
 */
function copyTableItem(id, tblOject) {
    showYesNoModal("Bent u zeker dat u dit item wil verwijderen? \r\n Let op: verwijderde items blijven in het systeem en kunnen weer actief gezet worden door een administrator. \r\n Gelieve de administrator te contacteren om een vak definitief te verwijderen.", function(val){
        if(val){
            $.ajax({
                url: "/api/coursecopy/" + id,
                type: "post",
                success: function() {
                    viewModel.tabledata.remove(tblOject);
                }
            });
        }
    });
}

/*
 * Add a new projecttype
 */
function addNewProjecttypeForm(serialData, callback) {
    $.ajax({
            url: "/api/courserapport",
            type: "POST",
            data: serialData,
            success: function(data) {
                viewModel.addTableData(data['id'], data['code'], data['name'], data['description']);
                callback(true);
            },
            error: function(data) {
                callback(false);
            }
        });
}

/*
 * Add a new projecttype
 */
function addNewProjecttypeRaw(code, name, description, callback) {
    addNewProjecttypeForm("code=" + encodeURIComponent(code) + "&name=" + encodeURIComponent(name) + "&description=" + encodeURIComponent(description), callback);
}

/*
 * Update the projecttype
 * @param {type} id
 * @param {type} code
 * @param {type} name
 * @param {type} description
 * @param {type} callback
 * @returns {undefined}
 */
function updateProjecttypeForm(id, serialData, callback) {
    $.ajax({
        url: "/api/courseupdate/" + id,
        type: "PUT",
        data: serialData,
        success: function(data) {
            //viewModel.addTableData(data['id'], data['code'], data['name'], data['description']);
            loadTablePage(1); //TODO now it is refreshing table after updating but it redirects to pagenr 1     WERKT NIET
            callback(true);
        },
        error: function(data) {
            callback(false);
        }
    });
}

/**
 * update project type
 * @param {type} id
 * @param {type} code
 * @param {type} name
 * @param {type} description
 * @param {type} callback
 * @returns {undefined}
 */
function updateProjecttypeRaw(id, code, name, description, callback) {
    updateProjecttypeForm(id, "code=" + encodeURIComponent(code) + "&name=" + encodeURIComponent(name) + "&description=" + encodeURIComponent(description), callback);
}

/*
 * Load page of the table
 */
function loadTablePage(pagenr)
{
    $.getJSON('/api/coursesrapport/page/' + pagenr, function(data){

        /* Clear current table page */
        viewModel.clearTable();

        // Load table data
        $.each(data.data, function(i, item) {
            viewModel.addTableData(item.id, item.code, item.name, item.description, item.leerkracht);
        });

        /* Let previous en next buttons work */
        if(data.prev == "none"){
            $('#pager-prev-btn').addClass('disabled');
        } else {
            $('#pager-prev-btn').removeClass('disabled');
            $('#pager-prev-btn a').click(function(){
                loadTablePage(data.prev);
            });
        }

        if(data.next == "none"){
            $('#pager-next-btn').addClass('disabled');
        } else {
            $('#pager-next-btn').removeClass('disabled');
            $('#pager-next-btn a').click(function(){
                loadTablePage(data.next);
            });
        }

        // Number of pager buttons
        var numItems = $('.pager-nr-btn').length;

        /* Calculate for the pager buttons */
        var lowPage = Math.floor(pagenr/numItems) + 1;

        $('.pager-nr-btn').each(function() {
            /* calculate current page number */
            var thispagenr = lowPage++;

            /* Add the page number */
            $(this).html('' + thispagenr + '');

            /* Add active class to current page */
            if(thispagenr == pagenr) {
                $(this).addClass('active');
            } else {
                $(this).removeClass('active');
            }

            /* Disable inactive classes and bind handlers to active classes */
            if(thispagenr > data.pagecount) {
                $(this).addClass('disabled');
            } else {
                /* Add click listener for button */
                $(this).click(function() {
                    loadTablePage(thispagenr);
                });
            }
        });
    });

}

/**
 * Show a new projecttype modal.
 * @returns {undefined}
 */
function showNewProjectTypeModal()
{
    resetGeneralModal();
    setGeneralModalTitle(i18n.__("AddNewCourse"));
    setGeneralModalBody('<form id="newprojectform"> \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('CodeTableTitle') + '" " name="code"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('NameTableTitle') + '" name="name"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('DescTableTitle') + '" name="description"> \

 \

' +
                '<button class="btn btn-wide btn-default btn-teacher dropdown-toggle" type="button" id="availableTeacher" data-toggle="dropdown" aria-expanded="true" placeholder="' + i18n.__('TeacherTableTitle') + '">' +
                'Teacher' + '' +
                '</button>' +
                '
' +
                '

' +
                '
' +
            '
' +
            '</form>' );

    addGeneralModalButton(i18n.__("AddBtn"), function(){
        console.log($('#newprojectform').serialize());
       addNewProjecttypeForm($('#newprojectform').serialize(), function(result){
            hideModal();
        });
    });

    showGeneralModal();
}

/**
 * Show the edit projecttype modal.
 * @param {type} code
 * @param {type} name
 * @param {type} description
 * @param {type} tid
 * @returns {undefined}
 */
function showEditProjectTypeModal(code, name, description, tid)
{
  resetGeneralModal();
    setGeneralModalTitle(i18n.__("EditProjectTitle2"));
    setGeneralModalBody('<form id="updateprojectform"> \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('CodeTableTitle') + '" " name="code" value="' + code + '"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('NameTableTitle') + '" name="name" value="' + name + '"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('DescTableTitle') + '" name="description" value="' + description + '"> \

 \
        </form>');
    $.getJSON()

    addGeneralModalButton(i18n.__("SaveBtn"), function(){
        updateProjecttypeForm(tid, $('#updateprojectform').serialize(), function(result){
            hideModal();
        });
    });

    addGeneralModalButton(i18n.__("CancelBtn"), function(){
        hideModal();
    })

    showGeneralModal();
}

function showCoupleStudentListModal(projectid) {
    viewModel.currentselectedlist = -1;
    resetGeneralModal();
    setGeneralModalTitle(i18n.__("CoupleStudentList"));
    setGeneralModalBody(
        '
' +
            '<button class="btn btn-default dropdown-toggle" type="button" id="dropdownStudLists" data-toggle="dropdown" aria-expanded="true">' +
                'Dropdown' +
                '' +
            '</button>' +
            '
' +
            '
' +
        '
');

    addGeneralModalButton(i18n.__("SaveBtn"), function() {
        updateListForm(viewModel.currentselectedlist, $('#coupleform').serialize(), function(result){
            hideModal();
        });
    });

    addGeneralModalButton(i18n.__("CancelBtn"), function(){
        hideModal();
    })
    showGeneralModal();
}
function loadCoupleDropdown() {
    $.getJSON('/api/studentlists/' + viewModel.userId, function(data) {
        $.each(data, function(i, item) {
            $("#ddlLists").append('
' + item.name + '
')
            $("#dropdownitem-" + item.id).click(function(){
                $(this).parent().parent().parent().removeClass("open");
                $(this).parent().parent().parent().find(".btn").html($(this).text() + '');
                viewModel.currentselectedlist = item.id;
            });
        });
    });
    $("#dropdownStudLists").click(function() {
        $(this).parent().toggleClass("open");
    });
}

function updateListForm(id, serialData, callback) {
    $.ajax({
        url: "/api/project/" + viewModel.currentprojectid + "/studentlist/" + id,
        type: "POST",
        data: serialData,
        success: function(data) {
            callback(true);
        },
        error: function(data) {
            callback(false);
        }
    });
}

function initPage() {
    // Add button handlers
    $('#addProjectTypeBtn').click(function(){
        showNewProjectTypeModal();
    });

    $.getJSON('/api/currentuser', function(data) {
        viewModel.userId = data.id;
        /*viewModel.updateDropdowns();*/
    });

    loadTablePage(1);
}

<commit_msg>update/edit courses<commit_after>// View model for the courses page
function pageViewModel(gvm) {
    // Page specific i18n bindings
    gvm.app  = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectRapportName")}, gvm);
    gvm.title = ko.computed(function(){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("CourseTitle2");}, gvm);
    gvm.pageHeader = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("CourseTitle2");}, gvm);
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectRapportName");}, gvm);

    gvm.availableLocations = ko.observableArray([]);
    gvm.availableTrainings = ko.observableArray([]);
    gvm.availableCourses = ko.observableArray([]);

    /*Teacher*/
    gvm.availableTeacher = ko.observableArray([]);
    gvm.currentteacherid = null;
    /*teacher*/

    // Pagination i18n bindings
    gvm.addBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddBtn")}, gvm);

    gvm.codeTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("CodeTableTitle");}, gvm);
    gvm.nameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("NameTableTitle");}, gvm);
    gvm.descTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("DescTableTitle");}, gvm);
    gvm.teacherTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("TeacherTableTitle");}, gvm);
    gvm.actionTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ActionTableTitle");}, gvm);

    // The table data observable array
    gvm.tabledata = ko.observableArray([]);

    // Add data to the table
    gvm.addTableData = function(id, code, name, desc, teach) {
        // Push data
        var tblOject = {tid: id, tcode: code, tname: name, tdesc: desc, tteach: teach};
        gvm.tabledata.push(tblOject);

        // Attach delete handler to delete button
        $('#removebtn-' + id).bind('click', function(event, data){
            // Delete the table item
            deleteTableItem(id, tblOject);
            event.stopPropagation();
        });

        // Attach edit handler to edit button
        $('#editbtn-' + id).bind('click', function(event, data){
            // Edit the table item
            showEditProjectTypeModal(code, name, desc, id);
            event.stopPropagation();
        });

        // Attach copy handler to copy button
        $('#copybtn-' + id).bind('click', function(event, data){
            // Delete the table item
            copyTableItem(id, tblOject);
            event.stopPropagation();
        });

        //Attach manage handler to manage competences, subcompetences and indicators to manage button
        $('#managebtn-' + id).bind('click', function(event, data) {
            //TODO
        });

        /*$('#studentbtn-' + id).bind('click', function(event, data) {
            showCoupleStudentListModal(id);
            gvm.currentprojectid = id;
            gvm.currentselectedlist = -1;
            event.stopPropagation();
            loadCoupleDropdown();
        });*/
    }

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    }
    /*
    gvm.updateDropdowns = function() {
        $.getJSON('api/teacherrapport/' + gvm.userId, function(data) {
            if(!$.isEmptyObject(data)) {
                $.each(data, function(i, item) {
                    $(".btn-teacher span:first").text(item.teacher);
                    gvm.currentteacherid = item.id;
                    gvm.updateTeacher(item.id);
                    LoadTablePage(item.currentteacherid, 1);
                });
            } else {
                gvm.updateTeacher();
            }
        });
    }*/

    gvm.updateTeacher = function(id) {
        $.getJSON('/api/getteacherrapport/' + id, function(data) {
            gvm.availableTeacher.removeAll();
            $.each(data, function(i, item) {
                console.log(item);
                gvm.availableTeacher.push(item);
                $("#teacherbtn-" + item.id).click(function(){
                    $(".btn-teacher span:first").text($(this).text());
                    gvm.currentteacherid = item.id;
                    gvm.saveLastSelectedDropdowns();
                    loadTablePage(item.id, 1);
                });
            });
        });
    }

    }

/*
 * Delete item from table given the id.
 */
function deleteTableItem(id, tblOject) {
    showYesNoModal("Bent u zeker dat u dit item wil verwijderen? \r\n Let op: verwijderde items blijven in het systeem en kunnen weer actief gezet worden door een administrator. \r\n Gelieve de administrator te contacteren om een vak definitief te verwijderen.", function(val){
        if(val){
            $.ajax({
                url: "/api/coursedelete/" + id,
                type: "DELETE",
                success: function() {
                    viewModel.tabledata.remove(tblOject);
                }
            });
        }
    });
}
/*
 * Delete item from table given the id.
 */
function copyTableItem(id, tblOject) {
    showYesNoModal("Bent u zeker dat u dit item wil verwijderen? \r\n Let op: verwijderde items blijven in het systeem en kunnen weer actief gezet worden door een administrator. \r\n Gelieve de administrator te contacteren om een vak definitief te verwijderen.", function(val){
        if(val){
            $.ajax({
                url: "/api/coursecopy/" + id,
                type: "post",
                success: function() {
                    viewModel.tabledata.remove(tblOject);
                }
            });
        }
    });
}

/*
 * Add a new projecttype
 */
function addNewProjecttypeForm(serialData, callback) {
    $.ajax({
            url: "/api/courserapport",
            type: "POST",
            data: serialData,
            success: function(data) {
                viewModel.addTableData(data['id'], data['code'], data['name'], data['description']);
                callback(true);
            },
            error: function(data) {
                callback(false);
            }
        });
}

/*
 * Add a new projecttype
 */
function addNewProjecttypeRaw(code, name, description, callback) {
    addNewProjecttypeForm("code=" + encodeURIComponent(code) + "&name=" + encodeURIComponent(name) + "&description=" + encodeURIComponent(description), callback);
}

/*
 * Update the projecttype
 * @param {type} id
 * @param {type} code
 * @param {type} name
 * @param {type} description
 * @param {type} callback
 * @returns {undefined}
 */
function updateProjecttypeForm(id, serialData, callback) {
    $.ajax({
        url: "/api/courseupdate/" + id,
        type: "PUT",
        data: serialData,
        success: function(data) {
            //viewModel.addTableData(data['id'], data['code'], data['name'], data['description']);
            loadTablePage(1); //TODO now it is refreshing table after updating but it redirects to pagenr 1     WERKT NIET
            callback(true);
        },
        error: function(data) {
            callback(false);
        }
    });
}

/**
 * update project type
 * @param {type} id
 * @param {type} code
 * @param {type} name
 * @param {type} description
 * @param {type} callback
 * @returns {undefined}
 */
function updateProjecttypeRaw(id, code, name, description, callback) {
    updateProjecttypeForm(id, "code=" + encodeURIComponent(code) + "&name=" + encodeURIComponent(name) + "&description=" + encodeURIComponent(description), callback);
}

/*
 * Load page of the table
 */
function loadTablePage(pagenr)
{
    $.getJSON('/api/coursesrapport/page/' + pagenr, function(data){

        /* Clear current table page */
        viewModel.clearTable();

        // Load table data
        $.each(data.data, function(i, item) {
            viewModel.addTableData(item.id, item.code, item.name, item.description, item.leerkracht);
        });

        /* Let previous en next buttons work */
        if(data.prev == "none"){
            $('#pager-prev-btn').addClass('disabled');
        } else {
            $('#pager-prev-btn').removeClass('disabled');
            $('#pager-prev-btn a').click(function(){
                loadTablePage(data.prev);
            });
        }

        if(data.next == "none"){
            $('#pager-next-btn').addClass('disabled');
        } else {
            $('#pager-next-btn').removeClass('disabled');
            $('#pager-next-btn a').click(function(){
                loadTablePage(data.next);
            });
        }

        // Number of pager buttons
        var numItems = $('.pager-nr-btn').length;

        /* Calculate for the pager buttons */
        var lowPage = Math.floor(pagenr/numItems) + 1;

        $('.pager-nr-btn').each(function() {
            /* calculate current page number */
            var thispagenr = lowPage++;

            /* Add the page number */
            $(this).html('' + thispagenr + '');

            /* Add active class to current page */
            if(thispagenr == pagenr) {
                $(this).addClass('active');
            } else {
                $(this).removeClass('active');
            }

            /* Disable inactive classes and bind handlers to active classes */
            if(thispagenr > data.pagecount) {
                $(this).addClass('disabled');
            } else {
                /* Add click listener for button */
                $(this).click(function() {
                    loadTablePage(thispagenr);
                });
            }
        });
    });

}

/**
 * Show a new projecttype modal.
 * @returns {undefined}
 */
function showNewProjectTypeModal()
{
    resetGeneralModal();
    setGeneralModalTitle(i18n.__("AddNewCourse"));
    setGeneralModalBody('<form id="newprojectform"> \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('CodeTableTitle') + '" " name="code"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('NameTableTitle') + '" name="name"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('DescTableTitle') + '" name="description"> \

 \

' +
                '<button class="btn btn-wide btn-default btn-teacher dropdown-toggle" type="button" id="availableTeacher" data-toggle="dropdown" aria-expanded="true" placeholder="' + i18n.__('TeacherTableTitle') + '">' +
                'Teacher' + '' +
                '</button>' +
                '
' +
                '

' +
                '
' +
            '
' +
            '</form>' );

    addGeneralModalButton(i18n.__("AddBtn"), function(){
        console.log($('#newprojectform').serialize());
       addNewProjecttypeForm($('#newprojectform').serialize(), function(result){
            hideModal();
        });
    });

    showGeneralModal();
}

/**
 * Show the edit projecttype modal.
 * @param {type} code
 * @param {type} name
 * @param {type} description
 * @param {type} tid
 * @returns {undefined}
 */
function showEditProjectTypeModal(code, name, description, tid)
{
  resetGeneralModal();
    setGeneralModalTitle(i18n.__("EditProjectTitle2"));
    setGeneralModalBody('<form id="updateprojectform"> \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('CodeTableTitle') + '" " name="code" value="' + code + '"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('NameTableTitle') + '" name="name" value="' + name + '"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('DescTableTitle') + '" name="description" value="' + description + '"> \

 \
        </form>');
    $.getJSON()

    addGeneralModalButton(i18n.__("SaveBtn"), function(){
        updateProjecttypeForm(tid, $('#updateprojectform').serialize(), function(result){
            hideModal();
        });
    });

    addGeneralModalButton(i18n.__("CancelBtn"), function(){
        hideModal();
    })

    showGeneralModal();
}

function showCoupleStudentListModal(projectid) {
    viewModel.currentselectedlist = -1;
    resetGeneralModal();
    setGeneralModalTitle(i18n.__("CoupleStudentList"));
    setGeneralModalBody(
        '
' +
            '<button class="btn btn-default dropdown-toggle" type="button" id="dropdownStudLists" data-toggle="dropdown" aria-expanded="true">' +
                'Dropdown' +
                '' +
            '</button>' +
            '
' +
            '
' +
        '
');

    addGeneralModalButton(i18n.__("SaveBtn"), function() {
        updateListForm(viewModel.currentselectedlist, $('#coupleform').serialize(), function(result){
            hideModal();
        });
    });

    addGeneralModalButton(i18n.__("CancelBtn"), function(){
        hideModal();
    })
    showGeneralModal();
}
function loadCoupleDropdown() {
    $.getJSON('/api/studentlists/' + viewModel.userId, function(data) {
        $.each(data, function(i, item) {
            $("#ddlLists").append('
' + item.name + '
')
            $("#dropdownitem-" + item.id).click(function(){
                $(this).parent().parent().parent().removeClass("open");
                $(this).parent().parent().parent().find(".btn").html($(this).text() + '');
                viewModel.currentselectedlist = item.id;
            });
        });
    });
    $("#dropdownStudLists").click(function() {
        $(this).parent().toggleClass("open");
    });
}

function updateListForm(id, serialData, callback) {
    $.ajax({
        url: "/api/project/" + viewModel.currentprojectid + "/studentlist/" + id,
        type: "POST",
        data: serialData,
        success: function(data) {
            callback(true);
        },
        error: function(data) {
            callback(false);
        }
    });
}

function initPage() {
    // Add button handlers
    $('#addProjectTypeBtn').click(function(){
        showNewProjectTypeModal();
    });

    $.getJSON('/api/currentuser', function(data) {
        viewModel.userId = data.id;
        /*viewModel.updateDropdowns();*/
    });

    loadTablePage(1);
}

<|endoftext|>


<commit_before>$.get('http://repairnator.lille.inria.fr/repairnator-mongo-api/scanners/weeksData/2', function (data) {
  console.log(data);
  var htmlElement = $('

');
  $('#charts').append(htmlElement);

  /*
   {
   '_id': '58e22490cefc9665e4354cde',
   'hostname': 'repairnator',
   'dateBegin': '2017-04-03T12:00:00.000Z',
   'dateLimit': '2017-04-03T08:00:00.000Z',
   'dayLimit': '03/04/2017',
   'totalRepoNumber': 1611,
   'totalRepoUsingTravis': 1601,
   'totalScannedBuilds': 205,
   'totalJavaBuilds': 198,
   'totalJavaPassingBuilds': 152,
   'totalJavaFailingBuilds': 27,
   'totalJavaFailingBuildsWithFailingTests': 8,
   'totalPRBuilds': 52,
   'duration': '0:31:4',
   'runId': '92d87100-e392-4b7c-8f49-2789af76ef7c',
   'dateBeginStr': '03/04/17 12:00',
   'dateLimitStr': '03/04/17 08:00'
   },
   */

  Highcharts.chart({
    chart: {
      type: 'spline',
      renderTo: htmlElement[0]
    },
    title: {
      text: 'Number of scanned builds'
    },
    xAxis: {
      type: 'datetime',
      dateTimeLabelFormats: { // don't display the dummy year
        minute:'%A, %b %e, %H:%M',
      },
      title: {
        text: 'Date'
      }
    },
    yAxis: {
      title: {
        text: 'Number of builds'
      },
      min: 0
    },
    tooltip: {
      headerFormat: '{series.name}
',
      pointFormat: '{point.x:%A, %b %e, %H:%M}: {point.y} builds'
    },

    plotOptions: {
      spline: {
        marker: {
          enabled: true
        }
      }
    },

    series: [
      {
        name: 'totalScannedBuilds',
        data: data.map( function (d) {
          return [
            Date.parse(d.dateLimit),
            d.totalScannedBuilds
          ]
        })
      },
      {
        name: 'totalJavaBuilds',
        data: data.map( function (d) {
          return [
            Date.parse(d.dateLimit),
            d.totalJavaBuilds
          ]
        })
      },
      {
        name: 'totalJavaPassingBuilds',
        data: data.map( function (d) {
          return [
            Date.parse(d.dateLimit),
            d.totalJavaPassingBuilds
          ]
        })
      },
      {
        name: 'totalJavaFailingBuilds',
        data: data.map( function (d) {
          return [
            Date.parse(d.dateLimit),
            d.totalJavaFailingBuilds
          ]
        })
      },
      {
        name: 'totalJavaFailingBuildsWithFailingTests',
        data: data.map( function (d) {
          return [
            Date.parse(d.dateLimit),
            d.totalJavaFailingBuildsWithFailingTests
          ]
        })
      }
    ]
  });
});
<commit_msg>Display timeline data by day instead of by hour #315<commit_after>$.get('http://repairnator.lille.inria.fr/repairnator-mongo-api/scanners/weeksData/2', function (data) {
  console.log(data);
  var htmlElement = $('

');
  $('#charts').append(htmlElement);

  /*
   {
   '_id': '58e22490cefc9665e4354cde',
   'hostname': 'repairnator',
   'dateBegin': '2017-04-03T12:00:00.000Z',
   'dateLimit': '2017-04-03T08:00:00.000Z',
   'dayLimit': '03/04/2017',
   'totalRepoNumber': 1611,
   'totalRepoUsingTravis': 1601,
   'totalScannedBuilds': 205,
   'totalJavaBuilds': 198,
   'totalJavaPassingBuilds': 152,
   'totalJavaFailingBuilds': 27,
   'totalJavaFailingBuildsWithFailingTests': 8,
   'totalPRBuilds': 52,
   'duration': '0:31:4',
   'runId': '92d87100-e392-4b7c-8f49-2789af76ef7c',
   'dateBeginStr': '03/04/17 12:00',
   'dateLimitStr': '03/04/17 08:00'
   },
   */

  var reducedData = data.reduce(function (accumulator, currentValue) {
    if (accumulator.length == 0) {
      return [ currentValue ];
    } else {
      var previousValue = accumulator[accumulator.length - 1];

      if (previousValue.dayLimit === currentValue.dayLimit) {
        for (var attr in previousValue) {
          if (attr.indexOf('total') != -1) {
            previousValue[attr] += currentValue[attr];
          }
        }
      } else {
        accumulator.push(currentValue);
      }

      return accumulator;
    }
  }, []);

  Highcharts.chart({
    chart: {
      type: 'spline',
      renderTo: htmlElement[0]
    },
    title: {
      text: 'Number of scanned builds'
    },
    xAxis: {
      type: 'datetime',
      dateTimeLabelFormats: { // don't display the dummy year
        day:'%A, %b %e',
      },
      title: {
        text: 'Date'
      }
    },
    yAxis: {
      title: {
        text: 'Number of builds'
      },
      min: 0
    },
    tooltip: {
      headerFormat: '{series.name}
',
      pointFormat: '{point.x:%A, %b %e}: {point.y} builds'
    },

    plotOptions: {
      spline: {
        marker: {
          enabled: true
        }
      }
    },

    series: [
      {
        name: 'totalScannedBuilds',
        data: reducedData.map( function (d) {
          return [
            Date.parse(d.dateLimit),
            d.totalScannedBuilds
          ]
        })
      },
      {
        name: 'totalJavaBuilds',
        data: reducedData.map( function (d) {
          return [
            Date.parse(d.dateLimit),
            d.totalJavaBuilds
          ]
        })
      },
      {
        name: 'totalJavaPassingBuilds',
        data: reducedData.map( function (d) {
          return [
            Date.parse(d.dateLimit),
            d.totalJavaPassingBuilds
          ]
        })
      },
      {
        name: 'totalJavaFailingBuilds',
        data: reducedData.map( function (d) {
          return [
            Date.parse(d.dateLimit),
            d.totalJavaFailingBuilds
          ]
        })
      },
      {
        name: 'totalJavaFailingBuildsWithFailingTests',
        data: reducedData.map( function (d) {
          return [
            Date.parse(d.dateLimit),
            d.totalJavaFailingBuildsWithFailingTests
          ]
        })
      }
    ]
  });
});
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */
'use strict';

jest.disableAutomock();

jest
  .setMock('worker-farm', () => () => undefined)
  .setMock('uglify-js')
  .mock('image-size')
  .mock('fs')
  .mock('os')
  .mock('assert')
  .mock('progress')
  .mock('../../node-haste')
  .mock('../../JSTransformer')
  .mock('../../lib/declareOpts')
  .mock('../../Resolver')
  .mock('../Bundle')
  .mock('../HMRBundle')
  .mock('../../Logger')
  .mock('../../lib/declareOpts');

var Bundler = require('../');
var Resolver = require('../../Resolver');
var defaults = require('../../../defaults');
var sizeOf = require('image-size');
var fs = require('fs');
const os = require('os');

var commonOptions = {
  allowBundleUpdates: false,
  assetExts: defaults.assetExts,
  cacheVersion: 'smth',
  extraNodeModules: {},
  platforms: defaults.platforms,
  resetCache: false,
  watch: false,
};

describe('Bundler', function() {

  function createModule({
    path,
    id,
    dependencies,
    isAsset,
    isJSON,
    isPolyfill,
    resolution,
  }) {
    return {
      path,
      resolution,
      getDependencies: () => Promise.resolve(dependencies),
      getName: () => Promise.resolve(id),
      isJSON: () => isJSON,
      isAsset: () => isAsset,
      isPolyfill: () => isPolyfill,
      read: () => ({
        code: 'arbitrary',
        source: 'arbitrary',
      }),
    };
  }

  var getDependencies;
  var getModuleSystemDependencies;
  var bundler;
  var assetServer;
  var modules;
  var projectRoots;

  beforeEach(function() {
    os.cpus.mockReturnValue({length: 1});

    getDependencies = jest.fn();
    getModuleSystemDependencies = jest.fn();
    projectRoots = ['/root'];

    Resolver.mockImplementation(function() {
      return {
        getDependencies,
        getModuleSystemDependencies,
      };
    });
    Resolver.load = jest.fn().mockImplementation(opts => Promise.resolve(new Resolver(opts)));

    fs.statSync.mockImplementation(function() {
      return {
        isDirectory: () => true,
      };
    });

    fs.readFile.mockImplementation(function(file, callback) {
      callback(null, '{"json":true}');
    });

    assetServer = {
      getAssetData: jest.fn(),
    };

    bundler = new Bundler({
      ...commonOptions,
      projectRoots,
      assetServer,
    });

    modules = [
      createModule({id: 'foo', path: '/root/foo.js', dependencies: []}),
      createModule({id: 'bar', path: '/root/bar.js', dependencies: []}),
      createModule({
        id: 'new_image.png',
        path: '/root/img/new_image.png',
        isAsset: true,
        resolution: 2,
        dependencies: [],
      }),
      createModule({
        id: 'package/file.json',
        path: '/root/file.json',
        isJSON: true,
        dependencies: [],
      }),
    ];

    getDependencies.mockImplementation((main, options, transformOptions) =>
      Promise.resolve({
        mainModuleId: 'foo',
        dependencies: modules,
        transformOptions,
        getModuleId: () => 123,
        getResolvedDependencyPairs: () => [],
      })
    );

    getModuleSystemDependencies.mockImplementation(function() {
      return [];
    });

    sizeOf.mockImplementation(function(path, cb) {
      cb(null, {width: 50, height: 100});
    });
  });

  it('create a bundle', function() {
    assetServer.getAssetData.mockImplementation(() => {
      return Promise.resolve({
        scales: [1, 2, 3],
        files: [
          '/root/img/img.png',
          '/root/img/img@2x.png',
          '/root/img/img@3x.png',
        ],
        hash: 'i am a hash',
        name: 'img',
        type: 'png',
      });
    });

    return bundler.bundle({
      entryFile: '/root/foo.js',
      runBeforeMainModule: [],
      runModule: true,
      sourceMapUrl: 'source_map_url',
    }).then(bundle => {
      const ithAddedModule = i => bundle.addModule.mock.calls[i][2].path;

      expect(ithAddedModule(0)).toEqual('/root/foo.js');
      expect(ithAddedModule(1)).toEqual('/root/bar.js');
      expect(ithAddedModule(2)).toEqual('/root/img/new_image.png');
      expect(ithAddedModule(3)).toEqual('/root/file.json');

      expect(bundle.finalize.mock.calls[0]).toEqual([{
        runModule: true,
        runBeforeMainModule: [],
        allowUpdates: false,
      }]);

      expect(bundle.addAsset.mock.calls[0]).toEqual([{
        __packager_asset: true,
        fileSystemLocation: '/root/img',
        httpServerLocation: '/assets/img',
        width: 50,
        height: 100,
        scales: [1, 2, 3],
        files: [
          '/root/img/img.png',
          '/root/img/img@2x.png',
          '/root/img/img@3x.png',
        ],
        hash: 'i am a hash',
        name: 'img',
        type: 'png',
      }]);

        // TODO(amasad) This fails with 0 != 5 in OSS
        //expect(ProgressBar.prototype.tick.mock.calls.length).toEqual(modules.length);
    });
  });

  it('loads and runs asset plugins', function() {
    jest.mock('mockPlugin1', () => {
      return asset => {
        asset.extraReverseHash = asset.hash.split('').reverse().join('');
        return asset;
      };
    }, {virtual: true});

    jest.mock('asyncMockPlugin2', () => {
      return asset => {
        expect(asset.extraReverseHash).toBeDefined();
        return new Promise(resolve => {
          asset.extraPixelCount = asset.width * asset.height;
          resolve(asset);
        });
      };
    }, {virtual: true});

    const mockAsset = {
      scales: [1, 2, 3],
      files: [
        '/root/img/img.png',
        '/root/img/img@2x.png',
        '/root/img/img@3x.png',
      ],
      hash: 'i am a hash',
      name: 'img',
      type: 'png',
    };
    assetServer.getAssetData.mockImplementation(() => Promise.resolve(mockAsset));

    return bundler.bundle({
      entryFile: '/root/foo.js',
      runBeforeMainModule: [],
      runModule: true,
      sourceMapUrl: 'source_map_url',
      assetPlugins: ['mockPlugin1', 'asyncMockPlugin2'],
    }).then(bundle => {
      expect(bundle.addAsset.mock.calls[0]).toEqual([{
        __packager_asset: true,
        fileSystemLocation: '/root/img',
        httpServerLocation: '/assets/img',
        width: 50,
        height: 100,
        scales: [1, 2, 3],
        files: [
          '/root/img/img.png',
          '/root/img/img@2x.png',
          '/root/img/img@3x.png',
        ],
        hash: 'i am a hash',
        name: 'img',
        type: 'png',
        extraReverseHash: 'hsah a ma i',
        extraPixelCount: 5000,
      }]);
    });
  });

  it('gets the list of dependencies from the resolver', function() {
    const entryFile = '/root/foo.js';
    return bundler.getDependencies({entryFile, recursive: true}).then(() =>
      // jest calledWith does not support jasmine.any
      expect(getDependencies.mock.calls[0].slice(0, -2)).toEqual([
        '/root/foo.js',
        {dev: true, platform: undefined, recursive: true},
        {
          dev: true,
          minify: false,
          platform: undefined,
          transform: {
            dev: true,
            generateSourceMaps: false,
            hot: false,
            inlineRequires: false,
            platform: undefined,
            preloadedModules: undefined,
            projectRoots,
            ramGroups: undefined,
          },
        },
      ])
    );
  });

  it('allows overriding the platforms array', () => {
    expect(bundler._opts.platforms).toEqual(['ios', 'android', 'windows', 'web']);
    const b = new Bundler({
      ...commonOptions,
      projectRoots,
      assetServer,
      platforms: ['android', 'vr'],
    });
    expect(b._opts.platforms).toEqual(['android', 'vr']);
  });

  describe('getOrderedDependencyPaths', () => {
    beforeEach(() => {
      assetServer.getAssetData.mockImplementation(function(relPath) {
        if (relPath === 'img/new_image.png') {
          return Promise.resolve({
            scales: [1, 2, 3],
            files: [
              '/root/img/new_image.png',
              '/root/img/new_image@2x.png',
              '/root/img/new_image@3x.png',
            ],
            hash: 'i am a hash',
            name: 'img',
            type: 'png',
          });
        } else if (relPath === 'img/new_image2.png') {
          return Promise.resolve({
            scales: [1, 2, 3],
            files: [
              '/root/img/new_image2.png',
              '/root/img/new_image2@2x.png',
              '/root/img/new_image2@3x.png',
            ],
            hash: 'i am a hash',
            name: 'img',
            type: 'png',
          });
        }

        throw new Error('unknown image ' + relPath);
      });
    });

    it('should get the concrete list of all dependency files', () => {
      modules.push(
        createModule({
          id: 'new_image2.png',
          path: '/root/img/new_image2.png',
          isAsset: true,
          resolution: 2,
          dependencies: [],
        }),
      );

      return bundler.getOrderedDependencyPaths('/root/foo.js', true)
        .then(paths => expect(paths).toEqual([
          '/root/foo.js',
          '/root/bar.js',
          '/root/img/new_image.png',
          '/root/img/new_image@2x.png',
          '/root/img/new_image@3x.png',
          '/root/file.json',
          '/root/img/new_image2.png',
          '/root/img/new_image2@2x.png',
          '/root/img/new_image2@3x.png',
        ]));
    });

    it('return correct number of workers', () => {
      os.cpus.mockReturnValue({length: 1});
      expect(Bundler.getMaxWorkerCount()).toBe(1);
      os.cpus.mockReturnValue({length: 8});
      expect(Bundler.getMaxWorkerCount()).toBe(6);
      os.cpus.mockReturnValue({length: 24});
      expect(Bundler.getMaxWorkerCount()).toBe(14);
      process.env.REACT_NATIVE_MAX_WORKERS = 5;
      expect(Bundler.getMaxWorkerCount()).toBe(5);
    });
  });
});
<commit_msg>make test independent from side effects<commit_after>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */
'use strict';

jest.disableAutomock();

jest
  .setMock('worker-farm', () => () => undefined)
  .setMock('uglify-js')
  .mock('image-size')
  .mock('fs')
  .mock('os')
  .mock('assert')
  .mock('progress')
  .mock('../../node-haste')
  .mock('../../JSTransformer')
  .mock('../../lib/declareOpts')
  .mock('../../Resolver')
  .mock('../Bundle')
  .mock('../HMRBundle')
  .mock('../../Logger')
  .mock('../../lib/declareOpts');

var Bundler = require('../');
var Resolver = require('../../Resolver');
var defaults = require('../../../defaults');
var sizeOf = require('image-size');
var fs = require('fs');
const os = require('os');

var commonOptions = {
  allowBundleUpdates: false,
  assetExts: defaults.assetExts,
  cacheVersion: 'smth',
  extraNodeModules: {},
  platforms: defaults.platforms,
  resetCache: false,
  watch: false,
};

describe('Bundler', function() {

  function createModule({
    path,
    id,
    dependencies,
    isAsset,
    isJSON,
    isPolyfill,
    resolution,
  }) {
    return {
      path,
      resolution,
      getDependencies: () => Promise.resolve(dependencies),
      getName: () => Promise.resolve(id),
      isJSON: () => isJSON,
      isAsset: () => isAsset,
      isPolyfill: () => isPolyfill,
      read: () => ({
        code: 'arbitrary',
        source: 'arbitrary',
      }),
    };
  }

  var getDependencies;
  var getModuleSystemDependencies;
  var bundler;
  var assetServer;
  var modules;
  var projectRoots;

  beforeEach(function() {
    os.cpus.mockReturnValue({length: 1});

    getDependencies = jest.fn();
    getModuleSystemDependencies = jest.fn();
    projectRoots = ['/root'];

    Resolver.mockImplementation(function() {
      return {
        getDependencies,
        getModuleSystemDependencies,
      };
    });
    Resolver.load = jest.fn().mockImplementation(opts => Promise.resolve(new Resolver(opts)));

    fs.statSync.mockImplementation(function() {
      return {
        isDirectory: () => true,
      };
    });

    fs.readFile.mockImplementation(function(file, callback) {
      callback(null, '{"json":true}');
    });

    assetServer = {
      getAssetData: jest.fn(),
    };

    bundler = new Bundler({
      ...commonOptions,
      projectRoots,
      assetServer,
    });

    modules = [
      createModule({id: 'foo', path: '/root/foo.js', dependencies: []}),
      createModule({id: 'bar', path: '/root/bar.js', dependencies: []}),
      createModule({
        id: 'new_image.png',
        path: '/root/img/new_image.png',
        isAsset: true,
        resolution: 2,
        dependencies: [],
      }),
      createModule({
        id: 'package/file.json',
        path: '/root/file.json',
        isJSON: true,
        dependencies: [],
      }),
    ];

    getDependencies.mockImplementation((main, options, transformOptions) =>
      Promise.resolve({
        mainModuleId: 'foo',
        dependencies: modules,
        transformOptions,
        getModuleId: () => 123,
        getResolvedDependencyPairs: () => [],
      })
    );

    getModuleSystemDependencies.mockImplementation(function() {
      return [];
    });

    sizeOf.mockImplementation(function(path, cb) {
      cb(null, {width: 50, height: 100});
    });
  });

  it('create a bundle', function() {
    assetServer.getAssetData.mockImplementation(() => {
      return Promise.resolve({
        scales: [1, 2, 3],
        files: [
          '/root/img/img.png',
          '/root/img/img@2x.png',
          '/root/img/img@3x.png',
        ],
        hash: 'i am a hash',
        name: 'img',
        type: 'png',
      });
    });

    return bundler.bundle({
      entryFile: '/root/foo.js',
      runBeforeMainModule: [],
      runModule: true,
      sourceMapUrl: 'source_map_url',
    }).then(bundle => {
      const ithAddedModule = i => bundle.addModule.mock.calls[i][2].path;

      expect(ithAddedModule(0)).toEqual('/root/foo.js');
      expect(ithAddedModule(1)).toEqual('/root/bar.js');
      expect(ithAddedModule(2)).toEqual('/root/img/new_image.png');
      expect(ithAddedModule(3)).toEqual('/root/file.json');

      expect(bundle.finalize.mock.calls[0]).toEqual([{
        runModule: true,
        runBeforeMainModule: [],
        allowUpdates: false,
      }]);

      expect(bundle.addAsset.mock.calls[0]).toEqual([{
        __packager_asset: true,
        fileSystemLocation: '/root/img',
        httpServerLocation: '/assets/img',
        width: 50,
        height: 100,
        scales: [1, 2, 3],
        files: [
          '/root/img/img.png',
          '/root/img/img@2x.png',
          '/root/img/img@3x.png',
        ],
        hash: 'i am a hash',
        name: 'img',
        type: 'png',
      }]);

        // TODO(amasad) This fails with 0 != 5 in OSS
        //expect(ProgressBar.prototype.tick.mock.calls.length).toEqual(modules.length);
    });
  });

  it('loads and runs asset plugins', function() {
    jest.mock('mockPlugin1', () => {
      return asset => {
        asset.extraReverseHash = asset.hash.split('').reverse().join('');
        return asset;
      };
    }, {virtual: true});

    jest.mock('asyncMockPlugin2', () => {
      return asset => {
        expect(asset.extraReverseHash).toBeDefined();
        return new Promise(resolve => {
          asset.extraPixelCount = asset.width * asset.height;
          resolve(asset);
        });
      };
    }, {virtual: true});

    const mockAsset = {
      scales: [1, 2, 3],
      files: [
        '/root/img/img.png',
        '/root/img/img@2x.png',
        '/root/img/img@3x.png',
      ],
      hash: 'i am a hash',
      name: 'img',
      type: 'png',
    };
    assetServer.getAssetData.mockImplementation(() => Promise.resolve(mockAsset));

    return bundler.bundle({
      entryFile: '/root/foo.js',
      runBeforeMainModule: [],
      runModule: true,
      sourceMapUrl: 'source_map_url',
      assetPlugins: ['mockPlugin1', 'asyncMockPlugin2'],
    }).then(bundle => {
      expect(bundle.addAsset.mock.calls[0]).toEqual([{
        __packager_asset: true,
        fileSystemLocation: '/root/img',
        httpServerLocation: '/assets/img',
        width: 50,
        height: 100,
        scales: [1, 2, 3],
        files: [
          '/root/img/img.png',
          '/root/img/img@2x.png',
          '/root/img/img@3x.png',
        ],
        hash: 'i am a hash',
        name: 'img',
        type: 'png',
        extraReverseHash: 'hsah a ma i',
        extraPixelCount: 5000,
      }]);
    });
  });

  it('gets the list of dependencies from the resolver', function() {
    const entryFile = '/root/foo.js';
    return bundler.getDependencies({entryFile, recursive: true}).then(() =>
      // jest calledWith does not support jasmine.any
      expect(getDependencies.mock.calls[0].slice(0, -2)).toEqual([
        '/root/foo.js',
        {dev: true, platform: undefined, recursive: true},
        {
          dev: true,
          minify: false,
          platform: undefined,
          transform: {
            dev: true,
            generateSourceMaps: false,
            hot: false,
            inlineRequires: false,
            platform: undefined,
            preloadedModules: undefined,
            projectRoots,
            ramGroups: undefined,
          },
        },
      ])
    );
  });

  it('allows overriding the platforms array', () => {
    expect(bundler._opts.platforms).toEqual(['ios', 'android', 'windows', 'web']);
    const b = new Bundler({
      ...commonOptions,
      projectRoots,
      assetServer,
      platforms: ['android', 'vr'],
    });
    expect(b._opts.platforms).toEqual(['android', 'vr']);
  });

  describe('getOrderedDependencyPaths', () => {
    beforeEach(() => {
      assetServer.getAssetData.mockImplementation(function(relPath) {
        if (relPath === 'img/new_image.png') {
          return Promise.resolve({
            scales: [1, 2, 3],
            files: [
              '/root/img/new_image.png',
              '/root/img/new_image@2x.png',
              '/root/img/new_image@3x.png',
            ],
            hash: 'i am a hash',
            name: 'img',
            type: 'png',
          });
        } else if (relPath === 'img/new_image2.png') {
          return Promise.resolve({
            scales: [1, 2, 3],
            files: [
              '/root/img/new_image2.png',
              '/root/img/new_image2@2x.png',
              '/root/img/new_image2@3x.png',
            ],
            hash: 'i am a hash',
            name: 'img',
            type: 'png',
          });
        }

        throw new Error('unknown image ' + relPath);
      });
    });

    it('should get the concrete list of all dependency files', () => {
      modules.push(
        createModule({
          id: 'new_image2.png',
          path: '/root/img/new_image2.png',
          isAsset: true,
          resolution: 2,
          dependencies: [],
        }),
      );

      return bundler.getOrderedDependencyPaths('/root/foo.js', true)
        .then(paths => expect(paths).toEqual([
          '/root/foo.js',
          '/root/bar.js',
          '/root/img/new_image.png',
          '/root/img/new_image@2x.png',
          '/root/img/new_image@3x.png',
          '/root/file.json',
          '/root/img/new_image2.png',
          '/root/img/new_image2@2x.png',
          '/root/img/new_image2@3x.png',
        ]));
    });

    describe('number of workers', () => {
      beforeEach(() => {
        delete process.env.REACT_NATIVE_MAX_WORKERS;
      });

      afterEach(() => {
        delete process.env.REACT_NATIVE_MAX_WORKERS;
      });

      it('return correct number of workers', () => {
        os.cpus.mockReturnValue({length: 1});
        expect(Bundler.getMaxWorkerCount()).toBe(1);
        os.cpus.mockReturnValue({length: 8});
        expect(Bundler.getMaxWorkerCount()).toBe(6);
        os.cpus.mockReturnValue({length: 24});
        expect(Bundler.getMaxWorkerCount()).toBe(14);
        process.env.REACT_NATIVE_MAX_WORKERS = 5;
        expect(Bundler.getMaxWorkerCount()).toBe(5);
      });
    });
  });
});
<|endoftext|>