<commit_before>define('app/models/cloud', ['app/controllers/machines', 'app/controllers/images', 'app/controllers/sizes',
                              'app/controllers/locations','app/controllers/networks', 'ember'],
    /**
     *  Cloud Model
     *
     *  @returns Class
     */
    function (MachinesController, ImagesController, SizesController,
        LocationsController, NetworksController, ProjectsController) {
        return Ember.Object.extend(Ember.Evented, {

            //
            //  Properties
            //

            id: null,
            host: null,
            state: null,
            title: null,
            apikey: null,
            enabled: null,
            provider: null,
            poll_interval: null,
            create_pending: null,
            selectedMachines: [],
            selectedNetworks: [],

            sizes: null,
            projects: null,
            images: null,
            machines: null,
            locations: null,
            networks: null,

            sizeCount: 0,
            imageCount: 0,
            machineCount: 0,
            networkCount: 0,
            locationCoount: 0,

            loadingSizes: null,
            loadingImages: null,
            loadingMachines: null,
            loadingLocations: null,
            loadingNetworks: null,

            isOpenStack: function () {
                return this.provider == 'openstack';
            }.property('provider'),

            isNephoscale: function () {
                return this.provider == 'nephoscale';
            }.property('provider'),

            hasNetworks: function () {
                return  ['openstack', 'nephoscale', 'azure', 'vcloud', 'ec2', 'gce', 'indonesian_vcloud', 'hpcloud']
                    .indexOf(this.provider) > -1;
            }.property('provider'),

            canHaveNetworks: Ember.computed('provider', function() {
                return  ['openstack', 'hpcloud'].indexOf(this.get('provider')) > -1;
            }),

            requiresNetworkOnCreation: function () {
                return  ['openstack', 'vcloud', 'indonesian_vcloud', 'hpcloud']
                    .indexOf(this.provider) > -1;
            }.property('provider'),

            isLibvirt: function () {
                return this.get('provider') == 'libvirt';
            }.property('provider'),

            isDocker: function () {
                return this.provider == 'docker';
            }.property('provider'),

            isAzure: function () {
                return this.provider == 'azure';
            }.property('provider'),

            isBareMetal: function () {
                return this.provider == 'bare_metal';
            }.property('provider'),

            canCreateMachine: function () {
                return this.enabled &&
                    ['indonesian_vcloud', 'bare_metal', 'libvirt', 'vsphere'].indexOf(this.provider) == -1;
            }.property('provider', 'enabled'),

            className: function () {
                return 'provider-' + this.getSimpleProvider();
            }.property('provider'),

            //
            //  Initialization
            //

            load: function () {
                Ember.run(this, function () {
                    // Add controllers
<<<<<<< HEAD:src/mist/io/static/js/app/models/backend.js
                    this.sizes = SizesController.create({backend: this, model: []});
                    this.images = ImagesController.create({backend: this, model: []});
                    this.machines = MachinesController.create({backend: this, model: []});
                    this.locations = LocationsController.create({backend: this, model: []});
                    this.networks = NetworksController.create({backend: this, model: []});
                    this.projects = ProjectsController.create({backend: this, model: []});
=======
                    this.sizes = SizesController.create({cloud: this, model: []});
                    this.images = ImagesController.create({cloud: this, model: []});
                    this.machines = MachinesController.create({cloud: this, model: []});
                    this.locations = LocationsController.create({cloud: this, model: []});
                    this.networks = NetworksController.create({cloud: this, model: []});
>>>>>>> staging:src/mist/io/static/js/app/models/cloud.js

                    // Add events
                    this.sizes.on('onSizeListChange', this, '_updateSizeCount');
                    this.images.on('onChange', this, '_updateImageCount');
                    this.machines.on('onMachineListChange', this, '_updateMachineCount');
                    this.locations.on('onLocationListChange', this, '_updateLocationCount');
                    this.networks.on('onChange', this, '_updateNetworkCount');
                    this.machines.on('onSelectedMachinesChange', this, '_updateSelectedMachines');
                    this.networks.on('onSelectedChange', this, '_updateSelectedNetworks');

                    // Add observers
                    this.sizes.addObserver('loading', this, function () {
                        Ember.run.once(this, 'loadingSizesObserver');
                    });
                    this.images.addObserver('loading', this, function () {
                        Ember.run.once(this, 'loadingImagesObserver');
                    });
                    this.machines.addObserver('loading', this, function () {
                        Ember.run.once(this, 'loadingMachinesObserver');
                    });
                    this.locations.addObserver('loading', this, function () {
                        Ember.run.once(this, 'loadingLocationsObserver');
                    });
                    this.networks.addObserver('loading', this, function () {
                        Ember.run.once(this, 'loadingNetowrksObserver');
                    });
                });
            }.on('init'),

            //
            //  Methods
            //

            getMachine: function (machineId) {
                return this.machines.getMachine(machineId);
            },

            getNetwork: function (networkId) {
                return this.networks.getObject(networkId);
            },

            getImage: function (imageId) {
                return this.images.getObject(imageId);
            },

            getMonitoredMachines: function () {
                return this.machines.getMonitoredMachines();
            },

            shutdownMachine: function (machineId, callback) {
                this.machines.shutdownMachine(machineId, callback);
            },

            destroyMachine: function (machineId, callback) {
                this.machines.destroyMachine(machineId, callback);
            },

            rebootMachine: function (machineId, callback) {
                this.machines.rebootMachine(machineId, callback);
            },

            startMachine: function (machineId, callback) {
                this.machines.startMachine(machineId, callback);
            },

            renameMachine: function (machineId, callback) {
                this.machines.renameMachine(machineId, callback);
            },

            searchImages: function (filter, callback) {
                this.images.searchImages(filter, callback);
            },

            toggleImageStar: function (imageId, callback) {
                this.images.toggleImageStar(imageId, callback);
            },

            getSimpleProvider: function () {
                if (this.provider.indexOf('ec2') == 0) return 'ec2';
                if (this.provider.indexOf('hpcloud') == 0) return 'hpcloud';
                if (this.provider.indexOf('openstack') == 0) return 'openstack';
                if (this.provider.indexOf('rackspace') == 0) return 'rackspace';
                if (this.provider.indexOf('bare_metal') == 0) return 'baremetal';
                if (this.provider.indexOf('indonesian_vcloud') == 0) return 'indonesian';
                return this.provider;
            },

            //
            //  Pseudo-Private Methods
            //

            _updateSizeCount: function () {
                Ember.run(this, function () {
                    this.set('sizeCount', this.sizes.model.length);
                    this.trigger('onSizeListChange');
                });
            },

            _updateImageCount: function () {
                Ember.run(this, function () {
                    this.set('imageCount', this.get('images').get('length'));
                    this.trigger('onImagesChange');
                });
            },

            _updateMachineCount: function () {
                Ember.run(this, function () {
                    this.set('machineCount', this.machines.model.length);
                    this.trigger('onMachineListChange');
                    Mist.cloudsController.trigger('onMachineListChange');
                });
            },

            _updateLocationCount: function () {
                Ember.run(this, function () {
                    this.set('locationCount', this.locations.model.length);
                    this.trigger('onLocationListChange');
                });
            },

            _updateNetworkCount: function () {
                Ember.run(this, function () {
                    this.set('networkCount', this.networks.model.length);
                    this.trigger('onNetworkListChange');
                });
            },

            _updateSelectedMachines: function () {
                Ember.run(this, function () {
                    this.set('selectedMachines', this.machines.selectedMachines);
                    this.trigger('onSelectedMachinesChange');
                });
            },

            _updateSelectedNetworks: function () {
                Ember.run(this, function () {
                    this.set('selectedNetworks', this.networks.get('selectedObjects'));
                    this.trigger('onSelectedNetworksChange');
                });
            },

            _updateState: function () {
                if (this.enabled) {
                    if (this.loadingMachines || this.loadingImages || this.loadingSizes || this.loadingLocations) {
                        this.set('state', 'waiting');
                    } else {
                        this.set('state', 'online');
                    }
                } else {
                    this.set('state', 'offline');
                }
            },

            //
            //  Observers
            //

            enabledObserver: function () {
                Ember.run.once(this, '_toggle');
            }.observes('enabled'),

            //
            //  Dynamic Observers
            //

            loadingSizesObserver: function () {
                this.set('loadingSizes', this.sizes.loading);
            },

            loadingImagesObserver: function () {
                this.set('loadingImages', this.images.loading);
            },

            loadingMachinesObserver: function () {
                this.set('loadingMachines', this.machines.loading);
            },

            loadingLocationsObserver: function () {
                this.set('loadingLocations', this.locations.loading);
            },

            loadingNetworksObserver: function () {
                this.set('loadingNeworks', this.networks.loading);
            },

            stateObserver: function () {
                Ember.run.once(this, '_updateState');
            }.observes('loadingMachines', 'loadingImages', 'loadingSizes', 'loadingLocations', 'enabled'),
        });
    }
);
<commit_msg>fix previous merge<commit_after>define('app/models/cloud', ['app/controllers/machines', 'app/controllers/images', 'app/controllers/sizes',
                              'app/controllers/locations','app/controllers/networks', 'ember'],
    /**
     *  Cloud Model
     *
     *  @returns Class
     */
    function (MachinesController, ImagesController, SizesController,
        LocationsController, NetworksController, ProjectsController) {
        return Ember.Object.extend(Ember.Evented, {

            //
            //  Properties
            //

            id: null,
            host: null,
            state: null,
            title: null,
            apikey: null,
            enabled: null,
            provider: null,
            poll_interval: null,
            create_pending: null,
            selectedMachines: [],
            selectedNetworks: [],

            sizes: null,
            projects: null,
            images: null,
            machines: null,
            locations: null,
            networks: null,

            sizeCount: 0,
            imageCount: 0,
            machineCount: 0,
            networkCount: 0,
            locationCoount: 0,

            loadingSizes: null,
            loadingImages: null,
            loadingMachines: null,
            loadingLocations: null,
            loadingNetworks: null,

            isOpenStack: function () {
                return this.provider == 'openstack';
            }.property('provider'),

            isNephoscale: function () {
                return this.provider == 'nephoscale';
            }.property('provider'),

            hasNetworks: function () {
                return  ['openstack', 'nephoscale', 'azure', 'vcloud', 'ec2', 'gce', 'indonesian_vcloud', 'hpcloud']
                    .indexOf(this.provider) > -1;
            }.property('provider'),

            canHaveNetworks: Ember.computed('provider', function() {
                return  ['openstack', 'hpcloud'].indexOf(this.get('provider')) > -1;
            }),

            requiresNetworkOnCreation: function () {
                return  ['openstack', 'vcloud', 'indonesian_vcloud', 'hpcloud']
                    .indexOf(this.provider) > -1;
            }.property('provider'),

            isLibvirt: function () {
                return this.get('provider') == 'libvirt';
            }.property('provider'),

            isDocker: function () {
                return this.provider == 'docker';
            }.property('provider'),

            isAzure: function () {
                return this.provider == 'azure';
            }.property('provider'),

            isBareMetal: function () {
                return this.provider == 'bare_metal';
            }.property('provider'),

            canCreateMachine: function () {
                return this.enabled &&
                    ['indonesian_vcloud', 'bare_metal', 'libvirt', 'vsphere'].indexOf(this.provider) == -1;
            }.property('provider', 'enabled'),

            className: function () {
                return 'provider-' + this.getSimpleProvider();
            }.property('provider'),

            //
            //  Initialization
            //

            load: function () {
                Ember.run(this, function () {
                    // Add controllers
                    this.sizes = SizesController.create({cloud: this, model: []});
                    this.images = ImagesController.create({cloud: this, model: []});
                    this.machines = MachinesController.create({cloud: this, model: []});
                    this.locations = LocationsController.create({cloud: this, model: []});
                    this.networks = NetworksController.create({cloud: this, model: []});
                    this.projects = ProjectsController.create({cloud: this, model: []});

                    // Add events
                    this.sizes.on('onSizeListChange', this, '_updateSizeCount');
                    this.images.on('onChange', this, '_updateImageCount');
                    this.machines.on('onMachineListChange', this, '_updateMachineCount');
                    this.locations.on('onLocationListChange', this, '_updateLocationCount');
                    this.networks.on('onChange', this, '_updateNetworkCount');
                    this.machines.on('onSelectedMachinesChange', this, '_updateSelectedMachines');
                    this.networks.on('onSelectedChange', this, '_updateSelectedNetworks');

                    // Add observers
                    this.sizes.addObserver('loading', this, function () {
                        Ember.run.once(this, 'loadingSizesObserver');
                    });
                    this.images.addObserver('loading', this, function () {
                        Ember.run.once(this, 'loadingImagesObserver');
                    });
                    this.machines.addObserver('loading', this, function () {
                        Ember.run.once(this, 'loadingMachinesObserver');
                    });
                    this.locations.addObserver('loading', this, function () {
                        Ember.run.once(this, 'loadingLocationsObserver');
                    });
                    this.networks.addObserver('loading', this, function () {
                        Ember.run.once(this, 'loadingNetowrksObserver');
                    });
                });
            }.on('init'),

            //
            //  Methods
            //

            getMachine: function (machineId) {
                return this.machines.getMachine(machineId);
            },

            getNetwork: function (networkId) {
                return this.networks.getObject(networkId);
            },

            getImage: function (imageId) {
                return this.images.getObject(imageId);
            },

            getMonitoredMachines: function () {
                return this.machines.getMonitoredMachines();
            },

            shutdownMachine: function (machineId, callback) {
                this.machines.shutdownMachine(machineId, callback);
            },

            destroyMachine: function (machineId, callback) {
                this.machines.destroyMachine(machineId, callback);
            },

            rebootMachine: function (machineId, callback) {
                this.machines.rebootMachine(machineId, callback);
            },

            startMachine: function (machineId, callback) {
                this.machines.startMachine(machineId, callback);
            },

            renameMachine: function (machineId, callback) {
                this.machines.renameMachine(machineId, callback);
            },

            searchImages: function (filter, callback) {
                this.images.searchImages(filter, callback);
            },

            toggleImageStar: function (imageId, callback) {
                this.images.toggleImageStar(imageId, callback);
            },

            getSimpleProvider: function () {
                if (this.provider.indexOf('ec2') == 0) return 'ec2';
                if (this.provider.indexOf('hpcloud') == 0) return 'hpcloud';
                if (this.provider.indexOf('openstack') == 0) return 'openstack';
                if (this.provider.indexOf('rackspace') == 0) return 'rackspace';
                if (this.provider.indexOf('bare_metal') == 0) return 'baremetal';
                if (this.provider.indexOf('indonesian_vcloud') == 0) return 'indonesian';
                return this.provider;
            },

            //
            //  Pseudo-Private Methods
            //

            _updateSizeCount: function () {
                Ember.run(this, function () {
                    this.set('sizeCount', this.sizes.model.length);
                    this.trigger('onSizeListChange');
                });
            },

            _updateImageCount: function () {
                Ember.run(this, function () {
                    this.set('imageCount', this.get('images').get('length'));
                    this.trigger('onImagesChange');
                });
            },

            _updateMachineCount: function () {
                Ember.run(this, function () {
                    this.set('machineCount', this.machines.model.length);
                    this.trigger('onMachineListChange');
                    Mist.cloudsController.trigger('onMachineListChange');
                });
            },

            _updateLocationCount: function () {
                Ember.run(this, function () {
                    this.set('locationCount', this.locations.model.length);
                    this.trigger('onLocationListChange');
                });
            },

            _updateNetworkCount: function () {
                Ember.run(this, function () {
                    this.set('networkCount', this.networks.model.length);
                    this.trigger('onNetworkListChange');
                });
            },

            _updateSelectedMachines: function () {
                Ember.run(this, function () {
                    this.set('selectedMachines', this.machines.selectedMachines);
                    this.trigger('onSelectedMachinesChange');
                });
            },

            _updateSelectedNetworks: function () {
                Ember.run(this, function () {
                    this.set('selectedNetworks', this.networks.get('selectedObjects'));
                    this.trigger('onSelectedNetworksChange');
                });
            },

            _updateState: function () {
                if (this.enabled) {
                    if (this.loadingMachines || this.loadingImages || this.loadingSizes || this.loadingLocations) {
                        this.set('state', 'waiting');
                    } else {
                        this.set('state', 'online');
                    }
                } else {
                    this.set('state', 'offline');
                }
            },

            //
            //  Observers
            //

            enabledObserver: function () {
                Ember.run.once(this, '_toggle');
            }.observes('enabled'),

            //
            //  Dynamic Observers
            //

            loadingSizesObserver: function () {
                this.set('loadingSizes', this.sizes.loading);
            },

            loadingImagesObserver: function () {
                this.set('loadingImages', this.images.loading);
            },

            loadingMachinesObserver: function () {
                this.set('loadingMachines', this.machines.loading);
            },

            loadingLocationsObserver: function () {
                this.set('loadingLocations', this.locations.loading);
            },

            loadingNetworksObserver: function () {
                this.set('loadingNeworks', this.networks.loading);
            },

            stateObserver: function () {
                Ember.run.once(this, '_updateState');
            }.observes('loadingMachines', 'loadingImages', 'loadingSizes', 'loadingLocations', 'enabled'),
        });
    }
);
<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

cr.define('options.autoFillOptions', function() {
  const DeletableItem = options.DeletableItem;
  const DeletableItemList = options.DeletableItemList;

  /**
   * Creates a new address list item.
   * @param {Array} entry An array of the form [guid, label].
   * @constructor
   * @extends {options.DeletableItem}
   */
  function AddressListItem(entry) {
    var el = cr.doc.createElement('div');
    el.guid = entry[0];
    el.label = entry[1];
    el.__proto__ = AddressListItem.prototype;
    el.decorate();

    return el;
  }

  AddressListItem.prototype = {
    __proto__: DeletableItem.prototype,

    /** @inheritDoc */
    decorate: function() {
      DeletableItem.prototype.decorate.call(this);

      // The stored label.
      var label = this.ownerDocument.createElement('div');
      label.className = 'autofill-list-item';
      label.textContent = this.label;
      this.contentElement.appendChild(label);
    },
  };

  /**
   * Creates a new credit card list item.
   * @param {Array} entry An array of the form [guid, label, icon].
   * @constructor
   * @extends {options.DeletableItem}
   */
  function CreditCardListItem(entry) {
    var el = cr.doc.createElement('div');
    el.guid = entry[0];
    el.label = entry[1];
    el.icon = entry[2];
    el.__proto__ = CreditCardListItem.prototype;
    el.decorate();

    return el;
  }

  CreditCardListItem.prototype = {
    __proto__: DeletableItem.prototype,

    /** @inheritDoc */
    decorate: function() {
      DeletableItem.prototype.decorate.call(this);

      // The stored label.
      var label = this.ownerDocument.createElement('div');
      label.className = 'autofill-list-item';
      label.textContent = this.label;
      this.contentElement.appendChild(label);

      // The credit card icon.
      var icon = this.ownerDocument.createElement('image');
      icon.src = this.icon;
      this.contentElement.appendChild(icon);
    },
  };

  /**
   * Create a new address list.
   * @constructor
   * @extends {options.DeletableItemList}
   */
  var AutoFillAddressList = cr.ui.define('list');

  AutoFillAddressList.prototype = {
    __proto__: DeletableItemList.prototype,

    /** @inheritDoc */
    createItem: function(entry) {
      return new AddressListItem(entry);
    },

    /** @inheritDoc */
    activateItemAtIndex: function(index) {
      AutoFillOptions.loadAddressEditor(this.dataModel.item(index)[0]);
    },

    /** @inheritDoc */
    deleteItemAtIndex: function(index) {
      AutoFillOptions.removeAddress(this.dataModel.item(index)[0]);
    },
  };

  /**
   * Create a new credit card list.
   * @constructor
   * @extends {options.DeletableItemList}
   */
  var AutoFillCreditCardList = cr.ui.define('list');

  AutoFillCreditCardList.prototype = {
    __proto__: DeletableItemList.prototype,

    /** @inheritDoc */
    createItem: function(entry) {
      return new CreditCardListItem(entry);
    },

    /** @inheritDoc */
    activateItemAtIndex: function(index) {
      AutoFillOptions.loadCreditCardEditor(this.dataModel.item(index)[0]);
    },

    /** @inheritDoc */
    deleteItemAtIndex: function(index) {
      AutoFillOptions.removeCreditCard(this.dataModel.item(index)[0]);
    },
  };

  return {
    AddressListItem: AddressListItem,
    CreditCardListItem: CreditCardListItem,
    AutoFillAddressList: AutoFillAddressList,
    AutoFillCreditCardList: AutoFillCreditCardList,
  };
});
<commit_msg>DOMUI: Unselect all list items when the Autofill lists are blurred.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

cr.define('options.autoFillOptions', function() {
  const DeletableItem = options.DeletableItem;
  const DeletableItemList = options.DeletableItemList;

  /**
   * Creates a new address list item.
   * @param {Array} entry An array of the form [guid, label].
   * @constructor
   * @extends {options.DeletableItem}
   */
  function AddressListItem(entry) {
    var el = cr.doc.createElement('div');
    el.guid = entry[0];
    el.label = entry[1];
    el.__proto__ = AddressListItem.prototype;
    el.decorate();

    return el;
  }

  AddressListItem.prototype = {
    __proto__: DeletableItem.prototype,

    /** @inheritDoc */
    decorate: function() {
      DeletableItem.prototype.decorate.call(this);

      // The stored label.
      var label = this.ownerDocument.createElement('div');
      label.className = 'autofill-list-item';
      label.textContent = this.label;
      this.contentElement.appendChild(label);
    },
  };

  /**
   * Creates a new credit card list item.
   * @param {Array} entry An array of the form [guid, label, icon].
   * @constructor
   * @extends {options.DeletableItem}
   */
  function CreditCardListItem(entry) {
    var el = cr.doc.createElement('div');
    el.guid = entry[0];
    el.label = entry[1];
    el.icon = entry[2];
    el.__proto__ = CreditCardListItem.prototype;
    el.decorate();

    return el;
  }

  CreditCardListItem.prototype = {
    __proto__: DeletableItem.prototype,

    /** @inheritDoc */
    decorate: function() {
      DeletableItem.prototype.decorate.call(this);

      // The stored label.
      var label = this.ownerDocument.createElement('div');
      label.className = 'autofill-list-item';
      label.textContent = this.label;
      this.contentElement.appendChild(label);

      // The credit card icon.
      var icon = this.ownerDocument.createElement('image');
      icon.src = this.icon;
      this.contentElement.appendChild(icon);
    },
  };

  /**
   * Create a new address list.
   * @constructor
   * @extends {options.DeletableItemList}
   */
  var AutoFillAddressList = cr.ui.define('list');

  AutoFillAddressList.prototype = {
    __proto__: DeletableItemList.prototype,

    decorate: function() {
      DeletableItemList.prototype.decorate.call(this);

      this.addEventListener('blur', this.onBlur_);
    },

    /**
     * When the list loses focus, unselect all items in the list.
     * @private
     */
    onBlur_: function() {
      this.selectionModel.unselectAll();
    },

    /** @inheritDoc */
    createItem: function(entry) {
      return new AddressListItem(entry);
    },

    /** @inheritDoc */
    activateItemAtIndex: function(index) {
      AutoFillOptions.loadAddressEditor(this.dataModel.item(index)[0]);
    },

    /** @inheritDoc */
    deleteItemAtIndex: function(index) {
      AutoFillOptions.removeAddress(this.dataModel.item(index)[0]);
    },
  };

  /**
   * Create a new credit card list.
   * @constructor
   * @extends {options.DeletableItemList}
   */
  var AutoFillCreditCardList = cr.ui.define('list');

  AutoFillCreditCardList.prototype = {
    __proto__: DeletableItemList.prototype,

    decorate: function() {
      DeletableItemList.prototype.decorate.call(this);

      this.addEventListener('blur', this.onBlur_);
    },

    /**
     * When the list loses focus, unselect all items in the list.
     * @private
     */
    onBlur_: function() {
      this.selectionModel.unselectAll();
    },

    /** @inheritDoc */
    createItem: function(entry) {
      return new CreditCardListItem(entry);
    },

    /** @inheritDoc */
    activateItemAtIndex: function(index) {
      AutoFillOptions.loadCreditCardEditor(this.dataModel.item(index)[0]);
    },

    /** @inheritDoc */
    deleteItemAtIndex: function(index) {
      AutoFillOptions.removeCreditCard(this.dataModel.item(index)[0]);
    },
  };

  return {
    AddressListItem: AddressListItem,
    CreditCardListItem: CreditCardListItem,
    AutoFillAddressList: AutoFillAddressList,
    AutoFillCreditCardList: AutoFillCreditCardList,
  };
});
<|endoftext|>


<commit_before>var PaymentAgentWithdrawWS = (function() {
    "use strict";

    var containerID,
        viewIDs,
        fieldIDs,
        errorClass,
        $views;

    var formData,
        isValid;

    var withdrawCurrency,
        minAmount,
        maxAmount;

    var init = function() {
        containerID = '#paymentagent_withdrawal';
        $views      = $(containerID + ' .viewItem');
        errorClass  = 'errorfield';
        viewIDs = {
            error   : '#viewError',
            success : '#viewSuccess',
            confirm : '#viewConfirm',
            form    : '#viewForm'
        };
        fieldIDs = {
            verificationCode : '#verification-code',
            ddlAgents        : '#ddlAgents',
            txtAmount        : '#txtAmount',
            txtDesc          : '#txtDescription'
        };
        withdrawCurrency = 'USD';
        minAmount = 10;
        maxAmount = 2000;

        $views.addClass('hidden');

        if(page.client.is_virtual()) { // Virtual Account
            showPageError(text.localize('You are not authorized for withdrawal via payment agent.'));
            return false;
        }

        BinarySocket.send({verify_email:page.user.email, type:'paymentagent_withdraw'});
        var residence = $.cookie('residence');
        BinarySocket.send({"paymentagent_list": residence});

        $(viewIDs.form + ' button').click(function(e){
            e.preventDefault();
            e.stopPropagation();
            formData = formValidate();
            if(!formData) {
                return false;
            }
            else {
                withdrawRequest(true);
            }
        });
    };

    // -----------------------
    // ----- Agents List -----
    // -----------------------
    var populateAgentsList = function(response) {
        var $ddlAgents = $(fieldIDs.ddlAgents);
        $ddlAgents.empty();
        var paList = response.paymentagent_list.list;
        if(paList.length > 0) {
            insertListOption($ddlAgents, text.localize('Please select a payment agent'), '');
            for(var i = 0; i < paList.length; i++){
                insertListOption($ddlAgents, paList[i].name, paList[i].paymentagent_loginid);
            }
            setActiveView(viewIDs.form);
        }
        else {
            showPageError(text.localize('The Payment Agent facility is currently not available in your country.'));
        }
    };

    var insertListOption = function($ddlObject, itemText, itemValue) {
        $ddlObject.append($('<option/>', {value: itemValue, text: itemText}));
    };

    // ----------------------------
    // ----- Form Validations -----
    // ----------------------------
    var formValidate = function() {
        clearError();
        isValid = true;

        var agent  = $(fieldIDs.ddlAgents).val(),
            amount = $(fieldIDs.txtAmount).val().trim(),
            desc   = $(fieldIDs.txtDesc).val().trim(),
            token  = $(fieldIDs.verificationCode).val().trim();

        var letters = Content.localize().textLetters,
            numbers = Content.localize().textNumbers,
            space   = Content.localize().textSpace,
            period  = Content.localize().textPeriod,
            comma   = Content.localize().textComma;

        // Payment Agent
        isRequiredError(fieldIDs.ddlAgents);

        // verification token
        if(!isRequiredError(fieldIDs.verificationCode)){
          if (token.length !== 48) {
            showError(fieldIDs.verificationCode, Content.errorMessage('valid', text.localize('verification token')));
          }
        }

        // Amount
        if(!isRequiredError(fieldIDs.txtAmount)){
            if(!(/^\d+(\.\d+)?$/).test(amount) || !$.isNumeric(amount)) {
                showError(fieldIDs.txtAmount, Content.errorMessage('reg', [numbers]));
            }
            else if(!(/^\d+(\.\d{1,2})?$/).test(amount)) {
                showError(fieldIDs.txtAmount, text.localize('Only 2 decimal points are allowed.'));
            }
            else if(amount < minAmount) {
                showError(fieldIDs.txtAmount, text.localize('Invalid amount, minimum is') + ' ' + withdrawCurrency + ' ' + minAmount);
            }
            else if(amount > maxAmount) {
                showError(fieldIDs.txtAmount, text.localize('Invalid amount, maximum is') + ' ' + withdrawCurrency + ' ' + maxAmount);
            }
        }

        // Description
        if(!(/^[a-zA-Z0-9\s\.\,\-']*$/).test(desc)) {
            showError(fieldIDs.txtDesc, Content.errorMessage('reg', [letters, numbers, space, period, comma, '- \'']));
        }

        if(isValid) {
            return {
                agent             : agent,
                agentname         : $(fieldIDs.ddlAgents + ' option:selected').text(),
                currency          : withdrawCurrency,
                amount            : amount,
                desc              : desc,
                verificationCode : token
            };
        }
        else {
            return false;
        }
    };

    var isRequiredError = function(fieldID) {
        if(!$(fieldID).val() || !(/.+/).test($(fieldID).val().trim())){
            showError(fieldID, Content.errorMessage('req'));
            return true;
        } else {
            return false;
        }
    };

    var isCountError = function(fieldID, min, max) {
        var fieldValue = $(fieldID).val().trim();
        if((fieldValue.length > 0 && fieldValue.length < min) || fieldValue.length > max) {
            showError(fieldID, Content.errorMessage('range', '(' + min + '-' + max + ')'));
            return true;
        } else {
            return false;
        }
    };

    // ----------------------------
    // ----- Withdraw Process -----
    // ----------------------------
    var withdrawRequest = function(isDryRun) {
        var dry_run = isDryRun ? 1 : 0;
        BinarySocket.send({
            "paymentagent_withdraw" : 1,
            "paymentagent_loginid"  : formData.agent,
            "currency"              : formData.currency,
            "amount"                : formData.amount,
            "description"           : formData.desc,
            "dry_run"               : dry_run,
            "verification_code"     : formData.verificationCode
        });
    };

    var withdrawResponse = function(response) {
        var responseCode = response.paymentagent_withdraw;
        switch(responseCode){
            case 2: // dry_run success: showing the confirmation page
                setActiveView(viewIDs.confirm);

                $('#lblAgentName').text(formData.agentname);
                $('#lblCurrency').text(formData.currency);
                $('#lblAmount').text(formData.amount);

                $(viewIDs.confirm + ' #btnConfirm').click(function(){
                    withdrawRequest(false);
                });
                $(viewIDs.confirm + ' #btnBack').click(function(){
                    setActiveView(viewIDs.form);
                });
                break;

            case 1: // withdrawal success
                setActiveView(viewIDs.success);
                $('#successMessage').css('display', '')
                    .attr('class', 'success-msg')
                    .html(
                        '

' +
                        text.localize('Your request to withdraw [_1] [_2] from your account [_3] to Payment Agent [_4] account has been successfully processed.')
                            .replace('[_1]', formData.currency)
                            .replace('[_2]', formData.amount)
                            .replace('[_3]', $.cookie('loginid'))
                            .replace('[_4]', formData.agentname) +
                        '

'
                    );
                break;

            default: // error
                if(response.echo_req.dry_run === 1) {
                    setActiveView(viewIDs.form);
                    $('#formMessage').css('display', '')
                        .attr('class', errorClass)
                        .html(response.error.message);
                } else {
                    showPageError(response.error.message);
                }
                break;
        }
    };

    // -----------------------------
    // ----- Message Functions -----
    // -----------------------------
    var showPageError = function(errMsg, noticeMsg) {
        setActiveView(viewIDs.error);
        $(viewIDs.error + ' > p').html(errMsg);
        if (noticeMsg) {
          $(viewIDs.error).append($('
', {html: noticeMsg}));
        }
    };

    var showError = function(fieldID, errMsg) {
        $(fieldID).parent().append($('
', {class: errorClass, text: errMsg}));
        isValid = false;
    };

    var clearError = function(fieldID) {
        $(fieldID ? fieldID : viewIDs.form + ' .' + errorClass).remove();
    };

    // ----- View Control -----
    var setActiveView = function(viewID) {
        $views.addClass('hidden');
        $(viewID).removeClass('hidden');
    };

    return {
        init: init,
        populateAgentsList: populateAgentsList,
        withdrawResponse: withdrawResponse
    };
}());

pjax_config_page("paymentagent/withdrawws", function() {
    return {
        onLoad: function() {
            if (page.client.redirect_if_logout()) {
                return;
            }
            BinarySocket.init({
                onmessage: function(msg) {
                    var response = JSON.parse(msg.data);
                    if (response) {
                        var type = response.msg_type;
                        switch(type){
                            case "authorize":
                                PaymentAgentWithdrawWS.init();
                                break;
                            case "paymentagent_list":
                                PaymentAgentWithdrawWS.populateAgentsList(response);
                                break;
                            case "paymentagent_withdraw":
                                PaymentAgentWithdrawWS.withdrawResponse(response);
                                break;
                            default:
                                break;
                        }
                    }
                    else {
                        console.log('some error occured');
                    }
                }
            });

            Content.populate();
            if(TUser.get().hasOwnProperty('is_virtual')) {
                PaymentAgentWithdrawWS.init();
            }
        }
    };
});
<commit_msg>only send email if payment agents are available<commit_after>var PaymentAgentWithdrawWS = (function() {
    "use strict";

    var containerID,
        viewIDs,
        fieldIDs,
        errorClass,
        $views;

    var formData,
        isValid;

    var withdrawCurrency,
        minAmount,
        maxAmount;

    var init = function() {
        containerID = '#paymentagent_withdrawal';
        $views      = $(containerID + ' .viewItem');
        errorClass  = 'errorfield';
        viewIDs = {
            error   : '#viewError',
            success : '#viewSuccess',
            confirm : '#viewConfirm',
            form    : '#viewForm'
        };
        fieldIDs = {
            verificationCode : '#verification-code',
            ddlAgents        : '#ddlAgents',
            txtAmount        : '#txtAmount',
            txtDesc          : '#txtDescription'
        };
        withdrawCurrency = 'USD';
        minAmount = 10;
        maxAmount = 2000;

        $views.addClass('hidden');

        if(page.client.is_virtual()) { // Virtual Account
            showPageError(text.localize('You are not authorized for withdrawal via payment agent.'));
            return false;
        }

        var residence = $.cookie('residence');
        BinarySocket.send({"paymentagent_list": residence});

        $(viewIDs.form + ' button').click(function(e){
            e.preventDefault();
            e.stopPropagation();
            formData = formValidate();
            if(!formData) {
                return false;
            }
            else {
                withdrawRequest(true);
            }
        });
    };

    // -----------------------
    // ----- Agents List -----
    // -----------------------
    var populateAgentsList = function(response) {
        var $ddlAgents = $(fieldIDs.ddlAgents);
        $ddlAgents.empty();
        var paList = response.paymentagent_list.list;
        if(paList.length > 0) {
            BinarySocket.send({verify_email:page.user.email, type:'paymentagent_withdraw'});
            insertListOption($ddlAgents, text.localize('Please select a payment agent'), '');
            for(var i = 0; i < paList.length; i++){
                insertListOption($ddlAgents, paList[i].name, paList[i].paymentagent_loginid);
            }
            setActiveView(viewIDs.form);
        }
        else {
            showPageError(text.localize('The Payment Agent facility is currently not available in your country.'));
        }
    };

    var insertListOption = function($ddlObject, itemText, itemValue) {
        $ddlObject.append($('<option/>', {value: itemValue, text: itemText}));
    };

    // ----------------------------
    // ----- Form Validations -----
    // ----------------------------
    var formValidate = function() {
        clearError();
        isValid = true;

        var agent  = $(fieldIDs.ddlAgents).val(),
            amount = $(fieldIDs.txtAmount).val().trim(),
            desc   = $(fieldIDs.txtDesc).val().trim(),
            token  = $(fieldIDs.verificationCode).val().trim();

        var letters = Content.localize().textLetters,
            numbers = Content.localize().textNumbers,
            space   = Content.localize().textSpace,
            period  = Content.localize().textPeriod,
            comma   = Content.localize().textComma;

        // Payment Agent
        isRequiredError(fieldIDs.ddlAgents);

        // verification token
        if(!isRequiredError(fieldIDs.verificationCode)){
          if (token.length !== 48) {
            showError(fieldIDs.verificationCode, Content.errorMessage('valid', text.localize('verification token')));
          }
        }

        // Amount
        if(!isRequiredError(fieldIDs.txtAmount)){
            if(!(/^\d+(\.\d+)?$/).test(amount) || !$.isNumeric(amount)) {
                showError(fieldIDs.txtAmount, Content.errorMessage('reg', [numbers]));
            }
            else if(!(/^\d+(\.\d{1,2})?$/).test(amount)) {
                showError(fieldIDs.txtAmount, text.localize('Only 2 decimal points are allowed.'));
            }
            else if(amount < minAmount) {
                showError(fieldIDs.txtAmount, text.localize('Invalid amount, minimum is') + ' ' + withdrawCurrency + ' ' + minAmount);
            }
            else if(amount > maxAmount) {
                showError(fieldIDs.txtAmount, text.localize('Invalid amount, maximum is') + ' ' + withdrawCurrency + ' ' + maxAmount);
            }
        }

        // Description
        if(!(/^[a-zA-Z0-9\s\.\,\-']*$/).test(desc)) {
            showError(fieldIDs.txtDesc, Content.errorMessage('reg', [letters, numbers, space, period, comma, '- \'']));
        }

        if(isValid) {
            return {
                agent             : agent,
                agentname         : $(fieldIDs.ddlAgents + ' option:selected').text(),
                currency          : withdrawCurrency,
                amount            : amount,
                desc              : desc,
                verificationCode : token
            };
        }
        else {
            return false;
        }
    };

    var isRequiredError = function(fieldID) {
        if(!$(fieldID).val() || !(/.+/).test($(fieldID).val().trim())){
            showError(fieldID, Content.errorMessage('req'));
            return true;
        } else {
            return false;
        }
    };

    var isCountError = function(fieldID, min, max) {
        var fieldValue = $(fieldID).val().trim();
        if((fieldValue.length > 0 && fieldValue.length < min) || fieldValue.length > max) {
            showError(fieldID, Content.errorMessage('range', '(' + min + '-' + max + ')'));
            return true;
        } else {
            return false;
        }
    };

    // ----------------------------
    // ----- Withdraw Process -----
    // ----------------------------
    var withdrawRequest = function(isDryRun) {
        var dry_run = isDryRun ? 1 : 0;
        BinarySocket.send({
            "paymentagent_withdraw" : 1,
            "paymentagent_loginid"  : formData.agent,
            "currency"              : formData.currency,
            "amount"                : formData.amount,
            "description"           : formData.desc,
            "dry_run"               : dry_run,
            "verification_code"     : formData.verificationCode
        });
    };

    var withdrawResponse = function(response) {
        var responseCode = response.paymentagent_withdraw;
        switch(responseCode){
            case 2: // dry_run success: showing the confirmation page
                setActiveView(viewIDs.confirm);

                $('#lblAgentName').text(formData.agentname);
                $('#lblCurrency').text(formData.currency);
                $('#lblAmount').text(formData.amount);

                $(viewIDs.confirm + ' #btnConfirm').click(function(){
                    withdrawRequest(false);
                });
                $(viewIDs.confirm + ' #btnBack').click(function(){
                    setActiveView(viewIDs.form);
                });
                break;

            case 1: // withdrawal success
                setActiveView(viewIDs.success);
                $('#successMessage').css('display', '')
                    .attr('class', 'success-msg')
                    .html(
                        '

' +
                        text.localize('Your request to withdraw [_1] [_2] from your account [_3] to Payment Agent [_4] account has been successfully processed.')
                            .replace('[_1]', formData.currency)
                            .replace('[_2]', formData.amount)
                            .replace('[_3]', $.cookie('loginid'))
                            .replace('[_4]', formData.agentname) +
                        '

'
                    );
                break;

            default: // error
                if(response.echo_req.dry_run === 1) {
                    setActiveView(viewIDs.form);
                    $('#formMessage').css('display', '')
                        .attr('class', errorClass)
                        .html(response.error.message);
                } else {
                    showPageError(response.error.message);
                }
                break;
        }
    };

    // -----------------------------
    // ----- Message Functions -----
    // -----------------------------
    var showPageError = function(errMsg, noticeMsg) {
        setActiveView(viewIDs.error);
        $(viewIDs.error + ' > p').html(errMsg);
        if (noticeMsg) {
          $(viewIDs.error).append($('
', {html: noticeMsg}));
        }
    };

    var showError = function(fieldID, errMsg) {
        $(fieldID).parent().append($('
', {class: errorClass, text: errMsg}));
        isValid = false;
    };

    var clearError = function(fieldID) {
        $(fieldID ? fieldID : viewIDs.form + ' .' + errorClass).remove();
    };

    // ----- View Control -----
    var setActiveView = function(viewID) {
        $views.addClass('hidden');
        $(viewID).removeClass('hidden');
    };

    return {
        init: init,
        populateAgentsList: populateAgentsList,
        withdrawResponse: withdrawResponse
    };
}());

pjax_config_page("paymentagent/withdrawws", function() {
    return {
        onLoad: function() {
            if (page.client.redirect_if_logout()) {
                return;
            }
            BinarySocket.init({
                onmessage: function(msg) {
                    var response = JSON.parse(msg.data);
                    if (response) {
                        var type = response.msg_type;
                        switch(type){
                            case "authorize":
                                PaymentAgentWithdrawWS.init();
                                break;
                            case "paymentagent_list":
                                PaymentAgentWithdrawWS.populateAgentsList(response);
                                break;
                            case "paymentagent_withdraw":
                                PaymentAgentWithdrawWS.withdrawResponse(response);
                                break;
                            default:
                                break;
                        }
                    }
                    else {
                        console.log('some error occured');
                    }
                }
            });

            Content.populate();
            if(TUser.get().hasOwnProperty('is_virtual')) {
                PaymentAgentWithdrawWS.init();
            }
        }
    };
});
<|endoftext|>


<commit_before>/*
 * Copyright 2018 Google LLC
 *
 * 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
 *
 *     https://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.
 */

// Update the client ID and search app ID for your deployment.
// [START cloud_search_github_tutorial_search_config]
let searchConfig = {
  clientId: "[client-id]",
  searchAppId: "[application-id]"
};
// [END cloud_search_github_tutorial_search_config]

// Reference to the results container to clear results on login/logout changes.
let resultsContainer;

/**
 * Load the cloud search widget & auth libraries. Runs after
 * the initial gapi bootstrap library is ready.
 */
 // [START cloud_search_github_tutorial_esw_load]
function onLoad() {
  gapi.load('client:auth2:cloudsearch-widget', initializeApp)
}
// [END cloud_search_github_tutorial_esw_load]

/**
 * Initialize the app after loading the Google API client &
 * Cloud Search widget.
 */
 // [START cloud_search_github_tutorial_init_app]
async function initializeApp() {
  await gapi.auth2.init({
    'clientId': searchConfig.clientId,
    'scope': 'https://www.googleapis.com/auth/cloud_search.query'
  });

  // [START cloud_search_github_tutorial_init_auth]
  let auth = gapi.auth2.getAuthInstance();

  // Watch for sign in status changes to update the UI appropriately
  let onSignInChanged = (isSignedIn) => {
    document.getElementById("app").hidden = !isSignedIn;
    document.getElementById("welcome").hidden = isSignedIn;
    if (resultsContainer) {
      resultsContainer.clear();
    }
  }
  auth.isSignedIn.listen(onSignInChanged);
  onSignInChanged(auth.isSignedIn.get()); // Trigger with current status

  // Connect sign-in/sign-out buttons
  document.getElementById("sign-in").onclick = (e) =>  auth.signIn();
  document.getElementById("sign-out").onclick = (e) => auth.signOut();
  // [END cloud_search_github_tutorial_init_auth]

  // [START cloud_search_github_tutorial_init_widget]
  gapi.config.update('cloudsearch.config/apiVersion', 'v1');
  resultsContainer = new gapi.cloudsearch.widget.resultscontainer.Builder()
    .setSearchApplicationId(searchConfig.searchAppId)
    .setSearchResultsContainerElement(document.getElementById('search_results'))
    .setFacetResultsContainerElement(document.getElementById('facet_results'))
    .build();

  const searchBox = new gapi.cloudsearch.widget.searchbox.Builder()
    .setSearchApplicationId(searchConfig.searchAppId)
    .setInput(document.getElementById('search_input'))
    .setAnchor(document.getElementById('suggestions_anchor'))
    .setResultsContainer(resultsContainer)
    .build();
  // [END cloud_search_github_tutorial_init_widget]
}
// [END cloud_search_github_tutorial_init_app]
<commit_msg>Clarify format of search app id<commit_after>// Update the client ID and search app ID for your deployment.
// [START cloud_search_github_tutorial_search_config]
let searchConfig = {
  clientId: "[client-id]",
  searchAppId: "searchapplications/[application-id]"
};
// [END cloud_search_github_tutorial_search_config]

// Reference to the results container to clear results on login/logout changes.
let resultsContainer;

/**
 * Load the cloud search widget & auth libraries. Runs after
 * the initial gapi bootstrap library is ready.
 */
 // [START cloud_search_github_tutorial_esw_load]
function onLoad() {
  gapi.load('client:auth2:cloudsearch-widget', initializeApp)
}
// [END cloud_search_github_tutorial_esw_load]

/**
 * Initialize the app after loading the Google API client &
 * Cloud Search widget.
 */
 // [START cloud_search_github_tutorial_init_app]
async function initializeApp() {
  await gapi.auth2.init({
      'clientId': searchConfig.clientId,
      'scope': 'https://www.googleapis.com/auth/cloud_search.query'
  });

  // [START cloud_search_github_tutorial_init_auth]
  let auth = gapi.auth2.getAuthInstance();

  // Watch for sign in status changes to update the UI appropriately
  let onSignInChanged = (isSignedIn) => {
    document.getElementById("app").hidden = !isSignedIn;
    document.getElementById("welcome").hidden = isSignedIn;
    if (resultsContainer) {
      resultsContainer.clear();
    }
  }
  auth.isSignedIn.listen(onSignInChanged);
  onSignInChanged(auth.isSignedIn.get()); // Trigger with current status

  // Connect sign-in/sign-out buttons
  document.getElementById("sign-in").onclick = (e) =>  auth.signIn();
  document.getElementById("sign-out").onclick = (e) => auth.signOut();
  // [END cloud_search_github_tutorial_init_auth]

  // [START cloud_search_github_tutorial_init_widget]
  gapi.config.update('cloudsearch.config/apiVersion', 'v1');
  resultsContainer = new gapi.cloudsearch.widget.resultscontainer.Builder()
    .setSearchApplicationId(searchConfig.searchAppId)
    .setSearchResultsContainerElement(document.getElementById('search_results'))
    .setFacetResultsContainerElement(document.getElementById('facet_results'))
    .build();

  const searchBox = new gapi.cloudsearch.widget.searchbox.Builder()
    .setSearchApplicationId(searchConfig.searchAppId)
    .setInput(document.getElementById('search_input'))
    .setAnchor(document.getElementById('suggestions_anchor'))
    .setResultsContainer(resultsContainer)
    .build();
  // [END cloud_search_github_tutorial_init_widget]
}
// [END cloud_search_github_tutorial_init_app]
<|endoftext|>


<commit_before>const models = require('../../../models');
const _ = require('lodash');
const async = require('async');
const log = require('../../../utils/logger');

const createAction = require('./events_manager').createAction;

const createManyActions = require('./events_manager').createManyActions;

let postUpdateAsyncLimit = 42;

var lineCrCounter = 0;

var processDots = function() {
  if (lineCrCounter>250) {
    process.stdout.write("\n");
    lineCrCounter = 1;
  } else {
    process.stdout.write(".");
    lineCrCounter += 1;
  }
};

const chunkArray = (myArray, chunk_size) => {
  var index = 0;
  var arrayLength = myArray.length;
  var tempArray = [];

  for (index = 0; index < arrayLength; index += chunk_size) {
    myChunk = myArray.slice(index, index+chunk_size);
    // Do something if you want with the group
    tempArray.push(myChunk);
  }

  return tempArray;
}

const importAllActionsFor = function (model, where, include, action, done, attributes) {
  log.info('AcImportAllActionsFor', {action:action, model: model, where: where, include: include});

  model.findAll(
    {
      where: where,
      include: include,
      attributes: attributes
    }
  ).then(function (objects) {
    lineCrCounter = 0;
    const chunks = chunkArray(objects, 1000);

    async.eachOfLimit(chunks, 1, (objects, index, callback) => {
      const actionsToSend = [];
      async.eachOfSeries(objects, (object, index, seriesCallback) => {
        let postId;
        if (action.indexOf('help') > -1) {
          postId = object.Point.Post.id;
        } else if (action.indexOf('post') > -1) {
          postId = object.id;
        } else {
          postId = object.Post.id;
        }

        if (postId) {
          const esId = `${postId}-${object.user_id}-${action}`;
          actionsToSend.push({
            postId,
            userId: object.user_id,
            date: object.created_at.toISOString(),
            user_agent: object.user_agent,
            ip_address: object.user_agent,
            action,
            esId
          });
          processDots();
          seriesCallback();
        } else {
          console.error("Can't find id for object: " + object);
          seriesCallback();
        }
    }, error => {
        if (!error) {
          createManyActions(JSON.parse(JSON.stringify(actionsToSend)), callback);
        } else {
          callback(error);}
      });
    }, function (error) {
      console.log(error);
      console.log("\n FIN");
      done();
    });
  });
};

var importAll = function(done) {
  async.series([
    function(callback){
      importAllActionsFor(models.Post, {}, [], 'new-post', function () {
        callback();
      }, ['id','user_id','created_at','ip_address','user_agent']);
    },
    function(callback){
      importAllActionsFor(models.Endorsement, { value: { $gt: 0 } }, [ { model: models.Post, attributes: ['id'] }  ], 'endorse', function () {
        callback();
      }, ['id','user_id','created_at','value','ip_address','user_agent']);
    },
    function(callback){
      importAllActionsFor(models.Endorsement, { value: { $lt: 0 } }, [  { model: models.Post, attributes: ['id'] } ], 'oppose', function () {
        callback();
      }, ['id','user_id','created_at','value','ip_address','user_agent']);
    },
    function(callback){
      importAllActionsFor(models.Point, { value: { $ne: 0 }}, [ { model: models.Post, attributes: ['id'] } ], 'new-point', function () {
        callback();
      }, ['id','user_id','created_at','value','ip_address','user_agent']);
    },
    function(callback){
      importAllActionsFor(models.Point, { value: 0 },  [{ model: models.Post, attributes: ['id'] } ], 'new-point-comment', function () {
        callback();
      }, ['id','user_id','created_at','value','ip_address','user_agent']);
    },
    function(callback){
      importAllActionsFor(models.PointQuality, { value: { $gt: 0 } }, [{
          model: models.Point,
          attributes: ['id','value'],
          include: [{ model: models.Post, attributes: ['id'] } ]
        }], 'point-helpful', function () {
        callback();
      }, ['id','user_id','created_at','value','ip_address','user_agent']);
    },
    function(callback){
      importAllActionsFor(models.PointQuality, { value: { $lt: 0 } }, [{
        model: models.Point,
        attributes: ['id','value'],
        include: [ models.Post ]
      }], 'point-unhelpful', function () {
        callback();
      }, ['id','user_id','created_at','value','ip_address','user_agent']);
    }
  ], function () {
    console.log("FIN");
    done();
  });
};

importAll(function () {
  console.log("Done importing all");
  process.exit();
});
<commit_msg>Work on rec<commit_after>const models = require('../../../models');
const _ = require('lodash');
const async = require('async');
const log = require('../../../utils/logger');

const createAction = require('./events_manager').createAction;

const createManyActions = require('./events_manager').createManyActions;

let postUpdateAsyncLimit = 42;

var lineCrCounter = 0;

var processDots = function() {
  if (lineCrCounter>250) {
    process.stdout.write("\n");
    lineCrCounter = 1;
  } else {
    process.stdout.write(".");
    lineCrCounter += 1;
  }
};

const chunkArray = (myArray, chunk_size) => {
  var index = 0;
  var arrayLength = myArray.length;
  var tempArray = [];

  for (index = 0; index < arrayLength; index += chunk_size) {
    myChunk = myArray.slice(index, index+chunk_size);
    // Do something if you want with the group
    tempArray.push(myChunk);
  }

  return tempArray;
}

const importAllActionsFor = function (model, where, include, action, done, attributes) {
  log.info('AcImportAllActionsFor', {action:action, model: model, where: where, include: include});

  model.findAll(
    {
      where: where,
      include: include,
      attributes: attributes
    }
  ).then(function (objects) {
    lineCrCounter = 0;
    const chunks = chunkArray(objects, 1000);

    async.eachOfLimit(chunks, 1, (objects, index, callback) => {
      const actionsToSend = [];
      async.eachOfSeries(objects, (object, index, seriesCallback) => {
        let postId;
        if (action.indexOf('help') > -1) {
          postId = object.Point.Post.id;
        } else if (action.indexOf('post') > -1) {
          postId = object.id;
        } else {
          postId = object.Post.id;
        }

        if (postId) {
          const esId = `${postId}-${object.user_id}-${action}`;
          actionsToSend.push({
            postId,
            userId: object.user_id,
            date: object.created_at.toISOString(),
            user_agent: object.user_agent,
            ip_address: object.ip_address,
            action,
            esId
          });
          processDots();
          seriesCallback();
        } else {
          console.error("Can't find id for object: " + object);
          seriesCallback();
        }
    }, error => {
        if (!error) {
          createManyActions(JSON.parse(JSON.stringify(actionsToSend)), callback);
        } else {
          callback(error);}
      });
    }, function (error) {
      console.log(error);
      console.log("\n FIN");
      done();
    });
  });
};

var importAll = function(done) {
  async.series([
    function(callback){
      importAllActionsFor(models.Post, {}, [], 'new-post', function () {
        callback();
      }, ['id','user_id','created_at','ip_address','user_agent']);
    },
    function(callback){
      importAllActionsFor(models.Endorsement, { value: { $gt: 0 } }, [ { model: models.Post, attributes: ['id'] }  ], 'endorse', function () {
        callback();
      }, ['id','user_id','created_at','value','ip_address','user_agent']);
    },
    function(callback){
      importAllActionsFor(models.Endorsement, { value: { $lt: 0 } }, [  { model: models.Post, attributes: ['id'] } ], 'oppose', function () {
        callback();
      }, ['id','user_id','created_at','value','ip_address','user_agent']);
    },
    function(callback){
      importAllActionsFor(models.Point, { value: { $ne: 0 }}, [ { model: models.Post, attributes: ['id'] } ], 'new-point', function () {
        callback();
      }, ['id','user_id','created_at','value','ip_address','user_agent']);
    },
    function(callback){
      importAllActionsFor(models.Point, { value: 0 },  [{ model: models.Post, attributes: ['id'] } ], 'new-point-comment', function () {
        callback();
      }, ['id','user_id','created_at','value','ip_address','user_agent']);
    },
    function(callback){
      importAllActionsFor(models.PointQuality, { value: { $gt: 0 } }, [{
          model: models.Point,
          attributes: ['id','value'],
          include: [{ model: models.Post, attributes: ['id'] } ]
        }], 'point-helpful', function () {
        callback();
      }, ['id','user_id','created_at','value','ip_address','user_agent']);
    },
    function(callback){
      importAllActionsFor(models.PointQuality, { value: { $lt: 0 } }, [{
        model: models.Point,
        attributes: ['id','value'],
        include: [ models.Post ]
      }], 'point-unhelpful', function () {
        callback();
      }, ['id','user_id','created_at','value','ip_address','user_agent']);
    }
  ], function () {
    console.log("FIN");
    done();
  });
};

importAll(function () {
  console.log("Done importing all");
  process.exit();
});
<|endoftext|>


<commit_before>(function () {
  'use strict';

  moj.Modules.SubTotal = {
    el: '.js-SubTotal',

    init: function () {
      _.bindAll(this, 'render', 'showSummary', 'calculate');
      this.cacheEls();
      this.bindEvents();
      moj.log('init');
    },

    bindEvents: function () {
      this.$sets.on('keyup', 'input[type=number]', this.showSummary);

      moj.Events.on('render', this.render);
    },

    cacheEls: function () {
      this.$sets = $(this.el);
    },

    render: function () {
      this.$sets.each(this.showSummary);
    },

    calculate: function (set) {
      var total = 0;

      set.find('input[type=number]').each(function (i, el) {
        var val = parseFloat($(el).val());
        if (!isNaN(val)) {
          total += val;
        }
      });

      return total;
    },

    showSummary: function (e, el) {
      var $set = el !== undefined ? $(el) : $(e.target).closest(this.el),
          value = this.calculate($set);

      moj.log(CLA.templates);

      if ($set.find('.ValueSummary').length > 0) {
        $set.find('.ValueSummary').replaceWith(CLA.templates.SubTotal({value: value}));
      } else {
        $set.append(CLA.templates.SubTotal({value: value}));
      }
    }
  };
}());<commit_msg>Stop sub totals being appended<commit_after>(function () {
  'use strict';

  moj.Modules.SubTotal = {
    el: '.js-SubTotal',

    init: function () {
      _.bindAll(this, 'render', 'showSummary', 'calculate');
      this.cacheEls();
      this.bindEvents();
      moj.log('init');
    },

    bindEvents: function () {
      this.$sets.on('keyup', 'input[type=number]', this.showSummary);

      moj.Events.on('render', this.render);
    },

    cacheEls: function () {
      this.$sets = $(this.el);
    },

    render: function () {
      this.$sets.each(this.showSummary);
    },

    calculate: function (set) {
      var total = 0;

      set.find('input[type=number]').each(function (i, el) {
        var val = parseFloat($(el).val());
        if (!isNaN(val)) {
          total += val;
        }
      });

      return total;
    },

    showSummary: function (e, el) {
      var $set = el !== undefined ? $(el) : $(e.target).closest(this.el),
          value = this.calculate($set);

      moj.log(CLA.templates);

      if ($set.find('.SubTotal').length > 0) {
        $set.find('.SubTotal').replaceWith(CLA.templates.SubTotal({value: value}));
      } else {
        $set.append(CLA.templates.SubTotal({value: value}));
      }
    }
  };
}());<|endoftext|>


<commit_before>const _ = require('underscore')

import checkPredicate from "./predicate"
import * as Actions from "./gameActions"

export default class Graph {
  constructor(options) {
    this.nodes = options.nodes;
    this.startNode = options.startNode;
  }

  completePassage(passageId, state) {
    const currentNode = this._nodeWithId(state.graph.currentNodeId)
    const currentPassage = currentNode.passages[state.graph.currentPassageIndex];

    if (passageId !== currentPassage.passageId) return;

    const newPassageIndex = state.graph.currentPassageIndex + 1;

    if (newPassageIndex >= currentNode.passages.length) {
      if (this.dispatch) {
        this.dispatch(Actions.COMPLETE_NODE, currentNode.nodeId)
      }
    } else {
      this.dispatch(Actions.CHANGE_PASSAGE, newPassageIndex)
    }
  }

  checkChoiceTransitions(state) {
    if (!state.graph.nodeComplete) return;

    const node = this._nodeWithId(state.graph.currentNodeId)
    if (!node.choices) return;

    let choices = node.choices.filter(function(choice) {
      return checkPredicate(choice.predicate, state)
    });

    if (choices.length > 0 && this.dispatch) {
      this.dispatch(Actions.CHANGE_NODE, choices[0].nodeId);
    }
  }

  playCurrentPassage(state) {
    const node = this._nodeWithId(state.graph.currentNodeId)
    const passage = node.passages[state.graph.currentPassageIndex]

    if (passage && this.dispatch) {
      this.dispatch(Actions.OUTPUT, passage);
    }
  }

  //--

  _nodeWithId(nodeId) {
    return this.nodes[nodeId];
  }
}<commit_msg>Add missing this.dispatch check to nodeGraph<commit_after>const _ = require('underscore')

import checkPredicate from "./predicate"
import * as Actions from "./gameActions"

export default class Graph {
  constructor(options) {
    this.nodes = options.nodes;
    this.startNode = options.startNode;
  }

  completePassage(passageId, state) {
    const currentNode = this._nodeWithId(state.graph.currentNodeId)
    const currentPassage = currentNode.passages[state.graph.currentPassageIndex];

    if (passageId !== currentPassage.passageId) return;

    const newPassageIndex = state.graph.currentPassageIndex + 1;

    if (newPassageIndex >= currentNode.passages.length) {
      if (this.dispatch) {
        this.dispatch(Actions.COMPLETE_NODE, currentNode.nodeId)
      }
    } else {
      if (this.dispatch) {
        this.dispatch(Actions.CHANGE_PASSAGE, newPassageIndex)
      }
    }
  }

  checkChoiceTransitions(state) {
    if (!state.graph.nodeComplete) return;

    const node = this._nodeWithId(state.graph.currentNodeId)
    if (!node.choices) return;

    let choices = node.choices.filter(function(choice) {
      return checkPredicate(choice.predicate, state)
    });

    if (choices.length > 0 && this.dispatch) {
      this.dispatch(Actions.CHANGE_NODE, choices[0].nodeId);
    }
  }

  playCurrentPassage(state) {
    const node = this._nodeWithId(state.graph.currentNodeId)
    const passage = node.passages[state.graph.currentPassageIndex]

    if (passage && this.dispatch) {
      this.dispatch(Actions.OUTPUT, passage);
    }
  }

  //--

  _nodeWithId(nodeId) {
    return this.nodes[nodeId];
  }
}<|endoftext|>


<commit_before>/* eslint-env es6,node */

'use strict';

var request = require('request'),
    through = require('through2'),
    vinyl = require('vinyl'),
    nsconfig = require('nsconfig'),
    path = require('path');

var PARAMS_DEF = [
    {name: 'rootPath', def: '/SuiteScripts'},
    {name: 'script', required : true },
    {name: 'deployment', def: 1},
    {name: 'isCLI', def : false },
    {name: 'isonline', def : false} ,
    {name: 'flatten', def : false}
];

module.exports = upload;
module.exports.upload = upload;
function upload (params) {
    params = checkParams(params);

    return through.obj(function (chunk, enc, callback) {
        if (chunk.isDirectory()) {
            this.push(chunk);
            return callback();
        }

        var that = this,
            fullCwd = path.resolve((params.isCLI && !params.flatten) ? nsconfig.CONF_CWD : chunk.cwd),
            remotePath = chunk.path.substr(fullCwd.length+1);

        if (params.flatten) {
            remotePath = path.basename(remotePath);
        }

        console.log('Uploading ' + remotePath + ' to ' + params.rootPath );

        var toRequest = _requestOpts(params);
        toRequest.json = {
            action : 'upload',
            filepath: remotePath,
            content: chunk.contents.toString('base64'),
            rootpath: params.rootPath ,
            isonline : params.isonline
        };

        request( toRequest ).on('response', response => {
            chunk.nscabinetResponse = response;
            that.push(chunk);
            var logger = _responseLogger();
            response.pipe(logger).on('finish', () => {
                callback();
            });
        });
    });
}

module.exports.download = download;
function download (files,params,info) {
    params = checkParams(params);
    var toRequest = _requestOpts(params);
    toRequest.json = {
        action : 'download' ,
        files : files ,
        rootpath: params.rootPath
    };
    var buffer = '';
    var emitter = through.obj(
        function transform(data,enc,cb) {
            buffer += data;
            cb();
        },
        function flush(cb) {
            var data = JSON.parse(buffer);
            if (data.error) {
                if (!data.error.length) data.error = [data.error];
                data.error = data.error.map( err => {
                    try {
                        return JSON.parse(err);
                    }catch(e) {
                        //keep as it came
                        return err;
                    }
                } );
                data.error.forEach( e => console.error('RESTLET ERROR: ' + (e.details || e.message || e)) );
                info = info || {};
                info.errors = info.errors || [];
                info.errors = info.errors.concat(data.error);
                //this.emit('error',data.error);
            }
            data.files = data.files || [];
            data.files.forEach( file => {
                var localPath = file.path.startsWith('/') ? 'cabinet_root' + file.path : file.path;
                var vynFile = new vinyl({
                    path : localPath ,
                    contents : Buffer.from(file.contents,'base64')
                });
                console.log(`Got file ${file.path}.`);
                this.push(vynFile);
            });
            cb();
        }
    );
    return request( toRequest ).pipe(emitter);
}

/* STUB */
/*
module.exports.deleteFolder = deleteFolder;
function deleteFolder (folders, params) {
    params = checkParams(params);
    if (!Array.isArray(folders)) folders = [folders];
    var toRequest = _requestOpts(params);
    toRequest.json = {
        action : 'deleteFolder' ,
        rootpath : params.rootPath ,
        folders : folders
    };
}
*/

module.exports.checkParams = checkParams;
function checkParams (override, noThrow) {
    var out = nsconfig(override, PARAMS_DEF, noThrow);
    if (!out.rootPath.startsWith('/')) throw Error('rootPath must begin with /');
    return out;
}

/**
 * this function does not work with streams/gulp,
 * instead it simply gets string and returns promise.
 */
module.exports.url = url;
function url(path, params) {
    params = checkParams(params);
    var toRequest = _requestOpts(params);
    toRequest.json = {
        action :  'url' ,
        path : params.rootPath.substr(1) + '/' + path
    };
    return new Promise((resolve,reject) => {
        request( toRequest , (err,resp,body) => {
            if (err) return reject(err);
            resolve(`https://${params.account.replace('_', '-')}.app.netsuite.com${body.url}`);
        });
    });
}

function _requestOpts (params) {
    var nlauthRolePortion = ( params.role ) ? `,nlauth_role=${params.role}` : '',
        server = process.env.NS_SERVER || `https://${params.account.replace('_', '-')}.restlets.api.netsuite.com/app/site/hosting/restlet.nl`;
    //NS_SERVER = testing + nsmockup

    var options = {
        url: server,
        qs: {
            script: params.script,
            deploy: params.deployment
        },
        method: 'POST'
    };

    if (params.token) {
        options.oauth = {
            consumer_key: params.consumerKey,
            consumer_secret: params.consumerSecret,
            token: params.token,
            token_secret: params.tokenSecret,
            realm: params.account
        };
    } else {
        options.headers = {
            authorization: `NLAuth nlauth_account=${params.account},nlauth_email=${params.email},nlauth_signature=${params.password}${nlauthRolePortion}`
        };
    }

    return options;
}

function _responseLogger () {

    var buffer = '';
    return through( function transform(data,enc,cb){
        buffer += data;
        this.push(data);
        cb();
    }, function flush(cb){
        try {
            var data = JSON.parse(buffer);
        } catch(e) {
            throw Error('Unable to parse response: ' + e);
        }
        if (data.message) console.log(data.message);
        if (data.error) console.log(`${data.error.code} - ${data.error.message}`);
        cb();
    });

}<commit_msg>Oauth signature method HMAC-SHA256<commit_after>/* eslint-env es6,node */

'use strict';

var request = require('request'),
    through = require('through2'),
    vinyl = require('vinyl'),
    nsconfig = require('nsconfig'),
    path = require('path');

var PARAMS_DEF = [
    {name: 'rootPath', def: '/SuiteScripts'},
    {name: 'script', required : true },
    {name: 'deployment', def: 1},
    {name: 'isCLI', def : false },
    {name: 'isonline', def : false} ,
    {name: 'flatten', def : false}
];

module.exports = upload;
module.exports.upload = upload;
function upload (params) {
    params = checkParams(params);

    return through.obj(function (chunk, enc, callback) {
        if (chunk.isDirectory()) {
            this.push(chunk);
            return callback();
        }

        var that = this,
            fullCwd = path.resolve((params.isCLI && !params.flatten) ? nsconfig.CONF_CWD : chunk.cwd),
            remotePath = chunk.path.substr(fullCwd.length+1);

        if (params.flatten) {
            remotePath = path.basename(remotePath);
        }

        console.log('Uploading ' + remotePath + ' to ' + params.rootPath );

        var toRequest = _requestOpts(params);
        toRequest.json = {
            action : 'upload',
            filepath: remotePath,
            content: chunk.contents.toString('base64'),
            rootpath: params.rootPath ,
            isonline : params.isonline
        };

        request( toRequest ).on('response', response => {
            chunk.nscabinetResponse = response;
            that.push(chunk);
            var logger = _responseLogger();
            response.pipe(logger).on('finish', () => {
                callback();
            });
        });
    });
}

module.exports.download = download;
function download (files,params,info) {
    params = checkParams(params);
    var toRequest = _requestOpts(params);
    toRequest.json = {
        action : 'download' ,
        files : files ,
        rootpath: params.rootPath
    };
    var buffer = '';
    var emitter = through.obj(
        function transform(data,enc,cb) {
            buffer += data;
            cb();
        },
        function flush(cb) {
            var data = JSON.parse(buffer);
            if (data.error) {
                if (!data.error.length) data.error = [data.error];
                data.error = data.error.map( err => {
                    try {
                        return JSON.parse(err);
                    }catch(e) {
                        //keep as it came
                        return err;
                    }
                } );
                data.error.forEach( e => console.error('RESTLET ERROR: ' + (e.details || e.message || e)) );
                info = info || {};
                info.errors = info.errors || [];
                info.errors = info.errors.concat(data.error);
                //this.emit('error',data.error);
            }
            data.files = data.files || [];
            data.files.forEach( file => {
                var localPath = file.path.startsWith('/') ? 'cabinet_root' + file.path : file.path;
                var vynFile = new vinyl({
                    path : localPath ,
                    contents : Buffer.from(file.contents,'base64')
                });
                console.log(`Got file ${file.path}.`);
                this.push(vynFile);
            });
            cb();
        }
    );
    return request( toRequest ).pipe(emitter);
}

/* STUB */
/*
module.exports.deleteFolder = deleteFolder;
function deleteFolder (folders, params) {
    params = checkParams(params);
    if (!Array.isArray(folders)) folders = [folders];
    var toRequest = _requestOpts(params);
    toRequest.json = {
        action : 'deleteFolder' ,
        rootpath : params.rootPath ,
        folders : folders
    };
}
*/

module.exports.checkParams = checkParams;
function checkParams (override, noThrow) {
    var out = nsconfig(override, PARAMS_DEF, noThrow);
    if (!out.rootPath.startsWith('/')) throw Error('rootPath must begin with /');
    return out;
}

/**
 * this function does not work with streams/gulp,
 * instead it simply gets string and returns promise.
 */
module.exports.url = url;
function url(path, params) {
    params = checkParams(params);
    var toRequest = _requestOpts(params);
    toRequest.json = {
        action :  'url' ,
        path : params.rootPath.substr(1) + '/' + path
    };
    return new Promise((resolve,reject) => {
        request( toRequest , (err,resp,body) => {
            if (err) return reject(err);
            resolve(`https://${params.account.replace('_', '-')}.app.netsuite.com${body.url}`);
        });
    });
}

function _requestOpts (params) {
    var nlauthRolePortion = ( params.role ) ? `,nlauth_role=${params.role}` : '',
        server = process.env.NS_SERVER || `https://${params.account.replace('_', '-')}.restlets.api.netsuite.com/app/site/hosting/restlet.nl`;
    //NS_SERVER = testing + nsmockup

    var options = {
        url: server,
        qs: {
            script: params.script,
            deploy: params.deployment
        },
        method: 'POST'
    };

    if (params.token) {
        options.oauth = {
            signature_method: 'HMAC-SHA256',
            consumer_key: params.consumerKey,
            consumer_secret: params.consumerSecret,
            token: params.token,
            token_secret: params.tokenSecret,
            realm: params.account
        };
    } else {
        options.headers = {
            authorization: `NLAuth nlauth_account=${params.account},nlauth_email=${params.email},nlauth_signature=${params.password}${nlauthRolePortion}`
        };
    }

    return options;
}

function _responseLogger () {

    var buffer = '';
    return through( function transform(data,enc,cb){
        buffer += data;
        this.push(data);
        cb();
    }, function flush(cb){
        try {
            var data = JSON.parse(buffer);
        } catch(e) {
            throw Error('Unable to parse response: ' + e);
        }
        if (data.message) console.log(data.message);
        if (data.error) console.log(`${data.error.code} - ${data.error.message}`);
        cb();
    });

}<|endoftext|>