<commit_before>define([
    "modules/jquery-mozu",
    "underscore",
    "modules/backbone-mozu",
    "modules/api",
    "hyprlivecontext",
    "hyprlive"
],function ($, _, Backbone, api, HyprLiveContext, Hypr) {

    var AwsCheckoutPage = Backbone.MozuModel.extend({
            mozuType: 'order',
            awsData: null,
            handlesMessages: true,
            initialize: function (data) {
                var self = this;
                _.bindAll(this, "submit");

            },
            applyShippingMethods: function(existingShippingMethodCode) {
                var me = this;
                //me.isLoading( true);
                me.apiModel.getShippingMethods().then(
                    function (methods) {

                        if (methods.length === 0) {
                            me.onCheckoutError(Hypr.getLabel("awsNoShippingOptions"));
                        }

                        var shippingMethod = "";
                        if (existingShippingMethodCode)
                            shippingMethod = _.findWhere(methods, {shippingMethodCode: existingShippingMethodCode});

                        if (!shippingMethod || !shippingMethod.shippingMethodCode)
                            shippingMethod =_.min(methods, function(method){return method.price;});

                        var fulfillmentInfo = me.get("fulfillmentInfo");
                        fulfillmentInfo.shippingMethodCode = shippingMethod.shippingMethodCode;
                        fulfillmentInfo.shippingMethodName = shippingMethod.shippingMethodName;
                        me.apiModel.update({ fulfillmentInfo: fulfillmentInfo}).then(
                            function() {
                                //me.isLoading (false);
                                me.set("fulfillmentInfo", fulfillmentInfo);
                                me.applyBilling();
                            });
                    });
            },
            applyBilling: function() {
                var me = this;
                //me.isLoading (true);

                return api.all.apply(api,_.map(_.filter(me.apiModel.getActivePayments(), function(payment) {
                    return payment.paymentType !== "StoreCredit" && payment.paymentType !== "GiftCard";
                }), function(payment) {
                    return me.apiVoidPayment(payment.id);
                })).then(function() {
                    return me.apiGet();
                }).then(function(order) {
                    console.log(order);
                    return me.applyPayment();
                });
            },
            applyPayment: function() {
                var me = this;
                if (me.get("amountRemainingForPayment") < 0) {
                    me.trigger('awscheckoutcomplete', me.id);
                    return;
                }
                 var billingInfo = {
                    "newBillingInfo" :
                    {
                        "paymentType": "PayWithAmazon",
                        "paymentWorkflow": "PayWithAmazon",
                        "card" : null,
                        "billingContact" : {
                            "email": me.get("fulfillmentInfo").fulfillmentContact.email
                        },
                        "orderId" : me.id,
                        "isSameBillingShippingAddress" : false
                    },
                    "externalTransactionId" : me.awsData.awsReferenceId
                };

                me.apiCreatePayment(billingInfo).then( function() {
                    me.trigger('awscheckoutcomplete', me.id);
                    me.isLoading(false);
               }, function(err) {
                    me.isLoading(false);
               });
            },
            submit: function() {
                var me = this;
                me.isLoading(true);
                var fulfillmentInfo = me.get("fulfillmentInfo"),
                    existingShippingMethodCode = fulfillmentInfo.shippingMethodCode;

                if (me.awsData === null)
                    me.awsData = fulfillmentInfo.data;
                else
                    fulfillmentInfo.data = me.awsData;

                me.apiUpdateShippingInfo( fulfillmentInfo ).then(function(result) {
                    me.set("fulfillmentInfo",result.data);
                    //me.isLoading(false);
                    if (me.apiModel.data.requiresFulfillmentInfo)
                        me.applyShippingMethods(existingShippingMethodCode);
                    else
                        me.applyBilling();
                });
            },
             onCheckoutError: function (msg) {
                var me = this,
                    errorHandled = false,
                    error = {};
                    //me.messages.add(msg || Hypr.getLabel('unknownError'));
                me.isLoading(false);
                error = {
                        items: [
                            {
                                message: msg || Hypr.getLabel('unknownError')
                            }
                        ]
                    };
                this.trigger('error', error);
                throw error;
            }
        });

    return {
            AwsCheckoutPage: AwsCheckoutPage
        };
});<commit_msg>Fix bug # 73731 - User registered shopper email insteand of amazon email during checkout<commit_after>define([
    "modules/jquery-mozu",
    "underscore",
    "modules/backbone-mozu",
    "modules/api",
    "hyprlivecontext",
    "hyprlive"
],function ($, _, Backbone, api, HyprLiveContext, Hypr) {

    var AwsCheckoutPage = Backbone.MozuModel.extend({
            mozuType: 'order',
            awsData: null,
            handlesMessages: true,
            initialize: function (data) {
                var self = this;
                _.bindAll(this, "submit");

            },
            applyShippingMethods: function(existingShippingMethodCode) {
                var me = this;
                //me.isLoading( true);
                me.apiModel.getShippingMethods().then(
                    function (methods) {

                        if (methods.length === 0) {
                            me.onCheckoutError(Hypr.getLabel("awsNoShippingOptions"));
                        }

                        var shippingMethod = "";
                        if (existingShippingMethodCode)
                            shippingMethod = _.findWhere(methods, {shippingMethodCode: existingShippingMethodCode});

                        if (!shippingMethod || !shippingMethod.shippingMethodCode)
                            shippingMethod =_.min(methods, function(method){return method.price;});

                        var fulfillmentInfo = me.get("fulfillmentInfo");
                        fulfillmentInfo.shippingMethodCode = shippingMethod.shippingMethodCode;
                        fulfillmentInfo.shippingMethodName = shippingMethod.shippingMethodName;
                        me.apiModel.update({ fulfillmentInfo: fulfillmentInfo}).then(
                            function() {
                                //me.isLoading (false);
                                me.set("fulfillmentInfo", fulfillmentInfo);
                                me.applyBilling();
                            });
                    });
            },
            applyBilling: function() {
                var me = this;
                //me.isLoading (true);

                return api.all.apply(api,_.map(_.filter(me.apiModel.getActivePayments(), function(payment) {
                    return payment.paymentType !== "StoreCredit" && payment.paymentType !== "GiftCard";
                }), function(payment) {
                    return me.apiVoidPayment(payment.id);
                })).then(function() {
                    return me.apiGet();
                }).then(function(order) {
                    console.log(order);
                    return me.applyPayment();
                });
            },
            applyPayment: function() {
                var me = this;
                if (me.get("amountRemainingForPayment") < 0) {
                    me.trigger('awscheckoutcomplete', me.id);
                    return;
                }
                var user = require.mozuData('user');
                 var billingInfo = {
                    "newBillingInfo" :
                    {
                        "paymentType": "PayWithAmazon",
                        "paymentWorkflow": "PayWithAmazon",
                        "card" : null,
                        "billingContact" : {
                            "email": (user.email !== "" ? user.email : me.get("fulfillmentInfo").fulfillmentContact.email)
                        },
                        "orderId" : me.id,
                        "isSameBillingShippingAddress" : false
                    },
                    "externalTransactionId" : me.awsData.awsReferenceId
                };

                me.apiCreatePayment(billingInfo).then( function() {
                    me.trigger('awscheckoutcomplete', me.id);
                    me.isLoading(false);
               }, function(err) {
                    me.isLoading(false);
               });
            },
            submit: function() {
                var me = this;
                me.isLoading(true);
                var fulfillmentInfo = me.get("fulfillmentInfo"),
                    existingShippingMethodCode = fulfillmentInfo.shippingMethodCode;

                if (me.awsData === null)
                    me.awsData = fulfillmentInfo.data;
                else
                    fulfillmentInfo.data = me.awsData;

                me.apiUpdateShippingInfo( fulfillmentInfo ).then(function(result) {
                    me.set("fulfillmentInfo",result.data);
                    //me.isLoading(false);
                    if (me.apiModel.data.requiresFulfillmentInfo)
                        me.applyShippingMethods(existingShippingMethodCode);
                    else
                        me.applyBilling();
                });
            },
             onCheckoutError: function (msg) {
                var me = this,
                    errorHandled = false,
                    error = {};
                    //me.messages.add(msg || Hypr.getLabel('unknownError'));
                me.isLoading(false);
                error = {
                        items: [
                            {
                                message: msg || Hypr.getLabel('unknownError')
                            }
                        ]
                    };
                this.trigger('error', error);
                throw error;
            }
        });

    return {
            AwsCheckoutPage: AwsCheckoutPage
        };
});<|endoftext|>


<commit_before>import * as actions from './auth-actions';

export const initialState = {
  session: !!sessionStorage.getItem('token')
};

export default {
  [actions.logInSuccess]: (state, { payload }) => ({ ...state, session: payload }),
  [actions.logOutSuccess]: (state, { payload }) => ({ ...state, session: payload })
};
<commit_msg>Pushed forgotten file<commit_after>import * as actions from './auth-actions';

export const initialState = {
  session: !!localStorage.getItem('token')
};

export default {
  [actions.logInSuccess]: (state, { payload }) => ({ ...state, session: payload }),
  [actions.logOutSuccess]: (state, { payload }) => ({ ...state, session: payload })
};
<|endoftext|>


<commit_before>Lizard.Views.WorkspaceItem = Backbone.Marionette.ItemView.extend({
  template: '#workspaceitem-template',
  tagName: 'li',
  className: 'drawer-item',
  initialize: function () {
    this.model.bind('change:selected change:visibility', this.render, this);
  },
  onBeforeRender: function () {
    this.el.setAttribute("id", this.model.cid);
  },
  onRender: function() {
    var that = this;
    that.$el.find('.opacity-slider').slider({
        value: that.model.get('opacity'),
        min: 0,
        max: 100,
        range: "min",
        step: 1,
        create: function( event, ui ) {
          //that.model.unbind('change:opacity'); // This prevents the item from re-rendering...
        },
        slide: function( event, ui ) {
          that.model.set('opacity', ui.value);
        },
        stop: function( event, ui ) {
          that.model.set('opacity', ui.value);
          $('.top-right').notify({
            message: {
              text: 'Zichtbaarheid van kaartlaag "' + that.model.get('display_name') + '" is nu ' + ui.value + '%'
            }}).show();
        }
    });
  },
  events: {
    'click .layer-item .indicator': 'toggleVisibility',
    'click .layer-item .content': 'select',
    'click .layer-item .toggle-layer-configuration': 'toggleLayerConfiguration',
    'click .layer-item .btn-delete-layer': 'removeLayer'
  },
  removeLayer: function(e) {
    // The collection belonging to this model, is not the same
    // as the workspace it is in.
    this.model.trigger('removeItem', this.model);
  },
  toggleLayerConfiguration: function() {
    $(this.el).find('.layer-configuration').toggle('fast');
    $(this.el).find('.toggle-layer-configuration i').toggleClass('chevron-closed chevron-open');
  },
  toggleVisibility: function () {
    if(this.model.attributes.visibility) {
      this.model.set({ visibility: false });
    } else {
      this.model.set({ visibility: true });
    }
  },
  select: function(e) {
    if(this.model.get('selected') === false) {
      this.model.collection.each(function(workspaceItem) {
        workspaceItem.set('selected', false);
      });
      this.model.set('selected', true);
      //this.model.trigger('select_layer', this.model);
    }
  }
});

Lizard.Views.ActiveWorkspace = Backbone.Marionette.CollectionView.extend({
  collection: new Lizard.Collections.Layer(), //layerCollection,
  tagName: 'ol',
  className: 'ui-sortable drawer-group wms_sources',
  itemView: Lizard.Views.WorkspaceItem,
  emptyView: Marionette.ItemView.extend({
    template: "#empty-workspace-list-message"
  }),
  events: {
    drop: 'drop'
  },
  initialize: function() {
    this.collection.listenTo(this.collection, 'reset', this.render);
    this.collection.listenTo(this.collection, 'removeItem', this.removeItem);
    this.collection.listenTo(this.collection, 'add remove', this.render);
    // this.on('render', this.afterRender, this);
  },
  _initialEvents: function(){
    //this.collection.on("removeItems", this.onItemRemoveds, this);
  },
  drop: function(event, args) {
    this.collection.move(args.item, args.index);
    this.collection.updateOrderFieldOfItems();
  },
  setWorkspace: function(workspace) {
    this.model = workspace;
    this.collection.reset(workspace.get('workspaceitems').models);
  },
  removeItem: function(model) {
    this.remove(model);
  },
  onShow: function () {
    var that = this;
    $('.drawer-group').sortable({
      stop: function(event, ui) {
        var item = that.collection.get({cid: ui.item.attr('id')});
        ui.item.trigger('drop', {
          item: item,
          index: ui.item.index()
        });
      }
    });
    $('.drawer-group').disableSelection();
  },
  getCollection: function() {
    return this.collection;
  },
  onClose: function(){
    this.collection.off('reset removeItem add remove');
  }
});

<commit_msg>Changing mousecursor into crosshair when a layer is selected to indicate the GetFeatureInfo feature<commit_after>Lizard.Views.WorkspaceItem = Backbone.Marionette.ItemView.extend({
  template: '#workspaceitem-template',
  tagName: 'li',
  className: 'drawer-item',
  initialize: function () {
    this.model.bind('change:selected change:visibility', this.render, this);
  },
  onBeforeRender: function () {
    this.el.setAttribute("id", this.model.cid);
  },
  onClose: function() {
    $('#map').css('cursor', 'pointer');
  },
  onRender: function() {
    var that = this;
    that.$el.find('.opacity-slider').slider({
        value: that.model.get('opacity'),
        min: 0,
        max: 100,
        range: "min",
        step: 1,
        create: function( event, ui ) {
          //that.model.unbind('change:opacity'); // This prevents the item from re-rendering...
        },
        slide: function( event, ui ) {
          that.model.set('opacity', ui.value);
        },
        stop: function( event, ui ) {
          that.model.set('opacity', ui.value);
          $('.top-right').notify({
            message: {
              text: 'Zichtbaarheid van kaartlaag "' + that.model.get('display_name') + '" is nu ' + ui.value + '%'
            }}).show();
        }
    });
  },
  events: {
    'click .layer-item .indicator': 'toggleVisibility',
    'click .layer-item .content': 'select',
    'click .layer-item .toggle-layer-configuration': 'toggleLayerConfiguration',
    'click .layer-item .btn-delete-layer': 'removeLayer'
  },
  removeLayer: function(e) {
    // The collection belonging to this model, is not the same
    // as the workspace it is in.
    this.model.trigger('removeItem', this.model);
  },
  toggleLayerConfiguration: function() {
    $(this.el).find('.layer-configuration').toggle('fast');
    $(this.el).find('.toggle-layer-configuration i').toggleClass('chevron-closed chevron-open');
  },
  toggleVisibility: function () {
    if(this.model.attributes.visibility) {
      this.model.set({ visibility: false });
    } else {
      this.model.set({ visibility: true });
    }
  },
  select: function(e) {
    if(this.model.get('selected') === false) {
      this.model.collection.each(function(workspaceItem) {
        workspaceItem.set('selected', false);
        $('#map').css('cursor', 'pointer');
      });
      this.model.set('selected', true);
      $('#map').css('cursor', 'crosshair');
      //this.model.trigger('select_layer', this.model);
    }
  }
});

Lizard.Views.ActiveWorkspace = Backbone.Marionette.CollectionView.extend({
  collection: new Lizard.Collections.Layer(), //layerCollection,
  tagName: 'ol',
  className: 'ui-sortable drawer-group wms_sources',
  itemView: Lizard.Views.WorkspaceItem,
  emptyView: Marionette.ItemView.extend({
    template: "#empty-workspace-list-message"
  }),
  events: {
    drop: 'drop'
  },
  initialize: function() {
    this.collection.listenTo(this.collection, 'reset', this.render);
    this.collection.listenTo(this.collection, 'removeItem', this.removeItem);
    this.collection.listenTo(this.collection, 'add remove', this.render);
    // this.on('render', this.afterRender, this);
  },
  _initialEvents: function(){
    //this.collection.on("removeItems", this.onItemRemoveds, this);
  },
  drop: function(event, args) {
    this.collection.move(args.item, args.index);
    this.collection.updateOrderFieldOfItems();
  },
  setWorkspace: function(workspace) {
    this.model = workspace;
    this.collection.reset(workspace.get('workspaceitems').models);
  },
  removeItem: function(model) {
    this.remove(model);
  },
  onShow: function () {
    var that = this;
    $('.drawer-group').sortable({
      stop: function(event, ui) {
        var item = that.collection.get({cid: ui.item.attr('id')});
        ui.item.trigger('drop', {
          item: item,
          index: ui.item.index()
        });
      }
    });
    $('.drawer-group').disableSelection();
  },
  getCollection: function() {
    return this.collection;
  },
  onClose: function(){
    this.collection.off('reset removeItem add remove');
  }
});

<|endoftext|>


<commit_before>'use strict';

/**
 * @ngdoc service
 * @name helmeditor2App.HELMNotationService
 * @description
 * # HELMNotationService
 * Service in the helmeditor2App.
 */
angular.module('helmeditor2App')
  .service('HELMNotationService', function () {
    var self = this;

    // store the current HELM string
    var helm = '';
    var sequences = [];
    var connections = [];

    // parses a given helm string into the sequences and connections
    var parseHelm = function (helmString) {
      // store the whole string
      helm = helmString;
      sequences = [];
      connections = [];

      // if we have something, try to get everything out of it
      if (helm.length > 0) {
        // get the sequences
        var sequenceString = helmString.substring(0, helmString.indexOf('$'));
        while (sequenceString.indexOf('|') > -1) {
          var strSequence = sequenceString.substring(0, sequenceString.indexOf('|'));
          if (strSequence.length > 0) {
            sequences.push(parseSequenceString(strSequence));
          }
          sequenceString = sequenceString.substring(sequenceString.indexOf('|') + 1);
        }
        // and the last one
        if (sequenceString.length > 0) {
          sequences.push(parseSequenceString(sequenceString));
        }

        // and get the connections
        helmString = helmString.substring(helmString.indexOf('$') + 1);
        var connectionString = helmString.substring(0, helmString.indexOf('$'));
        while (connectionString.indexOf('|') > -1) {
          var strConnection = connectionString.substring(0, connectionString.indexOf('|'));
          if (strConnection.length > 0) {
            connections.push(parseConnectionString(strConnection));
          }
          connectionString = connectionString.substring(connectionString.indexOf('|') + 1);
        }
        // and the last one
        if (connectionString.length > 0) {
          connections.push(parseConnectionString(connectionString));
        }
      }
    };

    // parses a single sequence string into its parts
    var parseSequenceString = function (sequenceString) {
      var sequence = {};
      sequence.name = sequenceString.substring(0, sequenceString.indexOf('{'));
      sequence.notation = sequenceString.substring(sequenceString.indexOf('{') + 1 , sequenceString.indexOf('}'));
      return sequence;
    };

    // parses a single connection string into its parts
    var parseConnectionString = function (connectionString) {
      var connection = {};
      connection.source = {};
      connection.dest = {};
      connection.source.sequenceName = connectionString.substring(0, connectionString.indexOf(','));
      connectionString = connectionString.substring(connectionString.indexOf(',') + 1);
      connection.dest.sequenceName = connectionString.substring(0, connectionString.indexOf(','));
      connectionString = connectionString.substring(connectionString.indexOf(',') + 1);
      connection.source.attachment = {};
      connection.source.attachment.nodeNum = connectionString.substring(0, connectionString.indexOf(':'));
      connectionString = connectionString.substring(connectionString.indexOf(':') + 1);
      connection.source.attachment.point = connectionString.substring(0, connectionString.indexOf('-'));
      connectionString = connectionString.substring(connectionString.indexOf('-') + 1);
      connection.dest.attachment = {};
      connection.dest.attachment.nodeNum = connectionString.substring(0, connectionString.indexOf(':'));
      connectionString = connectionString.substring(connectionString.indexOf(':') + 1);
      connection.dest.attachment.point = connectionString;
      return connection;
    };

    // retrieve the current HELM string
    var getHelm = function () {
      return helm;
    };

    // set the current helm string
    var setHelm = function (helmString) {
      parseHelm(helmString);
    };

    // retrieve the sequences
    var getSequences = function () {
      return sequences;
    };

    // retrieve the connections
    var getConnections = function () {
      return connections;
    };

    // add the new sequence to the current HELM string
    // type - must be RNA, PEPTIDE, or CHEM
    // notation should be the sequence of characters
    var addNewSequence = function (type, notation) {
      console.log(sequences);
      // see what label we need to add to the type for the new sequence
      var postfix = 1; // start at 1
      for (var i = 0; i < sequences.length; i++) {
        if (sequences[i].name.indexOf(type) === 0) {
          var num = parseInt(sequences[i].name.substring(type.length));
          postfix = postfix > num ? postfix : num + 1;
        }
      }

      // create our new sequence
      var sequence = {
        name: type + postfix,
        notation: notation
      };

      sequences.push(sequence);

      // and generate the new HELM notation
      updateHelm();
    };

    // private helper function to update the HELM notation from any added sequences
    var updateHelm = function () {
      // go through the sequences and generate the first blob
      var res = '';
      for (var i = 0; i < sequences.length; i++) {
        res = res + sequences[i].name + '{' + sequences[i].notation + '}';
        // only apply the | if there are more
        if (i < (sequences.length - 1)) {
          res = res + '|';
        }
      }

      console.log(res);

      // and swap it in
      if (helm === '') {
        helm = res + '$$$$';
      }
      else {
        helm = res + helm.substring(helm.indexOf('$'));
      }

      console.log(helm);
      // make sure to parse connections
      parseHelm(helm);
    };

    // make things global
    self.getHelm = getHelm;
    self.setHelm = setHelm;
    self.getSequences = getSequences;
    self.getConnections = getConnections;
    self.addNewSequence = addNewSequence;
  });
<commit_msg>remove logging lines from helm functions<commit_after>'use strict';

/**
 * @ngdoc service
 * @name helmeditor2App.HELMNotationService
 * @description
 * # HELMNotationService
 * Service in the helmeditor2App.
 */
angular.module('helmeditor2App')
  .service('HELMNotationService', function () {
    var self = this;

    // store the current HELM string
    var helm = '';
    var sequences = [];
    var connections = [];

    // parses a given helm string into the sequences and connections
    var parseHelm = function (helmString) {
      // store the whole string
      helm = helmString;
      sequences = [];
      connections = [];

      // if we have something, try to get everything out of it
      if (helm.length > 0) {
        // get the sequences
        var sequenceString = helmString.substring(0, helmString.indexOf('$'));
        while (sequenceString.indexOf('|') > -1) {
          var strSequence = sequenceString.substring(0, sequenceString.indexOf('|'));
          if (strSequence.length > 0) {
            sequences.push(parseSequenceString(strSequence));
          }
          sequenceString = sequenceString.substring(sequenceString.indexOf('|') + 1);
        }
        // and the last one
        if (sequenceString.length > 0) {
          sequences.push(parseSequenceString(sequenceString));
        }

        // and get the connections
        helmString = helmString.substring(helmString.indexOf('$') + 1);
        var connectionString = helmString.substring(0, helmString.indexOf('$'));
        while (connectionString.indexOf('|') > -1) {
          var strConnection = connectionString.substring(0, connectionString.indexOf('|'));
          if (strConnection.length > 0) {
            connections.push(parseConnectionString(strConnection));
          }
          connectionString = connectionString.substring(connectionString.indexOf('|') + 1);
        }
        // and the last one
        if (connectionString.length > 0) {
          connections.push(parseConnectionString(connectionString));
        }
      }
    };

    // parses a single sequence string into its parts
    var parseSequenceString = function (sequenceString) {
      var sequence = {};
      sequence.name = sequenceString.substring(0, sequenceString.indexOf('{'));
      sequence.notation = sequenceString.substring(sequenceString.indexOf('{') + 1 , sequenceString.indexOf('}'));
      return sequence;
    };

    // parses a single connection string into its parts
    var parseConnectionString = function (connectionString) {
      var connection = {};
      connection.source = {};
      connection.dest = {};
      connection.source.sequenceName = connectionString.substring(0, connectionString.indexOf(','));
      connectionString = connectionString.substring(connectionString.indexOf(',') + 1);
      connection.dest.sequenceName = connectionString.substring(0, connectionString.indexOf(','));
      connectionString = connectionString.substring(connectionString.indexOf(',') + 1);
      connection.source.attachment = {};
      connection.source.attachment.nodeNum = connectionString.substring(0, connectionString.indexOf(':'));
      connectionString = connectionString.substring(connectionString.indexOf(':') + 1);
      connection.source.attachment.point = connectionString.substring(0, connectionString.indexOf('-'));
      connectionString = connectionString.substring(connectionString.indexOf('-') + 1);
      connection.dest.attachment = {};
      connection.dest.attachment.nodeNum = connectionString.substring(0, connectionString.indexOf(':'));
      connectionString = connectionString.substring(connectionString.indexOf(':') + 1);
      connection.dest.attachment.point = connectionString;
      return connection;
    };

    // retrieve the current HELM string
    var getHelm = function () {
      return helm;
    };

    // set the current helm string
    var setHelm = function (helmString) {
      parseHelm(helmString);
    };

    // retrieve the sequences
    var getSequences = function () {
      return sequences;
    };

    // retrieve the connections
    var getConnections = function () {
      return connections;
    };

    // add the new sequence to the current HELM string
    // type - must be RNA, PEPTIDE, or CHEM
    // notation should be the sequence of characters
    var addNewSequence = function (type, notation) {
      // see what label we need to add to the type for the new sequence
      var postfix = 1; // start at 1
      for (var i = 0; i < sequences.length; i++) {
        if (sequences[i].name.indexOf(type) === 0) {
          var num = parseInt(sequences[i].name.substring(type.length));
          postfix = postfix > num ? postfix : num + 1;
        }
      }

      // create our new sequence
      var sequence = {
        name: type + postfix,
        notation: notation
      };

      sequences.push(sequence);

      // and generate the new HELM notation
      updateHelm();
    };

    // private helper function to update the HELM notation from any added sequences
    var updateHelm = function () {
      // go through the sequences and generate the first blob
      var res = '';
      for (var i = 0; i < sequences.length; i++) {
        res = res + sequences[i].name + '{' + sequences[i].notation + '}';
        // only apply the | if there are more
        if (i < (sequences.length - 1)) {
          res = res + '|';
        }
      }

      // and swap it in
      if (helm === '') {
        helm = res + '$$$$';
      }
      else {
        helm = res + helm.substring(helm.indexOf('$'));
      }

      // make sure to parse connections
      parseHelm(helm);
    };

    // make things global
    self.getHelm = getHelm;
    self.setHelm = setHelm;
    self.getSequences = getSequences;
    self.getConnections = getConnections;
    self.addNewSequence = addNewSequence;
  });
<|endoftext|>


<commit_before>/*jshint -W027*/

(function() {
  'use strict';

  angular.module('dimApp')
    .directive('dimStoreItem', StoreItem);

  StoreItem.$inject = ['dimStoreService', 'ngDialog', 'dimLoadoutService'];

  function StoreItem(dimStoreService, ngDialog, dimLoadoutService) {
    return {
      bindToController: true,
      controller: StoreItemCtrl,
      controllerAs: 'vm',
      link: Link,
      replace: true,
      scope: {
        'store': '=storeData',
        'item': '=itemData'
      },
      template: [
        '<div ui-draggable="{{ (vm.item.type !== \'Lost Items\') && (vm.item.type !== \'Missions\') && (vm.item.type !== \'Bounties\') && (vm.item.type !== \'Special Orders\') && (vm.item.type !== \'Messages\')  }}" id="item-{{:: $id }}" drag-channel="{{ (vm.item.notransfer) ? vm.item.owner + vm.item.type : vm.item.type }}" title="{{ vm.item.primStat.value }} {{ vm.item.name }}" alt="{{ vm.item.primStat.value }} {{ vm.item.name }}" drag="\'item-\' + $id" class="item" ng-class="{ \'search-hidden\': !vm.item.visible, \'search-item-hidden\': vm.item.visible === false && vm.hideFilteredItems === true, \'complete\': vm.item.complete }">',
        '

',
        '
 1">{{ vm.item.amount }}
',
        '
{{vm.item.xpComplete}}%
',
        '

',
        '
{{ vm.item.primStat.value }}
',
        '
'
      ].join('')
    };

    function Link(scope, element, attrs) {
      var vm = scope.vm;
      var dialogResult = null;

      $('').attr('src', 'http://www.bungie.net' + vm.item.icon).load(function() {
         $(this).remove(); // prevent memory leaks as @benweet suggested
        //  $('body').css('background-image', 'url(http://www.bungie.net' + vm.item.icon + ')');
        element[0].querySelector('.img')
          .style.backgroundImage = 'url(' + 'http://www.bungie.net' + vm.item.icon + ')';
      }).error(function() {
         $(this).remove(); // prevent memory leaks as @benweet suggested
        //  $('body').css('background-image', 'url(' + chrome.extension.getURL(vm.item.icon) + ')');
        element[0].querySelector('.img')
          .style.backgroundImage = 'url(' + chrome.extension.getURL(vm.item.icon) + ')';
      });

      // element[0].querySelector('.img')
      //   .style.backgroundImage = 'url(' + 'http://www.bungie.net' + vm.item.icon + ')';

      vm.clicked = function openPopup(item, e) {
        e.stopPropagation();

        if (!_.isNull(dialogResult)) {
          dialogResult.close();
        } else {
          ngDialog.closeAll();

          if (!dimLoadoutService.dialogOpen) {
            var bottom = ($(element).offset().top < 300) ? ' move-popup-bottom' : '';
            var right = ((($('body').width() - $(element).offset().left - 320) < 0) ? ' move-popup-right' : '');

            dialogResult = ngDialog.open({
              template: '

',
              plain: true,
              appendTo: 'div[id="item-' + scope.$id + '"]',
              overlay: false,
              className: 'move-popup' + right +  bottom,
              showClose: false,
              scope: scope
            });

            // if (($('body').width() - $(element).offset().left - 320) < 0) {
            //   $('.ngdialog.move-popup').css('left', $('body').width() - $(element).offset().left - 340);
            // }

            dialogResult.closePromise.then(function(data) {
              dialogResult = null;
            });
          } else {
            dimLoadoutService.addItemToLoadout(item);
          }
        }
      };

      vm.closePopup = function closePopup() {
        if (!_.isNull(dialogResult)) {
          dialogResult.close();
        }
      };
    }
  }

  StoreItemCtrl.$inject = ['$rootScope', 'dimSettingsService'];

  function StoreItemCtrl($rootScope, settings) {
    var vm = this;

    vm.hideFilteredItems = false;
    vm.itemStat = false;

    settings.getSetting('itemStat')
      .then(function(itemStat) {
        vm.itemStat = itemStat;
      });

    settings.getSetting('hideFilteredItems')
      .then(function(hideFilteredItems) {
        vm.hideFilteredItems = hideFilteredItems;
      });

    $rootScope.$on('dim-settings-updated', function(event, arg) {
      if (_.has(arg, 'hideFilteredItems')) {
        vm.hideFilteredItems = arg.hideFilteredItems;
      }

      if (_.has(arg, 'itemStat')) {
        vm.itemStat = arg.itemStat;
      }
    });

    vm.itemClicked = function clicked(item) {
      $rootScope.$broadcast('dim-store-item-clicked', {
        item: item
      });
    };
  }
})();
<commit_msg>hide stat badge on classified items.<commit_after>/*jshint -W027*/

(function() {
  'use strict';

  angular.module('dimApp')
    .directive('dimStoreItem', StoreItem);

  StoreItem.$inject = ['dimStoreService', 'ngDialog', 'dimLoadoutService'];

  function StoreItem(dimStoreService, ngDialog, dimLoadoutService) {
    return {
      bindToController: true,
      controller: StoreItemCtrl,
      controllerAs: 'vm',
      link: Link,
      replace: true,
      scope: {
        'store': '=storeData',
        'item': '=itemData'
      },
      template: [
        '<div ui-draggable="{{ (vm.item.type !== \'Lost Items\') && (vm.item.type !== \'Missions\') && (vm.item.type !== \'Bounties\') && (vm.item.type !== \'Special Orders\') && (vm.item.type !== \'Messages\')  }}" id="item-{{:: $id }}" drag-channel="{{ (vm.item.notransfer) ? vm.item.owner + vm.item.type : vm.item.type }}" title="{{ vm.item.primStat.value }} {{ vm.item.name }}" alt="{{ vm.item.primStat.value }} {{ vm.item.name }}" drag="\'item-\' + $id" class="item" ng-class="{ \'search-hidden\': !vm.item.visible, \'search-item-hidden\': vm.item.visible === false && vm.hideFilteredItems === true, \'complete\': vm.item.complete }">',
        '

',
        '
 1">{{ vm.item.amount }}
',
        '
{{vm.item.xpComplete}}%
',
        '

',
        '
{{ vm.item.primStat.value }}
',
        '
'
      ].join('')
    };

    function Link(scope, element, attrs) {
      var vm = scope.vm;
      var dialogResult = null;

      $('').attr('src', 'http://www.bungie.net' + vm.item.icon).load(function() {
         $(this).remove(); // prevent memory leaks as @benweet suggested
        //  $('body').css('background-image', 'url(http://www.bungie.net' + vm.item.icon + ')');
        element[0].querySelector('.img')
          .style.backgroundImage = 'url(' + 'http://www.bungie.net' + vm.item.icon + ')';
      }).error(function() {
         $(this).remove(); // prevent memory leaks as @benweet suggested
        //  $('body').css('background-image', 'url(' + chrome.extension.getURL(vm.item.icon) + ')');
        element[0].querySelector('.img')
          .style.backgroundImage = 'url(' + chrome.extension.getURL(vm.item.icon) + ')';
      });

      // element[0].querySelector('.img')
      //   .style.backgroundImage = 'url(' + 'http://www.bungie.net' + vm.item.icon + ')';

      vm.clicked = function openPopup(item, e) {
        e.stopPropagation();

        if (!_.isNull(dialogResult)) {
          dialogResult.close();
        } else {
          ngDialog.closeAll();

          if (!dimLoadoutService.dialogOpen) {
            var bottom = ($(element).offset().top < 300) ? ' move-popup-bottom' : '';
            var right = ((($('body').width() - $(element).offset().left - 320) < 0) ? ' move-popup-right' : '');

            dialogResult = ngDialog.open({
              template: '

',
              plain: true,
              appendTo: 'div[id="item-' + scope.$id + '"]',
              overlay: false,
              className: 'move-popup' + right +  bottom,
              showClose: false,
              scope: scope
            });

            // if (($('body').width() - $(element).offset().left - 320) < 0) {
            //   $('.ngdialog.move-popup').css('left', $('body').width() - $(element).offset().left - 340);
            // }

            dialogResult.closePromise.then(function(data) {
              dialogResult = null;
            });
          } else {
            dimLoadoutService.addItemToLoadout(item);
          }
        }
      };

      vm.closePopup = function closePopup() {
        if (!_.isNull(dialogResult)) {
          dialogResult.close();
        }
      };
    }
  }

  StoreItemCtrl.$inject = ['$rootScope', 'dimSettingsService'];

  function StoreItemCtrl($rootScope, settings) {
    var vm = this;

    vm.hideFilteredItems = false;
    vm.itemStat = false;

    settings.getSetting('itemStat')
      .then(function(itemStat) {
        vm.itemStat = itemStat;
      });

    settings.getSetting('hideFilteredItems')
      .then(function(hideFilteredItems) {
        vm.hideFilteredItems = hideFilteredItems;
      });

    $rootScope.$on('dim-settings-updated', function(event, arg) {
      if (_.has(arg, 'hideFilteredItems')) {
        vm.hideFilteredItems = arg.hideFilteredItems;
      }

      if (_.has(arg, 'itemStat')) {
        vm.itemStat = arg.itemStat;
      }
    });

    vm.itemClicked = function clicked(item) {
      $rootScope.$broadcast('dim-store-item-clicked', {
        item: item
      });
    };
  }
})();
<|endoftext|>


<commit_before>const sendMail = require('../utils/sendMail');
const getGroupUserEmail = require('../utils/getGroupUserEmail');
const getGroupUserPhoneNumber = require('../utils/getGroupUserPhoneNumber');

const Message = require('../models').Message;
const User = require('../models').User;
const Group = require('../models').Group;
const ReadMessage = require('../models').ReadMessage;
// Method to post message
exports.post_message = (req, res) => {
  if (req.body.message === '') {
    return res.status(404).send({ status: false,
      message: 'message body cannot be empty' });
  }
  const userId = req.decoded.data.id;
  Group.findById(req.params.id)
  .then((group) => {
    if (!group) {
      return res.send({
        status: 400,
        message: 'You cannot post to a group that does not exists'
      });
    }
  });
  Message.create({
    message_body: req.body.message,
    priority_level: req.body.priority,
    read_by: [userId],
    group_id: req.params.id,
    user_id: userId,
  })
  .then((message) => {
    // method to get all emails
    const { data, emailUsers } = getGroupUserEmail(req.params.id,
      message, req.decoded.data);
    switch (req.body.priority) {
    case 'Critical':
      sendMail(emailUsers, message.message_body);
      return res.status(201).send({
        data
      });
    case 'Urgent':
      const { status, payload } = sendMail(emailUsers, message.message_body);
      if (!status) {
        return res.status(400).send({
          message: 'Error sending message',
          error: payload
        });
      }
      return res.status(201).send({
        data: payload
      });
    default:
      return res.status(201).send({
        data: {
          id: message.id,
          message_body: message.message_body,
          priority_level: message.priority_level,
          createdAt: message.createdAt,
          User: {
            id: req.decoded.data.id,
            username: req.decoded.data.username
          }
        }
      });
    }
  })
  .catch(err => (
    res.status(500).send(err, 'An error occurred, try again')
  ));
};

// Method to get Messages
exports.get_messages = (req, res) => {
  const userId = req.decoded.data.id;
  const groupId = parseInt(req.params.id, 10);
  if (isNaN(groupId)) {
    return res.status(400).send({
      message: 'Group id must be an integer'
    });
  }
  Message.findAll({
    where: { group_id: groupId },
    attributes:
    ['id', 'message_body', 'priority_level', 'group_id', 'createdAt'],
    include: [{
      model: User,
      attributes: ['id', 'username', 'email'],
    }]
  })
  .then((messages) => {
    if (messages) {
      return res.status(200).send({
        messages
      });
    }
    res.status(400).send({ message: 'No messages to display' });
  });
};

// Method to record message views
exports.message_views = (req, res) => {
  const userId = req.decoded.data.id;
  Message.findOne({
    where: {
      id: req.body.messageId
    }
  })
  .then((message) => {
    if (message) {
      ReadMessage.findOne({
        where: {
          $and: [{ message_id: message.id }, { user_id: userId }]
        }
      })
      .then((response) => {
        if (response) {
          return res.status(400).send({ message: 'Message viewed already' });
        }
        ReadMessage.create({
          message_id: message.id,
          user_id: userId,
          group_id: message.group_id,
        })
        .then(() => res.status(200).send({ message: 'Message created!' }))
        .catch(error => res.status(400)
        .send({ message: 'An error occured!', error }));
      })
      .catch((error) => {
        res.status(400).send({ error, message: 'An error occured, try again' });
      });
    }
  })
  .catch((error) => {
    res.status(400).send({ error, message: 'An error occured, try again' });
  });
};
<commit_msg>fix app crashing issue<commit_after>const sendMail = require('../utils/sendMail');
const getGroupUserEmail = require('../utils/getGroupUserEmail');
const getGroupUserPhoneNumber = require('../utils/getGroupUserPhoneNumber');

const Message = require('../models').Message;
const User = require('../models').User;
const Group = require('../models').Group;
const ReadMessage = require('../models').ReadMessage;
// Method to post message
exports.post_message = (req, res) => {
  if (req.body.message === '') {
    return res.status(404).send({ status: false,
      message: 'message body cannot be empty' });
  }
  const userId = req.decoded.data.id;
  Group.findById(req.params.id)
  .then((group) => {
    if (!group) {
      return res.send({
        status: 400,
        message: 'You cannot post to a group that does not exists'
      });
    }
  });
  Message.create({
    message_body: req.body.message,
    priority_level: req.body.priority,
    read_by: [userId],
    group_id: req.params.id,
    user_id: userId,
  })
  .then((message) => {
    // method to get all emails
    const { data, emailUsers } = getGroupUserEmail(req.params.id,
      message, req.decoded.data);
    switch (req.body.priority) {
    case 'Critical':
      sendMail(emailUsers, message.message_body);
      return res.status(201).send({
        data
      });
    case 'Urgent':
      sendMail(emailUsers, message.message_body);
      // const { status, payload } = sendMail(emailUsers, message.message_body);
      // if (!status) {
      //   return res.status(400).send({
      //     message: 'Error sending message',
      //     error: payload
      //   });
      // }
      return res.status(201).send({
        data
      });
    default:
      return res.status(201).send({
        data: {
          id: message.id,
          message_body: message.message_body,
          priority_level: message.priority_level,
          createdAt: message.createdAt,
          User: {
            id: req.decoded.data.id,
            username: req.decoded.data.username
          }
        }
      });
    }
  })
  .catch(err => (
    res.status(500).send(err, 'An error occurred, try again')
  ));
};

// Method to get Messages
exports.get_messages = (req, res) => {
  const userId = req.decoded.data.id;
  const groupId = parseInt(req.params.id, 10);
  if (isNaN(groupId)) {
    return res.status(400).send({
      message: 'Group id must be an integer'
    });
  }
  Message.findAll({
    where: { group_id: groupId },
    attributes:
    ['id', 'message_body', 'priority_level', 'group_id', 'createdAt'],
    include: [{
      model: User,
      attributes: ['id', 'username', 'email'],
    }]
  })
  .then((messages) => {
    if (messages) {
      return res.status(200).send({
        messages
      });
    }
    res.status(400).send({ message: 'No messages to display' });
  });
};

// Method to record message views
exports.message_views = (req, res) => {
  const userId = req.decoded.data.id;
  Message.findOne({
    where: {
      id: req.body.messageId
    }
  })
  .then((message) => {
    if (message) {
      ReadMessage.findOne({
        where: {
          $and: [{ message_id: message.id }, { user_id: userId }]
        }
      })
      .then((response) => {
        if (response) {
          return res.status(400).send({ message: 'Message viewed already' });
        }
        ReadMessage.create({
          message_id: message.id,
          user_id: userId,
          group_id: message.group_id,
        })
        .then(() => res.status(200).send({ message: 'Message created!' }))
        .catch(error => res.status(400)
        .send({ message: 'An error occured!', error }));
      })
      .catch((error) => {
        res.status(400).send({ error, message: 'An error occured, try again' });
      });
    }
  })
  .catch((error) => {
    res.status(400).send({ error, message: 'An error occured, try again' });
  });
};
<|endoftext|>


<commit_before>/*
**  ComponentJS -- Component System for JavaScript <http://componentjs.com>
**  Copyright (c) 2009-2013 Ralf S. Engelschall <http://engelschall.com>
**
**  This Source Code Form is subject to the terms of the Mozilla Public
**  License, v. 2.0. If a copy of the MPL was not distributed with this
**  file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

(function (factory) {
    var name = "tracing";
    if (typeof exports === "object")
        exports[name] = factory();
    else if (typeof define === "function" && typeof define.amd === "object")
        define(name, function () { return factory(); });
    else
        window[name] = factory();
})(function () {
    var api = {};

    api.instrument = function (symbol, source) {
        var input = source;
        var output = "";

        var stack = [];
        var m, consume;
        while (input !== "") {
            consume = -1;

            /*  comment (block variant)  */
            if ((m = input.match(/^\/\*.*\*\//)) !== null) {}

            /*  comment (EOL variant)  */
            else if ((m = input.match(/^\/\/[^\r\n]*\r?\n/)) !== null) {}

            /*  string (double-quoted)  */
            else if ((m = input.match(/^"(\\"|[^"])*"/)) !== null) {}

            /*  string (single-quoted)  */
            else if ((m = input.match(/^'(\\'|[^'])*'/)) !== null) {}

            /*  regular expression  */
            else if ((m = input.match(/^\/(\\\/|[^\/])*\//)) !== null) {}

            /*  life-cycle functions  */
            else if (output.match(/(?:prepare|cleanup|create|destroy|render|release|show|hide):\s*$/) !== null) {
                m = input.match(/^function\s*\(.*?\)\s*\{/)
            }

            /*  start of function  */
            else if ((m = input.match(/^function\s*\(.*?\)\s*\{/)) !== null) {
                stack.push("function");
                output += symbol + ".fn(";
            }

            /*  any other opening brace  */
            else if ((m = input.match(/^\{/)) !== null) {
                stack.push("other");
            }

            /*  end of function or any other closing brace  */
            else if ((m = input.match(/^\}/)) !== null) {
                output += input.substr(0, m[0].length);
                input = input.substr(m[0].length);
                var type = stack.pop();
                if (type === "function")
                    output += ")";
                consume = 0;
            }

            /*  any other prefix  */
            else if ((m = input.match(/^([^\/"'f{}]+)/)) !== null) {}

            /*  any other character  */
            else
                consume = 1;

            /*  input to output shifting  */
            if (consume === -1) {
                if (m !== null) consume = m[0].length;
                else            consume = 0;
            }
            if (consume > 0) {
                output += input.substr(0, consume);
                input = input.substr(consume);
            }
        }

        return output;
    };

    return api;
});<commit_msg>Added todo<commit_after>/*
**  ComponentJS -- Component System for JavaScript <http://componentjs.com>
**  Copyright (c) 2009-2013 Ralf S. Engelschall <http://engelschall.com>
**
**  This Source Code Form is subject to the terms of the Mozilla Public
**  License, v. 2.0. If a copy of the MPL was not distributed with this
**  file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

(function (factory) {
    var name = "tracing";
    if (typeof exports === "object")
        exports[name] = factory();
    else if (typeof define === "function" && typeof define.amd === "object")
        define(name, function () { return factory(); });
    else
        window[name] = factory();
})(function () {
    var api = {};

    api.instrument = function (symbol, source) {
        var input = source;
        var output = "";

        var stack = [];
        var m, consume;
        while (input !== "") {
            consume = -1;

            /*  comment (block variant)  */
            if ((m = input.match(/^\/\*.*\*\//)) !== null) {}

            /*  comment (EOL variant)  */
            else if ((m = input.match(/^\/\/[^\r\n]*\r?\n/)) !== null) {}

            /*  string (double-quoted)  */
            else if ((m = input.match(/^"(\\"|[^"])*"/)) !== null) {}

            /*  string (single-quoted)  */
            else if ((m = input.match(/^'(\\'|[^'])*'/)) !== null) {}

            /*  regular expression  */
            else if ((m = input.match(/^\/(\\\/|[^\/])*\//)) !== null) {}

            /*  life-cycle functions  */
            //FIXME - take life-cycle methods from _cs.state
            else if (output.match(/(?:prepare|cleanup|create|destroy|render|release|show|hide):\s*$/) !== null) {
                m = input.match(/^function\s*\(.*?\)\s*\{/)
            }

            /*  start of function  */
            else if ((m = input.match(/^function\s*\(.*?\)\s*\{/)) !== null) {
                stack.push("function");
                output += symbol + ".fn(";
            }

            /*  any other opening brace  */
            else if ((m = input.match(/^\{/)) !== null) {
                stack.push("other");
            }

            /*  end of function or any other closing brace  */
            else if ((m = input.match(/^\}/)) !== null) {
                output += input.substr(0, m[0].length);
                input = input.substr(m[0].length);
                var type = stack.pop();
                if (type === "function")
                    output += ")";
                consume = 0;
            }

            /*  any other prefix  */
            else if ((m = input.match(/^([^\/"'f{}]+)/)) !== null) {}

            /*  any other character  */
            else
                consume = 1;

            /*  input to output shifting  */
            if (consume === -1) {
                if (m !== null) consume = m[0].length;
                else            consume = 0;
            }
            if (consume > 0) {
                output += input.substr(0, consume);
                input = input.substr(consume);
            }
        }

        return output;
    };

    return api;
});<|endoftext|>


<commit_before>"use strict";

var ModelError = require('./Error');
var ModelErrorCodes = require('./ErrorCodes');
var _ = require('lodash');

/**
 * @class
 * @abstract
 */
class ModelAbstract {

    /**
     * @param  {Object} config
     * @param  {mongodb} db
     */
    constructor(db) {
        this._db = db;
        this._collectionName = null;
        this._indexes = null;
        this._collection = null;
    }

    /**
     * init collection of model
     *
     * @return {Promise}
     */
    init() {

        if (!this._collectionName) {

            throw new ModelError(
                'no collection name for model',
                ModelErrorCodes.NO_COLLECTION_NAME
            );

        }

        this._collection = this._db.collection(this._collectionName);

        return this;
    }

    ensureIndexes() {

        return new Promise((resolve, reject) => {

            if (!this._indexes) {
                resolve([]);
                return;
            }

            var existsPromises = [];

            _.each(this._indexes, (index) => {
                existsPromises.push(this._collection.indexExists(index.options.name));
            });

            Promise.all(existsPromises)
                .then((data) => {
                    var createPromises = [];

                    _.each(data, (exists, key) => {

                        if (!exists) {
                            createPromises.push(
                                this._collection.createIndex(
                                    this._indexes[key].fields,
                                    this._indexes[key].options
                                )
                            );
                        }

                    });

                    if (!createPromises.length) {
                        resolve([]);
                        return;
                    }

                    Promise.all(createPromises)
                        .then((data) => {
                            resolve(data);
                        })
                        .catch((error) => {
                            reject(error);
                        });

                })
                .catch((error) => {
                    reject(error);
                });

        });

    }

    /**
     * insert new one
     *
     * @param  {Object} data
     * @return {Promise}
     */
    insertOne(data) {

        return new Promise((resolve, reject) => {

            if (data.id) {
                data._id = data.id;
            }

            this._collection.insertOne(data)
                .then((result) => {
                    if (result.ops && result.ops[0]) {
                        resolve(result.ops[0]);
                    } else {
                        resolve(null);
                    }
                })
                .catch((error) => {
                    if (error) {
                        var e;

                        if (error.code && error.code == 11000) {
                            // already exists
                            e = new ModelError(
                                'record with id = ' + data.id + ' already exists',
                                ModelErrorCodes.ALREADY_EXISTS
                            );
                        } else {
                            e = error;
                        }

                        reject(e);
                        return;
                    }
                });

        });
    }

    findOneAndUpdate(filter, update, options) {

        if (!options) {

            options = {
                returnOriginal: false
            };

        } else if (typeof options.returnOriginal == 'undefined') {
            options.returnOriginal = false;
        }

        return new Promise((resolve, reject) => {
            this._collection.findOneAndUpdate(filter, update, options)
                .then((data) => {
                    resolve(data);
                })
                .catch((error) => {
                    reject(error);
                });
        });

    }

    /**
     * get one
     *
     * @param  {Object} query
     * @param {Object} options
     *
     * @return {Promise}
     */
    findOne(query, options) {
        return new Promise((resolve, reject) => {

            this._collection.findOne(query, options, (err, doc) => {
                if (err) {
                    reject(err);
                    return;
                }

                if (doc) {
                    resolve(doc);
                } else {
                    resolve(null);
                }
            });
        });
    }

    /**
     * get one by id
     *
     * @param  {String} id
     * @return {Promise}
     */
    findOneById(id) {
        return new Promise((resolve, reject) => {
            this._collection.findOne({
                _id: id
            }, (err, doc) => {
                if (err) {
                    reject(err);
                    return;
                }

                if (doc) {
                    resolve(doc);
                } else {
                    resolve(null);
                }
            });
        });
    }

    /**
     * search by params
     *
     * @param  {Object} params
     * @param  {Object} fields
     * @param  {Object} sort
     * @param  {Number} limit
     * @param  {Number} offset
     * @return {Promise}
     */
    find(filter, fields, sort, limit, offset) {

        return new Promise((resolve, reject) => {

            var cursor = this._collection.find(filter);

            if (fields) {
                cursor.project(fields);
            }

            if (sort) {
                cursor.sort(sort);
            }

            if (limit) {
                cursor.limit(limit);
            }

            if (offset) {
                cursor.skip(offset);
            }

            Promise.all([cursor.count(), cursor.toArray()])
                .then((data) => {

                    resolve({
                        total: data[0],
                        docs: data[1]
                    });

                })
                .catch((error) => {
                    reject(error);
                });

        });

    }

    /**
     * update one
     *
     * @param  {Object} filters
     * @param  {Object} data
     * @return {Promise}
     */
    updateOne(filters, data) {

        return new Promise((resolve, reject) => {
            this._collection.update(filters, data, {}, (err, num) => {
                if (err) {
                    reject(err);
                    return;
                }

                resolve(data);
            });
        });
    }

    /**
     * remove one
     *
     * @param  {Object} filters
     * @return {Promise}
     */
    removeOne(filters) {
        return new Promise((resolve, reject) => {
            this._collection.remove(filters, {}, (err, count) => {
                if (err) {
                    reject(err);
                    return;
                }

                resolve(count);
            });
        });
    }

    /**
     * get cound by filters
     *
     * @param  {Object} filters
     * @return {Promise}
     */
    count(filters) {

        return new Promise((resolve, reject) => {

            this._collection.count(filters)
                .then((data) => {
                    resolve(data);
                })
                .catch((error) => {
                    reject(error);
                });

        });

    }

    /**
     * aggregate
     *
     * @param  {Object} pipeline
     * @param  {Object} options
     * @return {AggregationCursor}
     */
    aggregate(pipeline, options) {
        return this._collection.aggregate(pipeline, options);
    }

}

module.exports = ModelAbstract;
<commit_msg>Model/Abstract all methods return promises<commit_after>"use strict";

var ModelError = require('./Error');
var ModelErrorCodes = require('./ErrorCodes');
var _ = require('lodash');

/**
 * @class
 * @abstract
 */
class ModelAbstract {

    /**
     * @param  {Object} config
     * @param  {mongodb} db
     */
    constructor(db) {
        this._db = db;
        this._collectionName = null;
        this._indexes = null;
        this._collection = null;
    }

    /**
     * init collection of model
     *
     * @return {Promise}
     */
    init() {

        if (!this._collectionName) {

            throw new ModelError(
                'no collection name for model',
                ModelErrorCodes.NO_COLLECTION_NAME
            );

        }

        this._collection = this._db.collection(this._collectionName);

        return this;
    }

    ensureIndexes() {

        return new Promise((resolve, reject) => {

            if (!this._indexes) {
                resolve([]);
                return;
            }

            var existsPromises = [];

            _.each(this._indexes, (index) => {
                existsPromises.push(this._collection.indexExists(index.options.name));
            });

            Promise.all(existsPromises)
                .then((data) => {
                    var createPromises = [];

                    _.each(data, (exists, key) => {

                        if (!exists) {
                            createPromises.push(
                                this._collection.createIndex(
                                    this._indexes[key].fields,
                                    this._indexes[key].options
                                )
                            );
                        }

                    });

                    if (!createPromises.length) {
                        resolve([]);
                        return;
                    }

                    Promise.all(createPromises)
                        .then((data) => {
                            resolve(data);
                        })
                        .catch((error) => {
                            reject(error);
                        });

                })
                .catch((error) => {
                    reject(error);
                });

        });

    }

    /**
     * insert new one
     *
     * @param  {Object} data
     * @return {Promise}
     */
    insertOne(data) {

        return new Promise((resolve, reject) => {

            if (data.id) {
                data._id = data.id;
            }

            this._collection.insertOne(data)
                .then((result) => {
                    if (result.ops && result.ops[0]) {
                        resolve(result.ops[0]);
                    } else {
                        resolve(null);
                    }
                })
                .catch((error) => {
                    if (error) {
                        var e;

                        if (error.code && error.code == 11000) {
                            // already exists
                            e = new ModelError(
                                'record with id = ' + data.id + ' already exists',
                                ModelErrorCodes.ALREADY_EXISTS
                            );
                        } else {
                            e = error;
                        }

                        reject(e);
                        return;
                    }
                });

        });
    }

    findOneAndUpdate(filter, update, options) {

        if (!options) {

            options = {
                returnOriginal: false
            };

        } else if (typeof options.returnOriginal == 'undefined') {
            options.returnOriginal = false;
        }

        return new Promise((resolve, reject) => {
            this._collection.findOneAndUpdate(filter, update, options)
                .then((data) => {
                    resolve(data);
                })
                .catch((error) => {
                    reject(error);
                });
        });

    }

    /**
     * get one
     *
     * @param  {Object} query
     * @param {Object} options
     *
     * @return {Promise}
     */
    findOne(query, options) {
        return new Promise((resolve, reject) => {

            this._collection.findOne(query, options)
                .then((doc) => {
                    if (doc) {
                        resolve(doc);
                    } else {
                        resolve(null);
                    }
                })
                .catch((err) => {
                    reject(err);
                });
        });
    }

    /**
     * get one by id
     *
     * @param  {String} id
     * @return {Promise}
     */
    findOneById(id) {
        return new Promise((resolve, reject) => {

            this._collection.findOne({_id: id})
                .then((doc) => {
                    if (doc) {
                        resolve(doc);
                    } else {
                        resolve(null);
                    }
                })
                .catch((err) => {
                    reject(err);
                });

        });
    }

    /**
     * search by params
     *
     * @param  {Object} params
     * @param  {Object} fields
     * @param  {Object} sort
     * @param  {Number} limit
     * @param  {Number} offset
     * @return {Promise}
     */
    find(filter, fields, sort, limit, offset) {

        return new Promise((resolve, reject) => {

            var cursor = this._collection.find(filter);

            if (fields) {
                cursor.project(fields);
            }

            if (sort) {
                cursor.sort(sort);
            }

            if (limit) {
                cursor.limit(limit);
            }

            if (offset) {
                cursor.skip(offset);
            }

            Promise.all([cursor.count(), cursor.toArray()])
                .then((data) => {

                    resolve({
                        total: data[0],
                        docs: data[1]
                    });

                })
                .catch((error) => {
                    reject(error);
                });

        });

    }

    /**
     * update one
     *
     * @param  {Object} filters
     * @param  {Object} data
     * @return {Promise}
     */
    updateOne(filters, data) {

        return new Promise((resolve, reject) => {
            this._collection.update(filters, data, {})
                .then((num) => {
                    resolve(data);
                })
                .catch((err) => {
                    reject(err);
                });
        });
    }

    /**
     * remove one
     *
     * @param  {Object} filters
     * @return {Promise}
     */
    removeOne(filters) {

        return new Promise((resolve, reject) => {
            this._collection.remove(filters, {})
                .then((count) => {
                    resolve(count);
                })
                .catch((err) => {
                    reject(err);
                });
        });

    }

    /**
     * get cound by filters
     *
     * @param  {Object} filters
     * @return {Promise}
     */
    count(filters) {

        return new Promise((resolve, reject) => {

            this._collection.count(filters)
                .then((data) => {
                    resolve(data);
                })
                .catch((error) => {
                    reject(error);
                });

        });

    }

    /**
     * aggregate
     *
     * @param  {Object} pipeline
     * @param  {Object} options
     * @return {AggregationCursor}
     */
    aggregate(pipeline, options) {
        return this._collection.aggregate(pipeline, options);
    }

}

module.exports = ModelAbstract;
<|endoftext|>


<commit_before>define([
    'jquery',
    'underscore',
    'knockout',
    'moment',
    'bootstrap-datetimepicker',
], function ($, _, ko, moment) {
    /**
    * A knockout.js binding for the jQuery UI datepicker
    * @constructor
    * @name datepicker
    */
    ko.bindingHandlers.datepicker = {
        init: function (element, valueAccessor, allBindingsAccessor) {
            //initialize datepicker with some optional options
            var options = valueAccessor() || {};
            var minDate;
            var maxDate;

            _.forEach(options, function (value, key){
                if (ko.isObservable(value)) {
                    if (key === 'minDate') {
                        minDate = value;
                    } else if (key === 'maxDate') {
                        maxDate = value;
                    }

                    value.subscribe(function (newValue) {
                        if (_.isObject(newValue)) {
                          newValue = moment(newValue).format(options['format']);
                        }
                        options[key] = newValue;

                        if ((key === 'minDate' || key === 'maxDate') &&
                            typeof minDate === 'function' && minDate() &&
                            typeof maxDate === 'function' && maxDate() &&
                            (minDate() > maxDate() || maxDate() < minDate())) {
                            if (key === 'minDate') {
                                maxDate(minDate());
                            } else {
                                minDate(maxDate());
                            }
                            options[key === 'minDate' ? 'maxDate': 'minDate'] = newValue;
                        }

                        var picker = $(element).data("DateTimePicker");
                        if (picker) {
                            picker.options(options);
                        }
                    });

                    options[key] = options[key]();
                }
            })

            $(element).datetimepicker(options);

            ko.utils.registerEventHandler(element, "dp.change", function (event) {
                var value = allBindingsAccessor().value;
                var picker = $(element).data("DateTimePicker");
                if (ko.isObservable(value)) {
                    if (event.date != null && !(event.date instanceof Date)) {
                        value(event.date.format(picker.format()));
                    }
                }
            });

            ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
                var picker = $(element).data("datepicker");
                if (picker) {
                    picker.destroy();
                }
            });
        }
    };

    return ko.bindingHandlers.datepicker;
});
<commit_msg>date widget refactor<commit_after>define([
    'jquery',
    'underscore',
    'knockout',
    'moment',
    'bootstrap-datetimepicker',
], function ($, _, ko, moment) {
    /**
    * A knockout.js binding for the jQuery UI datepicker
    * @constructor
    * @name datepicker
    */
    ko.bindingHandlers.datepicker = {
        init: function (element, valueAccessor, allBindingsAccessor) {
            //initialize datepicker with some optional options
            var options = valueAccessor() || {};
            var minDate;
            var maxDate;

            _.forEach(options, function (value, key){
                if (ko.isObservable(value)) {
                    if (key === 'minDate') {
                        minDate = value;
                    } else if (key === 'maxDate') {
                        maxDate = value;
                    }

                    value.subscribe(function (newValue) {
                        if (_.isObject(newValue)) {
                          newValue = moment(newValue).format(options['format']);
                        }
                        options[key] = newValue;

                        if ((key === 'minDate' || key === 'maxDate') &&
                            typeof minDate === 'function' && minDate() &&
                            typeof maxDate === 'function' && maxDate() &&
                            (minDate() > maxDate() || maxDate() < minDate())) {
                            if (key === 'minDate') {
                                maxDate(minDate());
                            } else {
                                minDate(maxDate());
                            }
                            options[key === 'minDate' ? 'maxDate': 'minDate'] = newValue;
                        }

                        var picker = $(element).data("DateTimePicker");
                        if (picker) {
                            picker.options(options);
                        }
                    });

                    options[key] = options[key]();
                }
            })

            $(element).datetimepicker(options);

            ko.utils.registerEventHandler(element, "dp.change", function (event) {
                var value = allBindingsAccessor().value;
                var picker = $(element).data("DateTimePicker");
                if (ko.isObservable(value)) {
                    if (event.date != null) {
                        value(event.date.format(picker.format()));
                    }
                }
            });

            ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
                var picker = $(element).data("datepicker");
                if (picker) {
                    picker.destroy();
                }
            });
        }
    };

    return ko.bindingHandlers.datepicker;
});
<|endoftext|>