<commit_before>'use strict';

// external deps
var ObjectId = require('mongodb').ObjectId;

// internal deps
require('mongodb-toolkit');
var BateeqModels = require('bateeq-models');
var map = BateeqModels.map;
var ItemManager = require('./item-manager');
var FinishedGoods = BateeqModels.master.FinishedGoods;
var ArticleMotifManager = require('./article/article-motif-manager');
var ArticleColorManager = require('./article/article-color-manager');

module.exports = class FinishedGoodsManager extends ItemManager {
    // constructor(db, user) {
    //     super(db, user);
    // }

    _getQuery(paging) {
        var basicFilter = {
            _deleted: false,
            _type: 'finished-goods'
        }, keywordFilter = {};

        var query = {};

        if (paging.keyword) {
            var regex = new RegExp(paging.keyword, "i");
            var filterCode = {
                'code': {
                    '$regex': regex
                }
            };
            var filterName = {
                'name': {
                    '$regex': regex
                }
            };

            keywordFilter = {
                '$or': [filterCode, filterName]
            };
        }
        query = { '$and': [basicFilter, paging.filter, keywordFilter] };
        return query;
    }

    // _validate(data) {
    //     return super._validate(new FinishedGoods(data));
    //     // var errors = {};
    //     // return new Promise((resolve, reject) => {
    //     //     // 1. begin: Declare promises.
    //     //     var getFinishedGoods = this.collection.singleOrDefault({
    //     //         "$and": [{
    //     //             _id: {
    //     //                 '$ne': new ObjectId(data._id)
    //     //             }
    //     //         }, {
    //     //             code: data.code
    //     //         }]
    //     //     });
    //     //     // 1. end: Declare promises.

    //     //     // 2. begin: Validation.
    //     //     Promise.all([getFinishedGoods])
    //     //         .then(results => {
    //     //             var _item = results[0];

    //     //             if (!data.code || data.code == '')
    //     //                 errors["code"] = "code is required";
    //     //             else if (_item)
    //     //                 errors["code"] = "code already exists";

    //     //             if (!data.name || data.name == '')
    //     //                 errors["name"] = "name is required";

    //     //             if (data.domesticCOGS == undefined || (data.domesticCOGS && data.domesticCOGS == '')) {
    //     //                 errors["domesticCOGS"] = "domesticCOGS is required";
    //     //             }
    //     //             else if (parseInt(data.domesticCOGS) < 0) {
    //     //                 errors["domesticCOGS"] = "domesticCOGS must be greater with 0";
    //     //             }
    //     //             if (data.domesticWholesale == undefined || (data.domesticWholesale && data.domesticWholesale == '')) {
    //     //                 errors["domesticWholesale"] = "domesticWholesale is required";
    //     //             }
    //     //             else if (parseInt(data.domesticWholesale) < 0) {
    //     //                 errors["domesticWholesale"] = "domesticWholesale must be greater with 0";
    //     //             }
    //     //             if (data.domesticRetail == undefined || (data.domesticRetail && data.domesticRetail == '')) {
    //     //                 errors["domesticRetail"] = "domesticRetail is required";
    //     //             }
    //     //             else if (parseInt(data.domesticRetail) < 0) {
    //     //                 errors["domesticRetail"] = "domesticRetail must be greater with 0";
    //     //             }
    //     //             if (data.domesticSale == undefined || (data.domesticSale && data.domesticSale == '')) {
    //     //                 errors["domesticSale"] = "domesticSale is required";
    //     //             }
    //     //             else if (parseInt(data.domesticSale) < 0) {
    //     //                 errors["domesticSale"] = "domesticSale must be greater with 0";
    //     //             }
    //     //             if (data.internationalCOGS == undefined || (data.internationalCOGS && data.internationalCOGS == '')) {
    //     //                 errors["internationalCOGS"] = "internationalCOGS is required";
    //     //             }
    //     //             else if (parseInt(data.internationalCOGS) < 0) {
    //     //                 errors["internationalCOGS"] = "internationalCOGS must be greater with 0";
    //     //             }
    //     //             if (data.internationalWholesale == undefined || (data.internationalWholesale && data.internationalWholesale == '')) {
    //     //                 errors["internationalWholesale"] = "internationalWholesale is required";
    //     //             }
    //     //             else if (parseInt(data.internationalWholesale) < 0) {
    //     //                 errors["internationalWholesale"] = "internationalWholesale must be greater with 0";
    //     //             }
    //     //             if (data.internationalRetail == undefined || (data.internationalRetail && data.internationalRetail == '')) {
    //     //                 errors["internationalRetail"] = "internationalRetail is required";
    //     //             }
    //     //             else if (parseInt(data.internationalRetail) < 0) {
    //     //                 errors["internationalRetail"] = "internationalRetail must be greater with 0";
    //     //             }
    //     //             if (data.internationalSale == undefined || (data.internationalSale && data.internationalSale == '')) {
    //     //                 errors["internationalSale"] = "internationalSale is required";
    //     //             }
    //     //             else if (parseInt(data.internationalSale) < 0) {
    //     //                 errors["internationalSale"] = "internationalSale must be greater with 0";
    //     //             }

    //     //             // 2c. begin: check if data has any error, reject if it has.
    //     //             for (var prop in errors) {
    //     //                 var ValidationError = require('../../validation-error');
    //     //                 reject(new ValidationError('data does not pass validation', errors));
    //     //             }

    //     //             var valid = new FinishedGoods(data);
    //     //             valid.stamp(this.user.username, 'manager');
    //     //             resolve(valid);
    //     //         })
    //     //         .catch(e => {
    //     //             reject(e);
    //     //         })
    //     // });
    // }

    updateImage(colorCode, articleColor, products, imagePath, motifPath) {
        return new Promise((resolve, reject) => {
            var dataError = {};
            if (colorCode === "") {
                dataError["colorCode"] = "Kode warna harus diisi";
            }

            var articleMotifCode = "";

            if (!products || products.length == 0) {
                dataError["dataDestination"] = "Produk harus dipilih";
            } else {
                articleMotifCode = products[0].code.substring(9, 11);
            }

            var getItems = [];
            for (var item of products) {
                getItems.push(this.getByCode(item.code));
            }

            var motifManager = new ArticleMotifManager(this.db, this.user);
            var getMotif = motifManager.getSingleByQueryOrDefault({
                "code": articleMotifCode
            })

            var colorManager = new ArticleColorManager(this.db, this.user);
            var getColor = colorManager.getSingleByIdOrDefault(articleColor._id);

            Promise.all([getMotif, getColor].concat(getItems))
                .then(results => {
                    if (results[0] && results[1] && results.length > 2) {

                        var motif = results[0];
                        var color = results[1];
                        motif["filePath"] = motifPath;
                        var updateMotif = motifManager.update(motif);

                        var updateItem = [];
                        for (var i = 2; i < results.length; i++) {
                            var item = results[i];
                            item["imagePath"] = imagePath;
                            item["motifPath"] = imagePath;
                            item["motifDoc"] = motif;
                            item["colorCode"] = colorCode;
                            item["colorDoc"] = color;
                            updateItem.push(this.update(item));
                        }

                        Promise.all([updateMotif].concat(updateItem))
                            .then(updateResults => {
                                resolve(updateResults);
                            })
                            .catch(updateErrors => {
                                reject(updateErrors);
                            })
                    } else {
                        if (!results[2]) {
                            dataError["dataDestination"] = "produk tidak ditemukan";
                        }
                        if (!results[0]) {
                            dataError["motifUpload"] = "isi master motif terlebih dahulu. ";
                        }
                        if (!results[1]) {
                            dataError["color"] = "article color tidak ditemukan";
                        }

                        for (var prop in dataError) {
                            var ValidationError = require('module-toolkit').ValidationError;
                            reject(new ValidationError('data does not pass validation', dataError));
                        }
                    }
                })
                .catch(errors => {
                    reject(errors);
                });
        });
    }

    insert(dataFile) {
        return new Promise((resolve, reject) => {
            var data = [];
            if (dataFile != "") {
                for (var i = 1; i < dataFile.length; i++) {
                    data.push({ "code": dataFile[i][0], "name": dataFile[i][1], "uom": dataFile[i][2], "size": dataFile[i][3], "domesticCOGS": dataFile[i][4], "domesticSale": dataFile[i][5], "internationalSale": dataFile[i][6], "realizationOrder": dataFile[i][7] });
                }
            }
            var dataError = [], errorMessage;
            for (var i = 0; i < data.length; i++) {
                errorMessage = "";
                if (data[i]["code"] === "") {
                    errorMessage = errorMessage + "Barcode List tidak boleh kosong,";
                }
                if (data[i]["name"] === "") {
                    errorMessage = errorMessage + "Nama tidak boleh kosong,";
                }
                if (data[i]["size"] === "") {
                    errorMessage = errorMessage + "Size tidak boleh kosong,";
                }
                if (data[i]["domesticCOGS"] === "") {
                    errorMessage = errorMessage + "HPP tidak boleh kosong,";
                }
                if (data[i]["domesticCOGS"] !== "" || data[i]["domesticCOGS"] !== " ") {
                    if (isNaN(data[i]["domesticCOGS"])) {
                        errorMessage = errorMessage + "HPP harus numerik,";
                    }
                }
                if (data[i]["domesticSale"] === "") {
                    errorMessage = errorMessage + "Harga Jual (Domestic) tidak boleh kosong,";
                }
                if (data[i]["domesticSale"] !== "" || data[i]["domesticSale"] !== " ") {
                    if (isNaN(data[i]["domesticSale"])) {
                        errorMessage = errorMessage + "Harga Jual (Domestic) harus numerik,";
                    }
                }
                if (data[i]["internationalSale"] === "") {
                    errorMessage = errorMessage + "Harga Jual (Internasional) tidak boleh kosong,";
                }
                if (data[i]["internationalSale"] !== "" || data[i]["internationalSale"] !== " ") {
                    if (isNaN(data[i]["internationalSale"])) {
                        errorMessage = errorMessage + "Harga Jual (Internasional) harus numerik,";
                    }
                }
                if (data[i]["realizationOrder"] === "") {
                    errorMessage = errorMessage + "RO tidak boleh kosong,";
                }

                if (errorMessage !== "") {
                    dataError.push({ "Barcode": data[i]["code"], "Nama": data[i]["name"], "UOM": data[i]["uom"], "Size": data[i]["size"], "HPP": data[i]["domesticCOGS"], "Harga Jual (Domestic)": data[i]["domesticSale"], "Harga Jual (Internasional)": data[i]["internationalSale"], "RO": data[i]["realizationOrder"], "Error": errorMessage });
                }
            }
            if (dataError.length === 0) {
                var fgTemp = [];
                for (var fg of data) {
                    var finished = new Promise((resolve, reject) => {
                        var item = fg;
                        this.getByCode(item.code)
                            .then(resultItem => {
                                if (resultItem) {
                                    resultItem.name = item.name;
                                    resultItem.uom = item.uom;
                                    resultItem.size = item.size;
                                    resultItem.domesticCOGS = item.domesticCOGS;
                                    resultItem.domesticSale = item.domesticSale;
                                    resultItem.internationalSale = item.internationalSale;
                                    resultItem.article.realizationOrder = item.realizationOrder;
                                    this.update(resultItem)
                                        .then(id => {
                                            this.getSingleById(id)
                                                .then(resultItem => {
                                                    // fgTemp.push(resultItem)
                                                    resolve(resultItem);
                                                })
                                                .catch(e => {
                                                    reject(e);
                                                });
                                        })
                                        .catch(e => {
                                            reject(e);
                                        });
                                }
                                else {
                                    var finishGood = new FinishedGoods();
                                    finishGood.code = item.code;
                                    finishGood.name = item.name;
                                    finishGood.uom = item.uom;
                                    finishGood.size = item.size;
                                    finishGood.domesticCOGS = item.domesticCOGS;
                                    finishGood.internationalSale = item.internationalSale;
                                    finishGood.domesticSale = item.domesticSale;
                                    finishGood.article.realizationOrder = item.realizationOrder;
                                    this.create(finishGood)
                                        .then(id => {
                                            this.getSingleById(id)
                                                .then(resultItem => {
                                                    // fgTemp.push(resultItem)
                                                    resolve(resultItem);
                                                })
                                                .catch(e => {
                                                    reject(e);
                                                });
                                        })
                                        .catch(e => {
                                            reject(e);
                                        });
                                }
                            })
                            .catch(e => {
                                reject(e);
                            });
                    });
                    fgTemp.push(finished);
                }

                Promise.all(fgTemp)
                    .then(resultItem => {
                        resolve(resultItem);
                    })
                    .catch(e => {
                        reject(e);
                    });
            } else {
                resolve(dataError);
            }

        });
    }
};<commit_msg>update uploadImage<commit_after>'use strict';

// external deps
var ObjectId = require('mongodb').ObjectId;

// internal deps
require('mongodb-toolkit');
var BateeqModels = require('bateeq-models');
var map = BateeqModels.map;
var ItemManager = require('./item-manager');
var FinishedGoods = BateeqModels.master.FinishedGoods;
var ArticleMotifManager = require('./article/article-motif-manager');
var ArticleColorManager = require('./article/article-color-manager');

module.exports = class FinishedGoodsManager extends ItemManager {
    // constructor(db, user) {
    //     super(db, user);
    // }

    _getQuery(paging) {
        var basicFilter = {
            _deleted: false,
            _type: 'finished-goods'
        }, keywordFilter = {};

        var query = {};

        if (paging.keyword) {
            var regex = new RegExp(paging.keyword, "i");
            var filterCode = {
                'code': {
                    '$regex': regex
                }
            };
            var filterName = {
                'name': {
                    '$regex': regex
                }
            };

            keywordFilter = {
                '$or': [filterCode, filterName]
            };
        }
        query = { '$and': [basicFilter, paging.filter, keywordFilter] };
        return query;
    }

    // _validate(data) {
    //     return super._validate(new FinishedGoods(data));
    //     // var errors = {};
    //     // return new Promise((resolve, reject) => {
    //     //     // 1. begin: Declare promises.
    //     //     var getFinishedGoods = this.collection.singleOrDefault({
    //     //         "$and": [{
    //     //             _id: {
    //     //                 '$ne': new ObjectId(data._id)
    //     //             }
    //     //         }, {
    //     //             code: data.code
    //     //         }]
    //     //     });
    //     //     // 1. end: Declare promises.

    //     //     // 2. begin: Validation.
    //     //     Promise.all([getFinishedGoods])
    //     //         .then(results => {
    //     //             var _item = results[0];

    //     //             if (!data.code || data.code == '')
    //     //                 errors["code"] = "code is required";
    //     //             else if (_item)
    //     //                 errors["code"] = "code already exists";

    //     //             if (!data.name || data.name == '')
    //     //                 errors["name"] = "name is required";

    //     //             if (data.domesticCOGS == undefined || (data.domesticCOGS && data.domesticCOGS == '')) {
    //     //                 errors["domesticCOGS"] = "domesticCOGS is required";
    //     //             }
    //     //             else if (parseInt(data.domesticCOGS) < 0) {
    //     //                 errors["domesticCOGS"] = "domesticCOGS must be greater with 0";
    //     //             }
    //     //             if (data.domesticWholesale == undefined || (data.domesticWholesale && data.domesticWholesale == '')) {
    //     //                 errors["domesticWholesale"] = "domesticWholesale is required";
    //     //             }
    //     //             else if (parseInt(data.domesticWholesale) < 0) {
    //     //                 errors["domesticWholesale"] = "domesticWholesale must be greater with 0";
    //     //             }
    //     //             if (data.domesticRetail == undefined || (data.domesticRetail && data.domesticRetail == '')) {
    //     //                 errors["domesticRetail"] = "domesticRetail is required";
    //     //             }
    //     //             else if (parseInt(data.domesticRetail) < 0) {
    //     //                 errors["domesticRetail"] = "domesticRetail must be greater with 0";
    //     //             }
    //     //             if (data.domesticSale == undefined || (data.domesticSale && data.domesticSale == '')) {
    //     //                 errors["domesticSale"] = "domesticSale is required";
    //     //             }
    //     //             else if (parseInt(data.domesticSale) < 0) {
    //     //                 errors["domesticSale"] = "domesticSale must be greater with 0";
    //     //             }
    //     //             if (data.internationalCOGS == undefined || (data.internationalCOGS && data.internationalCOGS == '')) {
    //     //                 errors["internationalCOGS"] = "internationalCOGS is required";
    //     //             }
    //     //             else if (parseInt(data.internationalCOGS) < 0) {
    //     //                 errors["internationalCOGS"] = "internationalCOGS must be greater with 0";
    //     //             }
    //     //             if (data.internationalWholesale == undefined || (data.internationalWholesale && data.internationalWholesale == '')) {
    //     //                 errors["internationalWholesale"] = "internationalWholesale is required";
    //     //             }
    //     //             else if (parseInt(data.internationalWholesale) < 0) {
    //     //                 errors["internationalWholesale"] = "internationalWholesale must be greater with 0";
    //     //             }
    //     //             if (data.internationalRetail == undefined || (data.internationalRetail && data.internationalRetail == '')) {
    //     //                 errors["internationalRetail"] = "internationalRetail is required";
    //     //             }
    //     //             else if (parseInt(data.internationalRetail) < 0) {
    //     //                 errors["internationalRetail"] = "internationalRetail must be greater with 0";
    //     //             }
    //     //             if (data.internationalSale == undefined || (data.internationalSale && data.internationalSale == '')) {
    //     //                 errors["internationalSale"] = "internationalSale is required";
    //     //             }
    //     //             else if (parseInt(data.internationalSale) < 0) {
    //     //                 errors["internationalSale"] = "internationalSale must be greater with 0";
    //     //             }

    //     //             // 2c. begin: check if data has any error, reject if it has.
    //     //             for (var prop in errors) {
    //     //                 var ValidationError = require('../../validation-error');
    //     //                 reject(new ValidationError('data does not pass validation', errors));
    //     //             }

    //     //             var valid = new FinishedGoods(data);
    //     //             valid.stamp(this.user.username, 'manager');
    //     //             resolve(valid);
    //     //         })
    //     //         .catch(e => {
    //     //             reject(e);
    //     //         })
    //     // });
    // }

    updateImage(colorCode, articleColor, products, imagePath, motifPath) {
        return new Promise((resolve, reject) => {
            var dataError = {};
            if (colorCode === "") {
                dataError["colorCode"] = "Kode warna harus diisi";
            }

            var articleMotifCode = "";

            if (!products || products.length == 0) {
                dataError["dataDestination"] = "Produk harus dipilih";
            } else {
                articleMotifCode = products[0].code.substring(9, 11);
            }

            var getItems = [];
            for (var item of products) {
                getItems.push(this.getByCode(item.code));
            }

            var motifManager = new ArticleMotifManager(this.db, this.user);
            var getMotif = motifManager.getSingleByQueryOrDefault({
                "code": articleMotifCode
            })

            var colorManager = new ArticleColorManager(this.db, this.user);
            var getColor = colorManager.getSingleByIdOrDefault(articleColor._id);

            Promise.all([getMotif, getColor].concat(getItems))
                .then(results => {
                    if (results[0] && results[1] && results.length > 2) {

                        var motif = results[0];
                        var color = results[1];
                        motif["filePath"] = motifPath;
                        var updateMotif = motifManager.update(motif);

                        var updateItem = [];
                        for (var i = 2; i < results.length; i++) {
                            var item = results[i];
                            item["imagePath"] = imagePath;
                            item["motifPath"] = motifPath;
                            item["motifDoc"] = motif;
                            item["colorCode"] = colorCode;
                            item["colorDoc"] = color;
                            updateItem.push(this.update(item));
                        }

                        Promise.all([updateMotif].concat(updateItem))
                            .then(updateResults => {
                                resolve(updateResults);
                            })
                            .catch(updateErrors => {
                                reject(updateErrors);
                            })
                    } else {
                        if (!results[2]) {
                            dataError["dataDestination"] = "produk tidak ditemukan";
                        }
                        if (!results[0]) {
                            dataError["motifUpload"] = "isi master motif terlebih dahulu. ";
                        }
                        if (!results[1]) {
                            dataError["color"] = "article color tidak ditemukan";
                        }

                        for (var prop in dataError) {
                            var ValidationError = require('module-toolkit').ValidationError;
                            reject(new ValidationError('data does not pass validation', dataError));
                        }
                    }
                })
                .catch(errors => {
                    reject(errors);
                });
        });
    }

    insert(dataFile) {
        return new Promise((resolve, reject) => {
            var data = [];
            if (dataFile != "") {
                for (var i = 1; i < dataFile.length; i++) {
                    data.push({ "code": dataFile[i][0], "name": dataFile[i][1], "uom": dataFile[i][2], "size": dataFile[i][3], "domesticCOGS": dataFile[i][4], "domesticSale": dataFile[i][5], "internationalSale": dataFile[i][6], "realizationOrder": dataFile[i][7] });
                }
            }
            var dataError = [], errorMessage;
            for (var i = 0; i < data.length; i++) {
                errorMessage = "";
                if (data[i]["code"] === "") {
                    errorMessage = errorMessage + "Barcode List tidak boleh kosong,";
                }
                if (data[i]["name"] === "") {
                    errorMessage = errorMessage + "Nama tidak boleh kosong,";
                }
                if (data[i]["size"] === "") {
                    errorMessage = errorMessage + "Size tidak boleh kosong,";
                }
                if (data[i]["domesticCOGS"] === "") {
                    errorMessage = errorMessage + "HPP tidak boleh kosong,";
                }
                if (data[i]["domesticCOGS"] !== "" || data[i]["domesticCOGS"] !== " ") {
                    if (isNaN(data[i]["domesticCOGS"])) {
                        errorMessage = errorMessage + "HPP harus numerik,";
                    }
                }
                if (data[i]["domesticSale"] === "") {
                    errorMessage = errorMessage + "Harga Jual (Domestic) tidak boleh kosong,";
                }
                if (data[i]["domesticSale"] !== "" || data[i]["domesticSale"] !== " ") {
                    if (isNaN(data[i]["domesticSale"])) {
                        errorMessage = errorMessage + "Harga Jual (Domestic) harus numerik,";
                    }
                }
                if (data[i]["internationalSale"] === "") {
                    errorMessage = errorMessage + "Harga Jual (Internasional) tidak boleh kosong,";
                }
                if (data[i]["internationalSale"] !== "" || data[i]["internationalSale"] !== " ") {
                    if (isNaN(data[i]["internationalSale"])) {
                        errorMessage = errorMessage + "Harga Jual (Internasional) harus numerik,";
                    }
                }
                if (data[i]["realizationOrder"] === "") {
                    errorMessage = errorMessage + "RO tidak boleh kosong,";
                }

                if (errorMessage !== "") {
                    dataError.push({ "Barcode": data[i]["code"], "Nama": data[i]["name"], "UOM": data[i]["uom"], "Size": data[i]["size"], "HPP": data[i]["domesticCOGS"], "Harga Jual (Domestic)": data[i]["domesticSale"], "Harga Jual (Internasional)": data[i]["internationalSale"], "RO": data[i]["realizationOrder"], "Error": errorMessage });
                }
            }
            if (dataError.length === 0) {
                var fgTemp = [];
                for (var fg of data) {
                    var finished = new Promise((resolve, reject) => {
                        var item = fg;
                        this.getByCode(item.code)
                            .then(resultItem => {
                                if (resultItem) {
                                    resultItem.name = item.name;
                                    resultItem.uom = item.uom;
                                    resultItem.size = item.size;
                                    resultItem.domesticCOGS = item.domesticCOGS;
                                    resultItem.domesticSale = item.domesticSale;
                                    resultItem.internationalSale = item.internationalSale;
                                    resultItem.article.realizationOrder = item.realizationOrder;
                                    this.update(resultItem)
                                        .then(id => {
                                            this.getSingleById(id)
                                                .then(resultItem => {
                                                    // fgTemp.push(resultItem)
                                                    resolve(resultItem);
                                                })
                                                .catch(e => {
                                                    reject(e);
                                                });
                                        })
                                        .catch(e => {
                                            reject(e);
                                        });
                                }
                                else {
                                    var finishGood = new FinishedGoods();
                                    finishGood.code = item.code;
                                    finishGood.name = item.name;
                                    finishGood.uom = item.uom;
                                    finishGood.size = item.size;
                                    finishGood.domesticCOGS = item.domesticCOGS;
                                    finishGood.internationalSale = item.internationalSale;
                                    finishGood.domesticSale = item.domesticSale;
                                    finishGood.article.realizationOrder = item.realizationOrder;
                                    this.create(finishGood)
                                        .then(id => {
                                            this.getSingleById(id)
                                                .then(resultItem => {
                                                    // fgTemp.push(resultItem)
                                                    resolve(resultItem);
                                                })
                                                .catch(e => {
                                                    reject(e);
                                                });
                                        })
                                        .catch(e => {
                                            reject(e);
                                        });
                                }
                            })
                            .catch(e => {
                                reject(e);
                            });
                    });
                    fgTemp.push(finished);
                }

                Promise.all(fgTemp)
                    .then(resultItem => {
                        resolve(resultItem);
                    })
                    .catch(e => {
                        reject(e);
                    });
            } else {
                resolve(dataError);
            }

        });
    }
};<|endoftext|>


<commit_before>/**
 * Created by ivar on 21.11.15.
 */

define([
    'config/stateConfig',
    'config/global',
    'angular-ui-router',
    'angular-messages',
    'angular-sanitize',
    'ui-bootstrap',
    'angular-storage',
    'angular-animate',
    'angular-scroll',
    'angular-scroll-glue',
    'angular-ui-select',
    'angular-vertilize'
], function (stateConfig, globalConf/*etTranslations, $ocLazyLoad*/) {

    var app = angular.module('myApp', [
        'ui.router',
        'ui.bootstrap',
        'ui.select',
        'ngCookies',
        'ngResource',
        'ngStorage',
        'ngAnimate',
        'ngSanitize',
        'ngMessages',
        'duScroll',
        'angular.vertilize',
        'luegg.directives',
        'angularSpinners'
    ]);

    app.constant('config', globalConf);

    app.config(function($animateProvider) {
        $animateProvider.classNameFilter(/angular-animate/);
    });

    app.config(function(uiSelectConfig) {
        uiSelectConfig.theme = 'bootstrap';
    });

    app.config(function ($provide, $httpProvider) {

  	  // Intercept http calls.
  	  $provide.factory('MyHttpInterceptor', function ($q) {
  	    return {
  	      // On request success
  	      request: function (config) {
  	        // console.log(config); // Contains the data about the request before it is sent.
  	        // Return the config or wrap it in a promise if blank.
  	        return config || $q.when(config);
  	      },

  	      // On request failure
  	      requestError: function (rejection) {
  	        // console.log(rejection); // Contains the data about the error on the request.
  	        console.log('requestError');
  	        // Return the promise rejection.
  	        return $q.reject(rejection);
  	      },

  	      // On response success
  	      response: function (response) {
  	        // console.log(response); // Contains the data from the response.
  	        // Return the response or promise.
  	        return response || $q.when(response);
  	      },

  	      // On response failure
  	      responseError: function (rejection) {
  	        // console.log(rejection); // Contains the data about the error.
  	    	 console.log('wnwbApi responseError');

  	    	  if (rejection.status == 500){
  	    		 alert('Sorry, something went wrong.'
  	    				 + "\n" + rejection.status + ' ' + rejection.statusText
  	    				 + "\n" + rejection.config.url);
  	    	  }
  	    	 else if (rejection.status == 401){

  	    		/* alert('Please login first.'
  	    				 + "\n" + rejection.status + ' ' + rejection.statusText
  	    				 + "\n" + rejection.config.url); */
  	    	  }
  	    	  else if (rejection.status == 404){

  	    		 alert('Sorry, something went wrong.'
  	    				 + "\n" + rejection.status + ' ' + rejection.statusText
  	    				 + "\n" + rejection.config.url);
  	    	  }

  	        // Return the promise rejection.
  	        return $q.reject(rejection);
  	      }
  	    };
  	  });
  	  // Intercept http calls.

  	  // Add the interceptor to the $httpProvider.
  	  $httpProvider.interceptors.push('MyHttpInterceptor');

  	});
    var defaultResponseTransformer = function (data, headersGetter) {

        return JSON.parse(data).results;
    };

    app.factory('wnwbApi', ['config', '$resource', function(config, $resource) {
        return {
            Version: $resource(config.API_URL+'version/', {}, {}, {stripTrailingSlashes: false}),
            sensereltype: $resource(config.API_URL+'sensereltype/:id/', {}, {}, {stripTrailingSlashes: false}),
            Authorization: $resource(config.API_AUTH_URL, {}, {
                auth: {
                    method: 'POST',
                    params: {

                    }
                }
            }, {stripTrailingSlashes: false}),
            Lexicon: $resource(config.API_URL+'lexicon/:id/', {}, {
                get: {
                    method: 'GET',
                    isArray: false
                },
                query: {
                    method: 'GET',
                    transformResponse: [defaultResponseTransformer],
                    isArray: true
                }
            }, {stripTrailingSlashes: false}),
            Sense: $resource(config.API_URL+'sense/:id/', {}, {
                update: {
                    method: 'PUT'
                },
                query: {
                    method: 'GET',
                    transformResponse: [defaultResponseTransformer],
                    isArray: true
                },
                remove: {
                	method: 'DELETE'
                }
            }, {stripTrailingSlashes: false}),
            SynSet: $resource(config.API_URL+'synset/:id/', {}, {
                update: {
                    method: 'PUT'
                },
                query: {
                    method: 'GET',
                    transformResponse: [defaultResponseTransformer],
                    isArray: true
                },
                remove: {
                	method: 'DELETE'
                }
            }, {stripTrailingSlashes: false}),
            HyperonymRelTree: $resource(config.API_URL+'hypers/', {}, {
                get: {
                    method: 'GET',
                    isArray: true
                }
            }, {stripTrailingSlashes: false}),
            HyponymRelTree: $resource(config.API_URL+'hypos/', {}, {
                get: {
                    method: 'GET',
                    isArray: true
                }
            }, {stripTrailingSlashes: false}),
            SiblingRelTree: $resource(config.API_URL+'sibs/', {}, {
                get: {
                    method: 'GET',
                    isArray: true
                }
            }, {stripTrailingSlashes: false}),
            OtherRelTree: $resource(config.API_URL+'rels/', {}, {
                get: {
                    method: 'GET',
                    isArray: true
                }
            }, {stripTrailingSlashes: false}),
            SenseRel: $resource(config.API_URL+'senserel/:id/', {}, {}, {stripTrailingSlashes: false}),
            SynSetRel: $resource(config.API_URL+'synsetrel/:id/', {}, {}, {stripTrailingSlashes: false}),
            SenseRelType: $resource(config.API_URL+'sensereltype/:id/', {}, {
                update: {
                    method: 'PUT'
                },
                query: {
                    method: 'GET',
                    transformResponse: [defaultResponseTransformer],
                    isArray: true
                }
            }, {stripTrailingSlashes: false}),
            SenseStyle: $resource(config.API_URL+'refcode/:id/', {}, {
                update: {
                    method: 'PUT'
                },
                query: {
                    method: 'GET',
                    transformResponse: [defaultResponseTransformer],
                    isArray: true
                }
            }, {stripTrailingSlashes: false}),
            SynSetRelType: $resource(config.API_URL+'synsetreltype/:id/', {}, {
                update: {
                    method: 'PUT'
                },
                query: {
                    method: 'GET',
                    transformResponse: [defaultResponseTransformer],
                    isArray: true
                }
            }, {stripTrailingSlashes: false}),
            ExtRelType: $resource(config.API_URL+'extreltype/:id/', {}, {
                update: {
                    method: 'PUT'
                },
                query: {
                    method: 'GET',
                    transformResponse: [defaultResponseTransformer],
                    isArray: true
                }
            }, {stripTrailingSlashes: false}),
            ExtSystem: $resource(config.API_URL+'extsystem/:id/', {}, {
                update: {
                    method: 'PUT'
                },
                query: {
                    method: 'GET',
                    transformResponse: [defaultResponseTransformer],
                    isArray: true
                }
            }, {stripTrailingSlashes: false}),
            LexicalEntry: $resource(config.API_URL+'lexentry/', {}, {
                query: {
                    method: 'GET',
                    transformResponse: [defaultResponseTransformer],
                    isArray: true
                }
            }, {stripTrailingSlashes: false}),
             LexicalEntryUsage: $resource(config.API_URL+'lexentryusage/', {}, {
                query: {
                    method: 'GET',
                    //transformResponse: [defaultResponseTransformer],
                    isArray: true
                }
            }, {stripTrailingSlashes: false}),
            Statistics: $resource(config.API_URL+'stats/', {}, {
                query: {
                    method: 'GET',
                    isArray: true
                }
            }, {stripTrailingSlashes: false}),
            Principal: $resource(config.API_URL+'users/?principal', {}, {
                query: {
                    method: 'GET',
                    transformResponse: [defaultResponseTransformer],
                    isArray: true
                }
            }, {stripTrailingSlashes: false})
        };
    }]);

    return app;
});<commit_msg>new query factory ExtRel<commit_after>/**
 * Created by ivar on 21.11.15.
 */

define([
    'config/stateConfig',
    'config/global',
    'angular-ui-router',
    'angular-messages',
    'angular-sanitize',
    'ui-bootstrap',
    'angular-storage',
    'angular-animate',
    'angular-scroll',
    'angular-scroll-glue',
    'angular-ui-select',
    'angular-vertilize'
], function (stateConfig, globalConf/*etTranslations, $ocLazyLoad*/) {

    var app = angular.module('myApp', [
        'ui.router',
        'ui.bootstrap',
        'ui.select',
        'ngCookies',
        'ngResource',
        'ngStorage',
        'ngAnimate',
        'ngSanitize',
        'ngMessages',
        'duScroll',
        'angular.vertilize',
        'luegg.directives',
        'angularSpinners'
    ]);

    app.constant('config', globalConf);

    app.config(function($animateProvider) {
        $animateProvider.classNameFilter(/angular-animate/);
    });

    app.config(function(uiSelectConfig) {
        uiSelectConfig.theme = 'bootstrap';
    });

    app.config(function ($provide, $httpProvider) {

  	  // Intercept http calls.
  	  $provide.factory('MyHttpInterceptor', function ($q) {
  	    return {
  	      // On request success
  	      request: function (config) {
  	        // console.log(config); // Contains the data about the request before it is sent.
  	        // Return the config or wrap it in a promise if blank.
  	        return config || $q.when(config);
  	      },

  	      // On request failure
  	      requestError: function (rejection) {
  	        // console.log(rejection); // Contains the data about the error on the request.
  	        console.log('requestError');
  	        // Return the promise rejection.
  	        return $q.reject(rejection);
  	      },

  	      // On response success
  	      response: function (response) {
  	        // console.log(response); // Contains the data from the response.
  	        // Return the response or promise.
  	        return response || $q.when(response);
  	      },

  	      // On response failure
  	      responseError: function (rejection) {
  	        // console.log(rejection); // Contains the data about the error.
  	    	 console.log('wnwbApi responseError');

  	    	  if (rejection.status == 500){
  	    		 alert('Sorry, something went wrong.'
  	    				 + "\n" + rejection.status + ' ' + rejection.statusText
  	    				 + "\n" + rejection.config.url);
  	    	  }
  	    	 else if (rejection.status == 401){

  	    		/* alert('Please login first.'
  	    				 + "\n" + rejection.status + ' ' + rejection.statusText
  	    				 + "\n" + rejection.config.url); */
  	    	  }
  	    	  else if (rejection.status == 404){

  	    		 alert('Sorry, something went wrong.'
  	    				 + "\n" + rejection.status + ' ' + rejection.statusText
  	    				 + "\n" + rejection.config.url);
  	    	  }

  	        // Return the promise rejection.
  	        return $q.reject(rejection);
  	      }
  	    };
  	  });
  	  // Intercept http calls.

  	  // Add the interceptor to the $httpProvider.
  	  $httpProvider.interceptors.push('MyHttpInterceptor');

  	});
    var defaultResponseTransformer = function (data, headersGetter) {

        return JSON.parse(data).results;
    };

    app.factory('wnwbApi', ['config', '$resource', function(config, $resource) {
        return {
            Version: $resource(config.API_URL+'version/', {}, {}, {stripTrailingSlashes: false}),
            sensereltype: $resource(config.API_URL+'sensereltype/:id/', {}, {}, {stripTrailingSlashes: false}),
            Authorization: $resource(config.API_AUTH_URL, {}, {
                auth: {
                    method: 'POST',
                    params: {

                    }
                }
            }, {stripTrailingSlashes: false}),
            Lexicon: $resource(config.API_URL+'lexicon/:id/', {}, {
                get: {
                    method: 'GET',
                    isArray: false
                },
                query: {
                    method: 'GET',
                    transformResponse: [defaultResponseTransformer],
                    isArray: true
                }
            }, {stripTrailingSlashes: false}),
            Sense: $resource(config.API_URL+'sense/:id/', {}, {
                update: {
                    method: 'PUT'
                },
                query: {
                    method: 'GET',
                    transformResponse: [defaultResponseTransformer],
                    isArray: true
                },
                remove: {
                	method: 'DELETE'
                }
            }, {stripTrailingSlashes: false}),
            SynSet: $resource(config.API_URL+'synset/:id/', {}, {
                update: {
                    method: 'PUT'
                },
                query: {
                    method: 'GET',
                    transformResponse: [defaultResponseTransformer],
                    isArray: true
                },
                remove: {
                	method: 'DELETE'
                }
            }, {stripTrailingSlashes: false}),
            HyperonymRelTree: $resource(config.API_URL+'hypers/', {}, {
                get: {
                    method: 'GET',
                    isArray: true
                }
            }, {stripTrailingSlashes: false}),
            HyponymRelTree: $resource(config.API_URL+'hypos/', {}, {
                get: {
                    method: 'GET',
                    isArray: true
                }
            }, {stripTrailingSlashes: false}),
            SiblingRelTree: $resource(config.API_URL+'sibs/', {}, {
                get: {
                    method: 'GET',
                    isArray: true
                }
            }, {stripTrailingSlashes: false}),
            OtherRelTree: $resource(config.API_URL+'rels/', {}, {
                get: {
                    method: 'GET',
                    isArray: true
                }
            }, {stripTrailingSlashes: false}),
            SenseRel: $resource(config.API_URL+'senserel/:id/', {}, {}, {stripTrailingSlashes: false}),
            SynSetRel: $resource(config.API_URL+'synsetrel/:id/', {}, {}, {stripTrailingSlashes: false}),
            SenseRelType: $resource(config.API_URL+'sensereltype/:id/', {}, {
                update: {
                    method: 'PUT'
                },
                query: {
                    method: 'GET',
                    transformResponse: [defaultResponseTransformer],
                    isArray: true
                }
            }, {stripTrailingSlashes: false}),
            SenseStyle: $resource(config.API_URL+'refcode/:id/', {}, {
                update: {
                    method: 'PUT'
                },
                query: {
                    method: 'GET',
                    transformResponse: [defaultResponseTransformer],
                    isArray: true
                }
            }, {stripTrailingSlashes: false}),
            SynSetRelType: $resource(config.API_URL+'synsetreltype/:id/', {}, {
                update: {
                    method: 'PUT'
                },
                query: {
                    method: 'GET',
                    transformResponse: [defaultResponseTransformer],
                    isArray: true
                }
            }, {stripTrailingSlashes: false}),
            ExtRelType: $resource(config.API_URL+'extreltype/:id/', {}, {
                update: {
                    method: 'PUT'
                },
                query: {
                    method: 'GET',
                    transformResponse: [defaultResponseTransformer],
                    isArray: true
                }
            }, {stripTrailingSlashes: false}),
             ExtRel: $resource(config.API_URL+'extrel/', {}, {
                query: {
                    method: 'GET',
                    transformResponse: [defaultResponseTransformer],
                    isArray: true
                }
            }, {stripTrailingSlashes: false}),
            ExtSystem: $resource(config.API_URL+'extsystem/:id/', {}, {
                update: {
                    method: 'PUT'
                },
                query: {
                    method: 'GET',
                    transformResponse: [defaultResponseTransformer],
                    isArray: true
                }
            }, {stripTrailingSlashes: false}),
            LexicalEntry: $resource(config.API_URL+'lexentry/', {}, {
                query: {
                    method: 'GET',
                    transformResponse: [defaultResponseTransformer],
                    isArray: true
                }
            }, {stripTrailingSlashes: false}),
             LexicalEntryUsage: $resource(config.API_URL+'lexentryusage/', {}, {
                query: {
                    method: 'GET',
                    //transformResponse: [defaultResponseTransformer],
                    isArray: true
                }
            }, {stripTrailingSlashes: false}),
            Statistics: $resource(config.API_URL+'stats/', {}, {
                query: {
                    method: 'GET',
                    isArray: true
                }
            }, {stripTrailingSlashes: false}),
            Principal: $resource(config.API_URL+'users/?principal', {}, {
                query: {
                    method: 'GET',
                    transformResponse: [defaultResponseTransformer],
                    isArray: true
                }
            }, {stripTrailingSlashes: false})
        };
    }]);

    return app;
});<|endoftext|>


<commit_before>/* @flow weak */

import Helmet from 'react-helmet';
import IsomorphicRouter from 'isomorphic-relay-router';
import log from '../server/log.js';
import path from 'path';
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import Relay from 'react-relay';
import RelayLocalSchema from 'relay-local-schema';
import { match, Router } from 'react-router';

import { getUserByCookie, serveAuthenticationFailed } from '../server/credentials_check.js';
import isomorphicVars from './scripts/isomorphicVars';
import ObjectManager from '../data/ObjectManager';
import routes from './routes';
import schema from '../graphql/schema'; // Schema for GraphQL server

// Read environment
require( 'dotenv' ).load( );

// Load up isomorphic vars here, for server rendering
const isoVars = JSON.stringify( isomorphicVars( ) );

export function serveFailure( type, res, message, err )
{
  log.log( type, 'Server error: ' + message, err );

  res.status( 500 ).send( 'Server error' );
}

export default ( req, res, next, assetsPath ) =>
{
  match( { routes, location: req.originalUrl }, ( error, redirectLocation, renderProps ) => {
    if( error )
      next(error);
    else if( redirectLocation )
      res.redirect( 302, redirectLocation.pathname + redirectLocation.search );
    else if( renderProps )
      reunderOnServerCorrectRequest( req, res, next, assetsPath, renderProps );
    else
        res.status( 404 ).send( 'Not Found' );
  } );
};

function reunderOnServerCorrectRequest( req, res, next, assetsPath, renderProps )
{
  // create individual object manager for each request
  const objectManager = new ObjectManager( );

  getUserByCookie( objectManager, req, res )
  .then( ( a_User ) => {
    try
    {
      const user_id = a_User.id;

      const networkLayer = new RelayLocalSchema.NetworkLayer( {
        schema,
        rootValue: objectManager,
        onError: ( errors, request ) => serveFailure( 'error', res, 'local network layer GraphQL failure', { errors, request } )
      } );

      function render( { data, props } )
      {
        try
        {
          // Setting up static, global navigator object to pass user agent to material-ui. Previously
          // this was protected by the queue but is this legal now? Consult with new MUI
          // documentation.
          GLOBAL.navigator = { userAgent: req.headers[ 'user-agent' ] };

          // Setting up static, global location for the leftNav
          GLOBAL.location = { pathname: req.originalUrl };

          const reactOutput = ReactDOMServer.renderToString( <Router {...props} /> );
          const helmet = Helmet.rewind( );

          res.render( path.resolve( __dirname, 'renderOnServer.ejs' ), {
              preloadedData: JSON.stringify(data),
              assetsPath: assetsPath,
              reactOutput,
              title: helmet.title,
              meta: helmet.meta,
              link: helmet.link,
              isomorphicVars: isoVars,
              NODE_ENV: process.env.NODE_ENV,
          } );
        }
        catch( err )
        {
          serveFailure( 'error', res, 'renderOnServer render funcion failed', err )
        }
      }

      IsomorphicRouter.prepareData( renderProps, networkLayer ).then( render, next );
    }
    catch( err )
    {
      serveFailure( 'error', res, 'renderOnServer failed', err )
    }
  } )
  .catch( ( error ) => serveAuthenticationFailed( res, error ) )
  ; // then
}
<commit_msg>Provide protection against XSS problem. Close #5<commit_after>/* @flow weak */

import Helmet from 'react-helmet';
import IsomorphicRouter from 'isomorphic-relay-router';
import log from '../server/log.js';
import path from 'path';
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import Relay from 'react-relay';
import RelayLocalSchema from 'relay-local-schema';
import { match, Router } from 'react-router';

import { getUserByCookie, serveAuthenticationFailed } from '../server/credentials_check.js';
import isomorphicVars from './scripts/isomorphicVars';
import ObjectManager from '../data/ObjectManager';
import routes from './routes';
import schema from '../graphql/schema'; // Schema for GraphQL server

// Read environment
require( 'dotenv' ).load( );

// Load up isomorphic vars here, for server rendering
const isoVars = JSON.stringify( isomorphicVars( ) );

export function serveFailure( type, res, message, err )
{
  log.log( type, 'Server error: ' + message, err );

  res.status( 500 ).send( 'Server error' );
}

export default ( req, res, next, assetsPath ) =>
{
  match( { routes, location: req.originalUrl }, ( error, redirectLocation, renderProps ) => {
    if( error )
      next(error);
    else if( redirectLocation )
      res.redirect( 302, redirectLocation.pathname + redirectLocation.search );
    else if( renderProps )
      reunderOnServerCorrectRequest( req, res, next, assetsPath, renderProps );
    else
        res.status( 404 ).send( 'Not Found' );
  } );
};

function reunderOnServerCorrectRequest( req, res, next, assetsPath, renderProps )
{
  // create individual object manager for each request
  const objectManager = new ObjectManager( );

  getUserByCookie( objectManager, req, res )
  .then( ( a_User ) => {
    try
    {
      const user_id = a_User.id;

      const networkLayer = new RelayLocalSchema.NetworkLayer( {
        schema,
        rootValue: objectManager,
        onError: ( errors, request ) => serveFailure( 'error', res, 'local network layer GraphQL failure', { errors, request } )
      } );

      function render( { data, props } )
      {
        try
        {
          // Setting up static, global navigator object to pass user agent to material-ui. Previously
          // this was protected by the queue but is this legal now? Consult with new MUI
          // documentation.
          GLOBAL.navigator = { userAgent: req.headers[ 'user-agent' ] };

          // Setting up static, global location for the leftNav
          GLOBAL.location = { pathname: req.originalUrl };

          const reactOutput = ReactDOMServer.renderToString( <Router {...props} /> );
          const helmet = Helmet.rewind( );

          res.render( path.resolve( __dirname, 'renderOnServer.ejs' ), {
              preloadedData: JSON.stringify(data).replace(/\//g, '\\/'),
              assetsPath: assetsPath,
              reactOutput,
              title: helmet.title,
              meta: helmet.meta,
              link: helmet.link,
              isomorphicVars: isoVars,
              NODE_ENV: process.env.NODE_ENV,
          } );
        }
        catch( err )
        {
          serveFailure( 'error', res, 'renderOnServer render funcion failed', err )
        }
      }

      IsomorphicRouter.prepareData( renderProps, networkLayer ).then( render, next );
    }
    catch( err )
    {
      serveFailure( 'error', res, 'renderOnServer failed', err )
    }
  } )
  .catch( ( error ) => serveAuthenticationFailed( res, error ) )
  ; // then
}
<|endoftext|>


<commit_before>/*
leaflet-layerconfig
Library that communicates with a web service/reads a stored JavaScript object and adds layers to a leaflet map.
Copyright 2014 Norkart AS
*/

/*global L: false, ActiveXObject: false, window: false, XMLHttpRequest: false*/

L.LayerConfig = L.Class.extend(
{
    includes: L.Mixin.Events,
    _map: null,
    _json: null,
    initialize: function(map) {
        this._map = map;

    },
    parse: function (json) {
        this._json = json;

        if(typeof json == "string") { // We take a string to mean we got an url;
            var parent = this;
            function success(data) {
                var json = JSON.parse(data);
                if(this._map.setView && json.center && json.zoom)
                    this._map.setView(json.center, json.zoom);
                parent.addLayers(json);
            };
            this._ajaxRequest(json, success, function () {});
        }
        else {
            if(this._map.setView && json.center && json.zoom)
                    this._map.setView(json.center, json.zoom);
            if(this._map.fitBounds && json.bounds)
                this._map.fitBounds(json.bounds);
            this.addLayers(json);
        }
    },
    _ajaxRequest: function (url, callback, onerror) {
        var httpRequest;

          function makeRequest(url) {
            if (window.XMLHttpRequest) { // Mozilla, Safari, ...
              httpRequest = new XMLHttpRequest();
            } else if (window.ActiveXObject) { // IE
              try {
                httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
              }
              catch (e) {
                try {
                  httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
                }
                catch (e) {}
              }
            }

            if (!httpRequest) {
              throw new Error('Giving up :( Cannot create an XMLHTTP instance');
              return false;
            }
            httpRequest.onreadystatechange = alertContents;
            httpRequest.open('GET', url);
            httpRequest.send();
          }

          function alertContents() {
            if (httpRequest.readyState === 4) {
              if (httpRequest.status === 200) {
                callback(httpRequest.responseText);
              } else {
                onerror(httpRequest);
              }
            }
          }
          makeRequest(url);
    },
    _evalJsonOptions: function (options) {
        if (options && options.style && typeof options.style == "string") {
            eval("options.style = "+options.style);
        }
        if (options && options.onEachFeature && typeof options.onEachFeature == "string") {
            eval("options.onEachFeature = "+options.onEachFeature);
        }
        if (options && options.filter && typeof options.filter == "string") {
            eval("options.filter = "+options.filter);
        }
        if (options && options.pointToLayer && typeof options.pointToLayer == "string") {
            eval("options.pointToLayer = "+options.pointToLayer);
        }
        if (options && options.coordsToLatLng && typeof options.coordsToLatLng == "string") {
            eval("options.coordsToLatLng = "+json.options.coordsToLatLng);
        }
        return options;
    },
    _addLayer: function(layer, json, addTo) {
        if(json.baseLayer && this._addedBaseLayer) {

        }
        else if(!json.baseLayer) {
            addTo.addLayer(layer);
        }
        else {
            this._addedBaseLayer = true;
            addTo.addLayer(layer);
            if(layer.bringToFront) {
                layer.bringToFront();
            }
        }

        this.fire("LayerLoaded", { type: json.type, name: json.name, layer: layer, baseLayer: json.baseLayer });
    },
    addLayers: function (json, addTo) {
        if(!addTo)
            addTo = this._map;

        this.fire("startLayerLoading");
        for (var i = 0; i < json.layers.length; i++) {
            var layer = json.layers[i];
            switch (layer.type) {
                case 'marker':
                this.addMarker(layer, addTo);
                break;
                case 'geojson':
                this.addGeoJson(layer, addTo);
                break;
                case 'layergroup':
                this.addLayerGroup(layer, addTo);
                break;
                case 'featuregroup':
                this.addFeatureGroup(layer, addTo);
                break;
                case 'tilelayer':
                this.addTileLayer(layer, addTo);
                break;
                case 'wms':
                this.addWMS(layer, addTo);
                break;
                case 'circlemarker':
                this.addCircleMarker(layer, addTo);
                break;
                case 'circle':
                this.addCircle(layer, addTo);
                break;
                case 'rectangle':
                this.addRectangle(layer, addTo);
                break;
                case 'polygon':
                this.addPolygon(layer, addTo);
                break;
                case 'line':
                this.addLine(layer, addTo);
                break;
                case 'layer':
                this.addLayer(layer, addTo);
                break;
            }

        };
        this.fire("stopLayerLoading");
        return this;
    },
    addMarker: function(json, addTo) {
        json.options = this._evalJsonOptions(json.options);
        var l = L.marker(json.latLng, json.options);
        if(json.popupContent)
            l.bindPopup(json.popupContent);
        this._addLayer(l, json, addTo);
        return this;

    },

    addGeoJson: function(json, addTo) {
        json.options = this._evalJsonOptions(json.options);
        var parent = this;
        var addGeoJSON = function (geojson, options, map) {
            var l = L.geoJson(geojson,options);
            addTo.addLayer(l);
            parent._addLayer(l, json, addTo);
        }
        function onsuccess(data) {
            addGeoJSON(JSON.parse(data),json.options,parent._map);
        }
        function onerror(data) {
            console.debug(data);
        }
        if(json.url) {
            this._ajaxRequest(json.url, onsuccess, onerror);
        }
        else if(json.geojson) {
            addGeoJSON(json.geojson,json.options,this._map);
        }
        else {
            throw new Error("URL or GeoJSON object expected");
        }

        return this;

    },
    addLayerGroup: function(json, addTo) {
        json.options = this._evalJsonOptions(json.options);
        var l = L.layerGroup();
        this.fire("GroupLoadingStart", { layer: l });
        this.addLayers(json, l);
        this.fire("GroupLoadingEnd", { layer: l });
        this._addLayer(l, json, addTo);
        return this;

    },
    addFeatureGroup: function(json, addTo) {
        json.options = this._evalJsonOptions(json.options);
        var l = L.featureGroup();
        this.fire("GroupLoadingStart", { layer: l });
        this.addLayers(json, l);
        this.fire("GroupLoadingEnd", { layer: l });
        if(json.popupContent)
            l.bindPopup(json.popupContent);
        this._addLayer(l, json, addTo);
        return this;
    },
    addTileLayer: function (json, addTo) {
        json.options = this._evalJsonOptions(json.options);
        var l = L.tileLayer(json.url, json.options);
        this._addLayer(l, json, addTo);

        return this;
    },
    addWMS: function (json, addTo) {
        json.options = this._evalJsonOptions(json.options);
        var l = L.tileLayer.wms(json.url, json.options);
        this._addLayer(l, json, addTo);

        return this;
    },
    addCircleMarker: function (json, addTo) {
        json.options = this._evalJsonOptions(json.options);
        var l = L.circleMarker(json.latLng, json.options);
        if(json.popupContent)
            l.bindPopup(json.popupContent);
        this._addLayer(l, json, addTo);
        return this;
    },
    addCircle: function (json, addTo) {
        json.options = this._evalJsonOptions(json.options);
        var l = L.circle(json.latLng, json.radius, json.options);
        if(json.popupContent)
            l.bindPopup(json.popupContent);
        this._addLayer(l, json, addTo);
        return this;
    },
    addRectangle: function (json, addTo) {
        json.options = this._evalJsonOptions(json.options);
        var l = L.rectangle(json.path, json.options);
        if(json.popupContent)
            l.bindPopup(json.popupContent);
        this._addLayer(l, json, addTo);
        return this;
    },
    addPolygon: function (json, addTo) {
        json.options = this._evalJsonOptions(json.options);
        var l = L.polygon(json.path, json.options);
        if(json.popupContent)
            l.bindPopup(json.popupContent);
        this._addLayer(l, json, addTo);
        return this;
    },
    addLine: function (json, addTo) {
        json.options = this._evalJsonOptions(json.options);
        var l = L.polyline(json.path, json.options);
        if(json.popupContent)
            l.bindPopup(json.popupContent);
        this._addLayer(l, json, addTo);
        return this;
    },
    addLayer: function (json, addTo) {
        json.options = this._evalJsonOptions(json.options);
        var l = json.layer;
        if(json.popupContent)
            l.bindPopup(json.popupContent);
        this._addLayer(l, json, addTo);
        return this;
    }
}
);

L.layerConfig = function(json, map) {
    return new L.LayerConfig(json,map);
};<commit_msg>add newlines<commit_after>/*
leaflet-layerconfig
Library that communicates with a web service/reads a stored JavaScript object and adds layers to a leaflet map.
Copyright 2014 Norkart AS
*/

/*global L: false, ActiveXObject: false, window: false, XMLHttpRequest: false*/

L.LayerConfig = L.Class.extend({

    includes: L.Mixin.Events,

    _map: null,

    _json: null,

    initialize: function(map) {
        this._map = map;

    },

    parse: function (json) {
        this._json = json;

        if(typeof json == "string") { // We take a string to mean we got an url;
            var parent = this;
            function success(data) {
                var json = JSON.parse(data);
                if(this._map.setView && json.center && json.zoom)
                    this._map.setView(json.center, json.zoom);
                parent.addLayers(json);
            };
            this._ajaxRequest(json, success, function () {});
        }
        else {
            if(this._map.setView && json.center && json.zoom)
                    this._map.setView(json.center, json.zoom);
            if(this._map.fitBounds && json.bounds)
                this._map.fitBounds(json.bounds);
            this.addLayers(json);
        }
    },

    _ajaxRequest: function (url, callback, onerror) {
        var httpRequest;

          function makeRequest(url) {
            if (window.XMLHttpRequest) { // Mozilla, Safari, ...
              httpRequest = new XMLHttpRequest();
            } else if (window.ActiveXObject) { // IE
              try {
                httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
              }
              catch (e) {
                try {
                  httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
                }
                catch (e) {}
              }
            }

            if (!httpRequest) {
              throw new Error('Giving up :( Cannot create an XMLHTTP instance');
              return false;
            }
            httpRequest.onreadystatechange = alertContents;
            httpRequest.open('GET', url);
            httpRequest.send();
          }

          function alertContents() {
            if (httpRequest.readyState === 4) {
              if (httpRequest.status === 200) {
                callback(httpRequest.responseText);
              } else {
                onerror(httpRequest);
              }
            }
          }
          makeRequest(url);
    },

    _evalJsonOptions: function (options) {
        if (options && options.style && typeof options.style == "string") {
            eval("options.style = "+options.style);
        }
        if (options && options.onEachFeature && typeof options.onEachFeature == "string") {
            eval("options.onEachFeature = "+options.onEachFeature);
        }
        if (options && options.filter && typeof options.filter == "string") {
            eval("options.filter = "+options.filter);
        }
        if (options && options.pointToLayer && typeof options.pointToLayer == "string") {
            eval("options.pointToLayer = "+options.pointToLayer);
        }
        if (options && options.coordsToLatLng && typeof options.coordsToLatLng == "string") {
            eval("options.coordsToLatLng = "+json.options.coordsToLatLng);
        }
        return options;
    },

    _addLayer: function(layer, json, addTo) {
        if(json.baseLayer && this._addedBaseLayer) {

        }
        else if(!json.baseLayer) {
            addTo.addLayer(layer);
        }
        else {
            this._addedBaseLayer = true;
            addTo.addLayer(layer);
            if(layer.bringToFront) {
                layer.bringToFront();
            }
        }

        this.fire("LayerLoaded", { type: json.type, name: json.name, layer: layer, baseLayer: json.baseLayer });
    },

    addLayers: function (json, addTo) {
        if(!addTo)
            addTo = this._map;

        this.fire("startLayerLoading");
        for (var i = 0; i < json.layers.length; i++) {
            var layer = json.layers[i];
            switch (layer.type) {
                case 'marker':
                this.addMarker(layer, addTo);
                break;
                case 'geojson':
                this.addGeoJson(layer, addTo);
                break;
                case 'layergroup':
                this.addLayerGroup(layer, addTo);
                break;
                case 'featuregroup':
                this.addFeatureGroup(layer, addTo);
                break;
                case 'tilelayer':
                this.addTileLayer(layer, addTo);
                break;
                case 'wms':
                this.addWMS(layer, addTo);
                break;
                case 'circlemarker':
                this.addCircleMarker(layer, addTo);
                break;
                case 'circle':
                this.addCircle(layer, addTo);
                break;
                case 'rectangle':
                this.addRectangle(layer, addTo);
                break;
                case 'polygon':
                this.addPolygon(layer, addTo);
                break;
                case 'line':
                this.addLine(layer, addTo);
                break;
                case 'layer':
                this.addLayer(layer, addTo);
                break;
            }

        };
        this.fire("stopLayerLoading");
        return this;
    },

    addMarker: function(json, addTo) {
        json.options = this._evalJsonOptions(json.options);
        var l = L.marker(json.latLng, json.options);
        if(json.popupContent)
            l.bindPopup(json.popupContent);
        this._addLayer(l, json, addTo);
        return this;

    },

    addGeoJson: function(json, addTo) {
        json.options = this._evalJsonOptions(json.options);
        var parent = this;
        var addGeoJSON = function (geojson, options, map) {
            var l = L.geoJson(geojson,options);
            addTo.addLayer(l);
            parent._addLayer(l, json, addTo);
        }
        function onsuccess(data) {
            addGeoJSON(JSON.parse(data),json.options,parent._map);
        }
        function onerror(data) {
            console.debug(data);
        }
        if(json.url) {
            this._ajaxRequest(json.url, onsuccess, onerror);
        }
        else if(json.geojson) {
            addGeoJSON(json.geojson,json.options,this._map);
        }
        else {
            throw new Error("URL or GeoJSON object expected");
        }

        return this;

    },

    addLayerGroup: function(json, addTo) {
        json.options = this._evalJsonOptions(json.options);
        var l = L.layerGroup();
        this.fire("GroupLoadingStart", { layer: l });
        this.addLayers(json, l);
        this.fire("GroupLoadingEnd", { layer: l });
        this._addLayer(l, json, addTo);
        return this;

    },

    addFeatureGroup: function(json, addTo) {
        json.options = this._evalJsonOptions(json.options);
        var l = L.featureGroup();
        this.fire("GroupLoadingStart", { layer: l });
        this.addLayers(json, l);
        this.fire("GroupLoadingEnd", { layer: l });
        if(json.popupContent)
            l.bindPopup(json.popupContent);
        this._addLayer(l, json, addTo);
        return this;
    },

    addTileLayer: function (json, addTo) {
        json.options = this._evalJsonOptions(json.options);
        var l = L.tileLayer(json.url, json.options);
        this._addLayer(l, json, addTo);

        return this;
    },

    addWMS: function (json, addTo) {
        json.options = this._evalJsonOptions(json.options);
        var l = L.tileLayer.wms(json.url, json.options);
        this._addLayer(l, json, addTo);

        return this;
    },

    addCircleMarker: function (json, addTo) {
        json.options = this._evalJsonOptions(json.options);
        var l = L.circleMarker(json.latLng, json.options);
        if(json.popupContent)
            l.bindPopup(json.popupContent);
        this._addLayer(l, json, addTo);
        return this;
    },

    addCircle: function (json, addTo) {
        json.options = this._evalJsonOptions(json.options);
        var l = L.circle(json.latLng, json.radius, json.options);
        if(json.popupContent)
            l.bindPopup(json.popupContent);
        this._addLayer(l, json, addTo);
        return this;
    },

    addRectangle: function (json, addTo) {
        json.options = this._evalJsonOptions(json.options);
        var l = L.rectangle(json.path, json.options);
        if(json.popupContent)
            l.bindPopup(json.popupContent);
        this._addLayer(l, json, addTo);
        return this;
    },

    addPolygon: function (json, addTo) {
        json.options = this._evalJsonOptions(json.options);
        var l = L.polygon(json.path, json.options);
        if(json.popupContent)
            l.bindPopup(json.popupContent);
        this._addLayer(l, json, addTo);
        return this;
    },

    addLine: function (json, addTo) {
        json.options = this._evalJsonOptions(json.options);
        var l = L.polyline(json.path, json.options);
        if(json.popupContent)
            l.bindPopup(json.popupContent);
        this._addLayer(l, json, addTo);
        return this;
    },

    addLayer: function (json, addTo) {
        json.options = this._evalJsonOptions(json.options);
        var l = json.layer;
        if(json.popupContent)
            l.bindPopup(json.popupContent);
        this._addLayer(l, json, addTo);
        return this;
    }
});

L.layerConfig = function(json, map) {
    return new L.LayerConfig(json,map);
};<|endoftext|>


<commit_before>"use strict";
var configloader = require('./configfile');
var path         = require('path');
var logger       = require('./logger');

var config = exports;

var config_path = process.env.HARAKA ? path.join(process.env.HARAKA, 'config') : path.join(__dirname, './config');
var enabled = new RegExp('^(?:yes|true|enabled|ok|on|1)$', 'i');

config.get = function(name, type, cb) {
    if (type === 'nolog') {
        type = arguments[2]; // deprecated - TODO: remove later
    }

    type = type || 'value';
    var full_path = path.resolve(config_path, name);
    var results = configloader.read_config(full_path, type, cb);

    // Pass arrays by value to prevent config being modified accidentally.
    if (Array.isArray(results)) {
        return results.slice();
    }
    else {
        return results;
    }
};

config.is_enabled = function(value) {
    return enabled.match(value);
}
<commit_msg>Fix typo<commit_after>"use strict";
var configloader = require('./configfile');
var path         = require('path');
var logger       = require('./logger');

var config = exports;

var config_path = process.env.HARAKA ? path.join(process.env.HARAKA, 'config') : path.join(__dirname, './config');
var enabled = new RegExp('^(?:yes|true|enabled|ok|on|1)$', 'i');

config.get = function(name, type, cb) {
    if (type === 'nolog') {
        type = arguments[2]; // deprecated - TODO: remove later
    }

    type = type || 'value';
    var full_path = path.resolve(config_path, name);
    var results = configloader.read_config(full_path, type, cb);

    // Pass arrays by value to prevent config being modified accidentally.
    if (Array.isArray(results)) {
        return results.slice();
    }
    else {
        return results;
    }
};

config.is_enabled = function(value) {
    return enabled.test(value);
}
<|endoftext|>


<commit_before>define([
	"Config.flickr",
	"routers/AppRouter",
	"views/EndpointsView",
	"views/TryingView",
	"controllers/GroupsController",
	"controllers/ParamsController",
	"controllers/ErrorsController"
],function(Config, AppRouter, EndpointsView, TryingView, GroupsController, ParamsController, ErrorsController) {

	window.APIBuddy = {

		views: {
			"endpointsView": EndpointsView,
			"tryingView": TryingView
		},

		viewInstances: {},

		router: null,

		start: function() {

			// Register views
			this.registerViews();

			// Register Config globally, to make it easier to access
			window.Config = Config;

			// Parse config data
			GroupsController.parseGroups( Config.groups );
			ParamsController.parseGlobalParams( Config.globalParams );
			ErrorsController.parseGlobalErrors( Config.globalErrors );

			// Start first view
			APIBuddy.tryingView();
			APIBuddy.endpointsView().render();

			// Start history manager
			this.router = new AppRouter();
			Backbone.history.start();
		},

		registerViews: function() {

			for( var viewName in this.views ) {
				APIBuddy[viewName] = this.getView(viewName);
			}
		},

		getView: function(viewName) {
			return function() {

				if( typeof this.viewInstances[viewName] === "undefined" ) {
					this.viewInstances[viewName] = new this.views[viewName]();
				}

				return this.viewInstances[viewName];
			};
		}

	};

	_.extend(APIBuddy, Backbone.Events);

	return APIBuddy;

});<commit_msg>cleaning view instantiation code<commit_after>define([
	"Config.flickr",
	"routers/AppRouter",
	"views/EndpointsView",
	"views/TryingView",
	"controllers/GroupsController",
	"controllers/ParamsController",
	"controllers/ErrorsController"
],function(Config, AppRouter, EndpointsView, TryingView, GroupsController, ParamsController, ErrorsController) {

	window.APIBuddy = {

		router: null,

		start: function() {

			// Register Config globally, to make it easier to access
			window.Config = Config;

			// Parse config data
			GroupsController.parseGroups( Config.groups );
			ParamsController.parseGlobalParams( Config.globalParams );
			ErrorsController.parseGlobalErrors( Config.globalErrors );

			// Init views
			new TryingView();
			new EndpointsView().render();

			// Start history manager
			this.router = new AppRouter();
			Backbone.history.start();
		}

	};

	_.extend(APIBuddy, Backbone.Events);

	return APIBuddy;

});<|endoftext|>


<commit_before>var
  env = process.env.NODE_ENV || 'development',
  config;

config = {
  production : {
    db : {
      URL : process.env['wac_service_mongodb_url']
    },
    componentsURL : 'http://50.116.26.197/components/all',
    componentInstallDir : __dirname + '/components',
    componentBuildDir : __dirname + '/build',
    port : 80
  },
  development : {
    db : {
      URL : 'mongodb://localhost:27017/wac-service'
    },
    componentsURL : 'http://50.116.26.197/components/all',
    componentInstallDir : __dirname + '/components',
    componentBuildDir : __dirname + '/build',
    port : 8000
  },
  test : {
    db : {
      URL : 'mongodb://localhost:27017/wac-service-test'
    },
    componentsURL : 'http://localhost:8000/mock/registry',
    componentInstallDir : __dirname + '/mocks/components',
    componentBuildDir : __dirname + '/test/build',
    port : 8000
  }
};

config = config[env];

// Helper environment methods
config.env = env;
config.isTest = env === 'test';
config.isDevelopment = env === 'development';

module.exports = config;
<commit_msg>Change install directory for dev to mocks dir<commit_after>var
  env = process.env.NODE_ENV || 'development',
  config;

config = {
  production : {
    db : {
      URL : process.env['wac_service_mongodb_url']
    },
    componentsURL : 'http://50.116.26.197/components/all',
    componentInstallDir : __dirname + '/components',
    componentBuildDir : __dirname + '/build',
    port : 80
  },
  development : {
    db : {
      URL : 'mongodb://localhost:27017/wac-service'
    },
    componentsURL : 'http://50.116.26.197/components/all',
    componentInstallDir : __dirname + '/mocks/components',
    componentBuildDir : __dirname + '/build',
    port : 8000
  },
  test : {
    db : {
      URL : 'mongodb://localhost:27017/wac-service-test'
    },
    componentsURL : 'http://localhost:8000/mock/registry',
    componentInstallDir : __dirname + '/mocks/components',
    componentBuildDir : __dirname + '/test/build',
    port : 8000
  }
};

config = config[env];

// Helper environment methods
config.env = env;
config.isTest = env === 'test';
config.isDevelopment = env === 'development';

module.exports = config;
<|endoftext|>


<commit_before>import { combineReducers } from 'redux';
import { routeReducer } from 'redux-simple-router';
import { ADD_COMMENT, AUTHENTICATED, LOGGED_OUT } from './actions';

function commentsReducer(state = [], action) {

  switch (action.type) {
    case ADD_COMMENT:
      return state.concat(action.comment);

    default:
      return state;
  }
}

function authReducer(state = {signedIn: false, roles: []}, action) {

  switch (action.type) {
    case AUTHENTICATED:
      return Object.assign({}, state, {
        signedIn: true,
        roles: action.roles
      });

    case LOGGED_OUT:
      return Object.assign({}, state, {
        signedIn: false,
        roles: ['ROLE_ANONYMOUS']
      });

    default:
      return state;
  }
}

export { commentsReducer, authReducer };

/* Combine the routing reducer with the application's reducer(s) */
const reducer = combineReducers(Object.assign({}, {
  auth: authReducer,
  comments: commentsReducer,
  routing: routeReducer
}));

export default reducer;
<commit_msg>Remove unnecessary reducers exports<commit_after>import { combineReducers } from 'redux';
import { routeReducer } from 'redux-simple-router';
import { ADD_COMMENT, AUTHENTICATED, LOGGED_OUT } from './actions';

function commentsReducer(state = [], action) {

  switch (action.type) {
    case ADD_COMMENT:
      return state.concat(action.comment);

    default:
      return state;
  }
}

function authReducer(state = {signedIn: false, roles: []}, action) {

  switch (action.type) {
    case AUTHENTICATED:
      return Object.assign({}, state, {
        signedIn: true,
        roles: action.roles
      });

    case LOGGED_OUT:
      return Object.assign({}, state, {
        signedIn: false,
        roles: ['ROLE_ANONYMOUS']
      });

    default:
      return state;
  }
}

/* Combine the routing reducer with the application's reducer(s) */
const reducer = combineReducers(Object.assign({}, {
  auth: authReducer,
  comments: commentsReducer,
  routing: routeReducer
}));

export default reducer;
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import { hashHistory, Link } from 'react-router';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { Button, Form, Icon, Input, InputNumber, message, Tooltip } from 'antd';
import * as actions from './redux/actions';

const FormItem = Form.Item;

export class SettingsPage extends Component {
  static propTypes = {
    home: PropTypes.object.isRequired,
    actions: PropTypes.object.isRequired,
    form: PropTypes.object.isRequired,
  };

  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  getFormItemLabel(name, tooltip) {
    return (

        {name}
        <Tooltip title={tooltip}>
          <Icon type="question-circle-o" />
        </Tooltip>

    );
  }

  handleSubmit(evt) {
    evt.preventDefault();
    this.props.actions.saveSettings(this.props.form.getFieldsValue()).then(() => {
      message.success('Setting success.');
      hashHistory.push('/');
    });
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    return (

          <Link to="/"><Icon type="arrow-left" /></Link>

Settings

          <Form vertical required style={{ margin: 15 }} onSubmit={this.handleSubmit}>
            <FormItem label={this.getFormItemLabel('Max output rows', 'The max number of output rows.')}>
              {getFieldDecorator('outputRowsLimit', {
                initialValue: this.props.home.outputRowsLimit || 100,
              })(
                <InputNumber size="default" style={{ width: '100%' }} />
              )}
            </FormItem>
            <FormItem label={this.getFormItemLabel('Environment path', 'The environment path to find the command. You may need to set this when using nvm. i.e. /path/to/.nvm/versions/node//bin')}>
              {getFieldDecorator('envPath', {
                initialValue: this.props.home.envPath || '',
              })(
                <Input size="default" />
              )}
            </FormItem>
            <FormItem className="buttons">
              <Button size="default" type="primary" htmlType="submit">Ok</Button>
              <Button size="default" onClick={() => hashHistory.push('/')}>Cancel</Button>
            </FormItem>
          </Form>

    );
  }
}

SettingsPage = Form.create()(SettingsPage);

/* istanbul ignore next */
function mapStateToProps(state) {
  return {
    home: state.home,
  };
}

/* istanbul ignore next */
function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators({ ...actions }, dispatch)
  };
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(SettingsPage);
<commit_msg>Update SettingsPage.js<commit_after>import React, { Component, PropTypes } from 'react';
import { hashHistory, Link } from 'react-router';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { Button, Form, Icon, Input, InputNumber, message, Tooltip } from 'antd';
import * as actions from './redux/actions';

const FormItem = Form.Item;

export class SettingsPage extends Component {
  static propTypes = {
    home: PropTypes.object.isRequired,
    actions: PropTypes.object.isRequired,
    form: PropTypes.object.isRequired,
  };

  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  getFormItemLabel(name, tooltip) {
    return (

        {name}
        <Tooltip title={tooltip}>
          <Icon type="question-circle-o" />
        </Tooltip>

    );
  }

  handleSubmit(evt) {
    evt.preventDefault();
    this.props.actions.saveSettings(this.props.form.getFieldsValue()).then(() => {
      message.success('Setting success.');
      hashHistory.push('/');
    });
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    return (

          <Link to="/"><Icon type="arrow-left" /></Link>

Settings

          <Form vertical required style={{ margin: 15 }} onSubmit={this.handleSubmit}>
            <FormItem label={this.getFormItemLabel('Max output rows', 'The max number of output rows.')}>
              {getFieldDecorator('outputRowsLimit', {
                initialValue: this.props.home.outputRowsLimit || 100,
              })(
                <InputNumber size="default" style={{ width: '100%' }} />
              )}
            </FormItem>
            <FormItem label={this.getFormItemLabel('Environment path', 'The environment path to find the command. You may need to set this when using nvm. i.e. /path/to/.nvm/versions/node/bin')}>
              {getFieldDecorator('envPath', {
                initialValue: this.props.home.envPath || '',
              })(
                <Input size="default" />
              )}
            </FormItem>
            <FormItem className="buttons">
              <Button size="default" type="primary" htmlType="submit">Ok</Button>
              <Button size="default" onClick={() => hashHistory.push('/')}>Cancel</Button>
            </FormItem>
          </Form>

    );
  }
}

SettingsPage = Form.create()(SettingsPage);

/* istanbul ignore next */
function mapStateToProps(state) {
  return {
    home: state.home,
  };
}

/* istanbul ignore next */
function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators({ ...actions }, dispatch)
  };
}

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