<commit_before>import Em from 'ember';
import RemoveButton from '../views/remove-button-cell';
var set = Em.set;
var get = Em.get;

var IndexController = Em.Controller.extend({
	tableColumns: [
		{
			name: 'episode',
			label: 'Episode',
			order: 1,
			type: 'number',
			width: 80
		},
		{
			name: 'title',
			label: 'Title',
			order: 2
		},
		{
			name: 'airdate',
			label: 'Original airdate',
			order: 5
		},
		{
			name: 'description',
			label: 'Description',
			order: 3,
			width: 400
		},
		{
			name: 'million_viewers',
			label: 'Viewers (in millions)',
			order: 4,
			type: 'number',
			isClickable: true
		},
		{
			name: 'screenshot',
			label: 'Screenshot URL',
			order: 7,
			isHidden: true
		},
		{
			name: 'remove',
			label: 'Remove',
			order: 8,
			type: 'remove',
			isSortable: false
		}
	],
	tableData: [
		{
			screenshot: 'http://i.imgur.com/r3WXxQ8.jpg',
			episode: 1,
			title: 'Pilot',
			airdate: 'December 2, 2013',
			million_viewers: 1.095,
			description: 'Rick moves in with his daughter\'s family and establishes himself as a bad influence on his grandson, Morty.'
		},
		{
			screenshot: 'http://i.imgur.com/aaBXAXz.jpg',
			episode: 2,
			title: 'Lawnmower Dog',
			airdate: 'December 9, 2013',
			million_viewers: 1.510,
			description: 'Rick helps Jerry out with the dog, Snuffles. Don\'t even trip about this episode because they also incept the dreams of Mr. Goldenfold.'
		},
		{
			screenshot: 'http://i.imgur.com/AzbEBCT.jpg',
			episode: 3,
			title: 'Anatomy Park',
			airdate: 'December 16, 2013',
			million_viewers: 1.302,
			description: 'On this Christmas-themed episode, Jerry forces the family to bond during the holiday. Rick shrinks Morty in size to enter his creation, Anatomy Park.'
		},
		{
			screenshot: 'http://i.imgur.com/9p2KVpx.jpg',
			episode: 4,
			title: 'M. Night Shaym-Aliens!',
			airdate: 'January 13, 2014',
			million_viewers: 1.476,
			description: 'Rick, Morty, and Jerry find themselves trapped in a life-like simulation by an alien race of intergalactic scammers known as the Zigerions.'
		},
		{
			screenshot: 'http://i.imgur.com/ARS7yUu.jpg',
			episode: 5,
			title: 'Meeseeks and Destroy',
			airdate: 'January 20, 2014',
			million_viewers: 1.610,
			description: 'Morty makes a bet with Rick that he can lead a fun, successful adventure. Jerry, Beth, and Summer summon various helpers named Mr. Meeseeks to help solve their problems.'
		},
		{
			screenshot: 'http://i.imgur.com/6F7a5us.jpg',
			episode: 6,
			title: 'Rick Potion No. 9',
			airdate: 'January 27, 2014',
			million_viewers: 1.746,
			description: 'Morty asks Rick to brew him up a love potion to gain the affections of Jessica, but the potion fuses with an airborne flu virus and infects the worldwide population.'
		},
		{
			screenshot: 'http://i.imgur.com/IsUlCuf.jpg',
			episode: 7,
			title: 'Raising Gazorpazorp',
			airdate: 'March 10, 2014',
			million_viewers: 1.762,
			description: 'When Morty asks Rick to buy him a sex robot from a space pawn shop, it concieves his own half-alien son, leading Rick and Summer to investigate the robot\'s planet of origin.'
		},
		{
			screenshot: 'http://i.imgur.com/g8tdmZG.jpg',
			episode: 8,
			title: 'Rixty Minutes',
			airdate: 'March 17, 2014',
			million_viewers: 1.477,
			description: 'Rick installs a device within the family\'s TV set allowing them to watch shows from all possible realities, causing Jerry and Beth to contemplate their past decisions.'
		},
		{
			screenshot: 'http://i.imgur.com/51EVhy3.jpg',
			episode: 9,
			title: 'Something Ricked This Way Comes',
			airdate: 'March 24, 2014',
			million_viewers: 1.543,
			description: 'Summer gets a job at a strange shop selling eccentric, cursed items, Jerry commits himself to helping Morty on a science project.'
		},
		{
			screenshot: 'http://i.imgur.com/p4SXVnQ.jpg',
			episode: 10,
			title: 'Close Rick-counters of the Rick Kind',
			airdate: 'April 7, 2014',
			million_viewers: 1.750,
			description: 'Rick and Morty are imprisoned by a council of Rick\'s across alternate timelines for a crime they didn\'t commit, Jerry bonds with an alternate-reality Rick.'
		},
		{
			screenshot: 'http://i.imgur.com/aFELDzg.jpg',
			episode: 11,
			title: 'Ricksy Business',
			airdate: 'April 14, 2014',
			million_viewers: 1.823,
			description: 'Rick hosts a party while Beth and Jerry are away.'
		}
	],
	config: {
		sortProperties: ['episode'],
		sortAscending: true,
		types: [
			{
				name: 'remove',
				view: RemoveButton
			}
		]
	},
	clickEvents: Em.A(),
	actions: {
		addColumn: function () {
			this.get('tableColumns').pushObject({
				name: 'screenshot',
				label: 'Screenshot URL',
				order: 0
			});
		},
		shuffleColumns: function () {
			var cols = this.get('tableColumns');
			var n = cols.length;
			var j, left, right, tmp;
			for (var i = n - 1; i >= 1; i--) {
				j = Math.floor(Math.random() * i);
				left = cols.objectAt(i);
				right = cols.objectAt(j);
				tmp = get(right, 'order');
				set(right, 'order', get(left, 'order'));
				set(left, 'order', tmp);
			}
		},
		updateData: function () {
			var data = this.get('tableData');
			data.forEach(function (record) {
				var value = 1 + Math.random() * 1;
				value = value.toFixed(3);
				value = Number(value);
				set(record, 'million_viewers', value);
			});
		},
		removeRow: function (index) {
			this.get('tableData').removeAt(index);
		},
		toggleHidden: function () {
			var columnName = 'screenshot';
			this.get('tableColumns').forEach(function (column) {
				if (get(column, 'name') === columnName) {
					set(column, 'isHidden', !get(column, 'isHidden'));
				}
			});
		},
		cellClick: function (row, column) {
			this.get('clickEvents').pushObject({
				row: get(row, 'million_viewers'),
				clicked: get(column, 'name')
			});
		}
	}
});

export default IndexController;
<commit_msg>Changed demo table column definitions to demonstrate new functionality<commit_after>import Em from 'ember';
import RemoveButton from '../views/remove-button-cell';
var set = Em.set;
var get = Em.get;

var IndexController = Em.Controller.extend({
	tableColumns: [
		{
			name: 'episode',
			label: 'Episode',
			order: 1,
			type: 'number',
			width: 50
		},
		{
			name: 'title',
			label: 'Title',
			order: 2
		},
		{
			name: 'airdate',
			label: 'Original airdate',
			order: 5
		},
		{
			name: 'description',
			label: 'Description',
			order: 3,
			width: 400
		},
		{
			name: 'million_viewers',
			label: 'Viewers (in millions)',
			order: 4,
			type: 'number',
			isClickable: true
		},
		{
			name: 'screenshot',
			label: 'Screenshot URL',
			order: 7,
			isHidden: true
		},
		{
			name: 'remove',
			label: 'Remove',
			order: 8,
			type: 'remove',
			isSortable: false,
			minWidth: 100,
			maxWidth: 250
		}
	],
	tableData: [
		{
			screenshot: 'http://i.imgur.com/r3WXxQ8.jpg',
			episode: 1,
			title: 'Pilot',
			airdate: 'December 2, 2013',
			million_viewers: 1.095,
			description: 'Rick moves in with his daughter\'s family and establishes himself as a bad influence on his grandson, Morty.'
		},
		{
			screenshot: 'http://i.imgur.com/aaBXAXz.jpg',
			episode: 2,
			title: 'Lawnmower Dog',
			airdate: 'December 9, 2013',
			million_viewers: 1.510,
			description: 'Rick helps Jerry out with the dog, Snuffles. Don\'t even trip about this episode because they also incept the dreams of Mr. Goldenfold.'
		},
		{
			screenshot: 'http://i.imgur.com/AzbEBCT.jpg',
			episode: 3,
			title: 'Anatomy Park',
			airdate: 'December 16, 2013',
			million_viewers: 1.302,
			description: 'On this Christmas-themed episode, Jerry forces the family to bond during the holiday. Rick shrinks Morty in size to enter his creation, Anatomy Park.'
		},
		{
			screenshot: 'http://i.imgur.com/9p2KVpx.jpg',
			episode: 4,
			title: 'M. Night Shaym-Aliens!',
			airdate: 'January 13, 2014',
			million_viewers: 1.476,
			description: 'Rick, Morty, and Jerry find themselves trapped in a life-like simulation by an alien race of intergalactic scammers known as the Zigerions.'
		},
		{
			screenshot: 'http://i.imgur.com/ARS7yUu.jpg',
			episode: 5,
			title: 'Meeseeks and Destroy',
			airdate: 'January 20, 2014',
			million_viewers: 1.610,
			description: 'Morty makes a bet with Rick that he can lead a fun, successful adventure. Jerry, Beth, and Summer summon various helpers named Mr. Meeseeks to help solve their problems.'
		},
		{
			screenshot: 'http://i.imgur.com/6F7a5us.jpg',
			episode: 6,
			title: 'Rick Potion No. 9',
			airdate: 'January 27, 2014',
			million_viewers: 1.746,
			description: 'Morty asks Rick to brew him up a love potion to gain the affections of Jessica, but the potion fuses with an airborne flu virus and infects the worldwide population.'
		},
		{
			screenshot: 'http://i.imgur.com/IsUlCuf.jpg',
			episode: 7,
			title: 'Raising Gazorpazorp',
			airdate: 'March 10, 2014',
			million_viewers: 1.762,
			description: 'When Morty asks Rick to buy him a sex robot from a space pawn shop, it concieves his own half-alien son, leading Rick and Summer to investigate the robot\'s planet of origin.'
		},
		{
			screenshot: 'http://i.imgur.com/g8tdmZG.jpg',
			episode: 8,
			title: 'Rixty Minutes',
			airdate: 'March 17, 2014',
			million_viewers: 1.477,
			description: 'Rick installs a device within the family\'s TV set allowing them to watch shows from all possible realities, causing Jerry and Beth to contemplate their past decisions.'
		},
		{
			screenshot: 'http://i.imgur.com/51EVhy3.jpg',
			episode: 9,
			title: 'Something Ricked This Way Comes',
			airdate: 'March 24, 2014',
			million_viewers: 1.543,
			description: 'Summer gets a job at a strange shop selling eccentric, cursed items, Jerry commits himself to helping Morty on a science project.'
		},
		{
			screenshot: 'http://i.imgur.com/p4SXVnQ.jpg',
			episode: 10,
			title: 'Close Rick-counters of the Rick Kind',
			airdate: 'April 7, 2014',
			million_viewers: 1.750,
			description: 'Rick and Morty are imprisoned by a council of Rick\'s across alternate timelines for a crime they didn\'t commit, Jerry bonds with an alternate-reality Rick.'
		},
		{
			screenshot: 'http://i.imgur.com/aFELDzg.jpg',
			episode: 11,
			title: 'Ricksy Business',
			airdate: 'April 14, 2014',
			million_viewers: 1.823,
			description: 'Rick hosts a party while Beth and Jerry are away.'
		}
	],
	config: {
		sortProperties: ['episode'],
		sortAscending: true,
		types: [
			{
				name: 'remove',
				view: RemoveButton
			}
		]
	},
	clickEvents: Em.A(),
	actions: {
		addColumn: function () {
			this.get('tableColumns').pushObject({
				name: 'screenshot',
				label: 'Screenshot URL',
				order: 0
			});
		},
		shuffleColumns: function () {
			var cols = this.get('tableColumns');
			var n = cols.length;
			var j, left, right, tmp;
			for (var i = n - 1; i >= 1; i--) {
				j = Math.floor(Math.random() * i);
				left = cols.objectAt(i);
				right = cols.objectAt(j);
				tmp = get(right, 'order');
				set(right, 'order', get(left, 'order'));
				set(left, 'order', tmp);
			}
		},
		updateData: function () {
			var data = this.get('tableData');
			data.forEach(function (record) {
				var value = 1 + Math.random() * 1;
				value = value.toFixed(3);
				value = Number(value);
				set(record, 'million_viewers', value);
			});
		},
		removeRow: function (index) {
			this.get('tableData').removeAt(index);
		},
		toggleHidden: function () {
			var columnName = 'screenshot';
			this.get('tableColumns').forEach(function (column) {
				if (get(column, 'name') === columnName) {
					set(column, 'isHidden', !get(column, 'isHidden'));
				}
			});
		},
		cellClick: function (row, column) {
			this.get('clickEvents').pushObject({
				row: get(row, 'million_viewers'),
				clicked: get(column, 'name')
			});
		}
	}
});

export default IndexController;
<|endoftext|>


<commit_before>// HyperHTML Renderer ported to SkateJS
import {
  withComponent,
  shadow,
  props,
} from 'skatejs';
import { hyper, bind } from 'hyperhtml/cjs';
import { hasNativeShadowDomSupport } from '../utils/environment';
import { findParentTag } from '../utils/find-parent-tag';

export function BoltComponent(Base = HTMLElement) {
  return class extends withComponent(Base) {

    static props = {
      onClick: props.string,
      onClickTarget: props.string,
    }

    constructor(...args) {
      super(...args);

      this.hyper = hyper;

      if (findParentTag(this, 'FORM') || this.getAttribute('no-shadow') !== null) {
        this.useShadow = false;
      } else {
        this.useShadow = hasNativeShadowDomSupport;
      }
    }

    connectedCallback() {
      // if (this.dataset.ssrContent) {
      //   this.innerHTML = JSON.parse(this.dataset.ssrContent);
      // }
      this._checkSlots();
      this.connecting && this.connecting();
      this.connected && this.connected();
    }

    disconnectedCallback() {
      this.disconnecting && this.disconnecting();
      this.disconnected && this.disconnected();
    }

    addStyles(stylesheet) {
      let styles = Array.from(stylesheet);
      styles = styles.join(' ');

      if (this.useShadow) {
        return hyper.wire() `
          <style>${ styles} </style>
        `;
      }
    }

    slot(name) {
      if (this.useShadow && hasNativeShadowDomSupport) {
        if (name === 'default') {
          return hyper.wire() `
            <slot />
          `;
        } else {
          return hyper.wire() `
            <slot name="${name}" />
          `;
        }
      } else {
        if (this.slots[name]) {
          return hyper.wire() `
            ${this.slots.default}
          `;
        }
        else {
          console.log(`The ${name} slot doesn't appear to exist...`);
        }
      }
    }

    // Inspired by https://codepen.io/jovdb/pen/ddRZKo
    _checkSlots() {
      this.slots = {
        default: [],
      };

      const elem = this;

      // Loop through nodelist
      this.childNodes.forEach(function (child, index, nodelist) {
        const slotName = child.getAttribute ? child.getAttribute("slot") : null;

        if (!slotName) {
          elem.slots.default.push(child);
        } else {
          elem.slots[slotName] = child;
        }
      });
    }

    get renderRoot() {
      if (hasNativeShadowDomSupport && this.useShadow === true) {
        return super.renderRoot || shadow(this);
      } else {
        return this;
      }
    }

    renderer(root, render) {
      this.html = this.html || bind(root);
      render();
    }
  }
};
<commit_msg>fix: updating hyperHTML wire call to include a reference to the component being wired up<commit_after>// HyperHTML Renderer ported to SkateJS
import {
  withComponent,
  shadow,
  props,
} from 'skatejs';
import { hyper, bind } from 'hyperhtml/cjs';
import { hasNativeShadowDomSupport } from '../utils/environment';
import { findParentTag } from '../utils/find-parent-tag';

export function BoltComponent(Base = HTMLElement) {
  return class extends withComponent(Base) {

    static props = {
      onClick: props.string,
      onClickTarget: props.string,
    }

    constructor(...args) {
      super(...args);

      this.hyper = hyper;

      if (findParentTag(this, 'FORM') || this.getAttribute('no-shadow') !== null) {
        this.useShadow = false;
      } else {
        this.useShadow = hasNativeShadowDomSupport;
      }
    }

    connectedCallback() {
      // if (this.dataset.ssrContent) {
      //   this.innerHTML = JSON.parse(this.dataset.ssrContent);
      // }
      this._checkSlots();
      this.connecting && this.connecting();
      this.connected && this.connected();
    }

    disconnectedCallback() {
      this.disconnecting && this.disconnecting();
      this.disconnected && this.disconnected();
    }

    addStyles(stylesheet) {
      let styles = Array.from(stylesheet);
      styles = styles.join(' ');

      if (this.useShadow) {
        return hyper.wire(this) `
          <style>${ styles} </style>
        `;
      }
    }

    slot(name) {
      if (this.useShadow && hasNativeShadowDomSupport) {
        if (name === 'default') {
          return hyper.wire(this) `
            <slot />
          `;
        } else {
          return hyper.wire(this) `
            <slot name="${name}" />
          `;
        }
      } else {
        if (this.slots[name]) {
          return hyper.wire(this) `
            ${this.slots.default}
          `;
        }
        else {
          console.log(`The ${name} slot doesn't appear to exist...`);
        }
      }
    }

    // Inspired by https://codepen.io/jovdb/pen/ddRZKo
    _checkSlots() {
      this.slots = {
        default: [],
      };

      const elem = this;

      // Loop through nodelist
      this.childNodes.forEach(function (child, index, nodelist) {
          const slotName = child.getAttribute ? child.getAttribute("slot") : null;

          if (!slotName) {
          elem.slots.default.push(child);
          } else {
          elem.slots[slotName] = child;
          }
        });
      }

    get renderRoot() {
      if (hasNativeShadowDomSupport && this.useShadow === true) {
        return super.renderRoot || shadow(this);
      } else {
        return this;
      }
    }

    renderer(root, render) {
      this.html = this.html || bind(root);
      render();
    }
  }
};
<|endoftext|>


<commit_before>/*
 * This program was produced for the U.S. Agency for International Development. It was prepared by the USAID | DELIVER PROJECT, Task Order 4. It is part of a project which utilizes code originally licensed under the terms of the Mozilla Public License (MPL) v2 and therefore is licensed under MPL v2 or later.
 *
 * This program is free software: you can redistribute it and/or modify it under the terms of the Mozilla Public License as published by the Mozilla Foundation, either version 2 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 Mozilla Public License for more details.
 *
 * You should have received a copy of the Mozilla Public License along with this program. If not, see http://www.mozilla.org/MPL/
 */

function ListMailinglabelsController($scope,$filter, ngTableParams, MailingLabels, ReportFacilityTypes,RequisitionGroups, $http, $routeParams,$location) {

    $scope.filterGrid = function (){
       $scope.getPagedDataAsync(0, 0);
    };

    RequisitionGroups.get(function (data) {
        $scope.requisitionGroups = data.requisitionGroupList;
        $scope.requisitionGroups.unshift({'name':'-- All Requisition Groups --','id':'0'});
    });

    ReportFacilityTypes.get(function(data) {
        $scope.facilityTypes = data.facilityTypes;
        $scope.facilityTypes.unshift({'name':'-- All Facility Types --','id':'0'});
    });

    $scope.exportReport   = function (type){
        var url = '/reports/download/mailinglabels/' + type +'?facilityCodeFilter=' +  $scope.filterObject.facilityCodeFilter + '&facilityNameFilter=' +  $scope.filterObject.facilityNameFilter + '&facilityTypeId=' +  $scope.filterObject.facilityTypeId ;
        if(type == "mailing-list"){
            url = '/reports/download/mailinglabels/list/' + "pdf" +'?facilityCodeFilter=' +  $scope.filterObject.facilityCodeFilter + '&facilityNameFilter=' +  $scope.filterObject.facilityNameFilter + '&facilityTypeId=' +  $scope.filterObject.facilityTypeId ;
        }
        window.open(url);
    };

    // the grid options
    $scope.tableParams = new ngTableParams({
        page: 1,            // show first page
        total: 0,           // length of data
        count: 25           // count per page
    });

    $scope.paramsChanged = function(params) {

        // slice array data on pages
        if($scope.data === undefined ){
            $scope.datarows = [];
            params.total = 0;
        }else{
            var data = $scope.data;
            var orderedData = params.filter ? $filter('filter')(data, params.filter) : data;
            orderedData = params.sorting ?  $filter('orderBy')(orderedData, params.orderBy()) : data;

            params.total = orderedData.length;
            $scope.datarows = orderedData.slice( (params.page - 1) * params.count,  params.page * params.count );
            var i = 0;
            var baseIndex = params.count * (params.page - 1) + 1;
            while(i < $scope.datarows.length){
                $scope.datarows[i].no = baseIndex + i;
                i++;
            }
        }
    };

    // watch for changes of parameters
    $scope.$watch('tableParams', $scope.paramsChanged , true);

    $scope.getPagedDataAsync = function (pageSize, page) {
        var params =  {
            "max" : 10000,
            "page" : 1
        };

        //filter form data section
        $scope.filterObject = {
            facilityTypeId : $scope.facilityTypeId,
            rgroupId :  $scope.rgroupId
        };

        // copy the filters over
        $.each($scope.filterObject, function(index, value) {
           params[index] = value;
        });
        // go
        MailingLabels.get(params, function(data) {
            $scope.data = data.pages.rows ;
            $scope.paramsChanged($scope.tableParams);
        });
    };

    $scope.filterGrid();
}
<commit_msg>ELMIS-982: facility list report - apply same filter for pdf and excel exports<commit_after>/*
 * This program was produced for the U.S. Agency for International Development. It was prepared by the USAID | DELIVER PROJECT, Task Order 4. It is part of a project which utilizes code originally licensed under the terms of the Mozilla Public License (MPL) v2 and therefore is licensed under MPL v2 or later.
 *
 * This program is free software: you can redistribute it and/or modify it under the terms of the Mozilla Public License as published by the Mozilla Foundation, either version 2 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 Mozilla Public License for more details.
 *
 * You should have received a copy of the Mozilla Public License along with this program. If not, see http://www.mozilla.org/MPL/
 */

function ListMailinglabelsController($scope,$filter, ngTableParams, MailingLabels, ReportFacilityTypes,RequisitionGroups, $http, $routeParams,$location) {

    $scope.filterGrid = function (){
       $scope.getPagedDataAsync(0, 0);
    };

    RequisitionGroups.get(function (data) {
        $scope.requisitionGroups = data.requisitionGroupList;
        $scope.requisitionGroups.unshift({'name':'-- All Requisition Groups --','id':'0'});
    });

    ReportFacilityTypes.get(function(data) {
        $scope.facilityTypes = data.facilityTypes;
        $scope.facilityTypes.unshift({'name':'-- All Facility Types --','id':'0'});
    });

    $scope.exportReport   = function (type){

      $scope.filterObject = {
        facilityTypeId : $scope.facilityTypeId,
        rgroupId :  $scope.rgroupId
      };
      var params = jQuery.param($scope.filterObject);

      var url = '/reports/download/mailinglabels/' + type +'?' + params ;
      if(type == "mailing-list"){
          url = '/reports/download/mailinglabels/list/' + "pdf" +'?' + params ;
      }
      window.open(url);
    };

    // the grid options
    $scope.tableParams = new ngTableParams({
        page: 1,            // show first page
        total: 0,           // length of data
        count: 25           // count per page
    });

    $scope.paramsChanged = function(params) {

        // slice array data on pages
        if($scope.data === undefined ){
            $scope.datarows = [];
            params.total = 0;
        }else{
            var data = $scope.data;
            var orderedData = params.filter ? $filter('filter')(data, params.filter) : data;
            orderedData = params.sorting ?  $filter('orderBy')(orderedData, params.orderBy()) : data;

            params.total = orderedData.length;
            $scope.datarows = orderedData.slice( (params.page - 1) * params.count,  params.page * params.count );
            var i = 0;
            var baseIndex = params.count * (params.page - 1) + 1;
            while(i < $scope.datarows.length){
                $scope.datarows[i].no = baseIndex + i;
                i++;
            }
        }
    };

    // watch for changes of parameters
    $scope.$watch('tableParams', $scope.paramsChanged , true);

    $scope.getPagedDataAsync = function (pageSize, page) {
        var params =  {
            "max" : 10000,
            "page" : 1
        };

        //filter form data section
        $scope.filterObject = {
            facilityTypeId : $scope.facilityTypeId,
            rgroupId :  $scope.rgroupId
        };

        // copy the filters over
        $.each($scope.filterObject, function(index, value) {
           params[index] = value;
        });
        // go
        MailingLabels.get(params, function(data) {
            $scope.data = data.pages.rows ;
            $scope.paramsChanged($scope.tableParams);
        });
    };

    $scope.filterGrid();
}
<|endoftext|>


<commit_before>module.exports = {
	rules: {
		'camelcase': 0,
		'comma-dangle': [2, 'never'],
		'consistent-return': 0,
		'curly': 0,
		'default-case': 0,
		'eqeqeq': [2, 'smart'],
		'func-names': 0,
		'guard-for-in': 2,
		'keyword-spacing': [2, { before: true, after: true }],
		'max-len': 0,
		'new-cap': [2, { newIsCapExceptions: ['acl.memoryBackend', 'acl'] }],
		'no-bitwise': 0,
		'no-caller': 2,
		'no-console': 0,
		'no-else-return': 0,
		'no-empty-class': 0,
		'no-param-reassign': 0,
		'no-shadow': 0,
		'no-throw-literal': 2,
		'no-trailing-spaces': 2,
		'no-undef': 2,
		'no-unneeded-ternary': 2,
		'no-unreachable': 2,
		'no-underscore-dangle': 0,
		'no-unused-expressions': 0,
		'no-unused-vars': 0,
		'no-use-before-define': [1, 'nofunc'],
		'no-var': 0,
		'one-var': [0, 'never'],
		'one-var-declaration-per-line': [2, 'always'],
		'padded-blocks': 0,
		'spaced-comment': [2, 'always'],
		'strict': 0,
		'quote-props': 0,
		'quotes': [0, 'single'],
		'wrap-iife': [2, 'outside'],
		'vars-on-top': 0
	},
	env: {
		node: true,
		browser: true,
		jasmine: true,
		mocha: true,
		jquery: true,
		es6: true
	},
	globals: {
		angular: true,
		by: true,
		browser: true,
		element: true,
		inject: true,
		io: true,
		moment: true,
		Modernizr: true,
		Promise: true,
		__TESTING__: true,
		_: false,
		ApplicationConfiguration: true
	},
	parserOptions: {
		sourceType: 'module'
	}
};
<commit_msg>BA-1151 - Update eslintrc<commit_after>module.exports = {
	rules: {
		'camelcase': 0,
		'comma-dangle': [2, 'never'],
		'consistent-return': 0,
		'curly': 0,
		'default-case': 0,
		'eqeqeq': [2, 'smart'],
		'func-names': 0,
		'guard-for-in': 2,
		'keyword-spacing': [2, { before: true, after: true }],
		'max-len': 0,
		'new-cap': [2, { newIsCapExceptions: ['acl.memoryBackend', 'acl'] }],
		'no-bitwise': 0,
		'no-caller': 2,
		'no-console': 0,
		'no-else-return': 0,
		'no-empty-class': 0,
		'no-param-reassign': 0,
		'no-shadow': 0,
		'no-throw-literal': 2,
		'no-trailing-spaces': 2,
		'no-undef': 2,
		'no-unneeded-ternary': 2,
		'no-unreachable': 2,
		'no-underscore-dangle': 0,
		'no-unused-expressions': 0,
		'no-unused-vars': 0,
		'no-use-before-define': [1, 'nofunc'],
		'no-var': 0,
		'one-var': [0, 'never'],
		'one-var-declaration-per-line': [2, 'always'],
		'padded-blocks': 0,
		'spaced-comment': [2, 'always'],
		'strict': 0,
		'quote-props': 0,
		'quotes': [0, 'single'],
		'wrap-iife': [2, 'outside'],
		'vars-on-top': 0
	},
	env: {
		node: true,
		browser: true,
		jasmine: true,
		mocha: true,
		jquery: true,
		es6: true
	},
	globals: {
		angular: true,
		by: true,
		browser: true,
		element: true,
		inject: true,
		io: true,
		moment: true,
		Modernizr: true,
		Promise: true,
		__TESTING__: true,
		_: false,
		ApplicationConfiguration: true
	},
	parserOptions: {
		sourceType: 'module',
		ecmaVersion: 2017
	}
};
<|endoftext|>


<commit_before>$(document).ready(function () {

function update_product_image(event_source, product_id) {
    var $img = $(event_source).closest('tr.js_product, .oe_website_sale').find('span[data-oe-model^="product."][data-oe-type="image"] img:first, img.product_detail_img');
    $img.attr("src", "/website/image/product.product/" + product_id + "/image");
    $img.parent().attr('data-oe-model', 'product.product').attr('data-oe-id', product_id)
        .data('oe-model', 'product.product').data('oe-id', product_id);
}

$('.oe_website_sale').each(function () {
    var oe_website_sale = this;

    var $shippingDifferent = $("select[name='shipping_id']", oe_website_sale);
    $shippingDifferent.change(function (event) {
        var value = +$shippingDifferent.val();
        var data = $shippingDifferent.find("option:selected").data();
        var $snipping = $(".js_shipping", oe_website_sale);
        var $inputs = $snipping.find("input");
        var $selects = $snipping.find("select");

        $snipping.toggle(!!value);
        $inputs.attr("readonly", value <= 0 ? null : "readonly" ).prop("readonly", value <= 0 ? null : "readonly" );
        $selects.attr("disabled", value <= 0 ? null : "disabled" ).prop("disabled", value <= 0 ? null : "disabled" );

        $inputs.each(function () {
            $(this).val( data[$(this).attr("name")] || "" );
        });
    });

    $(oe_website_sale).on("change", 'input[name="add_qty"]', function (event) {
        product_ids = [];
        var product_dom = $(".js_product .js_add_cart_variants[data-attribute_value_ids]").last();
        product_dom.data("attribute_value_ids").forEach(function(entry) {
            product_ids.push(entry[0]);});
        var qty = $(event.target).closest('form').find('input[name="add_qty"]').val();

        openerp.jsonRpc("/shop/get_unit_price", 'call', {'product_ids': product_ids,'add_qty': parseInt(qty)})
        .then(function (data) {
            var current = product_dom.data("attribute_value_ids");
            for(var j=0; j < current.length; j++){
                current[j][2] = data[current[j][0]];
            }
            product_dom.attr("data-attribute_value_ids", JSON.stringify(current)).trigger("change");
        });
    });

    // change for css
    $(oe_website_sale).on('mouseup touchend', '.js_publish', function (ev) {
        $(ev.currentTarget).parents(".thumbnail").toggleClass("disabled");
    });

    $(oe_website_sale).find(".oe_cart input.js_quantity").on("change", function () {
        var $input = $(this);
        if ($input.data('update_change')) {
            return;
        }
        var value = parseInt($input.val(), 10);
        var $dom = $(this).closest('tr');
        var default_price = parseFloat($dom.find('.text-danger > span.oe_currency_value').text());
        var $dom_optional = $dom.nextUntil(':not(.optional_product.info)');
        var line_id = parseInt($input.data('line-id'),10);
        var product_id = parseInt($input.data('product-id'),10);
        var product_ids = [product_id];
        $dom_optional.each(function(){
            product_ids.push($(this).find('span[data-product-id]').data('product-id'));
        });
        if (isNaN(value)) value = 0;
        $input.data('update_change', true);
        openerp.jsonRpc("/shop/get_unit_price", 'call', {
            'product_ids': product_ids,
            'add_qty': value,
            'use_order_pricelist': true,
            'line_id': line_id})
        .then(function (res) {
            //basic case
            $dom.find('span.oe_currency_value').last().text(price_to_str(res[product_id]));
            $dom.find('.text-danger').toggle(res[product_id]<default_price && (default_price-res[product_id] > default_price/100));
            //optional case
            $dom_optional.each(function(){
                var id = $(this).find('span[data-product-id]').data('product-id');
                var price = parseFloat($(this).find(".text-danger > span.oe_currency_value").text());
                $(this).find("span.oe_currency_value").last().text(price_to_str(res[id]));
                $(this).find('.text-danger').toggle(res[id]<price && (price-res[id]>price/100));
            });
            openerp.jsonRpc("/shop/cart/update_json", 'call', {
            'line_id': line_id,
            'product_id': parseInt($input.data('product-id'),10),
            'set_qty': value})
            .then(function (data) {
                $input.data('update_change', false);
                if (value !== parseInt($input.val(), 10)) {
                    $input.trigger('change');
                    return;
                }
                if (!data.quantity) {
                    location.reload(true);
                    return;
                }
                var $q = $(".my_cart_quantity");
                $q.parent().parent().removeClass("hidden", !data.quantity);
                $q.html(data.cart_quantity).hide().fadeIn(600);

                $input.val(data.quantity);
                $('.js_quantity[data-line-id='+line_id+']').val(data.quantity).html(data.quantity);
                $("#cart_total").replaceWith(data['website_sale.total']);
            });
        });
    });

    // hack to add and rome from cart with json
    $(oe_website_sale).on('click', 'a.js_add_cart_json', function (ev) {
        ev.preventDefault();
        var $link = $(ev.currentTarget);
        var $input = $link.parent().parent().find("input");
        var min = parseFloat($input.data("min") || 0);
        var max = parseFloat($input.data("max") || Infinity);
        var quantity = ($link.has(".fa-minus").length ? -1 : 1) + parseFloat($input.val(),10);
        $input.val(quantity > min ? (quantity < max ? quantity : max) : min);
        $('input[name="'+$input.attr("name")+'"]').val(quantity > min ? (quantity < max ? quantity : max) : min);
        $input.change();
        return false;
    });

    $('.oe_website_sale .a-submit, #comment .a-submit').off('click').on('click', function () {
        $(this).closest('form').submit();
    });
    $('form.js_attributes input, form.js_attributes select', oe_website_sale).on('change', function () {
        $(this).closest("form").submit();
    });

    // change price when they are variants
    $('form.js_add_cart_json label', oe_website_sale).on('mouseup touchend', function (ev) {
        var $label = $(this);
        var $price = $label.parents("form:first").find(".oe_price .oe_currency_value");
        if (!$price.data("price")) {
            $price.data("price", parseFloat($price.text()));
        }
        var value = $price.data("price") + parseFloat($label.find(".badge span").text() || 0);
        var dec = value % 1;
        $price.html(value + (dec < 0.01 ? ".00" : (dec < 1 ? "0" : "") ));
    });
    // hightlight selected color
    $('.css_attribute_color input', oe_website_sale).on('change', function (ev) {
        $('.css_attribute_color').removeClass("active");
        $('.css_attribute_color:has(input:checked)').addClass("active");
    });

    // Copy from core.js that is not available in front end.
    function intersperse(str, indices, separator) {
        separator = separator || '';
        var result = [], last = str.length;

        for(var i=0; i<indices.length; ++i) {
            var section = indices[i];
            if (section === -1 || last <= 0) { break; }
            else if(section === 0 && i === 0) { break; }
            else if (section === 0) { section = indices[--i]; }
            result.push(str.substring(last-section, last));
            last -= section;
        }
        var s = str.substring(0, last);
        if (s) { result.push(s); }
        return result.reverse().join(separator);
    }
    function insert_thousand_seps(num) {
        var l10n = openerp._t.database.parameters;
        var negative = num[0] === '-';
        num = (negative ? num.slice(1) : num);
        // retro-compatibilit: if no website_id and so l10n.grouping = []
        var grouping = l10n.grouping instanceof Array ? l10n.grouping : JSON.parse(l10n.grouping);
        return (negative ? '-' : '') + intersperse(
            num, grouping, l10n.thousands_sep);
    }

    function price_to_str(price) {
        var l10n = openerp._t.database.parameters;
        var precision = 2;
        if ($(".decimal_precision").length) {
            var dec_precision = $(".decimal_precision").first().data('precision');
            //Math.log10 is not implemented in phantomJS
            dec_precision = Math.round(Math.log(1/parseFloat(dec_precision))/Math.log(10));
            if (!isNaN(dec_precision)) {
                precision = dec_precision;
            }
        }
        var formatted = _.str.sprintf('%.' + precision + 'f', price).split('.');
        formatted[0] = insert_thousand_seps(formatted[0]);
        return formatted.join(l10n.decimal_point);
    }

    $(oe_website_sale).on('change', 'input.js_product_change', function (ev) {
        var $parent = $(this).closest('.js_product');
        $parent.find(".oe_default_price:first .oe_currency_value").html( price_to_str(+$(this).data('lst_price')) );
        $parent.find(".oe_price:first .oe_currency_value").html(price_to_str(+$(this).data('price')) );
        update_product_image(this, +$(this).val());
    });

    $(oe_website_sale).on('change', 'input.js_variant_change, select.js_variant_change, ul[data-attribute_value_ids]', function (ev) {
        var $ul = $(ev.target).closest('.js_add_cart_variants');
        var $parent = $ul.closest('.js_product');
        var $product_id = $parent.find('input.product_id').first();
        var $price = $parent.find(".oe_price:first .oe_currency_value");
        var $default_price = $parent.find(".oe_default_price:first .oe_currency_value");
        var $optional_price = $parent.find(".oe_optional:first .oe_currency_value");
        var variant_ids = $ul.data("attribute_value_ids");
        var values = [];
        $parent.find('input.js_variant_change:checked, select.js_variant_change').each(function () {
            values.push(+$(this).val());
        });

        $parent.find("label").removeClass("text-muted css_not_available");

        var product_id = false;
        for (var k in variant_ids) {
            if (_.isEmpty(_.difference(variant_ids[k][1], values))) {
                openerp.website.ready(function() {
                    $price.html(price_to_str(variant_ids[k][2]));
                    $default_price.html(price_to_str(variant_ids[k][3]));
                });
                if (variant_ids[k][3]-variant_ids[k][2]>0.2) {
                    $default_price.closest('.oe_website_sale').addClass("discount");
                    $optional_price.closest('.oe_optional').show().css('text-decoration', 'line-through');
                } else {
                    $default_price.closest('.oe_website_sale').removeClass("discount");
                    $optional_price.closest('.oe_optional').hide();
                }
                product_id = variant_ids[k][0];
                break;
            }
        }

        if (product_id) {
            update_product_image(this, product_id);
        }

        $parent.find("input.js_variant_change:radio, select.js_variant_change").each(function () {
            var $input = $(this);
            var id = +$input.val();
            var values = [id];

            $parent.find("ul:not(:has(input.js_variant_change[value='" + id + "'])) input.js_variant_change:checked, select").each(function () {
                values.push(+$(this).val());
            });

            for (var k in variant_ids) {
                if (!_.difference(values, variant_ids[k][1]).length) {
                    return;
                }
            }
            $input.closest("label").addClass("css_not_available");
            $input.find("option[value='" + id + "']").addClass("css_not_available");
        });

        if (product_id) {
            $parent.removeClass("css_not_available");
            $product_id.val(product_id);
            $parent.find(".js_check_product").removeAttr("disabled");
        } else {
            $parent.addClass("css_not_available");
            $product_id.val(0);
            $parent.find(".js_check_product").attr("disabled", "disabled");
        }
    });

    $('div.js_product', oe_website_sale).each(function () {
        $('input.js_product_change', this).first().trigger('change');
    });

    $('.js_add_cart_variants', oe_website_sale).each(function () {
        $('input.js_variant_change, select.js_variant_change', this).first().trigger('change');
    });

    $(oe_website_sale).on('change', "select[name='country_id']", function () {
        var $select = $("select[name='state_id']");
        $select.find("option:not(:first)").hide();
        var nb = $select.find("option[data-country_id="+($(this).val() || 0)+"]").show().size();
        $select.parent().toggle(nb>1);
    });
    $(oe_website_sale).find("select[name='country_id']").change();

    $(oe_website_sale).on('change', "select[name='shipping_country_id']", function () {
        var $select = $("select[name='shipping_state_id']");
        $select.find("option:not(:first)").hide();
        var nb = $select.find("option[data-country_id="+($(this).val() || 0)+"]").show().size();
        $select.parent().toggle(nb>1);
    });
    $(oe_website_sale).find("select[name='shipping_country_id']").change();
});
});
<commit_msg>[FIX] website_sale: fix promise website.ready<commit_after>$(document).ready(function () {

function update_product_image(event_source, product_id) {
    var $img = $(event_source).closest('tr.js_product, .oe_website_sale').find('span[data-oe-model^="product."][data-oe-type="image"] img:first, img.product_detail_img');
    $img.attr("src", "/website/image/product.product/" + product_id + "/image");
    $img.parent().attr('data-oe-model', 'product.product').attr('data-oe-id', product_id)
        .data('oe-model', 'product.product').data('oe-id', product_id);
}

$('.oe_website_sale').each(function () {
    var oe_website_sale = this;

    var $shippingDifferent = $("select[name='shipping_id']", oe_website_sale);
    $shippingDifferent.change(function (event) {
        var value = +$shippingDifferent.val();
        var data = $shippingDifferent.find("option:selected").data();
        var $snipping = $(".js_shipping", oe_website_sale);
        var $inputs = $snipping.find("input");
        var $selects = $snipping.find("select");

        $snipping.toggle(!!value);
        $inputs.attr("readonly", value <= 0 ? null : "readonly" ).prop("readonly", value <= 0 ? null : "readonly" );
        $selects.attr("disabled", value <= 0 ? null : "disabled" ).prop("disabled", value <= 0 ? null : "disabled" );

        $inputs.each(function () {
            $(this).val( data[$(this).attr("name")] || "" );
        });
    });

    $(oe_website_sale).on("change", 'input[name="add_qty"]', function (event) {
        product_ids = [];
        var product_dom = $(".js_product .js_add_cart_variants[data-attribute_value_ids]").last();
        product_dom.data("attribute_value_ids").forEach(function(entry) {
            product_ids.push(entry[0]);});
        var qty = $(event.target).closest('form').find('input[name="add_qty"]').val();

        openerp.jsonRpc("/shop/get_unit_price", 'call', {'product_ids': product_ids,'add_qty': parseInt(qty)})
        .then(function (data) {
            var current = product_dom.data("attribute_value_ids");
            for(var j=0; j < current.length; j++){
                current[j][2] = data[current[j][0]];
            }
            product_dom.attr("data-attribute_value_ids", JSON.stringify(current)).trigger("change");
        });
    });

    // change for css
    $(oe_website_sale).on('mouseup touchend', '.js_publish', function (ev) {
        $(ev.currentTarget).parents(".thumbnail").toggleClass("disabled");
    });

    $(oe_website_sale).find(".oe_cart input.js_quantity").on("change", function () {
        var $input = $(this);
        if ($input.data('update_change')) {
            return;
        }
        var value = parseInt($input.val(), 10);
        var $dom = $(this).closest('tr');
        var default_price = parseFloat($dom.find('.text-danger > span.oe_currency_value').text());
        var $dom_optional = $dom.nextUntil(':not(.optional_product.info)');
        var line_id = parseInt($input.data('line-id'),10);
        var product_id = parseInt($input.data('product-id'),10);
        var product_ids = [product_id];
        $dom_optional.each(function(){
            product_ids.push($(this).find('span[data-product-id]').data('product-id'));
        });
        if (isNaN(value)) value = 0;
        $input.data('update_change', true);
        openerp.jsonRpc("/shop/get_unit_price", 'call', {
            'product_ids': product_ids,
            'add_qty': value,
            'use_order_pricelist': true,
            'line_id': line_id})
        .then(function (res) {
            //basic case
            $dom.find('span.oe_currency_value').last().text(price_to_str(res[product_id]));
            $dom.find('.text-danger').toggle(res[product_id]<default_price && (default_price-res[product_id] > default_price/100));
            //optional case
            $dom_optional.each(function(){
                var id = $(this).find('span[data-product-id]').data('product-id');
                var price = parseFloat($(this).find(".text-danger > span.oe_currency_value").text());
                $(this).find("span.oe_currency_value").last().text(price_to_str(res[id]));
                $(this).find('.text-danger').toggle(res[id]<price && (price-res[id]>price/100));
            });
            openerp.jsonRpc("/shop/cart/update_json", 'call', {
            'line_id': line_id,
            'product_id': parseInt($input.data('product-id'),10),
            'set_qty': value})
            .then(function (data) {
                $input.data('update_change', false);
                if (value !== parseInt($input.val(), 10)) {
                    $input.trigger('change');
                    return;
                }
                if (!data.quantity) {
                    location.reload(true);
                    return;
                }
                var $q = $(".my_cart_quantity");
                $q.parent().parent().removeClass("hidden", !data.quantity);
                $q.html(data.cart_quantity).hide().fadeIn(600);

                $input.val(data.quantity);
                $('.js_quantity[data-line-id='+line_id+']').val(data.quantity).html(data.quantity);
                $("#cart_total").replaceWith(data['website_sale.total']);
            });
        });
    });

    // hack to add and rome from cart with json
    $(oe_website_sale).on('click', 'a.js_add_cart_json', function (ev) {
        ev.preventDefault();
        var $link = $(ev.currentTarget);
        var $input = $link.parent().parent().find("input");
        var min = parseFloat($input.data("min") || 0);
        var max = parseFloat($input.data("max") || Infinity);
        var quantity = ($link.has(".fa-minus").length ? -1 : 1) + parseFloat($input.val(),10);
        $input.val(quantity > min ? (quantity < max ? quantity : max) : min);
        $('input[name="'+$input.attr("name")+'"]').val(quantity > min ? (quantity < max ? quantity : max) : min);
        $input.change();
        return false;
    });

    $('.oe_website_sale .a-submit, #comment .a-submit').off('click').on('click', function () {
        $(this).closest('form').submit();
    });
    $('form.js_attributes input, form.js_attributes select', oe_website_sale).on('change', function () {
        $(this).closest("form").submit();
    });

    // change price when they are variants
    $('form.js_add_cart_json label', oe_website_sale).on('mouseup touchend', function (ev) {
        var $label = $(this);
        var $price = $label.parents("form:first").find(".oe_price .oe_currency_value");
        if (!$price.data("price")) {
            $price.data("price", parseFloat($price.text()));
        }
        var value = $price.data("price") + parseFloat($label.find(".badge span").text() || 0);
        var dec = value % 1;
        $price.html(value + (dec < 0.01 ? ".00" : (dec < 1 ? "0" : "") ));
    });
    // hightlight selected color
    $('.css_attribute_color input', oe_website_sale).on('change', function (ev) {
        $('.css_attribute_color').removeClass("active");
        $('.css_attribute_color:has(input:checked)').addClass("active");
    });

    // Copy from core.js that is not available in front end.
    function intersperse(str, indices, separator) {
        separator = separator || '';
        var result = [], last = str.length;

        for(var i=0; i<indices.length; ++i) {
            var section = indices[i];
            if (section === -1 || last <= 0) { break; }
            else if(section === 0 && i === 0) { break; }
            else if (section === 0) { section = indices[--i]; }
            result.push(str.substring(last-section, last));
            last -= section;
        }
        var s = str.substring(0, last);
        if (s) { result.push(s); }
        return result.reverse().join(separator);
    }
    function insert_thousand_seps(num) {
        var l10n = openerp._t.database.parameters;
        var negative = num[0] === '-';
        num = (negative ? num.slice(1) : num);
        // retro-compatibilit: if no website_id and so l10n.grouping = []
        var grouping = l10n.grouping instanceof Array ? l10n.grouping : JSON.parse(l10n.grouping);
        return (negative ? '-' : '') + intersperse(
            num, grouping, l10n.thousands_sep);
    }

    function price_to_str(price) {
        var l10n = openerp._t.database.parameters;
        var precision = 2;
        if ($(".decimal_precision").length) {
            var dec_precision = $(".decimal_precision").first().data('precision');
            //Math.log10 is not implemented in phantomJS
            dec_precision = Math.round(Math.log(1/parseFloat(dec_precision))/Math.log(10));
            if (!isNaN(dec_precision)) {
                precision = dec_precision;
            }
        }
        var formatted = _.str.sprintf('%.' + precision + 'f', price).split('.');
        formatted[0] = insert_thousand_seps(formatted[0]);
        return formatted.join(l10n.decimal_point);
    }

    $(oe_website_sale).on('change', 'input.js_product_change', function (ev) {
        var $parent = $(this).closest('.js_product');
        $parent.find(".oe_default_price:first .oe_currency_value").html( price_to_str(+$(this).data('lst_price')) );
        $parent.find(".oe_price:first .oe_currency_value").html(price_to_str(+$(this).data('price')) );
        update_product_image(this, +$(this).val());
    });

    $(oe_website_sale).on('change', 'input.js_variant_change, select.js_variant_change, ul[data-attribute_value_ids]', function (ev) {
        var $ul = $(ev.target).closest('.js_add_cart_variants');
        var $parent = $ul.closest('.js_product');
        var $product_id = $parent.find('input.product_id').first();
        var $price = $parent.find(".oe_price:first .oe_currency_value");
        var $default_price = $parent.find(".oe_default_price:first .oe_currency_value");
        var $optional_price = $parent.find(".oe_optional:first .oe_currency_value");
        var variant_ids = $ul.data("attribute_value_ids");
        var values = [];
        $parent.find('input.js_variant_change:checked, select.js_variant_change').each(function () {
            values.push(+$(this).val());
        });

        $parent.find("label").removeClass("text-muted css_not_available");

        var product_id = false;
        for (var k in variant_ids) {
            if (_.isEmpty(_.difference(variant_ids[k][1], values))) {
                openerp.website.ready().then(function() {
                    $price.html(price_to_str(variant_ids[k][2]));
                    $default_price.html(price_to_str(variant_ids[k][3]));
                });
                if (variant_ids[k][3]-variant_ids[k][2]>0.2) {
                    $default_price.closest('.oe_website_sale').addClass("discount");
                    $optional_price.closest('.oe_optional').show().css('text-decoration', 'line-through');
                } else {
                    $default_price.closest('.oe_website_sale').removeClass("discount");
                    $optional_price.closest('.oe_optional').hide();
                }
                product_id = variant_ids[k][0];
                break;
            }
        }

        if (product_id) {
            update_product_image(this, product_id);
        }

        $parent.find("input.js_variant_change:radio, select.js_variant_change").each(function () {
            var $input = $(this);
            var id = +$input.val();
            var values = [id];

            $parent.find("ul:not(:has(input.js_variant_change[value='" + id + "'])) input.js_variant_change:checked, select").each(function () {
                values.push(+$(this).val());
            });

            for (var k in variant_ids) {
                if (!_.difference(values, variant_ids[k][1]).length) {
                    return;
                }
            }
            $input.closest("label").addClass("css_not_available");
            $input.find("option[value='" + id + "']").addClass("css_not_available");
        });

        if (product_id) {
            $parent.removeClass("css_not_available");
            $product_id.val(product_id);
            $parent.find(".js_check_product").removeAttr("disabled");
        } else {
            $parent.addClass("css_not_available");
            $product_id.val(0);
            $parent.find(".js_check_product").attr("disabled", "disabled");
        }
    });

    $('div.js_product', oe_website_sale).each(function () {
        $('input.js_product_change', this).first().trigger('change');
    });

    $('.js_add_cart_variants', oe_website_sale).each(function () {
        $('input.js_variant_change, select.js_variant_change', this).first().trigger('change');
    });

    $(oe_website_sale).on('change', "select[name='country_id']", function () {
        var $select = $("select[name='state_id']");
        $select.find("option:not(:first)").hide();
        var nb = $select.find("option[data-country_id="+($(this).val() || 0)+"]").show().size();
        $select.parent().toggle(nb>1);
    });
    $(oe_website_sale).find("select[name='country_id']").change();

    $(oe_website_sale).on('change', "select[name='shipping_country_id']", function () {
        var $select = $("select[name='shipping_state_id']");
        $select.find("option:not(:first)").hide();
        var nb = $select.find("option[data-country_id="+($(this).val() || 0)+"]").show().size();
        $select.parent().toggle(nb>1);
    });
    $(oe_website_sale).find("select[name='shipping_country_id']").change();
});
});
<|endoftext|>


<commit_before>/* jslint node: true, esnext: true */

'use strict';

const address = require('network-address'),
	url = require('url'),
	route = require('koa-route'),
	PromiseRepeat = require('promise-repeat'),
	endpoint = require('kronos-endpoint'),
	service = require('kronos-service'),
	ServiceConsumerMixin = require('kronos-service').ServiceConsumerMixin;

function createWatchEndpoint(name, owner, makeWatch, dataProvider) {
	let watch;

	const options = {
		createOpposite: true
	};

	options.willBeClosed = () => {
		owner.trace({
			endpoint: this.identifier,
			state: 'close'
		});

		if (watch) {
			watch.end();
			watch = undefined;
		}
	};

	options.hasBeenOpened = () => {
		owner.trace({
			endpoint: this.identifier,
			state: 'open'
		});

		watch = makeWatch();
		watch.on('change', (data, res) => this.opposite.receive(data));
		watch.on('error', err => owner.error({
			error: err,
			endpoint: this.identifier
		}));
	};

	const ep = new endpoint.ReceiveEndpoint(name, owner, options);

	ep.receive = request => {
		if (request) {
			if (request.update && watch === undefined) {

			} else if (request.update === false && watch) {
				watch.end();
				watch = undefined;
			}
		}

		return dataProvider();
	};

	return ep;
}

class ServiceConsul extends service.Service {
	static get name() {
		return 'consul';
	}

	get type() {
		return ServiceConsul.name;
	}

	get autostart() {
		return true;
	}

	constructor(config, owner) {
		super(config, owner);

		const svc = this;

		let watch;

		const nodesEndpoint = new endpoint.ReceiveEndpoint('nodes', this, {
			createOpposite: true,
			willBeClosed() {
				this.trace({
					endpoint: this.identifier,
					state: 'close'
				});

				if (watch) {
					watch.end();
					watch = undefined;
				}
			},
			hasBeenOpened() {
				this.trace({
					endpoint: this.identifier,
					state: 'open'
				});
			}
		});

		nodesEndpoint.receive = request => {
			if (request) {
				if (request.update && watch === undefined) {
					watch = this.consul.watch({
						method: this.consul.catalog.service.nodes,
						options: {
							service: this.serviceDefinition.name
						}
					});

					watch.on('change', (data, res) => nodesEndpoint.opposite.receive(data));
					watch.on('error', err => svc.error(err));
				} else if (request.update === false && watch) {
					watch.end();
					watch = undefined;
				}
			}

			return this.kronosNodes();
		};

		this.addEndpoint(nodesEndpoint);

		const options = {
			key: 'kronos',
			recurse: true
		};

		this.addEndpoint(createWatchEndpoint('kv', this, () => this.consul.watch({
			method: this.consul.kv.get,
			options: options
		}), () => this.consul.kv.get(options).then(r => {
			return {
				key: r.Key,
				value: r.Value
			};
		})));
	}

	get configurationAttributes() {
		const co = this.consulOptions;

		function consulOptionSetter(value, attribute) {
			if (value !== undefined) {
				co[attribute.name] = value;
			}
		}

		return Object.assign({
			host: {
				description: 'consul host',
				default: 'localhost',
				type: 'string',
				setter: consulOptionSetter
			},
			port: {
				description: 'consul port',
				default: 8500,
				type: 'integer',
				setter: consulOptionSetter
			},
			secure: {
				default: false,
				type: 'boolean',
				setter: consulOptionSetter
			},
			ca: {
				setter: consulOptionSetter
			},
			checkPath: {
				description: 'url path used for the kronos check',
				type: 'string',
				default: '/check'
			},
			checkInterval: {
				description: 'interval the kronos check is called',
				default: 10,
				type: 'duration'
			},
			checkTimeout: {
				description: 'timeout for the kronos check interval',
				default: 5,
				type: 'duration'
			},
			startTimeout: {
				description: 'timeout for the service startup',
				default: 600,
				type: 'duration'
			}

		}, super.configurationAttributes);
	}

	_configure(config) {
		if (this.consulOptions === undefined) {
			this.consulOptions = {
				promisify(fn) {
					return new Promise((resolve, reject) => {
						try {
							return fn((err, data, res) => {
								if (err) {
									err.res = res;
									return reject(err);
								}
								return resolve([data, res]);
							});
						} catch (err) {
							return reject(err);
						}
					});
				}
			};
		}

		const modified = super._configure(config);

		// TODO where does baseUrl come from ?
		delete this.consulOptions.baseUrl;

		// TODO repeat here ?
		this.consul = require('consul')(this.consulOptions);
		return modified;
	}

	get serviceDefinition() {
		function asSeconds(value) {
			return value instanceof String && value.matches(/s$/) ? value : `${value}s`;
		}

		return {
			name: 'kronos',
			id: this.owner.id,
			port: this.listener.port,
			address: this.listener.address,
			tags: this.tags,
			check: {
				id: this.listener.url + this.checkPath,
				http: this.listener.url + this.checkPath,
				interval: asSeconds(this.checkInterval),
				timeout: asSeconds(this.checkTimeout)
			}
		};
	}

	updateTags() {
		this.tags = Object.keys(this.owner.steps).map(name => `step:${name}`);
	}

	timeoutForTransition(transition) {
		if (transition.name === 'start') {
			return this.startTimeout * 1000; // 600000;
		}

		return super.timeoutForTransition(transition);
	}

	/**
	 * Register the kronos service in consul
	 * @return {Promise} that fullfills on succesfull startup
	 */
	_start() {
		return super._start().then(() => {
			this.updateTags();

			// wait until health-check and koa services are present
			return ServiceConsumerMixin.defineServiceConsumerProperties(this, {
				listener: {
					name: 'koa-admin',
					type: 'koa'
				},
				hcs: {
					name: 'health-check',
					type: 'health-check'
				}
			}, this.owner, true).then(() =>
				this.listener.start().then(() =>
					/*	PromiseRepeat(
							() =>*/
					this.consul.agent.service.register(this.serviceDefinition).then(fullfilled => {
						this._stepRegisteredListener = step => {
							this.updateTags();
							this.update(5000);
						};

						this.owner.addListener('stepRegistered', this._stepRegisteredListener);

						this.listener.koa.use(route.get(this.checkPath, ctx =>
							this.hcs.endpoints.state.receive({}).then(r => {
								this.status = r ? 200 : 300;
								ctx.body = r ? 'OK' : 'ERROR';
							})
						));

						return Promise.resolve();
					}), {
						maxAttempts: 5,
						minTimeout: 1000,
						maxTimeout: this.startTimeout * 1000,
						throttle: 1000
					})
				//	)
			);
		});
	}

	/**
	 * deregister the service from consul
	 * @return {Promise} that fullfills when the deregitering has finished
	 */
	_stop() {
		return this.consul.agent.service.deregister(this.serviceDefinition.id).then(f => {
			if (this._stepRegisteredListener) {
				this.owner.removeListener('stepRegistered', this._stepRegisteredListener);
				this._stepRegisteredListener = undefined;
			}
			return Promise.resolve();
		});
	}

	/**
	 * Update service definition in consul
	 * @param {Number} delay time to wait before doing the unregister/register action
	 */
	update(delay) {
		const reregister = () =>
			this.consul.agent.service.deregister(this.serviceDefinition.id)
			.then(() => this.consul.agent.service.register(this.serviceDefinition));

		if (this._updateTimer) {
			clearTimeout(this._updateTimer);
		}

		if (delay) {
			this._updateTimer = setTimeout(reregister, delay);
		} else {
			return reregister();
		}
	}

	kronosNodes() {
		return this.consul.catalog.service.nodes({
			service: this.serviceDefinition.name
		}).then(response => response[0]);
	}

	registerService(name, options) {
		this.info({
			message: 'registerService',
			name: name,
			options: options
		});

		const u = url.parse(options.url);

		/*
				const watch = this.consul.watch({
					method: this.consul.kv.get,
					options: {
						key: `services/${name}/${this.id}/url`
					}
				});

				watch.on('change', (data, res) => {
					console.log('change data:', data);
				});

				watch.on('error', err => console.log('error:', err));
		*/

		return this.consul.kv.set({
			key: `services/${name}/${this.owner.id}/url`,
			value: options.url
		});

		/*
				const serviceDefinition = {
					name: name,
					id: u.href,
					address: u.hostname,
					port: parseInt(u.port, 10),
					tags: options.tags
				};

				return consul.agent.service.register(serviceDefinition).then(f => {
					//this.info(`registered: ${JSON.stringify(f)}`);
					return Promise.resolve();
				});
				*/
	}

	unregisterService(name) {
		this.info({
			message: 'unregisterService',
			name: name
		});

		return this.consul.kv.del({
			key: `services/${name}/${this.id}`,
			recurse: true
		});

		//return consul.agent.service.deregister(name);
	}

	* serviceURLs(name) {
		let si = [];

		let firstPromise = this.consul.kv.get({
				key: `services/${name}`,
				recurse: true
			})
			.then(data => {
				si = data[0].map(d => d.Value);
				firstPromise = undefined;
				return si.length === 0 ? Promise.reject() : Promise.resolve(si[0]);
			});

		while (firstPromise) {
			yield firstPromise;
			//console.log(`size: ${si.length} ${firstPromise}`);
		}

		if (si.length) {
			for (let i = 1;; i++) {
				if (i >= si.length) {
					i = 0;
				}
				//console.log(`yield: ${i} ${si.length}`);
				yield Promise.resolve(si[i]);
			}
		}
		return undefined;
	}
}

module.exports.registerWithManager = manager =>
	manager.registerServiceFactory(ServiceConsul).then(sf =>
		manager.declareService({
			type: sf.name,
			name: 'registry'
		}));
<commit_msg>fix: deliver ky endpoints result as dictionay<commit_after>/* jslint node: true, esnext: true */

'use strict';

const address = require('network-address'),
	url = require('url'),
	route = require('koa-route'),
	PromiseRepeat = require('promise-repeat'),
	endpoint = require('kronos-endpoint'),
	service = require('kronos-service'),
	ServiceConsumerMixin = require('kronos-service').ServiceConsumerMixin;

function createWatchEndpoint(name, owner, makeWatch, dataProvider) {
	let watch;

	const options = {
		createOpposite: true
	};

	options.willBeClosed = () => {
		owner.trace({
			endpoint: this.identifier,
			state: 'close'
		});

		if (watch) {
			watch.end();
			watch = undefined;
		}
	};

	options.hasBeenOpened = () => {
		owner.trace({
			endpoint: this.identifier,
			state: 'open'
		});

		watch = makeWatch();
		watch.on('change', (data, res) => this.opposite.receive(data));
		watch.on('error', err => owner.error({
			error: err,
			endpoint: this.identifier
		}));
	};

	const ep = new endpoint.ReceiveEndpoint(name, owner, options);

	ep.receive = request => {
		if (request) {
			if (request.update && watch === undefined) {

			} else if (request.update === false && watch) {
				watch.end();
				watch = undefined;
			}
		}

		return dataProvider();
	};

	return ep;
}

class ServiceConsul extends service.Service {
	static get name() {
		return 'consul';
	}

	get type() {
		return ServiceConsul.name;
	}

	get autostart() {
		return true;
	}

	constructor(config, owner) {
		super(config, owner);

		const svc = this;

		let watch;

		const nodesEndpoint = new endpoint.ReceiveEndpoint('nodes', this, {
			createOpposite: true,
			willBeClosed() {
				this.trace({
					endpoint: this.identifier,
					state: 'close'
				});

				if (watch) {
					watch.end();
					watch = undefined;
				}
			},
			hasBeenOpened() {
				this.trace({
					endpoint: this.identifier,
					state: 'open'
				});
			}
		});

		nodesEndpoint.receive = request => {
			if (request) {
				if (request.update && watch === undefined) {
					watch = this.consul.watch({
						method: this.consul.catalog.service.nodes,
						options: {
							service: this.serviceDefinition.name
						}
					});

					watch.on('change', (data, res) => {
						console.log(data);
						return nodesEndpoint.opposite.receive(data);
					});
					watch.on('error', err => svc.error(err));
				} else if (request.update === false && watch) {
					watch.end();
					watch = undefined;
				}
			}

			return this.kronosNodes();
		};

		this.addEndpoint(nodesEndpoint);

		const options = {
			key: '',
			recurse: true
		};

		this.addEndpoint(createWatchEndpoint('kv', this, () => this.consul.watch({
			method: this.consul.kv.get,
			options: options
		}), () => this.consul.kv.get(options).then(r => {
			const dict = {};
			r[0].forEach(e => dict[e.Key] = e.Value);
			//console.log(dict);
			return dict;
		})));
	}

	get configurationAttributes() {
		const co = this.consulOptions;

		function consulOptionSetter(value, attribute) {
			if (value !== undefined) {
				co[attribute.name] = value;
			}
		}

		return Object.assign({
			host: {
				description: 'consul host',
				default: 'localhost',
				type: 'string',
				setter: consulOptionSetter
			},
			port: {
				description: 'consul port',
				default: 8500,
				type: 'integer',
				setter: consulOptionSetter
			},
			secure: {
				default: false,
				type: 'boolean',
				setter: consulOptionSetter
			},
			ca: {
				setter: consulOptionSetter
			},
			checkPath: {
				description: 'url path used for the kronos check',
				type: 'string',
				default: '/check'
			},
			checkInterval: {
				description: 'interval the kronos check is called',
				default: 10,
				type: 'duration'
			},
			checkTimeout: {
				description: 'timeout for the kronos check interval',
				default: 5,
				type: 'duration'
			},
			startTimeout: {
				description: 'timeout for the service startup',
				default: 600,
				type: 'duration'
			}

		}, super.configurationAttributes);
	}

	_configure(config) {
		if (this.consulOptions === undefined) {
			this.consulOptions = {
				promisify(fn) {
					return new Promise((resolve, reject) => {
						try {
							return fn((err, data, res) => {
								if (err) {
									err.res = res;
									return reject(err);
								}
								return resolve([data, res]);
							});
						} catch (err) {
							return reject(err);
						}
					});
				}
			};
		}

		const modified = super._configure(config);

		// TODO where does baseUrl come from ?
		delete this.consulOptions.baseUrl;

		// TODO repeat here ?
		this.consul = require('consul')(this.consulOptions);
		return modified;
	}

	get serviceDefinition() {
		function asSeconds(value) {
			return value instanceof String && value.matches(/s$/) ? value : `${value}s`;
		}

		return {
			name: 'kronos',
			id: this.owner.id,
			port: this.listener.port,
			address: this.listener.address,
			tags: this.tags,
			check: {
				id: this.listener.url + this.checkPath,
				http: this.listener.url + this.checkPath,
				interval: asSeconds(this.checkInterval),
				timeout: asSeconds(this.checkTimeout)
			}
		};
	}

	updateTags() {
		this.tags = Object.keys(this.owner.steps).map(name => `step:${name}`);
	}

	timeoutForTransition(transition) {
		if (transition.name === 'start') {
			return this.startTimeout * 1000; // 600000;
		}

		return super.timeoutForTransition(transition);
	}

	/**
	 * Register the kronos service in consul
	 * @return {Promise} that fullfills on succesfull startup
	 */
	_start() {
		return super._start().then(() => {
			this.updateTags();

			// wait until health-check and koa services are present
			return ServiceConsumerMixin.defineServiceConsumerProperties(this, {
				listener: {
					name: 'koa-admin',
					type: 'koa'
				},
				hcs: {
					name: 'health-check',
					type: 'health-check'
				}
			}, this.owner, true).then(() =>
				this.listener.start().then(() =>
					/*	PromiseRepeat(
							() =>*/
					this.consul.agent.service.register(this.serviceDefinition).then(fullfilled => {
						this._stepRegisteredListener = step => {
							this.updateTags();
							this.update(5000);
						};

						this.owner.addListener('stepRegistered', this._stepRegisteredListener);

						this.listener.koa.use(route.get(this.checkPath, ctx =>
							this.hcs.endpoints.state.receive({}).then(r => {
								this.status = r ? 200 : 300;
								ctx.body = r ? 'OK' : 'ERROR';
							})
						));

						return Promise.resolve();
					}), {
						maxAttempts: 5,
						minTimeout: 1000,
						maxTimeout: this.startTimeout * 1000,
						throttle: 1000
					})
				//	)
			);
		});
	}

	/**
	 * deregister the service from consul
	 * @return {Promise} that fullfills when the deregitering has finished
	 */
	_stop() {
		return this.consul.agent.service.deregister(this.serviceDefinition.id).then(f => {
			if (this._stepRegisteredListener) {
				this.owner.removeListener('stepRegistered', this._stepRegisteredListener);
				this._stepRegisteredListener = undefined;
			}
			return Promise.resolve();
		});
	}

	/**
	 * Update service definition in consul
	 * @param {Number} delay time to wait before doing the unregister/register action
	 */
	update(delay) {
		const reregister = () =>
			this.consul.agent.service.deregister(this.serviceDefinition.id)
			.then(() => this.consul.agent.service.register(this.serviceDefinition));

		if (this._updateTimer) {
			clearTimeout(this._updateTimer);
		}

		if (delay) {
			this._updateTimer = setTimeout(reregister, delay);
		} else {
			return reregister();
		}
	}

	kronosNodes() {
		return this.consul.catalog.service.nodes({
			service: this.serviceDefinition.name
		}).then(response => response[0]);
	}

	registerService(name, options) {
		this.info({
			message: 'registerService',
			name: name,
			options: options
		});

		const u = url.parse(options.url);

		/*
				const watch = this.consul.watch({
					method: this.consul.kv.get,
					options: {
						key: `services/${name}/${this.id}/url`
					}
				});

				watch.on('change', (data, res) => {
					console.log('change data:', data);
				});

				watch.on('error', err => console.log('error:', err));
		*/

		return this.consul.kv.set({
			key: `services/${name}/${this.owner.id}/url`,
			value: options.url
		});

		/*
				const serviceDefinition = {
					name: name,
					id: u.href,
					address: u.hostname,
					port: parseInt(u.port, 10),
					tags: options.tags
				};

				return consul.agent.service.register(serviceDefinition).then(f => {
					//this.info(`registered: ${JSON.stringify(f)}`);
					return Promise.resolve();
				});
				*/
	}

	unregisterService(name) {
		this.info({
			message: 'unregisterService',
			name: name
		});

		return this.consul.kv.del({
			key: `services/${name}/${this.id}`,
			recurse: true
		});

		//return consul.agent.service.deregister(name);
	}

	* serviceURLs(name) {
		let si = [];

		let firstPromise = this.consul.kv.get({
				key: `services/${name}`,
				recurse: true
			})
			.then(data => {
				si = data[0].map(d => d.Value);
				firstPromise = undefined;
				return si.length === 0 ? Promise.reject() : Promise.resolve(si[0]);
			});

		while (firstPromise) {
			yield firstPromise;
			//console.log(`size: ${si.length} ${firstPromise}`);
		}

		if (si.length) {
			for (let i = 1;; i++) {
				if (i >= si.length) {
					i = 0;
				}
				//console.log(`yield: ${i} ${si.length}`);
				yield Promise.resolve(si[i]);
			}
		}
		return undefined;
	}
}

module.exports.registerWithManager = manager =>
	manager.registerServiceFactory(ServiceConsul).then(sf =>
		manager.declareService({
			type: sf.name,
			name: 'registry'
		}));
<|endoftext|>


<commit_before>var cacheName='weatherPWA-step-6-1';var dataCacheName='weatherData-v1';var filesToCache=['/','/index.html','/scripts/appLogic.js','/styles/main.css','/resources/back.svg','/resources/loading.svg','/resources/refresh.svg'];self.addEventListener('install',function(e){console.log('[ServiceWorker] Install');e.waitUntil(caches.open(cacheName).then(function(cache){console.log('[ServiceWorker] Caching app shell');return cache.addAll(filesToCache)}))});self.addEventListener('activate',function(e){console.log('[ServiceWorker] Activate');e.waitUntil(caches.keys().then(function(keyList){return Promise.all(keyList.map(function(key){if(key!==cacheName&&key!==dataCacheName){console.log('[ServiceWorker] Removing old cache',key);return caches.delete(key)}}))}));return self.clients.claim()});self.addEventListener('fetch',function(e){console.log('[ServiceWorker] Fetch',e.request.url);var weatherURL;var newsURL='https://content.guardianapis.com/world';var articleURL;console.log(typeof e.request.url);if(e.request.url.includes(newsURL)){e.respondWith(caches.open(dataCacheName).then(function(cache){return fetch(e.request).then(function(response){cache.put(e.request.url,response.clone());return response})}))}
else{e.respondWith(caches.match(e.request).then(function(response){return response||fetch(e.request)}))}})<commit_msg>Update file paths<commit_after>var cacheName='weatherPWA-step-6-1';var dataCacheName='weatherData-v1';var filesToCache=['/','/index.html','./scripts/appLogic.js','./styles/main.css','./resources/back.svg','./resources/loading.svg','./resources/refresh.svg'];self.addEventListener('install',function(e){console.log('[ServiceWorker] Install');e.waitUntil(caches.open(cacheName).then(function(cache){console.log('[ServiceWorker] Caching app shell');return cache.addAll(filesToCache)}))});self.addEventListener('activate',function(e){console.log('[ServiceWorker] Activate');e.waitUntil(caches.keys().then(function(keyList){return Promise.all(keyList.map(function(key){if(key!==cacheName&&key!==dataCacheName){console.log('[ServiceWorker] Removing old cache',key);return caches.delete(key)}}))}));return self.clients.claim()});self.addEventListener('fetch',function(e){console.log('[ServiceWorker] Fetch',e.request.url);var weatherURL;var newsURL='https://content.guardianapis.com/world';var articleURL;console.log(typeof e.request.url);if(e.request.url.includes(newsURL)){e.respondWith(caches.open(dataCacheName).then(function(cache){return fetch(e.request).then(function(response){cache.put(e.request.url,response.clone());return response})}))}
else{e.respondWith(caches.match(e.request).then(function(response){return response||fetch(e.request)}))}})<|endoftext|>


<commit_before>
var
	extend               = req('/utilities/extend'),
	ServerMessage        = req('/lib/server/message'),
	ReplyNumerics        = req('/constants/reply-numerics'),
	ChannelNameValidator = req('/validators/channel-name');

class LinkChannelMessage extends ServerMessage {

	setDesiredChannelName(channel_name) {
		ChannelNameValidator.validate(channel_name);
		this.desired_channel_name = channel_name;
	}

	getDesiredChannelName() {
		return this.desired_channel_name;
	}

	setLinkedChannelName(channel_name) {
		ChannelNameValidator.validate(channel_name);
		this.linked_channel_name = channel_name;
	}

	getLinkedChannelName() {
		return this.linked_channel_name;
	}

	applyParsedParams(middle_params, trailing_param) {
		this.setDesiredChannelName(middle_params[0]);
		this.setLinkedChannelName(middle_params[1]);
		this.setBody(trailing_param);
	}

	serializeParams() {
		var
			desired_channel = this.getDesiredChannelName(),
			linked_channel  = this.getLinkedChannelName(),
			body            = this.getBody();

		return `${desired_channel} ${linked_channel} :${body}`;
	}

}

extend(LinkChannelMessage.prototype, {

	reply_numeric:        ReplyNumerics.ERR_LINKCHANNEL,
	desired_channel_name: null,
	linked_channel_name:  null,
	body:                 'Forwarding to another channel'

});

module.exports = LinkChannelMessage;
<commit_msg>Fix invalid deserialization of ERR_LINKCHANNEL<commit_after>
var
	extend               = req('/utilities/extend'),
	ServerMessage        = req('/lib/server/message'),
	ReplyNumerics        = req('/constants/reply-numerics'),
	ChannelNameValidator = req('/validators/channel-name');

class LinkChannelMessage extends ServerMessage {

	setDesiredChannelName(channel_name) {
		ChannelNameValidator.validate(channel_name);
		this.desired_channel_name = channel_name;
	}

	getDesiredChannelName() {
		return this.desired_channel_name;
	}

	setLinkedChannelName(channel_name) {
		ChannelNameValidator.validate(channel_name);
		this.linked_channel_name = channel_name;
	}

	getLinkedChannelName() {
		return this.linked_channel_name;
	}

	applyParsedParams(middle_params, trailing_param) {
		this.addTargetFromString(middle_params[0]);
		this.setDesiredChannelName(middle_params[1]);
		this.setLinkedChannelName(middle_params[2]);
		this.setBody(trailing_param);
	}

	serializeParams() {
		var
			targets         = this.serializeTargets(),
			desired_channel = this.getDesiredChannelName(),
			linked_channel  = this.getLinkedChannelName(),
			body            = this.getBody();

		return `${targets} ${desired_channel} ${linked_channel} :${body}`;
	}

}

extend(LinkChannelMessage.prototype, {

	reply_numeric:        ReplyNumerics.ERR_LINKCHANNEL,
	desired_channel_name: null,
	linked_channel_name:  null,
	body:                 'Forwarding to another channel'

});

module.exports = LinkChannelMessage;
<|endoftext|>


<commit_before>/*!
 * MiniBar 0.1.0
 * http://mobius.ovh/
 *
 * Released under the MIT license
 */
!function(t){"use strict";function e(t,e,o){var s;return function(){var i=this,n=arguments,r=function(){s=null,o||t.apply(i,n)},c=o&&!s;clearTimeout(s),s=setTimeout(r,e),c&&t.apply(i,n)}}var o={barType:"default",minBarSize:10,alwaysShowBars:!1,containerClass:"mb-container",contentClass:"mb-content",trackClass:"mb-track",barClass:"mb-bar",visibleClass:"mb-visible",progressClass:"mb-progress"},s=function(t,e){if(null==t)throw new TypeError("Cannot convert undefined or null to object");for(var o=Object(t),s=1;s<arguments.length;s++){var i=arguments[s];if(null!=i)for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&(o[n]=i[n])}return o},i=function(t,e,o){if("[object Object]"===Object.prototype.toString.call(t))for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&e.call(o,s,t[s]);else for(var i=0,n=t.length;i<n;i++)e.call(o,i,t[i])},n=function(t,e,o){t.addEventListener(e,o,!1)},r=function(t,e,o){t.removeEventListener(e,o)},c=function(t,e,o){var s=t&&t.style,n="[object Object]"===Object.prototype.toString.call(e);if(s){if(void 0===o&&!n)return o=window.getComputedStyle(t),void 0===e?o:o[e];n?i(e,function(t,e){t in s||(t="-webkit-"+t),s[t]=e+("string"==typeof e?"":"opacity"===t?"":"px")}):(e in s||(e="-webkit-"+e),s[e]=o+("string"==typeof o?"":"opacity"===e?"":"px"))}},a=function(t){var e=window,o=document,s=o.body,i=t.getBoundingClientRect(),n=void 0!==e.pageXOffset?e.pageXOffset:(o.documentElement||s.parentNode||s).scrollLeft,r=void 0!==e.pageYOffset?e.pageYOffset:(o.documentElement||s.parentNode||s).scrollTop;return{x:i.left+n,y:i.top+r,height:Math.round(i.height),width:Math.round(i.width)}},l=window.requestAnimationFrame||function(){var t=0;return window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||function(e){var o,s=(new Date).getTime();return o=Math.max(0,16-(s-t)),t=s+o,setTimeout(function(){e(s+o)},o)}}(),u=function(){var t=0,e=document.createElement("div");return e.style.cssText="width: 100; height: 100; overflow: scroll; position: absolute; top: -9999;",document.body.appendChild(e),t=e.offsetWidth-e.clientWidth,document.body.removeChild(e),t},h=function(t,i){this.container=t,"string"==typeof content&&(this.container=document.querySelector(t)),this.config=s({},o,i||window.MiniBarOptions||{}),this.css=window.getComputedStyle(this.container),this.scrollbarSize=u(),this.bars={x:{},y:{}},this.tracks={x:{},y:{}},this.trackPos={x:"left",y:"top"},this.trackSize={x:"width",y:"height"},this.scrollPos={x:"scrollLeft",y:"scrollTop"},this.scrollSize={x:"scrollWidth",y:"scrollHeight"},this.offsetAxis={x:"offsetX",y:"offsetY"},this.mouseAxis={x:"pageX",y:"pageY"},this.events={update:this.update.bind(this),scroll:this.scroll.bind(this),mouseenter:this.mouseenter.bind(this),mousedown:this.mousedown.bind(this),mousemove:this.mousemove.bind(this),mouseup:this.mouseup.bind(this)},this.events.debounce=e(this.events.update,50),this.init()};h.prototype.init=function(){var t=this;for(t.container.classList.add(t.config.containerClass),t.content=document.createElement("div"),t.content.classList.add(t.config.contentClass),t.config.alwaysShowBars&&t.container.classList.add(t.config.visibleClass);t.container.firstChild;)t.content.appendChild(t.container.firstChild);i(t.tracks,function(e,o){t.bars[e].node=document.createElement("div"),o.node=document.createElement("div"),o.node.classList.add(t.config.trackClass,t.config.trackClass+"-"+e),t.bars[e].node.classList.add(t.config.barClass),o.node.appendChild(t.bars[e].node),t.container.appendChild(o.node),"progress"===t.config.barType?(o.node.classList.add(t.config.progressClass),n(o.node,"mousedown",t.events.mousedown)):n(t.bars[e].node,"mousedown",t.events.mousedown)}),t.container.appendChild(t.content),t.container.style.position="static"===t.css.position?"relative":t.css.position,t.update(),n(t.content,"scroll",t.events.scroll),n(t.container,"mouseenter",t.events.mouseenter),n(window,"resize",t.events.debounce),n(document,"DOMContentLoaded",t.events.update),n(window,"load",t.events.update)},h.prototype.scroll=function(){this.updateScrollBars()},h.prototype.mouseenter=function(){this.updateScrollBars()},h.prototype.mousedown=function(t){t.preventDefault();var e="progress"===this.config.barType?"tracks":"bars",o=t.target===this[e].x.node?"x":"y";this.currentAxis=o,this.update(),this.container.classList.add(this.config.visibleClass),"progress"===this.config.barType?(this.origin={x:t.pageX-this.tracks[o].x,y:t.pageY-this.tracks[o].y},this.mousemove(t)):this.origin={x:t.pageX-this.bars[o].x,y:t.pageY-this.bars[o].y},n(document,"mousemove",this.events.mousemove),n(document,"mouseup",this.events.mouseup)},h.prototype.mousemove=function(t){t.preventDefault();var e,o,s=this,i=this.origin,n=s.tracks[s.currentAxis],r=n[s.trackSize[s.currentAxis]],c=s.rect[s.trackSize[s.currentAxis]];"progress"===s.config.barType?(e=t[s.mouseAxis[s.currentAxis]]-n[s.currentAxis],o=e/r*(s.content[s.scrollSize[s.currentAxis]]-c)):(e=t[s.mouseAxis[s.currentAxis]]-i[s.currentAxis]-n[s.currentAxis],o=e/r*s[s.scrollSize[s.currentAxis]]),l(function(){s.content[s.scrollPos[s.currentAxis]]=o})},h.prototype.mouseup=function(){this.origin={},this.currentAxis=null,this.container.classList.toggle(this.config.visibleClass,this.config.alwaysShowBars),r(document,"mousemove",this.events.mousemove),r(document,"mouseup",this.events.mouseup)},h.prototype.update=function(){var t=this;this.rect=a(this.container),this.scrollTop=this.content.scrollTop,this.scrollLeft=this.content.scrollLeft,this.scrollHeight=this.content.scrollHeight,this.scrollWidth=this.content.scrollWidth;var e=this.scrollWidth>this.rect.width,o=this.scrollHeight>this.rect.height;this.container.classList.toggle("mb-scroll-x",e),this.container.classList.toggle("mb-scroll-y",o),c(this.content,{overflow:"auto",marginBottom:e?-this.scrollbarSize:"",paddingBottom:e?this.scrollbarSize:"",marginRight:o?-this.scrollbarSize:"",paddingRight:o?this.scrollbarSize:""}),this.scrollX=e,this.scrollY=o,i(this.tracks,function(e,o){s(o,a(o.node)),s(t.bars[e],a(t.bars[e].node))}),this.updateScrollBars()},h.prototype.updateScrollBar=function(t){var e=this,o={},s=e.tracks[t][e.trackSize[t]],i=e.rect[e.trackSize[t]],n=e.content[e.scrollPos[t]],r=s/e[e.scrollSize[t]],a=n/(e[e.scrollSize[t]]-i);"progress"===e.config.barType?o[e.trackSize[t]]=Math.floor(s*a):(o[e.trackSize[t]]=Math.max(Math.floor(r*i),e.config.minBarSize),o[e.trackPos[t]]=Math.floor((s-o[e.trackSize[t]])*a)),l(function(){c(e.bars[t].node,o)})},h.prototype.updateScrollBars=function(){i(this.bars,function(t,e){this.updateScrollBar(t)},this)},h.prototype.destroy=function(){var t=this;for(r(t.container,"mouseenter",t.events.mouseenter),r(window,"resize",t.events.debounce),t.container.classList.remove(t.config.visibleClass),t.container.classList.remove(t.config.containerClass);t.content.firstChild;)t.container.appendChild(t.content.firstChild);i(t.tracks,function(e,o){t.container.removeChild(o.node),t.container.classList.remove("mb-scroll-"+e)}),t.container.removeChild(t.content),t.bars={x:{},y:{}},t.tracks={x:{},y:{}},t.content=null},t.MiniBar=h}(this);
<commit_msg>Update minibar.min.js<commit_after>/*!
 * MiniBar 0.1.1
 * http://mobius.ovh/
 *
 * Released under the MIT license
 */
!function(t){"use strict";function e(t,e,o){var s;return function(){var i=this,n=arguments,r=function(){s=null,o||t.apply(i,n)},c=o&&!s;clearTimeout(s),s=setTimeout(r,e),c&&t.apply(i,n)}}var o={barType:"default",minBarSize:10,alwaysShowBars:!1,containerClass:"mb-container",contentClass:"mb-content",trackClass:"mb-track",barClass:"mb-bar",visibleClass:"mb-visible",progressClass:"mb-progress"},s=function(t,e){if(null==t)throw new TypeError("Cannot convert undefined or null to object");for(var o=Object(t),s=1;s<arguments.length;s++){var i=arguments[s];if(null!=i)for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&(o[n]=i[n])}return o},i=function(t,e,o){if("[object Object]"===Object.prototype.toString.call(t))for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&e.call(o,s,t[s]);else for(var i=0,n=t.length;i<n;i++)e.call(o,i,t[i])},n=function(t,e,o){t.addEventListener(e,o,!1)},r=function(t,e,o){t.removeEventListener(e,o)},c=function(t,e,o){var s=t&&t.style,n="[object Object]"===Object.prototype.toString.call(e);if(s){if(void 0===o&&!n)return o=window.getComputedStyle(t),void 0===e?o:o[e];n?i(e,function(t,e){t in s||(t="-webkit-"+t),s[t]=e+("string"==typeof e?"":"opacity"===t?"":"px")}):(e in s||(e="-webkit-"+e),s[e]=o+("string"==typeof o?"":"opacity"===e?"":"px"))}},a=function(t){var e=window,o=document,s=o.body,i=t.getBoundingClientRect(),n=void 0!==e.pageXOffset?e.pageXOffset:(o.documentElement||s.parentNode||s).scrollLeft,r=void 0!==e.pageYOffset?e.pageYOffset:(o.documentElement||s.parentNode||s).scrollTop;return{x:i.left+n,y:i.top+r,height:Math.round(i.height),width:Math.round(i.width)}},l=window.requestAnimationFrame||function(){var t=0;return window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||function(e){var o,s=(new Date).getTime();return o=Math.max(0,16-(s-t)),t=s+o,setTimeout(function(){e(s+o)},o)}}(),u=function(){var t=0,e=document.createElement("div");return e.style.cssText="width: 100; height: 100; overflow: scroll; position: absolute; top: -9999;",document.body.appendChild(e),t=e.offsetWidth-e.clientWidth,document.body.removeChild(e),t},h=function(t,i){this.container=t,"string"==typeof content&&(this.container=document.querySelector(t)),this.config=s({},o,i||window.MiniBarOptions||{}),this.css=window.getComputedStyle(this.container),this.scrollbarSize=u(),this.bars={x:{},y:{}},this.tracks={x:{},y:{}},this.trackPos={x:"left",y:"top"},this.trackSize={x:"width",y:"height"},this.scrollPos={x:"scrollLeft",y:"scrollTop"},this.scrollSize={x:"scrollWidth",y:"scrollHeight"},this.offsetAxis={x:"offsetX",y:"offsetY"},this.mouseAxis={x:"pageX",y:"pageY"},this.events={update:this.update.bind(this),scroll:this.scroll.bind(this),mouseenter:this.mouseenter.bind(this),mousedown:this.mousedown.bind(this),mousemove:this.mousemove.bind(this),mouseup:this.mouseup.bind(this)},this.events.debounce=e(this.events.update,50),this.init()};h.prototype.init=function(){var t=this;for(t.container.classList.add(t.config.containerClass),t.content=document.createElement("div"),t.content.classList.add(t.config.contentClass),t.config.alwaysShowBars&&t.container.classList.add(t.config.visibleClass);t.container.firstChild;)t.content.appendChild(t.container.firstChild);i(t.tracks,function(e,o){t.bars[e].node=document.createElement("div"),o.node=document.createElement("div"),o.node.classList.add(t.config.trackClass,t.config.trackClass+"-"+e),t.bars[e].node.classList.add(t.config.barClass),o.node.appendChild(t.bars[e].node),t.container.appendChild(o.node),"progress"===t.config.barType?(o.node.classList.add(t.config.progressClass),n(o.node,"mousedown",t.events.mousedown)):n(t.bars[e].node,"mousedown",t.events.mousedown)}),t.container.appendChild(t.content),t.container.style.position="static"===t.css.position?"relative":t.css.position,t.update(),n(t.content,"scroll",t.events.scroll),n(t.container,"mouseenter",t.events.mouseenter),n(window,"resize",t.events.debounce),n(document,"DOMContentLoaded",t.events.update),n(window,"load",t.events.update)},h.prototype.scroll=function(){this.updateScrollBars()},h.prototype.mouseenter=function(){this.updateScrollBars()},h.prototype.mousedown=function(t){t.preventDefault();var e="progress"===this.config.barType?"tracks":"bars",o=t.target===this[e].x.node?"x":"y";this.currentAxis=o,this.update(),this.container.classList.add(this.config.visibleClass),"progress"===this.config.barType?(this.origin={x:t.pageX-this.tracks[o].x,y:t.pageY-this.tracks[o].y},this.mousemove(t)):this.origin={x:t.pageX-this.bars[o].x,y:t.pageY-this.bars[o].y},n(document,"mousemove",this.events.mousemove),n(document,"mouseup",this.events.mouseup)},h.prototype.mousemove=function(t){t.preventDefault();var e,o,s=this,i=this.origin,n=s.tracks[s.currentAxis],r=n[s.trackSize[s.currentAxis]],c=s.rect[s.trackSize[s.currentAxis]];"progress"===s.config.barType?(e=t[s.mouseAxis[s.currentAxis]]-n[s.currentAxis],o=e/r*(s.content[s.scrollSize[s.currentAxis]]-c)):(e=t[s.mouseAxis[s.currentAxis]]-i[s.currentAxis]-n[s.currentAxis],o=e/r*s[s.scrollSize[s.currentAxis]]),l(function(){s.content[s.scrollPos[s.currentAxis]]=o})},h.prototype.mouseup=function(){this.origin={},this.currentAxis=null,this.container.classList.toggle(this.config.visibleClass,this.config.alwaysShowBars),r(document,"mousemove",this.events.mousemove),r(document,"mouseup",this.events.mouseup)},h.prototype.update=function(){var t=this;this.rect=a(this.container),this.scrollTop=this.content.scrollTop,this.scrollLeft=this.content.scrollLeft,this.scrollHeight=this.content.scrollHeight,this.scrollWidth=this.content.scrollWidth;var e=this.scrollWidth>this.rect.width,o=this.scrollHeight>this.rect.height;this.container.classList.toggle("mb-scroll-x",e),this.container.classList.toggle("mb-scroll-y",o),c(this.content,{overflow:"auto",marginBottom:e?-this.scrollbarSize:"",paddingBottom:e?this.scrollbarSize:"",marginRight:o?-this.scrollbarSize:"",paddingRight:o?this.scrollbarSize:""}),this.scrollX=e,this.scrollY=o,i(this.tracks,function(e,o){s(o,a(o.node)),s(t.bars[e],a(t.bars[e].node))}),this.updateScrollBars()},h.prototype.updateScrollBar=function(t){var e=this,o={},s=e.tracks[t][e.trackSize[t]],i=e.rect[e.trackSize[t]],n=e.content[e.scrollPos[t]],r=s/e[e.scrollSize[t]],a=n/(e[e.scrollSize[t]]-i);"progress"===e.config.barType?o[e.trackSize[t]]=Math.floor(s*a):(o[e.trackSize[t]]=Math.max(Math.floor(r*i),e.config.minBarSize),o[e.trackPos[t]]=Math.floor((s-o[e.trackSize[t]])*a)),l(function(){c(e.bars[t].node,o)})},h.prototype.updateScrollBars=function(){i(this.bars,function(t,e){this.updateScrollBar(t)},this)},h.prototype.destroy=function(){var t=this;for(r(t.container,"mouseenter",t.events.mouseenter),r(window,"resize",t.events.debounce),t.container.classList.remove(t.config.visibleClass),t.container.classList.remove(t.config.containerClass);t.content.firstChild;)t.container.appendChild(t.content.firstChild);i(t.tracks,function(e,o){t.container.removeChild(o.node),t.container.classList.remove("mb-scroll-"+e)}),t.container.removeChild(t.content),t.bars={x:{},y:{}},t.tracks={x:{},y:{}},t.content=null},t.MiniBar=h}(this);
<|endoftext|>