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

var App = require('app');

module.exports = App.WizardRoute.extend({
  route: '/service/reassign',

  leaveWizard: function (router, context) {
    var reassignMasterController = router.get('reassignMasterController');
    App.router.get('updateController').set('isWorking', true);
    reassignMasterController.finish();
    App.clusterStatus.setClusterStatus({
      clusterName: App.router.get('content.cluster.name'),
      clusterState: 'DEFAULT',
      localdb: App.db.data
    }, {alwaysCallback: function () {
      context.hide();
      router.transitionTo('main.index');
      location.reload();
    }});
  },

  enter: function (router) {
    console.log('in /service/reassign:enter');
    var context = this;
    var reassignMasterController = router.get('reassignMasterController');
    reassignMasterController.dataLoading().done(function () {
      if (App.router.get('mainHostController.hostsCountMap.TOTAL') > 1) {
        Em.run.next(function () {
          App.router.get('updateController').set('isWorking', false);
          var popup = App.ModalPopup.show({
            classNames: ['full-width-modal'],
            header: Em.I18n.t('services.reassign.header'),
            bodyClass: App.ReassignMasterView.extend({
              controller: reassignMasterController
            }),
            primary: Em.I18n.t('form.cancel'),
            showFooter: false,
            secondary: null,

            onPrimary: function () {
              this.hide();
              App.router.get('updateController').set('isWorking', true);
              App.router.transitionTo('main.services.index');
            },
            onClose: function () {
              var reassignMasterController = router.get('reassignMasterController');
              var currStep = reassignMasterController.get('currentStep');

              if (parseInt(currStep) > 3) {
                var self = this;

                var step4Controller = router.get('reassignMasterWizardStep4Controller');
                var testDBTaskId = step4Controller.get('tasks').filterProperty('command', 'testDBConnection').get('firstObject.id');

                if(currStep !== "7"
                   && testDBTaskId
                   && reassignMasterController.get('content.tasksStatuses').get(testDBTaskId) === "FAILED")
                {
                  App.showConfirmationPopup(function () {
                    App.router.transitionTo('step7');
                  }, Em.I18n.t('services.reassign.rollback.confirm'));
                } else {
                  App.showConfirmationPopup(function () {
                    router.get('reassignMasterWizardStep' + currStep + 'Controller').removeObserver('tasks.@each.status', this, 'onTaskStatusChange');
                    context.leaveWizard(router, self);
                  }, Em.I18n.t('services.reassign.closePopup').format(reassignMasterController.get('content.reassign.display_name')));
                }
              } else {
                context.leaveWizard(router, this);
              }
            },
            didInsertElement: function () {
              this.fitHeight();
            }
          });
          reassignMasterController.set('popup', popup);
          reassignMasterController.loadSecurityEnabled();
          reassignMasterController.loadComponentToReassign();
          var currentClusterStatus = App.clusterStatus.get('value');
          if (currentClusterStatus) {
            switch (currentClusterStatus.clusterState) {
              case 'REASSIGN_MASTER_INSTALLING' :
                reassignMasterController.setCurrentStep(currentClusterStatus.localdb.ReassignMaster.currentStep);
                break;
            }
          }
          router.transitionTo('step' + reassignMasterController.get('currentStep'));
        });
      } else {
        App.showAlertPopup(Em.I18n.t('common.error'), Em.I18n.t('services.reassign.error.fewHosts'), function () {
          router.transitionTo('main.services.index');
        })
      }
    });
  },

  step1: Em.Route.extend({
    route: '/step1',
    connectOutlets: function (router) {
      console.log('in reassignMaster.step1:connectOutlets');
      var controller = router.get('reassignMasterController');
      var step1Controller = router.get('reassignMasterWizardStep1Controller');
      controller.setCurrentStep('1');
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.connectOutlet('reassignMasterWizardStep1', controller.get('content'));
        step1Controller.loadConfigsTags();
      })
    },
    next: function (router) {
      App.db.setMasterComponentHosts(undefined);
      router.transitionTo('step2');
    },

    unroutePath: function () {
      return false;
    }
  }),

  step2: Em.Route.extend({
    route: '/step2',
    connectOutlets: function (router) {
      console.log('in reassignMaster.step2:connectOutlets');
      var controller = router.get('reassignMasterController');
      controller.setCurrentStep('2');
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.connectOutlet('reassignMasterWizardStep2', controller.get('content'));
      })

    },
    back: Em.Router.transitionTo('step1'),
    next: function (router) {
      var controller = router.get('reassignMasterController');
      var reassignMasterWizardStep2 = router.get('reassignMasterWizardStep2Controller');
      controller.saveMasterComponentHosts(reassignMasterWizardStep2);
      var reassignHosts = {};
      var componentName = reassignMasterWizardStep2.get('content.reassign.component_name');
      var masterAssignmentsHosts = reassignMasterWizardStep2.get('selectedServicesMasters').filterProperty('component_name', componentName).mapProperty('selectedHost');
      var currentMasterHosts = App.HostComponent.find().filterProperty('componentName', componentName).mapProperty('hostName');
      masterAssignmentsHosts.forEach(function (host) {
        if (!currentMasterHosts.contains(host)) {
          reassignHosts.target = host;
        }
      }, this);
      currentMasterHosts.forEach(function (host) {
        if (!masterAssignmentsHosts.contains(host)) {
          reassignHosts.source = host;
        }
      }, this);
      controller.saveReassignHosts(reassignHosts);
      router.transitionTo('step3');
    },

    unroutePath: function () {
      return false;
    }
  }),

  step3: Em.Route.extend({
    route: '/step3',
    connectOutlets: function (router) {
      console.log('in reassignMaster.step3:connectOutlets');
      var controller = router.get('reassignMasterController');
      controller.setCurrentStep('3');
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.connectOutlet('reassignMasterWizardStep3', controller.get('content'));
      })
    },
    back: Em.Router.transitionTo('step2'),
    next: function (router) {
      App.db.setReassignTasksStatuses(undefined);
      App.db.setReassignTasksRequestIds(undefined);
      App.clusterStatus.setClusterStatus({
        clusterName: router.get('reassignMasterController.content.cluster.name'),
        clusterState: 'REASSIGN_MASTER_INSTALLING',
        wizardControllerName: 'reassignMasterController',
        localdb: App.db.data
      });
      router.transitionTo('step4');
    },

    unroutePath: function () {
      return false;
    }
  }),

  step4: Em.Route.extend({
    route: '/step4',
    connectOutlets: function (router) {
      console.log('in reassignMaster.step4:connectOutlets');
      var controller = router.get('reassignMasterController');
      controller.setCurrentStep('4');
      controller.setLowerStepsDisable(4);
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.connectOutlet('reassignMasterWizardStep4', controller.get('content'));
      })
    },
    next: function (router) {
      router.get('reassignMasterController').setCurrentStep('5');

      App.clusterStatus.setClusterStatus({
        clusterName: router.get('reassignMasterController.content.cluster.name'),
        clusterState: 'REASSIGN_MASTER_INSTALLING',
        wizardControllerName: 'reassignMasterController',
        localdb: App.db.data
      });

      router.transitionTo('step5');
    },

    complete: function (router) {
      var controller = router.get('reassignMasterController');
      var reassignMasterWizardStep4 = router.get('reassignMasterWizardStep4Controller');
      if (!reassignMasterWizardStep4.get('isSubmitDisabled')) {
        controller.finish();
        controller.get('popup').hide();
        App.clusterStatus.setClusterStatus({
          clusterName: router.get('reassignMasterController.content.cluster.name'),
          clusterState: 'DEFAULT',
          localdb: App.db.data
        }, {alwaysCallback: function () {
          controller.get('popup').hide();
          router.transitionTo('main.index');
          location.reload();
        }});
      }
    },

    unroutePath: function () {
      return false;
    }
  }),

  step5: Em.Route.extend({
    route: '/step5',
    connectOutlets: function (router) {
      console.log('in reassignMaster.step5:connectOutlets');
      var controller = router.get('reassignMasterController');
      controller.setCurrentStep('5');
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.setLowerStepsDisable(5);
        if ((controller.get('content.reassign.component_name') === 'NAMENODE') || controller.get('content.reassign.component_name') === 'SECONDARY_NAMENODE') {
          controller.usersLoading().done(function () {
            controller.connectOutlet('reassignMasterWizardStep5', controller.get('content'));
          })
        } else {
          controller.connectOutlet('reassignMasterWizardStep5', controller.get('content'));
        }
      })
    },
    next: function (router) {
      App.showConfirmationPopup(function () {
        router.transitionTo('step6');
      }, Em.I18n.t('services.reassign.step5.confirmPopup.body'));
    },

    unroutePath: function () {
      return false;
    }
  }),

  step6: Em.Route.extend({
    route: '/step6',
    connectOutlets: function (router) {
      console.log('in reassignMaster.step6:connectOutlets');
      var controller = router.get('reassignMasterController');
      controller.setCurrentStep('6');
      controller.setLowerStepsDisable(6);
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.connectOutlet('reassignMasterWizardStep6', controller.get('content'));
      })
    },

    next: function (router) {
      var controller = router.get('reassignMasterController');
      var reassignMasterWizardStep6 = router.get('reassignMasterWizardStep6Controller');
      if (!reassignMasterWizardStep6.get('isSubmitDisabled')) {
        controller.finish();
        controller.get('popup').hide();
        App.clusterStatus.setClusterStatus({
          clusterName: router.get('reassignMasterController.content.cluster.name'),
          clusterState: 'DEFAULT',
          localdb: App.db.data
        }, {alwaysCallback: function () {
          controller.get('popup').hide();
          router.transitionTo('main.index');
          location.reload();
        }});
      }
    },

    unroutePath: function () {
      return false;
    }
  }),

  step7: Em.Route.extend({
    route: '/step7',
    connectOutlets: function (router) {
      console.log('in reassignMaster.step7:connectOutlets');
      var controller = router.get('reassignMasterController');
      controller.setCurrentStep('7');
      controller.setLowerStepsDisable(7);
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.connectOutlet('reassignMasterWizardStep7', controller.get('content'));
      });
    },

    next: function (router) {
      var controller = router.get('reassignMasterController');
      var reassignMasterWizardStep7 = router.get('reassignMasterWizardStep7Controller');
      if (!reassignMasterWizardStep7.get('isSubmitDisabled')) {
        controller.finish();
        controller.get('popup').hide();
        App.clusterStatus.setClusterStatus({
          clusterName: router.get('reassignMasterController.content.cluster.name'),
          clusterState: 'DEFAULT',
          localdb: App.db.data
        }, {alwaysCallback: function () {
          controller.get('popup').hide();
          router.transitionTo('main.index');
          location.reload();
        }});
      }
    },

    complete: function (router) {
      var controller = router.get('reassignMasterController');
      var reassignMasterWizardStep7 = router.get('reassignMasterWizardStep7Controller');
      if (!reassignMasterWizardStep7.get('isSubmitDisabled')) {
        controller.finish();
        controller.get('popup').hide();
        App.clusterStatus.setClusterStatus({
          clusterName: router.get('reassignMasterController.content.cluster.name'),
          clusterState: 'DEFAULT',
          localdb: App.db.data
        }, {alwaysCallback: function () {
          controller.get('popup').hide();
          router.transitionTo('main.index');
          location.reload();
        }});
      }
    },

    unroutePath: function () {
      return false;
    }
  }),

  gotoStep7: Em.Router.transitionTo('step7'),

  backToServices: function (router) {
    App.router.get('updateController').set('isWorking', true);
    router.transitionTo('services');
  }

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

var App = require('app');

module.exports = App.WizardRoute.extend({
  route: '/service/reassign',

  leaveWizard: function (router, context) {
    var reassignMasterController = router.get('reassignMasterController');
    App.router.get('updateController').set('isWorking', true);
    reassignMasterController.finish();
    App.clusterStatus.setClusterStatus({
      clusterName: App.router.get('content.cluster.name'),
      clusterState: 'DEFAULT',
      localdb: App.db.data
    }, {alwaysCallback: function () {
      context.hide();
      router.transitionTo('main.index');
      location.reload();
    }});
  },

  enter: function (router) {
    console.log('in /service/reassign:enter');
    var context = this;
    var reassignMasterController = router.get('reassignMasterController');
    var currStep = reassignMasterController.get('currentStep');

    reassignMasterController.dataLoading().done(function () {
      if (App.router.get('mainHostController.hostsCountMap.TOTAL') > 1) {
        Em.run.next(function () {
          App.router.get('updateController').set('isWorking', false);
          var popup = App.ModalPopup.show({
            classNames: ['full-width-modal'],
            header: Em.I18n.t('services.reassign.header'),
            bodyClass: App.ReassignMasterView.extend({
              controller: reassignMasterController
            }),
            primary: Em.I18n.t('form.cancel'),
            showFooter: false,
            secondary: null,

            onPrimary: function () {
              this.hide();
              App.router.get('updateController').set('isWorking', true);
              App.router.transitionTo('main.services.index');
            },
            onClose: function () {
              if (parseInt(currStep) > 3) {
                var self = this;

                var step4Controller = router.get('reassignMasterWizardStep4Controller');
                var testDBTaskId = step4Controller.get('tasks').filterProperty('command', 'testDBConnection').get('firstObject.id');

                if(currStep !== "7"
                   && testDBTaskId
                   && reassignMasterController.get('content.tasksStatuses').get(testDBTaskId) === "FAILED")
                {
                  App.showConfirmationPopup(function () {
                    App.router.transitionTo('step7');
                  }, Em.I18n.t('services.reassign.rollback.confirm'));
                } else {
                  App.showConfirmationPopup(function () {
                    router.get('reassignMasterWizardStep' + currStep + 'Controller').removeObserver('tasks.@each.status', this, 'onTaskStatusChange');
                    context.leaveWizard(router, self);
                  }, Em.I18n.t('services.reassign.closePopup').format(reassignMasterController.get('content.reassign.display_name')));
                }
              } else {
                context.leaveWizard(router, this);
              }
            },
            didInsertElement: function () {
              this.fitHeight();
            }
          });
          reassignMasterController.set('popup', popup);
          reassignMasterController.loadSecurityEnabled();
          reassignMasterController.loadComponentToReassign();
          var currentClusterStatus = App.clusterStatus.get('value');
          if (currentClusterStatus) {
            switch (currentClusterStatus.clusterState) {
              case 'REASSIGN_MASTER_INSTALLING' :
                if (currentClusterStatus.localdb.ReassignMaster.currentStep !== currStep) {
                  reassignMasterController.setCurrentStep(currentClusterStatus.localdb.ReassignMaster.currentStep);
                }
                break;
            }
          }
          router.transitionTo('step' + currStep);
        });
      } else {
        App.showAlertPopup(Em.I18n.t('common.error'), Em.I18n.t('services.reassign.error.fewHosts'), function () {
          router.transitionTo('main.services.index');
        })
      }
    });
  },

  step1: Em.Route.extend({
    route: '/step1',
    connectOutlets: function (router) {
      console.log('in reassignMaster.step1:connectOutlets');
      var controller = router.get('reassignMasterController');
      var step1Controller = router.get('reassignMasterWizardStep1Controller');
      controller.setCurrentStep('1');
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.connectOutlet('reassignMasterWizardStep1', controller.get('content'));
        step1Controller.loadConfigsTags();
      })
    },
    next: function (router) {
      App.db.setMasterComponentHosts(undefined);
      router.transitionTo('step2');
    },

    unroutePath: function () {
      return false;
    }
  }),

  step2: Em.Route.extend({
    route: '/step2',
    connectOutlets: function (router) {
      console.log('in reassignMaster.step2:connectOutlets');
      var controller = router.get('reassignMasterController');
      controller.setCurrentStep('2');
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.connectOutlet('reassignMasterWizardStep2', controller.get('content'));
      })

    },
    back: Em.Router.transitionTo('step1'),
    next: function (router) {
      var controller = router.get('reassignMasterController');
      var reassignMasterWizardStep2 = router.get('reassignMasterWizardStep2Controller');
      controller.saveMasterComponentHosts(reassignMasterWizardStep2);
      var reassignHosts = {};
      var componentName = reassignMasterWizardStep2.get('content.reassign.component_name');
      var masterAssignmentsHosts = reassignMasterWizardStep2.get('selectedServicesMasters').filterProperty('component_name', componentName).mapProperty('selectedHost');
      var currentMasterHosts = App.HostComponent.find().filterProperty('componentName', componentName).mapProperty('hostName');
      masterAssignmentsHosts.forEach(function (host) {
        if (!currentMasterHosts.contains(host)) {
          reassignHosts.target = host;
        }
      }, this);
      currentMasterHosts.forEach(function (host) {
        if (!masterAssignmentsHosts.contains(host)) {
          reassignHosts.source = host;
        }
      }, this);
      controller.saveReassignHosts(reassignHosts);
      router.transitionTo('step3');
    },

    unroutePath: function () {
      return false;
    }
  }),

  step3: Em.Route.extend({
    route: '/step3',
    connectOutlets: function (router) {
      console.log('in reassignMaster.step3:connectOutlets');
      var controller = router.get('reassignMasterController');
      controller.setCurrentStep('3');
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.connectOutlet('reassignMasterWizardStep3', controller.get('content'));
      })
    },
    back: Em.Router.transitionTo('step2'),
    next: function (router) {
      App.db.setReassignTasksStatuses(undefined);
      App.db.setReassignTasksRequestIds(undefined);
      App.clusterStatus.setClusterStatus({
        clusterName: router.get('reassignMasterController.content.cluster.name'),
        clusterState: 'REASSIGN_MASTER_INSTALLING',
        wizardControllerName: 'reassignMasterController',
        localdb: App.db.data
      });
      router.transitionTo('step4');
    },

    unroutePath: function () {
      return false;
    }
  }),

  step4: Em.Route.extend({
    route: '/step4',
    connectOutlets: function (router) {
      console.log('in reassignMaster.step4:connectOutlets');
      var controller = router.get('reassignMasterController');
      controller.setCurrentStep('4');
      controller.setLowerStepsDisable(4);
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.connectOutlet('reassignMasterWizardStep4', controller.get('content'));
      })
    },
    next: function (router) {
      router.get('reassignMasterController').setCurrentStep('5');

      App.clusterStatus.setClusterStatus({
        clusterName: router.get('reassignMasterController.content.cluster.name'),
        clusterState: 'REASSIGN_MASTER_INSTALLING',
        wizardControllerName: 'reassignMasterController',
        localdb: App.db.data
      });

      router.transitionTo('step5');
    },

    complete: function (router) {
      var controller = router.get('reassignMasterController');
      var reassignMasterWizardStep4 = router.get('reassignMasterWizardStep4Controller');
      if (!reassignMasterWizardStep4.get('isSubmitDisabled')) {
        controller.finish();
        controller.get('popup').hide();
        App.clusterStatus.setClusterStatus({
          clusterName: router.get('reassignMasterController.content.cluster.name'),
          clusterState: 'DEFAULT',
          localdb: App.db.data
        }, {alwaysCallback: function () {
          controller.get('popup').hide();
          router.transitionTo('main.index');
          location.reload();
        }});
      }
    },

    unroutePath: function () {
      return false;
    }
  }),

  step5: Em.Route.extend({
    route: '/step5',
    connectOutlets: function (router) {
      console.log('in reassignMaster.step5:connectOutlets');
      var controller = router.get('reassignMasterController');
      controller.setCurrentStep('5');
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.setLowerStepsDisable(5);
        if ((controller.get('content.reassign.component_name') === 'NAMENODE') || controller.get('content.reassign.component_name') === 'SECONDARY_NAMENODE') {
          controller.usersLoading().done(function () {
            controller.connectOutlet('reassignMasterWizardStep5', controller.get('content'));
          })
        } else {
          controller.connectOutlet('reassignMasterWizardStep5', controller.get('content'));
        }
      })
    },
    next: function (router) {
      App.showConfirmationPopup(function () {
        router.transitionTo('step6');
      }, Em.I18n.t('services.reassign.step5.confirmPopup.body'));
    },

    unroutePath: function () {
      return false;
    }
  }),

  step6: Em.Route.extend({
    route: '/step6',
    connectOutlets: function (router) {
      console.log('in reassignMaster.step6:connectOutlets');
      var controller = router.get('reassignMasterController');
      controller.setCurrentStep('6');
      controller.setLowerStepsDisable(6);
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.connectOutlet('reassignMasterWizardStep6', controller.get('content'));
      })
    },

    next: function (router) {
      var controller = router.get('reassignMasterController');
      var reassignMasterWizardStep6 = router.get('reassignMasterWizardStep6Controller');
      if (!reassignMasterWizardStep6.get('isSubmitDisabled')) {
        controller.finish();
        controller.get('popup').hide();
        App.clusterStatus.setClusterStatus({
          clusterName: router.get('reassignMasterController.content.cluster.name'),
          clusterState: 'DEFAULT',
          localdb: App.db.data
        }, {alwaysCallback: function () {
          controller.get('popup').hide();
          router.transitionTo('main.index');
          location.reload();
        }});
      }
    },

    unroutePath: function () {
      return false;
    }
  }),

  step7: Em.Route.extend({
    route: '/step7',
    connectOutlets: function (router) {
      console.log('in reassignMaster.step7:connectOutlets');
      var controller = router.get('reassignMasterController');
      controller.setCurrentStep('7');
      controller.setLowerStepsDisable(7);
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.connectOutlet('reassignMasterWizardStep7', controller.get('content'));
      });
    },

    next: function (router) {
      var controller = router.get('reassignMasterController');
      var reassignMasterWizardStep7 = router.get('reassignMasterWizardStep7Controller');
      if (!reassignMasterWizardStep7.get('isSubmitDisabled')) {
        controller.finish();
        controller.get('popup').hide();
        App.clusterStatus.setClusterStatus({
          clusterName: router.get('reassignMasterController.content.cluster.name'),
          clusterState: 'DEFAULT',
          localdb: App.db.data
        }, {alwaysCallback: function () {
          controller.get('popup').hide();
          router.transitionTo('main.index');
          location.reload();
        }});
      }
    },

    complete: function (router) {
      var controller = router.get('reassignMasterController');
      var reassignMasterWizardStep7 = router.get('reassignMasterWizardStep7Controller');
      if (!reassignMasterWizardStep7.get('isSubmitDisabled')) {
        controller.finish();
        controller.get('popup').hide();
        App.clusterStatus.setClusterStatus({
          clusterName: router.get('reassignMasterController.content.cluster.name'),
          clusterState: 'DEFAULT',
          localdb: App.db.data
        }, {alwaysCallback: function () {
          controller.get('popup').hide();
          router.transitionTo('main.index');
          location.reload();
        }});
      }
    },

    unroutePath: function () {
      return false;
    }
  }),

  gotoStep7: Em.Router.transitionTo('step7'),

  backToServices: function (router) {
    App.router.get('updateController').set('isWorking', true);
    router.transitionTo('services');
  }

});
<|endoftext|>


<commit_before>'use strict';
var User = require('../../models/User.js');
var authCredentials = require('../../../config/auth/index');
var TwitterStrategy  = require('passport-twitter').Strategy;
module.exports = function (app, io, passport) {
  passport.use(new TwitterStrategy({
      consumerKey: authCredentials.twitter.consumer_key,
      consumerSecret: authCredentials.twitter.consumer_secret,
      callbackURL: authCredentials.twitter.callback_url
    }, function (token, tokenSecret, profile, done) {
      process.nextTick(function() {
        console.log('inside nexttick');
        User.findOne({ 'socialmediaData.twitter.id': profile.id }, function(err, user) {
          console.log(user.socialmediaData.twitter.id);
          // if there is an error, stop everything and return that
          // ie an error connecting to the database
          if (err) {
            return done(err);
          }
          // if the user is found then log them in
          if (user) {
            return done(null, user); // user found, return that user
          } else {
            // if there is no user, create them
            var newUser = new User();
            console.log(newUser);
            // set all of the user data that we need
            newUser.socialmediaData.twitter.id = profile.id;
            newUser.socialmediaData.twitter.token = token;
            newUser.socialmediaData.twitter.username = profile.username;
            newUser.socialmediaData.twitter.displayName = profile.displayName;
            // save our user into the database
            newUser.save(function(err) {
              if (err) {
                throw err;
              }
              return done(null, newUser);
            });
          }
        });

      });
    }
  ));
  /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
   * routes for OAuths
   * @callback follows the pattern '/<socialmedia>/callback'
   * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  app.get('/auth/twitter', passport.authenticate('twitter'));
  app.get('/auth/twitter/callback', passport.authenticate('twitter', {
      failureRedirect: '/'
    }),
    function(req, res) {
      // Successful authentication, redirect to connected state.
      res.redirect('/connected');
    });
};<commit_msg>refactor: renaming of twitter callbackURL<commit_after>'use strict';
var User = require('../../models/User.js');
var authCredentials = require('../../../config/auth/index');
var TwitterStrategy  = require('passport-twitter').Strategy;
module.exports = function (app, io, passport) {
  passport.use(new TwitterStrategy({
      consumerKey: authCredentials.twitter.consumer_key,
      consumerSecret: authCredentials.twitter.consumer_secret,
      callbackURL: authCredentials.twitter.callbackURL
    }, function (token, tokenSecret, profile, done) {
      process.nextTick(function() {
        console.log('inside nexttick');
        User.findOne({ 'socialmediaData.twitter.id': profile.id }, function(err, user) {
          console.log(user.socialmediaData.twitter.id);
          // if there is an error, stop everything and return that
          // ie an error connecting to the database
          if (err) {
            return done(err);
          }
          // if the user is found then log them in
          if (user) {
            return done(null, user); // user found, return that user
          } else {
            // if there is no user, create them
            var newUser = new User();
            console.log(newUser);
            // set all of the user data that we need
            newUser.socialmediaData.twitter.id = profile.id;
            newUser.socialmediaData.twitter.token = token;
            newUser.socialmediaData.twitter.username = profile.username;
            newUser.socialmediaData.twitter.displayName = profile.displayName;
            // save our user into the database
            newUser.save(function(err) {
              if (err) {
                throw err;
              }
              return done(null, newUser);
            });
          }
        });

      });
    }
  ));
  /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
   * routes for OAuths
   * @callback follows the pattern '/<socialmedia>/callback'
   * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  app.get('/auth/twitter', passport.authenticate('twitter'));
  app.get('/auth/twitter/callback', passport.authenticate('twitter', {
      failureRedirect: '/'
    }),
    function(req, res) {
      // Successful authentication, redirect to connected state.
      res.redirect('/connected');
    });
};<|endoftext|>


<commit_before>// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
define([
        'addons/documents/views-changes',
        'addons/databases/base',
        'testUtils'
], function (Views, Databases, testUtils) {
  var assert = testUtils.assert;

  describe('Documents Changes', function () {
    var filteredView;
    beforeEach(function () {
      var database = new Databases.Model({id: 'bla'});
      database.buildChanges({descending: 'true', limit: '100', include_docs: 'true'} );
      filteredView = new Views.Changes({
        model: database
      });
    });

    it('filter false in case of deleted documents in the changes feed', function () {
      filteredView.filters = [false];
      var res = filteredView.createFilteredData([
        {id: 'LALA', bar: 'ENTE'},
        {id: '1', bar: '1', deleted: true},
        {id: '2', bar: '2'}
      ]);

      assert.equal(res.length, 2);
    });
  });
});
<commit_msg>Add tests for documents/views-changes<commit_after>// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
define([
        'addons/documents/views-changes',
        'addons/databases/base',
        'testUtils'
], function (Views, Databases, testUtils) {
  var assert = testUtils.assert,
      ViewSandbox = testUtils.ViewSandbox,
      viewSandbox;

  describe('Documents Changes', function () {
    var model = new Databases.Model({id: 'foo'}),
        filteredView,
        view,
        handlerSpy;

    model.buildChanges();

    handlerSpy = sinon.spy(Views.Changes.prototype, 'toggleJson');

    beforeEach(function () {
      var database = new Databases.Model({id: 'bla'});
      database.buildChanges({descending: 'true', limit: '100', include_docs: 'true'} );
      filteredView = new Views.Changes({
        model: database
      });

      view = new Views.Changes({
        model: model
      });
      viewSandbox = new ViewSandbox();
      viewSandbox.renderView(view);
    });

    afterEach(function () {
      viewSandbox.remove();
    });

    it('filter false in case of deleted documents in the changes feed', function () {
      filteredView.filters = [false];
      var res = filteredView.createFilteredData([
        {id: 'LALA', bar: 'ENTE'},
        {id: '1', bar: '1', deleted: true},
        {id: '2', bar: '2'}
      ]);

      assert.equal(res.length, 2);
    });

    it('the toggle-json button calls a handler', function () {
      view.$('.js-toggle-json').trigger('click');
      assert.ok(handlerSpy.calledOnce);
    });

    it('rerenders on the sync event', function () {
      var spy = sinon.spy(view, 'afterRender');
      model.changes.trigger('sync');
      view.afterRender.restore();
      assert.ok(spy.calledOnce);
    });

    it('rerenders on the cachesync event', function () {
      var spy = sinon.spy(view, 'afterRender');
      model.changes.trigger('cachesync');
      assert.ok(spy.calledOnce);
      view.afterRender.restore();
    });
  });
});
<|endoftext|>


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

  this.id = infra_id;

  var self = this;

  var ajax_infra = new AjaxSet.Resources('infrastructures');
  ajax_infra.add_member('delete_stack', 'POST');
  ajax_infra.add_member('stack_events', 'GET');
  ajax_infra.add_collection('cloudformation_status', 'GET');
  ajax_infra.add_member('show_elb', 'GET');

  var ajax_resources = new AjaxSet.Resources('resources');

  this.show = function () {
    var dfd = $.Deferred();

    ajax_infra.show({
      id: self.id
    }).done(function (data, status, xhr) {
      dfd.resolve(data);
    }).fail(function (xhr) {
      dfd.reject(xhr.responseText);
    });

    return dfd.promise();
  };

  this.detach = function () {
    var dfd = $.Deferred();

    ajax_infra.destroy({
      id: self.id
    }).done(function (data, status, xhr) {
      dfd.resolve(data);
    }).fail(function (data, status, xhr) {
      dfd.reject(xhr.responseText);
    });

    return dfd.promise();
  };

  this.delete_stack = function () {
    var dfd = $.Deferred();

    ajax_infra.delete_stack({
      id: self.id
    }).done(function (data, status, xhr) {
      dfd.resolve(data);
    }).fail(function (xhr) {
      dfd.reject(xhr.responseText);
    });

    return dfd.promise();
  };

  this.stack_events = function () {
    var dfd = $.Deferred();

    ajax_infra.stack_events({
      id: self.id
    }).done(function (data, status, xhr) {
      dfd.resolve(data);
    }).fail(function (xhr) {
      dfd.reject(xhr.responseText);
    });

    return dfd.promise();
  };

  this.logs = function (page) {
    page = page || 1;
    var dfd = $.Deferred();
    $.ajax({
      url: '/infrastructure_logs',
      data: {
        infrastructure_id: infra_id,
        page: page,
      },
    }).done(function (data, status, xhr) {
      dfd.resolve(data);
    }).fail(function (xhr) {
      dfd.reject(xhr.responseText);
    });

    return dfd.promise();
  };

  this.show_elb = function (physical_id) {
    var dfd = $.Deferred();

    console.log(physical_id);
    ajax_infra.show_elb({
      id:          infra_id,
      physical_id: physical_id,
    }).done(function (data) {
      dfd.resolve(data);
    }).fail(function (xhr) {
      dfd.reject(xhr.responseText);
    });

    return dfd.promise();
  };
};
<commit_msg>bug fix<commit_after>var Infrastructure = function (infra_id) {
  'use strict';

  this.id = infra_id;

  var self = this;

  var ajax_infra = new AjaxSet.Resources('infrastructures');
  ajax_infra.add_member('delete_stack', 'POST');
  ajax_infra.add_member('stack_events', 'GET');
  ajax_infra.add_collection('cloudformation_status', 'GET');
  ajax_infra.add_member('show_elb', 'GET');

  var ajax_resources = new AjaxSet.Resources('resources');

  this.show = function () {
    var dfd = $.Deferred();

    ajax_infra.show({
      id: self.id
    }).done(function (data, status, xhr) {
      dfd.resolve(data);
    }).fail(function (xhr) {
      dfd.reject(xhr.responseText);
    });

    return dfd.promise();
  };

  this.detach = function () {
    var dfd = $.Deferred();

    ajax_infra.destroy({
      id: self.id
    }).done(function (data, status, xhr) {
      dfd.resolve(data);
    }).fail(function (xhr) {
      dfd.reject(xhr.responseText);
    });

    return dfd.promise();
  };

  this.delete_stack = function () {
    var dfd = $.Deferred();

    ajax_infra.delete_stack({
      id: self.id
    }).done(function (data, status, xhr) {
      dfd.resolve(data);
    }).fail(function (xhr) {
      dfd.reject(xhr.responseText);
    });

    return dfd.promise();
  };

  this.stack_events = function () {
    var dfd = $.Deferred();

    ajax_infra.stack_events({
      id: self.id
    }).done(function (data, status, xhr) {
      dfd.resolve(data);
    }).fail(function (xhr) {
      dfd.reject(xhr.responseText);
    });

    return dfd.promise();
  };

  this.logs = function (page) {
    page = page || 1;
    var dfd = $.Deferred();
    $.ajax({
      url: '/infrastructure_logs',
      data: {
        infrastructure_id: infra_id,
        page: page,
      },
    }).done(function (data, status, xhr) {
      dfd.resolve(data);
    }).fail(function (xhr) {
      dfd.reject(xhr.responseText);
    });

    return dfd.promise();
  };

  this.show_elb = function (physical_id) {
    var dfd = $.Deferred();

    console.log(physical_id);
    ajax_infra.show_elb({
      id:          infra_id,
      physical_id: physical_id,
    }).done(function (data) {
      dfd.resolve(data);
    }).fail(function (xhr) {
      dfd.reject(xhr.responseText);
    });

    return dfd.promise();
  };
};
<|endoftext|>


<commit_before>const fs = require('fs');
const path = require('path');
const color = require('color');
const mkdirp = require('mkdirp');
const utils = require('../utils');

const argbRegexp = /^(#)([0-9A-F]{2})([0-9A-F]{6})$/;

function mapDocument(doc, inputPackageDir, avdFileName, options, cb) {
  const outputPackageDir = utils.createTempDirectoryName();
  mkdirp.sync(outputPackageDir);

  const result = {};
  result.version = '2';
  result.id = options.id;
  result.name = options.name;
  result.parts = mapParts(doc.work);
  result.annotations = mapVisualizationsToAnnotations(doc.visualizations);
  result.sounds = mapVisualizationsToSounds(doc.visualizations, doc.resources, doc.rels, inputPackageDir, outputPackageDir, avdFileName);

  const docJson = JSON.stringify(result);
  const docFileName = path.normalize(path.join(outputPackageDir, 'anavis.json'));
  fs.writeFileSync(docFileName, docJson, 'utf8');
  // TODO: Copy sound files / delete old package dir, then call cb ...

  cb(null, outputPackageDir);
}

function mapParts(work) {
  return work.parts.map(part => {
    const category = work.categories.find(cat => cat.id === part.categoryId);
    return {
      id: part.id,
      name: category ? category.name : '???',
      color: category ? toHexString(category.color) : '#FF0000',
      length: Number(part.length)
    };
  });
}

function toHexString(clr) {
  if (argbRegexp.test(clr)) {
    clr = clr.replace(argbRegexp, '$1$3');
  }
  return color(clr).hex();
}

function mapVisualizationsToAnnotations(visualizations) {
  return visualizations
    .filter(vis => ['lyrics', 'harmonies', 'annotations'].indexOf(vis.type) !== -1)
    .map(vis => {
      return {
        id: vis.id,
        type: mapAnnotationTypeName(vis.type),
        values: vis[vis.type].parts.map(part => part.text)
      }
    });
}

function mapAnnotationTypeName(type) {
  switch (type) {
    case 'lyrics': return 'lyrics';
    case 'harmonies': return 'harmonies';
    default: return 'remarks';
  }
}

function mapVisualizationsToSounds(visualizations, resources, rels, inputPackageDir, outputPackageDir, avdFileName) {
  let results = [];
  let fileCopyActions = [];
  visualizations
    .filter(vis => vis.type === 'sound')
    .map(vis => {
      if (!vis.soundFile || !vis.soundFile.uri) {
        results.push({ path: null, embedded: false });
      } else if (vis.soundFile.uri.startsWith('file://')) {
        results.push({ path: path.relative(makeFileUriAbsolute(vis.soundFile.uri), path.dirname(avdFileName)), embedded: false });
      } else if (vis.soundFile.uri.startsWith('resource://')) {
        const soundResource = resources.find(res => res.visualizationId === vis.id);
        const relationshipId = soundResource.items[0].relationshipId;
        const relation = rels.find(rel => rel.id === relationshipId);
        const inputPath = path.normalize(relation.target);
        const outputPath = makeResourceUriAbsolute(vis.soundFile.uri, outputPackageDir);
        fileCopyActions.push({ source: inputPath, destination: outputPath })
        results.push({ path: path.relative(outputPath, outputPackageDir), embedded: true });
      } else {
        throw new Error('Invalid sound file');
      }
    });

    for (const action of fileCopyActions) {
      copyFileSync(action.source, action.destination);
    }

    return results;
}

function makeFileUriAbsolute(fileUri) {
  return path.normalize(fileUri.replace(/^file:\/\/\//, ''));
}

function makeResourceUriAbsolute(resourceUri, absoluteTo) {
  return path.normalize(path.resolve(absoluteTo, resourceUri.replace(/^resource:\/\/\//, '')));
}

// copies a file synchronously:
function copyFileSync(srcFile, destFile) {
  const BUF_LENGTH = 64 * 1024;
  const buff = new Buffer(BUF_LENGTH);
  const fdr = fs.openSync(srcFile, 'r');
  const fdw = fs.openSync(destFile, 'w');
  let bytesRead = 1;
  let pos = 0;
  while (bytesRead > 0) {
    bytesRead = fs.readSync(fdr, buff, 0, BUF_LENGTH, pos);
    fs.writeSync(fdw, buff, 0, bytesRead);
    pos += bytesRead;
  }
  fs.closeSync(fdr);
  fs.closeSync(fdw);
}

module.exports = { mapDocument };
<commit_msg>Fix file path for embedded sound files<commit_after>const fs = require('fs');
const path = require('path');
const color = require('color');
const mkdirp = require('mkdirp');
const utils = require('../utils');

const argbRegexp = /^(#)([0-9A-F]{2})([0-9A-F]{6})$/;

function mapDocument(doc, inputPackageDir, avdFileName, options, cb) {
  const outputPackageDir = utils.createTempDirectoryName();
  mkdirp.sync(outputPackageDir);

  const result = {};
  result.version = '2';
  result.id = options.id;
  result.name = options.name;
  result.parts = mapParts(doc.work);
  result.annotations = mapVisualizationsToAnnotations(doc.visualizations);
  result.sounds = mapVisualizationsToSounds(doc.visualizations, doc.resources, doc.rels, inputPackageDir, outputPackageDir, avdFileName);

  const docJson = JSON.stringify(result);
  const docFileName = path.normalize(path.join(outputPackageDir, 'anavis.json'));
  fs.writeFileSync(docFileName, docJson, 'utf8');
  // TODO: Delete old package dir, then call cb ...

  cb(null, outputPackageDir);
}

function mapParts(work) {
  return work.parts.map(part => {
    const category = work.categories.find(cat => cat.id === part.categoryId);
    return {
      id: part.id,
      name: category ? category.name : '???',
      color: category ? toHexString(category.color) : '#FF0000',
      length: Number(part.length)
    };
  });
}

function toHexString(clr) {
  if (argbRegexp.test(clr)) {
    clr = clr.replace(argbRegexp, '$1$3');
  }
  return color(clr).hex();
}

function mapVisualizationsToAnnotations(visualizations) {
  return visualizations
    .filter(vis => ['lyrics', 'harmonies', 'annotations'].indexOf(vis.type) !== -1)
    .map(vis => {
      return {
        id: vis.id,
        type: mapAnnotationTypeName(vis.type),
        values: vis[vis.type].parts.map(part => part.text)
      }
    });
}

function mapAnnotationTypeName(type) {
  switch (type) {
    case 'lyrics': return 'lyrics';
    case 'harmonies': return 'harmonies';
    default: return 'remarks';
  }
}

function mapVisualizationsToSounds(visualizations, resources, rels, inputPackageDir, outputPackageDir, avdFileName) {
  let results = [];
  let fileCopyActions = [];
  visualizations
    .filter(vis => vis.type === 'sound')
    .map(vis => {
      if (!vis.soundFile || !vis.soundFile.uri) {
        results.push({ path: null, embedded: false });
      } else if (vis.soundFile.uri.startsWith('file://')) {
        results.push({ path: path.relative(makeFileUriAbsolute(vis.soundFile.uri), path.dirname(avdFileName)), embedded: false });
      } else if (vis.soundFile.uri.startsWith('resource://')) {
        const soundResource = resources.find(res => res.visualizationId === vis.id);
        const relationshipId = soundResource.items[0].relationshipId;
        const relation = rels.find(rel => rel.id === relationshipId);
        const inputPath = path.normalize(relation.target);
        const outputPath = makeResourceUriAbsolute(vis.soundFile.uri, outputPackageDir);
        fileCopyActions.push({ source: inputPath, destination: outputPath })
        results.push({ path: path.relative(outputPackageDir, outputPath), embedded: true });
      } else {
        throw new Error('Invalid sound file');
      }
    });

    for (const action of fileCopyActions) {
      copyFileSync(action.source, action.destination);
    }

    return results;
}

function makeFileUriAbsolute(fileUri) {
  return path.normalize(fileUri.replace(/^file:\/\/\//, ''));
}

function makeResourceUriAbsolute(resourceUri, absoluteTo) {
  return path.normalize(path.resolve(absoluteTo, resourceUri.replace(/^resource:\/\/\//, '')));
}

// copies a file synchronously:
function copyFileSync(srcFile, destFile) {
  const BUF_LENGTH = 64 * 1024;
  const buff = new Buffer(BUF_LENGTH);
  const fdr = fs.openSync(srcFile, 'r');
  const fdw = fs.openSync(destFile, 'w');
  let bytesRead = 1;
  let pos = 0;
  while (bytesRead > 0) {
    bytesRead = fs.readSync(fdr, buff, 0, BUF_LENGTH, pos);
    fs.writeSync(fdw, buff, 0, bytesRead);
    pos += bytesRead;
  }
  fs.closeSync(fdr);
  fs.closeSync(fdw);
}

module.exports = { mapDocument };
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
    _ = require('lodash'),
    errorHandler = require('./errors.server.controller'),
    UserGoals = mongoose.model('UserGoals'),
    Goal = mongoose.model('Goal'),
    tincan = require('./tincan.server.controller.js');

/**
 * Create a User goal
 */
exports.create = function(req, res) {
  var goal = req.body.goal;
  var userGoals = new UserGoals(_.omit(req.body, 'goal'));
  userGoals.user = req.user;
  userGoals.goal = goal._id;

  userGoals.save(function(err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      /* Increment committed field in goal */
      Goal.update({_id: userGoals.goal}, {$inc: {committed: 1}}, function(err) {
        if (err) {
          return res.status(400).send({
            message: errorHandler.getErrorMessage(err)
          });
        } else {
          /* Send statement to LRS if committed to goal */
          if(userGoals.status === 'committed') {
            tincan.committedToGoal(req.user.email, req.user.displayName);
          }

          res.json(userGoals);
        }
      });

    }
  });
};

/**
 * Show the current User goal
 */
exports.read = function(req, res) {
  res.json(req.userGoal);
};

/**
 * Update a User goal
 */
exports.update = function(req, res) {
  var tags = _.pluck(req.body.tags, 'text');
  var requestBody = _.extend(_.omit(req.body, 'tags'), {tags: tags});
  var userGoal = _.extend(req.userGoal, requestBody);

  UserGoals.findById(userGoal._id).exec(function(err, oldGoal) {
    /* Changed finished date if finished value is flipped */
    if(oldGoal.finished !== userGoal.finished) {
      userGoal.finishedDate = new Date();

      /* Send tincan statement to LRS */
      if(userGoal.finished) {
        tincan.finishedGoal(req.user.email, req.user.displayName);
      }
    }

    /* Check if any subgoals are finished and send to LRS */
    _.each(userGoal.subgoals, function(subgoal) {
      _.each(oldGoal.subgoals, function(oldSubgoal) {
        if(subgoal.finished && oldSubgoal.finished === false) {
          tincan.progressedGoal(req.user.email, req.user.displayName);
        }
      });
    });

    userGoal.save(function(err) {
      if (err) {
        return res.status(400).send({
          message: errorHandler.getErrorMessage(err)
        });
      } else {
        res.json(userGoal);
      }
    });
  });
};

/**
 * Abort a goal
 * @param req
 * @param res
 */
exports.abort = function(req, res) {
  var userGoal = req.userGoal;
  userGoal.status = 'aborted';

  userGoal.save(function(err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      tincan.abortedGoal(req.user.email, req.user.displayName);
      res.json(userGoal);
    }
  });
};

/**
 * List of User goals
 */
exports.list = function(req, res) {
  UserGoals.find({user: req.user, status: 'committed', $or: [{group: null}, {grouped:{$gt: 0}}]}).populate('goal').sort('-created').exec(function(err, userGoals) {
    if (err) {
      console.log(err);
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {

      res.json(userGoals);
    }
  });
};

/**
 * Get user goals by group id
 * @param req
 * @param res
 */
exports.listByGroup = function(req, res) {
  UserGoals.find({group: req.param('userGoalGroupId')}).sort('-created').exec(function(err, userGoals) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {

      res.json(userGoals);
    }
  });
};

exports.getGoalStatistics = function(req, res) {
  var result = {};
  /* Count completed goals */
  UserGoals.aggregate(
    {
      $match: {
        'finishedDate': {$exists: true},
        'user': req.user._id
      }
    },
    {
      $sort: {
        'finishedDate': -1
      }
    },
    {
      $group:  {
        _id : {
          finishedDate: {
            day: {$dayOfMonth: 'finishedDate'},
            month: {$month: 'finishedDate'},
            year: {$year: 'finishedDate'}
          }
        },
        total: {$sum: 1}
      }
    }).exec(function(err, finished) {
      console.log(err);
      if (err) {
        return res.status(400).send({
          message: errorHandler.getErrorMessage(err)
        });
      } else {
        result.finished = finished;

        /* Count total number of goals */
        UserGoals.count({user: req.user._id}).exec(function(err, count) {
          console.log(err);
          if (err) {
            return res.status(400).send({
              message: errorHandler.getErrorMessage(err)
            });
          } else {
            result.total = count;

            /* Get number of aborted goals */
            UserGoals.count({user: req.user._id, status: 'aborted'}).exec(function(err, count) {
              console.log(err);
              if (err) {
                return res.status(400).send({
                  message: errorHandler.getErrorMessage(err)
                });
              } else {
                result.aborted = count;
                res.json(result);
              }
            });
          }
        });
      }
  });
};

/**
 * Middleware for userGoals
 * @param req
 * @param res
 * @param next
 * @param id
 */
exports.userGoalByID = function(req, res, next, id) {
  UserGoals.findById(id).populate('goal').exec(function(err, goal) {
    if (err) return next(err);
    if (!goal) return next(new Error('Failed to load user goal ' + id));
    req.userGoal = goal;
    next();
  });
};

/**
 * Check if user is creator of user goal
 * @param req
 * @param res
 * @param next
 * @returns {*}
 */
exports.hasAuthorization = function(req, res, next) {
  if (req.userGoal.user.toString() !== req.user.id) {
    return res.status(403).send({
      message: 'User is not authorized'
    });
  }
  next();
};
<commit_msg>Fix for showing goal groups<commit_after>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
    _ = require('lodash'),
    errorHandler = require('./errors.server.controller'),
    UserGoals = mongoose.model('UserGoals'),
    Goal = mongoose.model('Goal'),
    tincan = require('./tincan.server.controller.js');

/**
 * Create a User goal
 */
exports.create = function(req, res) {
  var goal = req.body.goal;
  var userGoals = new UserGoals(_.omit(req.body, 'goal'));
  userGoals.user = req.user;
  userGoals.goal = goal._id;

  userGoals.save(function(err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      /* Increment committed field in goal */
      Goal.update({_id: userGoals.goal}, {$inc: {committed: 1}}, function(err) {
        if (err) {
          return res.status(400).send({
            message: errorHandler.getErrorMessage(err)
          });
        } else {
          /* Send statement to LRS if committed to goal */
          if(userGoals.status === 'committed') {
            tincan.committedToGoal(req.user.email, req.user.displayName);
          }

          res.json(userGoals);
        }
      });

    }
  });
};

/**
 * Show the current User goal
 */
exports.read = function(req, res) {
  res.json(req.userGoal);
};

/**
 * Update a User goal
 */
exports.update = function(req, res) {
  var tags = _.pluck(req.body.tags, 'text');
  var requestBody = _.extend(_.omit(req.body, 'tags'), {tags: tags});
  var userGoal = _.extend(req.userGoal, requestBody);

  UserGoals.findById(userGoal._id).exec(function(err, oldGoal) {
    /* Changed finished date if finished value is flipped */
    if(oldGoal.finished !== userGoal.finished) {
      userGoal.finishedDate = new Date();

      /* Send tincan statement to LRS */
      if(userGoal.finished) {
        tincan.finishedGoal(req.user.email, req.user.displayName);
      }
    }

    /* Check if any subgoals are finished and send to LRS */
    _.each(userGoal.subgoals, function(subgoal) {
      _.each(oldGoal.subgoals, function(oldSubgoal) {
        if(subgoal.finished && oldSubgoal.finished === false) {
          tincan.progressedGoal(req.user.email, req.user.displayName);
        }
      });
    });

    userGoal.save(function(err) {
      if (err) {
        return res.status(400).send({
          message: errorHandler.getErrorMessage(err)
        });
      } else {
        res.json(userGoal);
      }
    });
  });
};

/**
 * Abort a goal
 * @param req
 * @param res
 */
exports.abort = function(req, res) {
  var userGoal = req.userGoal;
  userGoal.status = 'aborted';

  userGoal.save(function(err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      tincan.abortedGoal(req.user.email, req.user.displayName);
      res.json(userGoal);
    }
  });
};

/**
 * List of User goals
 */
exports.list = function(req, res) {
  UserGoals.find({user: req.user, status: 'committed', $or: [{group: null}, {grouped:{$gt: 0}}]}).populate('goal').sort('-created').exec(function(err, userGoals) {
    if (err) {
      console.log(err);
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {

      res.json(userGoals);
    }
  });
};

/**
 * Get user goals by group id
 * @param req
 * @param res
 */
exports.listByGroup = function(req, res) {
  UserGoals.find({group: req.param('userGoalGroupId')}).populate('goal').sort('-created').exec(function(err, userGoals) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {

      res.json(userGoals);
    }
  });
};

exports.getGoalStatistics = function(req, res) {
  var result = {};
  /* Count completed goals */
  UserGoals.aggregate(
    {
      $match: {
        'finishedDate': {$exists: true},
        'user': req.user._id
      }
    },
    {
      $sort: {
        'finishedDate': -1
      }
    },
    {
      $group:  {
        _id : {
          finishedDate: {
            day: {$dayOfMonth: 'finishedDate'},
            month: {$month: 'finishedDate'},
            year: {$year: 'finishedDate'}
          }
        },
        total: {$sum: 1}
      }
    }).exec(function(err, finished) {
      console.log(err);
      if (err) {
        return res.status(400).send({
          message: errorHandler.getErrorMessage(err)
        });
      } else {
        result.finished = finished;

        /* Count total number of goals */
        UserGoals.count({user: req.user._id}).exec(function(err, count) {
          console.log(err);
          if (err) {
            return res.status(400).send({
              message: errorHandler.getErrorMessage(err)
            });
          } else {
            result.total = count;

            /* Get number of aborted goals */
            UserGoals.count({user: req.user._id, status: 'aborted'}).exec(function(err, count) {
              console.log(err);
              if (err) {
                return res.status(400).send({
                  message: errorHandler.getErrorMessage(err)
                });
              } else {
                result.aborted = count;
                res.json(result);
              }
            });
          }
        });
      }
  });
};

/**
 * Middleware for userGoals
 * @param req
 * @param res
 * @param next
 * @param id
 */
exports.userGoalByID = function(req, res, next, id) {
  UserGoals.findById(id).populate('goal').exec(function(err, goal) {
    if (err) return next(err);
    if (!goal) return next(new Error('Failed to load user goal ' + id));
    req.userGoal = goal;
    next();
  });
};

/**
 * Check if user is creator of user goal
 * @param req
 * @param res
 * @param next
 * @returns {*}
 */
exports.hasAuthorization = function(req, res, next) {
  if (req.userGoal.user.toString() !== req.user.id) {
    return res.status(403).send({
      message: 'User is not authorized'
    });
  }
  next();
};
<|endoftext|>


<commit_before>import React from 'react'
import I18n from 'i18n!new_user_tutorial'
import plainStoreShape from 'jsx/shared/proptypes/plainStoreShape'
import Tray from 'instructure-ui/lib/components/Tray'
import Button from 'instructure-ui/lib/components/Button'
import NewUserTutorialToggleButton from '../NewUserTutorialToggleButton'
import ConfirmEndTutorialDialog from '../ConfirmEndTutorialDialog'

class TutorialTray extends React.Component {

  static propTypes = {
    // Used as a label for the content (screenreader-only)
    label: React.PropTypes.string.isRequired,
    // The specific tray that will be wrapped, unusable without this.
    children: React.PropTypes.node.isRequired,
    // The store to control the status of everything
    store: React.PropTypes.shape(plainStoreShape).isRequired,
    // Should return an element that focus can be set to
    returnFocusToFunc: React.PropTypes.func.isRequired
  }

  constructor (props) {
    super(props);
    this.state = {
      ...props.store.getState(),
      endUserTutorialShown: false
    };
  }

  componentDidMount () {
    this.props.store.addChangeListener(this.handleStoreChange)
  }

  componentWillUnmount () {
    this.props.store.removeChangeListener(this.handleStoreChange)
  }

  handleStoreChange = () => {
    this.setState(this.props.store.getState());
  }

  handleToggleClick = () => {
    this.props.store.setState({
      isCollapsed: !this.state.isCollapsed
    });
  }

  handleEndTutorialClick = () => {
    this.setState({
      endUserTutorialShown: true
    });
  }

  closeEndTutorialDialog = () => {
    this.setState({
      endUserTutorialShown: false
    });
    if (this.endTutorialButton) {
      this.endTutorialButton.focus();
    }
  }

  handleEntering = () => {
    this.toggleButton.focus()
  }

  handleExiting = () => {
    this.props.returnFocusToFunc().focus();
  }

  render () {
    return (
      <Tray
        label={this.props.label}
        isDismissable={false}
        isOpen={!this.state.isCollapsed}
        placement="right"
        zIndex="100"
        onEntering={this.handleEntering}
        onExiting={this.handleExiting}
      >

            <NewUserTutorialToggleButton
              ref={(c) => { this.toggleButton = c; }}
              onClick={this.handleToggleClick}
              store={this.props.store}
            />

          {this.props.children}

            <Button
              onClick={this.handleEndTutorialClick}
              ref={(c) => { this.endTutorialButton = c; }}
            >
              {I18n.t('End Tutorial')}
            </Button>

          <ConfirmEndTutorialDialog
            isOpen={this.state.endUserTutorialShown}
            handleRequestClose={this.closeEndTutorialDialog}
          />

      </Tray>
    );
  }
}

export default TutorialTray
<commit_msg>Add onEntered callback to tutorial tray<commit_after>import React from 'react'
import I18n from 'i18n!new_user_tutorial'
import plainStoreShape from 'jsx/shared/proptypes/plainStoreShape'
import Tray from 'instructure-ui/lib/components/Tray'
import Button from 'instructure-ui/lib/components/Button'
import NewUserTutorialToggleButton from '../NewUserTutorialToggleButton'
import ConfirmEndTutorialDialog from '../ConfirmEndTutorialDialog'

class TutorialTray extends React.Component {

  static propTypes = {
    // Used as a label for the content (screenreader-only)
    label: React.PropTypes.string.isRequired,
    // The specific tray that will be wrapped, unusable without this.
    children: React.PropTypes.node.isRequired,
    // The store to control the status of everything
    store: React.PropTypes.shape(plainStoreShape).isRequired,
    // Should return an element that focus can be set to
    returnFocusToFunc: React.PropTypes.func.isRequired
  }

  constructor (props) {
    super(props);
    this.state = {
      ...props.store.getState(),
      endUserTutorialShown: false
    };
  }

  componentDidMount () {
    this.props.store.addChangeListener(this.handleStoreChange)
  }

  componentWillUnmount () {
    this.props.store.removeChangeListener(this.handleStoreChange)
  }

  handleStoreChange = () => {
    this.setState(this.props.store.getState());
  }

  handleToggleClick = () => {
    this.props.store.setState({
      isCollapsed: !this.state.isCollapsed
    });
  }

  handleEndTutorialClick = () => {
    this.setState({
      endUserTutorialShown: true
    });
  }

  closeEndTutorialDialog = () => {
    this.setState({
      endUserTutorialShown: false
    });
    if (this.endTutorialButton) {
      this.endTutorialButton.focus();
    }
  }

  handleEntering = () => {
    this.toggleButton.focus()
  }

  handleExiting = () => {
    this.props.returnFocusToFunc().focus();
  }

  render () {
    return (
      <Tray
        label={this.props.label}
        isDismissable={false}
        isOpen={!this.state.isCollapsed}
        placement="right"
        zIndex="100"
        onEntering={this.handleEntering}
        onExiting={this.handleExiting}
        onEntered={this.handleEntering}
      >

            <NewUserTutorialToggleButton
              ref={(c) => { this.toggleButton = c; }}
              onClick={this.handleToggleClick}
              store={this.props.store}
            />

          {this.props.children}

            <Button
              onClick={this.handleEndTutorialClick}
              ref={(c) => { this.endTutorialButton = c; }}
            >
              {I18n.t('End Tutorial')}
            </Button>

          <ConfirmEndTutorialDialog
            isOpen={this.state.endUserTutorialShown}
            handleRequestClose={this.closeEndTutorialDialog}
          />

      </Tray>
    );
  }
}

export default TutorialTray
<|endoftext|>


<commit_before>//customer.component.js
'use strict';

angular.
module('customer').
component('customer', {
    templateUrl: 'main/profile/vendor/customer.template.html',
    controller: ['$scope',
        function СarrierController($scope) {
            //this.some = 0
        }
    ]
});
<commit_msg>customer<commit_after>//customer.component.js
'use strict';

angular.
module('customer').
component('customer', {
    templateUrl: 'main/profile/customer/customer.template.html',
    controller: ['$scope',
        function СarrierController($scope) {
            //this.some = 0
        }
    ]
});
<|endoftext|>


<commit_before>/* global angular Firebase */
(function(){
  'use strict';

  angular.module('iron-pong')
    .controller('LeaderboardController',
      function($scope, $filter, $firebase, $firebaseArray, ngTableParams){

        $scope.players = [
          {avatar_url: 'http://lorempixel.com/120/120/people/1', login: 'sjoyal',
          wins: 55, losses: 14, pct: .757, games: 69},
          {avatar_url: 'http://lorempixel.com/120/120/people/2', login: 'pcreglow',
          wins: 40, losses: 30, pct: .568, games: 70},
          {avatar_url: 'http://lorempixel.com/120/120/people/3', login: 'jorgehjr84',
          wins: 8, losses: 40, pct: .213, games: 48},
          {avatar_url: 'http://lorempixel.com/120/120/people/5', login: 'gatorpazz',
          wins: 0, losses: 0, pct: .000, games: 0},
          {avatar_url: 'http://lorempixel.com/120/120/people/6', login: 'jessyriordan',
          wins: 0, losses: 0, pct: .000, games: 0},
          {avatar_url: 'http://lorempixel.com/120/120/people/7', login: 'mstaehling',
          wins: 0, losses: 0, pct: .000, games: 0},
          {avatar_url: 'http://lorempixel.com/120/120/people/4', login: 'al-the-x',
          wins: 0, losses: 125, pct: .000, games: 125}
        ] // END players

        $scope.tableParams = new ngTableParams({
          sorting: {
            wins: 'desc'  // initial sorting
          }
        }, {
          getData: function($defer, params){
            $scope.players = $filter('orderBy')($scope.players, params.orderBy());
              $defer.resolve($scope.players);
          }
        });
      }); // END LeaderboardController

})();
<commit_msg>flag in the sand, need live dataz in the leaderboard table<commit_after>/* global angular Firebase */
(function(){
  'use strict';

  angular.module('iron-pong')
    .controller('LeaderboardController',
      function($scope, $filter, $firebase, $firebaseArray, ngTableParams){

      // FIXME: Pull and munge data for live stuff in the leaderboardz
        $scope.players = [
          {avatar_url: 'http://lorempixel.com/120/120/people/1', login: 'sjoyal',
          wins: 55, losses: 14, pct: .757, games: 69},
          {avatar_url: 'http://lorempixel.com/120/120/people/2', login: 'pcreglow',
          wins: 40, losses: 30, pct: .568, games: 70},
          {avatar_url: 'http://lorempixel.com/120/120/people/3', login: 'jorgehjr84',
          wins: 8, losses: 40, pct: .213, games: 48},
          {avatar_url: 'http://lorempixel.com/120/120/people/5', login: 'gatorpazz',
          wins: 0, losses: 0, pct: .000, games: 0},
          {avatar_url: 'http://lorempixel.com/120/120/people/6', login: 'jessyriordan',
          wins: 0, losses: 0, pct: .000, games: 0},
          {avatar_url: 'http://lorempixel.com/120/120/people/7', login: 'mstaehling',
          wins: 0, losses: 0, pct: .000, games: 0},
          {avatar_url: 'http://lorempixel.com/120/120/people/4', login: 'al-the-x',
          wins: 0, losses: 125, pct: .000, games: 125}
        ] // END players

        $scope.tableParams = new ngTableParams({
          sorting: {
            wins: 'desc'  // initial sorting
          }
        }, {
          getData: function($defer, params){
            $scope.players = $filter('orderBy')($scope.players, params.orderBy());
              $defer.resolve($scope.players);
          }
        });
      }); // END LeaderboardController

})();
<|endoftext|>


<commit_before>/*
  Setup user details for exception handling
 */

App.then(function(app) {
    App.CurrentUser.find('current').then(function(user) {
        if (typeof Raven == 'object') {
            Raven.setUser({
                id: user.get('id_for_ember'),
                name: user.get('full_name'),
                email: user.get('email'),
            });
        }
    });

    // Override the BB project / status search list
    // TODO: we should just define the 'list' when initializing
    //       and then BB should use it when setting up the list
    App.ProjectPhase.find().then(function(data){
        var list = [
            {id: 5, name: gettext("Running campaigns")},
            {id: [7,8], name: gettext("Finished campaigns")}
        ];
        App.ProjectPhaseSelectView.reopen({
            content: list
        });
    });

    // Facebook API ID
    if (FACEBOOK_AUTH_ID)
        App.set('appId', FACEBOOK_AUTH_ID);

    app.fbLogin = function (fbResponse) {
        var _this = this,
            currentUsercontroller = App.__container__.lookup('controller:currentUser');

        // Clear any existing tokens which might be present but expired. clearJwtToken action is on the App.ApplicationRoute
        // FIXME: should call the clearJwtToken action here but it isn't being called.
        // currentUsercontroller.send('clearJwtToken');
        delete localStorage['jwtToken'];
        App.set('jwtToken', null);

        return Ember.RSVP.Promise(function (resolve, reject) {
            var hash = {
              url: "/api/social-login/facebook/",
              dataType: "json",
              type: 'post',
              data: fbResponse
            };

            hash.success = function (response) {

                App.AuthJwt.processSuccessResponse(response).then(function (user) {

                    // If success
                    currentUsercontroller.set('model', user);
                    currentUsercontroller.send('close');

                    if (user.get('firstLogin')) {
                        currentUsercontroller.send('setFlash', currentUsercontroller.get('welcomeMessage'));
                    }

                    Ember.run(null, resolve, user);
                    // Trigger next transition in case a user was accesing a restricted page
                    currentUsercontroller.send('loadNextTransition');

                 }, function (error) {
                    // If Facebook login succeeded but something goes wrong on the token side we end up here
                    currentUsercontroller.send('setFlash', error, 'error');
                    Ember.run(null, reject, error);
                });
            };

            hash.error = function (response) {

                currentUsercontroller.send('setFlash', gettext('There was an error connecting Facebook'), 'error');
                var error = JSON.parse(response.responseText);
                Ember.run(null, reject, error);
            };

            Ember.$.ajax(hash);
        });
    };
});

/*
  Bluebottle Route Overrides
 */

App.ApplicationRoute.reopen(App.LogoutJwtMixin, {
    init: function () {
        this._super();

        // Set the facebook appId
        // TODO: move this to the server side settings
        this.set('appId', '1438115069790112');
    },

    actions: {
        logout: function (redirect) {
            // call the standard logout code => clear JWT token etc
            this._super(redirect);

            // If the has logged in via FB, eg there is a FBUser then they should
            // be logged out so that the user can log in with user/email
            if (FB && !Em.isEmpty(FB.getUserID()))
                FB.logout()
        },
        addDonation: function (project, fundraiser) {
            var route = this;
            App.CurrentOrder.find('current').then(function(order) {
                var store = route.get('store');

                var projectHasDonation = order.get('donations').anyBy('project', project);
                var fundraiserHasDonation = false;
                if(fundraiser !== undefined){
                    fundraiserHasDonation = order.get('donations').anyBy('fundraiser', fundraiser);
                }

                // TODO: functional test this.
                // *  Donate directly to project: check if no direct donations exist
                // *  Donate through fundraiser: check if donation for that fundraiser exists
                // *  We can have the same project multiple times, but all different fundraisers

                if (fundraiserHasDonation ||
                    (projectHasDonation && !fundraiserHasDonation && fundraiser === undefined)) {
                    // Donation for this already exists in this order.
                } else {
                    var donation = store.createRecord(App.CurrentOrderDonation);
                    donation.set('project', project);
                    if(fundraiser !== undefined){
                        donation.set('fundraiser', fundraiser);
                    }
                    donation.set('order', order);
                    donation.save();
                }
                route.transitionTo('currentOrder.donationList');
            });
        }
    }
});

/*
  Bluebottle Controller Overrides
 */
App.ApplicationController.reopen({
    needs: ['currentOrder', 'myProjectList'],

    missingCurrentUser: function () {
        // FIXME: should call the clearJwtToken action here but it isn't being called.
        delete localStorage['jwtToken'];
        App.set('jwtToken', null);
    },
});

App.EventMixin = Em.Mixin.create({

  bindScrolling: function(opts) {
    var onScroll, self = this;

    onScroll = function() {
      var scrollTop = $(this).scrollTop();
      return self.scrolled(scrollTop);
    };

    $(window).bind('scroll', onScroll);
    $(document).bind('touchmove', onScroll);
  },

  unbindScrolling: function () {
    $(window).unbind('scroll');
    $(document).unbind('touchmove');
  },

  bindMobileClick: function() {
    toggleMenu = function() {
      $('.mobile-nav-holder').toggleClass('is-active');
    };

    closeMenu = function(event) {
      $('.mobile-nav-holder').removeClass('is-active');
    };

    $('.mobile-nav-btn').bind('click', toggleMenu);
    $('#content').bind('hover', closeMenu);
  }
});

/*
  Bluebottle View Overrides
*/

App.ApplicationView.reopen(App.EventMixin, {
    setBindScrolling: function() {
        this.bindScrolling();
    }.on('didInsertElement'),

    setUnbindScrolling: function() {
        this.unbindScrolling();
    }.on('didInsertElement'),

    setBindClick: function() {
        this.bindMobileClick();
    }.on('didInsertElement'),

    scrolled: function(dist) {
        top = $('#content').offset();
        elm = top.screen.availTop;

        if (dist <= 53) {
            $('#header').removeClass('is-scrolled');
            $('.nav-member-dropdown').removeClass('is-scrolled');
            $('.mobile-nav-holder').removeClass('is-scrolled');
            $('#content').append('

');
        } else {
            $('#header').addClass('is-scrolled');
            $('.nav-member-dropdown').addClass('is-scrolled');
            $('.mobile-nav-holder').addClass('is-scrolled');
        }
    }
});

// Enable Google Ad Words with Ember
App.Router.reopen({

    // If you want to add Google conversion codes to a route just add:
    // googleConversion: {
    //      label: 'my_page_label'
    // }

    didTransition: function(infos) {
        this._super(infos);

        var currentRoute = infos.get('lastObject').handler;
        var gc = currentRoute.get('googleConversion');
        Ember.run.next(function() {
            if (gc &! DEBUG) {
                var google_conversion_id = gc.id || 986941294;
                var google_conversion_language = gc.language || 'en';
                var google_conversion_format = gc.format || '3';
                var google_conversion_color = gc.color || 'ffffff';
                var google_conversion_label = gc.label;
                var google_remarketing_only = false;
                $.getScript("https://www.googleadservices.com/pagead/conversion.js");
            }
        });
    }
});
<commit_msg>Update app_overrides.js<commit_after>/*
  Setup user details for exception handling
 */

App.then(function(app) {
    App.CurrentUser.find('current').then(function(user) {
        if (typeof Raven == 'object') {
            Raven.setUser({
                id: user.get('id_for_ember'),
                name: user.get('full_name'),
                email: user.get('email'),
            });
        }
    });

    // Override the BB project / status search list
    // TODO: we should just define the 'list' when initializing
    //       and then BB should use it when setting up the list
    App.ProjectPhase.find().then(function(data){
        var list = [
            {id: 5, name: gettext("Running campaigns")},
            {id: [7,8], name: gettext("Finished campaigns")}
        ];
        App.ProjectPhaseSelectView.reopen({
            content: list
        });
    });

    // Facebook API ID
    if (FACEBOOK_AUTH_ID)
        App.set('appId', FACEBOOK_AUTH_ID);

    app.fbLogin = function (fbResponse) {
        var _this = this,
            currentUsercontroller = App.__container__.lookup('controller:currentUser');

        // Clear any existing tokens which might be present but expired. clearJwtToken action is on the App.ApplicationRoute
        // FIXME: should call the clearJwtToken action here but it isn't being called.
        // currentUsercontroller.send('clearJwtToken');
        delete localStorage['jwtToken'];
        App.set('jwtToken', null);

        return Ember.RSVP.Promise(function (resolve, reject) {
            var hash = {
              url: "/api/social-login/facebook/",
              dataType: "json",
              type: 'post',
              data: fbResponse
            };

            hash.success = function (response) {

                App.AuthJwt.processSuccessResponse(response).then(function (user) {

                    // If success
                    currentUsercontroller.set('model', user);
                    currentUsercontroller.send('close');

                    if (user.get('firstLogin')) {
                        currentUsercontroller.send('setFlash', currentUsercontroller.get('welcomeMessage'));
                    }

                    Ember.run(null, resolve, user);

                    // Trigger next transition in case a user was accesing a restricted page
                    currentUsercontroller.send('loadNextTransition');

                 }, function (error) {
                    // If Facebook login succeeded but something goes wrong on the token side we end up here
                    currentUsercontroller.send('setFlash', error, 'error');
                    Ember.run(null, reject, error);
                });
            };

            hash.error = function (response) {

                currentUsercontroller.send('setFlash', gettext('There was an error connecting Facebook'), 'error');
                var error = JSON.parse(response.responseText);
                Ember.run(null, reject, error);
            };

            Ember.$.ajax(hash);
        });
    };
});

/*
  Bluebottle Route Overrides
 */

App.ApplicationRoute.reopen(App.LogoutJwtMixin, {
    init: function () {
        this._super();

        // Set the facebook appId
        // TODO: move this to the server side settings
        this.set('appId', '1438115069790112');
    },

    actions: {
        logout: function (redirect) {
            // call the standard logout code => clear JWT token etc
            this._super(redirect);

            // If the has logged in via FB, eg there is a FBUser then they should
            // be logged out so that the user can log in with user/email
            if (FB && !Em.isEmpty(FB.getUserID()))
                FB.logout()
        },
        addDonation: function (project, fundraiser) {
            var route = this;
            App.CurrentOrder.find('current').then(function(order) {
                var store = route.get('store');

                var projectHasDonation = order.get('donations').anyBy('project', project);
                var fundraiserHasDonation = false;
                if(fundraiser !== undefined){
                    fundraiserHasDonation = order.get('donations').anyBy('fundraiser', fundraiser);
                }

                // TODO: functional test this.
                // *  Donate directly to project: check if no direct donations exist
                // *  Donate through fundraiser: check if donation for that fundraiser exists
                // *  We can have the same project multiple times, but all different fundraisers

                if (fundraiserHasDonation ||
                    (projectHasDonation && !fundraiserHasDonation && fundraiser === undefined)) {
                    // Donation for this already exists in this order.
                } else {
                    var donation = store.createRecord(App.CurrentOrderDonation);
                    donation.set('project', project);
                    if(fundraiser !== undefined){
                        donation.set('fundraiser', fundraiser);
                    }
                    donation.set('order', order);
                    donation.save();
                }
                route.transitionTo('currentOrder.donationList');
            });
        }
    }
});

/*
  Bluebottle Controller Overrides
 */
App.ApplicationController.reopen({
    needs: ['currentOrder', 'myProjectList'],

    missingCurrentUser: function () {
        // FIXME: should call the clearJwtToken action here but it isn't being called.
        delete localStorage['jwtToken'];
        App.set('jwtToken', null);
    },
});

App.EventMixin = Em.Mixin.create({

  bindScrolling: function(opts) {
    var onScroll, self = this;

    onScroll = function() {
      var scrollTop = $(this).scrollTop();
      return self.scrolled(scrollTop);
    };

    $(window).bind('scroll', onScroll);
    $(document).bind('touchmove', onScroll);
  },

  unbindScrolling: function () {
    $(window).unbind('scroll');
    $(document).unbind('touchmove');
  },

  bindMobileClick: function() {
    toggleMenu = function() {
      $('.mobile-nav-holder').toggleClass('is-active');
    };

    closeMenu = function(event) {
      $('.mobile-nav-holder').removeClass('is-active');
    };

    $('.mobile-nav-btn').bind('click', toggleMenu);
    $('#content').bind('hover', closeMenu);
  }
});

/*
  Bluebottle View Overrides
*/

App.ApplicationView.reopen(App.EventMixin, {
    setBindScrolling: function() {
        this.bindScrolling();
    }.on('didInsertElement'),

    setUnbindScrolling: function() {
        this.unbindScrolling();
    }.on('didInsertElement'),

    setBindClick: function() {
        this.bindMobileClick();
    }.on('didInsertElement'),

    scrolled: function(dist) {
        top = $('#content').offset();
        elm = top.screen.availTop;

        if (dist <= 53) {
            $('#header').removeClass('is-scrolled');
            $('.nav-member-dropdown').removeClass('is-scrolled');
            $('.mobile-nav-holder').removeClass('is-scrolled');
            $('#content').append('

');
        } else {
            $('#header').addClass('is-scrolled');
            $('.nav-member-dropdown').addClass('is-scrolled');
            $('.mobile-nav-holder').addClass('is-scrolled');
        }
    }
});

// Enable Google Ad Words with Ember
App.Router.reopen({

    // If you want to add Google conversion codes to a route just add:
    // googleConversion: {
    //      label: 'my_page_label'
    // }

    didTransition: function(infos) {
        this._super(infos);

        var currentRoute = infos.get('lastObject').handler;
        var gc = currentRoute.get('googleConversion');
        Ember.run.next(function() {
            if (gc &! DEBUG) {
                var google_conversion_id = gc.id || 986941294;
                var google_conversion_language = gc.language || 'en';
                var google_conversion_format = gc.format || '3';
                var google_conversion_color = gc.color || 'ffffff';
                var google_conversion_label = gc.label;
                var google_remarketing_only = false;
                $.getScript("https://www.googleadservices.com/pagead/conversion.js");
            }
        });
    }
});
<|endoftext|>


<commit_before>var _ = require('lodash');

module.exports = function jacksMergeProcessor(log) {
	return {
		$runAfter: ['computePathsProcessor'],
		$runBefore: ['renderDocsProcessor'],
		$process: function (docs) {

			// var jsDocs = docs.filter(function(doc) {
			// 	if (doc.docType === 'js'){
			// 		return true;
			// 	}
			// });

			// jsDocs.forEach(function(jsdoc, idx, arr) {
			// 	// todo:
			// 	// 1. 	a. update path
			// 	// 		b. create a new doctype for method
			// 	// 		c. ignore the doc, add directly to the angular stuff as dependencies
			// 	// 2. remove the element if it is added to a parent
			// 	jsdoc.codeNode.type === 'FunctionDeclaration'
			// });
			// 1. do some stuff with docs
			// 2. update path
			// 3. add reference link to parent service or directive
			// find the memberof tag
			// check type from doc.codeNode.type: e.g. FunctionDeclaration

			docs.forEach( function(doc, idx, docs) {
				if (doc.docType === 'js') {
					// todo:
					// 1. 	a. update path
					// 		b. create a new doctype for method
					// 		c. ignore the doc, add directly to the angular stuff as dependencies
					// 2. remove the element if it is added to a parent

					var tags = doc.tags.tags;
					var memberofTag = _.find(tags, function(tag) {
						if(tag.tagName === 'memberof'){
							return true;
						}
					});

					if (typeof memberofTag !== 'undefined'){
						var parentName = memberofTag.description;

						log.debug("memberof: " + parentName);
						// find the associated doc e.g. service or directive
						var parentIdx = _.findIndex(docs, function(a) {
							return a.name === parentName;
						});

						log.debug("doc id:"+ doc.id + ", parentIdx:" + parentIdx + ", memberof:" + parentName);

						if(parentIdx > -1){

							var parentDoc = docs[parentIdx];

							if (! parentDoc.hasOwnProperty('methods')) {
								// add methods
								parentDoc.methods = [];
							}

							parentDoc.methods.push({
								"name": doc.id,
								"description": doc.description
							});
						}
					}

					// update doc type
					doc.docType = "gcMethod";

				}
			});

			return docs;
		}
	};
};<commit_msg>ref(dgeni processor): using lodash filters<commit_after>var _ = require('lodash');

module.exports = function jacksMergeProcessor(log) {
	return {
		$runAfter: ['computePathsProcessor'],
		$runBefore: ['renderDocsProcessor'],
		$process: function (docs) {

			// var jsDocs = docs.filter(function(doc) {
			// 	if (doc.docType === 'js'){
			// 		return true;
			// 	}
			// });

			// jsDocs.forEach(function(jsdoc, idx, arr) {
			// 	// todo:
			// 	// 1. 	a. update path
			// 	// 		b. create a new doctype for method
			// 	// 		c. ignore the doc, add directly to the angular stuff as dependencies
			// 	// 2. remove the element if it is added to a parent
			// 	jsdoc.codeNode.type === 'FunctionDeclaration'
			// });
			// 1. do some stuff with docs
			// 2. update path
			// 3. add reference link to parent service or directive
			// find the memberof tag
			// check type from doc.codeNode.type: e.g. FunctionDeclaration

			ngServiceDocs = _.filter(docs, { docType: 'ngService'});

			ngDirectiveDocs = _.filter(docs, {docType: 'ngDirective'});

			ngControllerDocs = _.filter(docs, {docType: 'ngController'});

			jsDocs = _.filter(docs, {docType: 'js'});

			jsDocs = _.filter(docs, function(doc) {
				var tags = doc.tags.tags;
				return _.find(tags, function(tag) {
					if(tag.tagName === 'memberof') {
						return true;
					}
					return false;
				});
			});

			jsDocsWithMemberOf = _(docs).filter({docType: 'js'})
										.filter(function(doc) {
											var tags = doc.tags.tags;
											return _.find(tags, function(tag) {
												if(tag.tagName === 'memberof') {
													return true;
												}
												return false;
											});
										})
										.value();

			docs.forEach( function(doc, idx, docs) {
				if (doc.docType === 'js') {
					// todo:
					// 1. 	a. update path
					// 		b. create a new doctype for method
					// 		c. ignore the doc, add directly to the angular stuff as dependencies
					// 2. remove the element if it is added to a parent

					var tags = doc.tags.tags;
					var memberofTag = _.find(tags, function(tag) {
						if(tag.tagName === 'memberof'){
							return true;
						}
					});

					if (typeof memberofTag !== 'undefined'){
						var parentName = memberofTag.description;

						log.debug("memberof: " + parentName);
						// find the associated doc e.g. service or directive
						var parentIdx = _.findIndex(docs, function(a) {
							return a.name === parentName;
						});

						log.debug("doc id:"+ doc.id + ", parentIdx:" + parentIdx + ", memberof:" + parentName);

						if(parentIdx > -1){

							var parentDoc = docs[parentIdx];

							if (! parentDoc.hasOwnProperty('methods')) {
								// add methods
								parentDoc.methods = [];
							}

							parentDoc.methods.push({
								"name": doc.id,
								"description": doc.description
							});
						}
					}

					// update doc type
					doc.docType = "gcMethod";

				}
			});

			return docs;
		}
	};
};<|endoftext|>


<commit_before>define([
    'knockout',
    'underscore',
    'knockout-mapping'
], function(ko, _, koMapping) {
    var WorkflowStep = function(config) {
        this.classUnvisited = 'workflow-step-icon';
        this.classActive = 'workflow-step-icon active';
        this.classComplete = 'workflow-step-icon complete';
        this.icon = 'fa-chevron-circle-right';
        this.title = '';
        this.subtitle = '';
        this.description = '';
        this.complete = ko.observable(false);
        this.active = ko.computed(function() {
            return config.workflow.activeStep() === this;
        }, this);

        this.value = function(){
            return {};
        };

        Object.keys(config).forEach(function(prop){
            if(prop !== 'workflow') {
                config[prop] = koMapping.fromJS(config[prop]);
            }
        });

        _.extend(this, config);

        this.iconClass = ko.computed(function(){
            var ret = '';
            if(this.active()){
                ret = this.classActive;
            }else if(this.complete()){
                ret = this.classComplete;
            }else {
                ret = this.classUnvisited;
            }
            return ret + ' ' + ko.unwrap(this.icon);
        }, this);
    };
    return WorkflowStep;
});
<commit_msg>Adds default requirements property to workflow steps. re #4821<commit_after>define([
    'knockout',
    'underscore',
    'knockout-mapping'
], function(ko, _, koMapping) {
    var WorkflowStep = function(config) {
        this.classUnvisited = 'workflow-step-icon';
        this.classActive = 'workflow-step-icon active';
        this.classComplete = 'workflow-step-icon complete';
        this.icon = 'fa-chevron-circle-right';
        this.title = '';
        this.subtitle = '';
        this.description = '';
        this.complete = ko.observable(false);
        this.active = ko.computed(function() {
            return config.workflow.activeStep() === this;
        }, this);

        this.requirements = {};

        this.value = function(){
            return {};
        };

        Object.keys(config).forEach(function(prop){
            if(prop !== 'workflow') {
                config[prop] = koMapping.fromJS(config[prop]);
            }
        });

        _.extend(this, config);

        this.iconClass = ko.computed(function(){
            var ret = '';
            if(this.active()){
                ret = this.classActive;
            }else if(this.complete()){
                ret = this.classComplete;
            }else {
                ret = this.classUnvisited;
            }
            return ret + ' ' + ko.unwrap(this.icon);
        }, this);
    };
    return WorkflowStep;
});
<|endoftext|>