<commit_before>define(
    [
        'jquery',
        'ko',
        'Omise_Payment/js/view/payment/omise-offsite-method-renderer',
        'Magento_Checkout/js/view/payment/default',
        'Magento_Checkout/js/model/quote',
        'Magento_Catalog/js/price-utils'
    ],
    function (
        $,
        ko,
        Base,
        Component,
        quote,
        priceUtils
    ) {
        'use strict';
        const INSTALLMENT_MIN_PURCHASE_AMOUNT = 3000;

        return Component.extend(Base).extend({
            defaults: {
                template: 'Omise_Payment/payment/offsite-installment-form'
            },

            code: 'omise_offsite_installment',
            restrictedToCurrencies: ['thb'],

            /**
             * Initiate observable fields
             *
             * @return this
             */
            initObservable: function () {
                this._super()
                    .observe([
                        'omiseOffsite',
                        'installmentTermsFC',
                        'installmentTermsKTC',
                        'installmentTermsKBank',
                        'installmentTermsBBL',
                        'installmentTermsBAY',
                    ]);

                return this;
            },

            /**
             * Format Price
             *
             * @param {float} amount - Amount to be formatted
             * @return {string}
             */
            getFormattedAmount: function (amount) {
                return priceUtils.formatPrice(amount, quote.getPriceFormat());
            },

            /**
             * Get formatted message about installment value limitation
             *
             * NOTE: this value should be taken directly from capability object when it is fully implemented.
             *
             * @return {string}
             */
            getMinimumOrderText: function () {
                return $.mage.__('Minimum order value is %amount').replace('%amount', this.getFormattedAmount(INSTALLMENT_MIN_PURCHASE_AMOUNT));
            },

            /**
             * Get Installment minimum
             * this function respects info from: https://www.omise.co/installment-payment
             *
             * NOTE: in the future this function should return data from capabilities object.
             *
             * @param {string} id - Bank ID
             * @return {integer}
             */
            getInstallmentMinimum: function (id) {
                return {
                    'kbank'         : 500,
                    'bbl'           : 500,
                    'bay'           : 300,
                    'first_choice'  : 300,
                    'ktc'           : 300
                }[id];
            },

            /**
             * Get Installment monthly interest rate
             *
             * NOTE: in the future this function should return data from capabilities object.
             *
             * @param {string} id - Bank id
             * @return {float}
             */
            getInstallmentInterestRate: function (id) {
                return {
                    'kbank'         : 0.0065,
                    'bbl'           : 0.008,
                    'bay'           : 0.008,
                    'first_choice'  : 0.013,
                    'ktc'           : 0.008
                }[id];
            },

            /**
             * Get zero interest setting
             *
             * @return {boolean}
             */
            isZeroInterest: function () {
                return window.checkoutConfig.is_zero_interest;
            },

            /**
             * Calculates single installment amount
             *
             * @param {string} id - Bank ID
             * @param {integer} terms - number of monthly installments
             * @return {integer}
             */
            calculateSingleInstallmentAmount: function (id, terms) {
                const total = this.getTotal();

                if (this.isZeroInterest()) {
                    //merchant pays interest
                    return (total / terms).toFixed(2)
                }

                const rate = this.getInstallmentInterestRate(id);
                const interest = rate * terms * total;

                return + (((total + interest) / terms).toFixed(2));
            },

            /**
             * Get total amount of an order
             *
             * @return {integer}
             */
            getTotal: function () {
                return + parseInt(window.checkoutConfig.quoteData.grand_total);
            },

            /**
             * Get installment terms
             *
             * @return {string|null}
             */
            getTerms: function () {
                return this.installmentTermsBBL() || this.installmentTermsKBank() || this.installmentTermsFC() || this.installmentTermsKTC() || this.installmentTermsBAY();
            },

            /**
             * Reset selected terms
             */
            resetTerms: function () {
                this.installmentTermsBBL(null);
                this.installmentTermsKBank(null);
                this.installmentTermsFC(null);
                this.installmentTermsKTC(null);
                this.installmentTermsBAY(null);
            },

            /**
             * Get a checkout form data
             *
             * @return {Object}
             */
            getData: function () {
                return {
                    'method': this.item.method,
                    'additional_data': {
                        'offsite': this.omiseOffsite(),
                        'terms': this.getTerms()
                    }
                };
            },

            /**
             * Returns Installment Terms
             * @param {string} id - Bank id
             * @return {array}
             */
            getInstallmentTerms: function (id) {
                const installmentBackends = checkoutConfig.installment_backends;
                const templateLabel = $.mage.__('%terms months (%amount / month)');

                for (const key in installmentBackends) {
                    if (installmentBackends[key]._id !== 'installment_' + id) {
                        continue;
                    }

                    let dispTerms = [];
                    const terms = installmentBackends[key].allowed_installment_terms;
                    const minSingleInstallment = this.getInstallmentMinimum(id);

                    for (let i = 0; i < terms.length; i++) {
                        const amount = this.calculateSingleInstallmentAmount(id, terms[i]);

                        if (amount >= minSingleInstallment) {
                            dispTerms.push({
                                label: templateLabel.replace('%terms', terms[i]).replace('%amount', this.getFormattedAmount(amount)),
                                key: terms[i]
                            });
                        }
                    }

                    return ko.observableArray(
                        dispTerms
                    );
                }
            },

            /**
             * Check if order value meets minimum requirement
             *
             * @return {boolean}
             */
            orderValueTooLow: function () {
                return this.getTotal() < INSTALLMENT_MIN_PURCHASE_AMOUNT;
            }

        });
    }
);
<commit_msg>removing unecessary parseInt function<commit_after>define(
    [
        'jquery',
        'ko',
        'Omise_Payment/js/view/payment/omise-offsite-method-renderer',
        'Magento_Checkout/js/view/payment/default',
        'Magento_Checkout/js/model/quote',
        'Magento_Catalog/js/price-utils'
    ],
    function (
        $,
        ko,
        Base,
        Component,
        quote,
        priceUtils
    ) {
        'use strict';
        const INSTALLMENT_MIN_PURCHASE_AMOUNT = 3000;

        return Component.extend(Base).extend({
            defaults: {
                template: 'Omise_Payment/payment/offsite-installment-form'
            },

            code: 'omise_offsite_installment',
            restrictedToCurrencies: ['thb'],

            /**
             * Initiate observable fields
             *
             * @return this
             */
            initObservable: function () {
                this._super()
                    .observe([
                        'omiseOffsite',
                        'installmentTermsFC',
                        'installmentTermsKTC',
                        'installmentTermsKBank',
                        'installmentTermsBBL',
                        'installmentTermsBAY',
                    ]);

                return this;
            },

            /**
             * Format Price
             *
             * @param {float} amount - Amount to be formatted
             * @return {string}
             */
            getFormattedAmount: function (amount) {
                return priceUtils.formatPrice(amount, quote.getPriceFormat());
            },

            /**
             * Get formatted message about installment value limitation
             *
             * NOTE: this value should be taken directly from capability object when it is fully implemented.
             *
             * @return {string}
             */
            getMinimumOrderText: function () {
                return $.mage.__('Minimum order value is %amount').replace('%amount', this.getFormattedAmount(INSTALLMENT_MIN_PURCHASE_AMOUNT));
            },

            /**
             * Get Installment minimum
             * this function respects info from: https://www.omise.co/installment-payment
             *
             * NOTE: in the future this function should return data from capabilities object.
             *
             * @param {string} id - Bank ID
             * @return {integer}
             */
            getInstallmentMinimum: function (id) {
                return {
                    'kbank'         : 500,
                    'bbl'           : 500,
                    'bay'           : 300,
                    'first_choice'  : 300,
                    'ktc'           : 300
                }[id];
            },

            /**
             * Get Installment monthly interest rate
             *
             * NOTE: in the future this function should return data from capabilities object.
             *
             * @param {string} id - Bank id
             * @return {float}
             */
            getInstallmentInterestRate: function (id) {
                return {
                    'kbank'         : 0.0065,
                    'bbl'           : 0.008,
                    'bay'           : 0.008,
                    'first_choice'  : 0.013,
                    'ktc'           : 0.008
                }[id];
            },

            /**
             * Get zero interest setting
             *
             * @return {boolean}
             */
            isZeroInterest: function () {
                return window.checkoutConfig.is_zero_interest;
            },

            /**
             * Calculates single installment amount
             *
             * @param {string} id - Bank ID
             * @param {integer} terms - number of monthly installments
             * @return {integer}
             */
            calculateSingleInstallmentAmount: function (id, terms) {
                const total = this.getTotal();

                if (this.isZeroInterest()) {
                    //merchant pays interest
                    return (total / terms).toFixed(2)
                }

                const rate = this.getInstallmentInterestRate(id);
                const interest = rate * terms * total;

                return + (((total + interest) / terms).toFixed(2));
            },

            /**
             * Get total amount of an order
             *
             * @return {integer}
             */
            getTotal: function () {
                return + window.checkoutConfig.quoteData.grand_total;
            },

            /**
             * Get installment terms
             *
             * @return {string|null}
             */
            getTerms: function () {
                return this.installmentTermsBBL() || this.installmentTermsKBank() || this.installmentTermsFC() || this.installmentTermsKTC() || this.installmentTermsBAY();
            },

            /**
             * Reset selected terms
             */
            resetTerms: function () {
                this.installmentTermsBBL(null);
                this.installmentTermsKBank(null);
                this.installmentTermsFC(null);
                this.installmentTermsKTC(null);
                this.installmentTermsBAY(null);
            },

            /**
             * Get a checkout form data
             *
             * @return {Object}
             */
            getData: function () {
                return {
                    'method': this.item.method,
                    'additional_data': {
                        'offsite': this.omiseOffsite(),
                        'terms': this.getTerms()
                    }
                };
            },

            /**
             * Returns Installment Terms
             * @param {string} id - Bank id
             * @return {array}
             */
            getInstallmentTerms: function (id) {
                const installmentBackends = checkoutConfig.installment_backends;
                const templateLabel = $.mage.__('%terms months (%amount / month)');

                for (const key in installmentBackends) {
                    if (installmentBackends[key]._id !== 'installment_' + id) {
                        continue;
                    }

                    let dispTerms = [];
                    const terms = installmentBackends[key].allowed_installment_terms;
                    const minSingleInstallment = this.getInstallmentMinimum(id);

                    for (let i = 0; i < terms.length; i++) {
                        const amount = this.calculateSingleInstallmentAmount(id, terms[i]);

                        if (amount >= minSingleInstallment) {
                            dispTerms.push({
                                label: templateLabel.replace('%terms', terms[i]).replace('%amount', this.getFormattedAmount(amount)),
                                key: terms[i]
                            });
                        }
                    }

                    return ko.observableArray(
                        dispTerms
                    );
                }
            },

            /**
             * Check if order value meets minimum requirement
             *
             * @return {boolean}
             */
            orderValueTooLow: function () {
                return this.getTotal() < INSTALLMENT_MIN_PURCHASE_AMOUNT;
            }

        });
    }
);
<|endoftext|>


<commit_before>/**
 * @class Oskari.mapframework.bundle.myplaces2.MyPlacesBundleInstance
 *
 * My places functionality
 */
Oskari.clazz.define("Oskari.mapframework.bundle.myplaces2.MyPlacesBundleInstance",

/**
 * @method create called automatically on construction
 * @static
 */
function() {
    this._localization = null;
    this.sandbox = null;
    this.buttons = undefined;
    this.categoryHandler = undefined;
    this.myPlacesService = undefined;
    this.featureNS = undefined;
    this.idPrefix = 'myplaces';
}, {
    __name : 'MyPlaces2',
    /**
     * @method getName
     * @return {String} the name for the component
     */
    getName : function() {
        return this.__name;
    },
    /**
     * @method getSandbox
     * @return {Oskari.mapframework.sandbox.Sandbox}
     */
    getSandbox : function() {
        return this.sandbox;
    },
    /**
     * @method getLocalization
     * Returns JSON presentation of bundles localization data for current language.
     * If key-parameter is not given, returns the whole localization data.
     *
     * @param {String} key (optional) if given, returns the value for key
     * @return {String/Object} returns single localization string or
     *      JSON object for complete data depending on localization
     *      structure and if parameter key is given
     */
    getLocalization : function(key) {
        if(!this._localization) {
            this._localization = Oskari.getLocalization(this.getName());
        }
        if (key) {
            if (this._localization &&
                this._localization[key]) {
                return this._localization[key];
            } else {
                return key;
            }
        }
        return this._localization;
    },
    /**
     * @method showMessage
     * Shows user a message with ok button
     * @param {String} title popup title
     * @param {String} message popup message
     */
    showMessage : function(title, message) {
        var loc = this.getLocalization();
        var dialog = Oskari.clazz.create('Oskari.userinterface.component.Popup');
        var okBtn = Oskari.clazz.create('Oskari.userinterface.component.Button');
        okBtn.setTitle(loc.buttons.ok);
        okBtn.addClass('primary');
        okBtn.setHandler(function() {
            dialog.close(true);
        });
        dialog.show(title, message, [okBtn]);
    },
    /**
     * @method forceDisable
     * Disables the functionality since something went wrong
     * (couldnt create default category)
     */
    forceDisable : function() {
        this.buttons.disableButtons();
        var loc = this.getLocalization();

        this.showMessage(loc.category.organization + ' - ' +
             loc.notification.error.title, loc.notification.error.generic);
    },
    /**
     * @method enableGfi
     * Enables/disables the gfi functionality
     * @param {Boolean} blnEnable true to enable, false to disable
     */
    enableGfi : function(blnEnable) {
        var gfiReqBuilder = this.sandbox.getRequestBuilder('MapModulePlugin.GetFeatureInfoActivationRequest');
        if(gfiReqBuilder) {
            this.sandbox.request(this.buttons, gfiReqBuilder(blnEnable));
        }
    },
    /**
     * @method getService
     * Returns the my places main service
     * @return {Oskari.mapframework.bundle.myplaces2.service.MyPlacesService}
     */
    getService : function() {
        return this.myPlacesService;
    },
    /**
     * @method getDrawPlugin
     * Returns reference to the draw plugin
     * @return {Oskari.mapframework.ui.module.common.mapmodule.DrawPlugin}
     */
    getDrawPlugin : function() {
        return this.view.drawPlugin;
    },
    /**
     * @method getCategoryHandler
     * Returns reference to the category handler
     * @return {Oskari.mapframework.bundle.myplaces2.CategoryHandler}
     */
    getCategoryHandler : function() {
        return this.categoryHandler;
    },
    /**
     * @method getMainView
     * Returns reference to the main view
     * @return {Oskari.mapframework.bundle.myplaces2.view.MainView}
     */
    getMainView : function() {
        return this.view;
    },
    /**
     * @method update
     * implements BundleInstance protocol update method - does nothing atm
     */
    update : function() {
    },
     /**
     * @method init
     * implements Module protocol init method
     */
    init : function() {
    },
    /**
     * @method start
     * implements BundleInstance protocol start methdod
     */
    start : function() {

        // Should this not come as a param?
        var me = this;
        var conf = me.conf ;
        var sandboxName = ( conf ? conf.sandbox : null ) || 'sandbox' ;
        var sandbox = Oskari.getSandbox(sandboxName);
        this.sandbox = sandbox;

        this.featureNS = conf ? conf.featureNS : null;
        if (!this.featureNS) {
            return;
        }

        sandbox.printDebug("Initializing my places module...");

        // handles toolbar buttons related to my places
        this.buttons = Oskari.clazz.create("Oskari.mapframework.bundle.myplaces2.ButtonHandler", this);
        this.buttons.start();

        var user = sandbox.getUser();
        if(!user.isLoggedIn()) {
            // guest users don't need anything else
            return;
        }

        sandbox.register(me);
        // handles category related logic - syncs categories to my places map layers etc
        this.categoryHandler = Oskari.clazz.create('Oskari.mapframework.bundle.myplaces2.CategoryHandler', this);
        this.categoryHandler.start();

        var defaults = this._getCategoryDefaults();
        var actionUrl = this.conf.queryUrl;
        // Set max features to configured.
        conf = conf || {};
        conf.maxFeatures = 2;
        var maxFeatures = (conf ? conf.maxFeatures : undefined);
        //'/web/fi/kartta?p_p_id=Portti2Map_WAR_portti2mapportlet&p_p_lifecycle=1&p_p_state=exclusive&p_p_mode=view&p_p_col_id=column-1&p_p_col_count=1&_Portti2Map_WAR_portti2mapportlet_fi.mml.baseportlet.CMD=ajax.jsp&myplaces=WFS';
        // this.conf.queryUrl;
        // back end communication
        this.myPlacesService = Oskari.clazz.create('Oskari.mapframework.bundle.myplaces2.service.MyPlacesService',
            actionUrl, user.getUuid(), sandbox, defaults, this, {
                maxFeatures: maxFeatures
            });
        // register service so personal data can access it
        this.sandbox.registerService(this.myPlacesService);
        // init loads the places/categories
        this.myPlacesService.init();

        // handles my places insert form etc
        this.view = Oskari.clazz.create("Oskari.mapframework.bundle.myplaces2.view.MainView", this);
        this.view.start();

        this.editRequestHandler = Oskari.clazz.create('Oskari.mapframework.bundle.myplaces2.request.EditRequestHandler', sandbox, me);
        this.openAddLayerDialogHandler = Oskari.clazz.create('Oskari.mapframework.bundle.myplaces2.request.OpenAddLayerDialogHandler', sandbox, me);
        sandbox.addRequestHandler('MyPlaces.EditPlaceRequest', this.editRequestHandler);
        sandbox.addRequestHandler('MyPlaces.DeletePlaceRequest', this.editRequestHandler);
        sandbox.addRequestHandler('MyPlaces.EditCategoryRequest', this.editRequestHandler);
        sandbox.addRequestHandler('MyPlaces.DeleteCategoryRequest', this.editRequestHandler);
        sandbox.addRequestHandler('MyPlaces.PublishCategoryRequest', this.editRequestHandler);
        sandbox.addRequestHandler('MyPlaces.OpenAddLayerDialogRequest', this.openAddLayerDialogHandler);

        var tabLocalization = this.getLocalization('tab');

        this.tab = Oskari.clazz.create('Oskari.mapframework.bundle.myplaces2.MyPlacesTab', this, tabLocalization);

        this.tab.initContainer();
         // binds tab to events
        if (this.tab.bindEvents) {
            this.tab.bindEvents();
        }

        var title =  this.tab.getTitle();
        var content = this.tab.getContent();

        var first = true;
        var reqName = 'PersonalData.AddTabRequest';
        var reqBuilder = sandbox.getRequestBuilder(reqName);

        var req = reqBuilder(title, content, first);
        sandbox.request(this, req);
    },
    /**
     * @method stop
     * implements BundleInstance protocol stop method - does nothing atm
     */
    stop : function () {
        this.sandbox = null;
    },

    openAddLayerDialog: function (originator, side) {
            // create popup
            // TODO popup doesn't block bg?
            var me = this,
                dialog = Oskari.clazz.create('Oskari.userinterface.component.Popup'),
                categoryForm = Oskari.clazz.create('Oskari.mapframework.bundle.myplaces2.view.CategoryForm', me),
                categoryHandler = Oskari.clazz.create("Oskari.mapframework.bundle.myplaces2.CategoryHandler", me),
                btnLoc = me.getLocalization('buttons'),
                buttons = [],
                saveBtn = Oskari.clazz.create('Oskari.userinterface.component.Button'),
                cancelBtn = dialog.createCloseButton(btnLoc.cancel);

            saveBtn.setTitle(btnLoc.save);
            saveBtn.addClass('primary');
            saveBtn.setHandler(function () {
                var values = categoryForm.getValues(),
                    errors = categoryHandler.validateCategoryFormValues(values);
                if (errors.length !== 0) {
                    categoryHandler.showValidationErrorMessage(errors);
                    return;
                }
                var category = categoryHandler.getCategoryFromFormValues(values);
                categoryHandler.saveCategory(category);

                dialog.close();
                me.instance.sandbox.postRequestByName('EnableMapKeyboardMovementRequest');
            });
            buttons.push(cancelBtn);
            buttons.push(saveBtn);

            // TODO add buttons
            dialog.show(me.getLocalization('tab').addCategory, categoryForm.getForm(), buttons);
            // Move dialog next to layer select
            if (originator) {
                dialog.moveTo(originator, side);
            }
            // Disable rest of UI
            dialog.makeModal();
            categoryForm.start();
    },

    _getCategoryDefaults : function () {
        var defaults = {
            name: this.getLocalization('category').defaultName,
            point: {
                shape: 1,
                color: "000000",
                size: 3
            },
            line: {
                style: "",
                cap: 0,
                corner: 0,
                width: 1,
                color: "3233ff"
            },
            area: {
                linestyle: "",
                linecorner: 0,
                linewidth: 1,
                linecolor: "000000",
                color: "ffde00",
                fill: -1
            }
        };
        if (!this.conf) return defaults;
        if (!this.conf.defaults) return defaults;
        for (var prop in defaults) {
            if(this.conf.defaults[prop]) {
                defaults[prop] = this.conf.defaults[prop];
            }
        }
        return defaults;
    },

    /**
     * Convert hexadecimal color values to decimal values (255,255,255)
     * Green: hexToRgb("#0033ff").g
     * http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb
     *
     * @method hex
     * hexadecimal color value e.g. '#00ff99'
     */
    hexToRgb: function(hex) {
        // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
        var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
        hex = hex.replace(shorthandRegex, function(m, r, g, b) {
            return r + r + g + g + b + b;
        });

        var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
        return result ? {
            r: parseInt(result[1], 16),
            g: parseInt(result[2], 16),
            b: parseInt(result[3], 16)
        } : null;
    },

    /**
     * Convert rgb values to hexadecimal color values
     *
     * @method rgb
     * decimal color values e.g. 'rgb(255,0,0)'
     */
    rgbToHex: function(rgb) {
        if (rgb.charAt(0) === '#') return rgb.substring(1);
        var parts = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
        delete (parts[0]);
        for (var j = 1; j <= 3; ++j) {
            parts[j] = parseInt(parts[j]).toString(16);
            if (parts[j].length == 1) parts[j] = '0' + parts[j];
        }
        return parts.join('');
    }
}, {
    /**
     * @property {String[]} protocol
     * @static
     */
    protocol : ['Oskari.bundle.BundleInstance']
});
<commit_msg>Removed a test value for max features<commit_after>/**
 * @class Oskari.mapframework.bundle.myplaces2.MyPlacesBundleInstance
 *
 * My places functionality
 */
Oskari.clazz.define("Oskari.mapframework.bundle.myplaces2.MyPlacesBundleInstance",

/**
 * @method create called automatically on construction
 * @static
 */
function() {
    this._localization = null;
    this.sandbox = null;
    this.buttons = undefined;
    this.categoryHandler = undefined;
    this.myPlacesService = undefined;
    this.featureNS = undefined;
    this.idPrefix = 'myplaces';
}, {
    __name : 'MyPlaces2',
    /**
     * @method getName
     * @return {String} the name for the component
     */
    getName : function() {
        return this.__name;
    },
    /**
     * @method getSandbox
     * @return {Oskari.mapframework.sandbox.Sandbox}
     */
    getSandbox : function() {
        return this.sandbox;
    },
    /**
     * @method getLocalization
     * Returns JSON presentation of bundles localization data for current language.
     * If key-parameter is not given, returns the whole localization data.
     *
     * @param {String} key (optional) if given, returns the value for key
     * @return {String/Object} returns single localization string or
     *      JSON object for complete data depending on localization
     *      structure and if parameter key is given
     */
    getLocalization : function(key) {
        if(!this._localization) {
            this._localization = Oskari.getLocalization(this.getName());
        }
        if (key) {
            if (this._localization &&
                this._localization[key]) {
                return this._localization[key];
            } else {
                return key;
            }
        }
        return this._localization;
    },
    /**
     * @method showMessage
     * Shows user a message with ok button
     * @param {String} title popup title
     * @param {String} message popup message
     */
    showMessage : function(title, message) {
        var loc = this.getLocalization();
        var dialog = Oskari.clazz.create('Oskari.userinterface.component.Popup');
        var okBtn = Oskari.clazz.create('Oskari.userinterface.component.Button');
        okBtn.setTitle(loc.buttons.ok);
        okBtn.addClass('primary');
        okBtn.setHandler(function() {
            dialog.close(true);
        });
        dialog.show(title, message, [okBtn]);
    },
    /**
     * @method forceDisable
     * Disables the functionality since something went wrong
     * (couldnt create default category)
     */
    forceDisable : function() {
        this.buttons.disableButtons();
        var loc = this.getLocalization();

        this.showMessage(loc.category.organization + ' - ' +
             loc.notification.error.title, loc.notification.error.generic);
    },
    /**
     * @method enableGfi
     * Enables/disables the gfi functionality
     * @param {Boolean} blnEnable true to enable, false to disable
     */
    enableGfi : function(blnEnable) {
        var gfiReqBuilder = this.sandbox.getRequestBuilder('MapModulePlugin.GetFeatureInfoActivationRequest');
        if(gfiReqBuilder) {
            this.sandbox.request(this.buttons, gfiReqBuilder(blnEnable));
        }
    },
    /**
     * @method getService
     * Returns the my places main service
     * @return {Oskari.mapframework.bundle.myplaces2.service.MyPlacesService}
     */
    getService : function() {
        return this.myPlacesService;
    },
    /**
     * @method getDrawPlugin
     * Returns reference to the draw plugin
     * @return {Oskari.mapframework.ui.module.common.mapmodule.DrawPlugin}
     */
    getDrawPlugin : function() {
        return this.view.drawPlugin;
    },
    /**
     * @method getCategoryHandler
     * Returns reference to the category handler
     * @return {Oskari.mapframework.bundle.myplaces2.CategoryHandler}
     */
    getCategoryHandler : function() {
        return this.categoryHandler;
    },
    /**
     * @method getMainView
     * Returns reference to the main view
     * @return {Oskari.mapframework.bundle.myplaces2.view.MainView}
     */
    getMainView : function() {
        return this.view;
    },
    /**
     * @method update
     * implements BundleInstance protocol update method - does nothing atm
     */
    update : function() {
    },
     /**
     * @method init
     * implements Module protocol init method
     */
    init : function() {
    },
    /**
     * @method start
     * implements BundleInstance protocol start methdod
     */
    start : function() {

        // Should this not come as a param?
        var me = this;
        var conf = me.conf ;
        var sandboxName = ( conf ? conf.sandbox : null ) || 'sandbox' ;
        var sandbox = Oskari.getSandbox(sandboxName);
        this.sandbox = sandbox;

        this.featureNS = conf ? conf.featureNS : null;
        if (!this.featureNS) {
            return;
        }

        sandbox.printDebug("Initializing my places module...");

        // handles toolbar buttons related to my places
        this.buttons = Oskari.clazz.create("Oskari.mapframework.bundle.myplaces2.ButtonHandler", this);
        this.buttons.start();

        var user = sandbox.getUser();
        if(!user.isLoggedIn()) {
            // guest users don't need anything else
            return;
        }

        sandbox.register(me);
        // handles category related logic - syncs categories to my places map layers etc
        this.categoryHandler = Oskari.clazz.create('Oskari.mapframework.bundle.myplaces2.CategoryHandler', this);
        this.categoryHandler.start();

        var defaults = this._getCategoryDefaults();
        var actionUrl = this.conf.queryUrl;
        // Set max features to configured.
        var maxFeatures = (conf ? conf.maxFeatures : undefined);
        //'/web/fi/kartta?p_p_id=Portti2Map_WAR_portti2mapportlet&p_p_lifecycle=1&p_p_state=exclusive&p_p_mode=view&p_p_col_id=column-1&p_p_col_count=1&_Portti2Map_WAR_portti2mapportlet_fi.mml.baseportlet.CMD=ajax.jsp&myplaces=WFS';
        // this.conf.queryUrl;
        // back end communication
        this.myPlacesService = Oskari.clazz.create('Oskari.mapframework.bundle.myplaces2.service.MyPlacesService',
            actionUrl, user.getUuid(), sandbox, defaults, this, {
                maxFeatures: maxFeatures
            });
        // register service so personal data can access it
        this.sandbox.registerService(this.myPlacesService);
        // init loads the places/categories
        this.myPlacesService.init();

        // handles my places insert form etc
        this.view = Oskari.clazz.create("Oskari.mapframework.bundle.myplaces2.view.MainView", this);
        this.view.start();

        this.editRequestHandler = Oskari.clazz.create('Oskari.mapframework.bundle.myplaces2.request.EditRequestHandler', sandbox, me);
        this.openAddLayerDialogHandler = Oskari.clazz.create('Oskari.mapframework.bundle.myplaces2.request.OpenAddLayerDialogHandler', sandbox, me);
        sandbox.addRequestHandler('MyPlaces.EditPlaceRequest', this.editRequestHandler);
        sandbox.addRequestHandler('MyPlaces.DeletePlaceRequest', this.editRequestHandler);
        sandbox.addRequestHandler('MyPlaces.EditCategoryRequest', this.editRequestHandler);
        sandbox.addRequestHandler('MyPlaces.DeleteCategoryRequest', this.editRequestHandler);
        sandbox.addRequestHandler('MyPlaces.PublishCategoryRequest', this.editRequestHandler);
        sandbox.addRequestHandler('MyPlaces.OpenAddLayerDialogRequest', this.openAddLayerDialogHandler);

        var tabLocalization = this.getLocalization('tab');

        this.tab = Oskari.clazz.create('Oskari.mapframework.bundle.myplaces2.MyPlacesTab', this, tabLocalization);

        this.tab.initContainer();
         // binds tab to events
        if (this.tab.bindEvents) {
            this.tab.bindEvents();
        }

        var title =  this.tab.getTitle();
        var content = this.tab.getContent();

        var first = true;
        var reqName = 'PersonalData.AddTabRequest';
        var reqBuilder = sandbox.getRequestBuilder(reqName);

        var req = reqBuilder(title, content, first);
        sandbox.request(this, req);
    },
    /**
     * @method stop
     * implements BundleInstance protocol stop method - does nothing atm
     */
    stop : function () {
        this.sandbox = null;
    },

    openAddLayerDialog: function (originator, side) {
            // create popup
            // TODO popup doesn't block bg?
            var me = this,
                dialog = Oskari.clazz.create('Oskari.userinterface.component.Popup'),
                categoryForm = Oskari.clazz.create('Oskari.mapframework.bundle.myplaces2.view.CategoryForm', me),
                categoryHandler = Oskari.clazz.create("Oskari.mapframework.bundle.myplaces2.CategoryHandler", me),
                btnLoc = me.getLocalization('buttons'),
                buttons = [],
                saveBtn = Oskari.clazz.create('Oskari.userinterface.component.Button'),
                cancelBtn = dialog.createCloseButton(btnLoc.cancel);

            saveBtn.setTitle(btnLoc.save);
            saveBtn.addClass('primary');
            saveBtn.setHandler(function () {
                var values = categoryForm.getValues(),
                    errors = categoryHandler.validateCategoryFormValues(values);
                if (errors.length !== 0) {
                    categoryHandler.showValidationErrorMessage(errors);
                    return;
                }
                var category = categoryHandler.getCategoryFromFormValues(values);
                categoryHandler.saveCategory(category);

                dialog.close();
                me.instance.sandbox.postRequestByName('EnableMapKeyboardMovementRequest');
            });
            buttons.push(cancelBtn);
            buttons.push(saveBtn);

            // TODO add buttons
            dialog.show(me.getLocalization('tab').addCategory, categoryForm.getForm(), buttons);
            // Move dialog next to layer select
            if (originator) {
                dialog.moveTo(originator, side);
            }
            // Disable rest of UI
            dialog.makeModal();
            categoryForm.start();
    },

    _getCategoryDefaults : function () {
        var defaults = {
            name: this.getLocalization('category').defaultName,
            point: {
                shape: 1,
                color: "000000",
                size: 3
            },
            line: {
                style: "",
                cap: 0,
                corner: 0,
                width: 1,
                color: "3233ff"
            },
            area: {
                linestyle: "",
                linecorner: 0,
                linewidth: 1,
                linecolor: "000000",
                color: "ffde00",
                fill: -1
            }
        };
        if (!this.conf) return defaults;
        if (!this.conf.defaults) return defaults;
        for (var prop in defaults) {
            if(this.conf.defaults[prop]) {
                defaults[prop] = this.conf.defaults[prop];
            }
        }
        return defaults;
    },

    /**
     * Convert hexadecimal color values to decimal values (255,255,255)
     * Green: hexToRgb("#0033ff").g
     * http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb
     *
     * @method hex
     * hexadecimal color value e.g. '#00ff99'
     */
    hexToRgb: function(hex) {
        // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
        var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
        hex = hex.replace(shorthandRegex, function(m, r, g, b) {
            return r + r + g + g + b + b;
        });

        var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
        return result ? {
            r: parseInt(result[1], 16),
            g: parseInt(result[2], 16),
            b: parseInt(result[3], 16)
        } : null;
    },

    /**
     * Convert rgb values to hexadecimal color values
     *
     * @method rgb
     * decimal color values e.g. 'rgb(255,0,0)'
     */
    rgbToHex: function(rgb) {
        if (rgb.charAt(0) === '#') return rgb.substring(1);
        var parts = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
        delete (parts[0]);
        for (var j = 1; j <= 3; ++j) {
            parts[j] = parseInt(parts[j]).toString(16);
            if (parts[j].length == 1) parts[j] = '0' + parts[j];
        }
        return parts.join('');
    }
}, {
    /**
     * @property {String[]} protocol
     * @static
     */
    protocol : ['Oskari.bundle.BundleInstance']
});
<|endoftext|>


<commit_before>Application.Controllers.controller('viewMeasurementController',
    ["$scope", "project", "$state", "$log", "modal", "mcapi", "pubsub", viewMeasurementController]);

function viewMeasurementController($scope, project, $state, $log, modal, mcapi, pubsub) {
    $scope.modal = modal;
    this.all = project.processes;
    $scope.selected = {
        item: {}
    };
    processColumns();
    function updateBestMeasure() {
        mcapi('/best_measure')
            .success(function () {
                pubsub.send('updateBestMeasurement');
            }).post({
                property_id: $scope.modal.property.property_id,
                measurement_id: $scope.selected.item.measurement_id
            })
    }

    $scope.ok = function () {
        updateBestMeasure();
        $scope.modal.instance.close($scope.selected.item);
        $state.go('projects.project.samples.edit');
    };

    $scope.cancel = function () {
        $scope.modal.instance.dismiss('cancel');
    };

    $scope.modal.instance.result.then(function (selectedItem) {
        $scope.selected = selectedItem;
    }, function () {
        $log.info('Modal dismissed at: ' + new Date());
    });

    function processColumns(){
        $scope.modal.property.measurements.forEach(function(measure){
            if(measure._type === 'line' || measure._type === 'histogram'){
                measure.categories = measure.value.categories.split("\n");
                measure.values = measure.value.values.split("\n");
            }
            //Setting radio button to checked if best measure is already present
            if($scope.modal.property.best_measure.length > 0){
                if(measure.measurement_id === $scope.modal.property.best_measure[0].id){
                    $scope.selected.item = measure;
                }
            }

        });
    }
}
<commit_msg>Go to correct page after editing the best measure for a sample.<commit_after>Application.Controllers.controller('viewMeasurementController',
    ["$scope", "project", "$state", "$log", "modal", "mcapi", "pubsub", viewMeasurementController]);

function viewMeasurementController($scope, project, $state, $log, modal, mcapi, pubsub) {
    $scope.modal = modal;
    this.all = project.processes;
    $scope.selected = {
        item: {}
    };
    processColumns();
    function updateBestMeasure() {
        mcapi('/best_measure')
            .success(function () {
                pubsub.send('updateBestMeasurement');
            }).post({
                property_id: $scope.modal.property.property_id,
                measurement_id: $scope.selected.item.measurement_id
            })
    }

    $scope.ok = function () {
        updateBestMeasure();
        $scope.modal.instance.close($scope.selected.item);
        $state.go('projects.project.samples.all.edit');
    };

    $scope.cancel = function () {
        $scope.modal.instance.dismiss('cancel');
    };

    $scope.modal.instance.result.then(function (selectedItem) {
        $scope.selected = selectedItem;
    }, function () {
        $log.info('Modal dismissed at: ' + new Date());
    });

    function processColumns(){
        $scope.modal.property.measurements.forEach(function(measure){
            if(measure._type === 'line' || measure._type === 'histogram'){
                measure.categories = measure.value.categories.split("\n");
                measure.values = measure.value.values.split("\n");
            }
            //Setting radio button to checked if best measure is already present
            if($scope.modal.property.best_measure.length > 0){
                if(measure.measurement_id === $scope.modal.property.best_measure[0].id){
                    $scope.selected.item = measure;
                }
            }

        });
    }
}
<|endoftext|>


<commit_before>import { createSelector, createStructuredSelector } from 'reselect';
import flatten from 'lodash/flatten';
import isEmpty from 'lodash/isEmpty';

import initialState from './initial-state';

// get list data
const getMapUrlState = state => (state.query && state.query.map) || null;
const getDatasets = state => state.datasets;
const getLoading = state => state.loading;
const getGeostore = state => state.geostore || null;

// get all map settings
export const getMapSettings = createSelector([getMapUrlState], urlState => ({
  ...initialState,
  ...urlState
}));

// get single map settings
export const getBasemap = createSelector(
  getMapSettings,
  settings => settings.basemap
);

export const getMapZoom = createSelector(
  getMapSettings,
  settings => settings.zoom
);

export const getLabels = createSelector(
  getMapSettings,
  settings => settings.label
);

export const getBBox = createSelector(getGeostore, geostore => {
  const { bbox } = geostore;
  if (isEmpty(bbox)) return {};
  return { bbox, options: { padding: [10, 10] } };
});

export const getMapOptions = createSelector(getMapSettings, settings => {
  if (!settings) return null;
  const {
    center,
    zoom,
    minZoom,
    maxZoom,
    zoomControl,
    basemap,
    label,
    attributionControl
  } = settings;
  return {
    center,
    zoom,
    minZoom,
    maxZoom,
    zoomControl,
    label,
    basemap,
    attributionControl
  };
});

// select datasets and dataset state
export const getActiveDatasetsState = createSelector(
  getMapSettings,
  settings => settings.activeDatasets
);

export const getActiveDatasetIds = createSelector(
  [getActiveDatasetsState],
  activeDatasetsState => {
    if (!activeDatasetsState || !activeDatasetsState.length) return null;
    return activeDatasetsState.map(l => l.dataset);
  }
);

export const getActiveDatasets = createSelector(
  [getDatasets, getActiveDatasetIds],
  (datasets, datasetIds) => {
    if (isEmpty(datasets) || isEmpty(datasetIds)) return null;
    return datasets.filter(d => datasetIds.includes(d.id));
  }
);

export const getBoundaryDatasets = createSelector([getDatasets], datasets => {
  if (isEmpty(datasets)) return null;
  return datasets.filter(d => d.isBoundary);
});

export const getActiveBoundaryDatasets = createSelector(
  [getBoundaryDatasets, getActiveDatasets],
  (datasets, activeDatasets) => {
    if (isEmpty(datasets)) return null;
    const datasetIds = activeDatasets.map(d => d.dataset);
    return datasets.find(d => datasetIds.includes(d.dataset));
  }
);

// parse active datasets to add config from url
export const getDatasetsWithConfig = createSelector(
  [getActiveDatasets, getActiveDatasetsState],
  (datasets, activeDatasetsState) => {
    if (isEmpty(datasets) || isEmpty(activeDatasetsState)) return null;

    return datasets.map(d => {
      const layerConfig =
        activeDatasetsState.find(l => l.dataset === d.id) || {};
      const {
        params,
        sqlParams,
        decodeParams,
        timelineParams,
        layers,
        visibility,
        opacity
      } =
        layerConfig || {};

      return {
        ...d,
        ...layerConfig,
        ...(d.selectorLayerConfig && {
          selectorLayerConfig: {
            ...d.selectorLayerConfig,
            selected: d.selectorLayerConfig.options.find(
              l => l.value === layers[0]
            )
          }
        }),
        layers: d.layers.map(l => {
          const { hasParamsTimeline, hasDecodeTimeline } = l;

          return {
            ...l,
            visibility,
            opacity,
            active: layers && layers.includes(l.id),
            ...(!isEmpty(l.params) && {
              params: {
                ...l.params,
                ...params,
                ...(hasParamsTimeline && {
                  ...timelineParams
                })
              }
            }),
            ...(!isEmpty(l.sqlParams) && {
              sqlParams: {
                ...l.sqlParams,
                ...sqlParams
              }
            }),
            ...(!isEmpty(l.decodeParams) &&
              l.decodeFunction && {
                decodeParams: {
                  ...l.decodeParams,
                  ...(layers &&
                    layers.includes('confirmedOnly') && {
                      confirmedOnly: true
                    }),
                  ...decodeParams,
                  ...(hasDecodeTimeline && {
                    ...timelineParams
                  })
                }
              }),
            ...((l.hasParamsTimeline || l.hasDecodeTimeline) && {
              timelineConfig: {
                ...(l.hasParamsTimeline && {
                  ...l.params
                }),
                ...(l.hasDecodeTimeline && {
                  ...l.decodeParams
                }),
                ...timelineParams
              }
            })
          };
        })
      };
    });
  }
);

// map active datasets into correct order based on url state (drag and drop)
export const getLayerGroups = createSelector(
  [getDatasetsWithConfig, getActiveDatasets],
  (datasets, activeDatasets) => {
    if (isEmpty(datasets) || isEmpty(activeDatasets)) return null;
    return activeDatasets.map(l => datasets.find(d => d.id === l.dataset));
  }
);

// filter out any boundary layers that are for the basemaps comp
export const getLegendLayerGroups = createSelector([getLayerGroups], groups => {
  if (!groups) return null;
  return groups.filter(g => !g.isBoundary);
});

// flatten datasets into layers for the layer manager
export const getActiveLayers = createSelector(getLayerGroups, layerGroups => {
  if (isEmpty(layerGroups)) return [];
  return flatten(layerGroups.map(d => d.layers))
    .filter(l => l.active && !l.confirmedOnly)
    .map((l, i) => ({
      ...l,
      zIndex:
        l.interactionConfig && l.interactionConfig.article ? 1000 + i : 1000 - i
    }));
});

export const getMapProps = createStructuredSelector({
  activeDatasets: getActiveDatasets,
  settings: getMapSettings,
  mapOptions: getMapOptions,
  basemap: getBasemap,
  label: getLabels,
  layerGroups: getLayerGroups,
  activeLayers: getActiveLayers,
  loading: getLoading,
  bbox: getBBox
});
<commit_msg>fix zindex dragdrop<commit_after>import { createSelector, createStructuredSelector } from 'reselect';
import flatten from 'lodash/flatten';
import isEmpty from 'lodash/isEmpty';

import initialState from './initial-state';

// get list data
const getMapUrlState = state => (state.query && state.query.map) || null;
const getDatasets = state => state.datasets;
const getLoading = state => state.loading;
const getGeostore = state => state.geostore || null;

// get all map settings
export const getMapSettings = createSelector([getMapUrlState], urlState => ({
  ...initialState,
  ...urlState
}));

// get single map settings
export const getBasemap = createSelector(
  getMapSettings,
  settings => settings.basemap
);

export const getMapZoom = createSelector(
  getMapSettings,
  settings => settings.zoom
);

export const getLabels = createSelector(
  getMapSettings,
  settings => settings.label
);

export const getBBox = createSelector(getGeostore, geostore => {
  const { bbox } = geostore;
  if (isEmpty(bbox)) return {};
  return { bbox, options: { padding: [10, 10] } };
});

export const getMapOptions = createSelector(getMapSettings, settings => {
  if (!settings) return null;
  const {
    center,
    zoom,
    minZoom,
    maxZoom,
    zoomControl,
    basemap,
    label,
    attributionControl
  } = settings;
  return {
    center,
    zoom,
    minZoom,
    maxZoom,
    zoomControl,
    label,
    basemap,
    attributionControl
  };
});

// select datasets and dataset state
export const getActiveDatasetsState = createSelector(
  getMapSettings,
  settings => settings.activeDatasets
);

export const getActiveDatasetIds = createSelector(
  [getActiveDatasetsState],
  activeDatasetsState => {
    if (!activeDatasetsState || !activeDatasetsState.length) return null;
    return activeDatasetsState.map(l => l.dataset);
  }
);

export const getActiveDatasets = createSelector(
  [getDatasets, getActiveDatasetIds],
  (datasets, datasetIds) => {
    if (isEmpty(datasets) || isEmpty(datasetIds)) return null;
    return datasets.filter(d => datasetIds.includes(d.id));
  }
);

export const getBoundaryDatasets = createSelector([getDatasets], datasets => {
  if (isEmpty(datasets)) return null;
  return datasets.filter(d => d.isBoundary);
});

export const getActiveBoundaryDatasets = createSelector(
  [getBoundaryDatasets, getActiveDatasets],
  (datasets, activeDatasets) => {
    if (isEmpty(datasets)) return null;
    const datasetIds = activeDatasets.map(d => d.dataset);
    return datasets.find(d => datasetIds.includes(d.dataset));
  }
);

// parse active datasets to add config from url
export const getDatasetsWithConfig = createSelector(
  [getActiveDatasets, getActiveDatasetsState],
  (datasets, activeDatasetsState) => {
    if (isEmpty(datasets) || isEmpty(activeDatasetsState)) return null;

    return datasets.map(d => {
      const layerConfig =
        activeDatasetsState.find(l => l.dataset === d.id) || {};
      const {
        params,
        sqlParams,
        decodeParams,
        timelineParams,
        layers,
        visibility,
        opacity
      } =
        layerConfig || {};

      return {
        ...d,
        ...layerConfig,
        ...(d.selectorLayerConfig && {
          selectorLayerConfig: {
            ...d.selectorLayerConfig,
            selected: d.selectorLayerConfig.options.find(
              l => l.value === layers[0]
            )
          }
        }),
        layers: d.layers.map(l => {
          const { hasParamsTimeline, hasDecodeTimeline } = l;

          return {
            ...l,
            visibility,
            opacity,
            active: layers && layers.includes(l.id),
            ...(!isEmpty(l.params) && {
              params: {
                ...l.params,
                ...params,
                ...(hasParamsTimeline && {
                  ...timelineParams
                })
              }
            }),
            ...(!isEmpty(l.sqlParams) && {
              sqlParams: {
                ...l.sqlParams,
                ...sqlParams
              }
            }),
            ...(!isEmpty(l.decodeParams) &&
              l.decodeFunction && {
                decodeParams: {
                  ...l.decodeParams,
                  ...(layers &&
                    layers.includes('confirmedOnly') && {
                      confirmedOnly: true
                    }),
                  ...decodeParams,
                  ...(hasDecodeTimeline && {
                    ...timelineParams
                  })
                }
              }),
            ...((l.hasParamsTimeline || l.hasDecodeTimeline) && {
              timelineConfig: {
                ...(l.hasParamsTimeline && {
                  ...l.params
                }),
                ...(l.hasDecodeTimeline && {
                  ...l.decodeParams
                }),
                ...timelineParams
              }
            })
          };
        })
      };
    });
  }
);

// map active datasets into correct order based on url state (drag and drop)
export const getLayerGroups = createSelector(
  [getDatasetsWithConfig, getActiveDatasetsState],
  (datasets, activeDatasetsState) => {
    if (isEmpty(datasets) || isEmpty(activeDatasetsState)) return null;
    return activeDatasetsState.map(l => datasets.find(d => d.id === l.dataset));
  }
);

// filter out any boundary layers that are for the basemaps comp
export const getLegendLayerGroups = createSelector([getLayerGroups], groups => {
  if (!groups) return null;
  return groups.filter(g => !g.isBoundary);
});

// flatten datasets into layers for the layer manager
export const getActiveLayers = createSelector(getLayerGroups, layerGroups => {
  if (isEmpty(layerGroups)) return [];
  return flatten(layerGroups.map(d => d.layers))
    .filter(l => l.active && !l.confirmedOnly)
    .map((l, i) => ({
      ...l,
      zIndex:
        l.interactionConfig && l.interactionConfig.article ? 1000 + i : 1000 - i
    }));
});

export const getMapProps = createStructuredSelector({
  activeDatasets: getActiveDatasets,
  settings: getMapSettings,
  mapOptions: getMapOptions,
  basemap: getBasemap,
  label: getLabels,
  layerGroups: getLayerGroups,
  activeLayers: getActiveLayers,
  loading: getLoading,
  bbox: getBBox
});
<|endoftext|>


<commit_before>import { bindActionCreators } from 'redux';
import { createElement, PureComponent } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { COUNTRY } from 'pages/country/router';
import isEqual from 'lodash/isEqual';

import {
  getAdminsOptions,
  getActiveAdmin,
  getAdminsSelected
} from 'pages/country/widget/widget-selectors';
import { format } from 'd3-format';

import * as actions from './header-actions';
import reducers, { initialState } from './header-reducers';

import HeaderComponent from './header-component';

const mapStateToProps = ({ countryData, location, header }) => {
  const {
    isCountriesLoading,
    isRegionsLoading,
    isSubRegionsLoading
  } = countryData;
  const {
    isExtentLoading,
    isPlantationsLossLoading,
    isTotalLossLoading
  } = header;
  const countryDataLoading =
    isCountriesLoading || isRegionsLoading || isSubRegionsLoading;
  const headerDataLoading =
    isExtentLoading || isPlantationsLossLoading || isTotalLossLoading;
  const adminData = {
    countries: countryData.countries,
    regions: countryData.regions,
    subRegions: countryData.subRegions
  };
  return {
    isLoading: countryDataLoading || headerDataLoading,
    locationOptions: getAdminsOptions({
      ...adminData,
      location: location.payload
    }),
    settings: header.settings,
    location: location.payload,
    locationNames: getAdminsSelected({
      ...adminData,
      location: location.payload
    }),
    activeLocation: getActiveAdmin({ location: location.payload }),
    data: header.data
  };
};

const mapDispatchToProps = dispatch =>
  bindActionCreators(
    {
      handleCountryChange: country => ({
        type: COUNTRY,
        payload: { country: country.value }
      }),
      handleRegionChange: (country, region) => ({
        type: COUNTRY,
        payload: { country: country.value, region: region.value }
      }),
      handleSubRegionChange: (country, region, subRegion) => ({
        type: COUNTRY,
        payload: {
          country: country.value,
          region: region.value,
          subRegion: subRegion.value
        }
      }),
      ...actions
    },
    dispatch
  );

class HeaderContainer extends PureComponent {
  componentDidMount() {
    const {
      location,
      settings,
      getTotalExtent,
      getTotalLoss,
      getPlantationsLoss
    } = this.props;
    getTotalExtent({ ...location, ...settings });
    getTotalLoss({ ...location, ...settings });
    getPlantationsLoss({ ...location, ...settings, indicator: 'plantations' });
    if (location.region) {
      getTotalExtent({ ...location, ...settings });
    }
    if (location.subRegion) {
      getTotalExtent({ ...location, ...settings });
    }
  }

  componentWillReceiveProps(nextProps) {
    const { location, settings } = nextProps;
    const { getTotalExtent, getTotalLoss, getPlantationsLoss } = this.props;

    if (!isEqual(location, this.props.location)) {
      getTotalExtent({ ...nextProps.location, ...settings });
      getTotalLoss({ ...nextProps.location, ...settings });
      getPlantationsLoss({
        ...nextProps.location,
        ...settings,
        indicator: 'plantations'
      });
    }
  }

  getHeaderDescription = () => {
    const { locationNames, data } = this.props;
    const extent = format('.2s')(data.extent);
    const percentageCover = format('.1f')(data.extent / data.totalArea * 100);
    const lossWithOutPlantations = format('.2s')(
      data.totalLoss.area - (data.plantationsLoss.area || 0)
    );
    const emissionsWithoutPlantations = format('.2s')(
      data.totalLoss.emissions - (data.plantationsLoss.emissions || 0)
    );
    const location = locationNames.current && locationNames.current.label;
    let firstSentence = '';
    let secondSentence = '';
    if (extent > 0) {
      firstSentence = `
        In 2010, ${location} had ${extent}ha of tree cover, extending over ${percentageCover}% of its land area.
      `;
    } else {
      firstSentence = `
        In 2010, ${location} had no tree cover.
      `;
    }
    if (data.totalLoss.area) {
      secondSentence = `
        In ${
          data.totalLoss.year
        }, it lost ${lossWithOutPlantations}ha of forest ${
          data.plantationsLoss.area ? 'excluding tree plantations' : ''
        }, equivalent to ${emissionsWithoutPlantations}tonnes of CO₂ of emissions.
      `;
    }
    return `${firstSentence} ${secondSentence}`;
  };

  render() {
    return createElement(HeaderComponent, {
      ...this.props,
      getHeaderDescription: this.getHeaderDescription
    });
  }
}

HeaderContainer.propTypes = {
  location: PropTypes.object.isRequired,
  locationNames: PropTypes.object.isRequired,
  getTotalExtent: PropTypes.func.isRequired,
  getTotalLoss: PropTypes.func.isRequired,
  getPlantationsLoss: PropTypes.func.isRequired,
  data: PropTypes.object.isRequired,
  settings: PropTypes.object.isRequired
};

export { actions, reducers, initialState };

export default connect(mapStateToProps, mapDispatchToProps)(HeaderContainer);
<commit_msg>Fix/bugs that should not be (#3176)<commit_after>import { bindActionCreators } from 'redux';
import { createElement, PureComponent } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { COUNTRY } from 'pages/country/router';
import isEqual from 'lodash/isEqual';

import {
  getAdminsOptions,
  getActiveAdmin,
  getAdminsSelected
} from 'pages/country/widget/widget-selectors';
import { format } from 'd3-format';

import * as actions from './header-actions';
import reducers, { initialState } from './header-reducers';

import HeaderComponent from './header-component';

const mapStateToProps = ({ countryData, location, header }) => {
  const {
    isCountriesLoading,
    isRegionsLoading,
    isSubRegionsLoading
  } = countryData;
  const {
    isExtentLoading,
    isPlantationsLossLoading,
    isTotalLossLoading
  } = header;
  const countryDataLoading =
    isCountriesLoading || isRegionsLoading || isSubRegionsLoading;
  const headerDataLoading =
    isExtentLoading || isPlantationsLossLoading || isTotalLossLoading;
  const adminData = {
    countries: countryData.countries,
    regions: countryData.regions,
    subRegions: countryData.subRegions
  };
  return {
    isLoading: countryDataLoading || headerDataLoading,
    locationOptions: getAdminsOptions({
      ...adminData,
      location: location.payload
    }),
    settings: header.settings,
    location: location.payload,
    locationNames: getAdminsSelected({
      ...adminData,
      location: location.payload
    }),
    activeLocation: getActiveAdmin({ location: location.payload }),
    data: header.data
  };
};

const mapDispatchToProps = dispatch =>
  bindActionCreators(
    {
      handleCountryChange: country => ({
        type: COUNTRY,
        payload: { country: country.value }
      }),
      handleRegionChange: (country, region) => ({
        type: COUNTRY,
        payload: { country: country.value, region: region.value }
      }),
      handleSubRegionChange: (country, region, subRegion) => ({
        type: COUNTRY,
        payload: {
          country: country.value,
          region: region.value,
          subRegion: subRegion.value
        }
      }),
      ...actions
    },
    dispatch
  );

class HeaderContainer extends PureComponent {
  componentDidMount() {
    const {
      location,
      settings,
      getTotalExtent,
      getTotalLoss,
      getPlantationsLoss
    } = this.props;
    getTotalExtent({ ...location, ...settings });
    getTotalLoss({ ...location, ...settings });
    getPlantationsLoss({ ...location, ...settings, indicator: 'plantations' });
    if (location.region) {
      getTotalExtent({ ...location, ...settings });
    }
    if (location.subRegion) {
      getTotalExtent({ ...location, ...settings });
    }
  }

  componentWillReceiveProps(nextProps) {
    const { location, settings } = nextProps;
    const { getTotalExtent, getTotalLoss, getPlantationsLoss } = this.props;

    if (!isEqual(location, this.props.location)) {
      getTotalExtent({ ...nextProps.location, ...settings });
      getTotalLoss({ ...nextProps.location, ...settings });
      getPlantationsLoss({
        ...nextProps.location,
        ...settings,
        indicator: 'plantations'
      });
    }
  }

  getHeaderDescription = () => {
    const { locationNames, data } = this.props;
    const extent = format('.2s')(data.extent);
    const percentageCover = format('.1f')(data.extent / data.totalArea * 100);
    const lossWithOutPlantations = format('.2s')(
      data.totalLoss.area - (data.plantationsLoss.area || 0)
    );
    const emissionsWithoutPlantations = format('.2s')(
      data.totalLoss.emissions - (data.plantationsLoss.emissions || 0)
    );
    const location = locationNames.current && locationNames.current.label;
    let firstSentence = '';
    let secondSentence = '';
    if (data.extent > 0) {
      firstSentence = `
        In 2010, ${location} had ${extent}ha of tree cover, extending over ${percentageCover}% of its land area.
      `;
    } else {
      firstSentence = `
        In 2010, ${location} had no tree cover.
      `;
    }
    if (data.extent > 0 && data.totalLoss.area) {
      secondSentence = `
        In ${
          data.totalLoss.year
        }, it lost ${lossWithOutPlantations}ha of forest ${
          data.plantationsLoss.area ? 'excluding tree plantations' : ''
        }, equivalent to ${emissionsWithoutPlantations}tonnes of CO₂ of emissions.
      `;
    }
    return `${firstSentence} ${secondSentence}`;
  };

  render() {
    return createElement(HeaderComponent, {
      ...this.props,
      getHeaderDescription: this.getHeaderDescription
    });
  }
}

HeaderContainer.propTypes = {
  location: PropTypes.object.isRequired,
  locationNames: PropTypes.object.isRequired,
  getTotalExtent: PropTypes.func.isRequired,
  getTotalLoss: PropTypes.func.isRequired,
  getPlantationsLoss: PropTypes.func.isRequired,
  data: PropTypes.object.isRequired,
  settings: PropTypes.object.isRequired
};

export { actions, reducers, initialState };

export default connect(mapStateToProps, mapDispatchToProps)(HeaderContainer);
<|endoftext|>


<commit_before>'use strict'
const express = require('express')
const Slapp = require('slapp')
const ConvoStore = require('slapp-convo-beepboop')
const Context = require('slapp-context-beepboop')
const BeepBoop = require('beepboop')
const bodyParser = require('body-parser')
const parameters = require('parameters-middleware');
var request = require('request')
const slackey = require('slackey')
// use `PORT` env var on Beep Boop - default to 3000 locally
var port = process.env.PORT || 3000
var channels = {}

var slackAPIClient
var beepboop = BeepBoop.start()

beepboop.on('open', () => {
  console.log('connection to Beep Boop server opened')
})
beepboop.on('error', (error) => {
  console.log('Error from Beep Boop connection: ', err)
})
beepboop.on('close', (code, message) => {
  console.log('Connection to Beep Boop was closed')
})
beepboop.on('add_resource', (message) => {
  console.log('Team added: ', message);
  console.log(message.resource.SlackBotAccessToken);
  slackAPIClient = slackey.getAPIClient(message.resource.SlackBotAccessToken);
	fetchChannels();
})
var slapp = Slapp({
  // Beep Boop sets the SLACK_VERIFY_TOKEN env var
  verify_token: process.env.SLACK_VERIFY_TOKEN,
  convo_store: ConvoStore(),
  context: Context()
})
var app = express()
app.use(bodyParser.json());
app.post('/recommendations',
  parameters({body : ["channel", "title", "url"]}),
  (req, res) => {
    var channelId = req.body.channel
    var channel = channels[channelId]
    if (channel == null) return res.status(400).send("Channel not found")
    var verifiedIcon = req.body.verified ? "http://smallbusiness.support/wp-content/uploads/2015/10/facebook-verified.png" : "https://cdn1.iconfinder.com/data/icons/rounded-flat-country-flag-collection-1/2000/_Unknown.png"
    var attachment = {
    	callback_id: "share",
	      author_icon: verifiedIcon,
	      title_link: req.body.url,
	      title: req.body.title,
	      actions: [
	          {
	            "name": "post",
	            "text": "Post",
	            "type": "button",
	            "style": "primary",
	            "value": channelId
	          },
	          {
	            "name": "discard",
	            "text": "Discard",
	            "type": "button",
	            "style": "danger",
	            "value": "discarded"
	          },
	          {
                  "name": "post",
                  "text": "Share to channel...",
                  "type": "select",
                  "options": [
                	   {
            		      "text":"second",
            		      "value":5
            		   },
            		   {
            		      "text":"test",
            		      "value":6
            		   },
            		   {
            		      "text":"Test",
            		      "value":1
            		   }
                  ]
              }
	        ]
    }
    if (req.body.host) {
      attachment.author_name = req.body.host
        attachment.author_link = req.body.host
    }
    if (req.body.summary) {
        attachment.text = req.body.summary
    }
    if (req.body.image_url) {
        attachment.image_url = req.body.image_url
    }
    if (req.body.pub_date) {
        attachment.ts = Date.parse(req.body.pub_date)
    }

    // Populating fields
    var fields = []
    if (req.body.keywords) {
      fields.push({
        title: "Keywords",
        short: false,
        value: req.body.keywords
      })
    }
    if (req.body.companies) {
      fields.push({
        title: "Companies",
        short: false,
        value: req.body.companies
      })
    }
    if (req.body.word_count) {
      fields.push({
        title: "Length",
        short: true,
        value: req.body.word_count
      })
    }
    if (req.body.engagement) {
      fields.push({
        title: "Shares",
        short: true,
        value: formatCount(req.body.engagement)
      })
    }
    if (req.body.sentiment) {
    	fields.push({
            title: "Sentiment",
            short: true,
            value: req.body.sentiment
          })
    }
    fields.push({
    	"title": "Sponsored",
        "value": ":warning: Undetected",
        "short": true
    })
    attachment.fields = fields
    slackAPIClient.send('chat.postMessage',
          {
          channel,
          attachments: [attachment]
          },
          (err, response) => {
	          if (err) {
	            console.log(err)
	            res.status(500).send(err)
	          } else {
	            res.status(201).send(response)
	          }
          }
        )
  }
)

slapp.action('share', 'post', (msg, value) => {
    console.log(`Article ${msg.body.original_message.attachments[0].title_link} shared to channel ${value}`)
    var originalMsg = msg.body.original_message;
	var chosenAttachment = originalMsg.attachments[msg.body.attachment_id - 1];
	addUrlToChannel(value, msg.body.original_message.attachments[0].title_link)
		.then(() => {
			chosenAttachment.actions = []
			var lastAttachment = {
					pretext: `:postbox: Article posted to channel ${value}`
			}
			originalMsg.attachments = [chosenAttachment, lastAttachment]
			msg.respond(msg.body.response_url, originalMsg)
		})
		.catch((err) => {
			var lastAttachment = {
					pretext: ':exclamation: Error posting article to channel'
			}
			originalMsg.attachments = [chosenAttachment, lastAttachment]
			msg.respond(msg.body.response_url, originalMsg)
		})
})

function addUrlToChannel(channelId, url) {
	return new Promise((resolve, reject) => {
		request.post('http://itao-server-55663464.eu-central-1.elb.amazonaws.com/itao/item/add/url',
			{ json: {
				url: url
			}}, (err, res, body) => {
				if (err) return reject(err);
				if (!body.success) return reject(JSON.stringify(body));
				request.post('http://itao-server-55663464.eu-central-1.elb.amazonaws.com/itao/channel/item/add',
	    			{ json: {
	    				channel_id: channelId,
	    				url: url
	    			}}, (err2, res2, body2) => {
	    				if (err) return reject(err);
	    				if (!body.success) return reject(JSON.stringify(body));
	    				resolve();
			})
		})
	})
}

slapp.action('share', 'discard', (msg, value) => {
	var originalMsg = msg.body.original_message
	var chosenAttachment = originalMsg.attachments[msg.body.attachment_id - 1]
    chosenAttachment.actions = []
	var lastAttachment = {
		pretext: `:no_entry: Article discarded`,
	}
	originalMsg.attachments = [chosenAttachment, lastAttachment]
	msg.respond(msg.body.response_url, originalMsg)
})

function fetchChannels() {
  slackAPIClient.send('channels.list',
      function(err, response) {
        if (err) console.log(err)
          for (var i = 0; i < response.channels.length; i++) {
            var channel = response.channels[i]
            try {
              var channelNumber = channel.name.split("-")[0]
              if (!isNaN(channelNumber)) {
                channels[channelNumber] = channel.id
              }
            } catch (err) {
              console.log(err)
            }
          }
        console.log(`${Object.keys(channels).length} channels loaded`)
        }
  )
}

function formatCount(x) {
  var magnitude = Math.max(Math.floor(Math.log10(Math.abs(x))), 0);
  var postfix = ""
  if (magnitude >= 6) {
    magnitude -= 6
    postfix = "M"
  } else if (magnitude >= 3) {
    magnitude -= 3
    postfix = "k"
  }
  var first_digit = String(x).charAt(0);
  var rounded_significant = first_digit >= 5 ? 5 : 1;
  return String(rounded_significant * Math.pow(10, magnitude)) + postfix + "+"
}

// attach Slapp to express server
var server = slapp.attachToExpress(app)
// start http server
server.listen(port, (err) => {
  if (err) {
    return console.error(err)
  }

  console.log(`Listening on port ${port}`)
})
<commit_msg>minor fixes<commit_after>'use strict'
const express = require('express')
const Slapp = require('slapp')
const ConvoStore = require('slapp-convo-beepboop')
const Context = require('slapp-context-beepboop')
const BeepBoop = require('beepboop')
const bodyParser = require('body-parser')
const parameters = require('parameters-middleware');
var request = require('request')
const slackey = require('slackey')
// use `PORT` env var on Beep Boop - default to 3000 locally
var port = process.env.PORT || 3000
var channels = {}

var slackAPIClient
var beepboop = BeepBoop.start()

beepboop.on('open', () => {
  console.log('connection to Beep Boop server opened')
})
beepboop.on('error', (error) => {
  console.log('Error from Beep Boop connection: ', err)
})
beepboop.on('close', (code, message) => {
  console.log('Connection to Beep Boop was closed')
})
beepboop.on('add_resource', (message) => {
  console.log('Team added: ', message);
  console.log(message.resource.SlackBotAccessToken);
  slackAPIClient = slackey.getAPIClient(message.resource.SlackBotAccessToken);
	fetchChannels();
})
var slapp = Slapp({
  // Beep Boop sets the SLACK_VERIFY_TOKEN env var
  verify_token: process.env.SLACK_VERIFY_TOKEN,
  convo_store: ConvoStore(),
  context: Context()
})
var app = express()
app.use(bodyParser.json());
app.post('/recommendations',
  parameters({body : ["channel", "title", "url"]}),
  (req, res) => {
    var channelId = req.body.channel
    var channel = channels[channelId]
    if (channel == null) return res.status(400).send("Channel not found")
    var verifiedIcon = req.body.verified ? "http://smallbusiness.support/wp-content/uploads/2015/10/facebook-verified.png" : "https://cdn1.iconfinder.com/data/icons/rounded-flat-country-flag-collection-1/2000/_Unknown.png"
    var attachment = {
    	callback_id: "share",
	      author_icon: verifiedIcon,
	      title_link: req.body.url,
	      title: req.body.title,
	      actions: [
	          {
	            "name": "post",
	            "text": "Post",
	            "type": "button",
	            "style": "primary",
	            "value": channelId
	          },
	          {
	            "name": "discard",
	            "text": "Discard",
	            "type": "button",
	            "style": "danger",
	            "value": "discarded"
	          },
	          {
                  "name": "post",
                  "text": "Share to channel...",
                  "type": "select",
                  "options": [
                	   {
            		      "text":"second",
            		      "value":5
            		   },
            		   {
            		      "text":"test",
            		      "value":6
            		   },
            		   {
            		      "text":"Test",
            		      "value":1
            		   }
                  ]
              }
	        ]
    }
    if (req.body.host) {
      attachment.author_name = req.body.host
        attachment.author_link = req.body.host
    }
    if (req.body.summary) {
        attachment.text = req.body.summary
    }
    if (req.body.image_url) {
        attachment.image_url = req.body.image_url
    }
    if (req.body.pub_date) {
        attachment.ts = Date.parse(req.body.pub_date)
    }

    // Populating fields
    var fields = []
    if (req.body.keywords) {
      fields.push({
        title: "Keywords",
        short: false,
        value: req.body.keywords
      })
    }
    if (req.body.companies) {
      fields.push({
        title: "Companies",
        short: false,
        value: req.body.companies
      })
    }
    if (req.body.word_count) {
      fields.push({
        title: "Length",
        short: true,
        value: req.body.word_count
      })
    }
    if (req.body.shares) {
      fields.push({
        title: "Shares",
        short: true,
        value: formatCount(req.body.shares)
      })
    }
    if (req.body.sentiment) {
    	fields.push({
            title: "Sentiment",
            short: true,
            value: req.body.sentiment
          })
    }
    fields.push({
    	"title": "Sponsored",
        "value": ":warning: Undetected",
        "short": true
    })
    attachment.fields = fields
    slackAPIClient.send('chat.postMessage',
          {
          channel,
          attachments: [attachment]
          },
          (err, response) => {
	          if (err) {
	            console.log(err)
	            res.status(500).send(err)
	          } else {
	            res.status(201).send(response)
	          }
          }
        )
  }
)

slapp.action('share', 'post', (msg, value) => {
    console.log(`Article ${msg.body.original_message.attachments[0].title_link} shared to channel ${value}`)
    var originalMsg = msg.body.original_message;
	var chosenAttachment = originalMsg.attachments[msg.body.attachment_id - 1];
	addUrlToChannel(value, msg.body.original_message.attachments[0].title_link)
		.then(() => {
			chosenAttachment.actions = []
			var lastAttachment = {
					pretext: `:postbox: Article posted to channel ${value}`
			}
			originalMsg.attachments = [chosenAttachment, lastAttachment]
			msg.respond(msg.body.response_url, originalMsg)
		})
		.catch((err) => {
			var lastAttachment = {
					pretext: `:exclamation: Error posting article to channel ${value}`
			}
			originalMsg.attachments = [chosenAttachment, lastAttachment]
			msg.respond(msg.body.response_url, originalMsg)
		})
})

function addUrlToChannel(channelId, url) {
	return new Promise((resolve, reject) => {
		request.post('http://itao-server-55663464.eu-central-1.elb.amazonaws.com/itao/item/add/url',
			{ json: {
				url: url
			}}, (err, res, body) => {
				if (err) return reject(err);
				if (!body.success) return reject(JSON.stringify(body));
				request.post('http://itao-server-55663464.eu-central-1.elb.amazonaws.com/itao/channel/item/add',
	    			{ json: {
	    				channel_id: channelId,
	    				url: url
	    			}}, (err2, res2, body2) => {
	    				if (err) return reject(err);
	    				if (!body.success) return reject(JSON.stringify(body));
	    				resolve();
			})
		})
	})
}

slapp.action('share', 'discard', (msg, value) => {
	var originalMsg = msg.body.original_message
	var chosenAttachment = originalMsg.attachments[msg.body.attachment_id - 1]
    chosenAttachment.actions = []
	var lastAttachment = {
		pretext: `:no_entry: Article discarded`,
	}
	originalMsg.attachments = [chosenAttachment, lastAttachment]
	msg.respond(msg.body.response_url, originalMsg)
})

function fetchChannels() {
  slackAPIClient.send('channels.list',
      function(err, response) {
        if (err) console.log(err)
          for (var i = 0; i < response.channels.length; i++) {
            var channel = response.channels[i]
            try {
              var channelNumber = channel.name.split("-")[0]
              if (!isNaN(channelNumber)) {
                channels[channelNumber] = channel.id
              }
            } catch (err) {
              console.log(err)
            }
          }
        console.log(`${Object.keys(channels).length} channels loaded`)
        }
  )
}

function formatCount(x) {
  var magnitude = Math.max(Math.floor(Math.log10(Math.abs(x))), 0);
  var postfix = ""
  if (magnitude >= 6) {
    magnitude -= 6
    postfix = "M"
  } else if (magnitude >= 3) {
    magnitude -= 3
    postfix = "k"
  }
  var first_digit = String(x).charAt(0);
  var rounded_significant = first_digit >= 5 ? 5 : 1;
  return String(rounded_significant * Math.pow(10, magnitude)) + postfix + "+"
}

// attach Slapp to express server
var server = slapp.attachToExpress(app)
// start http server
server.listen(port, (err) => {
  if (err) {
    return console.error(err)
  }

  console.log(`Listening on port ${port}`)
})
<|endoftext|>


<commit_before>var express = require('express');

var app = express();
const PORT = process.env.PORT || 3000;

app.use(function (req, res, next){
  if (req.headers['x-forwarded-proto'] === 'http') {
    next();
  } else {
    res.redirect('http://' + req.hostname + req.url);
  }
});

app.use(express.static('public'));

app.listen(3000, function () {
  console.log('Express server is up on port ' + PORT);
});
<commit_msg>fixed error in server.js<commit_after>var express = require('express');

var app = express();
const PORT = process.env.PORT || 3000;

app.use(function(req, res, next) {
    if (req.headers['x-forwarded-proto'] === 'http') {
        next();
    } else {
        res.redirect('http://' + req.hostname + req.url);
    }
});

app.use(express.static('public'));

app.listen(PORT, function() {
    console.log('Express server is up on port ' + PORT);
});
<|endoftext|>


<commit_before>'use strict';

var express = require('express');
var routes = require('./app/routes/index.js');
var mongoose = require('mongoose');
var passport = require('passport');
var session = require('express-session');

var app = express();
require('dotenv').load();
require('./app/config/passport')(passport);

mongoose.connect(process.env.MONGO_URI);

app.use('/controllers', express.static(process.cwd() + '/app/controllers'));
app.use('/', express.static(process.cwd() + '/public'));
app.use('/common', express.static(process.cwd() + '/app/common'));

app.use(session({
	secret: 'secretClementine',
	resave: false,
	saveUninitialized: true
}));

app.use(passport.initialize());
app.use(passport.session());

routes(app, passport);

var port = process.env.PORT || 8080;
app.listen(port,  function () {
	console.log('Node.js listening on port ' + port + '...');
});
<commit_msg>remove some clementine stuff for test<commit_after>'use strict';

var express = require('express');
var routes = require('./app/routes/index.js');
var mongoose = require('mongoose');
var session = require('express-session');

var app = express();
require('dotenv').load();

mongoose.connect(process.env.MONGO_URI);

app.use('/controllers', express.static(process.cwd() + '/app/controllers'));
app.use('/', express.static(process.cwd() + '/public'));
app.use('/common', express.static(process.cwd() + '/app/common'));

var port = process.env.PORT || 8080;
app.listen(port,  function () {
	console.log('Node.js listening on port ' + port + '...');
});
<|endoftext|>


<commit_before>/**
 * jQuery UUID plugin 1.0.0
 *
 * @author Eugene Burtsev
 */
(function($) {
  $.uuid = function() {
		return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
			var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
			return v.toString(16);
		});
	};
})(jQuery);
<commit_msg>Remove unused $.uuid library<commit_after><|endoftext|>


<commit_before>var app = require('./server/server-config.js');

var bodyParser = require('body-parser')
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())

app.set('port', process.env.PORT || 4568);
app.listen(app.get('port'));

//will replace this with db
var storage = {};

app.post('/', function(req, res) {
    console.log("[req.body] :", req.body);   // [req.body] : undefined

    storage[req.body.user_id] = req.body;
    res.sendStatus(200);
});

app.get('/', function(req, res){
  console.log(storage);
  res.sendStatus(200);
});
console.log('Server listening on port ', app.get('port'));<commit_msg>Removed code that was removed in production branch.<commit_after>var app = require('./server/server-config.js');
app.set('port', process.env.PORT || 4568);
app.listen(app.get('port'));
console.log('Server listening on port ', app.get('port'));<|endoftext|>


<commit_before>var express = require('express')
var app = express()
var http=require('http')

var inbounds=0

var parseString = require('xml2js').parseString;

app.set('view engine', 'pug')

app.get('/', function (req, res) {
  res.render(
      'index',
      { title: 'INBOUND SMS', message: 'Inbound Number '+inbounds+' Received!'})
})

app.get('/inbound', function (req, res) {
    console.log('inbound text received')
    inbounds++
    console.log(req.query.xml)
    parseString(req.query.xml, function (err, result) {
        console.dir(result)
        console.log(result["phonenumber"])
    });
    res.render(
        'index',
        { title: 'INBOUND SMS', message: 'Inbound Number '+inbounds+' Received!'})
})

app.listen(8080, function () {
    console.log('Example app listening on port 8080!')
})
<commit_msg>phone 2<commit_after>var express = require('express')
var app = express()
var http=require('http')

var inbounds=0

var parseString = require('xml2js').parseString;

app.set('view engine', 'pug')

app.get('/', function (req, res) {
  res.render(
      'index',
      { title: 'INBOUND SMS', message: 'Inbound Number '+inbounds+' Received!'})
})

app.get('/inbound', function (req, res) {
    console.log('inbound text received')
    inbounds++
    console.log(req.query.xml)
    parseString(req.query.xml, function (err, result) {
        console.dir(result)
        console.log(result["PHONENUMBER"][0])
    });
    res.render(
        'index',
        { title: 'INBOUND SMS', message: 'Inbound Number '+inbounds+' Received!'})
})

app.listen(8080, function () {
    console.log('Example app listening on port 8080!')
})
<|endoftext|>


<commit_before>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var emojiFavicon = require('emoji-favicon');

var app = express();

var port = process.env.PORT || 5656;

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/bower', express.static(path.join(__dirname, 'bower_components')));

app.use('/up', require('./routes/up'));

app.use(emojiFavicon('smiley'));

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
app.use(function (err, req, res, next) {
  res.status(err.status || 500);
  res.send({
    message: err.message,
    error: err
  });
});

app.listen(port)
console.log("Listening on port " + port)

module.exports = app;
<commit_msg>Added random endpoint for login wifi<commit_after>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var emojiFavicon = require('emoji-favicon');

var app = express();

var port = process.env.PORT || 5656;

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/bower', express.static(path.join(__dirname, 'bower_components')));

app.use('/up', require('./routes/up'));

app.get('/r', function(req, res){
  var fiveSeconds = Math.floor(new Date().getTime() / 5000);
  if(req.query.r != fiveSeconds){
    res.redirect('?r='+fiveSeconds);
  } else {
    res.send('Safe');
  }
});

app.use(emojiFavicon('smiley'));

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
app.use(function (err, req, res, next) {
  res.status(err.status || 500);
  res.send({
    message: err.message,
    error: err
  });
});

app.listen(port)
console.log("Listening on port " + port)

module.exports = app;
<|endoftext|>


<commit_before>"use strict";

//Load dependencies
var async = require("async");
var applicationStorage = process.require("core/applicationStorage.js");
var mythicDungeonModel = process.require("mythicDungeons/mythicDungeonModel.js");
var realmModel = process.require("realms/realmModel.js");

module.exports.getRanking = function (req, res, next) {

    var logger = applicationStorage.logger;
    logger.info("%s %s %s %s %s", req.headers['x-forwarded-for'] || req.connection.remoteAddress, req.method, req.path, JSON.stringify(req.params), JSON.stringify(req.query));

    var criteria = {};

    if (req.query && req.query.affixes) {
        criteria.affixes = req.query.affixes.split('#');
    }

    if (req.query && req.query.dungeon) {
        criteria.dungeon = req.query.dungeon;
    }

    var limit;
    if (req.query && req.query.limit) {
        limit = parseInt(req.query.limit, 10);

        if (limit < 0) {
            limit = 50;
        }

        if (limit > 50) {
            limit = 50;
        }

    } else {
        limit = 50;
    }

    var skip = 0;
    if (req.query && req.query.page) {

        var page = parseInt(req.query.page, 10);
        if (!isNaN(page)) {
            if (page >= 1) {
                page--;
            }
            if (page < 0) {
                page = 0;
            }
            skip = page * limit;
        }

    }

    async.waterfall([
            function (callback) {
                if (req.query && req.query.region) {
                    var localeArray = req.query.region.split('#');
                    if (localeArray.length == 2) {
                        realmModel.find({
                            "bnet.locale": localeArray[0],
                            "bnet.timezone": {$regex: "^" + localeArray[1], $options: "i"}
                        }, {name: 1}, function (error, realms) {
                            if (realms.length > 0) {
                                criteria["$or"] = [];
                                realms.forEach(function (realm) {
                                    criteria['$or'].push({region:realm.region,realms: realm.name});
                                });
                                callback();
                            } else {
                                callback();
                            }
                        });
                    } else {
                        criteria.region = req.query.region;
                        callback();
                    }
                } else {
                    callback();
                }
            },
            function (callback) {
                if (req.query && req.query.region && req.query.realm) {
                    realmModel.findOne({
                        region: req.query.region,
                        name: req.query.realm
                    }, {connected_realms: 1,region:1}, function (error, realm) {
                        if (realm) {
                            criteria["$or"] = [];
                            realm.connected_realms.forEach(function (realmName) {
                                criteria['$or'].push({region:realm.region,realms: realmName});
                            });
                            callback();

                        } else {
                            callback();
                        }
                    });
                } else {
                    callback();
                }
            },
            function (callback) {
                mythicDungeonModel.find(req.params.extension, criteria, limit, skip, function (error, runs) {
                    callback(error, runs);
                });
            }

        ],
        function (error, runs) {
            if (error) {
                logger.error(error.message);
                res.status(500).send(error.message);
            } else if (runs && runs.length > 0) {
                res.json(runs);
            } else {
                next();
            }
        }
    );
};<commit_msg>Fix subregion issue<commit_after>"use strict";

//Load dependencies
var async = require("async");
var applicationStorage = process.require("core/applicationStorage.js");
var mythicDungeonModel = process.require("mythicDungeons/mythicDungeonModel.js");
var realmModel = process.require("realms/realmModel.js");

module.exports.getRanking = function (req, res, next) {

    var logger = applicationStorage.logger;
    logger.info("%s %s %s %s %s", req.headers['x-forwarded-for'] || req.connection.remoteAddress, req.method, req.path, JSON.stringify(req.params), JSON.stringify(req.query));

    var criteria = {};

    if (req.query && req.query.affixes) {
        criteria.affixes = req.query.affixes.split('#');
    }

    if (req.query && req.query.dungeon) {
        criteria.dungeon = req.query.dungeon;
    }

    var limit;
    if (req.query && req.query.limit) {
        limit = parseInt(req.query.limit, 10);

        if (limit < 0) {
            limit = 50;
        }

        if (limit > 50) {
            limit = 50;
        }

    } else {
        limit = 50;
    }

    var skip = 0;
    if (req.query && req.query.page) {

        var page = parseInt(req.query.page, 10);
        if (!isNaN(page)) {
            if (page >= 1) {
                page--;
            }
            if (page < 0) {
                page = 0;
            }
            skip = page * limit;
        }

    }

    async.waterfall([
            function (callback) {
                if (req.query && req.query.region) {
                    var localeArray = req.query.region.split('#');
                    if (localeArray.length == 2) {
                        realmModel.find({
                            "bnet.locale": localeArray[0],
                            "bnet.timezone": {$regex: "^" + localeArray[1], $options: "i"}
                        }, {name: 1,region:1}, function (error, realms) {
                            if (realms.length > 0) {
                                criteria["$or"] = [];
                                realms.forEach(function (realm) {
                                    criteria['$or'].push({region:realm.region,realms: realm.name});
                                });
                                callback();
                            } else {
                                callback();
                            }
                        });
                    } else {
                        criteria.region = req.query.region;
                        callback();
                    }
                } else {
                    callback();
                }
            },
            function (callback) {
                if (req.query && req.query.region && req.query.realm) {
                    realmModel.findOne({
                        region: req.query.region,
                        name: req.query.realm
                    }, {connected_realms: 1,region:1}, function (error, realm) {
                        if (realm) {
                            criteria["$or"] = [];
                            realm.connected_realms.forEach(function (realmName) {
                                criteria['$or'].push({region:realm.region,realms: realmName});
                            });
                            callback();

                        } else {
                            callback();
                        }
                    });
                } else {
                    callback();
                }
            },
            function (callback) {
                mythicDungeonModel.find(req.params.extension, criteria, limit, skip, function (error, runs) {
                    callback(error, runs);
                });
            }

        ],
        function (error, runs) {
            if (error) {
                logger.error(error.message);
                res.status(500).send(error.message);
            } else if (runs && runs.length > 0) {
                res.json(runs);
            } else {
                next();
            }
        }
    );
};<|endoftext|>


<commit_before>var config = {
  //Should be dynamic using for instance /tokeninfo endpoint
  scopes: {
    'BBC1': 'http://local.ebu.io:8001/',
    'BBC2': 'http://local.ebu.io:8002/',
    'BBC3': 'http://local.ebu.io:8003/'
  },
  apBaseUrl: 'http://local.ebu.io:8000/',
  modes: {
    'BBC1': { anonymous: false, client: true, user: true },
    'BBC2': { anonymous: false, client: true, user: true },
    'BBC3': { anonymous: false, client: true, user: true }
  }
};
aa
<commit_msg>Remove config.js<commit_after><|endoftext|>