<commit_before>(function() {

  var _slice = Array.prototype.slice;

  /**
   * Takes id and returns an element with that id (if one exists in a document)
   * @memberOf fabric.util
   * @param {String|HTMLElement} id
   * @return {HTMLElement|null}
   */
  function getById(id) {
    return typeof id === 'string' ? fabric.document.getElementById(id) : id;
  }

  var sliceCanConvertNodelists,
      /**
       * Converts an array-like object (e.g. arguments or NodeList) to an array
       * @memberOf fabric.util
       * @param {Object} arrayLike
       * @return {Array}
       */
      toArray = function(arrayLike) {
        return _slice.call(arrayLike, 0);
      };

  try {
    sliceCanConvertNodelists = toArray(fabric.document.childNodes) instanceof Array;
  }
  catch (err) { }

  if (!sliceCanConvertNodelists) {
    toArray = function(arrayLike) {
      var arr = new Array(arrayLike.length), i = arrayLike.length;
      while (i--) {
        arr[i] = arrayLike[i];
      }
      return arr;
    };
  }

  /**
   * Creates specified element with specified attributes
   * @memberOf fabric.util
   * @param {String} tagName Type of an element to create
   * @param {Object} [attributes] Attributes to set on an element
   * @return {HTMLElement} Newly created element
   */
  function makeElement(tagName, attributes) {
    var el = fabric.document.createElement(tagName);
    for (var prop in attributes) {
      if (prop === 'class') {
        el.className = attributes[prop];
      }
      else if (prop === 'for') {
        el.htmlFor = attributes[prop];
      }
      else {
        el.setAttribute(prop, attributes[prop]);
      }
    }
    return el;
  }

  /**
   * Adds class to an element
   * @memberOf fabric.util
   * @param {HTMLElement} element Element to add class to
   * @param {String} className Class to add to an element
   */
  function addClass(element, className) {
    if (element && (' ' + element.className + ' ').indexOf(' ' + className + ' ') === -1) {
      element.className += (element.className ? ' ' : '') + className;
    }
  }

  /**
   * Wraps element with another element
   * @memberOf fabric.util
   * @param {HTMLElement} element Element to wrap
   * @param {HTMLElement|String} wrapper Element to wrap with
   * @param {Object} [attributes] Attributes to set on a wrapper
   * @return {HTMLElement} wrapper
   */
  function wrapElement(element, wrapper, attributes) {
    if (typeof wrapper === 'string') {
      wrapper = makeElement(wrapper, attributes);
    }
    if (element.parentNode) {
      element.parentNode.replaceChild(wrapper, element);
    }
    wrapper.appendChild(element);
    return wrapper;
  }

  /**
   * Returns element scroll offsets
   * @memberOf fabric.util
   * @param {HTMLElement} element Element to operate on
   * @param {HTMLElement} upperCanvasEl Upper canvas element
   * @return {Object} Object with left/top values
   */
  function getScrollLeftTop(element, upperCanvasEl) {

    var firstFixedAncestor,
        origElement,
        left = 0,
        top = 0,
        docElement = fabric.document.documentElement,
        body = fabric.document.body || {
          scrollLeft: 0, scrollTop: 0
        };

    origElement = element;

    while (element && element.parentNode && !firstFixedAncestor) {

      element = element.parentNode;

      if (element !== fabric.document &&
          fabric.util.getElementStyle(element, 'position') === 'fixed') {
        firstFixedAncestor = element;
      }

      if (element !== fabric.document &&
          origElement !== upperCanvasEl &&
          fabric.util.getElementStyle(element, 'position') === 'absolute') {
        left = 0;
        top = 0;
      }
      else if (element === fabric.document) {
        left = body.scrollLeft || docElement.scrollLeft || 0;
        top = body.scrollTop ||  docElement.scrollTop || 0;
      }
      else {
        left += element.scrollLeft || 0;
        top += element.scrollTop || 0;
      }
    }

    return { left: left, top: top };
  }

  /**
   * Returns offset for a given element
   * @function
   * @memberOf fabric.util
   * @param {HTMLElement} element Element to get offset for
   * @return {Object} Object with "left" and "top" properties
   */
  function getElementOffset(element) {
    var docElem,
        doc = element && element.ownerDocument,
        box = { left: 0, top: 0 },
        offset = { left: 0, top: 0 },
        scrollLeftTop,
        offsetAttributes = {
          borderLeftWidth: 'left',
          borderTopWidth:  'top',
          paddingLeft:     'left',
          paddingTop:      'top'
        };

    if (!doc) {
      return { left: 0, top: 0 };
    }

    for (var attr in offsetAttributes) {
      offset[offsetAttributes[attr]] += parseInt(getElementStyle(element, attr), 10) || 0;
    }

    docElem = doc.documentElement;
    if ( typeof element.getBoundingClientRect !== 'undefined' ) {
      box = element.getBoundingClientRect();
    }

    scrollLeftTop = fabric.util.getScrollLeftTop(element, null);

    return {
      left: box.left + scrollLeftTop.left - (docElem.clientLeft || 0) + offset.left,
      top: box.top + scrollLeftTop.top - (docElem.clientTop || 0)  + offset.top
    };
  }

  /**
  * Returns style attribute value of a given element
  * @memberOf fabric.util
  * @param {HTMLElement} element Element to get style attribute for
  * @param {String} attr Style attribute to get for element
  * @return {String} Style attribute value of the given element.
  */
  var getElementStyle;
  if (fabric.document.defaultView && fabric.document.defaultView.getComputedStyle) {
    getElementStyle = function(element, attr) {
      return fabric.document.defaultView.getComputedStyle(element, null)[attr];
    };
  }
  else {
    getElementStyle = function(element, attr) {
      var value = element.style[attr];
      if (!value && element.currentStyle) {
        value = element.currentStyle[attr];
      }
      return value;
    };
  }

  (function () {
    var style = fabric.document.documentElement.style,
        selectProp = 'userSelect' in style
          ? 'userSelect'
          : 'MozUserSelect' in style
            ? 'MozUserSelect'
            : 'WebkitUserSelect' in style
              ? 'WebkitUserSelect'
              : 'KhtmlUserSelect' in style
                ? 'KhtmlUserSelect'
                : '';

    /**
     * Makes element unselectable
     * @memberOf fabric.util
     * @param {HTMLElement} element Element to make unselectable
     * @return {HTMLElement} Element that was passed in
     */
    function makeElementUnselectable(element) {
      if (typeof element.onselectstart !== 'undefined') {
        element.onselectstart = fabric.util.falseFunction;
      }
      if (selectProp) {
        element.style[selectProp] = 'none';
      }
      else if (typeof element.unselectable === 'string') {
        element.unselectable = 'on';
      }
      return element;
    }

    /**
     * Makes element selectable
     * @memberOf fabric.util
     * @param {HTMLElement} element Element to make selectable
     * @return {HTMLElement} Element that was passed in
     */
    function makeElementSelectable(element) {
      if (typeof element.onselectstart !== 'undefined') {
        element.onselectstart = null;
      }
      if (selectProp) {
        element.style[selectProp] = '';
      }
      else if (typeof element.unselectable === 'string') {
        element.unselectable = '';
      }
      return element;
    }

    fabric.util.makeElementUnselectable = makeElementUnselectable;
    fabric.util.makeElementSelectable = makeElementSelectable;
  })();

  (function() {

    /**
     * Inserts a script element with a given url into a document; invokes callback, when that script is finished loading
     * @memberOf fabric.util
     * @param {String} url URL of a script to load
     * @param {Function} callback Callback to execute when script is finished loading
     */
    function getScript(url, callback) {
      var headEl = fabric.document.getElementsByTagName('head')[0],
          scriptEl = fabric.document.createElement('script'),
          loading = true;

      /** @ignore */
      scriptEl.onload = /** @ignore */ scriptEl.onreadystatechange = function(e) {
        if (loading) {
          if (typeof this.readyState === 'string' &&
              this.readyState !== 'loaded' &&
              this.readyState !== 'complete') {
            return;
          }
          loading = false;
          callback(e || fabric.window.event);
          scriptEl = scriptEl.onload = scriptEl.onreadystatechange = null;
        }
      };
      scriptEl.src = url;
      headEl.appendChild(scriptEl);
      // causes issue in Opera
      // headEl.removeChild(scriptEl);
    }

    fabric.util.getScript = getScript;
  })();

  fabric.util.getById = getById;
  fabric.util.toArray = toArray;
  fabric.util.makeElement = makeElement;
  fabric.util.addClass = addClass;
  fabric.util.wrapElement = wrapElement;
  fabric.util.getScrollLeftTop = getScrollLeftTop;
  fabric.util.getElementOffset = getElementOffset;
  fabric.util.getElementStyle = getElementStyle;

})();
<commit_msg>Fix issue with document fragments.<commit_after>(function() {

  var _slice = Array.prototype.slice;

  /**
   * Takes id and returns an element with that id (if one exists in a document)
   * @memberOf fabric.util
   * @param {String|HTMLElement} id
   * @return {HTMLElement|null}
   */
  function getById(id) {
    return typeof id === 'string' ? fabric.document.getElementById(id) : id;
  }

  var sliceCanConvertNodelists,
      /**
       * Converts an array-like object (e.g. arguments or NodeList) to an array
       * @memberOf fabric.util
       * @param {Object} arrayLike
       * @return {Array}
       */
      toArray = function(arrayLike) {
        return _slice.call(arrayLike, 0);
      };

  try {
    sliceCanConvertNodelists = toArray(fabric.document.childNodes) instanceof Array;
  }
  catch (err) { }

  if (!sliceCanConvertNodelists) {
    toArray = function(arrayLike) {
      var arr = new Array(arrayLike.length), i = arrayLike.length;
      while (i--) {
        arr[i] = arrayLike[i];
      }
      return arr;
    };
  }

  /**
   * Creates specified element with specified attributes
   * @memberOf fabric.util
   * @param {String} tagName Type of an element to create
   * @param {Object} [attributes] Attributes to set on an element
   * @return {HTMLElement} Newly created element
   */
  function makeElement(tagName, attributes) {
    var el = fabric.document.createElement(tagName);
    for (var prop in attributes) {
      if (prop === 'class') {
        el.className = attributes[prop];
      }
      else if (prop === 'for') {
        el.htmlFor = attributes[prop];
      }
      else {
        el.setAttribute(prop, attributes[prop]);
      }
    }
    return el;
  }

  /**
   * Adds class to an element
   * @memberOf fabric.util
   * @param {HTMLElement} element Element to add class to
   * @param {String} className Class to add to an element
   */
  function addClass(element, className) {
    if (element && (' ' + element.className + ' ').indexOf(' ' + className + ' ') === -1) {
      element.className += (element.className ? ' ' : '') + className;
    }
  }

  /**
   * Wraps element with another element
   * @memberOf fabric.util
   * @param {HTMLElement} element Element to wrap
   * @param {HTMLElement|String} wrapper Element to wrap with
   * @param {Object} [attributes] Attributes to set on a wrapper
   * @return {HTMLElement} wrapper
   */
  function wrapElement(element, wrapper, attributes) {
    if (typeof wrapper === 'string') {
      wrapper = makeElement(wrapper, attributes);
    }
    if (element.parentNode) {
      element.parentNode.replaceChild(wrapper, element);
    }
    wrapper.appendChild(element);
    return wrapper;
  }

  /**
   * Returns element scroll offsets
   * @memberOf fabric.util
   * @param {HTMLElement} element Element to operate on
   * @param {HTMLElement} upperCanvasEl Upper canvas element
   * @return {Object} Object with left/top values
   */
  function getScrollLeftTop(element, upperCanvasEl) {

    var firstFixedAncestor,
        origElement,
        left = 0,
        top = 0,
        docElement = fabric.document.documentElement,
        body = fabric.document.body || {
          scrollLeft: 0, scrollTop: 0
        };

    origElement = element;

    while (element && element.parentNode && !firstFixedAncestor) {

      element = element.parentNode;

      if (element !== fabric.document &&
          fabric.util.getElementStyle(element, 'position') === 'fixed') {
        firstFixedAncestor = element;
      }

      if (element !== fabric.document &&
          origElement !== upperCanvasEl &&
          fabric.util.getElementStyle(element, 'position') === 'absolute') {
        left = 0;
        top = 0;
      }
      else if (element === fabric.document) {
        left = body.scrollLeft || docElement.scrollLeft || 0;
        top = body.scrollTop ||  docElement.scrollTop || 0;
      }
      else {
        left += element.scrollLeft || 0;
        top += element.scrollTop || 0;
      }
    }

    return { left: left, top: top };
  }

  /**
   * Returns offset for a given element
   * @function
   * @memberOf fabric.util
   * @param {HTMLElement} element Element to get offset for
   * @return {Object} Object with "left" and "top" properties
   */
  function getElementOffset(element) {
    var docElem,
        doc = element && element.ownerDocument,
        box = { left: 0, top: 0 },
        offset = { left: 0, top: 0 },
        scrollLeftTop,
        offsetAttributes = {
          borderLeftWidth: 'left',
          borderTopWidth:  'top',
          paddingLeft:     'left',
          paddingTop:      'top'
        };

    if (!doc) {
      return { left: 0, top: 0 };
    }

    for (var attr in offsetAttributes) {
      offset[offsetAttributes[attr]] += parseInt(getElementStyle(element, attr), 10) || 0;
    }

    docElem = doc.documentElement;
    if ( typeof element.getBoundingClientRect !== 'undefined' ) {
      box = element.getBoundingClientRect();
    }

    scrollLeftTop = fabric.util.getScrollLeftTop(element, null);

    return {
      left: box.left + scrollLeftTop.left - (docElem.clientLeft || 0) + offset.left,
      top: box.top + scrollLeftTop.top - (docElem.clientTop || 0)  + offset.top
    };
  }

  /**
  * Returns style attribute value of a given element
  * @memberOf fabric.util
  * @param {HTMLElement} element Element to get style attribute for
  * @param {String} attr Style attribute to get for element
  * @return {String} Style attribute value of the given element.
  */
  var getElementStyle;
  if (fabric.document.defaultView && fabric.document.defaultView.getComputedStyle) {
    getElementStyle = function(element, attr) {
      var style = fabric.document.defaultView.getComputedStyle(element, null);
      return style ? style[attr] : undefined;
    };
  }
  else {
    getElementStyle = function(element, attr) {
      var value = element.style[attr];
      if (!value && element.currentStyle) {
        value = element.currentStyle[attr];
      }
      return value;
    };
  }

  (function () {
    var style = fabric.document.documentElement.style,
        selectProp = 'userSelect' in style
          ? 'userSelect'
          : 'MozUserSelect' in style
            ? 'MozUserSelect'
            : 'WebkitUserSelect' in style
              ? 'WebkitUserSelect'
              : 'KhtmlUserSelect' in style
                ? 'KhtmlUserSelect'
                : '';

    /**
     * Makes element unselectable
     * @memberOf fabric.util
     * @param {HTMLElement} element Element to make unselectable
     * @return {HTMLElement} Element that was passed in
     */
    function makeElementUnselectable(element) {
      if (typeof element.onselectstart !== 'undefined') {
        element.onselectstart = fabric.util.falseFunction;
      }
      if (selectProp) {
        element.style[selectProp] = 'none';
      }
      else if (typeof element.unselectable === 'string') {
        element.unselectable = 'on';
      }
      return element;
    }

    /**
     * Makes element selectable
     * @memberOf fabric.util
     * @param {HTMLElement} element Element to make selectable
     * @return {HTMLElement} Element that was passed in
     */
    function makeElementSelectable(element) {
      if (typeof element.onselectstart !== 'undefined') {
        element.onselectstart = null;
      }
      if (selectProp) {
        element.style[selectProp] = '';
      }
      else if (typeof element.unselectable === 'string') {
        element.unselectable = '';
      }
      return element;
    }

    fabric.util.makeElementUnselectable = makeElementUnselectable;
    fabric.util.makeElementSelectable = makeElementSelectable;
  })();

  (function() {

    /**
     * Inserts a script element with a given url into a document; invokes callback, when that script is finished loading
     * @memberOf fabric.util
     * @param {String} url URL of a script to load
     * @param {Function} callback Callback to execute when script is finished loading
     */
    function getScript(url, callback) {
      var headEl = fabric.document.getElementsByTagName('head')[0],
          scriptEl = fabric.document.createElement('script'),
          loading = true;

      /** @ignore */
      scriptEl.onload = /** @ignore */ scriptEl.onreadystatechange = function(e) {
        if (loading) {
          if (typeof this.readyState === 'string' &&
              this.readyState !== 'loaded' &&
              this.readyState !== 'complete') {
            return;
          }
          loading = false;
          callback(e || fabric.window.event);
          scriptEl = scriptEl.onload = scriptEl.onreadystatechange = null;
        }
      };
      scriptEl.src = url;
      headEl.appendChild(scriptEl);
      // causes issue in Opera
      // headEl.removeChild(scriptEl);
    }

    fabric.util.getScript = getScript;
  })();

  fabric.util.getById = getById;
  fabric.util.toArray = toArray;
  fabric.util.makeElement = makeElement;
  fabric.util.addClass = addClass;
  fabric.util.wrapElement = wrapElement;
  fabric.util.getScrollLeftTop = getScrollLeftTop;
  fabric.util.getElementOffset = getElementOffset;
  fabric.util.getElementStyle = getElementStyle;

})();
<|endoftext|>


<commit_before>// Load the http module to create an http server.
var http = require('http');
const util = require('util')
var fs = require('fs');

var home ='/home/jtraver/dev/git/jtraver/qaa/ci_tools/docker-java/tmp1/build/reports/tests';

// console.log(util.inspect(myObject, {showHidden: false, depth: null}))

// alternative shortcut
// console.log(util.inspect(myObject, false, null))

// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
    // console.log("request = " + request);
    // console.log(util.inspect(request, false, null))
    // console.log("response = " + response);
    // console.log(util.inspect(response, false, null))
    // console.log("request.url = " + request.url);
    if (request.url == '/')
    {
        response.writeHead(200, {"Content-Type": "text/html"});
        fs.readFile(home + '/index.html', 'utf8', function (err, data) {
            if (err) {
                return console.log(err);
            }
            response.end(data)
        });
    }
    else if (request.url == '/classes/com.aerospike.server.test.Test3374.html' ||
        request.url == '/classes/com.aerospike.server.test.TestClusterFormation1.html' ||
        request.url == '/classes/com.aerospike.server.test.CdtReplicationTest.html' ||
        request.url == '/classes/com.aerospike.server.test.ClusterFormationTest.html' ||
        request.url == '/packages/com.aerospike.server.test.html' ||
        request.url == '/index.html')
    {
        response.writeHead(200, {"Content-Type": "text/html"});
        fs.readFile(home + request.url, 'utf8', function (err, data) {
            if (err) {
                return console.log(err);
            }
            response.end(data)
        });
    }
    else if (request.url == '/js/report.js')
    {
        response.writeHead(200, {"Content-Type": "application/javascript"});
        fs.readFile(home + request.url, 'utf8', function (err, data) {
            if (err) {
                return console.log(err);
            }
            response.end(data)
        });
    }
    else if (request.url == '/css/base-style.css' ||
        request.url == '/css/style.css')
    {
        response.writeHead(200, {"Content-Type": "text/css"});
        fs.readFile(home + request.url, 'utf8', function (err, data) {
            if (err) {
                return console.log(err);
            }
            response.end(data)
        });
    }
    else if (request.url == '/images/logos/maven-feather.png' ||
        request.url == '/images/external.png')
    {
        response.writeHead(200, {"Content-Type": "image/png"});
        fs.readFile(home + request.url, function (err, data) {
            if (err) {
                return console.log(err);
            }
            response.end(data, 'binary')
        });
    }
    else if (request.url == '/images/expanded.gif' ||
        request.url == '/images/icon_success_sml.gif' ||
        request.url == '/images/icon_info_sml.gif' ||
        request.url == '/images/icon_info_sml.gif' ||
        request.url == '/images/icon_success_sml.gif')
    {
        response.writeHead(200, {"Content-Type": "image/gif"});
        fs.readFile(home + request.url, function (err, data) {
            if (err) {
                return console.log(err);
            }
            response.end(data, 'binary')
        });
    }
    else
    {
        response.writeHead(200, {"Content-Type": "text/plain"});
        response.end("End of the Internet\n");
        console.log("request.url = " + request.url);
    }
    // response.end("Hello World\n");
});

// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);

// Put a friendly message on the terminal
console.log("Server running at http://127.0.0.1:8000/");
<commit_msg>updates<commit_after>// Load the http module to create an http server.
var http = require('http');
const util = require('util')
var fs = require('fs');

var home ='/home/jtraver/dev/git/jtraver/qaa/ci_tools/docker-java/tmp1/build/reports/tests';

// console.log(util.inspect(myObject, {showHidden: false, depth: null}))

// alternative shortcut
// console.log(util.inspect(myObject, false, null))

// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
    // console.log("request = " + request);
    // console.log(util.inspect(request, false, null))
    // console.log("response = " + response);
    // console.log(util.inspect(response, false, null))
    // console.log("request.url = " + request.url);
    if (request.url == '/')
    {
        response.writeHead(200, {"Content-Type": "text/html"});
        fs.readFile(home + '/index.html', 'utf8', function (err, data) {
            if (err) {
                return console.log(err);
            }
            response.end(data)
        });
    }
    else if (request.url == '/classes/com.aerospike.server.test.Test3374.html' ||
        request.url == '/classes/com.aerospike.server.test.TestClusterFormation1.html' ||
        request.url == '/classes/com.aerospike.server.test.CdtReplicationTest.html' ||
        request.url == '/classes/com.aerospike.server.test.ClusterFormationTest.html' ||
        request.url == '/classes/com.aerospike.server.test.ClusteringV5Test.html' ||
        request.url == '/classes/com.aerospike.server.test.ConflictDigestLoggingTest.html' ||
        request.url == '/classes/com.aerospike.server.test.FastNodeRestartAer4698.html' ||
        request.url == '/classes/com.aerospike.server.test.HbV3V2Comparison.html' ||
        request.url == '/packages/com.aerospike.server.test.html' ||
        request.url == '/index.html')
    {
        response.writeHead(200, {"Content-Type": "text/html"});
        fs.readFile(home + request.url, 'utf8', function (err, data) {
            if (err) {
                return console.log(err);
            }
            response.end(data)
        });
    }
    else if (request.url == '/js/report.js')
    {
        response.writeHead(200, {"Content-Type": "application/javascript"});
        fs.readFile(home + request.url, 'utf8', function (err, data) {
            if (err) {
                return console.log(err);
            }
            response.end(data)
        });
    }
    else if (request.url == '/css/base-style.css' ||
        request.url == '/css/style.css')
    {
        response.writeHead(200, {"Content-Type": "text/css"});
        fs.readFile(home + request.url, 'utf8', function (err, data) {
            if (err) {
                return console.log(err);
            }
            response.end(data)
        });
    }
    else if (request.url == '/images/logos/maven-feather.png' ||
        request.url == '/images/external.png')
    {
        response.writeHead(200, {"Content-Type": "image/png"});
        fs.readFile(home + request.url, function (err, data) {
            if (err) {
                return console.log(err);
            }
            response.end(data, 'binary')
        });
    }
    else if (request.url == '/images/expanded.gif' ||
        request.url == '/images/icon_success_sml.gif' ||
        request.url == '/images/icon_info_sml.gif' ||
        request.url == '/images/icon_info_sml.gif' ||
        request.url == '/images/icon_success_sml.gif')
    {
        response.writeHead(200, {"Content-Type": "image/gif"});
        fs.readFile(home + request.url, function (err, data) {
            if (err) {
                return console.log(err);
            }
            response.end(data, 'binary')
        });
    }
    else
    {
        response.writeHead(200, {"Content-Type": "text/plain"});
        response.end("End of the Internet\n");
        console.log("request.url = " + request.url);
    }
    // response.end("Hello World\n");
});

// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);

// Put a friendly message on the terminal
console.log("Server running at http://127.0.0.1:8000/");
<|endoftext|>


<commit_before>report.customize_filters = function() {
  this.hide_all_filters();

  this.add_filter({fieldname:'transaction', label:'Transaction', fieldtype:'Select', options:'Quotation'+NEWLINE+'Sales Order'+NEWLINE+'Delivery Note'+NEWLINE+'Sales Invoice'+NEWLINE+'Purchase Order'+NEWLINE+'Purchase Receipt'+NEWLINE+'Purchase Invoice',report_default:'Delivery Note',ignore : 1,parent:'Profile',in_first_page : 1,single_select : 1});

  this.add_filter({fieldname:'period', label:'Period', fieldtype:'Select', options:'Monthly'+NEWLINE+'Quarterly'+NEWLINE+'Half Yearly'+NEWLINE+'Annual',report_default:'Quarterly',ignore : 1, parent:'Profile',in_first_page:1,single_select:1});

  this.add_filter({fieldname:'based_on', label:'Based On', fieldtype:'Select', options:'Item'+NEWLINE+'Item Group'+NEWLINE+'Customer'+NEWLINE+'Customer Group'+NEWLINE+'Territory'+NEWLINE+'Supplier'+NEWLINE+'Supplier Type', ignore : 1, parent:'Profile', report_default:'Item', in_first_page : 1,single_select:1});

  this.add_filter({fieldname:'group_by', label:'Group By', fieldtype:'Select', options:NEWLINE+'Item'+NEWLINE+'Customer'+NEWLINE+'Supplier', ignore : 1, parent:'Profile',single_select:1});

  this.add_filter({fieldname:'order_type', label:'Order Type', fieldtype:'Select', options:NEWLINE+'Sales'+NEWLINE+'Maintenance',ignore : 1, parent:'Profile',single_select:1});

  this.add_filter({fieldname:'company', label:'Company', fieldtype:'Link', options:'Company', report_default:sys_defaults.company, ignore : 1, parent:'Profile'});

  this.set_filter_properties('Profile','Fiscal Year',{filter_hide:0, in_first_page:1, report_default: sys_defaults.fiscal_year});
  this.get_filter('Profile', 'Fiscal Year').set_as_single();

  // Add Filters
  this.add_filter({fieldname:'item', label:'Item', fieldtype:'Link', options:'Item', ignore : 1, parent:'Profile'});
  this.add_filter({fieldname:'item_group', label:'Item Group', fieldtype:'Link', options:'Item Group', ignore : 1, parent:'Profile'});
  this.add_filter({fieldname:'customer', label:'Customer', fieldtype:'Link', options:'Customer', ignore : 1, parent:'Profile'});
  this.add_filter({fieldname:'customer_group', label:'Customer Group', fieldtype:'Link', options:'Customer Group', ignore : 1, parent:'Profile'});
  this.add_filter({fieldname:'territory', label:'Territory', fieldtype:'Link', options:'Territory', ignore : 1, parent:'Profile'});
  this.add_filter({fieldname:'supplier', label:'Supplier', fieldtype:'Link', options:'Supplier', ignore : 1, parent:'Profile'});
  this.add_filter({fieldname:'supplier_type', label:'Supplier Type', fieldtype:'Link', options:'Supplier Type', ignore : 1, parent:'Profile'});
}

this.mytabs.tabs['Select Columns'].hide();

report.aftertableprint = function(t) {
   $yt(t,'*',1,{whiteSpace:'pre'});
}

var validate_values = function(trans,based_on,order_type) {
  if(!fiscal_year){
    msgprint("Please select Fiscal Year");
    return 0;
  }
  if((in_list(['Quotation','Sales Order','Delivery Note','Sales Invoice'],trans) && in_list(['Supplier','Supplier Type'],based_on)) || (in_list(['Purchase Order','Purchase Receipt','Purchase Invoice'],trans) && in_list(['Customer','Customer Group','Territory'],based_on))){
    msgprint("Sorry! You cannot fetch "+trans+" trend based on "+based_on);
    return 0;
  }
  if(in_list(['Purchase Order','Purchase Receipt','Purchase Invoice'],trans) && order_type){
    msgprint("Please deselect Order Type for "+trans);
    return 0;
  }
  return 1;
}

report.get_query = function() {
  trans = this.get_filter('Profile', 'Transaction').get_value();
  order_type = this.get_filter('Profile', 'Order Type').get_value();
  based_on = this.get_filter('Profile', 'Based On').get_value();
  company = this.get_filter('Profile', 'Company').get_value();
  fiscal_year = this.get_filter('Profile', 'Fiscal Year').get_value();

  if(validate_values(trans,based_on,order_type)){
    col = '';
    add_cond = '';
    add_col = '';
    add_tables = '';
    sp_cond = '';
    if(trans == 'Sales Invoice') trans = 'Receivable Voucher';
    else if(trans == 'Purchase Invoice') trans = 'Payable Voucher';

    trans_det = trans+' Detail'

    if(trans == 'Receivable Voucher') trans_det = 'RV Detail';
    else if(trans == 'Payable Voucher') trans_det = 'PV Detail';
    else if(trans == 'Purchase Order') trans_det = 'PO Detail';

    if(order_type != '') add_code += ' AND t1.order_type = '+order_type;

    switch(based_on){
      case 'Item'           :     item = this.get_filter('Profile', 'Item').get_value();
                                  col = 'DISTINCT t2.item_code, t3.item_name';
                                  add_tables = ',tabItem t3';
                                  add_cond += ' AND t2.item_code = t3.name';
                                  if(item) add_cond += ' AND t2.item_code = "'+item+'"';
                                  break;
      case 'Customer'       :     cust = this.get_filter('Profile', 'Customer').get_value();
                                  col = 'DISTINCT t1.customer, t3.territory';
                                  add_tables = ',tabCustomer t3';
                                  add_cond += ' AND t1.customer = t3.name';
                                  if(cust) add_cond += ' AND t1.customer = "'+cust+'"';
                                  break;
      case 'Supplier'      :      supp = this.get_filter('Profile', 'Supplier').get_value();
                                  col = 'DISTINCT t1.supplier, t3.supplier_type';
                                  add_tables = ',tabSupplier t3';
                                  add_cond += ' AND t1.supplier = t3.name';
                                  if(supp) add_cond += ' AND t1.supplier = "'+supp+'"';
                                  break;
      case 'Supplier Type'  :     supp_type = this.get_filter('Profile', 'Supplier Type').get_value();
                                  col = 'DISTINCT t3.supplier_type';
                                  add_tables = ',tabSupplier t3';
                                  add_cond += ' AND t1.supplier = t3.name';
                                  if(supp_type) add_cond += ' AND t1.supplier_type = "'+supp_type+'"';
                                  break;
      case 'Item Group'     :     ig = this.get_filter('Profile', 'Item Group').get_value();
                                  if(ig) sp_cond += ' AND parent.name = "'+ig+'"';
                                  break;
      case 'Customer Group' :     cg = this.get_filter('Profile', 'Customer Group').get_value();
                                  if(cg) sp_cond += ' AND parent.name = "'+cg+'"';
                                  break;
      case 'Territory'      :     ter = this.get_filter('Profile', 'Territory').get_value();
                                  if(ter) sp_cond += ' AND parent.name = "'+ter+'"';
                                  break;
    }

    if(based_on == 'Item' || based_on == 'Customer' || based_on == 'Supplier' || based_on == 'Supplier Type')
      var q ='SELECT '+col+' FROM `tab'+trans+'` t1, `tab'+trans_det+'` t2 '+add_tables+' WHERE t1.fiscal_year = "'+fiscal_year+'" and t1.company = "'+company+'" and t2.parent = t1.name '+add_cond;
    else
      var q = 'SELECT CONCAT(REPEAT("     ", COUNT(parent.name) - 1), node.name) AS "Name" FROM `tab'+based_on+'` node,`tab'+based_on+'` parent WHERE node.lft BETWEEN parent.lft and parent.rgt and node.docstatus !=2 '+sp_cond+' GROUP BY node.name ORDER BY node.lft';

    return q;
  }
}<commit_msg>trend analyzer issue fixed<commit_after>report.customize_filters = function() {
  this.hide_all_filters();

  this.add_filter({fieldname:'transaction', label:'Transaction', fieldtype:'Select', options:'Quotation'+NEWLINE+'Sales Order'+NEWLINE+'Delivery Note'+NEWLINE+'Sales Invoice'+NEWLINE+'Purchase Order'+NEWLINE+'Purchase Receipt'+NEWLINE+'Purchase Invoice',report_default:'Delivery Note',ignore : 1,parent:'Profile',in_first_page : 1,single_select : 1});

  this.add_filter({fieldname:'period', label:'Period', fieldtype:'Select', options:'Monthly'+NEWLINE+'Quarterly'+NEWLINE+'Half Yearly'+NEWLINE+'Annual',report_default:'Quarterly',ignore : 1, parent:'Profile',in_first_page:1,single_select:1});

  this.add_filter({fieldname:'based_on', label:'Based On', fieldtype:'Select', options:'Item'+NEWLINE+'Item Group'+NEWLINE+'Customer'+NEWLINE+'Customer Group'+NEWLINE+'Territory'+NEWLINE+'Supplier'+NEWLINE+'Supplier Type', ignore : 1, parent:'Profile', report_default:'Item', in_first_page : 1,single_select:1});

  this.add_filter({fieldname:'group_by', label:'Group By', fieldtype:'Select', options:NEWLINE+'Item'+NEWLINE+'Customer'+NEWLINE+'Supplier', ignore : 1, parent:'Profile',single_select:1});

  this.add_filter({fieldname:'order_type', label:'Order Type', fieldtype:'Select', options:NEWLINE+'Sales'+NEWLINE+'Maintenance',ignore : 1, parent:'Profile',single_select:1});

  this.add_filter({fieldname:'company', label:'Company', fieldtype:'Link', options:'Company', report_default:sys_defaults.company, ignore : 1, parent:'Profile'});

  this.add_filter({fieldname:'fiscal_year', label:'Fiscal Year', fieldtype:'Link', options:'Fiscal Year', report_default:sys_defaults.fiscal_year, ignore : 1, parent:'Profile', in_first_page:1});

  // Add Filters
  this.add_filter({fieldname:'item', label:'Item', fieldtype:'Link', options:'Item', ignore : 1, parent:'Profile'});
  this.add_filter({fieldname:'item_group', label:'Item Group', fieldtype:'Link', options:'Item Group', ignore : 1, parent:'Profile'});
  this.add_filter({fieldname:'customer', label:'Customer', fieldtype:'Link', options:'Customer', ignore : 1, parent:'Profile'});
  this.add_filter({fieldname:'customer_group', label:'Customer Group', fieldtype:'Link', options:'Customer Group', ignore : 1, parent:'Profile'});
  this.add_filter({fieldname:'territory', label:'Territory', fieldtype:'Link', options:'Territory', ignore : 1, parent:'Profile'});
  this.add_filter({fieldname:'supplier', label:'Supplier', fieldtype:'Link', options:'Supplier', ignore : 1, parent:'Profile'});
  this.add_filter({fieldname:'supplier_type', label:'Supplier Type', fieldtype:'Link', options:'Supplier Type', ignore : 1, parent:'Profile'});
}

this.mytabs.tabs['Select Columns'].hide();

report.aftertableprint = function(t) {
   $yt(t,'*',1,{whiteSpace:'pre'});
}

var validate_values = function(trans,based_on,order_type) {
  if(!fiscal_year){
    msgprint("Please select Fiscal Year");
    return 0;
  }
  if((in_list(['Quotation','Sales Order','Delivery Note','Sales Invoice'],trans) && in_list(['Supplier','Supplier Type'],based_on)) || (in_list(['Purchase Order','Purchase Receipt','Purchase Invoice'],trans) && in_list(['Customer','Customer Group','Territory'],based_on))){
    msgprint("Sorry! You cannot fetch "+trans+" trend based on "+based_on);
    return 0;
  }
  if(in_list(['Purchase Order','Purchase Receipt','Purchase Invoice'],trans) && order_type){
    msgprint("Please deselect Order Type for "+trans);
    return 0;
  }
  return 1;
}

report.get_query = function() {
  trans = this.get_filter('Profile', 'Transaction').get_value();
  order_type = this.get_filter('Profile', 'Order Type').get_value();
  based_on = this.get_filter('Profile', 'Based On').get_value();
  company = this.get_filter('Profile', 'Company').get_value();
  fiscal_year = this.get_filter('Profile', 'Fiscal Year').get_value();

  if(validate_values(trans,based_on,order_type)){
    col = '';
    add_cond = '';
    add_col = '';
    add_tables = '';
    sp_cond = '';
    if(trans == 'Sales Invoice') trans = 'Receivable Voucher';
    else if(trans == 'Purchase Invoice') trans = 'Payable Voucher';

    trans_det = trans+' Detail'

    if(trans == 'Receivable Voucher') trans_det = 'RV Detail';
    else if(trans == 'Payable Voucher') trans_det = 'PV Detail';
    else if(trans == 'Purchase Order') trans_det = 'PO Detail';

    if(order_type != '') add_code += ' AND t1.order_type = '+order_type;

    switch(based_on){
      case 'Item'           :     item = this.get_filter('Profile', 'Item').get_value();
                                  col = 'DISTINCT t2.item_code, t3.item_name';
                                  add_tables = ',tabItem t3';
                                  add_cond += ' AND t2.item_code = t3.name';
                                  if(item) add_cond += ' AND t2.item_code = "'+item+'"';
                                  break;
      case 'Customer'       :     cust = this.get_filter('Profile', 'Customer').get_value();
                                  col = 'DISTINCT t1.customer, t3.territory';
                                  add_tables = ',tabCustomer t3';
                                  add_cond += ' AND t1.customer = t3.name';
                                  if(cust) add_cond += ' AND t1.customer = "'+cust+'"';
                                  break;
      case 'Supplier'      :      supp = this.get_filter('Profile', 'Supplier').get_value();
                                  col = 'DISTINCT t1.supplier, t3.supplier_type';
                                  add_tables = ',tabSupplier t3';
                                  add_cond += ' AND t1.supplier = t3.name';
                                  if(supp) add_cond += ' AND t1.supplier = "'+supp+'"';
                                  break;
      case 'Supplier Type'  :     supp_type = this.get_filter('Profile', 'Supplier Type').get_value();
                                  col = 'DISTINCT t3.supplier_type';
                                  add_tables = ',tabSupplier t3';
                                  add_cond += ' AND t1.supplier = t3.name';
                                  if(supp_type) add_cond += ' AND t1.supplier_type = "'+supp_type+'"';
                                  break;
      case 'Item Group'     :     ig = this.get_filter('Profile', 'Item Group').get_value();
                                  if(ig) sp_cond += ' AND parent.name = "'+ig+'"';
                                  break;
      case 'Customer Group' :     cg = this.get_filter('Profile', 'Customer Group').get_value();
                                  if(cg) sp_cond += ' AND parent.name = "'+cg+'"';
                                  break;
      case 'Territory'      :     ter = this.get_filter('Profile', 'Territory').get_value();
                                  if(ter) sp_cond += ' AND parent.name = "'+ter+'"';
                                  break;
    }

    if(based_on == 'Item' || based_on == 'Customer' || based_on == 'Supplier' || based_on == 'Supplier Type')
      var q ='SELECT '+col+' FROM `tab'+trans+'` t1, `tab'+trans_det+'` t2 '+add_tables+' WHERE t1.fiscal_year = "'+fiscal_year+'" and t1.company = "'+company+'" and t2.parent = t1.name '+add_cond;
    else
      var q = 'SELECT CONCAT(REPEAT("     ", COUNT(parent.name) - 1), node.name) AS "Name" FROM `tab'+based_on+'` node,`tab'+based_on+'` parent WHERE node.lft BETWEEN parent.lft and parent.rgt and node.docstatus !=2 '+sp_cond+' GROUP BY node.name ORDER BY node.lft';

    return q;
  }
}
<|endoftext|>


<commit_before>import React from 'react';
import {Link} from 'gatsby';

import {routes} from '../../src/i18n';

const LLink = ({locale, children, to, prefetch, ...props}) => {
  if (!prefetch) {
    return {children};
  }
  return <Link to={locale === "es" ? to : "en/" + routes.routes[to]} {...props}>{children}</Link>;
};

LLink.defaultProps = {
  prefetch: true,
};
export default LLink;
<commit_msg>Add '/' to the start of English language path [Skip CI]<commit_after>import React from 'react';
import {Link} from 'gatsby';

import {routes} from '../../src/i18n';

const LLink = ({locale, children, to, prefetch, ...props}) => {
  if (!prefetch) {
    return {children};
  }
  return <Link to={locale === "es" ? to : "/en/" + routes.routes[to]} {...props}>{children}</Link>;
};

LLink.defaultProps = {
  prefetch: true,
};
export default LLink;
<|endoftext|>


<commit_before>/*
Case Conductor is a Test Case Management system.
Copyright (C) 2011-2012 Mozilla

This file is part of Case Conductor.

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

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

You should have received a copy of the GNU General Public License
along with Case Conductor.  If not, see <http://www.gnu.org/licenses/>.
*/
/*jslint    browser:    true,
            indent:     4,
            confusion:  true */
/*global    ich, jQuery */

var CC = (function (CC, $) {

    'use strict';

    CC.createEnvProfile = function (container) {
        var context = $(container),
            elements = context.find('.bulkselectitem .elements .element'),
            updateLabels = function () {
                context.find('.bulkselectitem .elements input[name="elements"]').each(function () {
                    var thisID = $(this).attr('id');
                    if ($(this).is(':checked')) {
                        context.find('label[for=' + thisID + ']').addClass('checked');
                    } else {
                        context.find('label[for=' + thisID + ']').removeClass('checked');
                    }
                });
            },
            updateBulkInputs = function () {
                context.find('.bulkselectitem .elements input[name="elements"]').each(function () {
                    if ($(this).closest('.elements').find('input[name="elements"]:checked').length) {
                        $(this).closest('.bulkselectitem').find('.bulk-value').prop('checked', true);
                    }
                });
            };

        // some elements may load already checked
        updateLabels();
        updateBulkInputs();

        context.on('before-replace', '.bulkselectitem .element', function (event, replacement) {
            // Removes element preview (label) when element is deleted.
            // Other actions (other than delete) might also cause this to fire, with new HTML
            // (already parsed into jQuery object) in "replacement".
            if (!replacement.html()) {
                var thisElement = $(event.target),
                    thisElementID = thisElement.data('element-id'),
                    thisPreview = thisElement.closest('.bulkselectitem').find('.preview label[for="element-' + thisElementID + '"]').parent('li');
                thisPreview.detach();
                if (thisElement.closest('.elements').find('input[name="elements"]:checked').not(thisElement.find('input[name="elements"]')).length) {
                    thisElement.closest('.bulkselectitem').find('.bulk-value').prop('checked', true);
                } else {
                    thisElement.closest('.bulkselectitem').find('.bulk-value').prop('checked', false);
                }
            }
        });

        context.on('keydown', '#id_name', function (event) {
            if (event.keyCode === CC.keycodes.ENTER) {
                event.preventDefault();
                context.find('.form-actions button[type="submit"]').focus();
            }
        });

        context.on('change', '.bulkselectitem .element input[name="elements"]', function () {
            var thisID = $(this).attr('id');
            if ($(this).is(':checked')) {
                context.find('label[for=' + thisID + ']').addClass('checked');
            } else {
                context.find('label[for=' + thisID + ']').removeClass('checked');
            }
            if ($(this).closest('.elements').find('input[name="elements"]:checked').length) {
                $(this).closest('.bulkselectitem').find('.bulk-value').prop('checked', true);
            } else {
                $(this).closest('.bulkselectitem').find('.bulk-value').prop('checked', false);
            }
        });

        context.on('change', '.bulkselectitem .bulk-value', function () {
            if ($(this).is(':checked')) {
                $(this).closest('.bulkselectitem').find('.element input[name="elements"]').prop('checked', true);
            } else {
                $(this).closest('.bulkselectitem').find('.element input[name="elements"]').prop('checked', false);
            }
            updateLabels();
        });

        context.on('keydown', '.bulkselectitem input[name="new-element-name"]', function (event) {
            if (event.keyCode === CC.keycodes.ENTER) {
                if ($(this).val().length) {
                    var input = $(this),
                        name = input.val(),
                        loading = input.closest('.item-content'),
                        url = '',
                        data = {},
                        success = function (response) {
                            var newElem = $(response.elem),
                                newPreview = $(response.preview);
                            if (!response.no_replace) {
                                input.closest('.elements').find('.add-element').before(newElem);
                                input.closest('.bulkselectitem').find('.preview').append(newPreview);
                                input.val(null);
                            }
                            loading.loadingOverlay('remove');
                        };
                    data['category-id'] = input.data('category-id');
                    data[input.attr('name')] = input.val();

                    loading.loadingOverlay();
                    $.ajax(url, {
                        type: "POST",
                        data: data,
                        success: success
                    });
                } else {
                    $(ich.message({
                        message: "Please enter an element name.",
                        tags: "error"
                    })).appendTo($('#messages'));
                    $('#messages').messages();
                }
                event.preventDefault();
            }
        });

        context.on('keydown', '#new-category-name', function (event) {
            if (event.keyCode === CC.keycodes.ENTER) {
                if ($(this).val().length) {
                    var input = $(this),
                        loading = input.closest('.item-content'),
                        url = '',
                        data = {},
                        success = function (response) {
                            var newelem = $(response.html);
                            if (!response.no_replace) {
                                input.closest('.add-item').before(newelem);
                                newelem.find('.details').addClass('open').html5accordion();
                                input.val(null).closest('.add-item').find('.summary').first().click();
                                newelem.find('.elements .add-element input[name="new-element-name"]').focus();
                            }
                            loading.loadingOverlay('remove');
                        };
                    data[input.attr('name')] = input.val();

                    loading.loadingOverlay();
                    $.ajax(url, {
                        type: "POST",
                        data: data,
                        success: success
                    });
                } else {
                    $(ich.message({
                        message: "Please enter a category name.",
                        tags: "error"
                    })).appendTo($('#messages'));
                    $('#messages').messages();
                }
                event.preventDefault();
            }
        });

        context.on('click', '.bulkselectitem .element .edit-link', function (event) {
            var thisElement = $(this).closest('.element'),
                inputId = thisElement.find('input[name="elements"]').attr('id'),
                elementId = thisElement.data('element-id'),
                name = thisElement.find('label').text(),
                checked = thisElement.find('input[name="elements"]').is(':checked'),
                editThisElement = ich.env_profile_edit_input({
                    inputId: inputId,
                    id: elementId,
                    name: name,
                    checked: checked,
                    type: 'element'
                });
            thisElement.replaceWith(editThisElement);

            event.preventDefault();
        });

        context.on('click', '.bulkselectitem .item-content .edit-name .edit-link', function (event) {
            var thisName = $(this).closest('.edit-name'),
                categoryId = thisName.data('category-id'),
                inputId = 'edit-category-id-' + categoryId,
                name = thisName.data('category-name'),
                editThisName = ich.env_profile_edit_input({
                    inputId: inputId,
                    id: categoryId,
                    name: name,
                    type: 'category'
                });
            thisName.replaceWith(editThisName);

            event.preventDefault();
        });

        context.on('keydown', '.bulkselectitem .elements .editing input', function (event) {
            if (event.keyCode === CC.keycodes.ENTER) {
                if ($(this).val().length) {
                    var input = $(this),
                        thisElement = input.closest('.editing'),
                        name = input.val(),
                        inputId = input.attr('id'),
                        elementId = input.data('element-id'),
                        preview = input.closest('.bulkselectitem').find('.preview').find('label[for="' + inputId + '"]').closest('li'),
                        checked = input.data('checked'),
                        url = '',
                        data = {},
                        success = function (response) {
                            var editedElem = $(response.elem),
                                editedPreview = $(response.preview);

                            if (!response.no_replace) {
                                thisElement.replaceWith(editedElem);
                                preview.replaceWith(editedPreview);

                                if (checked) {
                                    context.find('#' + inputId).prop('checked', checked);
                                    updateLabels();
                                }
                                input.val(null);
                            }

                            thisElement.loadingOverlay('remove');
                        };

                    data['element-id'] = elementId;
                    data[input.attr('name')] = input.val();

                    thisElement.loadingOverlay();
                    $.ajax(url, {
                        type: "POST",
                        data: data,
                        success: success
                    });
                } else {
                    $(ich.message({
                        message: "Please enter an element name.",
                        tags: "error"
                    })).appendTo($('#messages'));
                    $('#messages').messages();
                }
                event.preventDefault();
            }
        });

        context.on('keydown', '.bulkselectitem .item-content .editing.category input', function (event) {
            if (event.keyCode === CC.keycodes.ENTER) {
                if ($(this).val().length) {
                    var input = $(this),
                        thisCategory = input.closest('.bulkselectitem'),
                        name = input.val(),
                        categoryId = input.data('category-id'),
                        url = '',
                        data = {},
                        success = function (response) {
                            var editedCat = $(response.html);

                            if (!response.no_replace) {
                                thisCategory.replaceWith(editedCat);
                            }

                            thisCategory.loadingOverlay('remove');
                        };

                    data['category-id'] = categoryId;
                    data[input.attr('name')] = input.val();

                    thisCategory.loadingOverlay();
                    $.ajax(url, {
                        type: "POST",
                        data: data,
                        success: success
                    });
                } else {
                    $(ich.message({
                        message: "Please enter a category name.",
                        tags: "error"
                    })).appendTo($('#messages'));
                    $('#messages').messages();
                }
                event.preventDefault();
            }
        });
    };

    CC.editEnvProfile = function () {
        var profileNameInput = $('#editprofile #profile-name-form .profile-name input'),
            profileName = profileNameInput.val(),
            profileNameSubmit = $('#editprofile #profile-name-form .form-actions button[type="submit"]').hide(),

            addEnv = function () {
                var replaceList = $('#editprofile .managelist.action-ajax-replace');

                if ($('#editprofile #add-environment-form').length) {
                    $('#editprofile #add-environment-form').ajaxForm({
                        beforeSubmit: function (arr, form, options) {
                            replaceList.loadingOverlay();
                        },
                        success: function (response) {
                            var newList = $(response.html);
                            replaceList.loadingOverlay('remove');
                            if (response.html) {
                                replaceList.replaceWith(newList);
                                $('#editprofile .add-item').customAutocomplete({
                                    textbox: '#env-elements-input',
                                    suggestionList: '.suggest',
                                    inputList: '.env-element-list',
                                    ajax: true,
                                    url: $('#env-elements-input').data('autocomplete-url'),
                                    hideFormActions: true,
                                    expiredList: '.env-element-list',
                                    inputType: 'element'
                                });
                                addEnv();
                                newList.find('.details').html5accordion();
                            }
                        }
                    });
                }
            };

        addEnv();

        $('#editprofile').on('after-replace', '.managelist.action-ajax-replace', function (event, replacement) {
            // Re-attaches handlers to list after it is reloaded via Ajax.
            addEnv();
            $('#editprofile .add-item').customAutocomplete({
                textbox: '#env-elements-input',
                suggestionList: '.suggest',
                inputList: '.env-element-list',
                ajax: true,
                url: $('#env-elements-input').data('autocomplete-url'),
                hideFormActions: true,
                expiredList: '.env-element-list',
                inputType: 'element'
            });
        });

        $('#editprofile').on('keyup', '#profile-name-form .profile-name input', function (event) {
            if ($(this).val() !== profileName) {
                profileNameSubmit.fadeIn();
            } else {
                profileNameSubmit.fadeOut();
            }
        });

        $('#editprofile').on('keydown', '#profile-name-form .profile-name input', function (event) {
            if (event.keyCode === CC.keycodes.ENTER && !profileNameSubmit.is(':visible')) {
                event.preventDefault();
            }
        });

        if ($('#editprofile #profile-name-form').length) {
            $('#editprofile #profile-name-form').ajaxForm({
                success: function (response) {
                    profileName = profileNameInput.val();
                    profileNameSubmit.fadeOut();
                    profileNameInput.blur();
                }
            });
        }
    };

    CC.envNarrowing = function (container) {
        var context = $(container),
            bulkSelect = context.find('#bulk_select'),
            inputs = context.find('input[type="checkbox"][name="environments"]');

        bulkSelect.change(function () {
            if ($(this).is(':checked')) {
                inputs.prop('checked', true);
            } else {
                inputs.prop('checked', false);
            }
        });

        inputs.change(function () {
            if (inputs.not(':checked').length) {
                bulkSelect.prop('checked', false);
            }
        });
    };

    return CC;

}(CC || {}, jQuery));<commit_msg>add-profile edit-category POSTs checked elements<commit_after>/*
Case Conductor is a Test Case Management system.
Copyright (C) 2011-2012 Mozilla

This file is part of Case Conductor.

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

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

You should have received a copy of the GNU General Public License
along with Case Conductor.  If not, see <http://www.gnu.org/licenses/>.
*/
/*jslint    browser:    true,
            indent:     4,
            confusion:  true */
/*global    ich, jQuery */

var CC = (function (CC, $) {

    'use strict';

    CC.createEnvProfile = function (container) {
        var context = $(container),
            elements = context.find('.bulkselectitem .elements .element'),
            updateLabels = function () {
                context.find('.bulkselectitem .elements input[name="elements"]').each(function () {
                    var thisID = $(this).attr('id');
                    if ($(this).is(':checked')) {
                        context.find('label[for=' + thisID + ']').addClass('checked');
                    } else {
                        context.find('label[for=' + thisID + ']').removeClass('checked');
                    }
                });
            },
            updateBulkInputs = function () {
                context.find('.bulkselectitem .elements input[name="elements"]').each(function () {
                    if ($(this).closest('.elements').find('input[name="elements"]:checked').length) {
                        $(this).closest('.bulkselectitem').find('.bulk-value').prop('checked', true);
                    }
                });
            };

        // some elements may load already checked
        updateLabels();
        updateBulkInputs();

        context.on('before-replace', '.bulkselectitem .element', function (event, replacement) {
            // Removes element preview (label) when element is deleted.
            // Other actions (other than delete) might also cause this to fire, with new HTML
            // (already parsed into jQuery object) in "replacement".
            if (!replacement.html()) {
                var thisElement = $(event.target),
                    thisElementID = thisElement.data('element-id'),
                    thisPreview = thisElement.closest('.bulkselectitem').find('.preview label[for="element-' + thisElementID + '"]').parent('li');
                thisPreview.detach();
                if (thisElement.closest('.elements').find('input[name="elements"]:checked').not(thisElement.find('input[name="elements"]')).length) {
                    thisElement.closest('.bulkselectitem').find('.bulk-value').prop('checked', true);
                } else {
                    thisElement.closest('.bulkselectitem').find('.bulk-value').prop('checked', false);
                }
            }
        });

        context.on('keydown', '#id_name', function (event) {
            if (event.keyCode === CC.keycodes.ENTER) {
                event.preventDefault();
                context.find('.form-actions button[type="submit"]').focus();
            }
        });

        context.on('change', '.bulkselectitem .element input[name="elements"]', function () {
            var thisID = $(this).attr('id');
            if ($(this).is(':checked')) {
                context.find('label[for=' + thisID + ']').addClass('checked');
            } else {
                context.find('label[for=' + thisID + ']').removeClass('checked');
            }
            if ($(this).closest('.elements').find('input[name="elements"]:checked').length) {
                $(this).closest('.bulkselectitem').find('.bulk-value').prop('checked', true);
            } else {
                $(this).closest('.bulkselectitem').find('.bulk-value').prop('checked', false);
            }
        });

        context.on('change', '.bulkselectitem .bulk-value', function () {
            if ($(this).is(':checked')) {
                $(this).closest('.bulkselectitem').find('.element input[name="elements"]').prop('checked', true);
            } else {
                $(this).closest('.bulkselectitem').find('.element input[name="elements"]').prop('checked', false);
            }
            updateLabels();
        });

        context.on('keydown', '.bulkselectitem input[name="new-element-name"]', function (event) {
            if (event.keyCode === CC.keycodes.ENTER) {
                if ($(this).val().length) {
                    var input = $(this),
                        name = input.val(),
                        loading = input.closest('.item-content'),
                        url = '',
                        data = {},
                        success = function (response) {
                            var newElem = $(response.elem),
                                newPreview = $(response.preview);
                            if (!response.no_replace) {
                                input.closest('.elements').find('.add-element').before(newElem);
                                input.closest('.bulkselectitem').find('.preview').append(newPreview);
                                input.val(null);
                            }
                            loading.loadingOverlay('remove');
                        };
                    data['category-id'] = input.data('category-id');
                    data[input.attr('name')] = input.val();

                    loading.loadingOverlay();
                    $.ajax(url, {
                        type: "POST",
                        data: data,
                        success: success
                    });
                } else {
                    $(ich.message({
                        message: "Please enter an element name.",
                        tags: "error"
                    })).appendTo($('#messages'));
                    $('#messages').messages();
                }
                event.preventDefault();
            }
        });

        context.on('keydown', '#new-category-name', function (event) {
            if (event.keyCode === CC.keycodes.ENTER) {
                if ($(this).val().length) {
                    var input = $(this),
                        loading = input.closest('.item-content'),
                        url = '',
                        data = {},
                        success = function (response) {
                            var newelem = $(response.html);
                            if (!response.no_replace) {
                                input.closest('.add-item').before(newelem);
                                newelem.find('.details').addClass('open').html5accordion();
                                input.val(null).closest('.add-item').find('.summary').first().click();
                                newelem.find('.elements .add-element input[name="new-element-name"]').focus();
                            }
                            loading.loadingOverlay('remove');
                        };
                    data[input.attr('name')] = input.val();

                    loading.loadingOverlay();
                    $.ajax(url, {
                        type: "POST",
                        data: data,
                        success: success
                    });
                } else {
                    $(ich.message({
                        message: "Please enter a category name.",
                        tags: "error"
                    })).appendTo($('#messages'));
                    $('#messages').messages();
                }
                event.preventDefault();
            }
        });

        context.on('click', '.bulkselectitem .element .edit-link', function (event) {
            var thisElement = $(this).closest('.element'),
                inputId = thisElement.find('input[name="elements"]').attr('id'),
                elementId = thisElement.data('element-id'),
                name = thisElement.find('label').text(),
                checked = thisElement.find('input[name="elements"]').is(':checked'),
                editThisElement = ich.env_profile_edit_input({
                    inputId: inputId,
                    id: elementId,
                    name: name,
                    checked: checked,
                    type: 'element'
                });
            thisElement.replaceWith(editThisElement);

            event.preventDefault();
        });

        context.on('click', '.bulkselectitem .item-content .edit-name .edit-link', function (event) {
            var thisName = $(this).closest('.edit-name'),
                categoryId = thisName.data('category-id'),
                inputId = 'edit-category-id-' + categoryId,
                name = thisName.data('category-name'),
                editThisName = ich.env_profile_edit_input({
                    inputId: inputId,
                    id: categoryId,
                    name: name,
                    type: 'category'
                });
            thisName.replaceWith(editThisName);

            event.preventDefault();
        });

        context.on('keydown', '.bulkselectitem .elements .editing input', function (event) {
            if (event.keyCode === CC.keycodes.ENTER) {
                if ($(this).val().length) {
                    var input = $(this),
                        thisElement = input.closest('.editing'),
                        name = input.val(),
                        inputId = input.attr('id'),
                        elementId = input.data('element-id'),
                        preview = input.closest('.bulkselectitem').find('.preview').find('label[for="' + inputId + '"]').closest('li'),
                        checked = input.data('checked'),
                        url = '',
                        data = {},
                        success = function (response) {
                            var editedElem = $(response.elem),
                                editedPreview = $(response.preview);

                            if (!response.no_replace) {
                                thisElement.replaceWith(editedElem);
                                preview.replaceWith(editedPreview);

                                if (checked) {
                                    context.find('#' + inputId).prop('checked', checked);
                                    updateLabels();
                                }
                                input.val(null);
                            }

                            thisElement.loadingOverlay('remove');
                        };

                    data['element-id'] = elementId;
                    data[input.attr('name')] = input.val();

                    thisElement.loadingOverlay();
                    $.ajax(url, {
                        type: "POST",
                        data: data,
                        success: success
                    });
                } else {
                    $(ich.message({
                        message: "Please enter an element name.",
                        tags: "error"
                    })).appendTo($('#messages'));
                    $('#messages').messages();
                }
                event.preventDefault();
            }
        });

        context.on('keydown', '.bulkselectitem .item-content .editing.category input', function (event) {
            if (event.keyCode === CC.keycodes.ENTER) {
                if ($(this).val().length) {
                    var input = $(this),
                        thisCategory = input.closest('.bulkselectitem'),
                        name = input.val(),
                        nameKey = input.attr('name'),
                        categoryId = input.data('category-id'),
                        url = '',
                        data = {},
                        success = function (response) {
                            var editedCat = $(response.html);

                            if (!response.no_replace) {
                                thisCategory.replaceWith(editedCat);
                            }

                            thisCategory.loadingOverlay('remove');
                        };

                    data = thisCategory.find('input[name="elements"]').serializeArray();
                    data.push({'name': 'category-id', 'value': categoryId}, {'name': nameKey, 'value': name});

                    thisCategory.loadingOverlay();
                    $.ajax(url, {
                        type: "POST",
                        data: data,
                        success: success
                    });
                } else {
                    $(ich.message({
                        message: "Please enter a category name.",
                        tags: "error"
                    })).appendTo($('#messages'));
                    $('#messages').messages();
                }
                event.preventDefault();
            }
        });
    };

    CC.editEnvProfile = function () {
        var profileNameInput = $('#editprofile #profile-name-form .profile-name input'),
            profileName = profileNameInput.val(),
            profileNameSubmit = $('#editprofile #profile-name-form .form-actions button[type="submit"]').hide(),

            addEnv = function () {
                var replaceList = $('#editprofile .managelist.action-ajax-replace');

                if ($('#editprofile #add-environment-form').length) {
                    $('#editprofile #add-environment-form').ajaxForm({
                        beforeSubmit: function (arr, form, options) {
                            replaceList.loadingOverlay();
                        },
                        success: function (response) {
                            var newList = $(response.html);
                            replaceList.loadingOverlay('remove');
                            if (response.html) {
                                replaceList.replaceWith(newList);
                                $('#editprofile .add-item').customAutocomplete({
                                    textbox: '#env-elements-input',
                                    suggestionList: '.suggest',
                                    inputList: '.env-element-list',
                                    ajax: true,
                                    url: $('#env-elements-input').data('autocomplete-url'),
                                    hideFormActions: true,
                                    expiredList: '.env-element-list',
                                    inputType: 'element'
                                });
                                addEnv();
                                newList.find('.details').html5accordion();
                            }
                        }
                    });
                }
            };

        addEnv();

        $('#editprofile').on('after-replace', '.managelist.action-ajax-replace', function (event, replacement) {
            // Re-attaches handlers to list after it is reloaded via Ajax.
            addEnv();
            $('#editprofile .add-item').customAutocomplete({
                textbox: '#env-elements-input',
                suggestionList: '.suggest',
                inputList: '.env-element-list',
                ajax: true,
                url: $('#env-elements-input').data('autocomplete-url'),
                hideFormActions: true,
                expiredList: '.env-element-list',
                inputType: 'element'
            });
        });

        $('#editprofile').on('keyup', '#profile-name-form .profile-name input', function (event) {
            if ($(this).val() !== profileName) {
                profileNameSubmit.fadeIn();
            } else {
                profileNameSubmit.fadeOut();
            }
        });

        $('#editprofile').on('keydown', '#profile-name-form .profile-name input', function (event) {
            if (event.keyCode === CC.keycodes.ENTER && !profileNameSubmit.is(':visible')) {
                event.preventDefault();
            }
        });

        if ($('#editprofile #profile-name-form').length) {
            $('#editprofile #profile-name-form').ajaxForm({
                success: function (response) {
                    profileName = profileNameInput.val();
                    profileNameSubmit.fadeOut();
                    profileNameInput.blur();
                }
            });
        }
    };

    CC.envNarrowing = function (container) {
        var context = $(container),
            bulkSelect = context.find('#bulk_select'),
            inputs = context.find('input[type="checkbox"][name="environments"]');

        bulkSelect.change(function () {
            if ($(this).is(':checked')) {
                inputs.prop('checked', true);
            } else {
                inputs.prop('checked', false);
            }
        });

        inputs.change(function () {
            if (inputs.not(':checked').length) {
                bulkSelect.prop('checked', false);
            }
        });
    };

    return CC;

}(CC || {}, jQuery));<|endoftext|>


<commit_before>/**
 * The Settings Modul reads the settings out of settings.json and provides
 * this information to the other modules
 */

/*
 * 2011 Peter 'Pita' Martischka
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS-IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var fs = require("fs");

/**
 * The IP ep-lite should listen to
 */
exports.ip = "0.0.0.0";

/**
 * The Port ep-lite should listen to
 */
exports.port = 9001;
/*
 * The Type of the database
 */
exports.dbType = "sqlite";
/**
 * This setting is passed with dbType to ueberDB to set up the database
 */
exports.dbSettings = { "filename" : "../var/sqlite.db" };
/**
 * The default Text of a new pad
 */
exports.defaultPadText = "Welcome to Etherpad Lite!\n\nThis pad text is synchronized as you type, so that everyone viewing this page sees the same text. This allows you to collaborate seamlessly on documents!\n\nEtherpad Lite on Github: http:\/\/j.mp/ep-lite\n";
/**
 * A flag that shows if minification is enabled or not
 */
exports.minify = true;

/**
 * The path of the abiword executable
 */
exports.abiword = null;

//read the settings sync
var settingsStr = fs.readFileSync("../settings.json").toString();

//remove all comments
settingsStr = settingsStr.replace(/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/gm,"").replace(/#.*/g,"").replace(/\/\/.*/g,"");

//try to parse the settings
var settings;
try
{
  settings = JSON.parse(settingsStr);
}
catch(e)
{
  console.error("There is a syntax error in your settings.json file");
  console.error(e.message);
  process.exit(1);
}

//loop trough the settings
for(var i in settings)
{
  //test if the setting start with a low character
  if(i.charAt(0).search("[a-z]") !== 0)
  {
    console.error("WARNING: Settings should start with a low character: '" + i + "'");
  }

  //we know this setting, so we overwrite it
  if(exports[i] !== undefined)
  {
    exports[i] = settings[i];
  }
  //this setting is unkown, output a warning and throw it away
  else
  {
    console.error("WARNING: Unkown Setting: '" + i + "'");
    console.error("This setting doesn't exist or it was removed");
  }
}
<commit_msg>Let settings warnings output as warnings, not as an error<commit_after>/**
 * The Settings Modul reads the settings out of settings.json and provides
 * this information to the other modules
 */

/*
 * 2011 Peter 'Pita' Martischka
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS-IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var fs = require("fs");

/**
 * The IP ep-lite should listen to
 */
exports.ip = "0.0.0.0";

/**
 * The Port ep-lite should listen to
 */
exports.port = 9001;
/*
 * The Type of the database
 */
exports.dbType = "sqlite";
/**
 * This setting is passed with dbType to ueberDB to set up the database
 */
exports.dbSettings = { "filename" : "../var/sqlite.db" };
/**
 * The default Text of a new pad
 */
exports.defaultPadText = "Welcome to Etherpad Lite!\n\nThis pad text is synchronized as you type, so that everyone viewing this page sees the same text. This allows you to collaborate seamlessly on documents!\n\nEtherpad Lite on Github: http:\/\/j.mp/ep-lite\n";
/**
 * A flag that shows if minification is enabled or not
 */
exports.minify = true;

/**
 * The path of the abiword executable
 */
exports.abiword = null;

//read the settings sync
var settingsStr = fs.readFileSync("../settings.json").toString();

//remove all comments
settingsStr = settingsStr.replace(/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/gm,"").replace(/#.*/g,"").replace(/\/\/.*/g,"");

//try to parse the settings
var settings;
try
{
  settings = JSON.parse(settingsStr);
}
catch(e)
{
  console.error("There is a syntax error in your settings.json file");
  console.error(e.message);
  process.exit(1);
}

//loop trough the settings
for(var i in settings)
{
  //test if the setting start with a low character
  if(i.charAt(0).search("[a-z]") !== 0)
  {
    console.warn("Settings should start with a low character: '" + i + "'");
  }

  //we know this setting, so we overwrite it
  if(exports[i] !== undefined)
  {
    exports[i] = settings[i];
  }
  //this setting is unkown, output a warning and throw it away
  else
  {
    console.warn("Unkown Setting: '" + i + "'");
    console.warn("This setting doesn't exist or it was removed");
  }
}
<|endoftext|>


<commit_before>import uuid from 'node-uuid';

const YEAR_IN_MS = 1000 * 60 * 60 * 24 * 365;
const COOKIE_OPTS = {
	encoding: 'none',
	path: '/',
	isHttpOnly: true,
};

/**
 * @method updateSessionId
 *
 * simple tracking id for the browser session
 *
 * @param {Object} hapi response object
 */
export const updateSessionId = response => {
	let session_id = response.request.state.session_id;

	if (!session_id) {
		session_id = uuid.v4();
		response.state(
			'session_id',
			session_id,
			COOKIE_OPTS
		);
	}
	return session_id;
};

/**
 * getter/setter for member_id cookie: if member_id is not passed, the cookie
 * will be unset
 */
export const updateMemberId = (response, member_id) => {
	if (!member_id) {
		response.unstate('member_id');
		return response.request.state.member_id;
	}
	response.state(
		'member_id',
		member_id,
		{
			...COOKIE_OPTS,
			ttl: YEAR_IN_MS * 20,
		}
	);
	return member_id;
};

/**
 * @method updateTrackId
 *
 * Initialize the track_id for member or anonymous user - the longest-living id
 * we can assigned to a user. Stays in place until login or logout, when it is
 * exchanged for a new track_id
 *
 *  - If the user has a tracking cookie already set, do nothing.
 *  - Otherwise, generate a new uuid and set a tracking cookie.
 *
 * @param {Object} hapi response object
 */
export const updateTrackId = (response, doRefresh) => {
	let track_id = response.request.state.track_id;

	if (!track_id || doRefresh) {
		// Generate a new track_id cookie
		track_id = uuid.v4();
		response.state(
			'track_id',
			track_id,
			{
				...COOKIE_OPTS,
				ttl: YEAR_IN_MS * 20,
			}
		);
	}
	return track_id;
};

export const trackLogout = log => response =>
	log(
		response,
		{
			description: 'logout',
			member_id: updateMemberId(this.response),
			track_id_from: this.response.request.state.track_id,
			track_id: updateTrackId(this.response, true),
			session_id: this.response.request.state.session_id,
		}
	);

export const trackLogin = log => (response, member_id) =>
	log(
		response,
		{
			description: 'login',
			member_id: updateMemberId(this.response, member_id),
			track_id_from: this.response.request.state.track_id,
			track_id: updateTrackId(this.response, true),
			session_id: this.response.request.state.session_id,
		}
	);

export const trackSession = log => response =>
	log(
		response,
		{
			description: 'new session',
			member_id: this.response.request.state.member_id,
			track_id: updateTrackId(this.response),
			session_id: updateSessionId(this.response),
		}
	);

export const logTrack = platform_agent => (response, trackInfo) => {
	const requestHeaders = response.request.headers;
	const trackLog = {
		...trackInfo,
		request_id: uuid.v4(),
		url: requestHeaders.referer,
		referrer: 'this will be handled in a special way for navigation actions',
		ip: requestHeaders['remote-addr'],
		agent: requestHeaders['user-agent'],
		platform: 'meetup-web-platform',
		platform_agent,
	};
	// response.request.log will provide timestaemp
	response.request.log(['tracking'], JSON.stringify(trackLog, null, 2));
	return trackLog;
};

export default function track(platform_agent) {
	const log = logTrack(platform_agent);
	const login = trackLogin(log);
	const logout = trackLogout(log);
	const session = trackSession(log);
	const trackers = {
		login,
		logout,
		session,
	};
	return function(type, ...args) {
		return trackers[type](this.response, ...args);
	};
}

<commit_msg>no longer this response<commit_after>import uuid from 'node-uuid';

const YEAR_IN_MS = 1000 * 60 * 60 * 24 * 365;
const COOKIE_OPTS = {
	encoding: 'none',
	path: '/',
	isHttpOnly: true,
};

/**
 * @method updateSessionId
 *
 * simple tracking id for the browser session
 *
 * @param {Object} hapi response object
 */
export const updateSessionId = response => {
	let session_id = response.request.state.session_id;

	if (!session_id) {
		session_id = uuid.v4();
		response.state(
			'session_id',
			session_id,
			COOKIE_OPTS
		);
	}
	return session_id;
};

/**
 * getter/setter for member_id cookie: if member_id is not passed, the cookie
 * will be unset
 */
export const updateMemberId = (response, member_id) => {
	if (!member_id) {
		response.unstate('member_id');
		return response.request.state.member_id;
	}
	response.state(
		'member_id',
		member_id,
		{
			...COOKIE_OPTS,
			ttl: YEAR_IN_MS * 20,
		}
	);
	return member_id;
};

/**
 * @method updateTrackId
 *
 * Initialize the track_id for member or anonymous user - the longest-living id
 * we can assigned to a user. Stays in place until login or logout, when it is
 * exchanged for a new track_id
 *
 *  - If the user has a tracking cookie already set, do nothing.
 *  - Otherwise, generate a new uuid and set a tracking cookie.
 *
 * @param {Object} hapi response object
 */
export const updateTrackId = (response, doRefresh) => {
	let track_id = response.request.state.track_id;

	if (!track_id || doRefresh) {
		// Generate a new track_id cookie
		track_id = uuid.v4();
		response.state(
			'track_id',
			track_id,
			{
				...COOKIE_OPTS,
				ttl: YEAR_IN_MS * 20,
			}
		);
	}
	return track_id;
};

export const trackLogout = log => response =>
	log(
		response,
		{
			description: 'logout',
			member_id: updateMemberId(response),
			track_id_from: response.request.state.track_id,
			track_id: updateTrackId(response, true),
			session_id: response.request.state.session_id,
		}
	);

export const trackLogin = log => (response, member_id) =>
	log(
		response,
		{
			description: 'login',
			member_id: updateMemberId(response, member_id),
			track_id_from: response.request.state.track_id,
			track_id: updateTrackId(response, true),
			session_id: response.request.state.session_id,
		}
	);

export const trackSession = log => response =>
	log(
		response,
		{
			description: 'new session',
			member_id: response.request.state.member_id,
			track_id: updateTrackId(response),
			session_id: updateSessionId(response),
		}
	);

export const logTrack = platform_agent => (response, trackInfo) => {
	const requestHeaders = response.request.headers;
	const trackLog = {
		...trackInfo,
		request_id: uuid.v4(),
		url: requestHeaders.referer,
		referrer: 'this will be handled in a special way for navigation actions',
		ip: requestHeaders['remote-addr'],
		agent: requestHeaders['user-agent'],
		platform: 'meetup-web-platform',
		platform_agent,
	};
	// response.request.log will provide timestaemp
	response.request.log(['tracking'], JSON.stringify(trackLog, null, 2));
	return trackLog;
};

export default function track(platform_agent) {
	const log = logTrack(platform_agent);
	const login = trackLogin(log);
	const logout = trackLogout(log);
	const session = trackSession(log);
	const trackers = {
		login,
		logout,
		session,
	};
	return function(type, ...args) {
		return trackers[type](this.response, ...args);
	};
}

<|endoftext|>