<commit_before>// Copyright (c) Cognitect, Inc.
// All rights reserved.

goog.provide("com.cognitect.transit.impl.decoder");
goog.require("com.cognitect.transit.util");
goog.require("com.cognitect.transit.delimiters");
goog.require("com.cognitect.transit.caching");
goog.require("com.cognitect.transit.types");

goog.scope(function() {

var decoder = com.cognitect.transit.impl.decoder,
    util    = com.cognitect.transit.util,
    d       = com.cognitect.transit.delimiters,
    caching = com.cognitect.transit.caching,
    types   = com.cognitect.transit.types;

// =============================================================================
// Decoder

decoder.isGroundHandler = function(handler) {
    switch(handler) {
        case "_":
        case "s":
        case "?":
        case "i":
        case "d":
        case "b":
        case "'":
        case "array":
        case "map":
        return true;
    }
    return false;
};

/**
 * A transit decoder
 * @constructor
 */
decoder.Decoder = function(options) {
    this.options = options || {};
    this.handlers = {};
    for(var h in this.defaults.handlers) {
        this.handlers[h] = this.defaults.handlers[h];
    }
    for(var h in this.options["handlers"]) {
        if(decoder.isGroundHandler(h)) {
            throw new Error("Cannot override handler for ground types");
        }
        this.handlers[h] = this.options["handlers"][h];
    }
    this.preferStrings = this.options["preferStrings"] != null ? this.options["preferStrings"] : this.defaults.preferStrings;
    this.preferObjects = this.options["preferObjects"] != null ? this.options["preferObjects"] : this.defaults.preferObjects;
    this.defaultHandler = this.options["defaultHandler"] || this.defaults.defaultHandler;
    /* NOT PUBLIC */
    this.mapBuilder = this.options["mapBuilder"];
    this.arrayBuilder = this.options["arrayBuilder"];
};

decoder.Decoder.prototype.defaults = {
    handlers: {
        "_": function(v) { return types.nullValue(); },
        "?": function(v) { return types.boolValue(v); },
        "b": function(v) { return types.binary(v); },
        "i": function(v) { return types.intValue(v); },
        "n": function(v) { return types.bigInteger(v); },
        "d": function(v) { return types.floatValue(v); },
        "f": function(v) { return types.bigDecimalValue(v); },
        "c": function(v) { return types.charValue(v); },
        ":": function(v) { return types.keyword(v); },
        "$": function(v) { return types.symbol(v); },
        "r": function(v) { return types.uri(v); },

        // tagged
        "'": function(v) { return v; },
        "m": function(v) { return types.date(v); },
        "t": function(v) { return types.verboseDate(v); },
        "u": function(v) { return types.uuid(v); },
        "set": function(v) { return types.set(v); },
        "list": function(v) { return types.list(v); },
        "ints": function(v) { return types.ints(v); },
        "longs": function(v) { return types.longs(v); },
        "floats": function(v) { return types.floats(v); },
        "doubles": function(v) { return types.doubles(v); },
        "bools": function(v) { return types.bools(v); },
        "cmap": function(v) { return types.map(v, false); }
    },
    defaultHandler: function(c, val) {
        return types.taggedValue(c, val);
    },
    preferStrings: true,
    preferObjects: false
};

decoder.Decoder.prototype.decode = function(node, cache, asMapKey, tagValue) {
    if(node == null) return null;

    var t = typeof node;

    switch(t) {
    case "string":
        return this.decodeString(node, cache, asMapKey, tagValue);
        break;
    case "object":
        if(util.isArray(node)) {
            if(node[0] === "^ ") {
                return this.decodeArrayHash(node, cache, asMapKey, tagValue);
            } else {
                return this.decodeArray(node, cache, false, tagValue);
            }
        } else {
            return this.decodeHash(node, cache, asMapKey, tagValue);
        }
        break;
    }

    return node;
};
decoder.Decoder.prototype["decode"] = decoder.Decoder.prototype.decode;

decoder.Decoder.prototype.decodeString = function(string, cache, asMapKey, tagValue) {
    if(caching.isCacheable(string, asMapKey)) {
        var val = this.parseString(string, cache, false);
        if(cache) {
            cache.write(val, asMapKey);
        }
        return val;
    } else if(caching.isCacheCode(string)) {
        return cache.read(string, asMapKey);
    } else {
        return this.parseString(string, cache, asMapKey);
    }
};

decoder.Decoder.prototype.isStringKey = function(node, cache) {
    if(typeof node !== "string") {
        return false;
    } else {
        var c0 = node[0],
            c1 = node[1];
        if(c0 === d.ESC) {
            if(this.handlers[c1] != null) {
                return false;
            } else {
                return (c1 === d.ESC || c1 === d.SUB || c1 === d.RES);
            }
        } else if(c0 === d.SUB && ((typeof cache.read(node)) !== "string"))  {
            return false;
        } else {
            return true;
        }
    }
};

decoder.Decoder.prototype.decodeHash = function(hash, cache, asMapKey, tagValue) {
    var ks     = util.objectKeys(hash),
        key    = ks[0],
        tagKey = ks.length == 1 ? this.decode(key, cache, false, false) : null;

    if((tagKey != null) &&
       (tagKey[0] === d.ESC) &&
       (tagKey[1] === d.TAG)) {
        var val     = hash[key],
            handler = this.handlers[tagKey.substring(2)];
        if(handler != null) {
            return handler(this.decode(val, cache, false, true));
        } else {
            return types.taggedValue(tagKey.substring(2), this.decode(val, cache, false, false));
        }
    } else if(this.mapBuilder) {
        if((ks.length < (types.SMALL_ARRAY_MAP_THRESHOLD*2)) && this.mapBuilder.fromArray) {
            var nodep = [];
            for(var i = 0; i < ks.length; i++) {
                var strKey = ks[i];
                nodep.push(this.decode(strKey, cache, true, false));
                nodep.push(this.decode(hash[strKey], cache, false, false));
            }
            return this.mapBuilder.fromArray(nodep);
        } else {
            var ret = this.mapBuilder.init();
            for(var i = 0; i < ks.length; i++) {
                var strKey = ks[i];
                ret = this.mapBuilder.add(ret, this.decode(strKey, cache, true, false),
                                               this.decode(hash[strKey], cache, false, false));
            }
            return this.mapBuilder.finalize(ret);
        }
    } else {
        var stringKeys = true,
            nodep      = [];

        for(var i = 0; i < ks.length; i++) {
            var strKey = ks[i];
            if(this.preferObjects) {
                stringKeys = stringKeys && this.isStringKey(strKey, cache);
            }
            nodep.push(this.decode(strKey, cache, true, false));
            nodep.push(this.decode(hash[strKey], cache, false, false));
        }

        if(this.preferObjects && stringKeys) {
            var ret = {};
            for(var j = 0; j < nodep.length; j+=2) {
                ret[nodep[j]] = nodep[j+1];
            }
            return ret;
        } else {
            return types.map(nodep, false);
        }
    }
};

decoder.Decoder.prototype.decodeArrayHash = function(node, cache, asMapKey, tagValue) {
    if(this.mapBuilder) {
        if((ks.length < (types.SMALL_ARRAY_MAP_THRESHOLD*2)) && this.mapBuilder.fromArray) {
            var nodep = [];
            for(var i = 1; i < node.length; i+=2) {
                nodep.push(this.decode(node[i], cache, true, false));
                nodep.push(this.decode(node[i+1], cache, false, false));
            }
            return this.mapBuilder.fromArray(nodep);
        } else {
            var ret = this.mapBuilder.init();
            for(var i = 1; i < node.length; i+=2) {
                ret = this.mapBuilder.add(ret, this.decode(node[i], cache, true, false),
                                               this.decode(node[i+1], cache, false, false))
            }
            return this.mapBuilder.finalize(ret);
        }
    } else {
        var stringKeys = true,
            nodep      = [];

        // collect keys
        for(var i = 1; i < node.length; i +=2) {
            if(this.preferObjects) {
                stringKeys = stringKeys && this.isStringKey(node[i], cache);
            }
            nodep.push(this.decode(node[i], cache, true, false));
            nodep.push(this.decode(node[i+1], cache, false, false));
        }

        if(this.preferObjects && stringKeys) {
            var ret = {};
            for(var j = 0; j < nodep.length; j+=2) {
                ret[nodep[j]] = nodep[j+1];
            }
            return ret;
        } else {
            return types.map(nodep, false);
        }
    }
};

decoder.Decoder.prototype.decodeArray = function(node, cache, asMapKey, tagValue) {
    if(tagValue) {
        var ret = [];
        for(var i = 0; i < node.length; i++) {
            ret.push(this.decode(node[i], cache, asMapKey, false));
        }
        return ret;
    } else if(this.arrayBuilder) {
        var ret = this.arrayBuilder.init();
        for(var i = 0; i < node.length; i++) {
            ret = this.arrayBuilder.add(ret, this.decode(node[i], cache, asMapKey, false));
        }
        return this.arrayBuilder.finalize(ret);
    } else {
        var ret = [];
        for(var i = 0; i < node.length; i++) {
            ret.push(this.decode(node[i], cache, asMapKey, false));
        }
        return ret;
    }
};

decoder.Decoder.prototype.parseString = function(string, cache, asMapKey) {
    if(string[0] === d.ESC) {
        var c = string[1];
        if(c === d.ESC || c === d.SUB || c === d.RES) {
            return string.substring(1);
        } else if (c === d.TAG) {
            return string;
        } else {
            var handler = this.handlers[c];
            if(handler == null) {
                return this.defaultHandler(c, string.substring(2));
            } else {
                return handler(string.substring(2));
            }
        }
    } else {
        return string;
    }
};

decoder.decoder = function(options) {
    return new decoder.Decoder(options);
};

});
<commit_msg>fix typo & bug<commit_after>// Copyright (c) Cognitect, Inc.
// All rights reserved.

goog.provide("com.cognitect.transit.impl.decoder");
goog.require("com.cognitect.transit.util");
goog.require("com.cognitect.transit.delimiters");
goog.require("com.cognitect.transit.caching");
goog.require("com.cognitect.transit.types");

goog.scope(function() {

var decoder = com.cognitect.transit.impl.decoder,
    util    = com.cognitect.transit.util,
    d       = com.cognitect.transit.delimiters,
    caching = com.cognitect.transit.caching,
    types   = com.cognitect.transit.types;

// =============================================================================
// Decoder

decoder.isGroundHandler = function(handler) {
    switch(handler) {
        case "_":
        case "s":
        case "?":
        case "i":
        case "d":
        case "b":
        case "'":
        case "array":
        case "map":
        return true;
    }
    return false;
};

/**
 * A transit decoder
 * @constructor
 */
decoder.Decoder = function(options) {
    this.options = options || {};
    this.handlers = {};
    for(var h in this.defaults.handlers) {
        this.handlers[h] = this.defaults.handlers[h];
    }
    for(var h in this.options["handlers"]) {
        if(decoder.isGroundHandler(h)) {
            throw new Error("Cannot override handler for ground types");
        }
        this.handlers[h] = this.options["handlers"][h];
    }
    this.preferStrings = this.options["preferStrings"] != null ? this.options["preferStrings"] : this.defaults.preferStrings;
    this.preferObjects = this.options["preferObjects"] != null ? this.options["preferObjects"] : this.defaults.preferObjects;
    this.defaultHandler = this.options["defaultHandler"] || this.defaults.defaultHandler;
    /* NOT PUBLIC */
    this.mapBuilder = this.options["mapBuilder"];
    this.arrayBuilder = this.options["arrayBuilder"];
};

decoder.Decoder.prototype.defaults = {
    handlers: {
        "_": function(v) { return types.nullValue(); },
        "?": function(v) { return types.boolValue(v); },
        "b": function(v) { return types.binary(v); },
        "i": function(v) { return types.intValue(v); },
        "n": function(v) { return types.bigInteger(v); },
        "d": function(v) { return types.floatValue(v); },
        "f": function(v) { return types.bigDecimalValue(v); },
        "c": function(v) { return types.charValue(v); },
        ":": function(v) { return types.keyword(v); },
        "$": function(v) { return types.symbol(v); },
        "r": function(v) { return types.uri(v); },

        // tagged
        "'": function(v) { return v; },
        "m": function(v) { return types.date(v); },
        "t": function(v) { return types.verboseDate(v); },
        "u": function(v) { return types.uuid(v); },
        "set": function(v) { return types.set(v); },
        "list": function(v) { return types.list(v); },
        "ints": function(v) { return types.ints(v); },
        "longs": function(v) { return types.longs(v); },
        "floats": function(v) { return types.floats(v); },
        "doubles": function(v) { return types.doubles(v); },
        "bools": function(v) { return types.bools(v); },
        "cmap": function(v) { return types.map(v, false); }
    },
    defaultHandler: function(c, val) {
        return types.taggedValue(c, val);
    },
    preferStrings: true,
    preferObjects: false
};

decoder.Decoder.prototype.decode = function(node, cache, asMapKey, tagValue) {
    if(node == null) return null;

    var t = typeof node;

    switch(t) {
    case "string":
        return this.decodeString(node, cache, asMapKey, tagValue);
        break;
    case "object":
        if(util.isArray(node)) {
            if(node[0] === "^ ") {
                return this.decodeArrayHash(node, cache, asMapKey, tagValue);
            } else {
                return this.decodeArray(node, cache, false, tagValue);
            }
        } else {
            return this.decodeHash(node, cache, asMapKey, tagValue);
        }
        break;
    }

    return node;
};
decoder.Decoder.prototype["decode"] = decoder.Decoder.prototype.decode;

decoder.Decoder.prototype.decodeString = function(string, cache, asMapKey, tagValue) {
    if(caching.isCacheable(string, asMapKey)) {
        var val = this.parseString(string, cache, false);
        if(cache) {
            cache.write(val, asMapKey);
        }
        return val;
    } else if(caching.isCacheCode(string)) {
        return cache.read(string, asMapKey);
    } else {
        return this.parseString(string, cache, asMapKey);
    }
};

decoder.Decoder.prototype.isStringKey = function(node, cache) {
    if(typeof node !== "string") {
        return false;
    } else {
        var c0 = node[0],
            c1 = node[1];
        if(c0 === d.ESC) {
            if(this.handlers[c1] != null) {
                return false;
            } else {
                return (c1 === d.ESC || c1 === d.SUB || c1 === d.RES);
            }
        } else if(c0 === d.SUB && ((typeof cache.read(node)) !== "string"))  {
            return false;
        } else {
            return true;
        }
    }
};

decoder.Decoder.prototype.decodeHash = function(hash, cache, asMapKey, tagValue) {
    var ks     = util.objectKeys(hash),
        key    = ks[0],
        tagKey = ks.length == 1 ? this.decode(key, cache, false, false) : null;

    if((tagKey != null) &&
       (tagKey[0] === d.ESC) &&
       (tagKey[1] === d.TAG)) {
        var val     = hash[key],
            handler = this.handlers[tagKey.substring(2)];
        if(handler != null) {
            return handler(this.decode(val, cache, false, true));
        } else {
            return types.taggedValue(tagKey.substring(2), this.decode(val, cache, false, false));
        }
    } else if(this.mapBuilder) {
        if((ks.length < (types.SMALL_ARRAY_MAP_THRESHOLD*2)) && this.mapBuilder.fromArray) {
            var nodep = [];
            for(var i = 0; i < ks.length; i++) {
                var strKey = ks[i];
                nodep.push(this.decode(strKey, cache, true, false));
                nodep.push(this.decode(hash[strKey], cache, false, false));
            }
            return this.mapBuilder.fromArray(nodep);
        } else {
            var ret = this.mapBuilder.init();
            for(var i = 0; i < ks.length; i++) {
                var strKey = ks[i];
                ret = this.mapBuilder.add(ret, this.decode(strKey, cache, true, false),
                                               this.decode(hash[strKey], cache, false, false));
            }
            return this.mapBuilder.finalize(ret);
        }
    } else {
        var stringKeys = true,
            nodep      = [];

        for(var i = 0; i < ks.length; i++) {
            var strKey = ks[i];
            if(this.preferObjects) {
                stringKeys = stringKeys && this.isStringKey(strKey, cache);
            }
            nodep.push(this.decode(strKey, cache, true, false));
            nodep.push(this.decode(hash[strKey], cache, false, false));
        }

        if(this.preferObjects && stringKeys) {
            var ret = {};
            for(var j = 0; j < nodep.length; j+=2) {
                ret[nodep[j]] = nodep[j+1];
            }
            return ret;
        } else {
            return types.map(nodep, false);
        }
    }
};

decoder.Decoder.prototype.decodeArrayHash = function(node, cache, asMapKey, tagValue) {
    if(this.mapBuilder) {
        if((node.length < ((types.SMALL_ARRAY_MAP_THRESHOLD*2)+1)) && this.mapBuilder.fromArray) {
            var nodep = [];
            for(var i = 1; i < node.length; i+=2) {
                nodep.push(this.decode(node[i], cache, true, false));
                nodep.push(this.decode(node[i+1], cache, false, false));
            }
            return this.mapBuilder.fromArray(nodep);
        } else {
            var ret = this.mapBuilder.init();
            for(var i = 1; i < node.length; i+=2) {
                ret = this.mapBuilder.add(ret, this.decode(node[i], cache, true, false),
                                               this.decode(node[i+1], cache, false, false))
            }
            return this.mapBuilder.finalize(ret);
        }
    } else {
        var stringKeys = true,
            nodep      = [];

        // collect keys
        for(var i = 1; i < node.length; i +=2) {
            if(this.preferObjects) {
                stringKeys = stringKeys && this.isStringKey(node[i], cache);
            }
            nodep.push(this.decode(node[i], cache, true, false));
            nodep.push(this.decode(node[i+1], cache, false, false));
        }

        if(this.preferObjects && stringKeys) {
            var ret = {};
            for(var j = 0; j < nodep.length; j+=2) {
                ret[nodep[j]] = nodep[j+1];
            }
            return ret;
        } else {
            return types.map(nodep, false);
        }
    }
};

decoder.Decoder.prototype.decodeArray = function(node, cache, asMapKey, tagValue) {
    if(tagValue) {
        var ret = [];
        for(var i = 0; i < node.length; i++) {
            ret.push(this.decode(node[i], cache, asMapKey, false));
        }
        return ret;
    } else if(this.arrayBuilder) {
        var ret = this.arrayBuilder.init();
        for(var i = 0; i < node.length; i++) {
            ret = this.arrayBuilder.add(ret, this.decode(node[i], cache, asMapKey, false));
        }
        return this.arrayBuilder.finalize(ret);
    } else {
        var ret = [];
        for(var i = 0; i < node.length; i++) {
            ret.push(this.decode(node[i], cache, asMapKey, false));
        }
        return ret;
    }
};

decoder.Decoder.prototype.parseString = function(string, cache, asMapKey) {
    if(string[0] === d.ESC) {
        var c = string[1];
        if(c === d.ESC || c === d.SUB || c === d.RES) {
            return string.substring(1);
        } else if (c === d.TAG) {
            return string;
        } else {
            var handler = this.handlers[c];
            if(handler == null) {
                return this.defaultHandler(c, string.substring(2));
            } else {
                return handler(string.substring(2));
            }
        }
    } else {
        return string;
    }
};

decoder.decoder = function(options) {
    return new decoder.Decoder(options);
};

});
<|endoftext|>


<commit_before>import {inject} from 'aurelia-framework';
import {App} from '../app';
import {json} from 'aurelia-fetch-client';
@inject(App)
export class Volunteer {
  constructor(app){
    this.app = app;
    this.events = [];
    this.signup = {};
    this.selectedFilter = ['future only'];
    this.doubleCheckSignups = false;
    this.canSignup = true;
    this.showPast = false;
    //this.showtable = false;
  }

  siteLocations = [];
  causes = [];
  filterby = ['keyword', 'zipcode', 'cause', 'future only'];
  // selectedFilter = [];
  keyword = false;
  siteLocation = false;
  causeFilter = false;
  filters = [
    {value: '', keys: ['voName', 'voDescription', 'voCharityName', 'voContactName', 'voStreet', 'voCity', 'voState']},
    {value: '', keys: ['voZipCode']},
    {value: '', keys: ['voCharityTypes']}
  ];

  async activate() {
    this.uid = this.app.auth.getTokenPayload().sub;
    this.user = await this.app.appState.getUser(this.uid);
    this.app.dashboardTitle = this.user.userType;
    this.app.role = this.user.userType;
    if (this.user.userDetails === 'newUser'){
      this.app.router.navigate('dashboard/user-account');
    } else {
      let res2 = await this.app.httpClient.fetch('/signup/getall');
      this.signups = await res2.json();
      await this.fetchAllEvents();
      this.displayEvents();
    }
  }

  async displayEvents(){
    if (this.events.length > 0){
      await this.checkSignups();
      this.fixZipcodes();
      this.fixDates();
      this.populateSites();
      this.populateCauses();
      await this.checkScheduled();
      if (this.selectedFilter.includes('future only')) {
        this.markPast();
      }
    }
  }

  async fetchAllEvents(){
    const res = await this.app.httpClient.fetch('/volopp/getall');
    this.events = await res.json();
  }

  async checkScheduled(){
    let total = 0;
    let signupUserIds = [];
    for (let i = 0; i < this.events.length; i++){
      for (let e = 0; e < this.signups.length; e++){
        if (this.events[i]._id === this.signups[e].voloppId){
          total = total + this.signups[e].numPeople;
          signupUserIds.push(this.signups[e].userId);
        }
      }
      this.events[i].voNumPeopleScheduled = total;
      this.events[i].voSignupUserIds = signupUserIds;
      if (this.events[i].voNumPeopleScheduled - this.events[i].voNumPeopleNeeded >= 0 && !this.events[i].scheduled){
        this.events[i].full = true;
        if (this.doubleCheckSignups){
          alert('someone else signed up for the last spot to volunteer at this event');
          this.doubleCheckSignups = false;
          return this.canSignup = false;
        }
      }
      if (this.events[i].voStatus === 'cancel' && !this.events[i].scheduled){
        this.events[i].full = true;
      }
      total = 0;
      signupUserIds = [];
    }
  }

  fixZipcodes(){
    for (let i = 0; i < this.events.length; i++){
      if (this.events[i].voZipCode === undefined || this.events[i].voZipCode === '' || this.events[i].voZipCode === null){
        this.events[i].voZipCode = '00000';
      }
    }
  }

  async checkSignups(){
    const resp = await this.app.httpClient.fetch('/signup/' + this.uid);
    this.userSignups = await resp.json();
    for (let next of this.userSignups){
      let nextEventId = next.voloppId;
      for (let i = 0; i < this.events.length; i++){
        if (this.events[i]._id === nextEventId){
          this.events[i].scheduled = true;
        }
      }
    }
  }

  filterPicked(){
    let arrayLength = this.selectedFilter.length;
    this.keyword = false;
    this.siteLocation = false;
    if (arrayLength === 0){
      this.filters[0].value = '';
      this.filters[1].value = '';
      this.filters[2].value = '';
      this.causeFilter = false;
      this.siteFilter = false;
      this.keyword = false;
      this.showPast = true;
      return;
    }
    if (this.selectedFilter.includes('keyword')) {
      this.keyword = true;
    } else {
      console.log('you unchecked the keyword filter');
      this.filters[0].value = '';
      this.keyword = false;
    }
    if (this.selectedFilter.includes('zipcode')) {
      this.siteLocation = true;
    } else {
      this.filters[1].value = '';
      this.siteLocation = false;
    }
    if (this.selectedFilter.includes('cause')) {
      this.causeFilter = true;
    } else {
      this.filters[2].value = '';
      this.causeFilter = false;
    }
    if (this.selectedFilter.includes('future only')) {
      console.log('you selected the starting date filter');
      this.markPast();
      this.showPast = false;
    } else {
      this.showPast = true;
    }
  }
  formatDate(today){
    console.log(today);
    let mm = today.getMonth() + 1; // getMonth() is zero-based
    let dd = today.getDate();
    today = [today.getFullYear(),
      (mm > 9 ? '' : '0') + mm,
      (dd > 9 ? '' : '0') + dd].join('');
    return today;
  }

  markPast() {
    let testDate;
    let today = new Date();
    today = this.formatDate(today);
    for (let i = 0; i < this.events.length; i++){
      if (this.events[i].voStartDate === undefined || this.events[i].voStartDate === null || this.events[i].voStartDate === ''){
        this.events[i].voStartDate = today;
      }
      testDate = this.events[i].voStartDate.replace('-', '');
      testDate = testDate.replace('-', '');
      if (testDate < today){
        this.events[i].past = true;
      } else {
        this.events[i].past = false;
      }
    }
  }

  populateSites(){
    this.siteLocations.push('');
    for (let next of this.events){
      let nextSite = next.voZipCode;
      if (this.siteLocations.indexOf(nextSite) === -1){
        this.siteLocations.push(nextSite);
      }
    }
  }

  populateCauses(){
    this.causes.push('');
    for (let next of this.events){
      let nextCharityType = next.voCharityTypes;
      for (let nextType of nextCharityType){
        if (this.causes.indexOf(nextType) === -1){
          this.causes.push(nextType);
        }
      }
    }
  }

  fixDates(){
    for (let i = 0; i < this.events.length; i++){
      let startDate = this.events[i].voStartDate;
      let endDate = this.events[i].voEndDate;
      if (startDate !== null && startDate !== undefined){
        if (startDate.indexOf('T') !== -1){
          this.events[i].voStartDate = startDate.substr(0, startDate.indexOf('T'));
        }
      }
      if (endDate !== null && endDate !== undefined){
        if (endDate.indexOf('T') !== -1){
          this.events[i].voEndDate = endDate.substr(0, endDate.indexOf('T'));
        }
      }
    }
  }

  buildVolunteerPTag(objectSelector, objectSelectorOther, elementId){
    let returnHtml = '';
    for (let i = 0; i < this.user[objectSelector].length; i++) {
      if (this.user[objectSelector][i] !== ''){
        if (this.user[objectSelector][i] !== 'other'){
          returnHtml = returnHtml + '
' + this.user[objectSelector][i] + '
';
        } else {
          returnHtml = returnHtml + '
' + this.user[objectSelectorOther] + '
';
        }
      }
    }
    if (returnHtml === ''){
      returnHtml = '
not specified
';
    }
    document.getElementById(elementId).innerHTML = returnHtml;
  }

  async signupEvent(thisevent){
    //doublecheck that someone else has not already signedup to hit the max volunteers needed
    this.doubleCheckSignups = true;
    await this.checkScheduled();
    if (!this.canSignup){
      return;
    }
    this.signup.voloppId = thisevent._id;
    this.signup.userId = this.uid;
    this.signup.numPeople = 1;
    this.signup.groupName = '';
    await this.app.httpClient.fetch('/signup/create', {
      method: 'post',
      body: json(this.signup)
    })
      .then((data) => {
        console.log(data);
        //this.showtable = false;
        this.activate();
      });
  }

  async cancelSignup(eId){
    await fetch;
    this.app.httpClient.fetch('/signup/' + eId, {
      method: 'delete'
    })
      .then((data) => {
        console.log('no longer volunteering for that event');
        //this.showtable = false;
        this.activate();
      });
  }

  attached(){
    this.buildVolunteerPTag('volCauses', 'volCauseOther', 'causes');
    this.buildVolunteerPTag('volTalents', 'volTalentOther', 'talents');
    this.buildVolunteerPTag('volWorkPrefs', 'volWorkOther', 'works');
  }
}
<commit_msg>refactoring for volunteer.js<commit_after>import {inject} from 'aurelia-framework';
import {App} from '../app';
import {json} from 'aurelia-fetch-client';
@inject(App)
export class Volunteer {
  constructor(app){
    this.app = app;
    this.events = [];
    this.signup = {};
    this.selectedFilter = ['future only'];
    this.doubleCheckSignups = false;
    this.canSignup = true;
    this.showPast = false;
    //this.showtable = false;
  }

  siteLocations = [];
  causes = [];
  filterby = ['keyword', 'zipcode', 'cause', 'future only'];
  // selectedFilter = [];
  keyword = false;
  siteLocation = false;
  causeFilter = false;
  filters = [
    {value: '', keys: ['voName', 'voDescription', 'voCharityName', 'voContactName', 'voStreet', 'voCity', 'voState']},
    {value: '', keys: ['voZipCode']},
    {value: '', keys: ['voCharityTypes']}
  ];

  async activate() {
    this.uid = this.app.auth.getTokenPayload().sub;
    this.user = await this.app.appState.getUser(this.uid);
    this.app.dashboardTitle = this.user.userType;
    this.app.role = this.user.userType;
    if (this.user.userDetails === 'newUser'){
      this.app.router.navigate('dashboard/user-account');
    } else {
      let res2 = await this.app.httpClient.fetch('/signup/getall');
      this.signups = await res2.json();
      await this.fetchAllEvents();
      this.displayEvents();
    }
  }

  async displayEvents(){
    if (this.events.length > 0){
      await this.checkSignups();
      this.fixZipcodes();
      this.fixDates('voStartDate');
      this.fixDates('voEndDate');
      this.populateSites();
      this.populateCauses();
      await this.checkScheduled();
      if (this.selectedFilter.includes('future only')) {
        this.markPast();
      }
    }
  }

  async fetchAllEvents(){
    const res = await this.app.httpClient.fetch('/volopp/getall');
    this.events = await res.json();
  }

  async checkScheduled(){
    let total = 0;
    let signupUserIds = [];
    for (let i = 0; i < this.events.length; i++){
      for (let e = 0; e < this.signups.length; e++){
        if (this.events[i]._id === this.signups[e].voloppId){
          total = total + this.signups[e].numPeople;
          signupUserIds.push(this.signups[e].userId);
        }
      }
      this.events[i].voNumPeopleScheduled = total;
      this.events[i].voSignupUserIds = signupUserIds;
      if (this.events[i].voNumPeopleScheduled - this.events[i].voNumPeopleNeeded >= 0 && !this.events[i].scheduled){
        this.events[i].full = true;
        if (this.doubleCheckSignups){
          alert('someone else signed up for the last spot to volunteer at this event');
          this.doubleCheckSignups = false;
          return this.canSignup = false;
        }
      }
      if (this.events[i].voStatus === 'cancel' && !this.events[i].scheduled){
        this.events[i].full = true;
      }
      total = 0;
      signupUserIds = [];
    }
  }

  fixZipcodes(){
    for (let i = 0; i < this.events.length; i++){
      if (this.events[i].voZipCode === undefined || this.events[i].voZipCode === '' || this.events[i].voZipCode === null){
        this.events[i].voZipCode = '00000';
      }
    }
  }

  async checkSignups(){
    const resp = await this.app.httpClient.fetch('/signup/' + this.uid);
    this.userSignups = await resp.json();
    for (let next of this.userSignups){
      let nextEventId = next.voloppId;
      for (let i = 0; i < this.events.length; i++){
        if (this.events[i]._id === nextEventId){
          this.events[i].scheduled = true;
        }
      }
    }
  }

  filterPicked(){
    let arrayLength = this.selectedFilter.length;
    this.keyword = false;
    this.siteLocation = false;
    if (arrayLength === 0){
      this.filters[0].value = '';
      this.filters[1].value = '';
      this.filters[2].value = '';
      this.causeFilter = false;
      this.siteFilter = false;
      this.keyword = false;
      this.showPast = true;
      return;
    }
    if (this.selectedFilter.includes('keyword')) {
      this.keyword = true;
    } else {
      console.log('you unchecked the keyword filter');
      this.filters[0].value = '';
      this.keyword = false;
    }
    if (this.selectedFilter.includes('zipcode')) {
      this.siteLocation = true;
    } else {
      this.filters[1].value = '';
      this.siteLocation = false;
    }
    if (this.selectedFilter.includes('cause')) {
      this.causeFilter = true;
    } else {
      this.filters[2].value = '';
      this.causeFilter = false;
    }
    if (this.selectedFilter.includes('future only')) {
      console.log('you selected the starting date filter');
      this.markPast();
      this.showPast = false;
    } else {
      this.showPast = true;
    }
  }
  formatDate(today){
    console.log(today);
    let mm = today.getMonth() + 1; // getMonth() is zero-based
    let dd = today.getDate();
    today = [today.getFullYear(),
      (mm > 9 ? '' : '0') + mm,
      (dd > 9 ? '' : '0') + dd].join('');
    return today;
  }

  markPast() {
    let testDate;
    let today = new Date();
    today = this.formatDate(today);
    for (let i = 0; i < this.events.length; i++){
      if (this.events[i].voStartDate === undefined || this.events[i].voStartDate === null || this.events[i].voStartDate === ''){
        this.events[i].voStartDate = today;
      }
      testDate = this.events[i].voStartDate.replace('-', '');
      testDate = testDate.replace('-', '');
      if (testDate < today){
        this.events[i].past = true;
      } else {
        this.events[i].past = false;
      }
    }
  }

  populateSites(){
    this.siteLocations.push('');
    for (let next of this.events){
      let nextSite = next.voZipCode;
      if (this.siteLocations.indexOf(nextSite) === -1){
        this.siteLocations.push(nextSite);
      }
    }
  }

  populateCauses(){
    this.causes.push('');
    for (let next of this.events){
      let nextCharityType = next.voCharityTypes;
      for (let nextType of nextCharityType){
        if (this.causes.indexOf(nextType) === -1){
          this.causes.push(nextType);
        }
      }
    }
  }

  fixDates(key){
    for (let i = 0; i < this.events.length; i++){
      let fixDate = this.events[i][key];
      //let endDate = this.events[i].voEndDate;
      if (fixDate !== null && fixDate !== undefined){
        if (fixDate.indexOf('T') !== -1){
          this.events[i][key] = fixDate.substr(0, fixDate.indexOf('T'));
        }
      }
      // if (endDate !== null && endDate !== undefined){
      //   if (endDate.indexOf('T') !== -1){
      //     this.events[i].voEndDate = endDate.substr(0, endDate.indexOf('T'));
      //   }
      // }
    }
  }

  buildVolunteerPTag(objectSelector, objectSelectorOther, elementId){
    let returnHtml = '';
    for (let i = 0; i < this.user[objectSelector].length; i++) {
      if (this.user[objectSelector][i] !== ''){
        if (this.user[objectSelector][i] !== 'other'){
          returnHtml = returnHtml + '
' + this.user[objectSelector][i] + '
';
        } else {
          returnHtml = returnHtml + '
' + this.user[objectSelectorOther] + '
';
        }
      }
    }
    if (returnHtml === ''){
      returnHtml = '
not specified
';
    }
    document.getElementById(elementId).innerHTML = returnHtml;
  }

  async signupEvent(thisevent){
    //doublecheck that someone else has not already signedup to hit the max volunteers needed
    this.doubleCheckSignups = true;
    await this.checkScheduled();
    if (!this.canSignup){
      return;
    }
    this.signup.voloppId = thisevent._id;
    this.signup.userId = this.uid;
    this.signup.numPeople = 1;
    this.signup.groupName = '';
    await this.app.httpClient.fetch('/signup/create', {
      method: 'post',
      body: json(this.signup)
    })
      .then((data) => {
        console.log(data);
        //this.showtable = false;
        this.activate();
      });
  }

  async cancelSignup(eId){
    await fetch;
    this.app.httpClient.fetch('/signup/' + eId, {
      method: 'delete'
    })
      .then((data) => {
        console.log('no longer volunteering for that event');
        //this.showtable = false;
        this.activate();
      });
  }

  attached(){
    this.buildVolunteerPTag('volCauses', 'volCauseOther', 'causes');
    this.buildVolunteerPTag('volTalents', 'volTalentOther', 'talents');
    this.buildVolunteerPTag('volWorkPrefs', 'volWorkOther', 'works');
  }
}
<|endoftext|>


<commit_before>import { createSelector } from 'reselect'

// ------------------------------------
// Initial State
// ------------------------------------
const initialState = {
  filterPulldown: false,
  filter: { key: 'ALL_ACTIVITY', name: 'All Activity' },
  filters: [
    { key: 'ALL_ACTIVITY', name: 'All' },
    { key: 'SENT_ACTIVITY', name: 'Sent' },
    { key: 'REQUESTED_ACTIVITY', name: 'Requested' },
    { key: 'PENDING_ACTIVITY', name: 'Pending' },
    { key: 'FUNDED_ACTIVITY', name: 'Funding Transactions' }
  ],
  modal: {
    modalType: null,
    modalProps: {}
  },
  searchText: ''
}

// ------------------------------------
// Constants
// ------------------------------------
export const SHOW_ACTIVITY_MODAL = 'SHOW_ACTIVITY_MODAL'
export const HIDE_ACTIVITY_MODAL = 'HIDE_ACTIVITY_MODAL'

export const CHANGE_FILTER = 'CHANGE_FILTER'

export const TOGGLE_PULLDOWN = 'TOGGLE_PULLDOWN'

export const UPDATE_SEARCH_TEXT = 'UPDATE_SEARCH_TEXT'

// ------------------------------------
// Actions
// ------------------------------------
export function showActivityModal(modalType, modalProps) {
  return {
    type: SHOW_ACTIVITY_MODAL,
    modalType,
    modalProps
  }
}

export function hideActivityModal() {
  return {
    type: HIDE_ACTIVITY_MODAL
  }
}

export function changeFilter(filter) {
  return {
    type: CHANGE_FILTER,
    filter
  }
}

export function toggleFilterPulldown() {
  return {
    type: TOGGLE_PULLDOWN
  }
}

export function updateSearchText(searchText) {
  return {
    type: UPDATE_SEARCH_TEXT,
    searchText
  }
}

// ------------------------------------
// Action Handlers
// ------------------------------------
const ACTION_HANDLERS = {
  [SHOW_ACTIVITY_MODAL]: (state, { modalType, modalProps }) => ({ ...state, modal: { modalType, modalProps } }),
  [HIDE_ACTIVITY_MODAL]: state => ({ ...state, modal: { modalType: null, modalProps: {} } }),
  [CHANGE_FILTER]: (state, { filter }) => ({ ...state, filter, filterPulldown: false }),
  [TOGGLE_PULLDOWN]: state => ({ ...state, filterPulldown: !state.filterPulldown }),

  [UPDATE_SEARCH_TEXT]: (state, { searchText }) => ({ ...state, searchText })
}

// ------------------------------------
// Selectors
// ------------------------------------
const activitySelectors = {}
const filtersSelector = state => state.activity.filters
const filterSelector = state => state.activity.filter
const searchSelector = state => state.activity.searchText
const paymentsSelector = state => state.payment.payments
const invoicesSelector = state => state.invoice.invoices
const transactionsSelector = state => state.transaction.transactions
const channelsSelector = state => state.channels.channels

const allActivity = createSelector(
  searchSelector,
  paymentsSelector,
  invoicesSelector,
  transactionsSelector,
  (searchText, payments, invoices, transactions) => {
    const searchedArr = [...payments, ...invoices, ...transactions].filter((tx) => {
      if ((tx.tx_hash && tx.tx_hash.includes(searchText)) ||
          (tx.payment_hash && tx.payment_hash.includes(searchText)) ||
          (tx.payment_request && tx.payment_request.includes(searchText))) {
        return true
      }

      return false
    })

    return searchedArr.sort((a, b) => {
      const aTimestamp = Object.prototype.hasOwnProperty.call(a, 'time_stamp') ? a.time_stamp : a.creation_date
      const bTimestamp = Object.prototype.hasOwnProperty.call(b, 'time_stamp') ? b.time_stamp : b.creation_date

      return bTimestamp - aTimestamp
    })
  }
)

const invoiceActivity = createSelector(
  invoicesSelector,
  invoices => invoices
)

const sentActivity = createSelector(
  transactionsSelector,
  paymentsSelector,
  (transactions, payments) => {
    const sentTransactions = transactions.filter(transaction => transaction.amount < 0)
    return [...sentTransactions, ...payments].sort((a, b) => {
      const aTimestamp = Object.prototype.hasOwnProperty.call(a, 'time_stamp') ? a.time_stamp : a.creation_date
      const bTimestamp = Object.prototype.hasOwnProperty.call(b, 'time_stamp') ? b.time_stamp : b.creation_date

      return bTimestamp - aTimestamp
    })
  }
)

const pendingActivity = createSelector(
  invoicesSelector,
  invoices => invoices.filter(invoice => !invoice.settled)
)

const fundedActivity = createSelector(
  transactionsSelector,
  channelsSelector,
  (transactions, channels) => {
    const fundingTxIds = channels.map(channel => channel.channel_point.split(':')[0])

    return transactions.filter(transaction => fundingTxIds.includes(transaction.tx_hash))
  }
)

const FILTERS = {
  ALL_ACTIVITY: allActivity,
  SENT_ACTIVITY: sentActivity,
  REQUESTED_ACTIVITY: invoiceActivity,
  PENDING_ACTIVITY: pendingActivity,
  FUNDED_ACTIVITY: fundedActivity
}

activitySelectors.currentActivity = createSelector(
  filterSelector,
  filter => FILTERS[filter.key]
)

activitySelectors.nonActiveFilters = createSelector(
  filtersSelector,
  filterSelector,
  (filters, filter) => filters.filter(f => f.key !== filter.key)
)

export { activitySelectors }

// ------------------------------------
// Reducer
// ------------------------------------
export default function activityReducer(state = initialState, action) {
  const handler = ACTION_HANDLERS[action.type]

  return handler ? handler(state, action) : state
}
<commit_msg>fix(funding-txs-odering)<commit_after>import { createSelector } from 'reselect'

// ------------------------------------
// Initial State
// ------------------------------------
const initialState = {
  filterPulldown: false,
  filter: { key: 'ALL_ACTIVITY', name: 'All Activity' },
  filters: [
    { key: 'ALL_ACTIVITY', name: 'All' },
    { key: 'SENT_ACTIVITY', name: 'Sent' },
    { key: 'REQUESTED_ACTIVITY', name: 'Requested' },
    { key: 'PENDING_ACTIVITY', name: 'Pending' },
    { key: 'FUNDED_ACTIVITY', name: 'Funding Transactions' }
  ],
  modal: {
    modalType: null,
    modalProps: {}
  },
  searchText: ''
}

// ------------------------------------
// Constants
// ------------------------------------
export const SHOW_ACTIVITY_MODAL = 'SHOW_ACTIVITY_MODAL'
export const HIDE_ACTIVITY_MODAL = 'HIDE_ACTIVITY_MODAL'

export const CHANGE_FILTER = 'CHANGE_FILTER'

export const TOGGLE_PULLDOWN = 'TOGGLE_PULLDOWN'

export const UPDATE_SEARCH_TEXT = 'UPDATE_SEARCH_TEXT'

// ------------------------------------
// Actions
// ------------------------------------
export function showActivityModal(modalType, modalProps) {
  return {
    type: SHOW_ACTIVITY_MODAL,
    modalType,
    modalProps
  }
}

export function hideActivityModal() {
  return {
    type: HIDE_ACTIVITY_MODAL
  }
}

export function changeFilter(filter) {
  return {
    type: CHANGE_FILTER,
    filter
  }
}

export function toggleFilterPulldown() {
  return {
    type: TOGGLE_PULLDOWN
  }
}

export function updateSearchText(searchText) {
  return {
    type: UPDATE_SEARCH_TEXT,
    searchText
  }
}

// ------------------------------------
// Action Handlers
// ------------------------------------
const ACTION_HANDLERS = {
  [SHOW_ACTIVITY_MODAL]: (state, { modalType, modalProps }) => ({ ...state, modal: { modalType, modalProps } }),
  [HIDE_ACTIVITY_MODAL]: state => ({ ...state, modal: { modalType: null, modalProps: {} } }),
  [CHANGE_FILTER]: (state, { filter }) => ({ ...state, filter, filterPulldown: false }),
  [TOGGLE_PULLDOWN]: state => ({ ...state, filterPulldown: !state.filterPulldown }),

  [UPDATE_SEARCH_TEXT]: (state, { searchText }) => ({ ...state, searchText })
}

// ------------------------------------
// Selectors
// ------------------------------------
const activitySelectors = {}
const filtersSelector = state => state.activity.filters
const filterSelector = state => state.activity.filter
const searchSelector = state => state.activity.searchText
const paymentsSelector = state => state.payment.payments
const invoicesSelector = state => state.invoice.invoices
const transactionsSelector = state => state.transaction.transactions
const channelsSelector = state => state.channels.channels

const allActivity = createSelector(
  searchSelector,
  paymentsSelector,
  invoicesSelector,
  transactionsSelector,
  (searchText, payments, invoices, transactions) => {
    const searchedArr = [...payments, ...invoices, ...transactions].filter((tx) => {
      if ((tx.tx_hash && tx.tx_hash.includes(searchText)) ||
          (tx.payment_hash && tx.payment_hash.includes(searchText)) ||
          (tx.payment_request && tx.payment_request.includes(searchText))) {
        return true
      }

      return false
    })

    return searchedArr.sort((a, b) => {
      const aTimestamp = Object.prototype.hasOwnProperty.call(a, 'time_stamp') ? a.time_stamp : a.creation_date
      const bTimestamp = Object.prototype.hasOwnProperty.call(b, 'time_stamp') ? b.time_stamp : b.creation_date

      return bTimestamp - aTimestamp
    })
  }
)

const invoiceActivity = createSelector(
  invoicesSelector,
  invoices => invoices
)

const sentActivity = createSelector(
  transactionsSelector,
  paymentsSelector,
  (transactions, payments) => {
    const sentTransactions = transactions.filter(transaction => transaction.amount < 0)
    return [...sentTransactions, ...payments].sort((a, b) => {
      const aTimestamp = Object.prototype.hasOwnProperty.call(a, 'time_stamp') ? a.time_stamp : a.creation_date
      const bTimestamp = Object.prototype.hasOwnProperty.call(b, 'time_stamp') ? b.time_stamp : b.creation_date

      return bTimestamp - aTimestamp
    })
  }
)

const pendingActivity = createSelector(
  invoicesSelector,
  invoices => invoices.filter(invoice => !invoice.settled)
)

const fundedActivity = createSelector(
  transactionsSelector,
  channelsSelector,
  (transactions, channels) => {
    const fundingTxIds = channels.map(channel => channel.channel_point.split(':')[0])
    const fundingTxs = transactions.filter(transaction => fundingTxIds.includes(transaction.tx_hash))

    return fundingTxs.sort((a, b) => b.time_stamp - a.time_stamp)
  }
)

const FILTERS = {
  ALL_ACTIVITY: allActivity,
  SENT_ACTIVITY: sentActivity,
  REQUESTED_ACTIVITY: invoiceActivity,
  PENDING_ACTIVITY: pendingActivity,
  FUNDED_ACTIVITY: fundedActivity
}

activitySelectors.currentActivity = createSelector(
  filterSelector,
  filter => FILTERS[filter.key]
)

activitySelectors.nonActiveFilters = createSelector(
  filtersSelector,
  filterSelector,
  (filters, filter) => filters.filter(f => f.key !== filter.key)
)

export { activitySelectors }

// ------------------------------------
// Reducer
// ------------------------------------
export default function activityReducer(state = initialState, action) {
  const handler = ACTION_HANDLERS[action.type]

  return handler ? handler(state, action) : state
}
<|endoftext|>


<commit_before>/*
   Copyright 2011-2012 Lukas Vlcek

   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.
*/

/*
{
    cluster: {
        cluster_name: {
            connectionVerified: bool,
            intervals: {_all_active_intervals_},
            timeouts: {_all_active_timeouts_},
            storeSize: int,
            health: {},
            nodesStats: [
                timestamp_x: {
                    [nodeStats, nodeStats, ...]
                },
                timestamp_y: {[...]},
                timestamp_z: {[...]},
                ...
            ],
            nodesState: [
                {node_with_id},
                {node_with_id},
                ...
            ],
            nodeInfo: {}, //relevant to selected node
            clusterState: [
                clusterStateTimestamp: {},
                ...
            ],
            indicesStatus: [
                indicesStatusTimestamp: {},
                ...
            ]
        }
    }
}
*/

var Cluster = Backbone.Model.extend({
    defaults: {
        id: "not_set_yet",
        connectionVerified: false,
        health: undefined,
        nodesStats: undefined,
        nodesState: undefined,
        nodeInfo: undefined,
        clusterState: undefined,
        indicesStatus: undefined,
        storeSize: 60000, // 1min
        intervals: {},
        timeouts: {},
        dispatcher: undefined
    },
    // id: "cluster_name"
    // baseUrl: "complete URL for REST API including port number"
    // refreshInterval: _some_number_ [optional, defaults to 2000ms]
    // dispatcher: function [optional].
    initialize: function(attrs){
        var _model = this;
        var _conn = _model.get("connectionVerified");
        if (_conn == false) {
            // ensure default dispatcher (in case user explicitly provided "undefined" value instead of function)
            if (this.get("dispatcher") == undefined /*|| typeof this.get("dispatcher") != "function"*/) {
                console.log("using default dispatcher");
                var _dispatcher = _.clone(Backbone.Events);
                _dispatcher.on("onAjaxResponse", function(clusterName, restApiName, response) {
                    console.log("["+clusterName+"] ["+restApiName+"]", response)
                });
                this.set({dispatcher: _dispatcher});
            }
            var connection = {
                baseUrl: attrs.baseUrl,
                refreshInterval: attrs.refreshInterval || 2000
            };
            var hello = new Hello({},connection);
            hello.fetch({
                success: function(model, response){
                    var version = hello.get("version");
                    if (version && version.number) {
                        version = version.number;
                        var _vArray = version.split(".");
                        if (_vArray.length > 2 && _model.checkVersion(_vArray[0], _vArray[1], _vArray[2])) {
                            _model.versionVerified(version);
                            _model.initCluster(connection);
                        } else {
                            _model.yellAboutVersion(version);
                        }
                    } else {
                        _model.yellAboutVersion("n/a");
                    }
                },
                error: function(model, response) {
                    console.log("[Error] something wrong happened...", model, response);
                }
            });
        }
    },

    // When creating a new cluster, client has to provide both REST URL endpoint and cluster name.
    // The idea is that the cluster name is obtained by client upfront using cluster health API for example.
    validate: function(attrs){
        // this must be constructor call
        if (this.get("connectionVerified") == undefined) {
            if (!attrs.id || !attrs.baseUrl) {
                return "Both cluster name and URL must be provided.\n" +
                    "Example: { " +
                        "id: \"_cluster_name_\", " +
                        "baseUrl: \"_ES_REST_end_point_\" " +
                    "}";
            }
            if (attrs.dispatcher != undefined) {
                if (typeof attrs.dispatcher != "function") {
                    return "dispatcher must be a function.";
                }
            }
        }
    },

    // returns false or true depending on given version numbers
    checkVersion: function(major, minor, maintenance) {
        if ( (major == 1 && minor == 0) || (major == 0 && minor == 90 && maintenance >= 0)) {
            return true;
        }
        return false;
    },

    versionVerified: function(version) {
        console.log("Check ES node version: " + version + " [ok]");
    },

    yellAboutVersion: function(version) {
        var message =
            "*********************************\n" +
            "Bigdesk may not work correctly!\n" +
            "Found ES node version: " + version + "\n" +
            "Requires ES node version: >= 0.90.0 or 1.0.x\n" +
            "*********************************";
        console.log(message);
        if (alert) { alert(message); }
    },

    // connection.baseUrl
    // connection.refreshInterval
    initCluster: function(connection) {
        var _model = this;
        // connection has been already verified
        _model.set({connectionVerified: true});

        _model.set({        health: new ClusterHealth({}, connection) });
        _model.set({    nodesStats: new NodesStats([],    connection) });
        _model.set({    nodesState: new NodesState([],    connection) });
        _model.set({      nodeInfo: new NodeInfo({},      connection) });
        _model.set({  clusterState: new ClusterState([],  connection) });
        _model.set({ indicesStatus: new IndicesStatus([], connection) });

        this.startFetch(connection.refreshInterval);

    },

    clearTimeouts: function() {
        var _cluster = this;
        var timeouts = _cluster.get("timeouts");
        _.each(timeouts, function(num, key){
            _cluster.clearTimeout(key);
        });
    },

    clearTimeout: function(timeoutId) {
        var timeouts = this.get("timeouts");
        if (timeouts && timeouts[timeoutId]) {
            window.clearTimeout(timeouts[timeoutId]);
            delete timeouts[timeoutId];
            this.set({timeouts: timeouts});
        }
    },

    clearIntervals: function() {
        var _cluster = this;
        var intervals = this.get("intervals");
        _.each(intervals, function(num, key){
            _cluster.clearInterval(key);
        });
    },

    clearInterval: function(intervalId) {
//        console.log("stop interval " + intervalId);
        var intervals = this.get("intervals");
        if (intervals && intervals[intervalId]) {
            window.clearInterval(intervals[intervalId]);
            delete intervals[intervalId];
            this.set({intervals: intervals});
        }
    },

    startTimeout: function(timeoutId, functionCall, interval) {
        var _model = this;
        var timeouts = _model.get("timeouts");
        if (timeouts) {
            if (timeouts[timeoutId]) {
                console.log("[WARN] clearing and replacing existing timeout");
                _model.clearTimeout(timeoutId);
            }

            var timeoutFn = function() {
                functionCall();
                var t = window.setTimeout(timeoutFn, interval);
                timeouts[timeoutId] = t;
                _model.set({timeouts: timeouts});
            };

            timeoutFn();
        }
    },

    startInterval: function(intervalId, functionCall, interval) {
        var _model = this;
        var intervals = this.get("intervals");
        if (intervals) {
            if (intervals[intervalId]) {
                console.log("[WARN] clearing and replacing existing interval");
                _model.clearInterval(intervalId);
            }
            var i = window.setInterval(functionCall, interval);
            intervals[intervalId] = i;
            this.set({intervals: intervals});
            // fire callback right now
            functionCall();
        }
    },

    // start fetching bigdesk models and collections
    // params:
    //  refreshInterval
    //  baseUrl [optional] can override baseUrl that was passed into Cluster constructor
    startFetch: function(refreshInterval, baseUrl) {
        var _cluster = this;
        var _dispatcher = _cluster.get("dispatcher");
        var _clusterName = _cluster.get("id");

        if (baseUrl && typeof baseUrl == "string") {
            _cluster.get("health").setBaseUrl(baseUrl);
            _cluster.get("nodesStats").setBaseUrl(baseUrl);
            _cluster.get("nodesState").setBaseUrl(baseUrl);
            _cluster.get("nodeInfo").setBaseUrl(baseUrl);
            _cluster.get("clusterState").setBaseUrl(baseUrl);
            _cluster.get("indicesStatus").setBaseUrl(baseUrl);
        }

        var healthRefreshFunction = function(){
            _cluster.get("health").fetch({
                success: function(model, response){
                    _dispatcher.trigger("onAjaxResponse", _clusterName, "cluster > Health", response);
                }
            });
        };

        var nodesStatsRefreshFunction = function(){
            _cluster.get("nodesStats").fetch({
                add:        true,
                storeSize:  _cluster.get("storeSize"),
                now:        new Date().getTime(),
                silent:     true,
                success:    function(model, response){
                    _dispatcher.trigger("onAjaxResponse", _clusterName, "cluster > NodesStats", response);
                }
            });
        };

        var nodesStateRefreshFunction = function(){
            _cluster.get("nodesState").fetch({
                add:        true,
                silent:     true,
                success:    function(model, response){
                    _dispatcher.trigger("onAjaxResponse", _clusterName, "cluster > NodesState", response);
                }
            });
        };

        var clusterStateRefreshFunction = function(){
            _cluster.get("clusterState").fetch({
                add:        true,
                storeSize:  _cluster.get("storeSize"),
                now:        new Date().getTime(),
                silent:     true,
                success:    function(model, response){
                    _dispatcher.trigger("onAjaxResponse", _clusterName, "cluster > State", response);
                    _dispatcher.trigger("newClusterState");
                }
            });
        };

        var indicesStatusRefreshFunction = function(){
            _cluster.get("indicesStatus").fetch({
                add:        true,
                storeSize:  _cluster.get("storeSize"),
                now:        new Date().getTime(),
                silent:     true,
                success:    function(model, response){
                    _dispatcher.trigger("onAjaxResponse", _clusterName, "indices > Status", response);
                    _dispatcher.trigger("newIndicesStatus");
                }
            });
        };

        this.clearInterval("nodesStateInterval");
        this.clearInterval("nodesStatsInterval");
        this.clearInterval("healthInterval");
        this.clearTimeout("clusterStateInterval");
        this.clearTimeout("indicesStatusInterval");

        this.startInterval("nodesStateInterval",   nodesStateRefreshFunction,    refreshInterval);
        this.startInterval("nodesStatsInterval",   nodesStatsRefreshFunction,    refreshInterval);
        this.startInterval("healthInterval",       healthRefreshFunction,        refreshInterval);
        this.startTimeout("clusterStateInterval",  clusterStateRefreshFunction,  refreshInterval);
        this.startTimeout("indicesStatusInterval", indicesStatusRefreshFunction, refreshInterval);
    },

    // set storeSize value of the cluster
    setStoreSize: function(storeSize) {
        var _cluster = this;
        _cluster.set({storeSize: storeSize});
    },

    // return master node id if available, otherwise return empty string
    getMasterNodeId: function() {
        var _cluster = this;
        return  _cluster.get("nodesState").getMasterNodeId();
    }
});

var ClusterCollection = Backbone.Collection.extend({
    model: Cluster
});

var BigdeskStore = Backbone.Model.extend({

    defaults: {
        cluster: new ClusterCollection()
    },

    // Returns an instance of a Cluster model with given name (id)
    // or undefined if no instance if found.
    getCluster: function(clusterName) {
        return this.get("cluster").get(clusterName);
    },

    // Add a new cluster into store. Parameter is an instance of a Cluster model.
    // Throws error if there already is a cluster with the same id.
    addCluster: function(clusterModel) {
        var _c = this.get("cluster");
        if (_c.get(clusterModel.get("id")) == undefined) {
            _c.add(clusterModel)
        } else {
            throw "Cluster already exists.";
        };
    }
});
<commit_msg>removed ES version check on initialization<commit_after>/*
   Copyright 2011-2012 Lukas Vlcek

   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.
*/

/*
{
    cluster: {
        cluster_name: {
            connectionVerified: bool,
            intervals: {_all_active_intervals_},
            timeouts: {_all_active_timeouts_},
            storeSize: int,
            health: {},
            nodesStats: [
                timestamp_x: {
                    [nodeStats, nodeStats, ...]
                },
                timestamp_y: {[...]},
                timestamp_z: {[...]},
                ...
            ],
            nodesState: [
                {node_with_id},
                {node_with_id},
                ...
            ],
            nodeInfo: {}, //relevant to selected node
            clusterState: [
                clusterStateTimestamp: {},
                ...
            ],
            indicesStatus: [
                indicesStatusTimestamp: {},
                ...
            ]
        }
    }
}
*/

var Cluster = Backbone.Model.extend({
    defaults: {
        id: "not_set_yet",
        connectionVerified: false,
        health: undefined,
        nodesStats: undefined,
        nodesState: undefined,
        nodeInfo: undefined,
        clusterState: undefined,
        indicesStatus: undefined,
        storeSize: 60000, // 1min
        intervals: {},
        timeouts: {},
        dispatcher: undefined
    },
    // id: "cluster_name"
    // baseUrl: "complete URL for REST API including port number"
    // refreshInterval: _some_number_ [optional, defaults to 2000ms]
    // dispatcher: function [optional].
    initialize: function(attrs){
        var _model = this;
        var _conn = _model.get("connectionVerified");
        if (_conn == false) {
            // ensure default dispatcher (in case user explicitly provided "undefined" value instead of function)
            if (this.get("dispatcher") == undefined /*|| typeof this.get("dispatcher") != "function"*/) {
                console.log("using default dispatcher");
                var _dispatcher = _.clone(Backbone.Events);
                _dispatcher.on("onAjaxResponse", function(clusterName, restApiName, response) {
                    console.log("["+clusterName+"] ["+restApiName+"]", response)
                });
                this.set({dispatcher: _dispatcher});
            }
            var connection = {
                baseUrl: attrs.baseUrl,
                refreshInterval: attrs.refreshInterval || 2000
            };
            var hello = new Hello({},connection);
            hello.fetch({
                success: function(model, response){
                    var version = hello.get("version");
                    if (version && version.number) {
                        _model.versionVerified(version);
                        _model.initCluster(connection);
                    } else {
                        _model.yellAboutVersion("n/a");
                    }
                },
                error: function(model, response) {
                    console.log("[Error] something wrong happened...", model, response);
                }
            });
        }
    },

    // When creating a new cluster, client has to provide both REST URL endpoint and cluster name.
    // The idea is that the cluster name is obtained by client upfront using cluster health API for example.
    validate: function(attrs){
        // this must be constructor call
        if (this.get("connectionVerified") == undefined) {
            if (!attrs.id || !attrs.baseUrl) {
                return "Both cluster name and URL must be provided.\n" +
                    "Example: { " +
                        "id: \"_cluster_name_\", " +
                        "baseUrl: \"_ES_REST_end_point_\" " +
                    "}";
            }
            if (attrs.dispatcher != undefined) {
                if (typeof attrs.dispatcher != "function") {
                    return "dispatcher must be a function.";
                }
            }
        }
    },

    // returns false or true depending on given version numbers
    checkVersion: function(major, minor, maintenance) {
        if ( (major == 1 && minor == 0) || (major == 0 && minor == 90 && maintenance >= 0)) {
            return true;
        }
        return false;
    },

    versionVerified: function(version) {
        console.log("Check ES node version: " + version + " [ok]");
    },

    yellAboutVersion: function(version) {
        var message =
            "*********************************\n" +
            "Bigdesk may not work correctly!\n" +
            "Found ES node version: " + version + "\n" +
            "Requires ES node version: >= 0.90.0 or 1.0.x\n" +
            "*********************************";
        console.log(message);
        if (alert) { alert(message); }
    },

    // connection.baseUrl
    // connection.refreshInterval
    initCluster: function(connection) {
        var _model = this;
        // connection has been already verified
        _model.set({connectionVerified: true});

        _model.set({        health: new ClusterHealth({}, connection) });
        _model.set({    nodesStats: new NodesStats([],    connection) });
        _model.set({    nodesState: new NodesState([],    connection) });
        _model.set({      nodeInfo: new NodeInfo({},      connection) });
        _model.set({  clusterState: new ClusterState([],  connection) });
        _model.set({ indicesStatus: new IndicesStatus([], connection) });

        this.startFetch(connection.refreshInterval);

    },

    clearTimeouts: function() {
        var _cluster = this;
        var timeouts = _cluster.get("timeouts");
        _.each(timeouts, function(num, key){
            _cluster.clearTimeout(key);
        });
    },

    clearTimeout: function(timeoutId) {
        var timeouts = this.get("timeouts");
        if (timeouts && timeouts[timeoutId]) {
            window.clearTimeout(timeouts[timeoutId]);
            delete timeouts[timeoutId];
            this.set({timeouts: timeouts});
        }
    },

    clearIntervals: function() {
        var _cluster = this;
        var intervals = this.get("intervals");
        _.each(intervals, function(num, key){
            _cluster.clearInterval(key);
        });
    },

    clearInterval: function(intervalId) {
//        console.log("stop interval " + intervalId);
        var intervals = this.get("intervals");
        if (intervals && intervals[intervalId]) {
            window.clearInterval(intervals[intervalId]);
            delete intervals[intervalId];
            this.set({intervals: intervals});
        }
    },

    startTimeout: function(timeoutId, functionCall, interval) {
        var _model = this;
        var timeouts = _model.get("timeouts");
        if (timeouts) {
            if (timeouts[timeoutId]) {
                console.log("[WARN] clearing and replacing existing timeout");
                _model.clearTimeout(timeoutId);
            }

            var timeoutFn = function() {
                functionCall();
                var t = window.setTimeout(timeoutFn, interval);
                timeouts[timeoutId] = t;
                _model.set({timeouts: timeouts});
            };

            timeoutFn();
        }
    },

    startInterval: function(intervalId, functionCall, interval) {
        var _model = this;
        var intervals = this.get("intervals");
        if (intervals) {
            if (intervals[intervalId]) {
                console.log("[WARN] clearing and replacing existing interval");
                _model.clearInterval(intervalId);
            }
            var i = window.setInterval(functionCall, interval);
            intervals[intervalId] = i;
            this.set({intervals: intervals});
            // fire callback right now
            functionCall();
        }
    },

    // start fetching bigdesk models and collections
    // params:
    //  refreshInterval
    //  baseUrl [optional] can override baseUrl that was passed into Cluster constructor
    startFetch: function(refreshInterval, baseUrl) {
        var _cluster = this;
        var _dispatcher = _cluster.get("dispatcher");
        var _clusterName = _cluster.get("id");

        if (baseUrl && typeof baseUrl == "string") {
            _cluster.get("health").setBaseUrl(baseUrl);
            _cluster.get("nodesStats").setBaseUrl(baseUrl);
            _cluster.get("nodesState").setBaseUrl(baseUrl);
            _cluster.get("nodeInfo").setBaseUrl(baseUrl);
            _cluster.get("clusterState").setBaseUrl(baseUrl);
            _cluster.get("indicesStatus").setBaseUrl(baseUrl);
        }

        var healthRefreshFunction = function(){
            _cluster.get("health").fetch({
                success: function(model, response){
                    _dispatcher.trigger("onAjaxResponse", _clusterName, "cluster > Health", response);
                }
            });
        };

        var nodesStatsRefreshFunction = function(){
            _cluster.get("nodesStats").fetch({
                add:        true,
                storeSize:  _cluster.get("storeSize"),
                now:        new Date().getTime(),
                silent:     true,
                success:    function(model, response){
                    _dispatcher.trigger("onAjaxResponse", _clusterName, "cluster > NodesStats", response);
                }
            });
        };

        var nodesStateRefreshFunction = function(){
            _cluster.get("nodesState").fetch({
                add:        true,
                silent:     true,
                success:    function(model, response){
                    _dispatcher.trigger("onAjaxResponse", _clusterName, "cluster > NodesState", response);
                }
            });
        };

        var clusterStateRefreshFunction = function(){
            _cluster.get("clusterState").fetch({
                add:        true,
                storeSize:  _cluster.get("storeSize"),
                now:        new Date().getTime(),
                silent:     true,
                success:    function(model, response){
                    _dispatcher.trigger("onAjaxResponse", _clusterName, "cluster > State", response);
                    _dispatcher.trigger("newClusterState");
                }
            });
        };

        var indicesStatusRefreshFunction = function(){
            _cluster.get("indicesStatus").fetch({
                add:        true,
                storeSize:  _cluster.get("storeSize"),
                now:        new Date().getTime(),
                silent:     true,
                success:    function(model, response){
                    _dispatcher.trigger("onAjaxResponse", _clusterName, "indices > Status", response);
                    _dispatcher.trigger("newIndicesStatus");
                }
            });
        };

        this.clearInterval("nodesStateInterval");
        this.clearInterval("nodesStatsInterval");
        this.clearInterval("healthInterval");
        this.clearTimeout("clusterStateInterval");
        this.clearTimeout("indicesStatusInterval");

        this.startInterval("nodesStateInterval",   nodesStateRefreshFunction,    refreshInterval);
        this.startInterval("nodesStatsInterval",   nodesStatsRefreshFunction,    refreshInterval);
        this.startInterval("healthInterval",       healthRefreshFunction,        refreshInterval);
        this.startTimeout("clusterStateInterval",  clusterStateRefreshFunction,  refreshInterval);
        this.startTimeout("indicesStatusInterval", indicesStatusRefreshFunction, refreshInterval);
    },

    // set storeSize value of the cluster
    setStoreSize: function(storeSize) {
        var _cluster = this;
        _cluster.set({storeSize: storeSize});
    },

    // return master node id if available, otherwise return empty string
    getMasterNodeId: function() {
        var _cluster = this;
        return  _cluster.get("nodesState").getMasterNodeId();
    }
});

var ClusterCollection = Backbone.Collection.extend({
    model: Cluster
});

var BigdeskStore = Backbone.Model.extend({

    defaults: {
        cluster: new ClusterCollection()
    },

    // Returns an instance of a Cluster model with given name (id)
    // or undefined if no instance if found.
    getCluster: function(clusterName) {
        return this.get("cluster").get(clusterName);
    },

    // Add a new cluster into store. Parameter is an instance of a Cluster model.
    // Throws error if there already is a cluster with the same id.
    addCluster: function(clusterModel) {
        var _c = this.get("cluster");
        if (_c.get(clusterModel.get("id")) == undefined) {
            _c.add(clusterModel)
        } else {
            throw "Cluster already exists.";
        };
    }
});
<|endoftext|>


<commit_before><commit_msg>adding a picture field to firebase db<commit_after><|endoftext|>


<commit_before>var
	kind = require('../kind');

/**
* @name CheckboxAccessibilityMixin
* @mixin
*/
module.exports = {

	/**
	* @private
	*/
	observers: [
		{method: 'updateAccessibilityAttributes', path: 'checked'}
	],

	/**
	* @private
	*/
	updateAccessibilityAttributes: kind.inherit(function (sup) {
		return function (was, is, prop) {
			var enabled = !this.accessibilityDisabled;
			sup.apply(this, arguments);
			this.setAttribute('role', enabled ? 'checkbox' : null);
			this.setAttribute('tabindex', enabled ? 0 : null);
			this.setAttribute('aria-checked', enabled ? this.checked ? 'true' : 'false' : null);
		};
	})
};<commit_msg>convert checked to String to set as attribute value<commit_after>var
	kind = require('../kind');

/**
* @name CheckboxAccessibilityMixin
* @mixin
*/
module.exports = {

	/**
	* @private
	*/
	observers: [
		{method: 'updateAccessibilityAttributes', path: 'checked'}
	],

	/**
	* @private
	*/
	updateAccessibilityAttributes: kind.inherit(function (sup) {
		return function (was, is, prop) {
			var enabled = !this.accessibilityDisabled;
			sup.apply(this, arguments);
			this.setAttribute('role', enabled ? 'checkbox' : null);
			this.setAttribute('tabindex', enabled ? 0 : null);
			this.setAttribute('aria-checked', enabled ? String(this.checked) : null);
		};
	})
};<|endoftext|>


<commit_before>import { ErrorHandler } from '@/helpers';
const ERRORS = {
  U2F_TIMEOUT: 'Failed to sign with Ledger device: U2F TIMEOUT',
  NO_LEDGER: 'No Ledger device found (timeout)',
  DEVICE_BUSY: 'Ledger Device is busy (lock signPersonalMessage)',
  UNKNOWN_ERROR_6804: 'Ledger device: UNKNOWN_ERROR (0x6804)'
};
export default err => {
  const errorValues = Object.values(ERRORS);
  if (errorValues.includes(err.message)) {
    ErrorHandler(err, true);
  } else {
    ErrorHandler(err, false);
  }
};
<commit_msg>add ledger error<commit_after>import { ErrorHandler } from '@/helpers';
const ERRORS = {
  U2F_TIMEOUT: 'Failed to sign with Ledger device: U2F TIMEOUT',
  NO_LEDGER: 'No Ledger device found (timeout)',
  DEVICE_BUSY: 'Ledger Device is busy (lock signPersonalMessage)',
  UNKNOWN_ERROR_6804: 'Ledger device: UNKNOWN_ERROR (0x6804)',
  U2F_OTHER_ERROR:
    'TransportError: Failed to sign with Ledger device: U2F OTHER_ERROR'
};
export default err => {
  const errorValues = Object.values(ERRORS);
  if (errorValues.includes(err.message)) {
    ErrorHandler(err, true);
  } else {
    ErrorHandler(err, false);
  }
};
<|endoftext|>


<commit_before>import * as yup from 'yup';
import i18next from '../../core/language';
import map from 'lodash/map';
import moment from 'moment';
import { MGDL_UNITS, MMOLL_UNITS, MS_IN_DAY } from '../../core/constants';

import {
  dateFormat,
  defaultUnits,
  deviceMeta,
  phoneRegex,
  revisionStates,
  pumpDeviceOptions,
  cgmDeviceOptions,
  insulinModelOptions,
  // typeOptions,
  sexOptions,
  trainingOptions,
  validCountryCodes,
} from './prescriptionFormConstants';

const t = i18next.t.bind(i18next);

export default (pumpId, bgUnits = defaultUnits.bloodGlucose) => {
  const pumpMeta = deviceMeta(pumpId, bgUnits);

  const rangeErrors = {
    basalRate: `Basal rate out of range. Please select a value between ${pumpMeta.ranges.basalRate.min}-${pumpMeta.ranges.basalRate.max}`,
    basalRateMaximum: `Basal limit out of range. Please select a value between ${pumpMeta.ranges.basalRateMaximum.min}-${pumpMeta.ranges.basalRateMaximum.max}`,
    bloodGlucoseTarget: `Correction target out of range. Please select a value between ${pumpMeta.ranges.bloodGlucoseTarget.min}-${pumpMeta.ranges.bloodGlucoseTarget.max}`,
    bolusAmountMaximum: `Bolus limit out of range. Please select a value between ${pumpMeta.ranges.bolusAmountMaximum.min}-${pumpMeta.ranges.bolusAmountMaximum.max}`,
    carbRatio: `Insulin-to-carb ratio of range. Please select a value between ${pumpMeta.ranges.carbRatio.min}-${pumpMeta.ranges.carbRatio.max}`,
    insulinSensitivityFactor: `Sensitivity factor out of range. Please select a value between ${pumpMeta.ranges.insulinSensitivityFactor.min}-${pumpMeta.ranges.insulinSensitivityFactor.max}`,
    suspendThreshold: `Threshold out of range. Please select a value between ${pumpMeta.ranges.suspendThreshold.min}-${pumpMeta.ranges.suspendThreshold.max}`,
  };

  return yup.object().shape({
    id: yup.string(),
    state: yup.string()
      .oneOf(revisionStates, t('Please select a valid option')),
    // type: yup.string()
    //   .oneOf(map(typeOptions, 'value'), t('Please select a valid option'))
    //   .required(t('Account type is required')),
    firstName: yup.string()
      .required(t('First name is required')),
    lastName: yup.string().required(t('Last name is required')),
    birthday: yup.string()
      .test('matchesDateFormat', t('Please enter a valid date in the requested format'), value => moment(value, dateFormat, true).isValid())
      .test('isPastDate', t('Please enter a date prior to today'), value => value < moment().format(dateFormat))
      .required(t('Patient\'s birthday is required')),
    email: yup.string()
      .email(t('Please enter a valid email address'))
      .required(t('Email address is required')),
    emailConfirm: yup.string()
      .oneOf([yup.ref('email')], t('Email address confirmation does not match'))
      .required(t('Email confirmation is required')),
    phoneNumber: yup.object().shape({
      countryCode: yup.number()
        .integer()
        .oneOf(validCountryCodes, t('Please set a valid country code'))
        .required(t('Country code is required')),
      number: yup.string()
        .matches(phoneRegex, t('Please enter a valid phone number'))
        .required(t('Patient phone number is required')),
    }),
    mrn: yup.string()
      .required(t('Patient MRN number is required')),
    sex: yup.string()
      .oneOf(map(sexOptions, 'value'), t('Please select a valid option'))
      .required(t('Patient gender is required')),
    initialSettings: yup.object().shape({
      bloodGlucoseUnits: yup.string()
        .oneOf([MGDL_UNITS, MMOLL_UNITS], t('Please set a valid blood glucose units option'))
        .default(bgUnits),
      pumpId: yup.string()
        .oneOf(map(pumpDeviceOptions, 'value'))
        .required(t('A pump type must be specified')),
      cgmId: yup.string()
        .oneOf(map(cgmDeviceOptions, 'value'))
        .required(t('A cgm type must be specified')),
      // insulinModel: yup.string()
      //   .oneOf(map(insulinModelOptions, 'value'))
      //   .required(t('An insulin model must be specified')),
      // suspendThreshold: yup.object().shape({
      //   value: yup.number()
      //     .min(pumpMeta.ranges.suspendThreshold.min, rangeErrors.suspendThreshold)
      //     .max(pumpMeta.ranges.suspendThreshold.max, rangeErrors.suspendThreshold)
      //     .required(t('Suspend threshold is required')),
      //   units: yup.string().default(bgUnits),
      // }),
      basalRateMaximum: yup.object().shape({
        value: yup.number()
          .min(pumpMeta.ranges.basalRateMaximum.min, rangeErrors.basalRateMaximum)
          .max(pumpMeta.ranges.basalRateMaximum.max, rangeErrors.basalRateMaximum)
          .required(t('Max basal rate is required')),
        units: yup.string()
          .default(defaultUnits.basalRate),
      }),
      bolusAmountMaximum: yup.object().shape({
        value: yup.number()
          .min(pumpMeta.ranges.bolusAmountMaximum.min, rangeErrors.bolusAmountMaximum)
          .max(pumpMeta.ranges.bolusAmountMaximum.max, rangeErrors.bolusAmountMaximum)
          .required(t('Max bolus amount is required')),
        units: yup.string()
          .default(defaultUnits.bolusAmount),
      }),
      bloodGlucoseTargetSchedule: yup.array().of(
        yup.object().shape({
          high: yup.number()
            .min(pumpMeta.ranges.bloodGlucoseTarget.min, rangeErrors.bloodGlucoseTarget)
            .max(pumpMeta.ranges.bloodGlucoseTarget.max, rangeErrors.bloodGlucoseTarget)
            .required(t('High target is required')),
          low: yup.number()
            .min(pumpMeta.ranges.bloodGlucoseTarget.min, rangeErrors.bloodGlucoseTarget)
            .max(pumpMeta.ranges.bloodGlucoseTarget.max, rangeErrors.bloodGlucoseTarget)
            .required(t('Low target is required')),
          start: yup.number()
            .integer()
            .min(0)
            .max(MS_IN_DAY)
            .required(t('Start time is required')),
        }),
      ),
      basalRateSchedule: yup.array().of(
        yup.object().shape({
          rate: yup.number()
            .min(pumpMeta.ranges.basalRate.min, rangeErrors.basalRate)
            .max(pumpMeta.ranges.basalRate.max, rangeErrors.basalRate)
            .required(t('Basal rate is required')),
          start: yup.number()
            .integer()
            .min(0)
            .max(MS_IN_DAY)
            .required(t('Start time is required')),
        }),
      ),
      carbohydrateRatioSchedule: yup.array().of(
        yup.object().shape({
          amount: yup.number()
            .min(pumpMeta.ranges.carbRatio.min, rangeErrors.carbRatio)
            .max(pumpMeta.ranges.carbRatio.max, rangeErrors.carbRatio)
            .required(t('Insulin-to-carb ratio is required')),
          start: yup.number()
            .integer()
            .min(0)
            .max(MS_IN_DAY)
            .required(t('Start time is required')),
        }),
      ),
      insulinSensitivitySchedule: yup.array().of(
        yup.object().shape({
          amount: yup.number()
            .min(pumpMeta.ranges.insulinSensitivityFactor.min, rangeErrors.insulinSensitivityFactor)
            .max(pumpMeta.ranges.insulinSensitivityFactor.max, rangeErrors.insulinSensitivityFactor)
            .required(t('Sensitivity factor is required')),
          start: yup.number()
            .integer()
            .min(0)
            .max(MS_IN_DAY)
            .required(t('Start time is required')),
        }),
      ),
    }),
    training: yup.string()
      .oneOf(map(trainingOptions, 'value'), t('Please select a valid option'))
      .required(t('Training type is required')),
    therapySettingsReviewed: yup.boolean()
      .test('isTrue', t('Please confirm the therapy settings for this patient'), value => (value === true)),
  });
};
<commit_msg>[WEB-863] Additional commenting out for insulinModel and suspendThreshold fields<commit_after>import * as yup from 'yup';
import i18next from '../../core/language';
import map from 'lodash/map';
import moment from 'moment';
import { MGDL_UNITS, MMOLL_UNITS, MS_IN_DAY } from '../../core/constants';

import {
  dateFormat,
  defaultUnits,
  deviceMeta,
  phoneRegex,
  revisionStates,
  pumpDeviceOptions,
  cgmDeviceOptions,
  // insulinModelOptions,
  // typeOptions,
  sexOptions,
  trainingOptions,
  validCountryCodes,
} from './prescriptionFormConstants';

const t = i18next.t.bind(i18next);

export default (pumpId, bgUnits = defaultUnits.bloodGlucose) => {
  const pumpMeta = deviceMeta(pumpId, bgUnits);

  const rangeErrors = {
    basalRate: `Basal rate out of range. Please select a value between ${pumpMeta.ranges.basalRate.min}-${pumpMeta.ranges.basalRate.max}`,
    basalRateMaximum: `Basal limit out of range. Please select a value between ${pumpMeta.ranges.basalRateMaximum.min}-${pumpMeta.ranges.basalRateMaximum.max}`,
    bloodGlucoseTarget: `Correction target out of range. Please select a value between ${pumpMeta.ranges.bloodGlucoseTarget.min}-${pumpMeta.ranges.bloodGlucoseTarget.max}`,
    bolusAmountMaximum: `Bolus limit out of range. Please select a value between ${pumpMeta.ranges.bolusAmountMaximum.min}-${pumpMeta.ranges.bolusAmountMaximum.max}`,
    carbRatio: `Insulin-to-carb ratio of range. Please select a value between ${pumpMeta.ranges.carbRatio.min}-${pumpMeta.ranges.carbRatio.max}`,
    insulinSensitivityFactor: `Sensitivity factor out of range. Please select a value between ${pumpMeta.ranges.insulinSensitivityFactor.min}-${pumpMeta.ranges.insulinSensitivityFactor.max}`,
    // suspendThreshold: `Threshold out of range. Please select a value between ${pumpMeta.ranges.suspendThreshold.min}-${pumpMeta.ranges.suspendThreshold.max}`,
  };

  return yup.object().shape({
    id: yup.string(),
    state: yup.string()
      .oneOf(revisionStates, t('Please select a valid option')),
    // type: yup.string()
    //   .oneOf(map(typeOptions, 'value'), t('Please select a valid option'))
    //   .required(t('Account type is required')),
    firstName: yup.string()
      .required(t('First name is required')),
    lastName: yup.string().required(t('Last name is required')),
    birthday: yup.string()
      .test('matchesDateFormat', t('Please enter a valid date in the requested format'), value => moment(value, dateFormat, true).isValid())
      .test('isPastDate', t('Please enter a date prior to today'), value => value < moment().format(dateFormat))
      .required(t('Patient\'s birthday is required')),
    email: yup.string()
      .email(t('Please enter a valid email address'))
      .required(t('Email address is required')),
    emailConfirm: yup.string()
      .oneOf([yup.ref('email')], t('Email address confirmation does not match'))
      .required(t('Email confirmation is required')),
    phoneNumber: yup.object().shape({
      countryCode: yup.number()
        .integer()
        .oneOf(validCountryCodes, t('Please set a valid country code'))
        .required(t('Country code is required')),
      number: yup.string()
        .matches(phoneRegex, t('Please enter a valid phone number'))
        .required(t('Patient phone number is required')),
    }),
    mrn: yup.string()
      .required(t('Patient MRN number is required')),
    sex: yup.string()
      .oneOf(map(sexOptions, 'value'), t('Please select a valid option'))
      .required(t('Patient gender is required')),
    initialSettings: yup.object().shape({
      bloodGlucoseUnits: yup.string()
        .oneOf([MGDL_UNITS, MMOLL_UNITS], t('Please set a valid blood glucose units option'))
        .default(bgUnits),
      pumpId: yup.string()
        .oneOf(map(pumpDeviceOptions, 'value'))
        .required(t('A pump type must be specified')),
      cgmId: yup.string()
        .oneOf(map(cgmDeviceOptions, 'value'))
        .required(t('A cgm type must be specified')),
      // insulinModel: yup.string()
      //   .oneOf(map(insulinModelOptions, 'value'))
      //   .required(t('An insulin model must be specified')),
      // suspendThreshold: yup.object().shape({
      //   value: yup.number()
      //     .min(pumpMeta.ranges.suspendThreshold.min, rangeErrors.suspendThreshold)
      //     .max(pumpMeta.ranges.suspendThreshold.max, rangeErrors.suspendThreshold)
      //     .required(t('Suspend threshold is required')),
      //   units: yup.string().default(bgUnits),
      // }),
      basalRateMaximum: yup.object().shape({
        value: yup.number()
          .min(pumpMeta.ranges.basalRateMaximum.min, rangeErrors.basalRateMaximum)
          .max(pumpMeta.ranges.basalRateMaximum.max, rangeErrors.basalRateMaximum)
          .required(t('Max basal rate is required')),
        units: yup.string()
          .default(defaultUnits.basalRate),
      }),
      bolusAmountMaximum: yup.object().shape({
        value: yup.number()
          .min(pumpMeta.ranges.bolusAmountMaximum.min, rangeErrors.bolusAmountMaximum)
          .max(pumpMeta.ranges.bolusAmountMaximum.max, rangeErrors.bolusAmountMaximum)
          .required(t('Max bolus amount is required')),
        units: yup.string()
          .default(defaultUnits.bolusAmount),
      }),
      bloodGlucoseTargetSchedule: yup.array().of(
        yup.object().shape({
          high: yup.number()
            .min(pumpMeta.ranges.bloodGlucoseTarget.min, rangeErrors.bloodGlucoseTarget)
            .max(pumpMeta.ranges.bloodGlucoseTarget.max, rangeErrors.bloodGlucoseTarget)
            .required(t('High target is required')),
          low: yup.number()
            .min(pumpMeta.ranges.bloodGlucoseTarget.min, rangeErrors.bloodGlucoseTarget)
            .max(pumpMeta.ranges.bloodGlucoseTarget.max, rangeErrors.bloodGlucoseTarget)
            .required(t('Low target is required')),
          start: yup.number()
            .integer()
            .min(0)
            .max(MS_IN_DAY)
            .required(t('Start time is required')),
        }),
      ),
      basalRateSchedule: yup.array().of(
        yup.object().shape({
          rate: yup.number()
            .min(pumpMeta.ranges.basalRate.min, rangeErrors.basalRate)
            .max(pumpMeta.ranges.basalRate.max, rangeErrors.basalRate)
            .required(t('Basal rate is required')),
          start: yup.number()
            .integer()
            .min(0)
            .max(MS_IN_DAY)
            .required(t('Start time is required')),
        }),
      ),
      carbohydrateRatioSchedule: yup.array().of(
        yup.object().shape({
          amount: yup.number()
            .min(pumpMeta.ranges.carbRatio.min, rangeErrors.carbRatio)
            .max(pumpMeta.ranges.carbRatio.max, rangeErrors.carbRatio)
            .required(t('Insulin-to-carb ratio is required')),
          start: yup.number()
            .integer()
            .min(0)
            .max(MS_IN_DAY)
            .required(t('Start time is required')),
        }),
      ),
      insulinSensitivitySchedule: yup.array().of(
        yup.object().shape({
          amount: yup.number()
            .min(pumpMeta.ranges.insulinSensitivityFactor.min, rangeErrors.insulinSensitivityFactor)
            .max(pumpMeta.ranges.insulinSensitivityFactor.max, rangeErrors.insulinSensitivityFactor)
            .required(t('Sensitivity factor is required')),
          start: yup.number()
            .integer()
            .min(0)
            .max(MS_IN_DAY)
            .required(t('Start time is required')),
        }),
      ),
    }),
    training: yup.string()
      .oneOf(map(trainingOptions, 'value'), t('Please select a valid option'))
      .required(t('Training type is required')),
    therapySettingsReviewed: yup.boolean()
      .test('isTrue', t('Please confirm the therapy settings for this patient'), value => (value === true)),
  });
};
<|endoftext|>