<commit_before>'use strict';

angular.module('mean.icu.ui.projectdetails', []).controller('ProjectDetailsController', ProjectDetailsController);

function ProjectDetailsController($scope, $rootScope, entity, people, tasks, projects, tags, $timeout, context, $state, ProjectsService, ActivitiesService, PermissionsService, EntityService, $stateParams, me, $window) {

  // ==================================================== init ==================================================== //

  if($state.$current.url.source.includes('search') || $state.$current.url.source.includes('projects')) {
    $scope.item = entity || context.entity;
  }
  else {
    $scope.item = context.entity || entity;
  }

  if(!$scope.item) {
    $state.go('main.projects.byentity', {
      entity: context.entityName,
      entityId: context.entityId
    });
  }
  else if($scope.item && ($state.current.name === 'main.projects.all.details' || $state.current.name === 'main.search.project' || $state.current.name === 'main.projects.byentity.details')) {
    $state.go('.activities');
  }

  $scope.items = projects.data || projects;

  $scope.editorOptions = {
    theme: 'bootstrap',
    buttons: ['bold', 'italic', 'underline', 'anchor', 'quote', 'orderedlist', 'unorderedlist']
  };
  $scope.statuses = ['new', 'assigned', 'in-progress', 'canceled', 'completed', 'archived'];

  $scope.me = me;
  $scope.tags = tags;

  let currentState = $state.current.name;

  // backup for previous changes - for updates
  var backupEntity = JSON.parse(JSON.stringify($scope.item));

  $scope.people = people.data || people;
  if($scope.people && $scope.people[Object.keys($scope.people).length - 1].name !== 'no select') {
    var newPeople = {
      name: 'no select'
    };
    $scope.people.push(_(newPeople).clone());
  }
  for(var i = 0; i < $scope.people.length; i++) {
    if($scope.people[i] && ($scope.people[i].job == undefined || $scope.people[i].job == null)) {
      $scope.people[i].job = $scope.people[i].name;
    }
  }

  ProjectsService.getStarred().then(function(starred) {
    $scope.item.star = _(starred).any(function(s) {
      return s._id === $scope.item._id;
    });
  });

  // ==================================================== onChanges ==================================================== //

  function navigateToDetails(project) {
    $scope.detailsState = context.entityName === 'all' ? 'main.projects.all.details' : 'main.projects.byentity.details';

    $state.go($scope.detailsState, {
      id: project._id,
      entity: context.entityName,
      entityId: context.entityId,
      starred: $stateParams.starred
    }, {
      reload: true
    });
  }

  $scope.onStar = function(value) {
    ProjectsService.star($scope.item).then(function() {
    navigateToDetails($scope.item);
    // "$scope.item.star" will be change in 'ProjectsService.star' function
    });
  };

  $scope.onAssign = function(value) {
    $scope.item.assign = value;
    $scope.updateAndNotify($scope.item);
  };

  $scope.onDateDue = function(value) {
    $scope.item.due = value;
    if(context.entityName === 'discussion') {
      $scope.item.discussion = context.entityId;
    }

    ProjectsService.updateDue($scope.item, backupEntity).then(function (result) {
      backupEntity = JSON.parse(JSON.stringify($scope.item));
      ActivitiesService.data.push(result);
    });

    ProjectsService.update($scope.item).then(function(result) {
      if(context.entityName === 'project') {
        var projId = result.project ? result.project._id : undefined;
        if(projId !== context.entityId) {
          $state.go('main.projects.byentity', {
            entity: context.entityName,
            entityId: context.entityId
          }, {
            reload: true
          });
        }
      }
    });
  };

  $scope.onStatus = function(value) {
    $scope.item.status = value;
    $scope.update($scope.item, {
      name: 'status'
    });
  };

  $scope.onColor = function(value) {
    $scope.update($scope.item, value);
  };

  $scope.onWantToCreateRoom = function() {
    $scope.item.WantRoom = true;
    $scope.update($scope.item, context);

    ProjectsService.WantToCreateRoom($scope.item).then(function(data) {
      navigateToDetails($scope.item);
      if(data.roomName) {
        $window.open(window.config.rocketChat.uri + '/group/', data.roomName);
        return true;
      }
      else {
        return false;
      }
    });
  };

  $scope.onTags = function(value) {
    $scope.item.tags = value;
    $scope.update($scope.item, {name: 'tag'});
  };

  // ==================================================== Menu events ==================================================== //

  $scope.recycle = function() {
    ProjectsService.removeFromParent($scope.item).then(()=>{
      EntityService.recycle('projects', $scope.item._id).then(function() {
        let clonedEntity = JSON.parse(JSON.stringify($scope.item));
        clonedEntity.status = 'Recycled';
        // just for activity status
        ProjectsService.updateStatus(clonedEntity, $scope.item).then(function(result) {
          ActivitiesService.data.push(result);
        });

        refreshList();
        if(currentState.indexOf('search') !== -1) {
          $state.go(currentState, {
            entity: context.entityName,
            entityId: context.entityId
          }, {
            reload: true,
            query: $stateParams.query
          });
        }
        else {
          $state.go('main.projects.all', {
            entity: 'all',
          }, {
            reload: true
          });
        }
      });
    }
    );
  };

  $scope.recycleRestore = function() {
    ProjectsService.addToParent($scope.item).then(()=>{
      EntityService.recycleRestore('projects', $scope.item._id).then(function() {
        let clonedEntity = JSON.parse(JSON.stringify($scope.item));
        clonedEntity.status = 'un-deleted';
        // just for activity status
        ProjectsService.updateStatus(clonedEntity, $scope.item).then(function(result) {
          ActivitiesService.data.push(result);
        });
        refreshList();

        var state = currentState.indexOf('search') !== -1 ? $state.current.name : 'main.projects.all';
        $state.go(state, {
          entity: context.entityName,
          entityId: context.entityId
        }, {
          reload: true
        });
      });
    }
    );
  };

  $scope.createWebhook = function() {
    if(!$scope.me || !$scope.me.uid) return;
    var url = location.origin + '/api/hook';
    url = url + '?entity=task&uid=' + $scope.me.uid + '&project=' + $scope.item._id;
    alert(url);
  };

  $scope.menuItems = [
    {
      label: 'recycleProject',
      fa: 'fa-times-circle',
      display: !$scope.item.hasOwnProperty('recycled'),
      action: $scope.recycle
    }, {
      label: 'unrecycleProject',
      fa: 'fa-times-circle',
      display: $scope.item.hasOwnProperty('recycled'),
      action: $scope.recycleRestore,
    }, {
      label: 'createWebhook',
      fa: 'fa-plus-circle',
      display: true,
      action: $scope.createWebhook,
    }
  ];

  // ==================================================== $watch: title / desc ==================================================== //

  $scope.$watch('item.title', function(nVal, oVal) {
    if(nVal !== oVal && oVal) {
      var newContext = {
        name: 'title',
        oldVal: oVal,
        newVal: nVal,
        action: 'renamed'
      };
      $scope.delayedUpdate($scope.item, newContext);
      ProjectsService.currentProjectName = $scope.item.title;
    }
  });

  var nText, oText;
  $scope.$watch('item.description', function(nVal, oVal) {
    nText = nVal ? nVal.replace(/<(?:.|\n)*?>/gm, '') : '';
    oText = oVal ? oVal.replace(/<(?:.|\n)*?>/gm, '') : '';
    if(nText != oText && oText) {
      var newContext = {
        name: 'description',
        oldVal: oVal,
        newVal: nVal,
        action: 'renamed'
      };
      $scope.delayedUpdate($scope.item, newContext);
    }
  });

  // ==================================================== Update  ==================================================== //

  $scope.updateAndNotify = function(project) {
    project.status = $scope.statuses[1];

    if(context.entityName === 'discussion') {
      project.discussion = context.entityId;
    }

    if(project.assign === undefined || project.assign === null) {
      delete project['assign'];
    }
    else {
      // check the assignee is not a watcher already
      let filtered = project.watchers.filter(watcher=>{
        return watcher._id == project.assign;
      }
      );

      // add assignee as watcher
      if(filtered.length == 0) {
        project.watchers.push(project.assign);
      }
    }

    ProjectsService.update(project).then(function(result) {
      if(context.entityName === 'project') {
        var projId = result.project ? result.project._id : undefined;
        if(projId !== context.entityId) {
          $state.go('main.projects.byentity', {
            entity: context.entityName,
            entityId: context.entityId
          }, {
            reload: true
          });
        }
      }

      ProjectsService.assign(project, me, backupEntity).then(function(res) {
        backupEntity = JSON.parse(JSON.stringify(result));
        ActivitiesService.data.push(res);
      });
    });

  };

  function refreshList() {
    $rootScope.$broadcast('refreshList');
  }

  $scope.update = function(item, type) {
    if(type.name === 'color') {
      item.color = type.newVal;
    }
    ProjectsService.update(item, context).then(function(res) {
      if(ProjectsService.selected && res._id === ProjectsService.selected._id) {
        if(type === 'title') {
          ProjectsService.selected.title = res.title;
        }
      }
      switch (type) {
      case 'status':
        if(context.entityName === 'discussion') {
          item.discussion = context.entityId;
        }

        ProjectsService.updateStatus(item, backupEntity).then(function(result) {
          backupEntity = JSON.parse(JSON.stringify($scope.item));
          ActivitiesService.data = ActivitiesService.data || [];
          ActivitiesService.data.push(result);
        });
        break;

      case 'color':
        ProjectsService.updateColor(item).then(function(result) {
          backupEntity = JSON.parse(JSON.stringify($scope.item));
          ActivitiesService.data = ActivitiesService.data || [];
          ActivitiesService.data.push(result);
        });
        break;
      case 'title':
      case 'description':
        ProjectsService.updateTitle(item, backupEntity, type).then(function(result) {
          backupEntity = JSON.parse(JSON.stringify($scope.item));
          ActivitiesService.data = ActivitiesService.data || [];
          ActivitiesService.data.push(result);
          refreshList();
        });
        break;
      }
    });
  };

  $scope.delayedUpdate = _.debounce($scope.update, 2000);

  // ==================================================== Buttons ==================================================== //

  $scope.updateStatusForApproval = function() {
    let context = {
      action: 'updated',
      name: 'status',
      type: 'project'
    };
    $scope.item.status = 'waiting-approval';
    $scope.update(entity, context);
  };

  // ==================================================== Template ==================================================== //

  $scope.saveTemplate = function(newTemplate) {
    return ProjectsService.saveTemplate($stateParams.id, newTemplate);
  };

  $scope.deleteTemplate = function(id) {
    return ProjectsService.deleteTemplate(id);
  };

  $scope.implementTemplate = function(id) {
    return ProjectsService.template2subProjects(id, {
      projectId: $stateParams.id
    }).then(function(result) {
      for(var i = result.length - 1; i >= 0; i--) {
        result[i].isNew = true;
      }
      $timeout(function() {
        for(var i = result.length - 1; i >= 0; i--) {
          result[i].isNew = false;
        }
      }, 5000);
      var tmp = $scope.item.subProjects.pop();
      $scope.item.subProjects = $scope.item.subProjects.concat(result);
      $scope.item.subProjects.push(tmp);
    });
  };
  // ==================================================== havePermissions ==================================================== //

  $scope.enableRecycled = true;
  $scope.isRecycled = $scope.item.hasOwnProperty('recycled');

  $scope.permsToSee = function() {
    return PermissionsService.haveAnyPerms($scope.item);
  };

  $scope.havePermissions = function(type, enableRecycled) {
    enableRecycled = enableRecycled || !$scope.isRecycled;
    return PermissionsService.havePermissions($scope.item, type) && enableRecycled;
  };

  $scope.haveEditiorsPermissions = function() {
    return PermissionsService.haveEditorsPerms($scope.item);
  };

}
<commit_msg>change menu items order<commit_after>'use strict';

angular.module('mean.icu.ui.projectdetails', []).controller('ProjectDetailsController', ProjectDetailsController);

function ProjectDetailsController($scope, $rootScope, entity, people, tasks, projects, tags, $timeout, context, $state, ProjectsService, ActivitiesService, PermissionsService, EntityService, $stateParams, me, $window) {

  // ==================================================== init ==================================================== //

  if($state.$current.url.source.includes('search') || $state.$current.url.source.includes('projects')) {
    $scope.item = entity || context.entity;
  }
  else {
    $scope.item = context.entity || entity;
  }

  if(!$scope.item) {
    $state.go('main.projects.byentity', {
      entity: context.entityName,
      entityId: context.entityId
    });
  }
  else if($scope.item && ($state.current.name === 'main.projects.all.details' || $state.current.name === 'main.search.project' || $state.current.name === 'main.projects.byentity.details')) {
    $state.go('.activities');
  }

  $scope.items = projects.data || projects;

  $scope.editorOptions = {
    theme: 'bootstrap',
    buttons: ['bold', 'italic', 'underline', 'anchor', 'quote', 'orderedlist', 'unorderedlist']
  };
  $scope.statuses = ['new', 'assigned', 'in-progress', 'canceled', 'completed', 'archived'];

  $scope.me = me;
  $scope.tags = tags;

  let currentState = $state.current.name;

  // backup for previous changes - for updates
  var backupEntity = JSON.parse(JSON.stringify($scope.item));

  $scope.people = people.data || people;
  if($scope.people && $scope.people[Object.keys($scope.people).length - 1].name !== 'no select') {
    var newPeople = {
      name: 'no select'
    };
    $scope.people.push(_(newPeople).clone());
  }
  for(var i = 0; i < $scope.people.length; i++) {
    if($scope.people[i] && ($scope.people[i].job == undefined || $scope.people[i].job == null)) {
      $scope.people[i].job = $scope.people[i].name;
    }
  }

  ProjectsService.getStarred().then(function(starred) {
    $scope.item.star = _(starred).any(function(s) {
      return s._id === $scope.item._id;
    });
  });

  // ==================================================== onChanges ==================================================== //

  function navigateToDetails(project) {
    $scope.detailsState = context.entityName === 'all' ? 'main.projects.all.details' : 'main.projects.byentity.details';

    $state.go($scope.detailsState, {
      id: project._id,
      entity: context.entityName,
      entityId: context.entityId,
      starred: $stateParams.starred
    }, {
      reload: true
    });
  }

  $scope.onStar = function(value) {
    ProjectsService.star($scope.item).then(function() {
    navigateToDetails($scope.item);
    // "$scope.item.star" will be change in 'ProjectsService.star' function
    });
  };

  $scope.onAssign = function(value) {
    $scope.item.assign = value;
    $scope.updateAndNotify($scope.item);
  };

  $scope.onDateDue = function(value) {
    $scope.item.due = value;
    if(context.entityName === 'discussion') {
      $scope.item.discussion = context.entityId;
    }

    ProjectsService.updateDue($scope.item, backupEntity).then(function (result) {
      backupEntity = JSON.parse(JSON.stringify($scope.item));
      ActivitiesService.data.push(result);
    });

    ProjectsService.update($scope.item).then(function(result) {
      if(context.entityName === 'project') {
        var projId = result.project ? result.project._id : undefined;
        if(projId !== context.entityId) {
          $state.go('main.projects.byentity', {
            entity: context.entityName,
            entityId: context.entityId
          }, {
            reload: true
          });
        }
      }
    });
  };

  $scope.onStatus = function(value) {
    $scope.item.status = value;
    $scope.update($scope.item, {
      name: 'status'
    });
  };

  $scope.onColor = function(value) {
    $scope.update($scope.item, value);
  };

  $scope.onWantToCreateRoom = function() {
    $scope.item.WantRoom = true;
    $scope.update($scope.item, context);

    ProjectsService.WantToCreateRoom($scope.item).then(function(data) {
      navigateToDetails($scope.item);
      if(data.roomName) {
        $window.open(window.config.rocketChat.uri + '/group/', data.roomName);
        return true;
      }
      else {
        return false;
      }
    });
  };

  $scope.onTags = function(value) {
    $scope.item.tags = value;
    $scope.update($scope.item, {name: 'tag'});
  };

  // ==================================================== Menu events ==================================================== //

  $scope.recycle = function() {
    ProjectsService.removeFromParent($scope.item).then(()=>{
      EntityService.recycle('projects', $scope.item._id).then(function() {
        let clonedEntity = JSON.parse(JSON.stringify($scope.item));
        clonedEntity.status = 'Recycled';
        // just for activity status
        ProjectsService.updateStatus(clonedEntity, $scope.item).then(function(result) {
          ActivitiesService.data.push(result);
        });

        refreshList();
        if(currentState.indexOf('search') !== -1) {
          $state.go(currentState, {
            entity: context.entityName,
            entityId: context.entityId
          }, {
            reload: true,
            query: $stateParams.query
          });
        }
        else {
          $state.go('main.projects.all', {
            entity: 'all',
          }, {
            reload: true
          });
        }
      });
    }
    );
  };

  $scope.recycleRestore = function() {
    ProjectsService.addToParent($scope.item).then(()=>{
      EntityService.recycleRestore('projects', $scope.item._id).then(function() {
        let clonedEntity = JSON.parse(JSON.stringify($scope.item));
        clonedEntity.status = 'un-deleted';
        // just for activity status
        ProjectsService.updateStatus(clonedEntity, $scope.item).then(function(result) {
          ActivitiesService.data.push(result);
        });
        refreshList();

        var state = currentState.indexOf('search') !== -1 ? $state.current.name : 'main.projects.all';
        $state.go(state, {
          entity: context.entityName,
          entityId: context.entityId
        }, {
          reload: true
        });
      });
    }
    );
  };

  $scope.createWebhook = function() {
    if(!$scope.me || !$scope.me.uid) return;
    var url = location.origin + '/api/hook';
    url = url + '?entity=task&uid=' + $scope.me.uid + '&project=' + $scope.item._id;
    alert(url);
  };

  $scope.menuItems = [
    {
      label: 'createWebhook',
      fa: 'fa-plus-circle',
      display: true,
      action: $scope.createWebhook,
    }, {
      label: 'recycleProject',
      fa: 'fa-times-circle',
      display: !$scope.item.hasOwnProperty('recycled'),
      action: $scope.recycle
    }, {
      label: 'unrecycleProject',
      fa: 'fa-times-circle',
      display: $scope.item.hasOwnProperty('recycled'),
      action: $scope.recycleRestore,
    }
  ];

  // ==================================================== $watch: title / desc ==================================================== //

  $scope.$watch('item.title', function(nVal, oVal) {
    if(nVal !== oVal && oVal) {
      var newContext = {
        name: 'title',
        oldVal: oVal,
        newVal: nVal,
        action: 'renamed'
      };
      $scope.delayedUpdate($scope.item, newContext);
      ProjectsService.currentProjectName = $scope.item.title;
    }
  });

  var nText, oText;
  $scope.$watch('item.description', function(nVal, oVal) {
    nText = nVal ? nVal.replace(/<(?:.|\n)*?>/gm, '') : '';
    oText = oVal ? oVal.replace(/<(?:.|\n)*?>/gm, '') : '';
    if(nText != oText && oText) {
      var newContext = {
        name: 'description',
        oldVal: oVal,
        newVal: nVal,
        action: 'renamed'
      };
      $scope.delayedUpdate($scope.item, newContext);
    }
  });

  // ==================================================== Update  ==================================================== //

  $scope.updateAndNotify = function(project) {
    project.status = $scope.statuses[1];

    if(context.entityName === 'discussion') {
      project.discussion = context.entityId;
    }

    if(project.assign === undefined || project.assign === null) {
      delete project['assign'];
    }
    else {
      // check the assignee is not a watcher already
      let filtered = project.watchers.filter(watcher=>{
        return watcher._id == project.assign;
      }
      );

      // add assignee as watcher
      if(filtered.length == 0) {
        project.watchers.push(project.assign);
      }
    }

    ProjectsService.update(project).then(function(result) {
      if(context.entityName === 'project') {
        var projId = result.project ? result.project._id : undefined;
        if(projId !== context.entityId) {
          $state.go('main.projects.byentity', {
            entity: context.entityName,
            entityId: context.entityId
          }, {
            reload: true
          });
        }
      }

      ProjectsService.assign(project, me, backupEntity).then(function(res) {
        backupEntity = JSON.parse(JSON.stringify(result));
        ActivitiesService.data.push(res);
      });
    });

  };

  function refreshList() {
    $rootScope.$broadcast('refreshList');
  }

  $scope.update = function(item, type) {
    if(type.name === 'color') {
      item.color = type.newVal;
    }
    ProjectsService.update(item, context).then(function(res) {
      if(ProjectsService.selected && res._id === ProjectsService.selected._id) {
        if(type === 'title') {
          ProjectsService.selected.title = res.title;
        }
      }
      switch (type) {
      case 'status':
        if(context.entityName === 'discussion') {
          item.discussion = context.entityId;
        }

        ProjectsService.updateStatus(item, backupEntity).then(function(result) {
          backupEntity = JSON.parse(JSON.stringify($scope.item));
          ActivitiesService.data = ActivitiesService.data || [];
          ActivitiesService.data.push(result);
        });
        break;

      case 'color':
        ProjectsService.updateColor(item).then(function(result) {
          backupEntity = JSON.parse(JSON.stringify($scope.item));
          ActivitiesService.data = ActivitiesService.data || [];
          ActivitiesService.data.push(result);
        });
        break;
      case 'title':
      case 'description':
        ProjectsService.updateTitle(item, backupEntity, type).then(function(result) {
          backupEntity = JSON.parse(JSON.stringify($scope.item));
          ActivitiesService.data = ActivitiesService.data || [];
          ActivitiesService.data.push(result);
          refreshList();
        });
        break;
      }
    });
  };

  $scope.delayedUpdate = _.debounce($scope.update, 2000);

  // ==================================================== Buttons ==================================================== //

  $scope.updateStatusForApproval = function() {
    let context = {
      action: 'updated',
      name: 'status',
      type: 'project'
    };
    $scope.item.status = 'waiting-approval';
    $scope.update(entity, context);
  };

  // ==================================================== Template ==================================================== //

  $scope.saveTemplate = function(newTemplate) {
    return ProjectsService.saveTemplate($stateParams.id, newTemplate);
  };

  $scope.deleteTemplate = function(id) {
    return ProjectsService.deleteTemplate(id);
  };

  $scope.implementTemplate = function(id) {
    return ProjectsService.template2subProjects(id, {
      projectId: $stateParams.id
    }).then(function(result) {
      for(var i = result.length - 1; i >= 0; i--) {
        result[i].isNew = true;
      }
      $timeout(function() {
        for(var i = result.length - 1; i >= 0; i--) {
          result[i].isNew = false;
        }
      }, 5000);
      var tmp = $scope.item.subProjects.pop();
      $scope.item.subProjects = $scope.item.subProjects.concat(result);
      $scope.item.subProjects.push(tmp);
    });
  };
  // ==================================================== havePermissions ==================================================== //

  $scope.enableRecycled = true;
  $scope.isRecycled = $scope.item.hasOwnProperty('recycled');

  $scope.permsToSee = function() {
    return PermissionsService.haveAnyPerms($scope.item);
  };

  $scope.havePermissions = function(type, enableRecycled) {
    enableRecycled = enableRecycled || !$scope.isRecycled;
    return PermissionsService.havePermissions($scope.item, type) && enableRecycled;
  };

  $scope.haveEditiorsPermissions = function() {
    return PermissionsService.haveEditorsPerms($scope.item);
  };

}
<|endoftext|>


<commit_before>var rootDir = process.cwd();
var config = require(rootDir + '/config');
var service = require(rootDir + '/service');
var fs = require('fs');
var dbActions = require(rootDir + '/server/utils/databaseActions');

var userModel = service.useModel('user', 'preload');
var tileModel = service.useModel('tile', 'preload');
var npcModel = service.useModel('npc', 'preload');
var resourceModel = service.useModel('resource','preload');
var gnomeModel = service.useModel('gnome', 'preload');
var gameModel = service.useModel('game', 'preload');

// var nodeEnv;

exports.actions = function(req, res, ss) {

	req.use('session');
	// req.use('debug');
	req.use('account.authenticated');

	return {

		loadData: function(dataType) {

			var userData, tileData, npcData, gnomeData, resourceData, gameData;

			if(req.session.role && req.session.role === 'superadmin') {

				if(dataType === 'users') {
					console.log('\n\n   * * * * * * * * * * * *   Pre-Loading Users   * * * * * * * * * * * *   \n\n'.yellow);
					userData = require(rootDir + '/data/users');
					dbActions.dropCollection('users', function() {
						dbActions.saveDocuments(userModel, userData.global, function() {
							res('Data loaded: ' + dataType);
						});
					});
				} else if(dataType === 'tiles') {
					console.log('\n\n   * * * * * * * * * * * *   Pre-Loading Tiles   * * * * * * * * * * * *   \n\n'.yellow);
					tileData = require(rootDir + '/data/tiles');
					dbActions.dropCollection('tiles', function() {
						var i,
						tileObject = tileData.global,
						backgroundArray = tileObject.backgroundArray,
						background2Array = tileObject.background2Array,
						background3Array = tileObject.background3Array,
						foregroundArray = tileObject.foregroundArray,
						foreground2Array = tileObject.foreground2Array,
						tileStateArray = tileObject.tileStateArray,
						numberOfTiles = backgroundArray.length,
						mapTilesWidth = config.get('MAP_TILES_WIDTH'),
						mapTilesHeight = config.get('MAP_TILES_HEIGHT'),
						mapX,
						mapY,
						tileStateVal,
						tiles = [];

						// dbActions.saveDocuments(tileModel, tileData.global);

						// (re)constructing tile data based on data dump from third party tool
						for(i = 0; i < numberOfTiles; i++) {
							mapX = i % mapTilesWidth;
							mapY = Math.floor(i / mapTilesWidth);

							//add the tile to the array
							//tileState: -1 if nothing (go!), -2 if something (nogo!), the index if it's an NPC
							//checking values are arbitrary right now,
							//based on the image used in tiled map editor

							// 0: this means there was nothing place in tilestate layer, aka GO
							if(tileStateArray[i] === 0) {
								tileStateVal = -1;
							}

							//2: this refers to the BLUE tile, means there is an NPC
							else if(tileStateArray[i] === 2	) {
								tileStateVal = i;
							}
							//3: this is the pink? tile, it is the gnome
							else if(tileStateArray[i] === 3) {
								tileStateVal = 99999;
							}
							//3: this means there was something OTHER than the blue tile place, NOGO
							else {
								tileStateVal = -2;
							}
							tiles.push({
								x: mapX,
								y: mapY,
								tileState: tileStateVal,
								isMapEdge: (mapX === 0 || mapY === 0 || mapX === mapTilesWidth - 1 || mapY === mapTilesHeight - 1) ? true : false,
								background: backgroundArray[i],
								background2: background2Array[i],
								background3: background3Array[i],
								foreground: foregroundArray[i],
								foreground2: foreground2Array[i],
								mapIndex: i
							});

						}
						dbActions.saveDocuments(tileModel, tiles, numberOfTiles, function() {
							res('Data loaded: ' + numberOfTiles + ' ' + dataType);
						});
					});
				} else if(dataType === 'npcs') {
					console.log('\n\n   * * * * * * * * * * * *   Pre-Loading NPCs and Gnome   * * * * * * * * * * * *   \n\n'.yellow);
					npcData = require(rootDir + '/data/npcs');
					gnomeData = require(rootDir + '/data/gnome');

					dbActions.dropCollection('npcs', function() {
						dbActions.saveDocuments(npcModel, npcData.global, function() {
							dbActions.dropCollection('gnomes', function() {
								dbActions.saveDocuments(gnomeModel, gnomeData.global, function() {
									res('Data loaded: ' + dataType);
								});
							});
						});
					});
				} else if(dataType === 'game') {
					console.log('\n\n   * * * * * * * * * * * *   Pre-Loading Game   * * * * * * * * * * * *   \n\n'.yellow);
					gameData = require(rootDir + '/data/game');
					dbActions.dropCollection('game', function() {
						dbActions.saveDocuments(gameModel, gameData.global, function() {
							res('Data loaded: ' + dataType);
						});
					});
				} else if(dataType === 'resources') {
					console.log('\n\n   * * * * * * * * * * * *   Pre-Loading Resources   * * * * * * * * * * * *   \n\n'.yellow);
					resourceData = require(rootDir + '/data/resources');
					dbActions.dropCollection('resources', function() {
						dbActions.saveDocuments(resourceModel, resourceData.global, function() {
							res('Data loaded: ' + dataType);
						});
					});
				}
			}
		}

	};

}<commit_msg>Fixed bug w/ tile loading.<commit_after>var rootDir = process.cwd();
var config = require(rootDir + '/config');
var service = require(rootDir + '/service');
var fs = require('fs');
var dbActions = require(rootDir + '/server/utils/databaseActions');

var userModel = service.useModel('user', 'preload');
var tileModel = service.useModel('tile', 'preload');
var npcModel = service.useModel('npc', 'preload');
var resourceModel = service.useModel('resource','preload');
var gnomeModel = service.useModel('gnome', 'preload');
var gameModel = service.useModel('game', 'preload');

// var nodeEnv;

exports.actions = function(req, res, ss) {

	req.use('session');
	// req.use('debug');
	req.use('account.authenticated');

	return {

		loadData: function(dataType) {

			var userData, tileData, npcData, gnomeData, resourceData, gameData;

			if(req.session.role && req.session.role === 'superadmin') {

				if(dataType === 'users') {
					console.log('\n\n   * * * * * * * * * * * *   Pre-Loading Users   * * * * * * * * * * * *   \n\n'.yellow);
					userData = require(rootDir + '/data/users');
					dbActions.dropCollection('users', function() {
						dbActions.saveDocuments(userModel, userData.global, function() {
							res('Data loaded: ' + dataType);
						});
					});
				} else if(dataType === 'tiles') {
					console.log('\n\n   * * * * * * * * * * * *   Pre-Loading Tiles   * * * * * * * * * * * *   \n\n'.yellow);
					tileData = require(rootDir + '/data/tiles');
					dbActions.dropCollection('tiles', function() {
						var i,
						tileObject = tileData.global,
						backgroundArray = tileObject.backgroundArray,
						background2Array = tileObject.background2Array,
						background3Array = tileObject.background3Array,
						foregroundArray = tileObject.foregroundArray,
						foreground2Array = tileObject.foreground2Array,
						tileStateArray = tileObject.tileStateArray,
						numberOfTiles = backgroundArray.length,
						mapTilesWidth = 142,
						mapTilesHeight = 132,
						mapX,
						mapY,
						tileStateVal,
						tiles = [];

						// dbActions.saveDocuments(tileModel, tileData.global);

						// (re)constructing tile data based on data dump from third party tool
						for(i = 0; i < numberOfTiles; i++) {
							mapX = i % mapTilesWidth;
							mapY = Math.floor(i / mapTilesWidth);

							//add the tile to the array
							//tileState: -1 if nothing (go!), -2 if something (nogo!), the index if it's an NPC
							//checking values are arbitrary right now,
							//based on the image used in tiled map editor

							// 0: this means there was nothing place in tilestate layer, aka GO
							if(tileStateArray[i] === 0) {
								tileStateVal = -1;
							}

							//2: this refers to the BLUE tile, means there is an NPC
							else if(tileStateArray[i] === 2	) {
								tileStateVal = i;
							}
							//3: this is the pink? tile, it is the gnome
							else if(tileStateArray[i] === 3) {
								tileStateVal = 99999;
							}
							//3: this means there was something OTHER than the blue tile place, NOGO
							else {
								tileStateVal = -2;
							}
							tiles.push({
								x: mapX,
								y: mapY,
								tileState: tileStateVal,
								isMapEdge: (mapX === 0 || mapY === 0 || mapX === mapTilesWidth - 1 || mapY === mapTilesHeight - 1) ? true : false,
								background: backgroundArray[i],
								background2: background2Array[i],
								background3: background3Array[i],
								foreground: foregroundArray[i],
								foreground2: foreground2Array[i],
								mapIndex: i
							});

						}
						dbActions.saveDocuments(tileModel, tiles, numberOfTiles, function() {
							res('Data loaded: ' + numberOfTiles + ' ' + dataType);
						});
					});
				} else if(dataType === 'npcs') {
					console.log('\n\n   * * * * * * * * * * * *   Pre-Loading NPCs and Gnome   * * * * * * * * * * * *   \n\n'.yellow);
					npcData = require(rootDir + '/data/npcs');
					gnomeData = require(rootDir + '/data/gnome');

					dbActions.dropCollection('npcs', function() {
						dbActions.saveDocuments(npcModel, npcData.global, function() {
							dbActions.dropCollection('gnomes', function() {
								dbActions.saveDocuments(gnomeModel, gnomeData.global, function() {
									res('Data loaded: ' + dataType);
								});
							});
						});
					});
				} else if(dataType === 'game') {
					console.log('\n\n   * * * * * * * * * * * *   Pre-Loading Game   * * * * * * * * * * * *   \n\n'.yellow);
					gameData = require(rootDir + '/data/game');
					dbActions.dropCollection('game', function() {
						dbActions.saveDocuments(gameModel, gameData.global, function() {
							res('Data loaded: ' + dataType);
						});
					});
				} else if(dataType === 'resources') {
					console.log('\n\n   * * * * * * * * * * * *   Pre-Loading Resources   * * * * * * * * * * * *   \n\n'.yellow);
					resourceData = require(rootDir + '/data/resources');
					dbActions.dropCollection('resources', function() {
						dbActions.saveDocuments(resourceModel, resourceData.global, function() {
							res('Data loaded: ' + dataType);
						});
					});
				}
			}
		}

	};

}<|endoftext|>


<commit_before>// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

import generate from "project-name-generator";
import { CommandsArray } from "../models/Command";
import UiState from "./view/UiState";

export default function seed(store, numberOfSuites = 5) {
  function generateSuite() {
    return store.createSuite(generate({ words: 2 }).spaced);
  }
  function generateTestCase() {
    return store.createTestCase(generate({ words: 2 }).spaced);
  }
  const targets = ["a", "button"];
  function generateCommand(test) {
    const command = test.createCommand();
    command.setCommand(CommandsArray[Math.floor(Math.random() * CommandsArray.length)]);
    let targetChance = Math.floor(Math.random() * 10);
    command.setTarget(targetChance < targets.length ? targets[targetChance] : "");
    command.setValue(Math.floor(Math.random() * 2) ? generate({ words: 1 }).spaced : "");
    return command;
  }
  function randomBetween(min, max) {
    return (Math.floor(Math.random() * (max - min)) + min);
  }
  for (let i = 0; i < numberOfSuites; i++) {
    let suite = generateSuite();
    for (let j = 0; j < randomBetween(3, 6); j++) {
      const testCase = generateTestCase();
      for (let k = 0; k < randomBetween(9, 16); k++) {
        generateCommand(testCase);
      }
      suite.addTestCase(testCase);
    }
  }

  const url = "https://en.wikipedia.org";
  store.setUrl(url);
  store.addUrl(url);
  const playbackTest = store.createTestCase("aa playback");
  const open = playbackTest.createCommand();
  open.setComment("Open the wikipedia Legislation article");
  open.setCommand("open");
  open.setTarget("/wiki/Legislation");
  const firstClick = playbackTest.createCommand();
  firstClick.setCommand("click");
  firstClick.setTarget("link=enacted");
  firstClick.setTargets([
    ["//div[@id='mw-content-text']/div/p[7]", "xpath:idRelative"]
  ]);
  const secondClick = playbackTest.createCommand();
  secondClick.setCommand("clickAt");
  secondClick.setTarget("link=parliamentary systems");

  const playbackTest2 = store.createTestCase("aab playback");
  const open2 = playbackTest2.createCommand();
  open2.setCommand("open");
  open2.setTarget("/wiki/River_Chater");
  const firstClick2 = playbackTest2.createCommand();
  firstClick2.setCommand("clickAt");
  firstClick2.setTarget("link=River Welland");
  const secondClick2 = playbackTest2.createCommand();
  secondClick2.setCommand("clickAt");
  secondClick2.setTarget("link=floods of 1947");
  const thirdClick2 = playbackTest2.createCommand();
  thirdClick2.setCommand("clickAt");
  thirdClick2.setTarget("link=scapegoat");

  const controlFlowIfTest = store.createTestCase("control flow if");
  controlFlowIfTest.createCommand(undefined, "open", "/wiki/River_Chater");
  controlFlowIfTest.createCommand(undefined, "if", "true");
  controlFlowIfTest.createCommand(undefined, "echo", "foo");
  controlFlowIfTest.createCommand(undefined, "else if", "true");
  controlFlowIfTest.createCommand(undefined, "echo", "bar");
  controlFlowIfTest.createCommand(undefined, "else");
  controlFlowIfTest.createCommand(undefined, "echo", "baz");
  controlFlowIfTest.createCommand(undefined, "end");

  const controlFlowDoTest = store.createTestCase("control flow do");
  controlFlowDoTest.createCommand(undefined, "open", "/wiki/River_Chater");
  controlFlowDoTest.createCommand(undefined, "do");
  controlFlowDoTest.createCommand(undefined, "echo", "foo");
  controlFlowDoTest.createCommand(undefined, "repeat if", "true", "2");

  const controlFlowTimesTest = store.createTestCase("control flow times");
  controlFlowTimesTest.createCommand(undefined, "open", "/wiki/River_Chater");
  controlFlowTimesTest.createCommand(undefined, "times", "2");
  controlFlowTimesTest.createCommand(undefined, "echo", "foo");
  controlFlowTimesTest.createCommand(undefined, "end");

  const controlFlowWhileTest = store.createTestCase("control flow while");
  controlFlowWhileTest.createCommand(undefined, "open", "/wiki/River_Chater");
  controlFlowWhileTest.createCommand(undefined, "while", "true", "2");
  controlFlowWhileTest.createCommand(undefined, "echo", "foo");
  controlFlowWhileTest.createCommand(undefined, "end");

  const typeTest = store.createTestCase("aab type");
  const open3 = typeTest.createCommand();
  open3.setCommand("open");
  open3.setTarget("/wiki/Main_Page");
  const clickSearch = typeTest.createCommand();
  clickSearch.setCommand("clickAt");
  clickSearch.setTarget("id=searchInput");
  const type = typeTest.createCommand();
  type.setCommand("type");
  type.setTarget("id=searchInput");
  type.setValue("Selenium IDE");

  const submit = typeTest.createCommand();
  submit.setCommand("clickAt");
  submit.setTarget("css=.mw-searchSuggest-link:first-child");

  const suite = store.createSuite("aaa suite");
  suite.addTestCase(playbackTest);

  const suite2 = store.createSuite("aaab suite");
  suite2.addTestCase(typeTest);
  suite2.addTestCase(playbackTest2);

  const suiteControlFlow = store.createSuite("control flow");
  suiteControlFlow.addTestCase(controlFlowIfTest);
  suiteControlFlow.addTestCase(controlFlowDoTest);
  suiteControlFlow.addTestCase(controlFlowTimesTest);
  suiteControlFlow.addTestCase(controlFlowWhileTest);

  UiState.selectTest(playbackTest);

  store.changeName("project");

  return store;
}
<commit_msg>Added a suite for all seed tests to make it a little easier to run them all.<commit_after>// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

import generate from "project-name-generator";
import { CommandsArray } from "../models/Command";
import UiState from "./view/UiState";

export default function seed(store, numberOfSuites = 5) {
  function generateSuite() {
    return store.createSuite(generate({ words: 2 }).spaced);
  }
  function generateTestCase() {
    return store.createTestCase(generate({ words: 2 }).spaced);
  }
  const targets = ["a", "button"];
  function generateCommand(test) {
    const command = test.createCommand();
    command.setCommand(CommandsArray[Math.floor(Math.random() * CommandsArray.length)]);
    let targetChance = Math.floor(Math.random() * 10);
    command.setTarget(targetChance < targets.length ? targets[targetChance] : "");
    command.setValue(Math.floor(Math.random() * 2) ? generate({ words: 1 }).spaced : "");
    return command;
  }
  function randomBetween(min, max) {
    return (Math.floor(Math.random() * (max - min)) + min);
  }
  for (let i = 0; i < numberOfSuites; i++) {
    let suite = generateSuite();
    for (let j = 0; j < randomBetween(3, 6); j++) {
      const testCase = generateTestCase();
      for (let k = 0; k < randomBetween(9, 16); k++) {
        generateCommand(testCase);
      }
      suite.addTestCase(testCase);
    }
  }

  const url = "https://en.wikipedia.org";
  store.setUrl(url);
  store.addUrl(url);
  const playbackTest = store.createTestCase("aa playback");
  const open = playbackTest.createCommand();
  open.setComment("Open the wikipedia Legislation article");
  open.setCommand("open");
  open.setTarget("/wiki/Legislation");
  const firstClick = playbackTest.createCommand();
  firstClick.setCommand("click");
  firstClick.setTarget("link=enacted");
  firstClick.setTargets([
    ["//div[@id='mw-content-text']/div/p[7]", "xpath:idRelative"]
  ]);
  const secondClick = playbackTest.createCommand();
  secondClick.setCommand("clickAt");
  secondClick.setTarget("link=parliamentary systems");

  const playbackTest2 = store.createTestCase("aab playback");
  const open2 = playbackTest2.createCommand();
  open2.setCommand("open");
  open2.setTarget("/wiki/River_Chater");
  const firstClick2 = playbackTest2.createCommand();
  firstClick2.setCommand("clickAt");
  firstClick2.setTarget("link=River Welland");
  const secondClick2 = playbackTest2.createCommand();
  secondClick2.setCommand("clickAt");
  secondClick2.setTarget("link=floods of 1947");
  const thirdClick2 = playbackTest2.createCommand();
  thirdClick2.setCommand("clickAt");
  thirdClick2.setTarget("link=scapegoat");

  const controlFlowIfTest = store.createTestCase("control flow if");
  controlFlowIfTest.createCommand(undefined, "open", "/wiki/River_Chater");
  controlFlowIfTest.createCommand(undefined, "if", "true");
  controlFlowIfTest.createCommand(undefined, "echo", "foo");
  controlFlowIfTest.createCommand(undefined, "else if", "true");
  controlFlowIfTest.createCommand(undefined, "echo", "bar");
  controlFlowIfTest.createCommand(undefined, "else");
  controlFlowIfTest.createCommand(undefined, "echo", "baz");
  controlFlowIfTest.createCommand(undefined, "end");

  const controlFlowElseIfTest = store.createTestCase("control flow else if");
  controlFlowElseIfTest.createCommand(undefined, "open", "/wiki/River_Chater");
  controlFlowElseIfTest.createCommand(undefined, "if", "false");
  controlFlowElseIfTest.createCommand(undefined, "echo", "foo");
  controlFlowElseIfTest.createCommand(undefined, "else if", "true");
  controlFlowElseIfTest.createCommand(undefined, "echo", "bar");
  controlFlowElseIfTest.createCommand(undefined, "else");
  controlFlowElseIfTest.createCommand(undefined, "echo", "baz");
  controlFlowElseIfTest.createCommand(undefined, "end");

  const controlFlowElseTest = store.createTestCase("control flow else");
  controlFlowElseTest.createCommand(undefined, "open", "/wiki/River_Chater");
  controlFlowElseTest.createCommand(undefined, "if", "false");
  controlFlowElseTest.createCommand(undefined, "echo", "foo");
  controlFlowElseTest.createCommand(undefined, "else if", "false");
  controlFlowElseTest.createCommand(undefined, "echo", "bar");
  controlFlowElseTest.createCommand(undefined, "else");
  controlFlowElseTest.createCommand(undefined, "echo", "baz");
  controlFlowElseTest.createCommand(undefined, "end");

  const controlFlowDoTest = store.createTestCase("control flow do");
  controlFlowDoTest.createCommand(undefined, "open", "/wiki/River_Chater");
  controlFlowDoTest.createCommand(undefined, "do");
  controlFlowDoTest.createCommand(undefined, "echo", "foo");
  controlFlowDoTest.createCommand(undefined, "repeat if", "true", "2");

  const controlFlowTimesTest = store.createTestCase("control flow times");
  controlFlowTimesTest.createCommand(undefined, "open", "/wiki/River_Chater");
  controlFlowTimesTest.createCommand(undefined, "times", "2");
  controlFlowTimesTest.createCommand(undefined, "echo", "foo");
  controlFlowTimesTest.createCommand(undefined, "end");

  const controlFlowWhileTest = store.createTestCase("control flow while");
  controlFlowWhileTest.createCommand(undefined, "open", "/wiki/River_Chater");
  controlFlowWhileTest.createCommand(undefined, "while", "true", "2");
  controlFlowWhileTest.createCommand(undefined, "echo", "foo");
  controlFlowWhileTest.createCommand(undefined, "end");

  const typeTest = store.createTestCase("aab type");
  const open3 = typeTest.createCommand();
  open3.setCommand("open");
  open3.setTarget("/wiki/Main_Page");
  const clickSearch = typeTest.createCommand();
  clickSearch.setCommand("clickAt");
  clickSearch.setTarget("id=searchInput");
  const type = typeTest.createCommand();
  type.setCommand("type");
  type.setTarget("id=searchInput");
  type.setValue("Selenium IDE");

  const submit = typeTest.createCommand();
  submit.setCommand("clickAt");
  submit.setTarget("css=.mw-searchSuggest-link:first-child");

  const suite = store.createSuite("aaa suite");
  suite.addTestCase(playbackTest);

  const suite2 = store.createSuite("aaab suite");
  suite2.addTestCase(typeTest);
  suite2.addTestCase(playbackTest2);

  const suiteControlFlow = store.createSuite("control flow");
  suiteControlFlow.addTestCase(controlFlowIfTest);
  suiteControlFlow.addTestCase(controlFlowElseIfTest);
  suiteControlFlow.addTestCase(controlFlowElseTest);
  suiteControlFlow.addTestCase(controlFlowDoTest);
  suiteControlFlow.addTestCase(controlFlowTimesTest);
  suiteControlFlow.addTestCase(controlFlowWhileTest);

  const suiteAll = store.createSuite("_all tests");
  store.tests.forEach(function(test) {
    suiteAll.addTestCase(test);
  });

  UiState.selectTest(playbackTest);

  store.changeName("project");

  return store;
}
<|endoftext|>


<commit_before>'use strict';

angular.module('mean.icu.ui.projectdetails', []).controller('ProjectDetailsController', ProjectDetailsController);

function ProjectDetailsController($scope, $rootScope, entity, people, tasks, projects, tags, $timeout, context, $state, ProjectsService, ActivitiesService, PermissionsService, EntityService, $stateParams, me) {

  // ==================================================== init ==================================================== //

  if (($state.$current.url.source.includes("search")) || ($state.$current.url.source.includes("projects"))) {
    $scope.item = entity || context.entity;
  } else {
    $scope.item = context.entity || entity;
  }

  if (!$scope.item) {
    $state.go('main.projects.byentity', {
      entity: context.entityName,
      entityId: context.entityId
    });
  } else if ($scope.item && ($state.current.name === 'main.projects.all.details' || $state.current.name === 'main.search.project' || $state.current.name === 'main.projects.byentity.details')) {
    $state.go('.activities');
  }

  $scope.items = projects.data || projects;

  $scope.editorOptions = {
    theme: 'bootstrap',
    buttons: ['bold', 'italic', 'underline', 'anchor', 'quote', 'orderedlist', 'unorderedlist']
  };
  $scope.statuses = ['new', 'assigned', 'in-progress', 'canceled', 'completed', 'archived'];

  $scope.me = me;
  $scope.tags = tags;

  var currentState = $state.current.name;

  // backup for previous changes - for updates
  var backupEntity = JSON.parse(JSON.stringify($scope.item));

  $scope.people = people.data || people;
  if ($scope.people && $scope.people[Object.keys($scope.people).length - 1].name !== 'no select') {
    var newPeople = {
      name: 'no select'
    };
    $scope.people.push(_(newPeople).clone());
  }
  for (var i = 0; i < $scope.people.length; i++) {
    if ($scope.people[i] && ($scope.people[i].job == undefined || $scope.people[i].job == null)) {
      $scope.people[i].job = $scope.people[i].name;
    }
  }

  ProjectsService.getStarred().then(function(starred) {
    $scope.item.star = _(starred).any(function(s) {
      return s._id === $scope.item._id;
    });
  });

  // ==================================================== onChanges ==================================================== //

  function navigateToDetails(project) {
    $scope.detailsState = context.entityName === 'all' ? 'main.projects.all.details' : 'main.projects.byentity.details';

    $state.go($scope.detailsState, {
      id: project._id,
      entity: context.entityName,
      entityId: context.entityId,
      starred: $stateParams.starred
    }, {
      reload: true
    });
  }

  $scope.onStar = function(value) {
    ProjectsService.star($scope.item).then(function() {
      navigateToDetails($scope.item);
      // "$scope.item.star" will be change in 'ProjectsService.star' function
    });
  }

  $scope.onAssign = function(value) {
    $scope.item.assign = value;
    $scope.updateAndNotify($scope.item);
  }

  $scope.onDateDue = function(value) {
    $scope.item.due = value;
    if (context.entityName === 'discussion') {
      $scope.item.discussion = context.entityId;
    }

    ProjectsService.updateDue($scope.item, backupEntity).then(function(result) {
      backupEntity = JSON.parse(JSON.stringify($scope.item));
      ActivitiesService.data.push(result);
    });

    ProjectsService.update($scope.item).then(function(result) {
      if (context.entityName === 'project') {
        var projId = result.project ? result.project._id : undefined;
        if (projId !== context.entityId) {
          $state.go('main.projects.byentity', {
            entity: context.entityName,
            entityId: context.entityId
          }, {
            reload: true
          });
        }
      }
    });
  }

  $scope.onStatus = function(value) {
    $scope.item.status = value;
    $scope.update($scope.item, {
      name: 'status'
    })
  }

  $scope.onColor = function(value) {
    $scope.update($scope.item, value);
  }

  $scope.onWantToCreateRoom = function() {
    $scope.item.WantRoom = true;

    $scope.update($scope.item, context);

    ProjectsService.WantToCreateRoom($scope.item).then(function() {
      navigateToDetails($scope.item);
    });
  }

  $scope.onTags = function(value) {
    $scope.item.tags = value;
    $scope.update($scope.item);
  }

  // ==================================================== Menu events ==================================================== //

  $scope.recycle = function() {
    ProjectsService.removeFromParent($scope.item).then(()=>{
      EntityService.recycle('projects', $scope.item._id).then(function() {
        let clonedEntity = JSON.parse(JSON.stringify($scope.item));
        clonedEntity.status = "Recycled"
        // just for activity status
        ProjectsService.updateStatus(clonedEntity, $scope.item).then(function(result) {
          ActivitiesService.data.push(result);
        });

        refreshList();
        if (currentState.indexOf('search') !== -1) {
          $state.go(currentState, {
            entity: context.entityName,
            entityId: context.entityId
          }, {
            reload: true,
            query: $stateParams.query
          });
        } else {
          $state.go('main.projects.all', {
            entity: 'all',
          }, {
            reload: true
          });
        }
      });
    }
    )
  }

  $scope.recycleRestore = function() {
    ProjectsService.addToParent($scope.item).then(()=>{
      EntityService.recycleRestore('projects', $scope.item._id).then(function() {
        let clonedEntity = JSON.parse(JSON.stringify($scope.item));
        clonedEntity.status = "un-deleted";
        // just for activity status
        ProjectsService.updateStatus(clonedEntity, $scope.item).then(function(result) {
          ActivitiesService.data.push(result);
        });
        refreshList();

        var state = currentState.indexOf('search') !== -1 ? $state.current.name : 'main.projects.all';
        $state.go(state, {
          entity: context.entityName,
          entityId: context.entityId
        }, {
          reload: true
        });
      });
    }
    )
  }

  $scope.menuItems = [{
      label: 'recycleProject',
      icon: 'times-circle',
      display: !$scope.item.hasOwnProperty('recycled'),
      action: $scope.recycle,
    }, {
      label: 'unrecycleProject',
      icon: 'times-circle',
      display: $scope.item.hasOwnProperty('recycled'),
      action: $scope.recycleRestore,
  }];

  // ==================================================== $watch: title / desc ==================================================== //

  $scope.$watch('item.title', function(nVal, oVal) {
    if (nVal !== oVal && oVal) {
      var newContext = {
        name: 'title',
        oldVal: oVal,
        newVal: nVal,
        action: 'renamed'
      };
      $scope.delayedUpdate($scope.item, newContext);

      ProjectsService.currentProjectName = $scope.item.title;
    }
  });

  var nText, oText;
  $scope.$watch('item.description', function(nVal, oVal) {
    nText = nVal ? nVal.replace(/<(?:.|\n)*?>/gm, '') : '';
    oText = oVal ? oVal.replace(/<(?:.|\n)*?>/gm, '') : '';
    if (nText != oText && oText) {
      var newContext = {
        name: 'description',
        oldVal: oVal,
        newVal: nVal,
        action: 'renamed'
      };
      $scope.delayedUpdate($scope.item, newContext);
    }
  });

  // ==================================================== Update  ==================================================== //

  $scope.updateAndNotify = function(project) {
    project.status = $scope.statuses[1];

    if (context.entityName === 'discussion') {
      project.discussion = context.entityId;
    }

    if (project.assign === undefined || project.assign === null) {
      delete project['assign'];
    } else {
      // check the assignee is not a watcher already
      let filtered = project.watchers.filter(watcher=>{
        return watcher._id == project.assign;
      }
      );

      // add assignee as watcher
      if (filtered.length == 0) {
        project.watchers.push(project.assign);
      }
    }

    ProjectsService.update(project).then(function(result) {
      if (context.entityName === 'project') {
        var projId = result.project ? result.project._id : undefined;
        if (projId !== context.entityId) {
          $state.go('main.projects.byentity', {
            entity: context.entityName,
            entityId: context.entityId
          }, {
            reload: true
          });
        }
      }

      ProjectsService.assign(project, me, backupEntity).then(function(res) {
        backupEntity = JSON.parse(JSON.stringify(result));
        ActivitiesService.data.push(res);
      });
    });

  }

  function refreshList() {
    $rootScope.$broadcast('refreshList');
  }

  $scope.update = function(item, type) {
    if (type === 'color') {
        item.color = context.newVal;
    }
    ProjectsService.update(item, context).then(function(res) {
      if (ProjectsService.selected && res._id === ProjectsService.selected._id) {
        if (type === 'title') {
          ProjectsService.selected.title = res.title;
        }
      }
      switch (type) {
      case 'status':
        if (context.entityName === 'discussion') {
          item.discussion = context.entityId;
        }

        ProjectsService.updateStatus(item, backupEntity).then(function(result) {
          backupEntity = JSON.parse(JSON.stringify($scope.item));
          ActivitiesService.data = ActivitiesService.data || [];
          ActivitiesService.data.push(result);
        });
        break;

      case 'color':
        ProjectsService.updateColor(item).then(function(result) {
          backupEntity = JSON.parse(JSON.stringify($scope.item));
          ActivitiesService.data = ActivitiesService.data || [];
          ActivitiesService.data.push(result);
        });
        break;
      case 'title':
      case 'description':
        ProjectsService.updateTitle(item, backupEntity, type).then(function(result) {
          backupEntity = JSON.parse(JSON.stringify($scope.item));
          ActivitiesService.data = ActivitiesService.data || [];
          ActivitiesService.data.push(result);
          refreshList();
        });
        break;
      }
    });
  }

  $scope.delayedUpdate = _.debounce($scope.update, 2000);

  // ==================================================== Buttons ==================================================== //

  $scope.updateStatusForApproval = function() {
    let context = {
      action: "updated",
      name: "status",
      type: "project"
    }
    $scope.item.status = "waiting-approval";
    $scope.update(entity, context);
  }

  // ==================================================== Template ==================================================== //

  $scope.saveTemplate = function(newTemplate) {
    return ProjectsService.saveTemplate($stateParams.id, newTemplate)
  }

  $scope.deleteTemplate = function(id) {
    return ProjectsService.deleteTemplate(id)
  }

  $scope.implementTemplate = function(id) {
    return ProjectsService.template2subProjects(id, {
        'projectId': $stateParams.id
    }).then(function(result) {
        for (var i = result.length - 1; i >= 0; i--) {
            result[i].isNew = true;
        }
        $timeout(function() {
          for (var i = result.length - 1; i >= 0; i--) {
            result[i].isNew = false;
          }
        }, 5000);
        var tmp = $scope.item.subProjects.pop()
        $scope.item.subProjects = $scope.item.subProjects.concat(result);
        $scope.item.subProjects.push(tmp);
    });
  }
  // ==================================================== havePermissions ==================================================== //

  $scope.enableRecycled = true;
  $scope.isRecycled = $scope.item.hasOwnProperty('recycled');

  $scope.permsToSee = function() {
    return PermissionsService.haveAnyPerms($scope.item);
  }

  $scope.havePermissions = function(type, enableRecycled) {
    enableRecycled = enableRecycled || !$scope.isRecycled;
    return (PermissionsService.havePermissions($scope.item, type) && enableRecycled);
  }

  $scope.haveEditiorsPermissions = function() {
    return PermissionsService.haveEditorsPerms($scope.item);
  }

}
<commit_msg>fixed bug with not saving color<commit_after>'use strict';

angular.module('mean.icu.ui.projectdetails', []).controller('ProjectDetailsController', ProjectDetailsController);

function ProjectDetailsController($scope, $rootScope, entity, people, tasks, projects, tags, $timeout, context, $state, ProjectsService, ActivitiesService, PermissionsService, EntityService, $stateParams, me) {

  // ==================================================== init ==================================================== //

  if (($state.$current.url.source.includes("search")) || ($state.$current.url.source.includes("projects"))) {
    $scope.item = entity || context.entity;
  } else {
    $scope.item = context.entity || entity;
  }

  if (!$scope.item) {
    $state.go('main.projects.byentity', {
      entity: context.entityName,
      entityId: context.entityId
    });
  } else if ($scope.item && ($state.current.name === 'main.projects.all.details' || $state.current.name === 'main.search.project' || $state.current.name === 'main.projects.byentity.details')) {
    $state.go('.activities');
  }

  $scope.items = projects.data || projects;

  $scope.editorOptions = {
    theme: 'bootstrap',
    buttons: ['bold', 'italic', 'underline', 'anchor', 'quote', 'orderedlist', 'unorderedlist']
  };
  $scope.statuses = ['new', 'assigned', 'in-progress', 'canceled', 'completed', 'archived'];

  $scope.me = me;
  $scope.tags = tags;

  var currentState = $state.current.name;

  // backup for previous changes - for updates
  var backupEntity = JSON.parse(JSON.stringify($scope.item));

  $scope.people = people.data || people;
  if ($scope.people && $scope.people[Object.keys($scope.people).length - 1].name !== 'no select') {
    var newPeople = {
      name: 'no select'
    };
    $scope.people.push(_(newPeople).clone());
  }
  for (var i = 0; i < $scope.people.length; i++) {
    if ($scope.people[i] && ($scope.people[i].job == undefined || $scope.people[i].job == null)) {
      $scope.people[i].job = $scope.people[i].name;
    }
  }

  ProjectsService.getStarred().then(function(starred) {
    $scope.item.star = _(starred).any(function(s) {
      return s._id === $scope.item._id;
    });
  });

  // ==================================================== onChanges ==================================================== //

  function navigateToDetails(project) {
    $scope.detailsState = context.entityName === 'all' ? 'main.projects.all.details' : 'main.projects.byentity.details';

    $state.go($scope.detailsState, {
      id: project._id,
      entity: context.entityName,
      entityId: context.entityId,
      starred: $stateParams.starred
    }, {
      reload: true
    });
  }

  $scope.onStar = function(value) {
    ProjectsService.star($scope.item).then(function() {
      navigateToDetails($scope.item);
      // "$scope.item.star" will be change in 'ProjectsService.star' function
    });
  }

  $scope.onAssign = function(value) {
    $scope.item.assign = value;
    $scope.updateAndNotify($scope.item);
  }

  $scope.onDateDue = function(value) {
    $scope.item.due = value;
    if (context.entityName === 'discussion') {
      $scope.item.discussion = context.entityId;
    }

    ProjectsService.updateDue($scope.item, backupEntity).then(function(result) {
      backupEntity = JSON.parse(JSON.stringify($scope.item));
      ActivitiesService.data.push(result);
    });

    ProjectsService.update($scope.item).then(function(result) {
      if (context.entityName === 'project') {
        var projId = result.project ? result.project._id : undefined;
        if (projId !== context.entityId) {
          $state.go('main.projects.byentity', {
            entity: context.entityName,
            entityId: context.entityId
          }, {
            reload: true
          });
        }
      }
    });
  }

  $scope.onStatus = function(value) {
    $scope.item.status = value;
    $scope.update($scope.item, {
      name: 'status'
    })
  }

  $scope.onColor = function(value) {
    $scope.update($scope.item, value);
  }

  $scope.onWantToCreateRoom = function() {
    $scope.item.WantRoom = true;

    $scope.update($scope.item, context);

    ProjectsService.WantToCreateRoom($scope.item).then(function() {
      navigateToDetails($scope.item);
    });
  }

  $scope.onTags = function(value) {
    $scope.item.tags = value;
    $scope.update($scope.item);
  }

  // ==================================================== Menu events ==================================================== //

  $scope.recycle = function() {
    ProjectsService.removeFromParent($scope.item).then(()=>{
      EntityService.recycle('projects', $scope.item._id).then(function() {
        let clonedEntity = JSON.parse(JSON.stringify($scope.item));
        clonedEntity.status = "Recycled"
        // just for activity status
        ProjectsService.updateStatus(clonedEntity, $scope.item).then(function(result) {
          ActivitiesService.data.push(result);
        });

        refreshList();
        if (currentState.indexOf('search') !== -1) {
          $state.go(currentState, {
            entity: context.entityName,
            entityId: context.entityId
          }, {
            reload: true,
            query: $stateParams.query
          });
        } else {
          $state.go('main.projects.all', {
            entity: 'all',
          }, {
            reload: true
          });
        }
      });
    }
    )
  }

  $scope.recycleRestore = function() {
    ProjectsService.addToParent($scope.item).then(()=>{
      EntityService.recycleRestore('projects', $scope.item._id).then(function() {
        let clonedEntity = JSON.parse(JSON.stringify($scope.item));
        clonedEntity.status = "un-deleted";
        // just for activity status
        ProjectsService.updateStatus(clonedEntity, $scope.item).then(function(result) {
          ActivitiesService.data.push(result);
        });
        refreshList();

        var state = currentState.indexOf('search') !== -1 ? $state.current.name : 'main.projects.all';
        $state.go(state, {
          entity: context.entityName,
          entityId: context.entityId
        }, {
          reload: true
        });
      });
    }
    )
  }

  $scope.menuItems = [{
      label: 'recycleProject',
      icon: 'times-circle',
      display: !$scope.item.hasOwnProperty('recycled'),
      action: $scope.recycle,
    }, {
      label: 'unrecycleProject',
      icon: 'times-circle',
      display: $scope.item.hasOwnProperty('recycled'),
      action: $scope.recycleRestore,
  }];

  // ==================================================== $watch: title / desc ==================================================== //

  $scope.$watch('item.title', function(nVal, oVal) {
    if (nVal !== oVal && oVal) {
      var newContext = {
        name: 'title',
        oldVal: oVal,
        newVal: nVal,
        action: 'renamed'
      };
      $scope.delayedUpdate($scope.item, newContext);

      ProjectsService.currentProjectName = $scope.item.title;
    }
  });

  var nText, oText;
  $scope.$watch('item.description', function(nVal, oVal) {
    nText = nVal ? nVal.replace(/<(?:.|\n)*?>/gm, '') : '';
    oText = oVal ? oVal.replace(/<(?:.|\n)*?>/gm, '') : '';
    if (nText != oText && oText) {
      var newContext = {
        name: 'description',
        oldVal: oVal,
        newVal: nVal,
        action: 'renamed'
      };
      $scope.delayedUpdate($scope.item, newContext);
    }
  });

  // ==================================================== Update  ==================================================== //

  $scope.updateAndNotify = function(project) {
    project.status = $scope.statuses[1];

    if (context.entityName === 'discussion') {
      project.discussion = context.entityId;
    }

    if (project.assign === undefined || project.assign === null) {
      delete project['assign'];
    } else {
      // check the assignee is not a watcher already
      let filtered = project.watchers.filter(watcher=>{
        return watcher._id == project.assign;
      }
      );

      // add assignee as watcher
      if (filtered.length == 0) {
        project.watchers.push(project.assign);
      }
    }

    ProjectsService.update(project).then(function(result) {
      if (context.entityName === 'project') {
        var projId = result.project ? result.project._id : undefined;
        if (projId !== context.entityId) {
          $state.go('main.projects.byentity', {
            entity: context.entityName,
            entityId: context.entityId
          }, {
            reload: true
          });
        }
      }

      ProjectsService.assign(project, me, backupEntity).then(function(res) {
        backupEntity = JSON.parse(JSON.stringify(result));
        ActivitiesService.data.push(res);
      });
    });

  }

  function refreshList() {
    $rootScope.$broadcast('refreshList');
  }

  $scope.update = function(item, type) {
    if (type.name === 'color') {
        item.color = context.newVal;
    }
    ProjectsService.update(item, context).then(function(res) {
      if (ProjectsService.selected && res._id === ProjectsService.selected._id) {
        if (type === 'title') {
          ProjectsService.selected.title = res.title;
        }
      }
      switch (type) {
      case 'status':
        if (context.entityName === 'discussion') {
          item.discussion = context.entityId;
        }

        ProjectsService.updateStatus(item, backupEntity).then(function(result) {
          backupEntity = JSON.parse(JSON.stringify($scope.item));
          ActivitiesService.data = ActivitiesService.data || [];
          ActivitiesService.data.push(result);
        });
        break;

      case 'color':
        ProjectsService.updateColor(item).then(function(result) {
          backupEntity = JSON.parse(JSON.stringify($scope.item));
          ActivitiesService.data = ActivitiesService.data || [];
          ActivitiesService.data.push(result);
        });
        break;
      case 'title':
      case 'description':
        ProjectsService.updateTitle(item, backupEntity, type).then(function(result) {
          backupEntity = JSON.parse(JSON.stringify($scope.item));
          ActivitiesService.data = ActivitiesService.data || [];
          ActivitiesService.data.push(result);
          refreshList();
        });
        break;
      }
    });
  }

  $scope.delayedUpdate = _.debounce($scope.update, 2000);

  // ==================================================== Buttons ==================================================== //

  $scope.updateStatusForApproval = function() {
    let context = {
      action: "updated",
      name: "status",
      type: "project"
    }
    $scope.item.status = "waiting-approval";
    $scope.update(entity, context);
  }

  // ==================================================== Template ==================================================== //

  $scope.saveTemplate = function(newTemplate) {
    return ProjectsService.saveTemplate($stateParams.id, newTemplate)
  }

  $scope.deleteTemplate = function(id) {
    return ProjectsService.deleteTemplate(id)
  }

  $scope.implementTemplate = function(id) {
    return ProjectsService.template2subProjects(id, {
        'projectId': $stateParams.id
    }).then(function(result) {
        for (var i = result.length - 1; i >= 0; i--) {
            result[i].isNew = true;
        }
        $timeout(function() {
          for (var i = result.length - 1; i >= 0; i--) {
            result[i].isNew = false;
          }
        }, 5000);
        var tmp = $scope.item.subProjects.pop()
        $scope.item.subProjects = $scope.item.subProjects.concat(result);
        $scope.item.subProjects.push(tmp);
    });
  }
  // ==================================================== havePermissions ==================================================== //

  $scope.enableRecycled = true;
  $scope.isRecycled = $scope.item.hasOwnProperty('recycled');

  $scope.permsToSee = function() {
    return PermissionsService.haveAnyPerms($scope.item);
  }

  $scope.havePermissions = function(type, enableRecycled) {
    enableRecycled = enableRecycled || !$scope.isRecycled;
    return (PermissionsService.havePermissions($scope.item, type) && enableRecycled);
  }

  $scope.haveEditiorsPermissions = function() {
    return PermissionsService.haveEditorsPerms($scope.item);
  }

}
<|endoftext|>