<commit_before>/*
    Copyright (C) 2014 Härnösands kommun

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
/**
 * Identify action
 *
 * TODO: Should be generic, is now hardcoded against search-lm parcels
 */
Ext.define('OpenEMap.action.Identify', {
    extend: 'OpenEMap.action.Action',
    requires: ['OpenEMap.view.IdentifyResults'],
    popup : null,

    getPopup : function(config){
        if (this.popup){
            this.popup.destroy();
        }
        this.popup = Ext.create('GeoExt.window.Popup', {
            title: 'Sökresultat',
            location: config.feature,
            anchored: false,
            unpinnable: false,
            draggable: true,
            map: config.mapPanel,
            maximizable : false,
            minimizable : false,
            resizable: true,
            width: 300,
            height: 400,
            layout: 'fit',
            items: config.items,
            collapsible: false,
            x : 200,
            y: 100,
            listeners : {
                close : function(){
                    config.mapPanel.searchLayer.removeAllFeatures();
                }
            }
        });

        return this.popup;
    },

    constructor: function(config) {
        var self = this;

        var mapPanel = config.mapPanel;
        var layer = mapPanel.searchLayer;
        var map = config.map;
        var layers = config.layers;

        var Click = OpenLayers.Class(OpenLayers.Control, {
            initialize: function(options) {
                OpenLayers.Control.prototype.initialize.apply(
                    this, arguments
                );
                this.handler = new OpenLayers.Handler.Click(
                    this, {
                        'click': this.onClick
                    }, this.handlerOptions
                );
            },
            onClick: function(evt) {
                mapPanel.setLoading(true);
                layer.destroyFeatures();

                var lonlat = map.getLonLatFromPixel(evt.xy);

                var x = lonlat.lon;
                var y = lonlat.lat;

                var point = new OpenLayers.Geometry.Point(x, y);
                var feature = new OpenLayers.Feature.Vector(point);
                layer.addFeatures([feature]);

                var identifyResults = Ext.create('OpenEMap.view.IdentifyResults', {
                    mapPanel : mapPanel
                });

                var popup = self.getPopup({mapPanel : mapPanel, location: feature, items: identifyResults});
                popup.show();

                OpenEMap.requestLM({
                    url: 'registerenheter?x=' + x + '&y=' + y,
                    success: function(response) {
                        var registerenhet = Ext.decode(response.responseText);

                        var feature = new OpenLayers.Feature.Vector(point, {
                            name: registerenhet.name
                        });
                        identifyResults.addResult([feature], {name:"Fastigheter"});
                    },
                    failure: function(response) {
                        Ext.Msg.alert('Fel', response.statusText);
                    },
                    callback: function() {
                        mapPanel.setLoading(false);
                    }
                });

                var parser = Ext.create('OpenEMap.config.Parser');

                var wfsLayers =  parser.extractWFS(layers);

                var wfsIdentify = function(wfsLayer) {
                    var options = Ext.apply({
                        version: "1.1.0",
                        srsName: "EPSG:3006"
                    }, wfsLayer.wfs);

                    var protocol = new OpenLayers.Protocol.WFS(options);

                    protocol.read({
                        filter: new OpenLayers.Filter({
                            type: OpenLayers.Filter.Spatial.BBOX,
                            value: point.getBounds()
                        }),
                        callback: function(response) {
                            var features = response.features;
                            if (features && features.length>0) {
                                identifyResults.addResult(features, wfsLayer);
                                layer.addFeatures(features);
                            }
                        }
                    });
                };

                wfsLayers.forEach(wfsIdentify);
            }
        });

        config.control = new Click({
            type: OpenLayers.Control.TYPE_TOGGLE
        });

        config.iconCls = config.iconCls || 'action-identify';
        config.tooltip = config.tooltip || 'Identifiera';
        config.toggleGroup = 'extraTools';

        this.callParent(arguments);
    }
});
<commit_msg>Identify tool WFS-layers supporting projection setting in config. #114<commit_after>/*
    Copyright (C) 2014 Härnösands kommun

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
/**
 * Identify action
 *
 * TODO: Should be generic, is now hardcoded against search-lm parcels
 */
Ext.define('OpenEMap.action.Identify', {
    extend: 'OpenEMap.action.Action',
    requires: ['OpenEMap.view.IdentifyResults'],
    popup : null,

    getPopup : function(config){
        if (this.popup){
            this.popup.destroy();
        }
        this.popup = Ext.create('GeoExt.window.Popup', {
            title: 'Sökresultat',
            location: config.feature,
            anchored: false,
            unpinnable: false,
            draggable: true,
            map: config.mapPanel,
            maximizable : false,
            minimizable : false,
            resizable: true,
            width: 300,
            height: 400,
            layout: 'fit',
            items: config.items,
            collapsible: false,
            x : 200,
            y: 100,
            listeners : {
                close : function(){
                    config.mapPanel.searchLayer.removeAllFeatures();
                }
            }
        });

        return this.popup;
    },

    constructor: function(config) {
        var self = this;

        var mapPanel = config.mapPanel;
        var layer = mapPanel.searchLayer;
        var map = config.map;
        var layers = config.layers;

        var Click = OpenLayers.Class(OpenLayers.Control, {
            initialize: function(options) {
                OpenLayers.Control.prototype.initialize.apply(
                    this, arguments
                );
                this.handler = new OpenLayers.Handler.Click(
                    this, {
                        'click': this.onClick
                    }, this.handlerOptions
                );
            },
            onClick: function(evt) {
                mapPanel.setLoading(true);
                layer.destroyFeatures();

                var lonlat = map.getLonLatFromPixel(evt.xy);

                var x = lonlat.lon;
                var y = lonlat.lat;

                var point = new OpenLayers.Geometry.Point(x, y);
                var feature = new OpenLayers.Feature.Vector(point);
                layer.addFeatures([feature]);

                var identifyResults = Ext.create('OpenEMap.view.IdentifyResults', {
                    mapPanel : mapPanel
                });

                var popup = self.getPopup({mapPanel : mapPanel, location: feature, items: identifyResults});
                popup.show();

				//TODO - check whether or not to identify parcel
				if map.
                OpenEMap.requestLM({
                    url: 'registerenheter?x=' + x + '&y=' + y,
                    success: function(response) {
                        var registerenhet = Ext.decode(response.responseText);

                        var feature = new OpenLayers.Feature.Vector(point, {
                            name: registerenhet.name
                        });
                        identifyResults.addResult([feature], {name:"Fastigheter"});
                    },
                    failure: function(response) {
                        Ext.Msg.alert('Fel', response.statusText);
                    },
                    callback: function() {
                        mapPanel.setLoading(false);
                    }
                });

                var parser = Ext.create('OpenEMap.config.Parser');

                var wfsLayers =  parser.extractWFS(layers);

                var wfsIdentify = function(wfsLayer) {
                    var options = Ext.apply({
                        version: "1.1.0",
                        srsName: map.projection,
                    }, wfsLayer.wfs);

                    var protocol = new OpenLayers.Protocol.WFS(options);

                    protocol.read({
                        filter: new OpenLayers.Filter({
                            type: OpenLayers.Filter.Spatial.BBOX,
                            value: point.getBounds()
                        }),
                        callback: function(response) {
                            var features = response.features;
                            if (features && features.length>0) {
                                identifyResults.addResult(features, wfsLayer);
                                layer.addFeatures(features);
                            }
                        }
                    });
                };

                wfsLayers.forEach(wfsIdentify);
            }
        });

        config.control = new Click({
            type: OpenLayers.Control.TYPE_TOGGLE
        });

        config.iconCls = config.iconCls || 'action-identify';
        config.tooltip = config.tooltip || 'Identifiera';
        config.toggleGroup = 'extraTools';

        this.callParent(arguments);
    }
});
<|endoftext|>


<commit_before>function ide_actions(tab)
{
    this.actions = new Gtk.ActionGroup({name:"toolbar"});

    this.accels = new Gtk.AccelGroup();
    window.add_accel_group(this.accels);

    this.new_action = new Gtk.Action({name:"new", label:"New",
                                      tooltip:"New File", stock_id:"gtk-new"});
    this.new_action.set_accel_group(this.accels);
    this.actions.add_action_with_accel(this.new_action, "<Control>n");
    this.new_action.connect_accelerator();
    this.new_action.signal_activate.connect(new_file, tab);

    this.open_action = new Gtk.Action({name:"open", label:"Open",
                                      tooltip:"Open File", stock_id:"gtk-open"});
    this.open_action.set_accel_group(this.accels);
    this.actions.add_action_with_accel(this.open_action, "<Control>o");
    this.open_action.connect_accelerator();
    this.open_action.signal_activate.connect(open_file, tab);

    this.save_action = new Gtk.Action({name:"save", label:"Save",
                                      tooltip:"Save File", stock_id:"gtk-save"});
    this.save_action.set_accel_group(this.accels);
    this.actions.add_action_with_accel(this.save_action, "<Control>s");
    this.save_action.connect_accelerator();
    this.save_action.signal_activate.connect(save_file, tab);

    this.undo_action = new Gtk.Action({name:"undo", label:"Undo",
                                      tooltip:"Undo", stock_id:"gtk-undo"});
    this.undo_action.signal_activate.connect(undo, tab);

    this.redo_action = new Gtk.Action({name:"redo", label:"Redo",
                                      tooltip:"Redo", stock_id:"gtk-redo"});
    this.redo_action.signal_activate.connect(redo, tab);

    this.execute_action = new Gtk.Action({name:"execute", label:"Execute",
                                      tooltip:"Execute File", stock_id:"gtk-execute"});
    this.execute_action.set_accel_group(this.accels);
    this.actions.add_action_with_accel(this.execute_action, "<Control>r");
    this.execute_action.connect_accelerator();
    this.execute_action.signal_activate.connect(execute, tab);
}

function new_file(sv)
{
    var tab = new ide_tab("");
}

function open_file(sv)
{
    var file_chooser = new Gtk.FileChooserDialog();
    var file_filter = new Gtk.FileFilter();
    file_filter.add_mime_type("text/javascript");
    file_chooser.set_filter(file_filter);
    file_chooser.add_button("Cancel", Gtk.ResponseType.cancel);
    file_chooser.add_button("Open", Gtk.ResponseType.accept);
    file_chooser.set_action(Gtk.FileChooserAction.open);

    if(file_chooser.run() == Gtk.ResponseType.accept)
    {
        if(this.filename == "")
            this.source_view.source_buf.load_file_data(file_chooser.get_filename(), this);
        else
            var tab = new ide_tab(file_chooser.get_filename());
    }

    file_chooser.destroy();
}

function save_file()
{
    if(this.filename == "")
    {
        var file_chooser = new Gtk.FileChooserDialog();
        var file_filter = new Gtk.FileFilter();
        file_filter.add_mime_type("text/javascript");
        file_chooser.set_filter(file_filter);
        file_chooser.add_button("Cancel", Gtk.ResponseType.cancel);
        file_chooser.add_button("Save", Gtk.ResponseType.accept);
        file_chooser.set_action(Gtk.FileChooserAction.save);

        if(file_chooser.run() == Gtk.ResponseType.accept)
        {
            update_filename(file_chooser.get_filename(), this);
        }

        file_chooser.destroy();
    }

    if(this.filename != "")
        Gio.simple_write(this.filename, this.source_view.source_buf.text);
}

function undo(button)
{
    this.source_view.source_buf.undo();
    this.source_view.source_buf.update_undo_state(this.toolbar);
}

function redo(button)
{
    this.source_view.source_buf.redo();
    this.source_view.source_buf.update_undo_state(this.toolbar);
}

function execute()
{
    if(this.filename == "")
        return; // TODO: something more intelligent!

    Gio.simple_write(this.filename, this.source_view.source_buf.text);

    this.terminal.reset(true, true);
    this.terminal.fork_command("/bin/dash");

    var command = "clear ; /usr/local/bin/seed \"" + this.filename + "\" ; sleep 1d\n";

    this.terminal.feed_child(command, command.length);
}

function ide_toolbar(tab)
{
    actions = new ide_actions(tab);
    this.toolbar = new Gtk.Toolbar();

    this.new_button = actions.new_action.create_tool_item();
    this.open_button = actions.open_action.create_tool_item();
    this.save_button = actions.save_action.create_tool_item();
    this.undo_button = actions.undo_action.create_tool_item();
    this.redo_button = actions.redo_action.create_tool_item();
    this.execute_button = actions.execute_action.create_tool_item();

    this.toolbar.insert(this.new_button, -1);
    this.toolbar.insert(this.open_button, -1);
    this.toolbar.insert(this.save_button, -1);
    this.toolbar.insert(new Gtk.SeparatorToolItem(), -1);
    this.toolbar.insert(this.undo_button, -1);
    this.toolbar.insert(this.redo_button, -1);
    this.toolbar.insert(new Gtk.SeparatorToolItem(), -1);
    this.toolbar.insert(this.execute_button, -1);
}

<commit_msg>Use stock keybindings some place....<commit_after>function ide_actions(tab)
{
    this.actions = new Gtk.ActionGroup({name:"toolbar"});

    this.accels = new Gtk.AccelGroup();
    window.add_accel_group(this.accels);

    this.new_action = new Gtk.Action({name:"new", label:"New",
                                      tooltip:"New File", stock_id:"gtk-new"});
    this.new_action.set_accel_group(this.accels);
    this.actions.add_action_with_accel(this.new_action);
    this.new_action.connect_accelerator();
    this.new_action.signal_activate.connect(new_file, tab);

    this.open_action = new Gtk.Action({name:"open", label:"Open",
                                      tooltip:"Open File", stock_id:"gtk-open"});
    this.open_action.set_accel_group(this.accels);
    this.actions.add_action_with_accel(this.open_action);
    this.open_action.connect_accelerator();
    this.open_action.signal_activate.connect(open_file, tab);

    this.save_action = new Gtk.Action({name:"save", label:"Save",
                                      tooltip:"Save File", stock_id:"gtk-save"});
    this.save_action.set_accel_group(this.accels);
    this.actions.add_action_with_accel(this.save_action);
    this.save_action.connect_accelerator();
    this.save_action.signal_activate.connect(save_file, tab);

    this.undo_action = new Gtk.Action({name:"undo", label:"Undo",
                                      tooltip:"Undo", stock_id:"gtk-undo"});
    this.undo_action.signal_activate.connect(undo, tab);

    this.redo_action = new Gtk.Action({name:"redo", label:"Redo",
                                      tooltip:"Redo", stock_id:"gtk-redo"});
    this.redo_action.signal_activate.connect(redo, tab);

    this.execute_action = new Gtk.Action({name:"execute", label:"Execute",
                                      tooltip:"Execute File", stock_id:"gtk-execute"});
    this.execute_action.set_accel_group(this.accels);
    this.actions.add_action_with_accel(this.execute_action, "<Control>r");
    this.execute_action.connect_accelerator();
    this.execute_action.signal_activate.connect(execute, tab);
}

function new_file(sv)
{
    var tab = new ide_tab("");
}

function open_file(sv)
{
    var file_chooser = new Gtk.FileChooserDialog();
    var file_filter = new Gtk.FileFilter();
    file_filter.add_mime_type("text/javascript");
    file_chooser.set_filter(file_filter);
    file_chooser.add_button("Cancel", Gtk.ResponseType.cancel);
    file_chooser.add_button("Open", Gtk.ResponseType.accept);
    file_chooser.set_action(Gtk.FileChooserAction.open);

    if(file_chooser.run() == Gtk.ResponseType.accept)
    {
        if(this.filename == "")
            this.source_view.source_buf.load_file_data(file_chooser.get_filename(), this);
        else
            var tab = new ide_tab(file_chooser.get_filename());
    }

    file_chooser.destroy();
}

function save_file()
{
    if(this.filename == "")
    {
        var file_chooser = new Gtk.FileChooserDialog();
        var file_filter = new Gtk.FileFilter();
        file_filter.add_mime_type("text/javascript");
        file_chooser.set_filter(file_filter);
        file_chooser.add_button("Cancel", Gtk.ResponseType.cancel);
        file_chooser.add_button("Save", Gtk.ResponseType.accept);
        file_chooser.set_action(Gtk.FileChooserAction.save);

        if(file_chooser.run() == Gtk.ResponseType.accept)
        {
            update_filename(file_chooser.get_filename(), this);
        }

        file_chooser.destroy();
    }

    if(this.filename != "")
        Gio.simple_write(this.filename, this.source_view.source_buf.text);
}

function undo(button)
{
    this.source_view.source_buf.undo();
    this.source_view.source_buf.update_undo_state(this.toolbar);
}

function redo(button)
{
    this.source_view.source_buf.redo();
    this.source_view.source_buf.update_undo_state(this.toolbar);
}

function execute()
{
    if(this.filename == "")
        return; // TODO: something more intelligent!

    Gio.simple_write(this.filename, this.source_view.source_buf.text);

    this.terminal.reset(true, true);
    this.terminal.fork_command("/bin/dash");

    var command = "clear ; /usr/local/bin/seed \"" + this.filename + "\" ; sleep 1d\n";

    this.terminal.feed_child(command, command.length);
}

function ide_toolbar(tab)
{
    actions = new ide_actions(tab);
    this.toolbar = new Gtk.Toolbar();

    this.new_button = actions.new_action.create_tool_item();
    this.open_button = actions.open_action.create_tool_item();
    this.save_button = actions.save_action.create_tool_item();
    this.undo_button = actions.undo_action.create_tool_item();
    this.redo_button = actions.redo_action.create_tool_item();
    this.execute_button = actions.execute_action.create_tool_item();

    this.toolbar.insert(this.new_button, -1);
    this.toolbar.insert(this.open_button, -1);
    this.toolbar.insert(this.save_button, -1);
    this.toolbar.insert(new Gtk.SeparatorToolItem(), -1);
    this.toolbar.insert(this.undo_button, -1);
    this.toolbar.insert(this.redo_button, -1);
    this.toolbar.insert(new Gtk.SeparatorToolItem(), -1);
    this.toolbar.insert(this.execute_button, -1);
}

<|endoftext|>


<commit_before>/*
    Copyright (C) 2014 Härnösands kommun

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
/**
 *
 */
Ext.define('OpenEMap.view.layer.Tree' ,{
    extend: 'Ext.tree.Panel',
    requires: [
        'OpenEMap.data.GroupedLayerTree',
        'GeoExt.tree.Column'
    ],

    rootVisible: false,
    hideHeaders: true,

    initComponent: function() {
        if(!this.store && this.mapPanel) {
            this.store = Ext.create('OpenEMap.data.GroupedLayerTree', {
                root: {
                    text: (this.mapPanel.config && this.mapPanel.config.name ? this.mapPanel.config.name : 'Lager'),
                    expanded: true,
                    isGroupLayer: true,
                    layers: this.mapPanel.map.layerSwitcherLayerTree
                },
                map: this.mapPanel.map
            });
        }

        this.on('checkchange', function(node, checked, eOpts) {
            var parent = node.parentNode;

            // Loop this node and children
            node.cascadeBy(function(n){
                n.set('checked', checked);
                var olLayerRef = n.get('layer');
                // Change layer visibility (Layer groups have no layer reference)
                if(olLayerRef) {
                    olLayerRef.setVisibility(checked);
                }

           });
            // Checking/unchecking parent node
            if (checked) {
                // check parent if not root
                if (!parent.isRoot()) {
                    parent.set('checked', checked);
                }
            } else {
                if (!parent.isRoot() && !parent.childNodes.some(function(node) { return node.get('checked'); })) {
                    parent.set('checked', checked);
                }
            }

        });

        this.on('cellclick', function(tree, td, cellIndex, node) {
            // Add legend if node have a wms legend and the node isnt removed
            if((node.gx_wmslegend || node.gx_urllegend) && node.store) {
                var legend = node.gx_wmslegend || node.gx_urllegend;
                if (legend.isHidden()) {
                    if (!legend.rendered) {
                        legend.render(td);
                    }
                    legend.show();
                } else {
                    legend.hide();
                }
            }
        });

        this.callParent(arguments);
    },

    getConfig: function(includeLayerRef) {
    	// Start with initial config to get a complete config object
        var config = Ext.clone(this.client.initialConfig);

        // Get layers config from layer tree, to reflect changes made by user
       	var layers = this.getStore().getLayerConfiguration(includeLayerRef);

        // layer tree does not include base layers so extract them from initial config
    	var baseLayers = config.layers.filter(function(layer) {
    		return (layer.wms && layer.wms.options.isBaseLayer) ? layer : false;
    	});
    	config.layers = baseLayers.concat(layers);

    	return config;
    }
});
<commit_msg>Check visibility fix<commit_after>/*
    Copyright (C) 2014 Härnösands kommun

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
/**
 *
 */
Ext.define('OpenEMap.view.layer.Tree' ,{
    extend: 'Ext.tree.Panel',
    requires: [
        'OpenEMap.data.GroupedLayerTree',
        'GeoExt.tree.Column'
    ],

    rootVisible: false,
    hideHeaders: true,

    initComponent: function() {
        if(!this.store && this.mapPanel) {
            this.store = Ext.create('OpenEMap.data.GroupedLayerTree', {
                root: {
                    text: (this.mapPanel.config && this.mapPanel.config.name ? this.mapPanel.config.name : 'Lager'),
                    expanded: true,
                    isGroupLayer: true,
                    layers: this.mapPanel.map.layerSwitcherLayerTree
                },
                map: this.mapPanel.map
            });
        }

        this.on('checkchange', function(node, checked, eOpts) {
            var parent = node.parentNode;

            // Loop this node and children
            node.cascadeBy(function(n){
                n.set('checked', checked);
                var olLayerRef = n.get('layer');
                // Change layer visibility (Layer groups have no layer reference)
                if(olLayerRef) {
                    olLayerRef.setVisibility(checked);
                    if (olLayerRef.options && olLayerRef.options.visibility) {
                    	olLayerRef.options.visibility = checked;
                    }
                }

           });
            // Checking/unchecking parent node
            if (checked) {
                // check parent if not root
                if (!parent.isRoot()) {
                    parent.set('checked', checked);
                }
            } else {
                if (!parent.isRoot() && !parent.childNodes.some(function(node) { return node.get('checked'); })) {
                    parent.set('checked', checked);
                }
            }

        });

        this.on('cellclick', function(tree, td, cellIndex, node) {
            // Add legend if node have a wms legend and the node isnt removed
            if((node.gx_wmslegend || node.gx_urllegend) && node.store) {
                var legend = node.gx_wmslegend || node.gx_urllegend;
                if (legend.isHidden()) {
                    if (!legend.rendered) {
                        legend.render(td);
                    }
                    legend.show();
                } else {
                    legend.hide();
                }
            }
        });

        this.callParent(arguments);
    },

    getConfig: function(includeLayerRef) {
    	// Start with initial config to get a complete config object
        var config = Ext.clone(this.client.initialConfig);

        // Get layers config from layer tree, to reflect changes made by user
       	var layers = this.getStore().getLayerConfiguration(includeLayerRef);

        // layer tree does not include base layers so extract them from initial config
    	var baseLayers = config.layers.filter(function(layer) {
    		return (layer.wms && layer.wms.options.isBaseLayer) ? layer : false;
    	});
    	config.layers = baseLayers.concat(layers);

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


<commit_before>// create an empty modbus client
//var ModbusRTU = require("modbus-serial");
var ModbusRTU = require("../index");
var client = new ModbusRTU();

// open connection to a C701 UDP-to-Serial bridge
client.connectC701("2.55.72.186", {"port": 28674}, run);
client.setID(1);

setInterval(run, 1000);

// read the values of 6 registers (12 bytes) starting at address 2
// on device number 1.and log the buffer as floats (4 bytes each)
// to the console.
function run() {
    client.readInputRegisters(2, 6)
        .then(printFloats)
        .catch(console.log);
}

// print out the buffer as floats
function printFloats(data) {
    var ans = [];

    // get data as 4 byte floats from the raw buffer data
    for (var i = 0; i < data.buffer.length; i += 4) {
        ans.push(data.buffer.readFloatBE(i));
    }

    // print the floats
    console.log(ans);
}
<commit_msg>move api and ports to different dirs<commit_after>// create an empty modbus client
//var ModbusRTU = require("modbus-serial");
var ModbusRTU = require("../index");
var client = new ModbusRTU();

// open connection to a C701 UDP-to-Serial bridge
client.connectC701("72.155.72.186", {"port": 28674}, run);
client.setID(1);

setInterval(run, 1000);

// read the values of 6 registers (12 bytes) starting at address 2
// on device number 1.and log the buffer as floats (4 bytes each)
// to the console.
function run() {
    client.readInputRegisters(2, 6)
        .then(printFloats)
        .catch(console.log);
}

// print out the buffer as floats
function printFloats(data) {
    var ans = [];

    // get data as 4 byte floats from the raw buffer data
    for (var i = 0; i < data.buffer.length; i += 4) {
        ans.push(data.buffer.readFloatBE(i));
    }

    // print the floats
    console.log(ans);
}
<|endoftext|>


<commit_before>/**
 * @fileoverview Description of file, its uses and information
 * about its dependencies.
 */

'use strict';

var urlparser = require('./urlparser');
var urlVars = urlparser.urlVars;
var db = urlparser.db;
var schema = urlparser.schema;
var cloud;
var layers;

/**
 * @private
 * @returns {string}
 */
var anchor = function (s) {
    var layerStr, newArr = [], p;

    if (layers.getLayers() && s) {
        let arr = layers.getLayers().split(",");
        $.each(arr, function (i, v) {
            newArr.push(s + "." + v.split(".")[1])
        });
        layerStr = newArr.reverse().join(",");
    } else {
        layerStr = (layers.getLayers()) ? layers.getLayers().split(",").reverse().join(",") : ""
    }

    p = geocloud.transformPoint(cloud.get().getCenter().x, cloud.get().getCenter().y, "EPSG:900913", "EPSG:4326");
    return "#" + cloud.get().getBaseLayerName() + "/" + Math.round(cloud.get().getZoom()).toString() + "/" + (Math.round(p.x * 10000) / 10000).toString() + "/" + (Math.round(p.y * 10000) / 10000).toString() + "/" + layerStr;
};
/**
 *
 * @type {{set: module.exports.set, init: module.exports.init, getAnchor: module.exports.getAnchor}}
 */
module.exports = {
    set: function (o) {
        cloud = o.cloud;
        layers = o.layers;
        return this;
    },
    init: function () {
        var param = [], paramStr, parr;
        $.each(urlVars, function (i, v) {
            parr = v.split("#");
            if (parr.length > 1) {
                parr.pop();
            }
            param.push(i + "=" + parr.join());
        });
        paramStr = param.join("&");
        return "/app/" + db + "/" + (schema !== "" ? schema + "/" : "") + ((paramStr === "") ? "" : "?" + paramStr) + anchor();
    },

    /**
     * Get the URL anchor for current state
     * @returns {string}
     */
    getUri: function (s) {
        schema = s || schema;
        return "/app/" + db + "/" + (schema !== "" ? schema + "/" : "");
    },

    getParam: function () {
        var param = [], paramStr, parr;
        $.each(urlVars, function (i, v) {
            parr = v.split("#");
            if (parr.length > 1) {
                parr.pop();
            }
            param.push(i + "=" + parr.join());
        });
        paramStr = param.join("&");
        return paramStr;
    },

    /**
     * Get the URL anchor for current state
     * @returns {string}
     */
    getAnchor: function (s) {
        return anchor(s);
    }
};<commit_msg>Anchor is not set on load, but whenever method is called<commit_after>/**
 * @fileoverview Description of file, its uses and information
 * about its dependencies.
 */

'use strict';

var urlparser = require('./urlparser');
var db = urlparser.db;
var schema = urlparser.schema;
var cloud;
var layers;

/**
 * @private
 * @returns {string}
 */
var anchor = function (s) {
    var layerStr, newArr = [], p;

    if (layers.getLayers() && s) {
        let arr = layers.getLayers().split(",");
        $.each(arr, function (i, v) {
            newArr.push(s + "." + v.split(".")[1])
        });
        layerStr = newArr.reverse().join(",");
    } else {
        layerStr = (layers.getLayers()) ? layers.getLayers().split(",").reverse().join(",") : ""
    }

    p = geocloud.transformPoint(cloud.get().getCenter().x, cloud.get().getCenter().y, "EPSG:900913", "EPSG:4326");
    return "#" + cloud.get().getBaseLayerName() + "/" + Math.round(cloud.get().getZoom()).toString() + "/" + (Math.round(p.x * 10000) / 10000).toString() + "/" + (Math.round(p.y * 10000) / 10000).toString() + "/" + layerStr;
};
/**
 *
 * @type {{set: module.exports.set, init: module.exports.init, getAnchor: module.exports.getAnchor}}
 */
module.exports = {
    set: function (o) {
        cloud = o.cloud;
        layers = o.layers;
        return this;
    },
    init: function () {
        var param = [], paramStr, parr;

        $.each(this.urlVars(), function (i, v) {
            parr = v.split("#");
            if (parr.length > 1) {
                parr.pop();
            }
            param.push(i + "=" + parr.join());
        });
        paramStr = param.join("&");
        return "/app/" + db + "/" + (schema !== "" ? schema + "/" : "") + ((paramStr === "") ? "" : "?" + paramStr) + anchor();
    },

    urlVars: function getUrlVars() {
        var mapvars = {};
        var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {
            mapvars[key] = value;
        });
        return mapvars;
    },

    /**
     * Get the URL anchor for current state
     * @returns {string}
     */
    getUri: function (s) {
        schema = s || schema;
        return "/app/" + db + "/" + (schema !== "" ? schema + "/" : "");
    },

    getParam: function () {
        var param = [], paramStr, parr;
        $.each(this.urlVars(), function (i, v) {
            parr = v.split("#");
            if (parr.length > 1) {
                parr.pop();
            }
            param.push(i + "=" + parr.join());
        });
        paramStr = param.join("&");
        return paramStr;
    },

    /**
     * Get the URL anchor for current state
     * @returns {string}
     */
    getAnchor: function (s) {
        return anchor(s);
    }
};<|endoftext|>


<commit_before>/*
 * NAME: nodejs-demo.js
 * AUTH: Brent Ely (https://github.com/gitbrent/)
 * DATE: Jul 17, 2017
 * DESC: Demonstrate PptxGenJS on Node.js
 * REQS: npm 4.x + `npm install pptxgenjs`
 * EXEC: `node nodejs-demo.js`
 */

// ============================================================================
const express = require('express'); // Not core - Only required for streaming
const app = express(); // Not core - Only required for streaming
var fs = require('fs');

var GIF_ANIM_FIRE = "";
var AUDIO_MP3 = "";
var VIDEO_MP4 = "";
var gConsoleLog = true;

function getTimestamp() {
	var dateNow = new Date();
	var dateMM = dateNow.getMonth() + 1; dateDD = dateNow.getDate(); dateYY = dateNow.getFullYear(), h = dateNow.getHours(); m = dateNow.getMinutes();
	return dateNow.getFullYear() +''+ (dateMM<=9 ? '0' + dateMM : dateMM) +''+ (dateDD<=9 ? '0' + dateDD : dateDD) + (h<=9 ? '0' + h : h) + (m<=9 ? '0' + m : m);
}
// ============================================================================

if (gConsoleLog) console.log(`
-------------
STARTING TEST
-------------`);

// STEP 1: Load pptxgenjs and show version to verify everything loaded correctly
var pptx;
if (fs.existsSync('../dist/pptxgen.js')) {
	pptx = require('../dist/pptxgen.js'); // for LOCAL TESTING
}
else {
	pptx = require("pptxgenjs");
}
var runEveryTest = require("../examples/pptxgenjs-demo.js");
if (gConsoleLog) console.log(` * pptxgenjs version: ${pptx.getVersion()}`); // Loaded okay?

// ============================================================================

// EX: Regular callback - will be sent the export filename once the file has been written to fs
function saveCallback(filename) {
	if (gConsoleLog) console.log('Good News Everyone!  File created: '+ filename);
}

// EX: JSZip callback - take the specified output (`data`) and do whatever
function jszipCallback(data) {
	if (gConsoleLog) {
		console.log('Done!');
		console.log('First 100 chars of output:\n');
		console.log( data.substring(0,100) );
	}
}

// EX: Callback that receives the PPT binary data - use this to stream file
function streamCallback(data) {
	var strFilename = "Node-Presenation-Streamed.pptx";

	app.get('/', function(req, res) {
		res.writeHead(200, { 'Content-disposition':'attachment;filename='+strFilename, 'Content-Length':data.length });
		res.end(new Buffer(data, 'binary'));
	});

	app.listen(3000, function() {
		console.log('PptxGenJS Node Demo app listening on port 3000!');
		console.log('Visit: http://localhost:3000/');
		console.log('(press Ctrl-C to quit app)');
	});
}

// ============================================================================

// STEP 2: Run all test funcs
runEveryTest();

// STEP 3: Export giant demo file

// A: Inline save
//pptx.save( 'Node_Demo_NoCallback'+getTimestamp() );

// B: or Save using callback function
//pptx.save( 'Node_Demo_'+getTimestamp(), function(filename){ console.log('Created: '+filename); } );

// C: or use a predefined callback function
pptx.save( 'Node_Demo_Callback_'+getTimestamp(), saveCallback );

// D: or use callback with 'http' in filename to get content back instead of writing a file - use this for streaming
//pptx.save( 'https://github.com/gitbrent/PptxGenJS/', streamCallback );

// E: or save using various JSZip formats ['arraybuffer', 'base64', 'binarystring', 'blob', 'nodebuffer', 'uint8array']
//pptx.save( 'jszip', jszipCallback, 'base64' );

// **NOTE** If you continue to use the `pptx` variable, new Slides will be added to the existing set
// Create a new variable or reset `pptx` for an empty Presenation
// EX: pptx = require("pptxgenjs");

// ============================================================================

if (gConsoleLog) console.log(`
--------------
TEST COMPLETE!
--------------
 * Files saved to...: ${__dirname}
`);
<commit_msg>Verbiage update<commit_after>/*
 * NAME: nodejs-demo.js
 * AUTH: Brent Ely (https://github.com/gitbrent/)
 * DATE: Jul 17, 2017
 * DESC: Demonstrate PptxGenJS on Node.js
 * REQS: npm 4.x + `npm install pptxgenjs`
 * EXEC: `node nodejs-demo.js`
 */

// ============================================================================
const express = require('express'); // Not core - Only required for streaming
const app = express(); // Not core - Only required for streaming
var fs = require('fs');

var GIF_ANIM_FIRE = "";
var AUDIO_MP3 = "";
var VIDEO_MP4 = "";
var gConsoleLog = true;

function getTimestamp() {
	var dateNow = new Date();
	var dateMM = dateNow.getMonth() + 1; dateDD = dateNow.getDate(); dateYY = dateNow.getFullYear(), h = dateNow.getHours(); m = dateNow.getMinutes();
	return dateNow.getFullYear() +''+ (dateMM<=9 ? '0' + dateMM : dateMM) +''+ (dateDD<=9 ? '0' + dateDD : dateDD) + (h<=9 ? '0' + h : h) + (m<=9 ? '0' + m : m);
}
// ============================================================================

if (gConsoleLog) console.log(`
-------------
STARTING DEMO
-------------`);

// STEP 1: Load pptxgenjs and show version to verify everything loaded correctly
var pptx;
if (fs.existsSync('../dist/pptxgen.js')) {
	pptx = require('../dist/pptxgen.js'); // for LOCAL TESTING
}
else {
	pptx = require("pptxgenjs");
}
var runEveryTest = require("../examples/pptxgenjs-demo.js");
if (gConsoleLog) console.log(` * pptxgenjs version: ${pptx.getVersion()}`); // Loaded okay?

// ============================================================================

// EX: Regular callback - will be sent the export filename once the file has been written to fs
function saveCallback(filename) {
	if (gConsoleLog) console.log('Good News Everyone!  File created: '+ filename);
}

// EX: JSZip callback - take the specified output (`data`) and do whatever
function jszipCallback(data) {
	if (gConsoleLog) {
		console.log('Done!');
		console.log('First 100 chars of output:\n');
		console.log( data.substring(0,100) );
	}
}

// EX: Callback that receives the PPT binary data - use this to stream file
function streamCallback(data) {
	var strFilename = "Node-Presenation-Streamed.pptx";

	app.get('/', function(req, res) {
		res.writeHead(200, { 'Content-disposition':'attachment;filename='+strFilename, 'Content-Length':data.length });
		res.end(new Buffer(data, 'binary'));
	});

	app.listen(3000, function() {
		console.log('PptxGenJS Node Demo app listening on port 3000!');
		console.log('Visit: http://localhost:3000/');
		console.log('(press Ctrl-C to quit app)');
	});
}

// ============================================================================

// STEP 2: Run all test funcs
runEveryTest();

// STEP 3: Export giant demo file

// A: Inline save
//pptx.save( 'Node_Demo_NoCallback'+getTimestamp() );

// B: or Save using callback function
//pptx.save( 'Node_Demo_'+getTimestamp(), function(filename){ console.log('Created: '+filename); } );

// C: or use a predefined callback function
pptx.save( 'Node_Demo_Callback_'+getTimestamp(), saveCallback );

// D: or use callback with 'http' in filename to get content back instead of writing a file - use this for streaming
//pptx.save( 'https://github.com/gitbrent/PptxGenJS/', streamCallback );

// E: or save using various JSZip formats ['arraybuffer', 'base64', 'binarystring', 'blob', 'nodebuffer', 'uint8array']
//pptx.save( 'jszip', jszipCallback, 'base64' );

// **NOTE** If you continue to use the `pptx` variable, new Slides will be added to the existing set
// Create a new variable or reset `pptx` for an empty Presenation
// EX: pptx = require("pptxgenjs");

// ============================================================================

if (gConsoleLog) console.log(`
--------------
TEST COMPLETE!
--------------
 * Files saved to...: ${__dirname}
`);
<|endoftext|>


<commit_before>/**
 * @fileoverview Description of file, its uses and information
 * about its dependencies.
 */

'use strict';

/**
 *
 * @type {*|exports|module.exports}
 */
var urlparser = require('./urlparser');

/**
 * @type {string}
 */
var db = urlparser.db;

/**
 * @type {Object}
 */
var cloud;

/**
 *
 * @type {boolean}
 */
var ready = false;

/**
 *
 * @type {boolean}
 */
var cartoDbLayersready = false;

/**
 *
 * @type {string}
 */
var BACKEND = require('../../config/config.js').backend;

/**
 * @type {string}
 */
var host;

/**
 *
 */
var meta;

/**
 *
 */
var backboneEvents;

var mustache = require('mustache');

var host = require("./connection").getHost();

var switchLayer;

var singleTiled = [];

var array =[];

/**
 *
 * @type {{set: module.exports.set, init: module.exports.init, getMetaDataKeys: module.exports.getMetaDataKeys, ready: module.exports.ready}}
 */
module.exports = {
    /**
     *
     * @param o
     * @returns {exports}
     */
    set: function (o) {
        cloud = o.cloud;
        meta = o.meta;
        backboneEvents = o.backboneEvents;
        switchLayer = o.switchLayer;
        return this;
    },

    /**
     *
     */
    init: function () {

    },

    ready: function () {
        // If CartoDB, we wait for cartodb.createLayer to finish
        if (BACKEND === "cartodb") {
            return (ready && cartoDbLayersready);
        }
        // GC2 layers are direct tile request
        else {
            return ready;
        }
    },

    getLayers: function (separator, includeHidden) {
        var layerArr = [];
        var layers = cloud.get().map._layers;
        for (var key in layers) {
            if (layers.hasOwnProperty(key)) {
                if (layers[key].baseLayer !== true && typeof layers[key]._tiles === "object") {
                    if (typeof layers[key].id === "undefined" || (typeof layers[key].id !== "undefined" && (layers[key].id.split(".")[0] !== "__hidden") || includeHidden === true)) {
                        layerArr.push(layers[key].id);
                    }
                }
            }
        }
        if (layerArr.length > 0) {
            return layerArr.join(separator ? separator : ",");
        }
        else {
            return false;
        }
    },

    removeHidden: function () {
        var layers = cloud.get().map._layers;
        for (var key in layers) {
            if (layers.hasOwnProperty(key)) {
                if (typeof layers[key].id !== "undefined" && layers[key].id.split(".")[0] === "__hidden") {
                    cloud.get().map.removeLayer(layers[key]);
                }
            }
        }
    },
    resetCount: function (i) {
        ready = cartoDbLayersready = false;
    },

    incrementCountLoading: function (i) {
        if (array.indexOf(i) === -1) {
            array.push(i)
        }
        return array.length;
    },

    decrementCountLoading: function (i) {
        array.splice(array.indexOf(i), 1);
        return array.length;
    },

    getCountLoading: function() {
      return  array.length;
    },

    getArray: function() {
      return  array;
    },

    /**
     *
     * @param l
     * @returns {Promise}
     */
    addLayer: function (l) {
        var me = this;

        if (typeof window.vidiConfig.singleTiled === "object" && window.vidiConfig.singleTiled.length > 0) {
            singleTiled = window.vidiConfig.singleTiled
        }

        return new Promise(function (resolve, reject) {

            var isBaseLayer, layers = [], metaData = meta.getMetaData();

            $.each(metaData.data, function (i, v) {

                var layer = v.f_table_schema + "." + v.f_table_name;

                if (layer === l) {

                    switch (BACKEND) {

                        case "gc2":

                            isBaseLayer = v.baselayer ? true : false;

                            layers[[layer]] = cloud.get().addTileLayers({
                                host: host,
                                layers: [layer],
                                db: db,
                                isBaseLayer: isBaseLayer,
                                tileCached: singleTiled.indexOf(layer) === -1,
                                visibility: false,
                                wrapDateLine: false,
                                displayInLayerSwitcher: true,
                                name: v.f_table_name,
                                // Single tile option
                                type: singleTiled.indexOf(layer) === -1 ? "tms" : "wms",
                                tileSize: singleTiled.indexOf(layer) === -1 ? 256 : 9999,
                                format: "image/png",
                                loadEvent: function () {
                                    me.decrementCountLoading(layer);
                                    backboneEvents.get().trigger("doneLoading:layers", layer);
                                },
                                loadingEvent: function () {
                                    me.incrementCountLoading(layer);
                                    backboneEvents.get().trigger("startLoading:layers", layer);
                                },
                                subdomains: window.gc2Options.subDomainsForTiles
                            });

                            layers[[layer]][0].setZIndex(v.sort_id + 10000);

                            resolve();

                            break;

                        case "cartodb":

                            var tooltipHtml;

                            var fieldconf = JSON.parse(v.fieldconf), interactivity = ["cartodb_id"], template;

                            template = (typeof v.tooltip !== "undefined" && v.tooltip.template !== "" ) ? v.tooltip.template : null;

                            $.each(fieldconf, function (name, property) {
                                if (typeof property.utfgrid !== "undefined" && property.utfgrid === true) {
                                    interactivity.push(name)
                                }
                            });

                            cartodb.createLayer(cloud.get().map, {
                                user_name: db,
                                type: 'cartodb',
                                sublayers: [{
                                    sql: v.sql,
                                    cartocss: v.cartocss,
                                    interactivity: interactivity.join(",")
                                }]
                            })
                                .on('done', function (cartoLayer) {

                                    cartoLayer.baseLayer = false;
                                    cartoLayer.id = v.f_table_schema + "." + v.f_table_name;
                                    cartoLayer.on("load", function () {
                                        me.decrementCountLoading(cartoLayer.id);
                                        backboneEvents.get().trigger("doneLoading:layers", cartoLayer.id);
                                    });
                                    cartoLayer.on("loading", function () {
                                        me.incrementCountLoading(cartoLayer.id);
                                        backboneEvents.get().trigger("startLoading:layers", cartoLayer.id);
                                    });
                                    cloud.get().addLayer(cartoLayer, v.f_table_name);

                                    // We switch the layer on/off, so they become ready for state.
                                    cloud.get().showLayer(cartoLayer.id);
                                    cloud.get().hideLayer(cartoLayer.id);

                                    // Carto layer object is not complete(!?), so we poll until _url prop is set
                                    if (interactivity.length > 0) {
                                        (function poll1() {
                                            if (typeof cartoLayer._url !== "undefined") {

                                                // A bit hackery way to set UTFgrid url
                                                var utfGrid = new L.UtfGrid(cartoLayer._url.replace(".png", "") + '.grid.json?callback={cb}&interactivity=name'), flag = false;
                                                utfGrid.id = cartoLayer.id + "_vidi_utfgrid";
                                                cloud.get().addLayer(utfGrid);
                                                utfGrid.on('mouseover', _.debounce(function (e) {
                                                    var tmp = $.extend(true, {}, e.data), fi = [];
                                                    flag = true;
                                                    $.each(tmp, function (name, property) {
                                                        if (name !== "cartodb_id") {
                                                            fi.push({
                                                                title: fieldconf[name].alias_tooltip || name,
                                                                value: property
                                                            });
                                                        }
                                                    });
                                                    tmp.fields = fi; // Used in a "loop" template
                                                    tooltipHtml = Mustache.render(template, tmp);
                                                    if (fi.length > 0) {
                                                        $("#tail").fadeIn(100);
                                                        $("#tail").html(tooltipHtml);
                                                    }

                                                }, 0));
                                                utfGrid.on('mouseout', function (e) {
                                                    flag = false;
                                                    // Wait 200 ms before closing tooltip, so its not blinking between close features
                                                    setTimeout(function () {
                                                        if (!flag) {
                                                            $("#tail").fadeOut(100);
                                                        }
                                                    }, 200)

                                                });
                                                cartoDbLayersready = true;
                                                backboneEvents.get().trigger("ready:layers");
                                                resolve();
                                            } else {
                                                setTimeout(function () {
                                                    poll1()
                                                }, 50);
                                            }
                                        }());
                                    } else {
                                        resolve();
                                    }

                                });
                            break;
                    }
                }
            });

            console.info(l + " added to the map.");
        })
    }
};<commit_msg>Print stuff<commit_after>/**
 * @fileoverview Description of file, its uses and information
 * about its dependencies.
 */

'use strict';

/**
 *
 * @type {*|exports|module.exports}
 */
var urlparser = require('./urlparser');

/**
 * @type {string}
 */
var db = urlparser.db;

/**
 * @type {Object}
 */
var cloud;

/**
 *
 * @type {boolean}
 */
var ready = false;

/**
 *
 * @type {boolean}
 */
var cartoDbLayersready = false;

/**
 *
 * @type {string}
 */
var BACKEND = require('../../config/config.js').backend;

/**
 *
 */
var meta;

/**
 *
 */
var backboneEvents;

var mustache = require('mustache');

var host = require("./connection").getHost();

var switchLayer;

var singleTiled = [];

var array =[];

/**
 *
 * @type {{set: module.exports.set, init: module.exports.init, getMetaDataKeys: module.exports.getMetaDataKeys, ready: module.exports.ready}}
 */
module.exports = {
    /**
     *
     * @param o
     * @returns {exports}
     */
    set: function (o) {
        cloud = o.cloud;
        meta = o.meta;
        backboneEvents = o.backboneEvents;
        switchLayer = o.switchLayer;
        return this;
    },

    /**
     *
     */
    init: function () {

    },

    ready: function () {
        // If CartoDB, we wait for cartodb.createLayer to finish
        if (BACKEND === "cartodb") {
            return (ready && cartoDbLayersready);
        }
        // GC2 layers are direct tile request
        else {
            return ready;
        }
    },

    getLayers: function (separator, includeHidden) {
        var layerArr = [];
        var layers = cloud.get().map._layers;
        for (var key in layers) {
            if (layers.hasOwnProperty(key)) {
                if (layers[key].baseLayer !== true && typeof layers[key]._tiles === "object") {
                    if (typeof layers[key].id === "undefined" || (typeof layers[key].id !== "undefined" && (layers[key].id.split(".")[0] !== "__hidden") || includeHidden === true)) {
                        layerArr.push(layers[key].id);
                    }
                }
            }
        }
        if (layerArr.length > 0) {
            return layerArr.join(separator ? separator : ",");
        }
        else {
            return false;
        }
    },

    removeHidden: function () {
        var layers = cloud.get().map._layers;
        for (var key in layers) {
            if (layers.hasOwnProperty(key)) {
                if (typeof layers[key].id !== "undefined" && layers[key].id.split(".")[0] === "__hidden") {
                    cloud.get().map.removeLayer(layers[key]);
                }
            }
        }
    },
    resetCount: function (i) {
        ready = cartoDbLayersready = false;
    },

    incrementCountLoading: function (i) {
        if (array.indexOf(i) === -1) {
            array.push(i)
        }
        return array.length;
    },

    decrementCountLoading: function (i) {
        array.splice(array.indexOf(i), 1);
        return array.length;
    },

    getCountLoading: function() {
      return  array.length;
    },

    getArray: function() {
      return  array;
    },

    /**
     *
     * @param l
     * @returns {Promise}
     */
    addLayer: function (l) {
        var me = this;

        if (typeof window.vidiConfig.singleTiled === "object" && window.vidiConfig.singleTiled.length > 0) {
            singleTiled = window.vidiConfig.singleTiled
        }

        return new Promise(function (resolve, reject) {

            var isBaseLayer, layers = [], metaData = meta.getMetaData();

            $.each(metaData.data, function (i, v) {

                var layer = v.f_table_schema + "." + v.f_table_name;

                if (layer === l) {

                    switch (BACKEND) {

                        case "gc2":

                            isBaseLayer = v.baselayer ? true : false;

                            layers[[layer]] = cloud.get().addTileLayers({
                                host: host,
                                layers: [layer],
                                db: db,
                                isBaseLayer: isBaseLayer,
                                tileCached: singleTiled.indexOf(layer) === -1,
                                visibility: false,
                                wrapDateLine: false,
                                displayInLayerSwitcher: true,
                                name: v.f_table_name,
                                // Single tile option
                                type: singleTiled.indexOf(layer) === -1 ? "tms" : "wms",
                                tileSize: singleTiled.indexOf(layer) === -1 ? 256 : 9999,
                                format: "image/png",
                                loadEvent: function () {
                                    me.decrementCountLoading(layer);
                                    backboneEvents.get().trigger("doneLoading:layers", layer);
                                },
                                loadingEvent: function () {
                                    me.incrementCountLoading(layer);
                                    backboneEvents.get().trigger("startLoading:layers", layer);
                                },
                                subdomains: window.gc2Options.subDomainsForTiles
                            });

                            layers[[layer]][0].setZIndex(v.sort_id + 10000);

                            resolve();

                            break;

                        case "cartodb":

                            var tooltipHtml;

                            var fieldconf = JSON.parse(v.fieldconf), interactivity = ["cartodb_id"], template;

                            template = (typeof v.tooltip !== "undefined" && v.tooltip.template !== "" ) ? v.tooltip.template : null;

                            $.each(fieldconf, function (name, property) {
                                if (typeof property.utfgrid !== "undefined" && property.utfgrid === true) {
                                    interactivity.push(name)
                                }
                            });

                            cartodb.createLayer(cloud.get().map, {
                                user_name: db,
                                type: 'cartodb',
                                sublayers: [{
                                    sql: v.sql,
                                    cartocss: v.cartocss,
                                    interactivity: interactivity.join(",")
                                }]
                            })
                                .on('done', function (cartoLayer) {

                                    cartoLayer.baseLayer = false;
                                    cartoLayer.id = v.f_table_schema + "." + v.f_table_name;
                                    cartoLayer.on("load", function () {
                                        me.decrementCountLoading(cartoLayer.id);
                                        backboneEvents.get().trigger("doneLoading:layers", cartoLayer.id);
                                    });
                                    cartoLayer.on("loading", function () {
                                        me.incrementCountLoading(cartoLayer.id);
                                        backboneEvents.get().trigger("startLoading:layers", cartoLayer.id);
                                    });
                                    cloud.get().addLayer(cartoLayer, v.f_table_name);

                                    // We switch the layer on/off, so they become ready for state.
                                    cloud.get().showLayer(cartoLayer.id);
                                    cloud.get().hideLayer(cartoLayer.id);

                                    // Carto layer object is not complete(!?), so we poll until _url prop is set
                                    if (interactivity.length > 0) {
                                        (function poll1() {
                                            if (typeof cartoLayer._url !== "undefined") {

                                                // A bit hackery way to set UTFgrid url
                                                var utfGrid = new L.UtfGrid(cartoLayer._url.replace(".png", "") + '.grid.json?callback={cb}&interactivity=name'), flag = false;
                                                utfGrid.id = cartoLayer.id + "_vidi_utfgrid";
                                                cloud.get().addLayer(utfGrid);
                                                utfGrid.on('mouseover', _.debounce(function (e) {
                                                    var tmp = $.extend(true, {}, e.data), fi = [];
                                                    flag = true;
                                                    $.each(tmp, function (name, property) {
                                                        if (name !== "cartodb_id") {
                                                            fi.push({
                                                                title: fieldconf[name].alias_tooltip || name,
                                                                value: property
                                                            });
                                                        }
                                                    });
                                                    tmp.fields = fi; // Used in a "loop" template
                                                    tooltipHtml = Mustache.render(template, tmp);
                                                    if (fi.length > 0) {
                                                        $("#tail").fadeIn(100);
                                                        $("#tail").html(tooltipHtml);
                                                    }

                                                }, 0));
                                                utfGrid.on('mouseout', function (e) {
                                                    flag = false;
                                                    // Wait 200 ms before closing tooltip, so its not blinking between close features
                                                    setTimeout(function () {
                                                        if (!flag) {
                                                            $("#tail").fadeOut(100);
                                                        }
                                                    }, 200)

                                                });
                                                cartoDbLayersready = true;
                                                backboneEvents.get().trigger("ready:layers");
                                                resolve();
                                            } else {
                                                setTimeout(function () {
                                                    poll1()
                                                }, 50);
                                            }
                                        }());
                                    } else {
                                        resolve();
                                    }

                                });
                            break;
                    }
                }
            });

            console.info(l + " added to the map.");
        })
    }
};<|endoftext|>


<commit_before>/**
 * @author daniel.joppi
 * @since 2/12/14.
 */
module.exports = function(mongoose) {
    var Schema = mongoose.Schema;

    // list models
//    require('./company-model.js')(mongoose, Schema);
//    require('./image-model.js')(mongoose, Schema);
//    require('./location-model.js')(mongoose, Schema);
//    require('./user-model.js')(mongoose, Schema);

    mongoose.model('company', new Schema({}), { strict: false });
    mongoose.model('image', new Schema({}), { strict: false });
    mongoose.model('location', new Schema({}), { strict: false });
    mongoose.model('user', new Schema({}), { strict: false });
};<commit_msg>change models<commit_after>/**
 * @author daniel.joppi
 * @since 2/12/14.
 */
module.exports = function(mongoose) {
    var Schema = mongoose.Schema;

    // list models
    require('./company-model.js')(mongoose, Schema);
    require('./image-model.js')(mongoose, Schema);
    require('./location-model.js')(mongoose, Schema);
    require('./user-model.js')(mongoose, Schema);

//    mongoose.model('company', new Schema({}), { strict: false });
//    mongoose.model('image', new Schema({}), { strict: false });
//    mongoose.model('location', new Schema({}), { strict: false });
//    mongoose.model('user', new Schema({}), { strict: false });
};<|endoftext|>


<commit_before>/*eslint-disable no-console*/

import * as actions from '../src/monitorActions'
import { as } from '../src/io'
import { is } from '../src/utils'

const PENDING = 'PENDING'
const RESOLVED = 'RESOLVED'
const REJECTED = 'REJECTED'

export const LOG_EFFECT = 'LOG_EFFECT'
export const logEffect = (effectId = 0) => ({type: LOG_EFFECT, effectId})

const DEFAULT_STYLE = 'color: black'
const LABEL_STYLE = 'font-weight: bold'
const EFFECT_TYPE_STYLE = 'color: blue'
const ERROR_STYLE = 'color: red'

const time = () => performance.now()

let effectsById = {}
export default () => next => action => {

  switch (action.type) {
    case actions.EFFECT_TRIGGERED:
      effectsById[action.effectId] = {...action,
        status: PENDING,
        start: time()
      }
      break;
    case actions.EFFECT_RESOLVED:
      resolveEffect(action.effectId, action.result)
      break;
    case actions.EFFECT_REJECTED:
      rejectEffect(action.effectId, action.error)
      break;
    case LOG_EFFECT:
      logEffectTree(action.effectId || 0)
      break;
    default:
      return next(action)
  }
}

function resolveEffect(effectId, result) {
  const effect = effectsById[effectId]
  const now = time()

  if(is.task(result)) {
    result._done.then(
      taskResult => resolveEffect(effectId, taskResult),
      taskError  => rejectEffect(effectId, taskError)
    )
  } else {
    effectsById[effectId] = {...effect,
      result: result,
      status: RESOLVED,
      end: now,
      duration: now - effect.start
    }

    if(effect && as.race(effect.effect))
      setRaceWinner(effectId, result)
  }
}

function rejectEffect(effectId, error) {
  const effect = effectsById[effectId]
  const now = time()
  effectsById[effectId] = {...effect,
    error: error,
    status: REJECTED,
    end: now,
    duration: now - effect.start
  }
  if(effect && as.race(effect.effect))
    setRaceWinner(effectId, error)
}

function setRaceWinner(raceEffectId, result) {
  const winnerLabel = Object.keys(result)[0]
  const children = getChildEffects(raceEffectId)
  for (var i = 0; i < children.length; i++) {
    const childEffect = effectsById[ children[i] ]
    if(childEffect.label === winnerLabel)
      childEffect.winner = true
  }
}

function getChildEffects(parentEffectId) {
  return Object.keys(effectsById)
    .filter(effectId => effectsById[effectId].parentEffectId === parentEffectId)
    .map(effectId => +effectId)
}

function logEffectTree(effectId) {
  const effect = effectsById[effectId]
  const childEffects = getChildEffects(effectId)

  if(!childEffects.length)
    logSimpleEffect(effect)
  else {
    if(effect) {
      const {formatter} = getEffectLog(effect)
      console.group(...formatter.getLog())
    } else
      console.group('root')
    childEffects.forEach(logEffectTree)
    console.groupEnd()
  }
}

function logSimpleEffect(effect) {
  const {method, formatter} = getEffectLog(effect)
  console[method](...formatter.getLog())
}

/*eslint-disable no-cond-assign*/
function getEffectLog(effect) {
  let data, log

  if(data = as.take(effect.effect)) {
    log = getLogPrefix('take', effect)
    log.formatter.addValue(data)
    logResult(effect, log.formatter)
  }

  else if(data = as.put(effect.effect)) {
    log = getLogPrefix('put', effect)
    logResult(effect, log.formatter)
  }

  else if(data = as.call(effect.effect)) {
    log = getLogPrefix('call', effect)
    log.formatter.addCall(data.fn.name, data.args)
    logResult(effect, log.formatter)
  }

  else if(data = as.cps(effect.effect)) {
    log = getLogPrefix('cps', effect)
    log.formatter.addCall(data.fn.name, data.args)
    logResult(effect, log.formatter)
  }

  else if(data = as.fork(effect.effect)) {
    log = getLogPrefix('', effect)
    log.formatter.addCall(data.task.name, data.args)
    logResult(effect, log.formatter)
  }

  else if(data = as.join(effect.effect)) {
    log = getLogPrefix('join', effect)
    logResult(effect, log.formatter)
  }

  else if(data = as.race(effect.effect)) {
    log = getLogPrefix('race', effect)
    logResult(effect, log.formatter, true)
  }

  else if(data = is.array(effect.effect)) {
    log = getLogPrefix('parallel', effect)
    logResult(effect, log.formatter, true)
  }

  else {
    log = getLogPrefix('unkown', effect)
    logResult(effect, log.formatter)
  }

  return log
}

function getLogPrefix(type, effect) {

  const isError = effect && effect.status === REJECTED
  const method = isError ? 'error' : 'log'
  const winnerInd = effect && effect.winner
    ? ( isError ? '✘' : '✓' )
    : ''

  const winnerStyle = isError ? ERROR_STYLE : LABEL_STYLE
  const labelStyle = isError ? ERROR_STYLE : LABEL_STYLE
  const typeStyle = isError ? ERROR_STYLE: EFFECT_TYPE_STYLE

  const formatter = logFormatter()

  if(winnerInd)
    formatter.add(`%c ${winnerInd}`, winnerStyle)

  if(effect && effect.label)
    formatter.add(`%c ${effect.label}: `, labelStyle)

  if(type)
    formatter.add(`%c ${type} `, typeStyle)

  formatter.add('%c', DEFAULT_STYLE)

  return {
    method,
    formatter
  }
}

function argToString(arg) {
  return (
      typeof arg === 'function' ? `${arg.name}`
    : typeof arg === 'string'   ? `'${arg}'`
    : arg
  )
}

function logResult({status, result, error, duration}, formatter, ignoreResult) {

  if(status === RESOLVED && !ignoreResult) {
    if( is.array(result) ) {
      formatter.addValue(' → ')
      formatter.addValue(result)
    } else
      formatter.appendData('→',result)
  }

  else if(status === REJECTED)
    formatter.appendData('→ ⚠', error)

  else if(status === PENDING)
    formatter.appendData('⌛')

  if(status !== PENDING)
    formatter.appendData(`(${duration.toFixed(2)}ms)`)
}

function isPrimitive(val) {
  return  typeof val === 'string'   ||
          typeof val === 'number'   ||
          typeof val === 'boolean'  ||
          typeof val === 'symbol'   ||
          val === null              ||
          val === undefined;
}

function logFormatter() {
  const logs = []
  let suffix = []

  function add(msg, ...args) {
    logs.push({msg, args})
  }

  function appendData(...data) {
    suffix = suffix.concat(data)
  }

  function addValue(value) {
    if(isPrimitive(value))
      add(value)
    else
      add('%O', value)
  }

  function addCall(name, args) {
    if(!args.length)
      add( `${name}()` )
    else {
      add(name)
      add('(')
      args.forEach( arg => addValue(argToString(arg)) )
      add(')')
    }
  }

  function getLog() {
    let msgs = [], msgsArgs = []
    for (var i = 0; i < logs.length; i++) {
      msgs.push(logs[i].msg)
      msgsArgs = msgsArgs.concat(logs[i].args)
    }
    return [msgs.join('')].concat(msgsArgs).concat(suffix)
  }

  return {
    add, addValue, addCall, appendData, getLog
  }
}
<commit_msg>add , separator to func calls<commit_after>/*eslint-disable no-console*/

import * as actions from '../src/monitorActions'
import { as } from '../src/io'
import { is } from '../src/utils'

const PENDING = 'PENDING'
const RESOLVED = 'RESOLVED'
const REJECTED = 'REJECTED'

export const LOG_EFFECT = 'LOG_EFFECT'
export const logEffect = (effectId = 0) => ({type: LOG_EFFECT, effectId})

const DEFAULT_STYLE = 'color: black'
const LABEL_STYLE = 'font-weight: bold'
const EFFECT_TYPE_STYLE = 'color: blue'
const ERROR_STYLE = 'color: red'

const time = () => performance.now()

let effectsById = {}
export default () => next => action => {

  switch (action.type) {
    case actions.EFFECT_TRIGGERED:
      effectsById[action.effectId] = {...action,
        status: PENDING,
        start: time()
      }
      break;
    case actions.EFFECT_RESOLVED:
      resolveEffect(action.effectId, action.result)
      break;
    case actions.EFFECT_REJECTED:
      rejectEffect(action.effectId, action.error)
      break;
    case LOG_EFFECT:
      logEffectTree(action.effectId || 0)
      break;
    default:
      return next(action)
  }
}

function resolveEffect(effectId, result) {
  const effect = effectsById[effectId]
  const now = time()

  if(is.task(result)) {
    result._done.then(
      taskResult => resolveEffect(effectId, taskResult),
      taskError  => rejectEffect(effectId, taskError)
    )
  } else {
    effectsById[effectId] = {...effect,
      result: result,
      status: RESOLVED,
      end: now,
      duration: now - effect.start
    }

    if(effect && as.race(effect.effect))
      setRaceWinner(effectId, result)
  }
}

function rejectEffect(effectId, error) {
  const effect = effectsById[effectId]
  const now = time()
  effectsById[effectId] = {...effect,
    error: error,
    status: REJECTED,
    end: now,
    duration: now - effect.start
  }
  if(effect && as.race(effect.effect))
    setRaceWinner(effectId, error)
}

function setRaceWinner(raceEffectId, result) {
  const winnerLabel = Object.keys(result)[0]
  const children = getChildEffects(raceEffectId)
  for (var i = 0; i < children.length; i++) {
    const childEffect = effectsById[ children[i] ]
    if(childEffect.label === winnerLabel)
      childEffect.winner = true
  }
}

function getChildEffects(parentEffectId) {
  return Object.keys(effectsById)
    .filter(effectId => effectsById[effectId].parentEffectId === parentEffectId)
    .map(effectId => +effectId)
}

function logEffectTree(effectId) {
  const effect = effectsById[effectId]
  const childEffects = getChildEffects(effectId)

  if(!childEffects.length)
    logSimpleEffect(effect)
  else {
    if(effect) {
      const {formatter} = getEffectLog(effect)
      console.group(...formatter.getLog())
    } else
      console.group('root')
    childEffects.forEach(logEffectTree)
    console.groupEnd()
  }
}

function logSimpleEffect(effect) {
  const {method, formatter} = getEffectLog(effect)
  console[method](...formatter.getLog())
}

/*eslint-disable no-cond-assign*/
function getEffectLog(effect) {
  let data, log

  if(data = as.take(effect.effect)) {
    log = getLogPrefix('take', effect)
    log.formatter.addValue(data)
    logResult(effect, log.formatter)
  }

  else if(data = as.put(effect.effect)) {
    log = getLogPrefix('put', effect)
    logResult(effect, log.formatter)
  }

  else if(data = as.call(effect.effect)) {
    log = getLogPrefix('call', effect)
    log.formatter.addCall(data.fn.name, data.args)
    logResult(effect, log.formatter)
  }

  else if(data = as.cps(effect.effect)) {
    log = getLogPrefix('cps', effect)
    log.formatter.addCall(data.fn.name, data.args)
    logResult(effect, log.formatter)
  }

  else if(data = as.fork(effect.effect)) {
    log = getLogPrefix('', effect)
    log.formatter.addCall(data.task.name, data.args)
    logResult(effect, log.formatter)
  }

  else if(data = as.join(effect.effect)) {
    log = getLogPrefix('join', effect)
    logResult(effect, log.formatter)
  }

  else if(data = as.race(effect.effect)) {
    log = getLogPrefix('race', effect)
    logResult(effect, log.formatter, true)
  }

  else if(data = is.array(effect.effect)) {
    log = getLogPrefix('parallel', effect)
    logResult(effect, log.formatter, true)
  }

  else {
    log = getLogPrefix('unkown', effect)
    logResult(effect, log.formatter)
  }

  return log
}

function getLogPrefix(type, effect) {

  const isError = effect && effect.status === REJECTED
  const method = isError ? 'error' : 'log'
  const winnerInd = effect && effect.winner
    ? ( isError ? '✘' : '✓' )
    : ''

  const winnerStyle = isError ? ERROR_STYLE : LABEL_STYLE
  const labelStyle = isError ? ERROR_STYLE : LABEL_STYLE
  const typeStyle = isError ? ERROR_STYLE: EFFECT_TYPE_STYLE

  const formatter = logFormatter()

  if(winnerInd)
    formatter.add(`%c ${winnerInd}`, winnerStyle)

  if(effect && effect.label)
    formatter.add(`%c ${effect.label}: `, labelStyle)

  if(type)
    formatter.add(`%c ${type} `, typeStyle)

  formatter.add('%c', DEFAULT_STYLE)

  return {
    method,
    formatter
  }
}

function argToString(arg) {
  return (
      typeof arg === 'function' ? `${arg.name}`
    : typeof arg === 'string'   ? `'${arg}'`
    : arg
  )
}

function logResult({status, result, error, duration}, formatter, ignoreResult) {

  if(status === RESOLVED && !ignoreResult) {
    if( is.array(result) ) {
      formatter.addValue(' → ')
      formatter.addValue(result)
    } else
      formatter.appendData('→',result)
  }

  else if(status === REJECTED)
    formatter.appendData('→ ⚠', error)

  else if(status === PENDING)
    formatter.appendData('⌛')

  if(status !== PENDING)
    formatter.appendData(`(${duration.toFixed(2)}ms)`)
}

function isPrimitive(val) {
  return  typeof val === 'string'   ||
          typeof val === 'number'   ||
          typeof val === 'boolean'  ||
          typeof val === 'symbol'   ||
          val === null              ||
          val === undefined;
}

function logFormatter() {
  const logs = []
  let suffix = []

  function add(msg, ...args) {
    logs.push({msg, args})
  }

  function appendData(...data) {
    suffix = suffix.concat(data)
  }

  function addValue(value) {
    if(isPrimitive(value))
      add(value)
    else
      add('%O', value)
  }

  function addCall(name, args) {
    if(!args.length)
      add( `${name}()` )
    else {
      add(name)
      add('(')
      args.forEach( (arg, i) => {
        addValue( argToString(arg) )
        addValue( i === args.length - 1 ? ')' : ', ')
      })
      add(')')
    }
  }

  function getLog() {
    let msgs = [], msgsArgs = []
    for (var i = 0; i < logs.length; i++) {
      msgs.push(logs[i].msg)
      msgsArgs = msgsArgs.concat(logs[i].args)
    }
    return [msgs.join('')].concat(msgsArgs).concat(suffix)
  }

  return {
    add, addValue, addCall, appendData, getLog
  }
}
<|endoftext|>


<commit_before>/**
 * Created by Peter on 2016/10/23.
 */
// CBoard settings
var settings = {
    preferredLanguage: "cn" // en/cn: Switch language to Chinese
}

<commit_msg>set default to en<commit_after>/**
 * Created by Peter on 2016/10/23.
 */
// CBoard settings
var settings = {
    preferredLanguage: "en" // en/cn: Switch language to Chinese
}

<|endoftext|>


<commit_before>var mongoose     = require('mongoose');
var Schema       = mongoose.Schema;
var moment = require("moment");
var async = require("async");
var ObjectId = mongoose.Schema.Types.ObjectId;
var Currency = require('./currency_model');
var User = require("./user_model");
var Organisation = require("./organisation_model");

var WalletSchema   = new Schema({
	name: { type: String, required: true, validate: /\S+/ },
	currency_id: { type: ObjectId, index: true, ref: "Currency", required: true },
	priority: { type: Number, required: true },
	quota_frequency: { type: String, validate: /daily|weekly|monthly|annually|never/, index: true, default: "never" },
	quota_amount: { type: Number, default: 0 },
	last_quota_date: { type: Date, index: true, default: Date.now },
	user_id: [{ type: ObjectId, index: true, ref: "User", required: true }],
	organisation_id: { type: ObjectId, index: true, ref: "Organisation" },
	balance: { type: Number, default: 0 },
	date_created: { type: Date, default: Date.now },
	personal: Boolean,
	_owner_id: ObjectId
});

WalletSchema.set("_perms", {
	admin: "crud",
	user: "r",
});

WalletSchema.index({ name: 1, user_id: 1 }, { unique: true });

WalletSchema.statics.topup_daily = function() {
	var Wallet = require("./wallet_model");
	var day_ago = moment().subtract(1, "day");
	return Wallet.find({ quota_frequency: "daily", last_quota_date: { $lte: day_ago } })
	.then(wallets => {
		var result = [];
		wallets.forEach(wallet => {
			wallet.balance = wallet.quota_amount;
			wallet.last_quota_date = new Date();
			wallet.save();
			result.push(wallet);
		});
		return result;
	});
};

WalletSchema.statics.topup_weekly = function() {
	var Wallet = require("./wallet_model");
	var day_ago = moment().subtract(1, "week");
	return Wallet.find({ quota_frequency: "weekly", last_quota_date: { $lte: day_ago } })
	.then(wallets => {
		var result = [];
		wallets.forEach(wallet => {
			wallet.balance = wallet.quota_amount;
			wallet.last_quota_date = new Date();
			wallet.save();
			result.push(wallet);
		});
		return result;
	});
};

WalletSchema.statics.topup_monthly = function() {
	var Wallet = require("./wallet_model");
	var day_ago = moment().startOf('month');
	console.log(day_ago);
	return Wallet.find({ quota_frequency: "monthly", last_quota_date: { $lt: day_ago } })
	.then(wallets => {
		var result = [];
		wallets.forEach(wallet => {
			wallet.balance = wallet.quota_amount;
			wallet.last_quota_date = new Date();
			wallet.save();
			result.push(wallet);
		});
		return result;
	});
};

WalletSchema.statics.topup_annually = function() {
	var Wallet = require("./wallet_model");
	var day_ago = moment().subtract(1, "year");
	return Wallet.find({ quota_frequency: "annually", last_quota_date: { $lte: day_ago } })
	.then(wallets => {
		var result = [];
		wallets.forEach(wallet => {
			wallet.balance = wallet.quota_amount;
			wallet.last_quota_date = new Date();
			wallet.save();
			result.push(wallet);
		});
		return result;
	});
};

// Set this wallet as the Personal wallet and unset any other wallets for the same currency and user
WalletSchema.statics.set_personal = function(_id) {
	var Wallet = require("./wallet_model");
	var queue = [];
	var wallet = null;
	return Wallet.findOne({ _id })
	.then(result => {
		wallet = result;
		return Wallet.find({ currency: wallet.currency, user_id: wallet.user_id, personal: true });
	})
	.then(wallets => {
		wallets.forEach(w => {
			if (w._id.toString() !== wallet._id.toString()) {
				console.log(w._id, wallet._id);
				queue.push(cb => {
					w.personal = false;
					w.save()
					.then(result => {
						cb(null, result);
					}, err => {
						console.error(err);
						cb(err);
					});
				});
			}
		});
		queue.push(cb => {
			wallet.personal = true;
			wallet.save()
			.then(result => {
				cb(null, result);
			}, err => {
				console.error(err);
				cb(err);
			});
		});
		return new Promise((resolve, reject) => {
			async.series(queue, (err, result) => {
				if (err)
					return reject(err);
				return resolve(result);
			});
		});
	});
};

module.exports = mongoose.model('Wallet', WalletSchema);<commit_msg>Move daily quota update to startOf(day)<commit_after>var mongoose     = require('mongoose');
var Schema       = mongoose.Schema;
var moment = require("moment");
var async = require("async");
var ObjectId = mongoose.Schema.Types.ObjectId;
var Currency = require('./currency_model');
var User = require("./user_model");
var Organisation = require("./organisation_model");

var WalletSchema   = new Schema({
	name: { type: String, required: true, validate: /\S+/ },
	currency_id: { type: ObjectId, index: true, ref: "Currency", required: true },
	priority: { type: Number, required: true },
	quota_frequency: { type: String, validate: /daily|weekly|monthly|annually|never/, index: true, default: "never" },
	quota_amount: { type: Number, default: 0 },
	last_quota_date: { type: Date, index: true, default: Date.now },
	user_id: [{ type: ObjectId, index: true, ref: "User", required: true }],
	organisation_id: { type: ObjectId, index: true, ref: "Organisation" },
	balance: { type: Number, default: 0 },
	date_created: { type: Date, default: Date.now },
	personal: Boolean,
	_owner_id: ObjectId
});

WalletSchema.set("_perms", {
	admin: "crud",
	user: "r",
});

WalletSchema.index({ name: 1, user_id: 1 }, { unique: true });

WalletSchema.statics.topup_daily = function() {
	var Wallet = require("./wallet_model");
	var day_ago = moment().subtract(1, "day").startOf("day");
	return Wallet.find({ quota_frequency: "daily", last_quota_date: { $lte: day_ago } })
	.then(wallets => {
		var result = [];
		wallets.forEach(wallet => {
			wallet.balance = wallet.quota_amount;
			wallet.last_quota_date = new Date();
			wallet.save();
			result.push(wallet);
		});
		return result;
	});
};

WalletSchema.statics.topup_weekly = function() {
	var Wallet = require("./wallet_model");
	var day_ago = moment().subtract(1, "week");
	return Wallet.find({ quota_frequency: "weekly", last_quota_date: { $lte: day_ago } })
	.then(wallets => {
		var result = [];
		wallets.forEach(wallet => {
			wallet.balance = wallet.quota_amount;
			wallet.last_quota_date = new Date();
			wallet.save();
			result.push(wallet);
		});
		return result;
	});
};

WalletSchema.statics.topup_monthly = function() {
	var Wallet = require("./wallet_model");
	var day_ago = moment().startOf('month');
	console.log(day_ago);
	return Wallet.find({ quota_frequency: "monthly", last_quota_date: { $lt: day_ago } })
	.then(wallets => {
		var result = [];
		wallets.forEach(wallet => {
			wallet.balance = wallet.quota_amount;
			wallet.last_quota_date = new Date();
			wallet.save();
			result.push(wallet);
		});
		return result;
	});
};

WalletSchema.statics.topup_annually = function() {
	var Wallet = require("./wallet_model");
	var day_ago = moment().subtract(1, "year");
	return Wallet.find({ quota_frequency: "annually", last_quota_date: { $lte: day_ago } })
	.then(wallets => {
		var result = [];
		wallets.forEach(wallet => {
			wallet.balance = wallet.quota_amount;
			wallet.last_quota_date = new Date();
			wallet.save();
			result.push(wallet);
		});
		return result;
	});
};

// Set this wallet as the Personal wallet and unset any other wallets for the same currency and user
WalletSchema.statics.set_personal = function(_id) {
	var Wallet = require("./wallet_model");
	var queue = [];
	var wallet = null;
	return Wallet.findOne({ _id })
	.then(result => {
		wallet = result;
		return Wallet.find({ currency: wallet.currency, user_id: wallet.user_id, personal: true });
	})
	.then(wallets => {
		wallets.forEach(w => {
			if (w._id.toString() !== wallet._id.toString()) {
				console.log(w._id, wallet._id);
				queue.push(cb => {
					w.personal = false;
					w.save()
					.then(result => {
						cb(null, result);
					}, err => {
						console.error(err);
						cb(err);
					});
				});
			}
		});
		queue.push(cb => {
			wallet.personal = true;
			wallet.save()
			.then(result => {
				cb(null, result);
			}, err => {
				console.error(err);
				cb(err);
			});
		});
		return new Promise((resolve, reject) => {
			async.series(queue, (err, result) => {
				if (err)
					return reject(err);
				return resolve(result);
			});
		});
	});
};

module.exports = mongoose.model('Wallet', WalletSchema);<|endoftext|>


<commit_before>"use strict"

var ObjectId = require("mongodb").ObjectId;
require("mongodb-toolkit");
var DLModels = require("dl-models");
var generateCode = require("../../utils/code-generator");
var map = DLModels.map;
var Contact = DLModels.master.Contact;
var BaseManager = require("module-toolkit").BaseManager;
var i18n = require("dl-i18n");
var CompanyManager = require('./company-manager');

module.exports = class ContactManager extends BaseManager {
    constructor(db, user) {
        super(db, user);
        this.collection = this.db.use(map.master.collection.Contact);
        this.companyManager = new CompanyManager(db, user);
    }

    _beforeInsert(data) {
        data.code = generateCode();

        return Promise.resolve(data);
    }

    _getQuery(paging) {
        var _default = {
            _deleted: false
        },
            pagingFilter = paging.filter || {},
            keywordFilter = {},
            query = {};

        if (paging.keyword) {
            var regex = new RegExp(paging.keyword, "i");
            var codeFilter = {
                "code": {
                    "$regex": regex
                }
            };
            var nameFilter = {
                "name": {
                    "$regex": regex
                }
            };
            keywordFilter["$or"] = [codeFilter, nameFilter];
        }
        query["$and"] = [_default, keywordFilter, pagingFilter];
        return query;
    }

    _validate(contact) {
        var errors = {};
        var valid = contact;
        // 1. begin: Declare promises.
        var getContactPromise = this.collection.singleOrDefault({
            _id: {
                "$ne": new ObjectId(valid._id)
            },
            code: valid.code
        });

        var getCompany = valid.company && ObjectId.isValid(valid.company._id) ? this.companyManager.getSingleByIdOrDefault(valid.company._id) : Promise.resolve(null);

        // 2. begin: Validation.
        return Promise.all([getContactPromise, getCompany])
            .then(results => {
                var _duplicateContact = results[0];
                var _company = results[1];

                if (_duplicateContact) {
                    errors["code"] = i18n.__("Contact.code.isExists:%s is already exists", i18n.__("Contact.code._:Code")); //"Kode sudah ada";
                }

                if (!valid.firstName || valid.firstName == '')
                    errors["firstName"] = i18n.__("Contact.firstName.isRequired:%s is required", i18n.__("Contact.firstName._:First name")); //"Nama Depan harus diisi";

                if (!_company)
                    errors["company"] = i18n.__("Contact.company.notFound:%s not found", i18n.__("Contact.company._:Company")); //"Perusahaan tidak ditemukan";

                if (Object.getOwnPropertyNames(errors).length > 0) {
                    var ValidationError = require("module-toolkit").ValidationError;
                    return Promise.reject(new ValidationError("data does not pass validation", errors));
                }

                valid.companyId = new ObjectId(valid.company._id);

                if (!valid.stamp) {
                    valid = new Contact(valid);
                }

                valid.stamp(this.user.username, "manager");
                return Promise.resolve(valid);
            });
    }

    _createIndexes() {
        var dateIndex = {
            name: `ix_${map.master.collection.Contact}__updatedDate`,
            key: {
                _updatedDate: -1
            }
        };

        var codeIndex = {
            name: `ix_${map.master.collection.Contact}_code`,
            key: {
                code: 1
            },
            unique: true
        };

        return this.collection.createIndexes([dateIndex, codeIndex]);
    }
}
<commit_msg>Update Contact Manager Search Filter<commit_after>"use strict"

var ObjectId = require("mongodb").ObjectId;
require("mongodb-toolkit");
var DLModels = require("dl-models");
var generateCode = require("../../utils/code-generator");
var map = DLModels.map;
var Contact = DLModels.master.Contact;
var BaseManager = require("module-toolkit").BaseManager;
var i18n = require("dl-i18n");
var CompanyManager = require('./company-manager');

module.exports = class ContactManager extends BaseManager {
    constructor(db, user) {
        super(db, user);
        this.collection = this.db.use(map.master.collection.Contact);
        this.companyManager = new CompanyManager(db, user);
    }

    _beforeInsert(data) {
        data.code = generateCode();

        return Promise.resolve(data);
    }

    _getQuery(paging) {
        var _default = {
            _deleted: false
        },
            pagingFilter = paging.filter || {},
            keywordFilter = {},
            query = {};

        if (paging.keyword) {
            var regex = new RegExp(paging.keyword, "i");
            var codeFilter = {
                "code": {
                    "$regex": regex
                }
            };
            var firstNameFilter = {
                "firstName": {
                    "$regex": regex
                }
            };
            var lastNameFilter = {
                "lastName": {
                    "$regex": regex
                }
            };
            keywordFilter["$or"] = [codeFilter, firstNameFilter, lastNameFilter];
        }
        query["$and"] = [_default, keywordFilter, pagingFilter];
        return query;
    }

    _validate(contact) {
        var errors = {};
        var valid = contact;
        // 1. begin: Declare promises.
        var getContactPromise = this.collection.singleOrDefault({
            _id: {
                "$ne": new ObjectId(valid._id)
            },
            code: valid.code
        });

        var getCompany = valid.company && ObjectId.isValid(valid.company._id) ? this.companyManager.getSingleByIdOrDefault(valid.company._id) : Promise.resolve(null);

        // 2. begin: Validation.
        return Promise.all([getContactPromise, getCompany])
            .then(results => {
                var _duplicateContact = results[0];
                var _company = results[1];

                if (_duplicateContact) {
                    errors["code"] = i18n.__("Contact.code.isExists:%s is already exists", i18n.__("Contact.code._:Code")); //"Kode sudah ada";
                }

                if (!valid.firstName || valid.firstName == '')
                    errors["firstName"] = i18n.__("Contact.firstName.isRequired:%s is required", i18n.__("Contact.firstName._:First name")); //"Nama Depan harus diisi";

                if (!_company)
                    errors["company"] = i18n.__("Contact.company.notFound:%s not found", i18n.__("Contact.company._:Company")); //"Perusahaan tidak ditemukan";

                if (Object.getOwnPropertyNames(errors).length > 0) {
                    var ValidationError = require("module-toolkit").ValidationError;
                    return Promise.reject(new ValidationError("data does not pass validation", errors));
                }

                valid.companyId = new ObjectId(valid.company._id);

                if (!valid.stamp) {
                    valid = new Contact(valid);
                }

                valid.stamp(this.user.username, "manager");
                return Promise.resolve(valid);
            });
    }

    _createIndexes() {
        var dateIndex = {
            name: `ix_${map.master.collection.Contact}__updatedDate`,
            key: {
                _updatedDate: -1
            }
        };

        var codeIndex = {
            name: `ix_${map.master.collection.Contact}_code`,
            key: {
                code: 1
            },
            unique: true
        };

        return this.collection.createIndexes([dateIndex, codeIndex]);
    }
}
<|endoftext|>