<commit_before>!( function( factory ) {
  if ( typeof define === "function" && define.amd ) {
    define(factory );
  } else {
    factory( );
  }
}(function( ){

  // Code form Zepto.js
  // @see https://github.com/madrobby/zepto/blob/master/src/form.js#files
  var serializeArray = function() {
    var name, type, result = [],
        add = function(value) {
          if (value.forEach) return value.forEach(add)
          result.push({ name: name, value: value })
        };

    [].slice.apply(this.elements).forEach(function(field) {

      type = field.type, name = field.name
      if (name && field.nodeName.toLowerCase() !== 'fieldset' &&
        !field.disabled && type !== 'submit' && type !== 'reset' && type !== 'button' && type !== 'file' &&
        ((type !== 'radio' && type !== 'checkbox') || field.checked))
          add(field.value)
    })
    return result
  }

  var serialize = function(){
    var result = []
    serializeArray.call(this).forEach(function(elm){
      result.push(encodeURIComponent(elm.name) + '=' + encodeURIComponent(elm.value))
    })
    return result.join('&')
  }

  var serializeJSONForGET = function(){
    var result = []
    serializeArray.call(this).forEach(function(elm){
      result.push(encodeURIComponent(elm.name) + '=' + encodeURIComponent(elm.value))
    })
    return result.join('&')
  }

    /**
   * Set obj's value by keys
   * @param  {[object]}           obj   The target you want to set.
   * @param  {[array]}            keys  The value's path.
   * @param  {[string, array...]} value Target's value.
   * @return {[object]}                 The target after setting value.
   *
   * Example: obj = {'a':'a'}, keys = ['b','bb'], value = 'b-value'
   * return {
   *         'a': 'a',
   *         'b': {
   *           'bb': 'b-value'
   *          }
   *        }
   */
  var deepSet = function(obj, keys, value) {

    var curKey = keys[0];
    if(keys.length === 1) {

      curKey === '' ? obj.push(value) : obj[curKey] = value;

      return;
    }
    if (keys.length > 1) {
      if (typeof obj[curKey] === 'undefined')
        obj[curKey] = keys[1] === '' ? [] : {};
    }

    var o = obj[curKey];
    keys.shift();
    return deepSet(o, keys, value);
  }

  var integerKeysAsArrayIndexes = function(obj, keys, value) {

    var allKeysIsInteger = true;
    var arr = [];
    var temp;
    keys = keys || [];
    value = value || obj;

    for (var key in value) {

      temp = keys.concat();

      if (isNaN(+key)) {
        allKeysIsInteger = false;
      } else {
        arr.push(value[key]);
      }
      temp.push(key);

      if ((typeof value[key] === 'object') && !Array.isArray(value[key])) {
        integerKeysAsArrayIndexes(obj, temp, value[key]);
      }
    }

    if (allKeysIsInteger) {

      if (keys.length === 0) {
        obj = arr;
      } else {
        deepSet(obj, keys, arr)
      }
    }
    return obj;
  }
  // TEST: integerKeysAsArrayIndexes
  // var json = integerKeysAsArrayIndexes({
  //   a: {
  //     0: {
  //       aa: "aa",
  //       bb: {
  //         0: "bb0",
  //         1: "bb1",
  //         3: "bb3"
  //       }
  //     },
  //     1: "a"
  //   },
  //   b: "b"
  // })
  // console.log(JSON.stringify(json));
  // var json = integerKeysAsArrayIndexes({
  //   0: "a",
  //   1: {
  //     "a": "b"
  //   }
  // })
  // console.log(JSON.stringify(json));

  // keys: ["a", ""]
  // ["a", "b", "c"], ["a", "b", "d"]
  // types: "string", "array", "number", "bool", "object"
  //
  // TEST
  // form.json
  // input(name='a')
  // input(name='images.')
  // input(name='images.')
  // input(name='b.b')
  // input(name='c.c.:number')
  // input(name='c.c.')
  // input(type='submit')
  //
  var submitHandler = function(e, options, action) {

    var self = this;
    var method = self.getAttribute('method') || 'POST';
    var res;

    if (self['_running']) {
      console.log('form submiting. return.')
      return;
    }
    res = {};
    serializeArray.call(self).forEach(function(t){
      var keys  = t.name.split('.');
      var len   = keys.length - 1;
      var index = keys[len].indexOf(':');
      var value = t.value;
      var type;
      if (index !== -1) {
        type    = keys[len].substr(index + 1);
        keys[len] = keys[len].substr(0, index);
      } else {
        type = 'string';
      }

      if (type === 'array' || type === 'object') {

        value  = JSON.parse(value);

      } else if (type === 'number') {

        value = +value;
      } else if (type === 'datetime') {

        // For +08 Beijing Time
        value = new Date(value + ':00+08:00').getTime()
        Number.isNaN(value) && (value = '')

      } else if (type === 'time') {

        value = new Date(value).getTime();
        Number.isNaN(value) && (value = '')

      } else if (type === 'bool' || type === 'boolean') {
        if (value === 'false')
          value = false
        else
          value = !!value;

      }

      deepSet(res, keys, value);
    });

    if (options.parseInteger)
      res = integerKeysAsArrayIndexes(res);
    res = options.data.call(self, res);

    // Stringify result object.
    if (method === "GET") {

      var keys = Object.keys(res);
      var arr = []
      for (var i = 0, max = keys.length; i < max; i ++) {
        if (typeof res[keys[i]] === 'string') {

          arr.push(encodeURIComponent(keys[i]) + '=' + encodeURIComponent( res[keys[i]]) )
        } else {
          arr.push(encodeURIComponent(keys[i]) + '=' + encodeURIComponent( JSON.stringify(res[keys[i]])) );
        }
      }
      res = arr.join('&')

    } else {
      res = JSON.stringify(res);
    }

    /**
     * If there are no data should be sent, just return.
     */
    if (res === 'null') {
      return;
    }

    /**
     *
     * AJAX request
     *
     */
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.timeout = 20000;
    /**
     * Add session header for cross-domain request.
     * You can't set cookies for ajax
     * and you have to response #options request# like:
     * "Access-Control-Allow-Headers: X-AVOSCloud-Session-Token"
     * before you send it.
     * */
    var session = document.cookie.match(/sessionToken=([^;]*)(;|$)/);
    action = (action === undefined ? self.getAttribute('action') : action);

    if (method === 'GET') {
      action += action.indexOf('?') === -1 ? ('?' + res) : ( '&' + res);
    }

    xmlHttp.open(method, action, true);
    xmlHttp.setRequestHeader('Content-Type', 'application/json');
    if (session) {
      xmlHttp.setRequestHeader('X-AVOSCloud-Session-Token', session[1])
    }

    xmlHttp.responseType = 'json';

    xmlHttp.onreadystatechange = function() {
      if (xmlHttp.readyState === 4) {
        self['_running'] = false;
        if (xmlHttp.status >= 200 && xmlHttp.status < 300) {

          if (typeof xmlHttp.response === 'string')
            options.ended.call(self, JSON.parse(xmlHttp.response), xmlHttp);
          else
            options.ended.call(self, xmlHttp.response, xmlHttp);

        } else {

          // xmlHttp.status == 0 timeout
          // xmlHttp.status == 404 not found
          xmlHttp.response = xmlHttp.response || {};
          options.error.call(self, xmlHttp);
        }
      }
    }

    self['_running'] = true;
    if (method === 'GET')
      xmlHttp.send();
    else
      xmlHttp.send(res);
  }

  /**
   * Example:
   * <form action='/action/a'>
   * <input type='submit'>
   * <input type='submit' formAction='/action/b'>
   * </form>
   */
  var formAction;
  document.addEventListener('click', function(e) {
    var target = e.target;

    if (target.type === 'submit' && target.formAction) {
      formAction = target.formAction;
    }

    setTimeout(function() {
      formAction = undefined;
    }, 1000);

  })

  /**
   * Submit form's handler.
   * Example:
   * <form data-role='formJSON'>
   * </form>
   */
  var submitListener = function(e) {

    var target = e.target;
    if (target.getAttribute('data-role') === 'formJSON') {

      e.preventDefault();
      e.stopPropagation();

      var temp = (temp = target.getAttribute('data-target')) && document.querySelector(temp);
      var parseInteger = target.getAttribute('data-parseInteger') === 'false' ? false : true;

      var options = {
        parseInteger: parseInteger,
        ended: target.onended || ( temp && temp.onended ) || function(){},
        // to change data
        data: target._data || ( temp && temp._data ) || function(d){return d},
        error: target.onerror || ( temp && temp.onerror ) || function(){}
      };

      submitHandler.call(target, e, options, formAction);

    }

  }
  document.addEventListener('submit', submitListener)
  document.addEventListener('formJSON-submit', submitListener)

  // Fix.
  // Submit a form by javascript won't fire submit event.
  // @see http://stackoverflow.com/questions/12819357/form-submitted-using-submit-from-a-link-cannot-be-caught-by-onsubmit-handler

  var _submit = HTMLFormElement.prototype.submit;
  HTMLFormElement.prototype.submit = function() {

    if (this.getAttribute('data-role') === 'formJSON') {
      this.dispatchEvent(new Event('formJSON-submit', {bubbles: true}));
    } else {
      _submit.call(this);
    }
  }

  return null;

}));
<commit_msg>Bugfixed: Input Element has formAction on chrome 47+.<commit_after>!( function( factory ) {
  if ( typeof define === "function" && define.amd ) {
    define(factory );
  } else {
    factory( );
  }
}(function( ){

  // Code form Zepto.js
  // @see https://github.com/madrobby/zepto/blob/master/src/form.js#files
  var serializeArray = function() {
    var name, type, result = [],
        add = function(value) {
          if (value.forEach) return value.forEach(add)
          result.push({ name: name, value: value })
        };

    [].slice.apply(this.elements).forEach(function(field) {

      type = field.type, name = field.name
      if (name && field.nodeName.toLowerCase() !== 'fieldset' &&
        !field.disabled && type !== 'submit' && type !== 'reset' && type !== 'button' && type !== 'file' &&
        ((type !== 'radio' && type !== 'checkbox') || field.checked))
          add(field.value)
    })
    return result
  }

  var serialize = function(){
    var result = []
    serializeArray.call(this).forEach(function(elm){
      result.push(encodeURIComponent(elm.name) + '=' + encodeURIComponent(elm.value))
    })
    return result.join('&')
  }

  var serializeJSONForGET = function(){
    var result = []
    serializeArray.call(this).forEach(function(elm){
      result.push(encodeURIComponent(elm.name) + '=' + encodeURIComponent(elm.value))
    })
    return result.join('&')
  }

    /**
   * Set obj's value by keys
   * @param  {[object]}           obj   The target you want to set.
   * @param  {[array]}            keys  The value's path.
   * @param  {[string, array...]} value Target's value.
   * @return {[object]}                 The target after setting value.
   *
   * Example: obj = {'a':'a'}, keys = ['b','bb'], value = 'b-value'
   * return {
   *         'a': 'a',
   *         'b': {
   *           'bb': 'b-value'
   *          }
   *        }
   */
  var deepSet = function(obj, keys, value) {

    var curKey = keys[0];
    if(keys.length === 1) {

      curKey === '' ? obj.push(value) : obj[curKey] = value;

      return;
    }
    if (keys.length > 1) {
      if (typeof obj[curKey] === 'undefined')
        obj[curKey] = keys[1] === '' ? [] : {};
    }

    var o = obj[curKey];
    keys.shift();
    return deepSet(o, keys, value);
  }

  var integerKeysAsArrayIndexes = function(obj, keys, value) {

    var allKeysIsInteger = true;
    var arr = [];
    var temp;
    keys = keys || [];
    value = value || obj;

    for (var key in value) {

      temp = keys.concat();

      if (isNaN(+key)) {
        allKeysIsInteger = false;
      } else {
        arr.push(value[key]);
      }
      temp.push(key);

      if ((typeof value[key] === 'object') && !Array.isArray(value[key])) {
        integerKeysAsArrayIndexes(obj, temp, value[key]);
      }
    }

    if (allKeysIsInteger) {

      if (keys.length === 0) {
        obj = arr;
      } else {
        deepSet(obj, keys, arr)
      }
    }
    return obj;
  }
  // TEST: integerKeysAsArrayIndexes
  // var json = integerKeysAsArrayIndexes({
  //   a: {
  //     0: {
  //       aa: "aa",
  //       bb: {
  //         0: "bb0",
  //         1: "bb1",
  //         3: "bb3"
  //       }
  //     },
  //     1: "a"
  //   },
  //   b: "b"
  // })
  // console.log(JSON.stringify(json));
  // var json = integerKeysAsArrayIndexes({
  //   0: "a",
  //   1: {
  //     "a": "b"
  //   }
  // })
  // console.log(JSON.stringify(json));

  // keys: ["a", ""]
  // ["a", "b", "c"], ["a", "b", "d"]
  // types: "string", "array", "number", "bool", "object"
  //
  // TEST
  // form.json
  // input(name='a')
  // input(name='images.')
  // input(name='images.')
  // input(name='b.b')
  // input(name='c.c.:number')
  // input(name='c.c.')
  // input(type='submit')
  //
  var submitHandler = function(e, options, action) {

    var self = this;
    var method = self.getAttribute('method') || 'POST';
    var res;

    if (self['_running']) {
      console.log('form submiting. return.')
      return;
    }
    res = {};
    serializeArray.call(self).forEach(function(t){
      var keys  = t.name.split('.');
      var len   = keys.length - 1;
      var index = keys[len].indexOf(':');
      var value = t.value;
      var type;
      if (index !== -1) {
        type    = keys[len].substr(index + 1);
        keys[len] = keys[len].substr(0, index);
      } else {
        type = 'string';
      }

      if (type === 'array' || type === 'object') {

        value  = JSON.parse(value);

      } else if (type === 'number') {

        value = +value;
      } else if (type === 'datetime') {

        // For +08 Beijing Time
        value = new Date(value + ':00+08:00').getTime()
        Number.isNaN(value) && (value = '')

      } else if (type === 'time') {

        value = new Date(value).getTime();
        Number.isNaN(value) && (value = '')

      } else if (type === 'bool' || type === 'boolean') {
        if (value === 'false')
          value = false
        else
          value = !!value;

      }

      deepSet(res, keys, value);
    });

    if (options.parseInteger)
      res = integerKeysAsArrayIndexes(res);
    res = options.data.call(self, res);

    // Stringify result object.
    if (method === "GET") {

      var keys = Object.keys(res);
      var arr = []
      for (var i = 0, max = keys.length; i < max; i ++) {
        if (typeof res[keys[i]] === 'string') {

          arr.push(encodeURIComponent(keys[i]) + '=' + encodeURIComponent( res[keys[i]]) )
        } else {
          arr.push(encodeURIComponent(keys[i]) + '=' + encodeURIComponent( JSON.stringify(res[keys[i]])) );
        }
      }
      res = arr.join('&')

    } else {
      res = JSON.stringify(res);
    }

    /**
     * If there are no data should be sent, just return.
     */
    if (res === 'null') {
      return;
    }

    /**
     *
     * AJAX request
     *
     */
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.timeout = 20000;
    /**
     * Add session header for cross-domain request.
     * You can't set cookies for ajax
     * and you have to response #options request# like:
     * "Access-Control-Allow-Headers: X-AVOSCloud-Session-Token"
     * before you send it.
     * */
    var session = document.cookie.match(/sessionToken=([^;]*)(;|$)/);
    action = (action === undefined ? self.getAttribute('action') : action);

    if (method === 'GET') {
      action += action.indexOf('?') === -1 ? ('?' + res) : ( '&' + res);
    }

    xmlHttp.open(method, action, true);
    xmlHttp.setRequestHeader('Content-Type', 'application/json');
    if (session) {
      xmlHttp.setRequestHeader('X-AVOSCloud-Session-Token', session[1])
    }

    xmlHttp.responseType = 'json';

    xmlHttp.onreadystatechange = function() {
      if (xmlHttp.readyState === 4) {
        self['_running'] = false;
        if (xmlHttp.status >= 200 && xmlHttp.status < 300) {

          if (typeof xmlHttp.response === 'string')
            options.ended.call(self, JSON.parse(xmlHttp.response), xmlHttp);
          else
            options.ended.call(self, xmlHttp.response, xmlHttp);

        } else {

          // xmlHttp.status == 0 timeout
          // xmlHttp.status == 404 not found
          xmlHttp.response = xmlHttp.response || {};
          options.error.call(self, xmlHttp);
        }
      }
    }

    self['_running'] = true;
    if (method === 'GET')
      xmlHttp.send();
    else
      xmlHttp.send(res);
  }

  /**
   * Example:
   * <form action='/action/a'>
   * <input type='submit'>
   * <input type='submit' formAction='/action/b'>
   * </form>
   */
  var formAction;
  document.addEventListener('click', function(e) {
    var target = e.target;

    if (target.type === 'submit' && target.getAttribute('formAction')) {
      formAction = target.getAttribute('formAction');
    }

    setTimeout(function() {
      formAction = undefined;
    }, 1000);

  })

  /**
   * Submit form's handler.
   * Example:
   * <form data-role='formJSON'>
   * </form>
   */
  var submitListener = function(e) {

    var target = e.target;
    if (target.getAttribute('data-role') === 'formJSON') {

      e.preventDefault();
      e.stopPropagation();

      var temp = (temp = target.getAttribute('data-target')) && document.querySelector(temp);
      var parseInteger = target.getAttribute('data-parseInteger') === 'false' ? false : true;

      var options = {
        parseInteger: parseInteger,
        ended: target.onended || ( temp && temp.onended ) || function(){},
        // to change data
        data: target._data || ( temp && temp._data ) || function(d){return d},
        error: target.onerror || ( temp && temp.onerror ) || function(){}
      };

      submitHandler.call(target, e, options, formAction);

    }

  }
  document.addEventListener('submit', submitListener)
  document.addEventListener('formJSON-submit', submitListener)

  // Fix.
  // Submit a form by javascript won't fire submit event.
  // @see http://stackoverflow.com/questions/12819357/form-submitted-using-submit-from-a-link-cannot-be-caught-by-onsubmit-handler

  var _submit = HTMLFormElement.prototype.submit;
  HTMLFormElement.prototype.submit = function() {

    if (this.getAttribute('data-role') === 'formJSON') {
      this.dispatchEvent(new Event('formJSON-submit', {bubbles: true}));
    } else {
      _submit.call(this);
    }
  }

  return null;

}));
<|endoftext|>


<commit_before>'use strict';
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import createReactClass from 'create-react-class';
import { RestMixin } from '../rest';
import { Form, FormMixin, Input } from '../../libs/bootstrap/form';
import * as CuratorHistory from '../curator_history';
import { queryKeyValue, editQueryValue, addQueryKey } from '../globals';
import * as curator from '../curator';

const GeneDiseaseSummaryClassification = module.exports.GeneDiseaseSummaryClassification = createReactClass({
    mixins: [FormMixin, RestMixin, CuratorHistory],

    propTypes: {
        gdm: PropTypes.object,
        provisional: PropTypes.object,
        user: PropTypes.string,
        totalScore: PropTypes.string,
        autoClassification: PropTypes.string,
        replicatedOverTime: PropTypes.bool,
        contradictingEvidence: PropTypes.object,
        editKey: PropTypes.string,
        calculateKey: PropTypes.string
    },

    getInitialState() {
        return {
            user: this.props.user, // login user uuid
            gdm: this.props.gdm, // current gdm object, must be null initially.
            provisional: this.props.provisional, // login user's existing provisional object, must be null initially.
            provisionalClassificationStatus: 'In progress',
            provisionalClassificationStatusChecked: false,
            alteredClassification: 'No Selection',
            reasons: '',
            evidenceSummary: ''
        };
    },

    componentDidMount() {
        if (Object.keys(this.state.provisional).length) {
            const provisional = this.state.provisional;
            this.setState({
                alteredClassification: provisional.alteredClassification,
                reasons: provisional.reasons,
                provisionalClassificationStatus: provisional.hasOwnProperty('provisionalClassificationStatus') ? provisional.provisionalClassificationStatus : 'In progress',
                provisionalClassificationStatusChecked: provisional.provisionalClassificationStatus !== 'In progress' ? true : false,
                evidenceSummary: provisional.hasOwnProperty('evidenceSummary') ? provisional.evidenceSummary : ''
            }, () => {
                this.refs['alteredClassification'].setValue(this.state.alteredClassification);
                this.refs['reasons'].setValue(this.state.reasons);
                this.refs['classification-evidence-summary'].setValue(this.state.evidenceSummary);
            });
        }
    },

    submitForm: function(e) {
        // Don't run through HTML submit handler
        e.preventDefault();
        e.stopPropagation();

        // Save all form values from the DOM.
        this.saveAllFormValues();
        if (this.validateDefault()) {
            var newProvisional = this.state.provisional.uuid ? curator.flatten(this.state.provisional) : {};
            newProvisional.totalScore = Number(this.props.totalScore);
            newProvisional.autoClassification = this.props.autoClassification;
            newProvisional.alteredClassification = this.state.alteredClassification;
            newProvisional.reasons = this.state.reasons;
            newProvisional.replicatedOverTime = this.props.replicatedOverTime;
            newProvisional.contradictingEvidence = this.props.contradictingEvidence;
            newProvisional.provisionalClassificationStatus = this.state.provisionalClassificationStatus;
            newProvisional.evidenceSummary = this.state.evidenceSummary;

            // check required item (reasons)
            var formErr = false;
            if (!newProvisional.reasons && newProvisional.alteredClassification !== 'No Selection') {
                formErr = true;
                this.setFormErrors('reasons', 'Required when changing classification.');
            }
            if (!formErr) {
                if (this.state.provisional.uuid) { // edit existing provisional
                    this.putRestData('/provisional/' + this.state.provisional.uuid, newProvisional).then(data => {
                        var provisionalClassification = data['@graph'][0];

                        // Record provisional classification history
                        var meta = {
                            provisionalClassification: {
                                gdm: this.state.gdm['@id'],
                                alteredClassification: provisionalClassification.alteredClassification
                            }
                        };
                        this.recordHistory('modify', provisionalClassification, meta);

                        /*
                        this.setState({provisionalClassificationSaved: true}, () => {
                            this.props.updateGdmObj();
                            if (queryKeyValue('edit', this.props.href)) {
                                window.history.replaceState(window.state, '', editQueryValue(window.location.href, 'edit', 'false'));
                            } else {
                                window.history.replaceState(window.state, '', addQueryKey(window.location.href, 'edit', 'false'));
                            }
                            if (queryKeyValue('calculate', this.props.href)) {
                                window.history.replaceState(window.state, '', editQueryValue(window.location.href, 'calculate', null));
                            }
                        });
                        */
                        window.location.replace('/provisional-classification/?gdm=' + this.state.gdm.uuid);
                    }).catch(function(e) {
                        console.log('PROVISIONAL GENERATION ERROR = : %o', e);
                    });
                } else { // save a new calculation and provisional classification
                    this.postRestData('/provisional/', newProvisional).then(data => {
                        return data['@graph'][0];
                    }).then(savedProvisional => {
                        // Record provisional classification history
                        var meta = {
                            provisionalClassification: {
                                gdm: this.state.gdm['@id'],
                                alteredClassification: savedProvisional.alteredClassification
                            }
                        };
                        this.recordHistory('add', savedProvisional, meta);

                        var theGdm = curator.flatten(this.state.gdm);
                        if (theGdm.provisionalClassifications) {
                            theGdm.provisionalClassifications.push(savedProvisional['@id']);
                        }
                        else {
                            theGdm.provisionalClassifications = [savedProvisional['@id']];
                        }

                        return this.putRestData('/gdm/' + this.state.gdm.uuid, theGdm).then(data => {
                            return data['@graph'][0];
                        });
                    }).then(savedGdm => {
                        /*
                        this.setState({provisionalClassificationSaved: true}, () => {
                            this.props.updateGdmObj();
                            if (queryKeyValue('edit', this.props.href)) {
                                window.history.replaceState(window.state, '', editQueryValue(window.location.href, 'edit', 'false'));
                            } else {
                                window.history.replaceState(window.state, '', addQueryKey(window.location.href, 'edit', 'false'));
                            }
                            if (queryKeyValue('calculate', this.props.href)) {
                                window.history.replaceState(window.state, '', editQueryValue(window.location.href, 'calculate', null));
                            }
                        });
                        */
                        window.location.replace('/provisional-classification/?gdm=' + this.state.gdm.uuid);
                    }).catch(function(e) {
                        console.log('PROVISIONAL GENERATION ERROR = %o', e);
                    });
                }
            }
        }
    },

    cancelForm(e) {
        // Changed modal cancel button from a form input to a html button
        // as to avoid accepting enter/return key as a click event.
        // Removed hack in this method.
        window.history.go(-1);
    },

    editForm(e) {
        // window.history.replaceState(window.state, '', addQueryKey(window.location.href, 'edit', 'true'));
        window.location.replace('/provisional-classification/?gdm=' + this.state.gdm.uuid + '&edit=true');
    },

    viewEvidenceSummary(e) {
        window.open('/gene-disease-evidence-summary/?gdm=' + this.state.gdm.uuid, '_blank');
    },

    handleChange(ref, e) {
        if (ref === 'alteredClassification') {
            this.setState({alteredClassification: this.refs[ref].getValue()});
        } else if (ref === 'reasons') {
            this.setState({reasons: this.refs[ref].getValue()});
        } else if (ref === 'classification-evidence-summary') {
            this.setState({evidenceSummary: this.refs[ref].getValue()});
        } else if (ref === 'classification-status') {
            this.setState({provisionalClassificationStatusChecked: !this.state.provisionalClassificationStatusChecked}, () => {
                if (this.state.provisionalClassificationStatusChecked) {
                    this.setState({provisionalClassificationStatus: 'Provisional'});
                } else {
                    this.setState({provisionalClassificationStatus: 'In progress'});
                }
            });
        }
    },

    render() {
        let gdm = this.state.gdm ? this.state.gdm : null;
        let autoClassification = this.props.autoClassification;
        let edit = this.props.editKey && this.props.editKey === 'true' ? true : false;
        let calculate = this.props.calculateKey && this.props.calculateKey === 'yes' ? true : false;
        // set the 'Current Classification' appropriately only if previous provisional exists
        let provisional = this.state.provisional;
        let currentClassification = 'None';
        if (provisional.last_modified) {
            if (provisional.alteredClassification && provisional.alteredClassification !== 'No Selection') {
                currentClassification = provisional.alteredClassification;
            } else {
                currentClassification = provisional.autoClassification ? provisional.autoClassification : this.props.autoClassification;
            }
        }

        return (
            <Form formClassName="form-horizontal form-std">

                                                <Input type="select" ref="alteredClassification"
                                                    label={Modify Clinical Validity Classification:}
                                                    labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group"
                                                    defaultValue={this.state.alteredClassification} handleChange={this.handleChange} inputDisabled={edit || calculate ? false : true}>
                                                    <option value="No Selection">No Selection</option>
                                                    {autoClassification === 'Definitive' ? null : <option value="Definitive">Definitive</option>}
                                                    {autoClassification === 'Strong' ? null : <option value="Strong">Strong</option>}
                                                    {autoClassification === 'Moderate' ? null : <option value="Moderate">Moderate</option>}
                                                    {autoClassification === 'Limited' ? null : <option value="Limited">Limited</option>}
                                                    <option value="Disputed">Disputed</option>
                                                    <option value="Refuted">Refuted</option>
                                                    <option value="No Reported Evidence">No Reported Evidence (calculated score is based on Experimental evidence only)</option>
                                                </Input>

                                                <Input type="textarea" ref="reasons" rows="5" label="Explain Reason(s) for Change" labelClassName="col-sm-5 control-label"
                                                    wrapperClassName="col-sm-7" groupClassName="form-group" error={this.getFormError('reasons')} value={this.state.reasons}
                                                    clearError={this.clrFormErrors.bind(null, 'reasons')} handleChange={this.handleChange} inputDisabled={edit || calculate ? false : true} />

                                                Mark status as "Provisional Classification" (optional):
                                                <Input type="checkbox" ref="classification-status" checked={this.state.provisionalClassificationStatusChecked} handleChange={this.handleChange}
                                                    labelClassName="col-sm-6 control-label" wrapperClassName="col-sm-1" groupClassName="form-group" inputDisabled={edit || calculate ? false : true} />

                                                <Input type="textarea" ref="classification-evidence-summary" label="Evidence Summary:"
                                                    value={this.state.evidenceSummary} handleChange={this.handleChange} inputDisabled={edit || calculate ? false : true}
                                                    placeholder="Summary of the evidence and rationale for the clinical validity classification (optional)." rows="5"
                                                    labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" />

                {(this.props.editKey && this.props.editKey === 'true') || (this.props.calculateKey && this.props.calculateKey === 'yes') ?

                        <Input type="button" inputClassName="btn-default btn-inline-spacer" clickHandler={this.cancelForm} title="Cancel" />
                        <Input type="button" inputClassName={(currentClassification && currentClassification !== 'None' ? "btn-info" : "btn-primary") + " btn-inline-spacer pull-right submit"}
                            clickHandler={this.submitForm} title={currentClassification && currentClassification !== 'None' ? 'Update' : 'Save'} />

                    :

                        <Input type="button" inputClassName="btn-default btn-inline-spacer" clickHandler={this.editForm} title="Edit" />
                        <Input type="button" inputClassName="btn-primary btn-inline-spacer pull-right" clickHandler={this.viewEvidenceSummary} title="View Evidence Summary" />

                }
            </Form>
        );
    }
});<commit_msg>Changed all instances of 'provisionalClassificationStatus' to 'classificationStatus'<commit_after>'use strict';
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import createReactClass from 'create-react-class';
import { RestMixin } from '../rest';
import { Form, FormMixin, Input } from '../../libs/bootstrap/form';
import * as CuratorHistory from '../curator_history';
import { queryKeyValue, editQueryValue, addQueryKey } from '../globals';
import * as curator from '../curator';

const GeneDiseaseSummaryClassification = module.exports.GeneDiseaseSummaryClassification = createReactClass({
    mixins: [FormMixin, RestMixin, CuratorHistory],

    propTypes: {
        gdm: PropTypes.object,
        provisional: PropTypes.object,
        user: PropTypes.string,
        totalScore: PropTypes.string,
        autoClassification: PropTypes.string,
        replicatedOverTime: PropTypes.bool,
        contradictingEvidence: PropTypes.object,
        editKey: PropTypes.string,
        calculateKey: PropTypes.string
    },

    getInitialState() {
        return {
            user: this.props.user, // login user uuid
            gdm: this.props.gdm, // current gdm object, must be null initially.
            provisional: this.props.provisional, // login user's existing provisional object, must be null initially.
            classificationStatus: 'In progress',
            classificationStatusChecked: false,
            alteredClassification: 'No Selection',
            reasons: '',
            evidenceSummary: ''
        };
    },

    componentDidMount() {
        if (Object.keys(this.state.provisional).length) {
            const provisional = this.state.provisional;
            this.setState({
                alteredClassification: provisional.alteredClassification,
                reasons: provisional.reasons,
                classificationStatus: provisional.hasOwnProperty('classificationStatus') ? provisional.classificationStatus : 'In progress',
                classificationStatusChecked: provisional.classificationStatus !== 'In progress' ? true : false,
                evidenceSummary: provisional.hasOwnProperty('evidenceSummary') ? provisional.evidenceSummary : ''
            }, () => {
                this.refs['alteredClassification'].setValue(this.state.alteredClassification);
                this.refs['reasons'].setValue(this.state.reasons);
                this.refs['classification-evidence-summary'].setValue(this.state.evidenceSummary);
            });
        }
    },

    submitForm: function(e) {
        // Don't run through HTML submit handler
        e.preventDefault();
        e.stopPropagation();

        // Save all form values from the DOM.
        this.saveAllFormValues();
        if (this.validateDefault()) {
            var newProvisional = this.state.provisional.uuid ? curator.flatten(this.state.provisional) : {};
            newProvisional.totalScore = Number(this.props.totalScore);
            newProvisional.autoClassification = this.props.autoClassification;
            newProvisional.alteredClassification = this.state.alteredClassification;
            newProvisional.reasons = this.state.reasons;
            newProvisional.replicatedOverTime = this.props.replicatedOverTime;
            newProvisional.contradictingEvidence = this.props.contradictingEvidence;
            newProvisional.classificationStatus = this.state.classificationStatus;
            newProvisional.evidenceSummary = this.state.evidenceSummary;

            // check required item (reasons)
            var formErr = false;
            if (!newProvisional.reasons && newProvisional.alteredClassification !== 'No Selection') {
                formErr = true;
                this.setFormErrors('reasons', 'Required when changing classification.');
            }
            if (!formErr) {
                if (this.state.provisional.uuid) { // edit existing provisional
                    this.putRestData('/provisional/' + this.state.provisional.uuid, newProvisional).then(data => {
                        var provisionalClassification = data['@graph'][0];

                        // Record provisional classification history
                        var meta = {
                            provisionalClassification: {
                                gdm: this.state.gdm['@id'],
                                alteredClassification: provisionalClassification.alteredClassification
                            }
                        };
                        this.recordHistory('modify', provisionalClassification, meta);

                        /*
                        this.setState({provisionalClassificationSaved: true}, () => {
                            this.props.updateGdmObj();
                            if (queryKeyValue('edit', this.props.href)) {
                                window.history.replaceState(window.state, '', editQueryValue(window.location.href, 'edit', 'false'));
                            } else {
                                window.history.replaceState(window.state, '', addQueryKey(window.location.href, 'edit', 'false'));
                            }
                            if (queryKeyValue('calculate', this.props.href)) {
                                window.history.replaceState(window.state, '', editQueryValue(window.location.href, 'calculate', null));
                            }
                        });
                        */
                        window.location.replace('/provisional-classification/?gdm=' + this.state.gdm.uuid);
                    }).catch(function(e) {
                        console.log('PROVISIONAL GENERATION ERROR = : %o', e);
                    });
                } else { // save a new calculation and provisional classification
                    this.postRestData('/provisional/', newProvisional).then(data => {
                        return data['@graph'][0];
                    }).then(savedProvisional => {
                        // Record provisional classification history
                        var meta = {
                            provisionalClassification: {
                                gdm: this.state.gdm['@id'],
                                alteredClassification: savedProvisional.alteredClassification
                            }
                        };
                        this.recordHistory('add', savedProvisional, meta);

                        var theGdm = curator.flatten(this.state.gdm);
                        if (theGdm.provisionalClassifications) {
                            theGdm.provisionalClassifications.push(savedProvisional['@id']);
                        }
                        else {
                            theGdm.provisionalClassifications = [savedProvisional['@id']];
                        }

                        return this.putRestData('/gdm/' + this.state.gdm.uuid, theGdm).then(data => {
                            return data['@graph'][0];
                        });
                    }).then(savedGdm => {
                        /*
                        this.setState({provisionalClassificationSaved: true}, () => {
                            this.props.updateGdmObj();
                            if (queryKeyValue('edit', this.props.href)) {
                                window.history.replaceState(window.state, '', editQueryValue(window.location.href, 'edit', 'false'));
                            } else {
                                window.history.replaceState(window.state, '', addQueryKey(window.location.href, 'edit', 'false'));
                            }
                            if (queryKeyValue('calculate', this.props.href)) {
                                window.history.replaceState(window.state, '', editQueryValue(window.location.href, 'calculate', null));
                            }
                        });
                        */
                        window.location.replace('/provisional-classification/?gdm=' + this.state.gdm.uuid);
                    }).catch(function(e) {
                        console.log('PROVISIONAL GENERATION ERROR = %o', e);
                    });
                }
            }
        }
    },

    cancelForm(e) {
        // Changed modal cancel button from a form input to a html button
        // as to avoid accepting enter/return key as a click event.
        // Removed hack in this method.
        window.history.go(-1);
    },

    editForm(e) {
        // window.history.replaceState(window.state, '', addQueryKey(window.location.href, 'edit', 'true'));
        window.location.replace('/provisional-classification/?gdm=' + this.state.gdm.uuid + '&edit=true');
    },

    viewEvidenceSummary(e) {
        window.open('/gene-disease-evidence-summary/?gdm=' + this.state.gdm.uuid, '_blank');
    },

    handleChange(ref, e) {
        if (ref === 'alteredClassification') {
            this.setState({alteredClassification: this.refs[ref].getValue()});
        } else if (ref === 'reasons') {
            this.setState({reasons: this.refs[ref].getValue()});
        } else if (ref === 'classification-evidence-summary') {
            this.setState({evidenceSummary: this.refs[ref].getValue()});
        } else if (ref === 'classification-status') {
            this.setState({classificationStatusChecked: !this.state.classificationStatusChecked}, () => {
                if (this.state.classificationStatusChecked) {
                    this.setState({classificationStatus: 'Provisional'});
                } else {
                    this.setState({classificationStatus: 'In progress'});
                }
            });
        }
    },

    render() {
        let gdm = this.state.gdm ? this.state.gdm : null;
        let autoClassification = this.props.autoClassification;
        let edit = this.props.editKey && this.props.editKey === 'true' ? true : false;
        let calculate = this.props.calculateKey && this.props.calculateKey === 'yes' ? true : false;
        // set the 'Current Classification' appropriately only if previous provisional exists
        let provisional = this.state.provisional;
        let currentClassification = 'None';
        if (provisional.last_modified) {
            if (provisional.alteredClassification && provisional.alteredClassification !== 'No Selection') {
                currentClassification = provisional.alteredClassification;
            } else {
                currentClassification = provisional.autoClassification ? provisional.autoClassification : this.props.autoClassification;
            }
        }

        return (
            <Form formClassName="form-horizontal form-std">

                                                <Input type="select" ref="alteredClassification"
                                                    label={Modify Clinical Validity Classification:}
                                                    labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group"
                                                    defaultValue={this.state.alteredClassification} handleChange={this.handleChange} inputDisabled={edit || calculate ? false : true}>
                                                    <option value="No Selection">No Selection</option>
                                                    {autoClassification === 'Definitive' ? null : <option value="Definitive">Definitive</option>}
                                                    {autoClassification === 'Strong' ? null : <option value="Strong">Strong</option>}
                                                    {autoClassification === 'Moderate' ? null : <option value="Moderate">Moderate</option>}
                                                    {autoClassification === 'Limited' ? null : <option value="Limited">Limited</option>}
                                                    <option value="Disputed">Disputed</option>
                                                    <option value="Refuted">Refuted</option>
                                                    <option value="No Reported Evidence">No Reported Evidence (calculated score is based on Experimental evidence only)</option>
                                                </Input>

                                                <Input type="textarea" ref="reasons" rows="5" label="Explain Reason(s) for Change" labelClassName="col-sm-5 control-label"
                                                    wrapperClassName="col-sm-7" groupClassName="form-group" error={this.getFormError('reasons')} value={this.state.reasons}
                                                    clearError={this.clrFormErrors.bind(null, 'reasons')} handleChange={this.handleChange} inputDisabled={edit || calculate ? false : true} />

                                                Mark status as "Provisional Classification" (optional):
                                                <Input type="checkbox" ref="classification-status" checked={this.state.classificationStatusChecked} handleChange={this.handleChange}
                                                    labelClassName="col-sm-6 control-label" wrapperClassName="col-sm-1" groupClassName="form-group" inputDisabled={edit || calculate ? false : true} />

                                                <Input type="textarea" ref="classification-evidence-summary" label="Evidence Summary:"
                                                    value={this.state.evidenceSummary} handleChange={this.handleChange} inputDisabled={edit || calculate ? false : true}
                                                    placeholder="Summary of the evidence and rationale for the clinical validity classification (optional)." rows="5"
                                                    labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" />

                {(this.props.editKey && this.props.editKey === 'true') || (this.props.calculateKey && this.props.calculateKey === 'yes') ?

                        <Input type="button" inputClassName="btn-default btn-inline-spacer" clickHandler={this.cancelForm} title="Cancel" />
                        <Input type="button" inputClassName={(currentClassification && currentClassification !== 'None' ? "btn-info" : "btn-primary") + " btn-inline-spacer pull-right submit"}
                            clickHandler={this.submitForm} title={currentClassification && currentClassification !== 'None' ? 'Update' : 'Save'} />

                    :

                        <Input type="button" inputClassName="btn-default btn-inline-spacer" clickHandler={this.editForm} title="Edit" />
                        <Input type="button" inputClassName="btn-primary btn-inline-spacer pull-right" clickHandler={this.viewEvidenceSummary} title="View Evidence Summary" />

                }
            </Form>
        );
    }
});<|endoftext|>


<commit_before>/* global QUnit */

sap.ui.define([
	"sap/ui/thirdparty/sinon-4",
	"sap/ui/fl/write/_internal/connectors/LrepConnector"
], function(
	sinon,
	LrepConnector
) {
	"use strict";

	var sandbox = sinon.sandbox.create();

	function fnReturnData(nStatus, oHeader, sBody) {
		sandbox.server.respondWith(function(request) {
			request.respond(nStatus, oHeader, sBody);
		});
	}

	QUnit.module("LrepConnector", {
		beforeEach : function () {
			sandbox.useFakeServer();
			sandbox.server.autoRespond = true;
		},
		afterEach: function() {
			sandbox.verifyAndRestore();
		}
	}, function() {
		QUnit.test("given a mock server, when get flex info is triggered", function (assert) {
			var oExpectedResponse = {
				isResetEnabled: false,
				isPublishEnabled: false
			};
			fnReturnData(200, {}, JSON.stringify(oExpectedResponse));

			var mPropertyBag = {url: "/sap/bc/lrep", reference: "reference", appVersion: "1.0.0", layer: "VENDOR"};
			var sUrl = "/sap/bc/lrep/flex/info/reference?layer=VENDOR&appVersion=1.0.0";
			return LrepConnector.getFlexInfo(mPropertyBag).then(function (oResponse) {
				assert.equal(sandbox.server.getRequest(0).method, "GET", "request method is GET");
				assert.equal(sandbox.server.getRequest(0).url, sUrl, "a flex info request is send containing the reference in the url and the app version and the layer as query parameters");
				assert.deepEqual(oResponse, oExpectedResponse, "getFlexInfo response flow is correct");
			});
		});
		QUnit.test("given a mock server, when publish is triggered", function (assert) {
			fnReturnData(204, {}, '[]');

			var mPropertyBag = {url: "/sap/bc/lrep", reference: "flexReference", appVersion: "1.0.0", layer: "VENDOR", changelist: "transportId", "package": "somePackage"};
			var sUrl = "/sap/bc/lrep/actions/make_changes_transportable/?reference=flexReference&layer=VENDOR&appVersion=1.0.0&changelist=transportId&package=somePackage";
			return LrepConnector.publish(mPropertyBag).then(function () {
				assert.equal(sandbox.server.getRequest(0).method, "POST", "request method is POST");
				assert.equal(sandbox.server.getRequest(0).url, sUrl, "a make changes transportable request is send containing the reference, the app version, the layer, the changelist and the package as query parameters");
			});
		});
		QUnit.test("given a mock server, when reset is triggered", function (assert) {
			var aExpectedResponse = [
				{
					appComponent: "sap.ui.demoapps.rta.freestyle.Component",
					appVersionFrom: 10000000000,
					name: "id_1565952176663_88_stashControl",
					tenantId: "555552-a23e-6666-3333-53002f046412",
					userName: "test.test@test.com"
				}
			];
			fnReturnData(200, {}, JSON.stringify(aExpectedResponse));
			var mPropertyBag = {url: "/sap/bc/lrep", reference: "flexReference", appVersion: "1.0.0", layer: "VENDOR", changelist: "transportId", generator: "someGenerator", selectorIds:"someSelectors", changeTypes:"someChangeTypes"};
			var sUrl = "/sap/bc/lrep/changes/?reference=flexReference&layer=VENDOR&appVersion=1.0.0&changelist=transportId&generator=someGenerator&selector=someSelectors&changeType=someChangeTypes";
			return LrepConnector.reset(mPropertyBag).then(function (oResponse) {
				assert.equal(sandbox.server.getRequest(0).method, "DELETE", "request method is DELETE");
				assert.equal(sandbox.server.getRequest(0).url, sUrl, "a delete request is send containing the reference, the app version, the layer, the changelist, the generator, the selector Ids and the change types as query parameters");
				assert.deepEqual(oResponse, aExpectedResponse, "reset response flow is correct");
			});
		});
		QUnit.test("given a mock server, when loadFeatures is triggered", function (assert) {
			var oExpectedResponse = {
				isKeyUser: true
			};
			fnReturnData(200, {}, JSON.stringify(oExpectedResponse));
			var mPropertyBag = {url: "/sap/bc/lrep"};
			var sUrl = "/sap/bc/lrep/flex/settings";

			return LrepConnector.loadFeatures(mPropertyBag).then(function (oResponse) {
				assert.equal(sandbox.server.getRequest(0).method, "GET", "request method is GET");
				assert.equal(sandbox.server.getRequest(0).url, sUrl, "Url is correct");
				assert.deepEqual(oResponse, oExpectedResponse, "loadFeatures response flow is correct");
			});
		});
	});
	QUnit.done(function () {
		jQuery('#qunit-fixture').hide();
	});
});
<commit_msg>[INTERNAL] sap.ui.fl.write...LrepConnector temp test removal<commit_after>/* global QUnit */

sap.ui.define([
	"sap/ui/thirdparty/sinon-4",
	"sap/ui/fl/write/_internal/connectors/LrepConnector"
], function(
	sinon,
	LrepConnector
) {
	"use strict";

	var sandbox = sinon.sandbox.create();

	function fnReturnData(nStatus, oHeader, sBody) {
		sandbox.server.respondWith(function(request) {
			request.respond(nStatus, oHeader, sBody);
		});
	}

	QUnit.module("LrepConnector", {
		beforeEach : function () {
			sandbox.useFakeServer();
			sandbox.server.autoRespond = true;
		},
		afterEach: function() {
			sandbox.verifyAndRestore();
		}
	}, function() {
		QUnit.skip("given a mock server, when get flex info is triggered", function (assert) {
			var oExpectedResponse = {
				isResetEnabled: false,
				isPublishEnabled: false
			};
			fnReturnData(200, {}, JSON.stringify(oExpectedResponse));

			var mPropertyBag = {url: "/sap/bc/lrep", reference: "reference", appVersion: "1.0.0", layer: "VENDOR"};
			var sUrl = "/sap/bc/lrep/flex/info/reference?layer=VENDOR&appVersion=1.0.0";
			return LrepConnector.getFlexInfo(mPropertyBag).then(function (oResponse) {
				assert.equal(sandbox.server.getRequest(0).method, "GET", "request method is GET");
				assert.equal(sandbox.server.getRequest(0).url, sUrl, "a flex info request is send containing the reference in the url and the app version and the layer as query parameters");
				assert.deepEqual(oResponse, oExpectedResponse, "getFlexInfo response flow is correct");
			});
		});
		QUnit.test("given a mock server, when publish is triggered", function (assert) {
			fnReturnData(204, {}, '[]');

			var mPropertyBag = {url: "/sap/bc/lrep", reference: "flexReference", appVersion: "1.0.0", layer: "VENDOR", changelist: "transportId", "package": "somePackage"};
			var sUrl = "/sap/bc/lrep/actions/make_changes_transportable/?reference=flexReference&layer=VENDOR&appVersion=1.0.0&changelist=transportId&package=somePackage";
			return LrepConnector.publish(mPropertyBag).then(function () {
				assert.equal(sandbox.server.getRequest(0).method, "POST", "request method is POST");
				assert.equal(sandbox.server.getRequest(0).url, sUrl, "a make changes transportable request is send containing the reference, the app version, the layer, the changelist and the package as query parameters");
			});
		});
		QUnit.skip("given a mock server, when reset is triggered", function (assert) {
			var aExpectedResponse = [
				{
					appComponent: "sap.ui.demoapps.rta.freestyle.Component",
					appVersionFrom: 10000000000,
					name: "id_1565952176663_88_stashControl",
					tenantId: "555552-a23e-6666-3333-53002f046412",
					userName: "test.test@test.com"
				}
			];
			fnReturnData(200, {}, JSON.stringify(aExpectedResponse));
			var mPropertyBag = {url: "/sap/bc/lrep", reference: "flexReference", appVersion: "1.0.0", layer: "VENDOR", changelist: "transportId", generator: "someGenerator", selectorIds:"someSelectors", changeTypes:"someChangeTypes"};
			var sUrl = "/sap/bc/lrep/changes/?reference=flexReference&layer=VENDOR&appVersion=1.0.0&changelist=transportId&generator=someGenerator&selector=someSelectors&changeType=someChangeTypes";
			return LrepConnector.reset(mPropertyBag).then(function (oResponse) {
				assert.equal(sandbox.server.getRequest(0).method, "DELETE", "request method is DELETE");
				assert.equal(sandbox.server.getRequest(0).url, sUrl, "a delete request is send containing the reference, the app version, the layer, the changelist, the generator, the selector Ids and the change types as query parameters");
				assert.deepEqual(oResponse, aExpectedResponse, "reset response flow is correct");
			});
		});
		QUnit.skip("given a mock server, when loadFeatures is triggered", function (assert) {
			var oExpectedResponse = {
				isKeyUser: true
			};
			fnReturnData(200, {}, JSON.stringify(oExpectedResponse));
			var mPropertyBag = {url: "/sap/bc/lrep"};
			var sUrl = "/sap/bc/lrep/flex/settings";

			return LrepConnector.loadFeatures(mPropertyBag).then(function (oResponse) {
				assert.equal(sandbox.server.getRequest(0).method, "GET", "request method is GET");
				assert.equal(sandbox.server.getRequest(0).url, sUrl, "Url is correct");
				assert.deepEqual(oResponse, oExpectedResponse, "loadFeatures response flow is correct");
			});
		});
	});
	QUnit.done(function () {
		jQuery('#qunit-fixture').hide();
	});
});
<|endoftext|>


<commit_before>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2016, OpenNebula Project, OpenNebula Systems                */
/*                                                                            */
/* 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.                                             */
/* -------------------------------------------------------------------------- */

define(function(require) {
  /*
    DEPENDENCIES
   */

  var Locale = require('utils/locale');
  var Tips = require('utils/tips');
  var CapacityCreate = require('./general/capacity-create');
  var WizardFields = require('utils/wizard-fields');
  var Config = require('sunstone-config');
  var UserInputs = require('utils/user-inputs');
  var UniqueId = require('utils/unique-id');

  /*
    TEMPLATES
   */

  var TemplateHTML = require('hbs!./general/html');

  /*
    CONSTANTS
   */

  var WIZARD_TAB_ID = require('./general/wizardTabId');

  /*
    CONSTRUCTOR
   */

  function WizardTab(opts) {
    if (!Config.isTemplateCreationTabEnabled(opts.tabId, 'general')) {
      throw "Wizard Tab not enabled";
    }

    this.wizardTabId = WIZARD_TAB_ID + UniqueId.id();
    this.icon = 'fa-laptop';
    this.title = Locale.tr("General");

    if(opts.listener != undefined){
      this.listener = opts.listener;
    }
  }

  WizardTab.prototype.constructor = WizardTab;
  WizardTab.prototype.html = _html;
  WizardTab.prototype.setup = _setup;
  WizardTab.prototype.onShow = _onShow;
  WizardTab.prototype.retrieve = _retrieve;
  WizardTab.prototype.fill = _fill;

  return WizardTab;

  /*
    FUNCTION DEFINITIONS
   */

  function _html() {
    return TemplateHTML({
      'capacityCreateHTML': CapacityCreate.html(),
      'logos': Config.vmLogos
    });
  }

  function _onShow(context, panelForm) {
    if (panelForm.action == 'create') {
      $('#NAME', context)
        .removeAttr('disabled')
        .attr("required", "")
        .prop('wizard_field_disabled', false);
    } else if (panelForm.action == 'update') {
      $('#NAME', context)
        .attr("disabled", "disabled")
        .removeAttr("required")
        .prop('wizard_field_disabled', true);
    }

    if (panelForm.resource == "VirtualRouterTemplate"){
      $("input[wizard_field=VROUTER]", context).attr("checked", "checked");
    }

    //context.foundation('slider', 'reflow');
  }
  function convertCostNumber(number){
    if(number >= 1000000){
      number = (number/1000000).toFixed(2)
      return number.toString()+"M";
    }
    else if(number >= 1000){
      number = (number/1000).toFixed(2)
      return number.toString()+"K";
    }
    return number;
  }
  function caculatedTotalMemory(context){
    var memory = document.getElementById('MEMORY_COST').value;
    var type = document.getElementById('MEMORY_UNIT_COST').value;
    if(type == "GB")
      memory *= 1024;
    memory = memory * 24 * 30; //24 hours and 30 days
    document.getElementById('total_value_memory').textContent = convertCostNumber(memory);
    $(".total_memory_cost", context).show();
  }

  function _setup(context) {
    var that = this;

    $(document).on('click', "[href='#" + this.wizardTabId + "']", function(){
      //context.foundation('slider', 'reflow');
    });

    context.on("change", "#MEMORY_COST", function() {
      caculatedTotalMemory(context);
      CapacityCreate.calculatedRealMemory(context);
    });

    context.on("change", "#MEMORY_UNIT_COST", function() {
      caculatedTotalMemory(context);
      CapacityCreate.calculatedRealMemory();
    });

     context.on("change", "#CPU_COST", function() {
      var cpu = document.getElementById('CPU_COST').value;
      document.getElementById('total_value_cpu').textContent = convertCostNumber(cpu * 24 * 30);
      $(".total_cpu_cost", context).show();
      CapacityCreate.calculatedRealCpu();
    });

    context.on("change", "#DISK_COST", function() {
      var disk = document.getElementById('DISK_COST').value;
      document.getElementById('total_value_disk').textContent = convertCostNumber(disk * 1024 * 24 * 30);
      $(".total_disk_cost", context).show();
    });

    context.on("change", "#LOGO", function() {
      $("#template_create_logo", context).show();
      $("#template_create_logo", context).html('' +
          '' +
        '');
    });

    context.on("change", "input[name='hypervisor']", function() {
      // TODO define context (for example: this.closest('form'))
      $(".hypervisor").hide();
      $(".only_" + this.value).show();

      if (this.value == "vcenter"){
        $("#vcenter_template_ref", context).attr("required", "");
      } else {
        $("#vcenter_template_ref", context).removeAttr("required");
      }
      // There is another listener in context.js setup
    });

    CapacityCreate.setup($("div.capacityCreate", context));

    if(that.listener != undefined){
      $(context).on("change", "input[wizard_field=VROUTER]", function(){
        that.listener.notify();
      });
    }
  }

  function _retrieve(context) {
    var templateJSON = WizardFields.retrieve(context);
    if(templateJSON["DISK_COST"]){
      templateJSON["DISK_COST"] = templateJSON["DISK_COST"] * 1024;
    }
    else{
      delete templateJSON["MEMORY_UNIT_COST"];
    }
    if(templateJSON["MEMORY_UNIT_COST"] == "GB")
      templateJSON["MEMORY_COST"] = templateJSON["MEMORY_COST"] * 1024;
    if (templateJSON["HYPERVISOR"] == 'vcenter') {
      templateJSON["VCENTER_TEMPLATE_REF"] = WizardFields.retrieveInput($("#vcenter_template_ref", context));

      if (Config.isFeatureEnabled("vcenter_vm_folder")) {
        templateJSON["VCENTER_VM_FOLDER"] = WizardFields.retrieveInput($("#vcenter_vm_folder", context))
      }
      templateJSON["KEEP_DISKS_ON_DONE"] = $("#KEEP_DISKS", context).is(':checked')?"YES":"NO"
    }

    var sunstone_template = {};

    if ($('#sunstone_network_select:checked', context).length > 0) {
      sunstone_template["NETWORK_SELECT"] = "NO"
    }

    if (!$.isEmptyObject(sunstone_template)) {
      templateJSON['SUNSTONE'] = sunstone_template;
    }

    var userInputs = {};

    // Retrieve Resource Pool Attribute
    var rpInput = $(".vcenter_rp_input", context);
    if (rpInput.length > 0) {
      var rpModify = WizardFields.retrieveInput($('.modify_rp', rpInput));
      var rpInitial = WizardFields.retrieveInput($('.initial_rp', rpInput));
      var rpParams = WizardFields.retrieveInput($('.available_rps', rpInput));

      if (rpModify === 'fixed' && rpInitial !== '') {
        templateJSON['VCENTER_RESOURCE_POOL'] = rpInitial;
      } else if (rpModify === 'list' && rpParams !== '') {
        var rpUserInputs = UserInputs.marshall({
            type: 'list',
            description: Locale.tr("Which resource pool you want this VM to run in?"),
            initial: rpInitial,
            params: WizardFields.retrieveInput($('.available_rps', rpInput))
          });

        userInputs['VCENTER_RESOURCE_POOL'] = rpUserInputs;
      }
    }

    // Since the USER_INPUTS section is not enabled for vCenter, we can assume that there are no more user inputs defined
    if (!$.isEmptyObject(userInputs)) {
      templateJSON['USER_INPUTS'] = userInputs;
    }

    $.extend(true, templateJSON, CapacityCreate.retrieve($("div.capacityCreate", context)));

    return templateJSON;
  }

  function _fill(context, templateJSON) {
    var sunstone_template = templateJSON.SUNSTONE;
    if(templateJSON["MEMORY_UNIT_COST"] =="GB")
      templateJSON["MEMORY_COST"] = templateJSON["MEMORY_COST"] / 1024;
    if (sunstone_template) {
      if (sunstone_template["NETWORK_SELECT"] &&
          sunstone_template["NETWORK_SELECT"].toUpperCase() == "NO") {
        $("#sunstone_network_select", context).attr("checked", "checked");
      }

      delete sunstone_template["NETWORK_SELECT"];
    }

    if (Config.isFeatureEnabled("vcenter_vm_folder")) {
      if (templateJSON["HYPERVISOR"] == 'vcenter' &&
        templateJSON["VCENTER_VM_FOLDER"]) {
        WizardFields.fillInput($("#vcenter_vm_folder", context), templateJSON["VCENTER_VM_FOLDER"]);
      }
    } else {
      $(".vcenter_vm_folder_input", context).remove();
    }

    delete templateJSON["VCENTER_VM_FOLDER"];

    if (templateJSON["HYPERVISOR"] == 'vcenter') {
      var publicClouds = templateJSON["PUBLIC_CLOUD"];

      if (publicClouds != undefined) {
        if (!$.isArray(publicClouds)){
          publicClouds = [publicClouds];
        }

        $.each(publicClouds, function(){
          if(this["TYPE"] == "vcenter"){
            WizardFields.fillInput($("#vcenter_template_ref", context), this["VCENTER_TEMPLATE_REF"]);
            return false;
          }
        });
      }
    }

    if (templateJSON["HYPERVISOR"]) {
      $("input[name='hypervisor'][value='"+templateJSON["HYPERVISOR"]+"']", context).trigger("click")
      delete templateJSON["HYPERVISOR"];
    }

    if (templateJSON["USER_INPUTS"]) {

      if (templateJSON["USER_INPUTS"]["VCENTER_RESOURCE_POOL"]) {
        var rp = UserInputs.unmarshall(templateJSON["USER_INPUTS"]["VCENTER_RESOURCE_POOL"]);
        $('.modify_rp', context).val('list');
        $('.initial_rp', context).val(rp.initial);
        $('.available_rps', context).val(rp.params);

        delete templateJSON["USER_INPUTS"]["VCENTER_RESOURCE_POOL"];
      }
    }

    if (templateJSON["VCENTER_RESOURCE_POOL"]) {
      $('.modify_rp', context).val('fixed');
      WizardFields.fillInput($('.initial_rp', context), templateJSON["VCENTER_RESOURCE_POOL"]);

      delete templateJSON["VCENTER_RESOURCE_POOL"];
    }

    if(templateJSON["VCENTER_TEMPLATE_REF"]){
      WizardFields.fillInput($("#vcenter_template_ref", context), templateJSON["VCENTER_TEMPLATE_REF"]);
      delete templateJSON["VCENTER_TEMPLATE_REF"];
    }

    CapacityCreate.fill($("div.capacityCreate", context), templateJSON);

    WizardFields.fill(context, templateJSON);
  }
});
<commit_msg>F #4913: Remove KEEP_DISKS_ON_DONE remnants<commit_after>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2016, OpenNebula Project, OpenNebula Systems                */
/*                                                                            */
/* 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.                                             */
/* -------------------------------------------------------------------------- */

define(function(require) {
  /*
    DEPENDENCIES
   */

  var Locale = require('utils/locale');
  var Tips = require('utils/tips');
  var CapacityCreate = require('./general/capacity-create');
  var WizardFields = require('utils/wizard-fields');
  var Config = require('sunstone-config');
  var UserInputs = require('utils/user-inputs');
  var UniqueId = require('utils/unique-id');

  /*
    TEMPLATES
   */

  var TemplateHTML = require('hbs!./general/html');

  /*
    CONSTANTS
   */

  var WIZARD_TAB_ID = require('./general/wizardTabId');

  /*
    CONSTRUCTOR
   */

  function WizardTab(opts) {
    if (!Config.isTemplateCreationTabEnabled(opts.tabId, 'general')) {
      throw "Wizard Tab not enabled";
    }

    this.wizardTabId = WIZARD_TAB_ID + UniqueId.id();
    this.icon = 'fa-laptop';
    this.title = Locale.tr("General");

    if(opts.listener != undefined){
      this.listener = opts.listener;
    }
  }

  WizardTab.prototype.constructor = WizardTab;
  WizardTab.prototype.html = _html;
  WizardTab.prototype.setup = _setup;
  WizardTab.prototype.onShow = _onShow;
  WizardTab.prototype.retrieve = _retrieve;
  WizardTab.prototype.fill = _fill;

  return WizardTab;

  /*
    FUNCTION DEFINITIONS
   */

  function _html() {
    return TemplateHTML({
      'capacityCreateHTML': CapacityCreate.html(),
      'logos': Config.vmLogos
    });
  }

  function _onShow(context, panelForm) {
    if (panelForm.action == 'create') {
      $('#NAME', context)
        .removeAttr('disabled')
        .attr("required", "")
        .prop('wizard_field_disabled', false);
    } else if (panelForm.action == 'update') {
      $('#NAME', context)
        .attr("disabled", "disabled")
        .removeAttr("required")
        .prop('wizard_field_disabled', true);
    }

    if (panelForm.resource == "VirtualRouterTemplate"){
      $("input[wizard_field=VROUTER]", context).attr("checked", "checked");
    }

    //context.foundation('slider', 'reflow');
  }
  function convertCostNumber(number){
    if(number >= 1000000){
      number = (number/1000000).toFixed(2)
      return number.toString()+"M";
    }
    else if(number >= 1000){
      number = (number/1000).toFixed(2)
      return number.toString()+"K";
    }
    return number;
  }
  function caculatedTotalMemory(context){
    var memory = document.getElementById('MEMORY_COST').value;
    var type = document.getElementById('MEMORY_UNIT_COST').value;
    if(type == "GB")
      memory *= 1024;
    memory = memory * 24 * 30; //24 hours and 30 days
    document.getElementById('total_value_memory').textContent = convertCostNumber(memory);
    $(".total_memory_cost", context).show();
  }

  function _setup(context) {
    var that = this;

    $(document).on('click', "[href='#" + this.wizardTabId + "']", function(){
      //context.foundation('slider', 'reflow');
    });

    context.on("change", "#MEMORY_COST", function() {
      caculatedTotalMemory(context);
      CapacityCreate.calculatedRealMemory(context);
    });

    context.on("change", "#MEMORY_UNIT_COST", function() {
      caculatedTotalMemory(context);
      CapacityCreate.calculatedRealMemory();
    });

     context.on("change", "#CPU_COST", function() {
      var cpu = document.getElementById('CPU_COST').value;
      document.getElementById('total_value_cpu').textContent = convertCostNumber(cpu * 24 * 30);
      $(".total_cpu_cost", context).show();
      CapacityCreate.calculatedRealCpu();
    });

    context.on("change", "#DISK_COST", function() {
      var disk = document.getElementById('DISK_COST').value;
      document.getElementById('total_value_disk').textContent = convertCostNumber(disk * 1024 * 24 * 30);
      $(".total_disk_cost", context).show();
    });

    context.on("change", "#LOGO", function() {
      $("#template_create_logo", context).show();
      $("#template_create_logo", context).html('' +
          '' +
        '');
    });

    context.on("change", "input[name='hypervisor']", function() {
      // TODO define context (for example: this.closest('form'))
      $(".hypervisor").hide();
      $(".only_" + this.value).show();

      if (this.value == "vcenter"){
        $("#vcenter_template_ref", context).attr("required", "");
      } else {
        $("#vcenter_template_ref", context).removeAttr("required");
      }
      // There is another listener in context.js setup
    });

    CapacityCreate.setup($("div.capacityCreate", context));

    if(that.listener != undefined){
      $(context).on("change", "input[wizard_field=VROUTER]", function(){
        that.listener.notify();
      });
    }
  }

  function _retrieve(context) {
    var templateJSON = WizardFields.retrieve(context);
    if(templateJSON["DISK_COST"]){
      templateJSON["DISK_COST"] = templateJSON["DISK_COST"] * 1024;
    }
    else{
      delete templateJSON["MEMORY_UNIT_COST"];
    }
    if(templateJSON["MEMORY_UNIT_COST"] == "GB")
      templateJSON["MEMORY_COST"] = templateJSON["MEMORY_COST"] * 1024;
    if (templateJSON["HYPERVISOR"] == 'vcenter') {
      templateJSON["VCENTER_TEMPLATE_REF"] = WizardFields.retrieveInput($("#vcenter_template_ref", context));

      if (Config.isFeatureEnabled("vcenter_vm_folder")) {
        templateJSON["VCENTER_VM_FOLDER"] = WizardFields.retrieveInput($("#vcenter_vm_folder", context))
      }
    }

    var sunstone_template = {};

    if ($('#sunstone_network_select:checked', context).length > 0) {
      sunstone_template["NETWORK_SELECT"] = "NO"
    }

    if (!$.isEmptyObject(sunstone_template)) {
      templateJSON['SUNSTONE'] = sunstone_template;
    }

    var userInputs = {};

    // Retrieve Resource Pool Attribute
    var rpInput = $(".vcenter_rp_input", context);
    if (rpInput.length > 0) {
      var rpModify = WizardFields.retrieveInput($('.modify_rp', rpInput));
      var rpInitial = WizardFields.retrieveInput($('.initial_rp', rpInput));
      var rpParams = WizardFields.retrieveInput($('.available_rps', rpInput));

      if (rpModify === 'fixed' && rpInitial !== '') {
        templateJSON['VCENTER_RESOURCE_POOL'] = rpInitial;
      } else if (rpModify === 'list' && rpParams !== '') {
        var rpUserInputs = UserInputs.marshall({
            type: 'list',
            description: Locale.tr("Which resource pool you want this VM to run in?"),
            initial: rpInitial,
            params: WizardFields.retrieveInput($('.available_rps', rpInput))
          });

        userInputs['VCENTER_RESOURCE_POOL'] = rpUserInputs;
      }
    }

    // Since the USER_INPUTS section is not enabled for vCenter, we can assume that there are no more user inputs defined
    if (!$.isEmptyObject(userInputs)) {
      templateJSON['USER_INPUTS'] = userInputs;
    }

    $.extend(true, templateJSON, CapacityCreate.retrieve($("div.capacityCreate", context)));

    return templateJSON;
  }

  function _fill(context, templateJSON) {
    var sunstone_template = templateJSON.SUNSTONE;
    if(templateJSON["MEMORY_UNIT_COST"] =="GB")
      templateJSON["MEMORY_COST"] = templateJSON["MEMORY_COST"] / 1024;
    if (sunstone_template) {
      if (sunstone_template["NETWORK_SELECT"] &&
          sunstone_template["NETWORK_SELECT"].toUpperCase() == "NO") {
        $("#sunstone_network_select", context).attr("checked", "checked");
      }

      delete sunstone_template["NETWORK_SELECT"];
    }

    if (Config.isFeatureEnabled("vcenter_vm_folder")) {
      if (templateJSON["HYPERVISOR"] == 'vcenter' &&
        templateJSON["VCENTER_VM_FOLDER"]) {
        WizardFields.fillInput($("#vcenter_vm_folder", context), templateJSON["VCENTER_VM_FOLDER"]);
      }
    } else {
      $(".vcenter_vm_folder_input", context).remove();
    }

    delete templateJSON["VCENTER_VM_FOLDER"];

    if (templateJSON["HYPERVISOR"] == 'vcenter') {
      var publicClouds = templateJSON["PUBLIC_CLOUD"];

      if (publicClouds != undefined) {
        if (!$.isArray(publicClouds)){
          publicClouds = [publicClouds];
        }

        $.each(publicClouds, function(){
          if(this["TYPE"] == "vcenter"){
            WizardFields.fillInput($("#vcenter_template_ref", context), this["VCENTER_TEMPLATE_REF"]);
            return false;
          }
        });
      }
    }

    if (templateJSON["HYPERVISOR"]) {
      $("input[name='hypervisor'][value='"+templateJSON["HYPERVISOR"]+"']", context).trigger("click")
      delete templateJSON["HYPERVISOR"];
    }

    if (templateJSON["USER_INPUTS"]) {

      if (templateJSON["USER_INPUTS"]["VCENTER_RESOURCE_POOL"]) {
        var rp = UserInputs.unmarshall(templateJSON["USER_INPUTS"]["VCENTER_RESOURCE_POOL"]);
        $('.modify_rp', context).val('list');
        $('.initial_rp', context).val(rp.initial);
        $('.available_rps', context).val(rp.params);

        delete templateJSON["USER_INPUTS"]["VCENTER_RESOURCE_POOL"];
      }
    }

    if (templateJSON["VCENTER_RESOURCE_POOL"]) {
      $('.modify_rp', context).val('fixed');
      WizardFields.fillInput($('.initial_rp', context), templateJSON["VCENTER_RESOURCE_POOL"]);

      delete templateJSON["VCENTER_RESOURCE_POOL"];
    }

    if(templateJSON["VCENTER_TEMPLATE_REF"]){
      WizardFields.fillInput($("#vcenter_template_ref", context), templateJSON["VCENTER_TEMPLATE_REF"]);
      delete templateJSON["VCENTER_TEMPLATE_REF"];
    }

    CapacityCreate.fill($("div.capacityCreate", context), templateJSON);

    WizardFields.fill(context, templateJSON);
  }
});
<|endoftext|>


<commit_before>import Ember from 'ember';
import multiton from 'ember-multiton-service';

const {
  Service,
  assign,
  computed,
  get,
  isPresent,
  set,
  typeOf
} = Ember;

export default Service.extend({
  activeState: computed(() => {
    return {};
  }),

  eBus: multiton('message-bus', 'engineId'),

  init(...args) {
    this._super(...args);

    const eBus = get(this, 'eBus');

    eBus.subscribe('shouldFileActiveState', this, this._shouldFileActiveState);
    eBus.subscribe('restartingEngine', this, this._reset);
    eBus.subscribe('shouldLoadLatestStatePoint', this, this._loadLatestStatePoint);

    eBus.subscribe('shouldSetStateValue', this, this._setStateValue);
    eBus.subscribe('shouldSetStateValueMax', this, this._setStateValueMax);
    eBus.subscribe('shouldSetStateValueMin', this, this._setStateValueMin);
    eBus.subscribe('shouldDecrementStateValue', this, this._decrementStateValue);
    eBus.subscribe('shouldIncrementStateValue', this, this._incrementStateValue);
    eBus.subscribe('shouldToggleStateValue', this, this._toggleStateValue);
    eBus.subscribe('shouldDeleteStateValue', this, this._deleteStateValue);
  },

  _reset() {
    set(this, 'activeState', {});
  },

  _shouldFileActiveState() {
    get(this, 'eBus').publish('rsa:shouldFileActiveState', get(this, 'activeState'));
  },

  _loadLatestStatePoint(statePoints) {
    const activeState = assign({}, statePoints[statePoints.length - 1]) || {};

    set(this, 'activeState', activeState);
  },

  _setStateValue(key, value) {
    set(this, `activeState.${key}`, this._cappedNumber(key, value));
  },

  _setStateValueMax(key, value) {
    const maxMap = get(this, 'activeState._maxMap') || set(this, 'activeState._maxMap', {});

    set(maxMap, key, value);
  },

  _setStateValueMin(key, value) {
    const minMap = get(this, 'activeState._minMap') || set(this, 'activeState._minMap', {});

    set(minMap, key, value);
  },

  _decrementStateValue(key, amount) {
    const newValue = this.decrementProperty(`activeState.${key}`, amount);

    this._setStateValue(key, newValue);
  },

  _incrementStateValue(key, amount) {
    const newValue = this.incrementProperty(`activeState.${key}`, amount);

    this._setStateValue(key, newValue);
  },

  _toggleStateValue(key) {
    this.toggleProperty(`activeState.${key}`);
  },

  _deleteStateValue(key) {
    this._setStateValue(key, undefined);
  },

  _cappedNumber(key, value) {
    if (typeOf(value) === 'number') {
      const max = get(this, `activeState._maxMap.${key}`);
      const min = get(this, `activeState._minMap.${key}`);

      if (isPresent(max) && value > max) {
        return max;
      } else if (isPresent(min) && value < min) {
        return min;
      }
    }

    return value
  }
});
<commit_msg>allow nested min max<commit_after>import Ember from 'ember';
import multiton from 'ember-multiton-service';

const {
  Service,
  assign,
  computed,
  get,
  isPresent,
  set,
  typeOf
} = Ember;

export default Service.extend({
  activeState: computed(() => {
    return {};
  }),

  eBus: multiton('message-bus', 'engineId'),

  init(...args) {
    this._super(...args);

    const eBus = get(this, 'eBus');

    eBus.subscribe('shouldFileActiveState', this, this._shouldFileActiveState);
    eBus.subscribe('restartingEngine', this, this._reset);
    eBus.subscribe('shouldLoadLatestStatePoint', this, this._loadLatestStatePoint);

    eBus.subscribe('shouldSetStateValue', this, this._setStateValue);
    eBus.subscribe('shouldSetStateValueMax', this, this._setStateValueMax);
    eBus.subscribe('shouldSetStateValueMin', this, this._setStateValueMin);
    eBus.subscribe('shouldDecrementStateValue', this, this._decrementStateValue);
    eBus.subscribe('shouldIncrementStateValue', this, this._incrementStateValue);
    eBus.subscribe('shouldToggleStateValue', this, this._toggleStateValue);
    eBus.subscribe('shouldDeleteStateValue', this, this._deleteStateValue);
  },

  _reset() {
    set(this, 'activeState', {});
  },

  _shouldFileActiveState() {
    get(this, 'eBus').publish('rsa:shouldFileActiveState', get(this, 'activeState'));
  },

  _loadLatestStatePoint(statePoints) {
    const activeState = assign({}, statePoints[statePoints.length - 1]) || {};

    set(this, 'activeState', activeState);
  },

  _setStateValue(key, value) {
    set(this, `activeState.${key}`, this._cappedNumber(key, value));
  },

  _setStateValueMax(key, value) {
    const maxMap = get(this, 'activeState._maxMap') || set(this, 'activeState._maxMap', {});

    this._addToMinMaxMap(maxMap, key, value);
  },

  _setStateValueMin(key, value) {
    const minMap = get(this, 'activeState._minMap') || set(this, 'activeState._minMap', {});

    this._addToMinMaxMap(minMap, key, value);
  },

  _addToMinMaxMap(map, key, value) {
    const segments = key.split('.');
    const lastIndex = segments.length - 1;

    segments.reduce((map, section, index) => {
      return lastIndex === index ? set(map, section, value) : get(map, section) || set(map, section, {});
    }, map);
  },

  _decrementStateValue(key, amount) {
    const newValue = this.decrementProperty(`activeState.${key}`, amount);

    this._setStateValue(key, newValue);
  },

  _incrementStateValue(key, amount) {
    const newValue = this.incrementProperty(`activeState.${key}`, amount);

    this._setStateValue(key, newValue);
  },

  _toggleStateValue(key) {
    this.toggleProperty(`activeState.${key}`);
  },

  _deleteStateValue(key) {
    this._setStateValue(key, undefined);
  },

  _cappedNumber(key, value) {
    if (typeOf(value) === 'number') {
      const max = get(this, `activeState._maxMap.${key}`);
      const min = get(this, `activeState._minMap.${key}`);

      if (isPresent(max) && value > max) {
        return max;
      } else if (isPresent(min) && value < min) {
        return min;
      }
    }

    return value
  }
});
<|endoftext|>


<commit_before>import sceneImportModalTpl from './sceneImportModal.html';

const rfSceneImportModal = {
    templateUrl: sceneImportModalTpl,
    bindings: {
        close: '&',
        dismiss: '&',
        modalInstance: '<',
        resolve: '<'
    },
    controller: 'ImportModalController'
};

export default rfSceneImportModal;
<commit_msg>Fix import modal<commit_after>import sceneImportModalTpl from './sceneImportModal.html';

const rfSceneImportModal = {
    templateUrl: sceneImportModalTpl,
    bindings: {
        close: '&',
        dismiss: '&',
        modalInstance: '<',
        resolve: '<'
    },
    controller: 'SceneImportModalController'
};

export default rfSceneImportModal;
<|endoftext|>


<commit_before>export default {
  title: {
    withLocation: 'Fire Alerts in {location}'
  },
  config: {
    size: 'large',
    categories: ['summary', 'forest-change'],
    weeks: [13, 26, 52],
    admins: ['country', 'region', 'subRegion'],
    type: 'fires',
    selectors: ['weeks', 'datasets'],
    metaKey: 'widget_fire_alert_location',
    interactive: true,
    locationWhitelist: [
      'IDN',
      'MEX',
      'AUS',
      'THA',
      'MMR',
      'KHM',
      'MWI',
      'CMR',
      'GAB',
      'COG',
      'COD',
      'FIN',
      'RUS',
      'NGA',
      'GNQ',
      'AGO',
      'NOR',
      'TZA',
      'IRN',
      'MAR',
      'ETH',
      'KEN',
      'UKR',
      'DZA',
      'ESP',
      'GRC',
      'LTU',
      'SSD',
      'EGY',
      'MLI',
      'SAU',
      'BLR',
      'GEO',
      'GHA',
      'SJM',
      'BFA',
      'NER',
      'ITA',
      'SEN',
      'FRA',
      'ROU',
      'TUN',
      'KAZ',
      'LVA',
      'STP',
      'POL',
      'HRV',
      'ARM',
      'JOR',
      'ESH',
      'PRT',
      'IRQ',
      'MRT',
      'TKM',
      'AZE',
      'ERI',
      'ZMB',
      'TUR',
      'BEN',
      'BGR',
      'SOM',
      'SYR',
      'SDN',
      'AUT',
      'CYP',
      'TCD',
      'SVN',
      'CZE',
      'YEM',
      'LBY',
      'KWT',
      'ALB',
      'SRB',
      'MKD',
      'SGS',
      'UGA',
      'MNE',
      'OMN',
      'BIH',
      'UZB',
      'GRL',
      'MDA',
      'TGO',
      'NAM',
      'EST',
      'BRA',
      'GMB',
      'CIV',
      'QAT',
      'ARE',
      'CAF',
      'IND',
      'XNC',
      'DEU',
      'DJI',
      'AFG',
      'ISR',
      'PAK',
      'AND',
      'CHE',
      'GNB',
      'XKO',
      'LBN',
      'CAN',
      'ZWE',
      'BHR',
      'ARG',
      'VEN',
      'MLT',
      'GIN',
      'COL',
      'GUF',
      'PER',
      'MDG',
      'SHN',
      'GBR',
      'HUN',
      'PRY',
      'SUR',
      'SWE',
      'ZAF',
      'CPV',
      'GIB',
      'CUB',
      'MOZ',
      'BOL',
      'TJK',
      'USA',
      'CHN',
      'HND',
      'IRL',
      'SYC',
      'BDI',
      'CHL',
      'ISL',
      'LSO',
      'NIC',
      'RWA',
      'SVK',
      'URY'
    ],
    sortOrder: {
      summary: 100,
      forestChange: 100
    },
    sentences: {
      initial:
        'There were {count} {dataset} fire alerts reported in the week of the {date}. This was {status} compared to the same week in previous years.'
    }
  },
  settings: {
    period: 'week',
    weeks: 13,
    dataset: 'MODIS',
    layerStartDate: null,
    layerEndDate: null
  },
  enabled: true
};
<commit_msg>fires locations updated<commit_after>export default {
  title: {
    withLocation: 'Fire Alerts in {location}'
  },
  config: {
    size: 'large',
    categories: ['summary', 'forest-change'],
    weeks: [13, 26, 52],
    admins: ['country', 'region', 'subRegion'],
    type: 'fires',
    selectors: ['weeks', 'datasets'],
    metaKey: 'widget_fire_alert_location',
    interactive: true,
    locationWhitelist: [
      'AFG',
      'AGO',
      'ALB',
      'AND',
      'ANT',
      'ARE',
      'ARG',
      'ARM',
      'AUS',
      'AUT',
      'AZE',
      'BDI',
      'BEL',
      'BEN',
      'BFA',
      'BGD',
      'BGR',
      'BHR',
      'BHS',
      'BIH',
      'BLM',
      'BLR',
      'BLZ',
      'BOL',
      'BRA',
      'BRB',
      'BRN',
      'BTN',
      'BWA',
      'CAF',
      'CAN',
      'CHE',
      'CHL',
      'CHN',
      'CIV',
      'CMR',
      'COD',
      'COG',
      'COL',
      'COM',
      'CPV',
      'CRI',
      'CUB',
      'CYP',
      'CZE',
      'DEU',
      'DJI',
      'DMA',
      'DNK',
      'DOM',
      'DZA',
      'ECU',
      'EGY',
      'ERI',
      'ESP',
      'EST',
      'ETH',
      'FIN',
      'FJI',
      'FLK',
      'FRA',
      'FSM',
      'GAB',
      'GBR',
      'GEO',
      'GHA',
      'GIB',
      'GIN',
      'GLP',
      'GMB',
      'GNB',
      'GNQ',
      'GRC',
      'GRL',
      'GTM',
      'GUF',
      'GUM',
      'GUY',
      'HND',
      'HRV',
      'HTI',
      'HUN',
      'IDN',
      'IND',
      'IRL',
      'IRN',
      'IRQ',
      'ISR',
      'ITA',
      'JAM',
      'JOR',
      'JPN',
      'KAZ',
      'KEN',
      'KGZ',
      'KHM',
      'KIR',
      'KNA',
      'KOR',
      'KWT',
      'LAO',
      'LBN',
      'LBR',
      'LBY',
      'LCA',
      'LIE',
      'LKA',
      'LSO',
      'LTU',
      'LUX',
      'LVA',
      'MAR',
      'MCO',
      'MDA',
      'MDG',
      'MDV',
      'MEX',
      'MHL',
      'MKD',
      'MLI',
      'MLT',
      'MMR',
      'MNE',
      'MNG',
      'MNP',
      'MOZ',
      'MRT',
      'MSR',
      'MTQ',
      'MUS',
      'MWI',
      'MYS',
      'NAM',
      'NCL',
      'NER',
      'NGA',
      'NIC',
      'NLD',
      'NOR',
      'NPL',
      'NZL',
      'OMN',
      'PAK',
      'PAN',
      'PCN',
      'PER',
      'PHL',
      'PNG',
      'POL',
      'PRI',
      'PRK',
      'PRT',
      'PRY',
      'PSE',
      'PYF',
      'QAT',
      'REU',
      'ROU',
      'RUS',
      'RWA',
      'SAU',
      'SDN',
      'SEN',
      'SGP',
      'SLB',
      'SLE',
      'SLV',
      'SOM',
      'SRB',
      'SSD',
      'STP',
      'SUR',
      'SVK',
      'SVN',
      'SWE',
      'SWZ',
      'SYR',
      'TCD',
      'TGO',
      'THA',
      'TJK',
      'TKL',
      'TKM',
      'TLS',
      'TON',
      'TTO',
      'TUN',
      'TUR',
      'TUV',
      'TZA',
      'UGA',
      'UKR',
      'URY',
      'USA',
      'UZB',
      'VAT',
      'VEN',
      'VIR',
      'VNM',
      'VUT',
      'WSM',
      'YEM',
      'ZAF',
      'ZMB',
      'ZWE'
    ],
    sortOrder: {
      summary: 100,
      forestChange: 100
    },
    sentences: {
      initial:
        'There were {count} {dataset} fire alerts reported in the week of the {date}. This was {status} compared to the same week in previous years.'
    }
  },
  settings: {
    period: 'week',
    weeks: 13,
    dataset: 'MODIS',
    layerStartDate: null,
    layerEndDate: null
  },
  enabled: true
};
<|endoftext|>