<commit_before>/*---------------------------------------------------------
 * OpenERP base library
 *---------------------------------------------------------*/

openerp.base_diagram = function (openerp) {
QWeb.add_template('/base_diagram/static/src/xml/base_diagram.xml');
openerp.base.views.add('diagram', 'openerp.base_diagram.DiagramView');
openerp.base_diagram.DiagramView = openerp.base.View.extend({
	init: function(parent, element_id, dataset, view_id, options) {
		this._super(parent, element_id);
		this.set_default_options(options);
        this.view_manager = parent;
        this.dataset = dataset;
        this.model = this.dataset.model;
        this.view_id = view_id;
        this.name = "";
		this.domain = this.dataset._domain ? this.dataset._domain: [];
		this.context = {};
		this.ids = this.dataset.ids;
	},
	start: function() {
		return this.rpc("/base_diagram/diagram/load", {"model": this.model, "view_id": this.view_id}, this.on_loaded);
	},

	toTitleCase: function(str) {
		return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
	},

	on_loaded: function(result) {

		var self = this;
		if(this.ids && this.ids.length) {
			this.id = this.ids[self.dataset.index || 0];
		}
		this.fields_view = result.fields_view;

		this.view_id = this.fields_view.view_id;
		this.name = this.fields_view.name;

		this.fields = this.fields_view.fields;
		var children = this.fields_view.arch.children;

		/*
		 * For Nodes (Fields)
		 */
		this.node = '';
		this.bgcolor = '';
		this.shape = '';
		this.visible_fields_nodes = [];
		this.invisible_fields_nodes = [];
		this.fields_nodes_string = [];

		/*
		 * For Arraows(Connector)
		 */
		this.connector = '';
		this.src_node = '';
		this.des_node = '';
		this.connector_fields = [];
		this.fields_connector_string = [];

		for(ch in children) {
			if(children[ch]['tag'] == 'node') {
				this.node = children[ch]['attrs']['object'];
				this.bgcolor = children[ch]['attrs']['bgcolor'] || '';
				this.shape = children[ch]['attrs']['shape'] || '';
				for(node_chld in children[ch]['children']) {
					if (children[ch]['children'][node_chld]['tag'] = 'field') {
						var ch_name = children[ch]['children'][node_chld]['attrs']['name'];

						if (children[ch]['children'][node_chld]['attrs']['invisible']) {
							if (children[ch]['children'][node_chld]['attrs']['invisible'] == 1 && children[ch]['children'][node_chld]['attrs']['invisible'] == '1') {
								this.invisible_fields_nodes.push(ch_name)
							}
						}
						else {
							this.visible_fields_nodes.push(ch_name);
							var ch_node_string = this.fields[ch_name]['string'] || this.toTitleCase(ch_name);
							this.fields_nodes_string.push(ch_node_string)
						}
					}
				}
			} else if(children[ch]['tag'] == 'arrow') {
				this.connector = children[ch]['attrs']['object'];
				this.src_node = children[ch]['attrs']['source'];
				this.des_node = children[ch]['attrs']['destination'];
				for (arrow_chld in children[ch]['children']) {
					if (children[ch]['children'][arrow_chld]['tag'] = 'field') {
						var arr_ch_name = children[ch]['children'][arrow_chld]['attrs']['name'];
						var ch_node_string = this.fields[arr_ch_name]['string'] || this.toTitleCase(arr_ch_name);
						this.fields_connector_string.push(ch_node_string);
						this.connector_fields.push(arr_ch_name);
					}
				}
			}
		}

		this.$element.html(QWeb.render("DiagramView", this));

		this.$element.find('div.oe_diagram_pager button[data-pager-action]').click(function() {
            var action = $(this).data('pager-action');
            self.on_pager_action(action);
        });

		this.do_update_pager();

		this.$element.find('.oe_diagram_button_new').click(function(){self.add_node()})

        if(this.id) {
        	self.get_diagram_info();
        }
	},

	add_node: function() {
		var self = this;
		console.log('self>>', self)
	},

	get_diagram_info: function() {
		var self = this;
        this.rpc(
            '/base_diagram/diagram/get_diagram_info',
            {
                'id': this.id,
                'model': this.model,
                'bgcolor': this.bgcolor,
                'shape': this.shape,
                'node': this.node,
                'connector': this.connector,
                'src_node': this.src_node,
                'des_node': this.des_node,
                'visible_node_fields': this.visible_fields_nodes,
                'invisible_node_fields': this.invisible_fields_nodes,
                'node_fields_string': this.fields_nodes_string,
                'connector_fields': this.connector_fields,
                'connector_fields_string': this.fields_connector_string
            },
            function(result) {
            	self.draw_diagram(result);
            }
        );
	},

	on_diagram_loaded: function(record) {
    	var self = this;
    	var id_record = record['id']
    	if(id_record) {
        	self.get_diagram_info();
        }
    },

    draw_diagram: function(result) {
        var dia = new Graph();

        this.active_model = result['id_model'];
        this.in_transition_field = result['in_transition_field'];
        this.out_transition_field = result['out_transition_field'];
        var res_nodes = result['nodes'];
        var res_connectors = result['conn'];

        //Custom logic
        var self = this;
        var renderer= function(r, n) {
        var node;
        var set;

        // ellipse
        if (n.node.shape == 'ellipse') {
            var node = r.ellipse(n.node.x - 30, n.node.y - 13, 40, 20).attr({
                    "fill": n.node.color,
                    r: "12px",
                    "stroke-width": n.distance == 0 ? "3px" : "1px"
                });

            set = r.set().push(node).push(r.text(n.node.x - 30, n.node.y - 10, (n.label || n.id)));
        }

        // rectangle
		else if(n.node.shape == 'rectangle') {
			var node = r.rect(n.node.x-30, n.node.y-13, 60, 44).attr({
             	"fill": n.node.color,
                 r : "12px",
                "stroke-width" : n.distance == 0 ? "3px" : "1px"
                });
        	set = r.set().push(node).push(r.text(n.node.x , n.node.y+5 , (n.label || n.id)));
		}

        // circle
		else {
            var node = r.circle(n.node.x, n.node.y, 150).attr({
                        "fill": n.node.color,
                        r : "30px",
                        "stroke-width" : n.distance == 0 ? "3px" : "1px"
                });
           	set = r.set().push(node).push(r.text(n.node.x , n.node.y , (n.label || n.id)));
		}

        jQuery(node.node).attr({
            'id': n.node.id,
            'name': n.id,
            'kind': n.node.options['Kind'] || n.node.options['kind']
        }).dblclick(function() {
            var $this = jQuery(this);
            self.search_activity($this.attr('id'), $this.attr('name'), $this.attr('kind'))
        });

        jQuery(node.next.node).attr({
            'id': n.node.id,
            'name': n.id,
            'kind': n.node.options['Kind'] || n.node.options['kind']
        }).dblclick(function() {
            var $this = jQuery(this);
            self.search_activity($this.attr('id'), $this.attr('name'), $this.attr('kind'))
        });
        return set;
        }

        for(node in res_nodes) {
            var res_node = res_nodes[node];
            dia.addNode(res_node['name'],{node: res_node,render: renderer});
        }

        for(cr in res_connectors) {
        	var res_connector = res_connectors[cr];
        	dia.addEdge(res_connector['source'], res_connector['destination']);
        }

        var layouter = new Graph.Layout.Spring(dia);
        layouter.layout();
        if ($('div#dia-canvas').children().length > 0) {
        	$('div#dia-canvas').children().remove();
        }
        var renderer = new Graph.Renderer.Raphael('dia-canvas', dia, $('div#dia-canvas').width(), $('div#dia-canvas').height());
        renderer.draw();

    },

    search_activity: function(id, name, kind) {
        var self = this;
        this.rpc(
        '/base_diagram/diagram/get_activity',
        {
            'id': id,
            'name': name,
            'kind': kind,
            'active_model': this.active_model,
            'model': this.node
        },
        function(result) {
            self.popup_activity(result)
        }
        )
    },

    popup_activity: function(result) {
    	var self = this;
    	var action_manager = new openerp.base.ActionManager(this);
    	var dialog = new openerp.base.Dialog(this, {
            title : 'Activity',
            width: 800,
            height: 600,
            buttons : {
                Cancel : function() {
                    $(this).dialog('destroy');
                },
                Save : function() {
                    $(this).dialog('destroy');
                }
            }
        }).start().open();
    	action_manager.appendTo(dialog.$element);
    	action_manager.do_action({
            res_model : this.node,
            res_id: result.activity_id[0],
            views : [[false, 'form']],
            type : 'ir.actions.act_window',
            auto_search : false,
            flags : {
    			search_view: false,
                sidebar : false,
                views_switcher : false,
                action_buttons : false
            }
        });
    },

    do_search: function(domains, contexts, groupbys) {
        var self = this;
        this.rpc('/base/session/eval_domain_and_context', {
            domains: domains,
            contexts: contexts,
            group_by_seq: groupbys
        }, function (results) {
            // TODO: handle non-empty results.group_by with read_group
            self.dataset.context = self.context = results.context;
            self.dataset.domain = self.domain = results.domain;
            self.dataset.read_slice(self.fields, 0, self.limit,function(events){
                self.schedule_events(events)
            });
        });
    },

    on_pager_action: function(action) {
    	switch (action) {
	        case 'first':
	            this.dataset.index = 0;
	            break;
	        case 'previous':
	            this.dataset.previous();
	            break;
	        case 'next':
	            this.dataset.next();
	            break;
	        case 'last':
	            this.dataset.index = this.dataset.ids.length - 1;
	            break;
    	}
	    this.dataset.read_index(_.keys(this.fields_view.fields), this.on_diagram_loaded);
	    this.do_update_pager();
    },

    do_update_pager: function(hide_index) {
        var $pager = this.$element.find('div.oe_diagram_pager');
        var index = hide_index ? '-' : this.dataset.index + 1;
        if(!this.dataset.count)
        	this.dataset.count = this.dataset.ids.length
        $pager.find('span.oe_pager_index').html(index);
        $pager.find('span.oe_pager_count').html(this.dataset.count);
    },

	do_show: function () {
        this.$element.show();
    },

    do_hide: function () {
        this.$element.hide();
    }
});
};

// vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax:
<commit_msg>[FIX] add or edit node.<commit_after>/*---------------------------------------------------------
 * OpenERP base library
 *---------------------------------------------------------*/

openerp.base_diagram = function (openerp) {
QWeb.add_template('/base_diagram/static/src/xml/base_diagram.xml');
openerp.base.views.add('diagram', 'openerp.base_diagram.DiagramView');
openerp.base_diagram.DiagramView = openerp.base.View.extend({
	init: function(parent, element_id, dataset, view_id, options) {
		this._super(parent, element_id);
		this.set_default_options(options);
        this.view_manager = parent;
        this.dataset = dataset;
        this.model = this.dataset.model;
        this.view_id = view_id;
        this.name = "";
		this.domain = this.dataset._domain ? this.dataset._domain: [];
		this.context = {};
		this.ids = this.dataset.ids;
	},
	start: function() {
		return this.rpc("/base_diagram/diagram/load", {"model": this.model, "view_id": this.view_id}, this.on_loaded);
	},

	toTitleCase: function(str) {
		return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
	},

	on_loaded: function(result) {

		var self = this;
		if(this.ids && this.ids.length) {
			this.id = this.ids[self.dataset.index || 0];
		}
		this.fields_view = result.fields_view;

		this.view_id = this.fields_view.view_id;
		this.name = this.fields_view.name;

		this.fields = this.fields_view.fields;
		var children = this.fields_view.arch.children;

		/*
		 * For Nodes (Fields)
		 */
		this.node = '';
		this.bgcolor = '';
		this.shape = '';
		this.visible_fields_nodes = [];
		this.invisible_fields_nodes = [];
		this.fields_nodes_string = [];

		/*
		 * For Arraows(Connector)
		 */
		this.connector = '';
		this.src_node = '';
		this.des_node = '';
		this.connector_fields = [];
		this.fields_connector_string = [];

		for(ch in children) {
			if(children[ch]['tag'] == 'node') {
				this.node = children[ch]['attrs']['object'];
				this.bgcolor = children[ch]['attrs']['bgcolor'] || '';
				this.shape = children[ch]['attrs']['shape'] || '';
				for(node_chld in children[ch]['children']) {
					if (children[ch]['children'][node_chld]['tag'] = 'field') {
						var ch_name = children[ch]['children'][node_chld]['attrs']['name'];

						if (children[ch]['children'][node_chld]['attrs']['invisible']) {
							if (children[ch]['children'][node_chld]['attrs']['invisible'] == 1 && children[ch]['children'][node_chld]['attrs']['invisible'] == '1') {
								this.invisible_fields_nodes.push(ch_name)
							}
						}
						else {
							this.visible_fields_nodes.push(ch_name);
							var ch_node_string = this.fields[ch_name]['string'] || this.toTitleCase(ch_name);
							this.fields_nodes_string.push(ch_node_string)
						}
					}
				}
			} else if(children[ch]['tag'] == 'arrow') {
				this.connector = children[ch]['attrs']['object'];
				this.src_node = children[ch]['attrs']['source'];
				this.des_node = children[ch]['attrs']['destination'];
				for (arrow_chld in children[ch]['children']) {
					if (children[ch]['children'][arrow_chld]['tag'] = 'field') {
						var arr_ch_name = children[ch]['children'][arrow_chld]['attrs']['name'];
						var ch_node_string = this.fields[arr_ch_name]['string'] || this.toTitleCase(arr_ch_name);
						this.fields_connector_string.push(ch_node_string);
						this.connector_fields.push(arr_ch_name);
					}
				}
			}
		}

		this.$element.html(QWeb.render("DiagramView", this));

		this.$element.find('div.oe_diagram_pager button[data-pager-action]').click(function() {
            var action = $(this).data('pager-action');
            self.on_pager_action(action);
        });

		this.do_update_pager();

		this.$element.find('.oe_diagram_button_new').click(function(){self.add_edit_node()})

        if(this.id) {
        	self.get_diagram_info();
        }
	},

	get_diagram_info: function() {
		var self = this;
        this.rpc(
            '/base_diagram/diagram/get_diagram_info',
            {
                'id': this.id,
                'model': this.model,
                'bgcolor': this.bgcolor,
                'shape': this.shape,
                'node': this.node,
                'connector': this.connector,
                'src_node': this.src_node,
                'des_node': this.des_node,
                'visible_node_fields': this.visible_fields_nodes,
                'invisible_node_fields': this.invisible_fields_nodes,
                'node_fields_string': this.fields_nodes_string,
                'connector_fields': this.connector_fields,
                'connector_fields_string': this.fields_connector_string
            },
            function(result) {
            	self.draw_diagram(result);
            }
        );
	},

	on_diagram_loaded: function(record) {
    	var self = this;
    	var id_record = record['id']
    	if(id_record) {
        	self.get_diagram_info();
        }
    },

    draw_diagram: function(result) {
        var dia = new Graph();

        this.active_model = result['id_model'];
        this.in_transition_field = result['in_transition_field'];
        this.out_transition_field = result['out_transition_field'];
        var res_nodes = result['nodes'];
        var res_connectors = result['conn'];

        //Custom logic
        var self = this;
        var renderer= function(r, n) {
        var node;
        var set;

        // ellipse
        if (n.node.shape == 'ellipse') {
            var node = r.ellipse(n.node.x - 30, n.node.y - 13, 40, 20).attr({
                    "fill": n.node.color,
                    r: "12px",
                    "stroke-width": n.distance == 0 ? "3px" : "1px"
                });

            set = r.set().push(node).push(r.text(n.node.x - 30, n.node.y - 10, (n.label || n.id)));
        }

        // rectangle
		else if(n.node.shape == 'rectangle') {
			var node = r.rect(n.node.x-30, n.node.y-13, 60, 44).attr({
             	"fill": n.node.color,
                 r : "12px",
                "stroke-width" : n.distance == 0 ? "3px" : "1px"
                });
        	set = r.set().push(node).push(r.text(n.node.x , n.node.y+5 , (n.label || n.id)));
		}

        // circle
		else {
            var node = r.circle(n.node.x, n.node.y, 150).attr({
                        "fill": n.node.color,
                        r : "30px",
                        "stroke-width" : n.distance == 0 ? "3px" : "1px"
                });
           	set = r.set().push(node).push(r.text(n.node.x , n.node.y , (n.label || n.id)));
		}

        jQuery(node.node).attr({
            'id': n.node.id,
            'name': n.id,
            'kind': n.node.options['Kind'] || n.node.options['kind']
        }).dblclick(function() {
            var $this = jQuery(this);
            self.search_activity($this.attr('id'), $this.attr('name'), $this.attr('kind'))
        });

        jQuery(node.next.node).attr({
            'id': n.node.id,
            'name': n.id,
            'kind': n.node.options['Kind'] || n.node.options['kind']
        }).dblclick(function() {
            var $this = jQuery(this);
            self.search_activity($this.attr('id'), $this.attr('name'), $this.attr('kind'))
        });
        return set;
        }

        for(node in res_nodes) {
            var res_node = res_nodes[node];
            dia.addNode(res_node['name'],{node: res_node,render: renderer});
        }

        for(cr in res_connectors) {
        	var res_connector = res_connectors[cr];
        	dia.addEdge(res_connector['source'], res_connector['destination']);
        }

        var layouter = new Graph.Layout.Spring(dia);
        layouter.layout();
        if ($('div#dia-canvas').children().length > 0) {
        	$('div#dia-canvas').children().remove();
        }
        var renderer = new Graph.Renderer.Raphael('dia-canvas', dia, $('div#dia-canvas').width(), $('div#dia-canvas').height());
        renderer.draw();

    },

    search_activity: function(id, name, kind) {
        var self = this;
        this.rpc(
        '/base_diagram/diagram/get_activity',
        {
            'id': id,
            'name': name,
            'kind': kind,
            'active_model': this.active_model,
            'model': this.node
        },
        function(result) {
            self.add_edit_node(result)
        }
        )
    },

    add_edit_node: function(result) {
    	var self = this;
    	var id;
    	if(result)
			id = result.activity_id[0];
    	var action_manager = new openerp.base.ActionManager(this);
    	var dialog = new openerp.base.Dialog(this, {
            title : 'Activity',
            width: 800,
            height: 600,
            buttons : {
                Cancel : function() {
                    $(this).dialog('destroy');
                },
                Save : function() {
                    $(this).dialog('destroy');
                }
            }
        }).start().open();
    	action_manager.appendTo(dialog.$element);
    	action_manager.do_action({
            res_model : this.node,
            res_id: id,
            views : [[false, 'form']],
            type : 'ir.actions.act_window',
            auto_search : false,
            flags : {
    			search_view: false,
                sidebar : false,
                views_switcher : false,
                action_buttons : false
            }
        });
    },

    do_search: function(domains, contexts, groupbys) {
        var self = this;
        this.rpc('/base/session/eval_domain_and_context', {
            domains: domains,
            contexts: contexts,
            group_by_seq: groupbys
        }, function (results) {
            // TODO: handle non-empty results.group_by with read_group
            self.dataset.context = self.context = results.context;
            self.dataset.domain = self.domain = results.domain;
            self.dataset.read_slice(self.fields, 0, self.limit,function(events){
                self.schedule_events(events)
            });
        });
    },

    on_pager_action: function(action) {
    	switch (action) {
	        case 'first':
	            this.dataset.index = 0;
	            break;
	        case 'previous':
	            this.dataset.previous();
	            break;
	        case 'next':
	            this.dataset.next();
	            break;
	        case 'last':
	            this.dataset.index = this.dataset.ids.length - 1;
	            break;
    	}
	    this.dataset.read_index(_.keys(this.fields_view.fields), this.on_diagram_loaded);
	    this.do_update_pager();
    },

    do_update_pager: function(hide_index) {
        var $pager = this.$element.find('div.oe_diagram_pager');
        var index = hide_index ? '-' : this.dataset.index + 1;
        if(!this.dataset.count)
        	this.dataset.count = this.dataset.ids.length
        $pager.find('span.oe_pager_index').html(index);
        $pager.find('span.oe_pager_count').html(this.dataset.count);
    },

	do_show: function () {
        this.$element.show();
    },

    do_hide: function () {
        this.$element.hide();
    }
});
};

// vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax:
<|endoftext|>


<commit_before>const menus = require('./menus');
const tabs = require('./tabs');
const palette = require('./palette');
const commands = require('./commands');
const config = require('./config');
const plugins = require('./plugins');

const EventEmitter = require('events').EventEmitter;
const resolve = require('path').resolve;

function registerWindowButtonHandlers() {
  const BrowserWindow = require('remote').require('browser-window');

  document.querySelector('.titlebar-close').addEventListener('click', () =>{
    window.close();
  });

  document.querySelector('.titlebar-minimize').addEventListener('click', () =>{
    BrowserWindow.getFocusedWindow().minimize();
  });

  document.querySelector('.titlebar-fullscreen').addEventListener('click', () =>{
    const win = BrowserWindow.getFocusedWindow();
    win.setFullScreen(!win.isFullScreen());
  });
}

module.exports = Object.assign(new EventEmitter(), {
  name: 'termite',
  window: null,

  palette: palette,
  tabs: tabs,
  commands: commands,
  config: config,
  menus: menus,
  plugins: plugins,

  quit() {
    this.commands.execute('quit');
  },

  initRenderer() {
    this.commands.init(this);
    this.palette.init(this);
    this.tabs.init(this);
    this.config.init(this);
    this.menus.init(this);
    this.plugins.init(this);

    this.packages = {};
    this.packagesFolder = __dirname + '/../packages';

    this.commands.register('inject-js', code => {
      const script = document.createElement('script');
      script.textContent = code;
      document.body.appendChild(script);
    });

    this.commands.register('inject-script', path => {
      const script = document.createElement('script');
      script.src = path;
      document.body.appendChild(script);
    });

    registerWindowButtonHandlers();

    global.termite = this;

    this.plugins.load()
      .then(() =>
        this.emit('packages-init-done')
      );

  },

  start() {
    const window = require('electron-window');

    const appIcon = resolve(__dirname, '../../media/icon.png');

    this.window = window.createWindow({
      resizable: true,
      icon: appIcon,
      'accept-first-mouse': true,
      frame: false
    });

    this.window.showUrl(__dirname + '/../assets/index.html', ()=>{});
  }
});
<commit_msg>extrcted js commands<commit_after>const menus = require('./menus');
const tabs = require('./tabs');
const palette = require('./palette');
const commands = require('./commands');
const config = require('./config');
const plugins = require('./plugins');

const EventEmitter = require('events').EventEmitter;
const resolve = require('path').resolve;

function registerWindowButtonHandlers() {
  const BrowserWindow = require('remote').require('browser-window');

  document.querySelector('.titlebar-close').addEventListener('click', () =>{
    window.close();
  });

  document.querySelector('.titlebar-minimize').addEventListener('click', () =>{
    BrowserWindow.getFocusedWindow().minimize();
  });

  document.querySelector('.titlebar-fullscreen').addEventListener('click', () =>{
    const win = BrowserWindow.getFocusedWindow();
    win.setFullScreen(!win.isFullScreen());
  });
}

function registerJsCommands() {
  commands.register('inject-js', code => {
    const script = document.createElement('script');
    script.textContent = code;
    document.body.appendChild(script);
  });

  commands.register('inject-script', path => {
    const script = document.createElement('script');
    script.src = path;
    document.body.appendChild(script);
  });
}

module.exports = Object.assign(new EventEmitter(), {
  name: 'termite',
  window: null,

  palette: palette,
  tabs: tabs,
  commands: commands,
  config: config,
  menus: menus,
  plugins: plugins,

  quit() {
    this.commands.execute('quit');
  },

  initRenderer() {
    this.commands.init(this);
    this.palette.init(this);
    this.tabs.init(this);
    this.config.init(this);
    this.menus.init(this);
    this.plugins.init(this);

    this.packages = {};
    this.packagesFolder = __dirname + '/../packages';

    registerJsCommands();
    registerWindowButtonHandlers();

    global.termite = this;

    this.plugins.load()
      .then(() =>
        this.emit('packages-init-done')
      );
  },

  start() {
    const window = require('electron-window');

    const appIcon = resolve(__dirname, '../../media/icon.png');

    this.window = window.createWindow({
      resizable: true,
      icon: appIcon,
      'accept-first-mouse': true,
      frame: false
    });

    this.window.showUrl(__dirname + '/../assets/index.html', ()=>{});
  }
});
<|endoftext|>


<commit_before>import ApiSearch from '@/ApiService/ApiSearch'
import Vue from 'vue'
import { uuid } from 'vue-uuid'
import {
  API_STORE_SEARCH,
  API_VIEW_SEARCH,
  API_LIST_SEARCHES,
  API_EDIT_SEARCH,
  API_DELETE_SEARCH,
  FIELD_TYPE_MAP,
  FIELD_OPERATOR_TYPES,
  SEARCH_INSTANCE
} from '@/utils/search'

export default {
  namespaced: true,

  state: {
    exportId: '',
    filters: [],
    operators: {
      map: FIELD_TYPE_MAP,
      types: FIELD_OPERATOR_TYPES
    },
    savedSearch: SEARCH_INSTANCE,
    savedSearches: []
  },

  getters: {
    filtersGroup (state) {
      const result = {}
      for (var index in state.filters) {
        const filter = state.filters[index]
        if (!result.hasOwnProperty(filter.group)) {
          result[filter.group] = []
        }
        result[filter.group].push(filter)
      }

      return result
    },

    filtersFlat (state) {
      const result = {}
      for (var index in state.filters) {
        const filter = state.filters[index]
        result[filter.field] = filter
      }

      return result
    }
  },

  mutations: {
    aggregator (state, value) {
      state.savedSearch.content.saved.aggregator = value
    },
    criteriaCreate (state, payload) {
      const filter = state.filters.filter(filter => filter.field === payload.field)

      const guid = uuid.v4()

      const criteria = state.savedSearch.content.saved.criteria
      if (!criteria.hasOwnProperty(filter[0].field)) {
        Vue.set(criteria, filter[0].field, {})
      }

      Vue.set(criteria[filter[0].field], guid, {
        type: filter[0].type,
        operator: payload.operator !== '' ? payload.operator : state.operators.types[state.operators.map[filter[0].type]][0].text,
        value: payload.value !== '' ? payload.value : (filter[0].type === 'boolean' ? 0 : '')
      })
    },
    criteriaCopy (state, value) {
      const newGuid = uuid.v4()
      const criteria = state.savedSearch.content.saved.criteria

      for (const field in criteria) {
        for (const guid in criteria[field]) {
          if (value !== guid) {
            continue
          }

          const data = Object.assign({}, criteria[field][guid])

          Vue.set(criteria[field], newGuid, data)
        }
      }
    },
    criteriaRemove (state, value) {
      const criteria = state.savedSearch.content.saved.criteria

      for (const field in criteria) {
        for (const guid in criteria[field]) {
          if (value !== guid) {
            continue
          }

          Vue.delete(criteria[field], guid)

          if (Object.keys(criteria[field]).length === 0) {
            Vue.delete(criteria, field)
          }
        }
      }
    },
    criteriaOperator (state, payload) {
      Vue.set(state.savedSearch.content.saved.criteria[payload.field][payload.guid], 'operator', payload.value)
    },
    criteriaValue (state, { field, guid, value }) {
      Vue.set(state.savedSearch.content.saved.criteria[field][guid], 'value', value)
    },
    displayColumns (state, payload) {
      if (['add', 'remove'].indexOf(payload.action) === -1) {
        return
      }

      const displayColumns = state.savedSearch.content.saved.display_columns

      if (payload.action === 'add') {
        payload.available.map(function (column) {
          const found = state.filters.find(filter => filter.field === column)
          if (displayColumns.indexOf(column) === -1 && found !== undefined) {
            displayColumns.push(column)
          }
        })
      }

      if (payload.action === 'remove') {
        payload.display.map(function (column) {
          const index = displayColumns.indexOf(column)
          if (index > -1) {
            displayColumns.splice(index, 1)
          }
        })
      }
    },
    displayColumnsSort (state, payload) {
      if (['up', 'down'].indexOf(payload.direction) === -1) {
        return
      }

      const displayColumns = state.savedSearch.content.saved.display_columns
      const selection = 'up' === payload.direction ? payload.columns : payload.columns.reverse()
      let previous = -1
      selection.forEach(function (column) {
        const length = 'up' === payload.direction ? 0 : displayColumns.length - 1
        const index = displayColumns.indexOf(column)
        const start = index + ('up' === payload.direction ? - 1 : 1)

        if (length === index || start === previous) {
          previous = index

          return
        }

        displayColumns.splice(start, 0, displayColumns.splice(index, 1)[0])
      })
    },
    exportId (state, value) {
      state.exportId = value
    },
    filters (state, value) {
      state.filters = value
    },
    groupBy (state, value) {
      state.savedSearch.content.saved.group_by = value
    },
    name(state, value) {
      state.savedSearch.name = value
    },
    result (state, value) {
      state.result = value
    },
    savedSearches (state, value) {
      value.sort((a, b) => (a.name > b.name) ? -1 : 1)
      state.savedSearches = value
    },
    savedSearchId (state, value) {
      state.savedSearch.id = value
    },
    savedSearchModel (state, value) {
      state.savedSearch.model = value
    },
    savedSearchUserId (state, value) {
      state.savedSearch.user_id = value
    },
    sortByField (state, value) {
      state.savedSearch.content.saved.sort_by_field = value
    },
    sortByOrder (state, value) {
      state.savedSearch.content.saved.sort_by_order = value
    }
  },

  actions: {
    savedSearchCopy ({ commit, state, dispatch }, payload) {
      return ApiSearch
        .getSearch(API_VIEW_SEARCH, payload.id)
        .then(response => {
          const data = response.data.data
          delete data.id
          data.user_id = payload.user_id

          ApiSearch
            .addSearch(API_STORE_SEARCH, data)
            .then(resp => {
              dispatch('savedSearchesGet')
              dispatch('setNotification', {
                'type': 'info',
                'msg': 'Successfully copied the search'
              })
            })
        })
    },
    savedSearchDelete ({ commit, state, dispatch }, id) {
      return ApiSearch
        .deleteSearch(`${API_DELETE_SEARCH}/${id}`)
        .then(response => {
          dispatch('savedSearchesGet')
          dispatch('setNotification', {
            'type': 'info',
            'msg': 'Saved Search successfully removed'
          })
        })
    },
    savedSearchExport ({ commit, state }) {
      const data = state.savedSearch
      // this is treated as temporary saved search
      data.name = ''

      return ApiSearch
        .exportSearch(API_STORE_SEARCH, data)
        .then(response => {
          commit('exportId', response.data.data.id)
        })
    },
    savedSearchGet ({ commit, state, dispatch }, id) {
      return ApiSearch
        .getSearch(API_VIEW_SEARCH, id)
        .then(response => {
          const data = response.data.data
          commit('aggregator', data.content.saved.aggregator)
          commit('displayColumns', { action: 'add', available: data.content.saved.display_columns })
          if (data.content.saved.hasOwnProperty('group_by')) {
            commit('groupBy', data.content.saved.group_by)
          }
          commit('name', data.name)
          commit('savedSearchId', data.id)
          commit('savedSearchModel', data.model)
          commit('savedSearchUserId', data.user_id)
          commit('sortByField', data.content.saved.sort_by_field)
          commit('sortByOrder', data.content.saved.sort_by_order)

          if (data.content.saved.hasOwnProperty('criteria')) {
            const criteria = data.content.saved.criteria
            Object.keys(criteria).forEach((item) => {
              const index = Object.keys(criteria[item])[0]
              const filter = criteria[item][index]
              commit('criteriaCreate', { field: item, value: filter.value, operator: filter.operator })
            })
          }

          dispatch('setNotification', {
            'type': 'info',
            'msg': 'Successfully loaded search results'
          })
        })
    },
    savedSearchSave ({ commit, state, dispatch }) {
      const create = state.savedSearch.id === ''
      let url = API_STORE_SEARCH

      if (!create) {
        url = `${API_EDIT_SEARCH}/${state.savedSearch.id}`
      }

      if (create) {
        return ApiSearch
          .addSearch(url, state.savedSearch)
          .then(response => {
            commit('savedSearchId', response.data.data.id)
            dispatch('savedSearchesGet')
            dispatch('setNotification', {
              'type': 'info',
              'msg': 'Search successfully saved'
            })
          })
      } else {
        return ApiSearch
          .editSearch(url, state.savedSearch)
          .then(response => {
            commit('savedSearchId', response.data.data.id)
            dispatch('savedSearchesGet')
            dispatch('setNotification', {
              'type': 'info',
              'msg': 'Search successfully saved'
            })
          })
      }
    },
    savedSearchesGet ({ commit, state }) {
      return ApiSearch
        .getSearches(API_LIST_SEARCHES, {
          'model': state.savedSearch.model,
          'system': 0,
          'user_id': state.savedSearch.user_id
        })
        .then(response => {
          commit('savedSearches', response.data.data)
        })
    },
    setNotification ({ commit, state }, data) {
      Vue.notify({
        'group': 'SearchNotification',
        'type': data.type,
        'text': data.msg
      })
    }
  }
}
<commit_msg>Adjust check (task #10054)<commit_after>import ApiSearch from '@/ApiService/ApiSearch'
import Vue from 'vue'
import { uuid } from 'vue-uuid'
import {
  API_STORE_SEARCH,
  API_VIEW_SEARCH,
  API_LIST_SEARCHES,
  API_EDIT_SEARCH,
  API_DELETE_SEARCH,
  FIELD_TYPE_MAP,
  FIELD_OPERATOR_TYPES,
  SEARCH_INSTANCE
} from '@/utils/search'

export default {
  namespaced: true,

  state: {
    exportId: '',
    filters: [],
    operators: {
      map: FIELD_TYPE_MAP,
      types: FIELD_OPERATOR_TYPES
    },
    savedSearch: SEARCH_INSTANCE,
    savedSearches: []
  },

  getters: {
    filtersGroup (state) {
      const result = {}
      for (var index in state.filters) {
        const filter = state.filters[index]
        if (!result.hasOwnProperty(filter.group)) {
          result[filter.group] = []
        }
        result[filter.group].push(filter)
      }

      return result
    },

    filtersFlat (state) {
      const result = {}
      for (var index in state.filters) {
        const filter = state.filters[index]
        result[filter.field] = filter
      }

      return result
    }
  },

  mutations: {
    aggregator (state, value) {
      state.savedSearch.content.saved.aggregator = value
    },
    criteriaCreate (state, payload) {
      const filter = state.filters.filter(filter => filter.field === payload.field)

      const guid = uuid.v4()

      const criteria = state.savedSearch.content.saved.criteria
      if (!criteria.hasOwnProperty(filter[0].field)) {
        Vue.set(criteria, filter[0].field, {})
      }

      Vue.set(criteria[filter[0].field], guid, {
        type: filter[0].type,
        operator: payload.operator !== undefined ? payload.operator : state.operators.types[state.operators.map[filter[0].type]][0].text,
        value: payload.value !== '' ? payload.value : (filter[0].type === 'boolean' ? 0 : '')
      })
    },
    criteriaCopy (state, value) {
      const newGuid = uuid.v4()
      const criteria = state.savedSearch.content.saved.criteria

      for (const field in criteria) {
        for (const guid in criteria[field]) {
          if (value !== guid) {
            continue
          }

          const data = Object.assign({}, criteria[field][guid])

          Vue.set(criteria[field], newGuid, data)
        }
      }
    },
    criteriaRemove (state, value) {
      const criteria = state.savedSearch.content.saved.criteria

      for (const field in criteria) {
        for (const guid in criteria[field]) {
          if (value !== guid) {
            continue
          }

          Vue.delete(criteria[field], guid)

          if (Object.keys(criteria[field]).length === 0) {
            Vue.delete(criteria, field)
          }
        }
      }
    },
    criteriaOperator (state, payload) {
      Vue.set(state.savedSearch.content.saved.criteria[payload.field][payload.guid], 'operator', payload.value)
    },
    criteriaValue (state, { field, guid, value }) {
      Vue.set(state.savedSearch.content.saved.criteria[field][guid], 'value', value)
    },
    displayColumns (state, payload) {
      if (['add', 'remove'].indexOf(payload.action) === -1) {
        return
      }

      const displayColumns = state.savedSearch.content.saved.display_columns

      if (payload.action === 'add') {
        payload.available.map(function (column) {
          const found = state.filters.find(filter => filter.field === column)
          if (displayColumns.indexOf(column) === -1 && found !== undefined) {
            displayColumns.push(column)
          }
        })
      }

      if (payload.action === 'remove') {
        payload.display.map(function (column) {
          const index = displayColumns.indexOf(column)
          if (index > -1) {
            displayColumns.splice(index, 1)
          }
        })
      }
    },
    displayColumnsSort (state, payload) {
      if (['up', 'down'].indexOf(payload.direction) === -1) {
        return
      }

      const displayColumns = state.savedSearch.content.saved.display_columns
      const selection = 'up' === payload.direction ? payload.columns : payload.columns.reverse()
      let previous = -1
      selection.forEach(function (column) {
        const length = 'up' === payload.direction ? 0 : displayColumns.length - 1
        const index = displayColumns.indexOf(column)
        const start = index + ('up' === payload.direction ? - 1 : 1)

        if (length === index || start === previous) {
          previous = index

          return
        }

        displayColumns.splice(start, 0, displayColumns.splice(index, 1)[0])
      })
    },
    exportId (state, value) {
      state.exportId = value
    },
    filters (state, value) {
      state.filters = value
    },
    groupBy (state, value) {
      state.savedSearch.content.saved.group_by = value
    },
    name(state, value) {
      state.savedSearch.name = value
    },
    result (state, value) {
      state.result = value
    },
    savedSearches (state, value) {
      value.sort((a, b) => (a.name > b.name) ? -1 : 1)
      state.savedSearches = value
    },
    savedSearchId (state, value) {
      state.savedSearch.id = value
    },
    savedSearchModel (state, value) {
      state.savedSearch.model = value
    },
    savedSearchUserId (state, value) {
      state.savedSearch.user_id = value
    },
    sortByField (state, value) {
      state.savedSearch.content.saved.sort_by_field = value
    },
    sortByOrder (state, value) {
      state.savedSearch.content.saved.sort_by_order = value
    }
  },

  actions: {
    savedSearchCopy ({ commit, state, dispatch }, payload) {
      return ApiSearch
        .getSearch(API_VIEW_SEARCH, payload.id)
        .then(response => {
          const data = response.data.data
          delete data.id
          data.user_id = payload.user_id

          ApiSearch
            .addSearch(API_STORE_SEARCH, data)
            .then(resp => {
              dispatch('savedSearchesGet')
              dispatch('setNotification', {
                'type': 'info',
                'msg': 'Successfully copied the search'
              })
            })
        })
    },
    savedSearchDelete ({ commit, state, dispatch }, id) {
      return ApiSearch
        .deleteSearch(`${API_DELETE_SEARCH}/${id}`)
        .then(response => {
          dispatch('savedSearchesGet')
          dispatch('setNotification', {
            'type': 'info',
            'msg': 'Saved Search successfully removed'
          })
        })
    },
    savedSearchExport ({ commit, state }) {
      const data = state.savedSearch
      // this is treated as temporary saved search
      data.name = ''

      return ApiSearch
        .exportSearch(API_STORE_SEARCH, data)
        .then(response => {
          commit('exportId', response.data.data.id)
        })
    },
    savedSearchGet ({ commit, state, dispatch }, id) {
      return ApiSearch
        .getSearch(API_VIEW_SEARCH, id)
        .then(response => {
          const data = response.data.data
          commit('aggregator', data.content.saved.aggregator)
          commit('displayColumns', { action: 'add', available: data.content.saved.display_columns })
          if (data.content.saved.hasOwnProperty('group_by')) {
            commit('groupBy', data.content.saved.group_by)
          }
          commit('name', data.name)
          commit('savedSearchId', data.id)
          commit('savedSearchModel', data.model)
          commit('savedSearchUserId', data.user_id)
          commit('sortByField', data.content.saved.sort_by_field)
          commit('sortByOrder', data.content.saved.sort_by_order)

          if (data.content.saved.hasOwnProperty('criteria')) {
            const criteria = data.content.saved.criteria
            Object.keys(criteria).forEach((item) => {
              const index = Object.keys(criteria[item])[0]
              const filter = criteria[item][index]
              commit('criteriaCreate', { field: item, value: filter.value, operator: filter.operator })
            })
          }

          dispatch('setNotification', {
            'type': 'info',
            'msg': 'Successfully loaded search results'
          })
        })
    },
    savedSearchSave ({ commit, state, dispatch }) {
      const create = state.savedSearch.id === ''
      let url = API_STORE_SEARCH

      if (!create) {
        url = `${API_EDIT_SEARCH}/${state.savedSearch.id}`
      }

      if (create) {
        return ApiSearch
          .addSearch(url, state.savedSearch)
          .then(response => {
            commit('savedSearchId', response.data.data.id)
            dispatch('savedSearchesGet')
            dispatch('setNotification', {
              'type': 'info',
              'msg': 'Search successfully saved'
            })
          })
      } else {
        return ApiSearch
          .editSearch(url, state.savedSearch)
          .then(response => {
            commit('savedSearchId', response.data.data.id)
            dispatch('savedSearchesGet')
            dispatch('setNotification', {
              'type': 'info',
              'msg': 'Search successfully saved'
            })
          })
      }
    },
    savedSearchesGet ({ commit, state }) {
      return ApiSearch
        .getSearches(API_LIST_SEARCHES, {
          'model': state.savedSearch.model,
          'system': 0,
          'user_id': state.savedSearch.user_id
        })
        .then(response => {
          commit('savedSearches', response.data.data)
        })
    },
    setNotification ({ commit, state }, data) {
      Vue.notify({
        'group': 'SearchNotification',
        'type': data.type,
        'text': data.msg
      })
    }
  }
}
<|endoftext|>


<commit_before>import React from 'react';
import { Link } from 'react-router';
import { sparqlConnect } from 'sparql-connect';

/**
  * Builds the query that retrieves the details on a given organization.
  */
const queryBuilder = operation => `
  PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
  PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
  SELECT ?label ?seeAlso
  FROM <http://rdf.insee.fr/graphes/organisations>
  WHERE {
    <${operation}> skos:prefLabel ?label .
    FILTER (lang(?label) = 'fr')
    OPTIONAL { <${operation}> rdfs:seeAlso ?seeAlso . }
  }
`;

const connector = sparqlConnect(queryBuilder, {
  queryName: 'organizationDetails',
  params: ['organization'],
  singleResult: true
});

function OrganizationDetails({ label, seeAlso }) {
  return (

Organisation {label}

Voir :&nsbp;
        site web

  );
}

export default connector(OrganizationDetails);
<commit_msg>First shot at organization mother<commit_after>import React from 'react';
import { Link } from 'react-router';
import { sparqlConnect } from 'sparql-connect';

/**
  * Builds the query that retrieves the details on a given organization.
  */
const queryBuilder = operation => `
  PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
  PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
  PREFIX dcterms: <http://purl.org/dc/terms/>
  PREFIX org: <http://www.w3.org/ns/org#>
  SELECT ?label ?seeAlso ?mother
  FROM <http://rdf.insee.fr/graphes/organisations>
  WHERE {
    <${operation}> skos:prefLabel ?label .
    FILTER (lang(?label) = 'fr')
    OPTIONAL { <${operation}> rdfs:seeAlso ?seeAlso . }
    OPTIONAL { <${operation}> org:unitOf ?mother . }
  }
`;

const connector = sparqlConnect(queryBuilder, {
  queryName: 'organizationDetails',
  params: ['organization'],
  singleResult: true
});

function OrganizationDetails({ label, seeAlso, mother }) {
  console.log(mother);
  return (

Organisation {label}

Voir :&nsbp;
        site web

      {mother &&
{mother}
}

  );
}

export default connector(OrganizationDetails);
<|endoftext|>


<commit_before>odoo.define('pos_multi_session_restaurant', function(require){
    var screens = require('point_of_sale.screens');
    var models = require('point_of_sale.models');
    var multiprint = require('pos_restaurant.multiprint');
    var floors = require('pos_restaurant.floors');
    var core = require('web.core');
    var gui = require('point_of_sale.gui');
    var chrome = require('point_of_sale.chrome');
    var multi_session = require('pos_multi_session');

    var FloorScreenWidget;
    _.each(gui.Gui.prototype.screen_classes, function(o){
        if (o.name == 'floors'){
            FloorScreenWidget = o.widget;
            FloorScreenWidget.include({
                start: function () {
                    var self = this;
                    this._super();
                    this.pos.bind('change:orders-count-on-floor-screen', function () {
                        self.renderElement();
                    });
                }
            });
            return false;
        }
    });
    var _t = core._t;

    gui.Gui.prototype.screen_classes.filter(function(el) {
        return el.name == 'splitbill'
    })[0].widget.include({
        pay: function(order,neworder,splitlines){
            this._super(order,neworder,splitlines);
            neworder.save_to_db();
        }
    });

    screens.OrderWidget.include({
        update_summary: function(){
            var order = this.pos.get('selectedOrder');
            if (!order){
                return;
            }
            this._super();
        },
        remove_orderline: function(order_line){
            if (this.pos.get_order() && this.pos.get_order().get_orderlines().length === 0){
                this._super(order_line);
            }
            else {
                order_line.node.parentNode.removeChild(order_line.node);
            }
        }
    });

    var PosModelSuper = models.PosModel;
    models.PosModel = models.PosModel.extend({
        initialize: function(){
            var ms_model = {
                model: 'pos.multi_session',
                fields: ['name','floor_ids'],
                domain: null,
                loaded: function(self,floors){
                    self.multi_session_floors = floors;
            }};
            this.models.splice(
                1 + this.models.indexOf(_.find(this.models, function(model){
                    return model.model === 'pos.config';
                })), 0, ms_model);
            var floor_model = _.find(this.models, function(model){ return model.model === 'restaurant.floor'; });
            floor_model.domain = function(self, ms_model){
                var temporary = [['id','in',self.config.floor_ids]];
                if (self.config.multi_session_id){
                    var ms_floors = _.find(self.multi_session_floors, function(session){
                        return session.id === self.config.multi_session_id[0];
                    });
                    temporary = [['id','in', ms_floors.floor_ids]];
                }
                return temporary;
            };
            var self = this;
            PosModelSuper.prototype.initialize.apply(this, arguments);
            this.ready.then(function () {
                if (!self.config.multi_session_id){
                    return;
                }
                self.multi_session.floor_ids = self.multi_session_floors.floor_ids;
                self.config.floor_ids = self.multi_session.floor_ids;
                var remove_order_super = Object.getPrototypeOf(self.multi_session).remove_order;
                self.multi_session.remove_order = function(data) {
                    if (data.transfer) {
                        data.transfer = false;
                        return;
                    } else {
                        remove_order_super.apply(self.multi_session, arguments);
                    }
                 };
            });
        },
        add_new_order: function(){
            var self = this;
            PosModelSuper.prototype.add_new_order.apply(this, arguments);
            if (this.multi_session){
                var current_order = this.get_order();
                current_order.ms_update();
                current_order.save_to_db();
            }
        },
        ms_create_order: function(options){
            var self = this;
            var order = PosModelSuper.prototype.ms_create_order.apply(this, arguments);
            if (options.data.table_id) {
                order.table = self.tables_by_id[options.data.table_id];
                order.customer_count = options.data.customer_count;
                order.save_to_db();
            }
            return order;
        },
        ms_on_update: function(message, sync_all){
            var self = this;
            var data = message.data || {};
            var order = false;
            var old_order = this.get_order();

            if (data.uid){
                order = this.get('orders').find(function(order){
                    return order.uid == data.uid;
                });
            }
            if (order && order.table.id != data.table_id) {
                order.transfer = true;
                order.destroy({'reason': 'abandon'});
            }
            PosModelSuper.prototype.ms_on_update.apply(this, arguments);
            if ((order && old_order && old_order.uid != order.uid) || (old_order == null)) {
                this.set('selectedOrder',old_order);
            }
            this.gui.screen_instances.floors.renderElement();
        },
        ms_do_update: function(order, data){
            PosModelSuper.prototype.ms_do_update.apply(this, arguments);
            if (order) {
                order.set_customer_count(data.customer_count, true);
                order.saved_resume = data.multiprint_resume;
                order.trigger('change');
                this.gui.screen_instances.floors.renderElement();
            }
        },
        ms_on_add_order: function(current_order){
            if (!current_order){
                this.trigger('change:orders-count-on-floor-screen');
            }else{
                PosModelSuper.prototype.ms_on_add_order.apply(this, arguments);
            }
        },
        on_removed_order: function(removed_order, index, reason){
            PosModelSuper.prototype.on_removed_order.apply(this, arguments);
            this.trigger('change:orders-count-on-floor-screen');
        },
        // changes the current table.
        set_table: function(table) {
            var self = this;
            if (table && this.order_to_transfer_to_different_table) {
                this.order_to_transfer_to_different_table.table = table;
                this.order_to_transfer_to_different_table.ms_update();
                this.order_to_transfer_to_different_table = null;
                // set this table
                this.set_table(table);
            } else {
                PosModelSuper.prototype.set_table.apply(this, arguments);
            }
        }
    });

    var OrderSuper = models.Order;
    models.Order = models.Order.extend({
        set_customer_count: function (count, skip_ms_update) {
            OrderSuper.prototype.set_customer_count.apply(this, arguments);
            if (!skip_ms_update) {
                this.ms_update();
            }
        },
        do_ms_remove_order: function(){
            if (this.transfer) {
                this.pos.multi_session.remove_order({
                    'uid': this.uid,
                    'revision_ID': this.revision_ID,
                    'transfer': this.transfer
                });
            } else {
                OrderSuper.prototype.do_ms_remove_order.apply(this, arguments);
            }
        },
    });

    var OrderlineSuper = models.Orderline;
    models.Orderline = models.Orderline.extend({
        get_line_diff_hash: function(){
            if (this.get_note()) {
                return this.uid + '|' + this.get_note();
            } else {
                return '' + this.uid;
            }
            OrderlineSuper.prototype.get_line_diff_hash.apply(this, arguments);
        },
        /*  There is no need to check the presence of super method.
            Because pos_multi_session_restaurant is loaded later than pos_multi_session.
        */
        apply_ms_data: function(data) {
            if(data.mp_dirty !== undefined){
                this.set_dirty(data.mp_dirty);
            }
            if(data.mp_skip !== undefined){
                this.set_skip(data.mp_skip);
            }
            if(data.note !== undefined){
                this.set_note(data.note);
            }
            OrderlineSuper.prototype.apply_ms_data.apply(this, arguments);
        },
    });
});
<commit_msg>Revert "[FIX] sync with pos_multi_session"<commit_after>odoo.define('pos_multi_session_restaurant', function(require){
    var screens = require('point_of_sale.screens');
    var models = require('point_of_sale.models');
    var multiprint = require('pos_restaurant.multiprint');
    var floors = require('pos_restaurant.floors');
    var core = require('web.core');
    var gui = require('point_of_sale.gui');
    var chrome = require('point_of_sale.chrome');
    var multi_session = require('pos_multi_session');

    var FloorScreenWidget;
    _.each(gui.Gui.prototype.screen_classes, function(o){
        if (o.name == 'floors'){
            FloorScreenWidget = o.widget;
            FloorScreenWidget.include({
                start: function () {
                    var self = this;
                    this._super();
                    this.pos.bind('change:orders-count-on-floor-screen', function () {
                        self.renderElement();
                    });
                }
            });
            return false;
        }
    });
    var _t = core._t;

    gui.Gui.prototype.screen_classes.filter(function(el) {
        return el.name == 'splitbill'
    })[0].widget.include({
        pay: function(order,neworder,splitlines){
            this._super(order,neworder,splitlines);
            neworder.save_to_db();
        }
    });

    screens.OrderWidget.include({
        update_summary: function(){
            var order = this.pos.get('selectedOrder');
            if (!order){
                return;
            }
            this._super();
        },
        remove_orderline: function(order_line){
            if (this.pos.get_order() && this.pos.get_order().get_orderlines().length === 0){
                this._super(order_line);
            }
            else {
                order_line.node.parentNode.removeChild(order_line.node);
            }
        }
    });

    var PosModelSuper = models.PosModel;
    models.PosModel = models.PosModel.extend({
        initialize: function(){
            var ms_model = {
                model: 'pos.multi_session',
                fields: ['name','floor_ids'],
                domain: null,
                loaded: function(self,floors){
                    self.multi_session_floors = floors;
            }};
            this.models.splice(
                1 + this.models.indexOf(_.find(this.models, function(model){
                    return model.model === 'pos.config';
                })), 0, ms_model);
            var floor_model = _.find(this.models, function(model){ return model.model === 'restaurant.floor'; });
            floor_model.domain = function(self, ms_model){
                var temporary = [['id','in',self.config.floor_ids]];
                if (self.config.multi_session_id){
                    var ms_floors = _.find(self.multi_session_floors, function(session){
                        return session.id === self.config.multi_session_id[0];
                    });
                    temporary = [['id','in', ms_floors.floor_ids]];
                }
                return temporary;
            };
            var self = this;
            PosModelSuper.prototype.initialize.apply(this, arguments);
            this.ready.then(function () {
                if (!self.config.multi_session_id){
                    return;
                }
                self.multi_session.floor_ids = self.multi_session_floors.floor_ids;
                self.config.floor_ids = self.multi_session.floor_ids;
                var remove_order_super = Object.getPrototypeOf(self.multi_session).remove_order;
                self.multi_session.remove_order = function(data) {
                    if (data.transfer) {
                        data.transfer = false;
                        return;
                    } else {
                        remove_order_super.apply(self.multi_session, arguments);
                    }
                 };
            });
        },
        add_new_order: function(){
            var self = this;
            PosModelSuper.prototype.add_new_order.apply(this, arguments);
            if (this.multi_session){
                var current_order = this.get_order();
                current_order.ms_update();
                current_order.save_to_db();
            }
        },
        ms_create_order: function(options){
            var self = this;
            var order = PosModelSuper.prototype.ms_create_order.apply(this, arguments);
            if (options.data.table_id) {
                order.table = self.tables_by_id[options.data.table_id];
                order.customer_count = options.data.customer_count;
                order.save_to_db();
            }
            return order;
        },
        ms_on_update: function(message, sync_all){
            var self = this;
            var data = message.data || {};
            var order = false;
            var old_order = this.get_order();

            if (data.uid){
                order = this.get('orders').find(function(order){
                    return order.uid == data.uid;
                });
            }
            if (order && order.table.id != data.table_id) {
                order.transfer = true;
                order.destroy({'reason': 'abandon'});
            }
            PosModelSuper.prototype.ms_on_update.apply(this, arguments);
            if ((order && old_order && old_order.uid != order.uid) || (old_order == null)) {
                this.set('selectedOrder',old_order);
            }
            this.gui.screen_instances.floors.renderElement();
        },
        ms_do_update: function(order, data){
            PosModelSuper.prototype.ms_do_update.apply(this, arguments);
            if (order) {
                order.set_customer_count(data.customer_count, true);
                order.saved_resume = data.multiprint_resume;
                order.trigger('change');
                this.gui.screen_instances.floors.renderElement();
            }
        },
        ms_on_add_order: function(current_order){
            if (!current_order){
                this.trigger('change:orders-count-on-floor-screen');
            }else{
                PosModelSuper.prototype.ms_on_add_order.apply(this, arguments);
            }
        },
        on_removed_order: function(removed_order, index, reason){
            PosModelSuper.prototype.on_removed_order.apply(this, arguments);
            this.trigger('change:orders-count-on-floor-screen');
        },
        // changes the current table.
        set_table: function(table) {
            var self = this;
            if (table && this.order_to_transfer_to_different_table) {
                this.order_to_transfer_to_different_table.table = table;
                this.order_to_transfer_to_different_table.ms_update();
                this.order_to_transfer_to_different_table = null;
                // set this table
                this.set_table(table);
            } else {
                PosModelSuper.prototype.set_table.apply(this, arguments);
            }
        }
    });

    var OrderSuper = models.Order;
    models.Order = models.Order.extend({
        set_customer_count: function (count, skip_ms_update) {
            OrderSuper.prototype.set_customer_count.apply(this, arguments);
            if (!skip_ms_update) {
                this.ms_update();
            }
        },
        do_ms_remove_order: function(){
            if (this.transfer) {
                this.pos.multi_session.remove_order({
                    'uid': this.uid,
                    'revision_ID': this.revision_ID,
                    'transfer': this.transfer
                });
            } else {
                OrderSuper.prototype.do_ms_remove_order.apply(this, arguments);
            }
        },
    });

    var OrderlineSuper = models.Orderline;
    models.Orderline = models.Orderline.extend({
        get_line_diff_hash: function(){
            if (this.get_note()) {
                return this.uid + '|' + this.get_note();
            } else {
                return '' + this.uid;
            }
        },
        /*  There is no need to check the presence of super method.
            Because pos_multi_session_restaurant is loaded later than pos_multi_session.
        */
        apply_ms_data: function(data) {
            if(data.mp_dirty !== undefined){
                this.set_dirty(data.mp_dirty);
            }
            if(data.mp_skip !== undefined){
                this.set_skip(data.mp_skip);
            }
            if(data.note !== undefined){
                this.set_note(data.note);
            }
            OrderlineSuper.prototype.apply_ms_data.apply(this, arguments);
        },
    });
});
<|endoftext|>


<commit_before>// the http server.
// Runs in the cluster worker processes.
//
// This is the only module that should create any
// long-lived things that might keep the event loop
// open indefinitely.  When the server closes, they
// should all be closed so that we can do a normal
// exit.

var cluster = require("cluster")
if (cluster.isMaster) {
  throw new Error("should only be invoked as cluster worker")
}

var config = require("./config.js")
, http = require("http")
, https = require("https")
, site = require("./site.js")
, server
, RedSess = require('redsess')
, bunyan = require('bunyan')

config.log.worker = cluster.worker.uniqueID
var logger = bunyan.createLogger(config.log)

RedSess.createClient(config.redis)

if (config.https) {
  server = https.createServer(config.https, site)
} else {
  server = http.createServer(site)
}

server.listen(config.port, function () {
  logger.info("Listening on %d", config.port)
})

server.on('close', function () {
  RedSess.close()
  logger.info('Worker closing')
})
<commit_msg>Use bunyan instead of console in workers<commit_after>// the http server.
// Runs in the cluster worker processes.
//
// This is the only module that should create any
// long-lived things that might keep the event loop
// open indefinitely.  When the server closes, they
// should all be closed so that we can do a normal
// exit.

var cluster = require("cluster")
if (cluster.isMaster) {
  throw new Error("should only be invoked as cluster worker")
}

var config = require("./config.js")
, http = require("http")
, https = require("https")
, site = require("./site.js")
, server
, RedSess = require('redsess')
, bunyan = require('bunyan')

config.log.worker = cluster.worker.uniqueID
var logger = bunyan.createLogger(config.log)

console.error = logger.info.bind(logger)
console.log = logger.info.bind(logger)

RedSess.createClient(config.redis)

if (config.https) {
  server = https.createServer(config.https, site)
} else {
  server = http.createServer(site)
}

server.listen(config.port, function () {
  logger.info("Listening on %d", config.port)
})

server.on('close', function () {
  RedSess.close()
  logger.info('Worker closing')
})
<|endoftext|>


<commit_before><commit_msg>Fix bug in ThreeModel remove<commit_after><|endoftext|>


<commit_before>#!/usr/bin/env node

import path from 'path';
import program from 'commander';
import shelljs from 'shelljs';
import Server from '../server';

program
  .option('-h, --host <host>', 'host to listen on')
  .option('-p, --port <port>', 'port to listen on')
  .option('--haul <configFile>', 'use haul with config file')
  .option('-s, --secured', 'whether server is running on https')
  .option('-c, --config-dir [dir-name]', 'storybook config directory')
  .option('-e, --environment [environment]', 'DEVELOPMENT/PRODUCTION environment for webpack')
  .option('-r, --reset-cache', 'reset react native packager')
  .option('--skip-packager', 'run only storybook server')
  .option('-i, --manual-id', 'allow multiple users to work with same storybook')
  .option('--smoke-test', 'Exit after successful start')
  .option('--packager-port <packagerPort>', 'Custom packager port')
  .parse(process.argv);

const projectDir = path.resolve();
const configDir = path.resolve(program.configDir || './storybook');
const listenAddr = [program.port];
if (program.host) {
  listenAddr.push(program.host);
}

const server = new Server({
  projectDir,
  configDir,
  environment: program.environment,
  manualId: program.manualId,
  secured: program.secured,
});

server.listen(...listenAddr, err => {
  if (err) {
    throw err;
  }
  const address = `http://${program.host || 'localhost'}:${program.port}/`;
  console.info(`\nReact Native Storybook started on => ${address}\n`); // eslint-disable-line no-console
  if (program.smokeTest) {
    process.exit(0);
  }
});

if (!program.skipPackager) {
  let symlinks = [];

  try {
    const findSymlinksPaths = require('react-native/local-cli/util/findSymlinksPaths'); // eslint-disable-line global-require
    symlinks = findSymlinksPaths(path.join(projectDir, 'node_modules'), [projectDir]);
  } catch (e) {
    console.warn(`Unable to load findSymlinksPaths: ${e.message}`);
  }

  const projectRoots = (configDir === projectDir ? [configDir] : [configDir, projectDir]).concat(
    symlinks
  );

  let cliCommand = 'node node_modules/react-native/local-cli/cli.js start';
  if (program.haul) {
    cliCommand = `node node_modules/.bin/haul start --config ${program.haul} --platform all`;
  }
  // RN packager
  shelljs.exec(
    [
      cliCommand,
      `--projectRoots ${projectRoots.join(',')}`,
      `--root ${projectDir}`,
      program.resetCache && '--reset-cache',
      program.packagerPort && `--port=${program.packagerPort}`,
    ]
      .filter(x => x)
      .join(' '),
    { async: true }
  );
}
<commit_msg>Add two additional CLI commands to storybook CLI<commit_after>#!/usr/bin/env node

import path from 'path';
import program from 'commander';
import shelljs from 'shelljs';
import Server from '../server';

program
  .option('-h, --host <host>', 'host to listen on')
  .option('-p, --port <port>', 'port to listen on')
  .option('--haul <configFile>', 'use haul with config file')
  .option('-s, --secured', 'whether server is running on https')
  .option('-c, --config-dir [dir-name]', 'storybook config directory')
  .option('-e, --environment [environment]', 'DEVELOPMENT/PRODUCTION environment for webpack')
  .option('-r, --reset-cache', 'reset react native packager')
  .option('--skip-packager', 'run only storybook server')
  .option('-i, --manual-id', 'allow multiple users to work with same storybook')
  .option('--smoke-test', 'Exit after successful start')
  .option('--packager-port <packagerPort>', 'Custom packager port')
  .option('--root [root]', 'Add additional root(s) to be used by the packager in this project')
  .option('--projectRoots [projectRoots]', 'Override the root(s) to be used by the packager')
  .parse(process.argv);

const projectDir = path.resolve();
const configDir = path.resolve(program.configDir || './storybook');
const listenAddr = [program.port];
if (program.host) {
  listenAddr.push(program.host);
}

const server = new Server({
  projectDir,
  configDir,
  environment: program.environment,
  manualId: program.manualId,
  secured: program.secured,
});

server.listen(...listenAddr, err => {
  if (err) {
    throw err;
  }
  const address = `http://${program.host || 'localhost'}:${program.port}/`;
  console.info(`\nReact Native Storybook started on => ${address}\n`); // eslint-disable-line no-console
  if (program.smokeTest) {
    process.exit(0);
  }
});

if (!program.skipPackager) {
  let symlinks = [];

  let roots = [projectDir];

  if (program.root) {
    roots = roots.concat(program.root.split(',').map(root => path.resolve(root)));
  }

  try {
    const findSymlinksPaths = require('react-native/local-cli/util/findSymlinksPaths'); // eslint-disable-line global-require
    symlinks = findSymlinksPaths(path.join(projectDir, 'node_modules'), [projectDir]);
  } catch (e) {
    console.warn(`Unable to load findSymlinksPaths: ${e.message}`);
  }

  let projectRoots = (configDir === projectDir ? [configDir] : [configDir, projectDir]).concat(
    symlinks
  );

  if (program.projectRoots) {
    projectRoots = projectRoots.concat(
      program.projectRoots.split(',').map(root => path.resolve(root))
    );
  }

  let cliCommand = 'node node_modules/react-native/local-cli/cli.js start';
  if (program.haul) {
    cliCommand = `node node_modules/.bin/haul start --config ${program.haul} --platform all`;
  }
  // RN packager
  shelljs.exec(
    [
      cliCommand,
      `--projectRoots ${projectRoots.join(',')}`,
      `--root ${roots.join(',')}`,
      program.resetCache && '--reset-cache',
      program.packagerPort && `--port=${program.packagerPort}`,
    ]
      .filter(x => x)
      .join(' '),
    { async: true }
  );
}
<|endoftext|>


<commit_before>const Helper = require('../../shared');
// cec types
// node-cec/lib/lib/cectypes.js
class CECcontroller extends Helper {
	// -------------------------------------------------------------------------- //
	// Example: basic.js
	// For more cec-events: http://www.cec-o-matic.com/
	// -------------------------------------------------------------------------- //
	constructor(){
		super('cec')
		const nodecec = require('node-cec');
		const NodeCec = nodecec.NodeCec;

		this.cectypes = nodecec.CEC;
		this.cec = new NodeCec( 'node-cec-monitor' );
		this.client;
		this.status = {
			on: false,
			source: 0,
		}

		// -------------------------------------------------------------------------- //
		//- CEC EVENT HANDLING
		this.cec.once( 'ready', (client)=>this.onReady(client));
		this.initBind();

		// -------------------------------------------------------------------------- //
		// -m  = start in monitor-mode
		// -d8 = set log level to 8 (=TRAFFIC) (-d 8)
		// -br = logical address set to `recording device`
		this.cec.start('cec-client', '-m', '-d', '8', '-b', 'r')
	}

	// -------------------------------------------------------------------------- //
	//- KILL CEC-CLIENT PROCESS ON EXIT
	killOnExit(){
		process.on('SIGINT', () =>this.killCec());
	}

	killCec(){
		if ( this.cec != null ) {
		  this.cec.stop();
		}
		process.exit();
	}

	onReady(client){
		this.log( ' -- READY -- ' );
		this.client = client;
		this.client.sendCommand( 0xf0, this.cectypes.Opcode.GIVE_DEVICE_POWER_STATUS );
	}

	initBind(){
		this.cec.on('REPORT_POWER_STATUS', (packet, status) => this.powerStatusCallback(packet, status));
		this.cec.on('ACTIVE_SOURCE', (packet, source) => this.powerStatusCallback(packet, source));
		this.cec.on('ROUTING_CHANGE', (packet, fromSource, toSource)=>this.emit('routeChange', fromSource, toSource));
	}

	powerStatusCallback(packet, status){
		this.log(status)
		var keys = Object.keys( this.cectypes.PowerStatus );

		for (var i = keys.length - 1; i >= 0; i--) {
			if (this.cectypes.PowerStatus[keys[i]] == status) {
				// this.status.on = (keys[i] == 'ON')?  true : false;
				break;
			}
		}
	}
}
module.exports = new CECcontroller();<commit_msg>simplier power check<commit_after>const Helper = require('../../shared');
// cec types
// node-cec/lib/lib/cectypes.js
class CECcontroller extends Helper {
	// -------------------------------------------------------------------------- //
	// Example: basic.js
	// For more cec-events: http://www.cec-o-matic.com/
	// -------------------------------------------------------------------------- //
	constructor(){
		super('cec')
		const nodecec = require('node-cec');
		const NodeCec = nodecec.NodeCec;

		this.cectypes = nodecec.CEC;
		this.cec = new NodeCec( 'node-cec-monitor' );
		this.client;
		this.status = {
			on: false,
			source: 0,
		}

		// -------------------------------------------------------------------------- //
		//- CEC EVENT HANDLING
		this.cec.once( 'ready', (client)=>this.onReady(client));
		this.initBind();

		// -------------------------------------------------------------------------- //
		// -m  = start in monitor-mode
		// -d8 = set log level to 8 (=TRAFFIC) (-d 8)
		// -br = logical address set to `recording device`
		this.cec.start('cec-client', '-m', '-d', '8', '-b', 'r')
	}

	// -------------------------------------------------------------------------- //
	//- KILL CEC-CLIENT PROCESS ON EXIT
	killOnExit(){
		process.on('SIGINT', () =>this.killCec());
	}

	killCec(){
		if ( this.cec != null ) {
		  this.cec.stop();
		}
		process.exit();
	}

	onReady(client){
		this.log( ' -- READY -- ' );
		this.client = client;
		this.client.sendCommand( 0xf0, this.cectypes.Opcode.GIVE_DEVICE_POWER_STATUS );
	}

	initBind(){
		this.cec.on('REPORT_POWER_STATUS', (packet, status) => this.powerStatusCallback(packet, status));
		this.cec.on('ACTIVE_SOURCE', (packet, source) => this.powerStatusCallback(packet, source));
		this.cec.on('ROUTING_CHANGE', (packet, fromSource, toSource)=>this.emit('routeChange', fromSource, toSource));
	}

	powerStatusCallback(packet, status){
		this.status.on = (status);
	}
}
module.exports = new CECcontroller();<|endoftext|>


<commit_before>var game = (function () {
  'use strict';

  function getInitialState () {
    return {
      paddles: [0, 0],
      score: [0, 0],
      ball: {x:0, y:0, vx:0.03, vy:0.025}
    };
  }

  function getDefaultInput () {
    return {
      paddle: 0
    }
  }

  // paddle 0 is top, 1 is bottom
  // paddle y positions are -0.9 and 0.9
  // paddle widths are 0.1
  //
  function constrainPaddles (paddles) {
    for (var i = 0; i < paddles.length; ++i) {
      if (paddles[i] < -0.9) paddles[i] = -0.9;
      if (paddles[i] >  0.9) paddles[i] =  0.9;
    }
  }

  function stepper (inputs, state)
  {
    if (inputs.length < 2) return state;

    var ns = {
      paddles: [
        state.paddles[0] + 0.05*inputs[0].paddle,
        state.paddles[1] + 0.05*inputs[1].paddle
      ],
      score: state.score.slice(),
      ball: {
         x: state.ball.x + state.ball.vx,
         y: state.ball.y + state.ball.vy,
        vx: state.ball.vx,
        vy: state.ball.vy
      }
    };

    if (ns.ball.x < -1) ns.ball.vx =  Math.abs (ns.ball.vx);
    if (ns.ball.x >  1) ns.ball.vx = -Math.abs (ns.ball.vx);

    constrainPaddles (ns.paddles);

    var scored = false;
    if (ns.ball.y < -1) {
        ns.score[0]++;
        scored = true;
    }
    else if (ns.ball.y > 1) {
        ns.score[1]++;
        scored = true;
    }
    if (scored) {
        ns.ball.x = ns.ball.y = 0;
    }

    if (ns.ball.vy > 0 && state.ball.y < 0.9 && ns.ball.y >= 0.9) {
        var dx = ns.ball.x - ns.paddles[1];
        if (Math.abs (dx) < 0.1) {
            ns.ball.vx = 0.05*(dx/0.1);
            ns.ball.vy = -Math.abs (ns.ball.vy);
        }
    }
    else if (ns.ball.vy < 0 && state.ball.y > -0.9 && ns.ball.y <= -0.9) {
        var dx = ns.ball.x - ns.paddles[0];
        if (Math.abs (dx) < 0.1) {
            ns.ball.vx = 0.05*(dx/0.1);
            ns.ball.vy = Math.abs (ns.ball.vy);
        }
    }

    return ns;
  }

  return {
    init: getInitialState,
    defaultInput: getDefaultInput,
    step: stepper,
    dt: 33,
    players: 2
  };
})();

if (typeof module !== 'undefined') module.exports = game;

<commit_msg>Style fix<commit_after>var game = (function () {
  'use strict';

  function getInitialState () {
    return {
      paddles: [0, 0],
      score: [0, 0],
      ball: {x:0, y:0, vx:0.03, vy:0.025}
    };
  }

  function getDefaultInput () {
    return {
      paddle: 0
    }
  }

  // paddle 0 is top, 1 is bottom
  // paddle y positions are -0.9 and 0.9
  // paddle widths are 0.1
  //
  function constrainPaddles (paddles) {
    for (var i = 0; i < paddles.length; ++i) {
      if (paddles[i] < -0.9) paddles[i] = -0.9;
      if (paddles[i] >  0.9) paddles[i] =  0.9;
    }
  }

  function stepper (inputs, state)
  {
    if (inputs.length < 2) return state;

    var ns = {
      paddles: [
        state.paddles[0] + 0.05*inputs[0].paddle,
        state.paddles[1] + 0.05*inputs[1].paddle
      ],
      score: state.score.slice(),
      ball: {
         x: state.ball.x + state.ball.vx,
         y: state.ball.y + state.ball.vy,
        vx: state.ball.vx,
        vy: state.ball.vy
      }
    };

    if (ns.ball.x < -1) ns.ball.vx =  Math.abs (ns.ball.vx);
    if (ns.ball.x >  1) ns.ball.vx = -Math.abs (ns.ball.vx);

    constrainPaddles (ns.paddles);

    var scored = false;
    if (ns.ball.y < -1) {
      ns.score[0]++;
      scored = true;
    }
    else if (ns.ball.y > 1) {
      ns.score[1]++;
      scored = true;
    }
    if (scored) {
      ns.ball.x = ns.ball.y = 0;
    }

    if (ns.ball.vy > 0 && state.ball.y < 0.9 && ns.ball.y >= 0.9) {
      var dx = ns.ball.x - ns.paddles[1];
      if (Math.abs (dx) < 0.1) {
        ns.ball.vx = 0.05*(dx/0.1);
        ns.ball.vy = -Math.abs (ns.ball.vy);
      }
    }
    else if (ns.ball.vy < 0 && state.ball.y > -0.9 && ns.ball.y <= -0.9) {
      var dx = ns.ball.x - ns.paddles[0];
      if (Math.abs (dx) < 0.1) {
        ns.ball.vx = 0.05*(dx/0.1);
        ns.ball.vy = Math.abs (ns.ball.vy);
      }
    }

    return ns;
  }

  return {
    init: getInitialState,
    defaultInput: getDefaultInput,
    step: stepper,
    dt: 33,
    players: 2
  };
})();

if (typeof module !== 'undefined') module.exports = game;

<|endoftext|>


<commit_before>/*
This file is part of Archivematica.

Copyright 2010-2013 Artefactual Systems Inc. <http://artefactual.com>

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

Archivematica 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 General Public License for more details.

You should have received a copy of the GNU General Public License
along with Archivematica.  If not, see <http://www.gnu.org/licenses/>.
*/

function selectField(name) {
  if (name == 'transferMetadataOther') {
    $('#aip-search-query-other-field-name').show('fade', {}, 250);
  } else {
    $('#aip-search-query-other-field-name').hide('fade', {}, 250);
  }
}

$(document).ready(function() {

  // create new form instance, providing a single row of default data
  var search = new advancedSearch.AdvancedSearchView({
    el: $('#search_form_container'),
//    allowAdd: false,
    rowTemplate: {
      'op': '',
      'query': '',
      'field': '',
      'fieldName': '',
      'type': 'term'
    },
    'deleteHandleHtml': '',
    'addHandleHtml': 'Add New'
  });

  // define op field
  var opAttributes = {
    title: 'boolean operator',
    class: 'search_op_selector'
  }
  search.addSelect('op', opAttributes, {
    'or': 'or',
    'and': 'and',
    'not': 'not'
  });

  // define query field
  search.addInput('query', {title: 'search query', 'class': 'aip-search-query-input'});

  // default field name field
  search.addSelect('field', {title: 'field name', onchange: 'selectField(this.value)'}, {
    '': 'Any',
    'FILEUUID': 'File UUID',
    'filePath': 'File path',
    'fileExtension': 'File extension',
    'AIPUUID': 'AIP UUID',
    'sipName': 'AIP name',
    'isPartOf': 'Part of AIC',
    'AICID': 'AIC Identifier',
    'transferMetadata': 'Transfer metadata',
    'transferMetadataOther': 'Transfer metadata (other)',
  });

  // "Other" field name, when selecting "transfer metadata (other)"
  search.addInput('fieldName', {title: 'other field name', 'class': 'aip-search-query-input', 'id': 'aip-search-query-other-field-name'});

  // default field name field
  search.addSelect('type', {title: 'query type'}, {
    'term': 'Keyword',
    'string': 'Phrase',
    'range': 'Date range'
  });

  // don't show first op field
  search.fieldVisibilityCheck = function(rowIndex, fieldName) {
    return rowIndex > 0 || fieldName != 'op';
  };

  // override default search state if URL parameters set
  if (search.urlParamsToData()) {
    search.rows = search.urlParamsToData();
  }

  search.render();

  // Ensure the select field name field is hidden/displayed as appropriate
  selectField($('.advanced_search_form_field_field > select')[0].value);

  function aipSearchSubmit() {
    var destination = '/archival-storage/search/' + '?' + search.toUrlParams();
    if($('#id_show_files').is(':checked')) {
      destination += '&filemode=true';
    }
    if($('#id_show_aics').is(':checked')) {
      destination += '&show_aics=true';
    }
    window.location = destination;
  }

  // submit logic
  $('#search_submit').click(function() {
    aipSearchSubmit();
  });

  $('#search_form').submit(function() {
    aipSearchSubmit();
    return false;
  });

  $('.aip-search-query-input').keypress(function (e) {
    if (e.which == 13) {  // Return key
      aipSearchSubmit();
      return false;
    }
  });
});
<commit_msg>Archival storage JS: hide/show correct field name box<commit_after>/*
This file is part of Archivematica.

Copyright 2010-2013 Artefactual Systems Inc. <http://artefactual.com>

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

Archivematica 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 General Public License for more details.

You should have received a copy of the GNU General Public License
along with Archivematica.  If not, see <http://www.gnu.org/licenses/>.
*/

function selectField(el) {
  var target = $(el.parentNode.nextSibling.firstChild);
  if (el.value == 'transferMetadataOther') {
    target.show('fade', {}, 250);
  } else {
    target.hide('fade', {}, 250);
  }
}

$(document).ready(function() {

  // create new form instance, providing a single row of default data
  var search = new advancedSearch.AdvancedSearchView({
    el: $('#search_form_container'),
//    allowAdd: false,
    rowTemplate: {
      'op': '',
      'query': '',
      'field': '',
      'fieldName': '',
      'type': 'term'
    },
    'deleteHandleHtml': '',
    'addHandleHtml': 'Add New'
  });

  // define op field
  var opAttributes = {
    title: 'boolean operator',
    class: 'search_op_selector'
  }
  search.addSelect('op', opAttributes, {
    'or': 'or',
    'and': 'and',
    'not': 'not'
  });

  // define query field
  search.addInput('query', {title: 'search query', 'class': 'aip-search-query-input'});

  // default field name field
  search.addSelect('field', {title: 'field name', onchange: 'selectField(this)'}, {
    '': 'Any',
    'FILEUUID': 'File UUID',
    'filePath': 'File path',
    'fileExtension': 'File extension',
    'AIPUUID': 'AIP UUID',
    'sipName': 'AIP name',
    'isPartOf': 'Part of AIC',
    'AICID': 'AIC Identifier',
    'transferMetadata': 'Transfer metadata',
    'transferMetadataOther': 'Transfer metadata (other)',
  });

  // "Other" field name, when selecting "transfer metadata (other)"
  search.addInput('fieldName', {title: 'other field name', 'class': 'aip-search-query-input', 'id': 'aip-search-query-other-field-name'});

  // default field name field
  search.addSelect('type', {title: 'query type'}, {
    'term': 'Keyword',
    'string': 'Phrase',
    'range': 'Date range'
  });

  // don't show first op field
  search.fieldVisibilityCheck = function(rowIndex, fieldName) {
    return rowIndex > 0 || fieldName != 'op';
  };

  // override default search state if URL parameters set
  if (search.urlParamsToData()) {
    search.rows = search.urlParamsToData();
  }

  search.render();

  // Ensure the select field name field is hidden/displayed as appropriate
  selectField($('.advanced_search_form_field_field > select')[0]);

  function aipSearchSubmit() {
    var destination = '/archival-storage/search/' + '?' + search.toUrlParams();
    if($('#id_show_files').is(':checked')) {
      destination += '&filemode=true';
    }
    if($('#id_show_aics').is(':checked')) {
      destination += '&show_aics=true';
    }
    window.location = destination;
  }

  // submit logic
  $('#search_submit').click(function() {
    aipSearchSubmit();
  });

  $('#search_form').submit(function() {
    aipSearchSubmit();
    return false;
  });

  $('.aip-search-query-input').keypress(function (e) {
    if (e.which == 13) {  // Return key
      aipSearchSubmit();
      return false;
    }
  });
});
<|endoftext|>