<commit_before>/*
 * #%L
 * ACS AEM Commons Package
 * %%
 * Copyright (C) 2013 Adobe
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 *
 * Extends /libs/foundation/components/parsys to configure drop zone placeholder text and colors
 * To enable this feature set the following properties on desing node - eg. /etc/designs/geometrixx/jcr:content/contentpage/par
 * acsParsysPlaceholderText - to replace default placeholder "Drop Components Here" with custom text eg. "Please drop images only!!!"
 * acsParsysTextColor - placeholder text color eg. #0000FF
 * acsParsysBackgroundColor - drop zone background color - eg.#9DB68C
 * acsParsysBorderColor - drop zone border color - eg. #E5E500
 */
(function(){
    var pathName = window.location.pathname,
        ACS_PARSYS_PLACEHOLDER_TEXT = "acsParsysPlaceholderText",
        ACS_PARSYS_TEXT_COLOR = "acsParsysTextColor",
        ACS_PARSYS_BG_COLOR = "acsParsysBackgroundColor",
        ACS_PARSYS_BORDER_COLOR = "acsParsysBorderColor";

    if( ( pathName !== "/cf" ) && ( pathName.indexOf("/content") !== 0)){
        return;
    }

    function isParsysNew(editable){
        if(!_.isObject(editable.params) || _.isEmpty(editable.params["./sling:resourceType"])){
            return false;
        }

        var resouceType = editable.params["./sling:resourceType"];

        return ( resouceType === CQ.wcm.EditBase.PARSYS_NEW || resouceType === "foundation/components/iparsys/new");
    }

    function getColor(color){
        color = color.trim();

        if(color.indexOf("#") !== 0){
            color = "#" + color;
        }

        return color;
    }

    function getConfiguration(editComponent) {
        var pageInfo = CQ.utils.WCM.getPageInfo(editComponent.path),
            designConfig = {}, cellSearchPath, parentPath, parName;

        if (!pageInfo || !pageInfo.designObject) {
            return;
        }

        try {
            cellSearchPath = editComponent.cellSearchPath;
            parentPath = editComponent.getParent().path;

            cellSearchPath = cellSearchPath.substring(0, cellSearchPath.indexOf("|"));
            parName = parentPath.substring(parentPath.lastIndexOf("/") + 1);

            designConfig = pageInfo.designObject.content[cellSearchPath][parName];
        } catch (err) {
            console.log("ACS AEM Commons - Error getting parsys configuration", err);
        }

        return designConfig;
    }

    function getParsyses(){
        var parsyses = {};

        _.each(CQ.WCM.getEditables(), function(e){
            if(!isParsysNew(e)){
                return;
            }

            parsyses[e.path] = e;
        });

        return parsyses;
    }

    function configureParsys(){
        var parsyses = getParsyses(), placeholder,
            $placeholder, $pContainer, designConfig;

        _.each(parsyses, function(parsys){
            if(!parsys.emptyComponent) {
                return;
            }

            designConfig = getConfiguration(parsys);
            if (!designConfig) {
              return;
            }

            placeholder = parsys.emptyComponent.findByType("static")[0];

            $placeholder = $(placeholder.el.dom);

            $pContainer = $placeholder.closest(".cq-editrollover-insert-container");

            if(designConfig[ACS_PARSYS_PLACEHOLDER_TEXT]){
                $placeholder.html(designConfig[ACS_PARSYS_PLACEHOLDER_TEXT]);
            }

            if(designConfig[ACS_PARSYS_TEXT_COLOR]){
                $placeholder.css("color", getColor(designConfig[ACS_PARSYS_TEXT_COLOR]));
            }

            if(designConfig[ACS_PARSYS_BG_COLOR]){
                $pContainer.css("background-color", getColor(designConfig[ACS_PARSYS_BG_COLOR]));
            }

            if(designConfig[ACS_PARSYS_BORDER_COLOR]){
                var color = getColor(designConfig[ACS_PARSYS_BORDER_COLOR]);

                parsys.highlight.on("beforeshow", function(highlight){
                    $("#" + highlight.id).css("background-color", color);
                });
            }
        });
    }

    function handleEditMode(){
        CQ.WCM.on("editablesready", configureParsys, this);
    }

    CQ.Ext.onReady(function () {
        if(CQ.WCM.isEditMode()){
            handleEditMode();
        }
    });
}());<commit_msg>replaced JS Object searching<commit_after>/*
 * #%L
 * ACS AEM Commons Package
 * %%
 * Copyright (C) 2013 Adobe
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 *
 * Extends /libs/foundation/components/parsys to configure drop zone placeholder text and colors
 * To enable this feature set the following properties on desing node - eg. /etc/designs/geometrixx/jcr:content/contentpage/par
 * acsParsysPlaceholderText - to replace default placeholder "Drop Components Here" with custom text eg. "Please drop images only!!!"
 * acsParsysTextColor - placeholder text color eg. #0000FF
 * acsParsysBackgroundColor - drop zone background color - eg.#9DB68C
 * acsParsysBorderColor - drop zone border color - eg. #E5E500
 */
(function(){
    var pathName = window.location.pathname,
        ACS_PARSYS_PLACEHOLDER_TEXT = "acsParsysPlaceholderText",
        ACS_PARSYS_TEXT_COLOR = "acsParsysTextColor",
        ACS_PARSYS_BG_COLOR = "acsParsysBackgroundColor",
        ACS_PARSYS_BORDER_COLOR = "acsParsysBorderColor";

    if( ( pathName !== "/cf" ) && ( pathName.indexOf("/content") !== 0)){
        return;
    }

    function isParsysNew(editable){
        if(!_.isObject(editable.params) || _.isEmpty(editable.params["./sling:resourceType"])){
            return false;
        }

        var resouceType = editable.params["./sling:resourceType"];

        return ( resouceType === CQ.wcm.EditBase.PARSYS_NEW || resouceType === "foundation/components/iparsys/new");
    }

    function getColor(color){
        color = color.trim();

        if(color.indexOf("#") !== 0){
            color = "#" + color;
        }

        return color;
    }

    function getConfiguration(editComponent) {
        var pageInfo = CQ.utils.WCM.getPageInfo(editComponent.path),
            designConfig = {}, cellSearchPath, cellSearchPathInfo, parentPath, parNames;

        if (!pageInfo || !pageInfo.designObject) {
            return;
        }

        try {
            cellSearchPath = editComponent.cellSearchPath;
            parentPath = editComponent.getParent().path;

            cellSearchPath = cellSearchPath.substring(0, cellSearchPath.indexOf("|"));
            parNames = parentPath.split("jcr:content/");
            parNames = parNames[1].split("/");
            cellSearchPathInfo = pageInfo.designObject.content[cellSearchPath];
            for(var i=0; i < parNames.length; i++){
                var prop = parNames[i];
                cellSearchPathInfo = cellSearchPathInfo[prop];
            }

            designConfig = cellSearchPathInfo;
        } catch (err) {
            console.log("ACS AEM Commons - Error getting parsys configuration", err);
        }

        return designConfig;
    }

    function getParsyses(){
        var parsyses = {};

        _.each(CQ.WCM.getEditables(), function(e){
            if(!isParsysNew(e)){
                return;
            }

            parsyses[e.path] = e;
        });

        return parsyses;
    }

    function configureParsys(){
        var parsyses = getParsyses(), placeholder,
            $placeholder, $pContainer, designConfig;

        _.each(parsyses, function(parsys){
            if(!parsys.emptyComponent) {
                return;
            }

            designConfig = getConfiguration(parsys);
            if (!designConfig) {
              return;
            }

            placeholder = parsys.emptyComponent.findByType("static")[0];

            $placeholder = $(placeholder.el.dom);

            $pContainer = $placeholder.closest(".cq-editrollover-insert-container");

            if(designConfig[ACS_PARSYS_PLACEHOLDER_TEXT]){
                $placeholder.html(designConfig[ACS_PARSYS_PLACEHOLDER_TEXT]);
            }

            if(designConfig[ACS_PARSYS_TEXT_COLOR]){
                $placeholder.css("color", getColor(designConfig[ACS_PARSYS_TEXT_COLOR]));
            }

            if(designConfig[ACS_PARSYS_BG_COLOR]){
                $pContainer.css("background-color", getColor(designConfig[ACS_PARSYS_BG_COLOR]));
            }

            if(designConfig[ACS_PARSYS_BORDER_COLOR]){
                var color = getColor(designConfig[ACS_PARSYS_BORDER_COLOR]);

                parsys.highlight.on("beforeshow", function(highlight){
                    $("#" + highlight.id).css("background-color", color);
                });
            }
        });
    }

    function handleEditMode(){
        CQ.WCM.on("editablesready", configureParsys, this);
    }

    CQ.Ext.onReady(function () {
        if(CQ.WCM.isEditMode()){
            handleEditMode();
        }
    });
}());
<|endoftext|>


<commit_before>/**
 * Copyright 2012 - present by OpenGamma Inc. and the OpenGamma group of companies
 * Please see distribution for license.
 */
$.register_module({
    name: 'og.blotter.forms.fungibletrade',
    dependencies: [],
    obj: function () {
        return function (config) {
            var constructor = this, form, data, security, $security_input, util = og.blotter.util,
            dropdown = '.og-blotter-security-select', bond_future = 'BondFutureSecurity',
            bond_arr = ['CorporateBondSecurity', 'GovernmentBondSecurity','MunicipalBondSecurity'],
            details_selector = 'og-blocks-fungible-details', ids_selector = 'og-blocks-fungible-security-ids',
            blank_details = "

";
            if(config) {data = config; data.id = config.trade.uniqueId;}
            else {data = {trade: og.blotter.util.fungible_trade};}
            constructor.load = function () {
                constructor.title = 'Fungible Trade';
                form = new og.common.util.ui.Form({
                    module: 'og.blotter.forms.fungible_tash',
                    data: data,
                    selector: '.OG-blotter-form-block'
                });
                security = new og.blotter.forms.blocks.Security({form: form, label: "Underlying ID",
                    security: data.trade.securityIdBundle, index: "trade.securityIdBundle"});
                form.children.push(
                    new og.blotter.forms.blocks.Portfolio({form: form, counterparty: data.trade.counterparty}),
                    new form.Block({module: 'og.blotter.forms.blocks.fungible_tash',
                        extras: {quantity: data.trade.quantity},
                        children: [security]
                    }),
                    new form.Block({content: blank_details}),
                    new form.Block({
                        module: 'og.blotter.forms.blocks.fungible_security_ids_tash'
                    }),
                    new og.common.util.ui.Attributes({
                        form: form, attributes: data.trade.attributes, index: 'trade.attributes'
                    })
                );
                form.dom();
                form.on('form:load', function (){
                    get_security();
                });
                form.on('form:submit', function (result){
                    og.api.rest.blotter.trades.put(result.data);
                });
                form.on('keyup', security.input_id(), function (event) {
                    get_security();
                });
            };
            get_security = function () {
                og.api.rest.blotter.securities.get({id:security.name()}).pipe(
                    function(data){poplate_switch(data);}
                );
            };
            populate_data = function (config){
                var details_block, ids_block;
                console.log(data);
                details_block = new form.Block({module: 'og.blotter.forms.blocks.fungible_bond_tash',
                    extras:{issuer: config.inputs.data.issuerName, coupon_type: config.inputs.data.couponType,
                        coupon_rate: config.inputs.data.couponRate, currency: config.inputs.data.currency}
                });
                details_block.html(function (html){
                    $('.' + details_selector).replaceWith(html);
                });
            };
            poplate_switch = function (data){
                if(data.error) {clear_info(); return;}
                if(bond_arr.indexOf(data.type)) populate_data({type:'bond', inputs: data});
                else if(bond_future.indexOf(data.type)) populate_data({type:'future', data: data});
                else populate_data({type:'stock', data: data});
            };
            clear_info = function (){
                $('.' + details_selector).replaceWith(blank_details);
            };
            constructor.load();
            constructor.submit = function () {
                form.submit();
            };
            constructor.submit_new = function () {
                delete data.id;
                form.submit();
            };
            constructor.kill = function () {
            };
        };
    }
});<commit_msg>removed console log<commit_after>/**
 * Copyright 2012 - present by OpenGamma Inc. and the OpenGamma group of companies
 * Please see distribution for license.
 */
$.register_module({
    name: 'og.blotter.forms.fungibletrade',
    dependencies: [],
    obj: function () {
        return function (config) {
            var constructor = this, form, data, security, $security_input, util = og.blotter.util,
            dropdown = '.og-blotter-security-select', bond_future = 'BondFutureSecurity',
            bond_arr = ['CorporateBondSecurity', 'GovernmentBondSecurity','MunicipalBondSecurity'],
            details_selector = 'og-blocks-fungible-details', ids_selector = 'og-blocks-fungible-security-ids',
            blank_details = "

";
            if(config) {data = config; data.id = config.trade.uniqueId;}
            else {data = {trade: og.blotter.util.fungible_trade};}
            constructor.load = function () {
                constructor.title = 'Fungible Trade';
                form = new og.common.util.ui.Form({
                    module: 'og.blotter.forms.fungible_tash',
                    data: data,
                    selector: '.OG-blotter-form-block'
                });
                security = new og.blotter.forms.blocks.Security({form: form, label: "Underlying ID",
                    security: data.trade.securityIdBundle, index: "trade.securityIdBundle"});
                form.children.push(
                    new og.blotter.forms.blocks.Portfolio({form: form, counterparty: data.trade.counterparty}),
                    new form.Block({module: 'og.blotter.forms.blocks.fungible_tash',
                        extras: {quantity: data.trade.quantity},
                        children: [security]
                    }),
                    new form.Block({content: blank_details}),
                    new form.Block({
                        module: 'og.blotter.forms.blocks.fungible_security_ids_tash'
                    }),
                    new og.common.util.ui.Attributes({
                        form: form, attributes: data.trade.attributes, index: 'trade.attributes'
                    })
                );
                form.dom();
                form.on('form:load', function (){
                    get_security();
                });
                form.on('form:submit', function (result){
                    og.api.rest.blotter.trades.put(result.data);
                });
                form.on('keyup', security.input_id(), function (event) {
                    get_security();
                });
            };
            get_security = function () {
                og.api.rest.blotter.securities.get({id:security.name()}).pipe(
                    function(data){poplate_switch(data);}
                );
            };
            populate_data = function (config){
                var details_block, ids_block;
                details_block = new form.Block({module: 'og.blotter.forms.blocks.fungible_bond_tash',
                    extras:{issuer: config.inputs.data.issuerName, coupon_type: config.inputs.data.couponType,
                        coupon_rate: config.inputs.data.couponRate, currency: config.inputs.data.currency}
                });
                details_block.html(function (html){
                    $('.' + details_selector).replaceWith(html);
                });
            };
            poplate_switch = function (data){
                if(data.error) {clear_info(); return;}
                if(bond_arr.indexOf(data.type)) populate_data({type:'bond', inputs: data});
                else if(bond_future.indexOf(data.type)) populate_data({type:'future', data: data});
                else populate_data({type:'stock', data: data});
            };
            clear_info = function (){
                $('.' + details_selector).replaceWith(blank_details);
            };
            constructor.load();
            constructor.submit = function () {
                form.submit();
            };
            constructor.submit_new = function () {
                delete data.id;
                form.submit();
            };
            constructor.kill = function () {
            };
        };
    }
});<|endoftext|>


<commit_before>/**
 * This <server-gardu-reporter> project created by :
 * Name         : syafiq
 * Date / Time  : 04 August 2017, 9:29 PM.
 * Email        : syafiq.rezpector@gmail.com
 * Github       : syafiqq
 */

(function ($) {
    $(function () {
        var table_report = 'table#tabel_pengukuran';
        var table = $(table_report).DataTable({
            "paging": true,
            "lengthChange": false,
            "searching": false,
            "ordering": false,
            "info": true,
            "autoWidth": true,
            "sScrollX": "100%",
            "bScrollCollapse": true,
            "sScrollXInner": "100%",
            "language": {
                "url": $('meta[name="datatable_lang"]').attr('content')
            }
        });
        var retriever = $('meta[name="retriever"]').attr('content');

        var retreiveData = function (table, link, progress) {
            progress.start();
            $.ajax({
                type: 'get',
                url: link,
                dataType: 'json'
            })
                .done(function (response) {
                    var kind = ['notify', 'message'];
                    var type = ['find'];
                    var status = ['danger', 'info', 'warning', 'success'];
                    if (response['data'] !== undefined)
                    {
                        var i, j, k, l, is, js, ks, ls;
                        if (response['data']['message'] !== undefined)
                        {
                            for (i = -1, is = kind.length; ++i < is;)
                            {
                                if (response['data']['message'][kind[i]] !== undefined)
                                {
                                    for (j = -1, js = type.length; ++j < js;)
                                    {
                                        if (response['data']['message'][kind[i]][type[j]] !== undefined)
                                        {
                                            for (k = -1, ks = status.length; ++k < ks;)
                                            {
                                                if (response['data']['message'][kind[i]][type[j]][status[k]] !== undefined)
                                                {
                                                    if (kind[i] === 'notify')
                                                    {
                                                        //noinspection JSDuplicatedDeclaration
                                                        for (l = -1, ls = response['data']['message'][kind[i]][type[j]][status[k]].length; ++l < ls;)
                                                        {
                                                            $.notify({
                                                                message: response['data']['message'][kind[i]][type[j]][status[k]][l]
                                                            }, {
                                                                type: status[k]
                                                            });
                                                        }
                                                    }
                                                    else
                                                    {

                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        if (response['data']['rekap_pengukuran_gardu'] !== undefined)
                        {
                            moment.locale('id');
                            var contents = response['data']['rekap_pengukuran_gardu'];
                            table.clear();
                            for (i = table.data().count() - 1, is = contents.length; ++i < is;)
                            {
                                var content = contents[i];
                                table.row.add([
                                    content['no_gardu'],
                                    content['gardu_induk'],
                                    content['gardu_penyulang'],
                                    content['lokasi'],
                                    content['latitude'],
                                    content['longitude'],
                                    content['petugas_1'],
                                    content['petugas_2'],
                                    content['no_kontrak'],
                                    moment(content['date'], "YYYY-MM-DD").tz('Asia/Jakarta').format('dddd, D MMMM YYYY'),
                                    moment(content['time'], "HH:mm:ss").tz('Asia/Jakarta').format('HH:mm:ss zz'),
                                    content['ir'],
                                    content['is'],
                                    content['it'],
                                    content['in'],
                                    content['vrn'],
                                    content['vsn'],
                                    content['vtn'],
                                    content['vrs'],
                                    content['vrt'],
                                    content['vst'],
                                    content['id_u1'],
                                    content['ir_u1'],
                                    content['is_u1'],
                                    content['it_u1'],
                                    content['in_u1'],
                                    content['vrn_u1'],
                                    content['vsn_u1'],
                                    content['vtn_u1'],
                                    content['vrs_u1'],
                                    content['vrt_u1'],
                                    content['vst_u1'],
                                    content['id_u2'],
                                    content['ir_u2'],
                                    content['is_u2'],
                                    content['it_u2'],
                                    content['in_u2'],
                                    content['vrn_u2'],
                                    content['vsn_u2'],
                                    content['vtn_u2'],
                                    content['vrs_u2'],
                                    content['vrt_u2'],
                                    content['vst_u2'],
                                    content['id_u3'],
                                    content['ir_u3'],
                                    content['is_u3'],
                                    content['it_u3'],
                                    content['in_u3'],
                                    content['vrn_u3'],
                                    content['vsn_u3'],
                                    content['vtn_u3'],
                                    content['vrs_u3'],
                                    content['vrt_u3'],
                                    content['vst_u3'],
                                    content['id_u4'],
                                    content['ir_u4'],
                                    content['is_u4'],
                                    content['it_u4'],
                                    content['in_u4'],
                                    content['vrn_u4'],
                                    content['vsn_u4'],
                                    content['vtn_u4'],
                                    content['vrs_u4'],
                                    content['vrt_u4'],
                                    content['vst_u4'],
                                    content['id_k1'],
                                    content['ir_k1'],
                                    content['is_k1'],
                                    content['it_k1'],
                                    content['in_k1'],
                                    content['vrn_k1'],
                                    content['vsn_k1'],
                                    content['vtn_k1'],
                                    content['vrs_k1'],
                                    content['vrt_k1'],
                                    content['vst_k1'],
                                    content['id_k2'],
                                    content['ir_k2'],
                                    content['is_k2'],
                                    content['it_k2'],
                                    content['in_k2'],
                                    content['vrn_k2'],
                                    content['vsn_k2'],
                                    content['vtn_k2'],
                                    content['vrs_k2'],
                                    content['vrt_k2'],
                                    content['vst_k2']
                                ]);
                            }
                            table.draw(true);
                        }
                    }
                    progress.done();
                })
                .fail(function () {
                    progress.done();
                });
        };

        if ((retriever !== undefined) && (retriever !== null))
        {
            retreiveData(table, retriever, NProgress);
        }
    });
    /*
     * Run right away
     * */
})(jQuery);

<commit_msg>Fixing date range filter<commit_after>/**
 * This <server-gardu-reporter> project created by :
 * Name         : syafiq
 * Date / Time  : 04 August 2017, 9:29 PM.
 * Email        : syafiq.rezpector@gmail.com
 * Github       : syafiqq
 */

(function ($) {
    $(function () {
        'use strict';
        moment.locale('id');
        var selector = {};
        selector['table_report'] = 'table#tabel_pengukuran';

        var table = $(selector['table_report']).DataTable({
            "paging": true,
            "lengthChange": false,
            "searching": true,
            "ordering": false,
            "info": true,
            "autoWidth": true,
            "sScrollX": "100%",
            "bScrollCollapse": true,
            "sScrollXInner": "100%",
            "language": {
                "url": $('meta[name="datatable_lang"]').attr('content')
            },
            "columnDefs": [
                {
                    "targets": [9],
                    "visible": false
                }
            ]
        });

        yadcf.init(table, [{
            column_number: 9,
            filter_type: "range_date",
            datepicker_type: 'jquery-ui',
            date_format: 'yyyy-mm-dd',
            filter_container_id: 'timestamp-filter'
        }]);

        var retriever = $('meta[name="retriever"]').attr('content');

        var retreiveData = function (table, link, progress) {
            progress.start();
            $.ajax({
                type: 'get',
                url: link,
                dataType: 'json'
            })
                .done(function (response) {
                    var kind = ['notify', 'message'];
                    var type = ['find'];
                    var status = ['danger', 'info', 'warning', 'success'];
                    if (response['data'] !== undefined)
                    {
                        var i, j, k, l, is, js, ks, ls;
                        if (response['data']['message'] !== undefined)
                        {
                            for (i = -1, is = kind.length; ++i < is;)
                            {
                                if (response['data']['message'][kind[i]] !== undefined)
                                {
                                    for (j = -1, js = type.length; ++j < js;)
                                    {
                                        if (response['data']['message'][kind[i]][type[j]] !== undefined)
                                        {
                                            for (k = -1, ks = status.length; ++k < ks;)
                                            {
                                                if (response['data']['message'][kind[i]][type[j]][status[k]] !== undefined)
                                                {
                                                    if (kind[i] === 'notify')
                                                    {
                                                        //noinspection JSDuplicatedDeclaration
                                                        for (l = -1, ls = response['data']['message'][kind[i]][type[j]][status[k]].length; ++l < ls;)
                                                        {
                                                            $.notify({
                                                                message: response['data']['message'][kind[i]][type[j]][status[k]][l]
                                                            }, {
                                                                type: status[k]
                                                            });
                                                        }
                                                    }
                                                    else
                                                    {

                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        if (response['data']['rekap_pengukuran_gardu'] !== undefined)
                        {
                            var contents = response['data']['rekap_pengukuran_gardu'];
                            table.clear();
                            for (i = table.data().count() - 1, is = contents.length; ++i < is;)
                            {
                                var content = contents[i];
                                table.row.add([
                                    content['no_gardu'],
                                    content['gardu_induk'],
                                    content['gardu_penyulang'],
                                    content['lokasi'],
                                    content['latitude'],
                                    content['longitude'],
                                    content['petugas_1'],
                                    content['petugas_2'],
                                    content['no_kontrak'],
                                    content['date'],
                                    moment(content['date'], "YYYY-MM-DD").tz('Asia/Jakarta').format('dddd, D MMMM YYYY'),
                                    moment(content['time'], "HH:mm:ss").tz('Asia/Jakarta').format('HH:mm:ss zz'),
                                    content['ir'],
                                    content['is'],
                                    content['it'],
                                    content['in'],
                                    content['vrn'],
                                    content['vsn'],
                                    content['vtn'],
                                    content['vrs'],
                                    content['vrt'],
                                    content['vst'],
                                    content['id_u1'],
                                    content['ir_u1'],
                                    content['is_u1'],
                                    content['it_u1'],
                                    content['in_u1'],
                                    content['vrn_u1'],
                                    content['vsn_u1'],
                                    content['vtn_u1'],
                                    content['vrs_u1'],
                                    content['vrt_u1'],
                                    content['vst_u1'],
                                    content['id_u2'],
                                    content['ir_u2'],
                                    content['is_u2'],
                                    content['it_u2'],
                                    content['in_u2'],
                                    content['vrn_u2'],
                                    content['vsn_u2'],
                                    content['vtn_u2'],
                                    content['vrs_u2'],
                                    content['vrt_u2'],
                                    content['vst_u2'],
                                    content['id_u3'],
                                    content['ir_u3'],
                                    content['is_u3'],
                                    content['it_u3'],
                                    content['in_u3'],
                                    content['vrn_u3'],
                                    content['vsn_u3'],
                                    content['vtn_u3'],
                                    content['vrs_u3'],
                                    content['vrt_u3'],
                                    content['vst_u3'],
                                    content['id_u4'],
                                    content['ir_u4'],
                                    content['is_u4'],
                                    content['it_u4'],
                                    content['in_u4'],
                                    content['vrn_u4'],
                                    content['vsn_u4'],
                                    content['vtn_u4'],
                                    content['vrs_u4'],
                                    content['vrt_u4'],
                                    content['vst_u4'],
                                    content['id_k1'],
                                    content['ir_k1'],
                                    content['is_k1'],
                                    content['it_k1'],
                                    content['in_k1'],
                                    content['vrn_k1'],
                                    content['vsn_k1'],
                                    content['vtn_k1'],
                                    content['vrs_k1'],
                                    content['vrt_k1'],
                                    content['vst_k1'],
                                    content['id_k2'],
                                    content['ir_k2'],
                                    content['is_k2'],
                                    content['it_k2'],
                                    content['in_k2'],
                                    content['vrn_k2'],
                                    content['vsn_k2'],
                                    content['vtn_k2'],
                                    content['vrs_k2'],
                                    content['vrt_k2'],
                                    content['vst_k2']
                                ]);
                            }
                            table.draw(true);
                        }
                    }
                    progress.done();
                })
                .fail(function () {
                    progress.done();
                });
        };

        if ((retriever !== undefined) && (retriever !== null))
        {
            retreiveData(table, retriever, NProgress);
        }
    });
    /*
     * Run right away
     * */
})(jQuery);

<|endoftext|>


<commit_before>Ext.define('devilry.extjshelpers.studentsmanager.MultiResultWindow', {
    extend: 'Ext.window.Window',
    layout: 'fit',
    closeAction: 'hide',
    closable: false,
    width: 800,
    height: 600,
    modal: true,
    maximizable: true,

    logTpl: Ext.create('Ext.XTemplate',
        '<tpl for="log">',
        '
',
        '
',
        '            <tpl if="record.data.name">',
        '               {record.data.name} -',
        '            </tpl>',
        '            <tpl for="record.data.candidates__identifier">',
        '               {.}<tpl if="xindex < xcount">, </tpl>',
        '            </tpl>',
        '
',
        '        {msg}',
        '
',
        '</tpl>'
    ),

    operationErrorTpl: Ext.create('Ext.XTemplate',
        '{msg}. ',
        'Error details: ',
        '<tpl if="status === 0">',
        '    Could not contact the Devilry server.',
        '</tpl>',
        '<tpl if="status !== 0">',
        '    {status} {statusText}.',
        '</tpl>'
    ),

    constructor: function(config) {
        this.callParent([config]);
    },

    initComponent: function() {
        this.errorcontainer = Ext.widget('panel', {
            title: 'Errors',
            bodyPadding: 10
        });
        this.warningcontainer = Ext.widget('panel', {
            title: 'Warnings',
            bodyPadding: 10
        });
        this.successcontainer = Ext.widget('panel', {
            title: 'Successful',
            bodyPadding: 10
        });
        Ext.apply(this, {
            items: {
                xtype: 'panel',
                border: false,
                layout: 'accordion'
                //layout: {
                    //type: 'vbox',
                    //align: 'stretch'
                //}
            },
            dockedItems: [{
                xtype: 'toolbar',
                dock: 'bottom',
                ui: 'footer',
                items: ['->', {
                    xtype: 'button',
                    text: 'Close this window',
                    scale: 'large',
                    listeners: {
                        scope: this,
                        click: function() {
                            this.close();
                        }
                    }
                }, '->']
            }]
        });
        this.callParent(arguments);
    },

    addToLog: function(level, record, msg) {
        var logitem = {
            record: record,
            msg: msg
        }
        this.log[level].push(logitem);
        //console.log(logitem);
    },

    addError: function(record, msg) {
        this.addToLog('error', record, msg);
    },

    addErrorFromOperation: function(record, msg, operation) {
        var fullMsg = this.operationErrorTpl.apply({
            msg: msg,
            status: operation.error.status,
            statusText: operation.error.statusText
        });
        this.addToLog('error', record, fullMsg);
    },

    addWarning: function(record, msg) {
        this.addToLog('warning', record, msg);
    },

    addSuccess: function(record, msg) {
        this.addToLog('success', record, msg);
    },

    start: function(title) {
        this.log = {
            error: [],
            warning: [],
            success: []
        };
        this.setTitle(title);
        this.down('panel').removeAll();
    },

    createMsgHtmlList: function(log) {
        Ext.each(log, function(logitem, index) {

        }, this);
    },

    addIfItems: function(log, csscls, title) {
        if(log.length > 0) {
            var container = Ext.widget('panel', {
                title: title,
                bodyPadding: 10,
                flex: 1,
                autoScroll: true,
                html: this.logTpl.apply({
                    csscls: csscls,
                    log: log
                })
            });
            this.down('panel').add(container);
        }
    },

    finish: function(resultMsg, successMsg) {
        this.addIfItems(this.log.error, 'error', 'Errors');
        if(successMsg && this.log.error.length === 0) {
            this.down('panel').add({
                xtype: 'panel',
                title: successMsg.title,
                html: successMsg.html,
                bodyPadding: 10,
                flex: 1
            });
        }
        if(resultMsg) {
            this.down('panel').add({
                xtype: 'panel',
                title: resultMsg.title,
                html: resultMsg.html,
                bodyPadding: 10,
                flex: 1
            });
        }
        this.addIfItems(this.log.warning, 'warning', 'Warnings');
        this.addIfItems(this.log.success, 'ok', 'Details about each successful save');
        this.show();
        this.down('panel').getComponent(0).expand();
    }
});
<commit_msg>apps.extjshelpers: Minor changes.<commit_after>Ext.define('devilry.extjshelpers.studentsmanager.MultiResultWindow', {
    extend: 'Ext.window.Window',
    layout: 'fit',
    closeAction: 'hide',
    closable: false,
    width: 800,
    height: 600,
    modal: true,
    maximizable: true,

    logTpl: Ext.create('Ext.XTemplate',
        '<tpl for="log">',
        '
',
        '
',
        '            <tpl if="record.data.name">',
        '               {record.data.name} -',
        '            </tpl>',
        '            <tpl for="record.data.candidates__identifier">',
        '               {.}<tpl if="xindex < xcount">, </tpl>',
        '            </tpl>',
        '
',
        '        {msg}',
        '
',
        '</tpl>'
    ),

    operationErrorTpl: Ext.create('Ext.XTemplate',
        '{msg}. ',
        'Error details: ',
        '<tpl if="status === 0">',
        '    Could not connect to the Devilry server.',
        '</tpl>',
        '<tpl if="status !== 0">',
        '    {status} {statusText}.',
        '</tpl>'
    ),

    constructor: function(config) {
        this.callParent([config]);
    },

    initComponent: function() {
        this.errorcontainer = Ext.widget('panel', {
            title: 'Errors',
            bodyPadding: 10
        });
        this.warningcontainer = Ext.widget('panel', {
            title: 'Warnings',
            bodyPadding: 10
        });
        this.successcontainer = Ext.widget('panel', {
            title: 'Successful',
            bodyPadding: 10
        });
        Ext.apply(this, {
            items: {
                xtype: 'panel',
                border: false,
                layout: 'accordion'
                //layout: {
                    //type: 'vbox',
                    //align: 'stretch'
                //}
            },
            dockedItems: [{
                xtype: 'toolbar',
                dock: 'bottom',
                ui: 'footer',
                items: ['->', {
                    xtype: 'button',
                    text: 'Close this window',
                    scale: 'large',
                    listeners: {
                        scope: this,
                        click: function() {
                            this.close();
                        }
                    }
                }, '->']
            }]
        });
        this.callParent(arguments);
    },

    addToLog: function(level, record, msg) {
        var logitem = {
            record: record,
            msg: msg
        }
        this.log[level].push(logitem);
        //console.log(logitem);
    },

    addError: function(record, msg) {
        this.addToLog('error', record, msg);
    },

    addErrorFromOperation: function(record, msg, operation) {
        var fullMsg = this.operationErrorTpl.apply({
            msg: msg,
            status: operation.error.status,
            statusText: operation.error.statusText
        });
        this.addToLog('error', record, fullMsg);
    },

    addWarning: function(record, msg) {
        this.addToLog('warning', record, msg);
    },

    addSuccess: function(record, msg) {
        this.addToLog('success', record, msg);
    },

    start: function(title) {
        this.log = {
            error: [],
            warning: [],
            success: []
        };
        this.setTitle(title);
        this.down('panel').removeAll();
    },

    createMsgHtmlList: function(log) {
        Ext.each(log, function(logitem, index) {

        }, this);
    },

    addIfItems: function(log, csscls, title) {
        if(log.length > 0) {
            var container = Ext.widget('panel', {
                title: title,
                bodyPadding: 10,
                flex: 1,
                autoScroll: true,
                html: this.logTpl.apply({
                    csscls: csscls,
                    log: log
                })
            });
            this.down('panel').add(container);
        }
    },

    finish: function(resultMsg, successMsg) {
        this.addIfItems(this.log.error, 'error', 'Errors');
        if(successMsg && this.log.error.length === 0) {
            this.down('panel').add({
                xtype: 'panel',
                title: successMsg.title,
                html: successMsg.html,
                bodyPadding: 10,
                flex: 1
            });
        }
        if(resultMsg) {
            this.down('panel').add({
                xtype: 'panel',
                title: resultMsg.title,
                html: resultMsg.html,
                bodyPadding: 10,
                flex: 1
            });
        }
        this.addIfItems(this.log.warning, 'warning', 'Warnings');
        this.addIfItems(this.log.success, 'info', 'Details about each successful save');
        this.show();
        this.down('panel').getComponent(0).expand();
    }
});
<|endoftext|>


<commit_before>import React from 'react';
import R from 'ramda';
import { Accordion, AccordionItem } from 'react-sanfona';
import { mapProps } from 'recompose';
import RulesList from '../RulesList/RulesList';
import TypedInput from '../../../common/Input/TypedInput';
import * as ContextService from '../../../../services/context-service';
import { InputValue } from '../RuleValue/RuleValue';
import './PartitionsList.css';
import '../../../../styles/core/core.css';

const extractPartitionToObject = (mutate, partitions) => {
  if (partitions.length === 0) {
    return [{ mutate }];
  }

  return R.flatten(
    Object.keys(mutate.getValue()).map((partitionValue) => {
      const innerResults = extractPartitionToObject(mutate.in(partitionValue), partitions.slice(1));
      return innerResults.map(innerResult => ({
        [partitions[0]]: partitionValue,
        ...innerResult,
      }));
    }),
  );
};

const NewPartitionPropertyValue = mapProps(
  ({ value, onUpdate: onChange, name, identity, id: property }) => {
    const propertyTypeDetails = ContextService.getPropertyTypeDetails(property);
    return {
      value,
      onChange,
      placeholder: `${name} (${identity})`,
      valueType: propertyTypeDetails.name,
      customType: propertyTypeDetails,
    };
  },
)(TypedInput);

class AddPartition extends React.Component {
  state = { partition: {}, defaultValue: '' }

  replaceState(state) {
    this.state = state;
    this.setState(state);
  }

  addPartition() {
    const { handlePartitionAddition } = this.props;
    if (handlePartitionAddition) handlePartitionAddition(this.state);
    this.replaceState({ partition: {}, defaultValue: '' });
  }

  render() {
    const { partitions, valueType } = this.props;
    const allProperties = ContextService.getProperties();
    const indexedPartitions = partitions.map(
      partition =>
        allProperties.find(property => property.id === partition) || {
          id: partition,
          name: partition,
        },
    );
    return (

        {indexedPartitions.map(partition =>

            <NewPartitionPropertyValue
              {...partition}
              value={this.state.partition[partition.id] || ''}
              onUpdate={value =>
                this.setState({ partition: { ...this.state.partition, [partition.id]: value } })}
            />

,
        )}
        <InputValue
          value={this.state.defaultValue}
          valueType={valueType}
          onChange={defaultValue => this.setState({ defaultValue })}
          placeholder="Partition's default value"
        />
        <button className={'add-partition-button'} onClick={this.addPartition.bind(this)} />

    );
  }
}

const deletePartitionGroupAlert = {
  title: 'Are you sure?',
  message:
    'This operation will delete the partition group along with all the rules inside it.\nDo you want to continue?',
};

export default class PartitionsList extends React.Component {
  state = {
    activeItems: [],
  }

  render() {
    const { partitions, mutate, valueType, alerter } = this.props;

    const rulesByPartitions = mutate.getValue();
    if (!rulesByPartitions) return
;

    let partitionsData = extractPartitionToObject(mutate, partitions);
    partitionsData = partitionsData.map((x, i) => ({
      ...x,
      valueType,
      id: i,
      partitionsValues: partitions.map(partitionName => x[partitionName]),
    }));

    const hasDefaultValue = Object.keys(rulesByPartitions).includes('*');

    return (

        {!hasDefaultValue
          ? <button
              className={'add-default-partition-button'}
              onClick={() => this.addPartition({})}
            >
              Add default partition
            </button>
          : null}

        <AddPartition
          partitions={partitions}
          handlePartitionAddition={this.addPartition.bind(this)}
          valueType={valueType}
        />

        <Accordion
          className={'partitions-accordion-container'}
          allowMultiple
          activeItems={this.state.activeItems || []}
          onChange={({ activeItems }) => this.setState({ activeItems })}
        >
          {partitionsData.map((partitionData) => {
            const rules = partitionData.mutate.getValue();
            const isOnlyDefault =
              rules.length === 1 &&
              Object.keys(rules[0].Matcher).length === 0 &&
              rules[0].Type === 'SingleVariant';

            const partitionGroupName = partitionData.partitionsValues
              .map(x => (x === '*' ? 'Default' : x))
              .join(', ');
            return (
              <AccordionItem
                title={



{partitionGroupName}

                      {isOnlyDefault ? `value: ${rules[0].Value}` : `rules: ${rules.length}`}

                      <button
                        className={'gray-circle-button'}
                        onClick={(e) => {
                          this.deletePartition(partitionData.partitionsValues);
                          e.stopPropagation();
                        }}
                      >
                        x
                      </button>

                }
                key={partitionGroupName}
                className={'partitions-accordion-container-item'}
                titleClassName={'partitions-accordion-container-item-title'}
                expandedClassName={'partitions-accordion-container-item-expanded'}
              >
                <RulesList {...{ valueType, alerter }} mutate={partitionData.mutate} />
              </AccordionItem>
            );
          })}
        </Accordion>

    );
  }

  addPartition({ partition: newPartition, defaultValue }) {
    console.log({ newPartition, defaultValue });
    const { mutate, partitions } = this.props;
    const partitionDefaultValue = defaultValue === ''
      ? []
      : [{ Type: 'SingleVariant', Matcher: {}, Value: defaultValue }];
    mutate.apply((m) => {
      partitions.forEach((partition, i) => {
        const partitionValue = newPartition[partition] || '*';
        if (!m.getValue()[partitionValue]) {
          m.insert(partitionValue, i === partitions.length - 1 ? partitionDefaultValue : {});
        }
        m = m.in(partitionValue);
      });

      return m;
    });
  }

  async deletePartition(partitionGroup) {
    const { mutate, alerter } = this.props;

    if ((await alerter.showConfirm(deletePartitionGroupAlert)).result) {
      mutate.apply((partitionMutate) => {
        for (const partition of partitionGroup) {
          partitionMutate = partitionMutate.in(partition);
        }

        let i = partitionGroup.length;
        do {
          partitionMutate.delete();
          partitionMutate = partitionMutate.up();
        } while (--i && Object.keys(partitionMutate.getValue()).length === 0);

        return partitionMutate;
      });
    }
  }
}
<commit_msg>fix partition custom type bug<commit_after>import React from 'react';
import R from 'ramda';
import { Accordion, AccordionItem } from 'react-sanfona';
import { mapProps } from 'recompose';
import RulesList from '../RulesList/RulesList';
import TypedInput from '../../../common/Input/TypedInput';
import * as ContextService from '../../../../services/context-service';
import { InputValue } from '../RuleValue/RuleValue';
import './PartitionsList.css';
import '../../../../styles/core/core.css';

const extractPartitionToObject = (mutate, partitions) => {
  if (partitions.length === 0) {
    return [{ mutate }];
  }

  return R.flatten(
    Object.keys(mutate.getValue()).map((partitionValue) => {
      const innerResults = extractPartitionToObject(mutate.in(partitionValue), partitions.slice(1));
      return innerResults.map(innerResult => ({
        [partitions[0]]: partitionValue,
        ...innerResult,
      }));
    }),
  );
};

const NewPartitionPropertyValue = mapProps(
  ({ value, onUpdate: onChange, name, identity, id: property }) => {
    const propertyTypeDetails = ContextService.getPropertyTypeDetails(property);
    return {
      value,
      onChange,
      placeholder: `${name} (${identity})`,
      valueType: propertyTypeDetails,
    };
  },
)(TypedInput);

class AddPartition extends React.Component {
  state = { partition: {}, defaultValue: '' };

  replaceState(state) {
    this.state = state;
    this.setState(state);
  }

  addPartition() {
    const { handlePartitionAddition } = this.props;
    if (handlePartitionAddition) handlePartitionAddition(this.state);
    this.replaceState({ partition: {}, defaultValue: '' });
  }

  render() {
    const { partitions, valueType } = this.props;
    const allProperties = ContextService.getProperties();
    const indexedPartitions = partitions.map(
      partition =>
        allProperties.find(property => property.id === partition) || {
          id: partition,
          name: partition,
        },
    );
    return (

        {indexedPartitions.map(partition =>

            <NewPartitionPropertyValue
              {...partition}
              value={this.state.partition[partition.id] || ''}
              onUpdate={value =>
                this.setState({ partition: { ...this.state.partition, [partition.id]: value } })}
            />

,
        )}
        <InputValue
          value={this.state.defaultValue}
          valueType={valueType}
          onChange={defaultValue => this.setState({ defaultValue })}
          placeholder="Partition's default value"
        />
        <button className={'add-partition-button'} onClick={this.addPartition.bind(this)} />

    );
  }
}

const deletePartitionGroupAlert = {
  title: 'Are you sure?',
  message:
    'This operation will delete the partition group along with all the rules inside it.\nDo you want to continue?',
};

export default class PartitionsList extends React.Component {
  state = {
    activeItems: [],
  };

  render() {
    const { partitions, mutate, valueType, alerter } = this.props;

    const rulesByPartitions = mutate.getValue();
    if (!rulesByPartitions) return
;

    let partitionsData = extractPartitionToObject(mutate, partitions);
    partitionsData = partitionsData.map((x, i) => ({
      ...x,
      valueType,
      id: i,
      partitionsValues: partitions.map(partitionName => x[partitionName]),
    }));

    const hasDefaultValue = Object.keys(rulesByPartitions).includes('*');

    return (

        {!hasDefaultValue
          ? <button
              className={'add-default-partition-button'}
              onClick={() => this.addPartition({})}
            >
              Add default partition
            </button>
          : null}

        <AddPartition
          partitions={partitions}
          handlePartitionAddition={this.addPartition.bind(this)}
          valueType={valueType}
        />

        <Accordion
          className={'partitions-accordion-container'}
          allowMultiple
          activeItems={this.state.activeItems || []}
          onChange={({ activeItems }) => this.setState({ activeItems })}
        >
          {partitionsData.map((partitionData) => {
            const rules = partitionData.mutate.getValue();
            const isOnlyDefault =
              rules.length === 1 &&
              Object.keys(rules[0].Matcher).length === 0 &&
              rules[0].Type === 'SingleVariant';

            const partitionGroupName = partitionData.partitionsValues
              .map(x => (x === '*' ? 'Default' : x))
              .join(', ');
            return (
              <AccordionItem
                title={



{partitionGroupName}

                      {isOnlyDefault ? `value: ${rules[0].Value}` : `rules: ${rules.length}`}

                      <button
                        className={'gray-circle-button'}
                        onClick={(e) => {
                          this.deletePartition(partitionData.partitionsValues);
                          e.stopPropagation();
                        }}
                      >
                        x
                      </button>

                }
                key={partitionGroupName}
                className={'partitions-accordion-container-item'}
                titleClassName={'partitions-accordion-container-item-title'}
                expandedClassName={'partitions-accordion-container-item-expanded'}
              >
                <RulesList {...{ valueType, alerter }} mutate={partitionData.mutate} />
              </AccordionItem>
            );
          })}
        </Accordion>

    );
  }

  addPartition({ partition: newPartition, defaultValue }) {
    console.log({ newPartition, defaultValue });
    const { mutate, partitions } = this.props;
    const partitionDefaultValue = defaultValue === ''
      ? []
      : [{ Type: 'SingleVariant', Matcher: {}, Value: defaultValue }];
    mutate.apply((m) => {
      partitions.forEach((partition, i) => {
        const partitionValue = newPartition[partition] || '*';
        if (!m.getValue()[partitionValue]) {
          m.insert(partitionValue, i === partitions.length - 1 ? partitionDefaultValue : {});
        }
        m = m.in(partitionValue);
      });

      return m;
    });
  }

  async deletePartition(partitionGroup) {
    const { mutate, alerter } = this.props;

    if ((await alerter.showConfirm(deletePartitionGroupAlert)).result) {
      mutate.apply((partitionMutate) => {
        for (const partition of partitionGroup) {
          partitionMutate = partitionMutate.in(partition);
        }

        let i = partitionGroup.length;
        do {
          partitionMutate.delete();
          partitionMutate = partitionMutate.up();
        } while (--i && Object.keys(partitionMutate.getValue()).length === 0);

        return partitionMutate;
      });
    }
  }
}
<|endoftext|>


<commit_before>/*
Copyright 2016 First People's Cultural Council

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import React, { Component, PropTypes } from 'react'
import Immutable, { List, Map } from 'immutable'
import provide from 'react-redux-provide'
import selectn from 'selectn'

import PromiseWrapper from 'views/components/Document/PromiseWrapper'

import ProviderHelpers from 'common/ProviderHelpers'
import DocumentListView from 'views/components/Document/DocumentListView'
import DocumentListViewDatatable from 'views/components/Document/DocumentListViewDatatable'

import DataListView from 'views/pages/explore/dialect/learn/base/data-list-view'
import IntlService from 'views/services/intl'

const intl = IntlService.instance
/**
 * List view for contributors
 */
@provide
class ListView extends DataListView {
  static defaultProps = {
    DISABLED_SORT_COLS: ['state'],
    DEFAULT_PAGE: 1,
    DEFAULT_PAGE_SIZE: 100,
    DEFAULT_LANGUAGE: 'english',
    DEFAULT_SORT_COL: 'dc:title',
    DEFAULT_SORT_TYPE: 'asc',
    dialect: null,
    filter: new Map(),
    gridListView: false,
    gridCols: 4,
    useDatatable: false,
  }

  static propTypes = {
    properties: PropTypes.object.isRequired,
    windowPath: PropTypes.string.isRequired,
    splitWindowPath: PropTypes.array.isRequired,
    pushWindowPath: PropTypes.func.isRequired,
    computeLogin: PropTypes.object.isRequired,
    fetchDialect2: PropTypes.func.isRequired,
    fetchContributors: PropTypes.func.isRequired,
    computeDialect2: PropTypes.object.isRequired,
    dialect: PropTypes.object,
    computeContributors: PropTypes.object.isRequired,
    routeParams: PropTypes.object.isRequired,
    filter: PropTypes.object,
    data: PropTypes.string,
    gridListView: PropTypes.bool,
    gridCols: PropTypes.number,
    action: PropTypes.func,

    DISABLED_SORT_COLS: PropTypes.array,
    DEFAULT_PAGE: PropTypes.number,
    DEFAULT_PAGE_SIZE: PropTypes.number,
    DEFAULT_SORT_COL: PropTypes.string,
    DEFAULT_SORT_TYPE: PropTypes.string,
    useDatatable: PropTypes.bool,
  }

  constructor(props, context) {
    super(props, context)

    this.state = {
      columns: [
        {
          name: 'title',
          title: intl.trans('contributor', 'Contributor', 'first'),
          render: (v, data, cellProps) => v,
        },
        {
          name: 'dc:description',
          title: intl.trans('short_proflile', 'Short Profile', 'words'),
          render: (v, data, cellProps) => selectn('properties.dc:description', data),
        },
      ],
      sortInfo: {
        uiSortOrder: [],
        currentSortCols: this.props.DEFAULT_SORT_COL,
        currentSortType: this.props.DEFAULT_SORT_TYPE,
      },
      pageInfo: {
        page: this.props.DEFAULT_PAGE,
        pageSize: this.props.DEFAULT_PAGE_SIZE,
      },
      contributorsPath: `${props.routeParams.dialect_path}/Contributors`,
    }

    // Bind methods to 'this'
    ;[
      '_onNavigateRequest',
      '_onEntryNavigateRequest',
      '_handleRefetch',
      '_handleSortChange',
      '_handleColumnOrderChange',
      '_resetColumns',
      '_fetchListViewData',
    ].forEach((method) => (this[method] = this[method].bind(this)))
  }

  // NOTE: DataListView calls `fetchData`
  fetchData(newProps) {
    if (newProps.dialect == null) {
      newProps.fetchDialect2(newProps.routeParams.dialect_path)
    }
    this._fetchListViewData(
      newProps,
      newProps.DEFAULT_PAGE,
      newProps.DEFAULT_PAGE_SIZE,
      newProps.DEFAULT_SORT_TYPE,
      newProps.DEFAULT_SORT_COL
    )
  }

  _onEntryNavigateRequest(item) {
    if (this.props.action) {
      this.props.action(item)
    } else {
      //this.props.pushWindowPath('/' + this.props.routeParams.theme + item.path.replace('Dictionary', 'words/contributors/' + item.uid));
    }
  }

  _fetchListViewData(props, pageIndex, pageSize, sortOrder, sortBy) {
    let currentAppliedFilter = ''

    if (props.filter.has('currentAppliedFilter')) {
      currentAppliedFilter = Object.values(props.filter.get('currentAppliedFilter').toJS()).join('')
    }

    props.fetchContributors(
      this.state.contributorsPath,
      `${currentAppliedFilter}&currentPageIndex=${pageIndex -
        1}&pageSize=${pageSize}&sortOrder=${sortOrder}&sortBy=${sortBy}`
    )
  }

  render() {
    const computeEntities = Immutable.fromJS([
      {
        id: this.state.contributorsPath,
        entity: this.props.computeContributors,
      },
      {
        id: this.props.routeParams.dialect_path,
        entity: this.props.computeDialect2,
      },
    ])

    const computeContributors = ProviderHelpers.getEntry(this.props.computeContributors, this.state.contributorsPath)
    const computeDialect2 = ProviderHelpers.getEntry(this.props.computeDialect2, this.props.routeParams.dialect_path)

    const DocumentView = this.props.useDatatable ? (
      <DocumentListViewDatatable
        objectDescriptions="contributors"
        type="FVContributor"
        data={computeContributors}
        gridCols={this.props.gridCols}
        gridListView={this.props.gridListView}
        refetcher={this._handleRefetch}
        onSortChange={this._handleSortChange}
        onSelectionChange={this._onEntryNavigateRequest}
        page={this.state.pageInfo.page}
        pageSize={this.state.pageInfo.pageSize}
        onColumnOrderChange={this._handleColumnOrderChange}
        columns={this.state.columns}
        sortInfo={this.state.sortInfo.uiSortOrder}
        className="browseDataGrid"
        dialect={selectn('response', computeDialect2)}
      />
    ) : (
      <DocumentListView
        objectDescriptions="contributors"
        type="FVContributor"
        data={computeContributors}
        gridCols={this.props.gridCols}
        gridListView={this.props.gridListView}
        refetcher={this._handleRefetch}
        onSortChange={this._handleSortChange}
        onSelectionChange={this._onEntryNavigateRequest}
        page={this.state.pageInfo.page}
        pageSize={this.state.pageInfo.pageSize}
        onColumnOrderChange={this._handleColumnOrderChange}
        columns={this.state.columns}
        sortInfo={this.state.sortInfo.uiSortOrder}
        className="browseDataGrid"
        dialect={selectn('response', computeDialect2)}
      />
    )
    return (
      <PromiseWrapper renderOnError computeEntities={computeEntities}>
        {selectn('response.entries', computeContributors) && DocumentView}
      </PromiseWrapper>
    )
  }
}
export default ListView
<commit_msg>Reduxed: `dialect/learn/base`: `<ListView />`<commit_after>/*
Copyright 2016 First People's Cultural Council

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import React, { PropTypes } from 'react'
import Immutable, { Map } from 'immutable'

// REDUX
import { connect } from 'react-redux'
// REDUX: actions/dispatch/func
import { fetchContributors } from 'providers/redux/reducers/fvContributor'
import { fetchDialect2 } from 'providers/redux/reducers/fvDialect'
import { pushWindowPath } from 'providers/redux/reducers/windowPath'

import selectn from 'selectn'

import PromiseWrapper from 'views/components/Document/PromiseWrapper'

import ProviderHelpers from 'common/ProviderHelpers'
import DocumentListView from 'views/components/Document/DocumentListView'
import DocumentListViewDatatable from 'views/components/Document/DocumentListViewDatatable'

import DataListView from 'views/pages/explore/dialect/learn/base/data-list-view'
import IntlService from 'views/services/intl'

const intl = IntlService.instance
/**
 * List view for contributors
 */

const { array, bool, func, number, object, string } = PropTypes
class ListView extends DataListView {
  static propTypes = {
    action: func,
    data: string,
    DEFAULT_PAGE: number,
    DEFAULT_PAGE_SIZE: number,
    DEFAULT_SORT_COL: string,
    DEFAULT_SORT_TYPE: string,
    dialect: object,
    DISABLED_SORT_COLS: array,
    filter: object,
    gridCols: number,
    gridListView: bool,
    routeParams: object.isRequired,
    useDatatable: bool,
    // REDUX: reducers/state
    properties: object.isRequired,
    windowPath: string.isRequired,
    splitWindowPath: array.isRequired,
    computeLogin: object.isRequired,
    computeDialect2: object.isRequired,
    computeContributors: object.isRequired,
    // REDUX: actions/dispatch/func
    fetchContributors: func.isRequired,
    fetchDialect2: func.isRequired,
    pushWindowPath: func.isRequired,
  }
  static defaultProps = {
    DISABLED_SORT_COLS: ['state'],
    DEFAULT_PAGE: 1,
    DEFAULT_PAGE_SIZE: 100,
    DEFAULT_LANGUAGE: 'english',
    DEFAULT_SORT_COL: 'dc:title',
    DEFAULT_SORT_TYPE: 'asc',
    dialect: null,
    filter: new Map(),
    gridListView: false,
    gridCols: 4,
    useDatatable: false,
  }

  constructor(props, context) {
    super(props, context)

    this.state = {
      columns: [
        {
          name: 'title',
          title: intl.trans('contributor', 'Contributor', 'first'),
          render: (v /*, data, cellProps*/) => v,
        },
        {
          name: 'dc:description',
          title: intl.trans('short_proflile', 'Short Profile', 'words'),
          render: (v, data /*, cellProps*/) => selectn('properties.dc:description', data),
        },
      ],
      sortInfo: {
        uiSortOrder: [],
        currentSortCols: this.props.DEFAULT_SORT_COL,
        currentSortType: this.props.DEFAULT_SORT_TYPE,
      },
      pageInfo: {
        page: this.props.DEFAULT_PAGE,
        pageSize: this.props.DEFAULT_PAGE_SIZE,
      },
      contributorsPath: `${props.routeParams.dialect_path}/Contributors`,
    }

    // Bind methods to 'this'
    ;[
      '_onNavigateRequest',
      '_onEntryNavigateRequest',
      '_handleRefetch',
      '_handleSortChange',
      '_handleColumnOrderChange',
      '_resetColumns',
      '_fetchListViewData',
    ].forEach((method) => (this[method] = this[method].bind(this)))
  }

  // NOTE: DataListView calls `fetchData`
  fetchData(newProps) {
    if (newProps.dialect === null) {
      newProps.fetchDialect2(newProps.routeParams.dialect_path)
    }
    this._fetchListViewData(
      newProps,
      newProps.DEFAULT_PAGE,
      newProps.DEFAULT_PAGE_SIZE,
      newProps.DEFAULT_SORT_TYPE,
      newProps.DEFAULT_SORT_COL
    )
  }

  _onEntryNavigateRequest(item) {
    if (this.props.action) {
      this.props.action(item)
    } else {
      //this.props.pushWindowPath('/' + this.props.routeParams.theme + item.path.replace('Dictionary', 'words/contributors/' + item.uid));
    }
  }

  _fetchListViewData(props, pageIndex, pageSize, sortOrder, sortBy) {
    let currentAppliedFilter = ''

    if (props.filter.has('currentAppliedFilter')) {
      currentAppliedFilter = Object.values(props.filter.get('currentAppliedFilter').toJS()).join('')
    }

    props.fetchContributors(
      this.state.contributorsPath,
      `${currentAppliedFilter}&currentPageIndex=${pageIndex -
        1}&pageSize=${pageSize}&sortOrder=${sortOrder}&sortBy=${sortBy}`
    )
  }

  render() {
    const computeEntities = Immutable.fromJS([
      {
        id: this.state.contributorsPath,
        entity: this.props.computeContributors,
      },
      {
        id: this.props.routeParams.dialect_path,
        entity: this.props.computeDialect2,
      },
    ])

    const computeContributors = ProviderHelpers.getEntry(this.props.computeContributors, this.state.contributorsPath)
    const computeDialect2 = ProviderHelpers.getEntry(this.props.computeDialect2, this.props.routeParams.dialect_path)

    const DocumentView = this.props.useDatatable ? (
      <DocumentListViewDatatable
        objectDescriptions="contributors"
        type="FVContributor"
        data={computeContributors}
        gridCols={this.props.gridCols}
        gridListView={this.props.gridListView}
        refetcher={this._handleRefetch}
        onSortChange={this._handleSortChange}
        onSelectionChange={this._onEntryNavigateRequest}
        page={this.state.pageInfo.page}
        pageSize={this.state.pageInfo.pageSize}
        onColumnOrderChange={this._handleColumnOrderChange}
        columns={this.state.columns}
        sortInfo={this.state.sortInfo.uiSortOrder}
        className="browseDataGrid"
        dialect={selectn('response', computeDialect2)}
      />
    ) : (
      <DocumentListView
        objectDescriptions="contributors"
        type="FVContributor"
        data={computeContributors}
        gridCols={this.props.gridCols}
        gridListView={this.props.gridListView}
        refetcher={this._handleRefetch}
        onSortChange={this._handleSortChange}
        onSelectionChange={this._onEntryNavigateRequest}
        page={this.state.pageInfo.page}
        pageSize={this.state.pageInfo.pageSize}
        onColumnOrderChange={this._handleColumnOrderChange}
        columns={this.state.columns}
        sortInfo={this.state.sortInfo.uiSortOrder}
        className="browseDataGrid"
        dialect={selectn('response', computeDialect2)}
      />
    )
    return (
      <PromiseWrapper renderOnError computeEntities={computeEntities}>
        {selectn('response.entries', computeContributors) && DocumentView}
      </PromiseWrapper>
    )
  }
}

// REDUX: reducers/state
const mapStateToProps = (state /*, ownProps*/) => {
  const { fvContributor, fvDialect, navigation, nuxeo, windowPath } = state

  const { properties } = navigation
  const { computeLogin } = nuxeo
  const { computeContributors } = fvContributor
  const { computeDialect2 } = fvDialect
  const { splitWindowPath, _windowPath } = windowPath

  return {
    computeContributors,
    computeDialect2,
    computeLogin,
    properties,
    splitWindowPath,
    windowPath: _windowPath,
  }
}

// REDUX: actions/dispatch/func
const mapDispatchToProps = {
  fetchContributors,
  fetchDialect2,
  pushWindowPath,
}

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


<commit_before>'use strict';

(function(){
    var ExcerptViewer = function(locationFilter, selectElementExistingExcerpts) {
        this.locationFilter = locationFilter;
        this.selectElementExistingExcerpts = selectElementExistingExcerpts;
        this.selectedExcerptGeoJson = null;
        this.country = null;

        // update excerpt on map on selection of existing excerpt in list
        var getExcerptOptionAndUpdateFilter = function() {
            // we have single select, if it would happen to have two selected, ignore it.
            var excerptOption = this.selectElementExistingExcerpts.querySelector('option:checked');
            if(excerptOption) {
                this._setLocationFilterFromExcerptID(excerptOption.value);
            }
        }.bind(this);
        this.selectElementExistingExcerpts.addEventListener('click', getExcerptOptionAndUpdateFilter);
        this.selectElementExistingExcerpts.addEventListener('keyup', function(event) {
            // enter, arrow up or down
            if (event.keyCode == 13 || event.keyCode == 38 || event.keyCode == 40) {
                getExcerptOptionAndUpdateFilter();
            }
        });

        this._setLocationFilterFromExcerptID = function(ID) {
            var that = this;

            this._handleCountry = function (country){
                if (that.country !== null) {
                    map.removeLayer(that.country);
                }

                that.locationFilter.disable();
                that.country = that.selectedExcerptGeoJson;
                map.addLayer(that.country);
                map.fitBounds(country.getBounds());
            };

            this._handleBBoxBoundingGeometry = function (geometry){
                if (that.country !== null) {
                    map.removeLayer(that.country);
                }

                that.locationFilter.enable();
                that.locationFilter.setBounds(geometry.getBounds());
                map.fitBounds(that.locationFilter.getBounds());
            };

            this.selectedExcerptGeoJson = L.geoJson.ajax("/api/bounding_geometry_from_excerpt/"+ID+"/").on('data:loaded', function(){
                // We are certain that there is only one layer on this feature, because our API provides it so.
                var feature_type = this.getLayers()[0].feature.properties.type_of_geometry;
                switch(feature_type) {
                    case 'BBoxBoundingGeometry':
                        that._handleBBoxBoundingGeometry(this);
                        break;
                    case 'Country':
                        that._handleCountry(this);
                        break;
                    default:
                        break;
                }
            });
            this.selectedExcerptGeoJson.on('data:loading', function(){
                map.spin(true);
            });

            this.selectedExcerptGeoJson.on('data:loaded', function(){
                map.spin(false);
            });
        }.bind(this);
    };

    var map = L.map('map').setView([0, 0], 2);
    // add an OpenStreetMap tile layer
    L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
        attribution: '© OpenStreetMap contributors'
    }).addTo(map);

    var locationFilter = new L.LocationFilter({
        enable: false,
        enableButton: false
    }).addTo(map);

    var excerptManager = new ExcerptViewer(
        locationFilter,
        document.getElementById('id_existing_excerpts')
    );
})();
<commit_msg>Fix zoom bug of map<commit_after>'use strict';

(function(){
    var ExcerptViewer = function(locationFilter, selectElementExistingExcerpts) {
        this.locationFilter = locationFilter;
        this.selectElementExistingExcerpts = selectElementExistingExcerpts;
        this.selectedExcerptGeoJson = null;
        this.country = null;

        // update excerpt on map on selection of existing excerpt in list
        var getExcerptOptionAndUpdateFilter = function() {
            // we have single select, if it would happen to have two selected, ignore it.
            var excerptOption = this.selectElementExistingExcerpts.querySelector('option:checked');
            if(excerptOption) {
                this._setLocationFilterFromExcerptID(excerptOption.value);
            }
        }.bind(this);
        this.selectElementExistingExcerpts.addEventListener('click', getExcerptOptionAndUpdateFilter);
        this.selectElementExistingExcerpts.addEventListener('keyup', function(event) {
            // enter, arrow up or down
            if (event.keyCode == 13 || event.keyCode == 38 || event.keyCode == 40) {
                getExcerptOptionAndUpdateFilter();
            }
        });

        // TODO: Replace this not understandable hack
        this._setLocationFilterFromExcerptID = function(ID) {
            var that = this;

            this._handleCountry = function (country){
                if (that.country !== null) {
                    map.removeLayer(that.country);
                }

                that.locationFilter.disable();
                that.country = that.selectedExcerptGeoJson;
                map.addLayer(that.country);
                map.fitBounds(country.getBounds());
            };

            this._handleBBoxBoundingGeometry = function (geometry){
                if (that.country !== null) {
                    map.removeLayer(that.country);
                }

                // If location filter is enabled, it will collide with fitBounds and you will get some strange behaviour
                that.locationFilter.disable();
                that.locationFilter.setBounds(geometry.getBounds());
                map.fitBounds(geometry.getBounds());
                that.locationFilter.enable();
            };

            this.selectedExcerptGeoJson = L.geoJson.ajax("/api/bounding_geometry_from_excerpt/"+ID+"/").on('data:loaded', function(){
                // We are certain that there is only one layer on this feature, because our API provides it so.
                var feature_type = this.getLayers()[0].feature.properties.type_of_geometry;
                switch(feature_type) {
                    case 'BBoxBoundingGeometry':
                        that._handleBBoxBoundingGeometry(this);
                        break;
                    case 'Country':
                        that._handleCountry(this);
                        break;
                    default:
                        break;
                }
            });
            this.selectedExcerptGeoJson.on('data:loading', function(){
                map.spin(true);
            });

            this.selectedExcerptGeoJson.on('data:loaded', function(){
                map.spin(false);
            });
        }.bind(this);
    };

    var map = L.map('map').setView([0, 0], 2);
    // add an OpenStreetMap tile layer
    L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
        attribution: '© OpenStreetMap contributors'
    }).addTo(map);

    var locationFilter = new L.LocationFilter({
        enable: false,
        enableButton: false
    }).addTo(map);

    var excerptManager = new ExcerptViewer(
        locationFilter,
        document.getElementById('id_existing_excerpts')
    );
})();
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';
import { chain } from 'lodash';

const getFirstTag = c => c.meta.tags[0];

export default function ConsortiumComputationSelector({
  computations,
  input,
  meta,
}) {
  let radioClassNames = 'consortium-computation-selector-radio radio';
  let helpBlock;

  if (meta.touched && meta.error) {
    helpBlock = {meta.error};
    radioClassNames += ' has-error';
  }

  /**
   * @todo Don't hard-code the 'Regressions' label. Determine a way to map
   * computation tags to human-readable names.
   */
  const computationsFields = chain(computations)
    .sortBy(getFirstTag)
    .groupBy(getFirstTag)
    .map((comps, tag) => (
      <fieldset className="consortium-computation-selector-group" key={tag}>
        <legend className="consortium-computation-selector-label">
          Regressions
        </legend>
        {comps.map(
          (
            {
              _id,
              meta: { description, name, tags },
              version,
            },
            index
          ) => {
            const isChecked = input.value === _id;

            return (

                  <input
                    checked={isChecked}
                    className="sr-only"
                    onChange={input.onChange}
                    name={input.name}
                    type="radio"
                    value={_id}
                  />
                  <span
                    aria-hidden="true"
                    className={`glyphicon glyphicon-${isChecked ? 'check' : 'unchecked'}`}
                  >

{name} Version {version}

{description}

            );
          }
        )}
      </fieldset>
    ))
    .value();

  return (

      {helpBlock}
      {computationsFields}

  );
}

ConsortiumComputationSelector.propTypes = {
  computations: PropTypes.array,
  input: PropTypes.object,
  meta: PropTypes.object,
};
<commit_msg>Clarify 'Regressions' → 'FreeSurfer Regressions' in consortium view.<commit_after>import React, { PropTypes } from 'react';
import { chain } from 'lodash';

const getFirstTag = c => c.meta.tags[0];

export default function ConsortiumComputationSelector({
  computations,
  input,
  meta,
}) {
  let radioClassNames = 'consortium-computation-selector-radio radio';
  let helpBlock;

  if (meta.touched && meta.error) {
    helpBlock = {meta.error};
    radioClassNames += ' has-error';
  }

  /**
   * @todo Don't hard-code the 'FreeSurfer Regressions' label. Determine a way
   * to map computation tags to human-readable names.
   */
  const computationsFields = chain(computations)
    .sortBy(getFirstTag)
    .groupBy(getFirstTag)
    .map((comps, tag) => (
      <fieldset className="consortium-computation-selector-group" key={tag}>
        <legend className="consortium-computation-selector-label">
          FreeSurfer Regressions
        </legend>
        {comps.map(
          (
            {
              _id,
              meta: { description, name, tags },
              version,
            },
            index
          ) => {
            const isChecked = input.value === _id;

            return (

                  <input
                    checked={isChecked}
                    className="sr-only"
                    onChange={input.onChange}
                    name={input.name}
                    type="radio"
                    value={_id}
                  />
                  <span
                    aria-hidden="true"
                    className={`glyphicon glyphicon-${isChecked ? 'check' : 'unchecked'}`}
                  >

{name} Version {version}

{description}

            );
          }
        )}
      </fieldset>
    ))
    .value();

  return (

      {helpBlock}
      {computationsFields}

  );
}

ConsortiumComputationSelector.propTypes = {
  computations: PropTypes.array,
  input: PropTypes.object,
  meta: PropTypes.object,
};
<|endoftext|>


<commit_before>/** Base class for windows used to Edit/Create RestfulSimplified models. */
Ext.define('devilry.extjshelpers.RestfulSimplifiedEditWindowBase', {
    extend: 'devilry.extjshelpers.MaximizableWindow',
    //width: 800,
    //height: 600,
    layout: 'fit',
    maximizable: true,
    modal: true,

    config: {
        /**
         * @cfg
         * The {@link devilry.extjshelpers.RestfulSimplifiedEditPanel} to use for editing.
         */
        editpanel: undefined
    },

    constructor: function(config) {
        this.callParent([config]);
        this.initConfig(config);
    },

    initComponent: function() {
        var me = this;

        var form = this.editpanel.down('form');
        if(!this.width && form.suggested_windowsize) {
            this.width = form.suggested_windowsize.width,
            this.height = form.suggested_windowsize.height
        }

        this.editpanel.addListener('saveSucess', function(record) {
            me.onSaveSuccess(record);
        });

        Ext.apply(this, {
            items: this.editpanel
        });
        this.callParent(arguments);
    },

    onSaveSuccess: function(record) {
        throw "Must implement onSaveSuccess()"
    }
});
<commit_msg>apps.extjshelpers...RestfulSimplifiedEditWindowBase: Autoresize when to small.<commit_after>/** Base class for windows used to Edit/Create RestfulSimplified models. */
Ext.define('devilry.extjshelpers.RestfulSimplifiedEditWindowBase', {
    extend: 'devilry.extjshelpers.MaximizableWindow',
    //width: 800,
    //height: 600,
    layout: 'fit',
    maximizable: true,
    modal: true,

    /**
     * @cfg
     * The {@link devilry.extjshelpers.RestfulSimplifiedEditPanel} to use for editing.
     */
    editpanel: undefined,

    initComponent: function() {
        var me = this;

        var form = this.editpanel.down('form');
        if(!this.width && form.suggested_windowsize) {
            this.width = form.suggested_windowsize.width,
            this.height = form.suggested_windowsize.height
        }
        this._preferredWidth = this.width || 700;
        this._preferredHeight = this.height || 500;

        this.editpanel.addListener('saveSucess', function(record) {
            me.onSaveSuccess(record);
        });

        Ext.apply(this, {
            items: this.editpanel
        });
        this._setupAutosizing();
        this.callParent(arguments);
    },

    onSaveSuccess: function(record) {
        throw "Must implement onSaveSuccess()"
    },

    _setupAutosizing: function() {
        Ext.fly(window).on('resize', this._onWindowResize, this);
        this.on('show', this._onShowWindow, this);
    },
    _onShowWindow: function() {
        this._setSizeAndPosition();
    },
    _onWindowResize: function() {
        if(this.isVisible() && this.isFloating()) {
            this._setSizeAndPosition();
        }
    },
    _setSizeAndPosition: function() {
        if(this.isFloating()) {
            var padding = 20;
            var bodysize = Ext.getBody().getViewSize();
            var bodyWidth = bodysize.width - padding;
            var bodyHeight = bodysize.height - padding;
            var height = bodyHeight < this._preferredHeight? bodyHeight: this._preferredHeight;
            var width = bodyWidth < this._preferredWidth? bodyWidth: this._preferredWidth;
            this.setSize({
                width: width,
                height: height,
            });
            this.center();
        }
    }
});
<|endoftext|>


<commit_before>var dbm = require('db-migrate');
var type = dbm.dataType;

exports.up = function(db, callback) {
  db.addColumn('external_transactions', 'to_account_id', {
    type: 'int'
  }, callback);
};

exports.down = function(db, callback) {
  db.addColumn('external_transactions', 'from_account_id', {
    type: 'int'
  }, callback);
};

<commit_msg>[FIX] Correct the down methods for rollback<commit_after>var dbm = require('db-migrate');
var type = dbm.dataType;

exports.up = function(db, callback) {
  db.addColumn('external_transactions', 'to_account_id', {
    type: 'int'
  }, callback);
};

exports.down = function(db, callback) {
  db.removeColumn('external_transactions', 'to_account_id', callback);
};

<|endoftext|>