<commit_before>(function($) {
  window.baseUrl = "/api/v2/projects/";
  var editingCard = null;
  var clickableElement = function(ele) {
    return _.any(['a', 'input', 'textarea', 'button', 'object'], function(tn) {
      return jQuery.nodeName(ele, tn);
    });
  };
  var render_from_server_paragraph = {
    // status: ['rendered', 'rendering', 'editing']
    //   rendering => rendered
    //   rendered => editing
    //   editing => rendering
    emit: function(div, item) {
      if (item.text == "") {
        div.data('status', 'rendered');
        return div.empty();
      } else {
        div.data('status', 'rendering');
        renderWiki(item.text, function(html) {
          if (div.data('status') == 'rendering') {
            div.data('status', 'rendered');
            div.find('img').remove();
            div.append(html);
          }
        });
        return div.html('');
      }
    },
    bind: function(div, item) {
      div.bind('click', function(e) {
        if (clickableElement(e.target)) {
          return;
        }
        if (div.data('status') == 'rendering') {
          alert("rendering " + item.text);
        } else {
          div.data('status', 'editing');
          div.trigger(wikimate.events.EDIT);
        }
      });
    }
  }

  $.extend(wikimate.plugins, {
    paragraph: render_from_server_paragraph,
    macro: render_from_server_paragraph,
    body_macro: render_from_server_paragraph,
    html: render_from_server_paragraph
  });

  var mingle_wiki_parser = {
    parse: function(desc) {
      function nextId(index) {
        return 'story_item_' + index;
      }
      return _.map(wiki_parser.parse(desc), function(text, i) {
        if (typeof(text) == 'string') {
          return {id: nextId(i), type: 'paragraph', text: text};
        } else {
          return $.extend({id: nextId(i)}, text);
        }
      });
    },
  };

  function renderWiki(content, onSuccess) {
    var card_id = editingCard.find('card id').text();
    var paramStr = $.param({
      content_provider: {
        id: card_id,
        type: 'card'
      },
      content: content
    });
    jQuery.ajax({
      url: window.baseUrl + project() + "/render?" + paramStr,
      dataType: 'html',
      success: onSuccess,
      failure: ajaxCallFailed
    });
  };

  function requestCard(uri, onSuccess) {
    jQuery.ajax({
      url: window.baseUrl + uri + '.xml',
      dataType: 'xml',
      success: onSuccess,
      failure: ajaxCallFailed
    });
  };

  function updateCardDescription(event, action) {
    var desc = $.map($('.wikimate').wikimate('story'), function(item){
      return item.text.trim();
    }).join("\n\n");

    updatingCardDescription();
    var url = window.baseUrl + project() + "/cards/" + number() + ".xml";
    $.ajax({
      url: url,
      dataType: 'xml',
      data: {card: {description: desc}},
      type: 'PUT',
      success: function(r) {
        updatedCardDescription();
      },
      failure: ajaxCallFailed
    })
  };

  function updatingCardDescription() {
    $('.wikimate').css('border-left', '2px solid yellow');
  };
  function updatedCardDescription() {
    $('.wikimate').css('border-left', '2px solid orange');
  };
  function ajaxCallFailed(ajax) {
    console.log("Ajax call failed");
    console.log(ajax);
    $('.wikimate').css('border-left', '2px solid red');
  };

  function parseCardDescription(description) {
    return step('Parsing description', function() {
      return mingle_wiki_parser.parse(description);
    });
  };

  function loadCard(project, number) {
    updatingCardDescription();
    step('Loading ' + project + ' card #' + number + ' description', function() {
      requestCard(project + '/cards/' + number, function(xmlDoc) {
        editingCard = $(xmlDoc);
        var story = parseCardDescription(editingCard.find('card description').text());
        $('#content').empty().wikimate({story: story, change: updateCardDescription});
        updatedCardDescription();
      });
    });
  };

  function cardPageMatch() {
    return window.location.href.match(/\/projects\/([\da-z_]+)\/cards\/(\d+)$/);
  };

  function project() {
    var match = cardPageMatch();
    if (match) {
      return match[1];
    }
    return undefined;
  };
  function number() {
    var match = cardPageMatch();
    if (match) {
      return match[2];
    }
    return undefined;
  };

  function step(msg, func) {
    $('#wiki').append(msg + "
");
    return func.call();
  };

  if (project() && number()) {
    console.log("on card show page: " + project() + " #" + number());
    loadCard(project(), number());
  }
})(jQuery);
<commit_msg>ignore single click on paragraph when item is not editable<commit_after>(function($) {
  window.baseUrl = "/api/v2/projects/";
  var editingCard = null;
  var clickableElement = function(ele) {
    return _.any(['a', 'input', 'textarea', 'button', 'object'], function(tn) {
      return jQuery.nodeName(ele, tn);
    });
  };
  var render_from_server_paragraph = {
    // status: ['rendered', 'rendering', 'editing']
    //   rendering => rendered
    //   rendered => editing
    //   editing => rendering
    emit: function(div, item) {
      if (item.text == "") {
        div.data('status', 'rendered');
        return div.empty();
      } else {
        div.data('status', 'rendering');
        renderWiki(item.text, function(html) {
          if (div.data('status') == 'rendering') {
            div.data('status', 'rendered');
            div.find('img').remove();
            div.append(html);
          }
        });
        return div.html('');
      }
    },
    bind: function(div, item) {
      var $this = this;
      div.bind('click', function(e) {
        if (clickableElement(e.target) || !$this.story_item('editable')) {
          return;
        }
        if (div.data('status') == 'rendering') {
          alert("Please wait for server rendering " + item.text + "");
        } else {
          div.data('status', 'editing');
          div.trigger(wikimate.events.EDIT);
        }
      });
    }
  }

  $.extend(wikimate.plugins, {
    paragraph: render_from_server_paragraph,
    macro: render_from_server_paragraph,
    body_macro: render_from_server_paragraph,
    html: render_from_server_paragraph
  });

  var mingle_wiki_parser = {
    parse: function(desc) {
      function nextId(index) {
        return 'story_item_' + index;
      }
      return _.map(wiki_parser.parse(desc), function(text, i) {
        if (typeof(text) == 'string') {
          return {id: nextId(i), type: 'paragraph', text: text};
        } else {
          return $.extend({id: nextId(i)}, text);
        }
      });
    },
  };

  function renderWiki(content, onSuccess) {
    var card_id = editingCard.find('card id').text();
    var paramStr = $.param({
      content_provider: {
        id: card_id,
        type: 'card'
      },
      content: content
    });
    jQuery.ajax({
      url: window.baseUrl + project() + "/render?" + paramStr,
      dataType: 'html',
      success: onSuccess,
      failure: ajaxCallFailed
    });
  };

  function requestCard(uri, onSuccess) {
    jQuery.ajax({
      url: window.baseUrl + uri + '.xml',
      dataType: 'xml',
      success: onSuccess,
      failure: ajaxCallFailed
    });
  };

  function updateCardDescription(event, action) {
    var desc = $.map($('.wikimate').wikimate('story'), function(item){
      return item.text.trim();
    }).join("\n\n");

    updatingCardDescription();
    var url = window.baseUrl + project() + "/cards/" + number() + ".xml";
    $.ajax({
      url: url,
      dataType: 'xml',
      data: {card: {description: desc}},
      type: 'PUT',
      success: function(r) {
        updatedCardDescription();
      },
      failure: ajaxCallFailed
    })
  };

  function updatingCardDescription() {
    $('.wikimate').css('border-left', '2px solid yellow');
  };
  function updatedCardDescription() {
    $('.wikimate').css('border-left', '2px solid orange');
  };
  function ajaxCallFailed(ajax) {
    console.log("Ajax call failed");
    console.log(ajax);
    $('.wikimate').css('border-left', '2px solid red');
  };

  function parseCardDescription(description) {
    return step('Parsing description', function() {
      return mingle_wiki_parser.parse(description);
    });
  };

  function loadCard(project, number) {
    updatingCardDescription();
    step('Loading ' + project + ' card #' + number + ' description', function() {
      requestCard(project + '/cards/' + number, function(xmlDoc) {
        editingCard = $(xmlDoc);
        var story = parseCardDescription(editingCard.find('card description').text());
        $('#content').empty().wikimate({story: story, change: updateCardDescription});
        updatedCardDescription();
      });
    });
  };

  function cardPageMatch() {
    return window.location.href.match(/\/projects\/([\da-z_]+)\/cards\/(\d+)$/);
  };

  function project() {
    var match = cardPageMatch();
    if (match) {
      return match[1];
    }
    return undefined;
  };
  function number() {
    var match = cardPageMatch();
    if (match) {
      return match[2];
    }
    return undefined;
  };

  function step(msg, func) {
    $('#wiki').append(msg + "
");
    return func.call();
  };

  if (project() && number()) {
    console.log("on card show page: " + project() + " #" + number());
    loadCard(project(), number());
  }
})(jQuery);
<|endoftext|>


<commit_before>odoo.define('jim_telesale.new_order_widgets2', function (require) {
"use strict";
var Model = require('web.DataModel');
var NewOrderWidgets = require('telesale.new_order_widgets');
var core = require('web.core');
var _t = core._t;

var OrderWidget = NewOrderWidgets.OrderWidget.include({
    create_line_from_vals: function(product_id, line_vals){
        var added_line = this.create_line_empty(product_id);
        added_line.set('qty', line_vals.qty || 1.0);
        added_line.set('pvp', line_vals.price || 0.0);
        added_line.set('discount', line_vals.discount || 0.0);
        added_line.set('taxes_ids', line_vals.tax_ids || []);
        added_line.update_line_values();
        return added_line;
    },

    // Creates a line with product and unit seted
    create_line_empty: function(product_id){
        var added_line = this._super(product_id);
        var product_obj = this.ts_model.db.get_product_by_id(product_id);
        var description = product_obj.display_name;
        if (product_obj.description_sale){
            description = description + '\n' + product.description_sale
        }
        added_line.set('description', description);
        return added_line;
    },

});

var OrderlineWidget = NewOrderWidgets.OrderlineWidget.include({

    // Link change chained discount to method
    set_input_handlers: function() {
        this._super();
        this.$('.col-chained_discount').change(_.bind(this.set_value, this, 'chained_discount'));
        this.$('.col-chained_discount').focus(_.bind(this.click_handler, this, 'chained_discount'));

        this.$('.col-description').blur(_.bind(this.set_value, this, 'description'));
        this.$('.col-description').focus(_.bind(this.click_handler, this, 'description'));

        this.$('.col-note').blur(_.bind(this.set_value, this, 'note'));
        this.$('.col-note').focus(_.bind(this.click_handler, this, 'note'));
    },

    // Convert a chained discout like (10.5+20) in a float (20.5)
    // or returns false if something wrong.
    chained_discount2float: function(value){
        if (!value){
            return 0.0
        }
        var split_disc = value.split('+')
        var discount = 0.0
        var disc = 0
        for (var i in split_disc){
            disc = split_disc[i]
            if (isNaN(disc) || disc == "") {
               return false // Break
            }
            else{
              discount = discount + parseFloat(disc);
            }
        }
        return discount;

    },

    // Manage chained_discount
    set_value: function(key) {
        this._super(key)
        if (key == 'chained_discount'){
            var value = this.$('.col-chained_discount').val();

            var discount = this.chained_discount2float(value);
            if (!discount){
                alert(value + _t("is not a valid format for chained discount. It must be something like 23+5.2+1"));
                this.model.set('discount', 0.0);
                this.model.set('chained_discount', 0.0);
            }
            else{
                this.model.set('discount', discount);
            }
            this.refresh('chained_discount');
        }
    },

    perform_onchange: function(key){
        if (key == 'pvp'){
            this.refresh('chained_discount');
        }

        this._super(key);

        if (key == 'template'){
            var value = this.$('.col-'+key).val();
            // Case name not valid
            var template_obj = this.get_template();

            // Get product from model
            if (template_obj){
                var description = template_obj.display_name;
                this.model.set('description', description);
            }

        }

    },

    // OVERWRITED Get global stock available in product_id change
    call_product_id_change: function(product_id, add_qty){
        var self = this;

        if (!add_qty){
            add_qty = 1.0
        }

        var customer_id = self.ts_model.db.partner_name_id[self.order.get('partner')];
        var pricelist_id = self.ts_model.db.pricelist_name_id[self.order.get('pricelist')];
        var model = new Model("sale.order.line");
        return model.call("ts_product_id_change", [product_id, customer_id, pricelist_id])
        .then(function(result){
            var product_obj = self.ts_model.db.get_product_by_id(product_id);
            var uom_obj = self.ts_model.db.get_unit_by_id(product_obj.uom_id)
            var description = product_obj.display_name;
            if (product_obj.description_sale){
                description = description + '\n' + product.description_sale
            }
            self.model.set('description', description);
            self.model.set('code', product_obj.default_code || "");
            self.model.set('product', product_obj.display_name || "");
            self.model.set('taxes_ids', result.tax_id || []); //TODO poner impuestos de producto o vacio
            self.model.set('unit', self.model.ts_model.db.unit_by_id[result.product_uom].name);
            self.model.set('qty', add_qty);
            self.model.set('discount', 0.0);
            self.model.set('standard_price', result.standard_price, 0.0);
            self.model.set('pvp', self.ts_model.my_round( result.price_unit));

            var subtotal = self.model.get('pvp') * self.model.get('qty') * (1 - self.model.get('discount') / 100.0)
            self.model.set('total', self.ts_model.my_round(subtotal || 0,2));

            // ADDED
            self.model.set('global_available_stock', result.global_available_stock || 0.0)

            self.refresh('qty');
            self.$('.col-qty').select();
        });
    },

    renderElement: function() {
        // Set lqdr route_name and global_available_stock
        var prod_name = this.model.get("product");
        // var prod_name = this.$('.col-product').val();
        var product_id = this.ts_model.db.product_name_id[prod_name];
        var product_obj = false
        if (product_id){
            product_obj = this.ts_model.db.get_product_by_id(product_id);
        }
        // Get first vatiant related
        else{
            var template_obj = this.get_template();
            if (template_obj){
                product_id = template_obj.product_variant_ids[0];
                product_obj = this.ts_model.db.get_product_by_id(product_id)
            }
        }

        // Always set lqdr route name and description.
        if (product_obj){
            var lqdr = (product_obj.lqdr)  ? _t("Yes") : _t("No")

            this.model.set('lqdr', lqdr);
            this.model.set('route_name', product_obj.route_name);
        }

        //set handler for fiscount plus field.
        this._super();
    },
    control_arrow_keys: function(){
        var self=this;
        this._super()
        this.$('.col-chained_discount').keydown(function(event){
          var keyCode = event.keyCode || event.which;
          if (keyCode == 40) {  // KEY DOWWN (40)
                event.preventDefault();
                $(this).parent().parent().next().find('.col-chained_discount').select();

            }
            else if (keyCode == 38){  //KEY UP
                event.preventDefault();
                $(this).parent().parent().prev().find('.col-chained_discount').select();
            }
        });
    },
});

var DataOrderWidget = NewOrderWidgets.DataOrderWidget.include({
    // fUllOverwrited to show warning  orblocking menssage menssagge and neutral documente
    // Maybe an improvement geting warning mode and message from the customer
    // and calling super after do the warning checks
    renderElement: function () {
        var self=this;
        this._super();
        this.$('#neutral').blur(_.bind(this.set_neutral_value, this, 'neutral'))
        var current_order = this.ts_model.get('selectedOrder')
        var neutral_document = current_order.get('neutral');
        if (neutral_document) {
            this.$('#neutral').prop('checked', true);
        }
        this.$('#epd').blur(_.bind(this.set_epd_value, this, 'epd'))
        var early_payment_discount = current_order.get('epd');
    },
    set_neutral_value: function(key) {
        var value = this.$('#' + key).is(':checked');
        this.order_model.set(key, value);
    },
    set_epd_value: function(key) {
        var value = this.$('#' + key).val();
        this.order_model.set(key, value);
    },

    perform_onchange: function(key, value) {
        var self=this;
        if (!value) {return;}
        if (key == "partner"){
            var partner_id = self.ts_model.db.partner_name_id[value];

            // Not partner found in backbone model
            if (value && !partner_id){
                var alert_msg = _t("Customer name '" + value + "' does not exist");
                alert(alert_msg);
                self.order_model.set('partner', "");
                self.refresh();
                self.$('#partner').focus();
            }
            else {
                var partner_obj = self.ts_model.db.get_partner_by_id(partner_id);
                var model = new Model("sale.order");
                model.call("ts_onchange_partner_id", [partner_id])
                .then(function(result){
                    var cus_name = self.ts_model.getComplexName(partner_obj);
                    self.order_model.set('partner', cus_name);
                    self.order_model.set('partner_code', partner_obj.ref ? partner_obj.ref : "");

                    self.order_model.set('customer_comment', partner_obj.comment);
                    // TODO nan_partner_risk migrar a la 10
                    // self.order_model.set('limit_credit', self.ts_model.my_round(partner_obj.credit_limit,2));
                    // self.order_model.set('customer_debt', self.ts_model.my_round(partner_obj.credit,2));

                    self.order_model.set('comercial', partner_obj.user_id ? partner_obj.user_id[1] : "");
                    var partner_shipp_obj = self.ts_model.db.get_partner_by_id(result.partner_shipping_id);
                    var shipp_addr =self.ts_model.getComplexName(partner_shipp_obj);
                    self.order_model.set('shipp_addr', shipp_addr);
                    var pricelist_obj = self.ts_model.db.pricelist_by_id[result.pricelist_id];
                    if (pricelist_obj){
                        self.order_model.set('pricelist', pricelist_obj.name);
                    }
                    self.order_model.set('epd', result.early_payment_discount);
                    // Get alert if warning is not false
                    if (result.warning){
                        alert(result.warning);
                        if (result.mode == 'block'){
                            self.order_model.set('partner', "");
                        }

                    }
                    self.refresh();
                    // New line and VUA button when chang
                    // Only do it when partner is setted
                    // if (self.order_model.get('partner')){
                    //     $('#vua-button').click();
                    // }
                    if(self.order_model.get('orderLines').length == 0 && self.order_model.get('partner')){
                        $('.add-line-button').click()
                    }
                    else{
                        self.$('#date_order').focus();
                    }

                });
            }
        }
        else if (key == "pricelist"){
            var pricelist_id = self.ts_model.db.pricelist_name_id[value];

            // Not partner found in backbone model
            if (!pricelist_id){
                var alert_msg = _t("Pricelist name '" + value + "' does not exist");
                alert(alert_msg);
                self.order_model.set('pricelist', "");
                self.refresh();
                self.$('#pricelist').focus();
            }
        }
    },
});

var TotalsOrderWidget = NewOrderWidgets.TotalsOrderWidget.include({
    renderElement: function(){
        var self=this;
        this._super();
        this.$('.proforma-button').click(function (){ self.promoCurrentOrder() });
        this.$('.print-alm-button').click(function (){ self.printAlmOrder() });
    },
     doPrintAlm: function(erp_id){
            this.do_action({
                model: 'sale.order',
                context: {'active_ids': [erp_id]},
                data: null,
                name: 'Quotation / Order',
                report_file: 'custom_documents.custom_sale_order_report_warehouse',
                report_name: 'custom_documents.custom_sale_order_report_warehouse',
                report_type: 'qweb-pdf',
                type: 'ir.actions.report.xml'
            });
        },
    printAlmOrder: function() {
        var self = this;
        self.print_id = false
        var current_order = this.ts_model.get('selectedOrder')
        if (current_order.get('erp_id')){
            if (current_order.get('state') != 'draft'){
                self.doPrint(current_order.get('erp_id'));
                return;
            }
            else{
                self.print_id = current_order.get('erp_id')
            }
        }
        this.ts_widget.new_order_screen.totals_order_widget.saveCurrentOrder()
        $.when( self.ts_model.ready2 )
        .done(function(){
            var domain = [['chanel', '=', 'telesale']]
            if (self.print_id){
                domain = [['id', '=', self.print_id]]
            }
            var loaded = self.ts_model.fetch('sale.order', ['id', 'name'], domain)
               .then(function(orders){
                   if (orders[0]) {
                   var my_id = orders[0].id
                   $.when( self.ts_widget.new_order_screen.order_widget.load_order_from_server(my_id) )
                   .done(function(){
                        var currentOrder = self.ts_model.get('selectedOrder')
                        self.doPrint(currentOrder.get('erp_id'));
                   });

                 }
               });
        });

    },
    promoCurrentOrder: function() {
        var self = this;
        var currentOrder = this.order_model;
        self.saveCurrentOrder()
        $.when( self.ts_model.ready2 )
        .done(function(){
            var loaded = self.ts_model.fetch('sale.order',
                                            ['id', 'name'],
                                            [
                                                ['chanel', '=', 'telesale']
                                            ])
                .then(function(orders){
                    if (orders[0]) {
                      // var my_id = orders[0].id
                      (new Model('sale.order')).call('ts_action_proforma',[orders[0].id])
                          .fail(function(unused, event){
                              //don't show error popup if it fails
                              console.error('Failed confirm order: ',orders[0].name);
                          })
                          .done(function(){
                          });

                    }
                });
         });
    },
    // Allways apply promotion when apply to server
    saveCurrentOrder: function() {
        var current_order = this.ts_model.get('selectedOrder')
        current_order.set('set_promotion', true)
        this._super();
    },

});

});
<commit_msg>Update new_order_widgets.js<commit_after>odoo.define('jim_telesale.new_order_widgets2', function (require) {
"use strict";
var Model = require('web.DataModel');
var NewOrderWidgets = require('telesale.new_order_widgets');
var core = require('web.core');
var _t = core._t;

var OrderWidget = NewOrderWidgets.OrderWidget.include({
    create_line_from_vals: function(product_id, line_vals){
        var added_line = this.create_line_empty(product_id);
        added_line.set('qty', line_vals.qty || 1.0);
        added_line.set('pvp', line_vals.price || 0.0);
        added_line.set('discount', line_vals.discount || 0.0);
        added_line.set('taxes_ids', line_vals.tax_ids || []);
        added_line.update_line_values();
        return added_line;
    },

    // Creates a line with product and unit seted
    create_line_empty: function(product_id){
        var added_line = this._super(product_id);
        var product_obj = this.ts_model.db.get_product_by_id(product_id);
        var description = product_obj.display_name;
        if (product_obj.description_sale){
            description = description + '\n' + product.description_sale
        }
        added_line.set('description', description);
        return added_line;
    },

});

var OrderlineWidget = NewOrderWidgets.OrderlineWidget.include({

    // Link change chained discount to method
    set_input_handlers: function() {
        this._super();
        this.$('.col-chained_discount').change(_.bind(this.set_value, this, 'chained_discount'));
        this.$('.col-chained_discount').focus(_.bind(this.click_handler, this, 'chained_discount'));

        this.$('.col-description').blur(_.bind(this.set_value, this, 'description'));
        this.$('.col-description').focus(_.bind(this.click_handler, this, 'description'));

        this.$('.col-note').blur(_.bind(this.set_value, this, 'note'));
        this.$('.col-note').focus(_.bind(this.click_handler, this, 'note'));
    },

    // Convert a chained discout like (10.5+20) in a float (20.5)
    // or returns false if something wrong.
    chained_discount2float: function(value){
        if (!value){
            return 0.0
        }
        var split_disc = value.split('+')
        var discount = 0.0
        var disc = 0
        for (var i in split_disc){
            disc = split_disc[i]
            if (isNaN(disc) || disc == "") {
               return false // Break
            }
            else{
              discount = discount + parseFloat(disc);
            }
        }
        return discount;

    },

    // Manage chained_discount
    set_value: function(key) {
        this._super(key)
        if (key == 'chained_discount'){
            var value = this.$('.col-chained_discount').val();

            var discount = this.chained_discount2float(value);
            if (!discount){
                alert(value + _t("is not a valid format for chained discount. It must be something like 23+5.2+1"));
                this.model.set('discount', 0.0);
                this.model.set('chained_discount', 0.0);
            }
            else{
                this.model.set('discount', discount);
            }
            this.refresh('chained_discount');
        }
    },

    perform_onchange: function(key){
        if (key == 'pvp'){
            this.refresh('chained_discount');
        }

        this._super(key);

        if (key == 'template'){
            var value = this.$('.col-'+key).val();
            // Case name not valid
            var template_obj = this.get_template();

            // Get product from model
            if (template_obj){
                var description = template_obj.display_name;
                this.model.set('description', description);
            }

        }

    },

    // OVERWRITED Get global stock available in product_id change
    call_product_id_change: function(product_id, add_qty){
        var self = this;

        if (!add_qty){
            add_qty = 1.0
        }

        var customer_id = self.ts_model.db.partner_name_id[self.order.get('partner')];
        var pricelist_id = self.ts_model.db.pricelist_name_id[self.order.get('pricelist')];
        var model = new Model("sale.order.line");
        return model.call("ts_product_id_change", [product_id, customer_id, pricelist_id])
        .then(function(result){
            var product_obj = self.ts_model.db.get_product_by_id(product_id);
            var uom_obj = self.ts_model.db.get_unit_by_id(product_obj.uom_id)
            var description = product_obj.display_name;
            if (product_obj.description_sale){
                description = description + '\n' + product.description_sale
            }
            self.model.set('description', description);
            self.model.set('code', product_obj.default_code || "");
            self.model.set('product', product_obj.display_name || "");
            self.model.set('taxes_ids', result.tax_id || []); //TODO poner impuestos de producto o vacio
            self.model.set('unit', self.model.ts_model.db.unit_by_id[result.product_uom].name);
            self.model.set('qty', add_qty);
            self.model.set('discount', 0.0);
            self.model.set('standard_price', result.standard_price, 0.0);
            self.model.set('pvp', self.ts_model.my_round( result.price_unit));

            var subtotal = self.model.get('pvp') * self.model.get('qty') * (1 - self.model.get('discount') / 100.0)
            self.model.set('total', self.ts_model.my_round(subtotal || 0,2));

            // ADDED
            self.model.set('global_available_stock', result.global_available_stock || 0.0)

            self.refresh('qty');
            self.$('.col-qty').select();
        });
    },

    renderElement: function() {
        // Set lqdr route_name and global_available_stock
        var prod_name = this.model.get("product");
        // var prod_name = this.$('.col-product').val();
        var product_id = this.ts_model.db.product_name_id[prod_name];
        var product_obj = false
        if (product_id){
            product_obj = this.ts_model.db.get_product_by_id(product_id);
        }
        // Get first vatiant related
        else{
            var template_obj = this.get_template();
            if (template_obj){
                product_id = template_obj.product_variant_ids[0];
                product_obj = this.ts_model.db.get_product_by_id(product_id)
            }
        }

        // Always set lqdr route name and description.
        if (product_obj){
            var lqdr = (product_obj.lqdr)  ? _t("Yes") : _t("No")

            this.model.set('lqdr', lqdr);
            this.model.set('route_name', product_obj.route_name);
        }

        //set handler for fiscount plus field.
        this._super();
    },
    control_arrow_keys: function(){
        var self=this;
        this._super()
        this.$('.col-chained_discount').keydown(function(event){
          var keyCode = event.keyCode || event.which;
          if (keyCode == 40) {  // KEY DOWWN (40)
                event.preventDefault();
                $(this).parent().parent().next().find('.col-chained_discount').select();

            }
            else if (keyCode == 38){  //KEY UP
                event.preventDefault();
                $(this).parent().parent().prev().find('.col-chained_discount').select();
            }
        });
    },
});

var DataOrderWidget = NewOrderWidgets.DataOrderWidget.include({
    // fUllOverwrited to show warning  orblocking menssage menssagge and neutral documente
    // Maybe an improvement geting warning mode and message from the customer
    // and calling super after do the warning checks
    renderElement: function () {
        var self=this;
        this._super();
        this.$('#neutral').blur(_.bind(this.set_neutral_value, this, 'neutral'))
        var current_order = this.ts_model.get('selectedOrder')
        var neutral_document = current_order.get('neutral');
        if (neutral_document) {
            this.$('#neutral').prop('checked', true);
        }
        this.$('#epd').blur(_.bind(this.set_epd_value, this, 'epd'))
        var early_payment_discount = current_order.get('epd');
    },
    set_neutral_value: function(key) {
        var value = this.$('#' + key).is(':checked');
        this.order_model.set(key, value);
    },
    set_epd_value: function(key) {
        var value = this.$('#' + key).val();
        this.order_model.set(key, value);
    },

    perform_onchange: function(key, value) {
        var self=this;
        if (!value) {return;}
        if (key == "partner"){
            var partner_id = self.ts_model.db.partner_name_id[value];

            // Not partner found in backbone model
            if (value && !partner_id){
                var alert_msg = _t("Customer name '" + value + "' does not exist");
                alert(alert_msg);
                self.order_model.set('partner', "");
                self.refresh();
                self.$('#partner').focus();
            }
            else {
                var partner_obj = self.ts_model.db.get_partner_by_id(partner_id);
                var model = new Model("sale.order");
                model.call("ts_onchange_partner_id", [partner_id])
                .then(function(result){
                    var cus_name = self.ts_model.getComplexName(partner_obj);
                    self.order_model.set('partner', cus_name);
                    self.order_model.set('partner_code', partner_obj.ref ? partner_obj.ref : "");

                    self.order_model.set('customer_comment', partner_obj.comment);
                    // TODO nan_partner_risk migrar a la 10
                    // self.order_model.set('limit_credit', self.ts_model.my_round(partner_obj.credit_limit,2));
                    // self.order_model.set('customer_debt', self.ts_model.my_round(partner_obj.credit,2));

                    self.order_model.set('comercial', partner_obj.user_id ? partner_obj.user_id[1] : "");
                    var partner_shipp_obj = self.ts_model.db.get_partner_by_id(result.partner_shipping_id);
                    var shipp_addr =self.ts_model.getComplexName(partner_shipp_obj);
                    self.order_model.set('shipp_addr', shipp_addr);
                    var pricelist_obj = self.ts_model.db.pricelist_by_id[result.pricelist_id];
                    if (pricelist_obj){
                        self.order_model.set('pricelist', pricelist_obj.name);
                    }
                    self.order_model.set('epd', result.early_payment_discount);
                    // Get alert if warning is not false
                    if (result.warning){
                        alert(result.warning);
                        if (result.mode == 'block'){
                            self.order_model.set('partner', "");
                        }

                    }
                    self.refresh();
                    // New line and VUA button when chang
                    // Only do it when partner is setted
                    // if (self.order_model.get('partner')){
                    //     $('#vua-button').click();
                    // }
                    if(self.order_model.get('orderLines').length == 0 && self.order_model.get('partner')){
                        $('.add-line-button').click()
                    }
                    else{
                        self.$('#date_order').focus();
                    }

                });
            }
        }
        else if (key == "pricelist"){
            var pricelist_id = self.ts_model.db.pricelist_name_id[value];

            // Not partner found in backbone model
            if (!pricelist_id){
                var alert_msg = _t("Pricelist name '" + value + "' does not exist");
                alert(alert_msg);
                self.order_model.set('pricelist', "");
                self.refresh();
                self.$('#pricelist').focus();
            }
        }
    },
});

var TotalsOrderWidget = NewOrderWidgets.TotalsOrderWidget.include({
    renderElement: function(){
        var self=this;
        this._super();
        this.$('.proforma-button').click(function (){ self.promoCurrentOrder() });
        this.$('.print-alm-button').click(function (){ self.printAlmOrder() });
    },
     doPrintAlm: function(erp_id){
            this.do_action({
                model: 'sale.order',
                context: {'active_ids': [erp_id]},
                data: null,
                name: 'Quotation / Order',
                report_file: 'custom_documents.custom_sale_order_report_warehouse',
                report_name: 'custom_documents.custom_sale_order_report_warehouse',
                report_type: 'qweb-pdf',
                type: 'ir.actions.report.xml'
            });
        },
    printAlmOrder: function() {
        var self = this;
        self.print_id = false
        var current_order = this.ts_model.get('selectedOrder')
        if (current_order.get('erp_id')){
            if (current_order.get('state') != 'draft'){
                self.doPrintAlm(current_order.get('erp_id'));
                return;
            }
            else{
                self.print_id = current_order.get('erp_id')
            }
        }
        this.ts_widget.new_order_screen.totals_order_widget.saveCurrentOrder()
        $.when( self.ts_model.ready2 )
        .done(function(){
            var domain = [['chanel', '=', 'telesale']]
            if (self.print_id){
                domain = [['id', '=', self.print_id]]
            }
            var loaded = self.ts_model.fetch('sale.order', ['id', 'name'], domain)
               .then(function(orders){
                   if (orders[0]) {
                   var my_id = orders[0].id
                   $.when( self.ts_widget.new_order_screen.order_widget.load_order_from_server(my_id) )
                   .done(function(){
                        var currentOrder = self.ts_model.get('selectedOrder')
                        self.doPrint(currentOrder.get('erp_id'));
                   });

                 }
               });
        });

    },
    promoCurrentOrder: function() {
        var self = this;
        var currentOrder = this.order_model;
        self.saveCurrentOrder()
        $.when( self.ts_model.ready2 )
        .done(function(){
            var loaded = self.ts_model.fetch('sale.order',
                                            ['id', 'name'],
                                            [
                                                ['chanel', '=', 'telesale']
                                            ])
                .then(function(orders){
                    if (orders[0]) {
                      // var my_id = orders[0].id
                      (new Model('sale.order')).call('ts_action_proforma',[orders[0].id])
                          .fail(function(unused, event){
                              //don't show error popup if it fails
                              console.error('Failed confirm order: ',orders[0].name);
                          })
                          .done(function(){
                          });

                    }
                });
         });
    },
    // Allways apply promotion when apply to server
    saveCurrentOrder: function() {
        var current_order = this.ts_model.get('selectedOrder')
        current_order.set('set_promotion', true)
        this._super();
    },

});

});
<|endoftext|>


<commit_before>var poker = require('./node-poker');

var table = new poker.Table(50,100,2,10,100,1000);

table.AddPlayer('bob',1000)
table.AddPlayer('jane',1000)
table.AddPlayer('dylan',1000)
table.AddPlayer('john',1000)

table.StartGame()

table.players[1].Call();
table.players[2].Call();
table.players[3].Call();
table.players[0].Call();
table.players[1].Call();
table.players[2].Call();
table.players[3].Call();
table.players[0].Call();
table.players[1].Call();
table.players[2].Call();
table.players[3].Call();
table.players[0].Call();
table.players[1].Call();
table.players[2].Call();
table.players[3].Call();
table.players[0].Call();

table.initNewRound()

console.log(table);<commit_msg>Fix poker lib getting referenced incorrectly<commit_after>var poker = require('./lib/node-poker');

var table = new poker.Table(50,100,2,10,100,1000);

table.AddPlayer('bob',1000)
table.AddPlayer('jane',1000)
table.AddPlayer('dylan',1000)
table.AddPlayer('john',1000)

table.StartGame()

table.players[1].Call();
table.players[2].Call();
table.players[3].Call();
table.players[0].Call();
table.players[1].Call();
table.players[2].Call();
table.players[3].Call();
table.players[0].Call();
table.players[1].Call();
table.players[2].Call();
table.players[3].Call();
table.players[0].Call();
table.players[1].Call();
table.players[2].Call();
table.players[3].Call();
table.players[0].Call();

table.initNewRound()

console.log(table);<|endoftext|>


<commit_before>import os from 'os'
import path from 'path'
import fs from 'fs'

const host = os.hostname().toLowerCase()
const rxrc = 'node_modules/@rxrc'

const targetRoot = os.homedir()

const ioType = 'linux'
const pkgType = 'pacman'

const defaults = {
  dmode: '0750',
  fmode: '0640',
  user: 'razorx',
  group: 'razorx'
}

const unlinks = []

const directories = [{
  src: `${rxrc}/systemd-user-units/user`,
  dst: '.config/systemd/user',
  pkgs: ['systemd']
}, {
  src: `${rxrc}/keymaps/xkb`,
  dst: '.config/xkb',
  pkgs: ['xorg-server']
}, {
  src: `${rxrc}/tmuxinator-profiles`,
  dst: '.config/tmuxinator',
  pkgs: ['tmux']
}, {
  src: `${rxrc}/xresources/Xresources.d`,
  dst: '.config/Xresources/Xresources.d',
  pkgs: ['xorg-server']
}, {
  src: `${rxrc}/hexchat-material-design-icons/icons-white`,
  dst: '.config/hexchat/icons',
  pkgs: ['hexchat']
}, {
  src: `${rxrc}/awesome-copycats`,
  dst: '.config/awesome',
  pkgs: ['awesome']
}, {
  src: `${rxrc}/apw`,
  dst: '.config/awesome/apw',
  order: 200,
  pkgs: ['awesome']
}]

const files = [{
  src: 'dotfiles/zshenv',
  dst: '.zshenv'
}, {
  src: `${rxrc}/ssh-config/config`,
  dst: '.ssh/config'
}, {
  src: `${rxrc}/ssh-config/authorized_keys`,
  dst: '.ssh/authorized_keys',
  fmode: '0600'
}, {
  src: 'config/gnupg/gpg-agent.conf',
  dst: '.config/gnupg/gpg-agent.conf'
}, {
  src: 'config/ignore',
  dst: '.config/ignore'
}, {
  src: 'config/git/config',
  dst: '.config/git/config'
}, {
  src: 'config/git/ignore',
  dst: '.config/git/ignore'
}, {
  src: 'config/rbenv/default-gems',
  dst: '.local/rbenv/default-gems'
}, {
  src: 'dotfiles/lein/profiles.clj',
  dst: '.lein/profiles.clj',
  pkgs: ['leiningen']
}, {
  src: 'config/npm/config',
  dst: '.config/npm/config'
}, {
  src: 'config/bundle/config',
  dst: '.config/bundle/config'
}, {
  src: 'config/ranger/rc.conf',
  dst: '.config/ranger/rc.conf',
  pkgs: ['ranger']
}, {
  src: 'config/stack/config.yaml',
  dst: '.config/stack/config.yaml',
  pkgs: ['stack-bin']
}, {
  src: 'config/chef/knife.rb',
  dst: '.config/chef/knife.rb'
}, {
  src: 'config/vagrant/Vagrantfile',
  dst: '.config/vagrant/Vagrantfile',
  pkgs: ['vagrant']
}, {
  src: 'config/user-dirs.dirs',
  dst: '.config/user-dirs.dirs',
  pkgs: ['xorg-server']
}, {
  src: 'config/mimeapps.list',
  dst: '.config/mimeapps.list',
  pkgs: ['xorg-server']
}, {
  src: `config/Xresources/default.${host}`,
  dst: '.config/Xresources/default',
  pkgs: ['xorg-server']
}, {
  src: `config/xbindkeys/xbindkeysrc.${host}`,
  dst: '.config/xbindkeys/xbindkeysrc',
  pkgs: ['xbindkeys']
}, {
  src: 'dotfiles/gtkrc-2.0',
  dst: '.gtkrc-2.0',
  pkgs: ['gtk2']
}, {
  src: 'config/gtk-3.0/settings.ini',
  dst: '.config/gtk-3.0/settings.ini',
  pkgs: ['gtk3']
}, {
  src: 'config/termite/config',
  dst: '.config/termite/config',
  pkgs: ['termite']
}, {
  src: 'config/kitty/kitty.conf',
  dst: '.config/kitty/kitty.conf',
  pkgs: ['kitty']
}, {
  src: 'config/sakura/sakura.conf',
  dst: '.config/sakura/sakura.conf',
  pkgs: ['sakura']
}, {
  src: 'config/terminator/config',
  dst: '.config/terminator/config',
  pkgs: ['terminator']
}, {
  src: 'config/zathura/zathurarc',
  dst: '.config/zathura/zathurarc',
  pkgs: ['zathura']
}, {
  src: 'dotfiles/xprofile',
  dst: '.xprofile',
  pkgs: ['xorg-server']
}]

const symlinks = async () => [{
  src: '.config/xkb/Sleipnir',
  dst: '.config/xkb/keymap/steelseries-6gv2.xkb',
  pkgs: ['xorg-server']
}, {
  src: '.config/xkb/Mimir',
  dst: '.config/xkb/keymap/steelseries-6gv2.xkb',
  pkgs: ['xorg-server']
}, {
  src: '.config/xkb/pixelbook',
  dst: '.config/xkb/keymap/samus.xkb',
  pkgs: ['xorg-server']
}, {
  src: '.config/xkb/Frigg',
  dst: '.config/xkb/keymap/steelseries-6gv2.xkb',
  pkgs: ['xorg-server']
}, {
  src: '.config/xkb/pixelbook-x60',
  dst: '.config/xkb/keymap/x60t.xkb',
  pkgs: ['xorg-server']
}, {
  src: '.config/xkb/Mjolnir',
  dst: '.config/xkb/keymap/matebook.xkb',
  pkgs: ['xorg-server']
}, {
  src: '.config/awesome/rc.lua',
  dst: '.config/awesome/rc.lua.template',
  pkgs: ['awesome']
}, {
  src: '.config/awesome/themes/powerarrow-dark/wall.png',
  dst: await randomFile('drive/wallpaper/hosts/mjolnir'),
  hosts: ['pixelbook', 'Mjolnir'],
  pkgs: ['awesome']
}, {
  src: '.config/awesome/themes/powerarrow-dark/wall.png',
  dst: 'drive/wallpaper/hosts/frigg/wallhaven-349408-16x10.png',
  hosts: ['Frigg'],
  pkgs: ['awesome']
}, {
  src: '.config/awesome/themes/powerarrow-dark/wall.png',
  dst: 'drive/wallpaper/hosts/frigg/wallhaven-500094.jpg',
  hosts: ['Frigg', 'Mimir'],
  pkgs: ['awesome']
}, {
  src: '.config/awesome/themes/powerarrow-dark/wall.png-2',
  dst: 'drive/wallpaper/hosts/frigg/wallhaven-416958.jpg',
  hosts: ['Frigg', 'Mimir'],
  pkgs: ['awesome']
}, {
  src: '.config/awesome/themes/powerarrow-dark/wall.png-3',
  dst: 'drive/wallpaper/hosts/frigg/wallhaven-14375-2560x1440.jpg',
  hosts: ['Frigg'],
  pkgs: ['awesome']
}, {
  src: '.config/awesome/themes/powerarrow-dark/wall.png',
  dst: 'Wallpaper/wallhaven-83639-4x3.jpg',
  hosts: ['pixelbook-x60'],
  pkgs: ['awesome']
}, {
  src: '.config/awesome/themes/powerarrow-dark/wall.png',
  dst: 'drive/wallpaper/wallbase/general/1920.1200/wallpaper-98843.jpg',
  hosts: ['Sleipnir'],
  pkgs: ['awesome']
}]

export default async () => ({
  unlinks,
  directories,
  files,
  symlinks: await symlinks(),
  targetRoot,
  ioType,
  pkgType,
  defaults
})

const randomFile = async dir => {
  const rootDir = path.join(targetRoot, dir)
  const files = await fs.promises.readdir(rootDir)
  if (!files.length) throw new Error(`No files in ${rootDir}`)

  const checkRandom = async () => {
    const randomIndex = Math.floor(Math.random() * files.length)
    const file = files[randomIndex]
    const stats = await fs.promises.stat(path.join(rootDir, file))
    if (stats.isFile()) return path.join(dir, file)
    files.splice(randomIndex, 1)
    return checkRandom()
  }

  return checkRandom()
}
<commit_msg>Use lowercase in host<commit_after>import os from 'os'
import path from 'path'
import fs from 'fs'

const host = os.hostname().toLowerCase()
const rxrc = 'node_modules/@rxrc'

const targetRoot = os.homedir()

const ioType = 'linux'
const pkgType = 'pacman'

const defaults = {
  dmode: '0750',
  fmode: '0640',
  user: 'razorx',
  group: 'razorx'
}

const unlinks = []

const directories = [{
  src: `${rxrc}/systemd-user-units/user`,
  dst: '.config/systemd/user',
  pkgs: ['systemd']
}, {
  src: `${rxrc}/keymaps/xkb`,
  dst: '.config/xkb',
  pkgs: ['xorg-server']
}, {
  src: `${rxrc}/tmuxinator-profiles`,
  dst: '.config/tmuxinator',
  pkgs: ['tmux']
}, {
  src: `${rxrc}/xresources/Xresources.d`,
  dst: '.config/Xresources/Xresources.d',
  pkgs: ['xorg-server']
}, {
  src: `${rxrc}/hexchat-material-design-icons/icons-white`,
  dst: '.config/hexchat/icons',
  pkgs: ['hexchat']
}, {
  src: `${rxrc}/awesome-copycats`,
  dst: '.config/awesome',
  pkgs: ['awesome']
}, {
  src: `${rxrc}/apw`,
  dst: '.config/awesome/apw',
  order: 200,
  pkgs: ['awesome']
}]

const files = [{
  src: 'dotfiles/zshenv',
  dst: '.zshenv'
}, {
  src: `${rxrc}/ssh-config/config`,
  dst: '.ssh/config'
}, {
  src: `${rxrc}/ssh-config/authorized_keys`,
  dst: '.ssh/authorized_keys',
  fmode: '0600'
}, {
  src: 'config/gnupg/gpg-agent.conf',
  dst: '.config/gnupg/gpg-agent.conf'
}, {
  src: 'config/ignore',
  dst: '.config/ignore'
}, {
  src: 'config/git/config',
  dst: '.config/git/config'
}, {
  src: 'config/git/ignore',
  dst: '.config/git/ignore'
}, {
  src: 'config/rbenv/default-gems',
  dst: '.local/rbenv/default-gems'
}, {
  src: 'dotfiles/lein/profiles.clj',
  dst: '.lein/profiles.clj',
  pkgs: ['leiningen']
}, {
  src: 'config/npm/config',
  dst: '.config/npm/config'
}, {
  src: 'config/bundle/config',
  dst: '.config/bundle/config'
}, {
  src: 'config/ranger/rc.conf',
  dst: '.config/ranger/rc.conf',
  pkgs: ['ranger']
}, {
  src: 'config/stack/config.yaml',
  dst: '.config/stack/config.yaml',
  pkgs: ['stack-bin']
}, {
  src: 'config/chef/knife.rb',
  dst: '.config/chef/knife.rb'
}, {
  src: 'config/vagrant/Vagrantfile',
  dst: '.config/vagrant/Vagrantfile',
  pkgs: ['vagrant']
}, {
  src: 'config/user-dirs.dirs',
  dst: '.config/user-dirs.dirs',
  pkgs: ['xorg-server']
}, {
  src: 'config/mimeapps.list',
  dst: '.config/mimeapps.list',
  pkgs: ['xorg-server']
}, {
  src: `config/Xresources/default.${host}`,
  dst: '.config/Xresources/default',
  pkgs: ['xorg-server']
}, {
  src: `config/xbindkeys/xbindkeysrc.${host}`,
  dst: '.config/xbindkeys/xbindkeysrc',
  pkgs: ['xbindkeys']
}, {
  src: 'dotfiles/gtkrc-2.0',
  dst: '.gtkrc-2.0',
  pkgs: ['gtk2']
}, {
  src: 'config/gtk-3.0/settings.ini',
  dst: '.config/gtk-3.0/settings.ini',
  pkgs: ['gtk3']
}, {
  src: 'config/termite/config',
  dst: '.config/termite/config',
  pkgs: ['termite']
}, {
  src: 'config/kitty/kitty.conf',
  dst: '.config/kitty/kitty.conf',
  pkgs: ['kitty']
}, {
  src: 'config/sakura/sakura.conf',
  dst: '.config/sakura/sakura.conf',
  pkgs: ['sakura']
}, {
  src: 'config/terminator/config',
  dst: '.config/terminator/config',
  pkgs: ['terminator']
}, {
  src: 'config/zathura/zathurarc',
  dst: '.config/zathura/zathurarc',
  pkgs: ['zathura']
}, {
  src: 'dotfiles/xprofile',
  dst: '.xprofile',
  pkgs: ['xorg-server']
}]

const symlinks = async () => [{
  src: '.config/xkb/Sleipnir',
  dst: '.config/xkb/keymap/steelseries-6gv2.xkb',
  pkgs: ['xorg-server']
}, {
  src: '.config/xkb/Mimir',
  dst: '.config/xkb/keymap/steelseries-6gv2.xkb',
  pkgs: ['xorg-server']
}, {
  src: '.config/xkb/Pixelbook',
  dst: '.config/xkb/keymap/samus.xkb',
  pkgs: ['xorg-server']
}, {
  src: '.config/xkb/Frigg',
  dst: '.config/xkb/keymap/steelseries-6gv2.xkb',
  pkgs: ['xorg-server']
}, {
  src: '.config/xkb/Gungnir-x60',
  dst: '.config/xkb/keymap/x60t.xkb',
  pkgs: ['xorg-server']
}, {
  src: '.config/xkb/Mjolnir',
  dst: '.config/xkb/keymap/matebook.xkb',
  pkgs: ['xorg-server']
}, {
  src: '.config/awesome/rc.lua',
  dst: '.config/awesome/rc.lua.template',
  pkgs: ['awesome']
}, {
  src: '.config/awesome/themes/powerarrow-dark/wall.png',
  dst: await randomFile('drive/wallpaper/hosts/mjolnir'),
  hosts: ['pixelbook', 'mjolnir'],
  pkgs: ['awesome']
}, {
  src: '.config/awesome/themes/powerarrow-dark/wall.png',
  dst: 'drive/wallpaper/hosts/frigg/wallhaven-349408-16x10.png',
  hosts: ['frigg'],
  pkgs: ['awesome']
}, {
  src: '.config/awesome/themes/powerarrow-dark/wall.png',
  dst: 'drive/wallpaper/hosts/frigg/wallhaven-500094.jpg',
  hosts: ['frigg', 'mimir'],
  pkgs: ['awesome']
}, {
  src: '.config/awesome/themes/powerarrow-dark/wall.png-2',
  dst: 'drive/wallpaper/hosts/frigg/wallhaven-416958.jpg',
  hosts: ['frigg', 'mimir'],
  pkgs: ['awesome']
}, {
  src: '.config/awesome/themes/powerarrow-dark/wall.png-3',
  dst: 'drive/wallpaper/hosts/frigg/wallhaven-14375-2560x1440.jpg',
  hosts: ['frigg'],
  pkgs: ['awesome']
}, {
  src: '.config/awesome/themes/powerarrow-dark/wall.png',
  dst: 'Wallpaper/wallhaven-83639-4x3.jpg',
  hosts: ['pixelbook-x60'],
  pkgs: ['awesome']
}, {
  src: '.config/awesome/themes/powerarrow-dark/wall.png',
  dst: 'drive/wallpaper/wallbase/general/1920.1200/wallpaper-98843.jpg',
  hosts: ['Sleipnir'],
  pkgs: ['awesome']
}]

export default async () => ({
  unlinks,
  directories,
  files,
  symlinks: await symlinks(),
  targetRoot,
  ioType,
  pkgType,
  defaults
})

const randomFile = async dir => {
  const rootDir = path.join(targetRoot, dir)
  const files = await fs.promises.readdir(rootDir)
  if (!files.length) throw new Error(`No files in ${rootDir}`)

  const checkRandom = async () => {
    const randomIndex = Math.floor(Math.random() * files.length)
    const file = files[randomIndex]
    const stats = await fs.promises.stat(path.join(rootDir, file))
    if (stats.isFile()) return path.join(dir, file)
    files.splice(randomIndex, 1)
    return checkRandom()
  }

  return checkRandom()
}
<|endoftext|>


<commit_before>/**
 * Tatoeba Project, free collaborative creation of multilingual corpuses project
 * Copyright (C) 2010  HO Ngoc Phuong Trang <tranglich@gmail.com>
 *
 * 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/>.
 */

$(document).ready(function () {
  $(document).watch('addrule', function () {
    $('.audioAvailable').off();
    $('.audioAvailable').click(function () {
      var audioURL = $(this).attr('href');
      var audio = new Audio(audioURL);
      audio.play();
    });
  });
});
<commit_msg>Replace jQuery with pure Javascript<commit_after>/**
 * Tatoeba Project, free collaborative creation of multilingual corpuses project
 * Copyright (C) 2010  HO Ngoc Phuong Trang <tranglich@gmail.com>
 *
 * 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/>.
 */

/* Polyfill for IE */
if (window.NodeList && !NodeList.prototype.forEach) {
   NodeList.prototype.forEach = Array.prototype.forEach;
}

var addAudio = function () {
    document.querySelectorAll('.audioAvailable').forEach(function(elem) {
       elem.addEventListener('click', function(event) {
           var audioURL = event.target.getAttribute('href');
           var audio = new Audio(audioURL);
           audio.play();
       });
    });
}

if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', addAudio);
} else {
  addAudio();
}
<|endoftext|>


<commit_before>{
	'type': 'game', // game or console
	'name': 'Galaxian',
	'authors': ['Kazunori Swano', 'Koichi Tashiro', 'Shigekazu Ishimura'],
	'company': ['Namco'],
	'year': '1979',
	'date': 'October of 1979',
	'headline': 'The evolution of the Space Invaders',
	'resume': [
		'Um jogo arcade segue a formula de Space Invaders, com um enredo ',
		'simples e bastante objetivo de eliminar uma froto alienígena de ',
		'uma raça chamada GALAXIAN.'
	].join(''),
	'full_text': [
		'Sendo desenvolvido pela Namco em 1979 e lançado no mesmo no Japão,',
		' sua jogabilidade consistia em atirar em uma frota de aliens que ',
		'tentam periodicamente ataques kamikazes, os quais o jogador pode ',
		'desviar se movendo pela vertical. Ademais, sua principal diferença',
		' de sua inspiração é o fato de ser colorido na palheta RGB e ter',
		' uma trilha sonora de fundo, além dos ataques Kamikazes.'
	].join(''),
        'thumbnail': 'thumbnail_example.png',
        'main_img': {'name': 'main_picture.png', 'caption': "description"},
        'images': [
            {'name': 'picture1.png', 'caption': "description1"},
        ],
        'video_gameplay': [
            {'url': 'https://www.youtube.com/watch?v=qKm8UnFCmeg', 'caption': "gameplay", 'type': "youtube"} // type: youtube or vimeo
        ],
        'demos': [
            {'url': 'http://www.letsplaysnes.com/play-galaxian-online-nes/?play=true#content', 'caption': "demo"}
        ],
        'references': [
            {'url': 'http://en.wikipedia.org/wiki/galaxian', 'caption': "Wikipedia"}
        ]
}
},
<commit_msg>Update galaxianpt_temp.js<commit_after>{
	'type': 'game', // game or console
	'name': 'Galaxian',
	'authors': ['Kazunori Swano', 'Koichi Tashiro', 'Shigekazu Ishimura'],
	'company': ['Namco'],
	'year': '1979',
	'date': 'October of 1979',
	'headline': 'The evolution of the Space Invaders',
	'resume': [
		'Um jogo arcade segue a formula de Space Invaders, com um enredo ',
		'simples e bastante objetivo de eliminar uma froto alienígena de ',
		'uma raça chamada GALAXIAN.'
	].join(''),
	'full_text': [
		'Sendo desenvolvido pela Namco em 1979 e lançado no mesmo no Japão,',
		' sua jogabilidade consistia em atirar em uma frota de aliens que ',
		'tentam periodicamente ataques kamikazes, os quais o jogador pode ',
		'desviar se movendo pela vertical. Ademais, sua principal diferença',
		' de sua inspiração é o fato de ser colorido na palheta RGB e ter',
		' uma trilha sonora de fundo, além dos ataques Kamikazes.'
	].join(''),
        'thumbnail': 'thumbnail_example.png',
        'main_img': {'name': 'main_picture.png', 'caption': "description"}
        'images': [
            {'name': 'picture1.png', 'caption': "description1"},
        ],
        'video_gameplay': [
            {'url': 'https://www.youtube.com/watch?v=qKm8UnFCmeg', 'caption': "gameplay", 'type': "youtube"} // type: youtube or vimeo
        ],
        'demos': [
            {'url': 'http://www.letsplaysnes.com/play-galaxian-online-nes/?play=true#content', 'caption': "demo"}
        ],
        'references': [
            {'url': 'http://en.wikipedia.org/wiki/galaxian', 'caption': "Wikipedia"}
        ]
}
},
<|endoftext|>


<commit_before>import {Point, Rotation} from '../geometry';
import {Graphics} from './Graphics';

/**
 * A simple rectangle.
 * @extends Graphics
 */
export class Rectangle extends Graphics {

  /**
   *
   * @param {number} [x=0] The X position of the rectangle (top-left corner).
   * @param {number} [y=0] The Y position of the rectangle (top-left corner).
   * @param {number} [width=400] The width of the rectangle.
   * @param {number} [height=250] The height of the rectangle.
   * @param {CanvasColour} [fillColour='#ff00ff'] The background colour of the rectangle.
   * @param {CanvasColour} [strokeColour='#ffffff'] The colour of the rectangle's strokes.
   * @param {number} [strokeWidth=2] The width of the rectangle's strokes. Set to 0 if none.
   */
  constructor(x=0, y=0, width=400, height=250, fillColour='#ff00ff', strokeColour='#ffffff', strokeWidth=2) {
    super();

    /**
     * The position of the rectangle (top-left corner).
     * @type {Point}
     */
    this.position = new Point(x, y);

    /**
     * The width of the rectangle.
     * @type {number}
     */
    this.width = width;

    /**
     * The height of the rectangle.
     * @type {number}
     */
    this.height = height;

    /**
     * The background colour.
     * @type {CanvasColour}
     */
    this.fillColour = fillColour;

    /**
     * The stroke colour of the rectangle.
     * @type {CanvasColour}
     */
    this.strokeColour = strokeColour;

    /**
     * The width of the rectangle's strokes. Set to 0 if none.
     * @type {number}
     */
    this.strokeWidth = strokeWidth;

    /**
     * The rotation of the rectangle, in degrees.
     * @type {number}
     * @default
     */
    this.rotation = 0;

    /**
     * Whether the rectangle should be rendered or not.
     * @type {boolean}
     * @default
     */
    this.visible = true;

    /**
     * Whether to fill or not the rectangle with its fill colour.
     * @type {boolean}
     * @default
     */
    this.fill = true;
  }

  /**
   * The X position of the rectangle (top-left).
   * @type {number}
   */
  get x() {
    return this.position.x;
  }

  set x(x) {
    this.position.x = x;
  }

  /**
   * The Y position of the rectangle (top-left).
   */
  get y() {
    return this.position.y;
  }

  set y(y) {
    this.position.y = y;
  }

  /**
   * The center point of the rectangle.
   * @type {Point}
   * @readonly
   */
  get center() {
    return new Point(this.x + this.width / 2, this.y + this.height / 2);
  }

  /**
   * The X coordinate of the rectangle's center.
   * @type {number}
   */
  get centerX() {
    return this.x + this.width / 2;
  }

  set centerX(centerX) {
    this.x = centerX - this.width / 2;
  }

  /**
   * The Y coordinate of the rectangle's center.
   * @type {number}
   */
  get centerY() {
    return this.y + this.height / 2;
  }

  set centerY(centerY) {
    this.y = centerY - this.height / 2;
  }

  /**
   * Change the rectangle's center point. This will update its position.
   * @param {Point} center The new center of the rectangle.
   */
  setCenter(center) {
    this.x = center.x - this.width / 2;
    this.y = center.y - this.height / 2;
  }

  /**
   * Draw the rectangle.
   * @param {CanvasRenderingContext2D} context The renderer's context.
   */
  draw(context) {
    if (!this.visible) return;

    context.save();

    if (this.rotation) {
      context.translate(this.centerX, this.centerY);
      context.rotate(Rotation.degreesToRadians(this.rotation));
      context.translate(-this.centerX, -this.centerY);
    }

    if (this.fill) {
      context.fillStyle = this.fillColour;
      context.fillRect(this.x, this.y, this.width, this.height);
    }

    if (this.strokeWidth) {
      context.lineWidth = this.strokeWidth;
      context.strokeStyle = this.strokeColour;
      context.strokeRect(this.x, this.y, this.width, this.height);
    }
  }
}
<commit_msg>Fix context restore in draw<commit_after>import {Point, Rotation} from '../geometry';
import {Graphics} from './Graphics';

/**
 * A simple rectangle.
 * @extends Graphics
 */
export class Rectangle extends Graphics {

  /**
   * Create a Rectangle.
   * @param {number} [x=0] The X position of the rectangle (top-left corner).
   * @param {number} [y=0] The Y position of the rectangle (top-left corner).
   * @param {number} [width=400] The width of the rectangle.
   * @param {number} [height=250] The height of the rectangle.
   * @param {CanvasColour} [fillColour='#ff00ff'] The background colour of the rectangle.
   * @param {CanvasColour} [strokeColour='#ffffff'] The colour of the rectangle's strokes.
   * @param {number} [strokeWidth=2] The width of the rectangle's strokes. Set to 0 if none.
   */
  constructor(x=0, y=0, width=400, height=250, fillColour='#ff00ff', strokeColour='#ffffff', strokeWidth=2) {
    super();

    /**
     * The position of the rectangle (top-left corner).
     * @type {Point}
     */
    this.position = new Point(x, y);

    /**
     * The width of the rectangle.
     * @type {number}
     */
    this.width = width;

    /**
     * The height of the rectangle.
     * @type {number}
     */
    this.height = height;

    /**
     * The background colour.
     * @type {CanvasColour}
     */
    this.fillColour = fillColour;

    /**
     * The stroke colour of the rectangle.
     * @type {CanvasColour}
     */
    this.strokeColour = strokeColour;

    /**
     * The width of the rectangle's strokes. Set to 0 if none.
     * @type {number}
     */
    this.strokeWidth = strokeWidth;

    /**
     * The rotation of the rectangle, in degrees.
     * @type {number}
     * @default
     */
    this.rotation = 0;

    /**
     * Whether to fill or not the rectangle with its fill colour.
     * @type {boolean}
     * @default
     */
    this.fill = true;
  }

  /**
   * The X position of the rectangle (top-left).
   * @type {number}
   */
  get x() {
    return this.position.x;
  }

  set x(x) {
    this.position.x = x;
  }

  /**
   * The Y position of the rectangle (top-left).
   */
  get y() {
    return this.position.y;
  }

  set y(y) {
    this.position.y = y;
  }

  /**
   * The center point of the rectangle.
   * @type {Point}
   * @readonly
   */
  get center() {
    return new Point(this.x + this.width / 2, this.y + this.height / 2);
  }

  /**
   * The X coordinate of the rectangle's center.
   * @type {number}
   */
  get centerX() {
    return this.x + this.width / 2;
  }

  set centerX(centerX) {
    this.x = centerX - this.width / 2;
  }

  /**
   * The Y coordinate of the rectangle's center.
   * @type {number}
   */
  get centerY() {
    return this.y + this.height / 2;
  }

  set centerY(centerY) {
    this.y = centerY - this.height / 2;
  }

  /**
   * Change the rectangle's center point. This will update its position.
   * @param {Point} center The new center of the rectangle.
   */
  setCenter(center) {
    this.x = center.x - this.width / 2;
    this.y = center.y - this.height / 2;
  }

  /**
   * Draw the rectangle.
   * @param {CanvasRenderingContext2D} context The renderer's context.
   */
  draw(context) {
    context.save();

    if (this.rotation) {
      context.translate(this.centerX, this.centerY);
      context.rotate(Rotation.degreesToRadians(this.rotation));
      context.translate(-this.centerX, -this.centerY);
    }

    if (this.fill) {
      context.fillStyle = this.fillColour;
      context.fillRect(this.x, this.y, this.width, this.height);
    }

    if (this.strokeWidth) {
      context.lineWidth = this.strokeWidth;
      context.strokeStyle = this.strokeColour;
      context.strokeRect(this.x, this.y, this.width, this.height);
    }

    context.restore();
  }
}
<|endoftext|>


<commit_before>// {namespace name="backend/swag_import_export/view/main"}
// {block name="backend/swag_import_export/controller/export"}
Ext.define('Shopware.apps.SwagImportExport.controller.Export', {
    extend: 'Ext.app.Controller',
    snippets: {
        exportWindow: '{s name=swag_import_export/export/window_title}Export window{/s}',
        finished: '{s name=swag_import_export/export/finished}Export finished successfully {/s}',
        process: '{s name=swag_import_export/export/process}Exporting... {/s}'
    },
    /**
     * This method creates listener for events fired from the export
     */
    init: function() {
        var me = this;

        me.control({
            // Export button
            'swag-import-export-manager-export': {
                export: me.onExport
            },
            'swag-import-export-manager-window-export': {
                startProcess: me.onStartProcess,
                downloadFile: me.onDownloadFile,
                cancelProcess: me.onCancelProcess
            },
            'swag-import-export-manager-session': {
                resumeExport: me.onResume
            }
        });

        me.callParent(arguments);
    },
    onExport: function(btn) {
        var me = this,
            form = btn.up('form'),
            values = form.getValues();

        if (Ext.isEmpty(values.profile) || values.profile < 1 || Ext.isEmpty(values.format)) {
            Shopware.Notification.createGrowlMessage(
                '{s name=swag_import_export/export/error_title}Swag import export{/s}',
                '{s name=swag_import_export/export/error_msg}Please select export configuration{/s}'
            );
            return false;
        }

        me.parameters = values;

        me.onCreateExportWindow();
    },
    /**
     * Triggers if the resume button was pressed
     * in the previous operation window.
     *
     * @param object Shopware.apps.SwagImportExport.model.Session
     */
    onResume: function(record, sessionStore) {
        var me = this;

        me.parameters = {
            sessionId: record.get('id'),
            profile: record.get('profileId'),
            format: record.get('format')
        };

        me.sessionStore = sessionStore;

        me.getConfig();
    },
    /**
     * Creates batch configuration
     */
    onCreateExportWindow: function() {
        var me = this;

        me.getBatchConfig = me.getConfig();
    },
    /**
     * Triggers if the start exporting button was pressed
     * in the export window.
     *
     * @param object Enlight.app.SubWindow win
     * @param object Ext.button.Button btn
     */
    onStartProcess: function(win, btn) {
        var me = this;

        me.cancelOperation = false;

        me.runRequest(win);

        btn.hide();
        win.cancelButton.show();
        win.closeButton.disable();
    },
    /**
     * Returns the needed configuration for the next batch call
     */
    getConfig: function() {
        var me = this;

        me.batchConfig = {
            requestUrl: '{url controller="SwagImportExportExport" action="export"}',
            params: {
                profileId: me.parameters.profile,
                sessionId: me.parameters.sessionId,
                format: me.parameters.format,
                limit: me.parameters.limit,
                offset: me.parameters.offset,
                categories: me.parameters.category,
                variants: me.parameters.variants,
                ordernumberFrom: me.parameters.ordernumberFrom,
                dateFrom: me.parameters.dateFrom,
                dateTo: me.parameters.dateTo,
                orderstate: me.parameters.orderstate,
                paymentstate: me.parameters.paymentstate,
                stockFilter: me.parameters.stockFilter,
                customFilterDirection: me.parameters.customFilterCombo,
                customFilterValue: me.parameters.filterThanValue,
                customerStreamId: me.parameters.customerStreamId
            }
        };

        Ext.Ajax.request({
            url: '{url controller="SwagImportExportExport" action="prepareExport"}',
            method: 'POST',
            params: me.batchConfig.params,
            success: function(response) {
                var result = Ext.decode(response.responseText);
                me.batchConfig.position = result.position;
                me.batchConfig.totalCount = result.count;
                me.batchConfig.snippet = me.snippets.process + me.batchConfig.position + ' / ' + me.batchConfig.totalCount;
                me.batchConfig.progress = me.batchConfig.position / me.batchConfig.totalCount;

                me.window = me.getView('Shopware.apps.SwagImportExport.view.manager.window.Export').create({
                    batchConfig: me.batchConfig
                }).show();
            },
            failure: function(response) {
                Shopware.Msg.createStickyGrowlMessage({
                    title: '{s name=swag_import_export/export/error_occured}An error occured{/s}',
                    text: response.responseText
                });
            }
        });
    },
    /**
     * This function sends a request to export data
     *
     * @param object Enlight.app.SubWindow win
     */
    runRequest: function(win) {
        var me = this,
            config = me.batchConfig,
            params = config.params;

        // if cancel button was pressed
        if (me.cancelOperation) {
            win.closeButton.enable();
            return;
        }

        Ext.Ajax.request({
            url: config.requestUrl,
            method: 'POST',
            params: params,
            timeout: 4000000,
            success: function(response) {
                var result = Ext.decode(response.responseText);

                if (result.success === false) {
                    Shopware.Msg.createStickyGrowlMessage({
                        title: '{s name=swag_import_export/export/error}Export error{/s}',
                        text: result.msg
                    });

                    win.closeButton.enable();
                    win.cancelButton.disable();
                    return;
                }

                me.batchConfig.params = result.data;
                me.batchConfig.position = result.data.position;

                win.exportProgress.updateProgress(
                        me.batchConfig.position / me.batchConfig.totalCount,
                        me.snippets.process + me.batchConfig.position + ' / ' + me.batchConfig.totalCount,
                        true
                        );

                if (me.batchConfig.position === me.batchConfig.totalCount) {
                    me.fileName = result.data.fileName;
                    me.onProcessFinish(win);
                } else {
                    me.runRequest(win);
                }
            },
            failure: function(response) {
                Shopware.Msg.createStickyGrowlMessage({
                    title: '{s name=swag_import_export/export/error_occured}An error occured{/s}',
                    text: response.responseText
                });

                win.closeButton.enable();
                win.cancelButton.disable();
            }
        });
    },
    /**
     * Sets cancelOperation to true which will be checked in the
     * next batch call and will stop.
     *
     * @param btn
     */
    onCancelProcess: function(btn) {
        var me = this;

        btn.disable();

        me.cancelOperation = true;
    },

    /**
     * Will be called when export finish
     *
     * @param object Enlight.app.SubWindow win
     */
    onProcessFinish: function(win) {
        var me = this;

        win.closeButton.enable();
        win.cancelButton.hide();
        win.downloadButton.show();
        win.exportProgress.updateText(me.snippets.finished + me.batchConfig.position + ' / ' + me.batchConfig.totalCount);

        if (!Ext.isEmpty(me.sessionStore)) {
            me.sessionStore.reload();
        }
    },

    onDownloadFile: function() {
        var me = this,
            url = '{url action="downloadFile"}' + '?fileName=' + me.fileName;

        window.open(url, '_blank');
    }
});
// {/block}
<commit_msg>PT-8611 - Allow parameter override<commit_after>// {namespace name="backend/swag_import_export/view/main"}
// {block name="backend/swag_import_export/controller/export"}
Ext.define('Shopware.apps.SwagImportExport.controller.Export', {
    extend: 'Ext.app.Controller',
    snippets: {
        exportWindow: '{s name=swag_import_export/export/window_title}Export window{/s}',
        finished: '{s name=swag_import_export/export/finished}Export finished successfully {/s}',
        process: '{s name=swag_import_export/export/process}Exporting... {/s}'
    },

    /**
     * This method creates listener for events fired from the export
     */
    init: function() {
        var me = this;

        me.control({
            // Export button
            'swag-import-export-manager-export': {
                export: me.onExport
            },
            'swag-import-export-manager-window-export': {
                startProcess: me.onStartProcess,
                downloadFile: me.onDownloadFile,
                cancelProcess: me.onCancelProcess
            },
            'swag-import-export-manager-session': {
                resumeExport: me.onResume
            }
        });

        me.callParent(arguments);
    },

    onExport: function(btn) {
        var me = this,
            form = btn.up('form'),
            values = form.getValues();

        if (Ext.isEmpty(values.profile) || values.profile < 1 || Ext.isEmpty(values.format)) {
            Shopware.Notification.createGrowlMessage(
                '{s name=swag_import_export/export/error_title}Swag import export{/s}',
                '{s name=swag_import_export/export/error_msg}Please select export configuration{/s}'
            );
            return false;
        }

        me.parameters = values;

        me.onCreateExportWindow();
    },

    /**
     * Triggers if the resume button was pressed
     * in the previous operation window.
     *
     * @param object Shopware.apps.SwagImportExport.model.Session
     */
    onResume: function(record, sessionStore) {
        var me = this;

        me.parameters = {
            sessionId: record.get('id'),
            profile: record.get('profileId'),
            format: record.get('format')
        };

        me.sessionStore = sessionStore;

        me.getConfig();
    },

    /**
     * Creates batch configuration
     */
    onCreateExportWindow: function() {
        var me = this;

        me.getBatchConfig = me.getConfig();
    },

    /**
     * Triggers if the start exporting button was pressed
     * in the export window.
     *
     * @param object Enlight.app.SubWindow win
     * @param object Ext.button.Button btn
     */
    onStartProcess: function(win, btn) {
        var me = this;

        me.cancelOperation = false;

        me.runRequest(win);

        btn.hide();
        win.cancelButton.show();
        win.closeButton.disable();
    },

    /**
     * Returns the needed configuration for the next batch call
     */
    getConfig: function() {
        var me = this;

        me.batchConfig = {
            requestUrl: '{url controller="SwagImportExportExport" action="export"}',
            params: me.getParams()
        };

        Ext.Ajax.request({
            url: '{url controller="SwagImportExportExport" action="prepareExport"}',
            method: 'POST',
            params: me.batchConfig.params,
            success: function(response) {
                var result = Ext.decode(response.responseText);
                me.batchConfig.position = result.position;
                me.batchConfig.totalCount = result.count;
                me.batchConfig.snippet = me.snippets.process + me.batchConfig.position + ' / ' + me.batchConfig.totalCount;
                me.batchConfig.progress = me.batchConfig.position / me.batchConfig.totalCount;

                me.window = me.getView('Shopware.apps.SwagImportExport.view.manager.window.Export').create({
                    batchConfig: me.batchConfig
                }).show();
            },
            failure: function(response) {
                Shopware.Msg.createStickyGrowlMessage({
                    title: '{s name=swag_import_export/export/error_occured}An error occured{/s}',
                    text: response.responseText
                });
            }
        });
    },

    /**
     * Returns the parameters that will be sent to the backend
     */
    getParams: function() {
        var me = this;

        return {
            profileId: me.parameters.profile,
            sessionId: me.parameters.sessionId,
            format: me.parameters.format,
            limit: me.parameters.limit,
            offset: me.parameters.offset,
            categories: me.parameters.category,
            variants: me.parameters.variants,
            ordernumberFrom: me.parameters.ordernumberFrom,
            dateFrom: me.parameters.dateFrom,
            dateTo: me.parameters.dateTo,
            orderstate: me.parameters.orderstate,
            paymentstate: me.parameters.paymentstate,
            stockFilter: me.parameters.stockFilter,
            customFilterDirection: me.parameters.customFilterCombo,
            customFilterValue: me.parameters.filterThanValue,
            customerStreamId: me.parameters.customerStreamId
        };
    },

    /**
     * This function sends a request to export data
     *
     * @param object Enlight.app.SubWindow win
     */
    runRequest: function(win) {
        var me = this,
            config = me.batchConfig,
            params = config.params;

        // if cancel button was pressed
        if (me.cancelOperation) {
            win.closeButton.enable();
            return;
        }

        Ext.Ajax.request({
            url: config.requestUrl,
            method: 'POST',
            params: params,
            timeout: 4000000,
            success: function(response) {
                var result = Ext.decode(response.responseText);

                if (result.success === false) {
                    Shopware.Msg.createStickyGrowlMessage({
                        title: '{s name=swag_import_export/export/error}Export error{/s}',
                        text: result.msg
                    });

                    win.closeButton.enable();
                    win.cancelButton.disable();
                    return;
                }

                me.batchConfig.params = result.data;
                me.batchConfig.position = result.data.position;

                win.exportProgress.updateProgress(
                        me.batchConfig.position / me.batchConfig.totalCount,
                        me.snippets.process + me.batchConfig.position + ' / ' + me.batchConfig.totalCount,
                        true
                        );

                if (me.batchConfig.position === me.batchConfig.totalCount) {
                    me.fileName = result.data.fileName;
                    me.onProcessFinish(win);
                } else {
                    me.runRequest(win);
                }
            },
            failure: function(response) {
                Shopware.Msg.createStickyGrowlMessage({
                    title: '{s name=swag_import_export/export/error_occured}An error occured{/s}',
                    text: response.responseText
                });

                win.closeButton.enable();
                win.cancelButton.disable();
            }
        });
    },

    /**
     * Sets cancelOperation to true which will be checked in the
     * next batch call and will stop.
     *
     * @param btn
     */
    onCancelProcess: function(btn) {
        var me = this;

        btn.disable();

        me.cancelOperation = true;
    },

    /**
     * Will be called when export finish
     *
     * @param object Enlight.app.SubWindow win
     */
    onProcessFinish: function(win) {
        var me = this;

        win.closeButton.enable();
        win.cancelButton.hide();
        win.downloadButton.show();
        win.exportProgress.updateText(me.snippets.finished + me.batchConfig.position + ' / ' + me.batchConfig.totalCount);

        if (!Ext.isEmpty(me.sessionStore)) {
            me.sessionStore.reload();
        }
    },

    onDownloadFile: function() {
        var me = this,
            url = '{url action="downloadFile"}' + '?fileName=' + me.fileName;

        window.open(url, '_blank');
    }
});
// {/block}
<|endoftext|>


<commit_before>TouchUI.prototype.DOM.create.webcam = {

	menu: {
		webcam: {
			cloneTo: "#term_link"
		}
	},

	container: {
		cloneTo: "#timelapse",

		webcam: {
			$container: $("#webcam_container"),
			cloneTo: "#webcam"
		}
	},

	init: function( tabbar ) {
		var self = this;

		this.container.$elm = $('

').insertAfter(this.container.cloneTo);
		this.menu.webcam.$elm = tabbar.createItem("webcam_link", "webcam", "tab").insertBefore(this.menu.webcam.cloneTo);

		this.container.webcam.$container.next().appendTo(this.container.webcam.cloneTo);
		this.container.webcam.$container.prependTo(this.container.webcam.cloneTo);

		$('').insertBefore(this.container.$elm);
		$('').insertBefore(this.container.$elm);

		$("#webcam_container").attr("data-bind", $("#webcam_container").attr("data-bind").replace("keydown: onKeyDown, ", ""));

	}

}
<commit_msg>Fix webcam content to show if timelapse div is not generated<commit_after>TouchUI.prototype.DOM.create.webcam = {

	menu: {
		webcam: {
			cloneTo: "#term_link"
		}
	},

	container: {
		cloneTo: ".tab-content",

		webcam: {
			$container: $("#webcam_container"),
			cloneTo: "#webcam"
		}
	},

	init: function( tabbar ) {
		var self = this;

		this.container.$elm = $('

').appendTo(this.container.cloneTo);
		this.menu.webcam.$elm = tabbar.createItem("webcam_link", "webcam", "tab").insertBefore(this.menu.webcam.cloneTo);

		this.container.webcam.$container.next().appendTo(this.container.webcam.cloneTo);
		this.container.webcam.$container.prependTo(this.container.webcam.cloneTo);

		$('').insertBefore(this.container.$elm);
		$('').insertAfter(this.container.$elm);

		$("#webcam_container").attr("data-bind", $("#webcam_container").attr("data-bind").replace("keydown: onKeyDown, ", ""));

	}

}
<|endoftext|>


<commit_before>var keyboardNavigation = (function () {
    var getPosition = function ($release) {
        var releasePosition = $release.position().top;
        var navbarHeight = $('.navbar').outerHeight();
        var spacer = 10;
        return releasePosition - navbarHeight - spacer;
    };

    var goToPreviousRelease = function () {
        var $previousRelease = $('.release').filter(function (index) {
            return $(window).scrollTop() > getPosition($(this));
        }).last();

        if ($previousRelease.length) {
            $(window).scrollTop(getPosition($previousRelease));
        } else {
            $(window).scrollTop(0);
        }
    };

    var goToNextRelease = function () {
        var $nextRelease = $('.release').filter(function (index) {
            return $(window).scrollTop() < getPosition($(this));
        }).first();

        if ($nextRelease.length) {
            $(window).scrollTop(getPosition($nextRelease));
        }
    };

    var goToPreviousPage = function () {
        var prev_url = $('#prev').attr('href');
        if (prev_url) {
            window.location = prev_url;
        }
    };

    var goToNextPage = function () {
        var next_url = $('#next').attr('href');
        if (next_url) {
            window.location = next_url;
        }
    };

    return function (event) {
        if (event.ctrlKey || event.altKey || event.metaKey) {
            return;
        }
        if (event.which === 63) {
            event.preventDefault();
            $('.keyboard-shortcuts.modal').modal();
        }
        if ($('#releases').length) {
            if (event.which === 72 || event.which === 104) { // H or h
                event.preventDefault();
                goToPreviousPage();
            } else if (event.which === 74 || event.which === 106) { // J or j
                event.preventDefault();
                goToNextRelease();
            } else if (event.which === 75 || event.which === 107) { // K or k
                event.preventDefault();
                goToPreviousRelease();
            } else if (event.which === 76 || event.which === 108) { // L or l
                event.preventDefault();
                goToNextPage();
            }
        }
    };
})();

var mycomicsToggler = (function () {
    var showConfirmation = function ($button) {
        $button.css('opacity', 1);
        $button.find('.action').hide();
        $button.find('.confirmation').show();
        $button.addClass('btn-danger');
    };

    var showSuccess = function ($button) {
        $button.css('opacity', 1);
        $button.find('.action').hide();
        $button.find('.confirmation').hide();
        $button.find('.success').show();
        $button
            .removeClass('btn-danger')
            .addClass('btn-success');
    };

    var isMyComicsPage = function () {
        return (window.location + '').match(/\/my\//);
    };

    return {
        addComic: function (event) {
            event.preventDefault();
            var $button = $(this);
            $button.attr('disabled', 'disabled');
            var $form = $button.parent('form');
            var data = $form.serialize() + '&add_comic=1';
            $.post($form.attr('action'), data, function () {
                showSuccess($button);
            });
        },
        removeComic: function (event) {
            event.preventDefault();
            var $button = $(this);
            if ($button.find('.action:visible').length) {
                showConfirmation($button);
            } else {
                $button.attr('disabled', 'disabled');
                var $form = $button.parent('form');
                var data = $form.serialize() + '&remove_comic=1';
                $.post($form.attr('action'), data, function () {
                    showSuccess($button);
                    if (isMyComicsPage()) {
                        var comic = $button.parents('.release').data('comic');
                        $('.release[data-comic="' + comic + '"]')
                            .slideUp('slow')
                            .children().fadeOut('slow');
                    }
                });
            }
        }
    };
})();

var mycomicsEditor = (function () {
    return {
        edit: function (event) {
            event.preventDefault();
            $('#cloud .edit-view').show();
            $('#cloud .show-view').hide();
        },
        cancel: function (event) {
            $('#cloud .show-view').show();
            $('#cloud .edit-view').hide();
        }
    };
})();

var newReleaseCheck = (function () {
    var secondsBeforeFirstCheck = 60;

    var getLastReleaseId = function () {
        return $('.release').first().data('release-id');
    };

    var checkForNewReleases = function () {
        var lastReleaseId = getLastReleaseId();
        if (lastReleaseId) {
            $.get('/my/num-releases-since/' + lastReleaseId + '/')
                .done(onSuccess)
                .fail(onFailure);
        }
    };

    var showNewReleaseNotification = function (numReleases) {
        var $el = $('.new-releases-alert');
        $el.find('.new-release-count').html(numReleases);
        $el.slideDown();
    };

    var onSuccess = function (data) {
        if (data.num_releases > 0) {
            showNewReleaseNotification(data.num_releases);
        }
        if (data.seconds_to_next_check !== null) {
            setTimeout(checkForNewReleases, data.seconds_to_next_check * 1000);
        }
    };

    var onFailure = function () {
        setTimeout(checkForNewReleases, secondsBeforeFirstCheck * 1000);
    };

    var isPageOneOfMyComicsLatest = function () {
        return (window.location + '').match(/\/my\/(page1\/)?$/);
    };

    return function () {
        if (isPageOneOfMyComicsLatest()) {
            setTimeout(checkForNewReleases, secondsBeforeFirstCheck * 1000);
        }
    };
})();

$(function () {
    $(document).keypress(keyboardNavigation);
    $('.mycomics-add').click(mycomicsToggler.addComic);
    $('.mycomics-remove').click(mycomicsToggler.removeComic);
    $('.mycomics-edit').click(mycomicsEditor.edit);
    $('.mycomics-cancel').click(mycomicsEditor.cancel);
    newReleaseCheck();
});
<commit_msg>Toggle "max-width" on release images when clicked<commit_after>var keyboardNavigation = (function () {
    var getPosition = function ($release) {
        var releasePosition = $release.position().top;
        var navbarHeight = $('.navbar').outerHeight();
        var spacer = 10;
        return releasePosition - navbarHeight - spacer;
    };

    var goToPreviousRelease = function () {
        var $previousRelease = $('.release').filter(function (index) {
            return $(window).scrollTop() > getPosition($(this));
        }).last();

        if ($previousRelease.length) {
            $(window).scrollTop(getPosition($previousRelease));
        } else {
            $(window).scrollTop(0);
        }
    };

    var goToNextRelease = function () {
        var $nextRelease = $('.release').filter(function (index) {
            return $(window).scrollTop() < getPosition($(this));
        }).first();

        if ($nextRelease.length) {
            $(window).scrollTop(getPosition($nextRelease));
        }
    };

    var goToPreviousPage = function () {
        var prev_url = $('#prev').attr('href');
        if (prev_url) {
            window.location = prev_url;
        }
    };

    var goToNextPage = function () {
        var next_url = $('#next').attr('href');
        if (next_url) {
            window.location = next_url;
        }
    };

    return function (event) {
        if (event.ctrlKey || event.altKey || event.metaKey) {
            return;
        }
        if (event.which === 63) {
            event.preventDefault();
            $('.keyboard-shortcuts.modal').modal();
        }
        if ($('#releases').length) {
            if (event.which === 72 || event.which === 104) { // H or h
                event.preventDefault();
                goToPreviousPage();
            } else if (event.which === 74 || event.which === 106) { // J or j
                event.preventDefault();
                goToNextRelease();
            } else if (event.which === 75 || event.which === 107) { // K or k
                event.preventDefault();
                goToPreviousRelease();
            } else if (event.which === 76 || event.which === 108) { // L or l
                event.preventDefault();
                goToNextPage();
            }
        }
    };
})();

var mycomicsToggler = (function () {
    var showConfirmation = function ($button) {
        $button.css('opacity', 1);
        $button.find('.action').hide();
        $button.find('.confirmation').show();
        $button.addClass('btn-danger');
    };

    var showSuccess = function ($button) {
        $button.css('opacity', 1);
        $button.find('.action').hide();
        $button.find('.confirmation').hide();
        $button.find('.success').show();
        $button
            .removeClass('btn-danger')
            .addClass('btn-success');
    };

    var isMyComicsPage = function () {
        return (window.location + '').match(/\/my\//);
    };

    return {
        addComic: function (event) {
            event.preventDefault();
            var $button = $(this);
            $button.attr('disabled', 'disabled');
            var $form = $button.parent('form');
            var data = $form.serialize() + '&add_comic=1';
            $.post($form.attr('action'), data, function () {
                showSuccess($button);
            });
        },
        removeComic: function (event) {
            event.preventDefault();
            var $button = $(this);
            if ($button.find('.action:visible').length) {
                showConfirmation($button);
            } else {
                $button.attr('disabled', 'disabled');
                var $form = $button.parent('form');
                var data = $form.serialize() + '&remove_comic=1';
                $.post($form.attr('action'), data, function () {
                    showSuccess($button);
                    if (isMyComicsPage()) {
                        var comic = $button.parents('.release').data('comic');
                        $('.release[data-comic="' + comic + '"]')
                            .slideUp('slow')
                            .children().fadeOut('slow');
                    }
                });
            }
        }
    };
})();

var mycomicsEditor = (function () {
    return {
        edit: function (event) {
            event.preventDefault();
            $('#cloud .edit-view').show();
            $('#cloud .show-view').hide();
        },
        cancel: function (event) {
            $('#cloud .show-view').show();
            $('#cloud .edit-view').hide();
        }
    };
})();

var fullSizeToggler = function () {
    if ($('img', this).css('max-width') !== 'none') {
        $('img', this).css('max-width', 'none');
    } else {
        $('img', this).css('max-width', '100%');
    }
};

var newReleaseCheck = (function () {
    var secondsBeforeFirstCheck = 60;

    var getLastReleaseId = function () {
        return $('.release').first().data('release-id');
    };

    var checkForNewReleases = function () {
        var lastReleaseId = getLastReleaseId();
        if (lastReleaseId) {
            $.get('/my/num-releases-since/' + lastReleaseId + '/')
                .done(onSuccess)
                .fail(onFailure);
        }
    };

    var showNewReleaseNotification = function (numReleases) {
        var $el = $('.new-releases-alert');
        $el.find('.new-release-count').html(numReleases);
        $el.slideDown();
    };

    var onSuccess = function (data) {
        if (data.num_releases > 0) {
            showNewReleaseNotification(data.num_releases);
        }
        if (data.seconds_to_next_check !== null) {
            setTimeout(checkForNewReleases, data.seconds_to_next_check * 1000);
        }
    };

    var onFailure = function () {
        setTimeout(checkForNewReleases, secondsBeforeFirstCheck * 1000);
    };

    var isPageOneOfMyComicsLatest = function () {
        return (window.location + '').match(/\/my\/(page1\/)?$/);
    };

    return function () {
        if (isPageOneOfMyComicsLatest()) {
            setTimeout(checkForNewReleases, secondsBeforeFirstCheck * 1000);
        }
    };
})();

$(function () {
    $(document).keypress(keyboardNavigation);
    $('.mycomics-add').click(mycomicsToggler.addComic);
    $('.mycomics-remove').click(mycomicsToggler.removeComic);
    $('.mycomics-edit').click(mycomicsEditor.edit);
    $('.mycomics-cancel').click(mycomicsEditor.cancel);
    $('.release .image').click(fullSizeToggler);
    newReleaseCheck();
});
<|endoftext|>