<commit_before>angular.module( 'App.Views' ).controller( 'Discover.Games.ViewCtrl', function(
	$scope, Location, Api, SplitTest, Game, Game_ViewState, GameLibrary_Game, Game_Rating, Game_ScoreTable, Growls, Translate, Analytics, game, gamePayload )
{
	var _this = this;

	$scope.Game = Game;
	$scope.Game_ViewState = Game_ViewState;

	Location.enforce( {
		slug: game.slug,
	} );

	this.testMediaBarPos = SplitTest.getMediaBarPos( gamePayload );

	this.game = game;
	this.followerCount = gamePayload.followerCount;
	this.libraryGame = gamePayload.libraryGame ? new GameLibrary_Game( gamePayload.libraryGame ) : null;
	this.newsArticlesCount = gamePayload.newsArticlesCount || 0;
	this.trophiesCount = gamePayload.trophiesCount || 0;
	this.hasScores = gamePayload.hasScores || false;
	this.primaryScoreTable = gamePayload.primaryScoreTable ? new Game_ScoreTable( gamePayload.primaryScoreTable ) : null;

	// Overview page will populate this.
	// We only need it for the overview page, but we need to show it in the view of this controller.
	this.mediaBarItems = [];

	processRatingPayload( gamePayload );

	this.notificationCounts = {};

	this.isNavAffixed = false;

	this.onFollowClick = onFollowClick;
	this.refreshRatingInfo = refreshRatingInfo;

	// If the game has a GA tracking ID, then we attach it to this scope so all page views within get tracked.
	if ( game.ga_tracking_id ) {
		Analytics.attachAdditionalPageTracker( $scope, game.ga_tracking_id );
	}

	// Any game rating change will broadcast this event.
	// We catch it so we can update the page with the new rating! Yay!
	$scope.$on( 'onGameRatingChange', onGameRatingChange );

	function onFollowClick()
	{
		if ( this.libraryGame ) {
			this.libraryGame.$remove().then( function( response )
			{
				_this.libraryGame = null;
				_this.followerCount = response.followers;
				Translate.growl( 'success', 'library.followed.remove_game_success' );
			} )
			.catch( function()
			{
				Translate.growl( 'success', 'library.followed.remove_game_error' );
			} );

			Analytics.trackEvent( 'game-following', 'unfollow' );
		}
		else {
			var newLibraryGame = new GameLibrary_Game( { game_id: this.game.id } );

			newLibraryGame.$save().then( function( response )
			{
				_this.libraryGame = newLibraryGame;
				_this.followerCount = response.followers;
				Translate.growl( 'success', 'library.followed.add_game_success' );
			} )
			.catch( function()
			{
				Translate.growl( 'success', 'library.followed.add_game_error' );
			} );

			Analytics.trackEvent( 'game-following', 'follow' );
		}
	}

	function refreshRatingInfo()
	{
		Api.sendRequest( '/web/discover/games/refresh-rating-info/' + this.game.id, null, { detach: true } ).then( processRatingPayload );
	}

	function processRatingPayload( payload )
	{
		_this.userRating = payload.userRating ? new Game_Rating( payload.userRating ) : null;
		_this.ratingBreakdown = payload.ratingBreakdown;
		_this.game.rating_count = payload.game.rating_count;
		_this.game.avg_rating = payload.game.avg_rating;
	}

	function onGameRatingChange( event, gameId )
	{
		if ( gameId == _this.game.id ) {
			_this.refreshRatingInfo();
		}
	}
} );
<commit_msg>Fix the follow/unfollow message for games not showing the game title. Fixes https://github.com/gamejolt/issue-tracker/issues/396<commit_after>angular.module( 'App.Views' ).controller( 'Discover.Games.ViewCtrl', function(
	$scope, Location, Api, SplitTest, Game, Game_ViewState, GameLibrary_Game, Game_Rating, Game_ScoreTable, Growls, Translate, Analytics, game, gamePayload )
{
	var _this = this;

	$scope.Game = Game;
	$scope.Game_ViewState = Game_ViewState;

	Location.enforce( {
		slug: game.slug,
	} );

	this.testMediaBarPos = SplitTest.getMediaBarPos( gamePayload );

	this.game = game;
	this.followerCount = gamePayload.followerCount;
	this.libraryGame = gamePayload.libraryGame ? new GameLibrary_Game( gamePayload.libraryGame ) : null;
	this.newsArticlesCount = gamePayload.newsArticlesCount || 0;
	this.trophiesCount = gamePayload.trophiesCount || 0;
	this.hasScores = gamePayload.hasScores || false;
	this.primaryScoreTable = gamePayload.primaryScoreTable ? new Game_ScoreTable( gamePayload.primaryScoreTable ) : null;

	// Overview page will populate this.
	// We only need it for the overview page, but we need to show it in the view of this controller.
	this.mediaBarItems = [];

	processRatingPayload( gamePayload );

	this.notificationCounts = {};

	this.isNavAffixed = false;

	this.onFollowClick = onFollowClick;
	this.refreshRatingInfo = refreshRatingInfo;

	// If the game has a GA tracking ID, then we attach it to this scope so all page views within get tracked.
	if ( game.ga_tracking_id ) {
		Analytics.attachAdditionalPageTracker( $scope, game.ga_tracking_id );
	}

	// Any game rating change will broadcast this event.
	// We catch it so we can update the page with the new rating! Yay!
	$scope.$on( 'onGameRatingChange', onGameRatingChange );

	function onFollowClick()
	{
		if ( this.libraryGame ) {
			this.libraryGame.$remove().then( function( response )
			{
				_this.libraryGame = null;
				_this.followerCount = response.followers;
				Translate.growl( 'success', 'library.followed.remove_game_success', { game: _this.game.title } );
			} )
			.catch( function()
			{
				Translate.growl( 'success', 'library.followed.remove_game_error' );
			} );

			Analytics.trackEvent( 'game-following', 'unfollow' );
		}
		else {
			var newLibraryGame = new GameLibrary_Game( { game_id: this.game.id } );

			newLibraryGame.$save().then( function( response )
			{
				_this.libraryGame = newLibraryGame;
				_this.followerCount = response.followers;
				Translate.growl( 'success', 'library.followed.add_game_success', { game: _this.game.title } );
			} )
			.catch( function()
			{
				Translate.growl( 'success', 'library.followed.add_game_error' );
			} );

			Analytics.trackEvent( 'game-following', 'follow' );
		}
	}

	function refreshRatingInfo()
	{
		Api.sendRequest( '/web/discover/games/refresh-rating-info/' + this.game.id, null, { detach: true } ).then( processRatingPayload );
	}

	function processRatingPayload( payload )
	{
		_this.userRating = payload.userRating ? new Game_Rating( payload.userRating ) : null;
		_this.ratingBreakdown = payload.ratingBreakdown;
		_this.game.rating_count = payload.game.rating_count;
		_this.game.avg_rating = payload.game.avg_rating;
	}

	function onGameRatingChange( event, gameId )
	{
		if ( gameId == _this.game.id ) {
			_this.refreshRatingInfo();
		}
	}
} );
<|endoftext|>


<commit_before>/**
 * Created by AMOS on 10/7/16.
 */

//TODO: Add various imports for challenge(s)
import * as mcq from './mcq/mcq.js';
import * as survey from './survey/survey.js';
import * as team from './teamActivity/teamactivity.js';

const noop = () => undefined;

//TODO: Add config for routing to various challenges
export function configRoute($routeProvider, routes){
    $routeProvider
        .when(routes.viewMcq, {
            template: mcq.newMcqTmpl,
            controller: mcq.newMcqController,
            controllerAs: 'ctrl',
            resolve:{
              initialData: createMCQInitialData
            }
        })

        .when(routes.editMcq, {
            template: mcq.editMcqTmpl,
            controller: mcq.editMcqController,
            controllerAs: 'ctrl',
            resolve:{
              initialData: editMCQInitialData
            }

        })

        .when(routes.viewSurvey, {
            template: survey.showSurveyTmpl,
            controller: surveyFormEvent,
            controllerAs: 'ctrl',
            resolve: {
                initialData: getTaskSurveyValues
            }
        })

        .when(routes.startMcq, {
            template: mcq.starMcqTmpl,
            controller: mcq.startMcqController,
            controllerAs: 'ctrl',
            resolve:{
              initialData: startMCQInitialData
            }
        })

        .when(routes.createTeamActivity, {
            template: team.teamActivityCreateTmpl,
            controller: team.createTeamActivityController,
            controllerAs: 'ctrl',
            resolve:{
                initialData: team.createTeamActivityInitialData
            }
        })
        .when(routes.viewIRAT,{
            template: team.teamIRATTmpl,
            controller: team.startIRATController,
            controllerAs:'ctrl',
            resolve:{
                initialData: team.createTeamActivityInitialData
            }
        })
        .when(routes.viewTRAT,{
            template: team.teamTRATTmpl,
            controller: team.startTRATController,
            controllerAs:'ctrl',
            resolve:{
                initialData: team.createTeamActivityInitialData
            }

        });

}
configRoute.$inject = ['$routeProvider', 'routes'];

function editMCQInitialData($q, eventService, clmDataStore){
  var data = eventService.get();
  console.log(data);
  return clmDataStore.events.getTaskAnswers(data.event.$id, data.task.$id).then(
      function(result){
        return {
          data: data,
          savedAnswers: result
        }
      }, function(error){
        console.log(error);
      }
  );
}
editMCQInitialData.$inject = [
    '$q',
    'eventService',
    'clmDataStore'
];

// Initial data for starting an MCQ
//todo: tidy up the codes; should be using promises to access some objects as well as validation
function startMCQInitialData($q, spfAuthData, eventService, clmDataStore){
    //promise object
   // var currentUser = spfAuthData.user().catch(noop);

    var data =  eventService.get();

    console.log("the data is here...,", data);
    //console.log("current user now is.", currentUser);

    return $q.all ({
       currentUser: spfAuthData.user(),
        answers: clmDataStore.events.getTaskAnswers(data.eventId, data.taskId),
        getProgress: clmDataStore.events.getProgress(data.eventId)
    }).then (function (result){
        return {
            data: data,
            correctAnswers: result.answers,
            currentUser: result.currentUser,
            progress: result.getProgress
        }
    });

    // return clmDataStore.events.getTaskAnswers(data.eventId, data.taskId).then(
    //       function(result){
    //         return {
    //           data: data,
    //           correctAnswers: result,
    //             currentUser: currentUser
    //         }
    //       }, function(error){
    //         console.log(error);
    //       }
    //   );
}
startMCQInitialData.$inject = [
    '$q',
    'spfAuthData',
    'eventService',
    'clmDataStore'
]

// Initial data for creating MCQ
function createMCQInitialData($q, eventService){
  var data =  eventService.get();
  console.log("data initialised are............................",data);
  return data;
}
createMCQInitialData.$inject = [
  '$q',
  'eventService'
]

//TODO: Generic save function
export function challengeServiceFactory
  ($q, $route, spfAuthData, clmDataStore, spfFirebase, $log, spfAlert, $location, urlFor){
  return {
    save : function(event, taskId, task, taskType, isOpen) {
      var copy = spfFirebase.cleanObj(task);
      var answers = copy.answers;
      console.log('COPY IS ... ', copy);
      self.creatingTask = true;
      if (taskType === 'multipleChoice'){
        delete copy.singPathProblem;
        delete copy.badge;
        delete copy.answers;

        var ref = clmDataStore.events.addTaskWithAns(event.$id, copy, isOpen,answers);
        ref.then(function() {
            spfAlert.success('Task created');
            $location.path(urlFor('editEvent', {eventId: event.$id}));
        }).catch(function(err) {
            $log.error(err);
            spfAlert.error('Failed to create new task');
        }).finally(function() {
            self.creatingTask = false;
        });

      } else if(taskType === 'teamActivity'){
        delete copy.singPathProblem;
        delete copy.badge;
        delete copy.answers;

        var ref = clmDataStore.events.addTaskWithAns(event.$id, copy, isOpen, answers);
        console.log("this ref is",ref);
        ref.then(function() {
            console.log("ref after promise", ref);
            spfAlert.success('Task created');
            $location.path(urlFor('editEvent', {eventId: event.$id}));
        }).catch(function(err) {
            $log.error(err);
            spfAlert.error('Failed to created new task');
        }).finally(function() {
            self.creatingTask = false;
        });
      }

    },
    update: function(event, taskId, task, taskType, isOpen) {
      var copy = spfFirebase.cleanObj(task);
      var answers = copy.answers;
      console.log('COPY IS ... ', copy);
      if (taskType === 'linkPattern') {
        delete copy.badge;
        delete copy.serviceId;
        delete copy.singPathProblem;
      } else if (copy.serviceId === 'singPath') {
        delete copy.badge;
        if (copy.singPathProblem) {
          copy.singPathProblem.path = spfFirebase.cleanObj(task.singPathProblem.path);
          copy.singPathProblem.level = spfFirebase.cleanObj(task.singPathProblem.level);
          copy.singPathProblem.problem = spfFirebase.cleanObj(task.singPathProblem.problem);
        }
      }else if (taskType === 'multipleChoice'){
        delete copy.singPathProblem;
        delete copy.badge;
        delete copy.answers;
      } else {
        delete copy.singPathProblem;
        copy.badge = spfFirebase.cleanObj(task.badge);
      }

      if (!copy.link) {
        // delete empty link. Can't be empty string
        delete copy.link;
      }

      self.creatingTask = true;
      var ref = clmDataStore.events.updateTaskWithAns(event.$id, taskId, copy, answers);
      ref.then(function() {
        if (
            (isOpen && task.openedAt) ||
            (!isOpen && task.closedAt)
        ) {
          return;
        } else if (isOpen) {
          return clmDataStore.events.openTask(event.$id, taskId);
        }

        return clmDataStore.events.closeTask(event.$id, taskId);
      }).then(function() {
        spfAlert.success('Task saved');
        $location.path(urlFor('editEvent', {eventId: event.$id}));
      }).catch(function() {
        spfAlert.error('Failed to save the task.');
      }).finally(function() {
        self.savingTask = false;
      });;
    }
  }
}
challengeServiceFactory.$inject =
    ['$q', '$route', 'spfAuthData', 'clmDataStore', 'spfFirebase', '$log', 'spfAlert', '$location', 'urlFor'];

// export const component = {
//
// }

function surveyFormEvent($scope, clmSurvey, spfFirebase, clmDataStore, $log, spfAlert, $location, urlFor) {

    this.surveys = [
        {id: 1, name: 'Education vs Dissatisfaction with learning'},
        {id: 2, name: 'Motivated strategies for learning'},
        {id: 3, name: 'School engagement scale'}

    ];
    //TODO: retrieve selected value, add task into firebase
    var sharedData = clmSurvey.get();
    //console.log("surveyFormEvent eventId : " + sharedData.taskType);
    var getTask = sharedData.task;
    var self = this;

    this.saveSurveyTask = function (surveyType) {
        var copy = spfFirebase.cleanObj(getTask);
        console.log('my copy is ', copy);
        if (sharedData.taskType === 'linkPattern') {
            delete copy.badge;
            delete copy.serviceId;
            delete copy.singPathProblem;
        } else if (copy.serviceId === 'singPath') {
            delete copy.badge;
            if (copy.singPathProblem) {
                copy.singPathProblem.path = spfFirebase.cleanObj(getTask.singPathProblem.path);
                copy.singPathProblem.level = spfFirebase.cleanObj(getTask.singPathProblem.level);
                copy.singPathProblem.problem = spfFirebase.cleanObj(getTask.singPathProblem.problem);
            }
        } else {
            delete copy.singPathProblem;
            copy.badge = spfFirebase.cleanObj(getTask.badge);
        }

        if (!copy.link) {
            // delete empty link. Can't be empty string
            delete copy.link;
        }

        self.creatingTask = true;
        console.log("survey type is " + surveyType);
        copy.survey = surveyType;
        clmDataStore.events.addTask(sharedData.eventId, copy, sharedData.isOpen).then(function () {
            spfAlert.success('Challenge created');
            $location.path(urlFor('editEvent', {eventId: sharedData.eventId}));
        }).catch(function (err) {
            $log.error(err);
            spfAlert.error('Failed to create new challenge.');
        }).finally(function () {
            self.creatingTask = false;
        });
    };

}
surveyFormEvent.$inject = [
    '$scope',
    'clmSurvey',
    'spfFirebase',
    'clmDataStore',
    '$log',
    'spfAlert',
    '$location',
    'urlFor'
];

function getTaskSurveyValues(clmSurvey, $q, $route, spfAuthData, clmDataStore, spfAuth) {
    var sharedData = clmSurvey.get();

    var data = baseEditCtrlInitialData(sharedData, $q, $route, spfAuthData, clmDataStore, clmSurvey);
    if (data != null) {
        console.log("Data is not null!!!");
    } else {
        console.log("DATA IS NULLLL!!");
    }
    data.badges = clmDataStore.badges.all();
    data.singPath = $q.all({
        paths: clmDataStore.singPath.paths(),
        levels: [],
        problems: []
    });

    return $q.all(data);
}
getTaskSurveyValues.$inject = ['clmSurvey', '$q', '$route', 'spfAuthData', 'clmDataStore', 'spfAuth'];

function baseEditCtrlInitialData(sharedData, $q, $route, spfAuthData, clmDataStore, clmSurvey) {

    var sharedData = clmSurvey.get();
    var errNoEvent = new Error('Event not found');
    var errNotAuthaurized = new Error('You cannot edit this event');
    var eventId = $route.current.params.eventId;

    var eventPromise = clmDataStore.events.get(sharedData.eventId).then(function (event) {
        if (event.$value === null) {
            return $q.reject(errNoEvent);
        }
        return event;
    });

    var data = {
        currentUser: spfAuthData.user(),
        event: eventPromise
    };
    console.log("current user id: " + data.currentUser);
    data.canEdit = $q.all({
        currentUser: spfAuthData.user(),
        event: eventPromise
    }).then(function (result) {
        if (
            !result.currentUser.publicId || !result.event.owner || !result.event.owner.publicId ||
            result.event.owner.publicId !== result.currentUser.publicId
        ) {
            return $q.reject(errNotAuthaurized);
        }

        return result;
    });

    return data;
}<commit_msg>Resolve merge conflicts<commit_after>/**
 * Created by AMOS on 10/7/16.
 */

//TODO: Add various imports for challenge(s)
import * as mcq from './mcq/mcq.js';
import * as survey from './survey/survey.js';
import * as team from './teamActivity/teamactivity.js';

const noop = () => undefined;

//TODO: Add config for routing to various challenges
export function configRoute($routeProvider, routes){
    $routeProvider
        .when(routes.viewMcq, {
            template: mcq.newMcqTmpl,
            controller: mcq.newMcqController,
            controllerAs: 'ctrl',
            resolve:{
              initialData: createMCQInitialData
            }
        })

        .when(routes.editMcq, {
            template: mcq.editMcqTmpl,
            controller: mcq.editMcqController,
            controllerAs: 'ctrl',
            resolve:{
              initialData: editMCQInitialData
            }

        })

        .when(routes.viewSurvey, {
            template: survey.showSurveyTmpl,
            controller: surveyFormEvent,
            controllerAs: 'ctrl',
            resolve: {
                initialData: getTaskSurveyValues
            }
        })

        .when(routes.startMcq, {
            template: mcq.starMcqTmpl,
            controller: mcq.startMcqController,
            controllerAs: 'ctrl',
            resolve:{
              initialData: startMCQInitialData
            }
        })

        .when(routes.createTeamActivity, {
            template: team.teamActivityCreateTmpl,
            controller: team.createTeamActivityController,
            controllerAs: 'ctrl',
            resolve:{
                initialData: team.createTeamActivityInitialData
            }
        })
        .when(routes.viewIRAT,{
            template: team.teamIRATTmpl,
            controller: team.startIRATController,
            controllerAs:'ctrl',
            resolve:{
                initialData: team.createTeamActivityInitialData
            }
        })
        .when(routes.viewTRAT,{
            template: team.teamTRATTmpl,
            controller: team.startTRATController,
            controllerAs:'ctrl',
            resolve:{
                initialData: team.createTeamActivityInitialData
            }

        });

}
configRoute.$inject = ['$routeProvider', 'routes'];

function editMCQInitialData($q, eventService, clmDataStore){
  var data = eventService.get();
  console.log(data);
  return clmDataStore.events.getTaskAnswers(data.event.$id, data.task.$id).then(
      function(result){
        return {
          data: data,
          savedAnswers: result
        }
      }, function(error){
        console.log(error);
      }
  );
}
editMCQInitialData.$inject = [
    '$q',
    'eventService',
    'clmDataStore'
];

// Initial data for starting an MCQ
//todo: tidy up the codes; should be using promises to access some objects as well as validation
function startMCQInitialData($q, spfAuthData, eventService, clmDataStore){
    //promise object
   // var currentUser = spfAuthData.user().catch(noop);

    var data =  eventService.get();

    console.log("the data is here...,", data);
    //console.log("current user now is.", currentUser);

    return $q.all ({
       currentUser: spfAuthData.user(),
        answers: clmDataStore.events.getTaskAnswers(data.eventId, data.taskId),
        getProgress: clmDataStore.events.getProgress(data.eventId)
    }).then (function (result){
        return {
            data: data,
            correctAnswers: result.answers,
            currentUser: result.currentUser,
            progress: result.getProgress
        }
    });

    // return clmDataStore.events.getTaskAnswers(data.eventId, data.taskId).then(
    //       function(result){
    //         return {
    //           data: data,
    //           correctAnswers: result,
    //             currentUser: currentUser
    //         }
    //       }, function(error){
    //         console.log(error);
    //       }
    //   );
}
startMCQInitialData.$inject = [
    '$q',
    'spfAuthData',
    'eventService',
    'clmDataStore'
]

// Initial data for creating MCQ
function createMCQInitialData($q, eventService){
  var data =  eventService.get();
  console.log("data initialised are............................",data);
  return data;
}
createMCQInitialData.$inject = [
  '$q',
  'eventService'
]

//TODO: Generic save function
export function challengeServiceFactory
  ($q, $route, spfAuthData, clmDataStore, spfFirebase, $log, spfAlert, $location, urlFor){
  return {
    save : function(event, taskId, task, taskType, isOpen) {
      var copy = spfFirebase.cleanObj(task);
      var answers = copy.answers;
      console.log('COPY IS ... ', copy);
      self.creatingTask = true;
      if (taskType === 'multipleChoice'){
        delete copy.singPathProblem;
        delete copy.badge;
        delete copy.answers;

        var ref = clmDataStore.events.addTaskWithAns(event.$id, copy, isOpen,answers);
        ref.then(function() {
            spfAlert.success('Task created');
            $location.path(urlFor('editEvent', {eventId: event.$id}));
        }).catch(function(err) {
            $log.error(err);
            spfAlert.error('Failed to created new task');
        }).finally(function() {
            self.creatingTask = false;
        });

      } else if(taskType === 'teamActivity'){
        delete copy.singPathProblem;
        delete copy.badge;
        delete copy.answers;
        console.log(copy);
        // Create reccord in eventTeams
        //TODO: refactor

        // Create reccord in answers and tasks
        var ref = clmDataStore.events.addTaskWithAns(event.$id, copy, isOpen,answers);
        ref.then(function() {
            spfAlert.success('Task created');
            $location.path(urlFor('editEvent', {eventId: event.$id}));
        }).catch(function(err) {
            $log.error(err);
            spfAlert.error('Failed to created new task');
        }).finally(function() {
            self.creatingTask = false;
        });
      }

    },
    update: function(event, taskId, task, taskType, isOpen) {
      var copy = spfFirebase.cleanObj(task);
      var answers = copy.answers;
      console.log('COPY IS ... ', copy);
      if (taskType === 'linkPattern') {
        delete copy.badge;
        delete copy.serviceId;
        delete copy.singPathProblem;
      } else if (copy.serviceId === 'singPath') {
        delete copy.badge;
        if (copy.singPathProblem) {
          copy.singPathProblem.path = spfFirebase.cleanObj(task.singPathProblem.path);
          copy.singPathProblem.level = spfFirebase.cleanObj(task.singPathProblem.level);
          copy.singPathProblem.problem = spfFirebase.cleanObj(task.singPathProblem.problem);
        }
      }else if (taskType === 'multipleChoice'){
        delete copy.singPathProblem;
        delete copy.badge;
        delete copy.answers;
      } else {
        delete copy.singPathProblem;
        copy.badge = spfFirebase.cleanObj(task.badge);
      }

      if (!copy.link) {
        // delete empty link. Can't be empty string
        delete copy.link;
      }

      self.creatingTask = true;
      var ref = clmDataStore.events.updateTaskWithAns(event.$id, taskId, copy, answers);
      ref.then(function() {
        if (
            (isOpen && task.openedAt) ||
            (!isOpen && task.closedAt)
        ) {
          return;
        } else if (isOpen) {
          return clmDataStore.events.openTask(event.$id, taskId);
        }

        return clmDataStore.events.closeTask(event.$id, taskId);
      }).then(function() {
        spfAlert.success('Task saved');
        $location.path(urlFor('editEvent', {eventId: event.$id}));
      }).catch(function() {
        spfAlert.error('Failed to save the task.');
      }).finally(function() {
        self.savingTask = false;
      });;
    }
  }
}
challengeServiceFactory.$inject =
    ['$q', '$route', 'spfAuthData', 'clmDataStore', 'spfFirebase', '$log', 'spfAlert', '$location', 'urlFor'];

// export const component = {
//
// }

function surveyFormEvent($scope, clmSurvey, spfFirebase, clmDataStore, $log, spfAlert, $location, urlFor) {

    this.surveys = [
        {id: 1, name: 'Education vs Dissatisfaction with learning'},
        {id: 2, name: 'Motivated strategies for learning'},
        {id: 3, name: 'School engagement scale'}

    ];
    //TODO: retrieve selected value, add task into firebase
    var sharedData = clmSurvey.get();
    //console.log("surveyFormEvent eventId : " + sharedData.taskType);
    var getTask = sharedData.task;
    var self = this;

    this.saveSurveyTask = function (surveyType) {
        var copy = spfFirebase.cleanObj(getTask);
        console.log('my copy is ', copy);
        if (sharedData.taskType === 'linkPattern') {
            delete copy.badge;
            delete copy.serviceId;
            delete copy.singPathProblem;
        } else if (copy.serviceId === 'singPath') {
            delete copy.badge;
            if (copy.singPathProblem) {
                copy.singPathProblem.path = spfFirebase.cleanObj(getTask.singPathProblem.path);
                copy.singPathProblem.level = spfFirebase.cleanObj(getTask.singPathProblem.level);
                copy.singPathProblem.problem = spfFirebase.cleanObj(getTask.singPathProblem.problem);
            }
        } else {
            delete copy.singPathProblem;
            copy.badge = spfFirebase.cleanObj(getTask.badge);
        }

        if (!copy.link) {
            // delete empty link. Can't be empty string
            delete copy.link;
        }

        self.creatingTask = true;
        console.log("survey type is " + surveyType);
        copy.survey = surveyType;
        clmDataStore.events.addTask(sharedData.eventId, copy, sharedData.isOpen).then(function () {
            spfAlert.success('Challenge created');
            $location.path(urlFor('editEvent', {eventId: sharedData.eventId}));
        }).catch(function (err) {
            $log.error(err);
            spfAlert.error('Failed to create new challenge.');
        }).finally(function () {
            self.creatingTask = false;
        });
    };

}
surveyFormEvent.$inject = [
    '$scope',
    'clmSurvey',
    'spfFirebase',
    'clmDataStore',
    '$log',
    'spfAlert',
    '$location',
    'urlFor'
];

function getTaskSurveyValues(clmSurvey, $q, $route, spfAuthData, clmDataStore, spfAuth) {
    var sharedData = clmSurvey.get();

    var data = baseEditCtrlInitialData(sharedData, $q, $route, spfAuthData, clmDataStore, clmSurvey);
    if (data != null) {
        console.log("Data is not null!!!");
    } else {
        console.log("DATA IS NULLLL!!");
    }
    data.badges = clmDataStore.badges.all();
    data.singPath = $q.all({
        paths: clmDataStore.singPath.paths(),
        levels: [],
        problems: []
    });

    return $q.all(data);
}
getTaskSurveyValues.$inject = ['clmSurvey', '$q', '$route', 'spfAuthData', 'clmDataStore', 'spfAuth'];

function baseEditCtrlInitialData(sharedData, $q, $route, spfAuthData, clmDataStore, clmSurvey) {

    var sharedData = clmSurvey.get();
    var errNoEvent = new Error('Event not found');
    var errNotAuthaurized = new Error('You cannot edit this event');
    var eventId = $route.current.params.eventId;

    var eventPromise = clmDataStore.events.get(sharedData.eventId).then(function (event) {
        if (event.$value === null) {
            return $q.reject(errNoEvent);
        }
        return event;
    });

    var data = {
        currentUser: spfAuthData.user(),
        event: eventPromise
    };
    console.log("current user id: " + data.currentUser);
    data.canEdit = $q.all({
        currentUser: spfAuthData.user(),
        event: eventPromise
    }).then(function (result) {
        if (
            !result.currentUser.publicId || !result.event.owner || !result.event.owner.publicId ||
            result.event.owner.publicId !== result.currentUser.publicId
        ) {
            return $q.reject(errNotAuthaurized);
        }

        return result;
    });

    return data;
}<|endoftext|>


<commit_before>/* eslint-disable security/detect-object-injection */
const fs = require("fs");
const figures = require("figures");
const chalk = require("chalk");
const wrapAndIndent = require("../../utl/wrap-and-indent");
const $defaults = require("../defaults.json");
const { readManifest } = require("./environment-helpers");
const { folderNameArrayToRE } = require("./utl");

const PACKAGE_MANIFEST = `./${$defaults.PACKAGE_MANIFEST}`;

/**
 *
 * @param {import("../../../types/init-config").IInitConfig} pInitOptions
 * @return {any} an bunch of key value pairs that can be plonked into a `scripts` attribute in a package.json
 */
function compileRunScripts(pInitOptions) {
  let lReturnValue = {};

  if (pInitOptions && (pInitOptions.sourceLocation || []).length > 0) {
    const lSourceLocations = pInitOptions.sourceLocation.join(" ");
    const lSourceLocationRE = folderNameArrayToRE(pInitOptions.sourceLocation);
    const lTestLocations = (pInitOptions.testLocation || []).join(" ");

    lReturnValue = {
      depcruise: `depcruise ${lSourceLocations} ${lTestLocations} --config`,
      "depcruise:graph": `depcruise ${lSourceLocations} --include-only '${lSourceLocationRE}' --config --output-type dot | dot -T svg | depcruise-wrap-stream-in-html > dependency-graph.html`,
      "depcruise:graph:dev": `depcruise ${lSourceLocations} --include-only '${lSourceLocationRE}' --prefix vscode://file/$(pwd)/ --config --output-type dot | dot -T svg | depcruise-wrap-stream-in-html | browser`,
      "depcruise:graph-archi": `depcruise ${lSourceLocations} --include-only '${lSourceLocationRE}' --config --output-type archi | dot -T svg | depcruise-wrap-stream-in-html > high-level-dependency-graph.html`,
      "depcruise:html": `depcruise ${lSourceLocations} ${lTestLocations} --config --output-type err-html --output-to dependency-violation-report.html`,
    };
  }

  return lReturnValue;
}

/**
 * Return the scripts in pAdditionalRunScripts that don't yet exist in
 * pExistingRunScripts
 *
 * @param {any} pAdditionalRunScripts
 * @param {any} pExistingRunScripts
 *
 * @return {any} the scripts in pAdditionalRunScripts that don't yet exist in
 * pExistingRunScripts
 */
function filterNewScriptEntries(pExistingRunScripts, pAdditionalRunScripts) {
  return Object.keys(pAdditionalRunScripts || {})
    .filter((pKey) => !pExistingRunScripts[pKey])
    .reduce((pAll, pKey) => {
      pAll[pKey] = pAdditionalRunScripts[pKey];
      return pAll;
    }, {});
}

function addRunScriptsToManifest(pManifest, pAdditionalRunScripts) {
  const lManifest = { ...(pManifest || {}) };
  const lExistingRunScripts = lManifest.scripts || {};

  // This could instead simply be done with
  // {...pAdditionalScriptEntries, ...lManifest} and no logic at all,
  // but that'd add the new scripts on top, which doesn't feel right
  //
  // An alternative would be to sort the keys - but that'd be rude
  lManifest.scripts = {
    ...lExistingRunScripts,
    ...filterNewScriptEntries(lExistingRunScripts, pAdditionalRunScripts),
  };

  return lManifest;
}

function getSuccessMessage(pDestinationManifestFileName) {
  const lExplanationIndent = 6;

  return (
    `  ${chalk.green(
      figures.tick
    )} Run scripts added to '${pDestinationManifestFileName}':` +
    `\n    ${chalk.green(figures.play)} npm run depcruise` +
    `\n${wrapAndIndent(
      "validates against the rules in .dependency-cruiser.js and writes the outcome to stdout",
      lExplanationIndent
    )}` +
    `\n\n    ${chalk.green(figures.play)} npm run depcruise:html` +
    `\n${wrapAndIndent(
      "validates against the rules in .dependency-cruiser.js and writes it to 'dependendency-violation-report.html' with a friendly layout",
      lExplanationIndent
    )}` +
    `\n\n    ${chalk.green(figures.play)} npm run depcruise:graph` +
    `\n${wrapAndIndent(
      "writes a detailed internal graph of your app to 'dependency-graph.html'",
      lExplanationIndent
    )}` +
    `\n\n    ${chalk.green(figures.play)} npm run depcruise:graph-archi` +
    `\n${wrapAndIndent(
      "writes a high-level internal graph of your app to 'high-level-dependency-graph.html'",
      lExplanationIndent
    )}` +
    `\n\n`
  );
}

module.exports = {
  addRunScriptsToManifest,
  compileRunScripts,
  writeRunScriptsToManifest: (
    pNormalizedInitOptions,
    pManifest = readManifest(),
    pDestinationManifestFileName = PACKAGE_MANIFEST
  ) => {
    const lUpdatedManifest = addRunScriptsToManifest(
      pManifest,
      compileRunScripts(pNormalizedInitOptions)
    );

    fs.writeFileSync(
      pDestinationManifestFileName,
      JSON.stringify(lUpdatedManifest, null, "  "),
      "utf8"
    );

    process.stdout.write(getSuccessMessage(pDestinationManifestFileName));
  },
};
<commit_msg>bugfix(init): update the doc output of --init experimental-scripts<commit_after>/* eslint-disable security/detect-object-injection */
const fs = require("fs");
const figures = require("figures");
const chalk = require("chalk");
const wrapAndIndent = require("../../utl/wrap-and-indent");
const $defaults = require("../defaults.json");
const { readManifest } = require("./environment-helpers");
const { folderNameArrayToRE } = require("./utl");

const PACKAGE_MANIFEST = `./${$defaults.PACKAGE_MANIFEST}`;

/**
 *
 * @param {import("../../../types/init-config").IInitConfig} pInitOptions
 * @return {any} an bunch of key value pairs that can be plonked into a `scripts` attribute in a package.json
 */
function compileRunScripts(pInitOptions) {
  let lReturnValue = {};

  if (pInitOptions && (pInitOptions.sourceLocation || []).length > 0) {
    const lSourceLocations = pInitOptions.sourceLocation.join(" ");
    const lSourceLocationRE = folderNameArrayToRE(pInitOptions.sourceLocation);
    const lTestLocations = (pInitOptions.testLocation || []).join(" ");

    lReturnValue = {
      depcruise: `depcruise ${lSourceLocations} ${lTestLocations} --config`,
      "depcruise:graph": `depcruise ${lSourceLocations} --include-only '${lSourceLocationRE}' --config --output-type dot | dot -T svg | depcruise-wrap-stream-in-html > dependency-graph.html`,
      "depcruise:graph:dev": `depcruise ${lSourceLocations} --include-only '${lSourceLocationRE}' --prefix vscode://file/$(pwd)/ --config --output-type dot | dot -T svg | depcruise-wrap-stream-in-html | browser`,
      "depcruise:graph-archi": `depcruise ${lSourceLocations} --include-only '${lSourceLocationRE}' --config --output-type archi | dot -T svg | depcruise-wrap-stream-in-html > high-level-dependency-graph.html`,
      "depcruise:html": `depcruise ${lSourceLocations} ${lTestLocations} --config --output-type err-html --output-to dependency-violation-report.html`,
    };
  }

  return lReturnValue;
}

/**
 * Return the scripts in pAdditionalRunScripts that don't yet exist in
 * pExistingRunScripts
 *
 * @param {any} pAdditionalRunScripts
 * @param {any} pExistingRunScripts
 *
 * @return {any} the scripts in pAdditionalRunScripts that don't yet exist in
 * pExistingRunScripts
 */
function filterNewScriptEntries(pExistingRunScripts, pAdditionalRunScripts) {
  return Object.keys(pAdditionalRunScripts || {})
    .filter((pKey) => !pExistingRunScripts[pKey])
    .reduce((pAll, pKey) => {
      pAll[pKey] = pAdditionalRunScripts[pKey];
      return pAll;
    }, {});
}

function addRunScriptsToManifest(pManifest, pAdditionalRunScripts) {
  const lManifest = { ...(pManifest || {}) };
  const lExistingRunScripts = lManifest.scripts || {};

  // This could instead simply be done with
  // {...pAdditionalScriptEntries, ...lManifest} and no logic at all,
  // but that'd add the new scripts on top, which doesn't feel right
  //
  // An alternative would be to sort the keys - but that'd be rude
  lManifest.scripts = {
    ...lExistingRunScripts,
    ...filterNewScriptEntries(lExistingRunScripts, pAdditionalRunScripts),
  };

  return lManifest;
}

function getSuccessMessage(pDestinationManifestFileName) {
  const lExplanationIndent = 6;

  return (
    `  ${chalk.green(
      figures.tick
    )} Run scripts added to '${pDestinationManifestFileName}':` +
    `\n    ${chalk.green(figures.play)} npm run depcruise` +
    `\n${wrapAndIndent(
      "validates against the rules in .dependency-cruiser.js and writes the outcome to stdout",
      lExplanationIndent
    )}` +
    `\n\n    ${chalk.green(figures.play)} npm run depcruise:html` +
    `\n${wrapAndIndent(
      "validates against the rules in .dependency-cruiser.js and writes it to 'dependendency-violation-report.html' with a friendly layout",
      lExplanationIndent
    )}` +
    `\n\n    ${chalk.green(figures.play)} npm run depcruise:graph` +
    `\n${wrapAndIndent(
      "writes a detailed internal graph of your app to 'dependency-graph.html'",
      lExplanationIndent
    )}` +
    `\n\n    ${chalk.green(figures.play)} npm run depcruise:graph:dev` +
    `\n${wrapAndIndent(
      "opens a detailed internal graph of your app in your default browser (uses the 'browser' command line program)",
      lExplanationIndent
    )}` +
    `\n\n    ${chalk.green(figures.play)} npm run depcruise:graph-archi` +
    `\n${wrapAndIndent(
      "writes a high-level internal graph of your app to 'high-level-dependency-graph.html'",
      lExplanationIndent
    )}` +
    `\n\n`
  );
}

module.exports = {
  addRunScriptsToManifest,
  compileRunScripts,
  writeRunScriptsToManifest: (
    pNormalizedInitOptions,
    pManifest = readManifest(),
    pDestinationManifestFileName = PACKAGE_MANIFEST
  ) => {
    const lUpdatedManifest = addRunScriptsToManifest(
      pManifest,
      compileRunScripts(pNormalizedInitOptions)
    );

    fs.writeFileSync(
      pDestinationManifestFileName,
      JSON.stringify(lUpdatedManifest, null, "  "),
      "utf8"
    );

    process.stdout.write(getSuccessMessage(pDestinationManifestFileName));
  },
};
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Overlay from 'react-bootstrap/lib/Overlay';
import DayPicker from 'react-day-picker';
import moment from 'moment';

const DatePickerWrapper = ({ children }) => (

    {children}

);

DatePickerWrapper.propTypes = {
  children: PropTypes.any
};

class NotificatorDatePicker extends Component {
  state = {
    isOpen: false
  };

  onChange = (newDate) => {
    const { onChange } = this.props;

    this.setState({ isOpen: false });

    onChange({ target: { value: newDate } }, 'until');
  };

  render() {
    const { date } = this.props;
    const { isOpen } = this.state;
    return (

 this.setState({ isOpen: true })}>
          {moment(date).format('DD.MM.YYYY')}

        <Overlay
          animation={false}
          container={this}
          onHide={() => this.setState({ isOpen: false })}
          placement="bottom"
          rootClose
          show={isOpen}
        >
          <DatePickerWrapper>
            <DayPicker
              onDayClick={newDate => this.onChange(newDate)}
              selectedDays={date}
            />
          </DatePickerWrapper>
        </Overlay>

    );
  }
}

NotificatorDatePicker.propTypes = {
  date: PropTypes.instanceOf(Date),
  onChange: PropTypes.func.isRequired
};

export default NotificatorDatePicker;
<commit_msg>Selected dates time will be end of that day.<commit_after>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Overlay from 'react-bootstrap/lib/Overlay';
import DayPicker from 'react-day-picker';
import moment from 'moment';

const DatePickerWrapper = ({ children }) => (

    {children}

);

DatePickerWrapper.propTypes = {
  children: PropTypes.any
};

class NotificatorDatePicker extends Component {
  state = {
    isOpen: false
  };

  onChange = (newDate) => {
    const { onChange } = this.props;

    this.setState({ isOpen: false });

    onChange({ target: { value: moment(newDate).endOf('day').toDate() } }, 'until');
  };

  render() {
    const { date } = this.props;
    const { isOpen } = this.state;
    return (

 this.setState({ isOpen: true })}>
          {moment(date).format('DD.MM.YYYY')}

        <Overlay
          animation={false}
          container={this}
          onHide={() => this.setState({ isOpen: false })}
          placement="bottom"
          rootClose
          show={isOpen}
        >
          <DatePickerWrapper>
            <DayPicker
              onDayClick={newDate => this.onChange(newDate)}
              selectedDays={date}
            />
          </DatePickerWrapper>
        </Overlay>

    );
  }
}

NotificatorDatePicker.propTypes = {
  date: PropTypes.instanceOf(Date),
  onChange: PropTypes.func.isRequired
};

export default NotificatorDatePicker;
<|endoftext|>


<commit_before>/*!
  Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
  Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
  Created By: ivan@reciprocitylabs.com
  Maintained By: ivan@reciprocitylabs.com
*/

(function(can, $) {
  var url = can.route.deparam(window.location.search.substr(1)),
      filterModel = can.Map({
        model_name: "Program",
        value: "",
        filter: {}
      }),
      panelModel = can.Map({
        selected: {},
        models: null,
        type: "Program",
        filter: "",
        relevant: can.compute(function () {
          return new can.List();
        }),
        columns: function () {
          return GGRC.model_attr_defs[this.attr("type")];
        }
      }),
      panelsModel = can.Map({
        items: new can.List()
      }),
      exportModel = can.Map({
        panels: new panelsModel(),
        url: "/_service/export_csv",
        type: url.model_type || "Program",
        edit_filename: false,
        only_relevant: false,
        filename: "Export Objects",
        get_filename: can.compute(function () {
          return this.attr("filename").replace(/\s+/, "_").toLowerCase() + ".csv";
        }),
        data_grid: can.compute(function () {
          return _.has(url, "data_grid");
        })
      });

  can.Component.extend({
    tag: "csv-export",
    template: "<content></content>",
    scope: function () {
      return {
        export: new exportModel()
      };
    },
    events: {
      ".btn-title-change click": function (el, ev) {
        ev.preventDefault();
        this.scope.attr("export.edit_filename", !this.scope.attr("export.edit_filename"));
      },
      ".save-template .btn-success click": function (el, ev) {
        ev.preventDefault();
        var panels = this.scope.attr("export.panels.items"),
            data_grid = this.scope.attr("export.data_grid"),
            only_relevant= this.scope.attr("export.only_relevant"),
            query = _.map(panels, function (panel, index) {
              var relevant_filter = "";
              if (data_grid && index > 0) {
                relevant_filter = "#__previous__,"+(index-1)+"#";
                if (only_relevant && index > 1){
                  relevant_filter += " AND #__previous__,"+(index-2)+"#";
                }
              } else {
                relevant_filter = _.reduce(panel.relevant(),  function(query, el){
                  return (query && query+" AND ")+"#"+el.model_name+","+el.filter.id+"#";
                }, "")
              }
              return {
                object_name: panel.type,
                fields: _.compact(_.map(Object.keys(panel.selected), function (key) {
                  return panel.selected[key] === true ? key : null;
                })),
                filters: GGRC.query_parser.join_queries(
                  GGRC.query_parser.parse(relevant_filter || ""),
                  GGRC.query_parser.parse(panel.filter || "")
                )
              };
            }),
            view = data_grid ? "grid" : "blocks";

        GGRC.Utils.export_request({
          data: query,
          headers: {
            "X-export-view": view
          }
        }).then(function (data) {
          GGRC.Utils.download(this.scope.attr("export.get_filename"), data);
        }.bind(this))
        .fail(function (data) {
          $("body").trigger("ajax:flash", {"error": data});
        }.bind(this));
      }
    }
  });

  can.Component.extend({
    tag: "export-group",
    template: "<content></content>",
    scope: {
      _index: 0
    },
    events: {
      "inserted": function () {
        this.addPanel({
          type: url.model_type || "Program"
        });
      },
      addPanel: function (data) {
        data = data || {};
        var index = this.scope.attr("_index") + 1;
        if (!data.type) {
          data.type = "Program";
        }

        this.scope.attr("_index", index);
        data.index = index;
        return this.scope.attr("panels.items").push(new panelModel(data));
      },
      getIndex: function (el) {
        return +el.closest("export-panel").control().scope.attr("item.index");
      },
      ".remove_filter_group click": function (el, ev) {
        ev.preventDefault();
        var elIndex = this.getIndex(el),
            index = _.pluck(this.scope.attr("panels.items"), "index").indexOf(elIndex);
        this.scope.attr("panels.items").splice(index, 1);
      },
      "#addAnotherObjectType click": function (el, ev) {
        ev.preventDefault();
        this.addPanel();
      }
    }
  });

  can.Component.extend({
    tag: "export-panel",
    template: "<content></content>",
    scope: {
      panel_number: "@",
      fetch_relevant_data: function (id, type) {
        var dfd = GGRC.Models.Search.search_for_types(id, [type]),
            que = new RefreshQueue();

        dfd.then(function (response) {
          var result = response.getResultsFor(url.relevant_type)[0];
          que.enqueue(result).trigger().then(function (item) {
            this.attr("item.relevant").push(new filterModel({
              model_name: url.relevant_type,
              value: url.relevant_id,
              filter: result
            }));
          }.bind(this));
        }.bind(this));
      }
    },
    events: {
      inserted: function () {
        if (!+this.scope.attr("panel_number") && url.relevant_id && url.relevant_type) {
          this.scope.fetch_relevant_data(url.relevant_id, url.relevant_type);
        }
      }
    },
    helpers: {
      first_panel: function (options) {
        if (+this.attr("panel_number") > 0) {
          return options.fn();
        }
        return options.inverse();
      }
    }
  });

  $("#csv_export").html(can.view(GGRC.mustache_path + "/import_export/export.mustache", {}));
})(window.can, window.can.$);
<commit_msg>Fix script error in export page<commit_after>/*!
  Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
  Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
  Created By: ivan@reciprocitylabs.com
  Maintained By: ivan@reciprocitylabs.com
*/

(function(can, $) {
  var url = can.route.deparam(window.location.search.substr(1)),
      filterModel = can.Map({
        model_name: "Program",
        value: "",
        filter: {}
      }),
      panelModel = can.Map({
        selected: {},
        models: null,
        type: "Program",
        filter: "",
        relevant: can.compute(function () {
          return new can.List();
        }),
        columns: function () {
          return GGRC.model_attr_defs[this.attr("type")];
        }
      }),
      panelsModel = can.Map({
        items: new can.List()
      }),
      exportModel = can.Map({
        panels: new panelsModel(),
        url: "/_service/export_csv",
        type: url.model_type || "Program",
        edit_filename: false,
        only_relevant: false,
        filename: "Export Objects",
        get_filename: can.compute(function () {
          return this.attr("filename").replace(/\s+/, "_").toLowerCase() + ".csv";
        }),
        data_grid: can.compute(function () {
          return _.has(url, "data_grid");
        })
      });

  can.Component.extend({
    tag: "csv-export",
    template: "<content></content>",
    scope: function () {
      return {
        export: new exportModel()
      };
    },
    events: {
      ".btn-title-change click": function (el, ev) {
        ev.preventDefault();
        this.scope.attr("export.edit_filename", !this.scope.attr("export.edit_filename"));
      },
      ".save-template .btn-success click": function (el, ev) {
        ev.preventDefault();
        var panels = this.scope.attr("export.panels.items"),
            data_grid = this.scope.attr("export.data_grid"),
            only_relevant= this.scope.attr("export.only_relevant"),
            query = _.map(panels, function (panel, index) {
              var relevant_filter = "";
              if (data_grid && index > 0) {
                relevant_filter = "#__previous__,"+(index-1)+"#";
                if (only_relevant && index > 1){
                  relevant_filter += " AND #__previous__,"+(index-2)+"#";
                }
              } else {
                relevant_filter = _.reduce(panel.relevant(),  function(query, el){
                  return (query && query+" AND ")+"#"+el.model_name+","+el.filter.id+"#";
                }, "")
              }
              return {
                object_name: panel.type,
                fields: _.compact(_.map(Object.keys(panel.selected), function (key) {
                  return panel.selected[key] === true ? key : null;
                })),
                filters: GGRC.query_parser.join_queries(
                  GGRC.query_parser.parse(relevant_filter || ""),
                  GGRC.query_parser.parse(panel.filter || "")
                )
              };
            }),
            view = data_grid ? "grid" : "blocks";

        GGRC.Utils.export_request({
          data: query,
          headers: {
            "X-export-view": view
          }
        }).then(function (data) {
          GGRC.Utils.download(this.scope.attr("export.get_filename"), data);
        }.bind(this))
        .fail(function (data) {
          $("body").trigger("ajax:flash", {"error": data});
        }.bind(this));
      }
    }
  });

  can.Component.extend({
    tag: "export-group",
    template: "<content></content>",
    scope: {
      _index: 0
    },
    events: {
      "inserted": function () {
        this.addPanel({
          type: url.model_type || "Program"
        });
      },
      addPanel: function (data) {
        data = data || {};
        var index = this.scope.attr("_index") + 1;
        if (!data.type) {
          data.type = "Program";
        }

        this.scope.attr("_index", index);
        data.index = index;
        return this.scope.attr("panels.items").push(new panelModel(data));
      },
      getIndex: function (el) {
        return +el.closest("export-panel").control().scope.attr("item.index");
      },
      ".remove_filter_group click": function (el, ev) {
        ev.preventDefault();
        var elIndex = this.getIndex(el),
            index = _.pluck(this.scope.attr("panels.items"), "index").indexOf(elIndex);
        this.scope.attr("panels.items").splice(index, 1);
      },
      "#addAnotherObjectType click": function (el, ev) {
        ev.preventDefault();
        this.addPanel();
      }
    }
  });

  can.Component.extend({
    tag: "export-panel",
    template: "<content></content>",
    scope: {
      panel_number: "@",
      fetch_relevant_data: function (id, type) {
        var dfd = CMS.Models[type].findOne({id: id})
        dfd.then(function (result) {
          this.attr("item.relevant").push(new filterModel({
            model_name: url.relevant_type,
            value: url.relevant_id,
            filter: result
          }));
        }.bind(this));
      }
    },
    events: {
      inserted: function () {
        if (!+this.scope.attr("panel_number") && url.relevant_id && url.relevant_type) {
          this.scope.fetch_relevant_data(url.relevant_id, url.relevant_type);
        }
      }
    },
    helpers: {
      first_panel: function (options) {
        if (+this.attr("panel_number") > 0) {
          return options.fn();
        }
        return options.inverse();
      }
    }
  });

  $("#csv_export").html(can.view(GGRC.mustache_path + "/import_export/export.mustache", {}));
})(window.can, window.can.$);
<|endoftext|>


<commit_before>'use strict';

(function() {
  angular
      .module('bitcoincom.controllers')
      .controller('buyBitcoinSuccessController', successController);

  function successController(
    bitAnalyticsService
    , $interval
    , $ionicHistory
    , $log
    , moonPayService
    , profileService
    , $scope
    , $state
    ) {
    var vm = this;

    // Functions
    vm.onDone = onDone;
    vm.onGoToWallet = onGoToWallet;
    vm.onMakeAnotherPurchase = onMakeAnotherPurchase;

    var moonpayTxId = '';
    var purchasedAmount = 0;
    var refreshPromise = null;
    var walletId = '';

    $scope.$on('$ionicView.beforeEnter', _onBeforeEnter);
    $scope.$on('$ionicView.beforeLeave', _onBeforeLeave);

    function _initVariables() {
      moonpayTxId = $state.params.moonpayTxId;
      purchasedAmount = $state.params.purchasedAmount;

      // Change this to crypto later when the transaction is complete.
      vm.purchasedAmount = purchasedAmount;
      vm.purchasedCurrency = 'USD';
      vm.walletName = '';
      vm.status = 'pending';
      console.log(moonpayTxId, purchasedAmount);
    }

    function _onBeforeEnter() {
      console.log('_onBeforeEnter()');
      _initVariables();

      moonPayService.getDefaultWalletId().then(
        function onGetDefaultWalletIdSuccess(id) {
          if (id) {
            walletId = id;
            var wallet = profileService.getWallet(walletId);
            vm.walletName = wallet.name;

          } else {
            $log.error('Success screen: Default wallet ID not found.');
            // Can't do much, leave in unknown wallet state
          }

        },
        function onGetDefaultWalletIdError(err) {
          $log.error(err);
          // Can't do much, leave in unknown wallet state
        }
      );

      bitAnalyticsService.postEvent('buy_bitcoin_purchase_success_screen_shown', [], ['leanplum']);

      if (moonpayTxId) {
        _refreshTransactionInfo();
        $interval(_refreshTransactionInfo, 5000);
      }
    }

    function _onBeforeLeave() {
      bitAnalyticsService.postEvent('buy_bitcoin_purchase_success_screen_close', [], ['leanplum']);
    }

    function onDone() {
      $ionicHistory.nextViewOptions({
        disableAnimation: true,
        historyRoot: true
      });
      $state.go('tabs.home').then(
        function () {
          $state.go('tabs.buybitcoin');
        }
      );
    }

    function onGoToWallet() {
      $ionicHistory.nextViewOptions({
        disableAnimation: true,
        historyRoot: true
      });
      $state.go('tabs.home').then(
        function() {
          $state.go('tabs.wallet', { walletId: walletId });
        }
      );
    }

    function _onBeforeLeave() {
      console.log('_onBeforeLeave()');
      if (refreshPromise !== null) {
        cancel(refreshPromise);
        refreshPromise = null;
      }
    }

    function onMakeAnotherPurchase() {
      $ionicHistory.nextViewOptions({
        disableAnimation: true,
        historyRoot: true
      });
      $state.go('tabs.home').then(
        function() {
          $state.go('tabs.buybitcoin').then(
            function () {
              $state.go('tabs.buybitcoin-amount');
            }
          );
        }
      );
    }

    function _refreshTransactionInfo() {

      moonPayService.getTransaction(moonpayTxId).then(
        function onGetTransactionSuccess(transaction) {
          vm.purchasedAmount = transaction.baseCurrencyAmount + transaction.feeAmount + transaction.extraFeeAmount;
          vm.status = transaction.status;
          console.log('_refreshTransactionInfo() ' + transaction.status);
          if (vm.status === 'completed') {
            cancel(refreshPromise);
            refreshPromise = null;
          }
        }, function onGetTransactionError(err) {
          $log.error(err);
          // Can't do much, wait for next refresh
        }
      )
    }

  }
})();
<commit_msg>comment promise<commit_after>'use strict';

(function() {
  angular
      .module('bitcoincom.controllers')
      .controller('buyBitcoinSuccessController', successController);

  function successController(
    bitAnalyticsService
    , $interval
    , $ionicHistory
    , $log
    , moonPayService
    , profileService
    , $scope
    , $state
    ) {
    var vm = this;

    // Functions
    vm.onDone = onDone;
    vm.onGoToWallet = onGoToWallet;
    vm.onMakeAnotherPurchase = onMakeAnotherPurchase;

    var moonpayTxId = '';
    var purchasedAmount = 0;
    var refreshPromise = null;
    var walletId = '';

    $scope.$on('$ionicView.beforeEnter', _onBeforeEnter);
    $scope.$on('$ionicView.beforeLeave', _onBeforeLeave);

    function _initVariables() {
      moonpayTxId = $state.params.moonpayTxId;
      purchasedAmount = $state.params.purchasedAmount;

      // Change this to crypto later when the transaction is complete.
      vm.purchasedAmount = purchasedAmount;
      vm.purchasedCurrency = 'USD';
      vm.walletName = '';
      vm.status = 'pending';
      console.log(moonpayTxId, purchasedAmount);
    }

    function _onBeforeEnter() {
      console.log('_onBeforeEnter()');
      _initVariables();

      moonPayService.getDefaultWalletId().then(
        function onGetDefaultWalletIdSuccess(id) {
          if (id) {
            walletId = id;
            var wallet = profileService.getWallet(walletId);
            vm.walletName = wallet.name;

          } else {
            $log.error('Success screen: Default wallet ID not found.');
            // Can't do much, leave in unknown wallet state
          }

        },
        function onGetDefaultWalletIdError(err) {
          $log.error(err);
          // Can't do much, leave in unknown wallet state
        }
      );

      bitAnalyticsService.postEvent('buy_bitcoin_purchase_success_screen_shown', [], ['leanplum']);

      if (moonpayTxId) {
        _refreshTransactionInfo();
        $interval(_refreshTransactionInfo, 5000);
      }
    }

    function _onBeforeLeave() {
      bitAnalyticsService.postEvent('buy_bitcoin_purchase_success_screen_close', [], ['leanplum']);
    }

    function onDone() {
      $ionicHistory.nextViewOptions({
        disableAnimation: true,
        historyRoot: true
      });
      $state.go('tabs.home').then(
        function () {
          $state.go('tabs.buybitcoin');
        }
      );
    }

    function onGoToWallet() {
      $ionicHistory.nextViewOptions({
        disableAnimation: true,
        historyRoot: true
      });
      $state.go('tabs.home').then(
        function() {
          $state.go('tabs.wallet', { walletId: walletId });
        }
      );
    }

    function _onBeforeLeave() {
      console.log('_onBeforeLeave()');
      if (refreshPromise !== null) {
        // cancel(refreshPromise);
        refreshPromise = null;
      }
    }

    function onMakeAnotherPurchase() {
      $ionicHistory.nextViewOptions({
        disableAnimation: true,
        historyRoot: true
      });
      $state.go('tabs.home').then(
        function() {
          $state.go('tabs.buybitcoin').then(
            function () {
              $state.go('tabs.buybitcoin-amount');
            }
          );
        }
      );
    }

    function _refreshTransactionInfo() {

      moonPayService.getTransaction(moonpayTxId).then(
        function onGetTransactionSuccess(transaction) {
          vm.purchasedAmount = transaction.baseCurrencyAmount + transaction.feeAmount + transaction.extraFeeAmount;
          vm.status = transaction.status;
          console.log('_refreshTransactionInfo() ' + transaction.status);
          if (vm.status === 'completed') {
            // cancel(refreshPromise);
            refreshPromise = null;
          }
        }, function onGetTransactionError(err) {
          $log.error(err);
          // Can't do much, wait for next refresh
        }
      )
    }

  }
})();
<|endoftext|>


<commit_before>import axios from "axios";
import { setBaseUrl } from "../../utilities/url-utilities";

const BASE_URL = setBaseUrl(`/ajax/clients`);

/**
 * Revoke all tokens for a given client by identifier.
 * @param {number} id for the client
 * @return {Promise<AxiosResponse<T>>}
 */
export async function revokeClientTokens(id) {
  return await axios.delete(`${BASE_URL}/revoke?id=${id}`);
}

export async function validateClientId(clientId) {
  return axios.get(`${BASE_URL}/validate?clientId=${clientId}`);
}

export async function createClient(details) {
  return axios.post(`${BASE_URL}`, details);
}
<commit_msg>📝 Updated JSDoc<commit_after>import axios from "axios";
import { setBaseUrl } from "../../utilities/url-utilities";

const BASE_URL = setBaseUrl(`/ajax/clients`);

/**
 * Revoke all tokens for a given client by identifier.
 * @param {number} id for the client
 * @return {Promise<AxiosResponse<T>>}
 */
export async function revokeClientTokens(id) {
  return await axios.delete(`${BASE_URL}/revoke?id=${id}`);
}

/**
 * Validate the identifier for client
 * @param clientId - the identifier to validate
 * @returns {Promise<AxiosResponse<any>>}
 */
export async function validateClientId(clientId) {
  return axios.get(`${BASE_URL}/validate?clientId=${clientId}`);
}

/**
 * Create a new client with the provided details.
 * @param details - {clientId, tokenValidity, grantType, refreshToken, read, write, redirectURI}
 * @returns {Promise<AxiosResponse<any>>}
 */
export async function createClient(details) {
  return axios.post(`${BASE_URL}`, details);
}
<|endoftext|>


<commit_before>goog.provide('ol.renderer.canvas.VectorLayer2');

goog.require('goog.dom');
goog.require('goog.dom.TagName');
goog.require('goog.vec.Mat4');
goog.require('ol.extent');
goog.require('ol.layer.Vector');
goog.require('ol.renderer.canvas.Layer');
goog.require('ol.renderer.canvas.Vector');

/**
 * @constructor
 * @extends {ol.renderer.canvas.Layer}
 * @param {ol.renderer.Map} mapRenderer Map renderer.
 * @param {ol.layer.Vector} layer Vector layer.
 */
ol.renderer.canvas.VectorLayer2 = function(mapRenderer, layer) {

  goog.base(this, mapRenderer, layer);

  /**
   * Final canvas made available to the map renderer.
   * @private
   * @type {HTMLCanvasElement}
   */
  this.canvas_ = /** @type {HTMLCanvasElement} */
      (goog.dom.createElement(goog.dom.TagName.CANVAS));

  /**
   * @private
   * @type {!goog.vec.Mat4.Number}
   */
  this.coordsTransform_ = goog.vec.Mat4.createNumber();

  /**
   * @private
   * @type {!goog.vec.Mat4.Number}
   */
  this.transform_ = goog.vec.Mat4.createNumber();

  /**
   * @private
   * @type {number}
   */
  this.renderedResolution_ = 0;

  /**
   * @private
   * @type {ol.Extent}
   */
  this.renderedExtent_ = null;

  /**
   * @private
   * @type {function()}
   */
  this.requestMapRenderFrame_ = goog.bind(function() {
    mapRenderer.getMap().requestRenderFrame();
  }, this);

};
goog.inherits(ol.renderer.canvas.VectorLayer2, ol.renderer.canvas.Layer);

/**
 * @inheritDoc
 */
ol.renderer.canvas.VectorLayer2.prototype.composeFrame =
    function(frameState, layerState, context) {

  var extent = frameState.extent;
  var view2DState = frameState.view2DState;
  var viewCenter = view2DState.center;
  var viewProjection = view2DState.projection;
  var viewResolution = view2DState.resolution;
  var viewRotation = view2DState.rotation;

  var vectorLayer = this.getVectorLayer();

  var features = vectorLayer.getFeaturesObjectForExtent(extent,
      viewProjection, this.requestMapRenderFrame_);

  if (goog.isNull(features)) {
    return;
  }

  this.renderedResolution_ = viewResolution;
  this.renderedExtent_ = extent;

  var canvasWidth = frameState.size[0];
  var canvasHeight = frameState.size[1];

  var halfWidth = canvasWidth;
  var halfHeight = canvasHeight;

  // transform for map coords to sketch canvas pixel coords
  var coordsTransform = this.coordsTransform_;
  var origin = ol.extent.getTopLeft(extent);
  goog.vec.Mat4.makeIdentity(coordsTransform);
  goog.vec.Mat4.translate(coordsTransform,
      halfWidth, halfHeight, 0);
  goog.vec.Mat4.scale(coordsTransform,
      1 / viewResolution, -1 / viewResolution, 1);
  goog.vec.Mat4.translate(coordsTransform,
      -(origin[0] + halfWidth * viewResolution),
      -(origin[1] - halfHeight * viewResolution),
      0);
  var renderer = new ol.renderer.canvas.Vector(context, coordsTransform,
      this.requestMapRenderFrame_);

  var groups = vectorLayer.groupFeaturesBySymbolizerLiteral(features,
      viewResolution);

  var i, ii, group, deferred;

  ii = groups.length;
  for (i = 0; i < ii; ++i) {
    group = groups[i];
    deferred = renderer.renderFeatures(group[0], group[1], group[2]);
    if (deferred) {
      break;
    }
  }

  var transform = this.transform_;
  goog.vec.Mat4.makeIdentity(transform);
  goog.vec.Mat4.translate(transform,
      frameState.size[0] / 2,
      frameState.size[1] / 2,
      0);
  goog.vec.Mat4.scale(transform,
      this.renderedResolution_ / viewResolution,
      this.renderedResolution_ / viewResolution,
      1);
  goog.vec.Mat4.rotateZ(transform, viewRotation);
  goog.vec.Mat4.translate(transform,
      (this.renderedExtent_[0] - viewCenter[0]) / this.renderedResolution_,
      (viewCenter[1] - this.renderedExtent_[3]) / this.renderedResolution_,
      0);

};

/**
 * @inheritDoc
 */
ol.renderer.canvas.VectorLayer2.prototype.getImage = function() {
  return this.canvas_;
};

/**
 * @return {ol.layer.Vector} Vector layer.
 */
ol.renderer.canvas.VectorLayer2.prototype.getVectorLayer = function() {
  return /** @type {ol.layer.Vector} */ (this.getLayer());
};

/**
 * @inheritDoc
 */
ol.renderer.canvas.VectorLayer2.prototype.getTransform = function() {
  return this.transform_;
};

/**
 * @param {ol.layer.VectorEvent} event Vector layer event.
 * @private
 */
ol.renderer.canvas.VectorLayer2.prototype.handleLayerChange_ = function(event) {
  this.requestMapRenderFrame_();
};

/**
 * @inheritDoc
 */
ol.renderer.canvas.VectorLayer2.prototype.prepareFrame = goog.nullFunction;
<commit_msg>Remove unused vector layer canvas<commit_after>goog.provide('ol.renderer.canvas.VectorLayer2');

goog.require('goog.dom');
goog.require('goog.vec.Mat4');
goog.require('ol.extent');
goog.require('ol.layer.Vector');
goog.require('ol.renderer.canvas.Layer');
goog.require('ol.renderer.canvas.Vector');

/**
 * @constructor
 * @extends {ol.renderer.canvas.Layer}
 * @param {ol.renderer.Map} mapRenderer Map renderer.
 * @param {ol.layer.Vector} layer Vector layer.
 */
ol.renderer.canvas.VectorLayer2 = function(mapRenderer, layer) {

  goog.base(this, mapRenderer, layer);

  /**
   * @private
   * @type {!goog.vec.Mat4.Number}
   */
  this.coordsTransform_ = goog.vec.Mat4.createNumber();

  /**
   * @private
   * @type {!goog.vec.Mat4.Number}
   */
  this.transform_ = goog.vec.Mat4.createNumber();

  /**
   * @private
   * @type {number}
   */
  this.renderedResolution_ = 0;

  /**
   * @private
   * @type {ol.Extent}
   */
  this.renderedExtent_ = null;

  /**
   * @private
   * @type {function()}
   */
  this.requestMapRenderFrame_ = goog.bind(function() {
    mapRenderer.getMap().requestRenderFrame();
  }, this);

};
goog.inherits(ol.renderer.canvas.VectorLayer2, ol.renderer.canvas.Layer);

/**
 * @inheritDoc
 */
ol.renderer.canvas.VectorLayer2.prototype.composeFrame =
    function(frameState, layerState, context) {

  var extent = frameState.extent;
  var view2DState = frameState.view2DState;
  var viewCenter = view2DState.center;
  var viewProjection = view2DState.projection;
  var viewResolution = view2DState.resolution;
  var viewRotation = view2DState.rotation;

  var vectorLayer = this.getVectorLayer();

  var features = vectorLayer.getFeaturesObjectForExtent(extent,
      viewProjection, this.requestMapRenderFrame_);

  if (goog.isNull(features)) {
    return;
  }

  this.renderedResolution_ = viewResolution;
  this.renderedExtent_ = extent;

  var canvasWidth = frameState.size[0];
  var canvasHeight = frameState.size[1];

  var halfWidth = canvasWidth;
  var halfHeight = canvasHeight;

  // transform for map coords to sketch canvas pixel coords
  var coordsTransform = this.coordsTransform_;
  var origin = ol.extent.getTopLeft(extent);
  goog.vec.Mat4.makeIdentity(coordsTransform);
  goog.vec.Mat4.translate(coordsTransform,
      halfWidth, halfHeight, 0);
  goog.vec.Mat4.scale(coordsTransform,
      1 / viewResolution, -1 / viewResolution, 1);
  goog.vec.Mat4.translate(coordsTransform,
      -(origin[0] + halfWidth * viewResolution),
      -(origin[1] - halfHeight * viewResolution),
      0);
  var renderer = new ol.renderer.canvas.Vector(context, coordsTransform,
      this.requestMapRenderFrame_);

  var groups = vectorLayer.groupFeaturesBySymbolizerLiteral(features,
      viewResolution);

  var i, ii, group, deferred;

  ii = groups.length;
  for (i = 0; i < ii; ++i) {
    group = groups[i];
    deferred = renderer.renderFeatures(group[0], group[1], group[2]);
    if (deferred) {
      break;
    }
  }

  var transform = this.transform_;
  goog.vec.Mat4.makeIdentity(transform);
  goog.vec.Mat4.translate(transform,
      frameState.size[0] / 2,
      frameState.size[1] / 2,
      0);
  goog.vec.Mat4.scale(transform,
      this.renderedResolution_ / viewResolution,
      this.renderedResolution_ / viewResolution,
      1);
  goog.vec.Mat4.rotateZ(transform, viewRotation);
  goog.vec.Mat4.translate(transform,
      (this.renderedExtent_[0] - viewCenter[0]) / this.renderedResolution_,
      (viewCenter[1] - this.renderedExtent_[3]) / this.renderedResolution_,
      0);

};

/**
 * @return {ol.layer.Vector} Vector layer.
 */
ol.renderer.canvas.VectorLayer2.prototype.getVectorLayer = function() {
  return /** @type {ol.layer.Vector} */ (this.getLayer());
};

/**
 * @inheritDoc
 */
ol.renderer.canvas.VectorLayer2.prototype.getTransform = function() {
  return this.transform_;
};

/**
 * @param {ol.layer.VectorEvent} event Vector layer event.
 * @private
 */
ol.renderer.canvas.VectorLayer2.prototype.handleLayerChange_ = function(event) {
  this.requestMapRenderFrame_();
};

/**
 * @inheritDoc
 */
ol.renderer.canvas.VectorLayer2.prototype.prepareFrame = goog.nullFunction;
<|endoftext|>


<commit_before>define(['require', 'lib/domUtils'], (require, {clearInnerHTML}) => {
    function promiseTry(fun) {
        return new Promise((resolve, reject) => {
            try {
                return resolve(fun());
            } catch (ex) {
                reject(ex);
            }
        });
    }
    class Dispatcher {
        constructor({node, runtime, views}) {
            this.currentPanel = null;
            this.hostNode = node;
            this.runtime = runtime;
            this.views = views;
            this.viewMap = new Map();
        }

        loadModule(modulePath) {
            return new Promise((resolve, reject) => {
                require([modulePath], (module) => {
                    resolve(module);
                }, (err) => {
                    reject(err);
                });
            });
        }

        start() {
            return Promise.all(
                this.views.map(({module, view, type}) => {
                    return this.loadModule(module).then((module) => {
                        return {module, view, type: type || 'es6'};
                    });
                })
            ).then((modules) => {
                modules.forEach((loadedView) => {
                    this.viewMap.set(loadedView.view, loadedView);
                });
                return this;
            });
        }

        selectView(view) {
            // let's just dispatch on the first element, if any.
            // Defaults to account.
            return this.viewMap.get(view);
        }

        unmount() {
            if (!this.currentPanel) {
                return Promise.resolve();
            }
            return promiseTry(() => {
                return this.currentPanel.widget.stop();
            }).then(() => {
                return this.currentPanel.widget.detach();
            });
        }

        dispatch({view: viewId, path, params}) {
            const view = this.selectView(viewId);
            if (!view || !view.module) {
                console.warn('bad view request', viewId, path, params);
                alert(`oops, bad view request: ${  view}`);
                return;
            }

            if (this.currentPanel && this.currentPanel.view === view && this.currentPanel.widget.run) {
                return this.currentPanel.widget.run(params);
            }

            return this.unmount()
                .then(() => {
                    let widget;
                    switch (view.type) {
                    case 'factory':
                        widget = view.module.make({runtime: this.runtime});
                        break;
                    case 'es6':
                        widget = new view.module({runtime: this.runtime});
                        break;
                    default:
                        throw new Error(`Invalid view type: ${  view.type}`);
                    }
                    this.currentPanel = {
                        view,
                        widget
                    };
                    if (this.currentPanel.widget.init) {
                        return this.currentPanel.widget.init();
                    }
                })
                .then(() => {
                    // clear the host node first.
                    clearInnerHTML(this.hostNode);
                    return this.currentPanel.widget.attach(this.hostNode);
                })
                .then(() => {
                    return this.currentPanel.widget.start(params);
                })
                .catch((err) => {
                    console.error('ERROR', err);
                });
        }
    }

    return Dispatcher;
});
<commit_msg>dispatcher should be tolerant of no stop method [CE-19]<commit_after>define(['require', 'lib/domUtils'], (require, {clearInnerHTML}) => {
    function promiseTry(fun) {
        return new Promise((resolve, reject) => {
            try {
                return resolve(fun());
            } catch (ex) {
                reject(ex);
            }
        });
    }
    class Dispatcher {
        constructor({node, runtime, views}) {
            this.currentPanel = null;
            this.hostNode = node;
            this.runtime = runtime;
            this.views = views;
            this.viewMap = new Map();
        }

        loadModule(modulePath) {
            return new Promise((resolve, reject) => {
                require([modulePath], (module) => {
                    resolve(module);
                }, (err) => {
                    reject(err);
                });
            });
        }

        start() {
            return Promise.all(
                this.views.map(({module, view, type}) => {
                    return this.loadModule(module).then((module) => {
                        return {module, view, type: type || 'es6'};
                    });
                })
            ).then((modules) => {
                modules.forEach((loadedView) => {
                    this.viewMap.set(loadedView.view, loadedView);
                });
                return this;
            });
        }

        selectView(view) {
            // let's just dispatch on the first element, if any.
            // Defaults to account.
            return this.viewMap.get(view);
        }

        unmount() {
            if (!this.currentPanel) {
                return Promise.resolve();
            }
            return promiseTry(() => {
                return this.currentPanel.widget.stop && this.currentPanel.widget.stop();
            }).then(() => {
                return this.currentPanel.widget.detach && this.currentPanel.widget.detach();
            });
        }

        dispatch({view: viewId, path, params}) {
            const view = this.selectView(viewId);
            if (!view || !view.module) {
                console.warn('bad view request', viewId, path, params);
                alert(`oops, bad view request: ${  view}`);
                return;
            }

            if (this.currentPanel && this.currentPanel.view === view && this.currentPanel.widget.run) {
                return this.currentPanel.widget.run(params);
            }

            return this.unmount()
                .then(() => {
                    let widget;
                    switch (view.type) {
                    case 'factory':
                        widget = view.module.make({runtime: this.runtime});
                        break;
                    case 'es6':
                        widget = new view.module({runtime: this.runtime});
                        break;
                    default:
                        throw new Error(`Invalid view type: ${  view.type}`);
                    }
                    this.currentPanel = {
                        view,
                        widget
                    };
                    if (this.currentPanel.widget.init) {
                        return this.currentPanel.widget.init();
                    }
                })
                .then(() => {
                    // clear the host node first.
                    clearInnerHTML(this.hostNode);
                    return this.currentPanel.widget.attach(this.hostNode);
                })
                .then(() => {
                    return this.currentPanel.widget.start(params);
                })
                .catch((err) => {
                    console.error('ERROR', err);
                });
        }
    }

    return Dispatcher;
});
<|endoftext|>


<commit_before>const CIDv0Schema = {
  type: 'string',
  pattern: '^(Qm)[1-9A-HJ-NP-Za-km-z]{44}$'
}

const albumInstanceSchema = {
  type: 'object',
  properties: {
    title: {
      type: 'string',
      minLength: 1,
      maxLength: 100
    },
    artist: {
      type: 'string',
      minLength: 1,
      maxLength: 100
    },
    cover: {
      type: 'object',
      properties: {
        image: CIDv0Schema
      },
      required: [ 'image' ]
    },
    tracks: {
      type: 'array',
      minItems: 1,
      items: {
        type: 'object',
        properties: {
          title: {
            type: 'string',
            minLength: 1,
            maxLength: 100
          },
          artist: {
            type: 'string',
            minLength: 1,
            maxLength: 100
          },
          audio: CIDv0Schema
        },
        required: [ 'title', 'artist', 'audio' ]
      }
    }
  },
  required: [ 'title', 'artist', 'tracks', 'cover' ]
}

export default albumInstanceSchema
<commit_msg>fix(): limit max tracklist size<commit_after>const CIDv0Schema = {
  type: 'string',
  pattern: '^(Qm)[1-9A-HJ-NP-Za-km-z]{44}$'
}

const albumInstanceSchema = {
  type: 'object',
  properties: {
    title: {
      type: 'string',
      minLength: 1,
      maxLength: 100
    },
    artist: {
      type: 'string',
      minLength: 1,
      maxLength: 100
    },
    cover: {
      type: 'object',
      properties: {
        image: CIDv0Schema
      },
      required: [ 'image' ]
    },
    tracks: {
      type: 'array',
      minItems: 1,
      maxItems: 100,
      items: {
        type: 'object',
        properties: {
          title: {
            type: 'string',
            minLength: 1,
            maxLength: 100
          },
          artist: {
            type: 'string',
            minLength: 1,
            maxLength: 100
          },
          audio: CIDv0Schema
        },
        required: [ 'title', 'artist', 'audio' ]
      }
    }
  },
  required: [ 'title', 'artist', 'tracks', 'cover' ]
}

export default albumInstanceSchema
<|endoftext|>


<commit_before>import get from 'lodash.get';
import { toGlossaryKey } from '../../../detail/services/endpoint-parser/endpoint-parser';
import GLOSSARY from '../../../detail/services/glossary.constant';
import { routing } from '../../../app/routes';
import { VIEW_MODE } from '../../ducks/ui/ui';
import { FETCH_DETAIL_SUCCESS } from '../../ducks/detail/constants';

export const homeDocumentTitle = (action, defaultTitle) => {
  let pageTitle = defaultTitle;
  const view = get(action, 'meta.query.view', '');
  const embed = get(action, 'meta.query.embed', 'false');
  if (view === VIEW_MODE.MAP) {
    pageTitle = 'Grote kaart';
    if (embed === 'true') {
      pageTitle = `${pageTitle} | Embeded`;
    }
  }

  return pageTitle;
};

export const detailDocumentTitle = (action, defaultTitle = 'UNKNOWN') => {
  const glossaryKey = toGlossaryKey(action.payload.type, action.payload.subtype);
  const glossaryDefinition = GLOSSARY.DEFINITIONS[glossaryKey];
  const label = glossaryDefinition ? glossaryDefinition.label_singular : defaultTitle;

  return `${label}: %display% `;
};

export const datasetDetailDocumentTitle = () => {
  const label = 'Datasets';

  return `${label}: %display% `;
};

export const detailDocumentTitleWithName = (action) => {
  // For now we fill the title for details in 2 steps
  const title = document.title
    .replace('%display%', action.payload.data._display)
    .replace(' - Dataportaal', '');
  return title;
};

const titleActionMapping = [
  {
    actionType: routing.home.type,
    getTitle: homeDocumentTitle
  },
  {
    actionType: routing.dataDetail.type,
    getTitle: detailDocumentTitle
  },
  {
    actionType: routing.datasetsDetail.type,
    getTitle: datasetDetailDocumentTitle
  },
  {
    actionType: FETCH_DETAIL_SUCCESS,
    getTitle: detailDocumentTitleWithName
  }
];

export default titleActionMapping;
<commit_msg>DP-6202 fill the detail and dataset name in document title<commit_after>import get from 'lodash.get';
import { toGlossaryKey } from '../../../detail/services/endpoint-parser/endpoint-parser';
import GLOSSARY from '../../../detail/services/glossary.constant';
import { routing } from '../../../app/routes';
import { VIEW_MODE } from '../../ducks/ui/ui';
import { FETCH_DETAIL_SUCCESS } from '../../ducks/detail/constants';

export const homeDocumentTitle = (action, defaultTitle) => {
  let pageTitle = defaultTitle;
  const view = get(action, 'meta.query.view', '');
  const embed = get(action, 'meta.query.embed', 'false');
  if (view === VIEW_MODE.MAP) {
    pageTitle = 'Grote kaart';
    if (embed === 'true') {
      pageTitle = `${pageTitle} | Embeded`;
    }
  }

  return pageTitle;
};

export const detailDocumentTitle = (action, defaultTitle = 'UNKNOWN') => {
  const glossaryKey = toGlossaryKey(action.payload.type, action.payload.subtype);
  const glossaryDefinition = GLOSSARY.DEFINITIONS[glossaryKey];
  const label = glossaryDefinition ? glossaryDefinition.label_singular : defaultTitle;

  return `${label}`;
};

export const datasetDetailDocumentTitle = () => {
  const label = 'Datasets';

  return `${label}`;
};

export const detailDocumentTitleWithName = (action) => {
  // For now we fill the title for details in 2 steps
  const title = document.title.replace(' - Dataportaal', '');
  if (title.indexOf(':') === -1) {
    return `${title}: ${action.payload.data._display}`;
  }

  return title;
};

const titleActionMapping = [
  {
    actionType: routing.home.type,
    getTitle: homeDocumentTitle
  },
  {
    actionType: routing.dataDetail.type,
    getTitle: detailDocumentTitle
  },
  {
    actionType: routing.datasetsDetail.type,
    getTitle: datasetDetailDocumentTitle
  },
  {
    actionType: FETCH_DETAIL_SUCCESS,
    getTitle: detailDocumentTitleWithName
  }
];

export default titleActionMapping;
<|endoftext|>


<commit_before>goog.provide('tic.coverage');

goog.require('tic');
goog.require('goog.dom');

tic.requireCss('tic.coverage.style');

/**
 * calculates and displays coverage information
 * @constructor
 */
tic.coverage = function(){

};

/**
 * calculates the coverage percentage
 */
tic.coverage.prototype.calculateCoveragePercentage = function(){
    var c = 0;
    for(var i=0; i< instrumentedObject.blockCounter; i++){
	if(!instrumentedObject.executedBlock[i]) {
	    instrumentedObject.executedBlock[i] = 0;
	    c++;
	}
    }
    return (instrumentedObject.blockCounter - c)/instrumentedObject.blockCounter * 100;
};

/**
 * renders the code with coverage
 */
tic.coverage.prototype.render = function(){
    var div = goog.dom.createDom('div');

    var executed = instrumentedObject.executedBlock;
    var commands = instrumentedObject.commands;
    var blockCounter = 0;
    console.log(executed);
    for(var i=1; i<commands.length; i++){ //start from 1 to skip the first 'undefined'
	var command = commands[i];
	if(this.adjustBlockNumber(command)) continue; // its a BEGIN or END of block don't care
	var executedBlockId = this.getCurrentBlock();
	var numberOfExecutions = executed[executedBlockId];
	var className = (numberOfExecutions == false) ? 'red' : 'green';
	var line = goog.dom.createDom('div', className);
	line.innerHTML = command.replace(/\s/g, '  ');
	div.appendChild(line);
    }
    goog.dom.getDocument().body.appendChild(div);
};

/**
 * current block
 * @type {Number}
 */
tic.coverage.prototype.currentBlock_ = [];

/**
 * gets the block number for a command
 */
tic.coverage.prototype.adjustBlockNumber = function(command){
    var result = false;
    if (command.indexOf('BRT_BLOCK_BEGIN') != -1) {
        this.currentBlock_.push(Number(command.match(/BRT_BLOCK_BEGIN:(\d+)/)[1]));
	result = true;
    } else if(command.indexOf('BRT_BLOCK_END') != -1) {
	this.currentBlock_.pop();
	result= true;
    }
    return result;
};

/**
 * returns the top of currentBlock_
 */
tic.coverage.prototype.getCurrentBlock = function(){
    return this.currentBlock_[this.currentBlock_.length-1];
};
<commit_msg>fixes some formating and calculates coverage based on line coverage<commit_after>goog.provide('tic.coverage');

goog.require('tic');
goog.require('goog.dom');

tic.requireCss('tic.coverage.style');

/**
 * calculates and displays coverage information
 * @constructor
 */
tic.coverage = function(){

};

/**
 * calculates the coverage percentage
 */
tic.coverage.prototype.calculateCoveragePercentage = function(){
    var c = 0;
    for(var i=0; i< instrumentedObject.blockCounter; i++){
	if(!instrumentedObject.executedBlock[i]) {
	    instrumentedObject.executedBlock[i] = 0;
	    c++;
	}
    }
    return (instrumentedObject.blockCounter - c)/instrumentedObject.blockCounter * 100;
};

/**
 * renders the code with coverage
 */
tic.coverage.prototype.render = function(){
    var div = goog.dom.createDom('div');

    var executed = instrumentedObject.executedBlock;
    var commands = instrumentedObject.commands;
    var executedLinesCounter = 0;
    var totalLinesCounter = 0;
    console.log(executed);
    for(var i=1; i<commands.length; i++){ //start from 1 to skip the first 'undefined'
	var command = commands[i];
	if(this.adjustBlockNumber(command)) continue; // its a BEGIN or END of block don't care

	totalLinesCounter++;
	var executedBlockId = this.getCurrentBlock();
	var numberOfExecutions = executed[executedBlockId];
	var className = 'red';
	if (numberOfExecutions) {
	    className = 'green';
	    executedLinesCounter++;
	}
	var line = goog.dom.createDom('div', className);
	line.innerHTML = ['', numberOfExecutions, '   ', command.replace(/\s/g, ' '), ''].join('');
	div.appendChild(line);
    }
    goog.dom.getDocument().body.appendChild(div);
    console.log('Coverage:' + (executedLinesCounter/totalLinesCounter*100) + '%');
};

/**
 * current block
 * @type {Number}
 */
tic.coverage.prototype.currentBlock_ = [];

/**
 * gets the block number for a command
 */
tic.coverage.prototype.adjustBlockNumber = function(command){
    var result = false;
    if (command.indexOf('BRT_BLOCK_BEGIN') != -1) {
        this.currentBlock_.push(Number(command.match(/BRT_BLOCK_BEGIN:(\d+)/)[1]));
	result = true;
    } else if(command.indexOf('BRT_BLOCK_END') != -1) {
	this.currentBlock_.pop();
	result= true;
    }
    return result;
};

/**
 * returns the top of currentBlock_
 */
tic.coverage.prototype.getCurrentBlock = function(){
    return this.currentBlock_[this.currentBlock_.length-1];
};
<|endoftext|>


<commit_before>require('../../helper');
var assert = require('../../support/assert');

var TestClient = require('../../support/test-client');
var BatchTestClient = require('../../support/batch-test-client');
var JobStatus = require('../../../batch/job_status');

describe('multiple batch clients job query order', function() {

    before(function(done) {
        this.batchTestClient1 = new BatchTestClient({ name: 'consumerA' });
        this.batchTestClient2 = new BatchTestClient({ name: 'consumerB' });

        this.testClient = new TestClient();
        this.testClient.getResult(
            'drop table if exists ordered_inserts; create table ordered_inserts (status numeric)',
            done
        );
    });

    after(function (done) {
        this.batchTestClient1.drain(function(err) {
            if (err) {
                return done(err);
            }

            this.batchTestClient2.drain(done);
        }.bind(this));
    });

    function createJob(queries) {
        return {
            query: queries
        };
    }

    it('should run job queries in order (multiple consumers)', function (done) {
        var jobRequest1 = createJob(["insert into ordered_inserts values(1)", "insert into ordered_inserts values(2)"]);
        var jobRequest2 = createJob(["insert into ordered_inserts values(3)"]);

        var self = this;

        this.batchTestClient1.createJob(jobRequest1, function(err, jobResult1) {
            if (err) {
                return done(err);
            }
            this.batchTestClient2.createJob(jobRequest2, function(err, jobResult2) {
                if (err) {
                    return done(err);
                }

                jobResult1.getStatus(function (err, job1) {
                    if (err) {
                        return done(err);
                    }
                    jobResult2.getStatus(function(err, job2) {
                        if (err) {
                            return done(err);
                        }
                        assert.equal(job1.status, JobStatus.DONE);
                        assert.equal(job2.status, JobStatus.DONE);

                        self.testClient.getResult('select * from ordered_inserts', function(err, rows) {
                            assert.ok(!err);

                            assert.deepEqual(rows, [{ status: 1 }, { status: 2 }, { status: 3 }]);
                            assert.ok(
                                new Date(job1.updated_at).getTime() < new Date(job2.updated_at).getTime(),
                                'job1 (' + job1.updated_at + ') should finish before job2 (' + job2.updated_at + ')'
                            );
                            done();
                        });

                    });
                });
            });
        }.bind(this));
    });

});
<commit_msg>Make test stable<commit_after>require('../../helper');
var assert = require('../../support/assert');

var TestClient = require('../../support/test-client');
var BatchTestClient = require('../../support/batch-test-client');
var JobStatus = require('../../../batch/job_status');

describe('multiple batch clients job query order', function() {

    before(function(done) {
        this.batchTestClient1 = new BatchTestClient({ name: 'consumerA' });
        this.batchTestClient2 = new BatchTestClient({ name: 'consumerB' });

        this.testClient = new TestClient();
        this.testClient.getResult(
            'drop table if exists ordered_inserts; create table ordered_inserts (status numeric)',
            done
        );
    });

    after(function (done) {
        this.batchTestClient1.drain(function(err) {
            if (err) {
                return done(err);
            }

            this.batchTestClient2.drain(done);
        }.bind(this));
    });

    function createJob(queries) {
        return {
            query: queries
        };
    }

    it('should run job queries in order (multiple consumers)', function (done) {
        var jobRequest1 = createJob([
            "insert into ordered_inserts values(1)",
            "select pg_sleep(1)",
            "insert into ordered_inserts values(2)"
        ]);
        var jobRequest2 = createJob([
            "insert into ordered_inserts values(3)"
        ]);

        var self = this;

        this.batchTestClient1.createJob(jobRequest1, function(err, jobResult1) {
            if (err) {
                return done(err);
            }
            this.batchTestClient2.createJob(jobRequest2, function(err, jobResult2) {
                if (err) {
                    return done(err);
                }

                jobResult1.getStatus(function (err, job1) {
                    if (err) {
                        return done(err);
                    }
                    jobResult2.getStatus(function(err, job2) {
                        if (err) {
                            return done(err);
                        }
                        assert.equal(job1.status, JobStatus.DONE);
                        assert.equal(job2.status, JobStatus.DONE);

                        self.testClient.getResult('select * from ordered_inserts', function(err, rows) {
                            assert.ok(!err);

                            assert.deepEqual(rows, [{ status: 1 }, { status: 2 }, { status: 3 }]);
                            assert.ok(
                                new Date(job1.updated_at).getTime() < new Date(job2.updated_at).getTime(),
                                'job1 (' + job1.updated_at + ') should finish before job2 (' + job2.updated_at + ')'
                            );
                            done();
                        });

                    });
                });
            });
        }.bind(this));
    });

});
<|endoftext|>