<commit_before>module.exports = [

	// see: https://github.com/tastejs/todomvc/issues/832
	// chapling brunch does not mark items as completed via the completed CSS class
	'TodoMVC - chaplin-brunch, No Todos, should hide #main and #footer',
	'TodoMVC - chaplin-brunch, Mark all as completed, should allow me to mark all items as completed',
	// jscs:disable
	'TodoMVC - chaplin-brunch, Mark all as completed, complete all checkbox should update state when items are completed / cleared',
	// jscs:enable
	'TodoMVC - chaplin-brunch, Item, should allow me to mark items as complete',
	'TodoMVC - chaplin-brunch, Item, should allow me to un-mark items as complete',
	'TodoMVC - chaplin-brunch, Item, should allow me to edit an item',

	// durandal routing is very very slow.
	// see: https://github.com/tastejs/todomvc/issues/831
	'TodoMVC - durandal, Routing, should allow me to display active items',
	'TodoMVC - durandal, Routing, should allow me to display completed items',
	'TodoMVC - durandal, Routing, should allow me to display all items',
	'TodoMVC - durandal, Routing, should highlight the currently applied filter',

	// see: https://github.com/tastejs/todomvc/issues/830
	// typescript-backbone has a nested div within the li element, and sets /li/div[@class=done]
	'TodoMVC - typescript-backbone, Mark all as completed, should allow me to mark all items as completed / cleared',
	'TodoMVC - typescript-backbone, Item, should allow me to mark items as complete',
	'TodoMVC - typescript-backbone, Item, should allow me to un-mark items as complete',
	'TodoMVC - typescript-backbone, Item, should allow me to edit an item',

	// https://github.com/tastejs/todomvc/issues/828
	// routing should default to all
	'TodoMVC - sammyjs, Routing, should highlight the currently applied filter',

	// https://github.com/tastejs/todomvc/issues/824
	// this implementation has numerous edit experience issues
	'TodoMVC - angularjs_require, Mark all as completed, should allow me to mark all items as completed',
	'TodoMVC - angularjs_require, Mark all as completed, should allow me to clear the completion state of all items',
	// jscs:disable
	'TodoMVC - angularjs_require, Mark all as completed, complete all checkbox should update state when items are completed / cleared',

	// jscs:enable
	// https://github.com/tastejs/todomvc/issues/815
	// does not hide other controls while editing
	'TodoMVC - dojo, Editing, should hide other controls when editing',

	// https://github.com/tastejs/todomvc/issues/816
	// atma does not hide the main section, instead it hides the toggle-all checkbox
	'TodoMVC - atmajs, No Todos, should hide #main and #footer',

	// https://github.com/tastejs/todomvc/issues/819
	// the edit experience with soma is quite broken. You can
	// get multiple elements into an edit state
	'TodoMVC - somajs_require, Editing, should remove the item if an empty text string was entered',
	'TodoMVC - somajs_require, Editing, should cancel edits on escape',

	// the following are covered by the following issue:
	// https://github.com/tastejs/todomvc/issues/789
	'TodoMVC - closure, Editing, should cancel edits on escape',
	'TodoMVC - ariatemplates, Editing, should cancel edits on escape',
	'TodoMVC - dermis, Editing, should cancel edits on escape',
	'TodoMVC - duel, Editing, should cancel edits on escape',
	'TodoMVC - extjs_deftjs, Editing, should cancel edits on escape',
	'TodoMVC - olives, Editing, should cancel edits on escape',
	'TodoMVC - rappidjs, Editing, should cancel edits on escape',
	'TodoMVC - serenadejs, Editing, should cancel edits on escape',
	'TodoMVC - thorax, Editing, should cancel edits on escape',
	'TodoMVC - typescript-angular, Editing, should cancel edits on escape',
	'TodoMVC - flight, Editing, should cancel edits on escape',
	'TodoMVC - thorax_lumbar, Editing, should cancel edits on escape',
	'TodoMVC - backbone_require, Editing, should cancel edits on escape',
	'TodoMVC - dijon, Editing, should cancel edits on escape',
	'TodoMVC - knockoutjs_require, Editing, should cancel edits on escape',

	// all the following are covered by this issue:
	// https://github.com/tastejs/todomvc/issues/856
	'TodoMVC - knockoutjs, Routing, should respect the back button',
	'TodoMVC - spine, Routing, should respect the back button',
	'TodoMVC - componentjs, Routing, should respect the back button',
	'TodoMVC - serenadejs, Routing, should respect the back button',
	'TodoMVC - flight, Routing, should respect the back button',
	'TodoMVC - lavaca_require, Routing, should respect the back button',
	'TodoMVC - somajs_require, Routing, should respect the back button',

	// the following are covered by this issue:
	// https://github.com/tastejs/todomvc/issues/795
	'TodoMVC - spine, Mark all as completed, complete all checkbox should update state when items are completed / cleared',

	// the following implementations do not support routing
	'TodoMVC - extjs_deftjs, Routing, should allow me to display active items',
	'TodoMVC - extjs_deftjs, Routing, should allow me to display completed items',
	'TodoMVC - extjs_deftjs, Routing, should allow me to display all items',
	'TodoMVC - extjs_deftjs, Routing, should highlight the currently applied filter',
	'TodoMVC - extjs_deftjs, Routing, should respect the back button',
	'TodoMVC - olives, Routing, should allow me to display active items',
	'TodoMVC - olives, Routing, should allow me to display completed items',
	'TodoMVC - olives, Routing, should allow me to display all items',
	'TodoMVC - olives, Routing, should highlight the currently applied filter',
	'TodoMVC - olives, Routing, should respect the back button',
	'TodoMVC - dijon, Routing, should allow me to display active items',
	'TodoMVC - dijon, Routing, should allow me to display completed items',
	'TodoMVC - dijon, Routing, should allow me to display all items',
	'TodoMVC - dijon, Routing, should highlight the currently applied filter',
	'TodoMVC - dijon, Routing, should respect the back button',
	'TodoMVC - duel, Routing, should allow me to display active items',
	'TodoMVC - duel, Routing, should allow me to display completed items',
	'TodoMVC - duel, Routing, should allow me to display all items',
	'TodoMVC - duel, Routing, should highlight the currently applied filter',
	'TodoMVC - duel, Routing, should respect the back button',
	'TodoMVC - knockoutjs_require, Routing, should allow me to display active items',
	'TodoMVC - knockoutjs_require, Routing, should allow me to display completed items',
	'TodoMVC - knockoutjs_require, Routing, should allow me to display all items',
	'TodoMVC - knockoutjs_require, Routing, should highlight the currently applied filter',
	'TodoMVC - knockoutjs_require, Routing, should respect the back button',
	'TodoMVC - angular-dart, Routing, should allow me to display active items',
	'TodoMVC - angular-dart, Routing, should allow me to display completed items',
	'TodoMVC - angular-dart, Routing, should allow me to display all items',
	'TodoMVC - angular-dart, Routing, should highlight the currently applied filter',
	'TodoMVC - angular-dart, Routing, should respect the back button',
	'TodoMVC - typescript-backbone, Routing, should allow me to display active items',
	'TodoMVC - typescript-backbone, Routing, should allow me to display completed items',
	'TodoMVC - typescript-backbone, Routing, should allow me to display all items',
	'TodoMVC - typescript-backbone, Routing, should highlight the currently applied filter',
	'TodoMVC - typescript-backbone, Routing, should respect the back button',

	// EXTJS is not spec compliant (by a long way!)
	'TodoMVC - extjs, New Todo, should show #main and #footer when items added',
	'TodoMVC - extjs, Mark all as completed, should allow me to mark all items as completed',
	'TodoMVC - extjs, Mark all as completed, complete all checkbox should update state when items are completed / cleared',
	'TodoMVC - extjs, Item, should allow me to mark items as complete',
	'TodoMVC - extjs, Item, should allow me to un-mark items as complete',
	'TodoMVC - extjs, Editing, should save edits on blur',
	'TodoMVC - extjs, Editing, should cancel edits on escape',
	'TodoMVC - extjs, Counter, should display the current number of todo items',
	'TodoMVC - extjs, Clear completed button, should display the number of completed items',
	'TodoMVC - extjs, Clear completed button, should remove completed items when clicked',
	'TodoMVC - extjs, Clear completed button, should be hidden when there are no items that are completed',
	'TodoMVC - extjs, Persistence, should persist its data',
	'TodoMVC - extjs, Routing, should allow me to display active items',
	'TodoMVC - extjs, Routing, should allow me to display completed items',
	'TodoMVC - extjs, Routing, should allow me to display all items',
	'TodoMVC - extjs, Routing, should highlight the currently applied filter',
	'TodoMVC - extjs, Routing, should respect the back button',

	// ----------------- Test framework issues -----------

	// for some reason the persistence test fails for knockout, even though persistence is working
	// just fine. Perhaps there is something asynchronous going on that is causing the assert
	// to be executed early?
	'TodoMVC - knockoutjs, Persistence, should persist its data',

	// chaplin edit tests fail with the following:
	// StaleElementReferenceError: stale element reference: element is not attached to the page document
	'TodoMVC - chaplin-brunch, Editing, should save edits on enter',
	'TodoMVC - chaplin-brunch, Editing, should save edits on blur',
	'TodoMVC - chaplin-brunch, Editing, should trim entered text',
	'TodoMVC - chaplin-brunch, Editing, should remove the item if an empty text string was entered',
	'TodoMVC - chaplin-brunch, Editing, should cancel edits on escape'
];
<commit_msg>Remove known issues regarding `chaplin-brunch`<commit_after>module.exports = [

	// durandal routing is very very slow.
	// see: https://github.com/tastejs/todomvc/issues/831
	'TodoMVC - durandal, Routing, should allow me to display active items',
	'TodoMVC - durandal, Routing, should allow me to display completed items',
	'TodoMVC - durandal, Routing, should allow me to display all items',
	'TodoMVC - durandal, Routing, should highlight the currently applied filter',

	// see: https://github.com/tastejs/todomvc/issues/830
	// typescript-backbone has a nested div within the li element, and sets /li/div[@class=done]
	'TodoMVC - typescript-backbone, Mark all as completed, should allow me to mark all items as completed / cleared',
	'TodoMVC - typescript-backbone, Item, should allow me to mark items as complete',
	'TodoMVC - typescript-backbone, Item, should allow me to un-mark items as complete',
	'TodoMVC - typescript-backbone, Item, should allow me to edit an item',

	// https://github.com/tastejs/todomvc/issues/828
	// routing should default to all
	'TodoMVC - sammyjs, Routing, should highlight the currently applied filter',

	// https://github.com/tastejs/todomvc/issues/824
	// this implementation has numerous edit experience issues
	'TodoMVC - angularjs_require, Mark all as completed, should allow me to mark all items as completed',
	'TodoMVC - angularjs_require, Mark all as completed, should allow me to clear the completion state of all items',
	// jscs:disable
	'TodoMVC - angularjs_require, Mark all as completed, complete all checkbox should update state when items are completed / cleared',

	// jscs:enable
	// https://github.com/tastejs/todomvc/issues/815
	// does not hide other controls while editing
	'TodoMVC - dojo, Editing, should hide other controls when editing',

	// https://github.com/tastejs/todomvc/issues/816
	// atma does not hide the main section, instead it hides the toggle-all checkbox
	'TodoMVC - atmajs, No Todos, should hide #main and #footer',

	// https://github.com/tastejs/todomvc/issues/819
	// the edit experience with soma is quite broken. You can
	// get multiple elements into an edit state
	'TodoMVC - somajs_require, Editing, should remove the item if an empty text string was entered',
	'TodoMVC - somajs_require, Editing, should cancel edits on escape',

	// the following are covered by the following issue:
	// https://github.com/tastejs/todomvc/issues/789
	'TodoMVC - closure, Editing, should cancel edits on escape',
	'TodoMVC - ariatemplates, Editing, should cancel edits on escape',
	'TodoMVC - dermis, Editing, should cancel edits on escape',
	'TodoMVC - duel, Editing, should cancel edits on escape',
	'TodoMVC - extjs_deftjs, Editing, should cancel edits on escape',
	'TodoMVC - olives, Editing, should cancel edits on escape',
	'TodoMVC - rappidjs, Editing, should cancel edits on escape',
	'TodoMVC - serenadejs, Editing, should cancel edits on escape',
	'TodoMVC - thorax, Editing, should cancel edits on escape',
	'TodoMVC - typescript-angular, Editing, should cancel edits on escape',
	'TodoMVC - flight, Editing, should cancel edits on escape',
	'TodoMVC - thorax_lumbar, Editing, should cancel edits on escape',
	'TodoMVC - backbone_require, Editing, should cancel edits on escape',
	'TodoMVC - dijon, Editing, should cancel edits on escape',
	'TodoMVC - knockoutjs_require, Editing, should cancel edits on escape',

	// all the following are covered by this issue:
	// https://github.com/tastejs/todomvc/issues/856
	'TodoMVC - knockoutjs, Routing, should respect the back button',
	'TodoMVC - spine, Routing, should respect the back button',
	'TodoMVC - componentjs, Routing, should respect the back button',
	'TodoMVC - serenadejs, Routing, should respect the back button',
	'TodoMVC - flight, Routing, should respect the back button',
	'TodoMVC - lavaca_require, Routing, should respect the back button',
	'TodoMVC - somajs_require, Routing, should respect the back button',

	// the following are covered by this issue:
	// https://github.com/tastejs/todomvc/issues/795
	'TodoMVC - spine, Mark all as completed, complete all checkbox should update state when items are completed / cleared',

	// the following implementations do not support routing
	'TodoMVC - extjs_deftjs, Routing, should allow me to display active items',
	'TodoMVC - extjs_deftjs, Routing, should allow me to display completed items',
	'TodoMVC - extjs_deftjs, Routing, should allow me to display all items',
	'TodoMVC - extjs_deftjs, Routing, should highlight the currently applied filter',
	'TodoMVC - extjs_deftjs, Routing, should respect the back button',
	'TodoMVC - olives, Routing, should allow me to display active items',
	'TodoMVC - olives, Routing, should allow me to display completed items',
	'TodoMVC - olives, Routing, should allow me to display all items',
	'TodoMVC - olives, Routing, should highlight the currently applied filter',
	'TodoMVC - olives, Routing, should respect the back button',
	'TodoMVC - dijon, Routing, should allow me to display active items',
	'TodoMVC - dijon, Routing, should allow me to display completed items',
	'TodoMVC - dijon, Routing, should allow me to display all items',
	'TodoMVC - dijon, Routing, should highlight the currently applied filter',
	'TodoMVC - dijon, Routing, should respect the back button',
	'TodoMVC - duel, Routing, should allow me to display active items',
	'TodoMVC - duel, Routing, should allow me to display completed items',
	'TodoMVC - duel, Routing, should allow me to display all items',
	'TodoMVC - duel, Routing, should highlight the currently applied filter',
	'TodoMVC - duel, Routing, should respect the back button',
	'TodoMVC - knockoutjs_require, Routing, should allow me to display active items',
	'TodoMVC - knockoutjs_require, Routing, should allow me to display completed items',
	'TodoMVC - knockoutjs_require, Routing, should allow me to display all items',
	'TodoMVC - knockoutjs_require, Routing, should highlight the currently applied filter',
	'TodoMVC - knockoutjs_require, Routing, should respect the back button',
	'TodoMVC - angular-dart, Routing, should allow me to display active items',
	'TodoMVC - angular-dart, Routing, should allow me to display completed items',
	'TodoMVC - angular-dart, Routing, should allow me to display all items',
	'TodoMVC - angular-dart, Routing, should highlight the currently applied filter',
	'TodoMVC - angular-dart, Routing, should respect the back button',
	'TodoMVC - typescript-backbone, Routing, should allow me to display active items',
	'TodoMVC - typescript-backbone, Routing, should allow me to display completed items',
	'TodoMVC - typescript-backbone, Routing, should allow me to display all items',
	'TodoMVC - typescript-backbone, Routing, should highlight the currently applied filter',
	'TodoMVC - typescript-backbone, Routing, should respect the back button',

	// EXTJS is not spec compliant (by a long way!)
	'TodoMVC - extjs, New Todo, should show #main and #footer when items added',
	'TodoMVC - extjs, Mark all as completed, should allow me to mark all items as completed',
	'TodoMVC - extjs, Mark all as completed, complete all checkbox should update state when items are completed / cleared',
	'TodoMVC - extjs, Item, should allow me to mark items as complete',
	'TodoMVC - extjs, Item, should allow me to un-mark items as complete',
	'TodoMVC - extjs, Editing, should save edits on blur',
	'TodoMVC - extjs, Editing, should cancel edits on escape',
	'TodoMVC - extjs, Counter, should display the current number of todo items',
	'TodoMVC - extjs, Clear completed button, should display the number of completed items',
	'TodoMVC - extjs, Clear completed button, should remove completed items when clicked',
	'TodoMVC - extjs, Clear completed button, should be hidden when there are no items that are completed',
	'TodoMVC - extjs, Persistence, should persist its data',
	'TodoMVC - extjs, Routing, should allow me to display active items',
	'TodoMVC - extjs, Routing, should allow me to display completed items',
	'TodoMVC - extjs, Routing, should allow me to display all items',
	'TodoMVC - extjs, Routing, should highlight the currently applied filter',
	'TodoMVC - extjs, Routing, should respect the back button',

	// ----------------- Test framework issues -----------

	// for some reason the persistence test fails for knockout, even though persistence is working
	// just fine. Perhaps there is something asynchronous going on that is causing the assert
	// to be executed early?
	'TodoMVC - knockoutjs, Persistence, should persist its data',

	// chaplin edit tests fail with the following:
	// StaleElementReferenceError: stale element reference: element is not attached to the page document
	'TodoMVC - chaplin-brunch, Editing, should save edits on enter',
	'TodoMVC - chaplin-brunch, Editing, should save edits on blur',
	'TodoMVC - chaplin-brunch, Editing, should trim entered text',
	'TodoMVC - chaplin-brunch, Editing, should remove the item if an empty text string was entered',
	'TodoMVC - chaplin-brunch, Editing, should cancel edits on escape'
];
<|endoftext|>


<commit_before>// Invoking IIFE for teams
(function() {

    'use strict';

    angular
        .module('evalai')
        .controller('TeamsCtrl', TeamsCtrl);

    TeamsCtrl.$inject = ['utilities', '$scope', '$state', '$http', '$rootScope', '$mdDialog'];

    function TeamsCtrl(utilities, $scope, $state, $http, $rootScope, $mdDialog) {
        var vm = this;
        // console.log(vm.teamId)
        var userKey = utilities.getData('userKey');
        var challengePk = 1;

        utilities.showLoader();

        // default variables/objects
        vm.team = {};
        vm.teamId = null;
        vm.existTeam = {};
        vm.currentPage = '';
        vm.isNext = '';
        vm.isPrev = '';
        vm.team.error = false;
        vm.showPagination = false;

        // loader for existng teams// loader for exisiting teams
        vm.isExistLoader = false;
        vm.loaderTitle = '';
        vm.loginContainer = angular.element('.exist-team-card');

        // show loader
        vm.startExistLoader = function(msg) {
            vm.isExistLoader = true;
            vm.loaderTitle = msg;
            vm.loginContainer.addClass('low-screen');
        };

        // stop loader
        vm.stopExistLoader = function() {
            vm.isExistLoader = false;
            vm.loaderTitle = '';
            vm.loginContainer.removeClass('low-screen');
        };

        vm.activateCollapsible = function() {
            angular.element('.collapsible').collapsible();
        };

        var parameters = {};
        parameters.url = 'participants/participant_team';
        parameters.method = 'GET';
        parameters.token = userKey;
        parameters.callback = {
            onSuccess: function(response) {
                var status = response.status;
                var details = response.data;
                if (status == 200) {
                    vm.existTeam = details;

                    if (vm.existTeam.count === 0) {
                        vm.showPagination = false;
                        vm.paginationMsg = "No team exists for now, start by creating a new team!";
                    } else {
                        vm.activateCollapsible();
                        vm.showPagination = true;
                        vm.paginationMsg = "";
                    }
                    // clear error msg from storage
                    utilities.deleteData('emailError');

                    // condition for pagination
                    if (vm.existTeam.next === null) {
                        vm.isNext = 'disabled';
                    } else {
                        vm.isNext = '';
                    }

                    if (vm.existTeam.previous === null) {
                        vm.isPrev = 'disabled';
                    } else {
                        vm.isPrev = '';
                    }
                    if (vm.existTeam.next !== null) {
                        vm.currentPage = vm.existTeam.next.split('page=')[1] - 1;
                    } else {
                        vm.currentPage = 1;
                    }

                    // select team from existing list
                    vm.selectExistTeam = function() {

                        // loader for exisiting teams
                        vm.isExistLoader = true;
                        vm.loaderTitle = '';
                        vm.loginContainer = angular.element('.exist-team-card');

                        // show loader
                        vm.startLoader = function(msg) {
                            vm.isExistLoader = true;
                            vm.loaderTitle = msg;
                            vm.loginContainer.addClass('low-screen');
                        };

                        // stop loader
                        vm.stopLoader = function() {
                            vm.isExistLoader = false;
                            vm.loaderTitle = '';
                            vm.loginContainer.removeClass('low-screen');
                        };

                        vm.startLoader("Loading Teams");
                        // loader end

                        var parameters = {};
                        parameters.url = 'challenges/challenge/' + challengePk + '/participant_team/' + vm.teamId;
                        parameters.method = 'POST';
                        parameters.token = userKey;
                        parameters.callback = {
                            onSuccess: function() {
                                $state.go('web.challenge-page.overview');
                                vm.stopLoader();
                            },
                            onError: function() {
                                vm.existTeamError = "Please select a team";
                                vm.stopLoader();
                            }
                        };
                        utilities.sendRequest(parameters);
                    };

                    // to load data with pagination
                    vm.load = function(url) {
                        // loader for exisiting teams
                        vm.isExistLoader = true;
                        vm.loaderTitle = '';
                        vm.loginContainer = angular.element('.exist-team-card');

                        // show loader
                        vm.startLoader = function(msg) {
                            vm.isExistLoader = true;
                            vm.loaderTitle = msg;
                            vm.loginContainer.addClass('low-screen');
                        };

                        // stop loader
                        vm.stopLoader = function() {
                            vm.isExistLoader = false;
                            vm.loaderTitle = '';
                            vm.loginContainer.removeClass('low-screen');
                        };

                        vm.startLoader("Loading Teams");
                        if (url !== null) {

                            //store the header data in a variable
                            var headers = {
                                'Authorization': "Token " + userKey
                            };

                            //Add headers with in your request
                            $http.get(url, { headers: headers }).then(function(response) {
                                // reinitialized data
                                var details = response.data;
                                vm.existTeam = details;

                                // condition for pagination
                                if (vm.existTeam.next === null) {
                                    vm.isNext = 'disabled';
                                    vm.currentPage = vm.existTeam.count / 10;
                                } else {
                                    vm.isNext = '';
                                    vm.currentPage = parseInt(vm.existTeam.next.split('page=')[1] - 1);
                                }

                                if (vm.existTeam.previous === null) {
                                    vm.isPrev = 'disabled';
                                } else {
                                    vm.isPrev = '';
                                }
                                vm.stopLoader();
                            });
                        } else {
                            vm.stopLoader();
                        }
                    };

                }
                utilities.hideLoader();
            },
            onError: function(response) {
                var error = response.data;
                utilities.storeData('emailError', error.detail);
                $state.go('web.permission-denied');
                utilities.hideLoader();
            }
        };

        utilities.sendRequest(parameters);

        // function to create new team
        vm.createNewTeam = function() {
            vm.isLoader = true;
            vm.loaderTitle = '';
            vm.newContainer = angular.element('.new-team-card');

            // show loader
            vm.startLoader = function(msg) {
                vm.isLoader = true;
                vm.loaderTitle = msg;
                vm.newContainer.addClass('low-screen');
            };

            // stop loader
            vm.stopLoader = function() {
                vm.isLoader = false;
                vm.loaderTitle = '';
                vm.newContainer.removeClass('low-screen');
            };

            vm.startLoader("Loading Teams");

            var parameters = {};
            parameters.url = 'participants/participant_team';
            parameters.method = 'POST';
            parameters.data = {
                "team_name": vm.team.name
            };
            parameters.token = userKey;
            parameters.callback = {
                onSuccess: function() {
                    $rootScope.notify("success", "Team- " + vm.team.name + " has been created successfully!");
                    vm.team.error = false;
                    vm.stopLoader();
                    vm.team.name = '';

                    vm.startExistLoader("Loading Teams");
                    var parameters = {};
                    parameters.url = 'participants/participant_team';
                    parameters.method = 'GET';
                    parameters.token = userKey;
                    parameters.callback = {
                        onSuccess: function(response) {
                            var status = response.status;
                            var details = response.data;
                            if (status == 200) {
                                vm.existTeam = details;
                                vm.showPagination = true;
                                vm.paginationMsg = '';

                                // condition for pagination
                                if (vm.existTeam.next === null) {
                                    vm.isNext = 'disabled';
                                    vm.currentPage = 1;
                                } else {
                                    vm.isNext = '';
                                    vm.currentPage = vm.existTeam.next.split('page=')[1] - 1;
                                }

                                if (vm.existTeam.previous === null) {
                                    vm.isPrev = 'disabled';
                                } else {
                                    vm.isPrev = '';
                                }

                                vm.stopExistLoader();
                            }
                        },
                        onError: function() {
                            vm.stopExistLoader();
                        }
                    };
                    utilities.sendRequest(parameters);
                },
                onError: function(response) {
                    var error = response.data;

                    vm.team.error = error.team_name[0];
                    vm.stopLoader();
                    $rootScope.notify("error", "New team couldn't be created.");
                }
            };

            utilities.sendRequest(parameters);

        };

        vm.confirmDelete = function(ev, participantTeamId) {
            ev.stopPropagation();
            // Appending dialog to document.body to cover sidenav in docs app
            var confirm = $mdDialog.confirm()
                .title('Would you like to remove yourself?')
                .textContent('Note: This action will remove you from the team.')
                .ariaLabel('Lucky day')
                .targetEvent(ev)
                .ok('Yes')
                .cancel("No");

            $mdDialog.show(confirm).then(function() {
                vm.startExistLoader();
                var parameters = {};
                parameters.url = 'participants/remove_self_from_participant_team/' + participantTeamId;
                parameters.method = 'DELETE';
                parameters.data = {};
                parameters.token = userKey;
                parameters.callback = {
                    onSuccess: function() {

                        vm.team.error = false;
                        $rootScope.notify("info", "You have removed yourself successfully");

                        var parameters = {};
                        parameters.url = 'participants/participant_team';
                        parameters.method = 'GET';
                        parameters.token = userKey;
                        parameters.callback = {
                            onSuccess: function(response) {
                                var status = response.status;
                                var details = response.data;
                                if (status == 200) {
                                    vm.existTeam = details;

                                    // condition for pagination
                                    if (vm.existTeam.next === null) {
                                        vm.isNext = 'disabled';
                                        vm.currentPage = vm.existTeam.count / 10;
                                    } else {
                                        vm.isNext = '';
                                        vm.currentPage = parseInt(vm.existTeam.next.split('page=')[1] - 1);
                                    }

                                    if (vm.existTeam.previous === null) {
                                        vm.isPrev = 'disabled';
                                    } else {
                                        vm.isPrev = '';
                                    }

                                    if (vm.existTeam.count === 0) {

                                        vm.showPagination = false;
                                        vm.paginationMsg = "No team exists for now, start by creating a new team!";
                                    } else {
                                        vm.showPagination = true;
                                        vm.paginationMsg = "";
                                    }
                                }

                                vm.stopExistLoader();
                            }
                        };
                        utilities.sendRequest(parameters);
                    },
                    onError: function() {
                        vm.stopExistLoader();
                        $rootScope.notify("error", "couldn't remove you from the challenge");
                    }
                };

                utilities.sendRequest(parameters);

            }, function() {
            });
        };

        vm.inviteOthers = function(ev, participantTeamId) {
            ev.stopPropagation();
            // Appending dialog to document.body to cover sidenav in docs app
            var confirm = $mdDialog.prompt()
                .title('Invite others to this team')
                .textContent('Enter the email address of the person')
                .placeholder('email')
                .ariaLabel('')
                .targetEvent(ev)
                .ok('Send Invite')
                .cancel('Cancel');

            $mdDialog.show(confirm).then(function(result) {
                var parameters = {};
                parameters.url = 'participants/participant_team/' + participantTeamId + '/invite';
                parameters.method = 'POST';
                parameters.data = {
                    "email": result
                };
                parameters.token = userKey;
                parameters.callback = {
                    onSuccess: function(response) {
                        var message = response.data['message'];
                        $rootScope.notify("success", message);
                    },
                    onError: function(response) {
                        var error = response.data['error'];
                        $rootScope.notify("error", error);
                    }
                };

                utilities.sendRequest(parameters);
            }, function() {
            });
        };
    }

})();
<commit_msg>Frontend: Integrate backend message to notify on team deletion (#964)<commit_after>// Invoking IIFE for teams
(function() {

    'use strict';

    angular
        .module('evalai')
        .controller('TeamsCtrl', TeamsCtrl);

    TeamsCtrl.$inject = ['utilities', '$scope', '$state', '$http', '$rootScope', '$mdDialog'];

    function TeamsCtrl(utilities, $scope, $state, $http, $rootScope, $mdDialog) {
        var vm = this;
        // console.log(vm.teamId)
        var userKey = utilities.getData('userKey');
        var challengePk = 1;

        utilities.showLoader();

        // default variables/objects
        vm.team = {};
        vm.teamId = null;
        vm.existTeam = {};
        vm.currentPage = '';
        vm.isNext = '';
        vm.isPrev = '';
        vm.team.error = false;
        vm.showPagination = false;

        // loader for existng teams// loader for exisiting teams
        vm.isExistLoader = false;
        vm.loaderTitle = '';
        vm.loginContainer = angular.element('.exist-team-card');

        // show loader
        vm.startExistLoader = function(msg) {
            vm.isExistLoader = true;
            vm.loaderTitle = msg;
            vm.loginContainer.addClass('low-screen');
        };

        // stop loader
        vm.stopExistLoader = function() {
            vm.isExistLoader = false;
            vm.loaderTitle = '';
            vm.loginContainer.removeClass('low-screen');
        };

        vm.activateCollapsible = function() {
            angular.element('.collapsible').collapsible();
        };

        var parameters = {};
        parameters.url = 'participants/participant_team';
        parameters.method = 'GET';
        parameters.token = userKey;
        parameters.callback = {
            onSuccess: function(response) {
                var status = response.status;
                var details = response.data;
                if (status == 200) {
                    vm.existTeam = details;

                    if (vm.existTeam.count === 0) {
                        vm.showPagination = false;
                        vm.paginationMsg = "No team exists for now, start by creating a new team!";
                    } else {
                        vm.activateCollapsible();
                        vm.showPagination = true;
                        vm.paginationMsg = "";
                    }
                    // clear error msg from storage
                    utilities.deleteData('emailError');

                    // condition for pagination
                    if (vm.existTeam.next === null) {
                        vm.isNext = 'disabled';
                    } else {
                        vm.isNext = '';
                    }

                    if (vm.existTeam.previous === null) {
                        vm.isPrev = 'disabled';
                    } else {
                        vm.isPrev = '';
                    }
                    if (vm.existTeam.next !== null) {
                        vm.currentPage = vm.existTeam.next.split('page=')[1] - 1;
                    } else {
                        vm.currentPage = 1;
                    }

                    // select team from existing list
                    vm.selectExistTeam = function() {

                        // loader for exisiting teams
                        vm.isExistLoader = true;
                        vm.loaderTitle = '';
                        vm.loginContainer = angular.element('.exist-team-card');

                        // show loader
                        vm.startLoader = function(msg) {
                            vm.isExistLoader = true;
                            vm.loaderTitle = msg;
                            vm.loginContainer.addClass('low-screen');
                        };

                        // stop loader
                        vm.stopLoader = function() {
                            vm.isExistLoader = false;
                            vm.loaderTitle = '';
                            vm.loginContainer.removeClass('low-screen');
                        };

                        vm.startLoader("Loading Teams");
                        // loader end

                        var parameters = {};
                        parameters.url = 'challenges/challenge/' + challengePk + '/participant_team/' + vm.teamId;
                        parameters.method = 'POST';
                        parameters.token = userKey;
                        parameters.callback = {
                            onSuccess: function() {
                                $state.go('web.challenge-page.overview');
                                vm.stopLoader();
                            },
                            onError: function() {
                                vm.existTeamError = "Please select a team";
                                vm.stopLoader();
                            }
                        };
                        utilities.sendRequest(parameters);
                    };

                    // to load data with pagination
                    vm.load = function(url) {
                        // loader for exisiting teams
                        vm.isExistLoader = true;
                        vm.loaderTitle = '';
                        vm.loginContainer = angular.element('.exist-team-card');

                        // show loader
                        vm.startLoader = function(msg) {
                            vm.isExistLoader = true;
                            vm.loaderTitle = msg;
                            vm.loginContainer.addClass('low-screen');
                        };

                        // stop loader
                        vm.stopLoader = function() {
                            vm.isExistLoader = false;
                            vm.loaderTitle = '';
                            vm.loginContainer.removeClass('low-screen');
                        };

                        vm.startLoader("Loading Teams");
                        if (url !== null) {

                            //store the header data in a variable
                            var headers = {
                                'Authorization': "Token " + userKey
                            };

                            //Add headers with in your request
                            $http.get(url, { headers: headers }).then(function(response) {
                                // reinitialized data
                                var details = response.data;
                                vm.existTeam = details;

                                // condition for pagination
                                if (vm.existTeam.next === null) {
                                    vm.isNext = 'disabled';
                                    vm.currentPage = vm.existTeam.count / 10;
                                } else {
                                    vm.isNext = '';
                                    vm.currentPage = parseInt(vm.existTeam.next.split('page=')[1] - 1);
                                }

                                if (vm.existTeam.previous === null) {
                                    vm.isPrev = 'disabled';
                                } else {
                                    vm.isPrev = '';
                                }
                                vm.stopLoader();
                            });
                        } else {
                            vm.stopLoader();
                        }
                    };

                }
                utilities.hideLoader();
            },
            onError: function(response) {
                var error = response.data;
                utilities.storeData('emailError', error.detail);
                $state.go('web.permission-denied');
                utilities.hideLoader();
            }
        };

        utilities.sendRequest(parameters);

        // function to create new team
        vm.createNewTeam = function() {
            vm.isLoader = true;
            vm.loaderTitle = '';
            vm.newContainer = angular.element('.new-team-card');

            // show loader
            vm.startLoader = function(msg) {
                vm.isLoader = true;
                vm.loaderTitle = msg;
                vm.newContainer.addClass('low-screen');
            };

            // stop loader
            vm.stopLoader = function() {
                vm.isLoader = false;
                vm.loaderTitle = '';
                vm.newContainer.removeClass('low-screen');
            };

            vm.startLoader("Loading Teams");

            var parameters = {};
            parameters.url = 'participants/participant_team';
            parameters.method = 'POST';
            parameters.data = {
                "team_name": vm.team.name
            };
            parameters.token = userKey;
            parameters.callback = {
                onSuccess: function() {
                    $rootScope.notify("success", "Team- " + vm.team.name + " has been created successfully!");
                    vm.team.error = false;
                    vm.stopLoader();
                    vm.team.name = '';

                    vm.startExistLoader("Loading Teams");
                    var parameters = {};
                    parameters.url = 'participants/participant_team';
                    parameters.method = 'GET';
                    parameters.token = userKey;
                    parameters.callback = {
                        onSuccess: function(response) {
                            var status = response.status;
                            var details = response.data;
                            if (status == 200) {
                                vm.existTeam = details;
                                vm.showPagination = true;
                                vm.paginationMsg = '';

                                // condition for pagination
                                if (vm.existTeam.next === null) {
                                    vm.isNext = 'disabled';
                                    vm.currentPage = 1;
                                } else {
                                    vm.isNext = '';
                                    vm.currentPage = vm.existTeam.next.split('page=')[1] - 1;
                                }

                                if (vm.existTeam.previous === null) {
                                    vm.isPrev = 'disabled';
                                } else {
                                    vm.isPrev = '';
                                }

                                vm.stopExistLoader();
                            }
                        },
                        onError: function() {
                            vm.stopExistLoader();
                        }
                    };
                    utilities.sendRequest(parameters);
                },
                onError: function(response) {
                    var error = response.data;

                    vm.team.error = error.team_name[0];
                    vm.stopLoader();
                    $rootScope.notify("error", "New team couldn't be created.");
                }
            };

            utilities.sendRequest(parameters);

        };

        vm.confirmDelete = function(ev, participantTeamId) {
            ev.stopPropagation();
            // Appending dialog to document.body to cover sidenav in docs app
            var confirm = $mdDialog.confirm()
                .title('Would you like to remove yourself?')
                .textContent('Note: This action will remove you from the team.')
                .ariaLabel('Lucky day')
                .targetEvent(ev)
                .ok('Yes')
                .cancel("No");

            $mdDialog.show(confirm).then(function() {
                vm.startExistLoader();
                var parameters = {};
                parameters.url = 'participants/remove_self_from_participant_team/' + participantTeamId;
                parameters.method = 'DELETE';
                parameters.data = {};
                parameters.token = userKey;
                parameters.callback = {
                    onSuccess: function() {

                        vm.team.error = false;
                        $rootScope.notify("info", "You have removed yourself successfully");

                        var parameters = {};
                        parameters.url = 'participants/participant_team';
                        parameters.method = 'GET';
                        parameters.token = userKey;
                        parameters.callback = {
                            onSuccess: function(response) {
                                var status = response.status;
                                var details = response.data;
                                if (status == 200) {
                                    vm.existTeam = details;

                                    // condition for pagination
                                    if (vm.existTeam.next === null) {
                                        vm.isNext = 'disabled';
                                        vm.currentPage = vm.existTeam.count / 10;
                                    } else {
                                        vm.isNext = '';
                                        vm.currentPage = parseInt(vm.existTeam.next.split('page=')[1] - 1);
                                    }

                                    if (vm.existTeam.previous === null) {
                                        vm.isPrev = 'disabled';
                                    } else {
                                        vm.isPrev = '';
                                    }

                                    if (vm.existTeam.count === 0) {

                                        vm.showPagination = false;
                                        vm.paginationMsg = "No team exists for now, start by creating a new team!";
                                    } else {
                                        vm.showPagination = true;
                                        vm.paginationMsg = "";
                                    }
                                }

                                vm.stopExistLoader();
                            }
                        };
                        utilities.sendRequest(parameters);
                    },
                    onError: function(response) {
                        var error = response.data['error'];
                        vm.stopExistLoader();
                        $rootScope.notify("error", error);
                    }
                };

                utilities.sendRequest(parameters);

            }, function() {
            });
        };

        vm.inviteOthers = function(ev, participantTeamId) {
            ev.stopPropagation();
            // Appending dialog to document.body to cover sidenav in docs app
            var confirm = $mdDialog.prompt()
                .title('Invite others to this team')
                .textContent('Enter the email address of the person')
                .placeholder('email')
                .ariaLabel('')
                .targetEvent(ev)
                .ok('Send Invite')
                .cancel('Cancel');

            $mdDialog.show(confirm).then(function(result) {
                var parameters = {};
                parameters.url = 'participants/participant_team/' + participantTeamId + '/invite';
                parameters.method = 'POST';
                parameters.data = {
                    "email": result
                };
                parameters.token = userKey;
                parameters.callback = {
                    onSuccess: function(response) {
                        var message = response.data['message'];
                        $rootScope.notify("success", message);
                    },
                    onError: function(response) {
                        var error = response.data['error'];
                        $rootScope.notify("error", error);
                    }
                };

                utilities.sendRequest(parameters);
            }, function() {
            });
        };
    }

})();
<|endoftext|>


<commit_before>// ---------------------------------------------------------------------------------------------------------------------
// Unit Tests for the models.spec.js module.
//
// @module models.spec.js
// ---------------------------------------------------------------------------------------------------------------------

var _ = require('lodash');
var assert = require("assert");

var trivialdb = require('../trivialdb');
var errors = require('../lib/errors');

// ---------------------------------------------------------------------------------------------------------------------

describe('Models', function()
{

    var TestModel, DateTestModel, PKTestModel, NestedTestModel;
    beforeEach(function()
    {
        TestModel = trivialdb.defineModel('model_test', {
            name: { type: String, required: true },
            admin: { type: Boolean, default: false, required: true },
            foo: Number,
            choice: { type: String, choices: ['foo', 'bar'] },
            toppings: { type: Array, choices: ['cheese', 'pepperoni', 'mushrooms'] }
        }, { writeToDisk: false });

        DateTestModel = trivialdb.defineModel('date_model_test', {
            name: { type: String, required: true },
            created: { type: Date, default: Date.now() }
        }, { writeToDisk: false });

        PKTestModel = trivialdb.defineModel('pk_model_test', {
            name: { type: String, required: true },
            admin: { type: Boolean, default: false, required: true }
        }, { writeToDisk: false, pk: 'name' });

        NestedTestModel = trivialdb.defineModel('nested_test_model', {
            name: String,
            test: {
                foo: String,
                bar: Number
            }
        }, { writeToDisk: false, pk: 'name' });

        // Populate the database
        return trivialdb.Promise.all([
                trivialdb.db('model_test').store('test1', { name: 'foobar', admin: false }),
                trivialdb.db('model_test').store('test2', { name: 'barbaz', admin: true }),
                trivialdb.db('model_test').store('test3', { name: 'foo 2', admin: false, foo: 3 }),
                trivialdb.db('model_test').store('test4', { name: 'glipi', admin: true, foo: -1.5 })
            ])
            .then(function()
            {
                return trivialdb.Promise.all([
                    trivialdb.db('pk_model_test').store({ name: 'foobar', admin: false }),
                    trivialdb.db('pk_model_test').store({ name: 'barbaz', admin: true })
                ]);
            })
            .then(function()
            {
                return trivialdb.Promise.all([
                    trivialdb.db('nested_test_model').store({ name: 'nt1', test: { foo: "Bar!", bar: 3 } }),
                    trivialdb.db('nested_test_model').store({ name: 'nt2', test: { foo: "apples"} })
                ]);
            });
    });

    describe('Model Instance', function()
    {
        it('can convert to simple json', function()
        {
            var test = new TestModel({ name: 'test' });
            var testJSON = JSON.stringify(test);

            assert.deepEqual(JSON.parse(testJSON), { name: 'test', admin: false });
        });

        it('can save new instances', function()
        {
            var test = new TestModel({ name: 'test' });

            return test.save().then(function(test)
            {
                // Ensure the document is saved in the db correctly.
                return trivialdb.db('model_test').get(test.id).then(function(doc)
                {
                    assert.deepEqual(doc, { id: test.id, name: 'test' });
                });
            });
        });

        it('can update existing instances', function()
        {
            return TestModel.get('test1').then(function(test)
            {
                test.admin = true;
                return test.save().then(function()
                {
                    // Ensure the document is saved in the db correctly.
                    return trivialdb.db('model_test').get(test.id).then(function(doc)
                    {
                        assert.deepEqual(doc, { id: test.id, name: 'foobar', admin: true });
                    });
                });
            });
        });

        it('validated before it saves', function()
        {
            return TestModel.get('test1').then(function(test)
            {
                test.admin = 'true';
                return test.save().then(function()
                {
                    assert(false, "Did not throw an error.");
                })
                .catch(errors.ValidationError, function() {});
            });
        });

        it('can validate models without saving', function()
        {
            return TestModel.get('test1').then(function(test)
            {
                test.admin = 'true';
                return test.validate()
                    .then(function()
                    {
                        assert(false, "Did not throw an error.");
                    })
                    .catch(errors.ValidationError, function() {});
            });
        });

        it('can remove models', function()
        {
            return TestModel.get('test1').then(function(test)
            {
                return test.remove()
                    .then(function()
                    {
                        return TestModel.get('test1');
                    })
                    .then(function()
                    {
                        assert(false, "Did not throw an error.");
                    })
                    .catch(errors.DocumentNotFound, function() {});
            });
        });

        it('can force a sync', function()
        {
            return TestModel.get('test1').then(function(test)
            {
                assert.equal(test.admin, false);

                test.foo = 23;

                assert.equal(test.$dirty, true);

                return trivialdb.db('model_test').merge('test1', { admin: true })
                    .then(function()
                    {
                        return test.sync(true)
                            .then(function()
                            {
                                assert.equal(test.admin, true);
                                assert.equal(test.foo, undefined);
                            });
                    });
            });
        });

        it('can specify a primary key', function()
        {
            return PKTestModel.get('foobar')
                .then(function(test)
                {
                    assert(test.id === test.name, "The 'id' property does not point to the correct field.");
                })
                .then(function()
                {
                    // Test saving
                    return new PKTestModel({ name: 'tom', admin: true }).save()
                        .then(function(test2)
                        {
                            assert(test2.id === test2.name, "The 'id' property does not point to the correct field.");
                            assert(test2.$$values.id === undefined, "The model has an 'id' property in $$values.");
                        });
                });
        });

        it('correctly handles Date objects', function()
        {
            return new DateTestModel({ name: "FredGeorge" }).save()
                .then(function(test)
                {
                    assert(_.isDate(test.created));
                });
        });

        it('supports nested schemas', function()
        {
            return NestedTestModel.get('nt1')
                .then(function(model)
                {
                    assert.equal(model.test.foo, "Bar!");
                })
                .then(function()
                {
                    return (new NestedTestModel({ name: 'foo', test: { bar: 5 } })).save()
                        .then(function(model)
                        {
                            assert.equal(model.test.bar, 5);
                        });
                });
        });
    });

    describe('Model API', function()
    {
        it('can retrieve model instances by id', function()
        {
            return TestModel.get('test1').then(function(test)
            {
                assert.deepEqual(test.$$values, { id: 'test1', name: 'foobar', admin: false });
            });
        });

        it('returns a DocumentNotFoundError when attempting to retrieve an non-existent id', function()
        {
            return TestModel.get('does-not-exist')
                .then(function()
                {
                    assert(false, "Did not throw an error.");
                })
                .catch(errors.DocumentNotFound, function() {});
        });

        it('can retrieve all models', function()
        {
            return TestModel.all()
                .then(function(allModels)
                {
                    assert.equal(allModels.length, 5);
                });
        });

        it('can filter all models down to a subset', function()
        {
            return TestModel.filter({ admin: true })
                .then(function(filtered)
                {
                    assert.equal(filtered.length, 2);
                });
        });

        describe('Remove', function()
        {
            it('can remove model instances by id', function()
            {
                return TestModel.remove('test2')
                    .then(function()
                    {
                        return TestModel.get('test2')
                            .then(function()
                            {
                                assert(false, "Did not throw an error.");
                            })
                            .catch(errors.DocumentNotFound, function() {});
                    });
            });

            it('can remove model instances by a filter', function()
            {
                return TestModel.remove({ admin: true })
                    .then(function()
                    {
                        return TestModel.get('test2')
                            .then(function()
                            {
                                assert(false, "Did not throw an error.");
                            })
                            .catch(errors.DocumentNotFound, function() {});
                    });
            });

            it('can remove all instances', function()
            {
                return TestModel.removeAll()
                    .then(function()
                    {
                        return TestModel.get('test4')
                            .then(function()
                            {
                                assert(false, "Did not throw an error.");
                            })
                            .catch(errors.DocumentNotFound, function() {});
                    });
            });
        });

        describe('Validation', function()
        {
            it('validates a correct instance', function()
            {
                return TestModel.get('test1').then(function(test)
                {
                    test.admin = true;
                    test.choice = 'bar';
                    test.toppings = ['cheese', 'mushrooms'];
                    return test.validate();
                });
            });

            it('fails to validate when missing a required field', function()
            {
                return TestModel.get('test1').then(function(test)
                {
                    test.admin = null;
                    return test.validate()
                        .then(function()
                        {
                            assert(false, "Did not throw an error.");
                        })
                        .catch(errors.ValidationError, function() {});
                });
            });

            it('fails to validate an incorrect type', function()
            {
                return TestModel.get('test1').then(function(test)
                {
                    test.admin = 3;
                    return test.validate()
                        .then(function()
                        {
                            assert(false, "Did not throw an error.");
                        })
                        .catch(errors.ValidationError, function() {});
                });
            });

            it('fails to validate an invalid choice', function()
            {
                return TestModel.get('test1').then(function(test)
                {
                    test.choice = 'baz';
                    test.toppings = ['cheese', 'pineapple'];
                    return test.validate()
                        .then(function()
                        {
                            assert(false, "Did not throw an error.");
                        })
                        .catch(errors.ValidationError, function() {});
                });
            });

            it('fails to validate an incorrect type on a nested field', function()
            {
                return NestedTestModel.get('nt2')
                    .then(function(model)
                    {
                        assert.equal(model.test.foo, "apples");

                        model.test.bar = "omg!";
                        return model.validate()
                            .then(function()
                            {
                                assert(false, "Did not throw an error.");
                            })
                            .catch(errors.ValidationError, function() {});
                    });
            });
        });

        describe('Relations', function()
        {
            xit('supports one-to-one relationships', function(done)
            {

            });

            xit('supports one-to-many relationships', function(done)
            {

            });

            xit('supports many-to-one relationships', function(done)
            {

            });

            xit('supports many-to-many relationships', function(done)
            {

            });

            xit('populates relationships', function(done)
            {

            });

            xit('depopulates relationships', function(done)
            {

            });

            xit('includes populated models in `toJSON()`', function(done)
            {

            });

            xit('supports hiding the key of relationships from `toJSON()`', function(done)
            {

            });

            xit('correctly saves changes when `hasOne` relation field is assigned to', function(done)
            {

            });

            xit('correctly saves changes when `hasMany` relation field is assigned to', function(done)
            {

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

// ---------------------------------------------------------------------------------------------------------------------
<commit_msg>implemented unit tests.<commit_after>// ---------------------------------------------------------------------------------------------------------------------
// Unit Tests for the models.spec.js module.
//
// @module models.spec.js
// ---------------------------------------------------------------------------------------------------------------------

var _ = require('lodash');
var assert = require("assert");

var trivialdb = require('../trivialdb');
var errors = require('../lib/errors');

// ---------------------------------------------------------------------------------------------------------------------

describe('Models', function()
{

    var TestModel, DateTestModel, PKTestModel, NestedTestModel, RelationsTestModel, RelationsManyModel;
    beforeEach(function()
    {
        TestModel = trivialdb.defineModel('model_test', {
            name: { type: String, required: true },
            admin: { type: Boolean, default: false, required: true },
            foo: Number,
            choice: { type: String, choices: ['foo', 'bar'] },
            toppings: { type: Array, choices: ['cheese', 'pepperoni', 'mushrooms'] }
        }, { writeToDisk: false });

        DateTestModel = trivialdb.defineModel('date_model_test', {
            name: { type: String, required: true },
            created: { type: Date, default: Date.now() }
        }, { writeToDisk: false });

        PKTestModel = trivialdb.defineModel('pk_model_test', {
            name: { type: String, required: true },
            admin: { type: Boolean, default: false, required: true }
        }, { writeToDisk: false, pk: 'name' });

        NestedTestModel = trivialdb.defineModel('nested_test_model', {
            name: String,
            test: {
                foo: String,
                bar: Number
            }
        }, { writeToDisk: false, pk: 'name' });

        RelationsTestModel = trivialdb.defineModel('relations_test_model', {
            name: String,
            testID: String
        }, { writeToDisk: false, pk: 'name' });

        RelationsManyModel = trivialdb.defineModel('relations_many_model', {
            name: String,
            modelIDs: Array
        }, { writeToDisk: false, pk: 'name' });

        // Populate the database
        return trivialdb.Promise.all([
                trivialdb.db('model_test').store('test1', { name: 'foobar', admin: false }),
                trivialdb.db('model_test').store('test2', { name: 'barbaz', admin: true }),
                trivialdb.db('model_test').store('test3', { name: 'foo 2', admin: false, foo: 3 }),
                trivialdb.db('model_test').store('test4', { name: 'glipi', admin: true, foo: -1.5 })
            ])
            .then(function()
            {
                return trivialdb.Promise.all([
                    trivialdb.db('pk_model_test').store({ name: 'foobar', admin: false }),
                    trivialdb.db('pk_model_test').store({ name: 'barbaz', admin: true })
                ]);
            })
            .then(function()
            {
                return trivialdb.Promise.all([
                    trivialdb.db('nested_test_model').store({ name: 'nt1', test: { foo: "Bar!", bar: 3 } }),
                    trivialdb.db('nested_test_model').store({ name: 'nt2', test: { foo: "apples"} })
                ]);
            })
            .then(function()
            {
                return trivialdb.Promise.all([
                    trivialdb.db('relations_test_model').store({ name: 'rtm1', testID: 'foobar', manyID: 'rmm1' }),
                    trivialdb.db('relations_test_model').store({ name: 'rtm2', testID: 'barbaz', manyID: 'rmm1' }),
                    trivialdb.db('relations_test_model').store({ name: 'rtm3', testID: 'barbaz' }),
                    trivialdb.db('relations_many_model').store({ name: 'rmm1' })
                ]);
            });
    });

    describe('Model Instance', function()
    {
        it('can convert to simple json', function()
        {
            var test = new TestModel({ name: 'test' });
            var testJSON = JSON.stringify(test);

            assert.deepEqual(JSON.parse(testJSON), { name: 'test', admin: false });
        });

        it('can save new instances', function()
        {
            var test = new TestModel({ name: 'test' });

            return test.save().then(function(test)
            {
                // Ensure the document is saved in the db correctly.
                return trivialdb.db('model_test').get(test.id).then(function(doc)
                {
                    assert.deepEqual(doc, { id: test.id, name: 'test' });
                });
            });
        });

        it('can update existing instances', function()
        {
            return TestModel.get('test1').then(function(test)
            {
                test.admin = true;
                return test.save().then(function()
                {
                    // Ensure the document is saved in the db correctly.
                    return trivialdb.db('model_test').get(test.id).then(function(doc)
                    {
                        assert.deepEqual(doc, { id: test.id, name: 'foobar', admin: true });
                    });
                });
            });
        });

        it('validated before it saves', function()
        {
            return TestModel.get('test1').then(function(test)
            {
                test.admin = 'true';
                return test.save().then(function()
                {
                    assert(false, "Did not throw an error.");
                })
                .catch(errors.ValidationError, function() {});
            });
        });

        it('can validate models without saving', function()
        {
            return TestModel.get('test1').then(function(test)
            {
                test.admin = 'true';
                return test.validate()
                    .then(function()
                    {
                        assert(false, "Did not throw an error.");
                    })
                    .catch(errors.ValidationError, function() {});
            });
        });

        it('can remove models', function()
        {
            return TestModel.get('test1').then(function(test)
            {
                return test.remove()
                    .then(function()
                    {
                        return TestModel.get('test1');
                    })
                    .then(function()
                    {
                        assert(false, "Did not throw an error.");
                    })
                    .catch(errors.DocumentNotFound, function() {});
            });
        });

        it('can force a sync', function()
        {
            return TestModel.get('test1').then(function(test)
            {
                assert.equal(test.admin, false);

                test.foo = 23;

                assert.equal(test.$dirty, true);

                return trivialdb.db('model_test').merge('test1', { admin: true })
                    .then(function()
                    {
                        return test.sync(true)
                            .then(function()
                            {
                                assert.equal(test.admin, true);
                                assert.equal(test.foo, undefined);
                            });
                    });
            });
        });

        it('can specify a primary key', function()
        {
            return PKTestModel.get('foobar')
                .then(function(test)
                {
                    assert(test.id === test.name, "The 'id' property does not point to the correct field.");
                })
                .then(function()
                {
                    // Test saving
                    return new PKTestModel({ name: 'tom', admin: true }).save()
                        .then(function(test2)
                        {
                            assert(test2.id === test2.name, "The 'id' property does not point to the correct field.");
                            assert(test2.$$values.id === undefined, "The model has an 'id' property in $$values.");
                        });
                });
        });

        it('correctly handles Date objects', function()
        {
            return new DateTestModel({ name: "FredGeorge" }).save()
                .then(function(test)
                {
                    assert(_.isDate(test.created));
                });
        });

        it('supports nested schemas', function()
        {
            return NestedTestModel.get('nt1')
                .then(function(model)
                {
                    assert.equal(model.test.foo, "Bar!");
                })
                .then(function()
                {
                    return (new NestedTestModel({ name: 'foo', test: { bar: 5 } })).save()
                        .then(function(model)
                        {
                            assert.equal(model.test.bar, 5);
                        });
                });
        });
    });

    describe('Model API', function()
    {
        it('can retrieve model instances by id', function()
        {
            return TestModel.get('test1').then(function(test)
            {
                assert.deepEqual(test.$$values, { id: 'test1', name: 'foobar', admin: false });
            });
        });

        it('returns a DocumentNotFoundError when attempting to retrieve an non-existent id', function()
        {
            return TestModel.get('does-not-exist')
                .then(function()
                {
                    assert(false, "Did not throw an error.");
                })
                .catch(errors.DocumentNotFound, function() {});
        });

        it('can retrieve all models', function()
        {
            return TestModel.all()
                .then(function(allModels)
                {
                    assert.equal(allModels.length, 5);
                });
        });

        it('can filter all models down to a subset', function()
        {
            return TestModel.filter({ admin: true })
                .then(function(filtered)
                {
                    assert.equal(filtered.length, 2);
                });
        });

        describe('Remove', function()
        {
            it('can remove model instances by id', function()
            {
                return TestModel.remove('test2')
                    .then(function()
                    {
                        return TestModel.get('test2')
                            .then(function()
                            {
                                assert(false, "Did not throw an error.");
                            })
                            .catch(errors.DocumentNotFound, function() {});
                    });
            });

            it('can remove model instances by a filter', function()
            {
                return TestModel.remove({ admin: true })
                    .then(function()
                    {
                        return TestModel.get('test2')
                            .then(function()
                            {
                                assert(false, "Did not throw an error.");
                            })
                            .catch(errors.DocumentNotFound, function() {});
                    });
            });

            it('can remove all instances', function()
            {
                return TestModel.removeAll()
                    .then(function()
                    {
                        return TestModel.get('test4')
                            .then(function()
                            {
                                assert(false, "Did not throw an error.");
                            })
                            .catch(errors.DocumentNotFound, function() {});
                    });
            });
        });

        describe('Validation', function()
        {
            it('validates a correct instance', function()
            {
                return TestModel.get('test1').then(function(test)
                {
                    test.admin = true;
                    test.choice = 'bar';
                    test.toppings = ['cheese', 'mushrooms'];
                    return test.validate();
                });
            });

            it('fails to validate when missing a required field', function()
            {
                return TestModel.get('test1').then(function(test)
                {
                    test.admin = null;
                    return test.validate()
                        .then(function()
                        {
                            assert(false, "Did not throw an error.");
                        })
                        .catch(errors.ValidationError, function() {});
                });
            });

            it('fails to validate an incorrect type', function()
            {
                return TestModel.get('test1').then(function(test)
                {
                    test.admin = 3;
                    return test.validate()
                        .then(function()
                        {
                            assert(false, "Did not throw an error.");
                        })
                        .catch(errors.ValidationError, function() {});
                });
            });

            it('fails to validate an invalid choice', function()
            {
                return TestModel.get('test1').then(function(test)
                {
                    test.choice = 'baz';
                    test.toppings = ['cheese', 'pineapple'];
                    return test.validate()
                        .then(function()
                        {
                            assert(false, "Did not throw an error.");
                        })
                        .catch(errors.ValidationError, function() {});
                });
            });

            it('fails to validate an incorrect type on a nested field', function()
            {
                return NestedTestModel.get('nt2')
                    .then(function(model)
                    {
                        assert.equal(model.test.foo, "apples");

                        model.test.bar = "omg!";
                        return model.validate()
                            .then(function()
                            {
                                assert(false, "Did not throw an error.");
                            })
                            .catch(errors.ValidationError, function() {});
                    });
            });
        });

        describe('Relations', function()
        {
            it('supports defining hasOne relationships', function()
            {
                RelationsTestModel.hasOne(TestModel, 'test', 'testID', 'id');

                assert.notEqual(RelationsTestModel.schema.$relations.test, undefined);
                assert.equal(RelationsTestModel.schema.$relations.test.type, 'hasOne');
            });

            it('supports defining hasMany relationships', function()
            {
                RelationsManyModel.hasMany(RelationsTestModel, 'rel', 'modelIDs', 'name');

                assert.notEqual(RelationsManyModel.schema.$relations.rel, undefined);
                assert.equal(RelationsManyModel.schema.$relations.rel.type, 'hasMany');
            });

            it('populates relationships', function(done)
            {
                // Define relationships
                RelationsTestModel.hasOne(TestModel, 'test', 'testID', 'name');
                RelationsManyModel.hasMany(RelationsTestModel, 'rel', 'name', 'manyID');

                // Test hasOne
                RelationsTestModel.get('rtm1', { populate: true })
                    .then(function(model)
                    {
                        assert.equal(model.name, 'rtm1');
                        assert.equal(model.test.name, 'foobar');

                        // Test hasMany
                        RelationsManyModel.get('rmm1', { populate: true })
                            .then(function(model)
                            {
                                assert.equal(model.name, 'rmm1');
                                assert.equal(model.rel[0].name, 'rtm1');
                                done();
                            });
                    });
            });

            it('depopulates relationships', function(done)
            {
                // Define relationships
                RelationsTestModel.hasOne(TestModel, 'test', 'testID', 'name');

                // Test hasOne
                RelationsTestModel.get('rtm1', { populate: true })
                    .then(function(model)
                    {
                        assert.equal(model.name, 'rtm1');
                        assert.equal(model.test.name, 'foobar');

                        model.depopulate()
                            .then(function(model)
                            {
                                assert.equal(model.test, undefined);
                                done();
                            });
                    });
            });

            it('includes populated models in `toJSON()`', function(done)
            {
                // Define relationships
                RelationsTestModel.hasOne(TestModel, 'test', 'testID', 'name');

                // Test hasOne
                RelationsTestModel.get('rtm1', { populate: true })
                    .then(function(model)
                    {
                        assert.equal(model.name, 'rtm1');
                        assert.equal(model.test.name, 'foobar');

                        var json = model.toJSON();
                        assert.equal(json.test.name, 'foobar');
                        done();
                    });
            });

            it('supports hiding the key of relationships from `toJSON()`', function(done)
            {
                // Define relationships
                RelationsTestModel.hasOne(TestModel, 'test', 'testID', 'name');

                // Test hasOne
                RelationsTestModel.get('rtm1', { populate: true })
                    .then(function(model)
                    {
                        assert.equal(model.name, 'rtm1');
                        assert.equal(model.test.name, 'foobar');

                        var json = model.toJSON();
                        assert.equal(json.$relationships, undefined);
                        done();
                    });
            });

            it('correctly saves changes when `hasOne` relation field is assigned to', function(done)
            {
                // Define relationships
                RelationsTestModel.hasOne(TestModel, 'test', 'testID', 'name');

                // Test hasOne
                RelationsTestModel.get('rtm1', { populate: true })
                    .then(function(model)
                    {
                        assert.equal(model.test.name, 'foobar');

                        TestModel.get('test2')
                            .then(function(testModel)
                            {
                                model.test = testModel;
                                model.save()
                                    .then(function(model)
                                    {
                                        assert.equal(model.test.name, 'barbaz');
                                        done();
                                    });
                            });
                    });
            });

            it('correctly saves changes when `hasMany` relation field is assigned to', function(done)
            {
                // Define relationships
                RelationsManyModel.hasMany(RelationsTestModel, 'rel', 'name', 'manyID');

                // Test hasMany
                RelationsManyModel.get('rmm1', { populate: true })
                    .then(function(model)
                    {
                        assert.equal(model.rel[0].name, 'rtm1');

                        RelationsTestModel.get('rtm3')
                            .then(function(testModel)
                            {
                                model.rel.push(testModel);

                                model.save()
                                    .then(function(model)
                                    {
                                        assert.equal(model.rel[2].name, 'rtm3');
                                        done();
                                    });
                            });
                    });
            });
        });
    });
});

// ---------------------------------------------------------------------------------------------------------------------
<|endoftext|>


<commit_before>/* View to ask to have your password reset.  If successful, user
   is emailed a link to the password-reset-form page that includes
   a limited-time password reset key.
 */
var Backbone = require('backbone'),
    template = require("../templates/password-reset-request.hbs"),
    forms = require('../forms'),
    messages = require('../messages'),
    i18n = require('i18next-client');

module.exports = Backbone.View.extend({
    initialize: function(opts){
        self.key = opts.key;
    },

    render: function() {
        var $el = this.$el;
        this.$el.html(template({}));
    },

    events: {
        "click .form-btn-submit": function () {
            var $el = this.$el;
            var $form = $el.find('form');

            var $submit = $form.find('.form-btn-submit');
            $submit.attr('disabled', 'disabled');

            $el.find('.error').text('');
            messages.clear();
            var email = $el.find('input[name=email]').val();
            var data = {
                email: email,
                base_reset_link: location.protocol + '//' + location.host + location.pathname + '?#/password-reset/'
            };
            forms.submit($form, 'api/password_reset_request/', data).then(
                function on_success() {
                    $submit.removeAttr('disabled');
                    messages.add(i18n.t('Password-Reset.Submitted'));
                },
                function on_error() {
                    $submit.removeAttr('disabled');
                    // forms.js has already displayed any errors
                }
            );
        }
    }
})
<commit_msg>Review feedback:<commit_after>/* View to ask to have your password reset.  If successful, user
   is emailed a link to the password-reset-form page that includes
   a limited-time password reset key.
 */
var Backbone = require('backbone'),
    template = require("../templates/password-reset-request.hbs"),
    forms = require('../forms'),
    messages = require('../messages'),
    i18n = require('i18next-client');

module.exports = Backbone.View.extend({
    initialize: function(){
    },

    render: function() {
        var $el = this.$el;
        this.$el.html(template({}));
    },

    events: {
        "click .form-btn-submit": function (e) {
            e.preventDefault();
            var $el = this.$el;
            var $form = $el.find('form');

            var $submit = $form.find('.form-btn-submit');
            $submit.attr('disabled', 'disabled');

            $el.find('.error').text('');
            messages.clear();
            var email = $el.find('input[name=email]').val();
            var data = {
                email: email,
                base_reset_link: location.protocol + '//' + location.host + location.pathname + '?#/password-reset/'
            };
            forms.submit($form, 'api/password_reset_request/', data).then(
                function on_success() {
                    $submit.removeAttr('disabled');
                    messages.add(i18n.t('Password-Reset.Submitted'));
                },
                function on_error() {
                    $submit.removeAttr('disabled');
                    // forms.js has already displayed any errors
                }
            );
        }
    }
})
<|endoftext|>