// DYMICO_TRANSPILER_V=v2-cleanroom1 source=gs-in-dymico runtime=dymicoAsset cacheTier=mem console.log("[DYMICO_TRANSPILER_V=v2-cleanroom1 source=gs-in-dymico runtime=dymicoAsset cacheTier=mem]"); if (typeof gs === "undefined" || typeof gs.mc !== "function") { /* * 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. */ (function() { var gs = function(obj) { if (obj instanceof gs) return obj; if (!(this instanceof gs)) return new gs(obj); }; var root = this; if (typeof exports !== 'undefined') { if (typeof module !== 'undefined' && module.exports) { exports = module.exports = gs; } exports.gs = gs; } else { root.gs = gs; } //Fails gs.fails = false; //Local console gs.consoleData = ''; //If true and console is available, all output will go through console gs.consoleOutput = true; //If true and console is available, some methods will show info on console gs.consoleInfo = false; var globalMetaClass = {}; //Categories var categories = []; // Mixins var mixins = []; var mixinsObjects = []; //Delegate var delegates = []; //Static this var aStT = null; //@Delegate var mapAddDelegate = {}; gs.myCategories = {}; ///////////////////////////////////////////////////////////////// // assert and println ///////////////////////////////////////////////////////////////// gs.assert = function(value) { if(value === false) { gs.fails = true; var message = 'Assert Fails! - '; if (arguments.length == 2 && arguments[1] !== null) { message = arguments[1] + ' - '; } gs.println(message + value); } }; //Function that used for print and println in groovy gs.println = function(value) { if (gs.consoleOutput) { console.log(value); } else { if (gs.consoleData !== "") { gs.consoleData = gs.consoleData + "\n"; } gs.consoleData = gs.consoleData + value; } }; gs.printNashorn = function(value) { print(value); }; //TODO We don't know if a function is constructor, atm if function name starts with uppercase, it is function isConstructor(name, func) { return name[0] == name[0].toUpperCase(); } function isFunction(f) { return typeof(f) === "function"; } function getterSetterRemove(name) { return name.charAt(3).toLowerCase() + name.slice(4); } ///////////////////////////////////////////////////////////////// // Class functions ///////////////////////////////////////////////////////////////// function BaseClass() { }; gs.BaseClass = BaseClass; //gs.baseClass = { //The with function, with is a reserved word in JavaScript BaseClass.prototype.clazz = {}; BaseClass.prototype.withz = function(closure) { return closure.apply(this, closure.arguments); }, BaseClass.prototype.getProperties = function() { var result = gs.map(), ob; for (ob in this) { if (isFunction(this[ob]) && ob.startsWith('get') && this[ob].length == 0 && ob !== 'getProperties' && ob !== 'getMethods' && ob !== 'getMetaClass') { result.add(getterSetterRemove(ob), this[ob]()); } else if (!isFunction(this[ob]) && ob != 'clazz' && ob.indexOf('__') < 0) { result.add(ob, this[ob]); } } return result; }; BaseClass.prototype.getMethods = function() { var result = gs.list([]), ob; for (ob in this) { if (isFunction(this[ob])) { if (!isObjectProperty(ob) && !(isConstructor(ob, this[ob]))) { var item = { name: ob }; result.add(item); } } } return result; }; BaseClass.prototype.invokeMethod = function(name, values) { var i, newArgs = []; if (values) { for (i=0; i < values.length; i++) { newArgs[i] = values[i]; } } var f = this[name]; return f.apply(this, newArgs); }; BaseClass.prototype.constructor = function() { return this; }; BaseClass.prototype.asType = function(type) { if (hasFunc(type, 'gSaT')) { type.gSaT(this); } return this; }; BaseClass.prototype.withTraits = function() { var i; for (i = 0; i < arguments.length; i++) { arguments[i].gSaT(this); } return this; }; BaseClass.prototype.getClass = function() { return this.clazz; }; BaseClass.prototype.getMetaClass = function() { return gs.metaClass(this); }; function applyBaseClassFunctions(item) { item.asType = BaseClass.prototype.asType; } function isObjectProperty(name) { return ['clazz','gSdefaultValue','leftShift', 'minus','plus','equals','toString', 'clone','withz','getProperties','getStatic', 'getClass', 'getMetaClass', 'getMethods','invokeMethod','constructor', 'asType', 'withTraits'].indexOf(name) >= 0; } function isJsArray(array) { return array['clazz'] === undefined } gs.expando = function() { var object = gs.init('Expando'); object.constructorWithMap = function(map) { gs.passMapToObject(map, this); return this;}; if (arguments.length == 1) {object.constructorWithMap(arguments[0]); } return object; }; gs.expandoMetaClass = function() { var object = gs.init('ExpandoMetaClass'); object.initialize = function() { return this; }; return object; }; function expandWithMetaClass(item, objectName) { if (globalMetaClass && globalMetaClass[objectName]) { var obj, map = globalMetaClass[objectName]; for (obj in map) { //Static methods var staticMap = map.getStatic(); if (staticMap) { var objStatic; for (objStatic in staticMap) { if (objStatic != 'gSparent') { //console.log('Adding static->'+objStatic); item[obj] = staticMap[objStatic]; } } } //Non static methods and properties item[obj] = map[obj]; } } return item; } gs.init = function(name) { return expandWithMetaClass(new BaseClass(), name); }; function createClassNames(item, items) { var number = items.length, i, container; for (i = 0; i < number ; i++) { if (i === 0) { container = {}; item.clazz = container; } container.name = items[i]; container.simpleName = getSimpleName(items[i]); if (i < number) { container.superclass = {}; container = container.superclass; } } } function getSimpleName(name) { var pos = name.indexOf("."); while (pos >= 0) { name = name.substring(pos + 1); pos = name.indexOf("."); } return name; } ///////////////////////////////////////////////////////////////// // set - as Set and HashSet from groovy ///////////////////////////////////////////////////////////////// gs.set = function(value) { var object; if (arguments.length === 0) { object = gs.list([]); } else { object = value; } createClassNames(object, ['java.util.HashSet']); object.isSet = true; object.withz = function(closure) { return interceptClosureCall(closure, this); }; object.add = function(item) { if (!(this.contains(item))) { this.push(item); return this; } else { return false; } }; object.addAll = function(elements) { if (elements instanceof Array) { var i, fails = false; //Check if items not in set for (i = 0; !fails && i < elements.length; i++) { if (this.contains(elements[i])) { fails = true; } } if (fails) { return false; } else { //All ok, we add items to the set for (i = 0; i < elements.length; i++) { this.add(elements[i]); } } } return this; }; object.equals = function(other) { if (!(other instanceof Array) || other.length != this.length || !(other.isSet)) { return false; } else { var i, result = true; for (i = 0; i < this.length && result; i++) { if (!(other.contains(this[i]))) { result = false; } } return result; } }; object.toList = function() { var i, list = []; for (i = 0; i < this.length; i++) { list[i] = this[i]; } return gs.list(list); }; object.plus = function(other) { var result = gs.set(); result.addAll(this); if (other instanceof Array) { var i; for (i = 0; i < other.length; i++) { if (!(result.contains(other[i]))) { result.add(other[i]); } } } return result; }; object.minus = function(other) { var result = gs.set(); result.addAll(this); if (other instanceof Array) { var i; for (i = 0;i < other.length; i++) { if (result.contains(other[i])) { result.remove(other[i]); } } } return result; }; object.remove = function(value) { var index = this.indexOf(value); if (index >= 0) { this.splice(index, 1); return true; } else { return false; } }; return object; }; ///////////////////////////////////////////////////////////////// // map - [:] from groovy ///////////////////////////////////////////////////////////////// function isMapProperty(name) { return isObjectProperty(name) || ['any','collect', 'collectEntries','collectMany','countBy','dropWhile', 'each','eachWithIndex','every','find','findAll', 'findResult','findResults','get','getAt','groupBy', 'inject','intersect','max','min', 'putAll','putAt','reverseEach', 'clear', 'sort','spread','subMap','add','take','takeWhile', 'withDefault','count','drop','keySet', 'put','size','isEmpty','remove','containsKey', 'containsValue','values'].indexOf(name) >= 0; } gs.map = function() { var gSobject = new GsGroovyMap(); expandWithMetaClass(gSobject, 'LinkedHashMap'); applyBaseClassFunctions(gSobject); if (arguments.length == 1 && arguments[0] instanceof Object) { gs.passMapToObject(arguments[0], gSobject); } return gSobject; }; function GsGroovyMap() {} GsGroovyMap.prototype.clazz = { name: 'java.util.LinkedHashMap', simpleName: 'LinkedHashMap', superclass: { name: 'java.util.HashMap', simpleName: 'HashMap'}}; GsGroovyMap.prototype.gSdefaultValue = null; GsGroovyMap.prototype.withz = BaseClass.prototype.withz; GsGroovyMap.prototype.add = function(key, value) { if (key == "spreadMap") { //We insert items of the map, from spread operator var ob; for (ob in value) { if (!isMapProperty(ob)) { this[ob] = value[ob]; } } } else { this[key] = value; } return this; }; GsGroovyMap.prototype.put = function(key,value) { return this.add(key,value); }; GsGroovyMap.prototype.leftShift = function(key,value) { if (arguments.length == 1) { return this.plus(arguments[0]); } else { return this.add(key,value); } }; GsGroovyMap.prototype.putAt = function(key,value) { this.put(key,value); }; GsGroovyMap.prototype.size = function() { var number = 0,ob; for (ob in this) { if (!isMapProperty(ob)) { number++; } } return number; }; GsGroovyMap.prototype.isEmpty = function() { return (this.size() === 0); }; GsGroovyMap.prototype.remove = function(key) { if (this[key]) { delete this[key]; } }; GsGroovyMap.prototype.each = function(closure) { var ob; for (ob in this) { if (!isMapProperty(ob)) { var f = arguments[0]; //Nice, number of arguments in length property if (f.length == 1) { closure({key: ob, value: this[ob]}); } if (f.length == 2) { closure(ob,this[ob]); } } } }; GsGroovyMap.prototype.count = function(closure) { var number = 0, ob; for (ob in this) { if (!isMapProperty(ob)) { if (closure.length == 1) { if (closure({key: ob, value: this[ob]})) { number++; } } if (closure.length == 2) { if (closure(ob, this[ob])) { number++; } } } } return number; }; GsGroovyMap.prototype.any = function(closure) { var ob; for (ob in this) { if (!isMapProperty(ob)) { var f = arguments[0]; if (f.length == 1) { if (closure({key:ob, value: this[ob]})) { return true; } } if (f.length == 2) { if (closure(ob, this[ob])) { return true; } } } } return false; }; GsGroovyMap.prototype.every = function(closure) { var ob; for (ob in this) { if (!isMapProperty(ob)) { var f = arguments[0]; if (f.length == 1) { if (!closure({key: ob, value: this[ob]})) { return false; } } if (f.length == 2) { if (!closure(ob, this[ob])) { return false; } } } } return true; }; GsGroovyMap.prototype.find = function(closure) { var ob; for (ob in this) { if (!isMapProperty(ob)) { var f = arguments[0]; if (f.length == 1) { var entry = {key: ob, value: this[ob]}; if (closure(entry)) { return entry; } } if (f.length == 2) { if (closure(ob, this[ob])) { return {key: ob, value: this[ob]}; } } } } return null; }; GsGroovyMap.prototype.dropWhile = function(closure) { var result = gs.map(), ob; for (ob in this) { if (!isMapProperty(ob)) { var entry = {key: ob, value: this[ob]}; var f = arguments[0]; if (f.length == 1) { if (!closure(entry)) { result.add(entry.key, entry.value); } } if (f.length == 2) { if (!closure(entry.key, entry.value)) { result.add(entry.key, entry.value); } } } } return result; }; GsGroovyMap.prototype.drop = function(number) { var result = gs.map(), ob, count = 0; for (ob in this) { if (!isMapProperty(ob)) { count ++; if (count > number) { result.add(ob, this[ob]); } } } return result; }; GsGroovyMap.prototype.findAll = function(closure) { var result = gs.map(), ob; for (ob in this) { if (!isMapProperty(ob)) { var f = arguments[0]; if (f.length == 1) { var entry = {key: ob, value: this[ob]}; if (closure(entry)) { result.add(entry.key, entry.value); } } if (f.length == 2) { if (closure(ob, this[ob])) { result.add(ob, this[ob]); } } } } return result; }; GsGroovyMap.prototype.collect = function(closure) { var result = gs.list([]), ob; for (ob in this) { if (!isMapProperty(ob)) { var f = arguments[0]; if (f.length==1) { result.add(closure({key:ob, value:this[ob]})); } if (f.length==2) { result.add(closure(ob,this[ob])); } } } if (result.size()>0) { return result; } else { return null; } }; GsGroovyMap.prototype.containsKey = function(key) { if (this[key] === undefined || this[key] === null) { return false; } else { return true; } }; GsGroovyMap.prototype.containsValue = function(value) { var ob, gotIt = false; for (ob in this) { if (!isMapProperty(ob)) { if (gs.equals(this[ob],value)) { gotIt = true; break; } } } return gotIt; }; GsGroovyMap.prototype.get = function(key, defaultValue) { if (!this.containsKey(key)) { this[key] = defaultValue; } return this[key]; }; GsGroovyMap.prototype.toString = function() { var items = ''; this.each (function(key,value) { items = items + key+': '+value+' ,'; }); return '[' + items + ']'; }; GsGroovyMap.prototype.equals = function(otherMap) { var result = true, ob; for (ob in this) { if (!isMapProperty(ob)) { if (!gs.equals(this[ob],otherMap[ob])) { result = false; } } } return result; }; GsGroovyMap.prototype.keySet = function() { var result = gs.list([]), ob; for (ob in this) { if (!isMapProperty(ob)) { result.add(ob); } } return result; }; GsGroovyMap.prototype.values = function() { var result = gs.list([]), ob; for (ob in this) { if (!isMapProperty(ob)) { result.add(this[ob]); } } return result; }; GsGroovyMap.prototype.withDefault = function(closure) { this.gSdefaultValue = closure; return this; }; GsGroovyMap.prototype.inject = function(initial,closure) { var ob; for (ob in this) { if (!isMapProperty(ob)) { if (closure.length == 2) { var entry = {key:ob, value:this[ob]}; initial = closure(initial, entry); } if (closure.length == 3) { initial = closure(initial, ob, this[ob]); } } } return initial; }; GsGroovyMap.prototype.putAll = function (items) { if (items instanceof Array) { var i; for (i=0;i= 0; i--) { interceptClosureCall(closure, this[i]); } return this; }; Array.prototype.eachWithIndex = function(closure,index) { for (index=0; index < this.length; index++) { closure(this[index], index); } return this; }; Array.prototype.any = function(closure) { var i; for (i = 0;i < this.length; i++) { if (closure(this[i])) { return true; } } return false; }; Array.prototype.oldValues = Array.prototype.values; Array.prototype.values = function() { if (isJsArray(this) && Array.prototype.oldValues) { return this.oldValues(); } else { var i, result = []; for (i = 0; i < this.length; i++) { result[i] = this[i]; } return result; } }; //Remove only 1 item from the list Array.prototype.remove = function(indexOrValue) { var result = false,index = -1; if (typeof indexOrValue == 'number') { index = indexOrValue; result = this[index]; } else { index = this.indexOf(indexOrValue); if (index >= 0) { result = true; } } if (index >= 0) { this.splice(index, 1); } return result; }; //Maybe too much complex, not much inspired Array.prototype.removeAll = function(data) { if (data instanceof Array) { var result = []; this.forEach(function(v, i, a) { if (data.contains(v)) { result.push(i); } }); //Now in result we have index of items to delete if (result.length>0) { var decremental = 0; var thisList = this; result.forEach(function(v, i, a) { //Had tho change this for thisList, other scope on this here thisList.splice(v-decremental,1); decremental=decremental+1; }); } } else if (isFunction(data)) { var i; for (i = this.length - 1; i >= 0; i--) { if (data(this[i])) { this.remove(i); } } } return this; }; Array.prototype.collect = function(closure) { var i, result = gs.list([]); for (i = 0; i < this.length; i++) { result[i] = closure(this[i]); } return result; }; Array.prototype.collectMany = function(closure) { var i, result = gs.list([]); for (i = 0;i < this.length; i++) { result.addAll(closure(this[i])); } return result; }; Array.prototype.takeWhile = function(closure) { var i, result = gs.list([]); for (i = 0; i < this.length; i++) { if (closure(this[i])) { result[i] = this[i]; } else { break; } } return result; }; Array.prototype.dropWhile = function(closure) { var result = gs.list([]); var i, j=0, insert = false; for (i = 0; i < this.length; i++) { if (!closure(this[i])) { insert=true; } if (insert) { result[j++] = this[i]; } } return result; }; Array.prototype.drop = function(number) { var i, result = gs.list([]); for (i = number; i < this.length; i++) { result.push(this[i]); } return result; }; Array.prototype.findAll = function(closure) { var values = this.filter(closure); return gs.list(values); }; if (!Array.prototype.find) { Array.prototype.find = function (closure) { var result, i; for (i = 0; !result && i < this.length; i++) { if (closure(this[i])) { result = this[i]; } } return result; }; } Array.prototype.first = function() { return this[0]; }; Array.prototype.head = function() { return this.first(); }; Array.prototype.last = function() { return this[this.length - 1]; }; Array.prototype.sum = function() { var i, result = 0; //can pass a closure to sum if (arguments.length == 1) { for (i = 0; i < this.length; i++) { result = result + arguments[0](this[i]); } } else { if (this.length > 0 && this[0].plus) { var item = this[0]; for (i = 0; i + 1 < this.length; i++) { item = item.plus(this[i + 1]); } return item; } else { for (i = 0; i < this.length; i++) { result = result + this[i]; } } } return result; }; Array.prototype.inject = function() { var acc; //only 1 argument, just the closure if (arguments.length == 1) { acc = this[0]; var i; for (i=1;i result) { result = this[i]; } } return result; }; Array.prototype.min = function() { var i, result = null; for (i = 0; i < this.length; i++) { if (result === null || this[i] < result) { result = this[i]; } } return result; }; Array.prototype.oldToString = Array.prototype.toString; Array.prototype.toString = function() { if (isJsArray(this)) { return this.oldToString(); } else if (this.length > 0) { return '[' + this.join(', ') + ']'; } else { return '[]'; } }; Array.prototype.grep = function(param) { var i, result = gs.list([]); if (param instanceof RegExp) { for (i = 0; i < this.length; i++) { if (gs.match(this[i],param)) { result.add(this[i]); } } return result; } else if (param instanceof Array) { return this.intersect(param); } else if (isFunction(param)) { for (i = 0; i < this.length; i++) { if (param(this[i])) { result.add(this[i]); } } return result; } else { for (i = 0; i < this.length ;i++) { if (this[i]==param) { result.add(this[i]); } } return result; } }; Array.prototype.equals = function(other) { if (!(other instanceof Array) || other.length!=this.length) { return false; } else { var i, result = true; for (i = 0;i < this.length && result; i++) { if (!gs.equals(this[i],other[i])) { result = false; } } return result; } }; Array.prototype.gSjoin = function() { var separator = ''; if (arguments.length == 1) { separator = arguments[0]; } var i, result = ''; for (i = 0; i < this.length; i++) { result = result + this[i]; if ((i + 1) < this.length) { result = result + separator; } } return result; }; Array.prototype.oldSort = Array.prototype.sort; Array.prototype.sort = function() { var modify = true; if (arguments.length > 0 && arguments[0] === false) { modify = false; } var i,copy = []; //Maybe some closure as last parameter var tempFunction = null; if (arguments.length == 2 && isFunction(arguments[1])) { tempFunction = arguments[1]; } if (arguments.length == 1 && isFunction(arguments[0])) { tempFunction = arguments[0]; } //Copy all items for (i=0;i 0 && arguments[0] === false) { modify = false; } var i, copy = []; //Copy all items for (i = 0; i < this.length; i++) { if (!copy.contains(this[i])) { copy.push(this[i]); } } if (modify) { this.length = 0; for (i = 0; i < copy.length; i++) { this[i] = copy[i]; } return this; } else { return gs.list(copy); } }; Array.prototype.oldReverse = Array.prototype.reverse; Array.prototype.reverse = function() { var i, count = 0; if (isJsArray(this)) { return this.oldReverse(); } else if (arguments.length == 1 && arguments[0] === true) { for (i = this.length - 1; i > count; i--) { var temp = this[count]; this[count++] = this[i]; this[i] = temp; } return this; } else { var result = []; for (i = this.length - 1; i >= 0; i--) { result[count++] = this[i]; } return gs.list(result); } }; Array.prototype.take = function(number) { var i, result = []; for (i = 0; i < number; i++) { if (i < this.length) { result[i] = this[i]; } } return gs.list(result); }; Array.prototype.takeWhile = function(closure) { var result = [], i, exit=false; for (i = 0; !exit && i < this.length; i++) { if (closure(this[i])) { result[i] = this[i]; } else { exit = true; } } return gs.list(result); }; Array.prototype.multiply = function(number) { if (number === 0) { return gs.list([]); } else { var i, result = gs.list([]); for (i=0;i 0) { var i; for (i = 0; i < value.length; i++) { if (value[i] instanceof gs.spread) { var values = value[i].values; if (values.length > 0) { var j; for (j = 0; j < values.length; j++) { data.push(values[j]); } } } else { data.push(value[i]); } } } var object = data; object.clazz = {name: 'java.util.ArrayList', simpleName: 'ArrayList'}; applyBaseClassFunctions(object); return object; }; gs.flatten = function(result, list) { list.each(function (it) { if (it instanceof Array) { if (it.length>0) { gs.flatten(result, it); } } else { result.add(it); } }); }; ///////////////////////////////////////////////////////////////// //range - [x..y] from groovy ///////////////////////////////////////////////////////////////// gs.range = function(begin, end, inclusive) { var start = begin; var finish = end; var areChars = (typeof(begin) == 'string'); if (areChars) { start = start.charCodeAt(0); finish = finish.charCodeAt(0); } var reverse = false; if (finish < start) { var oldStart = start; start = finish; finish = oldStart; reverse = true; if (!inclusive) { start = start + 1; } } else { if (!inclusive) { finish = finish - 1; } } var result,number,count; for (result=[], number = start, count = 0 ; number <= finish ; number++, count++) { if (areChars) { result[count] = String.fromCharCode(number); } else { result[count] = number; } } if (reverse) { result = result.reverse(); } var object = gs.list(result); object.toList = function() { return gs.list(this.values()); }; return object; }; ///////////////////////////////////////////////////////////////// //date - Date() object from groovy / java ///////////////////////////////////////////////////////////////// gs.date = function() { var gSobject; if (arguments.length == 1) { gSobject = new Date(arguments[0]); } else { gSobject = new Date(); } createClassNames(gSobject, ['java.util.Date']); gSobject.withz = BaseClass.prototype.withz; gSobject.time = gSobject.getTime(); gSobject.setTime = function(milis) { gSobject.time = milis; }; gSobject.year = gSobject.getFullYear(); gSobject.month = gSobject.getMonth(); gSobject.date = gSobject.getDay(); gSobject.plus = function(other) { if (typeof other == 'number') { return gs.date(gSobject.time + (other * 1440000)); } else { return gSobject + other; } }; gSobject.minus = function(other) { if (typeof other == 'number') { return gs.date(gSobject.time - (other * 1440000)); } else { return gSobject - other; } }; gSobject.format = function(rule) { //TODO complete var exit = ''; if (rule) { exit = rule; exit = exit.replaceAll('yyyy', gSobject.getFullYear()); exit = exit.replaceAll('MM', fillZerosLeft(gSobject.getMonth() + 1, 2)); exit = exit.replaceAll('dd', fillZerosLeft(gSobject.getUTCDate(), 2)); exit = exit.replaceAll('HH', fillZerosLeft(gSobject.getHours(), 2)); exit = exit.replaceAll('mm', fillZerosLeft(gSobject.getMinutes(), 2)); exit = exit.replaceAll('ss', fillZerosLeft(gSobject.getSeconds(), 2)); exit = exit.replaceAll('yy', lastChars(gSobject.getFullYear(), 2)); } return exit; }; gSobject.parse = function(rule, text) { //TODO complete var pos = rule.indexOf('MM'); if (pos >= 0) { var newMonth = text.substr(pos, 2) - 1; while (gSobject.getMonth() != newMonth) { gSobject.setMonth(newMonth); } } pos = rule.indexOf('dd'); if (pos >= 0) { var newDay = text.substr(pos, 2); while (gSobject.getUTCDate() != newDay) { gSobject.setUTCDate(newDay); } } pos = rule.indexOf('yyyy'); if (pos >= 0) { gSobject.setFullYear(text.substr(pos, 4)); } else { pos = rule.indexOf('yy'); if (pos >= 0) { gSobject.setFullYear(text.substr(pos, 2)); } } pos = rule.indexOf('HH'); if (pos >= 0) { gSobject.setHours(text.substr(pos, 2)); } pos = rule.indexOf('mm'); if (pos >= 0) { gSobject.setMinutes(text.substr(pos, 2)); } pos = rule.indexOf('ss'); if (pos >= 0) { gSobject.setSeconds(text.substr(pos, 2)); } return gSobject; }; gSobject.clearTime = function() { gSobject.setHours(0, 0, 0, 0); return gSobject; }; gSobject.equals = function(other) { return gSobject.time == other.time; }; gSobject.before = function(other) { return gSobject.time < other.time; }; gSobject.after = function(other) { return gSobject.time > other.time; }; return gSobject; }; gs.rangeFromList = function(list, begin, end) { return list.slice(begin, end + 1); }; function fillZerosLeft(item, size) { var value = item + ''; while (value.length < size) { value = '0' + value; } return value; } function lastChars(item, number) { var value = item + ''; value = value.substring(value.length - number); return value; } ///////////////////////////////////////////////////////////////// //exactMatch - For regular expressions ///////////////////////////////////////////////////////////////// gs.exactMatch = function(text, regExp) { var mock = text; if (regExp instanceof RegExp) { mock = mock.replace(regExp, "#"); } else { mock = mock.replace(new RegExp(regExp), "#"); } return mock == "#"; }; gs.match = function(text, regExp) { var pos; if (regExp instanceof RegExp) { pos = text.search(regExp); } return (pos>=0); }; ///////////////////////////////////////////////////////////////// //regExp - For regular expressions ///////////////////////////////////////////////////////////////// gs.regExp = function(text, ppattern) { var patt; if (ppattern instanceof RegExp) { patt = new RegExp(ppattern.source, 'g'); } else { //g for search all occurences patt = new RegExp(ppattern, 'g'); } var object; var data = patt.exec(text); if (data === null || data === undefined) { return null; } else { var list = gs.list([]); var i = 0; while (data) { if (data instanceof Array && data.length < 2) { list[i] = data[0]; } else { list[i] = gs.list(data); } i = i + 1; data = patt.exec(text); } object = expandWithMetaClass(list, 'RegExp'); } createClassNames(object, ['java.util.regex.Matcher']); object.pattern = patt; object.text = text; object.replaceFirst = function(data) { return this.text.replaceFirst(this[0], data); }; object.replaceAll = function(data) { return this.text.replaceAll(this.pattern, data); }; object.reset = function() { return this; }; return object; }; ///////////////////////////////////////////////////////////////// //Pattern ///////////////////////////////////////////////////////////////// gs.pattern = function(pattern) { var object = gs.init('Pattern'); createClassNames(object, ['java.util.regex.Pattern']); object.value = pattern; return object; }; ///////////////////////////////////////////////////////////////// // Regular Expresions ///////////////////////////////////////////////////////////////// gs.matcher = function(item, regExpression) { var object = gs.init('Matcher'); createClassNames(object, ['java.util.regex.Matcher']); object.data = item; object.regExp = regExpression; object.matches = function() { return gs.exactMatch(this.data, this.regExp); }; return object; }; RegExp.prototype.matcher = function(item) { return gs.matcher(item, this); }; ///////////////////////////////////////////////////////////////// //Number functions ///////////////////////////////////////////////////////////////// Number.prototype.times = function(closure) { var i; for (i = 0; i < this; i++) { closure(i); } }; Number.prototype.upto = function(number, closure) { var i; for (i = this.value; i <= number; i++) { closure(i); } }; Number.prototype.step = function(number, jump, closure) { var i; for (i = this.value; i < number;) { closure(i); i = i + jump; } }; Number.prototype.multiply = function(number) { return this * number; }; Number.prototype.power = function(number) { return Math.pow(this,number); }; Number.prototype.byteValue = Number.prototype.doubleValue = Number.prototype.shortValue = Number.prototype.floatValue = Number.prototype.longValue = function() { return this; }; Number.prototype.intValue = function() { return Math.floor(this); }; ///////////////////////////////////////////////////////////////// //String functions ///////////////////////////////////////////////////////////////// String.prototype.contains = function(value) { return this.indexOf(value) >= 0; }; String.prototype.startsWith = function(value) { return this.indexOf(value) === 0; }; String.prototype.endsWith = function(value) { return this.indexOf(value) > -1 && this.indexOf(value) == (this.length - value.length); }; String.prototype.count = function(value) { var reg = new RegExp(value, 'g'); var result = this.match(reg); if (result) { return result.length; } else { return 0; } }; String.prototype.size = function() { return this.length; }; String.prototype.replaceAll = function(oldValue, newValue) { var reg; if (oldValue instanceof RegExp) { reg = new RegExp(oldValue.source, 'g'); } else { reg = new RegExp(oldValue, 'g'); } return this.replace(reg, newValue); }; String.prototype.replaceFirst = function(oldValue, newValue) { return this.replace(oldValue, newValue); }; String.prototype.reverse = function() { return this.split("").reverse().join(""); }; String.prototype.tokenize = function() { var str = " "; if (arguments.length == 1 && arguments[0]) { str = arguments[0]; } var list = this.split(str); return gs.list(list); }; String.prototype.multiply = function(value) { if (typeof(value) == 'number') { var result = ''; var i; for (i=0; i < (value | 0); i++) { result = result + this; } return result; } }; String.prototype.capitalize = function() { return this.charAt(0).toUpperCase() + this.slice(1); }; String.prototype.each = function(closure) { var list = gs.list(this.split('')); list.each(closure); }; String.prototype.inject = function(initial, closure) { var list = gs.list(this.split('')); return list.inject(initial, closure); }; function getItemsMultiline(text) { var items = text.split('\n'); if (items.length > 1 && items[items.length - 1] === '') { items.splice(items.length - 1, 1); } return items; } String.prototype.eachLine = function(closure) { var i, items = getItemsMultiline(this); for (i = 0; i < items.length; i++) { var item = items[i]; //Closure with 2 arguments, line and count if (closure.length == 2) { closure(item, i); } else { closure(item); } } }; String.prototype.readLines = function() { var items = getItemsMultiline(this); return gs.list(items); }; String.prototype.padRight = function(number) { var sep = ' '; if (arguments.length==2) { sep = arguments[1]; } var item = this; while (item.length < number) { item = item + sep; } return item; }; String.prototype.padLeft = function(number) { var sep = ' '; if (arguments.length == 2) { sep = arguments[1]; } var item = this; while (item.length < number) { item = sep + item; } return item; }; String.prototype.isNumber = function() { if (this.trim() === '') { return false; } else { var res = Number(this); if (isNaN(res)) { return false; } else { return true; } } }; String.prototype.plus = function(other) { var addText = 'null'; if (other !== undefined && other !== null) { if (other['toString'] !== undefined) { addText = other.toString(); } else { addText = other; } } return this + addText; }; String.prototype.toInteger = function() { return parseInt(this); }; ///////////////////////////////////////////////////////////////// // Misc Functions ///////////////////////////////////////////////////////////////// gs.classForName = function(name, obj) { var result = null; try { var pos = name.indexOf("."); while (pos >= 0) { name = name.substring(pos + 1); pos = name.indexOf("."); } result = (typeof globalThis!=="undefined"&&globalThis[name]!==undefined?globalThis[name]:undefined); } catch (err) { result = obj; } return result; }; function StaticMethods(item) { this.gSparent = item; } gs.metaClass = function(item) { var type = typeof item; if (type == "string") { item = new String(item); } else if (type == "number") { item = new Number(item); //If type is a function, it's metaClass from a Class } else if (type === "function") { if (!globalMetaClass[item.name]) { globalMetaClass[item.name] = { gSstatic: new StaticMethods(item), getStatic : function() { return this.gSstatic; } }; } item = globalMetaClass[item.name]; } return item; }; gs.passMapToObject = function(source, destination) { var prop; for (prop in source) { if (isFunction(source[prop])) continue; if (!isMapProperty(prop)) { gs.sp(destination, prop, source[prop]); } } }; gs.equals = function(value1, value2) { if (!hasFunc(value1, 'equals')) { if (hasFunc(value2, 'equals')) { return value2.equals(value1); } else { return value1==value2; } } else { return value1.equals(value2); } }; gs.is = function(value1, value2) { if (value1 !== null && hasFunc(value1, 'is')) { var count, params = gs.list([value2]); for (count = 2; count < arguments.length; count++) { params.add(arguments[count]); } return gs.mc(value1, 'is', params); } else { return value1 == value2; } }; function interceptClosureCall(func, param) { if ((param instanceof Array) && func.length > 1) { return func.apply(func, param); } else { return func(param); } } gs.random = function() { var object = gs.init('Random'); object.nextInt = function(number) { var ran = Math.ceil(Math.random()*number); return ran - 1; }; object.nextBoolean = function() { var ran = Math.random(); return ran < 0.5; }; return object; }; gs.bool = function(item) { if (item && item.isEmpty !== undefined) { return !item.isEmpty(); } else { if (item) { if (item['asBoolean']) { return item['asBoolean'](); } else if (typeof(item) == 'number' && item === 0) { return false; } else if (typeof(item) == 'string') { return item !== ''; } } return item; } }; gs.less = function(itemLeft, itemRight) { return itemLeft < itemRight; }; gs.greater = function(itemLeft, itemRight) { return itemLeft > itemRight; }; // Operator <=> gs.spaceShip = function(itemLeft, itemRight) { if (gs.equals(itemLeft, itemRight)) { return 0; } if (gs.less(itemLeft, itemRight)) { return -1; } if (gs.greater(itemLeft, itemRight)) { return 1; } }; //InstanceOf function gs.instanceOf = function(item, name) { var gotIt = false; if (name == "String") { return typeof(item) == 'string'; } else if (name == "Number") { return typeof(item) == 'number'; } else if (item.clazz) { var classInfo; classInfo = item.clazz; while (classInfo && !gotIt) { if (classInfoContainsName(classInfo, name)) { gotIt = true; } else { classInfo = classInfo.superclass; } } if (!gotIt && item.clazz.interfaces) { var i; for (i = 0; i < item.clazz.interfaces.length && !gotIt; i++) { if (classInfoContainsName(item.clazz.interfaces[i], name)) { gotIt = true; } } } } else if (isFunction(item) && name == 'Closure') { gotIt = true; } return gotIt; }; function classInfoContainsName(classInfo, name) { return classInfo.name == name || classInfo.simpleName == name; } //Elvis operator gs.elvis = function(booleanExpression, trueExpression, falseExpression) { if (gs.bool(booleanExpression)) { return trueExpression; } else { return falseExpression; } }; // * operator gs.multiply = function(a, b) { if (!hasFunc(a, 'multiply')) { return a * b; } else { return a.multiply(b); } }; // / operator gs.div = function(a, b) { if (!hasFunc(a, 'div')) { return a / b; } else { return a.div(b); } }; // ** operator gs.power = function(a, b) { if (!hasFunc(a, 'power')) { return Math.pow(a, b); } else { return a.power(b); } }; // mod operator gs.mod = function(a, b) { if (!hasFunc(a, 'mod')) { return a % b; } else { return a.mod(b); } }; // + operator gs.plus = function(a, b) { if (!hasFunc(a, 'plus')) { if ((typeof a == 'number') && (typeof b == 'number') && (a + b < 1)) { return ((a * 1000) + (b * 1000)) / 1000; } else { return a + b; } } else { return a.plus(b); } }; // - operator gs.minus = function(a, b) { if (!hasFunc(a, 'minus')) { return a - b; } else { return a.minus(b); } }; // in operator gs.gSin = function(item, group) { if (group && (isFunction(group.contains))) { return group.contains(item); } else { return false; } }; //For some special cases where access a property with this."${name}" //This can be a closure gs.thisOrObject = function(thisItem, objectItem) { return objectItem || thisItem; }; // spread operator (*) gs.spread = function(item) { if (item && item instanceof Array) { this.values = item; } }; ///////////////////////////////////////////////////////////////// // Beans functions - From groovy beans ///////////////////////////////////////////////////////////////// //If an object has a function by name function hasFunc(item, name) { if (item === null || item === undefined || item[name] === undefined || (!isFunction(item[name]))) { return false; } else { return true; } } //Set a property of a class gs.sp = function(item, nameProperty, value) { if (nameProperty == 'setProperty') { item[nameProperty] = value; } else if (nameProperty == 'getProperty') { item[nameProperty] = value; } else if (item !== null && item instanceof StaticMethods) { item[nameProperty] = value; item.gSparent[nameProperty] = value; } else { if (nameProperty === 'methodMissing' && value) { item[nameProperty] = value; } else if (!item['setProperty']) { var nameFunction = 'set' + nameProperty.charAt(0).toUpperCase() + nameProperty.slice(1); if (!item[nameFunction]) { if (item[nameProperty] === undefined && item.setPropertyMissing !== undefined && isFunction(item.setPropertyMissing)) { item.setPropertyMissing(nameProperty, value); } else { item[nameProperty] = value; } } else { item[nameFunction](value); } } else { item.setProperty(nameProperty,value); } } }; //Get a property of a class gs.gp = function(item, nameProperty, inDelegates) { //It's a get with safe operator as item?.data if (arguments.length == 3) { if (item === null || item === undefined) { return null; } } else if (item == null || item === undefined) { throw 'gs.gp Get property: ' + nameProperty + ' on null or undefined object.' } if (!item['getProperty']) { return propFromObject(item, nameProperty, inDelegates); } else { var res = item.getProperty(nameProperty); return (res !== undefined ? res : propFromObject(item, nameProperty, inDelegates)) } }; function propFromObject(item, nameProperty, inDelegates) { var nameFunction = 'get' + nameProperty.charAt(0).toUpperCase() + nameProperty.slice(1); if (!item[nameFunction]) { if (nameProperty == 'size' && isFunction(item[nameProperty])) { return item[nameProperty](); } else { if (item[nameProperty] !== undefined) { return item[nameProperty]; } else { //Lets check gp in @Delegate if (item.clazz !== undefined) { var addDelegate = mapAddDelegate[item.clazz.simpleName]; if (addDelegate !== null && addDelegate !== undefined) { var i; for (i = 0; i < addDelegate.length; i++) { var prop = addDelegate[i]; var target = item[prop][nameProperty]; if (target !== undefined) { return item[prop][nameProperty]; } } } } //Default value of a map if (item.gSdefaultValue !== undefined && (isFunction(item.gSdefaultValue))) { item[nameProperty] = item.gSdefaultValue(); } //Maybe in categories if (categories.length > 0 && item[nameProperty] === undefined) { var whereExecutes = categorySearching(nameFunction); if (whereExecutes !== null) { return whereExecutes[nameFunction].apply(item, [item]); } } if (item.propertyMissing !== undefined && isFunction(item.propertyMissing)) { return item.propertyMissing(nameProperty); } else { if (!inDelegates && delegates.length > 0) { return findPropertyInDelegates(nameProperty, item); } else { return item[nameProperty]; } } } } } else { return item[nameFunction](); } } function findPropertyInDelegates(nameProperty, item) { var i = delegates.length; var found = false; var result; while (i > 0 && !found && item ) { i = i - 1; result = gs.gp(delegates[i], nameProperty, true); if (result !== undefined) { found = true; } } return result; } //Control property changes with ++,-- gs.plusPlus = function(item, nameProperty, plus, before) { var value = gs.gp(item, nameProperty); var newValue = value; if (plus) { gs.sp(item, nameProperty, value + 1); newValue++; } else { gs.sp(item, nameProperty, value - 1); newValue--; } if (before) { return newValue; } else { return value; } }; function exFn(we, mn, it, val) { return we[mn].apply(it, joinParameters(it, val)); } //Control all method calls gs.mc = function(item, methodName, values, objectVar, isSafe) { if (gs.consoleInfo && console) { console.log('[INFO] gs.mc (' + item + ').' + methodName + ' params:' + values); } if (item === null || item === undefined) { if (isSafe) { return null; } else { throw 'gs.mc Calling method: ' + methodName + ' on null or undefined object.'; } } if (methodName == 'split' && typeof(item) == 'string') { return item.tokenize(values[0]); } if (methodName == 'length' && typeof(item) == 'string') { return item.length; } if (methodName == 'join' && (item instanceof Array)) { if (values.size() > 0) { return item.gSjoin(values[0]); } else { return item.gSjoin(); } } if (objectVar) { try { //First, try to execute function in object return gs.mc(objectVar, methodName, values); } catch(e) {} } if (!item[methodName]) { if (methodName.startsWith('get') || methodName.startsWith('set')) { var varName = getterSetterRemove(methodName); if (item[varName] !== undefined && !hasFunc(item, varName)) { if (methodName.startsWith('get')) { return gs.gp(item, varName); } else { return gs.sp(item, varName, values[0]); } } } if (methodName.startsWith('is')) { var varName = methodName.charAt(2).toLowerCase() + methodName.slice(3); if (item[varName] !== undefined && !hasFunc(item, varName)) { return gs.gp(item, varName); } } //Check newInstance if (methodName=='newInstance') { return item(); } else { var whereExecutes; //Lets check if in any category we have the static method if (categories.length > 0) { whereExecutes = categorySearching(methodName); if (whereExecutes !== null) { return exFn(whereExecutes, methodName, item, values); } } //In @Category var ob; for (ob in annotatedCategories) { if (annotatedCategories[ob] == item.clazz.simpleName) { var categoryItem = gs.myCategories[ob](); if (categoryItem[methodName] && isFunction(categoryItem[methodName])) { return exFn(categoryItem, methodName, item, values); } } } //Lets check in mixins classes if (mixins.length > 0) { whereExecutes = mixinSearching(item, methodName); if (whereExecutes !== null) { return exFn(whereExecutes, methodName, item, values); } } //Lets check in mixins objects if (mixinsObjects.length > 0) { whereExecutes = mixinObjectsSearching(item, methodName); if (whereExecutes !== null) { return exFn(whereExecutes, methodName, item, values); } } //Lets check mc in @Delegate if (item.clazz !== undefined) { var addDelegate = mapAddDelegate[item.clazz.simpleName]; if (addDelegate) { var i; for (i = 0; i < addDelegate.length; i++) { var prop = addDelegate[i]; var target = item[prop][methodName]; if (target !== undefined) { return exFn(item[prop], methodName, item[prop], values); } } } } //Lets check in delegate if (delegates.length > 0) { var delegateFunc = delegatesFunc(methodName); if (delegateFunc) { return delegateFunc[methodName].apply(item, values); } } if (item.methodMissing) { return item.methodMissing(methodName, values); } else if (delegates.length > 0 && delegatesFunc('methodMissing')) { return gs.mc(delegatesFunc('methodMissing'), methodName, values); } else { if (item.invokeMethod && item.invokeMethod !== BaseClass.prototype.invokeMethod) { return item.invokeMethod(methodName, values); } else { //Maybe there is a function in the script with the name of the method //In Node.js 'this.xxFunction()' in the main context fails if (isFunction((typeof globalThis!=="undefined"&&typeof globalThis[methodName]==="function"?globalThis[methodName]:undefined))) { return (typeof globalThis!=="undefined"&&typeof globalThis[methodName]==="function"?globalThis[methodName]:undefined).apply(this, values); } //Not exist the method, throw exception throw 'gs.mc Method ' + methodName + ' not exist in ' + item; } } } } else { var f = item[methodName]; if (f['apply']) { return f.apply(item, values); } else { return gs.execCall(f, item, values); } } }; function delegatesFunc(nameMethod) { var result = null; if (delegates.length > 0) { var i; for (i = delegates.length - 1; i >= 0 && !result; i--) { if (delegates[i][nameMethod]) { result = delegates[i]; } } } return result; } function joinParameters(item, items) { var listParameters = [item],i; for (i=0; i < items.size(); i++) { listParameters.push(items[i]); } return listParameters; } //////////////////////////////////////////////////////////// // Categories //////////////////////////////////////////////////////////// gs.categoryUse = function(item, itemClass, closure) { var ob, categoryCreated; if (existAnnotatedCategory(item)) { categoryCreated = gs.myCategories[item](); for (ob in categoryCreated) { if (!isObjectProperty(ob) && !isConstructor(ob, categoryCreated[ob]) && isFunction(categoryCreated[ob])) { addFunctionToClassIfPrototyped(ob, categoryCreated[ob], annotatedCategories[item]); } } } else { categories.push(itemClass); } closure(); if (existAnnotatedCategory(item)) { categoryCreated = gs.myCategories[item](); for (ob in categoryCreated) { if (!isObjectProperty(ob) && !isConstructor(ob, categoryCreated[ob]) && isFunction(categoryCreated[ob])) { removeFunctionToClass(ob, categoryCreated[ob], annotatedCategories[item]); } } } else { categories.splice(categories.length - 1, 1); } }; function getPrototypeOfClass(className) { if (className == 'String') { return String.prototype; } if (className == 'Number') { return Number.prototype; } if (className == 'ArrayList') { return Array.prototype; } return null; } function addFunctionToClassIfPrototyped(name, func, className) { var proto = getPrototypeOfClass(className); if (proto !== null) { if (proto[name] === undefined) { proto[name] = func; } } } function removeFunctionToClass(name, func, className) { var proto = getPrototypeOfClass(className); if (proto !== null) { if (proto[name] == func) { proto[name] = null; } } } function categorySearching(methodName) { var i, result = null; for (i = categories.length - 1; i >= 0 && result === null; i--) { var itemClass = categories[i]; if (itemClass[methodName]) { result = itemClass; } } return result; } function existAnnotatedCategory(name) { return (annotatedCategories[name] !== null && annotatedCategories[name] !== undefined); } var annotatedCategories = {}; gs.addAnnotatedCategory = function(nameCategory, nameClass) { annotatedCategories[nameCategory] = nameClass; }; //////////////////////////////////////////////////////////// // Mixins //////////////////////////////////////////////////////////// gs.mixinClass = function(item, classes) { //First check in that class has mixins var gotIt = false; if (mixins.length > 0) { var i; for (i = 0; i < mixins.length && !gotIt; i++) { if (mixins[i].name == item) { var j; for (j=0; j < classes.length; j++) { mixins[i].items.push(classes[j]); } gotIt = true; } } } if (!gotIt) { mixins.push({ name: item, items: classes}); } }; gs.mixinObject = function(item, classes) { var gotIt = false; if (mixinsObjects.length > 0) { var i; for (i = 0; i < mixinsObjects.length && !gotIt; i++) { if (mixinsObjects[i].item == item) { var j; for (j = 0; j < classes.length; j++) { mixinsObjects[i].items.push(classes[j]); } gotIt = true; } } } if (!gotIt) { mixinsObjects.push({ item: item, items: classes}); } //TODO make any kinda cleanup if mixinsObjects growing }; function mixinSearching(item, methodName) { var result = null, className = null; if (typeof(item) == 'string') { className = 'String'; } if (item.clazz && item.clazz.simpleName && typeof(item) == 'object') { className = item.clazz.simpleName; } if (className !== null) { var i, ourMixin=null; for (i = mixins.length - 1; i >= 0 && ourMixin === null; i--) { var data = mixins[i]; if (data.name == className) { ourMixin = data.items; } } if (ourMixin !== null) { for (i = 0; i < ourMixin.length && result === null; i++) { if (ourMixin[i][methodName]) { result = ourMixin[i]; } else { var classItem = ourMixin[i](); if (classItem) { var notStatic = classItem[methodName]; if (notStatic !== null && isFunction(notStatic)) { result = classItem; } } } } } } return result; } function mixinObjectsSearching(item, methodName) { var result = null, i, ourMixin = null; for (i = mixinsObjects.length - 1; i >= 0 && ourMixin === null; i--) { var data = mixinsObjects[i]; if (data.item == item) { ourMixin = data.items; } } if (ourMixin !== null) { for (i=0 ; i < ourMixin.length && result === null; i++) { if (ourMixin[i][methodName]) { result = ourMixin[i]; } } } return result; } //////////////////////////////////////////////////////////// // StringBuffer - very basic support, for add with << //////////////////////////////////////////////////////////// gs.stringBuffer = function() { var object = gs.init('StringBuffer'); object.value = ''; if (arguments.length == 1 && typeof arguments[0] === 'string') { object.value = arguments[0]; } object.toString = function() { return this.value; }; object.leftShift = function(value) { return this.append(value); }; object.plus = function(value) { return this.append(value); }; object.size = function() { return this.value.length; }; object.append = function(value) { this.value = this.value + value; return this; }; return object; }; //////////////////////////////////////////////////////////// // @Delegate //////////////////////////////////////////////////////////// gs.astDelegate = function (baseClass, nameField) { var currentDelegate = mapAddDelegate[baseClass]; if (currentDelegate === null || currentDelegate === undefined) { currentDelegate = []; } currentDelegate.push(nameField); mapAddDelegate[baseClass] = currentDelegate; }; //////////////////////////////////////////////////////////// // Delegate //////////////////////////////////////////////////////////// function applyDelegate (func, delegate, params) { delegates.push(delegate); var result = func.apply(delegate, params); delegates.pop(); return result; } gs.execCall = function (func, thisObject, params) { if (func.delegate !== undefined) { return applyDelegate(func, func.delegate, params); } else { if (func['call'] !== undefined && typeof func === 'object') { return func['call'].apply(func, params); } else { return func.apply(thisObject, params); } } }; //////////////////////////////////////////////////////////// // Functional //////////////////////////////////////////////////////////// Function.prototype.curry = function () { var slice = Array.prototype.slice, args = slice.apply(arguments), that = this; return function () { return that.apply(null, args.concat(slice.apply(arguments))); }; }; Function.prototype.rcurry = function () { var slice = Array.prototype.slice, args = slice.apply(arguments), that = this; return function () { return that.apply(null, (slice.apply(arguments)).concat(args)); }; }; Function.prototype.ncurry = function () { var slice = Array.prototype.slice, args = slice.apply(arguments, [1]), begin = arguments[0], that = this; return function () { return that.apply(null, slice.apply(arguments, [0, begin]).concat(args).concat(slice.apply(arguments, [begin]))); }; }; Function.prototype.leftShift = function () { var func = arguments[0], that = this; return function () { return that(func.apply(null, arguments)); }; }; Function.prototype.rightShift = function () { var func = arguments[0], that = this; return function () { return func(that.apply(null, arguments)); }; }; Function.prototype.run = function() { return this(); }; Function.prototype.memoize = function() { var that = this; that._input = []; that._output = []; return function() { var i, result, foundPos = -1, inputs = Array.prototype.slice.call(arguments); for (i = 0; i < that._input.length && foundPos < 0; i++) { if (gs.equals(inputs, that._input[i])) { foundPos = i; } } if (foundPos > -1) { result = that._output[foundPos]; } else { that._input.push(inputs); result = that.apply(null, inputs); that._output.push(result); } return result; }; }; //MISC Find scope of a var gs.fs = function(name, thisScope, objScope) { if (objScope && objScope[name] !== undefined) { return objScope[name]; } else if (thisScope && thisScope[name] !== undefined) { return thisScope[name]; } else { var value = gs.gp(thisScope, name); if (value === undefined) { if (aStT && aStT[name] !== undefined) { return aStT[name]; } else { var func = new Function("return " + name); return func(); } } else { return value; } } }; //Convert a groovy object to javascript, but only properties gs.toJavascript = function(obj) { if (obj && gs.isGroovyObj(obj)) { var result; if (obj && !isFunction(obj)) { if (obj instanceof Array) { result = []; var i; for (i = 0; i < obj.length; i++) { result.push(gs.toJavascript(obj[i])); } } else { if (obj instanceof Object) { result = {}; var ob; for (ob in obj) { if (!isMapProperty(ob) && !isFunction(obj[ob])) { result[ob] = gs.toJavascript(obj[ob]); } } } else { result = obj; } } } return result; } else { return obj; } }; //Convert a javascript object to 'groovy', if you define groovy type, will use it, and not a map gs.toGroovy = function(obj, objClass) { var result; if (obj !== undefined && !isFunction(obj)) { if (obj instanceof Array) { result = gs.list([]); var i; for (i = 0; i < obj.length; i++) { result.add(gs.toGroovy(obj[i], objClass)); } } else { if (obj instanceof Object) { var ob; result = (objClass ? objClass() : gs.map()); for (ob in obj) { result[ob] = gs.toGroovy(obj[ob]); } } else { result = obj; } } } return result; }; gs.toNumber = function(number) { if (number) { if (typeof(number) == 'string') { return parseFloat(number); } else { return number; } } }; gs.isGroovyObj = function(maybeGroovyObject) { return maybeGroovyObject !== null && maybeGroovyObject !== undefined && maybeGroovyObject.clazz !== undefined; }; gs.execStatic = function(obj, methodName, thisObject, params) { var old = aStT; aStT = thisObject; var res = obj[methodName].apply(thisObject, params); aStT = old; return res; }; gs.asChar = function(value) { return value.charCodeAt(0); }; //Convert a groovy map to javascript object, including functions in the map gs.toJsObj = function(obj) { if (gs.isGroovyObj(obj)) { var ob, result = {}; for (ob in obj) { if (!isMapProperty(ob)) { if (isFunction(obj[ob])) { result[ob] = obj[ob]; } else { result[ob] = gs.toJsObj(obj[ob]); } } } return result; } else { return obj; } }; }).call(this);function HtmlBuilder() { var gSobject = gs.init('HtmlBuilder'); gSobject.clazz = { name: 'org.grooscript.builder.HtmlBuilder', simpleName: 'HtmlBuilder'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.tagSolver = function(name, args) { gSobject.htmCd += "<" + (name) + ""; if ((((gs.bool(args)) && (gs.mc(args,"size",[]) > 0)) && (!gs.bool(gs.instanceOf((args[0]), "String")))) && (!gs.bool(gs.instanceOf((args[0]), "Closure")))) { gs.mc(args[0],"each",[function(key, value) { return gSobject.htmCd += " " + (key) + "='" + (value) + "'"; }]); }; gSobject.htmCd += (!gs.bool(args) ? "/>" : ">"); if (gs.bool(args)) { if ((gs.equals(gs.mc(args,"size",[]), 1)) && (gs.instanceOf((args[0]), "String"))) { gs.mc(gSobject,"yield",[args[0]]); } else { var lastArg = gs.mc(args,"last",[]); if (gs.instanceOf(lastArg, "Closure")) { gs.sp(lastArg,"delegate",this); gs.execCall(lastArg, this, []); }; if ((gs.instanceOf(lastArg, "String")) && (gs.mc(args,"size",[]) > 1)) { gs.mc(gSobject,"yield",[lastArg]); }; }; return gSobject.htmCd += ""; }; }; gSobject.htmCd = null; gSobject.build = function(x0) { return HtmlBuilder.build(x0); } gSobject['yield'] = function(text) { return gs.mc(text,"each",[function(ch) { var gSswitch0 = ch; if (gs.equals(gSswitch0, "&")) { gSobject.htmCd += "&"; ; } else if (gs.equals(gSswitch0, "<")) { gSobject.htmCd += "<"; ; } else if (gs.equals(gSswitch0, ">")) { gSobject.htmCd += ">"; ; } else if (gs.equals(gSswitch0, "\"")) { gSobject.htmCd += """; ; } else if (gs.equals(gSswitch0, "'")) { gSobject.htmCd += "'"; ; } else { gSobject.htmCd += ch; ; }; }]); } gSobject['yieldUnescaped'] = function(text) { return gSobject.htmCd += text; } gSobject['comment'] = function(text) { return gSobject.htmCd += (gs.plus((gs.plus("")); } gSobject['newLine'] = function(it) { return gSobject.htmCd += "\n"; } gSobject['methodMissing'] = function(name, args) { gs.sp(this,"" + (name) + "",function(ars) { if (arguments.length == 1 && arguments[0] instanceof Array) { ars=gs.list(arguments[0]); } else if (arguments.length == 1) { ars=gs.list([arguments[1 - 1]]); } else if (arguments.length < 1) { ars=gs.list([]); } else if (arguments.length > 1) { ars=gs.list([ars]); for (gScount=1;gScount < arguments.length; gScount++) { ars.add(arguments[gScount]); } } return gs.mc(gSobject,"tagSolver",[name, ars]); }); return gs.mc(this,"invokeMethod",[name, args], gSobject); } gSobject['HtmlBuilder0'] = function(it) { gSobject.htmCd = ""; return this; } if (arguments.length==0) {gSobject.HtmlBuilder0(); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; HtmlBuilder.build = function(closure) { var mc = gs.expandoMetaClass(HtmlBuilder, false, true); gs.mc(mc,"initialize",[]); var builder = HtmlBuilder(); gs.sp(builder,"metaClass",mc); gs.sp(closure,"delegate",builder); gs.execCall(closure, this, []); return gs.gp(builder,"htmCd"); } function Observable() { var gSobject = gs.init('Observable'); gSobject.clazz = { name: 'org.grooscript.rx.Observable', simpleName: 'Observable'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.subscribers = gs.list([]); gSobject.sourceList = null; gSobject.chain = gs.list([]); gSobject.listen = function() { return Observable.listen(); } gSobject.from = function(x0) { return Observable.from(x0); } gSobject['produce'] = function(event) { return gs.mc(gSobject.subscribers,"each",[function(it) { return gs.mc(gSobject,"processFunction",[event, it]); }]); } gSobject['map'] = function(cl) { gs.mc(gSobject.chain,'leftShift', gs.list([cl])); return this; } gSobject['filter'] = function(cl) { gs.mc(gSobject.chain,'leftShift', gs.list([function(it) { if (gs.execCall(cl, this, [it])) { return it; } else { throw "Exception"; }; }])); return this; } gSobject['subscribe'] = function(cl) { while (gs.bool(gSobject.chain)) { cl = (gs.mc(cl,'leftShift', gs.list([gs.mc(gSobject.chain,"pop",[])]))); }; gs.mc(gSobject.subscribers,'leftShift', gs.list([cl])); if (gs.bool(gSobject.sourceList)) { return gs.mc(gSobject.sourceList,"each",[function(it) { return gs.mc(gSobject,"processFunction",[it, cl]); }]); }; } gSobject['removeSubscribers'] = function(it) { return gSobject.subscribers = gs.list([]); } gSobject['processFunction'] = function(data, cl) { try { gs.execCall(cl, this, [data]); } catch (e) { } ; } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; Observable.listen = function(it) { return Observable(); } Observable.from = function(list) { return Observable(gs.map().add("sourceList",list)); } function GQueryImpl() { var gSobject = gs.init('GQueryImpl'); gSobject.clazz = { name: 'org.grooscript.jquery.GQueryImpl', simpleName: 'GQueryImpl'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.clazz.interfaces = [{ name: 'org.grooscript.jquery.GQuery', simpleName: 'GQuery'}]; gSobject['bind'] = function(selector, target, nameProperty, closure) { if (closure === undefined) closure = null; return gs.mc(gs.execStatic(GQueryList,'of', this,[selector]),"bind",[target, nameProperty, closure]); } gSobject['bindProperty'] = function(selector, target, nameProperty, parent) { if (parent === undefined) parent = null; return gs.mc(gs.mc(gSobject,"resolveSelector",[selector, parent]),"bind",[target, nameProperty]); } gSobject['existsSelector'] = function(selector, parent) { if (parent === undefined) parent = null; return gs.mc(gs.mc(gSobject,"resolveSelector",[selector, parent]),"hasResults",[]); } gSobject['existsId'] = function(id, parent) { if (parent === undefined) parent = null; return gs.mc(gs.mc(gSobject,"resolveSelector",["#" + (id) + "", parent]),"hasResults",[]); } gSobject['existsName'] = function(name, parent) { if (parent === undefined) parent = null; return gs.mc(gs.mc(gSobject,"resolveSelector",["[name='" + (name) + "']", parent]),"hasResults",[]); } gSobject['existsGroup'] = function(name, parent) { if (parent === undefined) parent = null; return gs.mc(gs.mc(gSobject,"resolveSelector",["input:radio[name='" + (name) + "']", parent]),"hasResults",[]); } gSobject['onEvent'] = function(selector, nameEvent, func, parent) { if (parent === undefined) parent = null; return gs.mc(gs.mc(gSobject,"resolveSelector",[selector, parent]),"onEvent",[nameEvent, func]); } gSobject.doRemoteCall = function(url, type, params, onSuccess, onFailure, objectResult) { if (objectResult === undefined) objectResult = null; $.ajax({ type: type, //GET or POST data: gs.toJavascript(params), url: url, dataType: 'text' }).done(function(newData) { if (onSuccess) { onSuccess(gs.toGroovy(jQuery.parseJSON(newData), objectResult)); } }) .fail(function(error) { if (onFailure) { onFailure(error); } }); } gSobject.onReady = function(func) { $(document).ready(func); } gSobject['attachMethodsToDomEvents'] = function(obj, parent) { if (parent === undefined) parent = null; return gs.mc(gs.gp((obj = gs.metaClass(obj)),"methods"),"each",[function(method) { if (gs.mc(gs.gp(method,"name"),"endsWith",["Click"])) { var shortName = gs.mc(gs.gp(method,"name"),"substring",[0, gs.minus(gs.mc(gs.gp(method,"name"),"length",[]), 5)]); if (gs.mc(gSobject,"existsId",[shortName, parent])) { gs.mc(gSobject,"onEvent",[gs.plus("#", shortName), "click", obj["" + (gs.gp(method,"name")) + ""], parent]); }; }; if (gs.mc(gs.gp(method,"name"),"endsWith",["Submit"])) { var shortName = gs.mc(gs.gp(method,"name"),"substring",[0, gs.minus(gs.mc(gs.gp(method,"name"),"length",[]), 6)]); if (gs.mc(gSobject,"existsId",[shortName, parent])) { gs.mc(gSobject,"onEvent",[gs.plus("#", shortName), "submit", gs.mc(obj["" + (gs.gp(method,"name")) + ""],'leftShift', gs.list([function(it) { return gs.mc(it,"preventDefault",[]); }])), parent]); }; }; if (gs.mc(gs.gp(method,"name"),"endsWith",["Change"])) { var shortName = gs.mc(gs.gp(method,"name"),"substring",[0, gs.minus(gs.mc(gs.gp(method,"name"),"length",[]), 6)]); if (gs.mc(gSobject,"existsId",[shortName, parent])) { return gs.mc(gSobject,"onChange",[gs.plus("#", shortName), obj["" + (gs.gp(method,"name")) + ""], parent]); }; }; }]); } gSobject['onChange'] = function(selector, closure, parent) { if (parent === undefined) parent = null; return gs.mc(gs.mc(gSobject,"resolveSelector",[selector, parent]),"onChange",[closure]); } gSobject['focusEnd'] = function(selector, parent) { if (parent === undefined) parent = null; return gs.mc(gs.mc(gSobject,"resolveSelector",[selector, parent]),"focusEnd",[]); } gSobject['bindAllProperties'] = function(target, parent) { if (parent === undefined) parent = null; return gs.mc(gs.gp(target,"properties"),"each",[function(name, value) { if (gs.mc(gSobject,"existsId",[name, parent])) { gs.mc(gSobject,"bindProperty",["#" + (name) + "", target, name, parent]); }; if (gs.mc(gSobject,"existsName",[name, parent])) { gs.mc(gSobject,"bindProperty",["[name='" + (name) + "']", target, name, parent]); }; if (gs.mc(gSobject,"existsGroup",[name, parent])) { return gs.mc(gSobject,"bindProperty",["input:radio[name='" + (name) + "']", target, name, parent]); }; }]); } gSobject['bindAll'] = function(target, parent) { if (parent === undefined) parent = null; gs.mc(gSobject,"bindAllProperties",[target, parent]); return gs.mc(gSobject,"attachMethodsToDomEvents",[target, parent]); } gSobject['observeEvent'] = function(selector, nameEvent, data) { if (data === undefined) data = gs.map(); var observable = gs.execStatic(Observable,'listen', this,[]); gs.mc(gs.execCall(this, this, [selector]),"on",[nameEvent, data, function(event) { return gs.mc(observable,"produce",[event]); }]); return observable; } gSobject['call'] = function(selector) { return gs.execStatic(GQueryList,'of', this,[selector]); } gSobject['resolveSelector'] = function(selector, parent) { return gs.execStatic(GQueryList,'of', this,[(parent != null ? gs.mc(parent,"find",[selector]) : selector)]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function GQueryList() { var gSobject = gs.init('GQueryList'); gSobject.clazz = { name: 'org.grooscript.jquery.GQueryList', simpleName: 'GQueryList'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.list = null; gSobject.of = function(x0) { return GQueryList.of(x0); } gSobject.methodMissing = function(name, args) { return gSobject.list[name].apply(gSobject.list, args); } gSobject.withResultList = function(cl) { if (gSobject.list.length) { cl(gSobject.list.toArray()); } return gSobject; } gSobject.hasResults = function() { return gSobject.list.length > 0; } gSobject.onEvent = function(nameEvent, cl) { gSobject.list.on(nameEvent, cl); return gSobject; } gSobject.onChange = function(cl) { var jq = gSobject.list; if (jq.is(":text")) { jq.bind('input', function() { cl($(this).val()); }); } else if (jq.is('textarea')) { jq.bind('input propertychange', function() { cl($(this).val()); }); } else if (jq.is(":checkbox")) { jq.change(function() { cl($(this).is(':checked')); }); } else if (jq.is(":radio")) { jq.change(function() { cl($(this).val()); }); } else if (jq.is("select")) { jq.bind('change', function() { cl($(this).val()); }); } else { console.log('Not supporting onChange for jquery element'); console.log(jq); } return gSobject; } gSobject.focusEnd = function() { var jq = gSobject.list; if (jq.length) { if (jq.is(":text") || jq.is('textarea')) { var originalValue = jq.val(); jq.val(''); jq.blur().focus().val(originalValue); } else { jq.focus(); } } return gSobject; } gSobject.bind = function(target, nameProperty, closure) { if (closure === undefined) closure = null; var jq = gSobject.list; //Create set method var nameSetMethod = 'set'+nameProperty.capitalize(); if (jq.is(":text")) { target[nameSetMethod] = function(newValue) { this[nameProperty] = newValue; jq.val(newValue); if (closure) { closure(newValue); }; }; jq.bind('input', function() { var currentVal = $(this).val(); target[nameProperty] = currentVal; if (closure) { closure(currentVal); }; }); } else if (jq.is('textarea')) { target[nameSetMethod] = function(newValue) { this[nameProperty] = newValue; jq.val(newValue); if (closure) { closure(newValue); }; }; jq.bind('input propertychange', function() { var currentVal = $(this).val(); target[nameProperty] = currentVal; if (closure) { closure(currentVal); }; }); } else if (jq.is(":checkbox")) { target[nameSetMethod] = function(newValue) { this[nameProperty] = newValue; jq.prop('checked', newValue); if (closure) { closure(newValue); }; }; jq.change(function() { var currentVal = $(this).is(':checked'); target[nameProperty] = currentVal; if (closure) { closure(currentVal); }; }); } else if (jq.is(":radio")) { target[nameSetMethod] = function(newValue) { this[nameProperty] = newValue; jq.each(function(idx, elem) { if (elem.value == newValue) { $(elem).prop('checked', true) } }); if (closure) { closure(newValue); }; }; jq.change(function() { var currentVal = $(this).val(); target[nameProperty] = currentVal; if (closure) { closure(currentVal); }; }); } else if (jq.is("select")) { target[nameSetMethod] = function(newValue) { this[nameProperty] = newValue; jq.val(newValue); if (closure) { closure(newValue); }; }; jq.bind('change', function() { var currentVal = $(this).val(); target[nameProperty] = currentVal; if (closure) { closure(currentVal); }; }); } else { console.log('Not supporting bind for jquery element'); console.log(jq); } return gSobject; } gSobject.jqueryList = function(selec) { return $(selec); } gSobject['GQueryList1'] = function(selecOrJq) { gSobject.list = (gs.instanceOf(selecOrJq, "String") ? gs.mc(gSobject,"jqueryList",[selecOrJq]) : selecOrJq); return this; } if (arguments.length==1) {gSobject.GQueryList1(arguments[0]); } return gSobject; }; GQueryList.of = function(selecOrJq) { return GQueryList(selecOrJq); } function GrooscriptGrails() { var gSobject = gs.init('GrooscriptGrails'); gSobject.clazz = { name: 'org.grooscript.grails.util.GrooscriptGrails', simpleName: 'GrooscriptGrails'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; Object.defineProperty(gSobject, 'remoteUrl', { get: function() { return GrooscriptGrails.remoteUrl; }, set: function(gSval) { GrooscriptGrails.remoteUrl = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'controllerRemoteDomain', { get: function() { return GrooscriptGrails.controllerRemoteDomain; }, set: function(gSval) { GrooscriptGrails.controllerRemoteDomain = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'actionRemoteDomain', { get: function() { return GrooscriptGrails.actionRemoteDomain; }, set: function(gSval) { GrooscriptGrails.actionRemoteDomain = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'count', { get: function() { return GrooscriptGrails.count; }, set: function(gSval) { GrooscriptGrails.count = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'components', { get: function() { return GrooscriptGrails.components; }, set: function(gSval) { GrooscriptGrails.components = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'GRAILS_PROPERTIES', { get: function() { return GrooscriptGrails.GRAILS_PROPERTIES; }, set: function(gSval) { GrooscriptGrails.GRAILS_PROPERTIES = gSval; }, enumerable: true }); gSobject.register = function(x0) { return GrooscriptGrails.register(x0); } gSobject.recover = function(x0) { return GrooscriptGrails.recover(x0); } gSobject.getRemoteDomainClassProperties = function(x0) { return GrooscriptGrails.getRemoteDomainClassProperties(x0); } gSobject.sendClientMessage = function(x0,x1) { return GrooscriptGrails.sendClientMessage(x0,x1); } gSobject.sendWebsocketMessage = function(x0,x1) { return GrooscriptGrails.sendWebsocketMessage(x0,x1); } gSobject.doRemoteCall = function(x0,x1,x2,x3,x4) { return GrooscriptGrails.doRemoteCall(x0,x1,x2,x3,x4); } gSobject.remoteDomainAction = function(x0,x1,x2,x3) { return GrooscriptGrails.remoteDomainAction(x0,x1,x2,x3); } gSobject.createComponent = function(x0,x1) { return GrooscriptGrails.createComponent(x0,x1); } gSobject.findComponentById = function(x0) { return GrooscriptGrails.findComponentById(x0); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; GrooscriptGrails.register = function(component) { var number = GrooscriptGrails.count++; gs.sp(component,"cId",number); (GrooscriptGrails.components["id" + (number) + ""]) = component; return component; } GrooscriptGrails.recover = function(cId) { return GrooscriptGrails.components["id" + (cId) + ""]; } GrooscriptGrails.getRemoteDomainClassProperties = function(remoteDomainClass) { var data; var result = gs.map(); for (data in remoteDomainClass) { if ((typeof remoteDomainClass[data] !== "function") && !GrooscriptGrails.GRAILS_PROPERTIES.contains(data)) { result.add(data, remoteDomainClass[data]); } } return result; } GrooscriptGrails.sendClientMessage = function(channel, message) { var sendMessage = message; if (!gs.isGroovyObj(message)) { sendMessage = gs.toGroovy(message); } gsEvents.sendMessage(channel, sendMessage); } GrooscriptGrails.sendWebsocketMessage = function(channel, message) { var sendMessage = message; if (gs.isGroovyObj(message)) { sendMessage = gs.toJavascript(message); } websocketClient.send(channel, {}, JSON.stringify(sendMessage)); } GrooscriptGrails.doRemoteCall = function(controller, action, params, onSuccess, onFailure) { var url = GrooscriptGrails.remoteUrl; url = url + '/' + controller; if (action !== null) { url = url + '/' + action; } $.ajax({ type: "POST", data: (gs.isGroovyObj(params) ? gs.toJavascript(params) : params), url: url }).done(function(newData) { if (onSuccess !== null && onSuccess !== undefined) { var successData = gs.toGroovy(newData); onSuccess(successData); } }) .fail(function(error) { if (onFailure !== null && onFailure !== undefined) { onFailure(error); } }); } GrooscriptGrails.remoteDomainAction = function(params, onSuccess, onFailure, name) { var url = GrooscriptGrails.remoteUrl + params.url; var data = (gs.isGroovyObj(params.data) ? gs.toJavascript(params.data) : params.data); var type = 'GET'; if (params.action == 'create') { type = 'POST'; } if (params.action == 'update') { type = 'PUT'; } if (params.action == 'delete') { type = 'DELETE'; } if (params.action == 'read' || params.action == 'delete') { data = null; url = url + '/' + params.data.id; } $.ajax({ type: type, data: data, url: url, accepts: 'application/json' }).done(function(newData) { var successData = gs.toGroovy(newData, (typeof globalThis!=="undefined"&&globalThis[name]!==undefined?globalThis[name]:undefined)); if (onSuccess !== null && onSuccess !== undefined) { onSuccess(successData); } }) .fail(function(error) { if (onFailure !== null && onFailure !== undefined) { onFailure(error); } }); } GrooscriptGrails.createComponent = function(componentClass, name) { var component = Object.create(HTMLElement.prototype); component.createdCallback = function() { var shadow = this.createShadowRoot(); var content = this.textContent; var attrs = this.attributes; //name and value var map = {shadowRoot: shadow, content: content}; if (attrs && attrs.length > 0) { for (var i = 0; i < attrs.length; i++) { var element = attrs[i]; map[element.name] = element.value; } } GrooscriptGrails.register(componentClass(map)).render(); }; document.registerElement(name, {prototype: component}); } GrooscriptGrails.findComponentById = function(id) { return gs.gp(gs.mc(GrooscriptGrails.components,"find",[function(key, value) { return gs.equals(gs.gp(value,"id"), id); }]),"value",true); } GrooscriptGrails.remoteUrl = null; GrooscriptGrails.controllerRemoteDomain = "remoteDomain"; GrooscriptGrails.actionRemoteDomain = "doAction"; GrooscriptGrails.count = 0; GrooscriptGrails.components = gs.map(); GrooscriptGrails.GRAILS_PROPERTIES = gs.list(["url" , "class" , "clazz" , "gsName" , "transients" , "constraints" , "mapping" , "hasMany" , "belongsTo" , "validationSkipMap" , "gormPersistentEntity" , "properties" , "gormDynamicFinders" , "all" , "domainClass" , "attached" , "validationErrorsMap" , "dirtyPropertyNames" , "errors" , "dirty" , "count"]); function RemoteDomain() { var gSobject = gs.init('RemoteDomain'); gSobject.clazz = { name: 'org.grooscript.grails.promise.RemoteDomain', simpleName: 'RemoteDomain'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.clazz.interfaces = [{ name: 'org.grooscript.grails.promise.GsPromise', simpleName: 'GsPromise'}]; gSobject.action = null; gSobject.url = null; gSobject.data = null; gSobject.onSuccess = null; gSobject.onFail = null; gSobject.name = null; gSobject.closure = function(it) { var remoteData = gs.map().add("action",gSobject.action).add("url",gSobject.url).add("data",gSobject.data); return gs.execStatic(GrooscriptGrails,'remoteDomainAction', this,[remoteData, gSobject.onSuccess, gSobject.onFail, gSobject.name]); }; gSobject['then'] = function(success, fail) { gSobject.onSuccess = success; gSobject.onFail = fail; gs.sp(gSobject.closure,"delegate",this); return gs.mc(gSobject,"closure",[]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function ClientEventHandler() { var gSobject = gs.init('ClientEventHandler'); gSobject.clazz = { name: 'org.grooscript.grails.event.ClientEventHandler', simpleName: 'ClientEventHandler'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.clazz.interfaces = [{ name: 'org.grooscript.grails.event.EventHandler', simpleName: 'EventHandler'}]; gSobject.mapHandlers = gs.map(); gSobject['sendMessage'] = function(channel, data) { if (gSobject.mapHandlers[channel]) { return gs.mc(gSobject.mapHandlers[channel],"each",[function(action) { return gs.execCall(action, this, [data]); }]); }; } gSobject['onEvent'] = function(channel, action) { if (!gs.bool(gSobject.mapHandlers[channel])) { (gSobject.mapHandlers[channel]) = gs.list([]); }; return gs.mc((gSobject.mapHandlers[channel]),'leftShift', gs.list([action])); } gSobject['close'] = function(it) { return gSobject.mapHandlers = gs.map(); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; var gsEvents = ClientEventHandler(); } // __DYMICO_V1_USER_CODE__ function BootstrapBase() { var gSobject = gs.init('BootstrapBase'); gSobject.clazz = { name: 'BootstrapBase', simpleName: 'BootstrapBase'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.completed = false; gSobject.callbacks = gs.list([]); gSobject['callback'] = function(callback) { if (gs.bool(gSobject.completed)) { return gs.execCall(callback, this, []); }; return gs.mc(gSobject.callbacks,"add",[callback]); } gSobject['runCallbacks'] = function(it) { gSobject.completed = true; return gs.mc(gSobject.callbacks,"each",[function(callback) { return gs.execCall(callback, this, []); }]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function Transmission() { var gSobject = gs.init('Transmission'); gSobject.clazz = { name: 'Transmission', simpleName: 'Transmission'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; Object.defineProperty(gSobject, 'onReady', { get: function() { return Transmission.onReady; }, set: function(gSval) { Transmission.onReady = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'onAuthReady', { get: function() { return Transmission.onAuthReady; }, set: function(gSval) { Transmission.onAuthReady = gSval; }, enumerable: true }); if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; Transmission.onReady = BootstrapBase(); Transmission.onAuthReady = BootstrapBase(); function StartupParams() { var gSobject = gs.init('StartupParams'); gSobject.clazz = { name: 'StartupParams', simpleName: 'StartupParams'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.session = gs.execStatic(Session,'instance', this,[]); Object.defineProperty(gSobject, 'deviceReadyListers', { get: function() { return StartupParams.deviceReadyListers; }, set: function(gSval) { StartupParams.deviceReadyListers = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'bootstrapComplete', { get: function() { return StartupParams.bootstrapComplete; }, set: function(gSval) { StartupParams.bootstrapComplete = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'deviceReady', { get: function() { return StartupParams.deviceReady; }, set: function(gSval) { StartupParams.deviceReady = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'doAuthToken', { get: function() { return StartupParams.doAuthToken; }, set: function(gSval) { StartupParams.doAuthToken = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'supportOfflineStart', { get: function() { return StartupParams.supportOfflineStart; }, set: function(gSval) { StartupParams.supportOfflineStart = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'websocketClientDebug', { get: function() { return StartupParams.websocketClientDebug; }, set: function(gSval) { StartupParams.websocketClientDebug = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'offlineStartFunction', { get: function() { return StartupParams.offlineStartFunction; }, set: function(gSval) { StartupParams.offlineStartFunction = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'onlineStartNoAuthFunction', { get: function() { return StartupParams.onlineStartNoAuthFunction; }, set: function(gSval) { StartupParams.onlineStartNoAuthFunction = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'onlineStartAuthSuccessFunction', { get: function() { return StartupParams.onlineStartAuthSuccessFunction; }, set: function(gSval) { StartupParams.onlineStartAuthSuccessFunction = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'onlineStartTokenAuthFailedFunction', { get: function() { return StartupParams.onlineStartTokenAuthFailedFunction; }, set: function(gSval) { StartupParams.onlineStartTokenAuthFailedFunction = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'beforeSocketInit', { get: function() { return StartupParams.beforeSocketInit; }, set: function(gSval) { StartupParams.beforeSocketInit = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'afterSocketInit', { get: function() { return StartupParams.afterSocketInit; }, set: function(gSval) { StartupParams.afterSocketInit = gSval; }, enumerable: true }); gSobject.shouldCheckStartupAuth = function() { if (typeof checkStartupAuth !== 'undefined') { return checkStartupAuth } return true } gSobject['checkStartupAuth'] = function(it) { if (gs.execStatic(Utils,'getCookie', this,[gs.gp(Socket,"AUTH_TOKEN")])) { gs.println(gs.plus("Writing session auth to local storage:", gs.execStatic(Utils,'getCookie', this,[gs.gp(Socket,"AUTH_TOKEN")]))); gs.mc(gs.fs('localStorage', this, gSobject),"setItem",["authToken", gs.plus((gs.plus("\"", gs.execStatic(Utils,'getCookie', this,[gs.gp(Socket,"AUTH_TOKEN")]))), "\"")]); }; if (gs.execStatic(Utils,'getCookie', this,[gs.gp(Socket,"DEVICE_TOKEN")])) { gs.println(gs.plus("Writing device token to local storage:", gs.execStatic(Utils,'getCookie', this,[gs.gp(Socket,"DEVICE_TOKEN")]))); gs.mc(gs.fs('localStorage', this, gSobject),"setItem",["deviceToken", gs.plus((gs.plus("\"", gs.execStatic(Utils,'getCookie', this,[gs.gp(Socket,"DEVICE_TOKEN")]))), "\"")]); }; if ((gs.mc(gSobject,"shouldCheckStartupAuth",[])) && (gs.bool(StartupParams.doAuthToken))) { gs.println("Checking tokens..."); if ((!gs.bool(gs.gp(gSobject.session,"authToken"))) || (!gs.bool(gs.gp(gSobject.session,"deviceToken")))) { gs.println("Token NOT found"); return null; }; if (gs.mc(Utils,"rememberWindowExpired",[])) { gs.println("Remembered login has expired - clearing cached session"); gs.mc(Utils,"clearRememberedLogin",[]); return null; }; return gs.println("Tokens good"); }; } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; StartupParams.deviceReadyListers = gs.list([]); StartupParams.bootstrapComplete = false; StartupParams.deviceReady = true; StartupParams.doAuthToken = true; StartupParams.supportOfflineStart = false; StartupParams.websocketClientDebug = false; StartupParams.offlineStartFunction = null; StartupParams.onlineStartNoAuthFunction = function(it) { }; StartupParams.onlineStartAuthSuccessFunction = function(it) { return gs.println("NB: onlineStartAuthSuccessFunction NOT SET!"); }; StartupParams.onlineStartTokenAuthFailedFunction = function(it) { gs.println("onlineStartTokenAuthFailedFunction"); return gs.execStatic(Utils,'logout', this,[]); }; StartupParams.beforeSocketInit = function(it) { gs.println(gs.plus("beforeSocketInit:", StartupParams.supportOfflineStart)); if (gs.bool(StartupParams.supportOfflineStart)) { gs.println(gs.plus("beforeSocketInit:session.firstStartupCompleted:", gs.gp(this.session,"firstStartupCompleted"))); gs.println("startupParams.onlineStartFunction:3"); gs.mc(StartupParams,"offlineStartFunction",[]); StartupParams.bootstrapComplete = true; return gs.sp(this.session,"firstStartupCompleted",true); }; }; StartupParams.afterSocketInit = function(it) { gs.println("afterSocketInit"); if (!gs.bool(StartupParams.doAuthToken)) { gs.println("onlineStartNoAuthFunction:0"); gs.mc(StartupParams,"onlineStartNoAuthFunction",[]); StartupParams.bootstrapComplete = true; return null; }; return gs.execStatic(Utils,'tokenAuth', this,[function(it) { gs.println("onlineStartAuthSuccessFunction:1"); gs.mc(StartupParams,"onlineStartAuthSuccessFunction",[]); StartupParams.bootstrapComplete = true; return gs.mc(gs.gp(gs.fs('transmission', this),"onAuthReady"),"runCallbacks",[]); }, function(it) { gs.println("onlineStartTokenAuthFailedFunction:2"); gs.mc(StartupParams,"onlineStartTokenAuthFailedFunction",[]); StartupParams.bootstrapComplete = true; return gs.mc(gs.gp(gs.fs('transmission', this),"onAuthReady"),"runCallbacks",[]); }]); }; function Session() { var gSobject = gs.init('Session'); gSobject.clazz = { name: 'Session', simpleName: 'Session'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; Object.defineProperty(gSobject, 'sessionMap', { get: function() { return Session.sessionMap; }, set: function(gSval) { Session.sessionMap = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'self', { get: function() { return Session.self; }, set: function(gSval) { Session.self = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'zoner', { get: function() { return Session.zoner; }, set: function(gSval) { Session.zoner = gSval; }, enumerable: true }); gSobject.zonerRoleMap = gs.map(); gSobject.instance = function() { return Session.instance(); } gSobject.toJs = function() { return Session.toJs(); } gSobject.setSessionStorage = function(x0,x1) { return Session.setSessionStorage(x0,x1); } gSobject.getSessionStorage = function(x0) { return Session.getSessionStorage(x0); } gSobject.clear = function() { var remember_me = localStorage.getItem('remember_me'); localStorage.clear(); localStorage.setItem('remember_me', remember_me); } gSobject['setProperty'] = function(name, value) { (Session.sessionMap[name]) = value; Session.setSessionStorage(name, value); if (gs.equals(name, "zoner")) { Session.zoner = null; return gSobject.zonerRoleMap = gs.map(); }; } gSobject['getProperty'] = function(name) { if (!gs.bool(Session.sessionMap[name])) { var value = Session.getSessionStorage(name); (Session.sessionMap[name]) = value; }; return Session.sessionMap[name]; } gSobject['hasRole'] = function(roles) { if (!gs.bool(roles)) { return true; }; var result = gSobject.zonerRoleMap[roles]; if (result != null) { return result; }; if (!gs.bool(Session.zoner)) { Session.zoner = gs.mc(gSobject,"getProperty",["zoner"]); }; if (!gs.bool(Session.zoner)) { return false; }; if (gs.instanceOf(roles, "String")) { result = (gs.gSin(roles, gs.gp(Session.zoner,"roles"))); (gSobject.zonerRoleMap[roles]) = result; return result; }; for (_i26 = 0, role = roles[0]; _i26 < roles.length; role = roles[++_i26]) { if (gs.gSin(role, gs.gp(Session.zoner,"roles"))) { (gSobject.zonerRoleMap[roles]) = true; return true; }; }; (gSobject.zonerRoleMap[roles]) = false; return false; } gSobject['toString'] = function(it) { return gs.mc(Session.sessionMap,"toString",[]); } gSobject['Session0'] = function(it) { return this; } if (arguments.length==0) {gSobject.Session0(); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; Session.instance = function(it) { if (!gs.bool(Session.self)) { Session.self = Session(); }; return Session.self; } Session.toJs = function(it) { return Session.sessionMap; } Session.setSessionStorage = function(name, value) { value = JSON.stringify(value) localStorage.setItem(name, value) return value } Session.getSessionStorage = function(name) { var value = localStorage.getItem(name) try{ return gs.toGroovy(jQuery.parseJSON(value)) }catch(all){} return null } Session.sessionMap = gs.map(); Session.self = null; Session.zoner = null; function Modals() { var gSobject = gs.init('Modals'); gSobject.clazz = { name: 'Modals', simpleName: 'Modals'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.showModalCustom = function(x0,x1) { return Modals.showModalCustom(x0,x1); } gSobject.showModal = function(x0) { return Modals.showModal(x0); } gSobject.hideModal = function(x0) { return Modals.hideModal(x0); } gSobject.closeModal = function(x0) { return Modals.closeModal(x0); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; Modals.showModalCustom = function(id, type) { $(id).css("display", type); $(id).css("pointer-events", "initial"); } Modals.showModal = function(id) { $(id).css("display", "block"); $(id).css("pointer-events", "initial"); } Modals.hideModal = function(id) { $(id).css("display", "none"); $(id).css("pointer-events", "none"); } Modals.closeModal = function(id) { $(id).trigger( "click" ); } function Socket() { var gSobject = gs.init('Socket'); gSobject.clazz = { name: 'Socket', simpleName: 'Socket'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; Object.defineProperty(gSobject, 'SOCKET_URL', { get: function() { return Socket.SOCKET_URL; }, set: function(gSval) { Socket.SOCKET_URL = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'SOCKET_USER_URL', { get: function() { return Socket.SOCKET_USER_URL; }, set: function(gSval) { Socket.SOCKET_USER_URL = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'SOCKET_OBJECT_URL', { get: function() { return Socket.SOCKET_OBJECT_URL; }, set: function(gSval) { Socket.SOCKET_OBJECT_URL = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'SOCKET_TOPIC_URL', { get: function() { return Socket.SOCKET_TOPIC_URL; }, set: function(gSval) { Socket.SOCKET_TOPIC_URL = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'SOCKET_OVER_HTTP_SYNCHRONOUS_URL', { get: function() { return Socket.SOCKET_OVER_HTTP_SYNCHRONOUS_URL; }, set: function(gSval) { Socket.SOCKET_OVER_HTTP_SYNCHRONOUS_URL = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'SOCKET_OVER_HTTP_ASYNCHRONOUS_URL', { get: function() { return Socket.SOCKET_OVER_HTTP_ASYNCHRONOUS_URL; }, set: function(gSval) { Socket.SOCKET_OVER_HTTP_ASYNCHRONOUS_URL = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'SESSION_REFRESH_MINS', { get: function() { return Socket.SESSION_REFRESH_MINS; }, set: function(gSval) { Socket.SESSION_REFRESH_MINS = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'SOCKET_CHECK_MSG_RECEIVED_SEC', { get: function() { return Socket.SOCKET_CHECK_MSG_RECEIVED_SEC; }, set: function(gSval) { Socket.SOCKET_CHECK_MSG_RECEIVED_SEC = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'SOCKET_RUNNER_RETRY_MS', { get: function() { return Socket.SOCKET_RUNNER_RETRY_MS; }, set: function(gSval) { Socket.SOCKET_RUNNER_RETRY_MS = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'SOCKET_QUEUE_TIMEOUT_MIN', { get: function() { return Socket.SOCKET_QUEUE_TIMEOUT_MIN; }, set: function(gSval) { Socket.SOCKET_QUEUE_TIMEOUT_MIN = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'AUTH_TOKEN', { get: function() { return Socket.AUTH_TOKEN; }, set: function(gSval) { Socket.AUTH_TOKEN = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'DEVICE_TOKEN', { get: function() { return Socket.DEVICE_TOKEN; }, set: function(gSval) { Socket.DEVICE_TOKEN = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'window', { get: function() { return Socket.window; }, set: function(gSval) { Socket.window = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'navigator', { get: function() { return Socket.navigator; }, set: function(gSval) { Socket.navigator = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'sendProtocol', { get: function() { return Socket.sendProtocol; }, set: function(gSval) { Socket.sendProtocol = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'queue', { get: function() { return Socket.queue; }, set: function(gSval) { Socket.queue = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'socketHeadersMap', { get: function() { return Socket.socketHeadersMap; }, set: function(gSval) { Socket.socketHeadersMap = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'userDataPipe', { get: function() { return Socket.userDataPipe; }, set: function(gSval) { Socket.userDataPipe = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'session', { get: function() { return Socket.session; }, set: function(gSval) { Socket.session = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'connected', { get: function() { return Socket.connected; }, set: function(gSval) { Socket.connected = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'socket', { get: function() { return Socket.socket; }, set: function(gSval) { Socket.socket = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'websocketClient', { get: function() { return Socket.websocketClient; }, set: function(gSval) { Socket.websocketClient = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'subscriptions', { get: function() { return Socket.subscriptions; }, set: function(gSval) { Socket.subscriptions = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'sessionRefresherThreads', { get: function() { return Socket.sessionRefresherThreads; }, set: function(gSval) { Socket.sessionRefresherThreads = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'reconnectCallbacks', { get: function() { return Socket.reconnectCallbacks; }, set: function(gSval) { Socket.reconnectCallbacks = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'socketReadyQueue', { get: function() { return Socket.socketReadyQueue; }, set: function(gSval) { Socket.socketReadyQueue = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'intervalRunner', { get: function() { return Socket.intervalRunner; }, set: function(gSval) { Socket.intervalRunner = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'reconnectMutex', { get: function() { return Socket.reconnectMutex; }, set: function(gSval) { Socket.reconnectMutex = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'SOCKET_PING_TIMEOUT_MS', { get: function() { return Socket.SOCKET_PING_TIMEOUT_MS; }, set: function(gSval) { Socket.SOCKET_PING_TIMEOUT_MS = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'websocketPingCount', { get: function() { return Socket.websocketPingCount; }, set: function(gSval) { Socket.websocketPingCount = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'nextQueueClean', { get: function() { return Socket.nextQueueClean; }, set: function(gSval) { Socket.nextQueueClean = gSval; }, enumerable: true }); gSobject.init = function() { return Socket.init(); } gSobject.socketHeaders = function() { return Socket.socketHeaders(); } gSobject.initSocket = function(x0,x1) { return Socket.initSocket(x0,x1); } gSobject.socketReady = function(x0) { return Socket.socketReady(x0); } gSobject.socketReadyQueueCallAll = function() { return Socket.socketReadyQueueCallAll(); } gSobject.addUserDataPipe = function() { return Socket.addUserDataPipe(); } gSobject.onReconnect = function(x0) { return Socket.onReconnect(x0); } gSobject.fireReconnectCallbacks = function() { return Socket.fireReconnectCallbacks(); } gSobject.startSessionRefresher = function() { return Socket.startSessionRefresher(); } gSobject.sessionRefresher = function(x0,x1) { return Socket.sessionRefresher(x0,x1); } gSobject.reconnect = function(x0) { return Socket.reconnect(x0); } gSobject.socketConnectionInterval = function(x0) { return Socket.socketConnectionInterval(x0); } gSobject.socketConnect = function(x0,x1,x2) { return Socket.socketConnect(x0,x1,x2); } gSobject.pingHttp = function(callback) { if (!this.inUse) { this.status = 'unchecked'; this.inUse = true; this.callback = callback; this.ip = ip; var _that = this; this.img = new Image(); this.img.onload = function () { _that.inUse = false; _that.callback('responded'); }; this.img.onerror = function (e) { if (_that.inUse) { _that.inUse = false; _that.callback('responded', e); } }; this.start = new Date().getTime(); this.img.src = 'http://'+ window.location.hostname + '/index/ping'; this.timer = setTimeout(function () { if (_that.inUse) { _that.inUse = false; _that.callback('timeout'); } }, 1500); } } gSobject.pingWebSocket = function(x0) { return Socket.pingWebSocket(x0); } gSobject.remote = function(x0,x1,x2,x3) { return Socket.remote(x0,x1,x2,x3); } gSobject.callChain = function(x0,x1,x2) { return Socket.callChain(x0,x1,x2); } gSobject.callObject = function(x0,x1,x2,x3,x4) { return Socket.callObject(x0,x1,x2,x3,x4); } gSobject.isDymicoSystemUpdating = function() { return Socket.isDymicoSystemUpdating(); } gSobject.send = function(x0,x1,x2,x3) { return Socket.send(x0,x1,x2,x3); } gSobject.doSend = function(x0,x1) { return Socket.doSend(x0,x1); } gSobject.doSendNativeHttp = function(x0,x1) { return Socket.doSendNativeHttp(x0,x1); } gSobject.doSendNative = function(x0,x1) { return Socket.doSendNative(x0,x1); } gSobject.checkMessageReceived = function(x0) { return Socket.checkMessageReceived(x0); } gSobject.resendMessageQueue = function() { return Socket.resendMessageQueue(); } gSobject.cleanQueue = function() { return Socket.cleanQueue(); } gSobject.receive = function(x0) { return Socket.receive(x0); } gSobject.processException = function(x0) { return Socket.processException(x0); } gSobject.subscribe = function(x0,x1,x2) { return Socket.subscribe(x0,x1,x2); } gSobject.subscribeTopic = function(x0,x1) { return Socket.subscribeTopic(x0,x1); } gSobject.unsubscribeTopic = function(x0) { return Socket.unsubscribeTopic(x0); } gSobject.addSubscription = function(x0,x1,x2) { return Socket.addSubscription(x0,x1,x2); } gSobject.subscribeJs = function(x0,x1,x2) { return Socket.subscribeJs(x0,x1,x2); } gSobject.doReceiveNative = function(x0,x1) { return Socket.doReceiveNative(x0,x1); } gSobject.resubscribeAll = function() { return Socket.resubscribeAll(); } gSobject.unsubscribe = function(x0,x1) { return Socket.unsubscribe(x0,x1); } gSobject.post = function(x0,x1,x2,x3,x4) { return Socket.post(x0,x1,x2,x3,x4); } gSobject.postJson = function(x0,x1,x2,x3) { return Socket.postJson(x0,x1,x2,x3); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; Socket.init = function(it) { gs.sp(Socket.session,"domain",gs.gp(gs.gp(Socket.window,"location"),"hostname")); gs.sp(Socket.session,"incomingUrl",(gs.plus((gs.plus(gs.gp(gs.gp(Socket.window,"location"),"protocol"), "//")), gs.gp(gs.gp(Socket.window,"location"),"hostname")))); return gs.sp(GrooscriptGrails,"remoteUrl",gs.gp(Socket.session,"incomingUrl")); } Socket.socketHeaders = function(it) { gs.sp(Socket.socketHeadersMap,"domain",gs.gp(gs.gp(Socket.window,"location"),"hostname")); gs.sp(Socket.socketHeadersMap,"" + (Socket.AUTH_TOKEN) + "",gs.execStatic(Utils,'getAuthToken', this,[])); gs.sp(Socket.socketHeadersMap,"" + (Socket.DEVICE_TOKEN) + "",gs.execStatic(Utils,'getDeviceToken', this,[])); if (gs.bool(gs.gp(Socket.session,"jwt"))) { gs.sp(Socket.socketHeadersMap,"jwt",gs.gp(Socket.session,"jwt")); }; return Socket.socketHeadersMap; } Socket.initSocket = function(success, failure) { if (success === undefined) success = null; if (failure === undefined) failure = null; return gs.execStatic(Socket,'socketConnectionInterval', this,[success, failure]); } Socket.socketReady = function(callback) { if (gs.bool(Socket.connected)) { gs.execCall(callback, this, []); return null; }; return gs.mc(Socket.socketReadyQueue,"add",[callback]); } Socket.socketReadyQueueCallAll = function(it) { var socketReadyQueueLocal = Socket.socketReadyQueue; Socket.socketReadyQueue = gs.list([]); return gs.mc(socketReadyQueueLocal,"each",[function(callback) { try { gs.execCall(callback, this, []); } catch (all) { gs.println(gs.fs('all', this)); } ; }]); } Socket.addUserDataPipe = function(it) { return Socket.addSubscription(gs.execStatic(Utils,'getDeviceToken', this,[]), Socket.SOCKET_USER_URL, Socket.userDataPipe); } Socket.onReconnect = function(cb) { if (gs.bool(cb)) { return gs.mc(Socket.reconnectCallbacks,"add",[cb]); }; } Socket.fireReconnectCallbacks = function(it) { return gs.mc(Socket.reconnectCallbacks,"each",[function(cb) { try { gs.execCall(cb, this, []); } catch (all) { gs.println(gs.fs('all', this)); } ; }]); } Socket.startSessionRefresher = function(it) { if (gs.bool(gs.gp(Socket.session,"authToken"))) { var sessionRefresherCallback = function(data) { if (data != "authed") { gs.println("NOT AUTHED"); return gs.execStatic(Utils,'logout', this,[]); }; }; Socket.sessionRefresher(gs.gp(Socket.session,"authToken"), sessionRefresherCallback); for (_i0 = 0, sessionRefresherThread = Socket.sessionRefresherThreads[0]; _i0 < Socket.sessionRefresherThreads.length; sessionRefresherThread = Socket.sessionRefresherThreads[++_i0]) { gs.execStatic(Utils,'clearInterval', this,[sessionRefresherThread]); gs.mc(Socket.sessionRefresherThreads,"remove",[sessionRefresherThread]); }; return gs.mc(Socket.sessionRefresherThreads,"add",[gs.execStatic(Utils,'setInterval', this,[function(it) { return gs.mc(Socket,"sessionRefresher",[gs.gp(Socket.session,"authToken"), sessionRefresherCallback]); }, gs.multiply((gs.multiply(1000, 60)), Socket.SESSION_REFRESH_MINS)])]); }; } Socket.sessionRefresher = function(token, sessionRefresherCallback) { console.log("refreshing:" + token +':'+new Date()); $.ajax({ url : '/login/tokenAuth?token='+token, type : 'GET', processData: false, contentType: false, success : function(data) { console.log("grails session re-auth:"+data); sessionRefresherCallback(data) } }); } Socket.reconnect = function(retryInMs) { if (retryInMs === undefined) retryInMs = 0; if (gs.bool(retryInMs)) { return gs.execStatic(Utils,'setTimeout', this,[function(it) { return gs.mc(Socket,"reconnect",[]); }, retryInMs]); }; if ((gs.bool(Socket.reconnectMutex)) || (!gs.bool(Socket.intervalRunner))) { return Socket.reconnect(500); }; Socket.reconnectMutex = true; return gs.mc(Socket,"intervalRunner",[function(it) { return Socket.reconnectMutex = false; }]); } Socket.socketConnectionInterval = function(success) { var reconnectCallback = function(it) { gs.println("Socket reconnected"); Socket.connected = true; gs.mc(Socket,"addUserDataPipe",[]); gs.mc(Socket,"resubscribeAll",[]); gs.mc(Socket,"resendMessageQueue",[]); gs.mc(Socket,"startSessionRefresher",[]); gs.execCall(success, this, []); success = function(it) { }; gs.mc(Socket,"socketReadyQueueCallAll",[]); return gs.mc(Socket,"fireReconnectCallbacks",[]); }; var disconnectSockets = function(it) { gs.println("Socket disconnect"); Socket.connected = false; try { gs.mc(gs.gp(Socket,"websocketClient"),"disconnect",[]); } catch (all) { } ; }; Socket.intervalRunner = function(done) { gs.println(gs.plus((gs.plus((gs.plus((gs.plus((gs.plus("navigator.onLine:", gs.gp(Socket.navigator,"onLine"))), ":")), gs.gp(gs.gp(Socket,"websocketClient"),"connected"))), ":")), Socket.connected)); if (!gs.bool(gs.gp(gs.gp(Socket,"websocketClient"),"connected"))) { gs.println("Socket.websocketClient.connected:false:reconnecting..."); gs.mc(Socket,"socketConnect",[gs.map().add("domain",gs.gp(Socket.session,"domain")), function(it) { gs.println(gs.plus("Socket.websocketClient.connected:", gs.gp(gs.gp(Socket,"websocketClient"),"connected"))); Socket.connected = true; gs.execCall(reconnectCallback, this, []); return gs.execCall(done, this, []); }, function(it) { gs.println("Socket.websocketClient.connected:connection down"); gs.execCall(disconnectSockets, this, []); gs.execCall(done, this, []); if (gs.bool(Socket.queue)) { return gs.mc(Socket,"reconnect",[Socket.SOCKET_RUNNER_RETRY_MS]); }; }]); return null; }; gs.println("Sockets believed to be online. Pinging socket connection..."); gs.mc(Socket,"pingWebSocket",[function(pingResponse) { gs.println(gs.plus("pingWebSocket:", pingResponse)); if (gs.equals(pingResponse, "timeout")) { gs.println("Connection timed out, reconnecting..."); gs.execCall(disconnectSockets, this, []); gs.mc(Socket,"reconnect",[]); return gs.execCall(done, this, []); }; gs.println("Connection good, false alarm."); return gs.execCall(done, this, []); }]); return gs.println(gs.plus("intervalRunner:Socket.websocketClient.connected:", gs.gp(gs.gp(Socket,"websocketClient"),"connected"))); }; return Socket.reconnect(); } Socket.socketConnect = function(headers, success, failed) { try{ Socket.socket = new SockJS('/stomp'); Socket.websocketClient = Stomp.over(Socket.socket); if (!StartupParams.websocketClientDebug){ //switch off debuggging Socket.websocketClient.debug = function () {} } Socket.websocketClient.connect(gs.toJavascript(headers), success, failed); }catch(error) { console.info(error); } } Socket.pingWebSocket = function(callback) { var websocketPingCountNow = Socket.websocketPingCount; var wrapper = gs.mc(gs.map().add("uuid","ping").add("call","callChain").add("data",gs.list([gs.map().add("property","transmissionService") , gs.map().add("method","ping")])),'leftShift', gs.list([Socket.socketHeaders()])); Socket.doSendNative(Socket.SOCKET_URL, wrapper); return gs.execStatic(Utils,'setTimeout', this,[function(it) { if (gs.equals(websocketPingCountNow, Socket.websocketPingCount)) { gs.execCall(callback, this, ["timeout"]); return null; }; return gs.execCall(callback, this, ["responded"]); }, Socket.SOCKET_PING_TIMEOUT_MS]); } Socket.remote = function(closure, data, success, fail) { if (success === undefined) success = null; if (fail === undefined) fail = null; return gs.execStatic(Socket,'send', this,["remoteExec", closure, data, success, fail]); } Socket.callChain = function(callChain, success, fail) { if (success === undefined) success = null; if (fail === undefined) fail = null; if (Socket.isDymicoSystemUpdating()) { return null; }; gs.println(gs.plus("callChain:", callChain)); return gs.execStatic(Socket,'send', this,["callChain", callChain, success, fail]); } Socket.callObject = function(self, method, args, success, fail) { if (fail === undefined) fail = null; if (Socket.isDymicoSystemUpdating()) { return null; }; gs.println(gs.plus("callObject:OObject:", self)); gs.println(gs.plus("callObject:method:", method)); return gs.execStatic(Socket,'send', this,["callObject", gs.map().add("self",self).add("method",method).add("args",args), success, fail]); } Socket.isDymicoSystemUpdating = function() { try{ if (typeof dymicoVersionUpdater !== 'undefined') { return dymicoVersionUpdater.dymicoSystemUpdating; } }catch(all){ } return false; } Socket.send = function(call, data, success, fail) { if (fail === undefined) fail = function(it) { return false; }; var uuid = gs.execStatic(Utils,'uuid', this,[]); var wrapper = gs.map().add("uuid",uuid).add("call",call).add("data",data); var queueItem = gs.map().add("success",success).add("fail",fail).add("dataStr",gs.mc(data,"toString",[])).add("date",gs.gp(gs.date(),"time")).add("wrapper",wrapper); (Socket.queue[uuid]) = queueItem; Socket.doSend(Socket.SOCKET_URL, queueItem); return uuid; } Socket.doSend = function(channel, queueItem) { if (gs.equals(Socket.sendProtocol, "websocket")) { Socket.doSendNative(channel, gs.mc(gs.gp(queueItem,"wrapper"),'leftShift', gs.list([Socket.socketHeaders()]))); gs.execStatic(Utils,'setTimeout', this,[function(it) { return gs.mc(Socket,"checkMessageReceived",[queueItem]); }, gs.multiply(Socket.SOCKET_CHECK_MSG_RECEIVED_SEC, 1000)]); if (!gs.bool(Socket.connected)) { return Socket.reconnect(); }; } else { if (gs.equals(Socket.sendProtocol, "http")) { return Socket.doSendNativeHttp(gs.mc(gs.gp(queueItem,"wrapper"),'leftShift', gs.list([Socket.socketHeaders()])), function(it) { gs.println("HTTP TIMEOUT"); return gs.mc(Socket,"reconnect",[]); }); } else { throw "Exception"; }; }; } Socket.doSendNativeHttp = function(map, timeoutCallback) { var sendMessage = map; sendMessage = Utils.mapToJsonString(sendMessage); // sendMessage = LZString.compressToBase64(sendMessage); //no compression needed, cause the browser will gzip it anyway sendMessage = "message="+encodeURIComponent(sendMessage) var xhr = new XMLHttpRequest(); xhr.ontimeout = timeoutCallback xhr.open('POST', Socket.SOCKET_OVER_HTTP_SYNCHRONOUS_URL, true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.onreadystatechange = function(e) { if (this.status == 404) { console.log('AJAX FAILED'); } if (this.readyState == 4 && this.status == 200) { Socket.receive(Socket.doReceiveNative(this.responseText, false)) } }; xhr.send(sendMessage); } Socket.doSendNative = function(channel, map) { try{ var sendMessage = map; sendMessage = Utils.mapToJsonString(sendMessage) sendMessage = LZString.compressToBase64(sendMessage) return Socket.websocketClient.send(channel, {}, sendMessage); }catch(all){ } } Socket.checkMessageReceived = function(queueItem) { if (Socket.queue[gs.gp(gs.gp(queueItem,"wrapper"),"uuid")]) { Socket.reconnect(); return Socket.cleanQueue(); }; } Socket.resendMessageQueue = function(it) { return gs.mc(gs.mc(gs.mc(Socket.queue,"values",[]),"sort",[function(it) { return gs.gp(it,"date",true); }]),"each",[function(queueItem) { return gs.mc(Socket,"doSend",[Socket.SOCKET_URL, queueItem]); }]); } Socket.cleanQueue = function(it) { if (Socket.nextQueueClean < gs.gp(gs.date(),"time")) { var timeoutMs = gs.multiply((gs.multiply(Socket.SOCKET_QUEUE_TIMEOUT_MIN, 60)), 1000); Socket.nextQueueClean = (gs.plus(gs.gp(gs.date(),"time"), timeoutMs)); gs.println(gs.plus("nextQueueClean:", Socket.nextQueueClean)); gs.println("cleanQueue.start"); var timeout = gs.minus(gs.gp(gs.date(),"time"), timeoutMs); gs.println(gs.plus("cleanQueue.queue.size:", gs.mc(Socket.queue,"size",[]))); gs.mc(Socket.queue,"each",[function(key, queueItem) { if (gs.gp(queueItem,"date") < timeout) { gs.println("REMOVED"); gs.mc(Socket.queue,"remove",[key]); return gs.mc(queueItem,"fail",[]); }; }]); return gs.println("cleanQueue.end"); }; } Socket.receive = function(wrapper) { Socket.websocketPingCount++; if (gs.equals(gs.gp(wrapper,"uuid"), "ping")) { return null; }; var queueItem = Socket.queue[gs.gp(wrapper,"uuid")]; gs.mc(Socket.queue,"remove",[gs.gp(wrapper,"uuid")]); if (gs.bool(queueItem)) { if (gs.bool(gs.gp(wrapper,"error"))) { gs.mc(queueItem,"fail",[gs.gp(wrapper,"data")]); Socket.processException(gs.gp(wrapper,"data")); return null; }; var object = gs.execStatic(ObjectRegistry,'register', this,[gs.gp(wrapper,"data")]); return gs.mc(queueItem,"success",[object]); }; } Socket.processException = function(ex) { gs.execStatic(Utils,'logExceptionStack', this,[gs.plus((gs.plus(ex.clazz, ":")), gs.gp(ex,"message"))]); return gs.execStatic(Utils,'logExceptionStack', this,[gs.gp(ex,"stackTrace")]); } Socket.subscribe = function(objectId, success, topic) { if (topic === undefined) topic = Socket.SOCKET_OBJECT_URL; return Socket.socketReady(function(it) { gs.mc(Socket,"unsubscribe",[objectId, topic]); gs.println(gs.plus("subscribe:", objectId)); var successWrapper = function(messageObject) { return gs.execCall(success, this, [messageObject]); }; gs.mc(Socket,"addSubscription",[objectId, topic, success]); try { gs.mc(Socket,"subscribeJs",[objectId, gs.plus(topic, objectId), successWrapper]); } catch (all) { gs.println("subscribeJs failed"); gs.println(gs.fs('all', this)); } ; }); } Socket.subscribeTopic = function(topicId, success) { return Socket.subscribe(topicId, success, Socket.SOCKET_TOPIC_URL); } Socket.unsubscribeTopic = function(topicId) { return Socket.unsubscribe(topicId, Socket.SOCKET_TOPIC_URL); } Socket.addSubscription = function(objectId, topic, success) { return (Socket.subscriptions[objectId]) = gs.map().add("objectId",objectId).add("success",success).add("topic",topic); } Socket.subscribeJs = function(objectId, subId, success) { console.log('subscribeJs:'+subId) return Socket.websocketClient.subscribe(subId, function(message){ success(Socket.doReceiveNative(message.body)) }, {id:objectId}) } Socket.doReceiveNative = function(message, compressed) { if (compressed === undefined) compressed = true; if (compressed) message = LZString.decompressFromBase64(message) // console.log('message', message) return Utils.stringToJson(message) } Socket.resubscribeAll = function(it) { var oldSubscriptions = Socket.subscriptions; Socket.subscriptions = gs.map(); return gs.mc(oldSubscriptions,"each",[function(key, subscription) { return gs.mc(Socket,"subscribe",[gs.gp(subscription,"objectId"), gs.gp(subscription,"success"), gs.gp(subscription,"topic")]); }]); } Socket.unsubscribe = function(objectId, topic) { if (topic === undefined) topic = Socket.SOCKET_OBJECT_URL; gs.println(gs.plus("unsubscribe:", objectId)); try { gs.mc(gs.gp(Socket,"websocketClient"),"unsubscribe",[objectId]); gs.mc(Socket.subscriptions,"remove",[objectId]); } catch (all) { gs.println(all); } ; } Socket.post = function(file, parameter, objectName, id, callback) { var postUrl = "/post/upload"; var formData = new FormData(); formData.append('file', file); formData.append('id', id); formData.append('parameter', parameter); formData.append('objectName', objectName); $.ajax({ url : postUrl, type : 'POST', data : formData, processData: false, // tell jQuery not to process the data contentType: false, // tell jQuery not to set contentType success : function(data) { console.log(data); callback(data); } }); } Socket.postJson = function(url, map, success, failed) { if (success === undefined) success = function(it) { }; if (failed === undefined) failed = function(it) { }; } Socket.SOCKET_URL = "/app/api4WebSocketForPublic"; Socket.SOCKET_USER_URL = "/topic/api4WebSocketForUser/"; Socket.SOCKET_OBJECT_URL = "/topic/api4WebSocketForObject/"; Socket.SOCKET_TOPIC_URL = "/topic/api4WebSocketForTopic/"; Socket.SOCKET_OVER_HTTP_SYNCHRONOUS_URL = "/api4WebSocket/synchronous"; Socket.SOCKET_OVER_HTTP_ASYNCHRONOUS_URL = "/api4WebSocket/asynchronous"; Socket.SESSION_REFRESH_MINS = 10; Socket.SOCKET_CHECK_MSG_RECEIVED_SEC = 7; Socket.SOCKET_RUNNER_RETRY_MS = 5000; Socket.SOCKET_QUEUE_TIMEOUT_MIN = 2; Socket.AUTH_TOKEN = "secToken2"; Socket.DEVICE_TOKEN = "deviceToken1"; Socket.window = null; Socket.navigator = null; Socket.sendProtocol = "http"; Socket.queue = gs.map(); Socket.socketHeadersMap = gs.map(); Socket.userDataPipe = function(data) { return gs.mc(Socket,"receive",[data]); }; Socket.session = gs.execStatic(Session,'instance', this,[]); Socket.connected = false; Socket.socket = null; Socket.websocketClient = gs.map().add("connected",false).add("disconnect",function(it) { }).add("subscriptions",function(it) { }); Socket.subscriptions = gs.map(); Socket.sessionRefresherThreads = gs.list([]); Socket.reconnectCallbacks = gs.list([]); Socket.socketReadyQueue = gs.list([]); Socket.intervalRunner = null; Socket.reconnectMutex = false; Socket.SOCKET_PING_TIMEOUT_MS = 3000; Socket.websocketPingCount = 0; Socket.nextQueueClean = 0; function Utils() { var gSobject = gs.init('Utils'); gSobject.clazz = { name: 'Utils', simpleName: 'Utils'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; Object.defineProperty(gSobject, 'session', { get: function() { return Utils.session; }, set: function(gSval) { Utils.session = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'window', { get: function() { return Utils.window; }, set: function(gSval) { Utils.window = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'document', { get: function() { return Utils.document; }, set: function(gSval) { Utils.document = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'DeviceTypes', { get: function() { return Utils.DeviceTypes; }, set: function(gSval) { Utils.DeviceTypes = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'AUTH_FAILED', { get: function() { return Utils.AUTH_FAILED; }, set: function(gSval) { Utils.AUTH_FAILED = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'NO_AUTH', { get: function() { return Utils.NO_AUTH; }, set: function(gSval) { Utils.NO_AUTH = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'REMEMBER_FALLBACK_DAYS', { get: function() { return Utils.REMEMBER_FALLBACK_DAYS; }, set: function(gSval) { Utils.REMEMBER_FALLBACK_DAYS = gSval; }, enumerable: true }); gSobject.getAuthToken = function() { return Utils.getAuthToken(); } gSobject.getDeviceToken = function() { return Utils.getDeviceToken(); } gSobject.setTimeout = function(x0,x1) { return Utils.setTimeout(x0,x1); } gSobject.setInterval = function(x0,x1) { return Utils.setInterval(x0,x1); } gSobject.clearInterval = function(x0) { return Utils.clearInterval(x0); } gSobject.localDateString = function(x0) { return Utils.localDateString(x0); } gSobject.utcDateString = function(x0) { return Utils.utcDateString(x0); } gSobject.newDate = function(x0,x1,x2) { return Utils.newDate(x0,x1,x2); } gSobject.documentReady = function(x0) { return Utils.documentReady(x0); } gSobject.uniqueList = function(x0,x1) { return Utils.uniqueList(x0,x1); } gSobject.listsEqual = function(x0,x1) { return Utils.listsEqual(x0,x1); } gSobject.uuid = function() { return Utils.uuid(); } gSobject.guid = function() { return Utils.guid(); } gSobject.callChain = function(x0,x1,x2) { return Utils.callChain(x0,x1,x2); } gSobject.callObject = function(x0,x1,x2,x3,x4) { return Utils.callObject(x0,x1,x2,x3,x4); } gSobject.send = function(x0,x1,x2,x3) { return Utils.send(x0,x1,x2,x3); } gSobject.subscribe = function(x0,x1,x2) { return Utils.subscribe(x0,x1,x2); } gSobject.unsubscribe = function(x0) { return Utils.unsubscribe(x0); } gSobject.subscribeTopic = function(x0,x1) { return Utils.subscribeTopic(x0,x1); } gSobject.unsubscribeTopic = function(x0) { return Utils.unsubscribeTopic(x0); } gSobject.rememberDays = function() { return Utils.rememberDays(); } gSobject.rememberWindowExpired = function() { return Utils.rememberWindowExpired(); } gSobject.clearRememberedLogin = function() { return Utils.clearRememberedLogin(); } gSobject.parseDays = function(x0) { return Utils.parseDays(x0); } gSobject.toWholeNumber = function(x0) { return Utils.toWholeNumber(x0); } gSobject.nowMillis = function() { return Utils.nowMillis(); } gSobject.toMillis = function(x0) { return Utils.toMillis(x0); } gSobject.launchMarkerPresent = function() { return Utils.launchMarkerPresent(); } gSobject.markLaunch = function() { return Utils.markLaunch(); } gSobject.clearLaunchMarker = function() { return Utils.clearLaunchMarker(); } gSobject.tokenAuth = function(x0,x1) { return Utils.tokenAuth(x0,x1); } gSobject.userAgent = function() { return Utils.userAgent(); } gSobject.login = function(x0,x1,x2,x3) { return Utils.login(x0,x1,x2,x3); } gSobject.updateAuthTokenToSession = function(x0,x1) { return Utils.updateAuthTokenToSession(x0,x1); } gSobject.roleSignature = function(x0) { return Utils.roleSignature(x0); } gSobject.triggerLoginRerenderCheck = function(x0) { return Utils.triggerLoginRerenderCheck(x0); } gSobject.logout = function(x0,x1) { return Utils.logout(x0,x1); } gSobject.urlSafeBase64Encode = function(x0) { return Utils.urlSafeBase64Encode(x0); } gSobject.open = function(x0,x1,x2) { return Utils.open(x0,x1,x2); } gSobject.inAppBrowser = function(x0,x1,x2) { return Utils.inAppBrowser(x0,x1,x2); } gSobject.loadPage = function(x0) { return Utils.loadPage(x0); } gSobject.reloadPage = function() { return Utils.reloadPage(); } gSobject.setCookie = function(x0,x1) { return Utils.setCookie(x0,x1); } gSobject.getCookie = function(x0) { return Utils.getCookie(x0); } gSobject.deviceType = function() { return Utils.deviceType(); } gSobject.isBrowser = function() { return Utils.isBrowser(); } gSobject.isAndroid = function() { return Utils.isAndroid(); } gSobject.isIos = function() { return Utils.isIos(); } gSobject.isCordova = function() { return Utils.isCordova(); } gSobject.cordovaDevice = function() { return Utils.cordovaDevice(); } gSobject.isOnline = function() { return Utils.isOnline(); } gSobject.userAgent = function() { return Utils.userAgent(); } gSobject.toast = function(x0,x1) { return Utils.toast(x0,x1); } gSobject.post = function(x0,x1,x2,x3,x4) { return Utils.post(x0,x1,x2,x3,x4); } gSobject.validateEmail = function(x0) { return Utils.validateEmail(x0); } gSobject.validateCellphone = function(x0) { return Utils.validateCellphone(x0); } gSobject.getType = function(x0) { return Utils.getType(x0); } gSobject.dateString = function(x0) { return Utils.dateString(x0); } gSobject.clearTime = function(x0) { return Utils.clearTime(x0); } gSobject.utc = function(x0) { return Utils.utc(x0); } gSobject.appendAppVersion = function(x0) { return Utils.appendAppVersion(x0); } gSobject.logExceptionStack = function(x0) { return Utils.logExceptionStack(x0); } gSobject.getIp = function(x0) { return Utils.getIp(x0); } gSobject.preloadImage = function(x0) { return Utils.preloadImage(x0); } gSobject.loadScript = function(x0,x1,x2) { return Utils.loadScript(x0,x1,x2); } gSobject.mapToJsonString = function(x0) { return Utils.mapToJsonString(x0); } gSobject.stringToJson = function(x0,x1) { return Utils.stringToJson(x0,x1); } gSobject.stringToDate = function(x0) { return Utils.stringToDate(x0); } gSobject.isDate = function(x0) { return Utils.isDate(x0); } gSobject.deepCopyMap = function(x0) { return Utils.deepCopyMap(x0); } gSobject.findDeep = function(x0,x1) { return Utils.findDeep(x0,x1); } gSobject.removeMapKey = function(x0,x1,x2) { return Utils.removeMapKey(x0,x1,x2); } gSobject.formatNumber = function(x0,x1,x2,x3) { return Utils.formatNumber(x0,x1,x2,x3); } gSobject.iFrameById = function(x0) { return Utils.iFrameById(x0); } gSobject.decodeJWT = function(x0) { return Utils.decodeJWT(x0); } gSobject.embedTextInBlob = function(x0,x1,x2) { return Utils.embedTextInBlob(x0,x1,x2); } gSobject.embedTextInBlobNative = function(x0,x1,x2) { return Utils.embedTextInBlobNative(x0,x1,x2); } gSobject.blobToDataUrl = function(x0,x1) { return Utils.blobToDataUrl(x0,x1); } gSobject.dataUrlToBlob = function(x0,x1) { return Utils.dataUrlToBlob(x0,x1); } gSobject.take = function(x0,x1) { return Utils.take(x0,x1); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; Utils.getAuthToken = function(it) { return gs.gp(Utils.session,"authToken"); } Utils.getDeviceToken = function(it) { return gs.gp(Utils.session,"deviceToken"); } Utils.setTimeout = function(callback, timeout) { return setTimeout(callback, timeout); } Utils.setInterval = function(callback, timeout) { return setInterval(callback, timeout); } Utils.clearInterval = function(interval) { return clearInterval(interval); } Utils.localDateString = function(date) { return gs.mc(gs.mc(gs.mc(Utils,"moment",[date]),"utcOffset",[0, true]),"toISOString",[]); } Utils.utcDateString = function(date) { return gs.mc(gs.mc(gs.mc(Utils,"moment",[date]),"utc",[]),"toISOString",[]); } Utils.newDate = function(year, month, day) { return new Date(year, month, day) } Utils.documentReady = function(callback) { if ((gs.gp(Utils.document,"readyState") === "complete") || ((gs.gp(Utils.document,"readyState") !== "loading") && (!gs.bool(gs.gp(gs.gp(Utils.document,"documentElement"),"doScroll"))))) { return gs.execCall(callback, this, []); } else { return gs.mc(Utils.document,"addEventListener",["DOMContentLoaded", callback]); }; } Utils.uniqueList = function(list, closure) { var newList = gs.list([]); gs.mc(gs.mc(list,"reverse",[]),"each",[function(listItem) { if (!gs.bool(gs.mc(newList,"find",[function(it) { return gs.equals(gs.execCall(closure, this, [listItem]), gs.execCall(closure, this, [it])); }]))) { return gs.mc(newList,"add",[listItem]); }; }]); return gs.mc(newList,"reverse",[]); } Utils.listsEqual = function(a, b) { if (gs.mc(a,"size",[]) != gs.mc(b,"size",[])) { return false; }; for (var i = 0 ; i < gs.mc(a,"size",[]) ; i++) { if ((a[i]) != (b[i])) { return false; }; }; return true; } Utils.uuid = function(it) { return gs.mc(Utils.guid(),"replaceAll",["-", ""]); } Utils.guid = function() { const UNIX_TS_MS_BITS = 48; const VER_DIGIT = "7"; const SEQ_BITS = 12; const VAR = 0b10; const VAR_BITS = 2; const RAND_BITS = 62; let prevTimestamp = -1; let seq = 0; const timestamp = Math.max(Date.now(), prevTimestamp); seq = timestamp === prevTimestamp ? seq + 1 : 0; prevTimestamp = timestamp; const var_rand = new Uint32Array(2); crypto.getRandomValues(var_rand); var_rand[0] = (VAR << (32 - VAR_BITS)) | (var_rand[0] >>> VAR_BITS); const digits = timestamp.toString(16).padStart(UNIX_TS_MS_BITS / 4, "0") + VER_DIGIT + seq.toString(16).padStart(SEQ_BITS / 4, "0") + var_rand[0].toString(16).padStart((VAR_BITS + RAND_BITS) / 2 / 4, "0") + var_rand[1].toString(16).padStart((VAR_BITS + RAND_BITS) / 2 / 4, "0"); return (digits.slice(0, 8) + "-" + digits.slice(8, 12) + "-" + digits.slice(12, 16) + "-" + digits.slice(16, 20) + "-" + digits.slice(20)); } Utils.callChain = function(callChain, success, fail) { if (success === undefined) success = null; if (fail === undefined) fail = null; return gs.execStatic(Socket,'callChain', this,[callChain, success, fail]); } Utils.callObject = function(self, method, args, success, fail) { if (fail === undefined) fail = null; return gs.execStatic(Socket,'callObject', this,[self, method, args, success, fail]); } Utils.send = function(call, data, success, fail) { if (fail === undefined) fail = null; return gs.execStatic(Socket,'send', this,[call, data, success, fail]); } Utils.subscribe = function(objectId, success, topic) { if (topic === undefined) topic = gs.gp(Socket,"SOCKET_OBJECT_URL"); return gs.execStatic(Socket,'subscribe', this,[objectId, success, topic]); } Utils.unsubscribe = function(objectId) { return gs.execStatic(Socket,'unsubscribe', this,[objectId]); } Utils.subscribeTopic = function(topicId, success) { return gs.execStatic(Socket,'subscribeTopic', this,[topicId, success]); } Utils.unsubscribeTopic = function(topicId) { return gs.execStatic(Socket,'unsubscribeTopic', this,[topicId]); } Utils.rememberDays = function(it) { var days = Utils.parseDays(gs.gp(Utils.session,"rememberDays")); return (gs.equals(days, null) ? Utils.REMEMBER_FALLBACK_DAYS : days); } Utils.rememberWindowExpired = function(it) { var days = Utils.rememberDays(); if (gs.equals(days, 0)) { return !Utils.launchMarkerPresent(); }; var loginAt = gs.gp(Utils.session,"loginAt"); if (!gs.bool(loginAt)) { return true; }; return (gs.minus(Utils.nowMillis(), Utils.toMillis(loginAt))) > (gs.multiply((gs.multiply((gs.multiply((gs.multiply(days, 24)), 60)), 60)), 1000)); } Utils.clearRememberedLogin = function(it) { gs.sp(Utils.session,"zoner",null); gs.sp(Utils.session,"zonerId",null); gs.sp(Utils.session,"jwt",null); gs.sp(Utils.session,"loginAt",null); gs.sp(Utils.session,"rememberDays",null); return Utils.clearLaunchMarker(); } Utils.parseDays = function(raw) { if (gs.equals(raw, null)) { return null; }; return Utils.toWholeNumber(raw); } Utils.toWholeNumber = function(raw) { var s = ('' + raw).trim(); if (!/^[0-9]+$/.test(s)) return null; var n = parseInt(s, 10); return isNaN(n) ? null : n; } Utils.nowMillis = function() { return new Date().getTime(); } Utils.toMillis = function(value) { if (value == null) return 0; if (value instanceof Date) return value.getTime(); var n = parseInt('' + value, 10); return isNaN(n) ? 0 : n; } Utils.launchMarkerPresent = function() { try { return sessionStorage.getItem('dymicoLoginLaunch') === 'true'; } catch(e){ return false; } } Utils.markLaunch = function() { try { sessionStorage.setItem('dymicoLoginLaunch', 'true'); } catch(e){} } Utils.clearLaunchMarker = function() { try { sessionStorage.removeItem('dymicoLoginLaunch'); } catch(e){} } Utils.tokenAuth = function(success, fail) { if (fail === undefined) fail = function(it) { }; gs.println(gs.plus("Utils:tokenAuth:", gs.gp(StartupParams,"doAuthToken"))); if ((gs.bool(gs.gp(Utils.session,"zoner"))) && (!gs.bool(Utils.rememberWindowExpired()))) { gs.println("Utils:tokenAuth:zoner cached"); gs.execCall(success, this, []); success = null; return null; }; if (gs.bool(gs.gp(Utils.session,"zoner"))) { gs.println("Utils:tokenAuth:remember window expired"); Utils.clearRememberedLogin(); }; gs.println("Utils:tokenAuth:loading zoner"); var callback = function(authMap) { gs.println(gs.plus("tokenAuth:callback:authMap:", authMap)); if (gs.bool(gs.gp(authMap,"authenticated",true))) { gs.mc(Utils,"updateAuthTokenToSession",[authMap, false]); if (gs.bool(success)) { gs.execCall(success, this, []); }; return null; }; return gs.execCall(fail, this, []); }; gs.println(gs.plus("getDeviceToken():", Utils.getDeviceToken())); return gs.execStatic(Utils,'send', this,["authenticationToken", gs.map().add("deviceId",Utils.getDeviceToken()), callback]); } Utils.userAgent = function() { return navigator.userAgent.toLowerCase() } Utils.login = function(username, password, success, fail) { if (fail === undefined) fail = function(it) { }; var callback = function(authMap) { if (gs.bool(gs.gp(authMap,"authenticated",true))) { gs.mc(Utils,"updateAuthTokenToSession",[authMap]); gs.execCall(success, this, []); return null; }; gs.sp(Utils.session,"zoner",null); gs.println("Login failed"); return gs.execCall(fail, this, []); }; return gs.execStatic(Utils,'send', this,["authentication", gs.map().add("username",username).add("password",password).add("deviceId",Utils.getDeviceToken()).add("userAgent",Utils.userAgent()), callback, fail]); } Utils.updateAuthTokenToSession = function(authMap, freshLogin) { if (freshLogin === undefined) freshLogin = true; Utils.setCookie(gs.gp(Socket,"AUTH_TOKEN"), gs.gp(gs.gp(authMap,"zoner"),"token")); gs.sp(Utils.session,"zoner",gs.gp(authMap,"zoner")); gs.sp(Utils.session,"zonerId",gs.gp(gs.gp(authMap,"zoner"),"id")); if (gs.gp(authMap,"rememberDays") != null) { gs.sp(Utils.session,"rememberDays",gs.gp(authMap,"rememberDays")); }; if ((gs.bool(freshLogin)) || (!gs.bool(gs.gp(Utils.session,"loginAt")))) { gs.sp(Utils.session,"loginAt",Utils.nowMillis()); }; Utils.markLaunch(); if (gs.bool(gs.gp(authMap,"jwt"))) { gs.sp(Utils.session,"jwt",gs.gp(authMap,"jwt")); }; return Utils.triggerLoginRerenderCheck(Utils.roleSignature(gs.gp(gs.gp(authMap,"zoner"),"roles"))); } Utils.roleSignature = function(roles) { return gs.mc(gs.mc(gs.mc(gs.elvis(gs.bool(roles) , roles , gs.list([])),"collect",[function(it) { return gs.mc(it,"toString",[], null, true); }]),"sort",[]),"join",[","]); } Utils.triggerLoginRerenderCheck = function(zonerId) { try { if (window.dymicoVersionUpdater && window.dymicoVersionUpdater.checkAfterLogin){ window.dymicoVersionUpdater.checkAfterLogin(zonerId); } } catch(e){ console.log('triggerLoginRerenderCheck failed', e); } } Utils.logout = function(pathAfterLogout, dropDatabase) { if (pathAfterLogout === undefined) pathAfterLogout = "/login/logout"; if (dropDatabase === undefined) dropDatabase = true; if (!gs.bool(pathAfterLogout)) { pathAfterLogout = "/login/logout"; }; gs.println("Utils.logout"); gs.sp(Utils.session,"zoner",null); gs.sp(Utils.session,"redirectAfterLogin",null); gs.sp(Utils.session,"authToken",null); gs.sp(Utils.session,"deviceToken",null); gs.mc(Utils.session,"clear",[]); if (gs.bool(dropDatabase)) { gs.execStatic(LocalDB,'getInstance', this,[function(it) { return gs.mc(gs.execStatic(LocalDB,'getInstance', this,[]),"dropDatabase",[]); }]); }; gs.println(gs.plus("Utils.logout:redirect to ", pathAfterLogout)); return Utils.loadPage(pathAfterLogout); } Utils.urlSafeBase64Encode = function(str) { // 1. Encode to standard Base64 let base64 = btoa(str); // 2. Modify to be URL-safe (RFC 4648 Section 5) return base64 .replace(/\+/g, '-') // Replace + with - .replace(/\//g, '_') // Replace / with _ .replace(/=+$/, ''); // Remove trailing = padding } Utils.open = function(url, target, options) { if (target === undefined) target = "_system"; if (options === undefined) options = ""; if (Utils.isCordova()) { return Utils.inAppBrowser(gs.mc(Utils,"encodeURI",[url]), target, options); }; return gs.mc(Utils.window,"open",[url, target, options]); } Utils.inAppBrowser = function(url, target, options) { return cordova.InAppBrowser.open(encodeURI(url), target, options) } Utils.loadPage = function(url) { window.location = url } Utils.reloadPage = function() { var url = window.location.href; var seperator = '?' if (url.indexOf('?') > -1){ seperator = '&' } window.location.href = url+seperator+'v='+ new Date().getTime(); window.location.reload(true); } Utils.setCookie = function(name, value) { Cookies.set(name, JSON.stringify(value)); } Utils.getCookie = function(name) { try{ return JSON.parse(Cookies.get(name)); // return gs.toGroovy(jQuery.parseJSON(unescape(Cookies.get(name)))); }catch(all){ return null } } Utils.deviceType = function(it) { if (gs.mc(gs.mc(Utils.userAgent(),"toLowerCase",[]),"contains",["electron"])) { return gs.gp(gs.gp(Utils,"DeviceTypes"),"ELECTRON"); }; if ((gs.mc(gs.mc(Utils.userAgent(),"toLowerCase",[]),"contains",["iphone"])) || (gs.mc(gs.mc(Utils.userAgent(),"toLowerCase",[]),"contains",["ipad"]))) { return gs.gp(gs.gp(Utils,"DeviceTypes"),"IOS"); }; if (gs.mc(gs.mc(Utils.userAgent(),"toLowerCase",[]),"contains",["android"])) { return gs.gp(gs.gp(Utils,"DeviceTypes"),"ANDROID"); }; return gs.gp(gs.gp(Utils,"DeviceTypes"),"BROWSER"); } Utils.isBrowser = function(it) { return gs.equals(Utils.deviceType(), gs.gp(Utils.DeviceTypes,"BROWSER")); } Utils.isAndroid = function(it) { return gs.equals(Utils.deviceType(), gs.gp(gs.gp(Utils,"DeviceTypes"),"ANDROID")); } Utils.isIos = function(it) { return gs.equals(Utils.deviceType(), gs.gp(gs.gp(Utils,"DeviceTypes"),"IOS")); } Utils.isCordova = function(it) { return gs.mc(Utils.userAgent(),"contains",["cordova"]); } Utils.cordovaDevice = function(it) { return Utils.isCordova(); } Utils.isOnline = function() { return window.navigator.onLine } Utils.userAgent = function() { return navigator.userAgent.toLowerCase() } Utils.toast = function(message, showDuration) { if (showDuration === undefined) showDuration = 300; toastr.options = { "closeButton": false, "debug": false, "newestOnTop": false, "progressBar": false, "positionClass": "toast-bottom-center", "preventDuplicates": false, "onclick": null, "showDuration": showDuration, "hideDuration": "1000", "timeOut": "5000", "extendedTimeOut": "1000", "showEasing": "swing", "hideEasing": "linear", "showMethod": "fadeIn", "hideMethod": "fadeOut" } toastr.info(message); } Utils.post = function(file, parameter, objectName, id, callback) { return gs.execStatic(Socket,'post', this,[file, parameter, objectName, id, callback]); } Utils.validateEmail = function(text) { return gs.exactMatch(text,/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[A-Za-z.]{2,}$/); } Utils.validateCellphone = function(text) { var cleaned = gs.mc(gs.mc(gs.mc(text,"toString",[], null, true),"trim",[], null, true),"replaceAll",["[\s\-\(\)]", ""], null, true); if (!gs.bool(cleaned)) { return false; }; if (gs.mc(cleaned,"startsWith",["+"])) { return gs.exactMatch(cleaned,/^\+[0-9]{7,15}$/); }; return gs.exactMatch(cleaned,/^0[0-9]{9}$/); } Utils.getType = function(value) { return typeof value } Utils.dateString = function(date) { return gs.plus((gs.plus((gs.plus((gs.plus(gs.mc(date,"getDate",[]), "/")), (gs.plus(gs.mc(date,"getMonth",[]), 1)))), "/")), gs.mc(date,"getFullYear",[])); } Utils.clearTime = function(date) { if (date === undefined) date = gs.date(); return gs.mc(gs.mc(Utils,"moment",[date]),"startOf",["day"]); } Utils.utc = function(date) { if (date === undefined) date = gs.date(); return gs.mc(gs.mc(Utils,"moment",[date]),"utc",[]); } Utils.appendAppVersion = function(url) { if (gs.bool(gs.gp(Utils.session,"branchRevision"))) { var appender = "?"; if (gs.mc(url,"contains",["?"])) { appender = "&"; }; url += (gs.plus((gs.plus(appender, "branchRevision=")), gs.gp(Utils.session,"branchRevision"))); }; return url; } Utils.logExceptionStack = function(msg) { console.log('%c ' + msg + ' ', 'color: #cc0000'); } Utils.getIp = function(callback) { Utils.documentReady(function () { $.getJSON("http://jsonip.com/?callback=?", function (data) { callback(data.ip) }); }); } Utils.preloadImage = function(path) { new Image().src = path } Utils.loadScript = function(scriptUrl, type, callback) { if (type === undefined) type = "text/javascript"; if (callback === undefined) callback = function(it) { }; } Utils.mapToJsonString = function(map) { return JSON.stringify(map) } Utils.stringToJson = function(message, parseDate) { if (parseDate === undefined) parseDate = true; var jsonMessage = JSON.parse(message, function(key, value) { return Utils.stringToDate(value); } ) return gs.toGroovy(jsonMessage) } Utils.stringToDate = function(value) { if (typeof value === 'string') { //var a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); var a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})?\.(\d*)?Z$/.exec(value); if (a) { // console.log('stringToDate:value', value) const date = new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6], +a[7])); // console.log('stringToDate:date', date) return date } } return value; } Utils.isDate = function(date) { return date instanceof Date } Utils.deepCopyMap = function(map) { return Utils.removeMapKey(gs.toGroovy(Utils.stringToJson(Utils.mapToJsonString(map))),'clazz') } Utils.findDeep = function(m, key) { if (m[key]) { return m[key]; }; var foundValue = null; gs.mc(m,"each",[function(k, v) { if (gs.bool(foundValue)) { return null; }; if (gs.instanceOf(v, "HashMap")) { return foundValue = gs.mc(Utils,"findDeep",[v, key]); } else { if (gs.instanceOf(v, "ArrayList")) { return gs.mc(v,"each",[function(item) { if (gs.bool(foundValue)) { return null; }; if (gs.instanceOf(item, "HashMap")) { return foundValue = gs.mc(Utils,"findDeep",[item, key]); }; }]); }; }; }]); return foundValue; } Utils.removeMapKey = function(value, removeKey, list) { if (removeKey === undefined) removeKey = "clazz"; if (list === undefined) list = gs.list([]); if (!gs.bool(value)) { return value; }; if (((gs.instanceOf(value, "Map")) || (gs.instanceOf(value, "LinkedHashMap"))) || (gs.instanceOf(value, "HashMap"))) { gs.mc(value,"remove",[removeKey]); if (gs.mc(list,"includes",[value])) { return value; }; gs.mc(list,"add",[value]); gs.mc(value,"each",[function(key, mapValue) { return gs.mc(Utils,"removeMapKey",[mapValue, removeKey, list]); }]); }; if ((gs.instanceOf(value, "List")) || (gs.instanceOf(value, "ArrayList"))) { for (_i0 = 0, listValue = value[0]; _i0 < value.length; listValue = value[++_i0]) { Utils.removeMapKey(listValue, removeKey, list); }; }; return value; } Utils.formatNumber = function(number, decimals, dec, sep) { if (decimals === undefined) decimals = 0; if (dec === undefined) dec = "."; if (sep === undefined) sep = " "; var n = !isFinite(+number) ? 0 : +number, prec = Math.abs(decimals), toFixedFix = function (n, prec) { // Fix for IE parseFloat(0.55).toFixed(0) = 0; var k = Math.pow(10, prec); return Math.round(n * k) / k; }, s = (prec ? toFixedFix(n, prec) : Math.round(n)).toString().split('.'); if (s[0].length > 3) { s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep); } if ((s[1] || '').length < prec) { s[1] = s[1] || ''; s[1] += new Array(prec - s[1].length + 1).join('0'); } return s.join(dec); } Utils.iFrameById = function(id) { var x = gs.mc(Utils.document,"getElementById",[id]); return gs.elvis(gs.bool(gs.gp(x,"contentWindow")) , gs.gp(x,"contentWindow") , gs.gp(x,"contentDocument")); } Utils.decodeJWT = function(token) { var base64Url = token.split('.')[1]; var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/'); var jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) { return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2); }).join('')); return JSON.parse(jsonPayload); } Utils.embedTextInBlob = function(fileOrBlob, textToEmbed, callback) { gs.println("textToEmbed"); gs.println(textToEmbed); if (!gs.bool(textToEmbed)) { return gs.execCall(callback, this, [fileOrBlob]); }; return Utils.embedTextInBlobNative(fileOrBlob, textToEmbed, callback); } Utils.embedTextInBlobNative = function(fileOrBlob, text, callback) { const reader = new FileReader(); reader.onload = function (e) { const img = new Image(); img.onload = function () { const canvas = document.createElement("canvas"); const ctx = canvas.getContext("2d"); canvas.width = img.width; canvas.height = img.height; var fontSize = canvas.width * 0.025 console.log('fontSize1', fontSize) if (fontSize < 5 ) fontSize = 5 console.log('fontSize2', fontSize) // Draw the image ctx.drawImage(img, 0, 0); // Draw text bottom-right ctx.font = fontSize+"px Sans-serif"; ctx.fillStyle = "White"; ctx.textAlign = "right"; ctx.textBaseline = "bottom"; const padding = 2; ctx.fillText(text, canvas.width - padding, canvas.height - padding); // Return result as a Blob canvas.toBlob(function (blob) { callback(blob); }, "image/png"); }; img.onerror = function (err) { callback("Image failed to load: " + err); }; img.src = e.target.result; }; reader.onerror = function (err) { callback("FileReader error: " + err); }; // Read the file/blob as Data URL reader.readAsDataURL(fileOrBlob); } Utils.blobToDataUrl = function(blob, callback) { const fileReader = new FileReader(); fileReader.onload = function() { callback(fileReader.result) } fileReader.readAsDataURL(blob); } Utils.dataUrlToBlob = function(dataUrl, callback) { return gs.mc(gs.mc(gs.mc(Utils.window,"fetch",[dataUrl]),"then",[function(res) { return gs.mc(res,"blob",[]); }]),"then",[function(blob) { return gs.execCall(callback, this, [blob]); }]); } Utils.take = function(string, len) { if (len === undefined) len = 40; if ((!gs.bool(string)) || (gs.mc(string,"size",[]) < len)) { return string; }; return gs.rangeFromList(string, 0, len); } Utils.session = gs.execStatic(Session,'instance', this,[]); Utils.window = null; Utils.document = null; Utils.DeviceTypes = gs.map().add("ANDROID","android").add("IOS","ios").add("ELECTRON","electron").add("BROWSER","browser"); Utils.AUTH_FAILED = "AUTH_FAILED"; Utils.NO_AUTH = "NO_AUTH"; Utils.REMEMBER_FALLBACK_DAYS = 30; function ObjectRegistry() { var gSobject = gs.init('ObjectRegistry'); gSobject.clazz = { name: 'ObjectRegistry', simpleName: 'ObjectRegistry'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; Object.defineProperty(gSobject, 'objectRegistry', { get: function() { return ObjectRegistry.objectRegistry; }, set: function(gSval) { ObjectRegistry.objectRegistry = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'enabled', { get: function() { return ObjectRegistry.enabled; }, set: function(gSval) { ObjectRegistry.enabled = gSval; }, enumerable: true }); gSobject.object = function(x0) { return ObjectRegistry.object(x0); } gSobject.register = function(x0) { return ObjectRegistry.register(x0); } gSobject.registerSingle = function(x0,x1) { return ObjectRegistry.registerSingle(x0,x1); } gSobject.isDatabaseObject = function(x0) { return ObjectRegistry.isDatabaseObject(x0); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; ObjectRegistry.object = function(id) { return ObjectRegistry.objectRegistry[id]; } ObjectRegistry.register = function(objects) { if (!gs.bool(ObjectRegistry.enabled)) { return objects; }; if (gs.instanceOf(objects, "ArrayList")) { var oObjectList = gs.list([]); gs.mc(objects,"eachWithIndex",[function(object, index) { return gs.mc(oObjectList,"add",[gs.mc(ObjectRegistry,"registerSingle",[object])]); }]); return oObjectList; } else { return ObjectRegistry.registerSingle(objects); }; } ObjectRegistry.registerSingle = function(object, flatCopy) { if (flatCopy === undefined) flatCopy = true; if (!gs.bool(ObjectRegistry.isDatabaseObject(object))) { return object; }; var oObject = ObjectRegistry.objectRegistry[gs.gp(object,"_id")]; if (!gs.bool(oObject)) { oObject = OObject(object); (ObjectRegistry.objectRegistry[gs.gp(object,"_id")]) = oObject; } else { gs.mc(oObject,"merge",[object, flatCopy]); }; gs.mc(object,"each",[function(key, value) { if (gs.mc(ObjectRegistry,"isDatabaseObject",[value])) { var newValue = gs.mc(ObjectRegistry,"registerSingle",[value, false]); return (gs.gp(oObject,"internalMap")[key]) = gs.mc(newValue,"toJs",[]); } else { if ((value != null) && (gs.instanceOf(value, "ArrayList"))) { var oObjectList = gs.list([]); gs.mc(value,"eachWithIndex",[function(objectVal, index) { if (gs.mc(ObjectRegistry,"isDatabaseObject",[objectVal])) { return gs.mc(oObjectList,"add",[gs.mc(gs.mc(ObjectRegistry,"registerSingle",[objectVal]),"toJs",[])]); } else { return gs.mc(oObjectList,"add",[objectVal]); }; }]); return (gs.gp(oObject,"internalMap")[key]) = oObjectList; }; }; }]); gs.execStatic(Utils,'setTimeout', this,[function(it) { return gs.mc(gs.execStatic(LocalDB,'getInstance', this,[]),"updateIfExists",[oObject]); }, 100]); return oObject; } ObjectRegistry.isDatabaseObject = function(object) { return ((object != null) && (gs.instanceOf(object, "HashMap"))) && (gs.bool(gs.gp(object,"_id"))); } ObjectRegistry.objectRegistry = gs.map(); ObjectRegistry.enabled = false; function OObject() { var gSobject = gs.init('OObject'); gSobject.clazz = { name: 'OObject', simpleName: 'OObject'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.internalMap = gs.map(); gSobject.methodMissingName = null; gSobject.methodMissingArgs = null; gs.astDelegate('OObject', 'internalMap'); gSobject.refresher = null; gSobject.updateCallback = function(it) { }; gSobject['subscribe'] = function(it) { return gs.execStatic(Utils,'subscribe', this,[gs.gp(gSobject.internalMap,"_id"), gSobject.updateCallback]); } gSobject['unsubscribe'] = function(it) { return gs.execStatic(Utils,'unsubscribe', this,[gs.gp(gSobject.internalMap,"_id")]); } gSobject['setRefresher'] = function(closure, update) { if (update === undefined) update = true; gs.mc(gSobject,"subscribe",[]); if ((!gs.bool(gSobject.refresher)) || ((gs.bool(gSobject.refresher)) && (gs.bool(update)))) { return gSobject.refresher = closure; }; } gSobject['merge'] = function(object, flatCopy) { if (flatCopy === undefined) flatCopy = true; if ((gs.bool(object)) && (gs.instanceOf(object, "OObject"))) { object = gs.gp(object,"internalMap"); }; gs.mc(object,"each",[function(key, value) { if (gs.bool(flatCopy)) { (gSobject.internalMap[key]) = value; return null; }; if (!gs.bool(((value != null) && (gs.instanceOf(value, "String"))) && (gs.execStatic(ObjectRegistry,'isDatabaseObject', this,[gSobject.internalMap[key]])))) { return (gSobject.internalMap[key]) = value; } else { gs.println("WARNING: skip overwrite of DatabaseObject with String"); gs.println(gs.plus("Key:", key)); gs.println(gs.plus("String:", value)); gs.println("internalMap[key]:"); gs.println(gSobject.internalMap[key]); gs.println("Object:"); return gs.println(gSobject.internalMap); }; }]); if (gs.bool(gSobject.refresher)) { return gs.mc(gSobject,"refresher",[this]); }; } gSobject['toJs'] = function(it) { return gSobject.internalMap; } gSobject['toString'] = function(it) { return gs.mc(gSobject.internalMap,"toString",[]); } gSobject['setProperty'] = function(name, value) { return (gSobject.internalMap[name]) = value; } gSobject['getProperty'] = function(name) { return gSobject.internalMap[name]; } gSobject['methodMissing'] = function(name, args) { gSobject.methodMissingName = name; gSobject.methodMissingArgs = args; if (gs.bool(args)) { var successClosure = gs.mc(args,"last",[]); if (gs.instanceOf(successClosure, "Closure")) { if (gs.equals(gs.mc(args,"size",[]), 1)) { args = null; } else { args = (gs.rangeFromList(args, 0, -2)); }; gSobject.methodMissingArgs = args; return gs.mc(gSobject,"then",[successClosure]); }; }; } gSobject['then'] = function(successClosure, fail) { if (successClosure === undefined) successClosure = function(it) { }; if (fail === undefined) fail = function(it) { }; return gs.execStatic(Utils,'callObject', this,[gSobject.internalMap, gSobject.methodMissingName, gSobject.methodMissingArgs, successClosure, fail]); } gSobject['do'] = function(success) { if (success === undefined) success = function(it) { }; return gs.mc(gSobject,"then",[success, null]); } gSobject.await = function() { } gSobject.promise = function() { var self = this; return new Promise(function(resolve, reject) { self.then(resolve, function(err) { reject(err); }); }); } gSobject['OObject1'] = function(self) { gs.mc(gSobject,"merge",[self]); return this; } if (arguments.length==1) {gSobject.OObject1(arguments[0]); } return gSobject; }; function ObjectFinder() { var gSobject = gs.init('ObjectFinder'); gSobject.clazz = { name: 'ObjectFinder', simpleName: 'ObjectFinder'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; Object.defineProperty(gSobject, 'singleO', { get: function() { return ObjectFinder.singleO; }, set: function(gSval) { ObjectFinder.singleO = gSval; }, enumerable: true }); gSobject.log = RemoteLog("Transmission"); gSobject.getInstance = function() { return ObjectFinder.getInstance(); } gSobject['propertyMissing'] = function(name) { var argList = gs.list([gs.map().add("property",name)]); return NestedO(argList, CacheCallTracker(0, false, false)); } gSobject['local'] = function(ttl, remoteOnce) { if (remoteOnce === undefined) remoteOnce = false; var argList = gs.list([]); return NestedO(argList, CacheCallTracker(ttl, remoteOnce)); } gSobject['localAndRemote'] = function(ttl) { if (ttl === undefined) ttl = -1; gs.println("localAndRemote"); return gs.mc(gSobject,"local",[ttl]); } gSobject['localAndRemoteOnce'] = function(ttl) { if (ttl === undefined) ttl = -1; return gs.mc(gSobject,"local",[ttl, true]); } gSobject['post'] = function(file, parameter, objectName, id, callback) { if (objectName === undefined) objectName = null; if (id === undefined) id = null; if (callback === undefined) callback = function(it) { }; if (!gs.bool(file)) { gs.println("No file selected"); return null; }; gs.println(gs.plus("file: ", file)); gs.println(gs.plus("parameter: ", parameter)); gs.println(gs.plus("objectName: ", objectName)); gs.println(gs.plus("id: ", id)); return gs.execStatic(Utils,'post', this,[file, parameter, objectName, id, callback]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; ObjectFinder.getInstance = function(it) { if (gs.bool(ObjectFinder.singleO)) { return ObjectFinder.singleO; }; ObjectFinder.singleO = ObjectFinder(); return ObjectFinder.singleO; } ObjectFinder.singleO = null; function RemoteLog() { var gSobject = gs.init('RemoteLog'); gSobject.clazz = { name: 'RemoteLog', simpleName: 'RemoteLog'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.className = null; gSobject['info'] = function(message) { return gs.mc(gSobject,"generic",["info", message]); } gSobject['debug'] = function(message) { return gs.mc(gSobject,"generic",["debug", message]); } gSobject['warn'] = function(message) { return gs.mc(gSobject,"generic",["warn", message]); } gSobject['error'] = function(message) { return gs.mc(gSobject,"generic",["error", message]); } gSobject['off'] = function(message) { return gs.mc(gSobject,"generic",["off", message]); } gSobject['trace'] = function(message) { return gs.mc(gSobject,"generic",["trace", message]); } gSobject['generic'] = function(callName, message) { try { gs.println(gs.plus((gs.plus(gSobject.className, ":")), message)); } catch (all) { } ; return gs.mc(gs.mc(gs.mc(gs.execStatic(ObjectFinder,'getInstance', this,[]),"propertyMissing",["log"]),"" + (callName) + "",[message, gSobject.className]),"do",[]); } gSobject['RemoteLog1'] = function(className) { gs.sp(this,"className",className); return this; } if (arguments.length==1) {gSobject.RemoteLog1(arguments[0]); } return gSobject; }; function NestedO() { var gSobject = gs.init('NestedO'); gSobject.clazz = { name: 'NestedO', simpleName: 'NestedO'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.cacheCallTracker = null; gSobject.successClosure = null; gSobject.failClosure = function(it) { }; gSobject.argList = gs.list([]); gSobject['methodMissing'] = function(name, args) { if (gs.mc(gSobject.argList,"size",[]) > 16) { throw {message: "Maximum call stack size 16 exceeded"}; }; if (gs.bool(args)) { var successClosure = gs.mc(args,"last",[]); var failClosure = function(it) { }; if ((gs.bool(successClosure)) && (gs.instanceOf(successClosure, "Closure"))) { if (gs.equals(gs.mc(args,"size",[]), 1)) { args = null; } else { args = (gs.rangeFromList(args, 0, -2)); if ((gs.mc(args,"last",[])) && (gs.instanceOf(gs.mc(args,"last",[]), "Closure"))) { failClosure = successClosure; successClosure = gs.mc(args,"last",[]); if (gs.equals(gs.mc(args,"size",[]), 1)) { args = null; } else { args = (gs.rangeFromList(args, 0, -2)); }; }; }; gs.mc(gSobject.argList,"add",[gs.map().add("method",name).add("args",args)]); gs.sp(this,"successClosure",successClosure); gs.sp(this,"failClosure",failClosure); gs.mc(gSobject,"then",[successClosure, failClosure]); return null; }; }; gs.mc(gSobject.argList,"add",[gs.map().add("method",name).add("args",args)]); return NestedO(gSobject.argList, gSobject.cacheCallTracker); } gSobject.isUndefined = function(val) { return val === undefined } gSobject['propertyMissing'] = function(name) { if (gs.mc(gSobject.argList,"size",[]) > 16) { throw {message: "Maximum call stack size 16 exceeded"}; }; gs.mc(gSobject.argList,"add",[gs.map().add("property",name)]); return NestedO(gSobject.argList, gSobject.cacheCallTracker); } gSobject['then'] = function(success, fail) { if (fail === undefined) fail = function(it) { }; return gs.mc(gSobject.cacheCallTracker,"callAndCache",[gSobject.argList, success, fail]); } gSobject['do'] = function(it) { return gs.mc(gSobject,"then",[function(it) { }]); } gSobject.await = function() { } gSobject.promise = function() { var self = this; return new Promise(function(resolve, reject) { self.then(resolve, function(err) { reject(err); }); }); } gSobject['NestedO2'] = function(argList, cacheCallTracker) { gs.sp(this,"cacheCallTracker",cacheCallTracker); gs.sp(this,"argList",argList); return this; } if (arguments.length==2) {gSobject.NestedO2(arguments[0], arguments[1]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function LocalDB() { var gSobject = gs.init('LocalDB'); gSobject.clazz = { name: 'LocalDB', simpleName: 'LocalDB'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; Object.defineProperty(gSobject, 'DB_VERSION_NO', { get: function() { return LocalDB.DB_VERSION_NO; }, set: function(gSval) { LocalDB.DB_VERSION_NO = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'DB_NAME', { get: function() { return LocalDB.DB_NAME; }, set: function(gSval) { LocalDB.DB_NAME = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'MAX_ROWS_PER_BATCH', { get: function() { return LocalDB.MAX_ROWS_PER_BATCH; }, set: function(gSval) { LocalDB.MAX_ROWS_PER_BATCH = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'ASYNC_DB', { get: function() { return LocalDB.ASYNC_DB; }, set: function(gSval) { LocalDB.ASYNC_DB = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'DB_COMPRESS', { get: function() { return LocalDB.DB_COMPRESS; }, set: function(gSval) { LocalDB.DB_COMPRESS = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'DB_ENCRYPT', { get: function() { return LocalDB.DB_ENCRYPT; }, set: function(gSval) { LocalDB.DB_ENCRYPT = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'startupCompleted', { get: function() { return LocalDB.startupCompleted; }, set: function(gSval) { LocalDB.startupCompleted = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'instance', { get: function() { return LocalDB.instance; }, set: function(gSval) { LocalDB.instance = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'jsDbInstance', { get: function() { return LocalDB.jsDbInstance; }, set: function(gSval) { LocalDB.jsDbInstance = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'db', { get: function() { return LocalDB.db; }, set: function(gSval) { LocalDB.db = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'objectMaps', { get: function() { return LocalDB.objectMaps; }, set: function(gSval) { LocalDB.objectMaps = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'callbacks', { get: function() { return LocalDB.callbacks; }, set: function(gSval) { LocalDB.callbacks = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'checkVersion', { get: function() { return LocalDB.checkVersion; }, set: function(gSval) { LocalDB.checkVersion = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'cleanupStaleData', { get: function() { return LocalDB.cleanupStaleData; }, set: function(gSval) { LocalDB.cleanupStaleData = gSval; }, enumerable: true }); gSobject.localO = LocalDB$LocalO(this); gSobject.getInstance = function(x0) { return LocalDB.getInstance(x0); } gSobject.initDb = function(x0,x1) { return LocalDB.initDb(x0,x1); } gSobject.dropDatabase = function(x0) { return LocalDB.dropDatabase(x0); } gSobject['cacheObjects'] = function(key, objectsIn, ttl, callback) { var ttlInMs = (gs.equals(ttl, -1) ? null : gs.plus(gs.gp(gs.date(),"time"), (gs.multiply(ttl, 1000)))); key = (gs.plus("c:", key)); return gs.mc(LocalDB.db,"upsert",[gs.map().add("_id",key).add("_ttl",ttlInMs).add("stringValue",gs.execStatic(Utils,'mapToJsonString', this,[objectsIn])), function(it) { var callbackTmp = callback; callback = null; if (gs.bool(callbackTmp)) { return gs.execCall(callbackTmp, this, []); }; }]); } gSobject['readCache'] = function(key) { key = (gs.plus("c:", key)); var keyObject = gs.mc(LocalDB.db,"find",[gs.map().add("_id",key)]); gs.println(keyObject); if (gs.equals(gs.gp(keyObject,"length"), 0)) { return null; }; keyObject = (keyObject[0]); if ((gs.bool(gs.gp(keyObject,"_ttl"))) && (gs.gp(keyObject,"_ttl") <= gs.gp(gs.date(),"time"))) { gs.mc(LocalDB.db,"remove",[gs.map().add("_id",key)]); gs.mc(LocalDB.db,"save",[]); return null; }; return gs.execStatic(Utils,'stringToJson', this,[gs.gp(keyObject,"stringValue")]); } gSobject['registerPath'] = function(objectName, objectMap) { return (LocalDB.objectMaps[objectName]) = objectMap; } gSobject['insert'] = function(object, callback) { if (callback === undefined) callback = null; object = (gs.mc(gs.map(),'leftShift', gs.list([object]))); gs.mc(gSobject,"fixDatesToDb",[object]); if (gs.bool(callback)) { return gs.mc(LocalDB.db,"upsert",[object, function(it) { var callbackTmp = callback; callback = null; if (gs.bool(callbackTmp)) { return gs.execCall(callbackTmp, this, [object]); }; }]); }; gs.mc(LocalDB.db,"upsert",[object]); gs.mc(LocalDB.db,"save",[]); return object; } gSobject['save'] = function(object, callback) { if (callback === undefined) callback = null; gs.sp(object,"_dateCreated",gs.elvis(gs.bool(gs.gp(object,"_dateCreated")) , gs.gp(object,"_dateCreated") , gs.date())); gs.sp(object,"_lastUpdated",gs.date()); gs.sp(object,"_remoteChange",true); return gs.mc(gSobject,"insert",[object, callback]); } gSobject['insertAll'] = function(objects, callback) { if (callback === undefined) callback = function(it) { }; for (_i29 = 0, object = objects[0]; _i29 < objects.length; object = objects[++_i29]) { gs.mc(this,"fixDatesToDb",[object], gSobject); }; return gs.mc(LocalDB.db,"upsert",[objects, callback]); } gSobject['saveAll'] = function(objects, callback) { if (callback === undefined) callback = function(it) { }; for (_i30 = 0, object = objects[0]; _i30 < objects.length; object = objects[++_i30]) { gs.sp(object,"_dateCreated",gs.elvis(gs.bool(gs.gp(object,"_dateCreated")) , gs.gp(object,"_dateCreated") , gs.date())); gs.sp(object,"_lastUpdated",gs.date()); gs.sp(object,"_remoteChange",true); }; return gs.mc(gSobject,"insertAll",[objects, callback]); } gSobject['commit'] = function(errorCallback) { if (errorCallback === undefined) errorCallback = function(it) { }; return gs.mc(LocalDB.db,"save",[errorCallback]); } gSobject['updateIfExists'] = function(object) { var keyObject = gs.mc(LocalDB.db,"find",[gs.toJavascript(gs.map().add("_id",gs.gp(object,"_id")))]); if (gs.bool(keyObject)) { return gs.mc(gSobject,"insert",[object]); }; } gSobject['getO'] = function(it) { return gSobject.localO; } gSobject['objectCallWrapper'] = function(objectName) { var staticFilter = LocalDB.objectMaps[objectName]; return gs.map().add("getOne",function(id, callback) { if (callback === undefined) callback = null; return gs.mc(LocalDB.instance,"getOne",[id, callback]); }).add("findOne",function(filter, callback) { if (callback === undefined) callback = null; return gs.mc(LocalDB.instance,"findOne",[gs.mc(filter,'leftShift', gs.list([staticFilter])), callback]); }).add("findOrCreate",function(filter, mapToSave, callback) { if (mapToSave === undefined) mapToSave = gs.map(); if (callback === undefined) callback = null; return gs.mc(LocalDB.instance,"findOrCreate",[gs.mc(filter,'leftShift', gs.list([staticFilter])), mapToSave, callback]); }).add("find",function(filter, params) { if (params === undefined) params = gs.map(); return gs.mc(LocalDB.instance,"find",[gs.mc(filter,'leftShift', gs.list([staticFilter])), params]); }).add("findAll",function(params) { if (params === undefined) params = gs.map(); return gs.mc(LocalDB.instance,"find",[staticFilter, params]); }).add("new",function(initParams) { if (initParams === undefined) initParams = gs.map(); var item = gs.mc(initParams,'leftShift', gs.list([staticFilter])); gs.sp(item,"_id",gs.execStatic(Utils,'uuid', this,[])); return gs.mc(gSobject,"decorate",[item]); }); } gSobject['findOrCreate'] = function(filter, mapToSave, callback) { if (mapToSave === undefined) mapToSave = gs.map(); if (callback === undefined) callback = null; var item = gs.mc(gSobject,"findOne",[filter]); if (gs.bool(item)) { if (gs.bool(callback)) { return gs.execCall(callback, this, [item]); }; return item; }; mapToSave = (gs.mc(gs.mc(mapToSave,"clone",[]),'leftShift', gs.list([filter]))); gs.sp(mapToSave,"_id",gs.execStatic(Utils,'uuid', this,[])); if (gs.bool(callback)) { return gs.mc(LocalDB.instance,"save",[mapToSave, function(savedItem) { return gs.mc(gSobject,"getOne",[gs.gp(savedItem,"_id"), callback]); }]); }; item = gs.mc(LocalDB.instance,"save",[mapToSave]); return gs.mc(gSobject,"getOne",[gs.gp(item,"_id")]); } gSobject['getOne'] = function(id, expandableFields, level) { if (expandableFields === undefined) expandableFields = null; if (level === undefined) level = 1; return gs.mc(gSobject,"getOne",[id, null, expandableFields, level]); } gSobject['getOne'] = function(id, callback, expandableFields, level) { if (expandableFields === undefined) expandableFields = null; if (level === undefined) level = 1; if (gs.bool(expandableFields)) { return gs.mc(gSobject,"findOne",[gs.map().add("_id",id), callback, expandableFields, level]); } else { return gs.mc(gSobject,"findOne",[gs.map().add("_id",id), callback]); }; } gSobject['findOne'] = function(filter, callback, expandableFields, level) { if (callback === undefined) callback = null; if (expandableFields === undefined) expandableFields = null; if (level === undefined) level = 1; return gs.mc(gSobject,"findOne",[filter, null, expandableFields, level]); } gSobject['findOne'] = function(filter, callback, expandableFields, level) { if (callback === undefined) callback = null; if (expandableFields === undefined) expandableFields = null; if (level === undefined) level = 1; var item = null; if (gs.bool(expandableFields)) { item = gs.mc(gSobject,"find",[filter, gs.map().add("limit",1), expandableFields, level]); } else { item = gs.mc(gSobject,"find",[filter, gs.map().add("limit",1)]); }; if (!gs.bool(item)) { if (gs.bool(callback)) { gs.execCall(callback, this, [gs.map()]); }; return gs.map(); }; item = (item[0]); gs.mc(gSobject,"decorate",[item]); if (gs.bool(callback)) { gs.execCall(callback, this, [item]); }; return item; } gSobject['delete'] = function(id, callback) { if (callback === undefined) callback = function(it) { }; gs.mc(LocalDB.db,"remove",[gs.map().add("_id",id)]); return gs.mc(LocalDB.db,"save",[callback]); } gSobject['find'] = function(filter, params, expandableFields, level) { if (params === undefined) params = gs.map(); if (expandableFields === undefined) expandableFields = null; if (level === undefined) level = 1; var dbList = gs.mc(LocalDB.db,"find",[gs.toJavascript(filter), gs.toJavascript(gs.mc((gs.mc(gs.mc(gSobject,"getLimit",[params]),'leftShift', gs.list([gs.mc(gSobject,"getSkip",[params])]))),'leftShift', gs.list([gs.mc(gSobject,"getSort",[params])])))]); var objectList = gs.list([]); gs.mc(dbList,"each",[function(dbItem) { var item = gs.mc(gs.map(),'leftShift', gs.list([dbItem])); gs.mc(gSobject,"fixDatesFromDb",[item]); gs.mc(gSobject,"decorate",[item]); if (gs.bool(expandableFields)) { item = gs.mc(gSobject,"expandItem",[item, expandableFields, level]); }; return gs.mc(objectList,"add",[item]); }]); return objectList; } gSobject['remove'] = function(filter, callback) { if (callback === undefined) callback = function(it) { }; return gs.mc(LocalDB.db,"remove",[gs.toJavascript(filter)]); } gSobject['count'] = function(filter) { return gs.mc(LocalDB.db,"count",[gs.toJavascript(filter)]); } gSobject['expandItem'] = function(item, expandableFields, level) { if (level === undefined) level = 1; var fields = gs.mc(expandableFields,"collect",[function(it) { return gs.gp(it,"field"); }]); gs.mc(item,"each",[function(k, v) { if (gs.mc(fields,"contains",[k])) { if (((gs.equals(v, null)) || (gs.equals(v, gs.fs('undefined', this, gSobject)))) || (gs.equals(v, ""))) { return null; }; var currentField = gs.mc(expandableFields,"find",[function(it) { return gs.equals(gs.gp(it,"field"), k); }]); if (gs.instanceOf(v, "List")) { var expandResult = gs.mc(LocalDB.db,"find",[gs.toJavascript(gs.map().add("_id",gs.map().add("$in",v)).add("_path",gs.gp(currentField,"_path")))]); var expandResultObjects = gs.list([]); gs.mc(expandResult,"each",[function(expandResultItem) { var expandedItem = gs.mc(gs.map(),'leftShift', gs.list([expandResultItem])); gs.mc(gSobject,"fixDatesFromDb",[expandedItem]); if (level > 1) { expandedItem = gs.mc(gSobject,"expandItem",[expandedItem, expandableFields, gs.minus(level, 1)]); }; return gs.mc(expandResultObjects,"add",[expandedItem]); }]); return (item[k]) = gs.elvis(gs.bool(expandResultObjects) , expandResultObjects , gs.list([])); } else { var expandResult = gs.mc(LocalDB.db,"find",[gs.toJavascript(gs.map().add("_id",v).add("_path",gs.gp(currentField,"_path"))), gs.toJavascript(gs.mc(gSobject,"getLimit",[gs.map().add("limit",1)]))])[0]; var expandedItem = gs.mc(gs.map(),'leftShift', gs.list([expandResult])); gs.mc(gSobject,"fixDatesFromDb",[expandedItem]); if (level > 1) { expandedItem = gs.mc(gSobject,"expandItem",[expandedItem, expandableFields, gs.minus(level, 1)]); }; return (item[k]) = gs.elvis(gs.bool(expandedItem) , expandedItem , null); }; }; }]); return item; } gSobject['getLimit'] = function(params) { return gs.map().add("$limit",gs.elvis(gs.bool(params["limit"]) , params["limit"] , gs.elvis(gs.bool(gs.gp(params,"max")) , gs.gp(params,"max") , LocalDB.MAX_ROWS_PER_BATCH))); } gSobject['getSkip'] = function(params) { return gs.map().add("$skip",gs.elvis(gs.bool(gs.gp(params,"offset")) , gs.gp(params,"offset") , gs.elvis(gs.bool(params["skip"]) , params["skip"] , 0))); } gSobject['getSort'] = function(params) { var order = 1; if (gs.equals(gs.gp(params,"order"), "desc")) { order = -1; }; if (gs.bool(params["sort"])) { return gs.map().add("$orderBy",gs.map().add(params["sort"],order)); }; return gs.map(); } gSobject['fixDatesToDb'] = function(object) { gs.mc(object,"each",[function(key, value) { if ((gs.bool(value)) && (gs.instanceOf(value, "HashMap"))) { gs.mc(gSobject,"fixDatesToDb",[value]); }; if (gs.execStatic(Utils,'isDate', this,[value])) { return (object[key]) = gs.mc(LocalDB.db,"make",[value]); }; }]); return object; } gSobject['fixDatesFromDb'] = function(object) { gs.mc(object,"each",[function(key, value) { if ((gs.bool(value)) && (gs.instanceOf(value, "HashMap"))) { gs.mc(gSobject,"fixDatesFromDb",[value]); }; if (gs.execStatic(Utils,'isDate', this,[value])) { return (object[key]) = gs.date(value); }; }]); return object; } gSobject['decorate'] = function(item) { gs.sp(item,"merge",function(map) { gs.mc(item,"putAll",[map]); return item; }); gs.sp(item,"save",function(callback) { if (callback === undefined) callback = null; return gs.mc(LocalDB.instance,"save",[item, callback]); }); gs.sp(item,"delete",function(callback) { if (callback === undefined) callback = null; return gs.mc(LocalDB.instance,"delete",[gs.gp(item,"_id"), callback]); }); return item; } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; LocalDB.getInstance = function(callback) { if (callback === undefined) callback = function(it) { }; if (!gs.bool(LocalDB.instance)) { LocalDB.instance = LocalDB(); if (!gs.bool(LocalDB.db)) { LocalDB.initDb(LocalDB.DB_NAME, function(it) { return gs.mc(LocalDB,"checkVersion",[function(it) { return gs.mc(LocalDB,"cleanupStaleData",[function(it) { LocalDB.startupCompleted = true; gs.execCall(callback, this, [LocalDB.instance]); gs.mc(LocalDB.callbacks,"each",[function(it) { return gs.execCall(it, this, [LocalDB.instance]); }]); return LocalDB.callbacks = gs.list([]); }]); }]); }); }; } else { if (!gs.bool(LocalDB.startupCompleted)) { gs.mc(LocalDB.callbacks,"add",[callback]); return LocalDB.instance; }; gs.execCall(callback, this, [LocalDB.instance]); }; return LocalDB.instance; } LocalDB.initDb = function(dbName, callback) { var fdb = new ForerunnerDB(); var forerunnerdb = fdb.db(dbName); // if (LocalDB.DB_COMPRESS) forerunnerdb.persist.addStep(new forerunnerdb.shared.plugins.FdbCompress()); // if (LocalDB.DB_ENCRYPT) forerunnerdb.persist.addStep(new forerunnerdb.shared.plugins.FdbCrypto({ // pass: "dbStoreCode" // })); forerunnerdb.persist.addStep(new forerunnerdb.shared.plugins.FdbCompress()); forerunnerdb.persist.addStep(new forerunnerdb.shared.plugins.FdbCrypto({ pass: "dbStoreCode" })); var collection = forerunnerdb.collection("appCollection") // collection.deferredCalls(LocalDB.ASYNC_DB) collection.deferredCalls(false) collection.load(function (err, tableStats, metaStats) { if (err) { console.error('forerunnerdb error') }else{ console.log('forerunnerdb started') } LocalDB.jsDbInstance = forerunnerdb LocalDB.db = collection callback() }); } LocalDB.dropDatabase = function(callback) { if (callback === undefined) callback = function(it) { }; return gs.mc(LocalDB.jsDbInstance,"drop",[true, function(it) { return gs.mc(LocalDB,"initDb",[LocalDB.DB_NAME, function(it) { return gs.mc(LocalDB.db,"upsert",[gs.map().add("_id","dbVersionNumber").add("version",LocalDB.DB_VERSION_NO), callback]); }]); }]); } LocalDB.DB_VERSION_NO = "1.2"; LocalDB.DB_NAME = "1"; LocalDB.MAX_ROWS_PER_BATCH = 1000; LocalDB.ASYNC_DB = false; LocalDB.DB_COMPRESS = true; LocalDB.DB_ENCRYPT = true; LocalDB.startupCompleted = false; LocalDB.instance = null; LocalDB.jsDbInstance = null; LocalDB.db = null; LocalDB.objectMaps = gs.map(); LocalDB.callbacks = gs.list([]); LocalDB.checkVersion = function(callback) { if (callback === undefined) callback = function(it) { }; gs.println("LocalDB.checkVersion"); var version = gs.mc(LocalDB.db,"find",[gs.map().add("_id","dbVersionNumber")]); if ((gs.equals(gs.gp(version,"length"), 0)) || (gs.gp(version[0],"version") != LocalDB.DB_VERSION_NO)) { gs.println("FOUND OLD DB:DROP DB"); gs.mc(LocalDB,"dropDatabase",[callback]); return null; }; return gs.execCall(callback, this, []); }; LocalDB.cleanupStaleData = function(callback) { if (callback === undefined) callback = function(it) { }; gs.println("LocalDB.cleanupStaleData"); var nowMs = gs.gp(gs.date(),"time"); return gs.execCall(callback, this, []); }; function LocalDB$LocalO() { var gSobject = gs.init('LocalDB$LocalO'); gSobject.clazz = { name: 'LocalDB$LocalO', simpleName: 'LocalDB$LocalO'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.this$0 = null; gSobject['propertyMissing'] = function(objectName) { return gs.mc(gs.gp(LocalDB,"instance"),"objectCallWrapper",[objectName]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function CacheCallTracker() { var gSobject = gs.init('CacheCallTracker'); gSobject.clazz = { name: 'CacheCallTracker', simpleName: 'CacheCallTracker'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; Object.defineProperty(gSobject, 'remoteOnceMap', { get: function() { return CacheCallTracker.remoteOnceMap; }, set: function(gSval) { CacheCallTracker.remoteOnceMap = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'resultCache', { get: function() { return CacheCallTracker.resultCache; }, set: function(gSval) { CacheCallTracker.resultCache = gSval; }, enumerable: true }); gSobject.ttl = 0; gSobject.remoteOnce = false; gSobject['callAndCache'] = function(argList, successClosure, fail) { if (successClosure === undefined) successClosure = function(it) { }; if (fail === undefined) fail = null; var argListString = gs.mc(argList,"toString",[]); if (!gs.bool(gSobject.ttl)) { return gs.execStatic(Socket,'callChain', this,[argList, function(result) { return gs.execCall(successClosure, this, [result]); }, fail]); }; var objects = CacheCallTracker.resultCache[argListString]; return gs.execStatic(LocalDB,'getInstance', this,[function(localDB) { if (!gs.bool(objects)) { objects = gs.mc(gs.execStatic(LocalDB,'getInstance', this,[]),"readCache",[argListString]); }; if (gs.bool(objects)) { gs.execStatic(ObjectRegistry,'register', this,[objects]); gs.execCall(successClosure, this, [objects]); }; return gs.execStatic(Utils,'setTimeout', this,[function(it) { if (gs.bool(objects)) { (CacheCallTracker.remoteOnceMap[argListString]) = (CacheCallTracker.remoteOnceMap[argListString] ? gs.plus((CacheCallTracker.remoteOnceMap[argListString]), 1) : 1); if ((gs.bool(gSobject.remoteOnce)) && ((CacheCallTracker.remoteOnceMap[argListString]) > 1)) { return null; }; }; return gs.execStatic(Socket,'callChain', this,[argList, function(result) { (CacheCallTracker.resultCache[argListString]) = result; gs.execCall(successClosure, this, [result]); return gs.execStatic(Utils,'setTimeout', this,[function(it) { return gs.mc(gSobject,"syncCache",[argListString, result, function(it) { return gs.println("syncCache:done"); }]); }, 0]); }, fail]); }, 0]); }]); } gSobject['syncCache'] = function(argListString, objects, callback) { if (gs.bool(gSobject.ttl)) { return gs.execStatic(LocalDB,'getInstance', this,[function(it) { return gs.mc(gs.execStatic(LocalDB,'getInstance', this,[]),"cacheObjects",[argListString, objects, gSobject.ttl, callback]); }]); }; } gSobject['CacheCallTracker2'] = function(ttl, remoteOnce) { gs.sp(this,"ttl",ttl); gs.sp(this,"remoteOnce",remoteOnce); return this; } if (arguments.length==2) {gSobject.CacheCallTracker2(arguments[0], arguments[1]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; CacheCallTracker.remoteOnceMap = gs.map(); CacheCallTracker.resultCache = gs.map(); function GpsLocationTracker() { var gSobject = gs.init('GpsLocationTracker'); gSobject.clazz = { name: 'GpsLocationTracker', simpleName: 'GpsLocationTracker'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; Object.defineProperty(gSobject, 'HIGH_ACCURACY', { get: function() { return GpsLocationTracker.HIGH_ACCURACY; }, set: function(gSval) { GpsLocationTracker.HIGH_ACCURACY = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'MEDIUM_ACCURACY', { get: function() { return GpsLocationTracker.MEDIUM_ACCURACY; }, set: function(gSval) { GpsLocationTracker.MEDIUM_ACCURACY = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'LOW_ACCURACY', { get: function() { return GpsLocationTracker.LOW_ACCURACY; }, set: function(gSval) { GpsLocationTracker.LOW_ACCURACY = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'PASSIVE_ACCURACY', { get: function() { return GpsLocationTracker.PASSIVE_ACCURACY; }, set: function(gSval) { GpsLocationTracker.PASSIVE_ACCURACY = gSval; }, enumerable: true }); gSobject.gpsService = null; gSobject.lastLocation = null; Object.defineProperty(gSobject, 'singletonInstance', { get: function() { return GpsLocationTracker.singletonInstance; }, set: function(gSval) { GpsLocationTracker.singletonInstance = gSval; }, enumerable: true }); gSobject.desiredAccuracy = GpsLocationTracker.HIGH_ACCURACY; gSobject.instance = function() { return GpsLocationTracker.instance(); } gSobject['config'] = function(config) { gs.mc(gSobject.gpsService,"setConfig",[config]); return this; } gSobject['getCurrentLocation'] = function(successCallback, failedCallback, config) { if (failedCallback === undefined) failedCallback = function(it) { }; if (config === undefined) config = gs.map(); var callbackWrapper = function(location) { gSobject.lastLocation = location; gs.execCall(successCallback, this, [location]); return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"cordovaService"),"userLocation",[location]),"do",[]); }; gs.mc(gSobject.gpsService,"getCurrentLocation",[callbackWrapper, failedCallback]); return this; } gSobject['onLocation'] = function(successCallback, failedCallback) { if (failedCallback === undefined) failedCallback = function(it) { }; var callbackWrapper = function(location) { gSobject.lastLocation = location; gs.execCall(successCallback, this, [location]); return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"cordovaService"),"userLocation",[location]),"do",[]); }; gs.mc(gSobject.gpsService,"onLocation",[callbackWrapper, failedCallback]); return this; } gSobject['onStationary'] = function(stationaryCallback, failedCallback) { if (failedCallback === undefined) failedCallback = function(it) { }; gs.mc(gSobject.gpsService,"onStationary",[stationaryCallback, failedCallback]); return this; } gSobject['start'] = function(it) { gs.mc(gSobject.gpsService,"start",[]); return this; } gSobject['stop'] = function(it) { gs.mc(gSobject.gpsService,"stop",[]); return this; } gSobject['sync'] = function(it) { gs.mc(gSobject.gpsService,"sync",[]); return this; } gSobject['getName'] = function(it) { gs.mc(gSobject.gpsService,"getName",[]); return this; } gSobject.backgroundGeoLocationDefined = function() { return typeof BackgroundGeolocation !== 'undefined'; } gSobject['GpsLocationTracker0'] = function(it) { if (gs.mc(gSobject,"backgroundGeoLocationDefined",[])) { gSobject.gpsService = GpsLocationTracker$CordovaBackgroundGeolocation(this); } else { if (gs.bool(gs.gp(navigator,"geolocation"))) { gSobject.gpsService = GpsLocationTracker$Html5Gps(this); } else { throw {message: "GPS not supported"}; }; }; return this; } if (arguments.length==0) {gSobject.GpsLocationTracker0(); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; GpsLocationTracker.instance = function(it) { if (!gs.bool(GpsLocationTracker.singletonInstance)) { GpsLocationTracker.singletonInstance = GpsLocationTracker(); }; return GpsLocationTracker.singletonInstance; } GpsLocationTracker.HIGH_ACCURACY = 0; GpsLocationTracker.MEDIUM_ACCURACY = 10; GpsLocationTracker.LOW_ACCURACY = 1000; GpsLocationTracker.PASSIVE_ACCURACY = 10000; GpsLocationTracker.singletonInstance = null; function GpsLocationTracker$Html5Gps() { var gSobject = gs.init('GpsLocationTracker$Html5Gps'); gSobject.clazz = { name: 'GpsLocationTracker$Html5Gps', simpleName: 'GpsLocationTracker$Html5Gps'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.watchPositionId = null; gSobject.onLocationSuccessCallback = function(it) { }; gSobject.onLocationFailedCallback = function(it) { }; gSobject.config = gs.map().add("desiredAccuracy",gs.gp(GpsLocationTracker,"HIGH_ACCURACY")).add("backgroundDesiredAccuracy",gs.gp(GpsLocationTracker,"LOW_ACCURACY")).add("enableHighAccuracy",true).add("maximumAge",30000).add("timeout",30000); gSobject.this$0 = null; gSobject['getName'] = function(it) { return "Html5Gps"; } gSobject['setConfig'] = function(config) { return gs.mc(gs.gp(gs.thisOrObject(this,gSobject),"config"),'leftShift', gs.list([config])); } gSobject['getCurrentLocation'] = function(successCallback, failedCallback, config) { if (config === undefined) config = gs.map(); return gs.mc(gs.gp(gs.fs('navigator', this, gSobject),"geolocation"),"getCurrentPosition",[function(location) { return gs.execCall(successCallback, this, [gs.gp(location,"coords")]); }, failedCallback, gs.map().add("enableHighAccuracy",gs.gp(config,"desiredAccuracy") <= gs.gp(GpsLocationTracker,"MEDIUM_ACCURACY")).add("maximumAge",gs.gp(config,"maximumAge")).add("timeout",gs.gp(config,"timeout"))]); } gSobject['onLocation'] = function(successCallback, failedCallback) { gSobject.onLocationSuccessCallback = successCallback; return gSobject.onLocationFailedCallback = failedCallback; } gSobject['setDesiredAccuracy'] = function(desiredAccuracy) { return gs.sp(gSobject.config,"desiredAccuracy",desiredAccuracy); } gSobject['onStationary'] = function(stationaryCallback) { } gSobject['sync'] = function(it) { } gSobject['start'] = function(it) { return gSobject.watchPositionId = gs.mc(gs.gp(gs.fs('navigator', this, gSobject),"geolocation"),"watchPosition",[function(location) { var gpsMap = gs.mc(gs.map().add("fixId",gs.execStatic(Utils,'uuid', this,[])).add("provider",gs.mc(gSobject,"getName",[])).add("unixTimeMs",gs.gp(location,"timestamp")).add("accuracy",null).add("speed",null).add("altitude",null).add("latitude",null).add("longitude",null).add("bearing",gs.gp(gs.gp(location,"coords"),"heading")).add("service","Html5Gps").add("user",gs.gp(gs.fs('session', this, gSobject),"userId")).add("uuid",gs.gp(gs.gp(gs.fs('cordovaDevice', this, gSobject),"device"),"uuid")),'leftShift', gs.list([gs.gp(location,"coords")])); return gs.mc(gSobject,"onLocationSuccessCallback",[gs.mc(gs.fs('gs', this, gSobject),"toJavascript",[gpsMap])]); }, gSobject.onLocationFailedCallback, gs.map().add("enableHighAccuracy",gs.gp(gSobject.config,"backgroundDesiredAccuracy") <= gs.gp(GpsLocationTracker,"MEDIUM_ACCURACY")).add("maximumAge",gs.gp(gSobject.config,"maximumAge")).add("timeout",gs.gp(gSobject.config,"timeout"))]); } gSobject['stop'] = function(it) { if (gs.bool(gSobject.watchPositionId)) { return gs.mc(gs.gp(gs.fs('navigator', this, gSobject),"geolocation"),"clearWatch",[gSobject.watchPositionId]); }; } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function GpsLocationTracker$CordovaBackgroundGeolocation() { var gSobject = gs.init('GpsLocationTracker$CordovaBackgroundGeolocation'); gSobject.clazz = { name: 'GpsLocationTracker$CordovaBackgroundGeolocation', simpleName: 'GpsLocationTracker$CordovaBackgroundGeolocation'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.config = gs.map().add("debug",false).add("locationProvider",gs.gp(BackgroundGeolocation,"DISTANCE_FILTER_PROVIDER")).add("backgroundLocationProvider",gs.gp(BackgroundGeolocation,"DISTANCE_FILTER_PROVIDER")).add("desiredAccuracy",gs.gp(GpsLocationTracker,"HIGH_ACCURACY")).add("backgroundDesiredAccuracy",gs.gp(GpsLocationTracker,"HIGH_ACCURACY")).add("activityType","OtherNavigation").add("stationaryRadius",10).add("distanceFilter",10).add("notificationTitle","GPS tracking").add("notificationText","enabled").add("enableHighAccuracy",true).add("startForeground",true).add("stopOnTerminate",false).add("interval",5000).add("fastestInterval",5000).add("activitiesInterval",5000).add("autoSync",true).add("syncThreshold",100).add("maxLocations",gs.multiply(10, 1000)).add("url","" + (gs.gp(session,"incomingUrl")) + "/cordovaWrapper/gps").add("syncUrl","" + (gs.gp(session,"incomingUrl")) + "/cordovaWrapper/gps").add("httpHeaders",gs.map()).add("postTemplate",gs.map().add("fixId","@id").add("provider","@provider").add("unixTimeMs","@time").add("accuracy","@accuracy").add("speed","@speed").add("altitude","@altitude").add("latitude","@latitude").add("longitude","@longitude").add("bearing","@bearing").add("service","BackgroundGeolocation").add("user",gs.gp(session,"userId")).add("uuid",gs.gp(gs.gp(cordovaDevice,"device"),"uuid"))); gSobject.this$0 = null; gSobject['getName'] = function(it) { return "CordovaBackgroundGeolocation"; } gSobject['setConfig'] = function(config) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[gs.plus("BackgroundGeolocation:setConfig:", config)]); gs.mc(gs.gp(gs.thisOrObject(this,gSobject),"config"),'leftShift', gs.list([config])); gs.mc(gs.fs('BackgroundGeolocation', this, gSobject),"configure",[gs.gp(gs.thisOrObject(this,gSobject),"config")]); return this; } gSobject['getCurrentLocation'] = function(successCallback, failedCallback, config) { if (config === undefined) config = gs.map(); return gs.mc(gs.fs('BackgroundGeolocation', this, gSobject),"getCurrentLocation",[successCallback, failedCallback, gs.mc(gs.map().add("enableHighAccuracy",true).add("maximumAge",gs.multiply((gs.multiply(4, 60)), 1000)).add("timeout",gs.multiply(60, 1000)),'leftShift', gs.list([config]))]); } gSobject['onLocation'] = function(successCallback, failedCallback) { return gs.mc(gs.fs('BackgroundGeolocation', this, gSobject),"on",["location", function(location) { return gs.mc(gs.fs('BackgroundGeolocation', this, gSobject),"startTask",[function(taskKey) { gs.execCall(successCallback, this, [location]); return gs.mc(gs.fs('BackgroundGeolocation', this, gSobject),"endTask",[taskKey]); }]); }]); } gSobject['onStationary'] = function(stationaryCallback) { return gs.mc(gs.fs('BackgroundGeolocation', this, gSobject),"on",["stationary", stationaryCallback]); } gSobject['sync'] = function(it) { return gs.mc(gs.fs('BackgroundGeolocation', this, gSobject),"forceSync",[]); } gSobject['start'] = function(it) { gs.mc(gs.fs('BackgroundGeolocation', this, gSobject),"start",[]); gs.mc(gSobject,"sync",[]); return this; } gSobject['stop'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[gs.plus("BackgroundGeolocation:stop:", gs.gp(gs.fs('session', this, gSobject),"userId"))]); } gSobject['GpsLocationTracker$CordovaBackgroundGeolocation0'] = function(it) { gs.mc(BackgroundGeolocation,"on",["background", function(it) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["BackgroundGeolocation:background"]); appStatus = "background"; return gs.mc(gs.fs('BackgroundGeolocation', this, gSobject),"configure",[function(it) { return gs.gp(gSobject.config,"backgroundDesiredAccuracy"); }]); }]); gs.mc(BackgroundGeolocation,"on",["foreground", function(it) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["BackgroundGeolocation:foreground"]); appStatus = "foreground"; gs.mc(gs.fs('BackgroundGeolocation', this, gSobject),"configure",[function(it) { return gs.gp(gSobject.config,"desiredAccuracy"); }]); return gs.mc(gs.fs('BackgroundGeolocation', this, gSobject),"forceSync",[]); }]); gs.mc(BackgroundGeolocation,"on",["authorization", function(status) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[gs.plus("BackgroundGeolocation:authorization:status: ", status)]); if (status !== gs.gp(gs.fs('BackgroundGeolocation', this, gSobject),"AUTHORIZED")) { return gs.execStatic(Utils,'setTimeout', this,[function(it) { var showSettings = gs.mc(this,"confirm",["App requires location tracking permission. Would you like to open app settings?"], gSobject); if (gs.bool(showSettings)) { return gs.mc(gs.fs('BackgroundGeolocation', this, gSobject),"showAppSettings",[]); }; }, 500]); }; }]); return this; } if (arguments.length==0) {gSobject.GpsLocationTracker$CordovaBackgroundGeolocation0(); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function CordovaAppleSignIn() { var gSobject = gs.init('CordovaAppleSignIn'); gSobject.clazz = { name: 'CordovaAppleSignIn', simpleName: 'CordovaAppleSignIn'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.AppleSignIn = function(onSuccess, onError) { window.cordova.plugins.SignInWithApple.signin({ requestedScopes: [FullName, Email] }, function(succ){ console.log(succ) alert(JSON.stringify(succ)) }, function(err){ console.error(err) console.log(JSON.stringify(err)) onError(err) } ) } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function QRScanner() { var gSobject = gs.init('QRScanner'); gSobject.clazz = { name: 'QRScanner', simpleName: 'QRScanner'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject['scan'] = function(success, failure) { var options = gs.map().add("preferFrontCamera",false).add("showFlipCameraButton",true).add("prompt","Place a barcode inside the scan area"); return gs.mc(gs.gp(gs.gp(gs.fs('cordova', this, gSobject),"plugins"),"barcodeScanner"),"scan",[success, failure, options]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function CordovaCamera() { var gSobject = gs.init('CordovaCamera'); gSobject.clazz = { name: 'CordovaCamera', simpleName: 'CordovaCamera'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject['takePhotoAndUpload'] = function(objectName, property, objectId, onSuccess, onError) { if (onError === undefined) onError = function(it) { }; gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["takePhotoAndUpload"]); var success = function(tempImageUrl) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["takePhotoAndUpload:success1"]); gs.println(tempImageUrl); return gs.mc(gs.fs('cordovaFile', this, gSobject),"addFile",[tempImageUrl, objectName, property, objectId, onSuccess, onError]); }; return gs.mc(gSobject,"takePhoto",[success, onError]); } gSobject['takePhotoBlob'] = function(onSuccess, onError) { if (onError === undefined) onError = function(it) { }; var success = function(imageUri) { return gs.mc(gs.fs('cordovaFile', this, gSobject),"blobFromFileUrl",[imageUri, function(blob) { gs.execCall(onSuccess, this, [blob]); return gs.mc(gSobject,"clearCache",[]); }, onError]); }; return gs.mc(gSobject,"takePhoto",[success, onError]); } gSobject['takePhoto'] = function(onSuccess, onFail, config) { if (config === undefined) config = gs.map(); CordovaCamera.hasCameraPermission("android.permission.CAMERA", function(status) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[gs.plus("android.permission.CAMERA:", gs.gp(status,"hasPermission"))]); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[status]); }); CordovaCamera.hasCameraPermission("android.permission.ACTION_CREATE_DOCUMENT", function(status) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[gs.plus("android.permission.ACTION_CREATE_DOCUMENT:", gs.gp(status,"hasPermission"))]); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[status]); }); CordovaCamera.hasCameraPermission("android.permission.ACTION_OPEN_DOCUMENT", function(status) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[gs.plus("android.permission.ACTION_OPEN_DOCUMENT:", gs.gp(status,"hasPermission"))]); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[status]); }); CordovaCamera.hasCameraPermission("android.permission.READ_EXTERNAL_STORAGE", function(status) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[gs.plus("android.permission.READ_EXTERNAL_STORAGE:", gs.gp(status,"hasPermission"))]); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[status]); }); CordovaCamera.hasCameraPermission("android.permission.READ_MEDIA_IMAGES", function(status) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[gs.plus("android.permission.READ_MEDIA_IMAGES:", gs.gp(status,"hasPermission"))]); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[status]); }); CordovaCamera.hasCameraPermission("android.permission.READ_MEDIA_VIDEO", function(status) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[gs.plus("android.permission.READ_MEDIA_IMAGES:", gs.gp(status,"hasPermission"))]); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[status]); }); gs.mc(gs.fs('camera', this, gSobject),"getPicture",[onSuccess, onFail, gs.mc(gs.map().add("destinationType",gs.gp(gs.gp(gs.fs('camera', this, gSobject),"DestinationType"),"FILE_URI")).add("sourceType",gs.gp(gs.gp(gs.fs('camera', this, gSobject),"PictureSourceType"),"CAMERA")).add("encodingType",gs.gp(gs.gp(gs.fs('cameraConst', this, gSobject),"EncodingType"),"JPEG")).add("correctOrientation",true).add("saveToPhotoAlbum",false).add("targetHeight",1024).add("targetWidth",1024),'leftShift', gs.list([config]))]); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["takePhoto2"]); } gSobject.hasCameraPermission = function(x0,x1) { return CordovaCamera.hasCameraPermission(x0,x1); } gSobject.verifyCameraPlugin = function() { return CordovaCamera.verifyCameraPlugin(); } gSobject['clearCache'] = function(it) { return gs.mc(gs.fs('camera', this, gSobject),"cleanup",[]); } gSobject.getCamera = function() { return CordovaCamera.getCamera(); } gSobject.getCameraConst = function() { return CordovaCamera.getCameraConst(); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; CordovaCamera.hasCameraPermission = function(permission, callback) { if (!Utils.isCordova()) return false; var permissions = cordova.plugins.permissions; if (!permissions) return false console.log('permission', permission) permissions.checkPermission(permission, function( status ){ if ( status.hasPermission ) { return callback(status); } else { permissions.requestPermission(permissions.CAMERA, function( result ){ return callback(result) }); } }); } CordovaCamera.verifyCameraPlugin = function() { return ( typeof navigator !== 'undefined' && typeof navigator.camera !== 'undefined' ) } CordovaCamera.getCamera = function() { return navigator.camera } CordovaCamera.getCameraConst = function() { return Camera } function VueApp() { var gSobject = gs.init('VueApp'); gSobject.clazz = { name: 'VueApp', simpleName: 'VueApp'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.componentList = gs.list([]); gSobject.authComponentPath = null; gSobject.vue = null; gSobject.router = null; gSobject.scope = gs.map().add("topHeading","").add("backStack",gs.list([])); gSobject.data = function(it) { return gSobject.scope = gs.mc(gs.fs('Vue', this, gSobject),"reactive",[gSobject.scope]); }; gSobject.methods = gs.map(); gSobject.watch = gs.map(); gSobject.compute = gs.map(); gSobject.events = gs.map(); gSobject.filters = gs.map(); gSobject.mixins = gs.list([]); gSobject.toggleDarkMode = function(it) { gs.mc(gs.gp(gs.fs('Quasar', this, gSobject),"Dark"),"toggle",[]); return gs.sp(gs.fs('session', this, gSobject),"darkMode",gs.gp(gs.gp(gs.fs('Quasar', this, gSobject),"Dark"),"isActive")); }; gSobject.initialised = false; gSobject['init'] = function(mountElement) { if (mountElement === undefined) mountElement = "#vue-app"; gs.println("VueApp.init"); if (gs.bool(gSobject.initialised)) { return null; }; gSobject.initialised = true; gs.mc(gSobject.componentList,"each",[function(component) { return gs.mc(gSobject,"registerVueComponent",[gs.gp(component,"vueComponentName"), component]); }]); var routes = gs.list([]); var childComponents = gs.set(); gs.mc(gSobject.componentList,"each",[function(component) { return gs.mc(gs.gp(component,"children"),"each",[function(child) { return gs.mc(childComponents,"add",[gs.gp(child,"vueComponentName")]); }], null, true); }]); var buildRoute = null; buildRoute = function(component) { var route = gs.map().add("path",gs.gp(component,"path")).add("component",gs.mc(gSobject.componentList,"find",[function(it) { return gs.equals(gs.gp(it,"vueComponentName"), gs.gp(component,"vueComponentName")); }])); if (gs.bool(gs.gp(component,"children"))) { gs.sp(route,"children",gs.mc(gs.gp(component,"children"),"collect",[function(child) { return gs.execCall(buildRoute, this, [child]); }])); }; return route; }; gs.mc(gSobject.componentList,"each",[function(component) { if (!gs.bool(gs.mc(childComponents,"contains",[gs.gp(component,"vueComponentName")]))) { if (gs.instanceOf(gs.gp(component,"path"), "ArrayList")) { return gs.mc(gs.gp(component,"path"),"each",[function(it) { if (gs.bool(it)) { var cloned = gs.execStatic(Utils,'deepCopyMap', this,[component]); gs.sp(cloned,"path",it); return gs.mc(routes,"add",[gs.execCall(buildRoute, this, [cloned])]); }; }]); } else { if (gs.bool(gs.gp(component,"path"))) { return gs.mc(routes,"add",[gs.execCall(buildRoute, this, [component])]); }; }; }; }]); gs.println("routes"); gs.println(routes); gs.mc(gSobject.filters,"each",[function(key, filterFunction) { return gs.mc(gSobject,"addVueFilter",[key, filterFunction]); }]); gSobject.router = gs.mc(gSobject,"newVueRouter",[routes]); gs.mc(gSobject.vue,"use",[gs.fs('Quasar', this, gSobject)]); gs.mc(gSobject.vue,"use",[gSobject.router]); gs.mc(gSobject,"setQuasarTheme",[]); gs.mc(gSobject.vue,"mount",[mountElement]); return this; } gSobject['registerComponent'] = function(component) { return gs.mc(gSobject.componentList,"add",[component]); } gSobject['registerAuthComponent'] = function(component) { var path = gs.gp(component,"path"); if (gs.instanceOf(gs.gp(component,"path"), "ArrayList")) { path = (path[0]); }; return gSobject.authComponentPath = path; } gSobject['setQuasarTheme'] = function(it) { gs.sp(gs.fs('session', this, gSobject),"darkMode",gs.elvis(gs.bool(gs.gp(gs.fs('session', this, gSobject),"darkMode")) , gs.gp(gs.fs('session', this, gSobject),"darkMode") , gs.gp(gs.gp(gs.fs('Quasar', this, gSobject),"Dark"),"isActive"))); return gs.mc(gs.gp(gs.fs('Quasar', this, gSobject),"Dark"),"set",[gs.gp(gs.fs('session', this, gSobject),"darkMode")]); } gSobject['registerVueComponent'] = function(name, component) { return gs.mc(gSobject,"registerVueComponentNative",[gSobject.vue, name, component]); } gSobject.addVueFilter = function(name, filter) { Vue.filter(name, filter) } gSobject.registerVueComponentNative = function(vue, name, component) { return vue.component(name, component) } gSobject.newVue = function(router, data, methods, watch, compute, events, mixins) { return Vue.createApp({ router : router, data : data, methods : methods, watch : watch, computed : compute, events : events, mixins : mixins }); } gSobject.newVueRouter = function(routes) { return VueRouter.createRouter({routes:routes, history: VueRouter.createWebHashHistory()}) } gSobject['VueApp0'] = function(it) { gSobject.vue = gs.mc(gSobject,"newVue",[gSobject.router, gs.toJsObj(gSobject.data), gs.toJsObj(gSobject.methods), gs.toJsObj(gSobject.watch), gs.toJsObj(gSobject.compute), gs.toJsObj(gSobject.events), gSobject.mixins]); return this; } if (arguments.length==0) {gSobject.VueApp0(); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function VueComponent() { var gSobject = gs.init('VueComponent'); gSobject.clazz = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.vueComponentName = null; gSobject.path = ""; gSobject.template = ""; gSobject.props = gs.list([]); gSobject.vueMeta = gs.map(); gSobject.route = null; gSobject.q = null; gSobject.refs = null; gSobject.options = gs.map(); gSobject.emit = null; gSobject.scope = gs.map(); gSobject.methods = null; gSobject.watch = null; gSobject.compute = null; gSobject.events = null; gSobject.roles = gs.list([]); gSobject.self = null; gSobject.beforeCreate = function(it) { gSobject.self = this; gSobject.route = gs.gp(gSobject.self,"$route"); gSobject.q = gs.gp(gSobject.self,"$q"); gSobject.options = gs.gp(gSobject.self,"$options"); gSobject.nextTick = gs.gp(gSobject.self,"$nextTick"); gSobject.emit = gs.gp(gSobject.self,"$emit"); return gs.mc(gs.gp(gs.fs('document', this, gSobject),"body"),"scrollTo",[0, 0]); }; gSobject.nextTick = function(callback) { return gs.execCall(callback, this, []); }; Object.defineProperty(gSobject, 'notifyParams', { get: function() { return VueComponent.notifyParams; }, set: function(gSval) { VueComponent.notifyParams = gSval; }, enumerable: true }); gSobject.notify = function(message, type, map) { if (type === undefined) type = "positive"; if (map === undefined) map = gs.map(); gs.sp(map,"message",message); gs.sp(map,"type",type); return gs.mc(gSobject.q,"notify",[gs.mc(gs.mc(VueComponent.notifyParams,"clone",[]),'leftShift', gs.list([map]))]); }; Object.defineProperty(gSobject, 'dialogParams', { get: function() { return VueComponent.dialogParams; }, set: function(gSval) { VueComponent.dialogParams = gSval; }, enumerable: true }); gSobject.dialog = function(title, message, map) { if (map === undefined) map = gs.map(); gs.sp(map,"title",title); gs.sp(map,"message",message); return gs.mc(gSobject.q,"dialog",[gs.mc(gs.mc(VueComponent.dialogParams,"clone",[]),'leftShift', gs.list([map]))]); }; gSobject.data = function(it) { gSobject.scope = gs.map(); return gSobject.scope = gs.mc(gs.fs('Vue', this, gSobject),"reactive",[gSobject.scope]); }; gSobject.meta = function(it) { return gSobject.vueMeta; }; Object.defineProperty(gSobject, 'METHOD_EXCLUDE_LIST', { get: function() { return VueComponent.METHOD_EXCLUDE_LIST; }, set: function(gSval) { VueComponent.METHOD_EXCLUDE_LIST = gSval; }, enumerable: true }); gSobject['register'] = function(templateName, componentName) { if (templateName === undefined) templateName = ""; if (componentName === undefined) componentName = ""; gSobject.vueComponentName = gs.elvis(gs.bool(componentName) , componentName , gs.mc(gs.mc(this,"getClass",[], gSobject),"getSimpleName",[])); if (!gs.bool(gSobject.template)) { gSobject.template = (gs.bool(templateName) ? gs.plus("#", templateName) : gs.plus((gs.plus("#", gs.mc(gs.mc(this,"getClass",[], gSobject),"getSimpleName",[]))), "View")); }; gs.println("VueComponent.register:" + (gSobject.vueComponentName) + ":" + (gSobject.template) + ":" + (gSobject.path) + ""); var methodsMap = gs.map(); gs.mc(gs.mc(gs.gp(this,"methods"),"findAll",[function(method) { var name = gs.gp(method,"name"); return (((!gs.bool(gs.mc(name,"startsWith",["set"]))) && (!gs.bool(gs.mc(name,"startsWith",["get"])))) && (!gs.bool(gs.mc(name,"contains",["$"])))) && (!gs.bool(gs.gSin(name, VueComponent.METHOD_EXCLUDE_LIST))); }]),"each",[function(it) { return (methodsMap[gs.gp(it,"name")]) = gs.gp(gs.thisOrObject(this,gSobject),"" + (gs.gp(it,"name")) + ""); }]); gSobject.methods = gs.toJsObj(methodsMap); var watchMap = gs.map(); gs.mc(gs.mc(gs.gp(this,"methods"),"findAll",[function(method) { return gs.mc(gs.gp(method,"name"),"startsWith",["watch"]); }]),"each",[function(method) { var watchVar = gs.mc(gs.gp(method,"name"),"substring",[5]); watchVar = (gs.plus(gs.mc(watchVar[0],"toLowerCase",[]), gs.mc(watchVar,"substring",[1]))); return (watchMap[watchVar]) = gs.gp(gs.thisOrObject(this,gSobject),"" + (gs.gp(method,"name")) + ""); }]); gSobject.watch = gs.toJsObj(watchMap); var computeMap = gs.map(); gs.mc(gs.mc(gs.gp(this,"methods"),"findAll",[function(method) { return gs.mc(gs.gp(method,"name"),"startsWith",["computed"]); }]),"each",[function(it) { return (computeMap[gs.gp(it,"name")]) = gs.gp(gs.thisOrObject(this,gSobject),"" + (gs.gp(it,"name")) + ""); }]); gSobject.compute = gs.toJsObj(computeMap); var eventsMap = gs.map(); gs.mc(gs.mc(gs.gp(this,"methods"),"findAll",[function(method) { return gs.mc(gs.gp(method,"name"),"startsWith",["event"]); }]),"each",[function(it) { return (eventsMap[gs.gp(it,"name")]) = gs.gp(gs.thisOrObject(this,gSobject),"" + (gs.gp(it,"name")) + ""); }]); gSobject.events = gs.toJsObj(eventsMap); gs.mc(gs.fs('vue', this, gSobject),"registerComponent",[this]); return this; } gSobject['registerAsAuthComponent'] = function(it) { gs.mc(gs.fs('vue', this, gSobject),"registerAuthComponent",[this]); return this; } gSobject['getRefs'] = function(it) { gs.sp(this,"refs",gs.gp(gSobject.self,"$refs")); return gs.gp(gSobject.self,"$refs"); } gSobject['beforeMount'] = function(it) { return gs.mc(gSobject,"enforceComponentRoles",[]); } gSobject['created'] = function(it) { } gSobject['mounted'] = function(it) { return gs.mc(gSobject,"nextTick",[function(it) { gs.mc(gSobject,"getRefs",[]); return gs.mc(gSobject,"afterMounted",[]); }]); } gSobject['afterMounted'] = function(it) { } gSobject['unmounted'] = function(it) { return gs.mc(gSobject,"destroyed",[]); } gSobject['destroyed'] = function(it) { return gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"topHeading",""); } gSobject['toggleDarkMode'] = function(it) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"scope"),"toggleDarkMode",[]); } gSobject['showLoading'] = function(text, spinnerColor) { if (text === undefined) text = "Loading..."; if (spinnerColor === undefined) spinnerColor = "primary"; return gs.mc(gs.gp(gSobject.q,"loading"),"show",[gs.map().add("group",text).add("message",text).add("delay",250).add("spinnerColor",spinnerColor).add("backgroundColor","transparent")]); } gSobject['hideLoading'] = function(text) { if (text === undefined) text = ""; if (!gs.bool(text)) { return gs.mc(gs.gp(gSobject.q,"loading"),"hide",[]); }; return gs.mc(gs.gp(gSobject.q,"loading"),"hide",[gs.map().add("group",text)]); } gSobject.moment = function(date) { return moment(date) } gSobject['placeholder'] = function(value, placeholder) { return gs.elvis(gs.bool(value) , value , placeholder); } gSobject['onPaste'] = function(evt, reference) { var text = ""; var elem = (gs.mc(gSobject,"getRefs",[])[reference])[0]; if (!gs.bool(elem)) { elem = (gs.mc(gSobject,"getRefs",[])[reference]); }; if ((gs.bool(gs.gp(elem,"originalEvent"))) && (gs.bool(gs.gp(gs.gp(gs.gp(evt,"originalEvent"),"clipboardData"),"getData")))) { text = gs.mc(gs.gp(gs.gp(evt,"originalEvent"),"clipboardData"),"getData",["text/plain"]); }; if ((gs.bool(gs.gp(evt,"clipboardData"))) && (gs.bool(gs.gp(gs.gp(evt,"clipboardData"),"getData")))) { text = gs.mc(gs.gp(evt,"clipboardData"),"getData",["text/plain"]); }; return gs.mc(elem,"runCmd",["insertText", text]); } gSobject['filterOptions'] = function(val, update, options, filteredOptions, object, excludeSelected) { if (object === undefined) object = gs.map(); if (excludeSelected === undefined) excludeSelected = false; return gs.execCall(update, this, [function(it) { return (gSobject.scope[filteredOptions]) = gs.mc(gs.mc(gSobject.scope[options],"findAll",[function(option) { if ((gs.bool(excludeSelected)) && (gs.equals(gs.gp(option,"_id"), gs.gp(object,"_id")))) { return false; }; if (!gs.bool(val)) { return true; }; return gs.mc(gs.mc(gs.gp(option,"name"),"toLowerCase",[], null, true),"contains",[gs.mc(val,"toLowerCase",[], null, true)], null, true); }]),"sort",[]); }]); } gSobject['enforceComponentRoles'] = function(it) { if (gs.bool(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"embedded"))) { gs.println("enforceComponentRoles skipped for embedded mode"); return true; }; if ((!gs.bool(gSobject.roles)) || (gs.mc(gs.fs('session', this, gSobject),"hasRole",[gSobject.roles]))) { return true; }; if (gs.bool(gs.gp(gs.fs('vue', this, gSobject),"authComponentPath"))) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"replace",[gs.gp(gs.fs('vue', this, gSobject),"authComponentPath")]); }; throw {message: "" + (gSobject.vueComponentName) + " roles required: " + (gSobject.roles) + ""}; } gSobject['formatCurrency'] = function(value) { try { gs.mc(value,"split",["."]); gs.mc(this,"parseFloat",[value], gSobject); } catch (all) { value = "0.00"; } ; if (!gs.bool(gs.mc(value,"contains",["."]))) { value = (gs.plus("0.0", value)); }; var newValue = null; var decPartSize = gs.mc(gs.mc(value,"split",["."])[1],"size",[]); if (decPartSize > 2) { newValue = gs.mc(gs.multiply(gs.mc(this,"parseFloat",[value], gSobject), 10),"toFixed",[2]); } else { if (gs.equals(decPartSize, 1)) { newValue = gs.mc(gs.div(gs.mc(this,"parseFloat",[value], gSobject), 10),"toFixed",[2]); } else { newValue = gs.mc(gs.mc(this,"parseFloat",[value], gSobject),"toFixed",[2]); }; }; return newValue; } gSobject['formatNumberInput'] = function(scopeName, size, decimals, parent) { if (size === undefined) size = 0; if (decimals === undefined) decimals = 0; if (parent === undefined) parent = gSobject.scope; var oldVal = gs.mc(gs.gp(parent,"" + (scopeName) + ""),"toString",[]); var newVal = ""; if ((gs.equals((oldVal[0]), ".")) || (gs.equals((oldVal[0]), ","))) { newVal = "0"; }; var index = 0; var dotCount = 0; var afterDotCount = 0; gs.mc(oldVal,"each",[function(character) { index++; if (gs.equals(decimals, 0)) { if ((gs.mc(character,"isNumber",[])) && ((gs.equals(size, 0)) || (index <= size))) { newVal += character; }; return null; }; if (gs.equals(character, ",")) { character = "."; }; if (gs.equals(character, ".")) { dotCount++; }; if (dotCount > 1) { return null; }; if (gs.equals(dotCount, 1)) { afterDotCount++; if (afterDotCount > (gs.plus(decimals, 1))) { return null; }; }; if (((gs.mc(character,"isNumber",[])) || (gs.equals(character, "."))) && ((gs.equals(size, 0)) || (index <= size))) { return newVal += character; }; }]); return gs.mc(gSobject,"nextTick",[function(it) { return gs.sp(parent,"" + (scopeName) + "",newVal); }]); } gSobject['formatNumberInputOnBlur'] = function(scopeName, size, decimals, parent) { if (size === undefined) size = 0; if (decimals === undefined) decimals = 0; if (parent === undefined) parent = gSobject.scope; gs.mc(gSobject,"formatNumberInput",[scopeName, size, decimals, parent]); return gs.mc(gSobject,"nextTick",[function(it) { return gs.sp(parent,"" + (scopeName) + "",gs.mc(this,"Number",[gs.mc(gs.gp(parent,"" + (scopeName) + ""),"toString",[])], gSobject)); }]); } gSobject['formatCurrencyInput'] = function(scopeName, parent) { if (parent === undefined) parent = gSobject.scope; return gs.mc(gSobject,"formatNumberInput",[scopeName, 15, 2, parent]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; VueComponent.notifyParams = gs.map().add("type","positive").add("position","bottom").add("avatar","").add("timeout",3000).add("actions",null).add("spinner",false).add("multiLine",false).add("progress",false); VueComponent.dialogParams = gs.map().add("ok",gs.map().add("push",true).add("color","primary")).add("cancel",gs.map().add("push",true).add("color","negative")).add("persistent",true); VueComponent.METHOD_EXCLUDE_LIST = gs.list(["equals" , "hashCode" , "notify" , "notifyAll" , "toString" , "wait" , "register" , "invokeMethod" , "data" , "beforeCreate" , "created" , "mounted" , "destroyed"]); function LegionLoginComponent() { var gSobject = VueComponent(); gSobject.clazz = { name: 'LegionLoginComponent', simpleName: 'LegionLoginComponent'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.path = "/login"; gSobject.appleAuth = gs.map(); gSobject['created'] = function(it) { gs.println("LegionLoginComponent.created()"); gs.sp(gSobject.scope,"showFooter",false); gs.sp(gSobject.scope,"showApple",gs.execStatic(Utils,'isIos', this,[])); gs.sp(gSobject.scope,"showAndroid",gs.execStatic(Utils,'isAndroid', this,[])); gs.sp(gSobject.scope,"email",""); return gs.sp(gSobject.scope,"phoneNumber",""); } gSobject['login'] = function(it) { gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"username",gs.elvis(gs.bool(gs.gp(gSobject.scope,"email")) , gs.gp(gSobject.scope,"email") , gs.gp(gSobject.scope,"phoneNumber"))); if (!gs.bool(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"username"))) { gs.mc(gSobject,"notify",["Please enter details", "negative"]); return null; }; return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"legionAuthService"),"generatePinForExistingUser",[gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"username"), (gs.bool(gs.gp(gSobject.scope,"phoneNumber")) ? true : false)]),"then",[function(it) { gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/legionPin"]); return gs.mc(gSobject,"notify",["Pin Sent"]); }, function(error) { return gs.mc(gSobject,"notify",[gs.gp(error,"message"), "negative"]); }]); } gSobject['googleSignIn'] = function(it) { if (!gs.bool(gs.execStatic(Utils,'isCordova', this,[]))) { return gs.mc(gSobject,"notify",["Could not complete sign in", "negative"]); }; return gs.mc(gs.fs('cordovaGoogleSignIn', this, gSobject),"googleSignIn",[function(success) { gs.println("cordovaGoogleSignIn"); gs.println(success); var object = gs.mc(gSobject,"toObject",[success]); gs.println(object); return gs.mc(gSobject,"signInWith",[gs.gp(gs.gp(object,"message"),"email"), gs.gp(gs.gp(object,"message"),"id"), function(it) { return gs.mc(gs.fs('legionUserService', this, gSobject),"loadLegionUser",[function(user) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/"]); }]); }, function(error) { gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/login"]); return gs.mc(gSobject,"errorNotification",[error]); }]); }, function(error) { gs.println(error); return gs.mc(gSobject,"notify",["Error Signing in with Google", "negative"]); }]); } gSobject['signInWithApple'] = function(it) { if (!gs.bool(gs.execStatic(Utils,'isCordova', this,[]))) { return gs.mc(gSobject,"notify",["Could not complete sign in", "negative"]); }; return LegionLoginComponent.signInWithAppleAuth(function(result) { gs.println("signInWithAppleAuth result:"); gs.println(result); var jwt = gs.execStatic(Utils,'decodeJWT', this,[gs.gp(result,"identityToken")]); var email = gs.gp(jwt,"email"); var password = gs.gp(jwt,"sub"); gSobject.appleAuth = result; return gs.mc(gSobject,"signInWith",[email, password, function(it) { return gs.mc(gs.fs('legionUserService', this, gSobject),"loadLegionUser",[function(user) { gs.mc(gSobject,"saveAppleCustomer",[gs.gp(user,"_id")]); return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/"]); }]); }, function(error) { gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/login"]); return gs.mc(gSobject,"errorNotification",[error]); }]); }); } gSobject.signInWithAppleAuth = function(x0) { return LegionLoginComponent.signInWithAppleAuth(x0); } gSobject['saveAppleCustomer'] = function(userId) { var user = gs.map(); if (gs.bool(gs.gp(gs.gp(gSobject.appleAuth,"fullName"),"familyName"))) { gs.sp(user,"surname",gs.gp(gs.gp(gSobject.appleAuth,"fullName"),"familyName")); }; if (gs.bool(gs.gp(gs.gp(gSobject.appleAuth,"fullName"),"givenName"))) { gs.sp(user,"name",gs.gp(gs.gp(gSobject.appleAuth,"fullName"),"givenName")); }; return gs.mc(gs.fs('legionUserService', this, gSobject),"updateUserDetails",[userId, gs.gp(user,"name"), gs.gp(user,"surname")]); } gSobject['signInWith'] = function(email, password, successCallback, failCallback) { return gs.mc(gs.fs('legionUserService', this, gSobject),"auth",[email, password, function(authenticated) { if (gs.bool(authenticated)) { return gs.execCall(successCallback, this, [authenticated]); }; return gs.mc(gs.gp(gs.fs('o', this, gSobject),"legionAuthService"),"repairUser",[email, password, function(result) { if (!gs.bool(gs.gp(result,"success"))) { gs.execCall(failCallback, this, ["Registration Failed"]); }; return gs.mc(gs.fs('legionUserService', this, gSobject),"auth",[email, password, function(isAuthenticated) { if (gs.bool(isAuthenticated)) { return gs.execCall(successCallback, this, [isAuthenticated]); }; return gs.execCall(failCallback, this, ["Login Failed"]); }]); }]); }]); } gSobject['errorNotification'] = function(notification) { return gs.mc(this,"alert",[notification], gSobject); } gSobject['differentLogin'] = function(it) { return gs.mc(gSobject,"notify",["WIP"]); } gSobject.toObject = function(data) { return JSON.parse(data) } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; LegionLoginComponent.signInWithAppleAuth = function(callback) { var value window.cordova.plugins.SignInWithApple.signin( { requestedScopes: [0,1] }, function(succ){ value = succ console.log("signInWithAppleAuth----------------------------------") console.log(JSON.stringify(value)) callback(value) }, function(err){ if(err.code == "1001" || err.code == "1003"){ alert('Authentication failed: User cancelled sign in.'); }else if(err.code == "1002"){ alert('Error: Sign in response received an invalid response'); }else{ alert('Error: Authentication failed'); } } ) } function LegionUserService() { var gSobject = gs.init('LegionUserService'); gSobject.clazz = { name: 'LegionUserService', simpleName: 'LegionUserService'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.legionUser = null; gSobject.country = null; gSobject['lookupCountry'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"legionLocaleService"),"fetchCountry",[function(countryIn) { return gSobject.country = countryIn; }]); } gSobject['auth'] = function(username, password, callback) { if (callback === undefined) callback = function(it) { }; return gs.mc(gs.gp(gs.fs('o', this, gSobject),"legionAuthService"),"authenticate",[username, password, function(authData) { gs.println("LegionUserService.auth1"); gs.println(authData); if (!gs.bool(authData)) { return gs.execCall(callback, this, [false]); }; if (gs.bool(gs.gp(authData,"authenticated"))) { gs.execStatic(Utils,'updateAuthTokenToSession', this,[authData]); gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[gs.plus("User authdata:", authData)]); gs.mc(gSobject,"updateSession",[authData]); gs.mc(gSobject,"loadLegionUser",[function(it) { return gs.execCall(callback, this, [gs.gp(authData,"authenticated")]); }]); return null; }; return gs.execCall(callback, this, [gs.gp(authData,"authenticated")]); }]); } gSobject['updateSession'] = function(authData) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[gs.plus("User authdata:", authData)]); gs.sp(gs.fs('session', this, gSobject),"legionUser",gs.gp(authData,"legionUser")); gs.sp(gs.fs('session', this, gSobject),"user",gs.gp(authData,"legionUser")); gs.sp(gs.fs('session', this, gSobject),"legionUserId",gs.gp(gs.gp(authData,"legionUser"),"_id",true)); gs.sp(gs.fs('session', this, gSobject),"userId",gs.gp(gs.gp(authData,"legionUser"),"_id",true)); if (gs.bool(gs.gp(authData,"zoner"))) { gs.sp(gs.fs('session', this, gSobject),"zoner",gs.gp(authData,"zoner")); gs.sp(gs.fs('session', this, gSobject),"zonerId",gs.gp(gs.gp(authData,"zoner"),"id")); return gs.sp(gs.fs('session', this, gSobject),"authToken",gs.gp(gs.gp(authData,"zoner"),"token")); }; } gSobject['authWithPin'] = function(username, pin, callback, failCallback) { if (callback === undefined) callback = function(it) { }; if (failCallback === undefined) failCallback = function(it) { }; return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"legionAuthService"),"authenticateWithPin",[username, pin]),"then",[function(authData) { if (!gs.bool(authData)) { return gs.execCall(callback, this, [false]); }; if (gs.bool(gs.gp(authData,"authenticated"))) { gs.execStatic(Utils,'updateAuthTokenToSession', this,[authData]); gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[gs.plus("User authdata:", authData)]); gs.mc(gSobject,"updateSession",[authData]); gs.mc(gSobject,"loadLegionUser",[function(it) { return gs.execCall(callback, this, [gs.gp(authData,"authenticated")]); }]); return null; }; return gs.mc(this,"success",[gs.gp(authData,"authenticated")], gSobject); }, function(error) { return gs.execCall(failCallback, this, [error]); }]); } gSobject['loadLegionUserFromServer'] = function(callback) { if (callback === undefined) callback = function(it) { }; return gs.mc(gs.gp(gs.fs('transmission', this, gSobject),"onAuthReady"),"callback",[function(it) { if (gs.bool(gs.gp(gs.fs('session', this, gSobject),"legionUserId"))) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"legionAuthService"),"loadLegionUser",[gs.gp(gs.fs('session', this, gSobject),"legionUserId"), function(legionUser) { gs.mc(gSobject,"updateSession",[gs.map().add("legionUser",legionUser)]); return gs.execCall(callback, this, [gs.gp(gs.fs('session', this, gSobject),"legionUser")]); }]); return null; }; if (gs.bool(gs.gp(gs.gp(gs.fs('session', this, gSobject),"zoner"),"id",true))) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"legionAuthService"),"loadLegionUserFromZonerId",[gs.gp(gs.gp(gs.fs('session', this, gSobject),"zoner"),"id"), function(legionUser) { gs.println("legionUser2"); gs.println(legionUser); gs.mc(gSobject,"updateSession",[gs.map().add("legionUser",legionUser)]); return gs.execCall(callback, this, [gs.gp(gs.fs('session', this, gSobject),"legionUser")]); }]); }; return gs.execCall(callback, this, []); }]); } gSobject['loadLegionUser'] = function(callback, failCallback, resetCache) { if (callback === undefined) callback = function(it) { }; if (failCallback === undefined) failCallback = function(it) { }; if (resetCache === undefined) resetCache = false; if ((gs.bool(gSobject.legionUser)) && (!gs.bool(resetCache))) { return gs.execCall(callback, this, [gSobject.legionUser]); }; if (gs.bool(gs.gp(gs.fs('session', this, gSobject),"authToken"))) { gs.mc(gs.gp(gs.fs('transmission', this, gSobject),"onAuthReady"),"callback",[function(it) { if (!gs.bool(gs.gp(gs.fs('session', this, gSobject),"legionUser"))) { throw {message: "Auth is authenticated, but legionUser not found"}; }; gSobject.legionUser = gs.gp(gs.fs('session', this, gSobject),"legionUser"); gs.execStatic(Utils,'subscribe', this,[gs.gp(gSobject.legionUser,"_id"), function(updatedlegionUser) { return gSobject.legionUser = updatedlegionUser; }]); return gs.execCall(callback, this, [gSobject.legionUser]); }]); return null; }; return gs.execCall(failCallback, this, []); } gSobject['registerPushDevice'] = function(data) { return gs.mc(gSobject,"loadLegionUser",[function(user) { gs.println(">>>>>>>>>>> Register Push Device"); gs.println(gs.plus((gs.plus((gs.plus((gs.plus((gs.plus("Data: ", gs.gp(user,"_id"))), " ")), gs.gp(data,"registrationId"))), " ")), gs.execStatic(Utils,'deviceType', this,[]))); gs.println(data); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"legionPushService"),"registerDevice",[gs.gp(user,"_id"), gs.gp(data,"registrationId"), gs.execStatic(Utils,'deviceType', this,[]), function(it) { return gs.println(">>>>>>>>>>> Register Push Device - SUCCESS"); }]); }]); } gSobject['getSetting'] = function(key, callback) { if (callback === undefined) callback = function(it) { }; return gs.mc(gSobject,"loadLegionUser",[function(user) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"legionService"),"getUserSetting",[gs.gp(user,"_id"), key, function(result) { return gs.execCall(callback, this, [result]); }]); }]); } gSobject['setSetting'] = function(key, value, callback) { if (callback === undefined) callback = function(it) { }; return gs.mc(gSobject,"loadLegionUser",[function(user) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"legionService"),"getUserSetting",[gs.gp(user,"_id"), key, value, function(result) { return gs.execCall(callback, this, [result]); }]); }]); } gSobject['updateUserDetails'] = function(userId, name, surname) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"legionAuthService"),"loadLegionUser",[userId, function(user) { gs.sp(user,"name",name); gs.sp(user,"surname",surname); return gs.mc(user,"save",[]); }]); } gSobject['LegionUserService0'] = function(it) { gs.mc(gSobject,"loadLegionUserFromServer",[]); gs.mc(gSobject,"lookupCountry",[]); return this; } if (arguments.length==0) {gSobject.LegionUserService0(); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function RootComponent() { var gSobject = VueComponent(); gSobject.clazz = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject['created'] = function(it) { return gs.mc(gSobject,"componentTheme",[false]); } gSobject['showHeaderFooter'] = function(show) { if (show === undefined) show = true; gs.mc(gSobject,"showHeader",[show]); return gs.mc(gSobject,"showFooter",[show]); } gSobject['showHeader'] = function(header) { if (header === undefined) header = true; gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"showHeader",header); return gs.sp(gSobject.scope,"header",header); } gSobject['showFooter'] = function(footer) { if (footer === undefined) footer = true; return gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"showFooter",footer); } gSobject['home'] = function(it) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/home"]); } gSobject['back'] = function(it) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"back",[]); } gSobject['toggleDrawer'] = function(it) { return gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"drawer",!gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"drawer")); } gSobject['formatDate'] = function(date, format) { if (format === undefined) format = "YYYY-MM-DD"; return gs.mc(gs.mc(gSobject,"moment",[date]),"format",[format]); } gSobject['ruleRequired'] = function(val) { return (gs.mc(gs.mc(gs.mc(val,"toString",[], null, true),"trim",[]),"size",[]) != 0 ? true : "Field Required"); } gSobject['ruleSelection'] = function(val) { return (gs.bool(val) ? true : "Please select a type"); } gSobject['ruleEmail'] = function(val) { var emailPattern = "^(?=[a-zA-Z0-9@._%+-]{6,254}$)[a-zA-Z0-9._%+-]{1,64}@(?:[a-zA-Z0-9-]{1,63}\.){1,8}[a-zA-Z]{2,63}$"; return (gs.exactMatch(val,emailPattern) ? true : "Invalid Email"); } gSobject['ruleNumber'] = function(val) { return (gs.mc(gs.mc(gs.plus(val, ""),"replaceAll",[" ", ""], null, true),"isNumber",[]) ? true : "Enter a valid number"); } gSobject['ruleString'] = function(val) { var pattern = /~(^\D*$)/; return (gs.exactMatch(val,pattern) ? true : "No numbers allowed"); } gSobject['rulePassport'] = function(val) { var passportPattern = "^[a-zA-Z0-9]+$"; return (gs.exactMatch(val,passportPattern) ? true : "Invalid Passport"); } gSobject['ruleSP'] = function(val) { if (!gs.bool(val)) { return "Systolic pressure is required"; }; if ((val < 60) || (val > 300)) { return "Systolic value must be between 60 and 300"; }; return true; } gSobject['ruleDP'] = function(val) { if (!gs.bool(val)) { return "Diastolic pressure is required"; }; if ((val < 30) || (val > 200)) { return "Diastolic value must be between 30 and 200"; }; return true; } gSobject['rulePulse'] = function(val) { if (!gs.bool(val)) { return true; }; if (val < 30) { return "Pulse value must be between 30 and 200"; }; return (val <= 200 ? true : "Pulse value must be between 30 and 200"); } gSobject['ruleGlucose'] = function(val) { if (!gs.bool(val)) { return true; }; if (val < 1.1) { return "Glucose value must be positive"; }; return (val <= 33.3 ? true : "Glucose value must be between 1.1 and 33.3"); } gSobject['ruleStepsCount'] = function(val) { if ((gs.equals(val, null)) || (gs.equals(val, ""))) { return "steps value is required"; }; if (((val != null) && (val != "")) && (val < 0)) { return "steps cannot be negative"; }; return true; } gSobject['ruleStepsDistance'] = function(val) { if ((gs.equals(val, null)) || (gs.equals(val, ""))) { return "distance value is required"; }; if (((val != null) && (val != "")) && (val < 0)) { return "distance cannot be negative"; }; return true; } gSobject['ruleStepsHours'] = function(val) { if (((val != null) && (val != "")) && (val < 0)) { return "hour value cannot be negative"; }; if (((val != null) && (val != "")) && (val > 8)) { return "hour value must be ≤ 6"; }; return true; } gSobject['ruleStepsMinutes'] = function(val) { if ((gs.equals(val, null)) || (gs.equals(val, ""))) { return "minute value is required"; }; if (val < 0) { return "minute value cannot be negative"; }; if (val > 59) { return "minute value must be ≤ 59"; }; return true; } gSobject['ruleStepsSeconds'] = function(val) { if ((gs.equals(val, null)) || (gs.equals(val, ""))) { return "second value is required"; }; if (val < 0) { return "second value cannot be negative"; }; if (val > 59) { return "second value must be ≤ 59"; }; return true; } gSobject['ruleHR'] = function(val) { if (!gs.bool(val)) { return "Heart Rate is required"; }; if (val < 0) { return "Pulse value must be positive"; }; if ((val < 30) || (val > 200)) { return "Heart Rate value must be between 30 and 200"; }; return true; } gSobject['ruleHVR'] = function(val) { if ((gs.equals(val, null)) || (val === "")) { return true; }; if (val < 0) { return "Pulse value must be positive"; }; if ((val < 2) || (val > 200)) { return "HRV value must be between 2 and 200"; }; return true; } gSobject['ruleSymptomDuration'] = function(val) { if ((gs.equals(val, null)) || (gs.equals(val, ""))) { return "duration value is required"; }; if (val < 0) { return "minute value cannot be negative"; }; if (val > 59) { return "minute value must be ≤ 59"; }; return true; } gSobject['ruleValidRsaId'] = function(id) { id = gs.mc(id,"toString",[]); if (gs.mc(id,"size",[]) != 13) { return "Invalid ID Number"; }; var year = +(gs.mc(id,"substring",[0, 2])); var month = +(gs.mc(id,"substring",[2, 4])); var day = +(gs.mc(id,"substring",[4, 6])); var genderDigit = +(gs.mc(id,"substring",[6, 7])); var citizenshipDigit = gs.mc(id,"substring",[10, 11]); var currentYear = gs.mod(gs.mc(gs.date(),"getYear",[]), 100); var fullYear = (year <= currentYear ? gs.plus(2000, year) : gs.plus(1900, year)); var date = gs.mc(gSobject,"moment",["" + (fullYear) + "-" + (gs.mc(gs.mc(month,"toString",[]),"padLeft",[2, "0"])) + "-" + (gs.mc(gs.mc(day,"toString",[]),"padLeft",[2, "0"])) + ""]); if (((gs.plus(gs.mc(date,"month",[]), 1)) != month) || (gs.mc(date,"date",[]) != day)) { return "Invalid ID Number"; }; if ((genderDigit < 0) || (genderDigit > 9)) { return "Invalid ID Number"; }; if (!gs.bool(gs.mc(gs.list(["0" , "1"]),"contains",[citizenshipDigit]))) { return "Invalid ID Number"; }; var sum = 0; var index = 0; for (_i31 = 0, d = id[0]; _i31 < id.length; d = id[++_i31]) { d = +(d); if (gs.equals((gs.mod(index, 2)), 1)) { d = (gs.multiply(d, 2)); }; sum += Math.floor(gs.div(d, 10)); sum += (gs.mod(d, 10)); index++; }; if ((gs.mod(sum, 10)) != 0) { return "Invalid ID Number"; }; return true; } gSobject['ruleHours'] = function(val) { if ((gs.equals(val, null)) || (gs.equals(val, ""))) { return true; }; var v = val; return ((v >= 0) && (v <= 12)) || ("Hours must be between 0 and 12"); } gSobject['ruleMinutes'] = function(val) { if ((gs.equals(val, null)) || (gs.equals(val, ""))) { return true; }; var v = val; return ((v >= 0) && (v <= 60)) || ("Minutes must be between 0 and 60"); } gSobject['ruleSeconds'] = function(val) { if ((gs.equals(val, null)) || (gs.equals(val, ""))) { return true; }; var v = val; return ((v >= 0) && (v <= 60)) || ("Seconds must be between 0 and 60"); } gSobject['rulePassword'] = function(val) { return (gs.mc(gs.mc(gs.mc(val,"toString",[]),"trim",[]),"size",[]) >= 6 ? true : "Password must be at least 6 characters"); } gSobject['ruleHydration'] = function(val) { if (!gs.bool(val)) { return true; }; if (val < 0) { return "Hydration value must be positive"; }; return (val <= 8000 ? true : "Hydration value must be 8000ml or less"); } gSobject['ruleDate'] = function(val) { if (!gs.bool(val)) { return "Date needs to be filled in"; }; return true; } gSobject['componentTheme'] = function(dark) { if (dark === undefined) dark = false; return gs.mc(gs.gp(gs.fs('Quasar', this, gSobject),"Dark"),"set",[dark]); } gSobject['logout'] = function(it) { return gs.execStatic(Utils,'logout', this,["/"]); } gSobject['handleInput'] = function(index, ref, event) { if (gs.gp(gs.mc(event,"toString",[]),"length") === 6) { var values = gs.mc(event,"toString",[]); for (var i = 0 ; i < gs.gp(values,"length") ; i++) { (gs.gp(gSobject.scope,"pinValues")[i]) = (values[i]); }; return null; }; var matches = gs.exactMatch(gs.mc(event,"toString",[]),/^[0-9]$/); if (!gs.bool(matches)) { return (gs.gp(gSobject.scope,"pinValues")[(gs.minus(index, 1))]) = null; }; var otpRef = gSobject.refs["" + (ref) + "" + (gs.plus(index, 1)) + ""]; if ((gs.bool(otpRef)) && (otpRef[0])) { return gs.mc(otpRef[0],"focus",[]); }; } gSobject['handleBackspace'] = function(index, ref) { if (!gs.bool(gs.gp(gSobject.scope,"pinValues")[(gs.minus(index, 1))])) { var otpRef = gSobject.refs["" + (ref) + "" + (gs.minus(index, 1)) + ""]; if ((gs.bool(otpRef)) && (otpRef[0])) { return gs.mc(otpRef[0],"focus",[]); }; } else { return (gs.gp(gSobject.scope,"pinValues")[(gs.minus(index, 1))]) = null; }; } gSobject['sendUserPin'] = function(username, routeTo, isSms, callback) { if (callback === undefined) callback = function(it) { }; return gs.mc(gs.gp(gs.fs('o', this, gSobject),"legionAuthService"),"generateVerificationOtp",[function(result) { gs.println("result"); gs.println(result); if (gs.bool(isSms)) { return gs.mc(gSobject,"sendSmsVerification",[username, result, routeTo, callback]); } else { return gs.mc(gSobject,"sendEmailVerification",[username, result, routeTo, callback]); }; }]); } gSobject['sendSmsVerification'] = function(username, pin, routeTo, callback) { if (callback === undefined) callback = function(it) { }; gs.println("SMS VERIFY"); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeApiService"),"notificationGuest",["sms", username, "t1", gs.plus("Your RxME OTP is: ", pin), function(sent) { gs.println("sent"); gs.println(sent); gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"verifyPin",pin); gs.mc(gSobject,"notify",["Pin Sent"]); if (gs.bool(routeTo)) { gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",[routeTo]); }; return gs.execCall(callback, this, []); }]); } gSobject['sendEmailVerification'] = function(username, pin, routeTo, callback) { if (callback === undefined) callback = function(it) { }; gs.println("EMAIL VERIFY"); gs.mc(gSobject,"notify",["Email Work In Progress"]); if (gs.bool(routeTo)) { gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",[routeTo]); }; return gs.execCall(callback, this, []); } gSobject['push'] = function(path) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",[path]); } gSobject['loadTrackerData'] = function(name, callback) { if (callback === undefined) callback = function(it) { }; return gs.mc(gs.gp(gs.mc(gs.fs('o', this, gSobject),"localAndRemote",[]),"questService"),"getAllTrackables",[function(trackers) { var tracker = gs.mc(trackers,"find",[function(it) { return gs.equals(gs.gp(it,"name"), name); }]); return gs.execCall(callback, this, [tracker]); }]); } gSobject['generateAndSaveMotivation'] = function(userId, trackableName, datapointName, callback) { if (trackableName === undefined) trackableName = null; if (datapointName === undefined) datapointName = null; if (callback === undefined) callback = function(it) { }; var key = null; trackableName = trackableName; if ((!gs.bool(trackableName)) || (gs.equals(trackableName, "daily"))) { key = "motivation:daily"; gs.println("Generating DAILY motivational message for " + (userId) + ""); return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeLlmService"),"dailyMotivation",["Encouraging"]),"then",[function(message) { var safeMessage = gs.elvis(gs.bool(message) , message , "Keep going—your effort is noticed!"); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[userId, key, safeMessage]),"do",[]); return gs.println("Motivation saved for Daily: " + (safeMessage) + ""); }]); } else { var ut = gs.mc(gs.gp(gs.fs('o', this, gSobject),"userTrackable"),"findOne",[gs.map().add("user",userId).add("trackable",gs.map().add("name",trackableName))]); if (!gs.bool(gs.gp(ut,"motivationEnabled",true))) { gs.println("Motivation disabled for " + (trackableName) + ", skipping."); return null; }; gs.println("Generating TRACKABLE motivation for " + (userId) + " / " + (trackableName) + ""); return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"motivationalMessage",[userId, trackableName, datapointName]),"then",[function(message) { gs.println("Motivation saved for " + (trackableName) + ": " + (message) + ""); return gs.execCall(callback, this, []); }]); }; } gSobject['loadMotivation'] = function(userId, trackableName, callback) { if (trackableName === undefined) trackableName = null; var normalized = (gs.bool(trackableName) ? gs.mc(trackableName,"toLowerCase",[]) : null); var key = ((!gs.bool(normalized)) || (gs.equals(normalized, "daily")) ? "motivation:daily" : "motivational:text:" + (normalized) + ""); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[userId, key, function(msg) { var fallback = ((!gs.bool(normalized)) || (gs.equals(normalized, "daily")) ? "Stay strong — you’re making progress every day!" : "Your effort is being tracked — stay consistent!"); var text = gs.elvis(gs.bool(msg) , msg , fallback); gs.println("Loaded motivation for " + (gs.elvis(gs.bool(trackableName) , trackableName , "Daily")) + ": " + (text) + ""); return gs.execCall(callback, this, [text]); }]); } gSobject['saveLastUpdated'] = function(userId, trackerName) { var datapoint = gs.plus("health:updated_at:", trackerName); var timestamp = gs.date(); return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[userId, datapoint, timestamp]),"do",[]); } gSobject['loadLastUpdated'] = function(userId, trackerName, callback) { if (callback === undefined) callback = function(it) { }; var datapoint = gs.plus("health:updated_at:", trackerName); var timestamp = ""; return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[userId, datapoint, function(result) { if (gs.bool(result)) { timestamp = gs.mc(gs.mc(gSobject,"moment",[result]),"format",["ddd DD MMM [at] HH:mm"]); }; return gs.execCall(callback, this, [timestamp]); }]); } gSobject['loadLastUpdatedAlt'] = function(userId, trackerName, callback) { if (callback === undefined) callback = function(it) { }; var datapoint = gs.plus("health:updated_at:", trackerName); var timestamp = ""; return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[userId, datapoint, function(result) { if (gs.bool(result)) { timestamp = gs.mc(gs.mc(gSobject,"moment",[result]),"format",["YYYY-MM-DD"]); }; return gs.execCall(callback, this, [timestamp]); }]); } gSobject.formatRand = function(val) { if (val == null || val === '' || isNaN(val)) return 'R0.00'; return new Intl.NumberFormat('en-ZA', { style: 'currency', currency: 'ZAR' }).format(val); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function CordovaDevice() { var gSobject = gs.init('CordovaDevice'); gSobject.clazz = { name: 'CordovaDevice', simpleName: 'CordovaDevice'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.network = gs.map().add("type","NONE").add("status","online"); gSobject.battery = gs.map().add("level",50).add("isPlugged",false).add("state","normal").add("date",gs.date()); gSobject.device = gs.map().add("network",gSobject.network).add("battery",gSobject.battery).add("orientation","portrait").add("keyboard","hide"); gSobject.onKeyboardListeners = gs.list([]); gSobject.appEventListeners = gs.list([]); gSobject.onBackKeyDown = function(it) { }; gSobject.userId = null; gSobject['splashScreenHide'] = function(it) { if (gs.execStatic(Utils,'isCordova', this,[])) { try { gs.mc(gs.gp(gs.fs('navigator', this, gSobject),"splashscreen"),"hide",[], null, true); if (CordovaDevice.cordovaPluginStatusBarInstalled()) { gs.mc(gs.fs('StatusBar', this, gSobject),"overlaysWebView",[false]); gs.mc(gs.fs('StatusBar', this, gSobject),"backgroundColorByName",["black"]); }; try { var p = gs.mc(gs.gp(gs.fs('screen', this, gSobject),"orientation"),"lock",["portrait"]); if ((gs.bool(p)) && (gs.bool(gs.gp(p,"catch")))) { gs.mc(p,"catch",[gs.mc(this,"function",[function(it) { }], gSobject)]); }; } catch (e) { } ; } catch (all) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["splashScreenHide:" + (gs.fs('all', this, gSobject)) + ""]); } ; }; } gSobject['disableBackButton'] = function(it) { return gs.mc(gs.fs('document', this, gSobject),"addEventListener",["backbutton", gSobject.onBackKeyDown, false]); } gSobject['setupCordovaAppEvents'] = function(it) { gs.mc(gs.fs('document', this, gSobject),"addEventListener",["pause", function(it) { return gs.mc(gSobject,"emitEvent",["app.pause"]); }, false]); gs.mc(gs.fs('document', this, gSobject),"addEventListener",["resume", function(it) { return gs.mc(gSobject,"emitEvent",["app.resume"]); }, false]); return gs.mc(gs.fs('document', this, gSobject),"addEventListener",["menubutton", function(it) { return gs.mc(gSobject,"emitEvent",["app.menubutton"]); }, false]); } gSobject['preventScreenshots'] = function(it) { gs.execStatic(Utils,'setTimeout', this,[function(it) { return gs.mc(gs.fs('OurCodeWorldpreventscreenshots', this, gSobject),"enable",[]); }, 1]); return gs.execStatic(Utils,'setTimeout', this,[function(it) { return gs.mc(gs.gp(gs.gp(gs.fs('window', this, gSobject),"plugins"),"preventscreenshot"),"enable",[function(it) { }, function(it) { }]); }, 1]); } gSobject['allowScreenshots'] = function(it) { gs.execStatic(Utils,'setTimeout', this,[function(it) { return gs.mc(gs.fs('OurCodeWorldpreventscreenshots', this, gSobject),"disable",[]); }, 1]); return gs.execStatic(Utils,'setTimeout', this,[function(it) { return gs.mc(gs.gp(gs.gp(gs.fs('window', this, gSobject),"plugins"),"preventscreenshot"),"disable",[function(it) { }, function(it) { }]); }, 1]); } gSobject['setupCordovaPluginKeyboard'] = function(it) { var initialViewportHeight = gs.gp(gs.gp(gs.fs('window', this, gSobject),"visualViewport"),"height"); var initialViewportWidth = gs.gp(gs.gp(gs.fs('window', this, gSobject),"visualViewport"),"width"); return gs.mc(gs.gp(gs.fs('window', this, gSobject),"visualViewport"),"addEventListener",["resize", function(it) { if (initialViewportWidth != gs.gp(gs.gp(gs.fs('window', this, gSobject),"visualViewport"),"width")) { gs.execStatic(Utils,'setTimeout', this,[function(it) { initialViewportHeight = gs.gp(gs.gp(gs.fs('window', this, gSobject),"visualViewport"),"height"); initialViewportWidth = gs.gp(gs.gp(gs.fs('window', this, gSobject),"visualViewport"),"width"); gs.mc(gSobject,"emitEvent",["orientation." + (gs.mc(gSobject,"getOrientation",[])) + ""]); gs.sp(gSobject.device,"orientation",gs.mc(gSobject,"getOrientation",[])); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["setupCordovaPluginKeyboard:orientation." + (gs.mc(gSobject,"getOrientation",[])) + ""]); }, 100]); return null; }; if (gs.equals(gs.gp(gs.gp(gs.fs('window', this, gSobject),"visualViewport"),"height"), initialViewportHeight)) { gs.sp(gSobject.device,"keyboard","hide"); gs.mc(gSobject,"emitEvent",["keyboard.hide"]); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["setupCordovaPluginKeyboard:keyboard.hide"]); } else { gs.sp(gSobject.device,"keyboard","show"); gs.mc(gSobject,"emitEvent",["keyboard.show"]); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["setupCordovaPluginKeyboard:keyboard.show"]); }; }]); } gSobject['getOrientation'] = function(it) { return gs.gp(gs.fs('screen', this, gSobject)["orientation"],"type"); } gSobject['setupCordovaPluginDevice'] = function(it) { gs.mc(gSobject.device,"putAll",[gs.gp(gs.fs('window', this, gSobject),"device")]); return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"cordovaService"),"userDevice",[gSobject.userId, gSobject.device]),"do",[]); } gSobject['setupCordovaPluginBatteryStatus'] = function(it) { var batteryUpdate = function(status, state) { if (gs.bool(gs.gp(state,"level"))) { gSobject.battery = gs.map().add("level",gs.gp(state,"level")).add("isPlugged",gs.gp(state,"isPlugged")).add("isTrusted",gs.gp(state,"isTrusted")).add("status",status).add("date",gs.date()); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"cordovaService"),"userDeviceBattery",[gSobject.userId, gs.gp(gSobject.device,"uuid"), gSobject.battery]),"do",[]); }; gs.sp(gSobject.network,"bettery",status); return gs.mc(gSobject,"emitEvent",["bettery." + (status) + ""]); }; gs.mc(gs.fs('window', this, gSobject),"addEventListener",["batterystatus", function(state) { return gs.execCall(batteryUpdate, this, ["normal", state]); }, false]); gs.mc(gs.fs('window', this, gSobject),"addEventListener",["batterylow", function(state) { return gs.execCall(batteryUpdate, this, ["low", state]); }, false]); return gs.mc(gs.fs('window', this, gSobject),"addEventListener",["batterycritical", function(state) { return gs.execCall(batteryUpdate, this, ["critical", state]); }, false]); } gSobject['setupCordovaPluginNetworkInformation'] = function(it) { var networkUpdate = function(status) { gs.sp(gSobject.network,"status",status); gs.sp(gSobject.network,"type",gs.gp(gs.gp(gs.fs('navigator', this, gSobject),"connection"),"type")); gs.sp(gSobject.network,"date",gs.date()); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"cordovaService"),"userNetwork",[gSobject.userId, gs.gp(gSobject.device,"uuid"), gSobject.network]),"do",[]); return gs.mc(gSobject,"emitEvent",["network." + (status) + ""]); }; gs.mc(gs.fs('document', this, gSobject),"addEventListener",["offline", function(it) { return gs.execCall(networkUpdate, this, ["offline"]); }, false]); gs.mc(gs.fs('document', this, gSobject),"addEventListener",["online", function(it) { return gs.execCall(networkUpdate, this, ["online"]); }, false]); return gs.execCall(networkUpdate, this, ["online"]); } gSobject['addAppEventListeners'] = function(callback) { return gs.mc(gSobject.appEventListeners,"add",[callback]); } gSobject['emitEvent'] = function(event) { return gs.mc(gSobject.appEventListeners,"each",[function(listner) { return gs.execStatic(Utils,'setTimeout', this,[function(it) { return gs.execCall(listner, this, [event]); }, 0]); }]); } gSobject['vibrate'] = function(timeMs) { return gs.mc(gs.fs('navigator', this, gSobject),"vibrate",[timeMs]); } gSobject.spinnerInstalled = function() { return CordovaDevice.spinnerInstalled(); } gSobject['statusBarShow'] = function(it) { if (!gs.bool(CordovaDevice.cordovaPluginStatusBarInstalled())) { return null; }; try { gs.mc(gs.fs('StatusBar', this, gSobject),"show",[]); } catch (e) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["statusBarShow error: " + (gs.fs('e', this, gSobject)) + ""]); } ; } gSobject['statusBarHide'] = function(it) { if (!gs.bool(CordovaDevice.cordovaPluginStatusBarInstalled())) { return null; }; try { gs.mc(gs.fs('StatusBar', this, gSobject),"hide",[]); } catch (e) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["statusBarHide error: " + (gs.fs('e', this, gSobject)) + ""]); } ; } gSobject['statusBarColor'] = function(hex) { if (!gs.bool(CordovaDevice.cordovaPluginStatusBarInstalled())) { return null; }; try { gs.mc(gs.fs('StatusBar', this, gSobject),"backgroundColorByHexString",[hex]); } catch (e) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["statusBarColor error: " + (gs.fs('e', this, gSobject)) + ""]); } ; } gSobject['statusBarStyleLight'] = function(it) { if (!gs.bool(CordovaDevice.cordovaPluginStatusBarInstalled())) { return null; }; try { gs.mc(gs.fs('StatusBar', this, gSobject),"styleLightContent",[]); } catch (e) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["statusBarStyleLight error: " + (gs.fs('e', this, gSobject)) + ""]); } ; } gSobject['statusBarStyleDark'] = function(it) { if (!gs.bool(CordovaDevice.cordovaPluginStatusBarInstalled())) { return null; }; try { gs.mc(gs.fs('StatusBar', this, gSobject),"styleDefault",[]); } catch (e) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["statusBarStyleDark error: " + (gs.fs('e', this, gSobject)) + ""]); } ; } gSobject['statusBarOverlay'] = function(overlay) { if (!gs.bool(CordovaDevice.cordovaPluginStatusBarInstalled())) { return null; }; try { gs.mc(gs.fs('StatusBar', this, gSobject),"overlaysWebView",[overlay]); } catch (e) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["statusBarOverlay error: " + (gs.fs('e', this, gSobject)) + ""]); } ; } gSobject['lockPortrait'] = function(it) { return gs.mc(gSobject,"doLockOrientation",["portrait"]); } gSobject['lockLandscape'] = function(it) { return gs.mc(gSobject,"doLockOrientation",["landscape"]); } gSobject['unlockOrientation'] = function(it) { try { gs.mc(gs.gp(gs.fs('screen', this, gSobject),"orientation"),"unlock",[], null, true); } catch (e) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["unlockOrientation: " + (gs.fs('e', this, gSobject)) + ""]); } ; } gSobject.doLockOrientation = function(orientation) { try { var result = screen.orientation.lock(orientation); // iOS 16+ returns a Promise — handle rejection silently if (result && result.then) { result.catch(function(e) { console.log('orientation lock rejected:', e); }); } return 'ok'; } catch (e) { console.log('orientation lock error:', e); return 'Not supported: ' + (e.message || e); } } gSobject['hasPermission'] = function(name, callback) { if (!gs.bool(CordovaDevice.permissionsInstalled())) { gs.execCall(callback, this, [gs.map().add("hasPermission",true)]); return null; }; try { gs.mc(gs.gp(gs.gp(gs.fs('cordova', this, gSobject),"plugins"),"permissions"),"checkPermission",[name, callback, function(e) { return gs.execCall(callback, this, [gs.map().add("hasPermission",false).add("error",e)]); }]); } catch (e) { gs.execCall(callback, this, [gs.map().add("hasPermission",false).add("error",gs.fs('e', this, gSobject))]); } ; } gSobject['requestPermission'] = function(name, callback) { if (!gs.bool(CordovaDevice.permissionsInstalled())) { gs.execCall(callback, this, [gs.map().add("hasPermission",true)]); return null; }; try { gs.mc(gs.gp(gs.gp(gs.fs('cordova', this, gSobject),"plugins"),"permissions"),"requestPermission",[name, callback, function(e) { return gs.execCall(callback, this, [gs.map().add("hasPermission",false).add("error",e)]); }]); } catch (e) { gs.execCall(callback, this, [gs.map().add("hasPermission",false).add("error",gs.fs('e', this, gSobject))]); } ; } gSobject['hasPermissions'] = function(names, callback) { if (!gs.bool(CordovaDevice.permissionsInstalled())) { gs.execCall(callback, this, [gs.map().add("hasPermission",true)]); return null; }; try { gs.mc(gs.gp(gs.gp(gs.fs('cordova', this, gSobject),"plugins"),"permissions"),"checkPermission",[names, callback, function(e) { return gs.execCall(callback, this, [gs.map().add("hasPermission",false).add("error",e)]); }]); } catch (e) { gs.execCall(callback, this, [gs.map().add("hasPermission",false).add("error",gs.fs('e', this, gSobject))]); } ; } gSobject.permissionsInstalled = function() { return CordovaDevice.permissionsInstalled(); } gSobject.cordovaPluginStatusBarInstalled = function() { return CordovaDevice.cordovaPluginStatusBarInstalled(); } gSobject.cordovaPluginDeviceInstalled = function() { return CordovaDevice.cordovaPluginDeviceInstalled(); } gSobject.crdovaPluginNetworkInformationInstalled = function() { return CordovaDevice.crdovaPluginNetworkInformationInstalled(); } gSobject['showSpinner'] = function(message, cancelable) { if (message === undefined) message = ""; if (cancelable === undefined) cancelable = false; return gs.mc(gSobject,"nativeSpinnerShow",[gs.map().add("message",message).add("cancelable",cancelable), function(it) { }, function(it) { }]); } gSobject['hideSpinner'] = function(it) { return gs.mc(gSobject,"nativeSpinnerHide",[function(it) { }, function(it) { }]); } gSobject.nativeSpinnerShow = function(options, success, error) { if (typeof window.i3Spinner !== 'undefined') { window.i3Spinner.show(options, success, error); } else if (typeof SpinnerDialog !== 'undefined') { SpinnerDialog.show(null, options.message || '', options.cancelable || false); if (success) success(); } else { if (error) error('Spinner not available'); } } gSobject.nativeSpinnerHide = function(success, error) { if (typeof window.i3Spinner !== 'undefined') { window.i3Spinner.hide(success, error); } else if (typeof SpinnerDialog !== 'undefined') { SpinnerDialog.hide(); if (success) success(); } else { if (error) error('Spinner not available'); } } gSobject['preventCapture'] = function(enabled, success, error) { if (success === undefined) success = function(it) { }; if (error === undefined) error = function(it) { }; return gs.mc(gSobject,"nativePreventCapture",[enabled, success, error]); } gSobject['onScreenshot'] = function(callback) { return gs.mc(gSobject,"nativeOnScreenshot",[callback]); } gSobject['onScreenRecording'] = function(callback) { return gs.mc(gSobject,"nativeOnScreenRecording",[callback]); } gSobject.nativePreventCapture = function(enabled, success, error) { if (typeof cordova !== 'undefined' && cordova.plugins && cordova.plugins.i3Screenshot) { cordova.plugins.i3Screenshot.preventCapture(enabled, success, error); } else { if (error) error('i3Screenshot not available'); } } gSobject.nativeOnScreenshot = function(callback) { if (typeof cordova !== 'undefined' && cordova.plugins && cordova.plugins.i3Screenshot) { cordova.plugins.i3Screenshot.onScreenshot(callback); } } gSobject.nativeOnScreenRecording = function(callback) { if (typeof cordova !== 'undefined' && cordova.plugins && cordova.plugins.i3Screenshot) { cordova.plugins.i3Screenshot.onScreenRecording(callback); } } gSobject['getAppInfo'] = function(callback, error) { if (error === undefined) error = function(it) { }; return gs.mc(gSobject,"nativeGetAppInfo",[callback, error]); } gSobject['setBadge'] = function(count, success, error) { if (success === undefined) success = function(it) { }; if (error === undefined) error = function(it) { }; return gs.mc(gSobject,"nativeSetBadge",[count, success, error]); } gSobject['clearBadge'] = function(success, error) { if (success === undefined) success = function(it) { }; if (error === undefined) error = function(it) { }; return gs.mc(gSobject,"nativeSetBadge",[0, success, error]); } gSobject.nativeGetAppInfo = function(success, error) { if (typeof cordova !== 'undefined' && cordova.plugins && cordova.plugins.i3App) { cordova.plugins.i3App.getInfo(success, error); } else { if (error) error('i3App not available'); } } gSobject.nativeSetBadge = function(count, success, error) { if (typeof cordova !== 'undefined' && cordova.plugins && cordova.plugins.i3App) { cordova.plugins.i3App.setBadge(count, success, error); } else { if (error) error('i3App not available'); } } gSobject['print'] = function(content, options, callback) { if (options === undefined) options = gs.map(); if (callback === undefined) callback = function(it) { }; return gs.mc(gSobject,"nativePrint",[content, options, callback]); } gSobject.nativePrint = function(content, options, callback) { if (typeof cordova !== 'undefined' && cordova.plugins && cordova.plugins.printer) { cordova.plugins.printer.print(content, options, callback); } else { if (callback) callback(false); } } gSobject['installErrorCapture'] = function(it) { gs.mc(gSobject,"nativeInstallErrorCapture",[]); gs.mc(gSobject,"nativeInstallConsoleTail",[]); return gs.mc(gSobject,"nativeInstallRouteHistory",[]); } gSobject['enableErrorFlush'] = function(it) { gs.mc(gSobject,"nativePrimeErrorContext",[gs.map().add("userId",gs.elvis(gs.bool(gSobject.userId) , gSobject.userId , "")).add("uuid",gs.elvis(gs.bool(gs.gp(gSobject.device,"uuid")) , gs.gp(gSobject.device,"uuid") , "")).add("platform",gs.elvis(gs.bool(gs.gp(gSobject.device,"platform")) , gs.gp(gSobject.device,"platform") , "browser")).add("appVersion",gs.elvis(gs.bool(gs.gp(gSobject.device,"version")) , gs.gp(gSobject.device,"version") , "")).add("appBuild",gs.elvis(gs.bool(gs.gp(gSobject.device,"cordova")) , gs.gp(gSobject.device,"cordova") , ""))]); return gs.mc(gSobject,"nativeFlushErrors",[]); } gSobject.nativeInstallErrorCapture = function() { if (window._cwErr) return; // idempotent var BUF_KEY = 'cw.errBuf'; var BUF_CAP = 50; var DEDUP_MS = 60000; var dedup = {}; var ctx = { userId: '', uuid: '', platform: 'browser', appVersion: '', appBuild: '' }; var flushing = false; var buf; function readBuf() { try { var s = window.localStorage.getItem(BUF_KEY); return s ? JSON.parse(s) : []; } catch(e) { return []; } } function writeBuf(arr) { try { if (arr.length > BUF_CAP) arr = arr.slice(arr.length - BUF_CAP); window.localStorage.setItem(BUF_KEY, JSON.stringify(arr)); } catch(e) {} } buf = readBuf(); function fingerprint(type, msg, stack) { var first = (stack || '').split('\n')[0] || ''; var s = (type || '') + ':' + (msg || '').substring(0, 80) + ':' + first.substring(0, 120); var h = 0; for (var i = 0; i < s.length; i++) { h = ((h << 5) - h) + s.charCodeAt(i); h |= 0; } return ('00000000' + (h >>> 0).toString(16)).slice(-8); } function capture(rec) { try { if (!rec.fingerprint) rec.fingerprint = fingerprint(rec.type, rec.message, rec.stack); if (!rec.clientReportedAt) rec.clientReportedAt = Date.now(); if (!rec.userAgent && typeof navigator !== 'undefined') rec.userAgent = navigator.userAgent || ''; rec.count = rec.count || 1; var now = Date.now(); var d = dedup[rec.fingerprint]; if (d && (now - d.lastTs) < DEDUP_MS && buf[d.idx] && buf[d.idx].fingerprint === rec.fingerprint) { buf[d.idx].count = (buf[d.idx].count || 1) + 1; d.lastTs = now; writeBuf(buf); return; } buf.push(rec); if (buf.length > BUF_CAP) { buf = buf.slice(buf.length - BUF_CAP); dedup = {}; } dedup[rec.fingerprint] = { idx: buf.length - 1, lastTs: now }; writeBuf(buf); if (typeof navigator !== 'undefined' && navigator.onLine !== false) flush(); } catch(e) { try { console.log('[cwErr] capture failed:', e); } catch(_) {} } } function buildUrl() { try { var p = window.location.pathname.split('/').filter(function(s){ return s; }); if (p.length >= 2) return '/' + p[0] + '/' + p[1] + '/cordova/errors'; } catch(e) {} return '/cordova/errors'; } function flush() { if (flushing || buf.length === 0) return; if (typeof navigator !== 'undefined' && navigator.onLine === false) return; flushing = true; var sent = buf.length; var batch = buf.slice(); for (var i = 0; i < batch.length; i++) { if (!batch[i].user && ctx.userId) batch[i].user = ctx.userId; if (!batch[i].uuid && ctx.uuid) batch[i].uuid = ctx.uuid; if (!batch[i].platform && ctx.platform) batch[i].platform = ctx.platform; if (!batch[i].appVersion && ctx.appVersion) batch[i].appVersion = ctx.appVersion; if (!batch[i].appBuild && ctx.appBuild) batch[i].appBuild = ctx.appBuild; } var done = function(ok) { flushing = false; if (ok) { buf = buf.slice(sent); dedup = {}; writeBuf(buf); } }; try { var xhr = new XMLHttpRequest(); xhr.open('POST', buildUrl(), true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.timeout = 5000; xhr.onload = function() { done(xhr.status >= 200 && xhr.status < 300); }; xhr.onerror = function() { done(false); }; xhr.ontimeout = function() { done(false); }; xhr.send('json=' + encodeURIComponent(JSON.stringify(batch))); } catch(e) { done(false); } } window.onerror = function(message, source, line, col, error) { capture({ type: 'js_error', message: message ? String(message) : '', stack: error && error.stack ? String(error.stack) : '', source: source || '', line: line || 0, col: col || 0 }); }; window.addEventListener('unhandledrejection', function(event) { var reason = event.reason || {}; var msg; if (reason && reason.message) { msg = String(reason.message); } else { try { msg = String(reason); } catch(e) { msg = ''; } } capture({ type: 'unhandled_rejection', message: msg, stack: reason && reason.stack ? String(reason.stack) : '', source: '', line: 0, col: 0 }); }); function installExecInterceptor() { if (!(window.cordova && window.cordova.exec) || window.cordova.exec.__cwWrapped) return false; var orig = window.cordova.exec; var wrapped = function(success, fail, service, action, args) { var wrappedFail = function(err) { try { var emsg; if (typeof err === 'string') emsg = err; else if (err && err.message) emsg = String(err.message); else { try { emsg = JSON.stringify(err); } catch(e) { emsg = String(err); } } capture({ type: 'plugin_error', message: emsg, stack: '', source: service + '.' + action, line: 0, col: 0 }); } catch(_) {} if (fail) fail(err); }; return orig(success, wrappedFail, service, action, args); }; wrapped.__cwWrapped = true; window.cordova.exec = wrapped; return true; } if (!installExecInterceptor()) { var tries = 0; var iv = setInterval(function() { tries++; if (installExecInterceptor() || tries > 50) clearInterval(iv); }, 100); } window.addEventListener('online', flush); document.addEventListener('resume', flush, false); document.addEventListener('deviceready', flush, false); window._cwErr = { capture: capture, flush: flush, setContext: function(c) { for (var k in c) ctx[k] = c[k]; }, _ctx: ctx, _buf: function() { return buf.slice(); } }; try { console.log('[CordovaDevice] error capture installed (offline-aware)'); } catch(_) {} } gSobject.nativePrimeErrorContext = function(ctx) { if (window._cwErr) window._cwErr.setContext(ctx); } gSobject.nativeFlushErrors = function() { if (window._cwErr) window._cwErr.flush(); } gSobject['reportProblem'] = function(userMessage, opts, success, error) { if (opts === undefined) opts = gs.map(); if (success === undefined) success = function(it) { }; if (error === undefined) error = function(it) { }; if (!gs.bool(gs.mc(userMessage,"trim",[], null, true))) { return gs.execCall(error, this, ["userMessage is required"]); }; return gs.mc(gs.fs('cordovaScreenCapture', this, gSobject),"reportProblem",[userMessage, opts, success, error]); } gSobject.nativeInstallConsoleTail = function() { if (window._cwConsoleTailInstalled) return; window._cwConsoleTailInstalled = true; window._cwConsoleTail = window._cwConsoleTail || []; var CAP = 50; var levels = ['log', 'info', 'warn', 'error']; for (var i = 0; i < levels.length; i++) { (function(level) { var orig = console[level]; console[level] = function() { try { var parts = []; for (var j = 0; j < arguments.length; j++) { var a = arguments[j]; if (a == null) { parts.push(String(a)); continue; } if (typeof a === 'string') { parts.push(a); continue; } try { parts.push(JSON.stringify(a)); } catch(e) { parts.push(String(a)); } } var line = '[' + new Date().toISOString().substr(11,12) + '] ' + level.toUpperCase() + ' ' + parts.join(' '); if (line.length > 500) line = line.substring(0, 500) + '...'; window._cwConsoleTail.push(line); if (window._cwConsoleTail.length > CAP) { window._cwConsoleTail = window._cwConsoleTail.slice(-CAP); } } catch(_) {} if (orig && orig.apply) orig.apply(console, arguments); }; })(levels[i]); } } gSobject.nativeInstallRouteHistory = function() { if (window._cwRouteHistoryInstalled) return; var CAP = 10; window._cwRouteHistory = window._cwRouteHistory || []; var tries = 0; var iv = setInterval(function() { tries++; try { if (window.vue && window.vue.router && window.vue.router.afterEach) { window.vue.router.afterEach(function(to) { try { var path = to && (to.fullPath || to.path) ? (to.fullPath || to.path) : ''; if (path) { window._cwRouteHistory.push(path); if (window._cwRouteHistory.length > CAP) { window._cwRouteHistory = window._cwRouteHistory.slice(-CAP); } } } catch(_) {} }); window._cwRouteHistoryInstalled = true; clearInterval(iv); } } catch(_) {} if (tries > 100) clearInterval(iv); }, 200); } gSobject['CordovaDevice0'] = function(it) { gs.mc(gSobject,"installErrorCapture",[]); gs.mc(document,"addEventListener",["deviceready", function(it) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["CordovaDevice:deviceready"]); gs.mc(gSobject,"splashScreenHide",[]); gs.mc(gSobject,"setupCordovaPluginKeyboard",[]); if (!gs.bool(gs.mc(this,"cordovaPluginDeviceInstalled",[], gSobject))) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["CordovaDevice:NOT INSTALLED"]); gs.mc(gSobject,"enableErrorFlush",[]); return null; }; if (!gs.bool(gs.gp(gs.fs('session', this, gSobject),"userId"))) { gs.mc(gSobject,"enableErrorFlush",[]); return null; }; gSobject.userId = gs.gp(gs.fs('session', this, gSobject),"userId"); try { gs.mc(gSobject,"setupCordovaPluginDevice",[]); gs.mc(gSobject,"setupCordovaPluginBatteryStatus",[]); gs.mc(gSobject,"setupCordovaPluginNetworkInformation",[]); gs.mc(gSobject,"disableBackButton",[]); } catch (all) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"error",[gs.plus("CordovaDevice:init:ERROR:", gs.fs('all', this, gSobject))]); } ; return gs.mc(gSobject,"enableErrorFlush",[]); }]); gs.execStatic(Utils,'setTimeout', this,[function(it) { return gs.mc(gSobject,"splashScreenHide",[]); }, 1000]); return this; } if (arguments.length==0) {gSobject.CordovaDevice0(); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; CordovaDevice.spinnerInstalled = function() { return typeof window.i3Spinner !== 'undefined'; } CordovaDevice.permissionsInstalled = function() { return typeof cordova !== 'undefined' && cordova.plugins && typeof cordova.plugins.permissions !== 'undefined'; } CordovaDevice.cordovaPluginStatusBarInstalled = function() { return ( typeof StatusBar !== 'undefined' ) } CordovaDevice.cordovaPluginDeviceInstalled = function() { return ( typeof device !== 'undefined' || typeof window.device !== 'undefined') } CordovaDevice.crdovaPluginNetworkInformationInstalled = function() { return ( typeof navigator.connection !== 'undefined') } function CordovaDeepLink() { var gSobject = gs.init('CordovaDeepLink'); gSobject.clazz = { name: 'CordovaDeepLink', simpleName: 'CordovaDeepLink'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.callbackList = gs.list([]); gSobject['registerCallback'] = function(callback) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["================CordovaDeepLink registerCallback"]); return gs.mc(gSobject.callbackList,"add",[callback]); } gSobject['openDeepLink'] = function(eventData) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["=====================CordovaDeepLink openDeepLink"]); return gs.mc(gSobject.callbackList,"each",[function(callback) { return gs.execCall(callback, this, [eventData]); }]); } gSobject['CordovaDeepLink0'] = function(it) { gs.mc(document,"addEventListener",["deviceready", function(it) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["======================CordovaDeepLink eventlistener"]); return gs.mc(gs.fs('universalLinks', this, gSobject),"subscribe",["openDeepLink", gs.gp(gs.thisOrObject(this,gSobject),"openDeepLink")]); }, false]); return this; } if (arguments.length==0) {gSobject.CordovaDeepLink0(); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function I3QrCode() { var gSobject = VueComponent(); gSobject.clazz = { name: 'I3QrCode', simpleName: 'I3QrCode'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.props = gs.map().add("text",gs.map().add("default","")).add("width",gs.map().add("default",300)).add("height",gs.map().add("default",300)); gSobject.qRCodeObject = null; gSobject['created'] = function(it) { return gSobject.self = this; } gSobject['afterMounted'] = function(it) { if (gs.bool(gs.gp(gSobject.self,"text"))) { return gs.mc(gSobject,"generateQrCode",[]); }; } gSobject['watchText'] = function(it) { if ((gs.bool(gs.gp(gSobject.self,"text"))) && (gs.bool(gs.gp(gSobject.refs,"qrCodeRef")))) { return gs.mc(gSobject,"generateQrCode",[]); }; } gSobject['generateQrCode'] = function(it) { if (!gs.bool(gs.gp(gSobject.refs,"qrCodeRef"))) { return null; }; if (gs.bool(gSobject.qRCodeObject)) { gs.mc(gSobject.qRCodeObject,"clear",[]); }; gSobject.qRCodeObject = gs.mc(gSobject,"newQrCode",[gs.gp(gSobject.refs,"qrCodeRef"), gs.gp(gSobject.self,"text"), gs.gp(gSobject.self,"width"), gs.gp(gSobject.self,"height")]); return gs.mc(gSobject.qRCodeObject,"makeCode",[gs.gp(gSobject.self,"text")]); } gSobject.newQrCode = function(element, text, width, height) { return new QRCode(element, { text: text, width: width, height: height, colorDark: '#000000', colorLight: '#ffffff', correctLevel: QRCode.CorrectLevel.H }) } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function CordovaI3Health() { var gSobject = gs.init('CordovaI3Health'); gSobject.clazz = { name: 'CordovaI3Health', simpleName: 'CordovaI3Health'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; Object.defineProperty(gSobject, 'HEALTH_PERMISSIONS', { get: function() { return CordovaI3Health.HEALTH_PERMISSIONS; }, set: function(gSval) { CordovaI3Health.HEALTH_PERMISSIONS = gSval; }, enumerable: true }); gSobject['testIsAvailable'] = function(onSuccess, onError) { if (onSuccess === undefined) onSuccess = function(it) { }; if (onError === undefined) onError = function(it) { }; return gs.mc(gSobject,"nativeIsAvailable",[function(result) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["dymicoHealth.isAvailable -> " + (result) + ""]); return gs.execCall(onSuccess, this, [gs.elvis(gs.bool(gs.gp(result,"available",true)) , gs.gp(result,"available",true) , false)]); }, function(err) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["dymicoHealth.isAvailable error: " + (err) + ""]); return gs.execCall(onError, this, [err]); }]); } gSobject['requestPermissions'] = function(onSuccess, onError) { if (onSuccess === undefined) onSuccess = function(it) { }; if (onError === undefined) onError = function(it) { }; gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["dymicoHealth.requestPermissions: requesting via Android permissions plugin"]); return gs.mc(gSobject,"nativeRequestPermissions",[function(result) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["dymicoHealth.requestPermissions -> " + (result) + ""]); return gs.execCall(onSuccess, this, [result]); }, function(err) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["dymicoHealth.requestPermissions error: " + (err) + ""]); return gs.execCall(onError, this, [err]); }]); } gSobject['querySteps'] = function(startDate, endDate, onSuccess, onError) { if (onSuccess === undefined) onSuccess = function(it) { }; if (onError === undefined) onError = function(it) { }; return gs.mc(gSobject,"nativeQuery",["steps", startDate, endDate, function(result) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["dymicoHealth.query steps -> " + (gs.mc(result,"size",[], null, true)) + " records"]); return gs.execCall(onSuccess, this, [result]); }, function(err) { return gs.execCall(onError, this, [err]); }]); } gSobject['queryHeartRate'] = function(startDate, endDate, onSuccess, onError) { if (onSuccess === undefined) onSuccess = function(it) { }; if (onError === undefined) onError = function(it) { }; return gs.mc(gSobject,"nativeQuery",["heartRate", startDate, endDate, function(result) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["dymicoHealth.query heartRate -> " + (gs.mc(result,"size",[], null, true)) + " records"]); return gs.execCall(onSuccess, this, [result]); }, function(err) { return gs.execCall(onError, this, [err]); }]); } gSobject['queryBloodPressure'] = function(startDate, endDate, onSuccess, onError) { if (onSuccess === undefined) onSuccess = function(it) { }; if (onError === undefined) onError = function(it) { }; return gs.mc(gSobject,"nativeQuery",["bloodPressure", startDate, endDate, function(result) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["dymicoHealth.query bloodPressure -> " + (gs.mc(result,"size",[], null, true)) + " records"]); return gs.execCall(onSuccess, this, [result]); }, function(err) { return gs.execCall(onError, this, [err]); }]); } gSobject['queryAggregatedSteps'] = function(startDate, endDate, onSuccess, onError) { if (onSuccess === undefined) onSuccess = function(it) { }; if (onError === undefined) onError = function(it) { }; return gs.mc(gSobject,"nativeQueryAggregated",["steps", startDate, endDate, "day", function(result) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["dymicoHealth.queryAggregated steps -> success"]); return gs.execCall(onSuccess, this, [result]); }, function(err) { return gs.execCall(onError, this, [err]); }]); } gSobject['store'] = function(dataType, data, onSuccess, onError) { if (onSuccess === undefined) onSuccess = function(it) { }; if (onError === undefined) onError = function(it) { }; return gs.mc(gSobject,"nativeStore",[dataType, data, function(result) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["dymicoHealth.store " + (dataType) + " -> success"]); return gs.execCall(onSuccess, this, [result]); }, function(err) { return gs.execCall(onError, this, [err]); }]); } gSobject.nativeIsAvailable = function(successCallback, errorCallback) { try { if (!Utils.isCordova()) { errorCallback("Cordova not available"); return; } if (!cordova.plugins.dymicoHealth) { errorCallback("dymicoHealth plugin not installed"); return; } cordova.plugins.dymicoHealth.isAvailable( function(result) { successCallback(result); }, function(err) { errorCallback(err ? err.toString() : "Unknown error"); } ); } catch (e) { console.error('dymicoHealth.isAvailable exception:', e); errorCallback(e.toString()); } } gSobject.nativeRequestPermissions = function(successCallback, errorCallback) { try { if (!Utils.isCordova()) { errorCallback("Cordova not available"); return; } var permissions = cordova.plugins.permissions; if (!permissions) { errorCallback("Android permissions plugin not available"); return; } var perms = CordovaI3Health.HEALTH_PERMISSIONS; console.log('dymicoHealth: requesting', perms.length, 'permissions'); permissions.requestPermissions(perms, function(status) { console.log('dymicoHealth: permissions result:', status); successCallback({ authorized: status.hasPermission }); }, function(err) { console.error('dymicoHealth: permissions error:', err); errorCallback(err ? err.toString() : "Permission request failed"); }); } catch (e) { console.error('dymicoHealth.requestPermissions exception:', e); errorCallback(e.toString()); } } gSobject.nativeQuery = function(dataType, startDate, endDate, successCallback, errorCallback) { try { if (!Utils.isCordova()) { errorCallback("Cordova not available"); return; } if (!cordova.plugins.dymicoHealth) { errorCallback("dymicoHealth plugin not installed"); return; } cordova.plugins.dymicoHealth.query( dataType, startDate instanceof Date ? startDate : new Date(startDate), endDate instanceof Date ? endDate : new Date(endDate), function(result) { successCallback(result); }, function(err) { errorCallback(err ? err.toString() : "Unknown error"); } ); } catch (e) { console.error('dymicoHealth.query exception:', e); errorCallback(e.toString()); } } gSobject.nativeQueryAggregated = function(dataType, startDate, endDate, bucket, successCallback, errorCallback) { try { if (!Utils.isCordova()) { errorCallback("Cordova not available"); return; } if (!cordova.plugins.dymicoHealth) { errorCallback("dymicoHealth plugin not installed"); return; } cordova.plugins.dymicoHealth.queryAggregated( dataType, startDate instanceof Date ? startDate : new Date(startDate), endDate instanceof Date ? endDate : new Date(endDate), bucket || 'day', function(result) { successCallback(result); }, function(err) { errorCallback(err ? err.toString() : "Unknown error"); } ); } catch (e) { console.error('dymicoHealth.queryAggregated exception:', e); errorCallback(e.toString()); } } gSobject.nativeStore = function(dataType, data, successCallback, errorCallback) { try { if (!Utils.isCordova()) { errorCallback("Cordova not available"); return; } if (!cordova.plugins.dymicoHealth) { errorCallback("dymicoHealth plugin not installed"); return; } cordova.plugins.dymicoHealth.store( dataType, data, function(result) { successCallback(result); }, function(err) { errorCallback(err ? err.toString() : "Unknown error"); } ); } catch (e) { console.error('dymicoHealth.store exception:', e); errorCallback(e.toString()); } } gSobject['CordovaI3Health0'] = function(it) { return this; } if (arguments.length==0) {gSobject.CordovaI3Health0(); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; CordovaI3Health.HEALTH_PERMISSIONS = gs.list(["android.permission.health.READ_STEPS" , "android.permission.health.WRITE_STEPS" , "android.permission.health.READ_HEART_RATE" , "android.permission.health.WRITE_HEART_RATE" , "android.permission.health.READ_BLOOD_PRESSURE" , "android.permission.health.WRITE_BLOOD_PRESSURE" , "android.permission.health.READ_BLOOD_GLUCOSE" , "android.permission.health.WRITE_BLOOD_GLUCOSE" , "android.permission.health.READ_WEIGHT" , "android.permission.health.WRITE_WEIGHT" , "android.permission.health.READ_HEIGHT" , "android.permission.health.WRITE_HEIGHT" , "android.permission.health.READ_SLEEP" , "android.permission.health.WRITE_SLEEP" , "android.permission.health.READ_ACTIVE_CALORIES_BURNED" , "android.permission.health.WRITE_ACTIVE_CALORIES_BURNED"]); function I3DatePicker() { var gSobject = VueComponent(); gSobject.clazz = { name: 'I3DatePicker', simpleName: 'I3DatePicker'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.props = gs.map().add("date",Date).add("clearable",Boolean).add("label",String).add("disable",Boolean).add("readonly",Boolean).add("filled",Boolean).add("outlined",Boolean).add("borderless",Boolean).add("standout",Boolean).add("rounded",Boolean).add("square",Boolean).add("dense",Boolean).add("landscape",Boolean).add("todayBtn",Boolean).add("minimal",Boolean).add("mask",String); gSobject.data = function(it) { return gs.map().add("dateString","").add("formatString","DD MMM YYYY").add("datePickerDialog",false); }; gSobject['created'] = function(it) { var self = this; gs.println("self.date"); gs.println(gs.gp(self,"date")); return gs.mc(gSobject,"init",[self]); } gSobject['init'] = function(self) { if (gs.bool(gs.gp(self,"mask"))) { gs.sp(self,"formatString",gs.gp(self,"mask")); }; return gs.sp(self,"dateString",(gs.bool(gs.gp(self,"date")) ? gs.mc(gs.mc(gSobject,"moment",[gs.gp(self,"date")]),"format",["YYYY-MM-DD"]) : null)); } gSobject['openDatePickerDialog'] = function(it) { var self = this; return gs.sp(self,"datePickerDialog",true); } gSobject['selectDate'] = function(val) { var self = this; gs.println("val"); gs.println(val); var date = gs.date(val); gs.println("date"); gs.println(date); gs.sp(self,"dateString",(gs.bool(date) ? gs.mc(gs.mc(gSobject,"moment",[date]),"format",["YYYY-MM-DD"]) : null)); gs.sp(self,"datePickerDialog",false); return gs.mc(gSobject,"emit",["update:date", date]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function PeptideOrderComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'PeptideOrderComponent', simpleName: 'PeptideOrderComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/peptideOrder" , "/peptideOrder/standalone"]); gSobject['created'] = function(it) { gs.println("PeptideOrderComponent.created()"); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "peptide.order.page"]),"do",[]); gs.mc(gSobject,"componentTheme",[false]); gs.mc(gSobject,"showFooter",[]); gs.sp(gSobject.scope,"standalone",gs.mc(gs.gp(gSobject.route,"path"),"contains",["standalone"])); gs.println("Standalone mode? " + (gs.gp(gSobject.scope,"standalone")) + ""); gs.println("Current route: " + (gs.gp(gSobject.route,"path")) + ""); gs.sp(gSobject.scope,"can_order",gs.gp(gs.fs('session', this, gSobject),"can_order")); gs.sp(gSobject.scope,"selectedQuote",null); gs.sp(gSobject.scope,"detailsVisible",false); gs.sp(gSobject.scope,"orders",gs.list([])); gs.sp(gSobject.scope,"quotes",gs.list([])); gs.sp(gSobject.scope,"invoices",gs.list([])); gs.sp(gSobject.scope,"accountError",null); gs.sp(gSobject.scope,"requiresPrescription",false); gs.sp(gSobject.scope,"loading",true); return gs.mc(gSobject,"loadPatient",[]); } gSobject['loadPatient'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppApiService"),"portalPatient",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(resp) { gs.sp(gSobject.scope,"can_order",(gs.equals(gs.gp(resp,"can_order",true), true))); gs.sp(gs.fs('session', this, gSobject),"can_order",gs.gp(gSobject.scope,"can_order")); return gs.mc(gSobject,"loadOrders",[]); }]); } gSobject['loadOrders'] = function(it) { gs.sp(gSobject.scope,"errorMessage",null); gs.sp(gSobject.scope,"loading",true); if (gs.gp(gSobject.scope,"can_order") === false) { gs.sp(gSobject.scope,"orders",gs.list([])); gs.sp(gSobject.scope,"quotes",gs.list([])); gs.sp(gSobject.scope,"hasActiveOrder",false); gs.sp(gSobject.scope,"loading",false); return null; }; return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppApiService"),"orders",[gs.gp(gs.fs('session', this, gSobject),"userId")]),"then",[function(data) { gs.println(gs.plus((gs.multiply("=", 20)), "DATA")); gs.println(data); gs.println("ORDER STATUSES:"); gs.sp(gSobject.scope,"errorMessage",gs.gp(data,"message")); var msg = gs.mc(gs.elvis(gs.bool(gs.gp(data,"message",true)) , gs.gp(data,"message",true) , ""),"toString",[]); if (gs.mc(gs.mc(msg,"toLowerCase",[], null, true),"contains",["xero contact"], null, true)) { gs.sp(gSobject.scope,"loading",false); gs.sp(gSobject.scope,"errorMessage",gs.gp(data,"message")); gs.sp(gSobject.scope,"accountError","XERO_CONTACT_MISSING"); }; if (gs.mc(gs.mc(msg,"toLowerCase",[], null, true),"contains",["prescription"], null, true)) { gs.sp(gSobject.scope,"requiresPrescription",true); gs.sp(gSobject.scope,"hasActiveOrder",false); gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"hasActiveOrder",false); gs.sp(gSobject.scope,"loading",false); return null; }; gs.sp(gSobject.scope,"invoices",gs.gp(data,"invoices")); if (gs.mc(data,"size",[]) > 0) { if (gs.bool(gs.gp(gSobject.scope,"standalone"))) { gs.sp(gSobject.scope,"orders",gs.gp(data,"orders")); } else { gs.sp(gSobject.scope,"orders",gs.mc(gs.gp(data,"orders"),"findAll",[function(order) { return gs.gp(order,"status",true) != "completed"; }])); }; gs.sp(gSobject.scope,"quotes",gs.mc(gs.gp(data,"quotes"),"findAll",[function(quote) { return gs.gp(quote,"Status",true) != "ACCEPTED"; }])); }; gs.println("Filtered " + (gs.mc(gs.gp(gSobject.scope,"quotes"),"size",[])) + " non-ACCEPTED quotes"); return gs.sp(gSobject.scope,"loading",false); }, function(error) { gs.println(gs.gp(error,"message")); gs.sp(gSobject.scope,"errorMessage",gs.gp(error,"message")); return gs.sp(gSobject.scope,"loading",false); }]); } gSobject['formatTotal'] = function(num) { var total = num; gs.println("Total"); gs.println(total); return total; } gSobject['formatDateString'] = function(dateString) { var date = gs.date(dateString); return gs.mc(date,"format",["yyyy-MM-dd HH:mm"]); } gSobject['formatDotNetDateTime'] = function(dateString) { if (!gs.bool(dateString)) { return ""; }; var millis = gs.mc(dateString,"replaceAll",["[^0-9]", ""]); return gs.mc(gs.mc(gSobject,"moment",[gs.mc(this,"parseInt",[millis, 10], gSobject)]),"format",["DD MMM YYYY HH:mm"]); } gSobject['contactNumber'] = function(it) { return gs.gp(gs.gp(gs.fs('session', this, gSobject),"user"),"cellphone"); } gSobject['formatLabelText'] = function(text) { return text; } gSobject['nextSection'] = function(it) { gs.plusPlus(gSobject.scope,"currentIndex",true,false); if (gs.gp(gSobject.scope,"currentIndex") >= (gs.minus(gs.gp(gSobject.scope,"sectionsSize"), 1))) { return gs.sp(gSobject.scope,"isFinalSection",true); }; } gSobject['backSection'] = function(it) { return gs.plusPlus(gSobject.scope,"currentIndex",false,false); } gSobject['back'] = function(it) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/peptideOrders"]); } gSobject['showQuoteDetails'] = function(quote) { gs.sp(this,"selectedQuote",quote); return gs.sp(this,"detailsVisible",true); } gSobject['formatRelativeDate'] = function(dateString) { if (!gs.bool(dateString)) { return ""; }; return gs.mc(gs.mc(gSobject,"moment",[dateString]),"fromNow",[]); } gSobject['declineQuote'] = function(quote) { return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppApiService"),"declineQuote",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(quote,"QuoteID")]),"then",[function(response) { gs.println(gs.plus((gs.multiply("=", 20)), "RESPONSE")); gs.println(response); gs.mc(gSobject,"notify",["Quote Declined", "primary"]); return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/peptideOrders"]); }, function(error) { gs.println(error); return gs.mc(gSobject,"notify",[gs.plus("Order Failed: ", gs.gp(error,"message"))]); }]); } gSobject['placeOrder'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeApiService"),"placeOrder",[function(result) { return result; }]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function StreakComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'StreakComponent', simpleName: 'StreakComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/streak"; gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "streak.log.page"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); return gs.mc(gSobject,"componentTheme",[false]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function ConsentLandingComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'ConsentLandingComponent', simpleName: 'ConsentLandingComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/consent-landing"; gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "consent.landing.page"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[false]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"agreeConsent",false); gs.sp(gSobject.scope,"agreeTermsConditions",false); gs.sp(gSobject.scope,"user",gs.map()); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"loadRxmeUser",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(rxmeUser) { gs.sp(gSobject.scope,"user",rxmeUser); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"legionService"),"loadLegionUser",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(user) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"updateUserInfo",[user, rxmeUser, function(updatedUser) { gs.sp(gs.fs('session', this, gSobject),"user",updatedUser); if (gs.gp(gs.gp(gs.fs('session', this, gSobject),"user"),"tncAcceptedOn") != null) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/"]); }; }]); }]); }]); } gSobject['next'] = function(it) { if ((!gs.bool(gs.gp(gSobject.scope,"agreePrivacyPolicy"))) || (!gs.bool(gs.gp(gSobject.scope,"agreeTermsConditions")))) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/privacy-action"]); } else { gs.sp(gs.gp(gs.fs('session', this, gSobject),"user"),"tncAcceptedOn",gs.date()); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"legionService"),"saveUser",[gs.gp(gs.fs('session', this, gSobject),"user"), function(it) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/"]); }]); }; } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function I3Select() { var gSobject = VueComponent(); gSobject.clazz = { name: 'I3Select', simpleName: 'I3Select'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.props = gs.map().add("modelValue",gs.map().add("type",String).add("default","")).add("beforeIcon",gs.map().add("type",String).add("default","")).add("prependIcon",gs.map().add("type",String).add("default","")).add("appendIcon",gs.map().add("type",String).add("default","")).add("afterIcon",gs.map().add("type",String).add("default","")); gSobject.defaults = gs.map().add("filled",true).add("dense",false).add("outlined",false).add("rounded",false).add("borderless",false).add("square",false).add("dense",true).add("debounce","500"); gSobject.data = function(it) { return gs.list([]); }; gSobject['created'] = function(it) { var self = this; var appConfig = gs.elvis(gs.bool(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"appConfig")) , gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"appConfig") , gs.map()); var config = (gs.gp(appConfig,"input") != null ? gs.gp(appConfig,"input") : gs.map()); var attrs = (gs.gp(self,"$attrs") != null ? gs.gp(self,"$attrs") : gs.map()); return gs.sp(self,"selectProps",gs.toJavascript(gs.plus((gs.plus(gSobject.defaults, config)), attrs))); } gSobject['update'] = function(val) { var self = this; gs.mc(self,"$emit",["update:modelValue", val]); return gs.mc(self,"$emit",["change"]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function SvgIcon() { var gSobject = VueComponent(); gSobject.clazz = { name: 'SvgIcon', simpleName: 'SvgIcon'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.props = gs.map().add("name",String).add("color",String).add("size",String).add("whiteBg",Boolean); gSobject.data = function(it) { return gs.map().add("icon",""); }; gSobject['created'] = function(it) { var self = this; return gs.sp(self,"icon",gs.gp(gs.fs('svgIconsComponent', this, gSobject),"" + (gs.gp(self,"name")) + "")); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function VueDateComponent() { var gSobject = VueComponent(); gSobject.clazz = { name: 'VueDateComponent', simpleName: 'VueDateComponent'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.props = gs.toJavascript(gs.list(["modelValue" , "label" , "onSelect" , "outlined" , "filled" , "standout" , "borderless" , "square" , "dark" , "clearable" , "required" , "autoClose" , "format" , "time"])); gSobject.data = function(it) { return gs.map().add("dateString","").add("selectedDate","").add("selectedTime","").add("hasTime",false).add("showDate",false).add("showTime",false).add("rules",gs.list(["val => false"])).add("autoCloseData",true).add("formatData","DD MMM YYYY"); }; gSobject['mounted'] = function(it) { var self = this; gs.sp(self,"hasTime",(gs.equals(gs.gp(self,"time"), ""))); if (gs.bool(gs.gp(self,"hasTime"))) { gs.sp(self,"formatData","DD MMM YYYY HH:mm"); }; if (gs.bool(gs.gp(self,"required"))) { gs.sp(self,"rules",gs.list(["date"])); }; if (gs.equals(gs.gp(self,"autoClose"), "false")) { gs.sp(self,"autoCloseData",false); }; if (gs.bool(gs.gp(self,"format"))) { gs.sp(self,"formatData",gs.gp(self,"format")); }; return gs.mc(gSobject,"updateDate",[self, gs.gp(self,"modelValue")]); } gSobject['updateDate'] = function(self, date) { gs.sp(this,"modelValue",date); gs.sp(self,"dateString",(gs.bool(date) ? gs.mc(gs.mc(gSobject,"moment",[date]),"format",[gs.gp(self,"formatData")]) : null)); return gs.mc(self,"$emit",["update:modelValue", date]); } gSobject['clearDate'] = function(it) { gs.sp(this,"modelValue",null); gs.sp(this,"dateString",null); return gs.mc(gSobject.self,"$emit",["update:modelValue", gs.fs('date', this, gSobject)]); } gSobject['openDate'] = function(it) { return gs.sp(this,"showDate",true); } gSobject['closeAll'] = function(it) { gs.sp(this,"showDate",false); return gs.sp(this,"showTime",false); } gSobject['selectedDateString'] = function(dateStringValue) { if (!gs.bool(dateStringValue)) { return null; }; gs.mc(gSobject,"updateDate",[this, gs.date(dateStringValue)]); var self = this; gs.sp(this,"showDate",false); if (gs.bool(gs.gp(self,"hasTime"))) { return gs.sp(this,"showTime",true); }; } gSobject['selectedTimeString'] = function(timeStringValue) { if (!gs.bool(timeStringValue)) { return null; }; gs.sp(this,"showTime",false); var timeParts = gs.mc(timeStringValue,"split",[":"]); gs.mc(gs.gp(gs.thisOrObject(this,gSobject),"modelValue"),"setHours",[timeParts[0]]); gs.mc(gs.gp(gs.thisOrObject(this,gSobject),"modelValue"),"setMinutes",[timeParts[1]]); return gs.mc(gSobject,"updateDate",[this, gs.gp(gs.thisOrObject(this,gSobject),"modelValue")]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function WeightOverviewComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'WeightOverviewComponent', simpleName: 'WeightOverviewComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/weightOverview" , "/weightOverview/:id"]); gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.weight.overview"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"batchName","medical:score:body_weight"); gs.sp(gSobject.scope,"batchName2","medical:score:body_fat"); gs.sp(gSobject.scope,"graphPeriod","Day"); gs.sp(gSobject.scope,"bodyFatInfo",null); gs.sp(gSobject.scope,"bmiInfo",null); gs.sp(gSobject.scope,"tracker",null); gs.sp(gSobject.scope,"bodyWeight",0); gs.sp(gSobject.scope,"formattedWeight",""); gs.sp(gSobject.scope,"lastUpdated",""); gs.sp(gSobject.scope,"lastUpdatedAlt",""); gs.sp(gSobject.scope,"startWeight",0); gs.sp(gSobject.scope,"weightChange",0); gs.sp(gSobject.scope,"weightDistanceFromGoal",0); gs.sp(gSobject.scope,"selectedGraph","Weight"); gs.sp(gSobject.scope,"bodyWeightLogs",gs.list([])); gs.mc(gSobject,"loadLogs",[]); gs.mc(gSobject,"bodyFatInfo",[]); gs.mc(gSobject,"bmiResultInfo",[]); gs.mc(gSobject,"loadTrackerData",["Weight", function(tracker) { return gs.sp(gSobject.scope,"tracker",tracker); }]); gs.sp(gSobject.scope,"motivationalText",""); gs.sp(gSobject.scope,"motivationLoading",true); return gs.mc(gSobject,"loadMotivation",[gs.gp(gs.fs('session', this, gSobject),"userId"), "Weight", function(msg) { gs.sp(gSobject.scope,"motivationalText",msg); return gs.sp(gSobject.scope,"motivationLoading",false); }]); } gSobject['loadLogs'] = function(it) { gs.sp(gSobject.scope,"weightGoal",gs.map().add("weight","").add("unit",null).add("description","").add("progressText","Please configure your target weight.").add("goalDate","No Date")); gs.sp(gSobject.scope,"dateCreated",gs.mc(gs.mc(gSobject,"moment",[gs.gp(gs.gp(gs.fs('session', this, gSobject),"user"),"_dateCreated")]),"format",["YYYY-MM-DD"])); gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:body_weight_goal", function(weightGoal) { if (gs.bool(weightGoal)) { gs.mc(gs.gp(gSobject.scope,"weightGoal"),"putAll",[weightGoal]); gs.sp(gs.gp(gSobject.scope,"weightGoal"),"unit","kg"); gs.sp(gs.gp(gSobject.scope,"weightGoal"),"description","target weight"); gs.sp(gs.gp(gSobject.scope,"weightGoal"),"progressText","You're on track! Keep working hard to improve your health & overall score."); if (gs.bool(gs.gp(weightGoal,"date"))) { gs.sp(gs.gp(gSobject.scope,"weightGoal"),"goalDate",gs.mc(gs.mc(gSobject,"moment",[gs.gp(weightGoal,"date")]),"format",["YYYY-MM-DD"])); }; gs.println("WEIGHT GOAL"); gs.println(weightGoal); }; gs.sp(gSobject.scope,"bodyFat",null); gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:body_fat:value", function(bodyFat) { if (gs.bool(bodyFat)) { return gs.sp(gSobject.scope,"bodyFat",bodyFat); }; }]); return gs.mc(gs.gp(gs.mc(gs.fs('o', this, gSobject),"localAndRemote",[]),"protoDataPointTimelineService"),"listEntries",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:body_weight", gs.map().add("limit",10).add("sort","date").add("order","desc"), function(logs) { gs.println("logs"); gs.println(logs); gs.println("lastEntry: " + (gs.gp(gSobject.scope,"lastEntry")) + ""); gs.sp(gSobject.scope,"bodyWeightLogs",gs.list([])); gs.mc(logs,"each",[function(log) { return gs.mc(gs.gp(gSobject.scope,"bodyWeightLogs"),"add",[gs.map().add("_id",gs.gp(log,"_id")).add("value",gs.gp(log,"value")).add("subtext",gs.gp(log,"status")).add("unit","kg").add("_createdAt",gs.gp(log,"date"))]); }]); gs.sp(gSobject.scope,"bodyWeight",gs.elvis(gs.bool(gs.gp(logs[0],"value",true)) , gs.gp(logs[0],"value",true) , 0)); gs.sp(gSobject.scope,"formattedWeight",gs.mc(gs.gp(gSobject.scope,"bodyWeight"),"toFixed",[1])); if (gs.bool(gs.gp(logs[0],"date",true))) { gs.sp(gSobject.scope,"lastUpdated",gs.mc(gs.mc(gSobject,"moment",[gs.gp(logs[0],"date")]),"format",["ddd DD MMM [at] HH:mm"])); gs.sp(gSobject.scope,"lastUpdatedAlt",gs.mc(gs.mc(gSobject,"moment",[gs.gp(logs[0],"date")]),"format",["YYYY-MM-DD"])); }; gs.println("scope: " + (gs.gp(gSobject.scope,"bodyWeight")) + ""); return gs.mc(gSobject,"calcWeightStats",[]); }]); }]); gs.sp(gSobject.scope,"bodyFatLog",""); gs.sp(gSobject.scope,"bodyFatLogs",gs.list([])); gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"listEntries",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:body_fat", gs.map().add("limit",10), function(bodylogs) { gs.println("Body Fat"); gs.println(bodylogs); return gs.mc(bodylogs,"each",[function(log) { gs.mc(gs.gp(gSobject.scope,"bodyFatLogs"),"add",[gs.map().add("_id",gs.gp(log,"_id")).add("value",gs.gp(log,"value")).add("subtext",gs.gp(log,"status")).add("unit","%").add("_createdAt",gs.gp(log,"date"))]); return gs.sp(gSobject.scope,"bodyFatLog",gs.elvis(gs.bool(gs.gp(gSobject.scope,"bodyFatLog")) , gs.gp(gSobject.scope,"bodyFatLog") , gs.gp(log,"value"))); }]); }]); gs.sp(gSobject.scope,"bodyWeightLabels",null); gs.sp(gSobject.scope,"bodyWeightValues",null); gs.sp(gSobject.scope,"bodyBmiValues",null); gs.mc(gs.gp(gs.mc(gs.fs('o', this, gSobject),"localAndRemote",[]),"protoDataPointTimelineService"),"metrics",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:body_weight-value", gs.date(), gs.gp(gSobject.scope,"graphPeriod"), function(logs) { gs.println("bodyWeightValues"); gs.println(logs); gs.sp(gSobject.scope,"bodyWeightLabels",gs.gp(logs,"labels")); gs.sp(gSobject.scope,"bodyWeightValues",gs.mc(gs.gp(logs,"avgValues"),"collect",[function(it) { return (gs.equals(it, 0) ? null : it); }])); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "health:height", function(height) { gs.println("HEIGHT: " + (height) + ""); if (!gs.bool(height)) { gs.sp(gSobject.scope,"bodyBmiValues",gs.mc(gs.gp(logs,"avgValues"),"collect",[function(it) { return null; }])); return null; }; gs.sp(gSobject.scope,"bodyBmiValues",gs.mc(gs.gp(logs,"avgValues"),"collect",[function(w) { if (((gs.equals(w, null)) || (gs.equals(w, 0))) || (!gs.bool(height))) { return null; }; var h = gs.mc(this,"Number",[height], gSobject); h = (gs.div(h, 100.0)); if (h <= 0) { return null; }; return gs.div(Math.round(gs.multiply((gs.div(w, (gs.multiply(h, h)))), 10)), 10.0); }])); gs.println("BMI"); return gs.println(gs.gp(gSobject.scope,"bodyBmiValues")); }]); }]); gs.sp(gSobject.scope,"bodyFatLabels",null); gs.sp(gSobject.scope,"bodyFatValues",null); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"metrics",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:body_fat-value", gs.date(), gs.gp(gSobject.scope,"graphPeriod"), function(logs) { gs.println("bodyFatValues"); gs.println(logs); gs.sp(gSobject.scope,"bodyFatLabels",gs.gp(logs,"labels")); return gs.sp(gSobject.scope,"bodyFatValues",gs.mc(gs.gp(logs,"aggAvgValues"),"collect",[function(it) { return (gs.equals(it, 0) ? null : it); }])); }]); } gSobject['bodyFatInfo'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"medicalCalculationService"),"bodyFatInfo",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(bodyFatInfo) { return gs.sp(gSobject.scope,"bodyFatInfo",bodyFatInfo); }]); } gSobject['bmiResultInfo'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"medicalCalculationService"),"bmiInfo",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(bmiInfo) { return gs.sp(gSobject.scope,"bmiInfo",bmiInfo); }]); } gSobject['calcWeightStats'] = function(it) { return gs.mc(gs.gp(gs.mc(gs.fs('o', this, gSobject),"localAndRemote",[]),"protoDataPointTimelineService"),"listEntries",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:body_weight", gs.map().add("limit",1).add("sort","date").add("order","asc"), function(entries) { var earliest = (gs.bool(entries) ? entries[0] : null); if (gs.bool(earliest)) { gs.sp(gSobject.scope,"startWeight",gs.gp(earliest,"value")); gs.sp(gSobject.scope,"dateCreated",gs.mc(gs.mc(gSobject,"moment",[gs.gp(earliest,"date")]),"format",["YYYY-MM-DD"])); }; gs.println("Calculate weight change: "); gs.println("" + (gs.gp(gSobject.scope,"bodyWeight")) + " - " + (gs.gp(gSobject.scope,"startWeight")) + ""); gs.sp(gSobject.scope,"weightChange",(gs.minus(gs.gp(gSobject.scope,"bodyWeight"), gs.gp(gSobject.scope,"startWeight")))); gs.sp(gSobject.scope,"weightChange",gs.mc(gs.gp(gSobject.scope,"weightChange"),"toFixed",[1])); if (!gs.bool(gs.gp(gs.gp(gSobject.scope,"weightGoal"),"weight"))) { gs.sp(gSobject.scope,"weightDistanceFromGoal",0); return null; }; gs.println("Calculate weight goal distance: "); gs.println("" + (gs.gp(gSobject.scope,"bodyWeight")) + " - " + (gs.gp(gSobject.scope,"weightGoal")) + ""); gs.sp(gSobject.scope,"weightDistanceFromGoal",(gs.minus(gs.gp(gSobject.scope,"bodyWeight"), gs.gp(gs.gp(gSobject.scope,"weightGoal"),"weight")))); return gs.sp(gSobject.scope,"weightDistanceFromGoal",gs.mc(gs.gp(gSobject.scope,"weightDistanceFromGoal"),"toFixed",[1])); }]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function WeightDetailComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'WeightDetailComponent', simpleName: 'WeightDetailComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/weightDetail" , "/weightDetail/:id"]); gSobject['created'] = function(it) { gs.println("WeightDetailComponent"); gs.sp(gSobject.scope,"bmi",null); gs.sp(gSobject.scope,"weightGoal",null); gs.sp(gSobject.scope,"bmiInfo",null); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.weight.detail"]),"do",[]); gs.mc(gSobject,"loadDetails",[]); gs.mc(gSobject,"showHeaderFooter",[false]); gs.mc(gSobject,"componentTheme",[false]); gs.mc(gSobject,"loadBMI",[]); return gs.mc(gSobject,"bmiResultInfo",[]); } gSobject['loadBMI'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"medicalCalculationService"),"calculateBMI",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(bmi) { return gs.sp(gSobject.scope,"bmi",bmi); }]); } gSobject['loadDetails'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:body_weight_goal", function(weightGoal) { return gs.sp(gSobject.scope,"weightGoal",weightGoal); }]); } gSobject['bmiResultInfo'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"medicalCalculationService"),"bmiInfo",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(bmiInfo) { return gs.sp(gSobject.scope,"bmiInfo",bmiInfo); }]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function WeightInsightComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'WeightInsightComponent', simpleName: 'WeightInsightComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/weightInsight" , "/weightInsight/:id"]); gSobject['created'] = function(it) { gs.sp(gSobject.scope,"bmi",null); gs.sp(gSobject.scope,"bmiInfo",null); gs.sp(gSobject.scope,"bmiCategory",null); gs.sp(gSobject.scope,"bmiDescription",null); gs.sp(gSobject.scope,"bmiSummaryHeadline","Your weight and height place your BMI within the recommended range."); gs.sp(gSobject.scope,"bmr",null); gs.sp(gSobject.scope,"weight",null); gs.sp(gSobject.scope,"age",null); gs.sp(gSobject.scope,"height",null); gs.sp(gSobject.scope,"exercise",null); gs.sp(gSobject.scope,"bmiLogs",gs.list([])); gs.sp(gSobject.scope,"weightLogs",gs.list([])); gs.sp(gSobject.scope,"userHeightCm",null); gs.sp(gSobject.scope,"bmiHistory",gs.list([])); gs.sp(gSobject.scope,"rxmeUser",gs.map()); gs.sp(gSobject.scope,"currentWeight",null); gs.sp(gSobject.scope,"weightGoal",null); gs.sp(gSobject.scope,"weightLogsLoaded",false); gs.sp(gSobject.scope,"weightCategory",null); gs.sp(gSobject.scope,"weightSummaryHeadline","Your weight is within the recommended range."); gs.sp(gSobject.scope,"weightDescription","This suggests a healthy balance and a lower risk for weight-related health concerns. Maintaining consistent habits around nutrition, movement, and lifestyle can help you stay on track."); gs.sp(gSobject.scope,"bodyFatInfo",null); gs.sp(gSobject.scope,"bodyFatCategory",null); gs.sp(gSobject.scope,"bodyFatDescription","Body fat percentage helps estimate whether your fat mass is within a healthy range for metabolic health."); gs.sp(gSobject.scope,"bodyFatSummaryHeadline","Your body fat is within the recommended range."); gs.sp(gSobject.scope,"currentBodyFat",null); gs.sp(gSobject.scope,"bodyFatLogs",gs.list([])); gs.sp(gSobject.scope,"bmiMap",gs.list([gs.map().add("_id",0).add("label","Last Month").add("barValue",0).add("displayBmi","N/A") , gs.map().add("_id",1).add("label","This Month").add("barValue",0).add("displayBmi","N/A")])); gs.sp(gSobject.scope,"weightMap",gs.list([gs.map().add("_id",0).add("label","Last month").add("barValue",0).add("displayWeight","N/A") , gs.map().add("_id",1).add("label","This month").add("barValue",0).add("displayWeight","N/A")])); gs.sp(gSobject.scope,"bodyFatMap",gs.list([gs.map().add("_id",0).add("label","Last month").add("barValue",0).add("displayBodyFat","N/A") , gs.map().add("_id",1).add("label","This month").add("barValue",0).add("displayBodyFat","N/A")])); gs.sp(gSobject.scope,"bmiChartLabels",gs.list(["Last Month" , "This Month"])); gs.sp(gSobject.scope,"bmiChartValues",gs.list([0 , 0])); gs.sp(gSobject.scope,"weightChartLabels",gs.list(["Last month" , "This month"])); gs.sp(gSobject.scope,"weightChartValues",gs.list([0 , 0])); gs.sp(gSobject.scope,"bodyFatChartLabels",gs.list(["Last month" , "This month"])); gs.sp(gSobject.scope,"bodyFatChartValues",gs.list([0 , 0])); gs.sp(gSobject.scope,"barColors",gs.list(["#5ba9df" , "#41b74d"])); gs.sp(gSobject.scope,"weightBarColors",gs.list(["#5ba9df" , "#41b74d"])); gs.sp(gSobject.scope,"bodyFatBarColors",gs.list(["#5ba9df" , "#f0bd6b"])); gs.sp(gSobject.scope,"max",30); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.weight.insight"]),"do",[]); gs.mc(gSobject,"loadBMI",[]); gs.mc(gSobject,"loadBmiInfo",[]); gs.mc(gSobject,"loadHistory",[]); gs.mc(gSobject,"loadWeightHistoryForBmiFallback",[]); gs.mc(gSobject,"loadUserHeightForBmiFallback",[]); gs.mc(gSobject,"loadCurrentWeight",[]); gs.mc(gSobject,"loadWeightGoal",[]); gs.mc(gSobject,"loadCurrentBodyFat",[]); gs.mc(gSobject,"loadBodyFatHistory",[]); gs.mc(gSobject,"loadBodyFatInfo",[]); gs.mc(gSobject,"loadRxmeUser",[]); gs.mc(gSobject,"showHeaderFooter",[false]); return gs.mc(gSobject,"componentTheme",[false]); } gSobject['loadBMI'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"medicalCalculationService"),"calculateBMI",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(bmi) { gs.sp(gSobject.scope,"bmi",bmi); return gs.mc(gSobject,"updateBmiMap",[]); }]); } gSobject['loadBmiInfo'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"medicalCalculationService"),"bmiInfo",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(bmiInfo) { gs.sp(gSobject.scope,"bmiInfo",bmiInfo); gs.sp(gSobject.scope,"bmiCategory",gs.gp(bmiInfo,"category",true)); gs.sp(gSobject.scope,"bmiDescription",gs.gp(bmiInfo,"description",true)); gs.sp(gSobject.scope,"bmiSummaryHeadline",gs.mc(gSobject,"bmiHeadlineForCategory",[gs.gp(gSobject.scope,"bmiCategory")])); gs.sp(gSobject.scope,"weightCategory",gs.gp(bmiInfo,"category",true)); return gs.sp(gSobject.scope,"weightSummaryHeadline",gs.mc(gSobject,"weightHeadlineForCategory",[gs.gp(gSobject.scope,"weightCategory")])); }]); } gSobject['bmiHeadlineForCategory'] = function(category) { var normalized = gs.elvis(gs.mc(gs.mc(category,"toString",[], null, true),"toLowerCase",[], null, true) , gs.mc(gs.mc(category,"toString",[], null, true),"toLowerCase",[], null, true) , ""); if (gs.mc(normalized,"contains",["below"])) { return "Your BMI is below the recommended range."; }; if (gs.mc(normalized,"contains",["normal"])) { return "Your weight and height place your BMI within the recommended range."; }; return "Your BMI is above the recommended range."; } gSobject['weightHeadlineForCategory'] = function(category) { var normalized = gs.elvis(gs.mc(gs.mc(category,"toString",[], null, true),"toLowerCase",[], null, true) , gs.mc(gs.mc(category,"toString",[], null, true),"toLowerCase",[], null, true) , ""); if (gs.mc(normalized,"contains",["below"])) { return "Your weight is below the recommended range."; }; if (gs.mc(normalized,"contains",["normal"])) { return "Your weight is within the recommended range."; }; return "Your weight is above the recommended range."; } gSobject['bodyFatHeadlineForCategory'] = function(category) { var normalized = gs.elvis(gs.mc(gs.mc(category,"toString",[], null, true),"toLowerCase",[], null, true) , gs.mc(gs.mc(category,"toString",[], null, true),"toLowerCase",[], null, true) , ""); if ((gs.mc(normalized,"contains",["below"])) || (gs.mc(normalized,"contains",["low"]))) { return "Your body fat is below the recommended range."; }; if ((gs.mc(normalized,"contains",["normal"])) || (gs.mc(normalized,"contains",["average"]))) { return "Your body fat is within the recommended range."; }; if (((gs.mc(normalized,"contains",["over"])) || (gs.mc(normalized,"contains",["high"]))) || (gs.mc(normalized,"contains",["obese"]))) { return "Your body fat is above the recommended range."; }; } gSobject['loadCurrentWeight'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:body_weight:value", function(weight) { gs.sp(gSobject.scope,"currentWeight",weight); if (gs.bool(gs.gp(gSobject.scope,"weightLogsLoaded"))) { return gs.mc(gSobject,"updateWeightMap",[]); }; }]); } gSobject['loadWeightGoal'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:body_weight_goal", function(weightGoal) { return gs.sp(gSobject.scope,"weightGoal",gs.elvis(gs.bool(weightGoal) , weightGoal , null)); }]); } gSobject['loadCurrentBodyFat'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:body_fat:value", function(bodyFat) { gs.sp(gSobject.scope,"currentBodyFat",bodyFat); return gs.mc(gSobject,"updateBodyFatMap",[]); }]); } gSobject['loadBodyFatInfo'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"medicalCalculationService"),"bodyFatInfo",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(info) { gs.sp(gSobject.scope,"bodyFatInfo",info); gs.sp(gSobject.scope,"bodyFatCategory",gs.gp(info,"category",true)); gs.sp(gSobject.scope,"bodyFatDescription",gs.elvis(gs.bool(gs.gp(info,"description",true)) , gs.gp(info,"description",true) , gs.gp(gSobject.scope,"bodyFatDescription"))); return gs.sp(gSobject.scope,"bodyFatSummaryHeadline",gs.mc(gSobject,"bodyFatHeadlineForCategory",[gs.gp(gSobject.scope,"bodyFatCategory")])); }]); } gSobject['loadHistory'] = function(it) { return gs.mc(gs.gp(gs.mc(gs.fs('o', this, gSobject),"localAndRemote",[]),"protoDataPointTimelineService"),"listEntries",[gs.gp(gs.fs('session', this, gSobject),"userId"), "score_bmi", gs.map().add("limit",60), function(logs) { gs.sp(gSobject.scope,"bmiLogs",logs); return gs.mc(gSobject,"updateBmiMap",[]); }]); } gSobject['loadWeightHistoryForBmiFallback'] = function(it) { return gs.mc(gs.gp(gs.mc(gs.fs('o', this, gSobject),"localAndRemote",[]),"protoDataPointTimelineService"),"listEntries",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:body_weight", gs.map().add("limit",120), function(logs) { gs.sp(gSobject.scope,"weightLogs",gs.elvis(gs.bool(logs) , logs , gs.list([]))); gs.sp(gSobject.scope,"weightLogsLoaded",true); gs.mc(gSobject,"updateBmiMap",[]); return gs.mc(gSobject,"updateWeightMap",[]); }]); } gSobject['loadUserHeightForBmiFallback'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "health:height", function(height) { gs.sp(gSobject.scope,"userHeightCm",height); return gs.mc(gSobject,"updateBmiMap",[]); }]); } gSobject['extractBmiValue'] = function(log) { var raw = gs.elvis(gs.bool(gs.gp(log,"health:score:bmi",true)) , gs.gp(log,"health:score:bmi",true) , gs.elvis(gs.bool(gs.gp(log,"value",true)) , gs.gp(log,"value",true) , gs.gp(log,"bmi",true))); if (gs.equals(raw, null)) { return null; }; try { return gs.mc(raw,"doubleValue",[]); } catch (e) { return null; } ; } gSobject['extractWeightValue'] = function(log) { var raw = gs.elvis(gs.bool(gs.gp(log,"value",true)) , gs.gp(log,"value",true) , gs.gp(log,"medical:score:body_weight:value",true)); if (gs.equals(raw, null)) { return null; }; try { return gs.mc(raw,"doubleValue",[]); } catch (e) { return null; } ; } gSobject['extractBodyFatValue'] = function(log) { var raw = gs.elvis(gs.bool(gs.gp(log,"value",true)) , gs.gp(log,"value",true) , gs.gp(log,"medical:score:body_fat:value",true)); if (gs.equals(raw, null)) { return null; }; try { return gs.mc(raw,"doubleValue",[]); } catch (e) { return null; } ; } gSobject['parseLogDate'] = function(log) { var rawDate = gs.elvis(gs.bool(gs.gp(log,"date",true)) , gs.gp(log,"date",true) , gs.elvis(gs.bool(gs.gp(log,"_createdAt",true)) , gs.gp(log,"_createdAt",true) , gs.elvis(gs.bool(gs.gp(log,"createdAt",true)) , gs.gp(log,"createdAt",true) , gs.gp(log,"_lastUpdated",true)))); if (!gs.bool(rawDate)) { return null; }; var m = gs.mc(gSobject,"moment",[rawDate]); if (gs.mc(m,"isValid",[], null, true)) { return m; }; return null; } gSobject['latestEntryForMonth'] = function(logs, monthKey) { var monthLogs = gs.mc(gs.elvis(gs.bool(logs) , logs , gs.list([])),"findAll",[function(log) { var m = gs.mc(gSobject,"parseLogDate",[log]); return (gs.bool(m)) && (gs.equals(gs.mc(m,"format",["YYYY-MM"]), monthKey)); }]); if (!gs.bool(monthLogs)) { return null; }; return gs.mc(monthLogs,"sort",[function(a, b) { var aTime = gs.elvis(gs.mc(gs.mc(gSobject,"parseLogDate",[a]),"valueOf",[], null, true) , gs.mc(gs.mc(gSobject,"parseLogDate",[a]),"valueOf",[], null, true) , 0); var bTime = gs.elvis(gs.mc(gs.mc(gSobject,"parseLogDate",[b]),"valueOf",[], null, true) , gs.mc(gs.mc(gSobject,"parseLogDate",[b]),"valueOf",[], null, true) , 0); return gs.spaceShip(bTime, aTime); }])[0]; } gSobject['latestEntryBeforeMonth'] = function(logs, monthKey) { var monthStart = gs.mc(gSobject,"moment",[gs.plus(monthKey, "-01"), "YYYY-MM-DD"]); if (!gs.bool(gs.mc(monthStart,"isValid",[], null, true))) { return null; }; var olderLogs = gs.mc(gs.elvis(gs.bool(logs) , logs , gs.list([])),"findAll",[function(log) { var m = gs.mc(gSobject,"parseLogDate",[log]); return (gs.bool(m)) && (gs.mc(m,"isBefore",[monthStart, "month"])); }]); if (!gs.bool(olderLogs)) { return null; }; return gs.mc(olderLogs,"sort",[function(a, b) { var aTime = gs.elvis(gs.mc(gs.mc(gSobject,"parseLogDate",[a]),"valueOf",[], null, true) , gs.mc(gs.mc(gSobject,"parseLogDate",[a]),"valueOf",[], null, true) , 0); var bTime = gs.elvis(gs.mc(gs.mc(gSobject,"parseLogDate",[b]),"valueOf",[], null, true) , gs.mc(gs.mc(gSobject,"parseLogDate",[b]),"valueOf",[], null, true) , 0); return gs.spaceShip(bTime, aTime); }])[0]; } gSobject['bmiFromWeight'] = function(weightKg) { if ((!gs.bool(gs.gp(gSobject.scope,"userHeightCm"))) || (!gs.bool(weightKg))) { return null; }; try { var heightM = gs.div(gs.mc(gs.gp(gSobject.scope,"userHeightCm"),"doubleValue",[]), 100.0); if (heightM <= 0) { return null; }; return gs.div(Math.round(gs.multiply((gs.div(weightKg, (gs.multiply(heightM, heightM)))), 100)), 100.0); } catch (e) { return null; } ; } gSobject['bmiRangeScaleMin'] = function(it) { return 12.0; } gSobject['bmiRangeScaleMax'] = function(it) { return 40.0; } gSobject['bmiPointLeftPercent'] = function(value) { if (gs.equals(value, null)) { return null; }; try { var numericValue = gs.mc(value,"doubleValue",[]); var min = gs.mc(gSobject,"bmiRangeScaleMin",[]); var max = gs.mc(gSobject,"bmiRangeScaleMax",[]); if (max <= min) { return 0; }; var clamped = Math.max(min, Math.min(max, numericValue)); return gs.multiply((gs.div((gs.minus(clamped, min)), (gs.minus(max, min)))), 100); } catch (e) { return null; } ; } gSobject['bmiSegmentWidthPercent'] = function(startValue, endValue) { var start = gs.mc(gSobject,"bmiPointLeftPercent",[startValue]); var end = gs.mc(gSobject,"bmiPointLeftPercent",[endValue]); if ((gs.equals(start, null)) || (gs.equals(end, null))) { return 0; }; return Math.max(0, gs.minus(end, start)); } gSobject['bmiMarkerLeftPercent'] = function(it) { return gs.mc(gSobject,"bmiPointLeftPercent",[gs.gp(gSobject.scope,"bmi")]); } gSobject['bmiGoalValue'] = function(it) { if ((!gs.bool(gs.gp(gSobject.scope,"weightGoal"))) || (!gs.bool(gs.gp(gSobject.scope,"userHeightCm")))) { return null; }; try { var goalWeightRaw = gs.elvis(gs.bool(gs.gp(gs.gp(gSobject.scope,"weightGoal"),"weight",true)) , gs.gp(gs.gp(gSobject.scope,"weightGoal"),"weight",true) , gs.gp(gs.gp(gSobject.scope,"weightGoal"),"value",true)); if (gs.equals(goalWeightRaw, null)) { return null; }; var goalWeightKg = gs.mc(goalWeightRaw,"doubleValue",[]); if (goalWeightKg <= 0) { return null; }; var heightM = gs.div(gs.mc(gs.gp(gSobject.scope,"userHeightCm"),"doubleValue",[]), 100.0); if (heightM <= 0) { return null; }; return gs.div(Math.round(gs.multiply((gs.div(goalWeightKg, (gs.multiply(heightM, heightM)))), 100)), 100.0); } catch (e) { return null; } ; } gSobject['bmiGoalLeftPercent'] = function(it) { return gs.mc(gSobject,"bmiPointLeftPercent",[gs.mc(gSobject,"bmiGoalValue",[])]); } gSobject['weightRangeScaleMin'] = function(it) { return 35.0; } gSobject['weightRangeScaleMax'] = function(it) { return 110.0; } gSobject['weightPointLeftPercent'] = function(value) { if (gs.equals(value, null)) { return null; }; try { var numericValue = gs.mc(value,"doubleValue",[]); var min = gs.mc(gSobject,"weightRangeScaleMin",[]); var max = gs.mc(gSobject,"weightRangeScaleMax",[]); if (max <= min) { return 0; }; var clamped = Math.max(min, Math.min(max, numericValue)); return gs.multiply((gs.div((gs.minus(clamped, min)), (gs.minus(max, min)))), 100); } catch (e) { return null; } ; } gSobject['weightSegmentWidthPercent'] = function(startValue, endValue) { var start = gs.mc(gSobject,"weightPointLeftPercent",[startValue]); var end = gs.mc(gSobject,"weightPointLeftPercent",[endValue]); if ((gs.equals(start, null)) || (gs.equals(end, null))) { return 0; }; return Math.max(0, gs.minus(end, start)); } gSobject['weightMarkerLeftPercent'] = function(it) { return gs.mc(gSobject,"weightPointLeftPercent",[gs.gp(gSobject.scope,"currentWeight")]); } gSobject['weightMarkerBorderColor'] = function(it) { if (gs.equals(gs.gp(gSobject.scope,"currentWeight"), null)) { return "#234d52"; }; try { var value = gs.mc(gs.gp(gSobject.scope,"currentWeight"),"doubleValue",[]); if (value < 53.0) { return "#42a5f5"; }; if (value < 72.0) { return "#66bb6a"; }; if (value < 87.0) { return "#ffa726"; }; return "#ef5350"; } catch (e) { return "#234d52"; } ; } gSobject['weightGoalValue'] = function(it) { if (!gs.bool(gs.gp(gSobject.scope,"weightGoal"))) { return null; }; try { var goalWeightRaw = gs.elvis(gs.bool(gs.gp(gs.gp(gSobject.scope,"weightGoal"),"weight",true)) , gs.gp(gs.gp(gSobject.scope,"weightGoal"),"weight",true) , gs.gp(gs.gp(gSobject.scope,"weightGoal"),"value",true)); if (gs.equals(goalWeightRaw, null)) { return null; }; var goalWeightKg = gs.mc(goalWeightRaw,"doubleValue",[]); if (goalWeightKg <= 0) { return null; }; return gs.div(Math.round(gs.multiply(goalWeightKg, 10)), 10.0); } catch (e) { return null; } ; } gSobject['weightGoalLeftPercent'] = function(it) { return gs.mc(gSobject,"weightPointLeftPercent",[gs.mc(gSobject,"weightGoalValue",[])]); } gSobject['bodyFatRangeScaleMin'] = function(it) { return 10.0; } gSobject['bodyFatRangeScaleMax'] = function(it) { return 50.0; } gSobject['bodyFatPointLeftPercent'] = function(value) { if (gs.equals(value, null)) { return null; }; try { var numericValue = gs.mc(value,"doubleValue",[]); var min = gs.mc(gSobject,"bodyFatRangeScaleMin",[]); var max = gs.mc(gSobject,"bodyFatRangeScaleMax",[]); if (max <= min) { return 0; }; var clamped = Math.max(min, Math.min(max, numericValue)); return gs.multiply((gs.div((gs.minus(clamped, min)), (gs.minus(max, min)))), 100); } catch (e) { return null; } ; } gSobject['bodyFatSegmentWidthPercent'] = function(startValue, endValue) { var start = gs.mc(gSobject,"bodyFatPointLeftPercent",[startValue]); var end = gs.mc(gSobject,"bodyFatPointLeftPercent",[endValue]); if ((gs.equals(start, null)) || (gs.equals(end, null))) { return 0; }; return Math.max(0, gs.minus(end, start)); } gSobject['bodyFatMarkerLeftPercent'] = function(it) { return gs.mc(gSobject,"bodyFatPointLeftPercent",[gs.gp(gSobject.scope,"currentBodyFat")]); } gSobject['bmiMarkerBorderColor'] = function(it) { if (gs.equals(gs.gp(gSobject.scope,"bmi"), null)) { return "#234d52"; }; try { var value = gs.mc(gs.gp(gSobject.scope,"bmi"),"doubleValue",[]); if (value < 18.5) { return "#42a5f5"; }; if (value < 25.15) { return "#66bb6a"; }; if (value < 29.9) { return "#ffa726"; }; return "#ef5350"; } catch (e) { return "#234d52"; } ; } gSobject['bodyFatMarkerBorderColor'] = function(it) { if (gs.equals(gs.gp(gSobject.scope,"currentBodyFat"), null)) { return "#234d52"; }; try { var value = gs.mc(gs.gp(gSobject.scope,"currentBodyFat"),"doubleValue",[]); if (value < 21.0) { return "#42a5f5"; }; if (value < 25.0) { return "#66bb6a"; }; if (value < 38.0) { return "#ffa726"; }; return "#ef5350"; } catch (e) { return "#234d52"; } ; } gSobject['updateBmiMap'] = function(it) { var logs = gs.elvis(gs.bool(gs.gp(gSobject.scope,"bmiLogs")) , gs.gp(gSobject.scope,"bmiLogs") , gs.list([])); var weightLogs = gs.elvis(gs.bool(gs.gp(gSobject.scope,"weightLogs")) , gs.gp(gSobject.scope,"weightLogs") , gs.list([])); var thisMonthKey = gs.mc(gs.mc(gSobject,"moment",[]),"format",["YYYY-MM"]); var lastMonthKey = gs.mc(gs.mc(gs.mc(gSobject,"moment",[]),"subtract",[1, "month"]),"format",["YYYY-MM"]); var thisMonthLog = gs.mc(gSobject,"latestEntryForMonth",[logs, thisMonthKey]); var lastMonthLog = gs.elvis(gs.mc(gSobject,"latestEntryForMonth",[logs, lastMonthKey]) , gs.mc(gSobject,"latestEntryForMonth",[logs, lastMonthKey]) , gs.mc(gSobject,"latestEntryBeforeMonth",[logs, thisMonthKey])); var thisMonthTimelineValue = gs.mc(gSobject,"extractBmiValue",[thisMonthLog]); var thisMonthValue = (thisMonthTimelineValue != null ? thisMonthTimelineValue : gs.gp(gSobject.scope,"bmi")); var lastMonthValue = gs.mc(gSobject,"extractBmiValue",[lastMonthLog]); if (gs.equals(lastMonthValue, null)) { var lastMonthWeightLog = gs.elvis(gs.mc(gSobject,"latestEntryForMonth",[weightLogs, lastMonthKey]) , gs.mc(gSobject,"latestEntryForMonth",[weightLogs, lastMonthKey]) , gs.mc(gSobject,"latestEntryBeforeMonth",[weightLogs, thisMonthKey])); var lastMonthWeight = gs.mc(gSobject,"extractWeightValue",[lastMonthWeightLog]); lastMonthValue = (lastMonthWeight != null ? gs.mc(gSobject,"bmiFromWeight",[lastMonthWeight]) : null); }; if (gs.equals(thisMonthValue, null)) { var thisMonthWeightLog = gs.mc(gSobject,"latestEntryForMonth",[weightLogs, thisMonthKey]); var thisMonthWeight = gs.mc(gSobject,"extractWeightValue",[thisMonthWeightLog]); thisMonthValue = (thisMonthWeight != null ? gs.mc(gSobject,"bmiFromWeight",[thisMonthWeight]) : null); }; gs.sp(gSobject.scope,"bmiMap",gs.list([gs.map().add("_id",0).add("label","Last month").add("barValue",gs.elvis(gs.bool(lastMonthValue) , lastMonthValue , 0)).add("displayBmi",(lastMonthValue != null ? gs.mc(lastMonthValue,"toFixed",[2]) : "N/A")) , gs.map().add("_id",1).add("label","This month").add("barValue",gs.elvis(gs.bool(thisMonthValue) , thisMonthValue , 0)).add("displayBmi",(thisMonthValue != null ? gs.mc(thisMonthValue,"toFixed",[2]) : "N/A"))])); gs.sp(gSobject.scope,"bmiChartLabels",gs.mc(gs.gp(gSobject.scope,"bmiMap"),"collect",[function(it) { return gs.gp(it,"label"); }])); gs.sp(gSobject.scope,"bmiChartValues",gs.mc(gs.gp(gSobject.scope,"bmiMap"),"collect",[function(it) { return gs.gp(it,"barValue"); }])); var values = gs.mc(gs.list([lastMonthValue , thisMonthValue]),"findAll",[function(it) { return it != null; }]); var top = (gs.bool(values) ? gs.mc(values,"max",[]) : 30); return gs.sp(gSobject.scope,"max",Math.max(30, Math.ceil(gs.plus(top, 2)))); } gSobject['updateWeightMap'] = function(it) { if (!gs.bool(gs.gp(gSobject.scope,"weightLogsLoaded"))) { return null; }; var logs = gs.elvis(gs.bool(gs.gp(gSobject.scope,"weightLogs")) , gs.gp(gSobject.scope,"weightLogs") , gs.list([])); var thisMonthKey = gs.mc(gs.mc(gSobject,"moment",[]),"format",["YYYY-MM"]); var lastMonthKey = gs.mc(gs.mc(gs.mc(gSobject,"moment",[]),"subtract",[1, "month"]),"format",["YYYY-MM"]); var thisMonthWeightLog = gs.mc(gSobject,"latestEntryForMonth",[logs, thisMonthKey]); var lastMonthWeightLog = gs.elvis(gs.mc(gSobject,"latestEntryForMonth",[logs, lastMonthKey]) , gs.mc(gSobject,"latestEntryForMonth",[logs, lastMonthKey]) , gs.mc(gSobject,"latestEntryBeforeMonth",[logs, thisMonthKey])); var thisMonthValue = gs.mc(gSobject,"extractWeightValue",[thisMonthWeightLog]); if ((gs.equals(thisMonthValue, null)) && (gs.gp(gSobject.scope,"currentWeight") != null)) { try { thisMonthValue = gs.mc(gs.gp(gSobject.scope,"currentWeight"),"doubleValue",[]); } catch (e) { } ; }; var lastMonthValue = gs.mc(gSobject,"extractWeightValue",[lastMonthWeightLog]); gs.sp(gSobject.scope,"weightMap",gs.list([gs.map().add("_id",0).add("label","Last month").add("barValue",gs.elvis(gs.bool(lastMonthValue) , lastMonthValue , 0)).add("displayWeight",(lastMonthValue != null ? gs.mc(lastMonthValue,"toFixed",[1]) : "N/A")) , gs.map().add("_id",1).add("label","This month").add("barValue",gs.elvis(gs.bool(thisMonthValue) , thisMonthValue , 0)).add("displayWeight",(thisMonthValue != null ? gs.mc(thisMonthValue,"toFixed",[1]) : "N/A"))])); gs.sp(gSobject.scope,"weightChartLabels",gs.mc(gs.gp(gSobject.scope,"weightMap"),"collect",[function(it) { return gs.gp(it,"label"); }])); gs.sp(gSobject.scope,"weightChartValues",gs.mc(gs.gp(gSobject.scope,"weightMap"),"collect",[function(it) { return gs.gp(it,"barValue"); }])); if (thisMonthValue != null) { gs.sp(gSobject.scope,"currentWeight",thisMonthValue); if (!gs.bool(gs.gp(gSobject.scope,"weightCategory"))) { return gs.sp(gSobject.scope,"weightCategory","Tracked"); }; }; } gSobject['loadBodyFatHistory'] = function(it) { return gs.mc(gs.gp(gs.mc(gs.fs('o', this, gSobject),"localAndRemote",[]),"protoDataPointTimelineService"),"listEntries",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:body_fat", gs.map().add("limit",120), function(logs) { gs.sp(gSobject.scope,"bodyFatLogs",gs.elvis(gs.bool(logs) , logs , gs.list([]))); return gs.mc(gSobject,"updateBodyFatMap",[]); }]); } gSobject['updateBodyFatMap'] = function(it) { var logs = gs.elvis(gs.bool(gs.gp(gSobject.scope,"bodyFatLogs")) , gs.gp(gSobject.scope,"bodyFatLogs") , gs.list([])); var thisMonthKey = gs.mc(gs.mc(gSobject,"moment",[]),"format",["YYYY-MM"]); var lastMonthKey = gs.mc(gs.mc(gs.mc(gSobject,"moment",[]),"subtract",[1, "month"]),"format",["YYYY-MM"]); var thisMonthLog = gs.mc(gSobject,"latestEntryForMonth",[logs, thisMonthKey]); var lastMonthLog = gs.elvis(gs.mc(gSobject,"latestEntryForMonth",[logs, lastMonthKey]) , gs.mc(gSobject,"latestEntryForMonth",[logs, lastMonthKey]) , gs.mc(gSobject,"latestEntryBeforeMonth",[logs, thisMonthKey])); var thisMonthValue = gs.mc(gSobject,"extractBodyFatValue",[thisMonthLog]); if ((gs.equals(thisMonthValue, null)) && (gs.gp(gSobject.scope,"currentBodyFat") != null)) { try { thisMonthValue = gs.mc(gs.gp(gSobject.scope,"currentBodyFat"),"doubleValue",[]); } catch (e) { } ; }; var lastMonthValue = gs.mc(gSobject,"extractBodyFatValue",[lastMonthLog]); gs.sp(gSobject.scope,"bodyFatMap",gs.list([gs.map().add("_id",0).add("label","Last month").add("barValue",gs.elvis(gs.bool(lastMonthValue) , lastMonthValue , 0)).add("displayBodyFat",(lastMonthValue != null ? gs.plus(gs.mc(lastMonthValue,"toFixed",[1]), "%") : "N/A")) , gs.map().add("_id",1).add("label","This month").add("barValue",gs.elvis(gs.bool(thisMonthValue) , thisMonthValue , 0)).add("displayBodyFat",(thisMonthValue != null ? gs.plus(gs.mc(thisMonthValue,"toFixed",[1]), "%") : "N/A"))])); gs.sp(gSobject.scope,"bodyFatChartLabels",gs.mc(gs.gp(gSobject.scope,"bodyFatMap"),"collect",[function(it) { return gs.gp(it,"label"); }])); gs.sp(gSobject.scope,"bodyFatChartValues",gs.mc(gs.gp(gSobject.scope,"bodyFatMap"),"collect",[function(it) { return gs.gp(it,"barValue"); }])); if (thisMonthValue != null) { return gs.sp(gSobject.scope,"currentBodyFat",thisMonthValue); }; } gSobject['loadRxmeUser'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"loadRxmeUser",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(rxmeUser) { gs.sp(gSobject.scope,"rxmeUser",rxmeUser); return gs.mc(gSobject,"calculateBmr",[]); }]); } gSobject['calculateBmr'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"medicalCalculationService"),"calculateBMR",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(bmr) { return gs.sp(gSobject.scope,"bmr",bmr); }]); } gSobject['popup'] = function(title, message) { if (title === undefined) title = "Title"; if (message === undefined) message = "Info message"; return gs.mc(gSobject.q,"dialog",[gs.map().add("title",title).add("message",message)]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function WeightTrackComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'WeightTrackComponent', simpleName: 'WeightTrackComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/weightTrack/:type" , "/weightTrack/:type/:id"]); gSobject.metric = null; gSobject['created'] = function(it) { gs.sp(gSobject.scope,"dialog",false); gs.sp(gSobject.scope,"date",gs.mc(gs.mc(gSobject,"moment",[]),"format",["YYYY-MM-DD HH:mm"])); gs.sp(gSobject.scope,"today",gs.mc(gs.mc(gSobject,"moment",[]),"format",["YYYY-MM-DD"])); gs.sp(gSobject.scope,"allowedDates",function(d) { return gs.mc(gs.mc(gSobject,"moment",[d, "YYYY/MM/DD"]),"isSameOrBefore",[gs.mc(gSobject,"moment",[gs.gp(gSobject.scope,"today"), "YYYY/MM/DD"])]); }); gs.sp(gSobject.scope,"showDateTime",false); if (gs.equals(gs.gp(gs.gp(gSobject.route,"params"),"type"), "weight")) { gSobject.metric = "body_weight"; gs.sp(gSobject.scope,"min",30); gs.sp(gSobject.scope,"max",600); gs.sp(gSobject.scope,"metric",gs.map().add("value",70.1).add("unit","kg")); gs.sp(gSobject.scope,"isWeight",true); }; if (gs.equals(gs.gp(gs.gp(gSobject.route,"params"),"type"), "bodyFat")) { gSobject.metric = "body_fat"; gs.sp(gSobject.scope,"min",0); gs.sp(gSobject.scope,"max",40); gs.sp(gSobject.scope,"metric",gs.map().add("value",25).add("unit","%")); gs.sp(gSobject.scope,"isWeight",false); }; if (gs.bool(gs.gp(gs.gp(gSobject.route,"params"),"id"))) { gs.sp(gs.gp(gSobject.scope,"metric"),"value",null); gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"loadEntry",[gs.gp(gs.gp(gSobject.route,"params"),"id"), function(entry) { gs.sp(gs.gp(gSobject.scope,"metric"),"value",gs.gp(entry,"value")); return gs.sp(gSobject.scope,"date",gs.mc(gs.mc(gSobject,"moment",[gs.gp(entry,"date")]),"format",["YYYY-MM-DD HH:mm"])); }]); }; gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.weight.track"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[false]); return gs.mc(gSobject,"componentTheme",[false]); } gSobject['statusString'] = function(value) { return "Within normal range"; } gSobject['save'] = function(it) { var value = gs.div(Math.round(gs.multiply(gs.gp(gs.gp(gSobject.scope,"metric"),"value"), 10)), 10.0); gs.println("VALUE: " + (value) + ""); var status = gs.mc(gSobject,"statusString",[value]); var today = gs.mc(gs.mc(gSobject,"moment",[]),"format",["YYYY-MM-DD"]); var nowMinute = gs.mc(gs.mc(gSobject,"moment",[]),"format",["YYYY-MM-DD HH:mm"]); var pickerMinute = gs.mc(gs.mc(gSobject,"moment",[gs.gp(gSobject.scope,"date")]),"format",["YYYY-MM-DD HH:mm"]); var date = (gs.equals(pickerMinute, nowMinute) ? gs.date() : gs.date(gs.gp(gSobject.scope,"date"))); if (gs.equals(gs.mc(gs.mc(gSobject,"moment",[date]),"format",["YYYY-MM-DD"]), today)) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:" + (gSobject.metric) + ":value", value]),"do",[]); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:" + (gSobject.metric) + ":status", status]),"do",[]); }; if (gs.bool(gs.gp(gs.gp(gSobject.route,"params"),"id"))) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"deleteEntry",[gs.gp(gs.gp(gSobject.route,"params"),"id")]),"do",[]); }; gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"addEntryWithFts",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:" + (gSobject.metric) + "", gs.list(["value"]), gs.map().add("value",value).add("date",date)]),"then",[function(it) { if (gs.equals(gSobject.metric, "body_weight")) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"medicalConditionCalculationService"),"calcAll",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(it) { return gs.println("[BMI_DEBUG] calcAll completed after body_weight save"); }]); }; gs.mc(gSobject,"saveLastUpdated",[gs.gp(gs.fs('session', this, gSobject),"userId"), "weight"]); return gs.sp(gSobject.scope,"dialog",true); }, function(error) { return gs.sp(gSobject.scope,"dialog",true); }]); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"notificationService"),"removeNotification",[gs.gp(gs.fs('session', this, gSobject),"userId"), "trackable:Weight", "Weight"]),"do",[]); return gs.mc(gSobject,"generateAndSaveMotivation",[gs.gp(gs.fs('session', this, gSobject),"userId"), "Weight", "medical:score:${metric}:value"]); } gSobject['eventLogWeight'] = function(it) { var narrative = "Logged weight: " + (gs.gp(gs.gp(gSobject.scope,"metric"),"value")) + " kg"; return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"eventLogService"),"event",[gs.gp(gs.fs('session', this, gSobject),"userId"), narrative, "weight", "info"]),"do",[]); } gSobject['popup'] = function(title, message) { if (title === undefined) title = "Title"; if (message === undefined) message = "Info message"; return gs.mc(gSobject.q,"dialog",[gs.map().add("title",title).add("message",message)]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function WeightReminderComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'WeightReminderComponent', simpleName: 'WeightReminderComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/weightReminder" , "/weightReminder/:id"]); gSobject['created'] = function(it) { gs.sp(gSobject.scope,"time",gs.mc(gSobject,"moment",[])); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.weight.reminder"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[false]); return gs.mc(gSobject,"componentTheme",[false]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function WeightGoalDirectionComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'WeightGoalDirectionComponent', simpleName: 'WeightGoalDirectionComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/weightGoalDirection"; gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "weight.goal.direction"]),"do",[]); gs.sp(gSobject.scope,"weightGoal",gs.map().add("reason",null)); gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"weightGoal",gs.map().add("reason",null)); gs.mc(gSobject,"showHeaderFooter",[false]); return gs.mc(gSobject,"componentTheme",[false]); } gSobject['assignDirection'] = function(reason) { gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"weightGoal",gs.map().add("reason",reason)); gs.sp(gSobject.scope,"weightGoal",gs.map().add("reason",reason)); return gs.println(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"weightGoal")); } gSobject['saveDirection'] = function(reason) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["weightGoalPreview"]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function WeightGoalPreviewComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'WeightGoalPreviewComponent', simpleName: 'WeightGoalPreviewComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/weightGoalPreview" , "/weightGoalPreview/:id"]); gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "weight.goal.preview"]),"do",[]); gs.sp(gSobject.scope,"weightGoal",gs.map().add("weight","").add("goalDate","No Date")); gs.mc(gSobject,"showHeaderFooter",[false]); gs.mc(gSobject,"componentTheme",[false]); return gs.mc(gSobject,"loadGoal",[]); } gSobject['loadGoal'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:body_weight_goal", function(weightGoal) { if (gs.bool(weightGoal)) { gs.sp(gs.gp(gSobject.scope,"weightGoal"),"weight",gs.gp(weightGoal,"weight")); if (gs.bool(gs.gp(weightGoal,"date"))) { gs.sp(gs.gp(gSobject.scope,"weightGoal"),"goalDate",gs.mc(gs.mc(gSobject,"moment",[gs.gp(weightGoal,"date")]),"format",["DD MMMM YYYY"])); }; gs.println("WEIGHT GOAL"); return gs.println(weightGoal); }; }]); } gSobject['gotoGoal'] = function(reason) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["weightGoalTrack"]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function WeightGoalDeadlineComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'WeightGoalDeadlineComponent', simpleName: 'WeightGoalDeadlineComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/weightGoalDeadline"; gSobject['created'] = function(it) { gs.sp(gSobject.scope,"date",null); gs.sp(gSobject.scope,"dialog",false); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "weight.goal.deadline"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[false]); return gs.mc(gSobject,"componentTheme",[false]); } gSobject['fetchDateDiff'] = function(it) { if (!gs.bool(gs.gp(gSobject.scope,"date"))) { return "No deadline set"; }; var diff = gs.mc(gs.mc(gs.mc(gSobject,"moment",[gs.gp(gSobject.scope,"date")]),"startOf",["day"]),"diff",[gs.mc(gs.mc(gSobject,"moment",[]),"startOf",["day"]), "days"]); if (gs.equals(diff, 0)) { return "Your deadline is today"; }; if (diff < 1) { return "Your deadline was " + (gs.multiply(diff, -1)) + " days ago"; }; return "Your deadline is " + (diff) + " days from now"; } gSobject['save'] = function(it) { gs.sp(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"weightGoal"),"date",gs.gp(gSobject.scope,"date")); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:body_weight_goal", gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"weightGoal"), function(it) { gs.mc(gSobject,"eventLogGoal",[]); return gs.sp(gSobject.scope,"dialog",true); }]); } gSobject['eventLogGoal'] = function(it) { var goalReason = (gs.equals(gs.gp(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"weightGoal"),"reason"), "weight_los") ? "Lose Weight" : "Gain Weight"); var evtNarrative = "Logged weight goal: " + (gs.gp(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"weightGoal"),"weight")) + "kg (" + (goalReason) + ")"; return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"eventLogService"),"event",[gs.gp(gs.fs('session', this, gSobject),"userId"), evtNarrative, "weight:goal", "info"]),"do",[]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function WeightGoalTrackComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'WeightGoalTrackComponent', simpleName: 'WeightGoalTrackComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/weightGoalTrack"; gSobject['created'] = function(it) { gs.sp(gSobject.scope,"weight",85); gs.sp(gSobject.scope,"date",gs.date()); gs.sp(gSobject.scope,"goal",gs.map().add("value",70.0).add("unit","kg")); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "weight.goal.track"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[false]); return gs.mc(gSobject,"componentTheme",[false]); } gSobject['save'] = function(it) { if (!gs.bool(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"weightGoal"))) { gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"weightGoal",gs.map()); }; gs.sp(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"weightGoal"),"weight",gs.gp(gSobject.scope,"weight")); return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["weightGoalDeadline"]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function WeightGoalAchievedComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'WeightGoalAchievedComponent', simpleName: 'WeightGoalAchievedComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/weightGoalAchieved" , "/weightGoalAchieved/:id"]); gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "weight.goal.achieved"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[false]); return gs.mc(gSobject,"componentTheme",[false]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function WeightPhotoComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'WeightPhotoComponent', simpleName: 'WeightPhotoComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/weightPhotoUpload"]); gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "weight.photo.upload"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[false]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"activeTab","upload"); gs.sp(gSobject.scope,"frontImage",gs.map()); gs.sp(gSobject.scope,"backImage",gs.map()); gs.sp(gSobject.scope,"sideImage1",gs.map()); gs.sp(gSobject.scope,"sideImage2",gs.map()); gs.sp(gSobject.scope,"imageList",gs.list([gs.gp(gSobject.scope,"frontImage") , gs.gp(gSobject.scope,"backImage") , gs.gp(gSobject.scope,"sideImage1") , gs.gp(gSobject.scope,"sideImage2")])); gs.sp(gSobject.scope,"startedList",gs.list([])); gs.sp(gSobject.scope,"uploadedList",gs.list([])); gs.sp(gSobject.scope,"rxmeUser",gs.map()); gs.sp(gSobject.scope,"photoSessions",gs.list([])); gs.sp(gSobject.scope,"historyLoading",false); gs.sp(gSobject.scope,"isDisableSubmit",true); gs.mc(gSobject,"prepareImages",[]); gs.mc(gSobject,"loadRxmeUser",[]); return gs.mc(gSobject,"loadPhotoHistory",[]); } gSobject['loadRxmeUser'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"loadRxmeUser",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(rxmeUser) { return gs.sp(gSobject.scope,"rxmeUser",rxmeUser); }]); } gSobject['disableSubmit'] = function(it) { if (gs.bool(gs.gp(gSobject.scope,"startedList"))) { gs.println("startedList"); gs.sp(gSobject.scope,"isDisableSubmit",true); return null; }; if (gs.bool(gs.gp(gSobject.scope,"uploadedList"))) { gs.println("startedList"); gs.sp(gSobject.scope,"isDisableSubmit",false); return null; }; gs.println("default"); return gs.sp(gSobject.scope,"isDisableSubmit",true); } gSobject['removeUploaded'] = function(object) { gs.println("removeUploaded:"); gs.println(object); gs.mc(gs.gp(gSobject.scope,"uploadedList"),"remove",[gs.gp(object,"_id")]); return gs.mc(gSobject,"disableSubmit",[]); } gSobject['photoUploaded'] = function(object) { gs.println("photoUploaded:"); gs.println(object); gs.mc(gs.gp(gSobject.scope,"startedList"),"remove",[gs.gp(object,"_id")]); gs.mc(gs.gp(gSobject.scope,"uploadedList"),"add",[gs.gp(object,"_id")]); return gs.mc(gSobject,"disableSubmit",[]); } gSobject['initUploaded'] = function(object) { gs.println("initUploaded:"); gs.println(object); gs.mc(gs.gp(gSobject.scope,"startedList"),"add",[gs.gp(object,"_id")]); return gs.mc(gSobject,"disableSubmit",[]); } gSobject['prepareImages'] = function(it) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataFile"),"findOrCreate",[gs.map().add("_id",null), function(fileObj) { return gs.sp(gSobject.scope,"frontImage",fileObj); }]); gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataFile"),"findOrCreate",[gs.map().add("_id",null), function(fileObj) { return gs.sp(gSobject.scope,"backImage",fileObj); }]); gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataFile"),"findOrCreate",[gs.map().add("_id",null), function(fileObj) { return gs.sp(gSobject.scope,"sideImage1",fileObj); }]); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataFile"),"findOrCreate",[gs.map().add("_id",null), function(fileObj) { return gs.sp(gSobject.scope,"sideImage2",fileObj); }]); } gSobject['savePhotoEntry'] = function(user) { var date = gs.date(); var today = gs.mc(gs.mc(gSobject,"moment",[date]),"format",["YYYY-MM-DD"]); gs.println(">>> savePhotoEntry called"); gs.println(">>> User: " + (user) + ""); var frontImage = (gs.bool(gs.gp(gs.gp(gSobject.scope,"frontImage"),"file",true)) ? gs.gp(gs.gp(gSobject.scope,"frontImage"),"_id") : null); var backImage = (gs.bool(gs.gp(gs.gp(gSobject.scope,"backImage"),"file",true)) ? gs.gp(gs.gp(gSobject.scope,"backImage"),"_id") : null); var side1Image = (gs.bool(gs.gp(gs.gp(gSobject.scope,"sideImage1"),"file",true)) ? gs.gp(gs.gp(gSobject.scope,"sideImage1"),"_id") : null); var side2Image = (gs.bool(gs.gp(gs.gp(gSobject.scope,"sideImage2"),"file",true)) ? gs.gp(gs.gp(gSobject.scope,"sideImage2"),"_id") : null); var imageIds = gs.mc(gs.list([frontImage , backImage , side1Image , side2Image]),"findAll",[function(it) { return it != null; }]); if (gs.mc(imageIds,"size",[]) > 0) { return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"addEntryWithFts",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:weight_photo", gs.list(["imageIds"]), gs.map().add("imageIds",imageIds).add("date",date)]),"then",[function(it) { gs.println(">>> Photo entry saved successfully."); gs.mc(gSobject,"notify",["Your weight progress photos were saved successfully."]); gs.mc(gSobject,"prepareImages",[]); return gs.mc(gSobject,"loadPhotoHistory",[true]); }, function(error) { gs.println(">>> Error saving photo entry"); gs.println(error); return gs.mc(gSobject.q,"dialog",[gs.map().add("title","Error").add("message","Something went wrong while saving your photos.")]); }]); } else { return gs.mc(gSobject.q,"dialog",[gs.map().add("title","No Photos").add("message","Please upload at least one photo before submitting.")]); }; } gSobject['loadPhotoHistory'] = function(switchToHistory) { gs.sp(gSobject.scope,"historyLoading",true); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"listEntries",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:weight_photo", gs.map().add("limit",50), function(logs) { if ((!gs.bool(logs)) || (gs.equals(gs.mc(logs,"size",[]), 0))) { gs.sp(gSobject.scope,"photoSessions",gs.list([])); gs.sp(gSobject.scope,"historyLoading",false); if (gs.bool(switchToHistory)) { gs.sp(gSobject.scope,"activeTab","history"); }; return null; }; var sessions = gs.list([]); var imageLoads = gs.list([]); gs.mc(logs,"each",[function(log) { var photoSession = gs.map().add("_id",gs.gp(log,"_id")).add("date",gs.gp(log,"date")).add("formattedDate",gs.mc(gs.mc(gSobject,"moment",[gs.gp(log,"date")]),"format",["DD MMM YYYY"])).add("formattedTime",gs.mc(gs.mc(gSobject,"moment",[gs.gp(log,"date")]),"format",["hh:mm A"])).add("images",gs.list([])); gs.mc(sessions,'leftShift', gs.list([photoSession])); if (gs.bool(gs.gp(log,"imageIds"))) { return gs.mc(gs.gp(log,"imageIds"),"each",[function(imgId) { if (gs.bool(imgId)) { return gs.mc(imageLoads,'leftShift', gs.list([gs.map().add("photoSession",photoSession).add("imgId",imgId)])); }; }]); }; }]); if (gs.equals(gs.mc(imageLoads,"size",[]), 0)) { gs.sp(gSobject.scope,"photoSessions",sessions); gs.sp(gSobject.scope,"historyLoading",false); if (gs.bool(switchToHistory)) { gs.sp(gSobject.scope,"activeTab","history"); }; return null; }; var progress = gs.map().add("done",0); var total = gs.mc(imageLoads,"size",[]); return gs.mc(imageLoads,"each",[function(item) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataFile"),"findOne",[gs.map().add("_id",gs.gp(item,"imgId")), function(fileObj) { if (gs.bool(gs.gp(fileObj,"file",true))) { gs.mc(gs.gp(gs.gp(item,"photoSession"),"images"),'leftShift', gs.list([fileObj])); }; gs.sp(progress,"done",(gs.plus(gs.gp(progress,"done"), 1))); if (gs.gp(progress,"done") >= total) { gs.sp(gSobject.scope,"photoSessions",sessions); gs.sp(gSobject.scope,"historyLoading",false); if (gs.bool(switchToHistory)) { return gs.sp(gSobject.scope,"activeTab","history"); }; }; }]); }]); }]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function PrivacyPolicyComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'PrivacyPolicyComponent', simpleName: 'PrivacyPolicyComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/privacy-policy"; gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "user.privacy.policy"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[false]); gs.mc(gSobject,"componentTheme",[false]); return gs.sp(gSobject.scope,"appVersion",gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"appVersion")); } gSobject['decline'] = function(it) { return gs.execStatic(Utils,'logout', this,["/"]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function ConsentComponent() { var gSobject = VueComponent(); gSobject.clazz = { name: 'ConsentComponent', simpleName: 'ConsentComponent'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.path = "/consent"; gSobject['created'] = function(it) { gs.println("ConsentComponent.created()"); gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"showFooter",false); gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"showHeader",false); gs.sp(gSobject.scope,"agreements",gs.list([])); gs.sp(gSobject.scope,"active",gs.map()); gs.sp(gSobject.scope,"isSubmitting",false); return gs.mc(gSobject,"loadAgreements",[]); } gSobject['loadAgreements'] = function(it) { gs.mc(gSobject,"showLoading",[]); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"consentService"),"unconsentedAgreements",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(data) { gs.mc(gSobject,"hideLoading",[]); if (!gs.bool(data)) { gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"agreementsChecked",true); return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/home"]); }; gs.sp(gSobject.scope,"agreements",data); return gs.sp(gSobject.scope,"active",(gs.gp(gSobject.scope,"agreements")[0])); }]); } gSobject['onSubmit'] = function(it) { gs.sp(gSobject.scope,"isSubmitting",true); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"consentService"),"consentToAgreement",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gs.gp(gSobject.scope,"active"),"_id"), function(it) { gs.sp(gSobject.scope,"isSubmitting",false); gs.mc(gs.gp(gSobject.scope,"agreements"),"remove",[0]); if (gs.equals(gs.gp(gs.gp(gSobject.scope,"agreements"),"length"), 0)) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/home"]); }; return gs.sp(gSobject.scope,"active",(gs.gp(gSobject.scope,"agreements")[0])); }]); } gSobject['logout'] = function(it) { return gs.execStatic(Utils,'logout', this,["/"]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function CordovaSimBridgeAuth() { var gSobject = gs.init('CordovaSimBridgeAuth'); gSobject.clazz = { name: 'CordovaSimBridgeAuth', simpleName: 'CordovaSimBridgeAuth'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.active = false; gSobject.pendingCallbacks = gs.map(); gSobject.shouldActivate = function() { return CordovaSimBridgeAuth.shouldActivate(); } gSobject['activate'] = function(it) { gSobject.active = true; gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["CordovaSimBridgeAuth: ACTIVE — adding auth, health, and media stubs"]); gs.mc(gSobject,"patchUserAgent",[]); gs.mc(gSobject,"addPluginStubs",[]); gs.mc(gSobject,"listenForMessages",[]); return gs.mc(gSobject,"patchUtilsIsCordova",[]); } gSobject.patchUserAgent = function() { // Append 'cordova.simulator' to the user agent so Utils.isCordova() returns true. // Utils.isCordova() checks: userAgent().contains('cordova') try { var originalUA = navigator.userAgent; Object.defineProperty(navigator, 'userAgent', { get: function() { return originalUA + ' cordova.simulator.1.0.0'; }, configurable: true }); console.log('[SimBridgeAuth] User agent patched — appended cordova.simulator.1.0.0'); } catch(e) { console.warn('[SimBridgeAuth] Could not patch userAgent:', e); } } gSobject.addPluginStubs = function() { var bridge = this; // ===================== APPLE SIGN-IN ===================== window.cordova.plugins.SignInWithApple = { signin: function(options, success, error) { bridge._storePending('appleSignIn', 'signin', success, error); console.log('[SimBridgeAuth] Apple Sign-In: waiting for simulated auth...'); window.parent.postMessage({type:'cordova-sim-ready', plugin:'appleSignIn', action:'signin'}, '*'); } }; // ===================== GOOGLE SIGN-IN ===================== window.cordova.plugins.GoogleSignInPlugin = { signIn: function(success, error) { bridge._storePending('googleSignIn', 'signIn', success, error); console.log('[SimBridgeAuth] Google Sign-In: waiting for simulated auth...'); window.parent.postMessage({type:'cordova-sim-ready', plugin:'googleSignIn', action:'signIn'}, '*'); }, isSignedIn: function(success, error) { if (success) success({isSignedIn: false}); }, signOut: function(success, error) { console.log('[SimBridgeAuth] Google Sign-Out'); if (success) success(); }, oneTapLogin: function(success, error) { bridge._storePending('googleSignIn', 'oneTap', success, error); console.log('[SimBridgeAuth] Google One-Tap: waiting...'); window.parent.postMessage({type:'cordova-sim-ready', plugin:'googleSignIn', action:'oneTap'}, '*'); }, }; // ===================== HEALTH ===================== window.cordova.plugins.health = { isAvailable: function(success, error) { console.log('[SimBridgeAuth] Health: isAvailable -> true'); if (success) success(true); }, requestAuthorization: function(datatypes, success, error) { console.log('[SimBridgeAuth] Health: requestAuthorization granted'); if (success) success(true); }, isAuthorized: function(datatypes, success, error) { if (success) success(true); }, query: function(params, success, error) { bridge._storePending('health', 'query', success, error); console.log('[SimBridgeAuth] Health query:', params.dataType, '— waiting for simulated data...'); window.parent.postMessage({type:'cordova-sim-ready', plugin:'health', action:'query', data:params}, '*'); }, queryAggregated: function(params, success, error) { bridge._storePending('health', 'queryAggregated', success, error); console.log('[SimBridgeAuth] Health queryAggregated:', params.dataType, '— waiting...'); window.parent.postMessage({type:'cordova-sim-ready', plugin:'health', action:'queryAggregated', data:params}, '*'); }, store: function(data, success, error) { console.log('[SimBridgeAuth] Health store:', data); if (success) success(); }, }; // ===================== MEDIA CAPTURE ===================== window.navigator.device = window.navigator.device || {}; window.navigator.device.capture = { captureImage: function(success, error, options) { bridge._storePending('media', 'captureImage', success, error); console.log('[SimBridgeAuth] Media captureImage: waiting...'); window.parent.postMessage({type:'cordova-sim-ready', plugin:'media', action:'captureImage'}, '*'); }, captureAudio: function(success, error, options) { bridge._storePending('media', 'captureAudio', success, error); console.log('[SimBridgeAuth] Media captureAudio: waiting...'); window.parent.postMessage({type:'cordova-sim-ready', plugin:'media', action:'captureAudio'}, '*'); }, captureVideo: function(success, error, options) { bridge._storePending('media', 'captureVideo', success, error); console.log('[SimBridgeAuth] Media captureVideo: waiting...'); window.parent.postMessage({type:'cordova-sim-ready', plugin:'media', action:'captureVideo'}, '*'); }, }; console.log('[SimBridgeAuth] Plugin stubs registered: SignInWithApple, GoogleSignInPlugin, health, media capture'); } gSobject.listenForMessages = function() { var bridge = this; window.addEventListener('message', function(event) { var msg = event.data; if (!msg || msg.type !== 'cordova-sim') return; switch (msg.plugin) { case 'appleSignIn': if (msg.action === 'success') bridge._firePending('appleSignIn', 'signin', msg.data); if (msg.action === 'fail') bridge._firePendingError('appleSignIn', 'signin', msg.data || 'User cancelled'); break; case 'googleSignIn': if (msg.action === 'success') bridge._firePending('googleSignIn', 'signIn', msg.data); if (msg.action === 'oneTapSuccess') bridge._firePending('googleSignIn', 'oneTap', msg.data); if (msg.action === 'fail') bridge._firePendingError('googleSignIn', 'signIn', msg.data || 'Sign in cancelled'); break; case 'health': if (msg.action === 'queryResult') bridge._firePending('health', 'query', msg.data); if (msg.action === 'queryAggregatedResult') bridge._firePending('health', 'queryAggregated', msg.data); break; case 'media': if (msg.action === 'capturedImage') bridge._firePending('media', 'captureImage', msg.data); if (msg.action === 'capturedAudio') bridge._firePending('media', 'captureAudio', msg.data); if (msg.action === 'capturedVideo') bridge._firePending('media', 'captureVideo', msg.data); break; case 'console': if (msg.action === 'eval') { try { var result = eval(msg.data.code); window.parent.postMessage({type:'cordova-sim-event', plugin:'console', action:'result', data:{code: msg.data.code, result: JSON.stringify(result)}}, '*'); } catch(e) { window.parent.postMessage({type:'cordova-sim-event', plugin:'console', action:'error', data:{code: msg.data.code, error: e.message}}, '*'); } } break; } }); console.log('[SimBridgeAuth] postMessage listener registered for auth/health/media'); } gSobject.patchUtilsIsCordova = function() { // Utils is loaded later by GrooScript. Poll until it exists, then patch. var attempts = 0; var patcher = setInterval(function() { attempts++; if (typeof Utils !== 'undefined' && Utils.isCordova) { Utils.isCordova = function() { return true; }; Utils.cordovaDevice = function() { return true; }; console.log('[SimBridgeAuth] Utils.isCordova patched to return true'); clearInterval(patcher); } if (attempts > 100) clearInterval(patcher); // stop after ~10s }, 100); } gSobject._storePending = function(plugin, action, success, error) { var key = plugin + ':' + action; this.pendingCallbacks[key] = { success: success, error: error }; } gSobject._firePending = function(plugin, action, data) { var key = plugin + ':' + action; var pending = this.pendingCallbacks[key]; if (pending && pending.success) { pending.success(data); delete this.pendingCallbacks[key]; } } gSobject._firePendingError = function(plugin, action, data) { var key = plugin + ':' + action; var pending = this.pendingCallbacks[key]; if (pending && pending.error) { pending.error(data); delete this.pendingCallbacks[key]; } } gSobject['CordovaSimBridgeAuth0'] = function(it) { if (CordovaSimBridgeAuth.shouldActivate()) { gs.mc(gSobject,"activate",[]); }; return this; } if (arguments.length==0) {gSobject.CordovaSimBridgeAuth0(); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; CordovaSimBridgeAuth.shouldActivate = function() { // Only activate if CordovaSimBridge already created the fake cordova object // i.e. we're in an iframe and window.cordova exists but is our fake one return (window.parent !== window) && (typeof window.cordova !== 'undefined') && (typeof window.device !== 'undefined' && window.device.platform === 'Simulator'); } function LinkAccountComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'LinkAccountComponent', simpleName: 'LinkAccountComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/linkAccount"; gSobject['created'] = function(it) { gs.println("LinkAccountComponent.created()"); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "account.link.page"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); gs.sp(gSobject.scope,"email",""); gs.sp(gSobject.scope,"password",""); gs.sp(gSobject.scope,"showPassword",false); gs.sp(gSobject.scope,"showPasswordToggle",false); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"portalAuth",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(result) { if (gs.bool(gs.gp(result,"token"))) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"linkAccountFlow",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(it) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/"]); }]); }; }]); } gSobject['linkAccount'] = function(it) { if ((!gs.bool(gs.gp(gSobject.scope,"email"))) && (!gs.bool(gs.gp(gSobject.scope,"password")))) { return gs.mc(gSobject,"notify",["Please enter details", "negative"]); }; return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeApiService"),"authToken",[gs.gp(gSobject.scope,"email"), gs.gp(gSobject.scope,"password"), function(token) { if (!gs.bool(token)) { gs.mc(gSobject,"notify",["An Error Occurred", "negative"]); }; return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"moveStatusAfterLinkAccount",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(it) { gs.mc(gSobject,"notify",["Account Linked"]); return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/"]); }]); }]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function I3Chart() { var gSobject = VueComponent(); gSobject.clazz = { name: 'I3Chart', simpleName: 'I3Chart'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.props = gs.map().add("labels",Array).add("values",Array).add("data",Array).add("datasets",Array).add("id",String).add("type",String).add("title",String).add("legend",Boolean).add("borderWidth",Number).add("borderRadius",Number).add("borderColor",String).add("backgroundColor",String).add("color",String).add("tension",Number).add("filled",Boolean).add("horizontal",Boolean).add("xHide",Boolean).add("xStacked",Boolean).add("xGridHide",Boolean).add("yHide",Boolean).add("yStacked",Boolean).add("yGridHide",Boolean).add("rHide",Boolean).add("rGridHide",Boolean).add("yScaleLabel",String).add("yScalePos",String).add("min",Number).add("max",Number).add("yScaleType",String).add("pointStyle",String).add("pointRadius",Number).add("dashedLine",Array).add("stepped",Boolean).add("alternate",Boolean).add("transparent",Boolean); gSobject.colors = gs.list(["#37a2eb" , "#ff6383" , "#4ac1c0" , "#fca048" , "#9966ff" , "#ffce56" , "#c9cbcf"]); gSobject.data = function(it) { return gs.list([]); }; gSobject['created'] = function(it) { var self = this; return gs.mc(gSobject,"init",[self]); } gSobject['init'] = function(self) { if (self === undefined) self = this; return gs.mc(gSobject,"loadChart",[self, true]); } gSobject['loadChart'] = function(self, newChart) { if (self === undefined) self = this; if (newChart === undefined) newChart = false; var labels = gs.list([]); gs.mc(gs.range(0, 4, true),"each",[function(it) { return gs.mc(labels,"add",[it]); }]); var options = gs.map().add("responsive",true).add("animation",true).add("indexAxis",(gs.bool(gs.gp(self,"horizontal")) ? "y" : "x")).add("plugins",gs.toJavascript(gs.mc(gSobject,"plugins",[self]))).add("scales",gs.toJavascript(gs.mc(gSobject,"scales",[self]))); var data = gs.map(); gs.sp(data,"labels",(gs.bool(gs.gp(self,"labels")) ? gs.toJavascript(gs.gp(self,"labels")) : gs.toJavascript(labels))); gs.sp(data,"datasets",gs.toJavascript(gs.mc(gSobject,"datasets",[self]))); return gs.mc(gSobject,"nextTick",[function(it) { if (gs.bool(newChart)) { return gs.execStatic(I3Chart,'paintChart', this,[gs.gp(self,"id"), data, options, gs.gp(self,"type")]); } else { return gs.execStatic(I3Chart,'updateData', this,[gs.gp(self,"id"), gs.gp(self,"labels"), gs.gp(self,"values")]); }; }]); } gSobject['dataset'] = function(self, data, index) { if (self === undefined) self = this; if (index === undefined) index = 0; var dataset = gs.map(); gs.sp(dataset,"label",gs.elvis(gs.bool(gs.gp(self,"label")) , gs.gp(self,"label") , "")); gs.sp(dataset,"data",data); gs.sp(dataset,"borderWidth",gs.elvis(gs.bool(gs.gp(self,"borderWidth")) , gs.gp(self,"borderWidth") , 1)); gs.sp(dataset,"borderRadius",gs.elvis(gs.bool(gs.gp(self,"borderRadius")) , gs.gp(self,"borderRadius") , 0)); gs.sp(dataset,"borderSkipped",false); if (gs.bool(gs.gp(self,"data"))) { gs.sp(dataset,"borderColor",gs.elvis(gs.bool(gs.gp(self,"borderColor")) , gs.gp(self,"borderColor") , gs.elvis(gs.bool(gs.gp(self,"color")) , gs.gp(self,"color") , gSobject.colors))); gs.sp(dataset,"pointBackgroundColor",gs.elvis(gs.bool(gs.gp(self,"borderColor")) , gs.gp(self,"borderColor") , gs.elvis(gs.bool(gs.gp(self,"color")) , gs.gp(self,"color") , gSobject.colors))); var color = gs.elvis(gs.bool(gs.gp(self,"backgroundColor")) , gs.gp(self,"backgroundColor") , gs.elvis(gs.bool(gs.gp(self,"color")) , gs.gp(self,"color") , gSobject.colors)); gs.sp(dataset,"backgroundColor",color); }; if (gs.bool(gs.gp(self,"datasets"))) { var color = gs.elvis(gs.bool(gs.gp(self,"borderColor")) , gs.gp(self,"borderColor") , gs.elvis(gs.bool(gs.gp(self,"color")) , gs.gp(self,"color") , gSobject.colors)); gs.sp(dataset,"borderColor",(gs.mc(color,"contains",["#"]) ? color : color[(gs.mod(index, gs.gp(color,"length")))])); gs.sp(dataset,"pointBackgroundColor",color); color = gs.elvis(gs.bool(gs.gp(self,"backgroundColor")) , gs.gp(self,"backgroundColor") , gs.elvis(gs.bool(gs.gp(self,"color")) , gs.gp(self,"color") , gSobject.colors)); gs.sp(dataset,"backgroundColor",(gs.mc(color,"contains",["#"]) ? color : color[(gs.mod(index, gs.gp(color,"length")))])); }; gs.sp(dataset,"tension",gs.elvis(gs.bool(gs.gp(self,"tension")) , gs.gp(self,"tension") , 0.1)); gs.sp(dataset,"fill",gs.elvis(gs.bool(gs.gp(self,"filled")) , gs.gp(self,"filled") , false)); gs.sp(dataset,"pointStyle",gs.elvis(gs.bool(gs.gp(self,"pointStyle")) , gs.gp(self,"pointStyle") , false)); gs.sp(dataset,"pointRadius",gs.elvis(gs.bool(gs.gp(self,"pointRadius")) , gs.gp(self,"pointRadius") , 0)); gs.sp(dataset,"stepped",gs.elvis(gs.bool(gs.gp(self,"stepped")) , gs.gp(self,"stepped") , false)); gs.sp(dataset,"borderDash",gs.elvis(gs.bool(gs.gp(self,"dashedLine")) , gs.gp(self,"dashedLine") , gs.list([0 , 0]))); return dataset; } gSobject['datasets'] = function(self) { if (self === undefined) self = this; var datasets = gs.list([]); if (gs.bool(gs.gp(self,"data"))) { gs.mc(datasets,"add",[gs.mc(gSobject,"dataset",[self, gs.gp(self,"data")])]); }; if (gs.bool(gs.gp(self,"datasets"))) { gs.mc(gs.toJavascript(gs.gp(self,"datasets")),"eachWithIndex",[function(data, index) { return gs.mc(datasets,"add",[gs.mc(gSobject,"dataset",[self, data, index])]); }]); }; return datasets; } gSobject['plugins'] = function(self) { if (self === undefined) self = this; var title = gs.map(); if (gs.bool(gs.gp(self,"title"))) { gs.sp(title,"display",true); gs.sp(title,"text",gs.gp(self,"title")); }; var legend = gs.map(); gs.sp(legend,"display",gs.gp(self,"legend")); var plugins = gs.map(); gs.sp(plugins,"legend",legend); gs.sp(plugins,"title",title); return plugins; } gSobject['scales'] = function(self) { if (self === undefined) self = this; var xScale = gs.map(); gs.sp(xScale,"display",(gs.bool(gs.gp(self,"xHide")) ? false : true)); gs.sp(xScale,"stacked",gs.elvis(gs.bool(gs.gp(self,"xStacked")) , gs.gp(self,"xStacked") , false)); gs.sp(xScale,"grid",gs.map()); gs.sp(gs.gp(xScale,"grid"),"display",(gs.bool(gs.gp(self,"xGridHide")) ? false : true)); var yScale = gs.map(); gs.sp(yScale,"display",(gs.bool(gs.gp(self,"yHide")) ? false : true)); gs.sp(yScale,"stacked",gs.elvis(gs.bool(gs.gp(self,"yStacked")) , gs.gp(self,"yStacked") , false)); if (gs.bool(gs.gp(self,"min"))) { gs.sp(yScale,"suggestedMin",gs.gp(self,"min")); }; if (gs.bool(gs.gp(self,"max"))) { gs.sp(yScale,"suggestedMax",gs.gp(self,"max")); }; gs.sp(yScale,"grid",gs.map()); gs.sp(gs.gp(yScale,"grid"),"display",(gs.bool(gs.gp(self,"yGridHide")) ? false : true)); var rScale = gs.map(); gs.sp(rScale,"display",(gs.bool(gs.gp(self,"rHide")) ? false : true)); gs.sp(rScale,"grid",gs.map()); gs.sp(gs.gp(rScale,"grid"),"display",(gs.bool(gs.gp(self,"rGridHide")) ? false : true)); var scales = gs.map(); if (gs.mc(gs.list(["radar" , "polarArea"]),"includes",[gs.gp(self,"type")])) { gs.sp(scales,"r",gs.toJavascript(rScale)); }; if (!gs.bool(gs.mc(gs.list(["doughnut" , "pie" , "polarArea" , "radar"]),"includes",[gs.gp(self,"type")]))) { gs.sp(scales,"x",gs.toJavascript(xScale)); gs.sp(scales,"y",gs.toJavascript(yScale)); }; return scales; } gSobject.paintChart = function(x0,x1,x2,x3) { return I3Chart.paintChart(x0,x1,x2,x3); } gSobject.updateData = function(x0,x1,x2) { return I3Chart.updateData(x0,x1,x2); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; I3Chart.paintChart = function(chartId, data, options, type) { if (type === undefined) type = "line"; const oldChart = Chart.getChart(chartId) if (oldChart != undefined) oldChart.destroy() const config = { type: type, data: data, options: options, } const myChart = new Chart( document.getElementById(chartId), config) } I3Chart.updateData = function(chartId, chartLabels, dataSet) { let chart = Chart.getChart(chartId); chart.data.datasets[0].data = gs.toJavascript(dataSet) chart.data.labels = gs.toJavascript(chartLabels) chart.update() } function CycleLandingComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'CycleLandingComponent', simpleName: 'CycleLandingComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/cycleLanding"]); gSobject['created'] = function(it) { gs.println("CycleLandingComponent.created()"); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.cycle.landing"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); return gs.mc(gSobject,"componentTheme",[false]); } gSobject['startQN'] = function(it) { gs.println("Cycle Assessment Started"); return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["protocolQNComponent/Cycle Assessment"]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function CycleOverviewComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'CycleOverviewComponent', simpleName: 'CycleOverviewComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/cycleOverview"]); gSobject['created'] = function(it) { gs.println("CycleOverviewComponent.created()"); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.cycle.overview"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); gs.mc(gSobject,"componentTheme",[false]); var today = gs.mc(gSobject,"moment",[]); gs.sp(gSobject.scope,"selectedDate",gs.mc(today,"format",["YYYY-MM-DD"])); gs.sp(gSobject.scope,"year",gs.mc(today,"format",["YYYY"])); gs.sp(gSobject.scope,"month",gs.mc(today,"month",[])); gs.sp(gSobject.scope,"monthDropdown",false); gs.sp(gSobject.scope,"periodValue",45); gs.sp(gSobject.scope,"batchName","medical:score:cycles"); gs.sp(gSobject.scope,"friendlyCountdown",""); gs.sp(gSobject.scope,"lastEntry",gs.map()); gs.sp(gSobject.scope,"recentSymptoms",gs.list([])); gs.sp(gSobject.scope,"months",gs.list(["January" , "February" , "March" , "April" , "May" , "June" , "July" , "August" , "September" , "October" , "November" , "December"])); gs.sp(gSobject.scope,"articles",gs.list([gs.map().add("title","Tech Today").add("desc","AI & Innovation").add("cardTitle","Managing Your Period #101: How to do it Properly.").add("image","https://cdn.quasar.dev/img/mountains.jpg").add("author","Dr. Louis Hugo").add("routeTo","/mediaContent/").add("id","019512adfc737a58acbfd6196eb379e5")])); gs.sp(gSobject.scope,"symptomsOptions",gs.list([gs.map().add("value","Cramps") , gs.map().add("value","Insomnia") , gs.map().add("value","Breast tenderness") , gs.map().add("value","Acne") , gs.map().add("value","Fatigue") , gs.map().add("value","Backache") , gs.map().add("value","Cravings") , gs.map().add("value","Itching")])); gs.sp(gSobject.scope,"daysUntilNextPeriod",""); gs.sp(gSobject.scope,"monthDays",gs.list([])); gs.sp(gSobject.scope,"pregnancyChance","N/A"); gs.sp(gSobject.scope,"lastPeriodStart",""); gs.sp(gSobject.scope,"cycleLength",0); gs.sp(gSobject.scope,"cycleInsightsData",gs.list([gs.map().add("cycleDay",28).add("periodLength",5)])); gs.mc(gSobject,"loadCycles",[]); gs.mc(gSobject,"loadCycleOverview",[]); gs.mc(gSobject,"loadLatestCycleInsight",[]); return gs.mc(gSobject,"loadRecentSymptoms",[]); } gSobject['loadCycles'] = function(it) { gs.sp(gSobject.scope,"logs",gs.list([])); gs.sp(gSobject.scope,"lastEntryDate","None"); gs.sp(gSobject.scope,"lastEntry",gs.map()); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"listEntries",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gSobject.scope,"batchName"), gs.map().add("limit",7), function(logs) { return gs.mc(logs,"each",[function(log) { return gs.mc(gs.gp(gSobject.scope,"logs"),"add",[gs.map().add("_id",gs.gp(log,"_id")).add("value","Day " + (gs.gp(log,"cycleDay")) + "").add("subtext",gs.gp(log,"phase")).add("startDate",gs.gp(log,"startDate")).add("endDate",gs.gp(log,"endDate")).add("intensity",gs.gp(log,"intensity")).add("symptoms",gs.gp(log,"symptoms")).add("note",gs.gp(log,"note")).add("status",gs.gp(log,"status")).add("nextPeriod",gs.gp(log,"nextPeriodDate")).add("periodLength",gs.gp(log,"periodLength")).add("cycleDay",gs.gp(log,"cycleDay")).add("phase",gs.gp(log,"phase")).add("ovulation",gs.gp(log,"ovulationDate")).add("fertileWindowStart",gs.gp(log,"fertileWindowStart")).add("fertileWindowEnd",gs.gp(log,"fertileWindowEnd")).add("_createdAt",gs.gp(log,"startDate"))]); }]); }]); } gSobject['loadCycleOverview'] = function(it) { gs.println("Loading cycle overview"); var today = gs.mc(gSobject,"moment",[]); gs.sp(gSobject.scope,"today",today); gs.sp(gSobject.scope,"selectedDate",gs.mc(today,"format",["YYYY-MM-DD"])); var userId = gs.gp(gs.fs('session', this, gSobject),"userId"); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[userId, "pregnant:pregnant", function(pregnantVal) { var isPregnant = pregnantVal; if (gs.equals(isPregnant, "Yes")) { gs.sp(gSobject.scope,"daysUntilNextPeriod",null); gs.sp(gSobject.scope,"pregnancyChance","N/A"); gs.sp(gSobject.scope,"monthDays",gs.list([])); return null; }; return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[userId, "cycle_period:cycle_length_days", function(cycleLengthVal) { gs.sp(gSobject.scope,"cycleLength",gs.elvis(gs.bool(cycleLengthVal) , cycleLengthVal , 28)); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[userId, "menstrual_cycle:start_date", function(lastStartVal) { if (!gs.bool(lastStartVal)) { gs.println("No last period start date found"); gs.sp(gSobject.scope,"friendlyCountdown","No data"); return null; }; gs.sp(gSobject.scope,"lastPeriodStart",lastStartVal); gs.println("cycleLength: " + (gs.gp(gSobject.scope,"cycleLength")) + ""); var lastStart = gs.mc(gSobject,"moment",[lastStartVal, gs.list(["YYYY-MM-DD" , "YYYY/MM/DD"])]); gs.println("Parsed lastStart: " + (gs.mc(lastStart,"format",[])) + ""); var nextPeriodDate = gs.mc(gs.mc(gSobject,"moment",[lastStart]),"add",[gs.gp(gSobject.scope,"cycleLength"), "days"]); var safetyCounter = 0; while ((gs.mc(nextPeriodDate,"isBefore",[today, "day"])) && (safetyCounter < 50)) { gs.mc(nextPeriodDate,"add",[gs.gp(gSobject.scope,"cycleLength"), "days"]); safetyCounter++; }; var daysUntilNextPeriod = gs.mc(nextPeriodDate,"diff",[today, "days"]); var ovulationDate = gs.mc(gs.mc(gSobject,"moment",[nextPeriodDate]),"subtract",[14, "days"]); var fertileStart = gs.mc(gs.mc(gSobject,"moment",[ovulationDate]),"subtract",[5, "days"]); var fertileEnd = gs.mc(ovulationDate,"clone",[]); var pregnancyChance = (gs.mc(today,"isBetween",[fertileStart, fertileEnd, null, "[]"]) ? "High" : "Low"); gs.println("Pregnancy chance: " + (pregnancyChance) + ""); gs.println("\n lastStart: " + (gs.mc(lastStart,"format",["YYYY-MM-DD"])) + "\n nextPeriodDate: " + (gs.mc(nextPeriodDate,"format",["YYYY-MM-DD"])) + "\n ovulationDate: " + (gs.mc(ovulationDate,"format",["YYYY-MM-DD"])) + "\n fertileStart: " + (gs.mc(fertileStart,"format",["YYYY-MM-DD"])) + "\n fertileEnd: " + (gs.mc(fertileEnd,"format",["YYYY-MM-DD"])) + "\n daysUntilNextPeriod: " + (daysUntilNextPeriod) + "\n pregnancyChance: " + (pregnancyChance) + "\n "); var weekday = gs.mc(nextPeriodDate,"day",[]); var week = gs.list([]); var startOfWeek = gs.mc(gs.mc(gSobject,"moment",[nextPeriodDate]),"startOf",["isoWeek"]); for (var i = 0 ; i < 7 ; i++) { var date = gs.mc(gs.mc(gs.mc(this,"moment",[startOfWeek], gSobject),"add",[i, "days"]),"startOf",["day"]); var dot = null; if (gs.mc(date,"isSame",[gs.mc(nextPeriodDate,"startOf",["day"]), "day"])) { dot = "period"; } else { if (gs.mc(date,"isSame",[gs.mc(ovulationDate,"startOf",["day"]), "day"])) { dot = "ovulation"; } else { if (gs.mc(date,"isBetween",[gs.mc(fertileStart,"startOf",["day"]), gs.mc(fertileEnd,"startOf",["day"]), null, "[]"])) { dot = "fertile"; }; }; }; gs.mc(week,"add",[gs.map().add("date",gs.mc(date,"format",["YYYY-MM-DD"])).add("dayOfWeek",gs.mc(date,"format",["ddd"])).add("day",gs.mc(date,"format",["D"])).add("dot",dot)]); }; gs.sp(gSobject.scope,"nextPeriodDate",gs.mc(nextPeriodDate,"format",["YYYY-MM-DD"])); gs.sp(gSobject.scope,"daysUntilNextPeriod",daysUntilNextPeriod); gs.sp(gSobject.scope,"ovulationDate",gs.mc(ovulationDate,"format",["YYYY-MM-DD"])); gs.sp(gSobject.scope,"pregnancyChance",pregnancyChance); gs.sp(gSobject.scope,"monthDays",week); if (gs.equals(daysUntilNextPeriod, null)) { return gs.sp(gSobject.scope,"friendlyCountdown","—"); } else { if (daysUntilNextPeriod < 0) { return gs.sp(gSobject.scope,"friendlyCountdown","Started"); } else { if (gs.equals(daysUntilNextPeriod, 0)) { return gs.sp(gSobject.scope,"friendlyCountdown","Today"); } else { if (gs.equals(daysUntilNextPeriod, 1)) { return gs.sp(gSobject.scope,"friendlyCountdown","Tomorrow"); } else { return gs.sp(gSobject.scope,"friendlyCountdown","In " + (daysUntilNextPeriod) + " Days"); }; }; }; }; }]); }]); }]); } gSobject['loadLatestCycleInsight'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"listEntries",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gSobject.scope,"batchName"), function(logs) { if ((gs.bool(logs)) && (gs.mc(logs,"size",[]) > 1)) { var sorted = gs.mc(logs,"sort",[function(a, b) { return gs.mc(gs.mc(gSobject,"moment",[gs.gp(a,"startDate")]),"diff",[gs.mc(gSobject,"moment",[gs.gp(b,"startDate")])]); }]); var cycleLengths = gs.mc(logs,"collect",[function(log) { return gs.mc(gs.mc(gSobject,"moment",[gs.gp(log,"endDate")]),"diff",[gs.mc(gSobject,"moment",[gs.gp(log,"startDate")]), "days"]); }]); for (var i = 1 ; i < gs.mc(sorted,"size",[]) ; i++) { var prev = gs.mc(this,"moment",[gs.gp(sorted[(gs.minus(i, 1))],"startDate")], gSobject); var curr = gs.mc(this,"moment",[gs.gp(sorted[i],"startDate")], gSobject); gs.mc(cycleLengths,'leftShift', gs.list([gs.mc(curr,"diff",[prev, "days"])])); }; var recentCycleLength = gs.mc(cycleLengths,"last",[]); var variation = gs.minus(gs.mc(cycleLengths,"max",[]), gs.mc(cycleLengths,"min",[])); var isRegular = variation <= 3; var latest = gs.mc(sorted,"last",[]); return gs.sp(gSobject.scope,"cycleInsightsData",gs.map().add("periodLength",gs.gp(latest,"periodLength")).add("cycleLength",recentCycleLength).add("regularity",(gs.bool(isRegular) ? "Normal" : "Irregular"))); } else { return gs.sp(gSobject.scope,"cycleInsightsData",gs.map().add("periodLength",gs.elvis(gs.bool(gs.gp(logs[0],"periodLength",true)) , gs.gp(logs[0],"periodLength",true) , null)).add("cycleLength",gs.elvis(gs.bool(gs.gp(logs[0],"cycleLength",true)) , gs.gp(logs[0],"cycleLength",true) , null)).add("regularity","N/A")); }; }]); } gSobject['loadRecentSymptoms'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"listEntries",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:cycles", function(entries) { var withSymptoms = gs.mc(entries,"findAll",[function(it) { return (gs.bool(gs.gp(it,"symptoms"))) && (gs.mc(gs.gp(it,"symptoms"),"size",[]) > 0); }]); var latest = gs.mc(gs.mc(withSymptoms,"sort",[function(a, b) { return gs.mc(gs.mc(gSobject,"moment",[gs.gp(b,"startDate")]),"diff",[gs.mc(gSobject,"moment",[gs.gp(a,"startDate")])]); }]),"first",[]); return gs.sp(gSobject.scope,"recentSymptoms",gs.elvis(gs.bool(gs.gp(latest,"symptoms",true)) , gs.gp(latest,"symptoms",true) , gs.list([]))); }]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function CycleLogComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'CycleLogComponent', simpleName: 'CycleLogComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/logCycle" , "/logCycle/:id"]); gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.cycle.log"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"dialog",false); gs.sp(gSobject.scope,"date",gs.mc(gs.mc(gSobject,"moment",[]),"format",["YYYY-MM-DD"])); gs.sp(gSobject.scope,"tab","cycle"); gs.sp(gSobject.scope,"todayDateInput",gs.mc(gs.mc(gSobject,"moment",[]),"format",["YYYY-MM-DD"])); gs.sp(gSobject.scope,"fluidOptions",gs.list(["Egg White" , "Pink" , "Brown" , "Light Yellow" , "Yellow" , "Green" , "Gray"])); gs.sp(gSobject.scope,"intensityOptions",gs.list([gs.map().add("value","Spotting").add("icon","sym_o_spoke") , gs.map().add("value","Light").add("icon","sym_o_humidity_low") , gs.map().add("value","Medium").add("icon","sym_o_water_full") , gs.map().add("value","Heavy").add("icon","sym_o_air")])); gs.sp(gSobject.scope,"symptomsOptions",gs.list([gs.map().add("value","Cramps").add("icon","sym_o_gynecology") , gs.map().add("value","Insomnia").add("icon","sym_o_bedtime") , gs.map().add("value","Breast tenderness").add("icon","sym_o_rib_cage") , gs.map().add("value","Acne").add("icon","sym_o_dermatology") , gs.map().add("value","Fatigue").add("icon","sym_o_sentiment_very_dissatisfied") , gs.map().add("value","Backache").add("icon","sym_o_bug_report") , gs.map().add("value","Cravings").add("icon","sym_o_restaurant") , gs.map().add("value","Itching").add("icon","sym_o_warning")])); gs.sp(gSobject.scope,"selectedIntensity",""); gs.sp(gSobject.scope,"selectedSymptoms",gs.list([])); gs.sp(gSobject.scope,"entry",gs.map().add("startDate",gs.mc(gs.mc(gSobject,"moment",[]),"format",["YYYY-MM-DD"])).add("endDate",gs.mc(gs.mc(gSobject,"moment",[]),"format",["YYYY-MM-DD"])).add("fluid","").add("intensity","").add("symptoms",gs.list([])).add("note","").add("status","")); if (gs.bool(gs.gp(gs.gp(gSobject.route,"params"),"id"))) { gs.sp(gSobject.scope,"entry",null); gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"loadEntry",[gs.gp(gs.gp(gSobject.route,"params"),"id"), function(entry) { gs.println("entry"); gs.println(entry); gs.sp(gSobject.scope,"entry",entry); gs.sp(gs.gp(gSobject.scope,"entry"),"startDate",gs.mc(gs.mc(gSobject,"moment",[gs.gp(entry,"startDate")]),"format",["YYYY-MM-DD"])); gs.sp(gs.gp(gSobject.scope,"entry"),"endDate",gs.mc(gs.mc(gSobject,"moment",[gs.gp(entry,"endDate")]),"format",["YYYY-MM-DD"])); gs.sp(gSobject.scope,"selectedIntensity",gs.elvis(gs.bool(gs.gp(entry,"intensity")) , gs.gp(entry,"intensity") , "")); return gs.sp(gSobject.scope,"selectedSymptoms",gs.elvis(gs.bool(gs.gp(entry,"symptoms")) , gs.gp(entry,"symptoms") , gs.list([]))); }]); }; return gs.sp(gSobject.scope,"dialog",false); } gSobject['logCycle'] = function(it) { var entry = gs.gp(gSobject.scope,"entry"); gs.sp(entry,"intensity",gs.gp(gSobject.scope,"selectedIntensity")); gs.sp(entry,"symptoms",gs.gp(gSobject.scope,"selectedSymptoms")); if (!gs.bool(gs.gp(gSobject.scope,"selectedIntensity"))) { gs.mc(gSobject,"notify",["Please select a flow intensity", "negative"]); return null; }; if ((!gs.bool(gs.gp(gs.gp(gSobject.scope,"entry"),"startDate"))) || (!gs.bool(gs.gp(gs.gp(gSobject.scope,"entry"),"endDate")))) { gs.mc(gSobject,"notify",["Start and end date are required", "negative"]); return null; }; if (gs.mc(gs.mc(gSobject,"moment",[gs.gp(gs.gp(gSobject.scope,"entry"),"startDate")]),"isAfter",[gs.gp(gs.gp(gSobject.scope,"entry"),"endDate")])) { gs.mc(gSobject,"notify",["Start date cannot be after end date", "negative"]); return null; }; var phase = ""; var today = gs.mc(gs.mc(gSobject,"moment",[]),"format",["YYYY-MM-DD"]); var startDate = gs.date(gs.gp(entry,"startDate")); var endDate = gs.date(gs.gp(entry,"endDate")); var cycleDay = gs.plus(gs.mc(gs.mc(gSobject,"moment",[gs.gp(entry,"endDate")]),"diff",[gs.mc(gSobject,"moment",[gs.gp(entry,"startDate")]), "days"]), 1); var cycleLength = null; if (gs.equals(gs.mc(gs.mc(gSobject,"moment",[gs.gp(entry,"endDate")]),"format",["YYYY-MM-DD"]), today)) { if (cycleDay <= 5) { phase = "Menstrual Phase"; } else { if (cycleDay <= 13) { phase = "Follicular Phase"; } else { if (gs.equals(cycleDay, 14)) { phase = "Ovulation Phase"; } else { if (cycleDay <= 28) { phase = "Luteal Phase"; } else { phase = "Unknown Phase"; }; }; }; }; }; gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "menstrual_cycle:start_date", function(menstrual_cycle) { return cycleLength = menstrual_cycle; }]); var periodLength = gs.plus(gs.mc(gs.mc(gSobject,"moment",[gs.gp(entry,"endDate")]),"diff",[gs.mc(gSobject,"moment",[gs.gp(entry,"startDate")]), "days"]), 1); gs.sp(entry,"duration",periodLength); var nextPeriodDate = gs.mc(gs.mc(gs.mc(gSobject,"moment",[gs.gp(entry,"startDate")]),"add",[cycleLength, "days"]),"format",["YYYY-MM-DD"]); var ovulationDate = gs.mc(gs.mc(gSobject,"moment",[nextPeriodDate]),"subtract",[14, "days"]); var fertileWindowStart = gs.mc(gs.mc(gSobject,"moment",[ovulationDate]),"subtract",[5, "days"]); var fertileWindowEnd = gs.mc(ovulationDate,"clone",[]); var status = "Next period: " + (nextPeriodDate) + ", Ovulation: " + (ovulationDate) + ", Fertile window: " + (fertileWindowStart) + " to " + (fertileWindowEnd) + ""; if (gs.equals(gs.mc(gs.mc(gSobject,"moment",[gs.fs('date', this, gSobject)]),"format",["YYYY-MM-DD"]), today)) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:cycles:startDate", gs.gp(entry,"startDate")]),"do",[]); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:cycles:endDate", gs.gp(entry,"endDate")]),"do",[]); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:cycles:intensity", gs.gp(entry,"intensity")]),"do",[]); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:cycles:symptoms", gs.gp(entry,"symptoms")]),"do",[]); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:cycles:note", gs.gp(entry,"note")]),"do",[]); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:cycles:status", status]),"do",[]); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:cycles:nextPeriod", nextPeriodDate]),"do",[]); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:cycles:periodLength", periodLength]),"do",[]); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:cycles:ovulation", ovulationDate]),"do",[]); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:cycles:fertileWindowStart", fertileWindowStart]),"do",[]); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:cycles:fertileWindowEnd", fertileWindowEnd]),"do",[]); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:cycles:cycleDay", cycleDay]),"do",[]); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:cycles:phase", phase]),"do",[]); }; gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"addEntryWithFts",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:cycles", gs.list(["value"]), gs.map().add("startDate",startDate).add("endDate",endDate).add("intensity",gs.gp(entry,"intensity")).add("symptoms",gs.gp(entry,"symptoms")).add("note",gs.gp(entry,"note")).add("status",status).add("nextPeriod",nextPeriodDate).add("periodLength",periodLength).add("duration",periodLength).add("ovulation",ovulationDate).add("fertileWindowStart",fertileWindowStart).add("fertileWindowEnd",fertileWindowEnd).add("cycleDay",cycleDay).add("phase",phase).add("fluid",gs.gp(entry,"fluid"))]),"then",[function(it) { return gs.sp(gSobject.scope,"dialog",true); }, function(error) { return gs.sp(gSobject.scope,"dialog",true); }]); return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"notificationService"),"removeNotification",[gs.gp(gs.fs('session', this, gSobject),"userId"), "trackable:Cycles", "Cycles"]),"do",[]); } gSobject['toggleSelection'] = function(option) { if (gs.equals(gs.gp(gSobject.scope,"selectedIntensity"), gs.gp(option,"value"))) { return gs.sp(gSobject.scope,"selectedIntensity",""); } else { return gs.sp(gSobject.scope,"selectedIntensity",gs.gp(option,"value")); }; } gSobject['toggleSymptoms'] = function(option) { var index = gs.mc(gs.gp(gSobject.scope,"selectedSymptoms"),"indexOf",[gs.gp(option,"value")]); if (gs.equals(index, -1)) { gs.mc(gs.gp(gSobject.scope,"selectedSymptoms"),'leftShift', gs.list([gs.gp(option,"value")])); } else { gs.mc(gs.gp(gSobject.scope,"selectedSymptoms"),"remove",[index]); }; return gs.println("Current selection: " + (gs.gp(gSobject.scope,"selectedSymptoms")) + ""); } gSobject['error'] = function(it) { return gs.mc(gSobject,"notify",["Form Error", "negative"]); } gSobject['formatTwoDigits'] = function(number) { return (number < 10 ? gs.plus("0", number) : gs.mc(this,"String",[number], gSobject)); } gSobject['onFormError'] = function(it) { return gs.mc(gSobject,"notify",["Please fill all required fields correctly", "negative"]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function CycleDetailComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'CycleDetailComponent', simpleName: 'CycleDetailComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/cycleDetail" , "/cycleDetail/:id"]); gSobject['created'] = function(it) { gs.println("CycleDetailComponent.created()"); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.cycle.detail"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"entry",gs.map()); gs.sp(gSobject.scope,"daysUntilNextPeriod",""); gs.sp(gSobject.scope,"nextPeriodDate",""); gs.sp(gSobject.scope,"daysUntilNextPeriod",""); gs.sp(gSobject.scope,"fertileWindowStatus",""); gs.sp(gSobject.scope,"batchName","medical:score:cycles"); gs.sp(gSobject.scope,"symptomIntensity",""); gs.mc(gSobject,"calculateRegularity",[]); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"loadEntry",[gs.gp(gs.gp(gSobject.route,"params"),"id"), function(entry) { gs.sp(gSobject.scope,"entry",entry); var nextPeriod = gs.mc(gSobject,"moment",[gs.gp(entry,"nextPeriod")]); var now = gs.mc(gSobject,"moment",[]); if (!gs.bool(gs.mc(nextPeriod,"isBefore",[now, "day"]))) { gs.sp(gSobject.scope,"daysUntilNextPeriod",gs.mc(nextPeriod,"diff",[now, "days"])); gs.sp(gSobject.scope,"nextPeriodDate",gs.mc(nextPeriod,"format",["dddd, MMM DD, YYYY"])); gs.sp(gSobject.scope,"showNextPeriod",true); } else { gs.sp(gSobject.scope,"showNextPeriod",false); }; var fertileStart = gs.mc(gSobject,"moment",[gs.gp(entry,"fertileWindowStart"), "YYYY-MM-DD"]); var fertileEnd = gs.mc(gSobject,"moment",[gs.gp(entry,"fertileWindowEnd"), "YYYY-MM-DD"]); return gs.sp(gSobject.scope,"fertileWindowStatus",((gs.mc(now,"isSameOrAfter",[fertileStart, "day"])) && (gs.mc(now,"isSameOrBefore",[fertileEnd, "day"])) ? "Active" : "Inactive")); }]); } gSobject['calculateRegularity'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"listEntries",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gSobject.scope,"batchName"), function(entries) { var sorted = gs.mc(entries,"sort",[function(a, b) { return gs.mc(gs.mc(gSobject,"moment",[gs.gp(a,"startDate")]),"diff",[gs.mc(gSobject,"moment",[gs.gp(b,"startDate")])]); }]); var lengths = gs.list([]); for (var i = 1 ; i < gs.mc(sorted,"size",[]) ; i++) { var prev = gs.mc(this,"moment",[gs.gp(sorted[(gs.minus(i, 1))],"startDate")], gSobject); var curr = gs.mc(this,"moment",[gs.gp(sorted[i],"startDate")], gSobject); gs.mc(lengths,'leftShift', gs.list([gs.mc(curr,"diff",[prev, "days"])])); }; var regular = (gs.minus(gs.mc(lengths,"max",[]), gs.mc(lengths,"min",[]))) <= 3; gs.sp(gs.gp(gSobject.scope,"entry"),"cycleRegularity",(gs.bool(regular) ? "Regular" : "Irregular")); var symptomCount = gs.elvis(gs.mc(gs.gp(gs.gp(gSobject.scope,"entry"),"symptoms"),"size",[], null, true) , gs.mc(gs.gp(gs.gp(gSobject.scope,"entry"),"symptoms"),"size",[], null, true) , 0); gs.sp(gSobject.scope,"symptomIntensity",(symptomCount >= 4 ? "Severe" : (symptomCount >= 2 ? "Mild" : "None"))); return gs.println("ENTRY: " + (gs.gp(gSobject.scope,"entry")) + ""); }]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function CycleInsightComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'CycleInsightComponent', simpleName: 'CycleInsightComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/cycleInsight"]); gSobject['created'] = function(it) { gs.println("CycleInsightComponent.created()"); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.cycle.insight"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"cycleInsightsData",gs.list([gs.map().add("cycleDay",28).add("periodLength",5)])); gs.sp(gSobject.scope,"cycleComparisonData",gs.map().add("current",gs.map()).add("previous",gs.map())); gs.sp(gSobject.scope,"recentSymptoms",gs.list([])); gs.sp(gSobject.scope,"avgCycleData",gs.map()); gs.sp(gSobject.scope,"batchName","medical:score:cycles"); gs.mc(gSobject,"loadCycles",[]); gs.mc(gSobject,"loadLatestCycleInsight",[]); gs.mc(gSobject,"loadCycleComparisonData",[]); gs.mc(gSobject,"loadRecentSymptoms",[]); return gs.mc(gSobject,"loadAverageCycleData",[]); } gSobject['loadCycles'] = function(it) { gs.sp(gSobject.scope,"logs",gs.list([])); gs.sp(gSobject.scope,"lastEntryDate",""); gs.sp(gSobject.scope,"lastEntry",gs.map()); var symptoms = gs.list([gs.map().add("name","Acne").add("count",3) , gs.map().add("name","Headache").add("count",5)]); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"listEntries",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gSobject.scope,"batchName"), gs.map().add("limit",1), function(logs) { if ((gs.bool(logs)) && (gs.mc(logs,"size",[]) > 0)) { var log = logs[0]; gs.sp(gSobject.scope,"lastEntry",gs.map().add("_id",gs.gp(log,"_id")).add("value","Day " + (gs.gp(log,"cycleDay")) + "").add("subtext",gs.gp(log,"phase")).add("startDate",gs.gp(log,"startDate")).add("endDate",gs.gp(log,"endDate")).add("intensity",gs.gp(log,"intensity")).add("symptoms",symptoms).add("note",gs.gp(log,"note")).add("status",gs.gp(log,"status")).add("nextPeriod",gs.gp(log,"nextPeriodDate")).add("periodLength",gs.gp(log,"periodLength")).add("cycleLength",gs.gp(log,"cycleLength")).add("cycleDay",gs.gp(log,"cycleDay")).add("phase",gs.gp(log,"phase")).add("ovulation",gs.gp(log,"ovulationDate")).add("fertileWindowStart",gs.gp(log,"fertileWindowStart")).add("fertileWindowEnd",gs.gp(log,"fertileWindowEnd")).add("_createdAt",gs.gp(log,"date"))); return gs.sp(gSobject.scope,"lastEntryDate",gs.gp(log,"date")); }; }]); } gSobject['loadLatestCycleInsight'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"listEntries",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gSobject.scope,"batchName"), function(logs) { if ((gs.bool(logs)) && (gs.mc(logs,"size",[]) > 1)) { var sorted = gs.mc(logs,"sort",[function(a, b) { return gs.mc(gs.mc(gSobject,"moment",[gs.gp(a,"startDate")]),"diff",[gs.mc(gSobject,"moment",[gs.gp(b,"startDate")])]); }]); var cycleLengths = gs.list([]); for (var i = 1 ; i < gs.mc(sorted,"size",[]) ; i++) { var prev = gs.mc(this,"moment",[gs.gp(sorted[(gs.minus(i, 1))],"startDate")], gSobject); var curr = gs.mc(this,"moment",[gs.gp(sorted[i],"startDate")], gSobject); gs.mc(cycleLengths,'leftShift', gs.list([gs.mc(curr,"diff",[prev, "days"])])); }; var recentCycleLength = gs.mc(cycleLengths,"last",[]); var variation = gs.minus(gs.mc(cycleLengths,"max",[]), gs.mc(cycleLengths,"min",[])); var isRegular = variation <= 3; var latest = gs.mc(sorted,"last",[]); return gs.sp(gSobject.scope,"cycleInsightsData",gs.map().add("periodLength",gs.gp(latest,"periodLength")).add("cycleLength",recentCycleLength).add("regularity",(gs.bool(isRegular) ? "Normal" : "Irregular"))); } else { return gs.sp(gSobject.scope,"cycleInsightsData",gs.map().add("periodLength",gs.elvis(gs.bool(gs.gp(logs[0],"periodLength",true)) , gs.gp(logs[0],"periodLength",true) , null)).add("cycleLength",gs.elvis(gs.bool(gs.gp(logs[0],"cycleLength",true)) , gs.gp(logs[0],"cycleLength",true) , null)).add("regularity","N/A")); }; }]); } gSobject['loadRecentSymptoms'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"listEntries",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:cycles", function(entries) { var withSymptoms = gs.mc(entries,"findAll",[function(it) { return (gs.bool(gs.gp(it,"symptoms"))) && (gs.mc(gs.gp(it,"symptoms"),"size",[]) > 0); }]); gs.println("withSymptoms"); gs.println(withSymptoms); var latest = gs.mc(gs.mc(withSymptoms,"sort",[function(a, b) { return gs.mc(gs.mc(gSobject,"moment",[gs.gp(b,"startDate")]),"diff",[gs.mc(gSobject,"moment",[gs.gp(a,"startDate")])]); }]),"first",[]); gs.println("latest"); gs.println(latest); return gs.sp(gSobject.scope,"recentSymptoms",gs.elvis(gs.bool(gs.gp(latest,"symptoms",true)) , gs.gp(latest,"symptoms",true) , gs.list([]))); }]); } gSobject['loadCycleComparisonData'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"listEntries",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:cycles", function(logs) { if ((!gs.bool(logs)) || (gs.mc(logs,"size",[]) < 3)) { gs.sp(gSobject.scope,"cycleComparisonData",null); return null; }; var validLogs = gs.mc(logs,"findAll",[function(it) { return (gs.bool(it)) && (gs.bool(gs.gp(it,"startDate"))); }]); if (gs.mc(validLogs,"size",[]) < 3) { gs.sp(gSobject.scope,"cycleComparisonData",null); return null; }; var sorted = gs.mc(validLogs,"sort",[function(a, b) { return gs.mc(gs.mc(gSobject,"moment",[gs.gp(a,"startDate")]),"diff",[gs.mc(gSobject,"moment",[gs.gp(b,"startDate")])]); }]); var len = gs.mc(sorted,"size",[]); var latestLog = gs.mc(sorted,"get",[gs.minus(len, 1)]); var previousLog = gs.mc(sorted,"get",[gs.minus(len, 2)]); var beforePreviousLog = gs.mc(sorted,"get",[gs.minus(len, 3)]); var currentCycleLength = gs.mc(gs.mc(gSobject,"moment",[gs.gp(latestLog,"startDate")]),"diff",[gs.mc(gSobject,"moment",[gs.gp(previousLog,"startDate")]), "days"]); var previousCycleLength = gs.mc(gs.mc(gSobject,"moment",[gs.gp(previousLog,"startDate")]),"diff",[gs.mc(gSobject,"moment",[gs.gp(beforePreviousLog,"startDate")]), "days"]); return gs.sp(gSobject.scope,"cycleComparisonData",gs.map().add("current",gs.map().add("cycleLength",currentCycleLength).add("periodLength",gs.gp(latestLog,"periodLength")).add("startDate",gs.mc(gs.mc(gSobject,"moment",[gs.gp(latestLog,"startDate")]),"format",["MMM DD"]))).add("previous",gs.map().add("cycleLength",previousCycleLength).add("periodLength",gs.gp(previousLog,"periodLength")).add("startDate",gs.mc(gs.mc(gSobject,"moment",[gs.gp(previousLog,"startDate")]),"format",["MMM DD"])))); }]); } gSobject['loadAverageCycleData'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"listEntries",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gSobject.scope,"batchName"), function(logs) { if ((gs.bool(logs)) && (gs.mc(logs,"size",[]) > 1)) { var sorted = gs.mc(logs,"sort",[function(a, b) { return gs.mc(gs.mc(gSobject,"moment",[gs.gp(a,"startDate")]),"diff",[gs.mc(gSobject,"moment",[gs.gp(b,"startDate")])]); }]); var cycles = gs.list([]); for (var i = 1 ; i < gs.mc(sorted,"size",[]) ; i++) { var prev = sorted[(gs.minus(i, 1))]; var curr = sorted[i]; var length = gs.mc(gs.mc(this,"moment",[gs.gp(curr,"startDate")], gSobject),"diff",[gs.mc(this,"moment",[gs.gp(prev,"startDate")], gSobject), "days"]); gs.mc(cycles,'leftShift', gs.list([gs.map().add("start",gs.mc(gs.mc(this,"moment",[gs.gp(prev,"startDate")], gSobject),"format",["MMM D"])).add("end",gs.mc(gs.mc(this,"moment",[gs.gp(curr,"startDate")], gSobject),"format",["MMM D"])).add("length",length)])); }; var average = Math.round(gs.div(gs.mc(gs.mc(cycles,"collect",[function(it) { return gs.gp(it,"length"); }]),"sum",[]), gs.mc(cycles,"size",[]))); return gs.sp(gSobject.scope,"avgCycleData",gs.map().add("averageLength",average).add("cycles",cycles)); } else { return gs.sp(gSobject.scope,"avgCycleData",null); }; }]); } gSobject['loadRecentSymptoms'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"listEntries",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gSobject.scope,"batchName"), function(entries) { var symptomCounts = gs.map(); gs.mc(entries,"each",[function(entry) { var symptoms = gs.elvis(gs.bool(gs.gp(entry,"symptoms",true)) , gs.gp(entry,"symptoms",true) , gs.list([])); return gs.mc(symptoms,"each",[function(symptom) { var name = (gs.instanceOf(symptom, "Map") ? gs.gp(symptom,"name") : symptom); if (gs.bool(name)) { return (symptomCounts[name]) = (gs.plus(gs.elvis(symptomCounts[name] , symptomCounts[name] , 0), 1)); }; }]); }], null, true); var formattedSymptoms = gs.mc(symptomCounts,"collect",[function(name, count) { return gs.map().add("name",name).add("count",count); }]); return gs.sp(gSobject.scope,"recentSymptoms",formattedSymptoms); }]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function NutritionOverviewComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'NutritionOverviewComponent', simpleName: 'NutritionOverviewComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/nutritionOverview"; gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.nutrition.overview"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"caloriesToday",0); gs.sp(gSobject.scope,"nutritionThisWeek",0); gs.sp(gSobject.scope,"nutritionLogs",gs.list([])); gs.sp(gSobject.scope,"nutritionLabels",gs.list([])); gs.sp(gSobject.scope,"nutritionValues",gs.list([])); gs.sp(gSobject.scope,"nutritionHistory",gs.map()); gs.sp(gSobject.scope,"nutritionGoal",null); gs.sp(gSobject.scope,"motivationalText",""); gs.sp(gSobject.scope,"motivationLoading",true); gs.sp(gSobject.scope,"tracker",null); gs.sp(gSobject.scope,"graphPeriod","Day"); gs.mc(gSobject,"loadMotivation",[gs.gp(gs.fs('session', this, gSobject),"userId"), "Nutrition", function(msg) { gs.sp(gSobject.scope,"motivationalText",msg); return gs.sp(gSobject.scope,"motivationLoading",false); }]); gs.mc(gSobject,"loadTrackerData",["Nutrition", function(tracker) { return gs.sp(gSobject.scope,"tracker",tracker); }]); gs.sp(gSobject.scope,"lastUpdated",""); gs.mc(gSobject,"loadLastUpdated",[gs.gp(gs.fs('session', this, gSobject),"userId"), "nutrition", function(lastUpdated) { return gs.sp(gSobject.scope,"lastUpdated",lastUpdated); }]); gs.sp(gSobject.scope,"batchName","health:nutrition"); gs.sp(gSobject.scope,"articles",gs.list([gs.map().add("title","Tech Today").add("desc","AI & Innovation").add("cardTitle","Managing Your mealplan: How to do it Properly.").add("image","https://cdn.quasar.dev/img/mountains.jpg").add("author","Dr. Louis Hugo").add("routeTo","/mediaContent/").add("id","019512adfc737a58acbfd6196eb379e5")])); gs.mc(gSobject,"fetchNutritionLogs",[]); gs.mc(gSobject,"loadNutritionLogs",[]); gs.mc(gSobject,"loadGoal",[]); return gs.mc(gSobject,"generateChartData",[]); } gSobject['loadNutritionLogs'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"listEntries",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gSobject.scope,"batchName"), gs.map().add("sort","date").add("order","desc"), function(logs) { if (!gs.bool(logs)) { return null; }; gs.sp(gSobject.scope,"nutritionLogs",logs); gs.sp(gSobject.scope,"nutritionHistory",gs.mc(gs.gp(gSobject.scope,"nutritionLogs"),"take",[7])); return gs.mc(gSobject,"calculateToday",[logs]); }]); } gSobject['calculateToday'] = function(logs) { var todayStart = gs.mc(gs.mc(gs.mc(gSobject,"moment",[]),"startOf",["day"]),"toDate",[]); var todayEnd = gs.mc(gs.mc(gs.mc(gSobject,"moment",[]),"endOf",["day"]),"toDate",[]); var todaysLog = gs.mc(logs,"find",[function(log) { return (gs.gp(log,"date") >= todayStart) && (gs.gp(log,"date") <= todayEnd); }]); return gs.sp(gSobject.scope,"caloriesToday",gs.elvis(gs.bool(gs.gp(todaysLog,"value",true)) , gs.gp(todaysLog,"value",true) , 0)); } gSobject['fetchNutritionLogs'] = function(it) { gs.sp(gSobject.scope,"nutrition",""); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"listEntries",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gSobject.scope,"batchName"), gs.map().add("limit",7), function(logs) { gs.println(gs.plus("logs", logs)); gs.sp(gSobject.scope,"nutritionLogs",gs.mc(gs.mc(logs,"take",[7]),"collect",[function(log) { return gs.map().add("_id",gs.gp(log,"_id")).add("value",gs.gp(log,"value")).add("mealName",gs.gp(log,"mealName")).add("unit","kcal").add("_createdAt",gs.gp(log,"date")).add("batchName",gs.gp(gSobject.scope,"batchName")); }])); gs.println(gs.plus("nutrition history: ", gs.gp(gSobject.scope,"nutritionLogs"))); return gs.mc(gSobject,"calculateWeeklyCalories",[logs]); }]); } gSobject['generateChartData'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"metrics",[gs.gp(gs.fs('session', this, gSobject),"userId"), "health:nutrition-value", gs.date(), gs.gp(gSobject.scope,"graphPeriod"), function(metricData) { gs.sp(gSobject.scope,"nutritionLabels",gs.gp(metricData,"labels")); return gs.sp(gSobject.scope,"nutritionValues",gs.gp(metricData,"values")); }]); } gSobject['loadGoal'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"listEntries",[gs.gp(gs.fs('session', this, gSobject),"userId"), "health:nutrition:goal", gs.map().add("limit",1).add("sort","_lastUpdated").add("order","desc"), function(logs) { if (!gs.bool(logs)) { return null; }; var goal = logs[0]; return gs.sp(gSobject.scope,"nutritionGoal",gs.elvis(gs.bool(gs.gp(goal,"totalCalories")) , gs.gp(goal,"totalCalories") , 2300)); }]); } gSobject['hasNutritionGoal'] = function(it) { return gs.gp(gSobject.scope,"nutritionGoal") != null; } gSobject['calculateWeeklyCalories'] = function(logs) { var today = gs.mc(gs.mc(gSobject,"moment",[]),"startOf",["day"]); var weekAgo = gs.mc(gs.mc(gSobject,"moment",[today]),"subtract",[6, "days"]); var logsByDay = gs.map(); gs.mc(gs.elvis(gs.bool(logs) , logs , gs.list([])),"each",[function(log) { var logDay = gs.mc(gs.mc(gSobject,"moment",[gs.gp(log,"date")]),"format",["YYYY-MM-DD"]); return (logsByDay[logDay]) = log; }]); for (var i = 0 ; i < 7 ; i++) { var day = gs.mc(gs.mc(gs.mc(this,"moment",[weekAgo], gSobject),"add",[i, "days"]),"format",["YYYY-MM-DD"]); var log = gs.elvis(logsByDay[day] , logsByDay[day] , gs.map()); gs.sp(gSobject.scope,"nutritionThisWeek",gs.gp(gSobject.scope,"nutritionThisWeek") + gs.elvis(gs.bool(gs.gp(log,"value")) , gs.gp(log,"value") , 0)); }; } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function NutritionLogComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'NutritionLogComponent', simpleName: 'NutritionLogComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/nutritionLog" , "/nutritionLog/:id"]); gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.nutrition.log"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"dialog",false); gs.sp(gSobject.scope,"showDateTime",false); gs.sp(gSobject.scope,"image1",gs.map()); gs.sp(gSobject.scope,"image2",gs.map()); gs.sp(gSobject.scope,"image3",gs.map()); gs.mc(gSobject,"prepareImages",[]); gs.sp(gSobject.scope,"mealTypes",gs.list([gs.map().add("label","Breakfast").add("value","breakfast") , gs.map().add("label","Light Meal").add("value","light meal") , gs.map().add("label","Main Meal").add("value","main meal") , gs.map().add("label","Snack").add("value","snack")])); gs.sp(gSobject.scope,"mealIntake",gs.list([gs.map().add("label","Less than 50%").add("value","50") , gs.map().add("label","Between 50% and 100%").add("value","75") , gs.map().add("label","All of it").add("value","100")])); gs.sp(gSobject.scope,"ratingColors",gs.list(["yellow-1" , "yellow-2" , "yellow-3" , "yellow-4" , "yellow-5"])); gs.sp(gSobject.scope,"allowedDates",function(d) { return gs.mc(gs.mc(gSobject,"moment",[d, "YYYY/MM/DD"]),"isSameOrBefore",[gs.mc(gSobject,"moment",[gs.gp(gSobject.scope,"today"), "YYYY/MM/DD"])]); }); gs.sp(gSobject.scope,"entry",gs.map().add("mealName","").add("note","").add("value",null).add("feedback",null).add("mealIntakeValue",null).add("timePicked","breakfast").add("date",gs.mc(gs.mc(gSobject,"moment",[]),"format",["YYYY-MM-DD HH:mm"])).add("ref","nutrition")); gs.sp(gSobject.scope,"toggleGlucose",function(val) { return gs.sp(gs.gp(gSobject.scope,"entry"),"value",(gs.equals(gs.gp(gs.gp(gSobject.scope,"entry"),"value"), val) ? null : val)); }); if (gs.bool(gs.gp(gs.gp(gSobject.route,"params"),"id"))) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"loadEntry",[gs.gp(gs.gp(gSobject.route,"params"),"id"), function(entry) { gs.sp(gSobject.scope,"entry",entry); return gs.sp(gs.gp(gSobject.scope,"entry"),"date",gs.mc(gs.mc(gSobject,"moment",[gs.gp(entry,"date")]),"format",["YYYY-MM-DD HH:mm"])); }]); }; return gs.mc(gSobject,"loadMealPlanData",[]); } gSobject['loadMealPlanData'] = function(it) { if (gs.bool(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"nutritionLogData"))) { gs.sp(gs.gp(gSobject.scope,"entry"),"mealName",gs.elvis(gs.bool(gs.gp(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"nutritionLogData"),"mealName")) , gs.gp(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"nutritionLogData"),"mealName") , "")); gs.sp(gs.gp(gSobject.scope,"entry"),"note",gs.elvis(gs.bool(gs.gp(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"nutritionLogData"),"note")) , gs.gp(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"nutritionLogData"),"note") , "")); gs.sp(gs.gp(gSobject.scope,"entry"),"feedback",gs.elvis(gs.bool(gs.gp(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"nutritionLogData"),"feedback")) , gs.gp(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"nutritionLogData"),"feedback") , "")); gs.sp(gs.gp(gSobject.scope,"entry"),"value",gs.elvis(gs.bool(gs.gp(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"nutritionLogData"),"value")) , gs.gp(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"nutritionLogData"),"value") , null)); gs.sp(gs.gp(gSobject.scope,"entry"),"timePicked",gs.elvis(gs.bool(gs.gp(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"nutritionLogData"),"timePicked")) , gs.gp(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"nutritionLogData"),"timePicked") , "breakfast")); gs.println(gs.gp(gSobject.scope,"entry")); return gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"nutritionLogData",null); }; } gSobject['prepareImages'] = function(it) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataFile"),"findOrCreate",[gs.map().add("_id",null), function(fileObj) { return gs.sp(gSobject.scope,"image1",fileObj); }]); gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataFile"),"findOrCreate",[gs.map().add("_id",null), function(fileObj) { return gs.sp(gSobject.scope,"image2",fileObj); }]); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataFile"),"findOrCreate",[gs.map().add("_id",null), function(fileObj) { return gs.sp(gSobject.scope,"image3",fileObj); }]); } gSobject['logNutrition'] = function(it) { gs.sp(gSobject.scope,"value",gs.gp(gs.gp(gSobject.scope,"entry"),"value")); gs.sp(gSobject.scope,"timePicked",gs.gp(gs.gp(gSobject.scope,"entry"),"timePicked")); gs.sp(gSobject.scope,"mealIntakeValue",gs.gp(gs.gp(gSobject.scope,"entry"),"mealIntakeValue")); gs.sp(gSobject.scope,"mealName",gs.gp(gs.gp(gSobject.scope,"entry"),"mealName")); gs.sp(gSobject.scope,"note",gs.gp(gs.gp(gSobject.scope,"entry"),"note")); gs.sp(gSobject.scope,"feedback",gs.gp(gs.gp(gSobject.scope,"entry"),"feedback")); gs.sp(gSobject.scope,"imageIds",gs.list([gs.gp(gs.gp(gSobject.scope,"image1"),"_id") , gs.gp(gs.gp(gSobject.scope,"image2"),"_id") , gs.gp(gs.gp(gSobject.scope,"image3"),"_id")])); if (!gs.bool(gs.gp(gSobject.scope,"value"))) { gs.mc(gSobject,"notify",["Please select or enter a Nutrition value.", "negative"]); return null; }; gs.sp(gSobject.scope,"date",gs.mc(gs.mc(gSobject,"moment",[gs.gp(gs.gp(gSobject.scope,"entry"),"date"), "YYYY-MM-DD HH:mm"]),"toDate",[])); if (gs.mc(gs.mc(gSobject,"moment",[gs.gp(gSobject.scope,"date")]),"isSame",[gs.mc(gSobject,"moment",[]), "day"])) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "health:nutrition:mealName", gs.gp(gSobject.scope,"mealName")]),"do",[]); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "health:nutrition:note", gs.gp(gSobject.scope,"note")]),"do",[]); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "health:nutrition:value", gs.gp(gSobject.scope,"value")]),"do",[]); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "health:nutrition:timePicked", gs.gp(gSobject.scope,"timePicked")]),"do",[]); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "health:nutrition:mealIntakeValue", gs.gp(gSobject.scope,"mealIntakeValue")]),"do",[]); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "health:nutrition:feedback", gs.gp(gSobject.scope,"feedback")]),"do",[]); }; if (gs.bool(gs.gp(gs.gp(gSobject.route,"params"),"id"))) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"deleteEntry",[gs.gp(gs.gp(gSobject.route,"params"),"id")]),"do",[]); }; gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"addEntryWithFts",[gs.gp(gs.fs('session', this, gSobject),"userId"), "health:nutrition", gs.list(["mealName" , "value" , "timePicked" , "imageIds" , "mealIntakeValue" , "note" , "feedback"]), gs.map().add("mealName",gs.gp(gSobject.scope,"mealName")).add("note",gs.gp(gSobject.scope,"note")).add("feedback",gs.gp(gSobject.scope,"feedback")).add("value",gs.gp(gSobject.scope,"value")).add("timePicked",gs.gp(gSobject.scope,"timePicked")).add("date",gs.gp(gSobject.scope,"date")).add("imageIds",gs.gp(gSobject.scope,"imageIds")).add("mealIntakeValue",gs.gp(gSobject.scope,"mealIntakeValue"))]),"then",[function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"eventListener",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gSobject.scope,"entry")]),"do",[]); gs.mc(gSobject,"saveLastUpdated",[gs.gp(gs.fs('session', this, gSobject),"userId"), "nutrition"]); return gs.sp(gSobject.scope,"dialog",true); }, function(it) { return gs.sp(gSobject.scope,"dialog",true); }]); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"notificationService"),"removeNotification",[gs.gp(gs.fs('session', this, gSobject),"userId"), "trackable:nutrition", "Nutrition"]),"do",[]); return gs.mc(gSobject,"generateAndSaveMotivation",[gs.gp(gs.fs('session', this, gSobject),"userId"), "Nutrition", "health:nutrition:value"]); } gSobject['eventLogMeal'] = function(it) { var feedbackText = (gs.equals(gs.gp(gSobject.scope,"feedback"), "like") ? "👍 liked" : (gs.equals(gs.gp(gSobject.scope,"feedback"), "dislike") ? "👎 disliked" : "")); return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"eventLogService"),"event",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.fs('narrative', this, gSobject), "nutrition", "info"]),"do",[]); } gSobject['handlePopupClick'] = function(it) { return gs.sp(gSobject.scope,"dialog",false); } gSobject['error'] = function(it) { return gs.mc(gSobject,"notify",["Please fill in all required fields", "negative"]); } gSobject['ruleDate'] = function(val) { return (gs.bool(val) ? true : "Date is required"); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function NutritionInsightComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'NutritionInsightComponent', simpleName: 'NutritionInsightComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/nutritionInsight" , "/nutritionInsight/:id"]); gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.nutrition.insight"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"nutritionLogs",gs.list([])); gs.sp(gSobject.scope,"batchName","health:nutrition"); gs.sp(gSobject.scope,"columns",gs.list([gs.map().add("name","mealName").add("label","Meal").add("field","mealName").add("align","left").add("sortable",true) , gs.map().add("name","mealIntakeValue").add("label","Meal intake").add("field","mealIntakeValue").add("align","right").add("sortable",true) , gs.map().add("name","value").add("label","Calories").add("field","value").add("align","right").add("sortable",true) , gs.map().add("name","timePicked").add("label","Time Picked").add("field","timePicked").add("align","right").add("sortable",true) , gs.map().add("name","note").add("label","Note").add("field","note").add("align","right").add("sortable",true) , gs.map().add("name","date").add("label","Date").add("field","_createdAt").add("align","right").add("sortable",true)])); return gs.mc(gSobject,"fetchNutritionLogs",[]); } gSobject['fetchNutritionLogs'] = function(it) { gs.sp(gSobject.scope,"nutrition",""); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"listEntries",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gSobject.scope,"batchName"), gs.map().add("limit",7), function(logs) { gs.println(gs.plus("logs", logs)); gs.sp(gSobject.scope,"nutritionLogs",gs.mc(gs.mc(logs,"take",[7]),"collect",[function(log) { var dateStr = gs.mc(gs.date(gs.gp(log,"date")),"format",["yyyy-MM-dd HH:mm"]); return gs.map().add("mealName",gs.gp(log,"mealName")).add("note",gs.gp(log,"note")).add("value",gs.gp(log,"value")).add("mealIntakeValue",gs.gp(log,"mealIntakeValue")).add("unit","kcal").add("timePicked",gs.gp(log,"timePicked")).add("note",gs.gp(log,"note")).add("_createdAt",dateStr); }])); return gs.println(gs.plus("nutrition history: ", gs.gp(gSobject.scope,"nutritionLogs"))); }]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function NutritionDetailComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'NutritionDetailComponent', simpleName: 'NutritionDetailComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/nutritionDetail" , "/nutritionDetail/:id"]); gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.nutrition.detail"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"entryId",gs.gp(gs.gp(gSobject.route,"params"),"id")); gs.sp(gSobject.scope,"entry",gs.map()); gs.sp(gSobject.scope,"image1",gs.map()); gs.sp(gSobject.scope,"image2",gs.map()); gs.sp(gSobject.scope,"image3",gs.map()); return gs.mc(gSobject,"loadNutritionLog",[gs.gp(gSobject.scope,"entryId")]); } gSobject['loadNutritionLog'] = function(entryId) { if (!gs.bool(entryId)) { return null; }; return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"loadEntry",[gs.gp(gs.gp(gSobject.route,"params"),"id"), function(entry) { gs.sp(gSobject.scope,"entry",entry); gs.sp(gs.gp(gSobject.scope,"entry"),"date",gs.mc(gs.mc(gSobject,"moment",[gs.gp(entry,"date")]),"format",["YYYY-MM-DD HH:mm"])); return gs.mc(gSobject,"loadImages",[gs.gp(entry,"imageIds")]); }]); } gSobject['loadImages'] = function(ids) { return gs.mc(ids,"eachWithIndex",[function(id, index) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataFile"),"findOne",[gs.map().add("_id",id), function(fileObj) { (gSobject.scope["image" + (gs.plus(index, 1)) + ""]) = fileObj; return gs.println("image" + (gs.plus(index, 1)) + ": " + (fileObj) + ""); }]); }], null, true); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function NutritionGoalComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'NutritionGoalComponent', simpleName: 'NutritionGoalComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/nutritionGoal"; gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.nutrition.goal"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"nutritionGoalCalories",2300); gs.sp(gSobject.scope,"caloriesGoalId",null); gs.sp(gSobject.scope,"successDialog",false); return gs.mc(gSobject,"loadGoal",[]); } gSobject['loadGoal'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"listEntries",[gs.gp(gs.fs('session', this, gSobject),"userId"), "health:nutrition:goal", gs.map().add("limit",1).add("sort","_lastUpdated").add("order","desc"), function(logs) { if (!gs.bool(logs)) { return null; }; var goal = logs[0]; gs.println(logs); gs.sp(gSobject.scope,"nutritionGoalCalories",gs.gp(goal,"totalCalories")); return gs.sp(gSobject.scope,"caloriesGoalId",gs.gp(goal,"_id")); }]); } gSobject['saveGoal'] = function(it) { if (gs.bool(gs.gp(gSobject.scope,"caloriesGoalId"))) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"deleteEntry",[gs.gp(gSobject.scope,"caloriesGoalId")]); }; return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"addEntryWithFts",[gs.gp(gs.fs('session', this, gSobject),"userId"), "health:nutrition:goal", gs.list(["totalCalories" , "value"]), gs.map().add("totalCalories",gs.gp(gSobject.scope,"nutritionGoalCalories")).add("value",gs.gp(gSobject.scope,"nutritionGoalCalories"))]),"then",[function(it) { gs.mc(gSobject,"eventLogGoal",[]); return gs.sp(gSobject.scope,"successDialog",true); }, function(error) { return gs.mc(gSobject,"notify",["Failed to save calories goal.", "negative"]); }]); } gSobject['eventLogGoal'] = function(it) { var narrative = "Logged daily nutrition goal: " + (gs.gp(gSobject.scope,"nutritionGoalCalories")) + " kcal"; return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"eventLogService"),"event",[gs.gp(gs.fs('session', this, gSobject),"userId"), narrative, "nutrition:goal", "info"]),"do",[]); } gSobject['formatGoalDisplay'] = function(it) { return "" + (gs.gp(gSobject.scope,"nutritionGoalCalories")) + " kcal"; } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function NutritionMealplanComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'NutritionMealplanComponent', simpleName: 'NutritionMealplanComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/nutritionMealplan"; gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.nutrition.mealplan"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"isEditMode",false); gs.sp(gSobject.scope,"activeTab","weekly"); gs.sp(gSobject.scope,"activeDate",gs.mc(gs.mc(gSobject,"moment",[]),"format",["YYYY/MM/DD"])); gs.sp(gSobject.scope,"recipeDialog",false); gs.sp(gSobject.scope,"selectedRecipe",null); gs.sp(gSobject.scope,"totalCalories",0); gs.sp(gSobject.scope,"combinedIngredients",gs.list([])); gs.sp(gSobject.scope,"checkedIngredients",gs.map()); gs.sp(gSobject.scope,"mealPlan",gs.list([])); gs.sp(gSobject.scope,"userProfile",gs.map().add("weight",0).add("gender","").add("allergies",gs.list([])).add("conditions",gs.list([])).add("mealPreference","").add("blacklist",gs.list([]))); gs.sp(gSobject.scope,"mealTypes",gs.list(["Breakfast" , "Snack" , "Light meal" , "Main meal"])); gs.sp(gSobject.scope,"mealOptions",gs.map()); gs.mc(gSobject,"loadUserAllergies",[]); return gs.mc(gSobject,"loadUserProfile",[]); } gSobject['onDateChange'] = function(val) { if (!gs.bool(val)) { gs.sp(gSobject.scope,"activeDate",gs.mc(gs.mc(gSobject,"moment",[]),"format",["YYYY/MM/DD"])); return null; }; return gs.mc(gSobject,"loadSavedMealSelection",[]); } gSobject['loadUserProfile'] = function(it) { var promises = gs.list([gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:body_weight:value"]) , gs.mc(gs.gp(gs.fs('o', this, gSobject),"medicalCalculationService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "person:gender"]) , gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "health:nutrition:allergens"]) , gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "health:nutrition:conditions"]) , gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "health:nutrition:dietarypreference"]) , gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "health:nutrition:blacklist"])]); return gs.mc(gs.mc(gs.fs('Promise', this, gSobject),"all",[promises]),"then",[function(results) { gs.sp(gs.gp(gSobject.scope,"userProfile"),"weight",(results[0])); gs.sp(gs.gp(gSobject.scope,"userProfile"),"gender",(results[1])); gs.sp(gs.gp(gSobject.scope,"userProfile"),"allergies",gs.elvis(results[2] , results[2] , gs.list([]))); gs.sp(gs.gp(gSobject.scope,"userProfile"),"conditions",gs.elvis(results[3] , results[3] , gs.list([]))); gs.sp(gs.gp(gSobject.scope,"userProfile"),"mealPreference",(results[4])); gs.sp(gs.gp(gSobject.scope,"userProfile"),"blacklist",gs.elvis(results[5] , results[5] , gs.list([]))); return gs.mc(gSobject,"loadMealPlan",[gs.gp(gs.gp(gSobject.scope,"userProfile"),"gender"), gs.gp(gs.gp(gSobject.scope,"userProfile"),"weight")]); }]); } gSobject['loadMealPlan'] = function(gender, weight) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"loadMealplanForUser",[gender, weight, function(data) { gs.sp(gSobject.scope,"mealPlan",data); gs.println("Meal Plan Data------"); gs.println(gs.gp(gSobject.scope,"mealPlan")); gs.mc(gSobject,"organizeMealsByType",[]); gs.mc(gSobject,"loadSavedMealSelection",[]); return gs.mc(gSobject,"generateShoppingList",[]); }]); } gSobject['containsAllergen'] = function(recipe) { if ((!gs.bool(gs.gp(gs.gp(gSobject.scope,"userProfile"),"allergies"))) || (gs.equals(gs.mc(gs.gp(gs.gp(gSobject.scope,"userProfile"),"allergies"),"size",[]), 0))) { return false; }; if ((!gs.bool(gs.gp(recipe,"allergies"))) || (gs.equals(gs.mc(gs.gp(recipe,"allergies"),"size",[]), 0))) { return false; }; var userAllergensLower = gs.mc(gs.gp(gs.gp(gSobject.scope,"userProfile"),"allergies"),"collect",[function(it) { return gs.mc(gs.mc(gs.mc(it,"toString",[]),"toLowerCase",[]),"trim",[]); }]); for (_i35 = 0, recipeAllergen = gs.gp(recipe,"allergies")[0]; _i35 < gs.gp(recipe,"allergies").length; recipeAllergen = gs.gp(recipe,"allergies")[++_i35]) { var recipeAllergenName = gs.mc(gs.mc(gs.mc(gs.gp(recipeAllergen,"name"),"toString",[], null, true),"toLowerCase",[], null, true),"trim",[], null, true); if (!gs.bool(recipeAllergenName)) { continue; }; for (_i36 = 0, userAllergen = userAllergensLower[0]; _i36 < userAllergensLower.length; userAllergen = userAllergensLower[++_i36]) { if ((gs.mc(recipeAllergenName,"contains",[userAllergen])) || (gs.mc(userAllergen,"contains",[recipeAllergenName]))) { gs.println("Allergen match found: " + (recipeAllergenName) + " matches " + (userAllergen) + ""); return true; }; }; }; return false; } gSobject['containsBlacklistedIngredient'] = function(recipe) { if ((!gs.bool(gs.gp(gs.gp(gSobject.scope,"userProfile"),"blacklist"))) || (gs.equals(gs.mc(gs.gp(gs.gp(gSobject.scope,"userProfile"),"blacklist"),"size",[]), 0))) { return false; }; if ((!gs.bool(gs.gp(recipe,"ingredients"))) || (gs.equals(gs.mc(gs.gp(recipe,"ingredients"),"size",[]), 0))) { return false; }; var userBlacklistLower = gs.mc(gs.gp(gs.gp(gSobject.scope,"userProfile"),"blacklist"),"collect",[function(it) { return gs.mc(gs.mc(gs.mc(it,"toString",[]),"toLowerCase",[]),"trim",[]); }]); for (_i37 = 0, ingredient = gs.gp(recipe,"ingredients")[0]; _i37 < gs.gp(recipe,"ingredients").length; ingredient = gs.gp(recipe,"ingredients")[++_i37]) { var ingredientName = gs.mc(gs.mc(gs.mc(gs.gp(ingredient,"name"),"toString",[], null, true),"toLowerCase",[], null, true),"trim",[], null, true); if (!gs.bool(ingredientName)) { continue; }; for (_i38 = 0, blacklistItem = userBlacklistLower[0]; _i38 < userBlacklistLower.length; blacklistItem = userBlacklistLower[++_i38]) { if ((gs.mc(ingredientName,"contains",[blacklistItem])) || (gs.mc(blacklistItem,"contains",[ingredientName]))) { gs.println("Blacklisted ingredient found: " + (ingredientName) + " matches " + (blacklistItem) + ""); return true; }; }; }; return false; } gSobject['organizeMealsByType'] = function(it) { gs.sp(gSobject.scope,"mealOptions",gs.map()); gs.mc(gs.mc(gs.gp(gs.gp(gSobject.scope,"mealPlan"),"recipes",true),"groupBy",[function(it) { return gs.gp(it,"type"); }], null, true),"each",[function(mealType, recipes) { if (gs.gSin(mealType, gs.gp(gSobject.scope,"mealTypes"))) { var filteredRecipes = gs.mc(recipes,"findAll",[function(recipe) { return (!gs.bool(gs.mc(gSobject,"containsAllergen",[recipe]))) && (!gs.bool(gs.mc(gSobject,"containsBlacklistedIngredient",[recipe]))); }]); (gs.gp(gSobject.scope,"mealOptions")[mealType]) = gs.map().add("current",0).add("recipes",filteredRecipes); return gs.println("Filtered " + (mealType) + ": " + (gs.mc(recipes,"size",[])) + " recipes -> " + (gs.mc(filteredRecipes,"size",[])) + " recipes (allergens & blacklist)"); }; }]); return gs.mc(gs.gp(gSobject.scope,"mealTypes"),"each",[function(mealType) { if (!gs.bool(gs.gp(gSobject.scope,"mealOptions")[mealType])) { return (gs.gp(gSobject.scope,"mealOptions")[mealType]) = gs.map().add("current",0).add("recipes",gs.list([])); }; }]); } gSobject['loadUserAllergies'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:allergic:food", function(data) { return gs.println(gs.plus("Allergies:", data)); }]); } gSobject['generateShoppingList'] = function(it) { var ingredientsMap = gs.map(); gs.mc(gs.gp(gSobject.scope,"mealTypes"),"each",[function(mealType) { var meal = gs.mc(gSobject,"currentMeal",[mealType]); if ((gs.bool(meal)) && (gs.bool(gs.gp(meal,"ingredients")))) { return gs.mc(gs.gp(meal,"ingredients"),"each",[function(ingredient) { var name = gs.mc(gs.mc(gs.gp(ingredient,"name"),"toString",[], null, true),"trim",[], null, true); if (!gs.bool(name)) { return null; }; var amountRaw = gs.elvis(gs.bool(gs.gp(ingredient,"amount")) , gs.gp(ingredient,"amount") , gs.elvis(gs.bool(gs.gp(ingredient,"quantity")) , gs.gp(ingredient,"quantity") , gs.elvis(gs.bool(gs.gp(ingredient,"value")) , gs.gp(ingredient,"value") , gs.elvis(gs.bool(gs.gp(ingredient,"amountPerServing")) , gs.gp(ingredient,"amountPerServing") , 0)))); var amount = (gs.mc(this,"parseFloat",[amountRaw], gSobject)) || (0); var unit = gs.mc(gs.mc(gs.mc(gs.elvis(gs.bool(gs.gp(ingredient,"unit")) , gs.gp(ingredient,"unit") , gs.elvis(gs.bool(gs.gp(ingredient,"unitOfMeasure")) , gs.gp(ingredient,"unitOfMeasure") , gs.elvis(gs.bool(gs.gp(ingredient,"measurementUnit")) , gs.gp(ingredient,"measurementUnit") , ""))),"toString",[]),"toLowerCase",[]),"trim",[]); var key = "" + (name) + "|" + (unit) + ""; if (gs.mc(ingredientsMap,"containsKey",[key])) { return gs.sp((ingredientsMap[key]),"amount",gs.gp(ingredientsMap[key],"amount") + amount); } else { return (ingredientsMap[key]) = gs.map().add("name",gs.gp(ingredient,"name")).add("amount",amount).add("unit",gs.elvis(gs.bool(gs.gp(ingredient,"unit")) , gs.gp(ingredient,"unit") , gs.elvis(gs.bool(gs.gp(ingredient,"unitOfMeasure")) , gs.gp(ingredient,"unitOfMeasure") , gs.elvis(gs.bool(gs.gp(ingredient,"measurementUnit")) , gs.gp(ingredient,"measurementUnit") , "")))); }; }]); }; }]); gs.sp(gSobject.scope,"combinedIngredients",gs.mc(gs.mc(ingredientsMap,"values",[]),"sort",[function(it) { return gs.gp(it,"name"); }])); gs.sp(gSobject.scope,"checkedIngredients",gs.map()); gs.mc(gs.gp(gSobject.scope,"combinedIngredients"),"each",[function(ingredient) { return (gs.gp(gSobject.scope,"checkedIngredients")[gs.gp(ingredient,"name")]) = false; }]); return gs.mc(gSobject,"loadCheckedIngredients",[]); } gSobject['saveCheckedIngredients'] = function(it) { var checkedList = gs.list([]); var keys = gs.mc(Object,"keys",[gs.gp(gSobject.scope,"checkedIngredients")]); for (var i = 0 ; i < gs.gp(keys,"length") ; i++) { var name = keys[i]; if (gs.gp(gSobject.scope,"checkedIngredients")[name]) { gs.mc(checkedList,"push",[name]); }; }; return gs.mc(gs.fs('localStorage', this, gSobject),"setItem",[gs.plus("checkedIngredients_", gs.gp(gSobject.scope,"activeDate")), gs.mc(gs.fs('JSON', this, gSobject),"stringify",[checkedList])]); } gSobject['loadCheckedIngredients'] = function(it) { var savedData = gs.mc(gs.fs('localStorage', this, gSobject),"getItem",[gs.plus("checkedIngredients_", gs.gp(gSobject.scope,"activeDate"))]); if (gs.bool(savedData)) { var checkedList = gs.mc(gs.fs('JSON', this, gSobject),"parse",[savedData]); for (var i = 0 ; i < gs.gp(checkedList,"length") ; i++) { (gs.gp(gSobject.scope,"checkedIngredients")[(checkedList[i])]) = true; }; }; } gSobject['calculateTotalCalories'] = function(it) { var total = 0; gs.mc(gs.gp(gSobject.scope,"mealOptions"),"each",[function(mealType, data) { if (gs.mc(gs.gp(data,"recipes"),"size",[], null, true) > 0) { return total += gs.elvis(gs.bool(gs.gp(gs.gp(data,"recipes")[gs.gp(data,"current")],"totalCaloriesPerServing")) , gs.gp(gs.gp(data,"recipes")[gs.gp(data,"current")],"totalCaloriesPerServing") , 0); }; }]); return total; } gSobject['currentMeal'] = function(mealType) { var mealData = gs.gp(gSobject.scope,"mealOptions")[mealType]; if (((!gs.bool(mealData)) || (!gs.bool(gs.gp(mealData,"recipes")))) || (gs.equals(gs.mc(gs.gp(mealData,"recipes"),"size",[]), 0))) { return null; }; return gs.gp(mealData,"recipes")[gs.gp(mealData,"current")]; } gSobject['hasAvailableRecipes'] = function(mealType) { var mealData = gs.gp(gSobject.scope,"mealOptions")[mealType]; return ((gs.bool(mealData)) && (gs.bool(gs.gp(mealData,"recipes")))) && (gs.mc(gs.gp(mealData,"recipes"),"size",[]) > 0); } gSobject['cycleMealNext'] = function(mealType) { var mealData = gs.gp(gSobject.scope,"mealOptions")[mealType]; if ((!gs.bool(mealData)) || (gs.mc(gs.gp(mealData,"recipes"),"size",[]) <= 1)) { return null; }; gs.sp(mealData,"current",(gs.mod((gs.plus(gs.gp(mealData,"current"), 1)), gs.mc(gs.gp(mealData,"recipes"),"size",[])))); gs.sp(gSobject.scope,"totalCalories",gs.mc(gSobject,"calculateTotalCalories",[])); return gs.mc(gSobject,"generateShoppingList",[]); } gSobject['cycleMealPrevious'] = function(mealType) { var mealData = gs.gp(gSobject.scope,"mealOptions")[mealType]; if ((!gs.bool(mealData)) || (gs.mc(gs.gp(mealData,"recipes"),"size",[]) <= 1)) { return null; }; gs.sp(mealData,"current",(gs.equals(gs.gp(mealData,"current"), 0) ? gs.minus(gs.mc(gs.gp(mealData,"recipes"),"size",[]), 1) : gs.minus(gs.gp(mealData,"current"), 1))); gs.sp(gSobject.scope,"totalCalories",gs.mc(gSobject,"calculateTotalCalories",[])); return gs.mc(gSobject,"generateShoppingList",[]); } gSobject['loadSavedMealSelection'] = function(it) { var selectedDate = gs.mc(gs.mc(gSobject,"moment",[gs.gp(gSobject.scope,"activeDate")]),"format",["YYYY-MM-DD"]); var startOfDay = gs.mc(gs.mc(gs.mc(gSobject,"moment",[selectedDate]),"startOf",["day"]),"toDate",[]); var endOfDay = gs.mc(gs.mc(gs.mc(gSobject,"moment",[selectedDate]),"endOf",["day"]),"toDate",[]); var filter = gs.map().add("date",gs.map().add(">=",startOfDay).add("<",endOfDay)); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"listEntries",[gs.gp(gs.fs('session', this, gSobject),"userId"), "health:nutrition:mealplan:selection", gs.map().add("limit",1), filter, function(entries) { gs.mc(gs.gp(gSobject.scope,"mealTypes"),"each",[function(mealType) { if (gs.gp(gSobject.scope,"mealOptions")[mealType]) { return gs.sp((gs.gp(gSobject.scope,"mealOptions")[mealType]),"current",0); }; }]); if ((gs.bool(entries)) && (gs.mc(entries,"size",[]) > 0)) { var savedSelection = entries[0]; gs.mc(gs.gp(gSobject.scope,"mealTypes"),"each",[function(mealType) { if ((savedSelection[mealType]) && (gs.gp(gSobject.scope,"mealOptions")[mealType])) { var savedRecipeId = savedSelection[mealType]; var recipes = gs.gp(gs.gp(gSobject.scope,"mealOptions")[mealType],"recipes"); var recipeIndex = -1; for (var i = 0 ; i < gs.mc(recipes,"size",[]) ; i++) { if (gs.equals(gs.gp(recipes[i],"_id"), savedRecipeId)) { recipeIndex = i; break; }; }; if (recipeIndex >= 0) { return gs.sp((gs.gp(gSobject.scope,"mealOptions")[mealType]),"current",recipeIndex); }; }; }]); }; gs.sp(gSobject.scope,"totalCalories",gs.mc(gSobject,"calculateTotalCalories",[])); return gs.mc(gSobject,"generateShoppingList",[]); }]); } gSobject['saveMealSelection'] = function(it) { var selectedDate = gs.mc(gs.mc(gSobject,"moment",[gs.gp(gSobject.scope,"activeDate")]),"format",["YYYY-MM-DD"]); var selectionData = gs.map().add("date",gs.mc(gs.mc(gSobject,"moment",[selectedDate]),"toDate",[])); gs.mc(gs.gp(gSobject.scope,"mealTypes"),"each",[function(mealType) { if (gs.mc(gs.gp(gs.gp(gSobject.scope,"mealOptions")[mealType],"recipes",true),"size",[], null, true) > 0) { var currentRecipe = gs.gp(gs.gp(gSobject.scope,"mealOptions")[mealType],"recipes")[gs.gp(gs.gp(gSobject.scope,"mealOptions")[mealType],"current")]; return (selectionData[mealType]) = gs.gp(currentRecipe,"_id"); }; }]); var startOfDay = gs.mc(gs.mc(gs.mc(gSobject,"moment",[selectedDate]),"startOf",["day"]),"toDate",[]); var endOfDay = gs.mc(gs.mc(gs.mc(gSobject,"moment",[selectedDate]),"endOf",["day"]),"toDate",[]); var filter = gs.map().add("date",gs.map().add(">=",startOfDay).add("<",endOfDay)); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"listEntries",[gs.gp(gs.fs('session', this, gSobject),"userId"), "health:nutrition:mealplan:selection", gs.map().add("limit",1), filter, function(existingEntries) { if ((gs.bool(existingEntries)) && (gs.mc(existingEntries,"size",[]) > 0)) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"deleteEntry",[gs.gp(existingEntries[0],"_id")]),"do",[]); }; return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"addEntry",[gs.gp(gs.fs('session', this, gSobject),"userId"), "health:nutrition:mealplan:selection", gs.gp(gSobject.scope,"mealTypes"), selectionData]),"then",[function(it) { return gs.mc(gSobject,"notify",["Meal selection saved", "positive"]); }, function(error) { gs.mc(gSobject,"notify",["Failed to save meal selection", "negative"]); return gs.println("Error saving meal selection: " + (error) + ""); }]); }]); } gSobject['toggleEditMode'] = function(it) { if (gs.bool(gs.gp(gSobject.scope,"isEditMode"))) { gs.mc(gSobject,"saveMealSelection",[]); }; return gs.sp(gSobject.scope,"isEditMode",!gs.gp(gSobject.scope,"isEditMode")); } gSobject['viewRecipe'] = function(mealType) { var currentMeal = gs.mc(gSobject,"currentMeal",[mealType]); if (!gs.bool(currentMeal)) { return null; }; gs.sp(gSobject.scope,"selectedRecipe",currentMeal); return gs.sp(gSobject.scope,"recipeDialog",true); } gSobject['logMeal'] = function(mealType) { var meal = gs.mc(gSobject,"currentMeal",[mealType]); if (!gs.bool(meal)) { gs.mc(gSobject,"notify",["No meal selected", "negative"]); return null; }; var mealTypeMapping = gs.map().add("Breakfast","breakfast").add("Snack","snack").add("Light meal","light meal").add("Main meal","main meal"); gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"nutritionLogData",gs.map().add("mealName",gs.gp(meal,"name")).add("timePicked",gs.elvis(mealTypeMapping[mealType] , mealTypeMapping[mealType] , gs.mc(mealType,"toLowerCase",[]))).add("value",gs.gp(meal,"totalCaloriesPerServing"))); return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/nutritionLog"]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function NutritionFilterComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'NutritionFilterComponent', simpleName: 'NutritionFilterComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/nutritionFilter"; gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.nutrition.filter"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"allergenList",gs.list([])); gs.sp(gSobject.scope,"preferenceList",gs.list([gs.map().add("label","Vegetarian").add("value",0) , gs.map().add("label","Vegan").add("value",1) , gs.map().add("label","Pescatarian").add("value",2) , gs.map().add("label","Omnivore").add("value",3)])); gs.sp(gSobject.scope,"blackList",gs.list([])); gs.sp(gSobject.scope,"userPreference",3); gs.sp(gSobject.scope,"userAllergens",gs.list([])); gs.sp(gSobject.scope,"selectedItems",gs.list([])); gs.sp(gSobject.scope,"currentSelection",null); gs.sp(gSobject.scope,"filteredBlackList",gs.mc(gs.gp(gSobject.scope,"blackList"),"clone",[])); gs.sp(gSobject.scope,"popupOpen",false); gs.sp(gSobject.scope,"conditionsList",gs.list([])); gs.sp(gSobject.scope,"userConditions",gs.list([])); gs.mc(gSobject,"loadMergedDatapoints",[]); gs.mc(gSobject,"loadMergedAllergenDatapoints",[]); gs.mc(gSobject,"loadIngredients",[]); return gs.mc(gSobject,"loadUserMealPreference",[]); } gSobject['loadUserBlacklist'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "health:nutrition:blacklist", function(result) { return gs.sp(gSobject.scope,"selectedItems",gs.mc(gs.mc(gs.gp(gSobject.scope,"blackList"),"findAll",[function(it) { return gs.mc(result,"contains",[gs.gp(it,"label")]); }]),"collect",[function(it) { return gs.gp(it,"value"); }])); }]); } gSobject['loadUserMealPreference'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "health:nutrition:dietarypreference", function(result) { return gs.sp(gSobject.scope,"userPreference",gs.gp(gs.mc(gs.gp(gSobject.scope,"preferenceList"),"find",[function(it) { return gs.equals(gs.gp(it,"label"), result); }]),"value",true)); }]); } gSobject['loadIngredients'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"loadAllIngredients",[function(result) { gs.sp(gSobject.scope,"blackList",result); return gs.mc(gSobject,"loadUserBlacklist",[]); }]); } gSobject['saveMealPreference'] = function(it) { var pref = gs.gp(gs.mc(gs.gp(gSobject.scope,"preferenceList"),"find",[function(it) { return gs.equals(gs.gp(it,"value"), gs.gp(gSobject.scope,"userPreference")); }]),"label",true); return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "health:nutrition:dietarypreference", pref]),"do",[]); } gSobject['filterBlackList'] = function(val, update) { return gs.execCall(update, this, [function(it) { if (gs.equals(val, "")) { return gs.sp(gSobject.scope,"filteredBlackList",gs.mc(gSobject,"loadAvailableItems",[])); } else { var needle = gs.mc(val,"toLowerCase",[]); return gs.sp(gSobject.scope,"filteredBlackList",gs.mc(gs.mc(gSobject,"loadAvailableItems",[]),"findAll",[function(item) { return gs.mc(gs.mc(gs.gp(item,"label"),"toLowerCase",[]),"contains",[needle]); }])); }; }]); } gSobject['loadAvailableItems'] = function(it) { return gs.mc(gs.gp(gSobject.scope,"blackList"),"findAll",[function(item) { return !gs.mc(gs.gp(gSobject.scope,"selectedItems"),"contains",[gs.gp(item,"value")]); }]); } gSobject['onItemSelected'] = function(item) { if ((gs.bool(item)) && (!gs.bool(gs.mc(gs.gp(gSobject.scope,"selectedItems"),"contains",[gs.gp(item,"value")])))) { gs.mc(gs.gp(gSobject.scope,"selectedItems"),"add",[gs.gp(item,"value")]); }; gs.sp(gSobject.scope,"currentSelection",null); gs.sp(gSobject.scope,"filteredBlackList",gs.mc(gSobject,"loadAvailableItems",[])); return gs.mc(gSobject,"saveBlacklist",[]); } gSobject['removeItem'] = function(value) { gs.sp(gSobject.scope,"selectedItems",gs.mc(gs.gp(gSobject.scope,"selectedItems"),"findAll",[function(it) { return it != value; }])); gs.sp(gSobject.scope,"filteredBlackList",gs.mc(gSobject,"loadAvailableItems",[])); return gs.mc(gSobject,"saveBlacklist",[]); } gSobject['saveBlacklist'] = function(it) { var labels = gs.mc(gs.mc(gs.gp(gSobject.scope,"blackList"),"findAll",[function(it) { return gs.mc(gs.gp(gSobject.scope,"selectedItems"),"contains",[gs.gp(it,"value")]); }]),"collect",[function(it) { return gs.gp(it,"label"); }]); return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "health:nutrition:blacklist", labels]),"do",[]); } gSobject['loadSelectedLabels'] = function(it) { return gs.mc(gs.gp(gSobject.scope,"blackList"),"findAll",[function(item) { return gs.mc(gs.gp(gSobject.scope,"selectedItems"),"contains",[gs.gp(item,"value")]); }]); } gSobject['loadMergedDatapoints'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "health:nutrition:conditions", function(savedConditions) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadLabeledDataPointsForOwnerStartingWith",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:full:current_medical", function(data) { gs.sp(gSobject.scope,"conditionsList",gs.list([])); gs.sp(gSobject.scope,"userConditions",gs.list([])); var index = 0; var conditionsToSave = gs.list([]); gs.mc(data,"each",[function(dp) { gs.mc(gs.gp(gSobject.scope,"conditionsList"),'leftShift', gs.list([gs.map().add("label",gs.gp(dp,"label")).add("key",gs.gp(dp,"key")).add("value",index).add("userOption",gs.gp(dp,"value"))])); if (savedConditions != null) { if (gs.mc(savedConditions,"contains",[gs.gp(dp,"label")])) { gs.mc(gs.gp(gSobject.scope,"userConditions"),'leftShift', gs.list([index])); }; } else { if (gs.mc(gs.gp(dp,"value"),"toString",[], null, true)) { gs.mc(gs.gp(gSobject.scope,"userConditions"),'leftShift', gs.list([index])); gs.mc(conditionsToSave,'leftShift', gs.list([gs.gp(dp,"label")])); }; }; return index++; }]); if ((gs.equals(savedConditions, null)) && (gs.bool(conditionsToSave))) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "health:nutrition:conditions", conditionsToSave]),"do",[]); }; gs.println("Loaded " + (gs.mc(data,"size",[])) + " merged datapoints"); gs.println("ConditionsList → " + (gs.gp(gSobject.scope,"conditionsList")) + ""); return gs.println("UserConditions → " + (gs.gp(gSobject.scope,"userConditions")) + ""); }]); }]); } gSobject['loadMergedAllergenDatapoints'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "health:nutrition:allergens", function(savedAllergens) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadLabeledDataPointsForOwnerStartingWith",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:allergic:food", function(data) { gs.sp(gSobject.scope,"userAllergens",gs.list([])); gs.sp(gSobject.scope,"allergenList",gs.list([])); var index = 0; var allergensToSave = gs.list([]); var filtered = gs.mc(data,"findAll",[function(dp) { return gs.mc(gs.mc(gs.mc(gs.gp(dp,"label"),"toString",[], null, true),"trim",[], null, true),"toLowerCase",[], null, true) != "other"; }]); gs.mc(filtered,"each",[function(dp) { gs.mc(gs.gp(gSobject.scope,"allergenList"),'leftShift', gs.list([gs.map().add("label",gs.gp(dp,"label")).add("key",gs.gp(dp,"key")).add("value",index).add("userOption",gs.gp(dp,"value"))])); if (savedAllergens != null) { if (gs.mc(savedAllergens,"contains",[gs.gp(dp,"label")])) { gs.mc(gs.gp(gSobject.scope,"userAllergens"),'leftShift', gs.list([index])); }; } else { if (gs.mc(gs.gp(dp,"value"),"toString",[], null, true)) { gs.mc(gs.gp(gSobject.scope,"userAllergens"),'leftShift', gs.list([index])); gs.mc(allergensToSave,'leftShift', gs.list([gs.gp(dp,"label")])); }; }; return index++; }]); if ((gs.equals(savedAllergens, null)) && (gs.bool(allergensToSave))) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "health:nutrition:allergens", allergensToSave]),"do",[]); }; gs.println("Loaded " + (gs.mc(filtered,"size",[])) + " allergen datapoints"); gs.println("allergenList → " + (gs.gp(gSobject.scope,"allergenList")) + ""); return gs.println("userAllergens → " + (gs.gp(gSobject.scope,"userAllergens")) + ""); }]); }]); } gSobject['saveUserConditions'] = function(it) { var selectedLabels = gs.mc(gs.mc(gs.gp(gSobject.scope,"conditionsList"),"findAll",[function(condition) { return gs.mc(gs.gp(gSobject.scope,"userConditions"),"contains",[gs.gp(condition,"value")]); }]),"collect",[function(it) { return gs.gp(it,"label"); }]); return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "health:nutrition:conditions", selectedLabels]),"do",[]); } gSobject['saveUserAllergens'] = function(it) { var selectedLabels = gs.mc(gs.mc(gs.gp(gSobject.scope,"allergenList"),"findAll",[function(allergen) { return gs.mc(gs.gp(gSobject.scope,"userAllergens"),"contains",[gs.gp(allergen,"value")]); }]),"collect",[function(it) { return gs.gp(it,"label"); }]); return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "health:nutrition:allergens", selectedLabels]),"do",[]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function FitnessCustomisationComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'FitnessCustomisationComponent', simpleName: 'FitnessCustomisationComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/fitnessCustomisation"; gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.fitness.customisation"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"workoutTypes",gs.list([gs.map().add("name","Upper Body Strength").add("code","1").add("icon","fitness_center") , gs.map().add("name","Lower Body Strength").add("code","2").add("icon","airline_seat_recline_extra") , gs.map().add("name","Core and Stability").add("code","3").add("icon","sports_gymnastics") , gs.map().add("name","Cardio and HIIT").add("code","4").add("icon","directions_run") , gs.map().add("name","Flexibility and Mobility").add("code","5").add("icon","accessibility_new") , gs.map().add("name","Full Body and Functional").add("code","6").add("icon","self_improvement")])); gs.sp(gSobject.scope,"workoutType",(gs.gp(gSobject.scope,"workoutTypes")[0])); gs.sp(gSobject.scope,"content",gs.list([])); gs.sp(gSobject.scope,"allWorkouts",gs.map()); gs.sp(gSobject.scope,"userPlaylist",gs.list([])); gs.sp(gSobject.scope,"userPlaylistCount",0); gs.sp(gSobject.scope,"showVideoDialog",false); gs.sp(gSobject.scope,"selectedVideo",null); gs.sp(gSobject.scope,"selectedVideoSrc",null); gs.sp(gSobject.scope,"selectedVideoThumbnail",null); gs.mc(gSobject,"loadContent",[]); return gs.mc(gSobject,"loadUserPlaylist",[]); } gSobject['selectWorkoutType'] = function(type) { return gs.sp(gSobject.scope,"workoutType",type); } gSobject['loadContent'] = function(it) { return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"mediaContent"),"find",[gs.map().add("badges",gs.map().add("code",gs.map().add("in",gs.list(["1" , "2" , "3" , "4" , "5" , "6"]))))]),"expand",[1, function(results) { gs.sp(gSobject.scope,"content",gs.elvis(gs.bool(results) , results , gs.list([]))); gs.sp(gSobject.scope,"allWorkouts",gs.map()); return gs.mc(gs.gp(gSobject.scope,"workoutTypes"),"each",[function(wtype) { return (gs.gp(gSobject.scope,"allWorkouts")[gs.gp(wtype,"code")]) = gs.mc(gs.mc(gs.gp(gSobject.scope,"content"),"findAll",[function(media) { return gs.mc(gs.gp(media,"badges"),"find",[function(badge) { return gs.equals(gs.gp(badge,"code"), gs.gp(wtype,"code")); }], null, true); }]),"collect",[function(media) { gs.sp(media,"section",gs.gp(wtype,"name")); gs.sp(media,"badgeCode",gs.gp(wtype,"code")); return media; }]); }]); }]); } gSobject['loadUserPlaylist'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "health:fitness:workout:user_playlist", function(playlist) { gs.sp(gSobject.scope,"userPlaylist",gs.elvis(gs.bool(playlist) , playlist , gs.list([]))); return gs.sp(gSobject.scope,"userPlaylistCount",gs.mc(gs.gp(gSobject.scope,"userPlaylist"),"size",[])); }]); } gSobject['saveUserPlaylist'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "health:fitness:workout:user_playlist", gs.gp(gSobject.scope,"userPlaylist")]),"do",[]); return gs.sp(gSobject.scope,"userPlaylistCount",gs.mc(gs.gp(gSobject.scope,"userPlaylist"),"size",[])); } gSobject['loadCurrentVideos'] = function(it) { var code = gs.gp(gs.gp(gSobject.scope,"workoutType"),"code"); return gs.elvis(gs.gp(gSobject.scope,"allWorkouts")[code] , gs.gp(gSobject.scope,"allWorkouts")[code] , gs.list([])); } gSobject['loadUserPlaylistVideos'] = function(it) { return gs.gp(gSobject.scope,"userPlaylist"); } gSobject['handleMediaBanner'] = function(media) { if (!gs.bool(media)) { return ""; }; if (gs.bool(gs.gp(media,"preview"))) { return "/media-cache/filePreview/" + (gs.gp(media,"_id")) + "/preview/" + (gs.gp(media,"_lastUpdated")) + "/" + (gs.gp(gs.gp(media,"banner"),"filename",true)) + ""; }; if (gs.bool(gs.gp(media,"file"))) { return "/media-cache/filePreview/" + (gs.gp(media,"_id")) + "/file/" + (gs.gp(media,"_lastUpdated")) + "/" + (gs.gp(gs.gp(media,"banner"),"filename",true)) + ""; }; if (gs.bool(gs.gp(media,"banner"))) { return "/media-cache/filePreview/" + (gs.gp(media,"_id")) + "/banner/" + (gs.gp(media,"_lastUpdated")) + "/" + (gs.gp(gs.gp(media,"banner"),"filename",true)) + ""; }; return "/media-cache/filePreview/" + (gs.gp(media,"_id")) + "/preview/" + (gs.gp(media,"_lastUpdated")) + "/" + (gs.gp(gs.gp(media,"banner"),"filename",true)) + ""; } gSobject['handleVideoClick'] = function(media) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"mediaContentAppService"),"mediaUserContentByName",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(media,"name"), function(data) { gs.sp(gSobject.scope,"selectedVideo",data); gs.sp(gs.gp(gSobject.scope,"selectedVideo"),"section",gs.gp(media,"section")); gs.sp(gSobject.scope,"selectedVideoSrc","/media-cache/fileStream/" + (gs.gp(data,"_id")) + "/file/" + (gs.gp(data,"_lastUpdated")) + "/" + (gs.gp(gs.gp(data,"file"),"filename")) + ""); gs.sp(gSobject.scope,"selectedVideoThumbnail","/media-cache/filePreview/" + (gs.gp(data,"_id")) + "/file/" + (gs.gp(gs.gp(data,"file"),"filename")) + ""); gs.sp(gSobject.scope,"showVideoDialog",true); return gs.mc(gSobject,"nextTick",[function(it) { return gs.mc(gSobject,"playVideoInDialog",[]); }]); }]); } gSobject['playVideoInDialog'] = function(it) { gs.mc(gSobject,"getRefs",[]); var videoPlayerRef = gSobject.refs["dialogVideoPlayer"]; if ((gs.bool(videoPlayerRef)) && (videoPlayerRef[0])) { gs.mc(videoPlayerRef[0],"reset",[]); return gs.mc(gSobject,"nextTick",[function(it) { return gs.mc(videoPlayerRef[0],"play",[]); }]); }; } gSobject['closeVideoDialog'] = function(it) { gs.mc(gSobject,"getRefs",[]); var videoPlayerRef = gSobject.refs["dialogVideoPlayer"]; if ((gs.bool(videoPlayerRef)) && (videoPlayerRef[0])) { gs.mc(videoPlayerRef[0],"pause",[]); gs.mc(videoPlayerRef[0],"reset",[]); }; gs.sp(gSobject.scope,"showVideoDialog",false); gs.sp(gSobject.scope,"selectedVideo",null); gs.sp(gSobject.scope,"selectedVideoSrc",null); return gs.sp(gSobject.scope,"selectedVideoThumbnail",null); } gSobject['isVideoInPlaylist'] = function(media) { return gs.mc(gs.gp(gSobject.scope,"userPlaylist"),"find",[function(it) { return gs.equals(gs.gp(it,"_id"), gs.gp(media,"_id")); }]) != null; } gSobject['toggleVideoInPlaylist'] = function(media) { if (gs.mc(gSobject,"isVideoInPlaylist",[media])) { return gs.mc(gSobject,"removeVideoFromPlaylist",[media]); } else { return gs.mc(gSobject,"addVideoToPlaylist",[media]); }; } gSobject['addVideoToPlaylist'] = function(media) { if (!gs.bool(gs.mc(gSobject,"isVideoInPlaylist",[media]))) { gs.mc(gs.gp(gSobject.scope,"userPlaylist"),"add",[media]); gs.mc(gSobject,"saveUserPlaylist",[]); return gs.mc(gSobject,"notify",["Added " + (gs.gp(media,"label")) + " to playlist", "positive"]); }; } gSobject['removeVideoFromPlaylist'] = function(media) { gs.mc(gs.gp(gSobject.scope,"userPlaylist"),"removeAll",[function(it) { return gs.equals(gs.gp(it,"_id"), gs.gp(media,"_id")); }]); gs.mc(gSobject,"saveUserPlaylist",[]); return gs.mc(gSobject,"notify",["Removed " + (gs.gp(media,"label")) + " from playlist", "info"]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function QrCodeComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'QrCodeComponent', simpleName: 'QrCodeComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/qrcode" , "/qrcode/:url"]); gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "qrcode"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"url","https://admin.rxme.office.i3zone.com/rxmeExport/share/" + (gs.gp(gs.fs('session', this, gSobject),"userId")) + ""); gs.sp(gSobject.scope,"email",""); return gs.sp(gSobject.scope,"sending",false); } gSobject['sendReport'] = function(it) { gs.sp(gSobject.scope,"sending",true); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"emailService"),"sendEmailTemplate",[gs.gp(gSobject.scope,"email"), "rxme.medical.records", gs.map().add("username",gs.gp(gSobject.scope,"email")).add("name","" + (gs.gp(gs.gp(gs.fs('session', this, gSobject),"user"),"name")) + " " + (gs.gp(gs.gp(gs.fs('session', this, gSobject),"user"),"surname")) + "").add("url",gs.gp(gSobject.scope,"url")), function(result) { gs.sp(gSobject.scope,"sending",false); gs.mc(gSobject,"notify",["Report sent successfully!", "positive"]); return gs.sp(gSobject.scope,"email",null); }]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function CordovaCalendar() { var gSobject = gs.init('CordovaCalendar'); gSobject.clazz = { name: 'CordovaCalendar', simpleName: 'CordovaCalendar'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject['createEvent'] = function(title, location, notes, startDate, endDate, success, error) { if (success === undefined) success = function(it) { }; if (error === undefined) error = function(it) { }; return gs.mc(gSobject,"nativeCreateEvent",[title, location, notes, startDate, endDate, success, error]); } gSobject['createEventInteractively'] = function(title, location, notes, startDate, endDate, success, error) { if (success === undefined) success = function(it) { }; if (error === undefined) error = function(it) { }; return gs.mc(gSobject,"nativeCreateEventInteractively",[title, location, notes, startDate, endDate, success, error]); } gSobject['findEvent'] = function(title, location, notes, startDate, endDate, success, error) { if (success === undefined) success = function(it) { }; if (error === undefined) error = function(it) { }; return gs.mc(gSobject,"nativeFindEvent",[title, location, notes, startDate, endDate, success, error]); } gSobject['deleteEvent'] = function(title, location, notes, startDate, endDate, success, error) { if (success === undefined) success = function(it) { }; if (error === undefined) error = function(it) { }; return gs.mc(gSobject,"nativeDeleteEvent",[title, location, notes, startDate, endDate, success, error]); } gSobject['listCalendars'] = function(success, error) { if (success === undefined) success = function(it) { }; if (error === undefined) error = function(it) { }; return gs.mc(gSobject,"nativeListCalendars",[success, error]); } gSobject['openCalendar'] = function(date) { if (date === undefined) date = null; return gs.mc(gSobject,"nativeOpenCalendar",[date]); } gSobject.nativeCreateEvent = function(title, location, notes, startDate, endDate, success, error) { if (window.plugins && window.plugins.calendar) { window.plugins.calendar.createEvent(title, location, notes, startDate, endDate, success, error); } else { if (error) error('Calendar not available'); } } gSobject.nativeCreateEventInteractively = function(title, location, notes, startDate, endDate, success, error) { if (window.plugins && window.plugins.calendar) { window.plugins.calendar.createEventInteractively(title, location, notes, startDate, endDate, success, error); } else { if (error) error('Calendar not available'); } } gSobject.nativeFindEvent = function(title, location, notes, startDate, endDate, success, error) { if (window.plugins && window.plugins.calendar) { window.plugins.calendar.findEvent(title, location, notes, startDate, endDate, success, error); } else { if (success) success([]); } } gSobject.nativeDeleteEvent = function(title, location, notes, startDate, endDate, success, error) { if (window.plugins && window.plugins.calendar) { window.plugins.calendar.deleteEvent(title, location, notes, startDate, endDate, success, error); } else { if (error) error('Calendar not available'); } } gSobject.nativeListCalendars = function(success, error) { if (window.plugins && window.plugins.calendar) { window.plugins.calendar.listCalendars(success, error); } else { if (success) success([]); } } gSobject.nativeOpenCalendar = function(date) { if (window.plugins && window.plugins.calendar) { window.plugins.calendar.openCalendar(date); } } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function DymicoChatJsService() { var gSobject = gs.init('DymicoChatJsService'); gSobject.clazz = { name: 'DymicoChatJsService', simpleName: 'DymicoChatJsService'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; Object.defineProperty(gSobject, 'MAX_ATTACHMENT_SIZE_BYTES', { get: function() { return DymicoChatJsService.MAX_ATTACHMENT_SIZE_BYTES; }, set: function(gSval) { DymicoChatJsService.MAX_ATTACHMENT_SIZE_BYTES = gSval; }, enumerable: true }); gSobject.db = null; gSobject.subId = null; gSobject.sub = gs.map(); gSobject.messages = gs.list([]); gSobject['loadSub'] = function(chatMemberLinkId, callback) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"dymicoChatService"),"loadChatMemberLink",[chatMemberLinkId, function(subIn) { gs.mc(gSobject,"unsubscribe",[]); gSobject.subId = gs.gp(subIn,"_id"); var sub = gs.map(); gs.mc(sub,"putAll",[subIn]); return gs.execCall(callback, this, [sub]); }]); } gSobject['unsubscribe'] = function(it) { if (gs.bool(gSobject.subId)) { return gs.execStatic(Utils,'unsubscribe', this,[gSobject.subId]); }; } gSobject['loadChat'] = function(sub, filter, limit, callback) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"dymicoChatService"),"memberMessages",[gs.gp(sub,"_id"), filter, limit, 0, function(chatMap) { return gs.execCall(callback, this, [chatMap]); }]); } gSobject['loadAfter'] = function(subId, filter, date, batchLimit, callback) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"dymicoChatService"),"memberMessagesBySeqAfter",[subId, filter, date, batchLimit, function(chatMap) { return gs.execCall(callback, this, [chatMap]); }]); } gSobject['memberMessagesBySeqBefore'] = function(subId, filter, date, batchLimit, callback) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"dymicoChatService"),"memberMessagesBySeqBefore",[subId, filter, date, batchLimit, function(chatMap) { return gs.execCall(callback, this, [chatMap]); }]); } gSobject['reloadMessage'] = function(updatedMessageId, chatMap, callbackOnAdd) { if (callbackOnAdd === undefined) callbackOnAdd = function(it) { }; return gs.mc(gs.gp(gs.fs('o', this, gSobject),"dymicoChatService"),"message",[updatedMessageId, function(updatedMessage) { var message = gs.mc(gs.gp(chatMap,"messages"),"find",[function(it) { return gs.equals(gs.gp(it,"_id"), updatedMessageId); }]); if (gs.bool(message)) { return gs.mc(message,"putAll",[updatedMessage]); } else { gs.mc(gs.gp(chatMap,"messages"),"add",[updatedMessage]); return gs.execCall(callbackOnAdd, this, []); }; }]); } gSobject['sendMessage'] = function(messageText, html, link, pin, status, sendAt, filesToUpload, onSend) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["DymicoChatJsService.sendMessage:START"]); gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["DEBUG: sendMessage called with messageText: '" + (messageText) + "'"]); if ((((!gs.bool(messageText)) && (!gs.bool(filesToUpload))) && (!gs.bool(html))) && (!gs.bool(pin))) { return null; }; gs.println("messageText"); gs.println(messageText); return gs.mc(gs.mc(gs.gp(gs.gp(gSobject.db,"o"),"chatMessage"),"new",[gs.map().add("subId",gSobject.subId).add("status",status).add("sendAt",sendAt).add("meta",gs.map())]),"save",[function(dbMessage) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[gs.plus("DymicoChatJsService.sendMessage:NEW:", gs.gp(dbMessage,"_id"))]); var message = gs.mc(dbMessage,"clone",[]); if (gs.bool(onSend)) { gs.execCall(onSend, this, [message]); }; if (!gs.bool(messageText)) { messageText = " "; }; return gs.mc(gSobject,"addPart",[message, "pin", pin, 99, function(it) { return gs.mc(gSobject,"addPart",[message, "text", messageText, 100, function(it) { return gs.mc(gSobject,"addPart",[message, "html", html, 101, function(it) { return gs.mc(gSobject,"addPart",[message, "link", link, 102, function(it) { if (!gs.bool(filesToUpload)) { gs.mc(gSobject,"deliverMessages",[]); return null; }; var fileCounter = 0; return gs.mc(filesToUpload,"each",[function(fileData) { return gs.mc(gSobject,"addPartFile",[message, fileData, fileCounter++, function(it) { if (gs.equals(fileData, gs.mc(filesToUpload,"last",[]))) { return gs.mc(gSobject,"deliverMessages",[]); }; }]); }]); }]); }]); }]); }]); }]); } gSobject['deliverMessages'] = function(it) { return gs.mc(gs.mc(gs.gp(gs.gp(gSobject.db,"o"),"chatMessage"),"findAll",[]),"each",[function(message) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"dymicoChatService"),"sendMessage",[message, function(it) { return gs.mc(gs.mc(gs.gp(gs.gp(gSobject.db,"o"),"chatMessagePart"),"find",[gs.map().add("message",gs.gp(message,"_id"))]),"each",[function(part) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"dymicoChatService"),"sendPart",[gs.gp(message,"_id"), gs.gp(part,"_id"), gs.gp(part,"type"), gs.gp(part,"content"), gs.map(), gs.gp(part,"seq"), function(it) { return gs.mc(part,"delete",[function(it) { return gs.mc(gSobject,"deleteMessageAfterAllPartsSent",[message]); }]); }]); }]); }]); return gs.mc(gSobject,"deleteMessageAfterAllPartsSent",[message]); }]); } gSobject['deleteMessageAfterAllPartsSent'] = function(message) { if (gs.equals(gs.mc(gs.mc(gs.gp(gs.gp(gSobject.db,"o"),"chatMessagePart"),"find",[gs.map().add("message",gs.gp(message,"_id"))]),"size",[]), 0)) { var chatMessage = gs.mc(gs.gp(gs.gp(gSobject.db,"o"),"chatMessage"),"getOne",[gs.gp(message,"_id")]); if (!gs.bool(chatMessage)) { return null; }; return gs.mc(chatMessage,"delete",[function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"dymicoChatService"),"updateReadCountForChat",[gs.gp(message,"_id")]),"do",[]); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["DymicoChatJsService.sendMessage:DONE:" + (gs.gp(message,"_id")) + ""]); }]); }; } gSobject['addPart'] = function(message, type, content, seq, callback) { if (callback === undefined) callback = function(it) { }; if (!gs.bool(content)) { return gs.execCall(callback, this, []); }; gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["DymicoChatJsService.addPart:" + (gs.gp(message,"_id")) + ":" + (type) + ":" + (content) + ""]); if (!gs.bool(gs.gp(message,"parts"))) { gs.sp(message,"parts",gs.list([])); }; return gs.mc(gs.mc(gs.gp(gs.gp(gSobject.db,"o"),"chatMessagePart"),"new",[gs.map().add("_id",gs.execStatic(Utils,'uuid', this,[])).add("message",gs.gp(message,"_id")).add("content",content).add("type",type).add("seq",seq)]),"save",[function(part) { gs.mc(gs.gp(message,"parts"),"add",[part]); return gs.execCall(callback, this, []); }]); } gSobject['addPartFile'] = function(message, fileData, seq, callback) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["DymicoChatJsService.addPartFile:" + (gs.gp(message,"_id")) + ""]); gs.println(fileData); return gs.mc(gs.mc(gs.gp(gs.gp(gSobject.db,"o"),"chatMessagePart"),"new",[gs.map().add("_id",gs.execStatic(Utils,'uuid', this,[])).add("message",gs.gp(message,"_id")).add("content","").add("type",gs.gp(fileData,"type")).add("seq",seq)]),"save",[function(part) { gs.mc(gs.gp(message,"parts"),"add",[part]); gs.execCall(callback, this, []); var blob = gs.elvis(gs.bool(gs.gp(fileData,"file")) , gs.gp(fileData,"file") , gs.gp(fileData,"blob")); return gs.mc(gs.fs('cordovaFile', this, gSobject),"addFile",[blob, "dcMessagePart", "file", gs.gp(part,"_id"), function(it) { gs.println("addPartFile:dcMessagePart"); return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"dymicoChatService"),"updateReadCountForChat",[gs.gp(message,"_id")]),"do",[]); }, function(error) { return gs.println("addPartFile:error:" + (error) + ""); }]); }]); } gSobject['updateMessageMeta'] = function(messageId, meta) { return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"dymicoChatService"),"updateMessageMeta",[messageId, meta]),"do",[]); } gSobject['DymicoChatJsService0'] = function(it) { gs.mc(gs.gp(LocalDB,"instance"),"registerPath",["chatMessage", gs.map().add("_path","/chatMessage/")]); gs.mc(gs.gp(LocalDB,"instance"),"registerPath",["chatMessagePart", gs.map().add("_path","/chatMessagePart/")]); gs.execStatic(LocalDB,'getInstance', this,[function(instance) { gSobject.db = instance; return gs.execStatic(Utils,'setTimeout', this,[function(it) { return gs.mc(gSobject,"deliverMessages",[]); }, 5000]); }]); return this; } if (arguments.length==0) {gSobject.DymicoChatJsService0(); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; DymicoChatJsService.MAX_ATTACHMENT_SIZE_BYTES = gs.multiply((gs.multiply(40, 1024)), 1024); function VueTestComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'VueTestComponent', simpleName: 'VueTestComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/vueTesting"; gSobject['created'] = function(it) { gs.println("VueTestingComponent.created()"); gs.mc(gSobject,"showHeaderFooter",[]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"user",gs.gp(gs.fs('session', this, gSobject),"user")); gs.sp(gSobject.scope,"activeUser",gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"activeUser")); gs.sp(gSobject.scope,"items",gs.list([gs.map().add("id",0).add("value",0).add("color","#9C0F0F").add("label","above") , gs.map().add("id",1).add("value",4).add("color","#374F4F").add("label","in range") , gs.map().add("id",2).add("value",3).add("color","#E5CE89").add("label","below")])); gs.sp(gSobject.scope,"max",gs.elvis(gs.mc(gs.mc(gs.gp(gSobject.scope,"items"),"collect",[function(it) { return gs.gp(it,"num"); }]),"max",[]) , gs.mc(gs.mc(gs.gp(gSobject.scope,"items"),"collect",[function(it) { return gs.gp(it,"num"); }]),"max",[]) , 15)); gs.sp(gSobject.scope,"chartTypes",gs.list(["line" , "bar" , "doughnut" , "pie" , "polarArea" , "radar"])); gs.sp(gSobject.scope,"labels",gs.list(["January" , "February" , "March" , "April" , "May" , "June" , "July" , "August" , "September" , "October" , "November" , "December"])); gs.sp(gSobject.scope,"singleDataSet",gs.list([5 , -12 , 8 , -19 , 23 , -7 , 15 , 3 , -10 , 17 , -21 , 9])); gs.sp(gSobject.scope,"multipleDatasets",gs.list([gs.list([5 , -12 , 8 , -19 , 23 , -7 , 15 , 3 , -10 , 17 , -21 , 9]) , gs.list([10 , -3 , 14 , -6 , 22 , 5 , -17 , 11 , -8 , 13 , -4 , 19]) , gs.list([-9 , 18 , -21 , 7 , 13 , -16 , 20 , -11 , 6 , -5 , 8 , -12])])); gs.sp(gSobject.scope,"tensions",gs.list([0.5 , 1.0])); gs.sp(gSobject.scope,"borderWidths",gs.list([8])); gs.sp(gSobject.scope,"fills",gs.list([true , "start" , "end"])); gs.sp(gSobject.scope,"borderRadii",gs.list([16])); gs.sp(gSobject.scope,"value",70); gs.sp(gSobject.scope,"days",gs.list([gs.map().add("label","M").add("systolic",15).add("diastolic",0) , gs.map().add("label","T").add("systolic",60).add("diastolic",70) , gs.map().add("label","W").add("systolic",10).add("diastolic",50) , gs.map().add("label","T").add("systolic",50).add("diastolic",0) , gs.map().add("label","F").add("systolic",40).add("diastolic",60) , gs.map().add("label","S").add("systolic",0).add("diastolic",20) , gs.map().add("label","S").add("systolic",50).add("diastolic",0)])); gs.sp(gSobject.scope,"heartRates",gs.list([gs.map().add("label","M").add("value",55) , gs.map().add("label","T").add("value",62) , gs.map().add("label","W").add("value",70) , gs.map().add("label","T").add("value",69) , gs.map().add("label","F").add("value",58) , gs.map().add("label","S").add("value",74) , gs.map().add("label","S").add("value",66)])); return gs.sp(gSobject.scope,"cycles",gs.list([gs.map().add("label","M").add("color","brown-5") , gs.map().add("label","T").add("color","brown-5") , gs.map().add("label","W").add("color","brown-5") , gs.map().add("label","T").add("color","brown-5") , gs.map().add("label","F").add("color","grey-3") , gs.map().add("label","S").add("color","grey-3") , gs.map().add("label","S").add("color","grey-3")])); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function PhoneVerificationComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'PhoneVerificationComponent', simpleName: 'PhoneVerificationComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/phoneVerification"; gSobject.RETRY_MAX = 3; gSobject['created'] = function(it) { gs.println("PhoneVerificationComponent.created()"); gs.sp(gSobject.scope,"pin",""); gs.sp(gSobject.scope,"retries",0); gs.sp(gSobject.scope,"pinSize",6); gs.sp(gSobject.scope,"pinValues",gs.list([])); gs.sp(gSobject.scope,"phoneNumber",gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"phoneNumber")); gs.sp(gSobject.scope,"testEmail","test10@demo.i3zone.com"); gs.sp(gSobject.scope,"processing",false); gs.sp(gSobject.scope,"emailLoad",false); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "user.phone.verification"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[false]); return gs.mc(gSobject,"componentTheme",[false]); } gSobject['anonymiseNumber'] = function(number) { if (!gs.bool(number)) { return "your number"; }; if (gs.gp(number,"length") < 4) { return "Invalid Number"; }; var lastIndex = gs.minus(gs.mc(number,"length",[]), 1); return gs.plus("**", (gs.rangeFromList(number, gs.minus(lastIndex, 3), lastIndex))); } gSobject['resendOtp'] = function(it) { if (gs.gp(gSobject.scope,"retries") >= gSobject.RETRY_MAX) { return gs.mc(gSobject,"notify",["Retries Exceeded", "negative"]); }; gs.mc(gSobject,"sendUserPin",[gs.gp(gSobject.scope,"phoneNumber"), "", true]); return gs.sp(gSobject.scope,"retries",gs.gp(gSobject.scope,"retries") + 1); } gSobject['sendEmail'] = function(it) { gs.sp(gSobject.scope,"emailLoad",true); return gs.mc(gSobject,"sendUserPin",[gs.gp(gSobject.scope,"phoneNumber"), "", false, function(it) { return gs.sp(gSobject.scope,"emailLoad",false); }]); } gSobject['verifyPin'] = function(it) { gs.println("verifyPin"); gs.sp(gSobject.scope,"pin",""); gs.mc(gs.gp(gSobject.scope,"pinValues"),"each",[function(value) { return gs.sp(gSobject.scope,"pin",gs.gp(gSobject.scope,"pin") + "" + (value) + ""); }]); if (!gs.bool(gs.gp(gSobject.scope,"pin"))) { gs.mc(gSobject,"notify",["Please enter pin", "negative"]); return null; }; if (!gs.bool(gs.exactMatch(gs.gp(gSobject.scope,"pin"),/^[0-9]{6}$/))) { gs.mc(gSobject,"notify",["Invalid pin, pin must be a 6 digit number", "negative"]); return null; }; if (gs.gp(gSobject.scope,"pin") !== gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"verifyPin")) { return gs.mc(gSobject,"notify",["Invalid Pin", "negative"]); }; return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"loadRxmeUser",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(rxmeUser) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"legionService"),"loadLegionUser",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(user) { gs.sp(user,"phoneVerified",true); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"updateUserInfo",[user, rxmeUser, function(updatedUser) { gs.mc(gSobject,"notify",["Phone Verified"]); gs.sp(gs.fs('session', this, gSobject),"user",updatedUser); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"questService"),"moveStateForwardFromState",[gs.gp(gs.fs('session', this, gSobject),"userId"), "User Onboarding", "Setup Profile"]),"do",[]); if (gs.bool(gs.gp(updatedUser,"tncAcceptedOn"))) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/"]); } else { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/terms&condition"]); }; }]); }]); }]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function PhoneSetupComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'PhoneSetupComponent', simpleName: 'PhoneSetupComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/phoneSetup" , "/phoneSetup/:number"]); gSobject['created'] = function(it) { gs.println("PhoneSetupComponent.created()"); gs.sp(gSobject.scope,"phoneNumber",gs.elvis(gs.bool(gs.gp(gs.gp(gSobject.route,"params"),"number")) , gs.gp(gs.gp(gSobject.route,"params"),"number") , null)); gs.sp(gSobject.scope,"loading",false); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "user.phone.setup"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[false]); return gs.mc(gSobject,"componentTheme",[false]); } gSobject['verifyNumber'] = function(it) { if (!gs.bool(gs.gp(gSobject.scope,"phoneNumber"))) { return null; }; gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"phoneNumber",gs.gp(gSobject.scope,"phoneNumber")); var testEmail = "test10@demo.i3zone.com"; gs.sp(gSobject.scope,"loading",true); return gs.mc(gSobject,"sendUserPin",[gs.gp(gSobject.scope,"phoneNumber"), "/phoneVerification", true, function(it) { return gs.sp(gSobject.scope,"loading",false); }]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function InjectionOverviewComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'InjectionOverviewComponent', simpleName: 'InjectionOverviewComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/InjectionOverview"; gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.injection.overview"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"batchName","medical:score:injection"); gs.sp(gSobject.scope,"graphPeriod","Day"); gs.sp(gSobject.scope,"bmiInfo",null); gs.sp(gSobject.scope,"tracker",null); gs.println("Injection.created()"); gs.mc(gSobject,"loadLogs",[]); gs.mc(gSobject,"loadTrackerData",["Injection", function(tracker) { return gs.sp(gSobject.scope,"tracker",tracker); }]); gs.sp(gSobject.scope,"lastUpdated",""); return gs.mc(gSobject,"loadLastUpdated",[gs.gp(gs.fs('session', this, gSobject),"userId"), "injection", function(lastUpdated) { return gs.sp(gSobject.scope,"lastUpdated",lastUpdated); }]); } gSobject['loadLogs'] = function(it) { gs.sp(gSobject.scope,"injection",0); gs.sp(gSobject.scope,"injectionLogs",gs.list([])); gs.sp(gSobject.scope,"todayInjections",gs.list([])); gs.sp(gSobject.scope,"todayInjectionTotal",0); gs.sp(gSobject.scope,"injectionGraphLabels",gs.list([])); gs.sp(gSobject.scope,"injectionGraphValues",gs.list([])); var today = gs.mc(gs.date(),"clearTime",[]); gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"listEntries",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gSobject.scope,"batchName"), gs.map().add("limit",10), function(logs) { gs.mc(logs,"each",[function(log) { gs.mc(gs.gp(gSobject.scope,"injectionLogs"),"add",[gs.map().add("_id",gs.gp(log,"_id")).add("injectionName",gs.elvis(gs.bool(gs.gp(log,"injectionName")) , gs.gp(log,"injectionName") , "Injection")).add("value",gs.gp(log,"value")).add("subtext",gs.elvis(gs.bool(gs.gp(log,"injectionName")) , gs.gp(log,"injectionName") , "Standard Dose")).add("unit","ml").add("_createdAt",gs.gp(log,"timePicked"))]); if (gs.gp(log,"date") >= today) { gs.mc(gs.gp(gSobject.scope,"todayInjections"),"add",[gs.map().add("injectionName",gs.gp(log,"injectionName")).add("value",gs.gp(log,"value")).add("unit","ml")]); return gs.sp(gSobject.scope,"todayInjectionTotal",gs.gp(gSobject.scope,"todayInjectionTotal") + gs.elvis(gs.bool(gs.gp(log,"value")) , gs.gp(log,"value") , 0)); }; }]); if (gs.mc(gs.gp(gSobject.scope,"todayInjections"),"isEmpty",[])) { gs.mc(gs.gp(gSobject.scope,"todayInjections"),"add",[gs.map().add("injectionName","No injection taken").add("value",0).add("unit","ml")]); }; return gs.sp(gSobject.scope,"injection",gs.gp(gSobject.scope,"todayInjectionTotal")); }]); var graphKey = "medical:score:injection-value"; return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"metrics",[gs.gp(gs.fs('session', this, gSobject),"userId"), graphKey, gs.date(), gs.gp(gSobject.scope,"graphPeriod"), function(data) { if (((gs.bool(data)) && (gs.bool(gs.gp(data,"aggSumValues")))) && (gs.mc(gs.gp(data,"aggSumValues"),"any",[function(it) { return it > 0; }]))) { gs.sp(gSobject.scope,"injectionGraphLabels",gs.gp(data,"labels")); return gs.sp(gSobject.scope,"injectionGraphValues",gs.gp(data,"aggSumValues")); } else { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"metrics",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:injection", gs.date(), gs.gp(gSobject.scope,"graphPeriod"), function(retryData) { gs.sp(gSobject.scope,"injectionGraphLabels",gs.gp(retryData,"labels")); return gs.sp(gSobject.scope,"injectionGraphValues",gs.gp(retryData,"aggSumValues")); }]); }; }]); } gSobject['navInsight'] = function(it) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/injectionInsight"]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function InjectionLogComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'InjectionLogComponent', simpleName: 'InjectionLogComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/injectionLog" , "/injectionLog/:id"]); gSobject.onSelectFromDropdown = function(val) { gs.sp(gSobject.scope,"manualMode",false); return gs.sp(gSobject.scope,"manualError",false); }; gSobject.confirmManualSelection = function(it) { if (gs.bool(gs.gp(gSobject.scope,"manualMode"))) { if (!gs.bool(gs.gp(gSobject.scope,"manualInjection"))) { gs.sp(gSobject.scope,"manualError",true); return null; }; gs.sp(gs.gp(gSobject.scope,"entry"),"injectionType",gs.gp(gSobject.scope,"manualInjection")); } else { if (!gs.bool(gs.gp(gs.gp(gSobject.scope,"entry"),"injectionType"))) { return null; }; }; gs.sp(gSobject.scope,"manualError",false); return gs.sp(gSobject.scope,"showInjectionDialog",false); }; gSobject.toggleColor = function(color) { if (gs.equals(gs.gp(gSobject.scope,"selectedColor"), gs.gp(color,"name"))) { gs.sp(gSobject.scope,"selectedColor",""); gs.sp(gSobject.scope,"selectedColorValue",""); return gs.sp(gs.gp(gSobject.scope,"entry"),"color",""); } else { gs.sp(gSobject.scope,"selectedColor",gs.gp(color,"name")); gs.sp(gSobject.scope,"selectedColorValue",gs.gp(color,"value")); return gs.sp(gs.gp(gSobject.scope,"entry"),"color",gs.gp(color,"name")); }; }; gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.injection.log"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[false]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"showDateTime",false); gs.sp(gSobject.scope,"dialog",false); gs.sp(gSobject.scope,"showInjectionDialog",false); gs.sp(gSobject.scope,"manualMode",false); gs.sp(gSobject.scope,"manualInjection",""); gs.sp(gSobject.scope,"manualError",false); gs.sp(gSobject.scope,"medicationOptions",gs.list(["Blend" , "Half Blend" , "Tirzepatide 10mg" , "Tirzepatide 15mg" , "Semaglutide 2.4mg"])); gs.sp(gSobject.scope,"entry",gs.map().add("injectionName","").add("value",null).add("unit",null).add("timePicked",gs.mc(gs.mc(gSobject,"moment",[]),"format",["YYYY-MM-DD HH:mm"])).add("date",gs.mc(gs.mc(gSobject,"moment",[]),"format",["YYYY-MM-DD HH:mm"])).add("ref","injection").add("injectionType","").add("color","")); gs.sp(gSobject.scope,"colors",gs.list([gs.map().add("name","Soft Red").add("value","rgba(255, 99, 132, 0.6)") , gs.map().add("name","Sky Blue").add("value","rgba(54, 162, 235, 0.6)") , gs.map().add("name","Sun Yellow").add("value","rgba(255, 206, 86, 0.6)") , gs.map().add("name","Teal Green").add("value","rgba(75, 192, 192, 0.6)") , gs.map().add("name","Lavender Purple").add("value","rgba(153, 102, 255, 0.6)") , gs.map().add("name","Orange Spice").add("value","rgba(255, 159, 64, 0.6)") , gs.map().add("name","Mint Green").add("value","rgba(100, 255, 218, 0.6)") , gs.map().add("name","Rose Pink").add("value","rgba(255, 128, 171, 0.6)") , gs.map().add("name","Ocean Blue").add("value","rgba(28, 130, 181, 0.6)") , gs.map().add("name","Lime Zest").add("value","rgba(174, 255, 0, 0.6)") , gs.map().add("name","Coral Peach").add("value","rgba(255, 127, 80, 0.6)") , gs.map().add("name","Grape Violet").add("value","rgba(138, 43, 226, 0.6)") , gs.map().add("name","Blush Pink").add("value","rgba(255, 182, 193, 0.6)") , gs.map().add("name","Mustard").add("value","rgba(255, 219, 88, 0.6)") , gs.map().add("name","Ice Blue").add("value","rgba(173, 216, 230, 0.6)") , gs.map().add("name","Deep Plum").add("value","rgba(102, 0, 102, 0.6)") , gs.map().add("name","Forest Green").add("value","rgba(34, 139, 34, 0.6)") , gs.map().add("name","Cocoa Brown").add("value","rgba(139, 69, 19, 0.6)")])); gs.sp(gSobject.scope,"selectedColor",""); gs.sp(gSobject.scope,"selectedColorValue",""); if (gs.bool(gs.gp(gs.gp(gSobject.route,"params"),"id"))) { gs.sp(gSobject.scope,"entry",null); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"loadEntry",[gs.gp(gs.gp(gSobject.route,"params"),"id"), function(entry) { gs.sp(gSobject.scope,"entry",entry); gs.sp(gs.gp(gSobject.scope,"entry"),"date",gs.mc(gs.mc(gSobject,"moment",[gs.gp(entry,"date")]),"format",["YYYY-MM-DD HH:mm"])); gs.sp(gSobject.scope,"selectedColor",gs.gp(entry,"color")); var activeColor = gs.mc(gs.gp(gSobject.scope,"colors"),"find",[function(it) { return gs.equals(gs.gp(it,"name"), gs.gp(entry,"color")); }]); if (gs.bool(activeColor)) { return gs.sp(gSobject.scope,"selectedColorValue",gs.gp(activeColor,"value")); }; }]); }; } gSobject['logInjection'] = function(it) { var value = gs.gp(gs.gp(gSobject.scope,"entry"),"value"); var unit = gs.gp(gs.gp(gSobject.scope,"entry"),"unit"); var timePicked = gs.gp(gs.gp(gSobject.scope,"entry"),"timePicked"); var injectionType = gs.gp(gs.gp(gSobject.scope,"entry"),"injectionType"); var injectionName = gs.gp(gs.gp(gSobject.scope,"entry"),"injectionName"); if (!gs.bool(value)) { gs.mc(gs.fs('$q', this, gSobject),"notify",[gs.map().add("type","negative").add("message","Please select or enter an injection value.")]); return null; }; gs.sp(gSobject.scope,"date",gs.mc(gs.mc(gSobject,"moment",[gs.gp(gs.gp(gSobject.scope,"entry"),"timePicked"), "YYYY-MM-DD HH:mm"]),"toDate",[])); if (gs.mc(gs.mc(gSobject,"moment",[gs.gp(gSobject.scope,"date")]),"isSame",[gs.mc(gSobject,"moment",[]), "day"])) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:injection:injectionName", injectionName]),"do",[]); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:injection:value", value]),"do",[]); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:injection:unit", unit]),"do",[]); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:injection:timePicked", timePicked]),"do",[]); }; if (gs.bool(gs.gp(gs.gp(gSobject.route,"params"),"id"))) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"deleteEntry",[gs.gp(gs.gp(gSobject.route,"params"),"id")]),"do",[]); }; gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"addEntryWithFts",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:injection", gs.list(["value"]), gs.map().add("injectionName",injectionName).add("value",value).add("unit",unit).add("timePicked",timePicked).add("date",gs.gp(gSobject.scope,"date")).add("color",gs.gp(gs.gp(gSobject.scope,"entry"),"color")).add("injectionType",injectionType)]),"then",[function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"eventListener",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gSobject.scope,"entry")]),"do",[]); gs.mc(gSobject,"saveLastUpdated",[gs.gp(gs.fs('session', this, gSobject),"userId"), "injection"]); return gs.sp(gSobject.scope,"dialog",true); }, function(it) { return gs.sp(gSobject.scope,"dialog",true); }]); return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"notificationService"),"removeNotification",[gs.gp(gs.fs('session', this, gSobject),"userId"), "trackable:injection", "Injection"]),"do",[]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function InjectionInsightComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'InjectionInsightComponent', simpleName: 'InjectionInsightComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/injectionInsight"; gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.injection.insight"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[false]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"batchName","medical:score:injection"); gs.sp(gSobject.scope,"graphPeriod","Day"); gs.sp(gSobject.scope,"bmiInfo",null); gs.println("Injection.created()"); gs.sp(gSobject.scope,"injectionMin",999); gs.sp(gSobject.scope,"injectionMax",0); gs.mc(gSobject,"weeklySumInjection",[]); return gs.mc(gSobject,"loadLogs",[]); } gSobject['loadLogs'] = function(it) { gs.sp(gSobject.scope,"injection",""); gs.sp(gSobject.scope,"injectionLogs",gs.list([])); gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"listEntries",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:injection", gs.map().add("limit",7), function(logs) { return gs.mc(logs,"each",[function(log) { gs.mc(gs.gp(gSobject.scope,"injectionLogs"),"add",[gs.map().add("_id",gs.gp(log,"_id")).add("value",gs.gp(log,"value")).add("subtext",gs.gp(log,"status")).add("unit","ml").add("_createdAt",gs.gp(log,"date"))]); gs.sp(gSobject.scope,"injection",gs.elvis(gs.bool(gs.gp(gSobject.scope,"injection")) , gs.gp(gSobject.scope,"injection") , Math.round(gs.gp(log,"value")))); if (gs.gp(gSobject.scope,"injectionMin") > gs.gp(log,"value")) { gs.sp(gSobject.scope,"injectionMin",gs.gp(log,"value")); }; if (gs.gp(gSobject.scope,"injectionMax") < gs.gp(log,"value")) { return gs.sp(gSobject.scope,"injectionMax",gs.gp(log,"value")); }; }]); }]); gs.sp(gSobject.scope,"bodyWeightLabels",null); gs.sp(gSobject.scope,"bodyWeightValues",null); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"metrics",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:injection-value", gs.date(), gs.gp(gSobject.scope,"graphPeriod"), function(logs) { gs.sp(gSobject.scope,"bodyWeightLabels",gs.gp(logs,"labels")); return gs.sp(gSobject.scope,"bodyWeightValues",gs.gp(logs,"aggAvgValues")); }]); } gSobject['weeklySumInjection'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"metrics",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:injection-value", gs.date(), "Day", function(logs) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"calculateWeeklySum",[gs.gp(logs,"aggAvgValues"), function(sumDrink) { var injectWeeklySum = sumDrink; return gs.sp(gSobject.scope,"weeklySumDisplay","" + (injectWeeklySum) + ""); }]); }]); } gSobject['navInsight'] = function(it) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/injectionInsight"]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function InjectionDetailComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'InjectionDetailComponent', simpleName: 'InjectionDetailComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/injectionDetail/:id"; gSobject['created'] = function(it) { gs.println("Injection Detail"); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical.injection.detail"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[false]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"entryId",gs.gp(gs.gp(gSobject.route,"params"),"id")); gs.sp(gSobject.scope,"entry",gs.map()); return gs.mc(gSobject,"loadInjectionLog",[gs.gp(gSobject.scope,"entryId")]); } gSobject['loadInjectionLog'] = function(entryId) { if (!gs.bool(entryId)) { return null; }; return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"loadEntry",[gs.gp(gs.gp(gSobject.route,"params"),"id"), function(entry) { gs.sp(gSobject.scope,"entry",entry); return gs.sp(gs.gp(gSobject.scope,"entry"),"date",gs.mc(gs.mc(gSobject,"moment",[gs.gp(entry,"date")]),"format",["YYYY-MM-DD HH:mm"])); }]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function I3HeaderButton() { var gSobject = VueComponent(); gSobject.clazz = { name: 'I3HeaderButton', simpleName: 'I3HeaderButton'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.props = gs.map().add("icon",gs.map().add("type",String).add("default","o_square")).add("color",gs.map().add("type",String).add("default","primary")).add("dense",gs.map().add("type",Boolean).add("default",true)).add("flat",gs.map().add("type",Boolean).add("default",true)).add("round",gs.map().add("type",Boolean).add("default",true)); gSobject.data = function(it) { return gs.list([]); }; gSobject['created'] = function(it) { var self = this; } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function RewardsSwitchComponent() { var gSobject = VueComponent(); gSobject.clazz = { name: 'RewardsSwitchComponent', simpleName: 'RewardsSwitchComponent'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.self = null; gSobject.props = gs.map().add("tracker",String).add("color",String); gSobject['created'] = function(it) { gSobject.self = this; gs.sp(gSobject.scope,"useRewards",false); gs.sp(gSobject.scope,"showInfo",false); return gs.mc(gSobject,"loadSwitch",[]); } gSobject['normalizeTrackerName'] = function(trackerName) { var name = gs.mc(trackerName,"trim",[], null, true); if (!gs.bool(name)) { return name; }; if (gs.mc(name,"endsWith",[" Tracker"])) { return gs.mc(name,"substring",[0, gs.minus(gs.mc(name,"length",[]), gs.mc(" Tracker","length",[]))]); }; return name; } gSobject['loadSwitch'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rewardService"),"loadRewardSwitch",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gSobject.self,"tracker"), function(result) { return gs.sp(gSobject.scope,"useRewards",gs.elvis(gs.bool(result) , result , false)); }]); } gSobject['updateSwitch'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rewardService"),"updateRewardSwitch",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gSobject.self,"tracker"), gs.gp(gSobject.scope,"useRewards"), function(result) { return gs.sp(gSobject.scope,"useRewards",gs.elvis(gs.bool(result) , result , false)); }]); } gSobject['activateRewards'] = function(it) { gs.sp(gSobject.scope,"useRewards",true); gs.mc(gSobject,"updateSwitch",[]); return gs.sp(gSobject.scope,"showInfo",false); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function PinchToZoomHandler() { var gSobject = gs.init('PinchToZoomHandler'); gSobject.clazz = { name: 'PinchToZoomHandler', simpleName: 'PinchToZoomHandler'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.addPinchToZoomById = function(x0) { return PinchToZoomHandler.addPinchToZoomById(x0); } gSobject.addPinchToZoomByElement = function(x0) { return PinchToZoomHandler.addPinchToZoomByElement(x0); } gSobject.addPinchToZoomToPdf = function(x0) { return PinchToZoomHandler.addPinchToZoomToPdf(x0); } gSobject['PinchToZoomHandler2'] = function(id, type) { if (gs.equals(type, "pdf")) { return PinchToZoomHandler.addPinchToZoomToPdf(id); }; PinchToZoomHandler.addPinchToZoomById(id); return this; } if (arguments.length==2) {gSobject.PinchToZoomHandler2(arguments[0], arguments[1]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; PinchToZoomHandler.addPinchToZoomById = function(id) { new PinchZoom(document.getElementById(id)); } PinchToZoomHandler.addPinchToZoomByElement = function(element) { new PinchZoom(element); } PinchToZoomHandler.addPinchToZoomToPdf = function(id) { let canvasList = document.getElementById(id).children for (let canvas of canvasList) { PinchToZoomHandler.addPinchToZoomByElement(canvas); } } function BloodPressureOverviewComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'BloodPressureOverviewComponent', simpleName: 'BloodPressureOverviewComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/bloodPressureOverview" , "/bloodPressureOverview/:id"]); gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.bloodpressure.overview"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"labels",gs.list(["label1" , "label2" , "label3" , "label4" , "label5"])); gs.sp(gSobject.scope,"values",gs.list([10 , 40 , 30 , 50 , 10])); gs.sp(gSobject.scope,"batchName","medical:score:blood_pressure"); gs.sp(gSobject.scope,"graphPeriod","Day"); gs.sp(gSobject.scope,"tracker",null); gs.sp(gSobject.scope,"logs",gs.list([])); gs.sp(gSobject.scope,"lastEntry",gs.map()); gs.sp(gSobject.scope,"bpStatusMessage",""); gs.mc(gSobject,"loadLogs",[]); gs.mc(gSobject,"loadTrackerData",["Blood Pressure", function(tracker) { return gs.sp(gSobject.scope,"tracker",tracker); }]); gs.sp(gSobject.scope,"motivationalText",""); gs.sp(gSobject.scope,"motivationLoading",true); gs.mc(gSobject,"loadMotivation",[gs.gp(gs.fs('session', this, gSobject),"userId"), "Blood Pressure", function(msg) { gs.sp(gSobject.scope,"motivationalText",msg); return gs.sp(gSobject.scope,"motivationLoading",false); }]); gs.sp(gSobject.scope,"lastUpdated",""); return gs.mc(gSobject,"loadLastUpdated",[gs.gp(gs.fs('session', this, gSobject),"userId"), "blood_pressure", function(lastUpdated) { return gs.sp(gSobject.scope,"lastUpdated",lastUpdated); }]); } gSobject['loadLogs'] = function(it) { gs.sp(gSobject.scope,"lastEntryDate","None"); gs.mc(gSobject,"loadBloodPressureMinMax",[gs.fs('session', this, gSobject), gSobject.scope]); gs.sp(gSobject.scope,"systolicLabels",null); gs.sp(gSobject.scope,"systolicValues",null); gs.sp(gSobject.scope,"diastolicLabels",null); gs.sp(gSobject.scope,"diastolicValues",null); gs.sp(gSobject.scope,"systolicDiastolicValues",null); gs.mc(gs.gp(gs.mc(gs.fs('o', this, gSobject),"localAndRemote",[]),"protoDataPointTimelineService"),"metrics",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:blood_pressure-systolic", gs.date(), gs.gp(gSobject.scope,"graphPeriod"), function(logs) { gs.println("-----metric logs-----"); gs.println(logs); gs.sp(gSobject.scope,"systolicLabels",gs.gp(logs,"labels")); gs.sp(gSobject.scope,"systolicValues",gs.gp(logs,"avgValues")); return gs.mc(gs.gp(gs.mc(gs.fs('o', this, gSobject),"localAndRemote",[]),"protoDataPointTimelineService"),"metrics",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:blood_pressure-diastolic", gs.date(), gs.gp(gSobject.scope,"graphPeriod"), function(logs2) { gs.println("BP LOGS 2"); gs.println(logs2); gs.sp(gSobject.scope,"diastolicLabels",gs.mc(gs.gp(logs2,"labels"),"collect",[function(it) { return ""; }])); gs.sp(gSobject.scope,"diastolicValues",gs.gp(logs2,"avgValues")); gs.sp(gSobject.scope,"systolicDiastolicValues",gs.list([])); gs.mc(gs.gp(gSobject.scope,"systolicValues"),"eachWithIndex",[function(systolicValue, index) { return gs.mc(gs.gp(gSobject.scope,"systolicDiastolicValues"),"add",[gs.list([systolicValue , gs.gp(gSobject.scope,"diastolicValues")[index]])]); }]); gs.println("Blood pressure graph----"); gs.println(gs.gp(gSobject.scope,"systolicDiastolicValues")); return gs.mc(gs.gp(gs.mc(gs.fs('o', this, gSobject),"localAndRemote",[]),"protoDataPointTimelineService"),"metrics",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:blood_pressure-pulse", gs.date(), gs.gp(gSobject.scope,"graphPeriod"), function(logs3) { gs.sp(gSobject.scope,"pulseLabels",gs.mc(gs.gp(logs3,"labels"),"collect",[function(it) { return ""; }])); return gs.sp(gSobject.scope,"pulseValues",gs.gp(logs3,"aggAvgValues")); }]); }]); }]); gs.sp(gSobject.scope,"pulseLabels",null); return gs.sp(gSobject.scope,"pulseValues",null); } gSobject['updateBPStatus'] = function(scope, logs) { var lastLog = logs[0]; var systolic = gs.gp(lastLog,"systolic"); var diastolic = gs.gp(lastLog,"diastolic"); gs.sp(scope,"bpStatus",gs.mc(gSobject,"loadBloodPressureStatus",[systolic, diastolic])); return gs.sp(scope,"bpStatusMessage",gs.mc(gSobject,"loadBPStatusMessage",[gs.gp(scope,"bpStatus")])); } gSobject['loadBloodPressureMinMax'] = function(session, scope) { gs.sp(scope,"logs",gs.list([])); gs.sp(scope,"systolicMin",999); gs.sp(scope,"systolicMax",0); gs.sp(scope,"diastolicMin",999); gs.sp(scope,"diastolicMax",0); gs.sp(scope,"pulseMin",999); gs.sp(scope,"pulseMax",0); return gs.mc(gs.gp(gs.mc(gs.fs('o', this, gSobject),"localAndRemote",[]),"protoDataPointTimelineService"),"listEntries",[gs.gp(session,"userId"), gs.gp(scope,"batchName"), gs.map().add("limit",7), function(logs) { gs.mc(logs,"each",[function(log) { gs.mc(gs.gp(scope,"logs"),"add",[gs.map().add("_id",gs.gp(log,"_id")).add("value",gs.gp(log,"value")).add("subtext",gs.gp(log,"status")).add("unit","mmHg").add("_createdAt",gs.gp(log,"date"))]); gs.sp(scope,"lastEntryDate",gs.mc(gs.mc(gSobject,"moment",[gs.gp(log,"date")]),"calendar",[])); gs.sp(scope,"lastEntry",gs.elvis(gs.bool(gs.gp(scope,"lastEntry")) , gs.gp(scope,"lastEntry") , log)); if (gs.gp(scope,"systolicMin") > gs.gp(log,"systolic")) { gs.sp(scope,"systolicMin",gs.gp(log,"systolic")); }; if (gs.gp(scope,"systolicMax") < gs.gp(log,"systolic")) { gs.sp(scope,"systolicMax",gs.gp(log,"systolic")); }; if (gs.gp(scope,"diastolicMin") > gs.gp(log,"diastolic")) { gs.sp(scope,"diastolicMin",gs.gp(log,"diastolic")); }; if (gs.gp(scope,"diastolicMax") < gs.gp(log,"diastolic")) { gs.sp(scope,"diastolicMax",gs.gp(log,"diastolic")); }; if (gs.bool(gs.gp(log,"pulse"))) { if (gs.gp(scope,"pulseMin") > gs.gp(log,"pulse")) { gs.sp(scope,"pulseMin",gs.gp(log,"pulse")); }; if (gs.gp(scope,"pulseMax") < gs.gp(log,"pulse")) { return gs.sp(scope,"pulseMax",gs.gp(log,"pulse")); }; }; }]); gs.println("logs"); gs.println(logs); if (gs.bool(logs)) { gs.mc(gSobject,"updateBPStatus",[scope, logs]); }; return gs.mc(gSobject,"calcBloodPressureRisk",[scope, logs]); }]); } gSobject['calcBloodPressureRisk'] = function(scope, logs) { var avgSystolic = gs.div(gs.mc(gs.mc(logs,"collect",[function(it) { return gs.gp(it,"systolic"); }]),"sum",[]), gs.mc(logs,"size",[])); var avgDiastolic = gs.div(gs.mc(gs.mc(logs,"collect",[function(it) { return gs.gp(it,"diastolic"); }]),"sum",[]), gs.mc(logs,"size",[])); var levelRisk = function(s, d) { if ((s < 120) && (d < 80)) { return 0; }; if ((s < 130) && (d < 80)) { return 20; }; if ((s < 140) || (d < 90)) { return 40; }; if ((s < 180) || (d < 120)) { return 70; }; return 100; }; var avgLevelRisk = gs.execCall(levelRisk, this, [avgSystolic, avgDiastolic]); var systolicRange = gs.minus(gs.gp(scope,"systolicMax"), gs.gp(scope,"systolicMin")); var diastolicRange = gs.minus(gs.gp(scope,"diastolicMax"), gs.gp(scope,"diastolicMin")); var maxSystolicRange = 40; var maxDiastolicRange = 20; var systolicFluctuationRisk = gs.multiply((gs.div(systolicRange, maxSystolicRange)), 100); var diastolicFluctuationRisk = gs.multiply((gs.div(diastolicRange, maxDiastolicRange)), 100); var fluctuationRisk = Math.max(systolicFluctuationRisk, diastolicFluctuationRisk); fluctuationRisk = Math.min(fluctuationRisk, 100); gs.sp(scope,"riskRange",(gs.div(Math.round(gs.plus((gs.multiply(avgLevelRisk, 0.6)), (gs.multiply(fluctuationRisk, 0.4)))), 100))); return gs.println("Risk Range: " + (gs.gp(scope,"riskRange")) + ""); } gSobject['loadBloodPressureStatus'] = function(systolic, diastolic) { if ((systolic > 180) || (diastolic > 120)) { return "Hypertensive Crisis"; } else { if ((systolic >= 140) || (diastolic >= 90)) { return "High"; } else { if ((systolic >= 130) || (diastolic >= 80)) { return "Elevated"; } else { return "Normal"; }; }; }; } gSobject['loadBPStatusMessage'] = function(status) { var gSswitch0 = status; if (gs.equals(gSswitch0, "Hypertensive Crisis")) { return "Hypertensive crisis"; } else if (gs.equals(gSswitch0, "High")) { return "High blood pressure"; } else if (gs.equals(gSswitch0, "Elevated")) { return "Elevated blood pressure"; } else if (gs.equals(gSswitch0, "Normal")) { return "Normal blood pressure"; } else { return "Unknown"; }; } gSobject['motivationalText'] = function(it) { gs.sp(gSobject.scope,"motivationLoading",true); gs.sp(gSobject.scope,"motivationalText",""); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "motivational:text:blood_pressure", function(msg) { gs.println("Loaded motivational text: " + (msg) + ""); gs.sp(gSobject.scope,"motivationalText",gs.elvis(gs.bool(msg) , msg , "No motivation available yet.")); return gs.sp(gSobject.scope,"motivationLoading",false); }]); } gSobject['logBP'] = function(it) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/bloodPressureInput"]); } gSobject['navInsight'] = function(it) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/bloodPressureInsight"]); } gSobject['popup'] = function(title, message) { if (title === undefined) title = "Title"; if (message === undefined) message = "Info message"; return gs.mc(gSobject.q,"dialog",[gs.map().add("title",title).add("message",message)]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function BloodPressureResultComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'BloodPressureResultComponent', simpleName: 'BloodPressureResultComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/bloodPressureResult" , "/bloodPressureResult/:id"]); gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.bloodpressure.result"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[false]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"systolic",128); gs.sp(gSobject.scope,"diastolic",60); gs.sp(gSobject.scope,"systolicMax",200); return gs.sp(gSobject.scope,"diastolicMax",180); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function BloodPressureInputComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'BloodPressureInputComponent', simpleName: 'BloodPressureInputComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/bloodPressureInput" , "/bloodPressureInput/:id"]); gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.bloodpressure.input"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[false]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"today",gs.mc(gs.mc(gSobject,"moment",[]),"format",["YYYY-MM-DD"])); gs.sp(gSobject.scope,"allowedDates",function(d) { return gs.mc(gs.mc(gSobject,"moment",[d, "YYYY/MM/DD"]),"isSameOrBefore",[gs.mc(gSobject,"moment",[gs.gp(gSobject.scope,"today"), "YYYY/MM/DD"])]); }); gs.sp(gSobject.scope,"showDateTime",false); gs.sp(gSobject.scope,"entry",gs.map().add("systolic","").add("diastolic","").add("pulse","").add("date",gs.mc(gs.mc(gSobject,"moment",[]),"format",["YYYY-MM-DD HH:mm"])).add("ref","bp")); if (gs.bool(gs.gp(gs.gp(gSobject.route,"params"),"id"))) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"loadEntry",[gs.gp(gs.gp(gSobject.route,"params"),"id"), function(entry) { gs.sp(gSobject.scope,"entry",entry); return gs.sp(gs.gp(gSobject.scope,"entry"),"date",gs.mc(gs.mc(gSobject,"moment",[gs.gp(entry,"date")]),"format",["YYYY-MM-DD HH:mm"])); }]); }; return gs.sp(gSobject.scope,"dialog",false); } gSobject['showDateTimePicker'] = function(it) { gs.sp(gSobject.scope,"showDateTime",true); return gs.println(gs.gp(gSobject.scope,"showDateTime")); } gSobject['handlePopupClick'] = function(it) { return gs.sp(gSobject.scope,"dialog",false); } gSobject['bloodPressureStatus'] = function(systolic, diastolic) { return gs.elvis(gs.bool(gs.gp(gs.mc(gs.list([gs.map().add("systolic",89).add("diastolic",59).add("status","Below Normal") , gs.map().add("systolic",99).add("diastolic",69).add("status","Low Normal") , gs.map().add("systolic",119).add("diastolic",79).add("status","Within Optimal Range") , gs.map().add("systolic",129).add("diastolic",84).add("status","Above Optimal") , gs.map().add("systolic",139).add("diastolic",89).add("status","Slightly Above Range") , gs.map().add("systolic",159).add("diastolic",99).add("status","High") , gs.map().add("systolic",179).add("diastolic",109).add("status","Very High") , gs.map().add("systolic",999).add("diastolic",999).add("status","Severe Hypertension")]),"find",[function(range) { return (systolic < gs.gp(range,"systolic")) && (diastolic < gs.gp(range,"diastolic")); }]),"status",true)) , gs.gp(gs.mc(gs.list([gs.map().add("systolic",89).add("diastolic",59).add("status","Below Normal") , gs.map().add("systolic",99).add("diastolic",69).add("status","Low Normal") , gs.map().add("systolic",119).add("diastolic",79).add("status","Within Optimal Range") , gs.map().add("systolic",129).add("diastolic",84).add("status","Above Optimal") , gs.map().add("systolic",139).add("diastolic",89).add("status","Slightly Above Range") , gs.map().add("systolic",159).add("diastolic",99).add("status","High") , gs.map().add("systolic",179).add("diastolic",109).add("status","Very High") , gs.map().add("systolic",999).add("diastolic",999).add("status","Severe Hypertension")]),"find",[function(range) { return (systolic < gs.gp(range,"systolic")) && (diastolic < gs.gp(range,"diastolic")); }]),"status",true) , "Unknown"); } gSobject['logBloodPressure'] = function(it) { var entry = gs.gp(gSobject.scope,"entry"); if (((gs.bool(gs.gp(entry,"systolic"))) || (gs.bool(gs.gp(entry,"diastolic")))) || (gs.bool(gs.gp(entry,"pulse")))) { var value = "" + (gs.gp(entry,"systolic")) + "/" + (gs.gp(entry,"diastolic")) + ""; }; var status = gs.mc(gSobject,"bloodPressureStatus",[gs.gp(entry,"systolic"), gs.gp(entry,"diastolic")]); var today = gs.mc(gs.mc(gSobject,"moment",[]),"format",["YYYY-MM-DD"]); var date = gs.date(gs.gp(entry,"date")); if (gs.equals(gs.mc(gs.mc(gSobject,"moment",[date]),"format",["YYYY-MM-DD"]), today)) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:blood_pressure:value", value]),"do",[]); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:blood_pressure:status", status]),"do",[]); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:blood_pressure:systolic", gs.gp(entry,"systolic")]),"do",[]); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:blood_pressure:diastolic", gs.gp(entry,"diastolic")]),"do",[]); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:blood_pressure:pulse", gs.gp(entry,"pulse")]),"do",[]); }; if (gs.bool(gs.gp(gs.gp(gSobject.route,"params"),"id"))) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"deleteEntry",[gs.gp(gs.gp(gSobject.route,"params"),"id")]),"do",[]); }; gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"addEntryWithFts",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:blood_pressure", gs.list(["systolic" , "diastolic" , "pulse"]), gs.map().add("value",value).add("status",status).add("systolic",gs.gp(entry,"systolic")).add("diastolic",gs.gp(entry,"diastolic")).add("pulse",gs.gp(entry,"pulse")).add("date",date)]),"then",[function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"eventListener",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gSobject.scope,"entry")]),"do",[]); gs.mc(gSobject,"calculateRisk",[gs.gp(entry,"systolic"), gs.gp(entry,"diastolic")]); gs.mc(gSobject,"saveLastUpdated",[gs.gp(gs.fs('session', this, gSobject),"userId"), "blood_pressure"]); return gs.sp(gSobject.scope,"dialog",true); }, function(error) { return gs.sp(gSobject.scope,"dialog",true); }]); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"notificationService"),"removeNotification",[gs.gp(gs.fs('session', this, gSobject),"userId"), "trackable:Blood Pressure", "Blood Pressure"]),"do",[]); gs.mc(gSobject,"generateAndSaveMotivation",[gs.gp(gs.fs('session', this, gSobject),"userId"), "Blood Pressure", "medical:score:blood_pressure:value"]); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"medicalConditionCalculationService"),"calcAll",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(it) { return "Re-calculating health score"; }]); } gSobject['calculateRisk'] = function(systolic, diastolic) { return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"emergencyCalculationService"),"hypertension",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gs.gp(gs.fs('session', this, gSobject),"user"),"customerRef"), gs.gp(gs.gp(gs.fs('session', this, gSobject),"user"),"displayNameText"), systolic, diastolic]),"do",[]); } gSobject['eventLogBloodPressure'] = function(it) { var narrative = "Logged blood pressure: " + (gs.gp(gs.gp(gSobject.scope,"entry"),"systolic")) + "/" + (gs.gp(gs.gp(gSobject.scope,"entry"),"diastolic")) + " mmHg"; return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"eventLogService"),"event",[gs.gp(gs.fs('session', this, gSobject),"userId"), narrative, "bloodpressure", "info"]),"do",[]); } gSobject['error'] = function(it) { return gs.mc(gSobject,"notify",["Input required", "negative"]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function BloodPressureInsightComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'BloodPressureInsightComponent', simpleName: 'BloodPressureInsightComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/bloodPressureInsight"; gSobject['created'] = function(it) { gs.println("BloodPressureInsightComponent.created()"); gs.sp(gSobject.scope,"batchName","medical:score:blood_pressure"); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.bloodpressure.insight"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[false]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"progress1",0.1); gs.sp(gSobject.scope,"progress2",0.1); gs.sp(gSobject.scope,"progress3",0.1); gs.sp(gSobject.scope,"riskRange",(gs.div(45, 100))); gs.sp(gSobject.scope,"worstEntry",null); gs.sp(gSobject.scope,"bestEntry",null); gs.sp(gSobject.scope,"weeklyAvgDisplay",null); gs.sp(gSobject.scope,"weeklyAvgStatus",""); gs.sp(gSobject.scope,"weekDays",gs.list([gs.map().add("label","M").add("logged",false) , gs.map().add("label","T").add("logged",false) , gs.map().add("label","W").add("logged",false) , gs.map().add("label","T").add("logged",false) , gs.map().add("label","F").add("logged",false) , gs.map().add("label","S").add("logged",false) , gs.map().add("label","S").add("logged",false)])); gs.sp(gSobject.scope,"items",gs.list([gs.map().add("id",0).add("value",4).add("color","#afe3d0").add("label","In range").add("image","check").add("iconColor","#3ab54a") , gs.map().add("id",1).add("value",0).add("color","#deb4b6").add("label","Above range").add("image","glucosePeak").add("iconColor","#b71f25") , gs.map().add("id",2).add("value",3).add("color","#f5ceb5").add("label","Below range").add("image","arrowDown").add("iconColor","#ff751e")])); gs.sp(gSobject.scope,"statusMapper",gs.list([gs.map().add("id",0).add("index","Within Optimal Range").add("displayCategoryId",0).add("color","#afe3d0").add("image","check").add("iconColor","#3ab54a").add("totalCount",0) , gs.map().add("id",1).add("index","Low Normal").add("displayCategoryId",0).add("color","#afe3d0").add("image","check").add("iconColor","#3ab54a").add("totalCount",0) , gs.map().add("id",2).add("index","Above Optimal").add("displayCategoryId",1).add("color","#deb4b6").add("image","glucosePeak").add("iconColor","#b71f25").add("totalCount",0) , gs.map().add("id",3).add("index","Slightly Above Range").add("displayCategoryId",1).add("color","#deb4b6").add("image","glucosePeak").add("iconColor","#b71f25").add("totalCount",0) , gs.map().add("id",4).add("index","High").add("displayCategoryId",1).add("color","#deb4b6").add("image","glucosePeak").add("iconColor","#b71f25").add("totalCount",0) , gs.map().add("id",5).add("index","Very High").add("displayCategoryId",1).add("color","#deb4b6").add("image","glucosePeak").add("iconColor","#b71f25").add("totalCount",0) , gs.map().add("id",6).add("index","Severe Hypertension").add("displayCategoryId",1).add("color","#deb4b6").add("image","glucosePeak").add("iconColor","#b71f25").add("totalCount",0) , gs.map().add("id",7).add("index","Below Normal").add("displayCategoryId",2).add("color","#f5ceb5").add("image","arrowDown").add("iconColor","#ff751e").add("totalCount",0)])); gs.sp(gSobject.scope,"max",gs.elvis(gs.mc(gs.mc(gs.gp(gSobject.scope,"items"),"collect",[function(it) { return gs.gp(it,"value"); }]),"max",[]) , gs.mc(gs.mc(gs.gp(gSobject.scope,"items"),"collect",[function(it) { return gs.gp(it,"value"); }]),"max",[]) , 15)); gs.sp(gSobject.scope,"user",gs.gp(gs.fs('session', this, gSobject),"user")); gs.sp(gSobject.scope,"activeUser",gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"activeUser")); gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"weekEntries",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:blood_pressure-systolic", function(logs) { return gs.mc(gs.gp(logs,"values"),"eachWithIndex",[function(value, index) { if (gs.bool(value)) { return gs.sp((gs.gp(gSobject.scope,"weekDays")[index]),"logged",true); }; }]); }]); gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"listEntries",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gSobject.scope,"batchName"), gs.map().add("limit",31), function(logs) { gs.mc(gs.gp(gSobject.scope,"statusMapper"),"each",[function(it) { return gs.sp(it,"totalCount",0); }]); gs.sp(gSobject.scope,"max",0); gs.mc(logs,"each",[function(entry) { var match = gs.mc(gs.gp(gSobject.scope,"statusMapper"),"find",[function(it) { return gs.equals(gs.gp(it,"index"), gs.gp(entry,"status")); }]); if (gs.bool(match)) { return gs.plusPlus(match,"totalCount",true,false); }; }]); var displayCategories = gs.list([gs.map().add("id",0).add("label","In range").add("image","check").add("iconColor","#3ab54a").add("color","#afe3d0") , gs.map().add("id",1).add("label","Above range").add("image","glucosePeak").add("iconColor","#b71f25").add("color","#deb4b6") , gs.map().add("id",2).add("label","Below range").add("image","arrowDown").add("iconColor","#ff751e").add("color","#f5ceb5")]); gs.sp(gSobject.scope,"items",gs.mc(displayCategories,"collect",[function(category) { var totalValue = gs.elvis(gs.mc(gs.mc(gs.gp(gSobject.scope,"statusMapper"),"findAll",[function(it) { return gs.equals(gs.gp(it,"displayCategoryId"), gs.gp(category,"id")); }]),"sum",[function(it) { return gs.gp(it,"totalCount"); }]) , gs.mc(gs.mc(gs.gp(gSobject.scope,"statusMapper"),"findAll",[function(it) { return gs.equals(gs.gp(it,"displayCategoryId"), gs.gp(category,"id")); }]),"sum",[function(it) { return gs.gp(it,"totalCount"); }]) , 0); gs.sp(gSobject.scope,"max",Math.max(gs.gp(gSobject.scope,"max"), totalValue)); return gs.map().add("id",gs.gp(category,"id")).add("value",totalValue).add("color",gs.gp(category,"color")).add("label",gs.gp(category,"label")).add("image",gs.gp(category,"image")).add("iconColor",gs.gp(category,"iconColor")); }])); return gs.sp(gSobject.scope,"mostLoggedStatus",gs.mc(gs.gp(gSobject.scope,"statusMapper"),"max",[function(it) { return gs.gp(it,"totalCount"); }])); }]); gs.mc(gSobject,"findBestAndWorstBPDay",[]); gs.mc(gSobject,"weeklyAvg",[]); return gs.mc(gs.fs('bloodPressureOverviewComponent', this, gSobject),"loadBloodPressureMinMax",[gs.fs('session', this, gSobject), gSobject.scope]); } gSobject['findBestAndWorstBPDay'] = function(it) { var bestEntry = null; var worstEntry = null; var bestSeverity = 999; var worstSeverity = 0; return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"listEntries",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gSobject.scope,"batchName"), function(logs) { gs.mc(logs,"each",[function(entry) { var systolic = gs.gp(entry,"systolic"); var diastolic = gs.gp(entry,"diastolic"); var category = gs.mc(gSobject,"classifyBP",[systolic, diastolic]); var severity = gs.mc(gSobject,"severityLevel",[category]); if (severity < bestSeverity) { bestSeverity = severity; bestEntry = entry; }; if (severity > worstSeverity) { worstSeverity = severity; return worstEntry = entry; }; }]); gs.sp(gSobject.scope,"bestEntry",bestEntry); return gs.sp(gSobject.scope,"worstEntry",worstEntry); }]); } gSobject['classifyBP'] = function(systolic, diastolic) { if ((systolic < 90) && (diastolic < 60)) { return "Below Normal"; } else { if ((systolic < 100) && (diastolic < 70)) { return "Low Normal"; } else { if ((systolic < 120) && (diastolic < 80)) { return "Within Optimal Range"; } else { if ((systolic < 130) && (diastolic < 85)) { return "Above Optimal"; } else { if ((systolic < 140) && (diastolic < 90)) { return "Slightly Above Range"; } else { if ((systolic < 160) && (diastolic < 100)) { return "High"; } else { if ((systolic < 180) && (diastolic < 110)) { return "Very High"; } else { return "Severe Hypertension"; }; }; }; }; }; }; }; } gSobject['severityLevel'] = function(category) { var gSswitch0 = category; if (gs.equals(gSswitch0, "Below Normal")) { return 0; } else if (gs.equals(gSswitch0, "Low Normal")) { return 1; } else if (gs.equals(gSswitch0, "Within Optimal Range")) { return 2; } else if (gs.equals(gSswitch0, "Above Optimal")) { return 3; } else if (gs.equals(gSswitch0, "Slightly Above Range")) { return 4; } else if (gs.equals(gSswitch0, "High")) { return 5; } else if (gs.equals(gSswitch0, "Very High")) { return 6; } else if (gs.equals(gSswitch0, "Severe Hypertension")) { return 7; } else { return -1; }; } gSobject['weeklyAvg'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"metrics",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:blood_pressure-systolic", gs.date(), "Day", function(systolicLogs) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"metrics",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:blood_pressure-diastolic", gs.date(), "Day", function(diastolicLogs) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"calculateWeeklyAvg",[gs.gp(systolicLogs,"aggAvgValues"), function(sys) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"calculateWeeklyAvg",[gs.gp(diastolicLogs,"aggAvgValues"), function(dia) { var systolicWeeklyAvg = sys; var diastolicWeeklyAvg = dia; gs.println(gs.multiply("=", 20)); gs.println("Systolic Weekly Avg: " + (systolicWeeklyAvg) + ""); gs.println("Diastolic Weekly Avg: " + (diastolicWeeklyAvg) + ""); gs.sp(gSobject.scope,"weeklyAvgDisplay","" + (systolicWeeklyAvg) + "/" + (diastolicWeeklyAvg) + ""); var bpStatus = gs.mc(gSobject,"getBloodPressureStatus",[systolicWeeklyAvg, diastolicWeeklyAvg]); gs.sp(gSobject.scope,"weeklyAvgStatus",bpStatus); return gs.sp(gSobject.scope,"riskMessage",gs.mc(gSobject,"getRiskMessage",[bpStatus])); }]); }]); }]); }]); } gSobject['getBloodPressureStatus'] = function(systolic, diastolic) { if ((systolic > 180) || (diastolic > 120)) { return "Hypertensive Crisis"; } else { if ((systolic >= 140) || (diastolic >= 90)) { return "High (Stage 2)"; } else { if ((systolic >= 130) || (diastolic >= 80)) { return "High (Stage 1)"; } else { if ((systolic >= 120) && (diastolic < 80)) { return "Elevated"; } else { return "Normal"; }; }; }; }; } gSobject['dateFormat'] = function(date) { return gs.mc(gs.mc(gSobject,"moment",[date]),"format",["YYYY-MM-DD"]); } gSobject['getRiskMessage'] = function(status) { var gSswitch0 = status; if (gs.equals(gSswitch0, "Hypertensive Crisis")) { return "Immediate medical attention is required. Your readings indicate a hypertensive crisis. Please consult a healthcare provider urgently."; } else if (gs.equals(gSswitch0, "High (Stage 2)")) { return "Your blood pressure is significantly high. Consult your doctor about treatment options and monitor regularly."; } else if (gs.equals(gSswitch0, "High (Stage 1)")) { return "You are at risk of developing high blood pressure. Consider lifestyle adjustments like reducing sodium intake, exercising more, and managing stress."; } else if (gs.equals(gSswitch0, "Elevated")) { return "Your blood pressure is slightly elevated. Watch your diet, stay active, and monitor regularly to prevent further increase."; } else if (gs.equals(gSswitch0, "Normal")) { return "Your blood pressure is within a healthy range. Maintain your current lifestyle and keep monitoring regularly."; } else { return "Blood pressure data unavailable. Please log your readings for accurate insights."; }; } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function BloodPressureAchievedComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'BloodPressureAchievedComponent', simpleName: 'BloodPressureAchievedComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/bloodPressureAchieved" , "/bloodPressureAchieved/:id"]); gSobject['created'] = function(it) { gs.println("BloodPressureAchieved.created()"); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.bloodpressure.achieved"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[false]); return gs.mc(gSobject,"componentTheme",[false]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function PrivacyActionComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'PrivacyActionComponent', simpleName: 'PrivacyActionComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/privacy-action"; gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "user.privacy.action"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[false]); return gs.mc(gSobject,"componentTheme",[false]); } gSobject['decline'] = function(it) { return gs.execStatic(Utils,'logout', this,["/"]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function I3Container() { var gSobject = VueComponent(); gSobject.clazz = { name: 'I3Container', simpleName: 'I3Container'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.props = gs.map().add("margin",gs.map().add("type",String).add("default","lg")).add("gap",gs.map().add("type",String).add("default","sm")).add("maxWidth",gs.map().add("type",String).add("default","")).add("twoColumn",gs.map().add("type",Boolean).add("default",false)).add("threeColumn",gs.map().add("type",Boolean).add("default",false)); gSobject.data = function(it) { return gs.list([]); }; gSobject['created'] = function(it) { var self = this; } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function CordovaSimBridge() { var gSobject = gs.init('CordovaSimBridge'); gSobject.clazz = { name: 'CordovaSimBridge', simpleName: 'CordovaSimBridge'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.active = false; gSobject.pendingCallbacks = gs.map(); gSobject.eventListeners = gs.map(); gSobject.shouldActivate = function() { return CordovaSimBridge.shouldActivate(); } gSobject['activate'] = function(it) { gSobject.active = true; gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["CordovaSimBridge: ACTIVE — running in simulator mode"]); gs.mc(gSobject,"setupFakeCordova",[]); gs.mc(gSobject,"setupMessageListener",[]); return gs.mc(gSobject,"fireDeviceReady",[]); } gSobject['setupFakeCordova'] = function(it) { gs.mc(gSobject,"createFakePlugins",[]); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["CordovaSimBridge: fake plugin globals created"]); } gSobject.createFakePlugins = function() { var bridge = this; // Core cordova object window.cordova = window.cordova || {}; window.cordova.plugins = window.cordova.plugins || {}; // --- Scanner --- window.cordova.plugins.barcodeScanner = { scan: function(success, error, config) { bridge._storePending('scanner', 'scan', success, error); console.log('[SimBridge] Scanner: waiting for simulated scan...'); // Notify parent we're waiting window.parent.postMessage({type:'cordova-sim-ready', plugin:'scanner', action:'scan'}, '*'); } }; // --- BackgroundGeolocation (cordova-plugin-i3-bggeo) --- window.BackgroundGeolocation = { events: ['location','stationary','activity','start','stop','error','authorization','foreground','background','abort_requested','http_authorization','geofence'], AUTHORIZED: 1, NOT_AUTHORIZED: 0, AUTHORIZED_FOREGROUND: 2, HIGH_ACCURACY: 0, MEDIUM_ACCURACY: 100, LOW_ACCURACY: 1000, PASSIVE_ACCURACY: 10000, BACKGROUND_MODE: 0, FOREGROUND_MODE: 1, GEOFENCE_TRANSITION_ENTER: 1, GEOFENCE_TRANSITION_EXIT: 2, GEOFENCE_TRANSITION_DWELL: 4, PERMISSION_DENIED: 1, LOCATION_UNAVAILABLE: 2, TIMEOUT: 3, DISTANCE_FILTER_PROVIDER: 0, ACTIVITY_PROVIDER: 1, RAW_PROVIDER: 2, LOG_ERROR: 'ERROR', LOG_WARN: 'WARN', LOG_INFO: 'INFO', LOG_DEBUG: 'DEBUG', LOG_TRACE: 'TRACE', _listeners: {}, _config: {}, _geofences: [], _geofenceQueue: [], _status: { isRunning: false, locationServicesEnabled: true, authorization: 1 }, configure: function(config, success, failure) { var bg = window.BackgroundGeolocation; for (var k in (config || {})) bg._config[k] = config[k]; console.log('[SimBridge] BgGeo configured', config); if(success) success(); }, getConfig: function(success, failure) { if(success) success(window.BackgroundGeolocation._config || {}); }, start: function(s,f) { window.BackgroundGeolocation._status.isRunning = true; console.log('[SimBridge] BgGeo started'); if(s) s(); }, stop: function(s,f) { window.BackgroundGeolocation._status.isRunning = false; console.log('[SimBridge] BgGeo stopped'); if(s) s(); }, switchMode: function(m,s,f) { console.log('[SimBridge] BgGeo switchMode', m); if(s) s(); }, getCurrentLocation: function(success, failure, options) { bridge._storePending('gps', 'currentLocation', success, failure); console.log('[SimBridge] GPS: waiting for simulated location...'); window.parent.postMessage({type:'cordova-sim-ready', plugin:'gps', action:'currentLocation'}, '*'); }, on: function(event, fn) { var bg = window.BackgroundGeolocation; if (!bg._listeners[event]) bg._listeners[event] = []; bg._listeners[event].push(fn); return { remove: function() { var arr = bg._listeners[event] || []; for (var i = arr.length - 1; i >= 0; i--) if (arr[i] === fn) arr.splice(i, 1); }}; }, removeAllListeners: function(event) { var bg = window.BackgroundGeolocation; if(event) bg._listeners[event] = []; else bg._listeners = {}; }, checkStatus: function(cb) { var s = window.BackgroundGeolocation._status; if(cb) cb({isRunning: s.isRunning, locationServicesEnabled: s.locationServicesEnabled, authorization: s.authorization}); }, showAppSettings: function() { console.log('[SimBridge] BgGeo showAppSettings'); }, showLocationSettings: function() { console.log('[SimBridge] BgGeo showLocationSettings'); }, addGeofence: function(fence, s, e) { var fences = window.BackgroundGeolocation._geofences; for (var i = fences.length - 1; i >= 0; i--) if (fence && fences[i].id === fence.id) fences.splice(i, 1); if (fence) fences.push(fence); console.log('[SimBridge] BgGeo addGeofence', fence); if(s) s(); }, addGeofences: function(arr, s, e) { var fences = window.BackgroundGeolocation._geofences; arr = arr || []; for (var j = 0; j < arr.length; j++) { var fence = arr[j]; for (var i = fences.length - 1; i >= 0; i--) if (fences[i].id === fence.id) fences.splice(i, 1); fences.push(fence); } console.log('[SimBridge] BgGeo addGeofences count=' + arr.length); if(s) s(); }, removeGeofence: function(id, s, e) { var fences = window.BackgroundGeolocation._geofences; for (var i = fences.length - 1; i >= 0; i--) if (fences[i].id === id) fences.splice(i, 1); console.log('[SimBridge] BgGeo removeGeofence', id); if(s) s(); }, removeGeofences: function(ids, s, e) { var fences = window.BackgroundGeolocation._geofences; ids = ids || []; var idSet = {}; for (var k = 0; k < ids.length; k++) idSet[ids[k]] = true; for (var i = fences.length - 1; i >= 0; i--) if (idSet[fences[i].id]) fences.splice(i, 1); console.log('[SimBridge] BgGeo removeGeofences count=' + ids.length); if(s) s(); }, removeAllGeofences: function(s, e) { window.BackgroundGeolocation._geofences = []; console.log('[SimBridge] BgGeo removeAllGeofences'); if(s) s(); }, getGeofences: function(cb) { if(cb) cb((window.BackgroundGeolocation._geofences || []).slice()); }, getGeofenceEvents: function(cb) { var bg = window.BackgroundGeolocation; var q = (bg._geofenceQueue || []).slice(); bg._geofenceQueue = []; if(cb) cb(q); }, getStationaryLocation: function(s, f) { if(s) s(null); }, // Backward-compat no-ops (matched to plugin's own stubs) getLocations: function(s, f) { if(s) s([]); }, getValidLocations: function(s, f) { if(s) s([]); }, deleteLocation: function(id, s, f) { if(s) s(); }, deleteAllLocations: function(s, f) { if(s) s(); }, getLogEntries: function() { var args = arguments; for (var i = 0; i < args.length; i++) if (typeof args[i] === 'function') { args[i]([]); return; } }, startTask: function(s, f) { if(s) s(0); }, endTask: function(k, s, f) { if(s) s(); }, headlessTask: function(fn, s, f) { if(s) s(); }, forceSync: function(s, f) { if(s) s(); }, isLocationEnabled: function(s, f) { if(s) s(window.BackgroundGeolocation._status.locationServicesEnabled ? 1 : 0); }, }; // --- Bluetooth LE --- window.bluetoothle = { _scanCallback: null, initialize: function(success, params) { if(success) success({status: 'enabled'}); }, isInitialized: function(cb) { if(cb) cb({isInitialized: true}); }, isEnabled: function(cb) { if(cb) cb({isEnabled: true}); }, enable: function(s,e) { if(s) s(); }, startScan: function(success, error, params) { window.bluetoothle._scanCallback = success; if(success) success({status: 'scanStarted'}); console.log('[SimBridge] BLE: scanning, waiting for simulated devices...'); window.parent.postMessage({type:'cordova-sim-ready', plugin:'ble', action:'scan'}, '*'); }, stopScan: function(success, error) { window.bluetoothle._scanCallback = null; if(success) success({status: 'scanStopped'}); }, isScanning: function(cb) { if(cb) cb({isScanning: !!window.bluetoothle._scanCallback}); }, getAdapterInfo: function(cb) { if(cb) cb({name:'Simulated Adapter', address:'00:00:00:00:00:00', isInitialized:true, isEnabled:true, isScanning:false, isDiscoverable:false}); }, connect: function(s,e,p) { if(s) s({status:'connected', address:p.address}); }, disconnect: function(s,e,p) { if(s) s({status:'disconnected', address:p.address}); }, close: function(s,e,p) { if(s) s({status:'closed'}); }, discover: function(s,e,p) { if(s) s({status:'discovered', services:[]}); }, read: function(s,e,p) { if(s) s({status:'read', value:'AAAA'}); }, write: function(s,e,p) { if(s) s({status:'written'}); }, subscribe: function(s,e,p) { if(s) s({status:'subscribed'}); }, unsubscribe: function(s,e,p) { if(s) s({status:'unsubscribed'}); }, }; // --- Social Sharing --- window.plugins = window.plugins || {}; window.plugins.socialsharing = { share: function(msg, subj, files, url, success, failure) { console.log('[SimBridge] Share:', msg, subj, url); if(success) success(); }, shareViaEmail: function(msg, subj, to, cc, bcc, files, success, failure) { console.log('[SimBridge] Email:', msg, subj, to); if(success) success(); }, shareViaSMS: function(opts, phone, success, failure) { console.log('[SimBridge] SMS:', opts, phone); if(success) success(); }, shareViaWhatsApp: function(msg, files, url, success, failure) { console.log('[SimBridge] WhatsApp:', msg); if(success) success(); }, canShareVia: function(via, msg, subj, files, url, success, failure) { if(success) success(); }, available: function(cb) { if(cb) cb(true); }, saveToPhotoAlbum: function(files, s, e) { if(s) s(); }, }; // --- InAppBrowser --- window.cordova.InAppBrowser = { open: function(url, target, options) { console.log('[SimBridge] Browser:', url, target); if (target === '_system' || target === '_blank') { window.parent.postMessage({type:'cordova-sim-event', plugin:'browser', action:'open', data:{url:url, target:target}}, '*'); } return { addEventListener: function(e,cb) {}, removeEventListener: function(e,cb) {}, close: function() {}, show: function() {}, hide: function() {}, executeScript: function(d,cb) { if(cb) cb([]); }, }; } }; // --- Contacts --- window.navigator.contacts = window.navigator.contacts || { find: function(fields, success, error, options) { bridge._storePending('contacts', 'find', success, error); console.log('[SimBridge] Contacts: waiting for simulated contacts...'); window.parent.postMessage({type:'cordova-sim-ready', plugin:'contacts', action:'find', data:{filter: options ? options.filter : ''}}, '*'); }, pickContact: function(success, error) { bridge._storePending('contacts', 'pick', success, error); window.parent.postMessage({type:'cordova-sim-ready', plugin:'contacts', action:'pick'}, '*'); }, create: function(props) { return props || {}; }, fieldType: { displayName:'displayName', phoneNumbers:'phoneNumbers', emails:'emails', name:'name' }, }; // --- Deep Links --- window.universalLinks = { _callbacks: {}, subscribe: function(event, cb) { this._callbacks[event] = cb; }, unsubscribe: function(event) { delete this._callbacks[event]; }, checkDeepLink: function(ms) { return { then: function(cb) { return { catch: function(e) {} }; } }; }, }; // --- Camera --- window.navigator.camera = { getPicture: function(success, failure, opts) { bridge._storePending('camera', 'photo', success, failure); console.log('[SimBridge] Camera: waiting for simulated photo...'); window.parent.postMessage({type:'cordova-sim-ready', plugin:'camera', action:'photo'}, '*'); }, cleanup: function() {}, DestinationType: { FILE_URI: 1, DATA_URL: 0 }, PictureSourceType: { CAMERA: 1, PHOTOLIBRARY: 0 }, }; window.Camera = { EncodingType: { JPEG: 0, PNG: 1 } }; // --- i3 Spinner --- window.i3Spinner = { show: function(opts, success, error) { console.log('[SimBridge] Spinner show:', opts); window.parent.postMessage({type:'cordova-sim-event', plugin:'spinner', action:'show', data:opts}, '*'); if(success) success(); }, hide: function(success, error) { console.log('[SimBridge] Spinner hide'); window.parent.postMessage({type:'cordova-sim-event', plugin:'spinner', action:'hide'}, '*'); if(success) success(); }, }; // --- Fingerprint / Biometrics --- window.Fingerprint = { isAvailable: function(success, error) { bridge._storePending('biometrics', 'available', success, error); window.parent.postMessage({type:'cordova-sim-ready', plugin:'biometrics', action:'available'}, '*'); }, show: function(params, success, error) { bridge._storePending('biometrics', 'auth', success, error); console.log('[SimBridge] Biometrics: waiting for simulated auth...'); window.parent.postMessage({type:'cordova-sim-ready', plugin:'biometrics', action:'auth'}, '*'); }, registerBiometricSecret: function(params, success, error) { if(success) success('registered'); }, loadBiometricSecret: function(params, success, error) { if(success) success('sim-secret-123'); }, }; // --- Device --- window.device = { platform: 'Simulator', model: 'Desktop Browser', version: '1.0', manufacturer: 'Dymico', uuid: 'sim-' + Date.now(), serial: 'SIM000', cordova: '12.0.0', isVirtual: true, }; // --- StatusBar --- window.StatusBar = { show: function() { console.log('[SimBridge] StatusBar show'); }, hide: function() { console.log('[SimBridge] StatusBar hide'); }, overlaysWebView: function(v) { console.log('[SimBridge] StatusBar overlay', v); }, styleDefault: function() {}, styleLightContent: function() {}, backgroundColorByName: function(n) {}, backgroundColorByHexString: function(h) {}, }; // --- Battery (navigator.battery is set by cordova-plugin-battery-status) --- window.navigator.battery = { level: 75, isPlugged: false }; // --- Permissions --- window.cordova.plugins.permissions = { checkPermission: function(perm, success, error) { if(success) success({hasPermission: true}); }, requestPermission: function(perm, success, error) { if(success) success({hasPermission: true}); }, }; // --- Push --- window.PushNotification = { init: function(opts) { var _handlers = {}; var pushObj = { on: function(event, cb) { _handlers[event] = cb; }, _handlers: _handlers, }; // Fire registration after a tick setTimeout(function() { if(_handlers.registration) _handlers.registration({registrationId: 'sim-push-token-' + Date.now()}); }, 500); bridge._simPush = pushObj; return pushObj; } }; // --- Screen Orientation --- // screen.orientation is already available in browsers // --- SpinnerDialog (legacy fallback) --- window.SpinnerDialog = { show: function(t,m,c) { window.i3Spinner.show({message: m || t || '', cancelable: !!c}); }, hide: function() { window.i3Spinner.hide(); }, }; // --- Media --- window.Media = function(src, onSuccess, onError, onStatus) { return { startRecord: function() { console.log('[SimBridge] Media record:', src); }, stopRecord: function() { console.log('[SimBridge] Media stop record'); if(onSuccess) onSuccess(); }, play: function() { console.log('[SimBridge] Media play:', src); }, stop: function() { console.log('[SimBridge] Media stop'); }, release: function() {}, getDuration: function() { return 0; }, getCurrentPosition: function(cb) { if(cb) cb(0); }, }; }; console.log('[SimBridge] All fake Cordova plugins registered'); } gSobject['setupMessageListener'] = function(it) { return gs.mc(gSobject,"listenForMessages",[]); } gSobject.listenForMessages = function() { var bridge = this; window.addEventListener('message', function(event) { var msg = event.data; if (!msg || msg.type !== 'cordova-sim') return; console.log('[SimBridge] Received:', msg.plugin, msg.action, msg.data); switch(msg.plugin) { case 'scanner': if (msg.action === 'result') bridge._firePending('scanner', 'scan', msg.data); if (msg.action === 'cancel') bridge._firePending('scanner', 'scan', {text:'', format:'', cancelled:true}); break; case 'gps': if (msg.action === 'location') { bridge._firePending('gps', 'currentLocation', msg.data); var listeners = window.BackgroundGeolocation._listeners['location'] || []; for (var i = 0; i < listeners.length; i++) { listeners[i](msg.data); } } if (msg.action === 'stationary') { var sListeners = window.BackgroundGeolocation._listeners['stationary'] || []; for (var i = 0; i < sListeners.length; i++) { sListeners[i](msg.data); } } if (msg.action === 'activity') { var aListeners = window.BackgroundGeolocation._listeners['activity'] || []; for (var i = 0; i < aListeners.length; i++) { aListeners[i](msg.data); } } if (msg.action === 'geofence') { var fenceEvent = { fenceId: msg.data.fenceId || msg.data.id, transition: msg.data.transition, location: msg.data.location || null, data: msg.data.data || null, timestamp: msg.data.timestamp || Date.now() }; var bgGf = window.BackgroundGeolocation; bgGf._geofenceQueue = bgGf._geofenceQueue || []; bgGf._geofenceQueue.push(fenceEvent); var gListeners = bgGf._listeners['geofence'] || []; for (var i = 0; i < gListeners.length; i++) { gListeners[i](fenceEvent); } } if (msg.action === 'start' || msg.action === 'stop' || msg.action === 'foreground' || msg.action === 'background' || msg.action === 'abort_requested') { if (msg.action === 'start') window.BackgroundGeolocation._status.isRunning = true; if (msg.action === 'stop') window.BackgroundGeolocation._status.isRunning = false; var lListeners = window.BackgroundGeolocation._listeners[msg.action] || []; for (var i = 0; i < lListeners.length; i++) { lListeners[i](msg.data || {}); } } if (msg.action === 'error') { var eListeners = window.BackgroundGeolocation._listeners['error'] || []; for (var i = 0; i < eListeners.length; i++) { eListeners[i](msg.data); } } if (msg.action === 'authorization') { if (msg.data && typeof msg.data.code !== 'undefined') { window.BackgroundGeolocation._status.authorization = msg.data.code; } var auListeners = window.BackgroundGeolocation._listeners['authorization'] || []; for (var i = 0; i < auListeners.length; i++) { auListeners[i](msg.data); } } if (msg.action === 'http_authorization') { var hListeners = window.BackgroundGeolocation._listeners['http_authorization'] || []; for (var i = 0; i < hListeners.length; i++) { hListeners[i](msg.data || {}); } } if (msg.action === 'status') { if (msg.data && typeof msg.data === 'object') { var st = window.BackgroundGeolocation._status; for (var k in msg.data) st[k] = msg.data[k]; } } break; case 'ble': if (msg.action === 'device' && window.bluetoothle._scanCallback) { window.bluetoothle._scanCallback({status:'scanResult', name:msg.data.name, address:msg.data.address, rssi:msg.data.rssi}); } break; case 'camera': if (msg.action === 'photo') bridge._firePending('camera', 'photo', msg.data.uri || msg.data); break; case 'contacts': if (msg.action === 'results') bridge._firePending('contacts', 'find', msg.data); if (msg.action === 'picked') bridge._firePending('contacts', 'pick', msg.data); break; case 'deeplink': if (msg.action === 'trigger') { var dl = window.universalLinks._callbacks; for (var key in dl) { if (dl[key]) dl[key](msg.data); } } break; case 'battery': if (msg.action === 'status') { window.navigator.battery = msg.data; var evt = new CustomEvent('batterystatus', {detail: msg.data}); window.dispatchEvent(evt); } break; case 'network': if (msg.action === 'status') { var evtName = msg.data.online ? 'online' : 'offline'; document.dispatchEvent(new Event(evtName)); } break; case 'biometrics': if (msg.action === 'available') bridge._firePending('biometrics', 'available', msg.data.result || {biometryType:'face'}); if (msg.action === 'pass') bridge._firePending('biometrics', 'auth', msg.data || 'success'); if (msg.action === 'fail') bridge._firePendingError('biometrics', 'auth', msg.data || 'cancelled'); break; case 'push': if (msg.action === 'notification' && bridge._simPush && bridge._simPush._handlers.notification) { bridge._simPush._handlers.notification(msg.data); } break; } }); console.log('[SimBridge] postMessage listener registered'); } gSobject['fireDeviceReady'] = function(it) { return gs.mc(gSobject,"fireDeviceReadyEvent",[]); } gSobject.fireDeviceReadyEvent = function() { // Fire deviceready after a short delay so all plugins are set up setTimeout(function() { document.dispatchEvent(new Event('deviceready')); console.log('[SimBridge] deviceready fired'); }, 500); } gSobject._storePending = function(plugin, action, success, error) { var key = plugin + ':' + action; this.pendingCallbacks[key] = { success: success, error: error }; } gSobject._firePending = function(plugin, action, data) { var key = plugin + ':' + action; var pending = this.pendingCallbacks[key]; if (pending && pending.success) { pending.success(data); delete this.pendingCallbacks[key]; } } gSobject._firePendingError = function(plugin, action, data) { var key = plugin + ':' + action; var pending = this.pendingCallbacks[key]; if (pending && pending.error) { pending.error(data); delete this.pendingCallbacks[key]; } } gSobject['CordovaSimBridge0'] = function(it) { if (CordovaSimBridge.shouldActivate()) { gs.mc(gSobject,"activate",[]); }; return this; } if (arguments.length==0) {gSobject.CordovaSimBridge0(); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; CordovaSimBridge.shouldActivate = function() { // Activate in iframe without real Cordova, or when simulator flag is set by /cordova/header return (window.parent !== window) && ((typeof window.cordova === 'undefined') || window.__dymicoSimulator === true); } function ProfileComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'ProfileComponent', simpleName: 'ProfileComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/profile" , "/profile/:onboarding"]); gSobject.onMedicalAidChange = function(selectedProvider) { var normalized = gs.mc(selectedProvider,"toLowerCase",[], null, true); gs.sp(gSobject.scope,"filteredPlanOptions",gs.elvis(gs.gp(gSobject.scope,"planOptions")[normalized] , gs.gp(gSobject.scope,"planOptions")[normalized] , gs.list([]))); return gs.sp(gs.gp(gSobject.scope,"rxmeUser"),"medAidProvider",selectedProvider); }; gSobject.openQrShare = function(it) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/qrcode"]); }; gSobject.forceLogout = function(it) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/signIn"]); }; gSobject['created'] = function(it) { gs.println("ProfileComponent.created()"); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "profile.home.page"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"loading",false); gs.sp(gSobject.scope,"appVersion",gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"appVersion")); gs.sp(gSobject.scope,"deviceAppVersion",gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"deviceAppVersion")); gs.sp(gSobject.scope,"appRightsYear",gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"appRightsYear")); gs.sp(gSobject.scope,"user",gs.gp(gs.fs('session', this, gSobject),"user")); gs.sp(gSobject.scope,"birthDate",gs.mc(gSobject,"fetchReadableDate",[gs.gp(gs.gp(gSobject.scope,"user"),"birthDate")])); gs.sp(gSobject.scope,"activeUser",gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"activeUser")); gs.sp(gSobject.scope,"hasCompletedFullHealthQn",false); gs.sp(gSobject.scope,"profileEditDialog",false); gs.sp(gSobject.scope,"showDate",false); gs.sp(gSobject.scope,"heightDialog",false); gs.sp(gSobject.scope,"heightValue",170); gs.sp(gSobject.scope,"motivational",gs.map()); gs.sp(gSobject.scope,"importProfileDialog",false); gs.sp(gSobject.scope,"otpVerificationDialog",false); gs.sp(gSobject.scope,"portalEmail",""); gs.sp(gSobject.scope,"portalPatientData",null); gs.sp(gSobject.scope,"pinValues",gs.list(["" , "" , "" , "" , "" , ""])); gs.sp(gSobject.scope,"otpError",""); gs.sp(gSobject.scope,"verifyingOtp",false); gs.sp(gSobject.scope,"isOnboarding",false); if (gs.bool(gs.gp(gs.gp(gSobject.route,"params"),"onboarding"))) { gs.sp(gSobject.scope,"profileEditDialog",true); gs.sp(gSobject.scope,"isOnboarding",true); }; gs.sp(gSobject.scope,"idConflictDialog",false); gs.sp(gSobject.scope,"idConflictEmail",""); gs.sp(gSobject.scope,"ethnicity",""); gs.sp(gSobject.scope,"race",gs.list(["Black" , "White" , "Asian" , "Indian" , "Coloured"])); gs.sp(gSobject.scope,"marriageStatus",""); gs.sp(gSobject.scope,"status",gs.list(["Single" , "Married" , "Divorced" , "Widowed" , "Separated"])); gs.sp(gSobject.scope,"emergencyContactRelation",""); gs.sp(gSobject.scope,"emergencyContactRelationStatus",gs.list(["Parent" , "Spouse" , "Sibling" , "Child" , "Friend" , "Partner" , "Legal Guardian" , "Other"])); gs.sp(gSobject.scope,"genderOptions",gs.list(["Female" , "Male"])); gs.sp(gSobject.scope,"idOptions",gs.list(["RSA ID" , "Passport"])); gs.sp(gSobject.scope,"gender","Male"); gs.sp(gSobject.scope,"medicalAidProviders",gs.list(["No Medical Aid" , "Bestmed" , "Bonitas" , "Cape Medical" , "Compcare" , "Discovery" , "Fedhealth" , "Gems" , "Genesis" , "Keyhealth" , "Medimed" , "Medihelp" , "Medshield" , "Momentum" , "Profmed" , "Sizwe" , "Suremed"])); gs.sp(gSobject.scope,"planOptions",gs.map().add("bestmed",gs.list([gs.map().add("id","beat_1").add("label","Beat 1") , gs.map().add("id","beat_1_network").add("label","Beat 1 Network") , gs.map().add("id","beat_2").add("label","Beat 2") , gs.map().add("id","beat_2_network").add("label","Beat 2 Network") , gs.map().add("id","beat_3").add("label","Beat 3") , gs.map().add("id","beat_3_network").add("label","Beat 3 Network") , gs.map().add("id","beat_3_plus").add("label","Beat 3 Plus") , gs.map().add("id","beat_4").add("label","Beat 4") , gs.map().add("id","pulse_1").add("label","Pulse 1") , gs.map().add("id","pulse_2").add("label","Pulse 2") , gs.map().add("id","pulse_3").add("label","Pulse 3") , gs.map().add("id","pulse_4").add("label","Pulse 4") , gs.map().add("id","rhythm_1").add("label","Rhythm 1") , gs.map().add("id","rhythm_2").add("label","Rhythm 2")])).add("bonitas",gs.list([gs.map().add("id","boncap").add("label","BonCap") , gs.map().add("id","bonclassic").add("label","BonClassic") , gs.map().add("id","boncomplete").add("label","BonComplete") , gs.map().add("id","boncomprehensive").add("label","BonComprehensive") , gs.map().add("id","bonessential").add("label","BonEssential") , gs.map().add("id","bonessential_select").add("label","BonEssential Select") , gs.map().add("id","bonfit_select").add("label","BonFit Select") , gs.map().add("id","bonsave").add("label","BonSave") , gs.map().add("id","bonstart").add("label","BonStart") , gs.map().add("id","bonstart_plus").add("label","BonStart Plus") , gs.map().add("id","hospital_standard").add("label","Hospital Standard") , gs.map().add("id","primary").add("label","Primary") , gs.map().add("id","primary_select").add("label","Primary Select") , gs.map().add("id","standard").add("label","Standard")])).add("cape medical",gs.list([gs.map().add("id","100_saver").add("label","100 Saver") , gs.map().add("id","cape_medical_200").add("label","Cape Medical 200")])).add("compcare",gs.list([gs.map().add("id","execucare").add("label","ExecuCare") , gs.map().add("id","execucare_plus").add("label","ExecuCare Plus") , gs.map().add("id","extracare").add("label","ExtraCare") , gs.map().add("id","savercare_plus").add("label","SaverCare Plus") , gs.map().add("id","selfcare_plus").add("label","SelfCare Plus") , gs.map().add("id","ultracare").add("label","UltraCare") , gs.map().add("id","ultracare_plus").add("label","UltraCare Plus")])).add("discovery",gs.list([gs.map().add("id","active_smart").add("label","Active Smart") , gs.map().add("id","classic_comprehensive").add("label","Classic Comprehensive") , gs.map().add("id","classic_core").add("label","Classic Core") , gs.map().add("id","classic_delta_core").add("label","Classic Delta Core") , gs.map().add("id","classic_delta_saver").add("label","Classic Delta Saver") , gs.map().add("id","classic_priority").add("label","Classic Priority") , gs.map().add("id","classic_saver").add("label","Classic Saver") , gs.map().add("id","classic_smart").add("label","Classic Smart") , gs.map().add("id","coastal_core").add("label","Coastal Core") , gs.map().add("id","coastal_saver").add("label","Coastal Saver") , gs.map().add("id","dynamic_smart").add("label","Dynamic Smart") , gs.map().add("id","essential_core").add("label","Essential Core") , gs.map().add("id","essential_delta_core").add("label","Essential Delta Core") , gs.map().add("id","essential_delta_saver").add("label","Essential Delta Saver") , gs.map().add("id","essential_priority").add("label","Essential Priority") , gs.map().add("id","essential_saver").add("label","Essential Saver") , gs.map().add("id","essential_smart").add("label","Essential Smart") , gs.map().add("id","executive").add("label","Executive") , gs.map().add("id","keycare_core_income_based").add("label","KeyCare Core (income based)") , gs.map().add("id","keycare_plus_income_based").add("label","KeyCare Plus (income based)") , gs.map().add("id","keycare_start_income_based").add("label","KeyCare Start (income based)") , gs.map().add("id","keycare_start_regional_income_based").add("label","KeyCare Start Regional (income based)") , gs.map().add("id","smart_comprehensive").add("label","Smart Comprehensive")])).add("fedhealth",gs.list([gs.map().add("id","flexifed_1_elect").add("label","FlexiFed 1 Elect") , gs.map().add("id","flexifed_1_main").add("label","FlexiFed 1 Main") , gs.map().add("id","flexifed_2_any").add("label","FlexiFed 2 Any") , gs.map().add("id","flexifed_2_elect").add("label","FlexiFed 2 Elect") , gs.map().add("id","flexifed_2_grid").add("label","FlexiFed 2 Grid") , gs.map().add("id","flexifed_3_any").add("label","FlexiFed 3 Any") , gs.map().add("id","flexifed_3_elect").add("label","FlexiFed 3 Elect") , gs.map().add("id","flexifed_3_grid").add("label","FlexiFed 3 Grid") , gs.map().add("id","flexifed_4_any").add("label","FlexiFed 4 Any") , gs.map().add("id","flexifed_4_elect").add("label","FlexiFed 4 Elect") , gs.map().add("id","flexifed_4_grid").add("label","FlexiFed 4 Grid") , gs.map().add("id","flexifed_savvy").add("label","FlexiFed Savvy") , gs.map().add("id","maxima_exec").add("label","Maxima Exec") , gs.map().add("id","maxima_plus").add("label","Maxima Plus")])).add("genesis",gs.list([gs.map().add("id","med_100").add("label","Med 100") , gs.map().add("id","med_200").add("label","Med 200") , gs.map().add("id","med_200_plus").add("label","Med 200 Plus")])).add("keyhealth",gs.list([gs.map().add("id","equillibrium").add("label","Equillibrium") , gs.map().add("id","essence").add("label","Essence") , gs.map().add("id","gold").add("label","Gold") , gs.map().add("id","origin").add("label","Origin") , gs.map().add("id","platinum").add("label","Platinum") , gs.map().add("id","silver").add("label","Silver")])).add("medihelp",gs.list([gs.map().add("id","medadd").add("label","MedAdd") , gs.map().add("id","medadd_elect").add("label","MedAdd Elect") , gs.map().add("id","medelect").add("label","MedElect") , gs.map().add("id","medelite").add("label","MedElite") , gs.map().add("id","medmove").add("label","MedMove") , gs.map().add("id","medmove_student").add("label","MedMove Student") , gs.map().add("id","medplus").add("label","MedPlus") , gs.map().add("id","medprime").add("label","MedPrime") , gs.map().add("id","medprime_elect").add("label","MedPrime Elect") , gs.map().add("id","medsaver").add("label","MedSaver") , gs.map().add("id","medvital").add("label","MedVital") , gs.map().add("id","medvital_elect").add("label","MedVital Elect")])).add("medihelp",gs.list([gs.map().add("id","medadd").add("label","MedAdd") , gs.map().add("id","medadd_elect").add("label","MedAdd Elect") , gs.map().add("id","medelect").add("label","MedElect") , gs.map().add("id","medelite").add("label","MedElite") , gs.map().add("id","medmove").add("label","MedMove") , gs.map().add("id","medmove_student").add("label","MedMove Student") , gs.map().add("id","medplus").add("label","MedPlus") , gs.map().add("id","medprime").add("label","MedPrime") , gs.map().add("id","medprime_elect").add("label","MedPrime Elect") , gs.map().add("id","medsaver").add("label","MedSaver") , gs.map().add("id","medvital").add("label","MedVital") , gs.map().add("id","medvital_elect").add("label","MedVital Elect")])).add("medimed",gs.list([gs.map().add("id","alpha").add("label","Alpha") , gs.map().add("id","essential").add("label","Essential") , gs.map().add("id","max").add("label","Max") , gs.map().add("id","standard").add("label","Standard")])).add("medshield",gs.list([gs.map().add("id","mediCurve").add("label","MediCurve") , gs.map().add("id","premiumPlus").add("label","Premium Plus") , gs.map().add("id","mediPhila").add("label","MediPhila") , gs.map().add("id","mediValue").add("label","MediValue") , gs.map().add("id","mediValueCompact").add("label","MediValue Compact") , gs.map().add("id","mediCore").add("label","MediCore") , gs.map().add("id","mediPlus").add("label","MediPlus") , gs.map().add("id","mediPlusCompact").add("label","MediPlus Compact") , gs.map().add("id","mediSaver").add("label","MediSaver") , gs.map().add("id","mediBonus").add("label","MediBonus")])).add("momentum",gs.list([gs.map().add("id","custom_any").add("label","Custom (Any provider for chronic)") , gs.map().add("id","custom_network").add("label","Custom (Network provider for chronic)") , gs.map().add("id","custom_network_any").add("label","Custom Network (Any provider for chronic)") , gs.map().add("id","custom_network_network").add("label","Custom Network (Network provider for chronic)") , gs.map().add("id","custom_network_state").add("label","Custom Network (State provider for chronic)") , gs.map().add("id","custom_state").add("label","Custom (State provider for chronic)") , gs.map().add("id","evolve").add("label","Evolve") , gs.map().add("id","extender_any").add("label","Extender (Any provider for chronic)") , gs.map().add("id","extender_network").add("label","Extender (Network provider for chronic)") , gs.map().add("id","extender_network_any").add("label","Extender Network (Any provider for chronic)") , gs.map().add("id","extender_network_network").add("label","Extender Network (Network provider for chronic)") , gs.map().add("id","extender_network_state").add("label","Extender Network (State provider for chronic)") , gs.map().add("id","extender_state").add("label","Extender (State provider for chronic)") , gs.map().add("id","incentive_any").add("label","Incentive (Any provider for chronic)") , gs.map().add("id","incentive_network").add("label","Incentive (Network provider for chronic)") , gs.map().add("id","incentive_network_any").add("label","Incentive Network (Any provider for chronic)") , gs.map().add("id","incentive_network_network").add("label","Incentive Network (Network provider for chronic)") , gs.map().add("id","incentive_network_state").add("label","Incentive Network (State provider for chronic)") , gs.map().add("id","incentive_state").add("label","Incentive (State provider for chronic)") , gs.map().add("id","ingwe").add("label","Ingwe") , gs.map().add("id","ingwe_network").add("label","Ingwe Network") , gs.map().add("id","ingwe_state").add("label","Ingwe State") , gs.map().add("id","summit").add("label","Summit")])).add("profmed",gs.list([gs.map().add("id","proactive_plus_premium").add("label","ProActive Plus Premium") , gs.map().add("id","proactive_plus_savvy").add("label","ProActive Plus Savvy") , gs.map().add("id","propinnacle_premium").add("label","ProPinnacle Premium") , gs.map().add("id","propinnacle_savvy").add("label","ProPinnacle Savvy") , gs.map().add("id","prosecure_plus_premium").add("label","ProSecure Plus Premium") , gs.map().add("id","prosecure_plus_savvy").add("label","ProSecure Plus Savvy") , gs.map().add("id","prosecure_premium").add("label","ProSecure Premium") , gs.map().add("id","prosecure_savvy").add("label","ProSecure Savvy") , gs.map().add("id","proselect_premium").add("label","ProSelect Premium") , gs.map().add("id","proselect_savvy").add("label","ProSelect Savvy")])).add("sizwe",gs.list([gs.map().add("id","access_core").add("label","Access Core") , gs.map().add("id","access_saver_25").add("label","Access SAver 25%") , gs.map().add("id","essential_copper").add("label","Essential Copper") , gs.map().add("id","gold_ascend").add("label","Gold Ascend") , gs.map().add("id","gold_ascend_edo").add("label","Gold Ascend EDO") , gs.map().add("id","titanium_executive").add("label","Titanium Executive") , gs.map().add("id","value_platinum").add("label","Value Platinum") , gs.map().add("id","value_platinum_core").add("label","Value Platinum Core")])).add("suremed",gs.list([gs.map().add("id","challenger").add("label","Challenger") , gs.map().add("id","explorer").add("label","Explorer") , gs.map().add("id","navigator").add("label","Navigator") , gs.map().add("id","shuttle").add("label","Shuttle")])).add("gems",gs.list([gs.map().add("id","beryl").add("label","Beryl") , gs.map().add("id","emerald").add("label","Emerald") , gs.map().add("id","emerald_value").add("label","Emerald Value") , gs.map().add("id","onyx").add("label","Onyx") , gs.map().add("id","ruby").add("label","Ruby") , gs.map().add("id","tanzanite_one").add("label","Tanzanite One")]))); gs.sp(gSobject.scope,"medicalAidOptions",gs.list(["No Medical Aid" , "Hospital Plan" , "Discovery Health Options" , "Bestmed Options" , "Medihelp Options" , "Momentum Options" , "Fedhealth Options" , "Medshield Options" , "Bonitas Options" , "KeyHealth Options" , "Genesis Options" , "CompCare Options" , "Profmed Options" , "Liberty Options" , "Bankmed Options" , "Sizwe Options"])); gs.sp(gSobject.scope,"provinces",gs.list(["Eastern Cape" , "Free State" , "Gauteng" , "KwaZulu-Natal" , "Limpopo" , "Mpumalanga" , "Northern Cape" , "North West" , "Western Cape"])); gs.sp(gSobject.scope,"selectedMedicalAidProvider",""); gs.sp(gSobject.scope,"selectedPlan",""); gs.sp(gSobject.scope,"filteredPlanOptions",gs.list([])); gs.sp(gSobject.scope,"profileIcon",gs.gp(gs.fs('svgIconsComponent', this, gSobject),"profileIcon")); gs.sp(gSobject.scope,"medicalRecordsIcon",gs.gp(gs.fs('svgIconsComponent', this, gSobject),"medicalRecordsIcon")); gs.sp(gSobject.scope,"aiSettingsIcon",gs.gp(gs.fs('svgIconsComponent', this, gSobject),"aiSettingsIcon")); gs.sp(gSobject.scope,"liveChatIcon",gs.gp(gs.fs('svgIconsComponent', this, gSobject),"liveChatIcon")); gs.sp(gSobject.scope,"qrCodeIcon",gs.gp(gs.fs('svgIconsComponent', this, gSobject),"qrCodeIcon")); gs.sp(gSobject.scope,"healthApiIcon",gs.gp(gs.fs('svgIconsComponent', this, gSobject),"healthApiIcon")); gs.sp(gSobject.scope,"enrolmentStatus",""); gs.mc(gSobject,"checkFullHealthQnStatus",[]); gs.mc(gSobject,"loadRxmeUser",[]); gs.mc(gSobject,"loadHeight",[]); gs.mc(gSobject,"loadUser",[]); return gs.mc(gSobject,"checkEnrolmentStatus",[]); } gSobject['checkEnrolmentStatus'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "person:fha:complete", function(result) { if (!gs.bool(result)) { gs.sp(gSobject.scope,"enrolmentStatus","Patient"); }; if ((gs.bool(result)) && (!gs.bool(gs.gp(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"portalPatient"),"has_nurse_initial_call",true)))) { gs.sp(gSobject.scope,"enrolmentStatus","Enrolment pending"); }; if (gs.bool(gs.gp(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"portalPatient"),"has_nurse_initial_call",true))) { gs.sp(gSobject.scope,"enrolmentStatus","Member"); }; return gs.println("Patient enrolment status: " + (gs.gp(gSobject.scope,"enrolmentStatus")) + ""); }]); } gSobject['checkFullHealthQnStatus'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protocolQuestionnaireAppService"),"hasCompletedQuestionnaire",[gs.gp(gs.fs('session', this, gSobject),"userId"), "Full Health Assessment", function(result) { gs.sp(gSobject.scope,"hasCompletedFullHealthQn",!!result); return gs.println(gs.plus("Completed Full Health: ", gs.gp(gSobject.scope,"hasCompletedFullHealthQn"))); }]); } gSobject['loadHeight'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "health:height", function(result) { if (gs.bool(result)) { gs.sp(gSobject.scope,"heightValue",result); }; return gs.println("Loaded height: " + (gs.gp(gSobject.scope,"heightValue")) + ""); }]); } gSobject['openHeightDialog'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "open.height.dialog"]),"do",[]); return gs.sp(gSobject.scope,"heightDialog",true); } gSobject['saveHeight'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "health:height", gs.gp(gSobject.scope,"heightValue")]),"do",[]); gs.sp(gSobject.scope,"heightDialog",false); gs.mc(gSobject,"notify",["Height updated successfully"]); return gs.println("Saved height: " + (gs.gp(gSobject.scope,"heightValue")) + ""); } gSobject['loadRxmeUser'] = function(it) { gs.sp(gSobject.scope,"rxmeUser",gs.map()); gs.println("session.user._dateCreated"); gs.println(gs.gp(gs.gp(gs.fs('session', this, gSobject),"user"),"_dateCreated")); gs.sp(gSobject.scope,"dateCreated",gs.mc(gs.mc(gSobject,"moment",[gs.gp(gs.gp(gs.fs('session', this, gSobject),"user"),"_dateCreated")]),"format",["DD MMM YYYY"])); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"loadRxmeUser",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(rxmeUser) { gs.sp(gSobject.scope,"rxmeUser",rxmeUser); gs.sp(gs.gp(gSobject.scope,"rxmeUser"),"idType",(gs.gp(gSobject.scope,"idOptions")[0])); gs.sp(gSobject.scope,"selectedMedicalAidProvider",gs.gp(rxmeUser,"medAidProvider")); gs.mc(gs.gp(gs.fs('o', this, gSobject),"medicalCalculationService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "person:gender", function(identity) { return gs.sp(gs.gp(gSobject.scope,"rxmeUser"),"gender",identity); }]); var normalized = gs.mc(gs.gp(gSobject.scope,"selectedMedicalAidProvider"),"toLowerCase",[], null, true); return gs.sp(gSobject.scope,"filteredPlanOptions",gs.elvis(gs.gp(gSobject.scope,"planOptions")[normalized] , gs.gp(gSobject.scope,"planOptions")[normalized] , gs.list([]))); }]); } gSobject['loadUser'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"loadLegionUser",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(user) { return gs.sp(gSobject.scope,"user",user); }]); } gSobject['openLink'] = function(link) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",[link]); } gSobject['goToPolicy'] = function(it) { return gs.mc(gSobject,"confirmDelete",[]); } gSobject['fetchReadableDate'] = function(date) { if (!gs.bool(date)) { date = gs.date(); }; return gs.mc(gs.mc(gSobject,"moment",[date]),"format",["YYYY-MM-DD"]); } gSobject['prependIcon'] = function(it) { var selectedOption = gs.mc(gs.gp(gSobject.scope,"genderOptions"),"find",[function(it) { return gs.equals(gs.gp(it,"value"), gs.gp(gs.gp(gSobject.scope,"gender"),"value")); }]); return gs.elvis(gs.bool(gs.gp(selectedOption,"icon",true)) , gs.gp(selectedOption,"icon",true) , "wc"); } gSobject['save'] = function(it) { if (gs.equals(gs.gp(gs.gp(gSobject.scope,"rxmeUser"),"idType"), "RSA ID")) { if ((!gs.bool(gs.gp(gs.gp(gSobject.scope,"rxmeUser"),"idCardFront"))) || (!gs.bool(gs.gp(gs.gp(gSobject.scope,"rxmeUser"),"idCardBack")))) { gs.mc(gSobject,"popup",["Missing ID Photos", "Please upload both the front and back of your RSA ID before saving."]); return null; }; } else { if (gs.equals(gs.gp(gs.gp(gSobject.scope,"rxmeUser"),"idType"), "Passport")) { if (!gs.bool(gs.gp(gs.gp(gSobject.scope,"rxmeUser"),"passportCardFront"))) { gs.mc(gSobject,"popup",["Missing Passport Photos", "Please upload the front of your passport before saving."]); return null; }; }; }; gs.sp(gSobject.scope,"loading",true); gs.sp(gs.fs('user', this, gSobject),"birthDate",gs.date(gs.gp(gSobject.scope,"birthDate"))); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"updateUserInfo",[gs.gp(gSobject.scope,"user"), gs.gp(gSobject.scope,"rxmeUser"), function(merged) { if (gs.bool(gs.gp(merged,"user"))) { gs.sp(gSobject.scope,"user",gs.gp(merged,"user")); }; if (gs.bool(gs.gp(merged,"rxmeUser"))) { gs.sp(gSobject.scope,"rxmeUser",gs.gp(merged,"rxmeUser")); }; gs.sp(gs.fs('session', this, gSobject),"user",gs.gp(merged,"user")); return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"portalPatient",[gs.gp(gs.fs('session', this, gSobject),"userId")]),"then",[function(portalUser) { gs.println("Portal Patient Data:"); gs.println(portalUser); gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["App user pushed to portal: " + (portalUser) + ""]); return gs.mc(gSobject,"patientUpdated",[]); }, function(error) { gs.println("error message"); gs.println(error); return gs.mc(gSobject,"notify",["" + (gs.gp(error,"message")) + "", "negative"]); }]); }]); } gSobject['checkIdMatch'] = function(it) { gs.println("ID field deselcted"); if ((!gs.bool(gs.gp(gs.gp(gSobject.scope,"user"),"idNo",true))) || (gs.mc(gs.gp(gs.gp(gSobject.scope,"user"),"idNo"),"length",[]) < 13)) { return null; }; gs.println(gs.gp(gs.gp(gSobject.scope,"user"),"idNo",true)); gs.sp(gSobject.scope,"loading",true); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"checkIdMatchFlow",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gs.gp(gSobject.scope,"user"),"idNo"), function(result) { gs.sp(gSobject.scope,"loading",false); gs.println("result"); gs.println(result); if (gs.bool(gs.gp(result,"conflict"))) { gs.sp(gSobject.scope,"conflictEmail",gs.gp(result,"conflictEmail")); gs.sp(gSobject.scope,"idConflictDialog",true); return null; }; if (gs.bool(gs.gp(result,"portalEmail"))) { gs.sp(gSobject.scope,"portalEmail",gs.gp(result,"portalEmail")); gs.sp(gSobject.scope,"portalPatientData",gs.gp(result,"portalPatient")); gs.sp(gSobject.scope,"importProfileDialog",true); return null; }; }]); } gSobject['requestOtp'] = function(it) { gs.sp(gSobject.scope,"loading",true); return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"legionAuthService"),"generatePinForExistingUser",[gs.gp(gSobject.scope,"portalEmail"), false]),"then",[function(result) { gs.sp(gSobject.scope,"loading",false); gs.mc(gSobject,"notify",[gs.plus("Verification PIN sent to ", gs.gp(gSobject.scope,"portalEmail"))]); gs.sp(gSobject.scope,"pinValues",gs.list(["" , "" , "" , "" , "" , ""])); gs.sp(gSobject.scope,"otpError",""); gs.sp(gSobject.scope,"importProfileDialog",false); gs.sp(gSobject.scope,"otpVerificationDialog",true); return gs.sp(gSobject.scope,"correctPin",result); }, function(error) { gs.sp(gSobject.scope,"loading",false); return gs.mc(gSobject,"notify",[gs.elvis(gs.bool(gs.gp(error,"message")) , gs.gp(error,"message") , "Failed to send PIN"), "negative"]); }]); } gSobject['verifyOtpAndImport'] = function(it) { var pin = gs.mc(gs.gp(gSobject.scope,"pinValues"),"join",[""]); if (gs.mc(pin,"length",[]) != 6) { gs.sp(gSobject.scope,"otpError","Please enter all 6 digits"); return null; }; gs.sp(gSobject.scope,"verifyingOtp",true); gs.sp(gSobject.scope,"otpError",""); return gs.mc(gSobject,"verifyPinAndSyncProfile",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gSobject.scope,"portalEmail"), pin, gs.gp(gSobject.scope,"portalPatientData")]); } gSobject['verifyPinAndSyncProfile'] = function(userId, portalEmail, pin, portalPatientData) { if (gs.equals(gs.gp(gSobject.scope,"correctPin"), pin)) { return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"updateUserInfo",[gs.gp(gSobject.scope,"user"), gs.gp(gSobject.scope,"rxmeUser")]),"then",[function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"syncPortalPatientToUser",[userId, portalPatientData, function(response) { gs.sp(gSobject.scope,"verifyingOtp",false); gs.sp(gSobject.scope,"otpVerificationDialog",false); gs.mc(gSobject,"notify",["Profile imported successfully!"]); gs.mc(gSobject,"loadRxmeUser",[]); return gs.mc(gSobject,"loadUser",[]); }]); }, function(error) { gs.println("Failed to import"); return gs.mc(gSobject,"notify",["Import failed!", "negative"]); }]); } else { return gs.println("pin wrong"); }; } gSobject['cancelOtpVerification'] = function(it) { gs.sp(gSobject.scope,"otpVerificationDialog",false); gs.sp(gSobject.scope,"pinValues",gs.list(["" , "" , "" , "" , "" , ""])); return gs.sp(gSobject.scope,"otpError",""); } gSobject['patientUpdated'] = function(it) { gs.sp(gSobject.scope,"profileEditDialog",false); gs.sp(gSobject.scope,"loading",false); gs.mc(gSobject,"notify",["Profile updated successfully"]); if (!gs.bool(gs.gp(gs.gp(gSobject.route,"params"),"onboarding"))) { gs.mc(gSobject,"mapUsers",[gs.gp(gSobject.scope,"user"), gs.gp(gSobject.scope,"rxmeUser")]); }; gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["User: " + (gs.gp(gs.fs('session', this, gSobject),"user")) + ""]); if (gs.bool(gs.gp(gs.gp(gSobject.route,"params"),"onboarding"))) { gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/phoneSetup" + ((gs.bool(gs.gp(gs.gp(gSobject.scope,"user"),"cellphone")) ? gs.plus("/", gs.gp(gs.gp(gSobject.scope,"user"),"cellphone")) : "")) + ""]); gs.sp(gSobject.scope,"profileEditDialog",true); }; return gs.mc(gSobject,"loadRxmeUser",[]); } gSobject['mapUsers'] = function(appUser, rxmeUser) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppApiService"),"updatePatient",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(response) { gs.println("Response:"); return gs.println(response); }]); } gSobject['verifyPhone'] = function(it) { return gs.mc(gs.mc(gSobject.q,"dialog",[gs.map().add("title","Verify number").add("message","Would you like to verify your phone number?").add("cancel",true)]),"onOk",[function(data) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/phoneSetup" + ((gs.bool(gs.gp(gs.gp(gSobject.scope,"user"),"cellphone")) ? gs.plus("/", gs.gp(gs.gp(gSobject.scope,"user"),"cellphone")) : "")) + ""]); }]); } gSobject['popup'] = function(title, message) { if (title === undefined) title = "Title"; if (message === undefined) message = "Info message"; return gs.mc(gSobject.q,"dialog",[gs.map().add("title",title).add("message",message)]); } gSobject['confirmDelete'] = function(it) { return gs.mc(gs.mc(gSobject.q,"dialog",[gs.map().add("title","Confirmation").add("message","Are you sure you want to delete you're account?").add("cancel",true)]),"onOk",[function(data) { return gs.mc(gs.fs('window', this, gSobject),"open",["https://admin.rxme.office.i3zone.com/policy/showDelete", "_blank"]); }]); } gSobject['error'] = function(it) { return gs.mc(gSobject,"notify",["Please complete all required fields", "negative"]); } gSobject['faQ'] = function(it) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/mediaContent/01931aa337bd7a688d2dbd233dd93c8d"]); } gSobject['openProfileDialog'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "open.profile.dialog"]),"do",[]); return gs.sp(gSobject.scope,"profileEditDialog",true); } gSobject['openMedicalRecords'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "open.medical.records"]),"do",[]); return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/medicalRecords"]); } gSobject['closeProfileDIalog'] = function(it) { return gs.sp(gSobject.scope,"profileEditDialog",false); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function RegisterComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'RegisterComponent', simpleName: 'RegisterComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/signUp"; gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "register.langing.page"]),"do",[]); gs.println("RegisterComponent.created()"); gs.sp(gSobject.scope,"email",""); gs.sp(gSobject.scope,"phoneNumber",""); gs.sp(gSobject.scope,"processing",false); gs.mc(gSobject,"showHeaderFooter",[false]); return gs.mc(gSobject,"componentTheme",[false]); } gSobject['generatePin'] = function(it) { gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"username",gs.elvis(gs.bool(gs.gp(gSobject.scope,"email")) , gs.gp(gSobject.scope,"email") , gs.gp(gSobject.scope,"phoneNumber"))); if (!gs.bool(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"username"))) { gs.mc(gSobject,"notify",["Please enter details", "negative"]); return null; }; gs.sp(gSobject.scope,"processing",true); return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"legionAuthService"),"generatePinForNewOrExistingUser",[gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"username"), true, (gs.bool(gs.gp(gSobject.scope,"phoneNumber")) ? true : false)]),"then",[function(it) { gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/pinAuth"]); gs.mc(gSobject,"notify",["Pin Sent"]); return gs.sp(gSobject.scope,"processing",false); }, function(error) { gs.mc(gSobject,"notify",[gs.gp(error,"message"), "negative"]); return gs.sp(gSobject.scope,"processing",false); }]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function ResourceLandingComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'ResourceLandingComponent', simpleName: 'ResourceLandingComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/resourceLanding"; gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "resource.landing.page"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); return gs.mc(gSobject,"componentTheme",[false]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function HeartRateOverviewComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'HeartRateOverviewComponent', simpleName: 'HeartRateOverviewComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/heartRateOverview" , "/heartRateOverview/:id"]); gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.heartrate.overview"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"batchName","medical:score:heart_rate"); gs.sp(gSobject.scope,"graphPeriod","Day"); gs.sp(gSobject.scope,"hrv",null); gs.sp(gSobject.scope,"tracker",null); gs.sp(gSobject.scope,"logs",gs.list([])); gs.sp(gSobject.scope,"lastEntry",gs.map()); gs.mc(gSobject,"loadHeartRate",[]); gs.mc(gSobject,"loadDetails",[]); gs.mc(gSobject,"weeklyAvg",[]); gs.mc(gSobject,"loadTrackerData",["Heart Rate", function(tracker) { return gs.sp(gSobject.scope,"tracker",tracker); }]); gs.sp(gSobject.scope,"motivationalText",""); gs.sp(gSobject.scope,"motivationLoading",true); gs.mc(gSobject,"loadMotivation",[gs.gp(gs.fs('session', this, gSobject),"userId"), "HeartRate", function(msg) { gs.sp(gSobject.scope,"motivationalText",msg); return gs.sp(gSobject.scope,"motivationLoading",false); }]); gs.sp(gSobject.scope,"lastUpdated",""); return gs.mc(gSobject,"loadLastUpdated",[gs.gp(gs.fs('session', this, gSobject),"userId"), "heart_rate", function(lastUpdated) { return gs.sp(gSobject.scope,"lastUpdated",lastUpdated); }]); } gSobject['loadHeartRate'] = function(it) { gs.sp(gSobject.scope,"lastEntryDate","None"); gs.sp(gSobject.scope,"heartRate",""); gs.sp(gSobject.scope,"heartRateMin",999); gs.sp(gSobject.scope,"heartRateMax",0); gs.sp(gSobject.scope,"weeklyAvgDisplay",null); gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"listEntries",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gSobject.scope,"batchName"), gs.map().add("limit",7), function(logs) { return gs.mc(logs,"each",[function(log) { gs.mc(gs.gp(gSobject.scope,"logs"),"add",[gs.map().add("_id",gs.gp(log,"_id")).add("value",gs.gp(log,"value")).add("subtext",gs.gp(log,"status")).add("unit","BPM").add("_createdAt",gs.gp(log,"date"))]); gs.sp(gSobject.scope,"heartRate",gs.elvis(gs.bool(gs.gp(gSobject.scope,"heartRate")) , gs.gp(gSobject.scope,"heartRate") , gs.gp(log,"value"))); if (gs.gp(gSobject.scope,"heartRateMin") > gs.gp(log,"value")) { gs.sp(gSobject.scope,"heartRateMin",gs.gp(log,"value")); }; if (gs.gp(gSobject.scope,"heartRateMax") < gs.gp(log,"value")) { return gs.sp(gSobject.scope,"heartRateMax",gs.gp(log,"value")); }; }]); }]); gs.sp(gSobject.scope,"heartRateLabels",null); gs.sp(gSobject.scope,"heartRateValues",null); gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"metrics",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:heart_rate_value", gs.date(), gs.gp(gSobject.scope,"graphPeriod"), function(logs) { gs.println("bodyWeightValues"); gs.println(logs); gs.sp(gSobject.scope,"heartRateLabels",gs.gp(logs,"labels")); return gs.sp(gSobject.scope,"heartRateValues",gs.gp(logs,"aggAvgValues")); }]); return gs.mc(gSobject,"loadBPM",[]); } gSobject['loadDetails'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"medicalCalculationService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:heart_rate:hvr", function(hrv) { return gs.sp(gSobject.scope,"hrv",hrv); }]); } gSobject['weeklyAvg'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"metrics",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:heart_rate_value", gs.date(), "Day", function(heartRateLogs) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"calculateWeeklyAvg",[gs.gp(heartRateLogs,"aggAvgValues"), function(hrAvg) { var heartRateWeeklyAvg = hrAvg; gs.sp(gSobject.scope,"weeklyAvgDisplay","" + (heartRateWeeklyAvg) + ""); var hrStatus = gs.mc(gSobject,"getHeartRateStatus",[heartRateWeeklyAvg]); return gs.sp(gSobject.scope,"weeklyAvgStatus",hrStatus); }]); }]); } gSobject['getHeartRateStatus'] = function(avgHr) { if (avgHr < 60) { return "Low Heart Rate"; }; if (avgHr > 100) { return "High Heart Rate"; }; return "Normal Heart Rate"; } gSobject['loadBPM'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"medicalCalculationService"),"bpmInfo",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(bpmInfo) { return gs.sp(gSobject.scope,"bpmInfo",bpmInfo); }]); } gSobject['logHR'] = function(it) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/heartRateLog"]); } gSobject['navInsight'] = function(it) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/heartRateInsight"]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function HeartRateLogComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'HeartRateLogComponent', simpleName: 'HeartRateLogComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/heartRateLog" , "/heartRateLog/:id"]); gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.heartrate.log"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"dialog",false); gs.sp(gSobject.scope,"entry",gs.map().add("value","").add("hvr","").add("date",gs.mc(gs.mc(gSobject,"moment",[]),"format",["YYYY-MM-DD HH:mm"])).add("ref","heart")); if (gs.bool(gs.gp(gs.gp(gSobject.route,"params"),"id"))) { gs.sp(gSobject.scope,"entry",null); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"loadEntry",[gs.gp(gs.gp(gSobject.route,"params"),"id"), function(entry) { gs.sp(gSobject.scope,"entry",entry); return gs.sp(gs.gp(gSobject.scope,"entry"),"date",gs.mc(gs.mc(gSobject,"moment",[gs.gp(entry,"date")]),"format",["YYYY-MM-DD HH:mm"])); }]); }; } gSobject['bpmStatus'] = function(value) { return gs.elvis(gs.bool(gs.gp(gs.mc(gs.list([gs.map().add("max",59).add("status","Below Normal") , gs.map().add("max",69).add("status","Low Normal") , gs.map().add("max",79).add("status","Within Optimal Range") , gs.map().add("max",89).add("status","Above Optimal") , gs.map().add("max",99).add("status","Slightly Above Range") , gs.map().add("max",109).add("status","High") , gs.map().add("max",129).add("status","Very High") , gs.map().add("max",999).add("status","Severe Tachycardia")]),"find",[function(range) { return value <= gs.gp(range,"max"); }]),"status",true)) , gs.gp(gs.mc(gs.list([gs.map().add("max",59).add("status","Below Normal") , gs.map().add("max",69).add("status","Low Normal") , gs.map().add("max",79).add("status","Within Optimal Range") , gs.map().add("max",89).add("status","Above Optimal") , gs.map().add("max",99).add("status","Slightly Above Range") , gs.map().add("max",109).add("status","High") , gs.map().add("max",129).add("status","Very High") , gs.map().add("max",999).add("status","Severe Tachycardia")]),"find",[function(range) { return value <= gs.gp(range,"max"); }]),"status",true) , "Unknown"); } gSobject['logHeartRate'] = function(it) { gs.sp(gSobject.scope,"value",gs.gp(gs.fs('entry', this, gSobject),"value")); gs.sp(gSobject.scope,"hvr",gs.gp(gs.fs('entry', this, gSobject),"hvr")); gs.sp(gSobject.scope,"status",gs.mc(gSobject,"bpmStatus",[gs.fs('value', this, gSobject)])); var entry = gs.gp(gSobject.scope,"entry"); var today = gs.mc(gs.mc(gSobject,"moment",[]),"format",["YYYY-MM-DD"]); var date = gs.mc(gs.mc(gSobject,"moment",[gs.gp(entry,"date"), "YYYY-MM-DD HH:mm"]),"toDate",[]); if (gs.equals(gs.mc(gs.mc(gSobject,"moment",[date]),"format",["YYYY-MM-DD"]), today)) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:heart_rate:value", gs.fs('value', this, gSobject)]),"do",[]); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:heart_rate:hvr", gs.fs('hvr', this, gSobject)]),"do",[]); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:heart_rate:status", gs.fs('status', this, gSobject)]),"do",[]); }; if (gs.bool(gs.gp(gs.gp(gSobject.route,"params"),"id"))) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"deleteEntry",[gs.gp(gs.gp(gSobject.route,"params"),"id")]),"do",[]); }; gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"addEntryWithFts",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:heart_rate", gs.list(["value"]), gs.map().add("value",gs.fs('value', this, gSobject)).add("hvr",gs.fs('hvr', this, gSobject)).add("status",gs.fs('status', this, gSobject)).add("date",date)]),"then",[function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"eventListener",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gSobject.scope,"entry")]),"do",[]); gs.mc(gSobject,"saveLastUpdated",[gs.gp(gs.fs('session', this, gSobject),"userId"), "heart_rate"]); gs.mc(gSobject,"calculateRisk",[gs.gp(gSobject.scope,"value")]); return gs.sp(gSobject.scope,"dialog",true); }, function(error) { return gs.sp(gSobject.scope,"dialog",true); }]); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"notificationService"),"removeNotification",[gs.gp(gs.fs('session', this, gSobject),"userId"), "trackable:HeartRate", "BPM"]),"do",[]); return gs.mc(gSobject,"generateAndSaveMotivation",[gs.gp(gs.fs('session', this, gSobject),"userId"), "HeartRate", "medical:score:heart_rate:value"]); } gSobject['calculateRisk'] = function(heartRate) { return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"emergencyCalculationService"),"heartRate",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gs.gp(gs.fs('session', this, gSobject),"user"),"customerRef"), heartRate]),"do",[]); } gSobject['eventLogHeartRate'] = function(it) { return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"eventLogService"),"event",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.fs('narrative', this, gSobject), "heartrate", "info"]),"do",[]); } gSobject['error'] = function(it) { return gs.mc(gSobject,"notify",["Input required", "negative"]); } gSobject['handlePopupClick'] = function(it) { return gs.sp(gSobject.scope,"dialog",false); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function HeartRateDetailComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'HeartRateDetailComponent', simpleName: 'HeartRateDetailComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/heartRateDetail" , "/heartRateDetail/:id"]); gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.heartrate.detail"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"heartRate",null); gs.sp(gSobject.scope,"batchName","medical:score:heart_rate"); return gs.mc(gSobject,"loadHeartRateInfo",[function(it) { return gs.mc(gSobject,"loadBPM",[]); }]); } gSobject['loadHeartRateInfo'] = function(it) { gs.sp(gSobject.scope,"logs",gs.list([])); gs.sp(gSobject.scope,"heartRateMin",999); gs.sp(gSobject.scope,"heartRateMax",0); gs.sp(gSobject.scope,"weeklyAvgDisplay",null); gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"listEntries",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gSobject.scope,"batchName"), gs.map().add("limit",7), function(logs) { return gs.mc(logs,"each",[function(log) { gs.mc(gs.gp(gSobject.scope,"logs"),"add",[gs.map().add("_id",gs.gp(log,"_id")).add("value",gs.gp(log,"value")).add("subtext",gs.gp(log,"status")).add("_createdAt",gs.gp(log,"date"))]); gs.sp(gSobject.scope,"heartRate",gs.elvis(gs.bool(gs.gp(gSobject.scope,"heartRate")) , gs.gp(gSobject.scope,"heartRate") , gs.gp(log,"value"))); if (gs.gp(gSobject.scope,"heartRateMin") > gs.gp(log,"value")) { gs.sp(gSobject.scope,"heartRateMin",gs.gp(log,"value")); }; if (gs.gp(gSobject.scope,"heartRateMax") < gs.gp(log,"value")) { return gs.sp(gSobject.scope,"heartRateMax",gs.gp(log,"value")); }; }]); }]); gs.mc(gs.gp(gs.fs('o', this, gSobject),"medicalCalculationService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:heart_rate:hvr", function(hrv) { return gs.sp(gSobject.scope,"hrv",hrv); }]); return gs.mc(gSobject,"weeklyAvg",[function(it) { return gs.mc(gSobject,"loadBPM",[]); }]); } gSobject['weeklyAvg'] = function(callback) { if (callback === undefined) callback = function(it) { }; return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"metrics",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:heart_rate_value", gs.date(), "Day", function(heartRateLogs) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"calculateWeeklyAvg",[gs.gp(heartRateLogs,"aggAvgValues"), function(hrAvg) { var heartRateWeeklyAvg = hrAvg; gs.sp(gSobject.scope,"weeklyAvgDisplay","" + (heartRateWeeklyAvg) + ""); return gs.execCall(callback, this, []); }]); }]); } gSobject['loadBPM'] = function(callback) { if (callback === undefined) callback = function(it) { }; return gs.mc(gs.gp(gs.fs('o', this, gSobject),"medicalCalculationService"),"bpmInfo",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(bpmInfo) { gs.sp(gSobject.scope,"bpmInfo",bpmInfo); return gs.execCall(callback, this, []); }]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function HeartRateInsightComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'HeartRateInsightComponent', simpleName: 'HeartRateInsightComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/heartRateInsight" , "/heartRateInsight/:id"]); gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.heartrate.insight"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"batchName","medical:score:heart_rate"); gs.sp(gSobject.scope,"heartRate",null); gs.sp(gSobject.scope,"highHeartRate",null); gs.sp(gSobject.scope,"hrv",null); gs.sp(gSobject.scope,"scaleValue",44); gs.mc(gSobject,"loadHeartRateInfo",[]); gs.mc(gSobject,"weeklyAvg",[]); return gs.mc(gSobject,"loadBPMInfo",[]); } gSobject['loadHeartRateInfo'] = function(it) { gs.sp(gSobject.scope,"logs",gs.list([])); gs.sp(gSobject.scope,"heartRateMin",999); gs.sp(gSobject.scope,"heartRateMax",0); gs.sp(gSobject.scope,"weeklyAvgDisplay",null); gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"listEntries",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gSobject.scope,"batchName"), gs.map().add("limit",7), function(logs) { return gs.mc(logs,"each",[function(log) { gs.mc(gs.gp(gSobject.scope,"logs"),"add",[gs.map().add("_id",gs.gp(log,"_id")).add("value",gs.gp(log,"value")).add("subtext",gs.gp(log,"status")).add("_createdAt",gs.gp(log,"date"))]); gs.sp(gSobject.scope,"heartRate",gs.elvis(gs.bool(gs.gp(gSobject.scope,"heartRate")) , gs.gp(gSobject.scope,"heartRate") , gs.gp(log,"value"))); if (gs.gp(gSobject.scope,"heartRateMin") > gs.gp(log,"value")) { gs.sp(gSobject.scope,"heartRateMin",gs.gp(log,"value")); }; if (gs.gp(gSobject.scope,"heartRateMax") < gs.gp(log,"value")) { return gs.sp(gSobject.scope,"heartRateMax",gs.gp(log,"value")); }; }]); }]); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"medicalCalculationService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:heart_rate:hvr", function(hrv) { return gs.sp(gSobject.scope,"hrv",hrv); }]); } gSobject['weeklyAvg'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"metrics",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:heart_rate_value", gs.date(), "Day", function(heartRateLogs) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"calculateWeeklyAvg",[gs.gp(heartRateLogs,"aggAvgValues"), function(hrAvg) { var heartRateWeeklyAvg = hrAvg; return gs.sp(gSobject.scope,"weeklyAvgDisplay","" + (heartRateWeeklyAvg) + ""); }]); }]); } gSobject['loadBPMInfo'] = function(it) { gs.sp(gSobject.scope,"dataPoints",gs.list([])); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"listEntries",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gSobject.scope,"batchName"), gs.map().add("limit",7), function(dataPoints) { var filteredEntries = gs.mc(dataPoints,"findAll",[function(it) { return gs.gp(it,"value") > 100; }]); return gs.mc(filteredEntries,"each",[function(entry) { gs.mc(gs.gp(gSobject.scope,"dataPoints"),"add",[gs.map().add("_id",gs.gp(entry,"_id")).add("value",gs.gp(entry,"value")).add("subtext",gs.gp(entry,"status")).add("_createdAt",gs.gp(entry,"date"))]); return gs.sp(gSobject.scope,"highHeartRate",gs.elvis(gs.bool(gs.gp(gSobject.scope,"highHeartRate")) , gs.gp(gSobject.scope,"highHeartRate") , gs.gp(entry,"value"))); }]); }]); } gSobject['navHeartRateZone'] = function(it) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/heartRateZones"]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function HeartRateZonesComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'HeartRateZonesComponent', simpleName: 'HeartRateZonesComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/heartRateZones" , "/heartRateZones/:id"]); gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.heartrate.zones"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); return gs.mc(gSobject,"componentTheme",[false]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function MedicationCreateComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'MedicationCreateComponent', simpleName: 'MedicationCreateComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/medicationCreate" , "/medicationCreate/:id"]); gSobject.updateFormType = function(newType) { gs.println("new type"); gs.println(newType); if (!gs.bool(newType)) { return null; }; var applied = gs.mc(gs.fs('medicationDashboardJsService', this, gSobject),"applyFormType",[gs.gp(gSobject.scope,"entry"), newType]); gs.sp(gSobject.scope,"entry",gs.gp(applied,"entry")); gs.sp(gSobject.scope,"dosageUnit",gs.gp(applied,"dosageUnit")); gs.sp(gSobject.scope,"stockUnit",gs.gp(applied,"stockUnit")); gs.println("Updated formType: " + (gs.gp(gs.gp(gSobject.scope,"entry"),"formType")) + ""); gs.println("Route: " + (gs.gp(gs.gp(gSobject.scope,"entry"),"route")) + ""); return gs.println("Dosage unit: " + (gs.gp(gSobject.scope,"dosageUnit")) + ""); }; gSobject.formIcon = function(formType) { if (gs.equals(formType, "tablet")) { return "sym_o_pill"; } else { if (gs.equals(formType, "syrup")) { return "sym_o_local_drink"; } else { if (gs.equals(formType, "injection")) { return "sym_o_vaccines"; } else { if (gs.equals(formType, "topical")) { return "sym_o_sanitizer"; } else { return "sym_o_pill"; }; }; }; }; }; gSobject.toggleDay = function(day) { if (gs.mc(gs.gp(gSobject.scope,"selectedDays"),"contains",[gs.gp(day,"name")])) { gs.mc(gs.gp(gSobject.scope,"selectedDays"),"remove",[gs.gp(day,"name")]); } else { gs.mc(gs.gp(gSobject.scope,"selectedDays"),"push",[gs.gp(day,"name")]); }; return gs.sp(gs.gp(gSobject.scope,"entry"),"days",gs.gp(gSobject.scope,"selectedDays")); }; gSobject.allDaysSelected = function(it) { return gs.equals(gs.mc(gs.elvis(gs.bool(gs.gp(gSobject.scope,"selectedDays")) , gs.gp(gSobject.scope,"selectedDays") , gs.list([])),"size",[]), gs.mc(gs.elvis(gs.bool(gs.gp(gSobject.scope,"daysOfWeek")) , gs.gp(gSobject.scope,"daysOfWeek") , gs.list([])),"size",[])); }; gSobject.toggleAllDays = function(it) { if (gs.mc(gSobject,"allDaysSelected",[])) { gs.sp(gSobject.scope,"selectedDays",gs.list([])); } else { gs.sp(gSobject.scope,"selectedDays",gs.mc(gs.elvis(gs.bool(gs.gp(gSobject.scope,"daysOfWeek")) , gs.gp(gSobject.scope,"daysOfWeek") , gs.list([])),"collect",[function(it) { return gs.gp(it,"name"); }])); }; return gs.sp(gs.gp(gSobject.scope,"entry"),"days",gs.gp(gSobject.scope,"selectedDays")); }; gSobject.toggleColor = function(color) { if (gs.equals(gs.gp(gSobject.scope,"selectedColor"), gs.gp(color,"name"))) { gs.sp(gSobject.scope,"selectedColor",""); return gs.sp(gs.gp(gSobject.scope,"entry"),"color",""); } else { gs.sp(gSobject.scope,"selectedColor",gs.gp(color,"name")); return gs.sp(gs.gp(gSobject.scope,"entry"),"color",gs.gp(color,"name")); }; }; gSobject.toggleShape = function(shape) { if (gs.equals(gs.gp(gSobject.scope,"selectedShape"), gs.gp(shape,"id"))) { gs.sp(gSobject.scope,"selectedShape",""); return gs.sp(gs.gp(gSobject.scope,"entry"),"shape",""); } else { gs.sp(gSobject.scope,"selectedShape",gs.gp(shape,"id")); return gs.sp(gs.gp(gSobject.scope,"entry"),"shape",gs.gp(shape,"id")); }; }; gSobject.formatDate = function(dateStr) { if (!gs.bool(dateStr)) { return ""; }; return gs.mc(gs.mc(gSobject,"moment",[dateStr]),"format",["YYYY-MM-DD"]); }; gSobject.normalizeTimeValue = function(rawTime) { return gs.mc(gs.fs('medicationDashboardJsService', this, gSobject),"normalizeCreateTime",[rawTime]); }; gSobject.formatTime = function(timeStr) { if (!gs.bool(timeStr)) { return ""; }; return gs.mc(gs.mc(gSobject,"moment",[timeStr]),"format",["HH:mm A"]); }; gSobject.colorValue = function(name) { var value = "#e0e0e0"; for (_i41 = 0, c = gs.gp(gSobject.scope,"colors")[0]; _i41 < gs.gp(gSobject.scope,"colors").length; c = gs.gp(gSobject.scope,"colors")[++_i41]) { if (gs.equals(gs.gp(c,"name"), name)) { value = gs.gp(c,"value"); break; }; }; return value; }; gSobject.shapeIcon = function(shapeId) { var icon = "medication"; var legacyMap = gs.map().add("Rectangle","Rectangle Tablet.png").add("Rectangle_1","Rectangle Tablet.png").add("Rectangle_2","Rectangle Tablet.png").add("Polygon","Pentagon Tablet.png").add("Vector","Oval Tablet.png").add("Vector_1","Capsule Pill.png"); for (_i42 = 0, s = gs.gp(gSobject.scope,"drugShapes")[0]; _i42 < gs.gp(gSobject.scope,"drugShapes").length; s = gs.gp(gSobject.scope,"drugShapes")[++_i42]) { if (gs.equals(gs.gp(s,"id"), shapeId)) { icon = (gs.plus("img:/statics/icons/", gs.gp(s,"icon"))); break; }; }; if ((gs.equals(icon, "medication")) && (gs.mc(legacyMap,"containsKey",[shapeId]))) { icon = (gs.plus("img:/statics/icons/", (legacyMap[shapeId]))); }; return icon; }; gSobject.ruleRequired = function(val) { if (gs.equals(val, null)) { return "Required"; }; if (gs.instanceOf(val, "String")) { return (gs.mc(val,"trim",[]) ? true : "Required"); }; return (!gs.bool(!val)) || ("Required"); }; gSobject.rulePositive = function(val) { return (gs.mc(gs.fs('medicationDashboardJsService', this, gSobject),"toInt",[val]) > 0) || ("Must be greater than 0"); }; gSobject.ruleEndDate = function(val) { return (gs.mc(gs.fs('medicationDashboardJsService', this, gSobject),"isValidCreateDateRange",[gs.gp(gs.gp(gSobject.scope,"entry"),"startDate"), gs.gp(gs.gp(gSobject.scope,"entry"),"endDate")])) || ("End date cannot be before start date"); }; gSobject.ruleDays = function(val) { return ((gs.bool(gs.gp(gSobject.scope,"selectedDays"))) && (gs.mc(gs.gp(gSobject.scope,"selectedDays"),"size",[]) > 0)) || ("Select at least one day"); }; gSobject.ruleThreshold = function(val) { return ((!gs.bool(gs.gp(gs.gp(gSobject.scope,"entry"),"refill"))) || (gs.mc(gs.fs('medicationDashboardJsService', this, gSobject),"toInt",[val]) > 0)) || ("Must be greater than 0"); }; gSobject.onFormError = function(failedInputs) { return gs.mc(gSobject,"notify",["Please complete all required fields.", "negative"]); }; gSobject['created'] = function(it) { gs.println("MedicationCreateComponent.created()"); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.medication.create"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[false]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"user",gs.gp(gs.fs('session', this, gSobject),"user")); gs.sp(gSobject.scope,"showTime",false); gs.sp(gSobject.scope,"showStartDate",false); gs.sp(gSobject.scope,"showEndDate",false); gs.sp(gSobject.scope,"volumeOptions",gs.list(["10" , "20" , "30" , "40" , "50" , "60"])); gs.sp(gSobject.scope,"dosageUnit",gs.list(["tablets"])); gs.sp(gSobject.scope,"stockUnit","tablets"); gs.sp(gSobject.scope,"daysOfWeek",gs.list([gs.map().add("label","M").add("name","Monday") , gs.map().add("label","T").add("name","Tuesday") , gs.map().add("label","W").add("name","Wednesday") , gs.map().add("label","Th").add("name","Thursday") , gs.map().add("label","F").add("name","Friday") , gs.map().add("label","Sa").add("name","Saturday") , gs.map().add("label","Su").add("name","Sunday")])); gs.sp(gSobject.scope,"drugShapes",gs.list([gs.map().add("id","Triangle Tablet").add("icon","Triangle Tablet.png") , gs.map().add("id","Square Tablet").add("icon","Square Tablet.png") , gs.map().add("id","Round Tablet").add("icon","Round Tablet.png") , gs.map().add("id","Rectangle Tablet").add("icon","Rectangle Tablet.png") , gs.map().add("id","Pentagon Tablet").add("icon","Pentagon Tablet.png") , gs.map().add("id","Oval Tablet").add("icon","Oval Tablet.png") , gs.map().add("id","Gel Pill").add("icon","Gel Pill.png") , gs.map().add("id","Capsule Pill").add("icon","Capsule Pill.png")])); gs.sp(gSobject.scope,"colors",gs.list([gs.map().add("name","Soft Red").add("value","rgba(255, 99, 132, 0.6)") , gs.map().add("name","Sky Blue").add("value","rgba(54, 162, 235, 0.6)") , gs.map().add("name","Sun Yellow").add("value","rgba(255, 206, 86, 0.6)") , gs.map().add("name","Teal Green").add("value","rgba(75, 192, 192, 0.6)") , gs.map().add("name","Lavender Purple").add("value","rgba(153, 102, 255, 0.6)") , gs.map().add("name","Orange Spice").add("value","rgba(255, 159, 64, 0.6)") , gs.map().add("name","Mint Green").add("value","rgba(100, 255, 218, 0.6)") , gs.map().add("name","Rose Pink").add("value","rgba(255, 128, 171, 0.6)") , gs.map().add("name","Ocean Blue").add("value","rgba(28, 130, 181, 0.6)") , gs.map().add("name","Lime Zest").add("value","rgba(174, 255, 0, 0.6)") , gs.map().add("name","Coral Peach").add("value","rgba(255, 127, 80, 0.6)") , gs.map().add("name","Grape Violet").add("value","rgba(138, 43, 226, 0.6)") , gs.map().add("name","Blush Pink").add("value","rgba(255, 182, 193, 0.6)") , gs.map().add("name","Mustard").add("value","rgba(255, 219, 88, 0.6)") , gs.map().add("name","Ice Blue").add("value","rgba(173, 216, 230, 0.6)") , gs.map().add("name","Deep Plum").add("value","rgba(102, 0, 102, 0.6)") , gs.map().add("name","Forest Green").add("value","rgba(34, 139, 34, 0.6)") , gs.map().add("name","Cocoa Brown").add("value","rgba(139, 69, 19, 0.6)")])); gs.sp(gSobject.scope,"selectedMed",""); gs.sp(gSobject.scope,"selectedDays",gs.list([])); gs.sp(gSobject.scope,"selectedShape",""); gs.sp(gSobject.scope,"selectedColor",""); gs.sp(gSobject.scope,"reminder",false); gs.sp(gSobject.scope,"refill",false); gs.sp(gSobject.scope,"medications",gs.list([])); gs.sp(gSobject.scope,"dialog",false); gs.sp(gSobject.scope,"name",""); gs.sp(gSobject.scope,"formattedStartDate",null); gs.sp(gSobject.scope,"formattedEndDate",null); gs.sp(gSobject.scope,"timeView","hour"); gs.sp(gSobject.scope,"manualMode",false); gs.sp(gSobject.scope,"manualName",""); gs.sp(gSobject.scope,"entry",gs.mc(gs.fs('medicationDashboardJsService', this, gSobject),"createDefaultEntry",[])); gs.sp(gSobject.scope,"formTypes",gs.mc(gs.fs('medicationDashboardJsService', this, gSobject),"createFormTypes",[])); gs.mc(gSobject,"updateFormType",[gs.gp(gs.gp(gSobject.scope,"entry"),"formType")]); gs.sp(gSobject.scope,"unitOptions",gs.map().add("tablet","pills").add("syrup","ml").add("injection","ml").add("topical","g")); gs.sp(gSobject.scope,"medication",gs.map()); gs.mc(gSobject,"loadMedication",[]); if (gs.bool(gs.gp(gs.gp(gSobject.route,"params"),"id"))) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"loadMedication",[gs.gp(gs.gp(gSobject.route,"params"),"id"), function(med) { gs.sp(gSobject.scope,"entry",gs.mc(gs.fs('medicationDashboardJsService', this, gSobject),"createEntryFromMedication",[med])); gs.mc(gSobject,"updateFormType",[gs.gp(gs.gp(gSobject.scope,"entry"),"formType")]); if (gs.bool(gs.gp(med,"route"))) { gs.sp(gs.gp(gSobject.scope,"entry"),"route",gs.gp(med,"route")); }; gs.sp(gSobject.scope,"selectedColor",gs.gp(gs.gp(gSobject.scope,"entry"),"color")); gs.sp(gSobject.scope,"selectedShape",gs.gp(gs.gp(gSobject.scope,"entry"),"shape")); return gs.sp(gSobject.scope,"selectedDays",gs.gp(gs.gp(gSobject.scope,"entry"),"days")); }]); }; } gSobject['addMedication'] = function(it) { var validationError = gs.mc(gs.fs('medicationDashboardJsService', this, gSobject),"createValidationError",[gs.gp(gSobject.scope,"entry")]); if (gs.bool(validationError)) { gs.mc(gSobject,"notify",[validationError, "negative"]); return null; }; gs.sp(gSobject.scope,"medication",gs.mc(gs.fs('medicationDashboardJsService', this, gSobject),"createPayload",[gs.gp(gSobject.scope,"entry")])); if (gs.bool(gs.gp(gs.gp(gSobject.route,"params"),"id"))) { return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"updateRxmeUserMedication",[gs.gp(gs.gp(gSobject.route,"params"),"id"), gs.gp(gSobject.scope,"medication")]),"then",[function(it) { gs.println("Medication Updated"); gs.mc(gSobject,"notify",["Medication Updated"]); return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/medicationSchedule"]); }, function(error) { gs.println(error); return gs.mc(gSobject,"notify",[gs.plus("Updating Failed: ", gs.gp(error,"message"))]); }]); } else { return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"saveRxmeUserMedication",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gSobject.scope,"medication")]),"then",[function(savedMed) { gs.println("Medication Saved"); gs.mc(gSobject,"notify",["Medication Added"]); gs.mc(gSobject,"eventLogMedication",[]); gs.mc(gSobject,"saveLastUpdated",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medication"]); return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/medicationSchedule"]); }]); }; } gSobject['eventLogMedication'] = function(it) { var narrative = "Added medication: " + (gs.gp(gs.gp(gSobject.scope,"medication"),"name")) + ""; return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"eventLogService"),"event",[gs.gp(gs.fs('session', this, gSobject),"userId"), narrative, "medication", "info"]),"do",[]); } gSobject['loadMedication'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"medicalCalculationService"),"loadMeds",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:full:medication:all_medication", function(meds) { gs.println("MEDS: " + (meds) + ""); if (gs.gp(gSobject.scope,"medications") === null) { return gs.sp(gSobject.scope,"medications",gs.list(["Test Medication"])); } else { return gs.sp(gSobject.scope,"medications",meds); }; }]); } gSobject['confirmSelection'] = function(it) { if ((gs.bool(gs.gp(gSobject.scope,"manualMode"))) && (gs.bool(gs.gp(gSobject.scope,"manualName")))) { gs.sp(gs.gp(gSobject.scope,"entry"),"name",gs.mc(gs.gp(gSobject.scope,"manualName"),"trim",[])); }; if (!gs.bool(gs.gp(gs.gp(gSobject.scope,"entry"),"name"))) { gs.mc(gSobject,"notify",["Please select or enter a medication name", "negative"]); return null; }; gs.sp(gSobject.scope,"dialog",false); gs.sp(gSobject.scope,"manualMode",false); return gs.sp(gSobject.scope,"manualName",""); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function MedicationDashboardComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'MedicationDashboardComponent', simpleName: 'MedicationDashboardComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/medicationDashboard"; gSobject.hasLoggedMedicationToday = function(it) { return (gs.plus(gs.elvis(gs.bool(gs.gp(gSobject.scope,"medsTaken")) , gs.gp(gSobject.scope,"medsTaken") , 0), gs.elvis(gs.bool(gs.gp(gSobject.scope,"medsSkipped")) , gs.gp(gSobject.scope,"medsSkipped") , 0))) > 0; }; gSobject.effectiveStatus = function(med) { var today = gs.mc(gs.mc(gSobject,"moment",[]),"format",["YYYY-MM-DD"]); if (!gs.bool(gs.gp(med,"statusDate"))) { return "Pending"; }; var statusDay = gs.mc(gs.mc(gSobject,"moment",[gs.gp(med,"statusDate")]),"format",["YYYY-MM-DD"]); return (gs.equals(statusDay, today) ? gs.elvis(gs.bool(gs.gp(med,"status")) , gs.gp(med,"status") , "Pending") : "Pending"); }; gSobject.refillDueMeds = function(it) { return gs.mc(gs.elvis(gs.bool(gs.gp(gSobject.scope,"medications")) , gs.gp(gSobject.scope,"medications") , gs.list([])),"findAll",[function(med) { return (gs.bool(gs.gp(med,"refill",true))) && (gs.elvis(gs.bool(gs.gp(med,"qty")) , gs.gp(med,"qty") , 0) <= gs.elvis(gs.bool(gs.gp(med,"threshold")) , gs.gp(med,"threshold") , 0)); }]); }; gSobject.estimatedRunOutDateText = function(med) { return gs.mc(gs.fs('medicationDashboardJsService', this, gSobject),"estimatedRunOutDateText",[med, gs.mc(gSobject,"moment",[])]); }; gSobject.estimatedRunOutDay = function(med) { var runOut = gs.mc(gs.fs('medicationDashboardJsService', this, gSobject),"estimatedRunOutDate",[med, gs.mc(gSobject,"moment",[])]); return (gs.bool(runOut) ? gs.mc(runOut,"format",["DD"]) : "--"); }; gSobject.estimatedRunOutMonth = function(med) { var runOut = gs.mc(gs.fs('medicationDashboardJsService', this, gSobject),"estimatedRunOutDate",[med, gs.mc(gSobject,"moment",[])]); return (gs.bool(runOut) ? gs.mc(runOut,"format",["MMMM"]) : ""); }; gSobject.refillSummaryText = function(med) { var type = gs.mc(gs.elvis(gs.bool(gs.gp(med,"formType",true)) , gs.gp(med,"formType",true) , ""),"toLowerCase",[]); var qty = gs.mc(gs.fs('medicationDashboardJsService', this, gSobject),"toInt",[gs.gp(med,"qty",true)]); var amount = gs.mc(gs.fs('medicationDashboardJsService', this, gSobject),"toInt",[gs.gp(med,"amount",true)]); if (gs.equals(type, "tablet")) { return "" + (qty) + " tablets (" + (amount) + " mg each)"; }; if (gs.equals(type, "capsule")) { return "" + (qty) + " capsules (" + (amount) + " mg each)"; }; if (gs.equals(type, "syrup")) { return "" + (qty) + " units (" + (amount) + " ml each)"; }; if (gs.equals(type, "injection")) { return "" + (qty) + " units (" + (amount) + " ml each)"; }; if (gs.equals(type, "topical")) { return "" + (qty) + " units (" + (amount) + " g each)"; }; return "" + (qty) + " units"; }; gSobject.historyMeds = function(it) { return gs.mc(gs.mc(gs.elvis(gs.bool(gs.gp(gSobject.scope,"medications")) , gs.gp(gSobject.scope,"medications") , gs.list([])),"findAll",[function(med) { return (gs.bool(gs.gp(med,"statusDate",true))) || (gs.bool(gs.gp(med,"status",true))); }]),"sort",[function(a, b) { var aTime = (gs.bool(gs.gp(a,"statusDate",true)) ? gs.mc(gs.mc(gSobject,"moment",[gs.gp(a,"statusDate")]),"valueOf",[]) : 0); var bTime = (gs.bool(gs.gp(b,"statusDate",true)) ? gs.mc(gs.mc(gSobject,"moment",[gs.gp(b,"statusDate")]),"valueOf",[]) : 0); return gs.spaceShip(bTime, aTime); }]); }; gSobject.colorValue = function(name) { var value = "#e0e0e0"; for (_i43 = 0, c = gs.gp(gSobject.scope,"colors")[0]; _i43 < gs.gp(gSobject.scope,"colors").length; c = gs.gp(gSobject.scope,"colors")[++_i43]) { if (gs.equals(gs.gp(c,"name"), name)) { value = gs.gp(c,"value"); break; }; }; return value; }; gSobject.shapeIcon = function(shapeId) { var icon = "medication"; var legacyMap = gs.map().add("Rectangle","Rectangle Tablet.png").add("Rectangle_1","Rectangle Tablet.png").add("Rectangle_2","Rectangle Tablet.png").add("Polygon","Pentagon Tablet.png").add("Vector","Oval Tablet.png").add("Vector_1","Capsule Pill.png"); for (_i44 = 0, s = gs.gp(gSobject.scope,"drugShapes")[0]; _i44 < gs.gp(gSobject.scope,"drugShapes").length; s = gs.gp(gSobject.scope,"drugShapes")[++_i44]) { if (gs.equals(gs.gp(s,"id"), shapeId)) { icon = (gs.plus("img:/statics/icons/", gs.gp(s,"icon"))); break; }; }; if ((gs.equals(icon, "medication")) && (gs.mc(legacyMap,"containsKey",[shapeId]))) { icon = (gs.plus("img:/statics/icons/", (legacyMap[shapeId]))); }; return icon; }; gSobject['created'] = function(it) { gs.println("MedicationDashboardComponent.created()"); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.medication.dashboard"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"medicationsToday",gs.list([])); gs.sp(gSobject.scope,"todayMedsCount",0); gs.sp(gSobject.scope,"medsSkipped",0); gs.sp(gSobject.scope,"upcomingMeds",0); gs.sp(gSobject.scope,"medsTaken",0); gs.sp(gSobject.scope,"medications",gs.list([])); gs.sp(gSobject.scope,"medAdhLabels",null); gs.sp(gSobject.scope,"medAdhValues",null); gs.sp(gSobject.scope,"medTakenToday",0); gs.sp(gSobject.scope,"medAttemptsToday",0); gs.sp(gSobject.scope,"medAdherencePctToday",0); gs.sp(gSobject.scope,"medicationLogs",gs.list([])); gs.sp(gSobject.scope,"tracker",null); gs.sp(gSobject.scope,"metricHistoryTitleColor","medication"); gs.sp(gSobject.scope,"metricHistorySeeAllColor","medication"); gs.sp(gSobject.scope,"drugShapes",gs.list([gs.map().add("id","Triangle Tablet").add("icon","Triangle Tablet.png") , gs.map().add("id","Square Tablet").add("icon","Square Tablet.png") , gs.map().add("id","Round Tablet").add("icon","Round Tablet.png") , gs.map().add("id","Rectangle Tablet").add("icon","Rectangle Tablet.png") , gs.map().add("id","Pentagon Tablet").add("icon","Pentagon Tablet.png") , gs.map().add("id","Oval Tablet").add("icon","Oval Tablet.png") , gs.map().add("id","Gel Pill").add("icon","Gel Pill.png") , gs.map().add("id","Capsule Pill").add("icon","Capsule Pill.png")])); gs.sp(gSobject.scope,"colors",gs.list([gs.map().add("name","Soft Red").add("value","rgba(255, 99, 132, 0.6)") , gs.map().add("name","Sky Blue").add("value","rgba(54, 162, 235, 0.6)") , gs.map().add("name","Sun Yellow").add("value","rgba(255, 206, 86, 0.6)") , gs.map().add("name","Teal Green").add("value","rgba(75, 192, 192, 0.6)") , gs.map().add("name","Lavender Purple").add("value","rgba(153, 102, 255, 0.6)") , gs.map().add("name","Orange Spice").add("value","rgba(255, 159, 64, 0.6)") , gs.map().add("name","Mint Green").add("value","rgba(100, 255, 218, 0.6)") , gs.map().add("name","Rose Pink").add("value","rgba(255, 128, 171, 0.6)") , gs.map().add("name","Ocean Blue").add("value","rgba(28, 130, 181, 0.6)") , gs.map().add("name","Lime Zest").add("value","rgba(174, 255, 0, 0.6)") , gs.map().add("name","Coral Peach").add("value","rgba(255, 127, 80, 0.6)") , gs.map().add("name","Grape Violet").add("value","rgba(138, 43, 226, 0.6)") , gs.map().add("name","Blush Pink").add("value","rgba(255, 182, 193, 0.6)") , gs.map().add("name","Mustard").add("value","rgba(255, 219, 88, 0.6)") , gs.map().add("name","Ice Blue").add("value","rgba(173, 216, 230, 0.6)") , gs.map().add("name","Deep Plum").add("value","rgba(102, 0, 102, 0.6)") , gs.map().add("name","Forest Green").add("value","rgba(34, 139, 34, 0.6)") , gs.map().add("name","Cocoa Brown").add("value","rgba(139, 69, 19, 0.6)")])); gs.sp(gSobject.scope,"user",gs.gp(gs.fs('session', this, gSobject),"user")); gs.sp(gSobject.scope,"rxmeUser",gs.map()); gs.mc(gSobject,"loadRxmeUser",[]); gs.mc(gSobject,"loadMedication",[]); gs.mc(gSobject,"loadMedicationHistory",[]); gs.mc(gSobject,"loadMedicationMetrics",[]); gs.mc(gSobject,"loadTrackerData",["Medication", function(tracker) { gs.sp(gSobject.scope,"tracker",tracker); return gs.println(tracker); }]); gs.sp(gSobject.scope,"lastUpdated",""); return gs.mc(gSobject,"loadLastUpdated",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medication", function(lastUpdated) { return gs.sp(gSobject.scope,"lastUpdated",lastUpdated); }]); } gSobject['loadMedication'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"loadRxmeUserMedication",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(meds) { var summary = gs.mc(gs.fs('medicationDashboardJsService', this, gSobject),"summarizeToday",[meds, gs.mc(gSobject,"moment",[]), function(it) { return gs.println("SUMMARY"); }]); gs.sp(gSobject.scope,"medications",gs.elvis(gs.bool(gs.gp(summary,"medications")) , gs.gp(summary,"medications") , gs.list([]))); gs.sp(gSobject.scope,"todayMedsCount",gs.elvis(gs.bool(gs.gp(summary,"todayMedsCount")) , gs.gp(summary,"todayMedsCount") , 0)); gs.sp(gSobject.scope,"medsTaken",gs.elvis(gs.bool(gs.gp(summary,"medsTaken")) , gs.gp(summary,"medsTaken") , 0)); gs.sp(gSobject.scope,"medsSkipped",gs.elvis(gs.bool(gs.gp(summary,"medsSkipped")) , gs.gp(summary,"medsSkipped") , 0)); gs.sp(gSobject.scope,"upcomingMeds",gs.elvis(gs.bool(gs.gp(summary,"upcomingMeds")) , gs.gp(summary,"upcomingMeds") , 0)); gs.println("[MED DASHBOARD] today=" + (gs.gp(gSobject.scope,"todayMedsCount")) + " upcoming=" + (gs.gp(gSobject.scope,"upcomingMeds")) + " taken=" + (gs.gp(gSobject.scope,"medsTaken")) + " skipped=" + (gs.gp(gSobject.scope,"medsSkipped")) + ""); return gs.mc(gs.elvis(gs.bool(gs.gp(gSobject.scope,"medications")) , gs.gp(gSobject.scope,"medications") , gs.list([])),"each",[function(med) { var normalizedTime = gs.mc(gs.fs('medicationDashboardJsService', this, gSobject),"toHourMinute",[gs.gp(med,"time")]); var statusToday = gs.mc(gs.fs('medicationDashboardJsService', this, gSobject),"effectiveStatus",[med]); var isUpcoming = false; if ((gs.bool(normalizedTime)) && (!gs.bool(gs.mc(gs.list(["Taken" , "Skipped"]),"contains",[statusToday])))) { var medTimeToday = gs.mc(gSobject,"moment",[gs.plus((gs.plus(gs.mc(gs.mc(gSobject,"moment",[]),"format",["YYYY-MM-DD"]), " ")), normalizedTime), "YYYY-MM-DD HH:mm"]); isUpcoming = gs.mc(medTimeToday,"isAfter",[gs.mc(gSobject,"moment",[])]); }; return gs.println("[MED DASHBOARD ITEM] " + (gs.gp(med,"name")) + " | rawTime=" + (gs.gp(med,"time")) + " | time=" + (normalizedTime) + " | status=" + (statusToday) + " | upcoming=" + (isUpcoming) + ""); }]); }]); } gSobject['loadMedicationMetrics'] = function(it) { gs.sp(gSobject.scope,"medAdhLabels",null); gs.sp(gSobject.scope,"medAdhValues",null); gs.sp(gSobject.scope,"medAdhToday",null); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"metrics",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:medication-value", gs.date(), gs.gp(gSobject.scope,"graphPeriod"), function(logs) { if (!gs.bool(logs)) { return null; }; gs.println("adherence logs"); gs.println(logs); var todayIndex = gs.minus(gs.mc(gs.gp(logs,"values"),"size",[], null, true), 1); gs.sp(gSobject.scope,"medAdhLabels",gs.gp(logs,"labels")); gs.sp(gSobject.scope,"medAdhValues",gs.gp(logs,"aggAvgValues")); return gs.sp(gSobject.scope,"medAdhToday",(todayIndex >= 0 ? gs.gp(logs,"values")[todayIndex] : 0)); }]); } gSobject['loadRxmeUser'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"loadRxmeUser",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(rxmeUser) { return gs.sp(gSobject.scope,"rxmeUser",rxmeUser); }]); } gSobject['loadMedicationHistory'] = function(it) { gs.sp(gSobject.scope,"medicationLogs",gs.list([])); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"listEntries",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:medication", gs.map().add("limit",200), function(logs) { var latestByMedDay = gs.map(); gs.mc(gs.elvis(gs.bool(logs) , logs , gs.list([])),"each",[function(log) { var createdAt = gs.elvis(gs.bool(gs.gp(log,"date")) , gs.gp(log,"date") , gs.elvis(gs.bool(gs.gp(log,"_lastUpdated")) , gs.gp(log,"_lastUpdated") , gs.gp(log,"_dateCreated"))); var medId = gs.elvis(gs.bool(gs.gp(log,"medicationId")) , gs.gp(log,"medicationId") , gs.elvis(gs.bool(gs.gp(log,"medId")) , gs.gp(log,"medId") , gs.gp(log,"_id"))); if ((!gs.bool(createdAt)) || (!gs.bool(medId))) { return null; }; var dayKey = gs.mc(gs.mc(gSobject,"moment",[createdAt]),"format",["YYYY-MM-DD"]); var mapKey = "" + (medId) + ":" + (dayKey) + ""; var ts = gs.mc(gs.mc(gSobject,"moment",[createdAt]),"valueOf",[]); var existing = latestByMedDay[mapKey]; var existingTs = gs.elvis(gs.bool(gs.gp(existing,"_sortTs",true)) , gs.gp(existing,"_sortTs",true) , -1); if ((!gs.bool(existing)) || (ts >= existingTs)) { return (latestByMedDay[mapKey]) = gs.map().add("_id",medId).add("value",gs.elvis(gs.bool(gs.gp(log,"med")) , gs.gp(log,"med") , gs.elvis(gs.bool(gs.gp(log,"medication")) , gs.gp(log,"medication") , "Medication"))).add("subtext",gs.elvis(gs.bool(gs.gp(log,"status")) , gs.gp(log,"status") , (gs.equals(gs.elvis(gs.bool(gs.gp(log,"value")) , gs.gp(log,"value") , 0), 1) ? "Taken" : "Skipped"))).add("unit","").add("_createdAt",createdAt).add("_sortTs",ts); }; }]); return gs.sp(gSobject.scope,"medicationLogs",gs.mc(gs.mc(gs.mc(gs.mc(latestByMedDay,"values",[]),"toList",[]),"sort",[function(a, b) { return gs.spaceShip(gs.elvis(gs.bool(gs.gp(b,"_sortTs")) , gs.gp(b,"_sortTs") , 0), gs.elvis(gs.bool(gs.gp(a,"_sortTs")) , gs.gp(a,"_sortTs") , 0)); }]),"collect",[function(row) { gs.mc(row,"remove",["_sortTs"]); return row; }])); }]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function MedicationDetailComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'MedicationDetailComponent', simpleName: 'MedicationDetailComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/medicationDetail" , "/medicationDetail/:id"]); gSobject.actionLockedToday = function(it) { var med = gs.gp(gSobject.scope,"medication"); if ((!gs.bool(gs.gp(med,"statusDate",true))) || (!gs.bool(gs.gp(med,"status",true)))) { return false; }; if (!gs.bool(gs.gSin(gs.gp(med,"status"), gs.list(["Taken" , "Skipped"])))) { return false; }; return gs.mc(gs.mc(gSobject,"moment",[gs.gp(med,"statusDate")]),"isSame",[gs.mc(gSobject,"moment",[]), "day"]); }; gSobject['created'] = function(it) { gs.println("medicationDetailComponent.created()"); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.medication.detail"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[false]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"drugShapes",gs.list([gs.map().add("id","Triangle Tablet").add("icon","Triangle Tablet.png") , gs.map().add("id","Square Tablet").add("icon","Square Tablet.png") , gs.map().add("id","Round Tablet").add("icon","Round Tablet.png") , gs.map().add("id","Rectangle Tablet").add("icon","Rectangle Tablet.png") , gs.map().add("id","Pentagon Tablet").add("icon","Pentagon Tablet.png") , gs.map().add("id","Oval Tablet").add("icon","Oval Tablet.png") , gs.map().add("id","Gel Pill").add("icon","Gel Pill.png") , gs.map().add("id","Capsule Pill").add("icon","Capsule Pill.png")])); gs.sp(gSobject.scope,"colors",gs.list([gs.map().add("name","Soft Red").add("value","rgba(255, 99, 132, 0.6)") , gs.map().add("name","Sky Blue").add("value","rgba(54, 162, 235, 0.6)") , gs.map().add("name","Sun Yellow").add("value","rgba(255, 206, 86, 0.6)") , gs.map().add("name","Teal Green").add("value","rgba(75, 192, 192, 0.6)") , gs.map().add("name","Lavender Purple").add("value","rgba(153, 102, 255, 0.6)") , gs.map().add("name","Orange Spice").add("value","rgba(255, 159, 64, 0.6)") , gs.map().add("name","Mint Green").add("value","rgba(100, 255, 218, 0.6)") , gs.map().add("name","Rose Pink").add("value","rgba(255, 128, 171, 0.6)") , gs.map().add("name","Ocean Blue").add("value","rgba(28, 130, 181, 0.6)") , gs.map().add("name","Lime Zest").add("value","rgba(174, 255, 0, 0.6)") , gs.map().add("name","Coral Peach").add("value","rgba(255, 127, 80, 0.6)") , gs.map().add("name","Grape Violet").add("value","rgba(138, 43, 226, 0.6)") , gs.map().add("name","Blush Pink").add("value","rgba(255, 182, 193, 0.6)") , gs.map().add("name","Mustard").add("value","rgba(255, 219, 88, 0.6)") , gs.map().add("name","Ice Blue").add("value","rgba(173, 216, 230, 0.6)") , gs.map().add("name","Deep Plum").add("value","rgba(102, 0, 102, 0.6)") , gs.map().add("name","Forest Green").add("value","rgba(34, 139, 34, 0.6)") , gs.map().add("name","Cocoa Brown").add("value","rgba(139, 69, 19, 0.6)")])); gs.sp(gSobject.scope,"summaryText",""); gs.sp(gSobject.scope,"medication",gs.list([])); return gs.mc(gSobject,"loadMedication",[]); } gSobject['loadMedication'] = function(it) { if (gs.bool(gs.gp(gs.gp(gSobject.route,"params"),"id"))) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"loadMedication",[gs.gp(gs.gp(gSobject.route,"params"),"id"), function(med) { gs.sp(gSobject.scope,"medication",med); var type = gs.elvis(gs.mc(gs.gp(med,"formType"),"toLowerCase",[], null, true) , gs.mc(gs.gp(med,"formType"),"toLowerCase",[], null, true) , ""); gs.sp(gSobject.scope,"isTablet",gs.mc(gs.list(["tablet" , "capsule"]),"contains",[type])); gs.sp(gSobject.scope,"isSyrup",(gs.equals(type, "syrup"))); gs.sp(gSobject.scope,"isInjection",(gs.equals(type, "injection"))); gs.sp(gSobject.scope,"isTopical",(gs.equals(type, "topical"))); gs.sp(gSobject.scope,"summaryText",gs.mc(gSobject,"buildMedicationSummary",[med])); if (gs.bool(gs.gp(med,"_id",true))) { return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"notificationService"),"removeNotification",[gs.gp(gs.fs('session', this, gSobject),"userId"), "trackable:medication", "refill:" + (gs.gp(med,"_id")) + ""]),"do",[]); }; }]); }; } gSobject['buildMedicationSummary'] = function(med) { var form = gs.elvis(gs.bool(gs.gp(med,"formType")) , gs.gp(med,"formType") , "tablet"); var dosage = gs.elvis(gs.bool(gs.gp(med,"dosage")) , gs.gp(med,"dosage") , 0); var amount = gs.elvis(gs.bool(gs.gp(med,"amount")) , gs.gp(med,"amount") , 0); var qty = gs.elvis(gs.bool(gs.gp(med,"qty")) , gs.gp(med,"qty") , 0); var route = gs.elvis(gs.bool(gs.gp(med,"route")) , gs.gp(med,"route") , ""); var threshold = gs.elvis(gs.bool(gs.gp(med,"threshold")) , gs.gp(med,"threshold") , 0); var gSswitch0 = form; if (gs.equals(gSswitch0, "tablet")) { return "" + (dosage) + " Pill × " + (amount) + " mg | " + (qty) + " Pills Left (Refill at " + (threshold) + ")"; } else if (gs.equals(gSswitch0, "capsule")) { return "" + (dosage) + " Capsule × " + (amount) + " mg | " + (qty) + " capsules Left (Refill at " + (threshold) + ")"; } else if (gs.equals(gSswitch0, "syrup")) { return "" + (dosage) + " ml per dose | " + (qty) + " ml Left (" + (route) + ")"; } else if (gs.equals(gSswitch0, "injection")) { return "" + (dosage) + " ml Injection | " + (qty) + " Vials Left (" + (route) + ")"; } else if (gs.equals(gSswitch0, "topical")) { return "Apply thin layer daily (" + (route) + ")"; } else { return "" + (dosage) + " × " + (amount) + ""; }; } gSobject['markAs'] = function(value) { var medication = gs.gp(gSobject.scope,"medication"); value = (gs.equals(value, "Taken") ? "Taken" : "Skipped"); if (gs.mc(gSobject,"actionLockedToday",[])) { gs.mc(gSobject,"notify",["Medication already marked " + (gs.gp(medication,"status")) + " today"]); return null; }; var type = gs.mc(gs.elvis(gs.bool(gs.gp(medication,"formType")) , gs.gp(medication,"formType") , ""),"toLowerCase",[]); var isTrackable = gs.gSin(type, gs.list(["tablet" , "capsule" , "syrup"])); var isConsumable = gs.gSin(type, gs.list(["tablet" , "capsule" , "syrup" , "injection"])); var isTopical = gs.equals(type, "topical"); var stockResult = gs.mc(gs.fs('medicationDashboardJsService', this, gSobject),"stockAfterTaken",[medication, gs.mc(gSobject,"moment",[])]); if (((gs.equals(value, "Taken")) && (gs.bool(isTrackable))) && (gs.bool(gs.gp(stockResult,"alreadyTakenToday")))) { gs.println("Medication " + (gs.gp(medication,"name")) + " already marked Taken today. Ignoring duplicate take action."); gs.mc(gSobject,"notify",["Medication already marked Taken today"]); return null; }; gs.sp(medication,"status",value); gs.sp(medication,"statusDate",gs.date()); gs.println("Medication status value: " + (value) + ""); if ((gs.equals(value, "Taken")) && (gs.bool(isTrackable))) { var threshold = gs.elvis(gs.bool(gs.gp(medication,"threshold")) , gs.gp(medication,"threshold") , 0); var currentQty = gs.gp(stockResult,"currentQty"); var dosage = gs.gp(stockResult,"dosage"); var newQty = gs.gp(stockResult,"newQty"); gs.println("Medication intake: " + (gs.gp(medication,"name")) + " | old=" + (currentQty) + " | dosage=" + (dosage) + " | new=" + (newQty) + ""); gs.println("== Intake Debug =="); gs.println("Qty before: " + (currentQty) + ""); gs.println("Dosage: " + (gs.gp(medication,"dosage")) + ""); gs.println("Amount (mg): " + (gs.gp(medication,"amount")) + ""); gs.println("New qty: " + (newQty) + ""); gs.println("==================="); gs.sp(medication,"qty",newQty); if ((gs.bool(gs.gp(medication,"refill"))) && (newQty <= gs.elvis(gs.bool(gs.gp(medication,"threshold")) , gs.gp(medication,"threshold") , 0))) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"notificationService"),"add",[gs.gp(medication,"user"), "trackable:medication", "refill:" + (gs.gp(medication,"_id")) + "", "Time to Refill", "Your stock of " + (gs.gp(medication,"name")) + " is low (" + (newQty) + " pills left).", "/medicationDetail/" + (gs.gp(medication,"_id")) + "", gs.map().add("medId",gs.gp(medication,"_id")).add("qtyLeft",newQty)]); }; } else { if (((gs.equals(value, "Taken")) && (gs.bool(isConsumable))) && (!gs.bool(isTrackable))) { gs.println("Injection " + (gs.gp(medication,"name")) + " marked as Taken (no stock tracking)"); } else { if ((gs.equals(value, "Taken")) && (gs.bool(isTopical))) { gs.println("Topical " + (gs.gp(medication,"name")) + " applied (no tracking)"); }; }; }; return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"updateRxmeUserMedication",[gs.gp(medication,"_id"), medication]),"then",[function(it) { gs.mc(gSobject,"addIntakeEntry",[value]); gs.mc(gSobject,"notify",["Medication " + (value) + ""]); return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/medicationSchedule"]); }, function(error) { gs.println(error); return gs.mc(gSobject,"notify",[gs.plus("Action Failed: ", gs.gp(error,"message"))]); }]); } gSobject['colorValue'] = function(name) { var value = "#e0e0e0"; for (_i45 = 0, c = gs.gp(gSobject.scope,"colors")[0]; _i45 < gs.gp(gSobject.scope,"colors").length; c = gs.gp(gSobject.scope,"colors")[++_i45]) { if (gs.equals(gs.gp(c,"name"), name)) { value = gs.gp(c,"value"); break; }; }; return value; } gSobject['shapeIcon'] = function(shapeId) { var icon = "medication"; var legacyMap = gs.map().add("Rectangle","Rectangle Tablet.png").add("Rectangle_1","Rectangle Tablet.png").add("Rectangle_2","Rectangle Tablet.png").add("Polygon","Pentagon Tablet.png").add("Vector","Oval Tablet.png").add("Vector_1","Capsule Pill.png"); for (_i46 = 0, s = gs.gp(gSobject.scope,"drugShapes")[0]; _i46 < gs.gp(gSobject.scope,"drugShapes").length; s = gs.gp(gSobject.scope,"drugShapes")[++_i46]) { if (gs.equals(gs.gp(s,"id"), shapeId)) { icon = (gs.plus("img:/statics/icons/", gs.gp(s,"icon"))); break; }; }; if ((gs.equals(icon, "medication")) && (gs.mc(legacyMap,"containsKey",[shapeId]))) { icon = (gs.plus("img:/statics/icons/", (legacyMap[shapeId]))); }; return icon; } gSobject['rescheduleMedication'] = function(it) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/medicationCreate/" + (gs.gp(gs.gp(gSobject.scope,"medication"),"_id")) + ""]); } gSobject['deleteMedication'] = function(it) { if (gs.bool(gs.gp(gs.gp(gSobject.scope,"medication"),"_id",true))) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/medicationDelete/" + (gs.gp(gs.gp(gSobject.scope,"medication"),"_id")) + ""]); }; } gSobject['addIntakeEntry'] = function(status) { var med = gs.gp(gSobject.scope,"medication"); var now = gs.date(); var scheduledAt = (gs.instanceOf(gs.gp(med,"time"), "Date") ? gs.gp(med,"time") : null); var value = (gs.equals(status, "Taken") ? 1 : 0); var entry = gs.map().add("medicationId",gs.gp(med,"_id")).add("medication",gs.gp(med,"name")).add("status",status).add("dosage",gs.gp(med,"dosage")).add("amount",gs.gp(med,"amount")).add("color",gs.gp(med,"color")).add("shape",gs.gp(med,"shape")).add("scheduledAt",scheduledAt).add("frequency",gs.gp(med,"frequency")).add("days",(gs.instanceOf(gs.gp(med,"days"), "List") ? gs.gp(med,"days") : gs.list([]))); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:medication:value", value]),"do",[]); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:medication:status", status]),"do",[]); return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"addEntryWithFts",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:medication", gs.list(["value" , "status" , "med" , "medicationId"]), gs.map().add("value",value).add("status",status).add("med",gs.gp(med,"name")).add("medicationId",gs.gp(med,"_id"))]),"then",[function(it) { gs.mc(gSobject,"eventLogMedication",[]); return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"notificationService"),"removeNotification",[gs.gp(gs.fs('session', this, gSobject),"userId"), "trackable:medication", "refill:" + (gs.gp(gs.gp(gSobject.scope,"medication"),"_id")) + ""]),"do",[]); }, function(e) { return gs.println("Failed to add intake entry: " + (gs.gp(e,"message",true)) + ""); }]); } gSobject['eventLogMedication'] = function(it) { var narrative = "Logged medication intake: " + (gs.gp(gs.gp(gSobject.scope,"medication"),"name")) + " (" + (gs.gp(gs.gp(gSobject.scope,"medication"),"status")) + ")"; return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"eventLogService"),"event",[gs.gp(gs.fs('session', this, gSobject),"userId"), narrative, "medication:intake", "info"]),"do",[]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function MedicationDeleteComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'MedicationDeleteComponent', simpleName: 'MedicationDeleteComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/medicationDelete" , "/medicationDelete/:id"]); gSobject['created'] = function(it) { gs.println("medicationDeleteComponent.created()"); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.medication.delete"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[false]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"medication",gs.list([])); gs.sp(gSobject.scope,"selectedReason",""); gs.sp(gSobject.scope,"customReason",""); gs.sp(gSobject.scope,"options",gs.list([gs.map().add("label","Side effects").add("value","op1") , gs.map().add("label","End of prescription").add("value","op2") , gs.map().add("label","Medication Substituted / Changed").add("value","op3")])); gs.sp(gSobject.scope,"drugShapes",gs.list([gs.map().add("id","Triangle Tablet").add("icon","Triangle Tablet.png") , gs.map().add("id","Square Tablet").add("icon","Square Tablet.png") , gs.map().add("id","Round Tablet").add("icon","Round Tablet.png") , gs.map().add("id","Rectangle Tablet").add("icon","Rectangle Tablet.png") , gs.map().add("id","Pentagon Tablet").add("icon","Pentagon Tablet.png") , gs.map().add("id","Oval Tablet").add("icon","Oval Tablet.png") , gs.map().add("id","Gel Pill").add("icon","Gel Pill.png") , gs.map().add("id","Capsule Pill").add("icon","Capsule Pill.png")])); gs.sp(gSobject.scope,"colors",gs.list([gs.map().add("name","Soft Red").add("value","rgba(255, 99, 132, 0.6)") , gs.map().add("name","Sky Blue").add("value","rgba(54, 162, 235, 0.6)") , gs.map().add("name","Sun Yellow").add("value","rgba(255, 206, 86, 0.6)") , gs.map().add("name","Teal Green").add("value","rgba(75, 192, 192, 0.6)") , gs.map().add("name","Lavender Purple").add("value","rgba(153, 102, 255, 0.6)") , gs.map().add("name","Orange Spice").add("value","rgba(255, 159, 64, 0.6)") , gs.map().add("name","Mint Green").add("value","rgba(100, 255, 218, 0.6)") , gs.map().add("name","Rose Pink").add("value","rgba(255, 128, 171, 0.6)") , gs.map().add("name","Ocean Blue").add("value","rgba(28, 130, 181, 0.6)") , gs.map().add("name","Lime Zest").add("value","rgba(174, 255, 0, 0.6)") , gs.map().add("name","Coral Peach").add("value","rgba(255, 127, 80, 0.6)") , gs.map().add("name","Grape Violet").add("value","rgba(138, 43, 226, 0.6)") , gs.map().add("name","Blush Pink").add("value","rgba(255, 182, 193, 0.6)") , gs.map().add("name","Mustard").add("value","rgba(255, 219, 88, 0.6)") , gs.map().add("name","Ice Blue").add("value","rgba(173, 216, 230, 0.6)") , gs.map().add("name","Deep Plum").add("value","rgba(102, 0, 102, 0.6)") , gs.map().add("name","Forest Green").add("value","rgba(34, 139, 34, 0.6)") , gs.map().add("name","Cocoa Brown").add("value","rgba(139, 69, 19, 0.6)")])); return gs.mc(gSobject,"loadMedication",[]); } gSobject['loadMedication'] = function(it) { if (gs.bool(gs.gp(gs.gp(gSobject.route,"params"),"id"))) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"loadMedication",[gs.gp(gs.gp(gSobject.route,"params"),"id"), function(it) { return gs.sp(gSobject.scope,"medication",it); }]); }; } gSobject['colorValue'] = function(name) { var value = "#e0e0e0"; for (_i47 = 0, c = gs.gp(gSobject.scope,"colors")[0]; _i47 < gs.gp(gSobject.scope,"colors").length; c = gs.gp(gSobject.scope,"colors")[++_i47]) { if (gs.equals(gs.gp(c,"name"), name)) { value = gs.gp(c,"value"); break; }; }; return value; } gSobject['shapeIcon'] = function(shapeId) { var icon = "medication"; var legacyMap = gs.map().add("Rectangle","Rectangle Tablet.png").add("Rectangle_1","Rectangle Tablet.png").add("Rectangle_2","Rectangle Tablet.png").add("Polygon","Pentagon Tablet.png").add("Vector","Oval Tablet.png").add("Vector_1","Capsule Pill.png"); for (_i48 = 0, s = gs.gp(gSobject.scope,"drugShapes")[0]; _i48 < gs.gp(gSobject.scope,"drugShapes").length; s = gs.gp(gSobject.scope,"drugShapes")[++_i48]) { if (gs.equals(gs.gp(s,"id"), shapeId)) { icon = (gs.plus("img:/statics/icons/", gs.gp(s,"icon"))); break; }; }; if ((gs.equals(icon, "medication")) && (gs.mc(legacyMap,"containsKey",[shapeId]))) { icon = (gs.plus("img:/statics/icons/", (legacyMap[shapeId]))); }; return icon; } gSobject['deleteMedication'] = function(it) { var finalReason = gs.gp(gSobject.scope,"customReason"); if ((!gs.bool(finalReason)) && (gs.bool(gs.gp(gSobject.scope,"selectedReason")))) { var opt = gs.mc(gs.gp(gSobject.scope,"options"),"find",[function(it) { return gs.equals(gs.gp(it,"value"), gs.gp(gSobject.scope,"selectedReason")); }]); finalReason = (gs.bool(opt) ? gs.gp(opt,"label") : gs.gp(gSobject.scope,"selectedReason")); }; if (!gs.bool(finalReason)) { gs.mc(gSobject,"notify",["Please select or enter a reason before deleting.", "negative"]); return null; }; gs.sp(gs.gp(gSobject.scope,"medication"),"deleteReason",finalReason); return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"deleteRxmeUserMedication",[gs.gp(gs.gp(gSobject.route,"params"),"id"), finalReason]),"then",[function(it) { gs.println("Medication deleted, reason: " + (finalReason) + ""); gs.println(it); gs.mc(gSobject,"notify",["Medication Deleted"]); gs.mc(gSobject,"eventLogMedication",[]); return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/medicationSchedule"]); }, function(error) { gs.println(error); return gs.mc(gSobject,"notify",[gs.plus("Deletion Failed: ", gs.gp(error,"message"))]); }]); } gSobject['eventLogMedication'] = function(it) { var narrative = "Removed medication: " + (gs.gp(gs.gp(gSobject.scope,"medication"),"name")) + " (" + (gs.gp(gs.gp(gSobject.scope,"medication"),"deleteReason")) + ")"; return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"eventLogService"),"event",[gs.gp(gs.fs('session', this, gSobject),"userId"), narrative, "medication:remove", "info"]),"do",[]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function FitnessDetailsComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'FitnessDetailsComponent', simpleName: 'FitnessDetailsComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/fitnessDetails"; gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.fitness.overview"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); gs.mc(gSobject,"componentTheme",[false]); return gs.sp(gSobject.scope,"duration",30); } gSobject['updateDuration'] = function(it) { return gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"duration",gs.gp(gSobject.scope,"duration")); } gSobject['startWorkout'] = function(it) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/fitnessPlayer"]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function I3Toolbar() { var gSobject = VueComponent(); gSobject.clazz = { name: 'I3Toolbar', simpleName: 'I3Toolbar'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.props = gs.list([]); gSobject.data = function(it) { return gs.list([]); }; gSobject['created'] = function(it) { var self = this; } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function VueListSearchComponent() { var gSobject = VueComponent(); gSobject.clazz = { name: 'VueListSearchComponent', simpleName: 'VueListSearchComponent'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.props = gs.toJavascript(gs.list(["value" , "onFilter" , "onSelect" , "label" , "options" , "outlined" , "filled" , "standout" , "borderless" , "square" , "dark" , "clearable" , "required" , "style" , "onLabel" , "optionLabel"])); gSobject.data = function(it) { var self = this; return gs.map().add("objectValue",gs.gp(self,"value")).add("optionsList",gs.list([])).add("initOptions",gs.gp(self,"options")).add("optionLabelValue",gs.elvis(gs.bool(gs.gp(self,"optionLabel")) , gs.gp(self,"optionLabel") , "name")); }; gSobject['mounted'] = function(it) { var self = this; } gSobject['watchValue'] = function(newValue, oldValue) { var self = this; return gs.sp(self,"objectValue",newValue); } gSobject['lookupObjects'] = function(val, update, abort) { if (val === undefined) val = null; if (update === undefined) update = function(it) { return gs.execCall(it, this, []); }; if (abort === undefined) abort = null; var self = this; if (gs.bool(gs.gp(self,"options"))) { gs.execCall(update, this, [function(it) { gs.sp(self,"optionsList",gs.gp(self,"options")); return gs.mc(gSobject,"configLabel",[self]); }]); return null; }; return gs.mc(self,"onFilter",[val, function(dbOptionsList) { return gs.execCall(update, this, [function(it) { gs.sp(self,"optionsList",dbOptionsList); return gs.mc(gSobject,"configLabel",[self]); }]); }]); } gSobject['configLabel'] = function(self) { if (gs.bool(gs.gp(self,"onLabel"))) { return gs.sp(self,"optionLabel",gs.gp(self,"onLabel")); }; } gSobject['objectSelected'] = function(it) { var self = this; gs.mc(self,"$emit",["input", gs.gp(self,"objectValue")]); if (gs.bool(gs.gp(self,"onSelect"))) { return gs.mc(self,"onSelect",[gs.gp(self,"objectValue")]); }; } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function AchievementComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'AchievementComponent', simpleName: 'AchievementComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/achievement"; gSobject['created'] = function(it) { gs.println("AchievementComponent.created()"); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "achievement.landing.page"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); gs.mc(gSobject,"componentTheme",[false]); gs.mc(gSobject,"showHeader",[false]); gs.sp(gSobject.scope,"user",gs.gp(gs.fs('session', this, gSobject),"user")); return gs.sp(gSobject.scope,"activeUser",gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"activeUser")); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function AchievementListComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'AchievementListComponent', simpleName: 'AchievementListComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/achievementList"; gSobject['created'] = function(it) { gs.println("AchievementListComponent.created()"); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "achievement.list.page"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); gs.mc(gSobject,"componentTheme",[false]); gs.mc(gSobject,"showHeader",[false]); gs.sp(gSobject.scope,"user",gs.gp(gs.fs('session', this, gSobject),"user")); gs.sp(gSobject.scope,"activeUser",gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"activeUser")); gs.sp(gSobject.scope,"tab","achievement"); return gs.sp(gSobject.scope,"progress",5); } gSobject['achievementNavigate'] = function(it) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/achievementInfo"]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function AchievementLeaderboardComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'AchievementLeaderboardComponent', simpleName: 'AchievementLeaderboardComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/leaderboard"; gSobject['created'] = function(it) { gs.println("AchievementLeaderboardComponent.created()"); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "achievement.leaderboard.page"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); gs.mc(gSobject,"componentTheme",[false]); gs.mc(gSobject,"showHeader",[false]); gs.sp(gSobject.scope,"user",gs.gp(gs.fs('session', this, gSobject),"user")); gs.sp(gSobject.scope,"activeUser",gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"activeUser")); return gs.sp(gSobject.scope,"tab","leaderboard"); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function AchievementStatsComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'AchievementStatsComponent', simpleName: 'AchievementStatsComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/stats"; gSobject['created'] = function(it) { gs.println("AchievementStatsComponent.created()"); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "achievement.stats.page"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"user",gs.gp(gs.fs('session', this, gSobject),"user")); gs.sp(gSobject.scope,"activeUser",gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"activeUser")); return gs.sp(gSobject.scope,"tab","stats"); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function PersonalAchievementComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'PersonalAchievementComponent', simpleName: 'PersonalAchievementComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/personalStats"; gSobject['created'] = function(it) { gs.println("PersonalAchievementComponent.created()"); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "achievement.personal.page"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); gs.mc(gSobject,"componentTheme",[false]); gs.mc(gSobject,"showHeader",[false]); gs.sp(gSobject.scope,"user",gs.gp(gs.fs('session', this, gSobject),"user")); return gs.sp(gSobject.scope,"activeUser",gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"activeUser")); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function AchievementInfoComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'AchievementInfoComponent', simpleName: 'AchievementInfoComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/achievementInfo"; gSobject['created'] = function(it) { gs.println("AchievementInfoComponent.created()"); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "achievement.info.page"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); gs.mc(gSobject,"componentTheme",[false]); gs.mc(gSobject,"showHeader",[false]); gs.sp(gSobject.scope,"user",gs.gp(gs.fs('session', this, gSobject),"user")); gs.sp(gSobject.scope,"activeUser",gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"activeUser")); return gs.sp(gSobject.scope,"progress",29); } gSobject['share'] = function(it) { return gs.mc(gSobject,"notify",["WIP"]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function AllAchievementComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'AllAchievementComponent', simpleName: 'AllAchievementComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/allAchievements"; gSobject['created'] = function(it) { gs.println("AchievementInfoComponent.created()"); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "achievement.all.page"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"user",gs.gp(gs.fs('session', this, gSobject),"user")); gs.sp(gSobject.scope,"activeUser",gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"activeUser")); return gs.sp(gSobject.scope,"progress",29); } gSobject['share'] = function(it) { return gs.mc(gSobject,"notify",["WIP"]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function LiveChatComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'LiveChatComponent', simpleName: 'LiveChatComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/chat" , "/chat/:subId"]); gSobject['created'] = function(it) { gs.println("LiveChatComponent.created()"); gs.sp(gSobject.scope,"userChats",gs.list([])); gs.sp(gSobject.scope,"chatMemberLink",null); gs.sp(gSobject.scope,"loading",false); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "user.live.chat"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[true]); gs.mc(gSobject,"componentTheme",[false]); gs.mc(gSobject,"loadUserChats",[]); return gs.mc(gSobject,"openChatFromId",[gs.gp(gs.gp(gSobject.route,"params"),"subId")]); } gSobject['loadUserChats'] = function(it) { if (!gs.bool(gs.gp(gs.fs('session', this, gSobject),"userId"))) { return gs.mc(gSobject,"notify",["User not found", "negative"]); }; gs.sp(gSobject.scope,"loading",true); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"loadUserSupportChats",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(chats) { gs.sp(gSobject.scope,"loading",false); return gs.sp(gSobject.scope,"userChats",chats); }]); } gSobject['openChatFromId'] = function(chatLinkId) { if (!gs.bool(chatLinkId)) { return null; }; return gs.mc(gs.gp(gs.fs('o', this, gSobject),"dymicoChatService"),"chatForMember",[chatLinkId, function(chatLink) { return gs.mc(gSobject,"openChat",[chatLink]); }]); } gSobject['openChat'] = function(chatLink) { gs.println("openChat"); gs.println(chatLink); gs.mc(gSobject,"showHeaderFooter",[false]); return gs.sp(gSobject.scope,"chatMemberLink",chatLink); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function I3BottomContainer() { var gSobject = VueComponent(); gSobject.clazz = { name: 'I3BottomContainer', simpleName: 'I3BottomContainer'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.props = gs.map().add("margin",gs.map().add("type",String).add("default","lg")).add("maxWidth",gs.map().add("type",String).add("default","")); gSobject.data = function(it) { return gs.map().add("bottomContainerHeight",60); }; gSobject['created'] = function(it) { var self = this; return gs.mc(gSobject,"waitForRefs",[function(it) { return gs.sp(self,"bottomContainerHeight",gs.gp(gs.gp(gSobject.refs,"bottomContainer"),"offsetHeight")); }]); } gSobject['waitForRefs'] = function(callback) { if (callback === undefined) callback = function(it) { }; if (gs.bool(gs.gp(gSobject.refs,"bottomContainer",true))) { return gs.execCall(callback, this, []); } else { return gs.execStatic(Utils,'setTimeout', this,[function(it) { return gs.mc(gSobject,"waitForRefs",[callback]); }, 100]); }; } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function TrackerStreakCardComponent() { var gSobject = VueComponent(); gSobject.clazz = { name: 'TrackerStreakCardComponent', simpleName: 'TrackerStreakCardComponent'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.self = null; gSobject.props = gs.map().add("batchName",String).add("tracker",String).add("icon",String).add("accentColor",String); gSobject['created'] = function(it) { gSobject.self = this; gs.sp(gSobject.scope,"streakDays",0); gs.sp(gSobject.scope,"streakTitle",""); gs.sp(gSobject.scope,"streakDescription",""); return gs.mc(gSobject,"loadStreak",[]); } gSobject['loadStreak'] = function(it) { if (!gs.bool(gs.gp(gSobject.self,"batchName"))) { gs.sp(gSobject.scope,"streakDays",0); return null; }; return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"listEntries",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gSobject.self,"batchName"), gs.map().add("sort","date").add("order","desc"), function(entries) { var streak = gs.mc(gSobject,"computeStreak",[entries]); var trackerLabel = gs.mc(gs.elvis(gs.bool(gs.gp(gSobject.self,"tracker")) , gs.gp(gSobject.self,"tracker") , "tracker"),"toLowerCase",[]); var dayLabel = (gs.equals(streak, 1) ? "day" : "days"); gs.sp(gSobject.scope,"streakDays",streak); gs.sp(gSobject.scope,"streakTitle","" + (streak) + " " + (dayLabel) + " " + (trackerLabel) + " streak"); return gs.sp(gSobject.scope,"streakDescription","You've checked in your " + (trackerLabel) + " for " + (streak) + " " + (dayLabel) + " straight!"); }]); } gSobject['computeStreak'] = function(entries) { if ((!gs.bool(entries)) || (gs.equals(gs.mc(entries,"size",[]), 0))) { return 0; }; var dateStrings = gs.list([]); gs.mc(entries,"each",[function(entry) { var rawDate = gs.elvis(gs.bool(gs.gp(entry,"date")) , gs.gp(entry,"date") , gs.gp(entry,"_dateCreated")); if (!gs.bool(rawDate)) { return null; }; try { var m = gs.mc(gSobject,"moment",[rawDate]); if ((gs.bool(m)) && (gs.mc(m,"isValid",[]))) { gs.mc(dateStrings,'leftShift', gs.list([gs.mc(m,"format",["YYYY-MM-DD"])])); }; } catch (all) { } ; }]); if ((!gs.bool(dateStrings)) || (gs.equals(gs.mc(dateStrings,"size",[]), 0))) { return 0; }; var uniqueDates = gs.mc(gs.mc(gs.mc(dateStrings,"unique",[]),"sort",[function(a, b) { return gs.spaceShip(gs.mc(gs.mc(gSobject,"moment",[a, "YYYY-MM-DD"]),"valueOf",[]), gs.mc(gs.mc(gSobject,"moment",[b, "YYYY-MM-DD"]),"valueOf",[])); }]),"reverse",[]); var today = gs.mc(gs.mc(gSobject,"moment",[]),"format",["YYYY-MM-DD"]); var yesterday = gs.mc(gs.mc(gs.mc(gSobject,"moment",[]),"subtract",[1, "days"]),"format",["YYYY-MM-DD"]); if (((uniqueDates[0]) != today) && ((uniqueDates[0]) != yesterday)) { return 0; }; var streak = 0; var expected = gs.mc(gSobject,"moment",[uniqueDates[0], "YYYY-MM-DD"]); for (_i49 = 0, dateStr = uniqueDates[0]; _i49 < uniqueDates.length; dateStr = uniqueDates[++_i49]) { var mDate = gs.mc(this,"moment",[dateStr, "YYYY-MM-DD"], gSobject); if (!gs.bool(gs.mc(mDate,"isValid",[]))) { break; }; if (gs.mc(mDate,"isSame",[expected, "day"])) { streak++; gs.mc(expected,"subtract",[1, "days"]); } else { break; }; }; return streak; } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function CordovaContacts() { var gSobject = gs.init('CordovaContacts'); gSobject.clazz = { name: 'CordovaContacts', simpleName: 'CordovaContacts'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.findContacts = function(filterText, callback) { navigator.contacts.find( [ navigator.contacts.fieldType.phoneNumbers, navigator.contacts.fieldType.displayName, navigator.contacts.fieldType.name ], function(data) { callback(data); }, function(error) { console.log('Error finding contacts: ', error); }, { hasPhoneNumber: true, filter: filterText || '', } ); } gSobject.newContact = function(callback) { let contact = navigator.contacts.create(); callback(contact); } gSobject.saveContact = function(contact, callback) { contact.save( function(success) { console.log('CordovaContacts: Contact Saved: ', success); callback({status: true, message: 'Contact saved successfully', contact: success}); }, function(error) { console.log('CordovaContacts: Error Saving contacts: ', error); callback({status: false, message: 'Failed to save contact'}); } ); } gSobject.deleteContact = function(contact, callback) { contact.remove( function(success) { console.log('CordovaContacts: Contact Deleted: ', success); callback({status: true, message: 'Contact deleted successfully'}); }, function(error) { console.log('CordovaContacts: Failed to delete contact: ', error); callback({status: false, message: 'Failed to delete contact'}); } ); } gSobject.isAvailable = function() { return CordovaContacts.isAvailable(); } gSobject.getContactsInstance = function() { return CordovaContacts.getContactsInstance(); } gSobject['CordovaContacts0'] = function(it) { gs.mc(document,"addEventListener",["deviceReady", function(it) { if (!gs.bool(gs.mc(this,"isAvailable",[], gSobject))) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["cordova-plugin-contacts: Not Available"]); return null; } else { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["cordova-plugin-contacts: Available"]); }; }]); return this; } if (arguments.length==0) {gSobject.CordovaContacts0(); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; CordovaContacts.isAvailable = function() { // Contacts plugin is not available if (!navigator.contacts) return false; else return true; } CordovaContacts.getContactsInstance = function() { return navigator.contacts; } function CommunicationsComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'CommunicationsComponent', simpleName: 'CommunicationsComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/oldChat" , "/oldChat/:subId"]); gSobject['created'] = function(it) { gs.println("CommunicationsComponent.created()"); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "communication.landing.page"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); gs.sp(gSobject.scope,"unreadMessages",true); gs.sp(gSobject.scope,"userId",gs.gp(gs.fs('session', this, gSobject),"userId")); gs.sp(gSobject.scope,"subId",gs.gp(gs.gp(gSobject.route,"params"),"subId")); gs.sp(gSobject.scope,"selectChat",function(it) { return gs.mc(gSobject,"showHeaderFooter",[false]); }); return gs.sp(gSobject.scope,"deselectChat",function(it) { return gs.mc(gSobject,"showHeaderFooter",[]); }); } gSobject['hasUnreadMessage'] = function(it) { return gs.gp(gSobject.scope,"unreadMessages"); } gSobject['checkUnreadMessage'] = function(it) { return gs.sp(gSobject.scope,"unreadMessages",true); } gSobject['back'] = function(it) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/"]); } gSobject['CommunicationsComponent0'] = function(it) { gs.mc(gSobject,"checkUnreadMessage",[]); return this; } if (arguments.length==0) {gSobject.CommunicationsComponent0(); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function NutritionalGuidelineComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'NutritionalGuidelineComponent', simpleName: 'NutritionalGuidelineComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/nutritionalGuideline" , "/nutritionalGuideline/:id"]); gSobject['created'] = function(it) { gs.println("NutritionalGuidelineComponent.created()"); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "nutritional.guideline.page"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"id",gs.gp(gs.gp(gSobject.route,"params"),"id")); gs.sp(gSobject.scope,"assessment",gs.map()); return gs.mc(gSobject,"loadQuestionnaireAssessment",[gs.gp(gSobject.scope,"id")]); } gSobject['navigateBack'] = function(it) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"back",[]); } gSobject['loadQuestionnaireAssessment'] = function(qnId) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"getQuestionnaireAssessment",[qnId, function(it) { return gs.sp(gSobject.scope,"assessment",it); }]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function AiSettingDialogComponent() { var gSobject = VueComponent(); gSobject.clazz = { name: 'AiSettingDialogComponent', simpleName: 'AiSettingDialogComponent'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.props = gs.map().add("modelValue",Boolean).add("title",String).add("saveLabel",String); gSobject.watch = gs.map().add("modelValue",function(val) { gs.println("watch:modelValue -> " + (val) + ""); return gs.sp(this,"internalModel",val); }).add("internalModel",function(val) { gs.println("watch:internalModel -> " + (val) + ""); return gs.mc(this,"$emit",["update:modelValue", val], gSobject); }); gSobject.data = function(it) { return gs.map().add("internalModel",false).add("selectedValue",null); }; gSobject['created'] = function(it) { gs.sp(this,"internalModel",gs.gp(gs.thisOrObject(this,gSobject),"modelValue")); return gs.println("AiSettingDialogComponent.created() -> internalModel=" + (gs.gp(gs.thisOrObject(this,gSobject),"internalModel")) + ""); } gSobject['close'] = function(it) { return gs.sp(this,"internalModel",false); } gSobject['save'] = function(it) { gs.println("AiSettingDialogComponent.save() -> " + (gs.gp(gs.thisOrObject(this,gSobject),"selectedValue")) + ""); gs.mc(this,"$emit",["save", gs.gp(gs.thisOrObject(this,gSobject),"selectedValue")], gSobject); return gs.mc(gSobject,"close",[]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function I3MenuButton() { var gSobject = VueComponent(); gSobject.clazz = { name: 'I3MenuButton', simpleName: 'I3MenuButton'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.props = gs.list([]); gSobject.defaults = gs.map().add("type","button").add("label","Button").add("color","primary").add("textColor","").add("size","xs").add("noCaps",true).add("outline",false).add("flat",false).add("unelevated",true).add("rounded",false).add("push",false).add("square",false).add("glossy",false).add("dense",false); gSobject['created'] = function(it) { var self = this; var appConfig = gs.elvis(gs.bool(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"appConfig")) , gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"appConfig") , gs.map()); var config = (gs.gp(appConfig,"menubutton") != null ? gs.gp(appConfig,"menubutton") : gs.map()); var attrs = (gs.gp(self,"$attrs") != null ? gs.gp(self,"$attrs") : gs.map()); gs.sp(self,"btnProps",gs.toJavascript(gs.plus((gs.plus(gSobject.defaults, config)), attrs))); return gs.sp(gs.gp(self,"btnProps"),"size",gs.elvis(attrs["size"] , attrs["size"] , gs.elvis(config["size"] , config["size"] , gSobject.defaults["size"]))); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function CordovaBle() { var gSobject = gs.init('CordovaBle'); gSobject.clazz = { name: 'CordovaBle', simpleName: 'CordovaBle'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; Object.defineProperty(gSobject, 'singletonInstance', { get: function() { return CordovaBle.singletonInstance; }, set: function(gSval) { CordovaBle.singletonInstance = gSval; }, enumerable: true }); gSobject.initialized = false; gSobject.scanning = false; gSobject.discoveredDevices = gs.map(); gSobject.connectedDevices = gs.map(); gSobject.instance = function() { return CordovaBle.instance(); } gSobject['initialize'] = function(callback, params) { if (callback === undefined) callback = function(it) { }; if (params === undefined) params = gs.map().add("request",true).add("statusReceiver",false); if (!gs.bool(CordovaBle.bleInstalled())) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["CordovaBle: bluetoothle not installed"]); gs.execCall(callback, this, [gs.map().add("status","unavailable")]); return this; }; try { gs.mc(gs.fs('bluetoothle', this, gSobject),"initialize",[function(result) { gSobject.initialized = (gs.equals(gs.gp(result,"status"), "enabled")); return gs.execCall(callback, this, [result]); }, params]); } catch (e) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["CordovaBle.initialize error: " + (gs.fs('e', this, gSobject)) + ""]); gs.execCall(callback, this, [gs.map().add("status","error").add("message","" + (gs.fs('e', this, gSobject)) + "")]); } ; return this; } gSobject['isEnabled'] = function(callback) { if (!gs.bool(CordovaBle.bleInstalled())) { gs.execCall(callback, this, [gs.map().add("isEnabled",false)]); return this; }; try { gs.mc(gs.fs('bluetoothle', this, gSobject),"isEnabled",[callback]); } catch (e) { gs.execCall(callback, this, [gs.map().add("isEnabled",false)]); } ; return this; } gSobject['enable'] = function(success, error) { if (success === undefined) success = function(it) { }; if (error === undefined) error = function(it) { }; if (!gs.bool(CordovaBle.bleInstalled())) { gs.execCall(error, this, [gs.map().add("message","BLE not installed")]); return this; }; try { gs.mc(gs.fs('bluetoothle', this, gSobject),"enable",[success, error]); } catch (e) { gs.execCall(error, this, [gs.map().add("message","" + (gs.fs('e', this, gSobject)) + "")]); } ; return this; } gSobject['startScan'] = function(onDevice, onError, params) { if (onDevice === undefined) onDevice = function(it) { }; if (onError === undefined) onError = function(it) { }; if (params === undefined) params = gs.map().add("services",gs.list([])).add("allowDuplicates",false); if (!gs.bool(CordovaBle.bleInstalled())) { gs.execCall(onError, this, [gs.map().add("message","BLE not installed")]); return this; }; gSobject.discoveredDevices = gs.map(); gSobject.scanning = true; try { gs.mc(gs.fs('bluetoothle', this, gSobject),"startScan",[function(result) { if (gs.equals(gs.gp(result,"status"), "scanStarted")) { return null; }; if (gs.equals(gs.gp(result,"status"), "scanResult")) { if (!gs.bool(gs.mc(gSobject.discoveredDevices,"containsKey",[gs.gp(result,"address")]))) { var dev = gs.map().add("name",gs.elvis(gs.bool(gs.gp(result,"name")) , gs.gp(result,"name") , "Unknown")).add("address",gs.gp(result,"address")).add("rssi",gs.gp(result,"rssi")); (gSobject.discoveredDevices[gs.gp(result,"address")]) = dev; return gs.execCall(onDevice, this, [dev]); }; }; }, function(e) { gSobject.scanning = false; return gs.execCall(onError, this, [e]); }, params]); } catch (e) { gSobject.scanning = false; gs.execCall(onError, this, [gs.map().add("message","" + (gs.fs('e', this, gSobject)) + "")]); } ; return this; } gSobject['stopScan'] = function(callback) { if (callback === undefined) callback = function(it) { }; if (!gs.bool(CordovaBle.bleInstalled())) { gs.execCall(callback, this, [gs.map()]); return this; }; try { gs.mc(gs.fs('bluetoothle', this, gSobject),"stopScan",[function(r) { gSobject.scanning = false; return gs.execCall(callback, this, [r]); }, function(e) { gSobject.scanning = false; return gs.execCall(callback, this, [gs.map().add("error",e)]); }]); } catch (e) { gSobject.scanning = false; gs.execCall(callback, this, [gs.map().add("error","" + (gs.fs('e', this, gSobject)) + "")]); } ; return this; } gSobject['isScanning'] = function(callback) { if (!gs.bool(CordovaBle.bleInstalled())) { gs.execCall(callback, this, [gs.map().add("isScanning",false)]); return this; }; try { gs.mc(gs.fs('bluetoothle', this, gSobject),"isScanning",[callback]); } catch (e) { gs.execCall(callback, this, [gs.map().add("isScanning",gSobject.scanning)]); } ; return this; } gSobject['getAdapterInfo'] = function(callback) { if (!gs.bool(CordovaBle.bleInstalled())) { gs.execCall(callback, this, [gs.map()]); return this; }; try { gs.mc(gs.fs('bluetoothle', this, gSobject),"getAdapterInfo",[callback]); } catch (e) { gs.execCall(callback, this, [gs.map().add("error","" + (gs.fs('e', this, gSobject)) + "")]); } ; return this; } gSobject['connect'] = function(address, onStatus, onError) { if (onStatus === undefined) onStatus = function(it) { }; if (onError === undefined) onError = function(it) { }; if (!gs.bool(CordovaBle.bleInstalled())) { gs.execCall(onError, this, [gs.map().add("message","BLE not installed")]); return this; }; try { gs.mc(gs.fs('bluetoothle', this, gSobject),"connect",[function(result) { if (gs.equals(gs.gp(result,"status"), "connected")) { (gSobject.connectedDevices[address]) = result; }; if (gs.equals(gs.gp(result,"status"), "disconnected")) { gs.mc(gSobject.connectedDevices,"remove",[address]); }; return gs.execCall(onStatus, this, [result]); }, onError, gs.map().add("address",address)]); } catch (e) { gs.execCall(onError, this, [gs.map().add("message","" + (gs.fs('e', this, gSobject)) + "")]); } ; return this; } gSobject['disconnect'] = function(address, success, error) { if (success === undefined) success = function(it) { }; if (error === undefined) error = function(it) { }; if (!gs.bool(CordovaBle.bleInstalled())) { gs.execCall(error, this, [gs.map().add("message","BLE not installed")]); return this; }; try { gs.mc(gs.fs('bluetoothle', this, gSobject),"disconnect",[function(r) { gs.mc(gSobject.connectedDevices,"remove",[address]); gs.mc(gs.fs('bluetoothle', this, gSobject),"close",[function(it) { }, function(it) { }, gs.map().add("address",address)]); return gs.execCall(success, this, [r]); }, error, gs.map().add("address",address)]); } catch (e) { gs.execCall(error, this, [gs.map().add("message","" + (gs.fs('e', this, gSobject)) + "")]); } ; return this; } gSobject['discoverServices'] = function(address, callback) { if (!gs.bool(CordovaBle.bleInstalled())) { gs.execCall(callback, this, [gs.map()]); return this; }; try { gs.mc(gs.fs('bluetoothle', this, gSobject),"discover",[callback, function(e) { return gs.execCall(callback, this, [gs.map().add("error",e)]); }, gs.map().add("address",address)]); } catch (e) { gs.execCall(callback, this, [gs.map().add("error","" + (gs.fs('e', this, gSobject)) + "")]); } ; return this; } gSobject['read'] = function(address, service, characteristic, callback) { if (!gs.bool(CordovaBle.bleInstalled())) { gs.execCall(callback, this, [gs.map()]); return this; }; try { gs.mc(gs.fs('bluetoothle', this, gSobject),"read",[callback, function(e) { return gs.execCall(callback, this, [gs.map().add("error",e)]); }, gs.map().add("address",address).add("service",service).add("characteristic",characteristic)]); } catch (e) { gs.execCall(callback, this, [gs.map().add("error","" + (gs.fs('e', this, gSobject)) + "")]); } ; return this; } gSobject['write'] = function(address, service, characteristic, value, callback) { if (!gs.bool(CordovaBle.bleInstalled())) { gs.execCall(callback, this, [gs.map()]); return this; }; try { gs.mc(gs.fs('bluetoothle', this, gSobject),"write",[callback, function(e) { return gs.execCall(callback, this, [gs.map().add("error",e)]); }, gs.map().add("address",address).add("service",service).add("characteristic",characteristic).add("value",value)]); } catch (e) { gs.execCall(callback, this, [gs.map().add("error","" + (gs.fs('e', this, gSobject)) + "")]); } ; return this; } gSobject['subscribe'] = function(address, service, characteristic, onNotify) { if (!gs.bool(CordovaBle.bleInstalled())) { return this; }; try { gs.mc(gs.fs('bluetoothle', this, gSobject),"subscribe",[onNotify, function(e) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["subscribe error: " + (e) + ""]); }, gs.map().add("address",address).add("service",service).add("characteristic",characteristic)]); } catch (e) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["subscribe: " + (gs.fs('e', this, gSobject)) + ""]); } ; return this; } gSobject['unsubscribe'] = function(address, service, characteristic, callback) { if (callback === undefined) callback = function(it) { }; if (!gs.bool(CordovaBle.bleInstalled())) { gs.execCall(callback, this, [gs.map()]); return this; }; try { gs.mc(gs.fs('bluetoothle', this, gSobject),"unsubscribe",[callback, function(e) { return gs.execCall(callback, this, [gs.map().add("error",e)]); }, gs.map().add("address",address).add("service",service).add("characteristic",characteristic)]); } catch (e) { gs.execCall(callback, this, [gs.map().add("error","" + (gs.fs('e', this, gSobject)) + "")]); } ; return this; } gSobject.bleInstalled = function() { return CordovaBle.bleInstalled(); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; CordovaBle.instance = function(it) { if (!gs.bool(CordovaBle.singletonInstance)) { CordovaBle.singletonInstance = CordovaBle(); }; return CordovaBle.singletonInstance; } CordovaBle.bleInstalled = function() { return typeof window.bluetoothle !== 'undefined'; } CordovaBle.singletonInstance = null; function ScoreDetailComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'ScoreDetailComponent', simpleName: 'ScoreDetailComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/score"; gSobject['created'] = function(it) { gs.println("ScoreDetailComponent.created()"); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "score.detail.page"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); return gs.mc(gSobject,"loadGraph",[true]); } gSobject['loadGraph'] = function(newGraph) { if (newGraph === undefined) newGraph = false; return gs.execStatic(Utils,'setTimeout', this,[function(it) { var labels = gs.list([]); var values = gs.list([]); gs.mc(gs.range(1, 40, true),"each",[function(it) { gs.mc(labels,"add",[it]); return gs.mc(values,"add",[gs.plus((gs.plus(Math.round(gs.multiply(Math.random(), 10)), 20)), it)]); }]); if (gs.bool(newGraph)) { return gs.execStatic(ScoreDetailComponent,'paintGraph', this,["myGraph", labels, values]); } else { return gs.execStatic(ScoreDetailComponent,'updateData', this,["myGraph", labels, values]); }; }, 100]); } gSobject.updateData = function(x0,x1,x2) { return ScoreDetailComponent.updateData(x0,x1,x2); } gSobject.paintGraph = function(x0,x1,x2,x3) { return ScoreDetailComponent.paintGraph(x0,x1,x2,x3); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; ScoreDetailComponent.updateData = function(graphId, graphLabels, dataSet) { let chart = Chart.getChart(graphId); chart.data.datasets[0].data = gs.toJavascript(dataSet) chart.data.labels = gs.toJavascript(graphLabels) chart.update() } ScoreDetailComponent.paintGraph = function(graphId, graphLabels, dataSet, type) { if (type === undefined) type = "line"; const oldChart = Chart.getChart(graphId) if (oldChart != undefined) oldChart.destroy() const data = { labels: gs.toJavascript(graphLabels), datasets: [{ data: gs.toJavascript(dataSet), borderColor: Quasar.getCssVar('accent'), tension: 0.1, pointStyle: false, pointRadius: 0, }] } const options = { scales: { y: { max: 120, beginAtZero: true, grid: { display: false }, ticks: { display: false }, }, x: { grid: { display: false }, ticks: { display: false }, }, }, plugins: { legend: { display: false }, }, animation: true, responsive: true, } const config = { type: type, data: data, options: options, } const myChart = new Chart( document.getElementById(graphId), config) } function ResourcesComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'ResourcesComponent', simpleName: 'ResourcesComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/resources" , "/resources/:contentName"]); gSobject.handleShort = function(media, sectionName) { if (gs.equals(gs.mc(sectionName,"toLowerCase",[], null, true), "articles")) { gs.sp(gSobject.scope,"articleName",gs.gp(media,"label")); return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/mediaContent/" + (gs.gp(media,"_id")) + ""]); } else { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/shorts/" + (gs.gp(media,"_id")) + ""]); }; }; gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "resource.content.page"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"rootContent",gs.elvis(gs.bool(gs.gp(gs.gp(gSobject.route,"params"),"contentName")) , gs.gp(gs.gp(gSobject.route,"params"),"contentName") , gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"rootContent"))); gs.sp(gSobject.scope,"mediaBackStack",gs.list([])); gs.sp(gSobject.scope,"media",gs.map()); gs.sp(gSobject.scope,"allMedia",gs.list([])); gs.sp(gSobject.scope,"categories",gs.list([])); gs.sp(gSobject.scope,"mediaContent",gs.list([])); gs.sp(gSobject.scope,"mediaSections",gs.map()); gs.sp(gSobject.scope,"searchText",""); gs.sp(gSobject.scope,"searchResults",gs.list([])); gs.sp(gSobject.scope,"searching",false); gs.sp(gSobject.scope,"loading",true); gs.sp(gSobject.scope,"articleName",""); return gs.mc(gSobject,"loadContent",[null, function(it) { return gs.mc(gSobject,"callbackHelper",[]); }]); } gSobject['callbackHelper'] = function(it) { gs.sp(gSobject.scope,"loading",false); return gs.mc(gSobject,"hideLoading",[]); } gSobject['navigateToContent'] = function(category) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/resources/" + (gs.gp(category,"name")) + ""]); } gSobject['loadContent'] = function(rootContent, callback) { if (rootContent === undefined) rootContent = null; if (callback === undefined) callback = function(it) { }; gs.mc(gSobject,"showLoading",[]); var rootContentTemp = gs.gp(gSobject.scope,"rootContent"); if (gs.bool(rootContent)) { rootContentTemp = rootContent; gs.sp(gSobject.scope,"categories",gs.list([])); gs.sp(gSobject.scope,"allMedia",gs.list([])); gs.sp(gSobject.scope,"mediaContent",gs.list([])); }; if (!gs.bool(gs.mc(gs.gp(gSobject.scope,"mediaBackStack"),"contains",[rootContentTemp]))) { gs.mc(gs.gp(gSobject.scope,"mediaBackStack"),"add",[rootContentTemp]); }; return gs.mc(gs.gp(gs.fs('o', this, gSobject),"mediaContentAppService"),"mediaUserContentByName",[gs.gp(gs.fs('session', this, gSobject),"userId"), rootContentTemp, function(data) { gs.println(gs.plus((gs.plus((gs.multiply("=", 20)), "DATA")), (gs.multiply("=", 20)))); gs.println(data); gs.println(gs.plus((gs.plus((gs.multiply("=", 20)), "DATA CHILDREN")), (gs.multiply("=", 20)))); gs.println(gs.gp(data,"children")); gs.sp(gSobject.scope,"categories",gs.mc(gs.gp(data,"children"),"findAll",[function(it) { return it; }])); gs.println(gs.plus((gs.plus((gs.multiply("=", 20)), "CATEGORIES")), (gs.multiply("=", 20)))); gs.println(gs.gp(gSobject.scope,"categories")); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"mediaContentAppService"),"mediaUserContentGrouped",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(data,"_id"), function(groupedItems) { gs.sp(gSobject.scope,"mediaSections",groupedItems); return gs.execCall(callback, this, []); }]); }]); } gSobject['handleSearch'] = function(text) { if (gs.bool(text)) { return gs.sp(gSobject.scope,"mediaContent",gs.mc(gs.gp(gSobject.scope,"mediaContent"),"findAll",[function(it) { return gs.mc(gs.gp(it,"label"),"contains",[text]); }])); } else { gs.sp(gSobject.scope,"categories",gs.list([])); gs.sp(gSobject.scope,"allMedia",gs.list([])); gs.sp(gSobject.scope,"mediaContent",gs.list([])); gs.sp(gSobject.scope,"mediaSection",gs.list([])); return gs.mc(gSobject,"loadContent",[null, gSobject.callbackHelper]); }; } gSobject['searchSubmit'] = function(it) { gs.sp(gSobject.scope,"searchResults",gs.list([])); gs.sp(gSobject.scope,"searchLoading",true); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"mediaContentAppService"),"mediaUserSearchContent",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gSobject.scope,"searchText"), gs.gp(gSobject.scope,"rootContent"), function(data) { gs.sp(gSobject.scope,"searchResults",gs.mc(data,"findAll",[function(item) { return !gs.gSin(gs.gp(item,"type"), gs.list(["menu" , "navigation"])); }])); return gs.sp(gSobject.scope,"searchLoading",false); }]); } gSobject['searchNavigate'] = function(content) { if (gs.mc(gs.gp(content,"customPath"),"startsWith",["http"], null, true)) { return gs.execStatic(Utils,'open', this,[gs.gp(content,"customPath")]); }; if (gs.mc(gs.gp(content,"customPath"),"startsWith",["/statics/"], null, true)) { return gs.execStatic(Utils,'open', this,[gs.gp(content,"customPath")]); }; if (gs.bool(gs.gp(content,"customPath"))) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",[gs.gp(content,"customPath")]); }; if (gs.equals(gs.mc(gs.gp(content,"section"),"toLowerCase",[], null, true), "articles")) { return gs.sp(gSobject.scope,"articleName",gs.mc(content,"label",[gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/mediaContent/" + (gs.gp(content,"_id")) + ""])])); } else { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/shorts/" + (gs.gp(content,"_id")) + ""]); }; } gSobject['internalBack'] = function(it) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"back",[]); } gSobject['handleMediaBanner'] = function(media) { gs.println("handleMediaBanner"); gs.println(media); if (!gs.bool(media)) { return ""; }; if (gs.bool(gs.gp(media,"preview"))) { return "/media-cache/filePreview/" + (gs.gp(media,"_id")) + "/preview/" + (gs.gp(media,"_lastUpdated")) + "/" + (gs.gp(gs.gp(media,"banner"),"filename",true)) + ""; }; if (gs.bool(gs.gp(media,"file"))) { return "/media-cache/filePreview/" + (gs.gp(media,"_id")) + "/file/" + (gs.gp(media,"_lastUpdated")) + "/" + (gs.gp(gs.gp(media,"banner"),"filename",true)) + ""; }; if (gs.bool(gs.gp(media,"banner"))) { return "/media-cache/filePreview/" + (gs.gp(media,"_id")) + "/banner/" + (gs.gp(media,"_lastUpdated")) + "/" + (gs.gp(gs.gp(media,"banner"),"filename",true)) + ""; }; return "/media-cache/filePreview/" + (gs.gp(media,"_id")) + "/preview/" + (gs.gp(media,"_lastUpdated")) + "/" + (gs.gp(gs.gp(media,"banner"),"filename",true)) + ""; } gSobject['searchClose'] = function(it) { gs.mc(gSobject,"searchClear",[]); return gs.sp(gSobject.scope,"searching",false); } gSobject['searchClear'] = function(it) { gs.sp(gSobject.scope,"searchText",""); return gs.sp(gSobject.scope,"searchResults",gs.list([])); } gSobject['isType'] = function(media, sectionName) { return gs.equals(gs.mc(gs.gp(media,"sectionName",true),"toLowerCase",[], null, true), gs.mc(sectionName,"toLowerCase",[])); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function ResourceCategoriesComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'ResourceCategoriesComponent', simpleName: 'ResourceCategoriesComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/resourceCategories"; gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "resource.categories.page"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); return gs.mc(gSobject,"componentTheme",[false]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function HydrationOverviewComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'HydrationOverviewComponent', simpleName: 'HydrationOverviewComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/hydrationOverview" , "/hydrationOverview/:id"]); gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.hydration.overview"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"batchName","medical:score:hydration"); gs.sp(gSobject.scope,"graphPeriod","Day"); gs.sp(gSobject.scope,"hydrationLogs",gs.list([])); gs.sp(gSobject.scope,"filledCups",0); gs.sp(gSobject.scope,"hydrationText",null); gs.sp(gSobject.scope,"goalDialog",false); gs.sp(gSobject.scope,"tracker",null); gs.sp(gSobject.scope,"hydrationtLabels",null); gs.sp(gSobject.scope,"bodyWeightValues",null); gs.sp(gSobject.scope,"hydrationToday",null); gs.mc(gSobject,"loadLogs",[]); gs.mc(gSobject,"loadTrackerData",["Hydration", function(tracker) { return gs.sp(gSobject.scope,"tracker",tracker); }]); gs.sp(gSobject.scope,"motivationalText",""); gs.sp(gSobject.scope,"motivationLoading",true); gs.mc(gSobject,"loadMotivation",[gs.gp(gs.fs('session', this, gSobject),"userId"), "Hydration", function(msg) { gs.sp(gSobject.scope,"motivationalText",msg); return gs.sp(gSobject.scope,"motivationLoading",false); }]); gs.sp(gSobject.scope,"lastUpdated",""); return gs.mc(gSobject,"loadLastUpdated",[gs.gp(gs.fs('session', this, gSobject),"userId"), "hydration", function(lastUpdated) { return gs.sp(gSobject.scope,"lastUpdated",lastUpdated); }]); } gSobject['loadLogs'] = function(it) { gs.mc(gSobject,"initHydrationGoal",[]); gs.mc(gSobject,"fetchHydrationGoal",[]); gs.mc(gSobject,"fetchHydrationLogs",[]); gs.mc(gSobject,"loadHydrationMetrics",[]); return gs.mc(gSobject,"loadHydrationText",[]); } gSobject['initHydrationGoal'] = function(it) { return gs.sp(gSobject.scope,"hydrationGoal",gs.map().add("hydration","SETUP").add("unit",null).add("description","").add("progressText","Please configure your target hydration.")); } gSobject['fetchHydrationGoal'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:hydrations_goal", function(hydrationGoal) { if (gs.bool(hydrationGoal)) { gs.mc(gs.gp(gSobject.scope,"hydrationGoal"),"putAll",[hydrationGoal]); gs.sp(gs.gp(gSobject.scope,"hydrationGoal"),"unit","ml"); gs.sp(gs.gp(gSobject.scope,"hydrationGoal"),"description","Daily Liquid Intake"); return gs.sp(gs.gp(gSobject.scope,"hydrationGoal"),"progressText","You’re on track! Stay hydrated every day to improve your health & overall score."); }; }]); } gSobject['fetchHydrationLogs'] = function(it) { gs.sp(gSobject.scope,"hydration",""); gs.sp(gSobject.scope,"hydrationLogs",gs.list([])); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"listEntries",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:hydration", gs.map().add("limit",7), function(logs) { return gs.mc(logs,"each",[function(log) { gs.mc(gs.gp(gSobject.scope,"hydrationLogs"),"add",[gs.map().add("_id",gs.gp(log,"_id")).add("value",gs.gp(log,"value")).add("unit","ml").add("_createdAt",gs.gp(log,"timePicked"))]); if (!gs.bool(gs.gp(gSobject.scope,"hydration"))) { return gs.sp(gSobject.scope,"hydration",Math.round(gs.gp(log,"value"))); }; }]); }]); } gSobject['loadHydrationText'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"medicalCalculationService"),"waterInfo",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(hydrationText) { return gs.sp(gSobject.scope,"hydrationText",hydrationText); }]); } gSobject['loadHydrationMetrics'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"metrics",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:hydration-value", gs.date(), gs.gp(gSobject.scope,"graphPeriod"), function(logs) { var todayIndex = gs.minus(gs.mc(gs.gp(logs,"values"),"size",[], null, true), 1); gs.sp(gSobject.scope,"hydrationtLabels",gs.gp(logs,"labels")); gs.sp(gSobject.scope,"bodyWeightValues",gs.gp(logs,"aggSumValues")); if (gs.equals(gs.gp(gSobject.scope,"graphPeriod"), "Day")) { gs.sp(gSobject.scope,"hydrationToday",(gs.gp(logs,"values")[todayIndex])); }; var goalValue = gs.elvis(gs.bool(gs.gp(gs.gp(gSobject.scope,"hydrationGoal"),"water",true)) , gs.gp(gs.gp(gSobject.scope,"hydrationGoal"),"water",true) , 1000); var todayValue = gs.elvis(gs.bool(gs.gp(gSobject.scope,"hydrationToday")) , gs.gp(gSobject.scope,"hydrationToday") , 0); var totalCups = 10; var cupsFilled = Math.round(gs.multiply((gs.div(todayValue, goalValue)), totalCups)); gs.sp(gSobject.scope,"filledCups",Math.min(Math.max(cupsFilled, 0), totalCups)); var progressPercent = gs.multiply((gs.div(todayValue, goalValue)), 100); if (progressPercent >= 100) { return gs.sp(gs.gp(gSobject.scope,"hydrationGoal"),"progressText","Goal crushed! You've hit your daily hydration target. Cheers to your health!"); } else { if (progressPercent >= 80) { return gs.sp(gs.gp(gSobject.scope,"hydrationGoal"),"progressText","Almost there! Just a few more sips to go!"); } else { if (progressPercent >= 50) { return gs.sp(gs.gp(gSobject.scope,"hydrationGoal"),"progressText","Halfway hydrated! Keep going strong!"); } else { if (progressPercent > 0) { return gs.sp(gs.gp(gSobject.scope,"hydrationGoal"),"progressText","You're getting started! Let’s build that hydration momentum!"); } else { return gs.sp(gs.gp(gSobject.scope,"hydrationGoal"),"progressText","You haven’t logged any hydration today yet. Time to sip!"); }; }; }; }; }]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function HydrationInsightComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'HydrationInsightComponent', simpleName: 'HydrationInsightComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/HydrationInsight"; gSobject['created'] = function(it) { gs.sp(gSobject.scope,"logs",gs.list([])); gs.sp(gSobject.scope,"batchName","medical:score:hydration"); gs.sp(gSobject.scope,"weeklySumDisplay",null); gs.sp(gSobject.scope,"hydrationLogs",gs.list([])); gs.sp(gSobject.scope,"hydrationToday",0); gs.sp(gSobject.scope,"mostUsedTimePicked",null); gs.sp(gSobject.scope,"filledCups",0); gs.sp(gSobject.scope,"graphPeriod","Day"); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.hydration.insight"]),"do",[]); gs.sp(gSobject.scope,"hydrationTypeLabels",gs.list([])); gs.sp(gSobject.scope,"hydrationTypeData",gs.list([])); gs.sp(gSobject.scope,"hydrationTypeColors",gs.list([])); gs.mc(gSobject,"showHeaderFooter",[false]); gs.mc(gSobject,"componentTheme",[false]); gs.mc(gSobject,"loadLogs",[]); gs.mc(gSobject,"weeklySumDrink",[]); gs.mc(gSobject,"loadHydrationTypeBreakdown",[]); return gs.sp(gSobject.scope,"drinkTypes",gs.elvis(gs.bool(gs.gp(gSobject.scope,"drinkTypes")) , gs.gp(gSobject.scope,"drinkTypes") , gs.list([gs.map().add("label","Alcohol").add("value","alcohol") , gs.map().add("label","Coffee").add("value","coffee") , gs.map().add("label","Juice").add("value","juice") , gs.map().add("label","Tea").add("value","tea") , gs.map().add("label","Water").add("value","water") , gs.map().add("label","Other").add("value","other")]))); } gSobject['loadLogs'] = function(it) { gs.mc(gSobject,"initHydrationGoal",[]); gs.mc(gSobject,"fetchHydrationGoal",[]); return gs.mc(gSobject,"fetchHydrationLogsAndTimeAnalysis",[]); } gSobject['initHydrationGoal'] = function(it) { return gs.sp(gSobject.scope,"hydrationGoal",gs.map().add("hydration","SETUP").add("unit",null).add("description","").add("progressText","Please configure your target hydration.")); } gSobject['fetchHydrationGoal'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:hydrations_goal", function(hydrationGoal) { if (gs.bool(hydrationGoal)) { gs.mc(gs.gp(gSobject.scope,"hydrationGoal"),"putAll",[hydrationGoal]); gs.sp(gs.gp(gSobject.scope,"hydrationGoal"),"unit","ml"); gs.sp(gs.gp(gSobject.scope,"hydrationGoal"),"description","Daily Liquid Intake"); gs.sp(gs.gp(gSobject.scope,"hydrationGoal"),"progressText","You’re on track! Stay hydrated every day to improve your health & overall score."); }; return gs.mc(gSobject,"loadHydrationMetrics",[]); }]); } gSobject['fetchHydrationLogsAndTimeAnalysis'] = function(it) { gs.sp(gSobject.scope,"hydration",""); gs.sp(gSobject.scope,"timePicked",""); gs.sp(gSobject.scope,"timePickedList",gs.list([])); gs.sp(gSobject.scope,"hydrationLogs",gs.list([])); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"listEntries",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:hydration", gs.map().add("limit",7), function(logs) { gs.mc(logs,"each",[function(log) { gs.mc(gs.gp(gSobject.scope,"hydrationLogs"),"add",[gs.map().add("_id",gs.gp(log,"_id")).add("value",gs.gp(log,"value")).add("unit","ml").add("_createdAt",gs.gp(log,"timePicked"))]); if (!gs.bool(gs.gp(gSobject.scope,"hydration"))) { gs.sp(gSobject.scope,"hydration",Math.round(gs.gp(log,"value"))); }; if (!gs.bool(gs.gp(gSobject.scope,"timePicked"))) { gs.sp(gSobject.scope,"timePicked",gs.gp(log,"timePicked")); }; gs.sp(gSobject.scope,"timePickedList",gs.elvis(gs.bool(gs.gp(gSobject.scope,"timePickedList")) , gs.gp(gSobject.scope,"timePickedList") , gs.list([]))); return gs.mc(gs.gp(gSobject.scope,"timePickedList"),'leftShift', gs.list([gs.gp(log,"timePicked")])); }]); var timeCounts = gs.map(); gs.mc(gs.gp(gSobject.scope,"timePickedList"),"each",[function(time) { return (timeCounts[time]) = (gs.plus(gs.elvis(timeCounts[time] , timeCounts[time] , 0), 1)); }]); var mostCommonTime = null; var highestCount = 0; gs.mc(timeCounts,"each",[function(time, count) { if (count > highestCount) { highestCount = count; return mostCommonTime = time; }; }]); return gs.sp(gSobject.scope,"mostUsedTimePicked",mostCommonTime); }]); } gSobject['loadHydrationMetrics'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"metrics",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:hydration-value", gs.date(), gs.gp(gSobject.scope,"graphPeriod"), function(logs) { var todayIndex = gs.minus(gs.mc(gs.gp(logs,"values"),"size",[], null, true), 1); gs.sp(gSobject.scope,"hydrationToday",(gs.gp(logs,"values")[todayIndex])); var goalValue = gs.elvis(gs.bool(gs.gp(gs.gp(gSobject.scope,"hydrationGoal"),"water",true)) , gs.gp(gs.gp(gSobject.scope,"hydrationGoal"),"water",true) , 1000); var todayValue = gs.elvis(gs.bool(gs.gp(gSobject.scope,"hydrationToday")) , gs.gp(gSobject.scope,"hydrationToday") , 0); var totalCups = 10; var cupsFilled = Math.round(gs.multiply((gs.div(todayValue, goalValue)), totalCups)); return gs.sp(gSobject.scope,"filledCups",Math.min(Math.max(cupsFilled, 0), totalCups)); }]); } gSobject['weeklySumDrink'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"metrics",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:hydration-value", gs.date(), "Day", function(logs) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"calculateWeeklySum",[gs.gp(logs,"aggAvgValues"), function(sumDrink) { var drinkWeeklySum = sumDrink; return gs.sp(gSobject.scope,"weeklySumDisplay","" + (drinkWeeklySum) + ""); }]); }]); } gSobject['loadHydrationTypeBreakdown'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"listEntries",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:hydration", gs.map(), function(logs) { var counts = gs.map(); var total = 0; gs.mc(gs.elvis(gs.bool(logs) , logs , gs.list([])),"each",[function(log) { var type = gs.mc(gs.mc(gs.elvis(gs.bool(gs.gp(log,"type",true)) , gs.gp(log,"type",true) , "water"),"toString",[]),"toLowerCase",[]); (counts[type]) = (gs.plus(gs.elvis(counts[type] , counts[type] , 0), 1)); return total++; }]); if (!gs.bool(total)) { gs.sp(gSobject.scope,"hydrationTypeLabels",gs.list([])); gs.sp(gSobject.scope,"hydrationTypeData",gs.list([])); gs.sp(gSobject.scope,"hydrationTypeColors",gs.list([])); return null; }; var colorMap = gs.map().add("alcohol","#4CAF50").add("coffee","#0F177C").add("juice","#1BB3C7").add("tea","#71BEFA").add("water","#5170FF").add("other","#3AB54A"); var labels = gs.list([]); var data = gs.list([]); var colors = gs.list([]); gs.mc(gs.elvis(gs.bool(gs.gp(gSobject.scope,"drinkTypes")) , gs.gp(gSobject.scope,"drinkTypes") , gs.list([])),"each",[function(drink) { var value = gs.gp(drink,"value"); var count = gs.elvis(counts[value] , counts[value] , 0); if (count > 0) { gs.mc(labels,'leftShift', gs.list([gs.gp(drink,"label")])); gs.mc(data,'leftShift', gs.list([Math.round(gs.div((gs.multiply(count, 100.0)), total))])); return gs.mc(colors,'leftShift', gs.list([(colorMap[value])])); }; }]); gs.sp(gSobject.scope,"hydrationTypeLabels",labels); gs.sp(gSobject.scope,"hydrationTypeData",data); return gs.sp(gSobject.scope,"hydrationTypeColors",colors); }]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function HydrationLogComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'HydrationLogComponent', simpleName: 'HydrationLogComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/hydrationLog" , "/hydrationLog/:id"]); gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.hydration.log"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[false]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"showDateTime",false); gs.sp(gSobject.scope,"dialog",false); gs.sp(gSobject.scope,"drinkTypes",gs.list([gs.map().add("label","Alcohol").add("value","alcohol") , gs.map().add("label","Coffee").add("value","coffee") , gs.map().add("label","Juice").add("value","juice") , gs.map().add("label","Tea").add("value","tea") , gs.map().add("label","Water").add("value","water") , gs.map().add("label","Other").add("value","other")])); gs.sp(gSobject.scope,"selectedDrinkType",null); gs.sp(gSobject.scope,"entry",gs.map().add("value",null).add("timePicked",gs.mc(gs.mc(gSobject,"moment",[]),"format",["YYYY-MM-DD HH:mm"])).add("date",gs.mc(gs.mc(gSobject,"moment",[]),"format",["YYYY-MM-DD HH:mm"])).add("ref","hydration")); gs.sp(gSobject.scope,"glucoseOptions",gs.list([gs.map().add("label","500").add("value",500).add("image","/statics/images/hydration_glass.png").add("size","small").add("ml",500) , gs.map().add("label","1000").add("value",1000).add("image","/statics/images/hydration_smallBottle.png").add("size","medium").add("ml",1000) , gs.map().add("label","1500").add("value",1500).add("image","/statics/images/hydration_bottle.png").add("size","large").add("ml",1500)])); gs.sp(gSobject.scope,"toggleGlucose",function(val) { return gs.sp(gs.gp(gSobject.scope,"entry"),"value",(gs.equals(gs.gp(gs.gp(gSobject.scope,"entry"),"value"), val) ? null : val)); }); if (gs.bool(gs.gp(gs.gp(gSobject.route,"params"),"id"))) { gs.sp(gSobject.scope,"entry",null); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"loadEntry",[gs.gp(gs.gp(gSobject.route,"params"),"id"), function(entry) { gs.sp(gSobject.scope,"entry",entry); return gs.sp(gs.gp(gSobject.scope,"entry"),"date",gs.mc(gs.mc(gSobject,"moment",[gs.gp(entry,"date")]),"format",["YYYY-MM-DD HH:mm"])); }]); }; } gSobject['showDateTimePicker'] = function(it) { return gs.sp(gSobject.scope,"showDateTime",true); } gSobject['logHydration'] = function(it) { var entry = gs.gp(gSobject.scope,"entry"); var value = gs.gp(entry,"value"); var drinkType = gs.gp(gSobject.scope,"selectedDrinkType"); var timePicked = gs.gp(entry,"timePicked"); if (!gs.bool(value)) { gs.mc(gSobject,"notify",["Please enter a hydration amount.", "negative"]); return null; }; if (!gs.bool(drinkType)) { gs.mc(gSobject,"notify",["Please select a drink type.", "negative"]); return null; }; if (!gs.bool(timePicked)) { gs.mc(gSobject,"notify",["Please select a time.", "negative"]); return null; }; gs.sp(entry,"date",gs.date(gs.gp(entry,"timePicked"))); if (gs.mc(gs.mc(gSobject,"moment",[gs.gp(entry,"date")]),"isSame",[gs.mc(gSobject,"moment",[]), "day"])) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:hydration:value", value]),"do",[]); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:hydration:timePicked", timePicked]),"do",[]); }; if (gs.bool(gs.gp(gs.gp(gSobject.route,"params"),"id"))) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"deleteEntry",[gs.gp(gs.gp(gSobject.route,"params"),"id")]),"do",[]); }; gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"addEntryWithFts",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:hydration", gs.list(["value" , "timePicked"]), gs.map().add("value",value).add("timePicked",timePicked).add("date",gs.gp(entry,"date")).add("type",gs.gp(gSobject.scope,"selectedDrinkType")).add("ref","hydration")]),"then",[function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"eventListener",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gSobject.scope,"entry")]),"do",[]); gs.mc(gSobject,"saveLastUpdated",[gs.gp(gs.fs('session', this, gSobject),"userId"), "hydration"]); return gs.sp(gSobject.scope,"dialog",true); }, function(it) { return gs.sp(gSobject.scope,"dialog",true); }]); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"notificationService"),"removeNotification",[gs.gp(gs.fs('session', this, gSobject),"userId"), "trackable:hydration", "Hydration"]),"do",[]); return gs.mc(gSobject,"generateAndSaveMotivation",[gs.gp(gs.fs('session', this, gSobject),"userId"), "Hydration", "medical:score:hydration:value"]); } gSobject['eventLogHydration'] = function(it) { return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"eventLogService"),"event",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.fs('narrative', this, gSobject), "hydration", "info"]),"do",[]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function HydrationGoalPreviewComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'HydrationGoalPreviewComponent', simpleName: 'HydrationGoalPreviewComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/hydrationGoalPreview" , "/hydrationGoalPreview/:id"]); gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "hydration.goal.preview"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[false]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"progress",0); gs.sp(gSobject.scope,"totalhydration",0); gs.sp(gSobject.scope,"hydrationGoal",gs.map().add("water",0)); gs.sp(gSobject.scope,"batchName","medical:score:hydration"); gs.mc(gSobject,"loadLogs",[]); return gs.mc(gSobject,"fetchHydrationGoal",[]); } gSobject['loadLogs'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:hydrations_goal", function(hydrationGoal) { if (gs.bool(hydrationGoal)) { gs.mc(gs.gp(gSobject.scope,"hydrationGoal"),"putAll",[hydrationGoal]); gs.sp(gs.gp(gSobject.scope,"hydrationGoal"),"unit","ml"); }; return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"metrics",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:hydration-value", gs.date(), "Day", function(logs) { if (((gs.bool(logs)) && (gs.bool(gs.gp(logs,"values")))) && (gs.mc(gs.gp(logs,"values"),"size",[]) > 0)) { var todayIndex = gs.minus(gs.mc(gs.gp(logs,"values"),"size",[]), 1); gs.sp(gSobject.scope,"totalhydration",gs.elvis(gs.gp(logs,"values")[todayIndex] , gs.gp(logs,"values")[todayIndex] , 0)); } else { gs.sp(gSobject.scope,"totalhydration",0); }; return gs.mc(gSobject,"calculateProgress",[gs.gp(gSobject.scope,"totalhydration")]); }]); }]); } gSobject['calculateProgress'] = function(total) { if (total === undefined) total = null; var goalValue = gs.gp(gs.gp(gSobject.scope,"hydrationGoal"),"water"); var goal = ((goalValue != null) && (gs.mc(gs.mc(goalValue,"toString",[]),"isNumber",[])) ? gs.mc(gs.mc(goalValue,"toString",[]),"toInteger",[]) : 0); if ((goal > 0) && (total != null)) { var percent = gs.multiply((gs.div(total, goal)), 100); return gs.sp(gSobject.scope,"progress",Math.round(percent)); } else { return gs.sp(gSobject.scope,"progress",0); }; } gSobject['fetchHydrationGoal'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:hydrations_goal", function(goalData) { var rawWater = gs.elvis(gs.bool(gs.gp(goalData,"water",true)) , gs.gp(goalData,"water",true) , gs.elvis(gs.bool(gs.gp(goalData,"hydration",true)) , gs.gp(goalData,"hydration",true) , 0)); var goal = (gs.mc(gs.mc(rawWater,"toString",[]),"isNumber",[]) ? gs.mc(gs.mc(rawWater,"toString",[]),"toInteger",[]) : 0); var desc = ""; if (gs.equals(goal, 0)) { desc = "Please configure your target hydration."; } else { if ((goal >= 2000) && (goal < 3000)) { desc = "You're currently aiming for the standard recommended hydration intake for a healthy lifestyle."; } else { if (goal < 2000) { desc = "Your goal is below the average recommendation; consider increasing it."; } else { desc = "You've set a high performance hydration goal."; }; }; }; gs.sp(gs.gp(gSobject.scope,"hydrationGoal"),"water",goal); gs.sp(gs.gp(gSobject.scope,"hydrationGoal"),"progressText",desc); gs.sp(gs.gp(gSobject.scope,"hydrationGoal"),"unit","ml"); return gs.mc(gSobject,"calculateProgress",[gs.gp(gSobject.scope,"totalhydration")]); }]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function HydrationGoalTrackComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'HydrationGoalTrackComponent', simpleName: 'HydrationGoalTrackComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/hydrationGoalTrack"; gSobject['created'] = function(it) { gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"hydrationsGoal",gs.map()); gs.sp(gSobject.scope,"hydrationGoal",gs.map()); gs.sp(gSobject.scope,"water",null); gs.sp(gSobject.scope,"date",gs.date()); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "hydration.goal.track"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[false]); gs.mc(gSobject,"componentTheme",[false]); return gs.mc(gSobject,"loadLogs",[]); } gSobject['loadLogs'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:hydrations_goal", function(hydrationGoal) { if (gs.bool(hydrationGoal)) { gs.mc(gs.gp(gSobject.scope,"hydrationGoal"),"putAll",[hydrationGoal]); gs.sp(gs.gp(gSobject.scope,"hydrationGoal"),"unit","ml"); gs.sp(gs.gp(gSobject.scope,"hydrationGoal"),"description","target weight"); return gs.sp(gs.gp(gSobject.scope,"hydrationGoal"),"progressText","You’re on track! Keep working hard to improve your health & overall score."); }; }]); } gSobject['save'] = function(it) { gs.sp(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"hydrationsGoal"),"water",gs.gp(gs.gp(gSobject.scope,"hydrationGoal"),"water")); gs.sp(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"hydrationsGoal"),"date",gs.gp(gs.gp(gSobject.scope,"hydrationGoal"),"date")); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:hydrations_goal", gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"hydrationsGoal"), function(it) { gs.mc(gSobject,"eventLogGoal",[]); return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["hydrationOverview"]); }]); } gSobject['eventLogGoal'] = function(it) { var narrative = "Logged hydration goal: " + (gs.gp(gs.gp(gSobject.scope,"hydrationGoal"),"water")) + " ml"; return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"eventLogService"),"event",[gs.gp(gs.fs('session', this, gSobject),"userId"), narrative, "hydration:goal", "info"]),"do",[]); } gSobject['increaseWater'] = function(it) { var current = gs.elvis(gs.bool(gs.gp(gs.gp(gSobject.scope,"hydrationGoal"),"water")) , gs.gp(gs.gp(gSobject.scope,"hydrationGoal"),"water") , 0); return gs.sp(gs.gp(gSobject.scope,"hydrationGoal"),"water",(gs.plus(current, 100))); } gSobject['decreaseWater'] = function(it) { var current = gs.elvis(gs.bool(gs.gp(gs.gp(gSobject.scope,"hydrationGoal"),"water")) , gs.gp(gs.gp(gSobject.scope,"hydrationGoal"),"water") , 0); if (current >= 100) { return gs.sp(gs.gp(gSobject.scope,"hydrationGoal"),"water",(gs.minus(current, 100))); } else { return gs.sp(gs.gp(gSobject.scope,"hydrationGoal"),"water",0); }; } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function FitnessGoalComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'FitnessGoalComponent', simpleName: 'FitnessGoalComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/fitnessGoal"; gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.fitness.goal"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"batchName","health:fitness:goal"); gs.sp(gSobject.scope,"fitnessGoal",gs.map().add("duration",150)); gs.sp(gSobject.scope,"goalId",null); gs.sp(gSobject.scope,"successDialog",false); return gs.mc(gSobject,"loadGoal",[]); } gSobject['loadGoal'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"listEntries",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gSobject.scope,"batchName"), gs.map().add("limit",1).add("sort","_lastUpdated").add("order","desc"), function(logs) { if (!gs.bool(logs)) { return null; }; var goal = logs[0]; gs.sp(gs.gp(gSobject.scope,"fitnessGoal"),"duration",gs.elvis(gs.bool(gs.gp(goal,"duration")) , gs.gp(goal,"duration") , 150)); return gs.sp(gSobject.scope,"goalId",gs.gp(goal,"_id")); }]); } gSobject['saveGoal'] = function(it) { if (gs.bool(gs.gp(gSobject.scope,"sleepGoalId"))) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"deleteEntry",[gs.gp(gSobject.scope,"goalId")]); }; return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"addEntryWithFts",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.fs('batchName', this, gSobject), gs.list(["duration"]), gs.fs('fitnessGoal', this, gSobject)]),"then",[function(it) { gs.mc(gSobject,"eventLogGoal",[]); return gs.sp(gSobject.scope,"successDialog",true); }, function(error) { return gs.mc(gSobject,"notify",["Failed to save fitness goal.", "negative"]); }]); } gSobject['eventLogGoal'] = function(it) { var narrative = "Logged weekly fitness goal: " + (gs.gp(gs.gp(gSobject.scope,"fitnessGoal"),"duration")) + " minutes"; return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"eventLogService"),"event",[gs.gp(gs.fs('session', this, gSobject),"userId"), narrative, "fitness:goal", "info"]),"do",[]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function CordovaHealth() { var gSobject = gs.init('CordovaHealth'); gSobject.clazz = { name: 'CordovaHealth', simpleName: 'CordovaHealth'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject['testIsAvailable'] = function(onSuccess, onError) { if (onSuccess === undefined) onSuccess = function(it) { }; if (onError === undefined) onError = function(it) { }; return gs.mc(gSobject,"nativeIsAvailable",[function(available) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["cordova.plugins.health. isAvailable -> success: " + (available) + ""]); return gs.execCall(onSuccess, this, [available]); }, function(err) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["cordova.plugins.health.isAvailable -> error: " + (err) + ""]); return gs.execCall(onError, this, [err]); }]); } gSobject['requestPermissions'] = function(onSuccess, onError) { if (onSuccess === undefined) onSuccess = function(it) { }; if (onError === undefined) onError = function(it) { }; datatypes = gs.map().add("read",gs.list(["steps" , "blood_pressure" , "heart_rate"])); return gs.mc(gSobject,"nativeRequestAuthorization",[datatypes, function(result) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["cordova.plugins.health. requestAuthorization -> success: " + (result) + ""]); return gs.execCall(onSuccess, this, [result]); }, function(err) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["cordova. plugins.health.requestAuthorization -> error: " + (err) + ""]); return gs.execCall(onError, this, [err]); }]); } gSobject['querySteps'] = function(startDate, endDate, onSuccess, onError) { if (onSuccess === undefined) onSuccess = function(it) { }; if (onError === undefined) onError = function(it) { }; var queryParams = gs.map().add("startDate",startDate).add("endDate",endDate).add("dataType","steps").add("limit",50000); return gs.mc(gSobject,"nativeQuery",[queryParams, function(result) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["cordova.plugins.health.query steps -> success: " + (gs.mc(result,"size",[], null, true)) + " records"]); return gs.execCall(onSuccess, this, [result]); }, function(err) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["cordova.plugins.health.query steps -> error: " + (err) + ""]); return gs.execCall(onError, this, [err]); }]); } gSobject['queryBloodPressure'] = function(startDate, endDate, onSuccess, onError) { if (onSuccess === undefined) onSuccess = function(it) { }; if (onError === undefined) onError = function(it) { }; var queryParams = gs.map().add("startDate",startDate).add("endDate",endDate).add("dataType","blood_pressure").add("limit",2000); return gs.mc(gSobject,"nativeQuery",[queryParams, function(result) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["cordova.plugins.health.query blood_pressure -> success: " + (gs.mc(result,"size",[], null, true)) + " records"]); return gs.execCall(onSuccess, this, [result]); }, function(err) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["cordova.plugins.health.query blood_pressure -> error: " + (err) + ""]); return gs.execCall(onError, this, [err]); }]); } gSobject['queryHeartRate'] = function(startDate, endDate, onSuccess, onError) { if (onSuccess === undefined) onSuccess = function(it) { }; if (onError === undefined) onError = function(it) { }; var queryParams = gs.map().add("startDate",startDate).add("endDate",endDate).add("dataType","heart_rate").add("limit",50000); return gs.mc(gSobject,"nativeQuery",[queryParams, function(result) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["cordova.plugins.health.query heart_rate -> success: " + (gs.mc(result,"size",[], null, true)) + " records"]); return gs.execCall(onSuccess, this, [result]); }, function(err) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["cordova.plugins.health.query heart_rate -> error: " + (err) + ""]); return gs.execCall(onError, this, [err]); }]); } gSobject['queryAggregatedSteps'] = function(startDate, endDate, onSuccess, onError) { if (onSuccess === undefined) onSuccess = function(it) { }; if (onError === undefined) onError = function(it) { }; var queryParams = gs.map().add("startDate",startDate).add("endDate",endDate).add("dataType","steps").add("bucket","day"); return gs.mc(gSobject,"nativeQueryAggregated",[queryParams, function(result) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["cordova.plugins. health.queryAggregated steps -> success"]); return gs.execCall(onSuccess, this, [result]); }, function(err) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["cordova. plugins.health.queryAggregated steps -> error: " + (err) + ""]); return gs.execCall(onError, this, [err]); }]); } gSobject['isAuthorizedForHealth'] = function(onSuccess, onError) { if (onSuccess === undefined) onSuccess = function(it) { }; if (onError === undefined) onError = function(it) { }; datatypes = gs.map().add("read",gs.list(["steps"])); return gs.mc(gSobject,"nativeIsAuthorized",[datatypes, function(result) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["cordova.plugins.health.isAuthorized health -> success: " + (result) + ""]); return gs.execCall(onSuccess, this, [result]); }, function(err) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["cordova.plugins.health.isAuthorized health -> error: " + (err) + ""]); return gs.execCall(onError, this, [err]); }]); } gSobject.nativeIsAvailable = function(successCallback, errorCallback) { try { if (! Utils.isCordova()) { errorCallback("Cordova not available"); return; } cordova.plugins.health.isAvailable( function(available) { successCallback(available); }, function(err) { errorCallback(err.toString()); } ); } catch (e) { console.error('Exception calling cordova.plugins.health.isAvailable:', e); errorCallback(e.toString()); } } gSobject.nativeRequestAuthorization = function(datatypes, successCallback, errorCallback) { try { if (!Utils.isCordova()) { errorCallback("Cordova not available"); return; } cordova.plugins.health.requestAuthorization( datatypes, function(result) { successCallback(result); }, function(err) { errorCallback(err.toString()); } ); } catch (e) { console.error('Exception calling cordova.plugins.health.requestAuthorization:', e); errorCallback(e.toString()); } } gSobject.nativeQuery = function(queryParams, successCallback, errorCallback) { try { if (! Utils.isCordova()) { errorCallback("Cordova not available"); return; } cordova.plugins.health.query( queryParams, function(result) { successCallback(result); }, function(err) { errorCallback(err.toString()); } ); } catch (e) { console.error('Exception calling cordova.plugins. health.query:', e); errorCallback(e.toString()); } } gSobject.nativeQueryAggregated = function(queryParams, successCallback, errorCallback) { try { if (!Utils.isCordova()) { errorCallback("Cordova not available"); return; } cordova.plugins.health.queryAggregated( queryParams, function(result) { successCallback(result); }, function(err) { errorCallback(err.toString()); } ); } catch (e) { console.error('Exception calling cordova.plugins.health.queryAggregated:', e); errorCallback(e.toString()); } } gSobject.nativeIsAuthorized = function(datatypes, successCallback, errorCallback) { try { if (!Utils.isCordova()) { errorCallback("Cordova not available"); return; } cordova.plugins.health.isAuthorized( datatypes, function(result) { successCallback(result); }, function(err) { errorCallback(err.toString()); } ); } catch (e) { console.error('Exception calling cordova.plugins.health.isAuthorized:', e); errorCallback(e.toString()); } } gSobject['CordovaHealth0'] = function(it) { return this; } if (arguments.length==0) {gSobject.CordovaHealth0(); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function DymicoAuthService() { var gSobject = gs.init('DymicoAuthService'); gSobject.clazz = { name: 'DymicoAuthService', simpleName: 'DymicoAuthService'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject['auth'] = function(username, password, callback) { if (callback === undefined) callback = function(it) { }; return gs.mc(gs.gp(gs.fs('o', this, gSobject),"dymicoAuthService"),"authenticate",[username, password, function(authData) { gs.println("DymicoAuthService"); gs.println(authData); if (gs.bool(gs.gp(authData,"authenticated"))) { gs.execStatic(Utils,'updateAuthTokenToSession', this,[authData]); gs.sp(gs.fs('session', this, gSobject),"authToken",gs.gp(gs.gp(authData,"zoner"),"token")); return null; }; return gs.execCall(callback, this, [gs.gp(authData,"authenticated")]); }]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function DymicoChatListComponent() { var gSobject = VueComponent(); gSobject.clazz = { name: 'DymicoChatListComponent', simpleName: 'DymicoChatListComponent'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.props = gs.map().add("userId",String).add("subId",String).add("selectChat",Function).add("deselectChat",Function).add("theme",String); gSobject.data = function(it) { return gs.map().add("selectedChat",false).add("chatLinks",gs.list([])).add("chatMemberLink",null); }; gSobject['created'] = function(it) { var self = this; gs.sp(self,"selectedChat",null); gs.sp(self,"chatLinks",gs.list([])); return gs.mc(gSobject,"loadChats",[self]); } gSobject['loadChats'] = function(self) { if (self === undefined) self = this; return gs.mc(gs.gp(gs.fs('o', this, gSobject),"dymicoChatService"),"chatsForMemberRef",[gs.gp(self,"userId"), function(data) { gs.sp(self,"chatLinks",gs.gp(data,"chatLinks")); if (gs.equals(gs.mc(gs.gp(self,"chatLinks"),"size",[]), 1)) { gs.mc(gSobject,"openWithChatLink",[gs.gp(self,"chatLinks")[0], self]); }; if (gs.bool(gs.gp(self,"subId"))) { return gs.mc(gSobject,"openWithSubId",[gs.gp(self,"subId"), self]); }; }]); } gSobject['openWithChatLink'] = function(chatLink, self) { if (self === undefined) self = this; gs.sp(self,"chatMemberLink",chatLink); if (gs.bool(gs.gp(self,"selectChat"))) { return gs.mc(self,"selectChat",[]); }; } gSobject['openWithSubId'] = function(subId, self) { if (self === undefined) self = this; gs.sp(self,"chatMemberLink",gs.mc(gs.gp(self,"chatLinks"),"find",[function(it) { return gs.equals(gs.gp(it,"_id"), subId); }])); if (gs.bool(gs.gp(self,"selectChat"))) { return gs.mc(self,"selectChat",[]); }; } gSobject['back'] = function(it) { var self = this; gs.sp(self,"chatMemberLink",null); if (gs.bool(gs.gp(self,"deselectChat"))) { return gs.mc(self,"deselectChat",[]); }; } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function HomeComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'HomeComponent', simpleName: 'HomeComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/home"; gSobject['created'] = function(it) { gs.println("HomeComponent:v5"); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "home.landing.page"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); gs.mc(gSobject,"componentTheme",[true]); gs.sp(gSobject.scope,"user",gs.gp(gs.fs('session', this, gSobject),"user")); gs.sp(gSobject.scope,"searching",false); gs.sp(gSobject.scope,"searchText",""); gs.sp(gSobject.scope,"searchResults",gs.list([])); gs.sp(gSobject.scope,"searchLoading",false); gs.sp(gSobject.scope,"information",false); gs.sp(gSobject.scope,"homeData",gs.map()); gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"popoverTrackables",gs.list([])); gs.sp(gSobject.scope,"showEnrolDialog",false); gs.mc(gSobject,"loadHomeData",[]); gs.mc(gSobject,"loadUserPathway",[]); return gs.mc(gSobject,"loadFHAStatus",[]); } gSobject['loadFHAStatus'] = function(it) { if (gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"fhaStatus") != gs.fs('undefined', this, gSobject)) { gs.sp(gSobject.scope,"showEnrolDialog",!gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"fhaStatus")); }; return gs.mc(gSobject,"showHeaderFooter",[!gs.gp(gSobject.scope,"showEnrolDialog")]); } gSobject['healthColour'] = function(it) { if (gs.gp(gs.gp(gSobject.scope,"homeData"),"healthScore") <= 39) { return "#e21f23"; }; if (gs.gp(gs.gp(gSobject.scope,"homeData"),"healthScore") <= 74) { return "#ff751f"; }; return "#3ab54a"; } gSobject['loadHomeData'] = function(it) { return gs.mc(gs.gp(gs.mc(gs.fs('o', this, gSobject),"localAndRemote",[]),"rxmeAppService"),"homeMenu",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(homeData) { gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"homeData",homeData); if (gs.bool(gs.gp(homeData,"pushTo"))) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",[gs.gp(homeData,"pushTo")]); }; gs.sp(gSobject.scope,"homeData",homeData); gs.println("homeData"); gs.println(homeData); gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"rootContent",gs.gp(homeData,"rootContent")); gs.mc(gSobject,"applyGlobalTrackableTheme",[homeData]); gs.mc(gSobject,"updateMedicationMenuUpcomingToday",[]); gs.mc(gSobject,"loadPopoverTrackables",[]); if (!gs.bool(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"loadedPatient"))) { gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"loadedPatient",true); return gs.mc(gs.fs('peptideOrdersComponent', this, gSobject),"loadPatient",[]); }; }]); } gSobject['updateMedicationMenuUpcomingToday'] = function(it) { if (!gs.bool(gs.gp(gs.gp(gSobject.scope,"homeData"),"menus",true))) { return null; }; return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"loadRxmeUserMedication",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(meds) { var summary = null; try { summary = gs.mc(gs.fs('medicationDashboardJsService', this, gSobject),"summarizeToday",[gs.elvis(gs.bool(meds) , meds , gs.list([])), gs.mc(gSobject,"moment",[])]); } catch (ignored) { return null; } ; var upcoming = gs.elvis(gs.bool(gs.gp(summary,"upcomingMeds",true)) , gs.gp(summary,"upcomingMeds",true) , 0); var medicationMenu = gs.mc(gs.gp(gs.gp(gSobject.scope,"homeData"),"menus"),"find",[function(it) { return (gs.equals(gs.gp(it,"dataPoint",true), "medical:score:medication")) || (gs.equals(gs.gp(it,"name",true), "Medication")); }]); if (!gs.bool(medicationMenu)) { return null; }; gs.sp(medicationMenu,"data",gs.elvis(gs.bool(gs.gp(medicationMenu,"data")) , gs.gp(medicationMenu,"data") , gs.map())); gs.sp(gs.gp(medicationMenu,"data"),"value",upcoming); gs.sp(gs.gp(medicationMenu,"data"),"unit","upcoming today"); gs.sp(gs.gp(medicationMenu,"data"),"status","" + (upcoming) + " upcoming today"); gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"homeData",gs.gp(gSobject.scope,"homeData")); return gs.mc(gSobject,"loadPopoverTrackables",[]); }]); } gSobject['loadPopoverTrackables'] = function(it) { if ((gs.bool(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"homeData"))) && (gs.bool(gs.gp(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"homeData"),"menus")))) { gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"popoverTrackables",gs.mc(gs.gp(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"homeData"),"menus"),"findAll",[function(it) { return (gs.equals(gs.gp(it,"type"), "trackable")) && (gs.bool(gs.gp(it,"favorite"))); }])); return gs.println("Popover trackables updated"); }; } gSobject['applyGlobalTrackableTheme'] = function(homeData) { var menusData = gs.gp(homeData,"menus",true); if (!gs.bool(menusData)) { return null; }; var trackableMap = gs.map().add("Blood Pressure","--q-bloodpressure").add("Weight","--q-weight").add("Mood","--q-mood").add("Steps","--q-steps").add("Glucose","--q-glucose").add("Smoking","--q-smoking").add("Sleep","--q-sleep").add("Hydration","--q-hydration").add("Heart Rate","--q-heartrate").add("Injection","--q-injection").add("Medication","--q-medication").add("Symptoms","--q-symptoms").add("Nutrition","--q-nutrition").add("Fitness Tracker","--q-fitness"); var root = gs.gp(gs.gp(gs.fs('document', this, gSobject),"documentElement"),"style"); return gs.mc(menusData,"each",[function(trackable) { if ((!gs.bool(gs.gp(trackable,"name"))) || (!gs.bool(gs.gp(trackable,"color")))) { return null; }; var cssVarName = trackableMap[gs.gp(trackable,"name")]; if (gs.bool(cssVarName)) { return gs.mc(root,"setProperty",[cssVarName, gs.gp(trackable,"color")]); }; }]); } gSobject['isUserAllowed'] = function(userId) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppApiService"),"checkConsentAndActivate",[userId, function(it) { return null; }]); } gSobject['loadAppointment'] = function(it) { gs.sp(gSobject.scope,"appointments",null); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppApiService"),"appointments",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(appointments) { gs.println("appointments"); gs.println(appointments); if (!gs.bool(appointments)) { return null; }; var userEmail = gs.gp(gs.gp(gs.fs('session', this, gSobject),"user"),"email"); gs.mc(appointments,"each",[function(appointment) { gs.sp(appointment,"rxmeParticipants",gs.mc(gs.gp(appointment,"participants"),"findAll",[function(it) { return gs.gp(it,"email") != userEmail; }], null, true)); return gs.sp(appointment,"appointment_at",gs.mc(gSobject,"moment",[gs.gp(appointment,"appointment_at")])); }]); return gs.sp(gSobject.scope,"appointments",appointments); }]); } gSobject['searchClose'] = function(it) { gs.mc(gSobject,"searchClear",[]); return gs.sp(gSobject.scope,"searching",false); } gSobject['searchClear'] = function(it) { gs.sp(gSobject.scope,"searchText",""); return gs.sp(gSobject.scope,"searchResults",gs.list([])); } gSobject['searchSubmit'] = function(it) { gs.sp(gSobject.scope,"searchResults",gs.list([])); gs.sp(gSobject.scope,"searchLoading",true); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"mediaContentAppService"),"mediaUserSearchContent",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gSobject.scope,"searchText"), gs.gp(gSobject.scope,"rootContent"), function(data) { gs.sp(gSobject.scope,"searchResults",gs.mc(data,"findAll",[function(item) { return !gs.gSin(gs.gp(item,"type"), gs.list(["menu"])); }])); return gs.sp(gSobject.scope,"searchLoading",false); }]); } gSobject['searchNavigate'] = function(content) { if (gs.mc(gs.gp(content,"customPath"),"startsWith",["http"], null, true)) { return gs.execStatic(Utils,'open', this,[gs.gp(content,"customPath")]); }; if (gs.mc(gs.gp(content,"customPath"),"startsWith",["/statics/"], null, true)) { return gs.execStatic(Utils,'open', this,[gs.gp(content,"customPath")]); }; if (gs.bool(gs.gp(content,"customPath"))) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",[gs.gp(content,"customPath")]); }; if (gs.equals(gs.mc(gs.gp(content,"section"),"toLowerCase",[], null, true), "articles")) { return gs.sp(gSobject.scope,"articleName",gs.mc(content,"label",[gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/mediaContent/" + (gs.gp(content,"_id")) + ""])])); } else { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/shorts/" + (gs.gp(content,"_id")) + ""]); }; } gSobject['hasData'] = function(menu) { return (gs.bool(gs.gp(menu,"data")) ? true : false); } gSobject['hasVisibleHealthMetrics'] = function(it) { return gs.mc(gs.elvis(gs.bool(gs.gp(gs.gp(gSobject.scope,"homeData"),"userPathway",true)) , gs.gp(gs.gp(gSobject.scope,"homeData"),"userPathway",true) , gs.list([])),"any",[function(pathwayUser) { var trackables = gs.elvis(gs.bool(gs.gp(gs.gp(pathwayUser,"pathway",true),"trackables",true)) , gs.gp(gs.gp(pathwayUser,"pathway",true),"trackables",true) , gs.elvis(gs.bool(gs.gp(gs.gp(gs.gp(pathwayUser,"pathway",true),"scoreConfig",true),"trackers",true)) , gs.gp(gs.gp(gs.gp(pathwayUser,"pathway",true),"scoreConfig",true),"trackers",true) , gs.list([]))); return (gs.bool(trackables)) && (gs.mc(trackables,"size",[]) > 0); }]); } gSobject['open'] = function(menu) { if (gs.equals(gs.gp(menu,"type"), "trackable")) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",[gs.gp(menu,"navPath")]); }; if (gs.bool(gs.gp(menu,"setupPath"))) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",[gs.gp(menu,"setupPath")]); }; } gSobject['goToAppointment'] = function(appointment) { gs.println("goToAppointment"); gs.println(appointment); return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",[gs.plus("/appointmentsController/", gs.gp(appointment,"id"))]); } gSobject['cancelAppointment'] = function(appointment) { return gs.mc(gs.mc(gSobject.q,"dialog",[gs.map().add("title","").add("message","Cancel the appointment?").add("cancel",true).add("color","primary").add("dark",false).add("class","text-black")]),"onOk",[function(data) { return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppApiService"),"appointmentDelete",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(appointment,"id")]),"then",[function(result) { gs.mc(gSobject,"notify",["Appointment Cancelled"]); return gs.mc(gSobject,"loadAppointment",[]); }, function(error) { return gs.mc(gSobject,"notify",[gs.gp(error,"message")]); }]); }]); } gSobject['loadUserPathway'] = function(it) { gs.println("loadUserPathway"); gs.sp(gSobject.scope,"rxmeUserPathway",gs.list([])); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"pathwayAdminService"),"loadUserPathway",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(pathway) { return gs.sp(gSobject.scope,"rxmeUserPathway",pathway); }]); } gSobject['showQuestionnaire'] = function(isAdvancedTester, menu) { return ((gs.bool(isAdvancedTester)) && (gs.equals(gs.gp(menu,"setupComponent"), "MenuCardLarge"))) || ((gs.equals(gs.gp(menu,"setupComponent"), "MenuCardLarge")) && ((gs.bool(gs.gp(menu,"questionnaireExpired"))) || (!gs.bool(gs.gp(gs.gp(menu,"data"),"completed"))))); } gSobject['formatCompletedDate'] = function(date) { return gs.mc(gs.mc(gSobject,"moment",[date]),"format",["MMMM DD, YYYY"]); } gSobject['hideEnrolDialog'] = function(it) { gs.sp(gSobject.scope,"showEnrolDialog",false); return gs.mc(gSobject,"showHeaderFooter",[true]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function HealthScoreComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'HealthScoreComponent', simpleName: 'HealthScoreComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/healthScore" , "/healthScore/:id"]); gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "user.health.score"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"infoDialog",false); gs.sp(gSobject.scope,"healthScore",null); gs.sp(gSobject.scope,"healthMessage",""); gs.sp(gSobject.scope,"userPathways",gs.list([])); gs.sp(gSobject.scope,"colorMap",gs.mc(gs.gp(ProtocolQNResultComponent,"colorMap"),"clone",[])); gs.mc(gs.gp(gs.mc(gs.fs('o', this, gSobject),"localAndRemote",[]),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "health:score:main:score", function(healthScore) { gs.sp(gSobject.scope,"healthScore",healthScore); return gs.sp(gSobject.scope,"healthMessage",gs.mc(gSobject,"healthScoreMessage",[healthScore])); }]); gs.sp(gSobject.scope,"healthBackgound",null); gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "health:score:main:background", function(healthBackgound) { return gs.sp(gSobject.scope,"healthBackgound",healthBackgound); }]); gs.sp(gSobject.scope,"lastUpdated",null); gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "health:score:main:last_updated", function(lastUpdated) { return gs.sp(gSobject.scope,"lastUpdated",lastUpdated); }]); gs.mc(gSobject,"loadUserPathways",[]); return gs.mc(gSobject,"loadMedicalReport",[]); } gSobject['loadUserPathways'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"pathwayAdminService"),"loadUserPathway",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(userPathways) { gs.sp(gSobject.scope,"userPathways",gs.elvis(gs.bool(userPathways) , userPathways , gs.list([]))); return gs.mc(gs.gp(gs.mc(gs.fs('o', this, gSobject),"localAndRemote",[]),"rxmeAppService"),"loadAllScoreResults",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(allHealthMetrics) { return gs.mc(gs.gp(gSobject.scope,"userPathways"),"each",[function(pathwayUser) { if (gs.bool(gs.gp(gs.gp(pathwayUser,"pathway"),"questionnaires",true))) { return gs.mc(gs.gp(gs.gp(pathwayUser,"pathway"),"questionnaires"),"each",[function(questionnaire) { if (!gs.bool(questionnaire)) { return null; }; var scoreResult = allHealthMetrics[gs.gp(questionnaire,"_id")]; if (gs.bool(scoreResult)) { gs.sp(questionnaire,"scoreResult",scoreResult); return gs.sp(questionnaire,"hasData",true); } else { gs.sp(questionnaire,"scoreResult",null); return gs.sp(questionnaire,"hasData",false); }; }]); }; }]); }]); }]); } gSobject['healthScoreMessage'] = function(score) { var gSswitch0 = score; if (function(it) { if (it === undefined) it = gSswitch0; return gs.equals(it, null); }()) { return ""; } else if (function(it) { if (it === undefined) it = gSswitch0; return it < 10; }()) { return "Every journey starts somewhere. Small steps today are your springboard."; } else if (function(it) { if (it === undefined) it = gSswitch0; return it < 20; }()) { return "Getting started is the key. A little progress each week adds up."; } else if (function(it) { if (it === undefined) it = gSswitch0; return it < 30; }()) { return "You are making progress. Stick with your habits and watch your health grow."; } else if (function(it) { if (it === undefined) it = gSswitch0; return it < 40; }()) { return "Solid effort! Keep pushing, your health is moving forward."; } else if (function(it) { if (it === undefined) it = gSswitch0; return it < 50; }()) { return "Making headway. Stay consistent and you’ll keep climbing."; } else if (function(it) { if (it === undefined) it = gSswitch0; return it < 60; }()) { return "You’re halfway there – a strong base for even better days ahead."; } else if (function(it) { if (it === undefined) it = gSswitch0; return it < 70; }()) { return "Things are looking good. Celebrate your wins and keep going."; } else if (function(it) { if (it === undefined) it = gSswitch0; return it < 80; }()) { return "Impressive! Your commitment is paying off. Strive for excellence."; } else if (function(it) { if (it === undefined) it = gSswitch0; return it < 90; }()) { return "Great work. You’re among the healthiest – keep your momentum."; } else if (function(it) { if (it === undefined) it = gSswitch0; return it <= 100; }()) { return "Outstanding! You’re a health star. Continue to inspire yourself and others."; } else { return "Keep steady. Every day is a new opportunity for your wellbeing."; }; } gSobject['loadMedicalReport'] = function(it) { gs.sp(gSobject.scope,"medicalReportEntry",null); gs.sp(gSobject.scope,"loadingReport",true); gs.sp(gSobject.scope,"reportGenerating",false); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeApiDataService"),"loadLatestMedicalReportEntry",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(entry) { gs.println("MEDICAL ENTRY"); gs.println(entry); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "person:fha:report:requested", function(requested) { gs.println("REPORT REQUESTED: " + (requested) + ""); var requestedTime = (gs.bool(requested) ? gs.mc(this,"parseInt",[requested], gSobject) : 0); var reportTime = gs.elvis(gs.mc(gs.gp(entry,"_dateCreated",true),"getTime",[], null, true) , gs.mc(gs.gp(entry,"_dateCreated",true),"getTime",[], null, true) , 0); if ((gs.bool(entry)) && (requestedTime <= reportTime)) { gs.sp(gSobject.scope,"loadingReport",false); return gs.sp(gSobject.scope,"medicalReportEntry",entry); } else { if (requestedTime > 0) { gs.sp(gSobject.scope,"loadingReport",false); return gs.sp(gSobject.scope,"reportGenerating",true); } else { return gs.sp(gSobject.scope,"loadingReport",false); }; }; }]); }]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function SleepUtilsComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'SleepUtilsComponent', simpleName: 'SleepUtilsComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject['formatTime'] = function(time) { var hour12 = (gs.equals(gs.gp(time,"hour"), 0) ? 12 : (gs.gp(time,"hour") > 12 ? gs.minus(gs.gp(time,"hour"), 12) : gs.gp(time,"hour"))); var hourStr = gs.mc(gs.mc(hour12,"toString",[]),"padStart",[2, "0"]); var minuteStr = gs.mc(gs.mc(gs.gp(time,"minute"),"toString",[]),"padStart",[2, "0"]); var period = (gs.gp(time,"hour") < 12 ? "AM" : "PM"); return "" + (hourStr) + ":" + (minuteStr) + " " + (period) + ""; } gSobject['calculateSleepDuration'] = function(bedtime, wakeupTime) { if ((!gs.bool(bedtime)) || (!gs.bool(wakeupTime))) { return 0; }; var bedMinutes = gs.plus((gs.multiply(gs.gp(bedtime,"hour"), 60)), gs.gp(bedtime,"minute")); var wakeMinutes = gs.plus((gs.multiply(gs.gp(wakeupTime,"hour"), 60)), gs.gp(wakeupTime,"minute")); var durationMinutes = (wakeMinutes >= bedMinutes ? gs.minus(wakeMinutes, bedMinutes) : gs.plus((gs.minus((gs.multiply(24, 60)), bedMinutes)), wakeMinutes)); var hours = Math.floor(gs.div(durationMinutes, 60)); var minutes = gs.mod(durationMinutes, 60); return gs.plus(hours, (gs.div(minutes, 60))); } gSobject['formatDuration'] = function(duration) { if (!gs.bool(duration)) { return "0h"; }; var hours = Math.floor(duration); var minutes = Math.round(gs.multiply((gs.minus(duration, hours)), 60)); return (minutes > 0 ? "" + (hours) + "h " + (minutes) + "m" : "" + (hours) + "h"); } gSobject['formatSleepGoal'] = function(sleepGoal) { if (!gs.bool(sleepGoal)) { return "0h"; }; var hours = Math.floor(gs.div(sleepGoal, 60)); var minutes = gs.mod(sleepGoal, 60); return (minutes > 0 ? "" + (hours) + "h " + (minutes) + "m" : "" + (hours) + "h"); } gSobject['formatDate'] = function(dateString) { if (!gs.bool(dateString)) { return ""; }; var dateParts = gs.mc(dateString,"split",["-"]); if (gs.gp(dateParts,"length") >= 3) { var year = dateParts[0]; var month = dateParts[1]; var day = dateParts[2]; return "" + (day) + "/" + (month) + "/" + (year) + ""; }; return dateString; } gSobject['timeTillBedtimeFormatted'] = function(bedtimeObj) { if (bedtimeObj === undefined) bedtimeObj = gs.map().add("hour",22).add("minute",0); var currentTime = gs.date(); var bedTime = gs.date(gs.mc(currentTime,"getTime",[])); gs.mc(bedTime,"setHours",[gs.gp(bedtimeObj,"hour")]); gs.mc(bedTime,"setMinutes",[gs.gp(bedtimeObj,"minute")]); gs.mc(bedTime,"setSeconds",[0]); if (gs.mc(bedTime,"getTime",[]) <= gs.mc(currentTime,"getTime",[])) { gs.mc(bedTime,"setDate",[gs.plus(gs.mc(bedTime,"getDate",[]), 1)]); }; var durationMillis = gs.minus(gs.mc(bedTime,"getTime",[]), gs.mc(currentTime,"getTime",[])); var hours = Math.floor(gs.div(durationMillis, (gs.multiply((gs.multiply(1000, 60)), 60)))); var minutes = Math.floor(gs.div((gs.mod(durationMillis, (gs.multiply((gs.multiply(1000, 60)), 60)))), (gs.multiply(1000, 60)))); var formatted = "" + (hours) + "h"; if (minutes != 0) { formatted += " " + (minutes) + "m"; }; return formatted; } gSobject['estimateSleepStages'] = function(bedtime, wakeupTime, duration) { var totalMinutes = Math.round(gs.multiply(duration, 60)); var stageProfiles = gs.list([gs.map().add("maxDuration",1.5).add("light",0.60).add("deep",0.05).add("rem",0.10).add("awake",0.25) , gs.map().add("maxDuration",3.0).add("light",0.55).add("deep",0.10).add("rem",0.15).add("awake",0.20) , gs.map().add("maxDuration",5.0).add("light",0.52).add("deep",0.15).add("rem",0.20).add("awake",0.13) , gs.map().add("maxDuration",999).add("light",0.50).add("deep",0.20).add("rem",0.22).add("awake",0.08)]); var profile = gs.mc(stageProfiles,"find",[function(it) { return gs.gp(it,"maxDuration") >= duration; }]); var lightMins = Math.round(gs.multiply(totalMinutes, gs.gp(profile,"light"))); var deepMins = Math.round(gs.multiply(totalMinutes, gs.gp(profile,"deep"))); var remMins = Math.round(gs.multiply(totalMinutes, gs.gp(profile,"rem"))); var awakeMins = gs.minus(totalMinutes, (gs.plus((gs.plus(lightMins, deepMins)), remMins))); return gs.map().add("light",lightMins).add("deep",deepMins).add("rem",remMins).add("awake",awakeMins); } gSobject['getRegularityScore'] = function(sleepLogs) { if (gs.mc(sleepLogs,"size",[]) <= 1) { return 50; }; var bedtimeVariance = gs.mc(gSobject,"calculateTimeVariance",[gs.mc(sleepLogs,"collect",[function(it) { return gs.gp(it,"bedtime"); }])]); var waketimeVariance = gs.mc(gSobject,"calculateTimeVariance",[gs.mc(sleepLogs,"collect",[function(it) { return gs.gp(it,"wakeupTime"); }])]); var bedtimeScore = Math.max(0, gs.minus(100, (gs.multiply(bedtimeVariance, 50)))); var waketimeScore = Math.max(0, gs.minus(100, (gs.multiply(waketimeVariance, 50)))); return gs.div((gs.plus(bedtimeScore, waketimeScore)), 2); } gSobject['getFrequencyScore'] = function(loggedDays, currentDate) { var daysInMonth = (gs.equals(gs.mc(currentDate,"format",["MM"]), "02") ? 28 : 30); return Math.min(100, gs.multiply((gs.div(loggedDays, daysInMonth)), 100)); } gSobject['calculateSleepScore'] = function(sleepLogs) { if ((!gs.bool(sleepLogs)) || (gs.mc(sleepLogs,"isEmpty",[]))) { return 0; }; var individualScores = gs.mc(sleepLogs,"collect",[function(log) { return gs.mc(gSobject,"calculateIndividualSleepScore",[gs.gp(log,"bedtime"), gs.gp(log,"wakeupTime"), gs.gp(log,"duration"), gs.gp(log,"stages")]); }]); var avgIndividualScore = gs.div(gs.mc(individualScores,"sum",[]), gs.mc(individualScores,"size",[])); var regularityScore = gs.mc(gSobject,"getRegularityScore",[sleepLogs]); var frequencyScore = gs.mc(gSobject,"getFrequencyScore",[gs.mc(sleepLogs,"size",[]), gs.date()]); var totalScore = gs.plus((gs.plus((gs.multiply(avgIndividualScore, 0.7)), (gs.multiply(regularityScore, 0.15)))), (gs.multiply(frequencyScore, 0.15))); return Math.round(totalScore); } gSobject['calculateTimeVariance'] = function(times) { if ((!gs.bool(times)) || (gs.mc(times,"size",[]) <= 1)) { return 0; }; var minutesFromMidnight = gs.mc(times,"collect",[function(time) { var minutes = gs.plus((gs.multiply(gs.gp(time,"hour"), 60)), gs.gp(time,"minute")); if (minutes < 360) { minutes += 1440; }; return minutes; }]); var mean = gs.div(gs.mc(minutesFromMidnight,"sum",[]), gs.mc(minutesFromMidnight,"size",[])); var variance = gs.div(gs.mc(gs.mc(minutesFromMidnight,"collect",[function(it) { return Math.pow(gs.minus(it, mean), 2); }]),"sum",[]), gs.mc(minutesFromMidnight,"size",[])); return gs.div(Math.sqrt(variance), 60.0); } gSobject['round1'] = function(x) { return gs.div(Math.round(gs.multiply(x, 10)), 10); } gSobject['calculateIndividualSleepScore'] = function(bedtime, wakeupTime, duration, breakdown) { var durationScore = gs.mc(gSobject,"calculateDurationScore",[duration]); var qualityScore = gs.mc(gSobject,"calculateQualityScore",[duration, breakdown]); var efficiencyScore = gs.mc(gSobject,"calculateEfficiencyScore",[duration, breakdown]); var totalScore = gs.plus((gs.plus((gs.multiply(durationScore, 0.50)), (gs.multiply(qualityScore, 0.30)))), (gs.multiply(efficiencyScore, 0.20))); return Math.round(totalScore); } gSobject['calculateDurationScore'] = function(duration) { if (duration <= 0) { return 0; }; var optimal = 8.0; var deviation = Math.abs(gs.minus(duration, optimal)); var score = gs.multiply(100, Math.exp(-(Math.pow(gs.div(deviation, 2.5), 2)))); if (duration < 1) { score = Math.min(score, 5); }; if (duration < 2) { score = Math.min(score, 15); }; return Math.max(0, Math.min(100, Math.round(score))); } gSobject['calculateQualityScore'] = function(duration, breakdown) { if (duration < 2) { return Math.min(20, gs.mc(gSobject,"calculateDurationScore",[duration])); }; var totalSleep = gs.plus((gs.plus((gs.plus(gs.gp(breakdown,"deep"), gs.gp(breakdown,"rem"))), gs.gp(breakdown,"light"))), gs.gp(breakdown,"awake")); if (totalSleep <= 0) { return 0; }; var restorativeSleep = gs.plus(gs.gp(breakdown,"deep"), gs.gp(breakdown,"rem")); var restorativeRatio = gs.div(restorativeSleep, totalSleep); var qualityRanges = gs.list([gs.map().add("min",0.35).add("max",0.50).add("score",100) , gs.map().add("min",0.25).add("max",0.60).add("score",80) , gs.map().add("min",0.15).add("max",0.70).add("score",60) , gs.map().add("min",0.10).add("max",0.80).add("score",40) , gs.map().add("min",0.00).add("max",1.00).add("score",20)]); return gs.elvis(gs.bool(gs.gp(gs.mc(qualityRanges,"find",[function(range) { return (restorativeRatio >= gs.gp(range,"min")) && (restorativeRatio <= gs.gp(range,"max")); }]),"score",true)) , gs.gp(gs.mc(qualityRanges,"find",[function(range) { return (restorativeRatio >= gs.gp(range,"min")) && (restorativeRatio <= gs.gp(range,"max")); }]),"score",true) , 20); } gSobject['calculateEfficiencyScore'] = function(duration, breakdown) { if (duration < 1.5) { return 5; }; var totalSleep = gs.plus((gs.plus((gs.plus(gs.gp(breakdown,"deep"), gs.gp(breakdown,"rem"))), gs.gp(breakdown,"light"))), gs.gp(breakdown,"awake")); if (totalSleep <= 0) { return 0; }; var awakeRatio = gs.div(gs.gp(breakdown,"awake"), totalSleep); var efficiency = Math.max(0, gs.minus(100, (gs.multiply(awakeRatio, 400)))); return Math.round(efficiency); } gSobject['getSleepScoreDescription'] = function(score) { if (score >= 90) { return "Exceptional sleep! You're well-rested and recovered."; } else { if (score >= 80) { return "Excellent sleep quality with optimal recovery."; } else { if (score >= 70) { return "Good sleep quality with effective restoration."; } else { if (score >= 60) { return "Fair sleep - some room for improvement."; } else { if (score >= 50) { return "Average sleep - consider optimizing your routine."; } else { if (score >= 40) { return "Below average - focus on sleep hygiene."; } else { if (score >= 30) { return "Poor sleep quality - improvements needed."; } else { if (score >= 20) { return "Very poor sleep - significant issues present."; } else { if (score >= 10) { return "Critical sleep problems - seek professional help."; } else { return "Severely disrupted sleep - immediate attention required."; }; }; }; }; }; }; }; }; }; } gSobject['getSleepStageInfo'] = function(stage) { var stageInfoMap = gs.map().add("deep",gs.map().add("title","Deep Sleep").add("description","Deep sleep is the most restorative stage of sleep. During this stage, your body repairs tissues, strengthens your immune system, and consolidates memories. This is when growth hormone is released and your brain clears out toxins.")).add("rem",gs.map().add("title","REM Sleep").add("description","REM (Rapid Eye Movement) sleep is crucial for cognitive function, memory consolidation, and emotional processing. Most vivid dreams occur during this stage. REM sleep helps with learning, creativity, and mental restoration.")).add("light",gs.map().add("title","Light Sleep").add("description","Light sleep serves as a transition between wakefulness and deeper sleep stages. While it's easier to wake up during this stage, light sleep still contributes to feeling refreshed and helps with memory formation and learning.")).add("awake",gs.map().add("title","Awake Time").add("description","Brief awakenings during the night are completely normal and part of healthy sleep architecture. These short periods typically occur between sleep cycles and most people don't remember them in the morning.")); return gs.elvis(stageInfoMap[stage] , stageInfoMap[stage] , gs.map().add("title","Sleep Stage").add("description","Information about this sleep stage.")); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function I3SidePanel() { var gSobject = VueComponent(); gSobject.clazz = { name: 'I3SidePanel', simpleName: 'I3SidePanel'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.props = gs.map().add("modelValue",gs.map().add("type",String)).add("position",gs.map().add("type",String).add("default","right")); gSobject.data = function(it) { return gs.list([]); }; gSobject['created'] = function(it) { var self = this; } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function MedicationDashboardJsService() { var gSobject = gs.init('MedicationDashboardJsService'); gSobject.clazz = { name: 'MedicationDashboardJsService', simpleName: 'MedicationDashboardJsService'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject['createFormTypes'] = function(it) { return gs.list([gs.map().add("label","Tablet").add("value","tablet") , gs.map().add("label","Capsule").add("value","capsule") , gs.map().add("label","Oral Solution").add("value","syrup") , gs.map().add("label","Injection").add("value","injection") , gs.map().add("label","Topical (Cream/Ointment)").add("value","topical")]); } gSobject['createDefaultEntry'] = function(it) { return gs.map().add("name","").add("formType","tablet").add("route","").add("doseLabel","Tablets per dose").add("hint","How many tablets per dose").add("startDate",gs.date()).add("endDate",gs.date()).add("time",gs.date()).add("volume","10").add("dosage","").add("amount","").add("shape","").add("color","").add("days",gs.list([])).add("refill",false).add("reminder",false).add("threshold","").add("qty","").add("applicationSite","").add("applicationInstructions","").add("prn",false).add("prnReason",""); } gSobject['formTypeConfig'] = function(rawType) { var typeVal = gs.elvis(gs.bool(gs.gp(rawType,"value",true)) , gs.gp(rawType,"value",true) , gs.elvis(gs.bool(rawType) , rawType , "tablet")); if (gs.equals(typeVal, "capsule")) { return gs.map().add("type","capsule").add("route","").add("unit",gs.list(["units"])).add("doseLabel","Capsules per dose").add("hint","How many capsules per dose").add("stockUnit","units"); }; if (gs.equals(typeVal, "syrup")) { return gs.map().add("type","syrup").add("route","PO").add("unit",gs.list(["units"])).add("doseLabel","Volume per Dose").add("hint","How many ml per dose").add("stockUnit","units"); }; if (gs.equals(typeVal, "injection")) { return gs.map().add("type","injection").add("route","IMI").add("unit",gs.list(["units"])).add("doseLabel","Volume per Injection").add("hint","How many ml per injection").add("stockUnit","units"); }; if (gs.equals(typeVal, "topical")) { return gs.map().add("type","topical").add("route","skin").add("unit",gs.list(["units"])).add("doseLabel","Amount per Application").add("hint","How much cream/lotion to apply").add("stockUnit","units"); }; return gs.map().add("type","tablet").add("route","").add("unit",gs.list(["units"])).add("doseLabel","Tablets per dose").add("hint","How many tablets per dose").add("stockUnit","units"); } gSobject['applyFormType'] = function(entry, rawType) { var config = gs.mc(gSobject,"formTypeConfig",[rawType]); gs.sp(entry,"formType",gs.gp(config,"type")); gs.sp(entry,"route",gs.gp(config,"route")); gs.sp(entry,"doseLabel",gs.gp(config,"doseLabel")); gs.sp(entry,"hint",gs.gp(config,"hint")); if (gs.equals(gs.gp(config,"type"), "topical")) { gs.sp(entry,"amount",""); gs.sp(entry,"dosage",""); gs.sp(entry,"qty",""); gs.sp(entry,"refill",false); gs.sp(entry,"threshold",""); } else { gs.sp(entry,"applicationSite",""); gs.sp(entry,"applicationInstructions",""); gs.sp(entry,"prn",false); gs.sp(entry,"prnReason",""); }; return gs.map().add("entry",entry).add("dosageUnit",gs.gp(config,"unit")).add("stockUnit",gs.gp(config,"stockUnit")); } gSobject['toInt'] = function(value) { if ((gs.equals(value, null)) || (gs.equals(gs.mc(gs.mc(value,"toString",[]),"trim",[]), ""))) { return 0; }; try { return parseInt(gs.mc(value,"toString",[])); } catch (ignored) { return 0; } ; } gSobject['toHourMinute'] = function(rawTime) { if (!gs.bool(rawTime)) { return null; }; if (gs.instanceOf(rawTime, "Date")) { return gs.mc(gs.mc(this,"moment",[rawTime], gSobject),"format",["HH:mm"]); }; var text = gs.mc(rawTime,"toString",[]); var strictFormats = gs.list(["HH:mm" , "HH:mm:ss" , "h:mm A" , "h:mm:ss A"]); for (_i50 = 0, fmt = strictFormats[0]; _i50 < strictFormats.length; fmt = strictFormats[++_i50]) { var parsed = gs.mc(this,"moment",[text, fmt, true], gSobject); if (gs.mc(parsed,"isValid",[])) { return gs.mc(parsed,"format",["HH:mm"]); }; }; var fallback = gs.mc(this,"moment",[text], gSobject); return (gs.mc(fallback,"isValid",[]) ? gs.mc(fallback,"format",["HH:mm"]) : null); } gSobject['normalizeCreateTime'] = function(rawTime) { return gs.elvis(gs.mc(gSobject,"toHourMinute",[rawTime]) , gs.mc(gSobject,"toHourMinute",[rawTime]) , "08:00"); } gSobject['createEntryFromMedication'] = function(med) { var normalizedTime = gs.mc(gSobject,"normalizeCreateTime",[gs.gp(med,"time",true)]); return gs.map().add("name",gs.elvis(gs.bool(gs.gp(med,"name",true)) , gs.gp(med,"name",true) , "")).add("formType",gs.elvis(gs.bool(gs.gp(med,"formType",true)) , gs.gp(med,"formType",true) , "tablet")).add("route",gs.elvis(gs.bool(gs.gp(med,"route",true)) , gs.gp(med,"route",true) , "")).add("startDate",gs.mc(gs.mc(this,"moment",[gs.gp(med,"startDate",true)], gSobject),"format",["YYYY-MM-DD"])).add("endDate",(gs.bool(gs.gp(med,"endDate",true)) ? gs.mc(gs.mc(this,"moment",[gs.gp(med,"endDate")], gSobject),"format",["YYYY-MM-DD"]) : gs.mc(gs.mc(this,"moment",[gs.gp(med,"startDate",true)], gSobject),"format",["YYYY-MM-DD"]))).add("time",normalizedTime).add("volume",gs.elvis(gs.bool(gs.gp(med,"volume",true)) , gs.gp(med,"volume",true) , "")).add("dosage",gs.elvis(gs.bool(gs.gp(med,"dosage",true)) , gs.gp(med,"dosage",true) , 0)).add("amount",gs.elvis(gs.bool(gs.gp(med,"amount",true)) , gs.gp(med,"amount",true) , "")).add("qty",gs.elvis(gs.bool(gs.gp(med,"qty",true)) , gs.gp(med,"qty",true) , 0)).add("shape",gs.elvis(gs.bool(gs.gp(med,"shape",true)) , gs.gp(med,"shape",true) , "")).add("color",gs.elvis(gs.bool(gs.gp(med,"color",true)) , gs.gp(med,"color",true) , "")).add("days",gs.elvis(gs.bool(gs.gp(med,"days",true)) , gs.gp(med,"days",true) , gs.list([]))).add("refill",!!gs.gp(med,"refill",true)).add("reminder",!!gs.gp(med,"reminder",true)).add("threshold",gs.elvis(gs.bool(gs.gp(med,"threshold",true)) , gs.gp(med,"threshold",true) , 0)).add("applicationSite",gs.elvis(gs.bool(gs.gp(med,"applicationSite",true)) , gs.gp(med,"applicationSite",true) , "")).add("applicationInstructions",gs.elvis(gs.bool(gs.gp(med,"applicationInstructions",true)) , gs.gp(med,"applicationInstructions",true) , "")).add("prn",!!gs.gp(med,"prn",true)).add("prnReason",gs.elvis(gs.bool(gs.gp(med,"prnReason",true)) , gs.gp(med,"prnReason",true) , "")); } gSobject['createValidationError'] = function(entry) { if ((!gs.bool(gs.gp(entry,"name",true))) || (!gs.bool(gs.mc(gs.mc(gs.gp(entry,"name"),"toString",[]),"trim",[])))) { return "Medication name is required"; }; var start = gs.mc(this,"moment",[gs.gp(entry,"startDate")], gSobject); var end = gs.mc(this,"moment",[gs.gp(entry,"endDate")], gSobject); if (!gs.bool(gs.mc(start,"isValid",[]))) { return "Start date is required"; }; if (!gs.bool(gs.mc(end,"isValid",[]))) { return "End date is required"; }; if (gs.mc(end,"isBefore",[start, "day"])) { return "End date cannot be before start date"; }; if ((!gs.bool(gs.gp(entry,"time"))) || (!gs.bool(gs.mc(gSobject,"normalizeCreateTime",[gs.gp(entry,"time")])))) { return "Medication time is required"; }; if ((!gs.bool(gs.gp(entry,"days"))) || (gs.equals(gs.mc(gs.gp(entry,"days"),"size",[]), 0))) { return "Select at least one day"; }; var isTopical = gs.equals(gs.gp(entry,"formType"), "topical"); if ((!gs.bool(isTopical)) && (gs.mc(gSobject,"toInt",[gs.gp(entry,"amount")]) <= 0)) { return "Strength per unit must be greater than 0"; }; if ((!gs.bool(isTopical)) && (gs.mc(gSobject,"toInt",[gs.gp(entry,"dosage")]) <= 0)) { return "Dosage must be greater than 0"; }; if ((!gs.bool(isTopical)) && (gs.mc(gSobject,"toInt",[gs.gp(entry,"qty")]) <= 0)) { return "Current stock must be greater than 0"; }; if ((gs.bool(isTopical)) && (!gs.bool(gs.mc(gs.mc(gs.gp(entry,"applicationSite"),"toString",[], null, true),"trim",[], null, true)))) { return "Application site is required for topical medication"; }; if ((gs.bool(isTopical)) && (!gs.bool(gs.mc(gs.mc(gs.gp(entry,"applicationInstructions"),"toString",[], null, true),"trim",[], null, true)))) { return "Application instructions are required for topical medication"; }; if (((gs.bool(isTopical)) && (gs.bool(gs.gp(entry,"prn")))) && (!gs.bool(gs.mc(gs.mc(gs.gp(entry,"prnReason"),"toString",[], null, true),"trim",[], null, true)))) { return "PRN reason is required when As needed is enabled"; }; if ((gs.bool(gs.gp(entry,"refill"))) && (gs.mc(gSobject,"toInt",[gs.gp(entry,"threshold")]) <= 0)) { return "Refill threshold must be greater than 0"; }; return null; } gSobject['createPayload'] = function(entry) { var formType = gs.gp(entry,"formType"); var isTrackable = gs.gSin(formType, gs.list(["tablet" , "capsule" , "syrup"])); var isConsumable = gs.gSin(formType, gs.list(["tablet" , "capsule" , "syrup" , "injection"])); var isTopical = gs.equals(formType, "topical"); return gs.map().add("name",gs.gp(entry,"name")).add("formType",gs.gp(entry,"formType")).add("route",gs.gp(entry,"route")).add("startDate",gs.gp(entry,"startDate")).add("endDate",gs.gp(entry,"endDate")).add("frequency","Daily").add("time",gs.gp(entry,"time")).add("volume",gs.gp(entry,"volume")).add("dosage",gs.mc(gSobject,"toInt",[gs.gp(entry,"dosage")])).add("amount",gs.mc(gSobject,"toInt",[gs.gp(entry,"amount")])).add("qty",gs.mc(gSobject,"toInt",[gs.gp(entry,"qty")])).add("shape",gs.elvis(gs.bool(gs.gp(entry,"shape")) , gs.gp(entry,"shape") , "Rectangle")).add("color",gs.elvis(gs.bool(gs.gp(entry,"color")) , gs.gp(entry,"color") , "Soft Red")).add("days",gs.gp(entry,"days")).add("refill",!!gs.gp(entry,"refill")).add("reminder",!!gs.gp(entry,"reminder")).add("threshold",gs.mc(gSobject,"toInt",[gs.gp(entry,"threshold")])).add("applicationSite",gs.elvis(gs.bool(gs.gp(entry,"applicationSite")) , gs.gp(entry,"applicationSite") , "")).add("applicationInstructions",gs.elvis(gs.bool(gs.gp(entry,"applicationInstructions")) , gs.gp(entry,"applicationInstructions") , "")).add("prn",!!gs.gp(entry,"prn")).add("prnReason",gs.elvis(gs.bool(gs.gp(entry,"prnReason")) , gs.gp(entry,"prnReason") , "")).add("isTrackable",isTrackable).add("isConsumable",isConsumable).add("isTopical",isTopical); } gSobject['isValidCreateDateRange'] = function(startDate, endDate) { var start = gs.mc(this,"moment",[startDate], gSobject); var end = gs.mc(this,"moment",[endDate], gSobject); return ((!gs.bool(gs.mc(start,"isValid",[]))) || (!gs.bool(gs.mc(end,"isValid",[])))) || (!gs.bool(gs.mc(end,"isBefore",[start, "day"]))); } gSobject['stockAfterTaken'] = function(medication, nowRef) { if (nowRef === undefined) nowRef = null; var now = gs.elvis(gs.bool(nowRef) , nowRef , gs.mc(this,"moment",[], gSobject)); var type = gs.mc(gs.mc(gs.elvis(gs.bool(gs.gp(medication,"formType",true)) , gs.gp(medication,"formType",true) , ""),"toString",[]),"toLowerCase",[]); var isTrackable = gs.gSin(type, gs.list(["tablet" , "capsule" , "syrup"])); var qty = gs.mc(gSobject,"toInt",[gs.gp(medication,"qty",true)]); var dosage = gs.mc(gSobject,"toInt",[gs.gp(medication,"dosage",true)]); var takenToday = ((gs.equals(gs.gp(medication,"status",true), "Taken")) && (gs.bool(gs.gp(medication,"statusDate",true)))) && (gs.mc(gs.mc(this,"moment",[gs.gp(medication,"statusDate")], gSobject),"isSame",[now, "day"])); if (!gs.bool(isTrackable)) { return gs.map().add("isTrackable",false).add("alreadyTakenToday",takenToday).add("currentQty",qty).add("dosage",dosage).add("newQty",qty).add("shouldDeduct",false); }; var shouldDeduct = (!gs.bool(takenToday)) && (dosage > 0); var newQty = (gs.bool(shouldDeduct) ? Math.max(0, gs.minus(qty, dosage)) : qty); return gs.map().add("isTrackable",true).add("alreadyTakenToday",takenToday).add("currentQty",qty).add("dosage",dosage).add("newQty",newQty).add("shouldDeduct",shouldDeduct); } gSobject['effectiveStatus'] = function(med, todayRef) { if (todayRef === undefined) todayRef = null; var today = gs.elvis(gs.bool(todayRef) , todayRef , gs.mc(gs.mc(this,"moment",[], gSobject),"format",["YYYY-MM-DD"])); if (!gs.bool(gs.gp(med,"statusDate",true))) { return "Pending"; }; var statusDay = gs.mc(gs.mc(this,"moment",[gs.gp(med,"statusDate")], gSobject),"format",["YYYY-MM-DD"]); return (gs.equals(statusDay, today) ? gs.elvis(gs.bool(gs.gp(med,"status")) , gs.gp(med,"status") , "Pending") : "Pending"); } gSobject['dailyStatus'] = function(med, dayMoment, nowRef) { if (dayMoment === undefined) dayMoment = null; if (nowRef === undefined) nowRef = null; var day = gs.elvis(gs.bool(dayMoment) , dayMoment , gs.mc(this,"moment",[], gSobject)); var now = gs.elvis(gs.bool(nowRef) , nowRef , gs.mc(this,"moment",[], gSobject)); if (!gs.bool(gs.mc(gSobject,"isScheduledForDay",[med, day]))) { return "NotScheduled"; }; var dayKey = gs.mc(day,"format",["YYYY-MM-DD"]); var status = gs.mc(gSobject,"effectiveStatus",[med, dayKey]); if (gs.mc(gs.list(["Taken" , "Skipped"]),"contains",[status])) { return status; }; var normalizedTime = gs.mc(gSobject,"toHourMinute",[gs.gp(med,"time",true)]); if (!gs.bool(normalizedTime)) { return "Pending"; }; var medTime = gs.mc(this,"moment",[gs.plus((gs.plus(dayKey, " ")), normalizedTime), "YYYY-MM-DD HH:mm"], gSobject); if ((gs.mc(day,"isSame",[now, "day"])) && (gs.mc(medTime,"isAfter",[now]))) { return "Upcoming"; }; return "Pending"; } gSobject['isScheduledForDay'] = function(med, dayMoment) { if (dayMoment === undefined) dayMoment = null; var today = gs.elvis(gs.bool(dayMoment) , dayMoment , gs.mc(this,"moment",[], gSobject)); var todayDay = gs.mc(today,"format",["dddd"]); var startDate = (gs.bool(gs.gp(med,"startDate",true)) ? gs.mc(this,"moment",[gs.gp(med,"startDate")], gSobject) : null); var endDate = (gs.bool(gs.gp(med,"endDate",true)) ? gs.mc(this,"moment",[gs.gp(med,"endDate")], gSobject) : null); var medDays = gs.elvis(gs.bool(gs.gp(med,"days",true)) , gs.gp(med,"days",true) , gs.list([])); return (((!gs.bool(startDate)) || (gs.mc(today,"isSameOrAfter",[startDate, "day"]))) && ((!gs.bool(endDate)) || (gs.mc(today,"isSameOrBefore",[endDate, "day"])))) && (gs.mc(medDays.collect(function(it) { return gs.mc(it, 'toLowerCase', []);}),"contains",[gs.mc(todayDay,"toLowerCase",[])])); } gSobject['summarizeToday'] = function(meds, nowRef) { if (nowRef === undefined) nowRef = null; var now = gs.elvis(gs.bool(nowRef) , nowRef , gs.mc(this,"moment",[], gSobject)); var today = gs.mc(this,"moment",[now], gSobject); var todayMeds = gs.mc(gs.elvis(gs.bool(meds) , meds , gs.list([])),"findAll",[function(med) { return gs.mc(gSobject,"isScheduledForDay",[med, today]); }]); var sorted = gs.mc(todayMeds,"sort",[function(a, b) { var aTime = gs.elvis(gs.mc(gSobject,"toHourMinute",[gs.gp(a,"time",true)]) , gs.mc(gSobject,"toHourMinute",[gs.gp(a,"time",true)]) , "99:99"); var bTime = gs.elvis(gs.mc(gSobject,"toHourMinute",[gs.gp(b,"time",true)]) , gs.mc(gSobject,"toHourMinute",[gs.gp(b,"time",true)]) , "99:99"); return gs.spaceShip(aTime, bTime); }]); var taken = gs.mc(sorted,"count",[function(med) { return gs.equals(gs.mc(gSobject,"dailyStatus",[med, today, now]), "Taken"); }]); var skipped = gs.mc(sorted,"count",[function(med) { return gs.equals(gs.mc(gSobject,"dailyStatus",[med, today, now]), "Skipped"); }]); var upcoming = gs.mc(sorted,"count",[function(med) { return gs.equals(gs.mc(gSobject,"dailyStatus",[med, today, now]), "Upcoming"); }]); return gs.map().add("medications",sorted).add("todayMedsCount",gs.mc(sorted,"size",[])).add("medsTaken",taken).add("medsSkipped",skipped).add("upcomingMeds",upcoming); } gSobject['refillDueMeds'] = function(medications) { return gs.mc(gs.elvis(gs.bool(medications) , medications , gs.list([])),"findAll",[function(med) { return (gs.bool(gs.gp(med,"refill",true))) && (gs.elvis(gs.bool(gs.gp(med,"qty")) , gs.gp(med,"qty") , 0) <= gs.elvis(gs.bool(gs.gp(med,"threshold")) , gs.gp(med,"threshold") , 0)); }]); } gSobject['estimatedRunOutDate'] = function(med, fromMoment) { if (fromMoment === undefined) fromMoment = null; if (!gs.bool(med)) { return null; }; var now = gs.elvis(gs.bool(fromMoment) , fromMoment , gs.mc(this,"moment",[], gSobject)); var qty = gs.mc(gSobject,"toInt",[gs.gp(med,"qty",true)]); var dosage = gs.mc(gSobject,"toInt",[gs.gp(med,"dosage",true)]); if (qty <= 0) { return gs.mc(gs.mc(this,"moment",[now], gSobject),"startOf",["day"]); }; if (dosage <= 0) { return null; }; var validDays = gs.list(["monday" , "tuesday" , "wednesday" , "thursday" , "friday" , "saturday" , "sunday"]); var daysPerWeek = gs.mc(gs.mc(gs.mc(gs.mc(gs.elvis(gs.bool(gs.gp(med,"days",true)) , gs.gp(med,"days",true) , gs.list([])),"collect",[function(it) { return gs.mc(gs.mc(it,"toString",[], null, true),"toLowerCase",[], null, true); }]),"findAll",[function(it) { return gs.mc(validDays,"contains",[it]); }]),"unique",[]),"size",[]); if (daysPerWeek <= 0) { daysPerWeek = 7; }; var dailyUse = gs.multiply(dosage, (gs.div(daysPerWeek, 7.0))); if (dailyUse <= 0) { return null; }; var daysLeft = Math.ceil(gs.div(qty, dailyUse)); var runOut = gs.mc(gs.mc(gs.mc(this,"moment",[now], gSobject),"add",[Math.max(0, gs.minus(daysLeft, 1)), "day"]),"startOf",["day"]); var endDate = (gs.bool(gs.gp(med,"endDate",true)) ? gs.mc(this,"moment",[gs.gp(med,"endDate")], gSobject) : null); if ((gs.mc(endDate,"isValid",[], null, true)) && (gs.mc(runOut,"isAfter",[endDate, "day"]))) { return gs.mc(endDate,"startOf",["day"]); }; return runOut; } gSobject['estimatedRunOutDateText'] = function(med, fromMoment) { if (fromMoment === undefined) fromMoment = null; var date = gs.mc(gSobject,"estimatedRunOutDate",[med, fromMoment]); return (gs.bool(date) ? gs.mc(date,"format",["YYYY-MM-DD"]) : null); } gSobject['historyMeds'] = function(medications) { return gs.mc(gs.mc(gs.elvis(gs.bool(medications) , medications , gs.list([])),"findAll",[function(med) { return (gs.bool(gs.gp(med,"statusDate",true))) || (gs.bool(gs.gp(med,"status",true))); }]),"sort",[function(a, b) { var aTime = (gs.bool(gs.gp(a,"statusDate",true)) ? gs.mc(gs.mc(this,"moment",[gs.gp(a,"statusDate")], gSobject),"valueOf",[]) : 0); var bTime = (gs.bool(gs.gp(b,"statusDate",true)) ? gs.mc(gs.mc(this,"moment",[gs.gp(b,"statusDate")], gSobject),"valueOf",[]) : 0); return gs.spaceShip(bTime, aTime); }]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function VueMediaUploadComponent() { var gSobject = VueComponent(); gSobject.clazz = { name: 'VueMediaUploadComponent', simpleName: 'VueMediaUploadComponent'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.props = gs.list(["oObject" , "oName" , "oPropName" , "label" , "width" , "height" , "mimeType" , "upload" , "controls" , "autoplay" , "playOnHover" , "muted" , "fit" , "controlsList" , "previewOnly" , "loop" , "customControls" , "trapezoid" , "fill" , "radius" , "downloadFile" , "zoom" , "uploadCallback" , "showFileName" , "staticHeight"]); gSobject.data = function(it) { return gs.map().add("mediaUrl","").add("myStyle","").add("acceptFiles","").add("contentType","").add("showPlayer",false).add("isCordova",false).add("playing",false).add("muted",false).add("fullscreen",false).add("showImageDialog",false); }; gSobject['mounted'] = function(it) { var self = this; if (!gs.bool(gs.gp(self,"playOnHover"))) { gs.sp(self,"playOnHover",false); }; if (!gs.bool(gs.gp(self,"upload"))) { gs.sp(self,"upload",false); }; if (!gs.bool(gs.gp(self,"controls"))) { gs.sp(self,"controls",false); }; if (!gs.bool(gs.gp(self,"muted"))) { gs.sp(self,"muted",false); }; if (!gs.bool(gs.gp(self,"autoplay"))) { gs.sp(self,"autoplay",false); }; if (gs.bool(gs.gp(self,"previewOnly"))) { gs.sp(self,"previewOnly",true); } else { gs.sp(self,"previewOnly",false); }; if (!gs.bool(gs.gp(self,"loop"))) { gs.sp(self,"loop",false); }; if (!gs.bool(gs.gp(self,"trapezoid"))) { gs.sp(self,"trapezoid",false); }; if (!gs.bool(gs.gp(self,"fit"))) { gs.sp(self,"fit","cover"); }; if (!gs.bool(gs.gp(self,"fill"))) { gs.sp(self,"fill","fill"); }; if (!gs.bool(gs.gp(self,"downloadFile"))) { gs.sp(self,"downloadFile",false); }; if (!gs.bool(gs.gp(self,"zoom"))) { gs.sp(self,"zoom",false); }; if (!gs.bool(gs.gp(self,"showFileName"))) { gs.sp(self,"showFileName",false); }; if (!gs.bool(gs.gp(self,"controlsList"))) { gs.sp(self,"controlsList","nofullscreen nodownload"); }; if (!gs.bool(gs.gp(self,"customControls"))) { gs.sp(self,"customControls",false); }; gs.sp(self,"isCordova",gs.execStatic(Utils,'isCordova', this,[])); if (((!gs.bool(gs.gp(self,"previewOnly"))) && (!gs.bool(gs.gp(self,"playOnHover")))) && (gs.mc(gSobject,"isType",["media", self]))) { gs.sp(self,"showPlayer",true); }; gs.sp(self,"showImageDialog",false); gs.mc(gSobject,"setupUrls",[self]); return gs.mc(gSobject,"setupZoomView",[self]); } gSobject['watchOObject'] = function(val, oldVal) { var self = this; gs.mc(gSobject,"setupUrls",[self]); return gs.mc(gSobject,"setupZoomView",[self]); } gSobject['created'] = function(it) { } gSobject['mouseover'] = function(it) { return gs.mc(gSobject,"videoControl",[this, true]); } gSobject['mouseout'] = function(it) { return gs.mc(gSobject,"videoControl",[this, false]); } gSobject['videoControl'] = function(self, playNow) { if (gs.bool(gs.gp(self,"playOnHover"))) { gs.sp(self,"showPlayer",playNow); if (gs.bool(playNow)) { return gs.mc(gSobject,"nextTick",[function(it) { return gs.mc(gs.gp(gs.gp(self,"$refs"),"video"),"play",[]); }]); }; }; } gSobject['play'] = function(it) { var self = this; gs.mc(gs.gp(gs.gp(self,"$refs"),"video"),"play",[]); gs.sp(self,"playing",true); return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.gp(gs.fs('session', this, gSobject),"legionUser"),"_id",true), "fitworld.video.play", gs.gp(gs.gp(self,"oObject"),"_id")]),"do",[]); } gSobject['pause'] = function(it) { var self = this; gs.mc(gs.gp(gs.gp(self,"$refs"),"video"),"pause",[]); return gs.sp(self,"playing",false); } gSobject['show'] = function(it) { var self = this; if (!gs.bool(gs.gp(self,"zoom"))) { return null; }; gs.sp(self,"showImageDialog",true); gs.mc(gSobject,"nextTick",[function(it) { }]); if (gs.execStatic(Utils,'isCordova', this,[])) { return gs.mc(gs.gp(gs.fs('screen', this, gSobject),"orientation"),"lock",["any"]); }; } gSobject['hideImageDialog'] = function(it) { gs.sp(gSobject.self,"showImageDialog",false); if (gs.execStatic(Utils,'isCordova', this,[])) { return gs.mc(gs.gp(gs.fs('screen', this, gSobject),"orientation"),"lock",["portrait"]); }; } gSobject['changeFullscreen'] = function(it) { gs.println("fullscreen"); var self = this; gs.sp(self,"fullscreen",true); var video = gs.gp(gs.gp(self,"$refs"),"video"); var onfullscreenchange = function(it) { gs.println("onfullscreenchange"); gs.sp(self,"fullscreen",!gs.gp(self,"fullscreen")); return gs.println(gs.gp(self,"fullscreen")); }; gs.sp(video,"onfullscreenchange",onfullscreenchange); gs.sp(video,"mozfullscreenchange",onfullscreenchange); gs.sp(video,"webkitfullscreenchange",onfullscreenchange); gs.sp(video,"msfullscreenchange",onfullscreenchange); if (gs.bool(gs.gp(video,"requestFullScreen"))) { return gs.mc(video,"requestFullScreen",[]); }; if (gs.bool(gs.gp(video,"webkitEnterFullScreen"))) { return gs.mc(video,"webkitEnterFullScreen",[]); }; if (gs.bool(gs.gp(video,"webkitRequestFullScreen"))) { return gs.mc(video,"webkitRequestFullScreen",[]); }; if (gs.bool(gs.gp(video,"mozRequestFullScreen"))) { return gs.mc(video,"mozRequestFullScreen",[]); }; if (gs.bool(gs.gp(video,"msRequestFullscreen"))) { return gs.mc(video,"msRequestFullscreen",[]); }; } gSobject['mute'] = function(it) { var self = this; gs.sp(gs.gp(gs.gp(self,"$refs"),"video"),"muted",true); return gs.sp(self,"muted",true); } gSobject['unmute'] = function(it) { var self = this; gs.sp(gs.gp(gs.gp(self,"$refs"),"video"),"muted",false); return gs.sp(self,"muted",false); } gSobject['download'] = function(it) { var self = this; return gs.mc(gs.fs('window', this, gSobject),"open",[gs.gp(self,"downloadUrl"), "_system", "closebuttoncaption=DONE&location=no"]); } gSobject['isProcessing'] = function(it) { return (gs.bool(gs.gp(gSobject.self,"oObject"))) && (gs.equals(gs.gp(gs.gp(gSobject.self,"oObject")[gs.gp(gSobject.self,"oPropName")],"processing",true), true)); } gSobject['setupUrls'] = function(self) { gs.sp(self,"placeHolderUrl","/statics/vue-wrapper/img/placeHolder.png?" + ((gs.bool(gs.gp(self,"width")) ? gs.plus("&width=", gs.gp(self,"width")) : "")) + "" + ((gs.bool(gs.gp(self,"height")) ? gs.plus("&height=", gs.gp(self,"height")) : "")) + ";" + ((gs.bool(gs.gp(self,"staticHeight")) ? gs.plus("height:", gs.gp(self,"staticHeight")) : "")) + ";"); gs.sp(self,"myStyle","" + ((gs.bool(gs.gp(self,"width")) ? gs.plus((gs.plus("min-width:", gs.gp(self,"width"))), "px") : "")) + ";" + ((gs.bool(gs.gp(self,"height")) ? gs.plus((gs.plus("min-height:", gs.gp(self,"height"))), "px") : "")) + ";" + ((gs.bool(gs.gp(self,"radius")) ? gs.plus((gs.plus("border-radius:", gs.gp(self,"radius"))), "px") : "")) + ";" + ((gs.bool(gs.gp(self,"staticHeight")) ? gs.plus("height:", gs.gp(self,"staticHeight")) : "")) + ";"); gs.sp(self,"acceptFiles",gs.elvis(gs.bool(gs.gp(self,"mimeType")) , gs.gp(self,"mimeType") , "image/*")); if ((!gs.bool(gs.gp(self,"oObject"))) || (!gs.bool(gs.gp(self,"oObject")[gs.gp(self,"oPropName")]))) { gs.println("NO OBJECT"); gs.sp(self,"previewUrl",gs.gp(self,"placeHolder")); gs.sp(self,"downloadUrl",gs.gp(self,"placeHolderUrl")); gs.println(gs.gp(self,"previewUrl")); gs.println(gs.gp(self,"downloadUrl")); return null; }; if (gs.mc(gSobject,"isProcessing",[])) { gs.println("isProcessing"); gs.sp(self,"placeHolderUrl","/statics/vue-wrapper/img/spinner.gif"); gs.sp(self,"previewUrl",gs.gp(self,"placeHolder")); gs.sp(self,"downloadUrl",gs.gp(self,"placeHolderUrl")); gs.println(gs.gp(self,"previewUrl")); gs.println(gs.gp(self,"downloadUrl")); return null; }; gs.println("ALL GOOD"); var fileInfo = gs.gp(self,"oObject")[gs.gp(self,"oPropName")]; gs.sp(self,"contentType",gs.gp(fileInfo,"contentType")); var objectId = gs.gp(gs.gp(self,"oObject"),"_id"); var lastUpdated = gs.gp(gs.gp(self,"oObject"),"_lastUpdated"); try { lastUpdated = gs.mc(lastUpdated,"getTime",[]); } catch (all) { } ; gs.sp(self,"previewUrl","/media-cache/filePreview/" + (objectId) + "/" + (gs.gp(self,"oPropName")) + "/" + (lastUpdated) + "/" + (gs.gp(fileInfo,"filename")) + "?" + ((gs.bool(gs.gp(self,"width")) ? gs.plus("&width=", gs.gp(self,"width")) : "")) + "" + ((gs.bool(gs.gp(self,"height")) ? gs.plus("&height=", gs.gp(self,"height")) : "")) + ""); gs.sp(self,"downloadUrl","/media-cache/file/" + (objectId) + "/" + (gs.gp(self,"oPropName")) + "/" + (lastUpdated) + "/" + (gs.gp(fileInfo,"filename")) + ""); gs.println(gs.gp(self,"previewUrl")); return gs.println(gs.gp(self,"downloadUrl")); } gSobject['setupZoomView'] = function(self) { return gs.sp(self,"hammerRef",(gs.bool(gs.gp(self,"oObject")) ? gs.plus((gs.plus((gs.plus("hammerRef:", gs.gp(gs.gp(self,"oObject"),"_id"))), ":")), gs.gp(self,"oPropName")) : "")); } gSobject['isType'] = function(testType, self) { if (self === undefined) self = this; if (!gs.bool(gs.gp(self,"oObject"))) { if (gs.equals(testType, "empty")) { return true; }; return false; }; var fileInfo = gs.gp(self,"oObject")[gs.gp(self,"oPropName")]; if ((gs.equals(testType, "empty")) && (!gs.bool(fileInfo))) { return true; }; if (!gs.bool(fileInfo)) { return false; }; if (gs.equals(testType, "image")) { return gs.mc(gs.gp(fileInfo,"contentType"),"startsWith",["image"]); }; if (gs.equals(testType, "media")) { return (gs.mc(gs.gp(fileInfo,"contentType"),"startsWith",["video"])) || (gs.mc(gs.gp(fileInfo,"contentType"),"startsWith",["audio"])); }; if (gs.equals(testType, "application/pdf")) { return gs.mc(gs.gp(fileInfo,"contentType"),"startsWith",["application/pdf"]); }; return false; } gSobject['saveFile'] = function(newFile) { var self = this; var uploadFile = gs.gp(gs.gp(newFile,"target"),"files")[0]; return gs.execStatic(Utils,'post', this,[uploadFile, gs.fs('oPropName', this, gSobject), gs.fs('oName', this, gSobject), gs.gp(gs.fs('oObject', this, gSobject),"_id"), function(data) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"mediaCacheService"),"deleteCache",[gs.gp(gs.gp(self,"oObject"),"_id"), gs.gp(self,"oPropName")]),"do",[]); var fileInfo = gs.map().add("id","" + (gs.gp(gs.gp(self,"oObject"),"_id")) + "_" + (gs.gp(self,"oPropName")) + "").add("filename",gs.gp(uploadFile,"name")).add("contentType",gs.gp(uploadFile,"type")); gs.sp(gs.gp(self,"oObject"),"_lastUpdated",gs.date()); (gs.gp(self,"oObject")[gs.gp(self,"oPropName")]) = fileInfo; gs.mc(gSobject,"setupUrls",[self]); if (gs.bool(gs.gp(self,"uploadCallback"))) { return gs.mc(self,"uploadCallback",[]); }; }]); } gSobject['beforeUnmount'] = function(it) { var self = this; return gs.sp(self,"showPlayer",false); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function MetricGraphComponent() { var gSobject = VueComponent(); gSobject.clazz = { name: 'MetricGraphComponent', simpleName: 'MetricGraphComponent'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.props = gs.map().add("objectId",String).add("metricName",String).add("type",String); gSobject.data = function(it) { return gs.map().add("selectedPeriod","Day").add("timePeriod",gs.list([])); }; gSobject['created'] = function(it) { var self = this; gs.sp(self,"timePeriod",gs.list([gs.map().add("label","Hour").add("value","Hour") , gs.map().add("label","Day").add("value","Day") , gs.map().add("label","Month").add("value","Month")])); return gs.mc(gSobject,"loadGraph",[true, self]); } gSobject['watchObjectId'] = function(it) { return gs.mc(gSobject,"loadGraph",[true, this]); } gSobject['loadGraph'] = function(newGraph, self) { if (newGraph === undefined) newGraph = false; if (self === undefined) self = this; return gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"loadSelectedPeriodSeries",[gs.gp(self,"metricName"), gs.date(), gs.gp(self,"selectedPeriod"), gs.gp(self,"objectId"), function(data) { var rangeValues = gs.gp(data,"values"); if (gs.equals(gs.gp(self,"type"), "aggregated")) { rangeValues = gs.gp(data,"aggValues"); } else { if (gs.equals(gs.gp(self,"type"), "average")) { rangeValues = gs.gp(data,"avgValues"); }; }; if (gs.bool(newGraph)) { return gs.execStatic(MetricGraphComponent,'paintGraph', this,["graph", gs.gp(data,"labels"), rangeValues]); } else { return gs.execStatic(MetricGraphComponent,'updateData', this,["graph", gs.gp(data,"labels"), rangeValues]); }; }]); } gSobject.updateData = function(x0,x1,x2) { return MetricGraphComponent.updateData(x0,x1,x2); } gSobject.paintGraph = function(x0,x1,x2,x3) { return MetricGraphComponent.paintGraph(x0,x1,x2,x3); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; MetricGraphComponent.updateData = function(graphId, graphLabels, dataSet) { let chart = Chart.getChart(graphId); chart.data.datasets[0].data = gs.toJavascript(dataSet) chart.data.labels = gs.toJavascript(graphLabels) chart.update() } MetricGraphComponent.paintGraph = function(graphId, graphLabels, dataSet, type) { if (type === undefined) type = "line"; const oldChart = Chart.getChart(graphId) if (oldChart != undefined) oldChart.destroy() const data = { labels: gs.toJavascript(graphLabels), datasets: [{ data: gs.toJavascript(dataSet), borderColor: Quasar.getCssVar('primary'), tension: 0.1, }] } const options = { scales: { y: { beginAtZero:true, min:0 } }, plugins: { legend: { display: false } } } const config = { type: type, data: data, options: options, }; console.log('data', data) const myChart = new Chart( document.getElementById(graphId),config); } function PinComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'PinComponent', simpleName: 'PinComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/pinAuth"; gSobject['created'] = function(it) { gs.println("PinComponent.created()"); gs.sp(gSobject.scope,"pin",""); gs.sp(gSobject.scope,"email",gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"username")); gs.sp(gSobject.scope,"pinSize",6); gs.sp(gSobject.scope,"pinValues",gs.list([])); gs.sp(gSobject.scope,"processing",false); gs.sp(gSobject.scope,"resending",false); gs.sp(gSobject.scope,"resendDisabled",false); gs.sp(gSobject.scope,"resendCountdown",0); gs.sp(gSobject.scope,"showResend",false); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "user.pin.auth"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[false]); return gs.mc(gSobject,"componentTheme",[false]); } gSobject['resendPin'] = function(it) { gs.sp(gSobject.scope,"resending",true); gs.sp(gSobject.scope,"resendDisabled",true); gs.sp(gSobject.scope,"resendCountdown",30); return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"legionAuthService"),"generatePinForExistingUser",[gs.gp(gSobject.scope,"email"), (gs.mc(gs.gp(gSobject.scope,"email"),"contains",["@"], null, true) ? false : true)]),"then",[function(it) { gs.mc(gSobject,"notify",["A new OTP has been sent", "positive"]); gs.sp(gSobject.scope,"resending",false); return gs.mc(gSobject,"startCountdown",[]); }, function(error) { gs.mc(gSobject,"notify",["Failed to resend OTP", "negative"]); gs.sp(gSobject.scope,"resending",false); return gs.sp(gSobject.scope,"resendDisabled",false); }]); } gSobject['startCountdown'] = function(it) { if (gs.gp(gSobject.scope,"resendCountdown") > 0) { return gs.mc(gs.fs('window', this, gSobject),"setTimeout",[function(it) { gs.sp(gSobject.scope,"resendCountdown",(gs.minus(gs.gp(gSobject.scope,"resendCountdown"), 1))); if (gs.gp(gSobject.scope,"resendCountdown") <= 0) { return gs.sp(gSobject.scope,"resendDisabled",false); } else { return gs.mc(gSobject,"startCountdown",[]); }; }, 1000]); }; } gSobject['pinAuth'] = function(it) { gs.sp(gSobject.scope,"pin",""); gs.mc(gs.gp(gSobject.scope,"pinValues"),"each",[function(value) { return gs.sp(gSobject.scope,"pin",gs.gp(gSobject.scope,"pin") + "" + (value) + ""); }]); return gs.mc(gSobject,"pinAuthWithPin",[gs.gp(gSobject.scope,"pin"), gs.gp(gSobject.scope,"email")]); } gSobject['pinAuthWithPin'] = function(pin, email) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["pinAuthWithPin:1"]); gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["pinAuthWithPin:1.2:" + (pin) + ""]); gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["pinAuthWithPin:1.3:" + (email) + ""]); if (!gs.bool(pin)) { gs.mc(gSobject,"notify",["Please enter pin", "negative"]); return null; }; gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["pinAuthWithPin:2"]); if (!gs.bool(gs.exactMatch(pin,/^[0-9]{6}$/))) { gs.mc(gSobject,"notify",["Invalid pin, pin must be a 6 digit number", "negative"]); return null; }; gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["pinAuthWithPin:3"]); if (!gs.bool(email)) { gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/signIn"]); }; gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["pinAuthWithPin:4"]); gs.sp(gSobject.scope,"processing",true); gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["pinAuthWithPin:" + (email) + ":" + (pin) + ""]); return gs.mc(gs.fs('legionUserService', this, gSobject),"authWithPin",[email, pin, function(authenticated) { if (!gs.bool(authenticated)) { gs.mc(gSobject,"notify",["Wrong PIN", "negative"]); gs.sp(gSobject.scope,"showResend",true); gs.sp(gSobject.scope,"processing",false); return null; }; gs.sp(gs.fs('session', this, gSobject),"user",gs.gp(gs.fs('session', this, gSobject),"legionUser")); gs.sp(gs.fs('session', this, gSobject),"userId",gs.gp(gs.fs('session', this, gSobject),"legionUserId")); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "user.authenticated"]),"do",[]); gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["USER EMAIL:" + (email) + ""]); gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"createUserFromPortalViaEmail",[email, function(user) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["Portal user synced: " + (user) + ""]); }]); gs.sp(gSobject.scope,"processing",false); return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/"]); }, function(error) { gs.mc(gSobject,"notify",[gs.gp(error,"message"), "negative"]); return gs.sp(gSobject.scope,"processing",false); }]); } gSobject['deeplinkCallback'] = function(eventData) { var jsonString = gs.mc(Utils,"fromBase64",[gs.gp(gs.gp(eventData,"params"),"base64")]); gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["jsonString:" + (jsonString) + ""]); var json = gs.execStatic(Utils,'stringToJson', this,[jsonString]); gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["json:" + (json) + ""]); gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["json:1:" + (gs.gp(json,"pin")) + ""]); gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["json:2:" + (gs.gp(json,"email")) + ""]); return gs.mc(gSobject,"nextTick",[function(it) { return gs.mc(gSobject,"pinAuthWithPin",[gs.gp(json,"pin"), gs.gp(json,"email")]); }]); } gSobject['anonymiseEmail'] = function(email) { if (!gs.bool(email)) { return "your email"; }; var mailParts = gs.mc(email,"split",["@"]); var local = mailParts[0]; var domain = mailParts[1]; var visibleLength = 3; if (gs.mc(local,"length",[]) <= 4) { visibleLength = 1; }; var secret = gs.mc("*","repeat",[Math.max(gs.minus(gs.mc(local,"length",[]), visibleLength), 4)]); return "" + (gs.rangeFromList(local, 0, visibleLength)) + "" + (secret) + "@" + (domain) + ""; } gSobject['PinComponent0'] = function(it) { gs.mc(cordovaDeepLink,"registerCallback",[gs.gp(gs.thisOrObject(this,gSobject),"deeplinkCallback")]); return this; } if (arguments.length==0) {gSobject.PinComponent0(); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function StepsOverviewComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'StepsOverviewComponent', simpleName: 'StepsOverviewComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/stepsOverview" , "/stepsOverview/:id"]); gSobject['created'] = function(it) { gs.println("StepsOverviewComponent.created()"); gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"stepsGoal",gs.map()); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.steps.overview"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"batchName","medical:score:steps"); gs.sp(gSobject.scope,"graphPeriod","Day"); gs.sp(gSobject.scope,"totalSteps",0); gs.sp(gSobject.scope,"stepsMessage",gs.map().add("title","").add("description","")); gs.sp(gSobject.scope,"tracker",null); gs.mc(gSobject,"loadLogs",[]); gs.mc(gSobject,"remainingSteps",[]); gs.sp(gSobject.scope,"remainingStepsLabel",""); gs.sp(gSobject.scope,"sevenDayAvg",0); gs.mc(gSobject,"loadTrackerData",["Steps", function(tracker) { return gs.sp(gSobject.scope,"tracker",tracker); }]); gs.mc(gSobject,"loadMotivationMessage",[]); gs.sp(gSobject.scope,"lastUpdated",""); return gs.mc(gSobject,"loadLastUpdated",[gs.gp(gs.fs('session', this, gSobject),"userId"), "steps", function(lastUpdated) { return gs.sp(gSobject.scope,"lastUpdated",lastUpdated); }]); } gSobject['loadMotivationMessage'] = function(it) { gs.sp(gSobject.scope,"motivationalText",""); gs.sp(gSobject.scope,"motivationLoading",true); return gs.mc(gSobject,"loadMotivation",[gs.gp(gs.fs('session', this, gSobject),"userId"), "Steps", function(msg) { gs.sp(gSobject.scope,"motivationalText",msg); return gs.sp(gSobject.scope,"motivationLoading",false); }]); } gSobject['loadLogs'] = function(it) { gs.sp(gSobject.scope,"logs",gs.list([])); gs.sp(gSobject.scope,"lastEntryDate","None"); gs.sp(gSobject.scope,"lastEntry",gs.map()); gs.sp(gSobject.scope,"stepsMin",999); gs.sp(gSobject.scope,"stepsMax",0); gs.sp(gSobject.scope,"stepsGoal",gs.map().add("steps","SETUP").add("unit","steps").add("description","").add("progressText","Set your daily steps goal")); gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:steps_goal", function(stepsGoal) { gs.println("stepsGoal"); gs.println(stepsGoal); if (gs.bool(stepsGoal)) { gs.mc(gs.gp(gSobject.scope,"stepsGoal"),"putAll",[stepsGoal]); gs.sp(gs.gp(gSobject.scope,"stepsGoal"),"unit","steps"); gs.sp(gs.gp(gSobject.scope,"stepsGoal"),"description","target steps"); gs.sp(gs.gp(gSobject.scope,"stepsGoal"),"progressText","You’re on track! Keep working hard to improve your health & overall score."); return gs.mc(gSobject,"remainingSteps",[]); }; }]); gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"listEntries",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gSobject.scope,"batchName"), gs.map().add("limit",7), function(logs) { gs.mc(logs,"each",[function(log) { gs.mc(gs.gp(gSobject.scope,"logs"),"add",[gs.map().add("_id",gs.gp(log,"_id")).add("value",gs.gp(log,"value")).add("subtext",gs.gp(log,"status")).add("unit","steps").add("_createdAt",gs.gp(log,"date"))]); gs.println("Entry logs"); gs.println(gs.gp(gSobject.scope,"logs")); gs.sp(gSobject.scope,"lastEntryDate",gs.mc(gs.mc(gSobject,"moment",[gs.gp(log,"date")]),"calendar",[])); gs.sp(gSobject.scope,"lastEntry",gs.elvis(gs.bool(gs.gp(gSobject.scope,"lastEntry")) , gs.gp(gSobject.scope,"lastEntry") , log)); var val = gs.gp(log,"value"); if ((gs.instanceOf(val, "String")) && (val != "undefined")) { var entry = parseInt(val); gs.sp(gSobject.scope,"totalSteps",gs.gp(gSobject.scope,"totalSteps") + entry); } else { if (gs.instanceOf(val, "Number")) { gs.sp(gSobject.scope,"totalSteps",gs.gp(gSobject.scope,"totalSteps") + val); } else { gs.println("Skipping invalid value: " + (val) + ""); }; }; gs.sp(gSobject.scope,"sevenDayAvg",(gs.bool(gs.gp(gSobject.scope,"totalSteps")) ? Math.round(gs.div(gs.gp(gSobject.scope,"totalSteps"), 7)) : null)); return gs.mc(gSobject,"stepsStatus",[]); }]); return gs.mc(gSobject,"remainingSteps",[]); }]); gs.sp(gSobject.scope,"stepsLabels",null); gs.sp(gSobject.scope,"stepsValues",null); gs.sp(gSobject.scope,"stepsToday",null); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"metrics",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:steps-value", gs.date(), gs.gp(gSobject.scope,"graphPeriod"), function(logs) { gs.println("logs"); gs.println(logs); var todayIndex = gs.minus(gs.mc(gs.gp(logs,"values"),"size",[], null, true), 1); gs.sp(gSobject.scope,"stepsLabels",gs.gp(logs,"labels")); gs.sp(gSobject.scope,"stepsValues",gs.gp(logs,"aggSumValues")); return gs.sp(gSobject.scope,"stepsToday",(gs.gp(logs,"values")[todayIndex])); }]); } gSobject['stepsStatus'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"medicalCalculationService"),"stepsInfo",[gs.gp(gSobject.scope,"sevenDayAvg"), function(stepsMessage) { return gs.sp(gSobject.scope,"stepsMessage",stepsMessage); }]); } gSobject['remainingSteps'] = function(it) { var defaultGoal = 5000; var goalCandidate = gs.gp(gs.gp(gSobject.scope,"stepsGoal",true),"steps",true); var goal = null; if ((!gs.bool(goalCandidate)) || (gs.equals(goalCandidate, "SETUP"))) { goal = defaultGoal; } else { if (gs.instanceOf(goalCandidate, "Number")) { goal = goalCandidate; } else { var s = gs.mc(gs.mc(goalCandidate,"toString",[]),"trim",[]); var parsed = parseInt(s); goal = (parsed > 0 ? parsed : defaultGoal); }; }; if (!gs.bool(goal)) { goal = defaultGoal; }; var today = gs.mc(gs.mc(gSobject,"moment",[]),"format",["YYYY-MM-DD"]); var todayLogs = gs.mc(gs.gp(gSobject.scope,"logs"),"findAll",[function(log) { return gs.equals(gs.mc(gs.mc(gSobject,"moment",[gs.gp(log,"_createdAt")]),"format",["YYYY-MM-DD"]), today); }]); if ((!gs.bool(todayLogs)) || (gs.mc(todayLogs,"isEmpty",[]))) { gs.sp(gSobject.scope,"stepsRemaining",goal); gs.sp(gSobject.scope,"remainingStepsLabel",goal); return goal; }; var totalToday = 0; gs.mc(todayLogs,"each",[function(log) { var val = gs.gp(log,"value"); if (gs.instanceOf(val, "Number")) { return totalToday += val; } else { if (gs.instanceOf(val, "String")) { var vs = gs.mc(val,"trim",[]); if (gs.mc(vs,"isInteger",[])) { return totalToday += gs.mc(vs,"toInteger",[]); }; }; }; }]); var remaining = Math.max(0, gs.minus(goal, totalToday)); gs.sp(gSobject.scope,"stepsRemaining",remaining); gs.sp(gSobject.scope,"remainingStepsLabel",remaining); return remaining; } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function StepsInsightComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'StepsInsightComponent', simpleName: 'StepsInsightComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/stepsInsight"; gSobject['created'] = function(it) { gs.println("StepsInsightComponent.created()"); gs.sp(gSobject.scope,"logs",gs.list([])); gs.sp(gSobject.scope,"batchName","medical:score:steps"); gs.sp(gSobject.scope,"weeklyAvgDisplay",null); gs.sp(gSobject.scope,"tracker",null); gs.sp(gSobject.scope,"trackerInsights",""); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.steps.insight"]),"do",[]); gs.mc(gSobject,"loadTrackerData",["Steps", function(tracker) { return gs.sp(gSobject.scope,"tracker",tracker); }]); gs.mc(gSobject,"showHeaderFooter",[false]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"converter",gs.mc(gSobject,"makeConverter",[])); gs.mc(gSobject,"loadLogs",[]); return gs.mc(gSobject,"weeklyAvgSteps",[]); } gSobject['loadLogs'] = function(it) { gs.sp(gSobject.scope,"stepsLabels",null); gs.sp(gSobject.scope,"stepsValues",null); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"metrics",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:steps-value", gs.date(), "Day", function(logs) { gs.println("Metric logs"); gs.println(logs); gs.sp(gSobject.scope,"stepsLabels",gs.mc(gs.mc(gs.mc(gs.gp(logs,"labels"),"reverse",[]),"take",[7]),"reverse",[])); return gs.sp(gSobject.scope,"stepsValues",gs.mc(gs.mc(gs.mc(gs.gp(logs,"aggAvgValues"),"reverse",[]),"take",[7]),"reverse",[])); }]); } gSobject['weeklyAvgSteps'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"metrics",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:steps-value", gs.date(), "Day", function(logs) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"calculateWeeklyAvg",[gs.gp(logs,"aggAvgValues"), function(steps) { var stepsWeeklyAvg = steps; gs.println(gs.multiply("=", 20)); gs.println("Steps Weekly Avg: " + (stepsWeeklyAvg) + ""); gs.sp(gSobject.scope,"weeklyAvgDisplay","" + (stepsWeeklyAvg) + ""); return gs.mc(gSobject,"trackerInsights",[gs.gp(logs,"aggAvgValues")]); }]); }]); } gSobject['trackerInsights'] = function(data) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"timelineService"),"generateStepsInsights",[data, function(response) { gs.println("generateTrackerInsights"); gs.println(data); gs.println(response); var html = gs.mc(gs.gp(gSobject.scope,"converter"),"makeHtml",[response]); return gs.sp(gSobject.scope,"trackerInsights",html); }]); } gSobject.makeConverter = function() { return new showdown.Converter({tables: true, simpleLineBreaks: true}) } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function StepsTrackComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'StepsTrackComponent', simpleName: 'StepsTrackComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/stepsTrack" , "/stepsTrack/:id"]); gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.steps.track"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[false]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"today",gs.mc(gs.mc(gSobject,"moment",[]),"format",["YYYY-MM-DD HH:mm"])); gs.sp(gSobject.scope,"allowedDates",function(d) { return gs.mc(gs.mc(gSobject,"moment",[d, "YYYY/MM/DD"]),"isSameOrBefore",[gs.mc(gSobject,"moment",[gs.gp(gSobject.scope,"today"), "YYYY/MM/DD"])]); }); gs.sp(gSobject.scope,"showDateTime",false); gs.sp(gSobject.scope,"date",gs.mc(gs.mc(gSobject,"moment",[]),"format",["YYYY-MM-DD HH:mm"])); gs.sp(gSobject.scope,"showTimeDialog",false); gs.sp(gSobject.scope,"hours",null); gs.sp(gSobject.scope,"minutes",null); gs.sp(gSobject.scope,"seconds",null); gs.sp(gSobject.scope,"dialog",false); gs.sp(gSobject.scope,"entry",gs.map().add("date",gs.mc(gs.mc(gSobject,"moment",[]),"format",["YYYY-MM-DD HH:mm"])).add("steps","").add("distance","").add("time","").add("ref","steps")); if (gs.bool(gs.gp(gs.gp(gSobject.route,"params"),"id"))) { gs.sp(gSobject.scope,"entry",null); gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"loadEntry",[gs.gp(gs.gp(gSobject.route,"params"),"id"), function(entry) { gs.sp(gSobject.scope,"entry",entry); return gs.sp(gs.gp(gSobject.scope,"entry"),"date",gs.mc(gs.mc(gSobject,"moment",[gs.gp(entry,"date")]),"format",["YYYY-MM-DD HH:mm"])); }]); }; return gs.sp(gSobject.scope,"dialog",false); } gSobject['logSteps'] = function(it) { var entry = gs.gp(gSobject.scope,"entry"); var hours = (gs.bool(gs.gp(gSobject.scope,"hours")) ? gs.mc(gs.mc(gs.gp(gSobject.scope,"hours"),"toString",[]),"toInteger",[]) : 0); var minutes = (gs.bool(gs.gp(gSobject.scope,"minutes")) ? gs.mc(gs.mc(gs.gp(gSobject.scope,"minutes"),"toString",[]),"toInteger",[]) : 0); var seconds = (gs.bool(gs.gp(gSobject.scope,"seconds")) ? gs.mc(gs.mc(gs.gp(gSobject.scope,"seconds"),"toString",[]),"toInteger",[]) : 0); var formattedHours = gs.mc(gSobject,"formatTwoDigits",[hours]); var formattedMinutes = gs.mc(gSobject,"formatTwoDigits",[minutes]); var formattedSeconds = gs.mc(gSobject,"formatTwoDigits",[seconds]); var value = "" + (gs.gp(entry,"steps")) + ""; var today = gs.mc(gs.mc(gSobject,"moment",[]),"format",["YYYY-MM-DD HH:mm"]); var date = gs.date(gs.gp(gs.gp(gSobject.scope,"entry"),"date")); var distance = gs.gp(entry,"distance"); var time = "" + (formattedHours) + ":" + (formattedMinutes) + ":" + (formattedSeconds) + ""; gs.println("Formatted time: " + (time) + ""); var status = "On track"; var currentSteps = (gs.bool(gs.gp(entry,"steps")) ? gs.mc(gs.mc(gs.gp(entry,"steps"),"toString",[]),"toInteger",[]) : 0); var todayStr = gs.mc(gs.mc(gSobject,"moment",[]),"format",["YYYY-MM-DD"]); var saveStepsDp = function(totalDailySteps) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:steps:value", totalDailySteps]),"do",[]); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:steps:distance", distance]),"do",[]); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:steps:time", gs.gp(entry,"time")]),"do",[]); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:steps:date", gs.date()]),"do",[]); return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:steps:status", status]),"do",[]); }; gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:steps:date", function(savedDate) { var savedDateStr = (gs.bool(savedDate) ? gs.mc(gs.mc(gSobject,"moment",[gs.date(savedDate)]),"format",["YYYY-MM-DD"]) : null); if (gs.equals(savedDateStr, todayStr)) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:steps:value", function(savedValue) { var previousSteps = gs.elvis(gs.bool(savedValue) , savedValue , 0); var total = gs.plus(previousSteps, currentSteps); return gs.execCall(saveStepsDp, this, [total]); }]); } else { var total = currentSteps; return gs.execCall(saveStepsDp, this, [total]); }; }]); if (gs.bool(gs.gp(gs.gp(gSobject.route,"params"),"id"))) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"deleteEntry",[gs.gp(gs.gp(gSobject.route,"params"),"id")]),"do",[]); }; gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"addEntryWithFts",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:steps", gs.list(["value"]), gs.map().add("value",value).add("date",date).add("distance",distance).add("time",time)]),"then",[function(it) { var stepsLogged = gs.elvis(gs.bool(gs.gp(gs.gp(gSobject.scope,"entry"),"steps")) , gs.gp(gs.gp(gSobject.scope,"entry"),"steps") , 0); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"eventListener",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gSobject.scope,"entry")]),"do",[]); gs.mc(gSobject,"saveLastUpdated",[gs.gp(gs.fs('session', this, gSobject),"userId"), "steps"]); return gs.sp(gSobject.scope,"dialog",true); }, function(it) { return gs.sp(gSobject.scope,"dialog",true); }]); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"notificationService"),"removeNotification",[gs.gp(gs.fs('session', this, gSobject),"userId"), "trackable:Steps", "Steps"]),"do",[]); gs.mc(gSobject,"generateAndSaveMotivation",[gs.gp(gs.fs('session', this, gSobject),"userId"), "Steps", "medical:score:steps-value", function(it) { return gs.mc(gs.fs('stepsOverviewComponent', this, gSobject),"loadMotivationMessage",[]); }]); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"medicalConditionCalculationService"),"calcAll",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(it) { return "Re-calculating health score"; }]); } gSobject['eventLogSteps'] = function(it) { return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"eventLogService"),"event",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.fs('narrative', this, gSobject), "steps", "info"]),"do",[]); } gSobject['updateGoalAfterLogging'] = function(newSteps) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:steps_goal", function(goal) { var goalSteps = gs.elvis(gs.bool(gs.gp(goal,"steps",true)) , gs.gp(goal,"steps",true) , 0); var updatedGoal = gs.minus(goalSteps, newSteps); gs.println("Updating goal: " + (goalSteps) + " - " + (newSteps) + " = " + (updatedGoal) + ""); gs.sp(goal,"steps",updatedGoal); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:steps_goal", goal]),"do",[]); return gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"stepsGoal",goal); }]); } gSobject['error'] = function(it) { return gs.mc(gSobject,"notify",["Form Error", "negative"]); } gSobject['formatTwoDigits'] = function(number) { return (number < 10 ? gs.plus("0", number) : gs.mc(this,"String",[number], gSobject)); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function StepsDetailComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'StepsDetailComponent', simpleName: 'StepsDetailComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/stepsDetail" , "/stepsDetail/:id"]); gSobject['created'] = function(it) { gs.println("StepsDetailComponent"); gs.sp(gSobject.scope,"stepGoal",gs.map()); gs.sp(gSobject.scope,"totalSteps",0); gs.sp(gSobject.scope,"stepsTitle",""); gs.sp(gSobject.scope,"stepsDescription",""); gs.mc(gSobject,"loadDetails",[]); gs.mc(gSobject,"remainingSteps",[]); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.steps.detail"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[false]); return gs.mc(gSobject,"componentTheme",[false]); } gSobject['loadDetails'] = function(it) { gs.println("[DEBUG] loadDetails() starting"); if (gs.bool(gs.gp(gs.gp(gSobject.route,"params"),"id"))) { gs.println("[DEBUG] Loading entry id: " + (gs.gp(gs.gp(gSobject.route,"params"),"id")) + ""); gs.sp(gSobject.scope,"entry",null); gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"loadEntry",[gs.gp(gs.gp(gSobject.route,"params"),"id"), function(entry) { gs.println("[DEBUG] loadEntry() response: " + (entry) + ""); if (entry != null) { gs.sp(gSobject.scope,"entry",entry); return gs.mc(gSobject,"stepsStatus",[gs.gp(gSobject.scope,"entry")]); }; }]); }; var logsLoaded = false; var goalLoaded = false; gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"listEntries",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:steps", gs.map().add("limit",1), function(logs) { gs.sp(gSobject.scope,"totalSteps",0); gs.mc(logs,"each",[function(log) { var raw = gs.gp(log,"value",true); if (((raw != null) && (raw != gs.fs('undefined', this, gSobject))) && (!gs.bool(gs.mc(this,"isNaN",[gs.mc(this,"parseFloat",[raw], gSobject)], gSobject)))) { return gs.sp(gSobject.scope,"totalSteps",gs.gp(gSobject.scope,"totalSteps") + gs.mc(this,"parseFloat",[raw], gSobject)); }; }]); logsLoaded = true; gs.println("[DEBUG] totalSteps: " + (gs.gp(gSobject.scope,"totalSteps")) + ""); if ((gs.bool(logsLoaded)) && (gs.bool(goalLoaded))) { return gs.mc(gSobject,"updateProgressText",[]); }; }]); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:steps_goal", function(stepGoal) { if (gs.bool(stepGoal)) { gs.mc(gs.gp(gSobject.scope,"stepGoal"),"putAll",[stepGoal]); gs.sp(gs.gp(gSobject.scope,"stepGoal"),"unit","steps"); gs.sp(gs.gp(gSobject.scope,"stepGoal"),"description","Target steps"); goalLoaded = true; gs.println("[DEBUG] stepGoal loaded: " + (gs.gp(gs.gp(gSobject.scope,"stepGoal"),"steps")) + ""); if ((gs.bool(logsLoaded)) && (gs.bool(goalLoaded))) { return gs.mc(gSobject,"updateProgressText",[]); }; }; }]); } gSobject['parseTimeString'] = function(timeStr) { if (!gs.bool(timeStr)) { return null; }; var parts = gs.mc(timeStr,"split",[":"]); if ((gs.mc(parts,"size",[]) != 3) || (gs.mc(parts,"any",[function(it) { return gs.equals(gs.mc(it,"trim",[]), ""); }]))) { return ""; }; var hours = gs.mc(parts[0],"toInteger",[]); var minutes = gs.mc(parts[1],"toInteger",[]); var seconds = gs.mc(parts[2],"toInteger",[]); var formattedString = gs.mc("" + ((gs.bool(hours) ? "" + (hours) + "h " : "")) + "" + ((gs.bool(minutes) ? "" + (minutes) + "m " : "")) + "" + ((gs.bool(seconds) ? "" + (seconds) + "s" : "")) + "","trim",[]); return formattedString; } gSobject['stepsRemaining'] = function(it) { var goalStr = gs.gp(gs.gp(gSobject.scope,"stepGoal"),"steps",true); if ((!gs.bool(goalStr)) || (gs.mc(this,"isNaN",[gs.mc(this,"parseFloat",[goalStr], gSobject)], gSobject))) { return 0; }; var originalGoal = gs.mc(this,"parseFloat",[goalStr], gSobject); var totalToday = 0; var today = gs.mc(gs.mc(gSobject,"moment",[]),"format",["YYYY-MM-DD"]); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"listEntries",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:steps", function(logs) { gs.mc(logs,"each",[function(log) { var createdAt = gs.elvis(gs.bool(gs.gp(log,"_dateCreated",true)) , gs.gp(log,"_dateCreated",true) , gs.gp(log,"date",true)); if (!gs.bool(createdAt)) { return null; }; var logDate = gs.mc(gs.mc(gSobject,"moment",[createdAt]),"format",["YYYY-MM-DD"]); var val = gs.gp(log,"value"); if (gs.equals(logDate, today)) { if (gs.instanceOf(val, "Number")) { return totalToday += val; } else { if (((gs.instanceOf(val, "String")) && (val != "undefined")) && (!gs.bool(gs.mc(this,"isNaN",[gs.mc(this,"parseFloat",[val], gSobject)], gSobject)))) { return totalToday += gs.mc(this,"parseFloat",[val], gSobject); }; }; }; }]); var remaining = gs.minus(originalGoal, totalToday); if (remaining < 0) { remaining = 0; }; gs.sp(gSobject.scope,"stepsRemaining",remaining); gs.sp(gs.gp(gSobject.scope,"stepGoal"),"progressText","" + (gs.gp(gSobject.scope,"stepsDescription")) + ". You still need " + (remaining) + " steps to reach your goal."); return gs.println("[StepsDetail] totalToday=" + (totalToday) + ", goal=" + (originalGoal) + ", remaining=" + (remaining) + ""); }]); } gSobject['stepsStatus'] = function(entry) { gs.println("entry"); gs.println(entry); if (gs.gp(entry,"value") < 1000) { gs.sp(gSobject.scope,"stepsTitle","Minimal Movement"); gs.sp(gSobject.scope,"stepsDescription","Typically bedbound or sedentary day"); } else { if ((gs.gp(entry,"value") >= 1000) && (gs.gp(entry,"value") <= 2999)) { gs.sp(gSobject.scope,"stepsTitle","Sedentary"); gs.sp(gSobject.scope,"stepsDescription","Very low daily movement"); } else { if ((gs.gp(entry,"value") >= 3000) && (gs.gp(entry,"value") <= 4999)) { gs.sp(gSobject.scope,"stepsTitle","Lightly Active"); gs.sp(gSobject.scope,"stepsDescription","Light movement, often without structured activity"); } else { if ((gs.gp(entry,"value") >= 5000) && (gs.gp(entry,"value") <= 7499)) { gs.sp(gSobject.scope,"stepsTitle","Fairly Active"); gs.sp(gSobject.scope,"stepsDescription","Base level for daily movement"); } else { if ((gs.gp(entry,"value") >= 7500) && (gs.gp(entry,"value") <= 12499)) { gs.sp(gSobject.scope,"stepsTitle","Moderately Active"); gs.sp(gSobject.scope,"stepsDescription","Supports general fitness and metabolic health"); } else { if (gs.gp(entry,"value") >= 12500) { gs.sp(gSobject.scope,"stepsTitle","Highly Active"); gs.sp(gSobject.scope,"stepsDescription","Exceeds standard activity recommendations"); }; }; }; }; }; }; return gs.mc(gSobject,"updateProgressText",[]); } gSobject['updateProgressText'] = function(it) { var rem = gs.mc(gSobject,"stepsRemaining",[]); gs.println("[DEBUG] updateProgressText(): stepGoal=" + (gs.gp(gSobject.scope,"stepGoal")) + ", totalSteps=" + (gs.gp(gSobject.scope,"totalSteps")) + ", remaining=" + (rem) + ""); if ((gs.bool(gs.gp(gs.gp(gSobject.scope,"stepGoal"),"steps",true))) && (gs.gp(gSobject.scope,"totalSteps") != null)) { return gs.sp(gs.gp(gSobject.scope,"stepGoal"),"progressText","" + (gs.gp(gSobject.scope,"stepsDescription")) + ". You still need " + (rem) + " steps to reach your goal."); } else { return gs.sp(gs.gp(gSobject.scope,"stepGoal"),"progressText","" + (gs.gp(gSobject.scope,"stepsDescription")) + "."); }; } gSobject['remainingSteps'] = function(it) { var goalStr = gs.gp(gs.gp(gSobject.scope,"stepGoal"),"steps",true); gs.println("goalStr: " + (goalStr) + ""); if ((((!gs.bool(goalStr)) || (gs.equals(goalStr, "SETUP"))) || (gs.mc(this,"isNaN",[gs.mc(this,"parseFloat",[goalStr], gSobject)], gSobject))) || (gs.equals(gs.mc(this,"parseFloat",[goalStr], gSobject), 0))) { gs.println("[No valid step goal set, skipping remainingSteps()]"); gs.sp(gSobject.scope,"stepsRemaining",null); return 0; }; var originalGoal = gs.mc(this,"parseFloat",[goalStr], gSobject); var totalToday = 0; var today = gs.mc(gs.mc(gSobject,"moment",[]),"format",["YYYY-MM-DD"]); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"listEntries",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:steps", function(logs) { gs.mc(logs,"each",[function(log) { var createdAt = gs.elvis(gs.bool(gs.gp(log,"_dateCreated",true)) , gs.gp(log,"_dateCreated",true) , gs.gp(log,"date",true)); if (!gs.bool(createdAt)) { return null; }; var logDate = gs.mc(gs.mc(gSobject,"moment",[createdAt]),"format",["YYYY-MM-DD"]); var val = gs.gp(log,"value"); if (gs.equals(logDate, today)) { if (gs.instanceOf(val, "Number")) { return totalToday += val; } else { if (((gs.instanceOf(val, "String")) && (val != "undefined")) && (!gs.bool(gs.mc(this,"isNaN",[gs.mc(this,"parseFloat",[val], gSobject)], gSobject)))) { return totalToday += gs.mc(this,"parseFloat",[val], gSobject); }; }; }; }]); var remaining = gs.minus(originalGoal, totalToday); if (remaining < 0) { remaining = 0; }; gs.sp(gSobject.scope,"stepsRemaining",remaining); gs.println("[StepsDetail] Today’s total: " + (totalToday) + ", Goal: " + (originalGoal) + ", Remaining: " + (remaining) + ""); return gs.sp(gs.gp(gSobject.scope,"stepGoal"),"progressText","" + (gs.gp(gSobject.scope,"stepsDescription")) + ". You still need " + (remaining) + " steps to reach your goal."); }]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function StepsGoalPreviewComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'StepsGoalPreviewComponent', simpleName: 'StepsGoalPreviewComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/stepGoalPreview" , "/stepGoalPreview/:id"]); gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "steps.goal.preview"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[false]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"progress",0); gs.sp(gSobject.scope,"totalSteps",0); gs.sp(gSobject.scope,"stepGoal",gs.map()); gs.sp(gSobject.scope,"batchName","medical:score:steps"); return gs.mc(gSobject,"loadLogs",[]); } gSobject['loadLogs'] = function(it) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:steps_goal", function(stepGoal) { if (gs.bool(stepGoal)) { gs.mc(gs.gp(gSobject.scope,"stepGoal"),"putAll",[stepGoal]); gs.sp(gs.gp(gSobject.scope,"stepGoal"),"unit","steps"); gs.sp(gs.gp(gSobject.scope,"stepGoal"),"description","target steps"); return gs.sp(gs.gp(gSobject.scope,"stepGoal"),"progressText","You’re on track! Keep working hard to improve your health & overall score."); }; }]); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"listEntries",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gSobject.scope,"batchName"), gs.map().add("limit",7), function(logs) { gs.mc(logs,"each",[function(log) { var val = gs.gp(log,"value"); if ((gs.instanceOf(val, "String")) && (val != "undefined")) { var entry = parseInt(val); gs.sp(gSobject.scope,"totalSteps",gs.gp(gSobject.scope,"totalSteps") + entry); return gs.mc(gSobject,"calculateProgress",[gs.gp(gSobject.scope,"totalSteps")]); } else { if (gs.instanceOf(val, "Number")) { gs.sp(gSobject.scope,"totalSteps",gs.gp(gSobject.scope,"totalSteps") + val); return gs.mc(gSobject,"calculateProgress",[gs.gp(gSobject.scope,"totalSteps")]); } else { return gs.println("Skipping invalid value: " + (val) + ""); }; }; }]); return gs.mc(gSobject,"calculateProgress",[gs.gp(gSobject.scope,"totalSteps")]); }]); } gSobject['calculateProgress'] = function(total) { if (total === undefined) total = null; gs.println("Step goal: " + (gs.gp(gs.gp(gSobject.scope,"stepGoal"),"steps")) + ""); gs.println("Total steps: " + (total) + ""); var goal = parseInt(gs.gp(gs.gp(gSobject.scope,"stepGoal"),"steps")); if (((goal > 0) && (total != null)) && (gs.instanceOf(total, "Number"))) { return gs.sp(gSobject.scope,"progress",Math.round(gs.multiply((gs.div(total, goal)), 100))); } else { return gs.sp(gSobject.scope,"progress",0); }; } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function StepsGoalTrackComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'StepsGoalTrackComponent', simpleName: 'StepsGoalTrackComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/stepsGoalTrack"; gSobject['created'] = function(it) { gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"stepsGoal",gs.map()); gs.sp(gSobject.scope,"stepGoal",gs.map()); gs.sp(gSobject.scope,"steps",null); gs.sp(gSobject.scope,"date",gs.date()); gs.sp(gSobject.scope,"goal",gs.map().add("value",70).add("unit","steps")); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "steps.goal.track"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[false]); gs.mc(gSobject,"componentTheme",[false]); return gs.mc(gSobject,"loadLogs",[]); } gSobject['loadLogs'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:steps_goal", function(stepGoal) { if (gs.bool(stepGoal)) { gs.mc(gs.gp(gSobject.scope,"stepGoal"),"putAll",[stepGoal]); gs.sp(gs.gp(gSobject.scope,"stepGoal"),"unit","steps"); gs.sp(gs.gp(gSobject.scope,"stepGoal"),"description","target weight"); return gs.sp(gs.gp(gSobject.scope,"stepGoal"),"progressText","You’re on track! Keep working hard to improve your health & overall score."); }; }]); } gSobject['increaseStep'] = function(it) { var current = parseInt(gs.elvis(gs.mc(gs.gp(gs.gp(gSobject.scope,"stepGoal"),"steps"),"toString",[], null, true) , gs.mc(gs.gp(gs.gp(gSobject.scope,"stepGoal"),"steps"),"toString",[], null, true) , "0")); return gs.sp(gs.gp(gSobject.scope,"stepGoal"),"steps",gs.mc(gs.plus(current, 1000),"toString",[])); } gSobject['decreaseStep'] = function(it) { var current = parseInt(gs.elvis(gs.mc(gs.gp(gs.gp(gSobject.scope,"stepGoal"),"steps"),"toString",[], null, true) , gs.mc(gs.gp(gs.gp(gSobject.scope,"stepGoal"),"steps"),"toString",[], null, true) , "0")); return gs.sp(gs.gp(gSobject.scope,"stepGoal"),"steps",gs.mc(Math.max(0, gs.minus(current, 1000)),"toString",[])); } gSobject['fixedSteps'] = function(val) { var current = parseInt(gs.elvis(gs.mc(gs.gp(gs.gp(gSobject.scope,"stepGoal"),"steps"),"toString",[], null, true) , gs.mc(gs.gp(gs.gp(gSobject.scope,"stepGoal"),"steps"),"toString",[], null, true) , "0")); return gs.sp(gs.gp(gSobject.scope,"stepGoal"),"steps",gs.mc(val,"toString",[])); } gSobject['recommendedSteps'] = function(val) { var current = parseInt(gs.elvis(gs.mc(gs.gp(gs.gp(gSobject.scope,"stepGoal"),"steps"),"toString",[], null, true) , gs.mc(gs.gp(gs.gp(gSobject.scope,"stepGoal"),"steps"),"toString",[], null, true) , "0")); return gs.sp(gs.gp(gSobject.scope,"stepGoal"),"steps",gs.mc(val,"toString",[])); } gSobject['save'] = function(it) { gs.println(gs.multiply("=", 20)); gs.println("SAVING"); gs.sp(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"stepsGoal"),"steps",gs.gp(gs.gp(gSobject.scope,"stepGoal"),"steps")); gs.sp(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"stepsGoal"),"date",gs.gp(gs.gp(gSobject.scope,"stepGoal"),"date")); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:steps_goal", gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"stepsGoal"), function(it) { gs.mc(gSobject,"eventLogGoal",[]); return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["stepsOverview"]); }]); } gSobject['eventLogGoal'] = function(it) { var narrative = "Logged steps goal: " + (gs.gp(gs.gp(gSobject.scope,"stepGoal"),"steps")) + ""; return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"eventLogService"),"event",[gs.gp(gs.fs('session', this, gSobject),"userId"), narrative, "steps:goal", "info"]),"do",[]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function StepsGoalAchievedComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'StepsGoalAchievedComponent', simpleName: 'StepsGoalAchievedComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/stepGoalAchieved" , "/stepGoalAchieved/:id"]); gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "steps.goal.achieved"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[false]); return gs.mc(gSobject,"componentTheme",[false]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function AiSettingsComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'AiSettingsComponent', simpleName: 'AiSettingsComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/settings"; Object.defineProperty(gSobject, 'MAX_REMINDERS_PER_DAY', { get: function() { return AiSettingsComponent.MAX_REMINDERS_PER_DAY; }, set: function(gSval) { AiSettingsComponent.MAX_REMINDERS_PER_DAY = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'TRANSLATE_LANGUAGE_CODES', { get: function() { return AiSettingsComponent.TRANSLATE_LANGUAGE_CODES; }, set: function(gSval) { AiSettingsComponent.TRANSLATE_LANGUAGE_CODES = gSval; }, enumerable: true }); gSobject['created'] = function(it) { gs.sp(gSobject.scope,"trackables",gs.list(["Steps" , "Weight" , "Glucose"])); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"aiDialogs",gs.map().add("tone",false).add("frequency",false).add("focus",false).add("quiet",false)); gs.sp(gSobject.scope,"languages",AiSettingsComponent.TRANSLATE_LANGUAGE_CODES); gs.sp(gSobject.scope,"activeTab","tone"); gs.sp(gSobject.scope,"selectedTone","Encouraging"); gs.sp(gSobject.scope,"showQuietStartDialog",false); gs.sp(gSobject.scope,"showQuietEndDialog",false); gs.sp(gSobject.scope,"aiTones",gs.mc(gSobject,"aiTones",[])); gs.mc(gSobject,"loadRxmeUser",[]); return gs.mc(gSobject,"loadUser",[]); } gSobject['loadRxmeUser'] = function(it) { gs.sp(gSobject.scope,"rxmeUser",gs.map()); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"loadRxmeUser",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(rxmeUser) { gs.sp(gSobject.scope,"rxmeUser",rxmeUser); gs.sp(gs.gp(gSobject.scope,"rxmeUser"),"aiTone",gs.elvis(gs.bool(gs.gp(rxmeUser,"aiTone")) , gs.gp(rxmeUser,"aiTone") , "Encouraging")); gs.sp(gs.gp(gSobject.scope,"rxmeUser"),"aiFrequency",gs.elvis(gs.bool(gs.gp(rxmeUser,"aiFrequency")) , gs.gp(rxmeUser,"aiFrequency") , 1)); gs.sp(gs.gp(gSobject.scope,"rxmeUser"),"aiFocusAreas",gs.elvis(gs.bool(gs.gp(rxmeUser,"aiFocusAreas")) , gs.gp(rxmeUser,"aiFocusAreas") , gs.list([]))); gs.sp(gs.gp(gSobject.scope,"rxmeUser"),"quietStart",gs.elvis(gs.bool(gs.gp(rxmeUser,"quietStart")) , gs.gp(rxmeUser,"quietStart") , "22:00")); gs.sp(gs.gp(gSobject.scope,"rxmeUser"),"quietEnd",gs.elvis(gs.bool(gs.gp(rxmeUser,"quietEnd")) , gs.gp(rxmeUser,"quietEnd") , "07:00")); gs.sp(gs.gp(gSobject.scope,"rxmeUser"),"aiEnabled",(gs.gp(rxmeUser,"aiEnabled") != null ? gs.gp(rxmeUser,"aiEnabled") : true)); return gs.sp(gs.gp(gSobject.scope,"rxmeUser"),"aiLang",gs.elvis(gs.bool(gs.gp(gs.gp(gSobject.scope,"rxmeUser"),"aiLang")) , gs.gp(gs.gp(gSobject.scope,"rxmeUser"),"aiLang") , "en")); }]); } gSobject['loadUser'] = function(it) { return gs.mc(gs.fs('legionUserService', this, gSobject),"loadLegionUserFromServer",[function(it) { return gs.sp(gSobject.scope,"user",gs.gp(gs.fs('session', this, gSobject),"user")); }]); } gSobject['saveSettings'] = function(it) { return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"updateUserInfo",[gs.gp(gSobject.scope,"user"), gs.gp(gSobject.scope,"rxmeUser")]),"then",[function(user) { gs.mc(gSobject,"notify",["Settings Saved"]); gs.mc(gSobject,"loadRxmeUser",[]); gs.mc(gSobject,"loadUser",[]); return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/profile"]); }, function(error) { return gs.println("Error saving settings"); }]); } gSobject['formatTime'] = function(time) { if (!gs.bool(time)) { return "--:--"; }; return gs.mc(gs.mc(gSobject,"moment",[time]),"format",["HH:mm"]); } gSobject['aiTones'] = function(it) { return gs.list([gs.map().add("tone","Inspirational").add("desc","Uplifting and visionary, focusing on big dreams and aspirations.") , gs.map().add("tone","Empowering").add("desc","Bold and confidence-boosting, emphasizing personal strength and capability.") , gs.map().add("tone","Encouraging").add("desc","Warm and supportive, offering gentle nudges toward progress.") , gs.map().add("tone","Energetic").add("desc","High-energy and dynamic, sparking enthusiasm and action.") , gs.map().add("tone","Resilient").add("desc","Gritty and determined, highlighting perseverance through challenges.") , gs.map().add("tone","Optimistic").add("desc","Bright and hopeful, focusing on positive outcomes and possibilities.") , gs.map().add("tone","Reflective").add("desc","Thoughtful and introspective, encouraging self-awareness and growth.") , gs.map().add("tone","Bold").add("desc","Fearless and daring, pushing for courage and big moves.") , gs.map().add("tone","Calm").add("desc","Soothing and grounded, promoting inner peace and steady progress.") , gs.map().add("tone","Humorous").add("desc","Lighthearted and witty, using humor to inspire and motivate.")]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; AiSettingsComponent.MAX_REMINDERS_PER_DAY = 3; AiSettingsComponent.TRANSLATE_LANGUAGE_CODES = gs.list([]); function CordovaShare() { var gSobject = gs.init('CordovaShare'); gSobject.clazz = { name: 'CordovaShare', simpleName: 'CordovaShare'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject['share'] = function(message, subject, files, url, success, failure) { if (subject === undefined) subject = null; if (files === undefined) files = null; if (url === undefined) url = null; if (success === undefined) success = function(it) { }; if (failure === undefined) failure = function(it) { }; if (!gs.bool(CordovaShare.shareInstalled())) { gs.execCall(failure, this, ["socialsharing not installed"]); return null; }; try { gs.mc(gs.gp(gs.gp(gs.fs('window', this, gSobject),"plugins"),"socialsharing"),"share",[message, subject, files, url, success, failure]); } catch (e) { gs.execCall(failure, this, ["" + (gs.fs('e', this, gSobject)) + ""]); } ; } gSobject['shareViaEmail'] = function(message, subject, to, cc, bcc, files, success, failure) { if (subject === undefined) subject = ""; if (to === undefined) to = gs.list([]); if (cc === undefined) cc = gs.list([]); if (bcc === undefined) bcc = gs.list([]); if (files === undefined) files = null; if (success === undefined) success = function(it) { }; if (failure === undefined) failure = function(it) { }; if (!gs.bool(CordovaShare.shareInstalled())) { gs.execCall(failure, this, ["socialsharing not installed"]); return null; }; try { gs.mc(gs.gp(gs.gp(gs.fs('window', this, gSobject),"plugins"),"socialsharing"),"shareViaEmail",[message, subject, to, cc, bcc, files, success, failure]); } catch (e) { gs.execCall(failure, this, ["" + (gs.fs('e', this, gSobject)) + ""]); } ; } gSobject['shareViaSMS'] = function(message, phoneNumbers, success, failure) { if (phoneNumbers === undefined) phoneNumbers = ""; if (success === undefined) success = function(it) { }; if (failure === undefined) failure = function(it) { }; if (!gs.bool(CordovaShare.shareInstalled())) { gs.execCall(failure, this, ["socialsharing not installed"]); return null; }; try { gs.mc(gs.gp(gs.gp(gs.fs('window', this, gSobject),"plugins"),"socialsharing"),"shareViaSMS",[gs.map().add("message",message), phoneNumbers, success, failure]); } catch (e) { gs.execCall(failure, this, ["" + (gs.fs('e', this, gSobject)) + ""]); } ; } gSobject['shareViaWhatsApp'] = function(message, files, url, success, failure) { if (files === undefined) files = null; if (url === undefined) url = null; if (success === undefined) success = function(it) { }; if (failure === undefined) failure = function(it) { }; if (!gs.bool(CordovaShare.shareInstalled())) { gs.execCall(failure, this, ["socialsharing not installed"]); return null; }; try { gs.mc(gs.gp(gs.gp(gs.fs('window', this, gSobject),"plugins"),"socialsharing"),"shareViaWhatsApp",[message, files, url, success, failure]); } catch (e) { gs.execCall(failure, this, ["" + (gs.fs('e', this, gSobject)) + ""]); } ; } gSobject['shareViaTwitter'] = function(message, files, url, success, failure) { if (files === undefined) files = null; if (url === undefined) url = null; if (success === undefined) success = function(it) { }; if (failure === undefined) failure = function(it) { }; if (!gs.bool(CordovaShare.shareInstalled())) { gs.execCall(failure, this, ["socialsharing not installed"]); return null; }; try { gs.mc(gs.gp(gs.gp(gs.fs('window', this, gSobject),"plugins"),"socialsharing"),"shareViaTwitter",[message, files, url, success, failure]); } catch (e) { gs.execCall(failure, this, ["" + (gs.fs('e', this, gSobject)) + ""]); } ; } gSobject['shareViaFacebook'] = function(message, files, url, success, failure) { if (files === undefined) files = null; if (url === undefined) url = null; if (success === undefined) success = function(it) { }; if (failure === undefined) failure = function(it) { }; if (!gs.bool(CordovaShare.shareInstalled())) { gs.execCall(failure, this, ["socialsharing not installed"]); return null; }; try { gs.mc(gs.gp(gs.gp(gs.fs('window', this, gSobject),"plugins"),"socialsharing"),"shareViaFacebook",[message, files, url, success, failure]); } catch (e) { gs.execCall(failure, this, ["" + (gs.fs('e', this, gSobject)) + ""]); } ; } gSobject['canShareVia'] = function(via, message, subject, files, url, success, failure) { if (message === undefined) message = ""; if (subject === undefined) subject = null; if (files === undefined) files = null; if (url === undefined) url = null; if (success === undefined) success = function(it) { }; if (failure === undefined) failure = function(it) { }; if (!gs.bool(CordovaShare.shareInstalled())) { gs.execCall(failure, this, ["socialsharing not installed"]); return null; }; try { gs.mc(gs.gp(gs.gp(gs.fs('window', this, gSobject),"plugins"),"socialsharing"),"canShareVia",[via, message, subject, files, url, success, failure]); } catch (e) { gs.execCall(failure, this, ["" + (gs.fs('e', this, gSobject)) + ""]); } ; } gSobject['saveToPhotoAlbum'] = function(files, success, failure) { if (success === undefined) success = function(it) { }; if (failure === undefined) failure = function(it) { }; if (!gs.bool(CordovaShare.shareInstalled())) { gs.execCall(failure, this, ["socialsharing not installed"]); return null; }; try { gs.mc(gs.gp(gs.gp(gs.fs('window', this, gSobject),"plugins"),"socialsharing"),"saveToPhotoAlbum",[files, success, failure]); } catch (e) { gs.execCall(failure, this, ["" + (gs.fs('e', this, gSobject)) + ""]); } ; } gSobject['available'] = function(callback) { if (!gs.bool(CordovaShare.shareInstalled())) { gs.execCall(callback, this, [false]); return null; }; try { gs.mc(gs.gp(gs.gp(gs.fs('window', this, gSobject),"plugins"),"socialsharing"),"available",[callback]); } catch (e) { gs.execCall(callback, this, [false]); } ; } gSobject.shareInstalled = function() { return CordovaShare.shareInstalled(); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; CordovaShare.shareInstalled = function() { return typeof window.plugins !== 'undefined' && typeof window.plugins.socialsharing !== 'undefined'; } function PdfJsHandler() { var gSobject = gs.init('PdfJsHandler'); gSobject.clazz = { name: 'PdfJsHandler', simpleName: 'PdfJsHandler'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; Object.defineProperty(gSobject, 'rendering', { get: function() { return PdfJsHandler.rendering; }, set: function(gSval) { PdfJsHandler.rendering = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'numberPending', { get: function() { return PdfJsHandler.numberPending; }, set: function(gSval) { PdfJsHandler.numberPending = gSval; }, enumerable: true }); gSobject['build'] = function(filePath, callback) { if (callback === undefined) callback = function(it) { }; return PdfJsHandler.paintWholePdf(filePath, callback); } gSobject.paintWholePdf = function(x0,x1) { return PdfJsHandler.paintWholePdf(x0,x1); } gSobject.renderPageScroll = function(x0,x1) { return PdfJsHandler.renderPageScroll(x0,x1); } gSobject.paintPdf = function(x0,x1) { return PdfJsHandler.paintPdf(x0,x1); } gSobject.renderPage = function(x0,x1) { return PdfJsHandler.renderPage(x0,x1); } gSobject['PdfJsHandler1'] = function(filePath) { if (filePath === undefined) filePath = ""; if (!gs.bool(filePath)) { return null; }; gs.mc(this,"paintWholePdf",[filePath], gSobject); return this; } if (arguments.length==1) {gSobject.PdfJsHandler1(arguments[0]); } return gSobject; }; PdfJsHandler.paintWholePdf = function(filePath, callback) { spinnerDiv = document.createElement('div'); spinnerDiv.setAttribute("id", "spinner"); spinnerDiv.setAttribute("class", "fixed-center") spinner = document.createElement('div'); spinner.setAttribute("class", "i3-media-pdf-spinner"); spinnerDiv.append(spinner); $('#pdf-viewer').append(spinnerDiv); pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.10.111/pdf.worker.min.js'; var loadPdf = pdfjsLib.getDocument(filePath); loadPdf.promise.then(function(pdf) { const maxPage = pdf._pdfInfo.numPages; for (var i = 1; i <= maxPage; i++) { PdfJsHandler.renderPageScroll(pdf, i); } document.getElementById('spinner').remove(); callback() }) } PdfJsHandler.renderPageScroll = function(pdf, number) { pdf.getPage(number).then(function(page) { const canvasId = 'pdf_viewer-' + number; $('#pdf-viewer').append($('', {'id': canvasId, 'style': 'object-fit:contain', 'class':'full-width'})); // $('#pdf-viewer').append($('', {'id': canvasId})); const canvas = document.getElementById(canvasId); const viewport = page.getViewport({scale: 1}); const context = canvas.getContext("2d"); canvas.height = viewport.height; canvas.width = viewport.width; var renderContext = { canvasContext: context, viewport: viewport }; const renderTask = page.render(renderContext); }); } PdfJsHandler.paintPdf = function(filePath, getPage) { pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.10.111/pdf.worker.min.js'; var loadPdf = pdfjsLib.getDocument(filePath); loadPdf.promise.then(function(pdf) { const minPage = 1; const maxPage = pdf._pdfInfo.numPages; let currentPage = 1; PdfJsHandler.rendering = false; PdfJsHandler.numberPending = null; PdfJsHandler.renderPage(pdf, currentPage); document.getElementById("pdfPageNumber").innerHTML = `Page ${currentPage} of ${maxPage}`; document.getElementById("pdfPrev").addEventListener("click", () => { if (currentPage > minPage) { currentPage = currentPage - 1 PdfJsHandler.renderPage(pdf, currentPage); document.getElementById("pdfPageNumber").innerHTML = `Page ${currentPage} of ${maxPage}`; } }) document.getElementById("pdfNext").addEventListener("click", () => { if (currentPage < maxPage) { currentPage = currentPage + 1 PdfJsHandler.renderPage(pdf, currentPage); document.getElementById("pdfPageNumber").innerHTML = `Page ${currentPage} of ${maxPage}`; } }) }) } PdfJsHandler.renderPage = function(pdf, number) { console.log('renderPage with ' + number + ', ' + PdfJsHandler.rendering + ', ' + PdfJsHandler.numberPending) if (PdfJsHandler.rendering) { PdfJsHandler.numberPending = number; } else { PdfJsHandler.rendering = true; pdf.getPage(number).then(function(page) { const canvas = document.getElementById("pdf_canvas"); const viewport = page.getViewport({scale: 1}); const context = canvas.getContext("2d"); canvas.height = viewport.height; canvas.width = viewport.width; var renderContext = { canvasContext: context, viewport: viewport }; const renderTask = page.render(renderContext); renderTask.promise.then(function() { PdfJsHandler.rendering = false; if (PdfJsHandler.numberPending !== null) { PdfJsHandler.renderPage(pdf, number); PdfJsHandler.numberPending = null; } }); }); } } PdfJsHandler.rendering = false; PdfJsHandler.numberPending = null; function ReferComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'ReferComponent', simpleName: 'ReferComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/refer"; gSobject['created'] = function(it) { gs.println("ReferComponent.created()"); gs.mc(gSobject,"showHeaderFooter",[]); return gs.sp(gSobject.scope,"email",""); } gSobject['sendEmail'] = function(it) { return gs.mc(gSobject,"notify",["WIP"]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function CordovaGoogleSignIn() { var gSobject = gs.init('CordovaGoogleSignIn'); gSobject.clazz = { name: 'CordovaGoogleSignIn', simpleName: 'CordovaGoogleSignIn'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.googleSignIn = function(success, error) { // Try new i3 plugin first, fall back to old plugin if (cordova.plugins.i3GoogleSignIn) { cordova.plugins.i3GoogleSignIn.login(function(authData) { success(authData); }, function(err) { if (error) error(err); }); } else if (cordova.plugins.GoogleSignInPlugin) { cordova.plugins.GoogleSignInPlugin.signIn(function(authData) { success(authData); }, function(err) { if (error) error(err); }); } else { if (error) error('No Google Sign-In plugin available'); } } gSobject.isSignedIn = function(success, error) { if (cordova.plugins.GoogleSignInPlugin && cordova.plugins.GoogleSignInPlugin.isSignedIn) { cordova.plugins.GoogleSignInPlugin.isSignedIn(function(result) { success(result); }, function(err) { if (error) error(err); }); } else { success({isSignedIn: false}); } } gSobject.signOut = function(success, error) { if (cordova.plugins.i3GoogleSignIn) { cordova.plugins.i3GoogleSignIn.logout(function(result) { if (success) success(result); }, function(err) { if (error) error(err); }); } else if (cordova.plugins.GoogleSignInPlugin) { cordova.plugins.GoogleSignInPlugin.signOut(function(result) { if (success) success(result); }, function(err) { if (error) error(err); }); } else { if (success) success(); } } gSobject.trySilentLogin = function(success, error) { if (cordova.plugins.i3GoogleSignIn) { cordova.plugins.i3GoogleSignIn.trySilentLogin(function(result) { success(result); }, function(err) { if (error) error(err); }); } else { if (error) error('Silent login not available'); } } gSobject.isAvailable = function() { return CordovaGoogleSignIn.isAvailable(); } gSobject['CordovaGoogleSignIn0'] = function(it) { gs.mc(document,"addEventListener",["deviceready", function(it) { if (!gs.bool(gs.mc(this,"isAvailable",[], gSobject))) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["GoogleSignIn: Not Available"]); return null; } else { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["GoogleSignIn: Available"]); }; }]); return this; } if (arguments.length==0) {gSobject.CordovaGoogleSignIn0(); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; CordovaGoogleSignIn.isAvailable = function() { return !!(cordova.plugins.i3GoogleSignIn || cordova.plugins.GoogleSignInPlugin); } function MealPlanIdealWeightComponent() { var gSobject = VueComponent(); gSobject.clazz = { name: 'MealPlanIdealWeightComponent', simpleName: 'MealPlanIdealWeightComponent'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.path = "/mealPlanIdealWeightComponent"; gSobject.roles = gs.list(["ROLE_USER"]); gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "meal.plan.ideal"]),"do",[]); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"idealWeightMealPlan",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(contentId) { gs.println(contentId); return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/mediaContent/" + (contentId) + ""]); }]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function ResourceWebinarsComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'ResourceWebinarsComponent', simpleName: 'ResourceWebinarsComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/resourceWebinars"; gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "resource.webinars.page"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); return gs.mc(gSobject,"componentTheme",[false]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function SymptomComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'SymptomComponent', simpleName: 'SymptomComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/symptomsOverview"; gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.symptom.overview"]),"do",[]); gs.println("SymptomComponent.created()"); gs.mc(gSobject,"showHeaderFooter",[]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"batchName","medical:score:symptom"); gs.sp(gSobject.scope,"graphPeriod","Day"); gs.sp(gSobject.scope,"tracker",null); gs.sp(gSobject.scope,"symptomsOptions",gs.list([gs.map().add("label","Pain").add("value","Pain").add("icon","sym_o_rheumatology") , gs.map().add("label","Vomiting").add("value","vomiting").add("icon","sym_o_dirty_lens") , gs.map().add("label","Constipation").add("value","constipation").add("icon","sym_o_oncology") , gs.map().add("label","Diarrhea").add("value","diarrhea").add("icon","sym_o_gastroenterology") , gs.map().add("label","Dizziness").add("value","dizziness").add("icon","rotate_right") , gs.map().add("label","Palpitations").add("value","Palpitations").add("icon","sym_o_cadence") , gs.map().add("label","Nausea").add("value","nausea").add("icon","waves")])); gs.mc(gSobject,"loadLogs",[]); gs.mc(gSobject,"symptomIcon",[]); gs.mc(gSobject,"loadTrackerData",["Symptoms", function(tracker) { return gs.sp(gSobject.scope,"tracker",tracker); }]); gs.sp(gSobject.scope,"motivationalText",""); return gs.mc(gSobject,"motivationalText",[]); } gSobject['loadLogs'] = function(it) { gs.sp(gSobject.scope,"logs",gs.list([])); gs.sp(gSobject.scope,"lastEntry",gs.map()); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"listEntries",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gSobject.scope,"batchName"), gs.map().add("limit",7), function(logs) { return gs.mc(logs,"each",[function(log) { gs.mc(logs,"sort",[function(a, b) { return gs.spaceShip(gs.gp(b,"_createdAt"), gs.gp(a,"_createdAt")); }]); gs.mc(gs.gp(gSobject.scope,"logs"),"add",[gs.map().add("_id",gs.gp(log,"_id")).add("symptom",gs.gp(log,"symptom")).add("value",gs.gp(log,"symptom")).add("subtext",gs.gp(log,"notes")).add("intensity",gs.gp(log,"intensity")).add("notes",gs.gp(log,"notes")).add("type",gs.gp(log,"type")).add("_createdAt",gs.gp(log,"date"))]); gs.sp(gSobject.scope,"lastEntry",(gs.bool(gs.gp(gSobject.scope,"logs")) ? gs.gp(gSobject.scope,"logs")[0] : gs.map())); gs.println("Entry logs"); return gs.println(gs.gp(gSobject.scope,"logs")); }]); }]); } gSobject['symptomIcon'] = function(key) { var match = gs.mc(gs.gp(gSobject.scope,"symptomsOptions"),"find",[function(it) { return gs.equals(gs.gp(it,"value"), key); }]); gs.println("MATCH"); gs.println(match); return gs.elvis(gs.bool(gs.gp(match,"icon",true)) , gs.gp(match,"icon",true) , "thermostat"); } gSobject['motivationalText'] = function(it) { gs.sp(gSobject.scope,"motivationLoading",true); return gs.mc(gSobject,"loadMotivation",[gs.gp(gs.fs('session', this, gSobject),"userId"), "Symptom", function(msg) { gs.sp(gSobject.scope,"motivationalText",msg); return gs.sp(gSobject.scope,"motivationLoading",false); }]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function SymptomDetailComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'SymptomDetailComponent', simpleName: 'SymptomDetailComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/symptomDetail" , "/symptomDetail/:id"]); gSobject['created'] = function(it) { gs.println("SymptomDetailComponent.created()"); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.symptom.detail"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); gs.mc(gSobject,"componentTheme",[false]); gs.mc(gSobject,"loadSymptomDetails",[gs.gp(gs.gp(gSobject.route,"params"),"id")]); return gs.sp(gSobject.scope,"images",gs.list([])); } gSobject['loadSymptomDetails'] = function(id) { if (gs.bool(gs.gp(gs.gp(gSobject.route,"params"),"id"))) { gs.sp(gSobject.scope,"entry",null); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"loadEntry",[gs.gp(gs.gp(gSobject.route,"params"),"id"), function(entry) { if (entry != null) { gs.sp(gSobject.scope,"entry",entry); if (gs.bool(gs.gp(entry,"imageIds"))) { return gs.mc(gs.gp(entry,"imageIds"),"each",[function(imgId) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataFile"),"findOne",[gs.map().add("_id",imgId), function(fileObj) { if (gs.bool(gs.gp(fileObj,"file"))) { return gs.mc(gs.gp(gSobject.scope,"images"),'leftShift', gs.list([fileObj])); }; }]); }]); }; }; }]); }; } gSobject['formatDate'] = function(date) { return gs.mc(gs.mc(gSobject,"moment",[date]),"format",["dddd, MMM DD, YYYY"]); } gSobject['formatTime'] = function(date) { return gs.mc(gs.mc(gSobject,"moment",[date]),"format",["hh:mm A"]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function HealthAPI() { var gSobject = RootComponent(); gSobject.clazz = { name: 'HealthAPI', simpleName: 'HealthAPI'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/healthapi"; gSobject['created'] = function(it) { gs.mc(gSobject,"componentTheme",[false]); if (gs.equals(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"syncing"), null)) { gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"syncing",false); }; gs.sp(gSobject.scope,"data",gs.map().add("syncEnabled",null).add("loading",true).add("lastSync",null).add("syncSteps",null).add("syncBp",null).add("syncHeartRate",null).add("syncing",gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"syncing"))); return gs.mc(gSobject,"loadSyncStatus",[]); } gSobject['loadSyncStatus'] = function(it) { gs.sp(gs.gp(gSobject.scope,"data"),"loading",true); gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:sync:enabled", function(syncEnabled) { gs.sp(gs.gp(gSobject.scope,"data"),"syncEnabled",syncEnabled); return gs.sp(gs.gp(gSobject.scope,"data"),"loading",false); }]); gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:steps:last_sync", function(lastSync) { return gs.sp(gs.gp(gSobject.scope,"data"),"lastSync",lastSync); }]); gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:sync:steps", function(syncSteps) { return gs.sp(gs.gp(gSobject.scope,"data"),"syncSteps",syncSteps); }]); gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:sync:bp", function(syncBp) { return gs.sp(gs.gp(gSobject.scope,"data"),"syncBp",syncBp); }]); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:sync:heart_rate", function(syncHeartRate) { return gs.sp(gs.gp(gSobject.scope,"data"),"syncHeartRate",syncHeartRate); }]); } gSobject['toggleSync'] = function(enabled) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:sync:enabled", enabled]),"do",[]); gs.sp(gs.gp(gSobject.scope,"data"),"syncEnabled",enabled); if (gs.bool(enabled)) { return gs.mc(gs.fs('rxmeHealthSyncJsService', this, gSobject),"enableSync",[]); }; } gSobject['toggleStepsSync'] = function(enabled) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:sync:steps", enabled]),"do",[]); return gs.sp(gs.gp(gSobject.scope,"data"),"syncSteps",enabled); } gSobject['toggleBpSync'] = function(enabled) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:sync:bp", enabled]),"do",[]); return gs.sp(gs.gp(gSobject.scope,"data"),"syncBp",enabled); } gSobject['toggleHeartRateSync'] = function(enabled) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:sync:heart_rate", enabled]),"do",[]); return gs.sp(gs.gp(gSobject.scope,"data"),"syncHeartRate",enabled); } gSobject['triggerSync'] = function(it) { if (gs.bool(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"syncing"))) { gs.mc(gSobject.q,"notify",[gs.map().add("message","Sync already in progress").add("color","warning").add("icon","info")]); return null; }; gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"syncing",true); gs.sp(gs.gp(gSobject.scope,"data"),"syncing",true); gs.mc(gSobject.q,"dialog",[gs.map().add("title","Syncing Health Data").add("message","Health data is being synced in the background. You can continue using the app.").add("persistent",false)]); return gs.mc(gs.fs('rxmeHealthSyncJsService', this, gSobject),"syncHealthApi",[function(stats) { gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"syncing",false); gs.sp(gs.gp(gSobject.scope,"data"),"syncing",false); gs.mc(gSobject,"loadSyncStatus",[]); if (gs.bool(stats)) { return gs.mc(gSobject.q,"notify",[gs.map().add("message","Health data synced successfully").add("color","positive").add("icon","check_circle")]); } else { return gs.mc(gSobject.q,"notify",[gs.map().add("message","Sync completed with errors").add("color","warning").add("icon","warning")]); }; }]); } gSobject['testBtn'] = function(it) { return gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"requestHealthSync",true); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function CordovaPhoto() { var gSobject = gs.init('CordovaPhoto'); gSobject.clazz = { name: 'CordovaPhoto', simpleName: 'CordovaPhoto'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject['takePhoto'] = function(onSuccess, onFail, config) { if (config === undefined) config = gs.map(); return gs.mc(gSobject,"capture",["camera", onSuccess, onFail, config]); } gSobject['pickFromLibrary'] = function(onSuccess, onFail, config) { if (config === undefined) config = gs.map(); return gs.mc(gSobject,"capture",["library", onSuccess, onFail, config]); } gSobject['takePhotoBlob'] = function(onSuccess, onError) { if (onError === undefined) onError = function(it) { }; var success = function(imageUri) { return gs.mc(gs.fs('cordovaFile', this, gSobject),"blobFromFileUrl",[imageUri, function(blob) { gs.execCall(onSuccess, this, [blob]); return gs.mc(gSobject,"clearCache",[]); }, onError]); }; return gs.mc(gSobject,"takePhoto",[success, onError]); } gSobject['takePhotoAndUpload'] = function(objectName, property, objectId, onSuccess, onError) { if (onError === undefined) onError = function(it) { }; var success = function(tempImageUrl) { return gs.mc(gs.fs('cordovaFile', this, gSobject),"addFile",[tempImageUrl, objectName, property, objectId, onSuccess, onError]); }; return gs.mc(gSobject,"takePhoto",[success, onError]); } gSobject['clearCache'] = function(it) { } gSobject['capture'] = function(source, onSuccess, onFail, config) { var opts = gs.mc(gs.map().add("source",source).add("output","fileUri").add("maxWidth",1024).add("maxHeight",1024),'leftShift', gs.list([config])); return CordovaPhoto.pick(opts, function(result) { return gs.execCall(onSuccess, this, [gs.gp(result,"data")]); }, onFail); } gSobject.pick = function(x0,x1,x2) { return CordovaPhoto.pick(x0,x1,x2); } gSobject.isAvailable = function() { return CordovaPhoto.isAvailable(); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; CordovaPhoto.pick = function(options, onSuccess, onFail) { if (typeof cordova === 'undefined' || !cordova.plugins || !cordova.plugins.dymicoPhoto) { return onFail('dymico-photo plugin not available'); } cordova.plugins.dymicoPhoto.pick(options, onSuccess, onFail); } CordovaPhoto.isAvailable = function() { return ( typeof cordova !== 'undefined' && cordova.plugins && typeof cordova.plugins.dymicoPhoto !== 'undefined' ); } function I3Media() { var gSobject = VueComponent(); gSobject.clazz = { name: 'I3Media', simpleName: 'I3Media'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; Object.defineProperty(gSobject, 'PREVIEW_LIMIT', { get: function() { return I3Media.PREVIEW_LIMIT; }, set: function(gSval) { I3Media.PREVIEW_LIMIT = gSval; }, enumerable: true }); gSobject.props = gs.map().add("object",Map).add("prop",String).add("objectName",String).add("serverWidth",String).add("serverHeight",String).add("placeholder",String).add("eager",Boolean).add("path",String).add("type",String).add("upload",Boolean).add("delete",Boolean).add("camera",Boolean).add("initCallback",gs.map().add("type",Function).add("default",function(it) { })).add("removedCallback",gs.map().add("type",Function).add("default",function(it) { })).add("callback",gs.map().add("type",Function).add("default",function(it) { })).add("base64",Boolean).add("embedText",Function).add("view",Boolean).add("download",Boolean).add("preview",Boolean).add("autoplay",Boolean).add("muted",Boolean).add("loop",Boolean).add("controls",Boolean).add("customControls",Boolean).add("fullscreenControl",Boolean).add("muteControl",Boolean).add("classes",String).add("width",String).add("height",String).add("maxWidth",String).add("maxHeight",String).add("borderRadius",String).add("ratio",String).add("fit",String).add("noSpinner",Boolean).add("noTransition",Boolean).add("noAnimation",Boolean).add("location",Boolean).add("grayScale",Boolean); gSobject.data = function(it) { return gs.map().add("mediaType","").add("uploadSpinner",false).add("viewDialog",false).add("videoPlaying",false).add("videoEnded",false).add("videoMuted",false).add("imageMetadata",gs.map()); }; gSobject['created'] = function(it) { gs.println("I3Media.created()"); var self = this; return gs.mc(gSobject,"init",[self]); } gSobject['watchObject'] = function(it) { var self = this; return gs.mc(gSobject,"init",[self]); } gSobject['init'] = function(self) { gs.sp(self,"placeholderUrl","/statics/vue-wrapper/img/placeHolder.png"); gs.sp(self,"mediaType",""); gs.sp(self,"fileToUpload",null); gs.sp(self,"viewDialog",false); gs.sp(self,"uploadEnabled",false); gs.sp(self,"deleteEnabled",false); gs.sp(self,"downloadEnabled",false); gs.sp(self,"cameraEnabled",false); gs.sp(self,"ratioStyle",(gs.bool(gs.gp(self,"ratio")) ? gs.plus((gs.plus("padding-top:", (gs.multiply(Math.pow(gs.gp(self,"ratio"), -1), 100)))), "%") : "")); gs.sp(self,"ratioClass",(gs.bool(gs.gp(self,"ratio")) ? "absolute" : "")); gs.sp(self,"borderRadiusStyle",(gs.bool(gs.gp(self,"borderRadius")) ? gs.plus("border-radius:", gs.gp(self,"borderRadius")) : "")); gs.sp(self,"maxWidthStyle",(gs.bool(gs.gp(self,"maxWidth")) ? gs.plus("max-width:", gs.gp(self,"maxWidth")) : "")); gs.sp(self,"maxHeightStyle",(gs.bool(gs.gp(self,"maxHeight")) ? gs.plus("max-height:", gs.gp(self,"maxHeight")) : "")); gs.sp(self,"grayScaleStyle",(gs.bool(gs.gp(self,"grayScale")) ? "filter: grayscale(1)" : "")); gs.sp(self,"staticWidth",(gs.bool(gs.gp(self,"width")) ? gs.plus("width:", gs.gp(self,"width")) : "")); gs.sp(self,"staticHeight",(gs.bool(gs.gp(self,"height")) ? gs.plus("height:", gs.gp(self,"height")) : "")); gs.sp(self,"loading",(gs.bool(gs.gp(self,"eager")) ? "eager" : "lazy")); gs.sp(self,"videoMuted",gs.gp(self,"muted")); gs.sp(self,"accepted",gs.mc(gSobject,"resolveAcceptedType",[gs.gp(self,"type")])); if (gs.bool(gs.gp(self,"path"))) { return gs.sp(self,"previewUrl",gs.gp(self,"path")); }; if (gs.bool(gs.gp(self,"placeholder"))) { gs.sp(self,"placeholderUrl",gs.gp(self,"placeholder")); }; if ((!gs.bool(gs.gp(self,"object"))) || (!gs.bool(gs.gp(self,"prop")))) { return gs.sp(self,"previewUrl",gs.gp(self,"placeholderUrl")); }; if (gs.bool(gs.gp(self,"upload"))) { gs.sp(self,"uploadEnabled",true); }; if (gs.bool(gs.gp(self,"camera"))) { gs.sp(self,"cameraEnabled",((gs.execStatic(Utils,'isCordova', this,[])) && (gs.bool(gs.gp(self,"camera"))))); }; if (!gs.bool(gs.gp(self,"object")[gs.gp(self,"prop")])) { return gs.sp(self,"previewUrl",gs.gp(self,"placeholderUrl")); }; if (gs.bool(gs.gp(self,"delete"))) { gs.sp(self,"deleteEnabled",true); }; if (gs.bool(gs.gp(self,"download"))) { gs.sp(self,"downloadEnabled",true); }; var fileInfo = gs.gp(self,"object")[gs.gp(self,"prop")]; var lastUpdated = gs.gp(gs.gp(self,"object"),"_lastUpdated"); try { lastUpdated = gs.mc(lastUpdated,"getTime",[]); } catch (all) { } ; if (gs.bool(gs.gp(self,"base64"))) { gs.sp(self,"mediaType","image"); gs.sp(self,"previewUrl",(gs.gp(self,"object")[gs.gp(self,"prop")])); gs.sp(self,"downloadUrl",(gs.gp(self,"object")[gs.gp(self,"prop")])); gs.sp(self,"uploadSpinner",false); return null; }; gs.sp(self,"mediaType",gs.mc(gSobject,"resolveMediaType",[fileInfo, gs.gp(self,"preview")])); var url = "/media-cache/filePreview/" + (gs.gp(gs.gp(self,"object"),"_id")) + "/" + (gs.gp(self,"prop")) + "/" + (lastUpdated) + "/" + (gs.gp(fileInfo,"filename")) + "?"; if (gs.bool(gs.gp(self,"serverWidth"))) { url += (gs.plus("&width=", gs.gp(self,"serverWidth"))); }; if (gs.bool(gs.gp(self,"serverHeight"))) { url += (gs.plus("&height=", gs.gp(self,"serverHeight"))); }; gs.sp(self,"previewUrl",url); gs.sp(self,"downloadUrl","/media-cache/file/" + (gs.gp(gs.gp(self,"object"),"_id")) + "/" + (gs.gp(self,"prop")) + "/" + (lastUpdated) + "/" + (gs.gp(fileInfo,"filename")) + ""); if (gs.mc(gs.gp(fileInfo,"contentType",true),"contains",["svg"])) { gs.sp(self,"previewUrl",gs.gp(self,"downloadUrl")); }; return gs.mc(gSobject,"loadFromBlob",[self]); } gSobject['loadFromBlob'] = function(self) { if (gs.equals(gs.gp(gs.gp(gs.fs('cordovaDevice', this, gSobject),"network"),"status"), "online")) { return null; }; return gs.mc(gs.fs('cordovaFile', this, gSobject),"getBlobFromCachedFile",[gs.mc(gSobject,"objectName",[self]), gs.gp(self,"prop"), gs.gp(gs.gp(self,"object"),"_id"), function(entry) { if ((gs.bool(gs.gp(entry,"blob"))) && (gs.mc(gs.gp(entry,"type"),"startsWith",["image/"]))) { var blob = gs.gp(entry,"blob"); return gs.execStatic(Utils,'blobToDataUrl', this,[blob, function(base64) { gs.sp(self,"previewUrl",base64); gs.sp(self,"downloadUrl",base64); gs.sp(self,"uploadSpinner",false); return gs.mc(gSobject,"refreshImage",[self]); }]); }; }]); } gSobject['refreshImage'] = function(self) { var mediaType = gs.gp(self,"mediaType"); gs.sp(self,"mediaType",""); return gs.mc(gSobject,"nextTick",[function(it) { return gs.sp(self,"mediaType",mediaType); }]); } gSobject['objectName'] = function(self) { if (gs.bool(gs.gp(self,"objectName"))) { return gs.gp(self,"objectName"); }; return gs.mc(gs.gp(gs.gp(self,"object"),"_path"),"split",["/"])[2]; } gSobject['openViewDialog'] = function(it) { var self = this; if (!gs.bool(gs.gp(self,"view"))) { return null; }; if (!gs.bool(gs.mc(gSobject,"fileExists",[self]))) { return null; }; gs.sp(self,"viewDialog",true); return gs.mc(gSobject,"nextTick",[function(it) { if (gs.equals(gs.gp(self,"mediaType"), "pdf")) { return gs.mc(PdfJsHandler(),"build",[gs.gp(self,"downloadUrl"), function(it) { return gs.execStatic(Utils,'setTimeout', this,[function(it) { return PinchToZoomHandler("pdf-viewer", "pdf"); }, 3000]); }]); } else { return PinchToZoomHandler("viewer-id", "image"); }; }]); } gSobject['closeViewDialog'] = function(it) { var self = this; return gs.sp(self,"viewDialog",false); } gSobject['fileExists'] = function(self) { if (self === undefined) self = this; if (!gs.bool(self)) { self = this; }; if (!gs.bool(gs.gp(self,"object"))) { return false; }; return (gs.gp(self,"object")[gs.gp(self,"prop")] ? true : false); } gSobject['downloadFile'] = function(it) { var self = this; return gs.mc(gs.fs('window', this, gSobject),"open",[gs.gp(self,"downloadUrl"), "_system"]); } gSobject['saveFile'] = function(it) { var self = this; gs.sp(self,"uploadSpinner",true); gs.mc(self,"initCallback",[gs.gp(self,"object")]); gs.println("self.embedText()"); gs.println(gs.gp(self,"embedText")); var embedText = ""; if (gs.bool(gs.gp(self,"embedText"))) { embedText = gs.mc(self,"embedText",[]); }; return gs.mc(gs.fs('cordovaFile', this, gSobject),"addFile",[gs.gp(self,"fileToUpload"), gs.mc(gSobject,"objectName",[self]), gs.gp(self,"prop"), gs.gp(gs.gp(self,"object"),"_id"), function(result, blob) { gs.mc(gSobject,"notify",["Media Uploaded"]); gs.sp(self,"uploadSpinner",false); return gs.mc(gSobject,"updateMedia",[self, gs.gp(gs.gp(self,"fileToUpload"),"name"), gs.gp(gs.gp(self,"fileToUpload"),"type")]); }, function(error) { gs.mc(gSobject,"notify",["Your offline. Upload will resume later..."]); return gs.mc(gSobject,"updateMedia",[self, gs.gp(gs.gp(self,"fileToUpload"),"name"), gs.gp(gs.gp(self,"fileToUpload"),"type")]); }]); } gSobject['deleteFile'] = function(it) { var self = this; gs.sp(gs.gp(self,"object"),"_lastUpdated",gs.date()); (gs.gp(self,"object")[gs.gp(self,"prop")]) = null; gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"vueWrapperService"),"deleteFile",[gs.gp(gs.gp(self,"object"),"_id"), gs.gp(self,"prop")]),"do",[]); gs.mc(gs.fs('cordovaFile', this, gSobject),"deleteFile",[gs.mc(gSobject,"objectName",[self]), gs.gp(self,"prop"), gs.gp(gs.gp(self,"object"),"_id")]); gs.mc(gSobject,"init",[self]); return gs.mc(self,"removedCallback",[gs.gp(self,"object")]); } gSobject['startCamera'] = function(it) { var self = this; gs.sp(self,"uploadSpinner",true); gs.mc(self,"initCallback",[gs.gp(self,"object")]); return gs.mc(gs.fs('cordovaCamera', this, gSobject),"takePhotoAndUpload",[gs.mc(gSobject,"objectName",[self]), gs.gp(self,"prop"), gs.gp(gs.gp(self,"object"),"_id"), function(localFile, blob) { gs.mc(gSobject,"notify",["Photo Uploaded"]); gs.sp(self,"uploadSpinner",false); return gs.mc(gSobject,"updateMedia",[self, "blob", gs.gp(localFile,"type")]); }, function(error) { gs.mc(gSobject,"notify",["Photo Upload Failed", "negative"]); return gs.sp(self,"uploadSpinner",false); }]); } gSobject['updateMedia'] = function(self, filename, contentType) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"mediaCacheService"),"deleteCache",[gs.gp(gs.gp(self,"object"),"_id"), gs.gp(self,"prop")]),"do",[]); var fileInfo = gs.map().add("id","" + (gs.gp(gs.gp(self,"object"),"_id")) + "_" + (gs.gp(self,"prop")) + "").add("filename",filename).add("contentType",contentType); gs.sp(gs.gp(self,"object"),"_lastUpdated",gs.date()); (gs.gp(self,"object")[gs.gp(self,"prop")]) = fileInfo; gs.mc(gSobject,"init",[self]); return gs.mc(self,"callback",[gs.gp(self,"object")]); } gSobject['resolveMediaType'] = function(fileInfo, preview) { if ((gs.mc(gs.gp(fileInfo,"contentType",true),"contains",["image"], null, true)) || (gs.bool(preview))) { return "image"; }; if (gs.mc(gs.gp(fileInfo,"contentType",true),"contains",["video"], null, true)) { return "video"; }; if (gs.mc(gs.gp(fileInfo,"contentType",true),"contains",["audio"], null, true)) { return "audio"; }; if (gs.mc(gs.gp(fileInfo,"contentType",true),"contains",["application"], null, true)) { return "pdf"; }; return "image"; } gSobject['resolveAcceptedType'] = function(type) { if (gs.equals(type, "pdf")) { return "application/pdf"; }; if (gs.equals(type, "video")) { return "video/*"; }; if (gs.equals(type, "audio")) { return "audio/*"; }; if (gs.equals(type, "image")) { return "image/*"; }; } gSobject.clearPdfViewer = function() { const element = document.getElementById("pdf-viewer"); while (element.firstChild) { element.removeChild(element.lastChild); } } gSobject['handlePlayback'] = function(it) { var self = this; if (!gs.bool(gs.gp(self,"customControls"))) { return null; }; if (gs.bool(gs.gp(self,"videoEnded"))) { gs.mc(gs.gp(gs.gp(self,"$refs"),"video"),"play",[]); } else { if (gs.bool(gs.gp(self,"videoPlaying"))) { gs.mc(gs.gp(gs.gp(self,"$refs"),"video"),"pause",[]); gs.sp(self,"videoPlaying",false); } else { if (!gs.bool(gs.gp(self,"videoPlaying"))) { gs.mc(gs.gp(gs.gp(self,"$refs"),"video"),"play",[]); gs.sp(self,"videoPlaying",true); }; }; }; return gs.sp(self,"videoEnded",false); } gSobject['playbackEnded'] = function(it) { var self = this; return gs.sp(self,"videoEnded",true); } gSobject['goFullscreen'] = function(it) { var self = this; var video = gs.gp(gs.gp(self,"$refs"),"video"); if (gs.bool(gs.gp(video,"requestFullscreen"))) { return gs.mc(video,"requestFullscreen",[]); }; if (gs.bool(gs.gp(video,"webkitRequestFullscreen"))) { return gs.mc(video,"webkitRequestFullscreen",[]); }; } gSobject['handleMute'] = function(it) { var self = this; if (gs.bool(gs.gp(self,"videoMuted"))) { gs.sp(gs.gp(gs.gp(self,"$refs"),"video"),"muted",false); return gs.sp(self,"videoMuted",false); } else { gs.sp(gs.gp(gs.gp(self,"$refs"),"video"),"muted",true); return gs.sp(self,"videoMuted",true); }; } gSobject['updateImageMetadata'] = function(metadata) { var self = this; return gs.sp(self,"imageMetadata",metadata); } gSobject['hasLocationData'] = function(it) { var self = this; return (gs.gp(gs.gp(self,"imageMetadata"),"latitude",true) != null) && (gs.gp(gs.gp(self,"imageMetadata"),"longitude",true) != null); } gSobject['loadGoogleMapsLink'] = function(it) { var self = this; return "https://www.google.com/maps?q=" + (gs.gp(gs.gp(self,"imageMetadata"),"latitude")) + "," + (gs.gp(gs.gp(self,"imageMetadata"),"longitude")) + ""; } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; I3Media.PREVIEW_LIMIT = gs.multiply((gs.multiply(10, 1024)), 1024); function LandingComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'LandingComponent', simpleName: 'LandingComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/landing"; gSobject['created'] = function(it) { gs.println("Landing.created() v3"); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "landing.startup.page"]),"do",[]); gs.sp(gSobject.scope,"landingPage",true); gs.sp(gSobject.scope,"slide",0); gs.sp(gSobject.scope,"fullscreen",true); gs.mc(gSobject,"showHeader",[false]); gs.mc(gSobject,"showFooter",[false]); return gs.mc(gSobject,"componentTheme",[false]); } gSobject['previousSlide'] = function(it) { if (gs.gp(gSobject.scope,"slide") > 0) { return gs.plusPlus(gSobject.scope,"slide",false,false); }; } gSobject['nextSlide'] = function(it) { if (gs.gp(gSobject.scope,"slide") < (gs.minus(gs.gp(gs.gp(gSobject.scope,"items"),"length"), 1))) { return gs.plusPlus(gSobject.scope,"slide",true,false); } else { return gs.mc(gSobject,"finalSlide",[]); }; } gSobject['finalSlide'] = function(it) { gs.sp(gs.fs('session', this, gSobject),"hasCompletedPreviewScreens",true); return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/"]); } gSobject['goToSignIn'] = function(it) { gs.sp(gs.fs('session', this, gSobject),"hasCompletedPreviewScreens",true); return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/signIn"]); } gSobject['LandingComponent0'] = function(it) { gs.sp(gs.gp(vue,"scope"),"keyboardShowing",false); return this; } if (arguments.length==0) {gSobject.LandingComponent0(); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function ProtocolQNScoreComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'ProtocolQNScoreComponent', simpleName: 'ProtocolQNScoreComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/protocolQNScoreComponent/:questionnaireId" , "/protocolQNScoreComponent/:questionnaireId/:someId"]); gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "protoqol.qn.score"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[false]); gs.mc(gSobject,"componentTheme",[true]); gs.sp(gSobject.scope,"background","#000000"); gs.sp(gSobject.scope,"backgroundGradient","#000000"); gs.sp(gSobject.scope,"backgroundStyle","radial-gradient(circle at center, #000000 0%, #000000 100%)"); gs.sp(gSobject.scope,"score",0); return gs.mc(gSobject,"loadscoreDetails",[]); } gSobject['loadscoreDetails'] = function(it) { gs.sp(gSobject.scope,"scoreMap",gs.map()); gs.sp(gSobject.scope,"toPathOnAfterScore",""); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"loadScoreResult",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gs.gp(gSobject.route,"params"),"questionnaireId"), function(scoreMap) { gs.println("scoreMap"); gs.println(scoreMap); gs.sp(gSobject.scope,"scoreMap",scoreMap); gs.sp(gSobject.scope,"background",gs.elvis(gs.bool(gs.gp(scoreMap,"background")) , gs.gp(scoreMap,"background") , "#000000")); gs.sp(gSobject.scope,"backgroundGradient",gs.elvis(gs.bool(gs.gp(scoreMap,"background_gradient")) , gs.gp(scoreMap,"background_gradient") , gs.gp(gSobject.scope,"background"))); gs.sp(gSobject.scope,"backgroundStyle","radial-gradient(circle at center, " + (gs.gp(gSobject.scope,"backgroundGradient")) + " 0%, " + (gs.gp(gSobject.scope,"background")) + " 100%)"); return gs.sp(gSobject.scope,"toPathOnAfterScore",gs.elvis(gs.bool(gs.gp(scoreMap,"toPathOnAfterScore")) , gs.gp(scoreMap,"toPathOnAfterScore") , "/protocolQNResultComponent/" + (gs.gp(gs.gp(gSobject.route,"params"),"questionnaireId")) + "")); }]); } gSobject['toolbar'] = function(it) { return (!gs.bool(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"showFooter"))) || (!gs.bool(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"keyboardShowing"))); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function HealthMetricsComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'HealthMetricsComponent', simpleName: 'HealthMetricsComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/healthMetrics"; gSobject['created'] = function(it) { gs.sp(gSobject.scope,"metricCardData",gs.map()); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.health.metrics"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); gs.mc(gSobject,"componentTheme",[false]); return gs.mc(gSobject,"loadMetricCardData",[]); } gSobject['loadMetricCardData'] = function(it) { if (gs.bool(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"homeData"))) { return gs.sp(gSobject.scope,"metricCardData",gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"homeData")); } else { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"homeMenu",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(homeData) { return gs.sp(gSobject.scope,"metricCardData",homeData); }]); }; } gSobject['hasData'] = function(menu) { if (gs.bool(gs.gp(menu,"data"))) { return true; }; return false; } gSobject['open'] = function(menu) { if (gs.bool(gs.gp(menu,"data"))) { if (gs.bool(gs.gp(menu,"navPath"))) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",[gs.gp(menu,"navPath")]); }; }; if (!gs.bool(gs.gp(menu,"data"))) { if (gs.bool(gs.gp(menu,"setupPath"))) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",[gs.gp(menu,"setupPath")]); }; }; } gSobject['saveFavorite'] = function(menu) { gs.println(menu); return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"saveFavorite",[gs.gp(menu,"userTrackableId"), gs.gp(menu,"favorite")]),"do",[]); } gSobject['selectAllLabel'] = function(it) { if (!gs.bool(gs.gp(gs.gp(gSobject.scope,"metricCardData"),"menus",true))) { return "Select All"; }; var trackables = gs.mc(gs.gp(gs.gp(gSobject.scope,"metricCardData"),"menus"),"findAll",[function(it) { return gs.equals(gs.gp(it,"type"), "trackable"); }]); if (!gs.bool(trackables)) { return "Select All"; }; return (gs.mc(trackables,"every",[function(it) { return gs.gp(it,"favorite"); }]) ? "Deselect All" : "Select All"); } gSobject['toggleAllFavorites'] = function(it) { if (!gs.bool(gs.gp(gs.gp(gSobject.scope,"metricCardData"),"menus",true))) { return null; }; var trackables = gs.mc(gs.gp(gs.gp(gSobject.scope,"metricCardData"),"menus"),"findAll",[function(it) { return gs.equals(gs.gp(it,"type"), "trackable"); }]); if (!gs.bool(trackables)) { return null; }; var newValue = !gs.mc(trackables,"every",[function(it) { return gs.gp(it,"favorite"); }]); return gs.mc(trackables,"each",[function(menu) { gs.sp(menu,"favorite",newValue); return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"saveFavorite",[gs.gp(menu,"userTrackableId"), newValue]),"do",[]); }]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function SmokingUtilsComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'SmokingUtilsComponent', simpleName: 'SmokingUtilsComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.formatRand = function(val) { if (val == null || val === '' || isNaN(val)) return 'R0.00'; return new Intl.NumberFormat('en-ZA', { style: 'currency', currency: 'ZAR' }).format(val); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function I3Table() { var gSobject = VueComponent(); gSobject.clazz = { name: 'I3Table', simpleName: 'I3Table'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.props = gs.list([]); gSobject.data = function(it) { return gs.list([]); }; gSobject['created'] = function(it) { var self = this; } gSobject['onRequest'] = function(props) { if (props === undefined) props = gs.map(); var self = this; gs.mc(self,"$emit",["paginate", gs.gp(props,"pagination")]); return gs.mc(self,"$emit",["update:pagination", gs.gp(props,"pagination")]); } gSobject['selectRow'] = function(evt, row, index) { var self = this; return gs.mc(self,"$emit",["select-row", gs.gp(row,"_id")]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function GoalCircleComponent() { var gSobject = VueComponent(); gSobject.clazz = { name: 'GoalCircleComponent', simpleName: 'GoalCircleComponent'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.props = gs.map().add("color",String).add("value",Number); gSobject['created'] = function(it) { var self = this; } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function AuditTrailComponent() { var gSobject = VueComponent(); gSobject.clazz = { name: 'AuditTrailComponent', simpleName: 'AuditTrailComponent'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.props = gs.map().add("objectId",String).add("exclude",String); gSobject.data = function(it) { return gs.map().add("auditTrail",gs.list([])).add("columns",gs.list([])); }; gSobject['created'] = function(it) { gs.println("AuditTrailComponent.created()"); var self = this; var fieldRender = function(value) { if (!gs.bool(value)) { return value = ""; }; if (gs.gp(value,"constructor") === Date) { return gs.mc(gs.mc(gSobject,"moment",[value]),"format",["YYYY-MM-DD hh:mm:ss"]); }; return gs.mc(value,"toString",[]); }; gs.sp(self,"columns",gs.list([gs.map().add("name","lastUpdated").add("label","Date").add("field","lastUpdated").add("align","left") , gs.map().add("name","updatedBy").add("label","Updated By").add("field","updatedBy").add("align","left") , gs.map().add("name","propertyName").add("label","Property").add("field","propertyName").add("align","left") , gs.map().add("name","oldValue").add("label","Before").add("field",function(row) { return gs.execCall(fieldRender, this, [gs.gp(row,"oldValue")]); }).add("align","left") , gs.map().add("name","newValue").add("label","After").add("field",function(row) { return gs.execCall(fieldRender, this, [gs.gp(row,"newValue")]); }).add("align","left")])); return gs.mc(gSobject,"init",[self]); } gSobject['watchObject'] = function(it) { var self = this; return gs.mc(gSobject,"init",[self]); } gSobject['init'] = function(self) { gs.sp(self,"exclude",gs.list([])); gs.println("-------------"); gs.println("self.objectId"); gs.println(gs.gp(self,"objectId")); gs.println("self.exclude"); gs.println(gs.gp(self,"exclude")); return gs.mc(gSobject,"loadAuditTrail",[self]); } gSobject['loadAuditTrail'] = function(self) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"auditTrailService"),"loadAuditTrail",[gs.gp(self,"objectId"), gs.list([]), gs.map().add("limit",1000), function(auditTrail) { gs.sp(self,"auditTrail",auditTrail); gs.println("audit trail 2"); return gs.println(auditTrail); }]); } gSobject['exportCsvFile'] = function(it) { var self = this; return gs.execStatic(Utils,'open', this,["/auditTrail/export/" + (gs.gp(self,"objectId")) + "?exclude=" + (gs.gp(self,"exclude")) + ""]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function MoodOverviewComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'MoodOverviewComponent', simpleName: 'MoodOverviewComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/moodOverview"; Object.defineProperty(gSobject, 'monthList', { get: function() { return MoodOverviewComponent.monthList; }, set: function(gSval) { MoodOverviewComponent.monthList = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'moodMapper', { get: function() { return MoodOverviewComponent.moodMapper; }, set: function(gSval) { MoodOverviewComponent.moodMapper = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'moodInsightIconMap', { get: function() { return MoodOverviewComponent.moodInsightIconMap; }, set: function(gSval) { MoodOverviewComponent.moodInsightIconMap = gSval; }, enumerable: true }); gSobject.buildMoodMapperWithIcons = function() { return MoodOverviewComponent.buildMoodMapperWithIcons(); } gSobject.buildMoodMapperForInsight = function() { return MoodOverviewComponent.buildMoodMapperForInsight(); } gSobject['created'] = function(it) { gs.mc(gSobject,"componentTheme",[]); gs.sp(gSobject.scope,"logs",gs.list([])); gs.sp(gSobject.scope,"lastMood",gs.map()); gs.sp(gSobject.scope,"monthDropdown",false); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.mood.overview"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); gs.sp(gSobject.scope,"moodMapper",gs.execStatic(MoodOverviewComponent,'buildMoodMapperWithIcons', this,[])); gs.sp(gSobject.scope,"batchName","medical:score:mood"); gs.sp(gSobject.scope,"months",gs.mc(gSobject,"lastSixMonths",[])); gs.sp(gSobject.scope,"selectedMonth",(gs.gp(gSobject.scope,"months")[0])); gs.sp(gSobject.scope,"reminders",gs.map()); gs.sp(gSobject.scope,"currentStreak",0); gs.sp(gSobject.scope,"lastUpdated",""); gs.mc(gSobject,"loadCalendarSeries",[]); gs.mc(gSobject,"loadLogs",[]); gs.mc(gSobject,"loadReminders",[]); gs.mc(gSobject,"loadStreak",[]); gs.sp(gSobject.scope,"motivationalText",""); gs.sp(gSobject.scope,"motivationLoading",true); gs.mc(gSobject,"loadMotivation",[gs.gp(gs.fs('session', this, gSobject),"userId"), "Mood", function(msg) { gs.sp(gSobject.scope,"motivationalText",msg); return gs.sp(gSobject.scope,"motivationLoading",false); }]); return gs.mc(gSobject,"loadLastUpdated",[gs.gp(gs.fs('session', this, gSobject),"userId"), "mood", function(lastUpdated) { return gs.sp(gSobject.scope,"lastUpdated",lastUpdated); }]); } gSobject['loadStreak'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"moodCurrentStreak",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(streak) { return gs.sp(gSobject.scope,"currentStreak",gs.elvis(gs.bool(streak) , streak , 0)); }]); } gSobject['lastSixMonths'] = function(it) { var dates = gs.list([]); var today = gs.date(); var year = gs.mc(today,"getFullYear",[]); var month = gs.mc(today,"getMonth",[]); gs.mc(gs.range(0, 5, true),"each",[function(i) { var targetDate = gs.execStatic(Utils,'newDate', this,[year, gs.minus(month, i), 1]); return gs.mc(dates,"add",[gs.map().add("date",targetDate).add("month","" + (MoodOverviewComponent.monthList[gs.mc(targetDate,"getMonth",[])]) + " " + (gs.mc(targetDate,"getFullYear",[])) + "").add("monthString",gs.execStatic(Utils,'localDateString', this,[targetDate]))]); }]); return dates; } gSobject['loadLogs'] = function(it) { gs.sp(gSobject.scope,"logs",gs.list([])); gs.sp(gSobject.scope,"lastEntry","None"); gs.sp(gSobject.scope,"lastMood",gs.map().add("label","No mood logged").add("icon",gs.gp(SvgIconsComponent,"iconMap")["overjoyed"])); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"moodOverviewLogs",[gs.gp(gs.fs('session', this, gSobject),"userId"), 7, function(logs) { if ((!gs.bool(logs)) || (gs.equals(gs.mc(logs,"size",[]), 0))) { return null; }; var mappedLogs = gs.mc(logs,"collect",[function(log) { var resolvedMood = gs.mc(gs.gp(gSobject.scope,"moodMapper"),"find",[function(mood) { return gs.equals(gs.gp(mood,"index"), gs.gp(log,"index")); }]); return gs.plus(log, gs.map().add("imgsrc",gs.elvis(gs.bool(gs.gp(resolvedMood,"icon",true)) , gs.gp(resolvedMood,"icon",true) , gs.gp(SvgIconsComponent,"iconMap")["overjoyed"]))); }]); gs.mc(gs.gp(gSobject.scope,"logs"),"addAll",[mappedLogs]); gs.sp(gSobject.scope,"lastEntry",(gs.bool(gs.gp(gs.gp(gSobject.scope,"logs")[0],"_createdAt",true)) ? gs.mc(gs.mc(gSobject,"moment",[gs.gp(gs.gp(gSobject.scope,"logs")[0],"_createdAt")]),"calendar",[]) : "None")); var topLog = gs.gp(gSobject.scope,"logs")[0]; var lastMood = gs.mc(gs.gp(gSobject.scope,"moodMapper"),"find",[function(mood) { return gs.equals(gs.gp(mood,"index"), gs.gp(topLog,"index",true)); }]); return gs.sp(gSobject.scope,"lastMood",gs.elvis(gs.bool(lastMood) , lastMood , gs.map().add("label",gs.elvis(gs.bool(gs.gp(topLog,"value",true)) , gs.gp(topLog,"value",true) , "No mood logged")).add("icon",gs.elvis(gs.bool(gs.gp(topLog,"imgsrc",true)) , gs.gp(topLog,"imgsrc",true) , gs.gp(SvgIconsComponent,"iconMap")["overjoyed"])))); }]); } gSobject['loadCalendarSeries'] = function(it) { gs.sp(gSobject.scope,"calendarSeries",gs.list([])); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"moodCalendar",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gs.gp(gSobject.scope,"selectedMonth"),"monthString"), function(result) { gs.sp(gSobject.scope,"calendarSeries",gs.elvis(gs.bool(gs.gp(result,"series")) , gs.gp(result,"series") , gs.list([]))); return gs.mc(gSobject,"syncCalendarWithLatestMoodLogs",[]); }]); } gSobject['syncCalendarWithLatestMoodLogs'] = function(it) { if ((!gs.bool(gs.gp(gSobject.scope,"calendarSeries"))) || (gs.equals(gs.mc(gs.gp(gSobject.scope,"calendarSeries"),"size",[]), 0))) { return null; }; return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"moodLatestByDay",[gs.gp(gs.fs('session', this, gSobject),"userId"), 180, function(latestMoodByDay) { return gs.mc(gs.gp(gSobject.scope,"calendarSeries"),"each",[function(day) { var dayKey = gs.mc(gs.mc(gSobject,"moment",[gs.gp(day,"date")]),"format",["YYYY-MM-DD"]); return gs.sp(day,"max",gs.elvis(latestMoodByDay[dayKey] , latestMoodByDay[dayKey] , 0)); }]); }]); } gSobject['renderCalendarMood'] = function(day) { var max = Math.round(gs.elvis(gs.bool(gs.gp(day,"max",true)) , gs.gp(day,"max",true) , 0)); if (max < 1) { return gs.gp(SvgIconsComponent,"iconMap")["overjoyed"]; }; var mood = gs.mc(gs.gp(gSobject.scope,"moodMapper"),"find",[function(it) { return gs.equals(gs.gp(it,"index"), max); }]); return gs.elvis(gs.bool(gs.gp(mood,"icon",true)) , gs.gp(mood,"icon",true) , gs.gp(SvgIconsComponent,"iconMap")["overjoyed"]); } gSobject['renderCalendarMoodColor'] = function(day) { var max = Math.round(gs.elvis(gs.bool(gs.gp(day,"max",true)) , gs.gp(day,"max",true) , 0)); if (max < 1) { return "#B9C3C8"; }; var mood = gs.mc(gs.gp(gSobject.scope,"moodMapper"),"find",[function(it) { return gs.equals(gs.gp(it,"index"), max); }]); return gs.elvis(gs.bool(gs.gp(mood,"color",true)) , gs.gp(mood,"color",true) , "#B9C3C8"); } gSobject['loadReminders'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"scheduleService"),"loadTrackable",[gs.gp(gs.fs('session', this, gSobject),"userId"), "Mood", function(schedule) { gs.println(gs.plus((gs.plus((gs.multiply("=", 20)), "SCHEDULE")), (gs.multiply("=", 20)))); gs.println(schedule); return gs.sp(gSobject.scope,"reminders",schedule); }]); } gSobject['selectMonth'] = function(monthItem) { gs.sp(gSobject.scope,"selectedMonth",monthItem); return gs.mc(gSobject,"loadCalendarSeries",[]); } gSobject['handleClick'] = function(it) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/moodInsight"]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; MoodOverviewComponent.buildMoodMapperWithIcons = function(it) { return gs.mc(MoodOverviewComponent.moodMapper,"collect",[function(mood) { return gs.plus(mood, gs.map().add("icon",gs.gp(SvgIconsComponent,"iconMap")[gs.gp(mood,"value")])); }]); } MoodOverviewComponent.buildMoodMapperForInsight = function(it) { return gs.mc(MoodOverviewComponent.moodMapper,"collect",[function(mood) { return gs.plus(mood, gs.map().add("insightIcon",gs.elvis(MoodOverviewComponent.moodInsightIconMap[gs.gp(mood,"value")] , MoodOverviewComponent.moodInsightIconMap[gs.gp(mood,"value")] , "/statics/rxme/images/mood_default.png"))); }]); } MoodOverviewComponent.monthList = gs.list(["January" , "February" , "March" , "April" , "May" , "June" , "July" , "August" , "September" , "October" , "November" , "December"]); MoodOverviewComponent.moodMapper = gs.list([gs.map().add("index",1).add("label","Overjoyed").add("value","overjoyed").add("icon","/statics/mood/images/happy.svg").add("color","#14ba78") , gs.map().add("index",2).add("label","Angry").add("value","angry").add("icon","/statics/mood/images/angry.svg").add("color","#e21f23") , gs.map().add("index",3).add("label","Frustrated").add("value","frustrated").add("icon","/statics/mood/images/frustrated.svg").add("color","#6820b1") , gs.map().add("index",4).add("label","Neutral").add("value","neutral").add("icon","/statics/mood/images/neutral.svg").add("color","#0f177c") , gs.map().add("index",5).add("label","Calm").add("value","calm").add("icon","/statics/mood/images/calm.svg").add("color","#5170ff") , gs.map().add("index",6).add("label","Stressed").add("value","stressed").add("icon","/statics/mood/images/stressed.svg").add("color","#fcb040") , gs.map().add("index",7).add("label","Happy").add("value","happy").add("icon","/statics/mood/images/happy.svg").add("color","#00d3cd") , gs.map().add("index",8).add("label","Sick").add("value","sick").add("icon","/statics/mood/images/sick.svg").add("color","#ff7722") , gs.map().add("index",9).add("label","Unhappy").add("value","unhappy").add("icon","/statics/mood/images/unhappy.svg").add("color","#b840de") , gs.map().add("index",10).add("label","Sad").add("value","sad").add("icon","/statics/mood/images/sad.svg").add("color","#f8519d") , gs.map().add("index",11).add("label","Woozy").add("value","woozy").add("icon","/statics/mood/images/woozy.svg").add("color","#a29bfe")]); MoodOverviewComponent.moodInsightIconMap = gs.map().add("overjoyed","/statics/rxme/images/mood_overjoyed_filled.png").add("angry","/statics/rxme/images/angry_filled.png").add("frustrated","/statics/rxme/images/mood_frustrated_filled.png").add("neutral","/statics/rxme/images/mood_neutral_filled.png").add("calm","/statics/rxme/images/calm_filled.png").add("stressed","/statics/rxme/images/mood_stressed_filled.png").add("happy","/statics/rxme/images/mood_happy_filled.png").add("sick","/statics/rxme/images/mood_default.png").add("unhappy","/statics/rxme/images/sad_filled.png").add("sad","/statics/rxme/images/mood_sad_filled.png").add("woozy","/statics/rxme/images/mood_default.png"); function LogMoodComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'LogMoodComponent', simpleName: 'LogMoodComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/logMood" , "/logMood/:id"]); gSobject['created'] = function(it) { gs.sp(gSobject.scope,"logs",gs.list([])); gs.sp(gSobject.scope,"moodItems",gs.execStatic(MoodOverviewComponent,'buildMoodMapperWithIcons', this,[])); gs.sp(gSobject.scope,"description","Mood and mental wellbeing play a huge role in metabolism, habits, chronic disease, and long-term success. Your emotional state matters to us."); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.mood.log"]),"do",[]); gs.sp(gSobject.scope,"dialog",false); gs.mc(gSobject,"componentTheme",[false]); gs.mc(gSobject,"showHeaderFooter",[false]); gs.sp(gSobject.scope,"selectedMood",(gs.bool(gs.gp(gSobject.scope,"moodItems")) ? gs.gp(gSobject.scope,"moodItems")[0] : null)); gs.sp(gSobject.scope,"entry",gs.map().add("value","").add("status","").add("thoughts","").add("date",gs.mc(gs.mc(gSobject,"moment",[]),"format",["YYYY-MM-DD HH:mm"])).add("ref","mood")); gs.sp(gSobject.scope,"pageBackground",null); if (gs.bool(gs.gp(gs.gp(gSobject.route,"params"),"id"))) { gs.sp(gSobject.scope,"entry",null); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"loadEntry",[gs.gp(gs.gp(gSobject.route,"params"),"id"), function(entry) { var matchedMood = gs.mc(gs.gp(gSobject.scope,"moodItems"),"find",[function(it) { return gs.equals(gs.gp(entry,"value"), gs.gp(it,"index")); }]); gs.sp(gSobject.scope,"selectedMood",gs.gp(matchedMood,"value")); var formatDate = gs.mc(gs.mc(gSobject,"moment",[gs.gp(entry,"date")]),"format",["YYYY-MM-DD HH:mm"]); gs.sp(entry,"date",formatDate); return gs.sp(gSobject.scope,"entry",entry); }]); }; } gSobject['moodUpdate'] = function(mood) { gs.println("[MOOD][moodUpdate] incoming mood payload=" + (mood) + ""); if (!gs.bool(mood)) { return null; }; var resolvedMood = null; if (((gs.gp(mood,"index",true) != null) && (gs.bool(gs.gp(mood,"label",true)))) && (gs.bool(gs.gp(mood,"icon",true)))) { resolvedMood = gs.map().add("index",gs.gp(mood,"index")).add("label",gs.gp(mood,"label")).add("value",gs.gp(mood,"value")).add("icon",gs.gp(mood,"icon")).add("color",gs.gp(mood,"color")); } else { resolvedMood = gs.mc(gs.gp(gSobject.scope,"moodItems"),"find",[function(item) { return ((gs.equals(gs.gp(item,"index"), mood)) || (gs.equals(gs.gp(item,"value"), mood))) || (gs.equals(gs.gp(item,"label"), mood)); }]); }; if (!gs.bool(resolvedMood)) { return null; }; gs.sp(gSobject.scope,"pageBackground",gs.gp(resolvedMood,"color")); gs.sp(gs.gp(gSobject.scope,"entry"),"value",gs.gp(resolvedMood,"index")); gs.sp(gs.gp(gSobject.scope,"entry"),"icon",gs.gp(resolvedMood,"icon")); gs.sp(gs.gp(gSobject.scope,"entry"),"status",gs.gp(resolvedMood,"label")); gs.println("[MOOD][moodUpdate] resolvedMood=" + (resolvedMood) + ""); return gs.println("[MOOD][moodUpdate] entry after update=" + (gs.gp(gSobject.scope,"entry")) + ""); } gSobject['toLogMoodComponent'] = function(it) { if (((gs.gp(gs.gp(gSobject.scope,"selectedMood"),"index",true) != null) && (gs.bool(gs.gp(gs.gp(gSobject.scope,"selectedMood"),"label",true)))) && (gs.bool(gs.gp(gs.gp(gSobject.scope,"selectedMood"),"icon",true)))) { gs.sp(gs.gp(gSobject.scope,"entry"),"value",gs.gp(gs.gp(gSobject.scope,"selectedMood"),"index")); gs.sp(gs.gp(gSobject.scope,"entry"),"icon",gs.gp(gs.gp(gSobject.scope,"selectedMood"),"icon")); gs.sp(gs.gp(gSobject.scope,"entry"),"status",gs.gp(gs.gp(gSobject.scope,"selectedMood"),"label")); }; gs.println("[MOOD][toLogMoodComponent] selectedMood=" + (gs.gp(gSobject.scope,"selectedMood")) + ""); gs.println("[MOOD][toLogMoodComponent] entry before route=" + (gs.gp(gSobject.scope,"entry")) + ""); gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"moodSelectedDebug",gs.gp(gSobject.scope,"selectedMood")); gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"moodEntry",gs.gp(gSobject.scope,"entry")); return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/moodEdit"]); } gSobject['popup'] = function(title, message) { if (title === undefined) title = "Title"; if (message === undefined) message = "Info message"; return gs.mc(gSobject.q,"dialog",[gs.map().add("title",title).add("message",message)]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function MoodEditComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'MoodEditComponent', simpleName: 'MoodEditComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/moodEdit" , "/moodEdit/:id"]); gSobject['created'] = function(it) { gs.mc(gSobject,"componentTheme",[]); gs.sp(gSobject.scope,"moodItems",gs.mc(gs.gp(MoodOverviewComponent,"moodMapper"),"clone",[])); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.mood.edit"]),"do",[]); gs.sp(gSobject.scope,"entry",gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"moodEntry")); gs.sp(gSobject.scope,"today",gs.mc(gs.mc(gSobject,"moment",[]),"format",["YYYY-MM-DD HH:mm"])); gs.sp(gSobject.scope,"showDateTime",false); gs.sp(gSobject.scope,"allowedDates",function(d) { return gs.mc(gs.mc(gSobject,"moment",[d, "YYYY/MM/DD"]),"isSameOrBefore",[gs.mc(gSobject,"moment",[gs.gp(gSobject.scope,"today"), "YYYY/MM/DD"])]); }); gs.sp(gSobject.scope,"dialog",false); if (gs.bool(gs.gp(gs.gp(gSobject.route,"params"),"id"))) { gs.sp(gSobject.scope,"entry",null); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"loadEntry",[gs.gp(gs.gp(gSobject.route,"params"),"id"), function(entry) { var matchedMood = gs.mc(gs.gp(gSobject.scope,"moodItems"),"find",[function(it) { return gs.equals(gs.gp(entry,"value"), gs.gp(it,"index")); }]); gs.sp(gSobject.scope,"selectedMood",gs.gp(matchedMood,"value")); var formatDate = gs.mc(gs.mc(gSobject,"moment",[gs.gp(entry,"date")]),"format",["YYYY-MM-DD HH:mm"]); gs.sp(entry,"date",formatDate); return gs.sp(gSobject.scope,"entry",entry); }]); }; } gSobject['submitMood'] = function(it) { gs.println("[MOOD][submitMood] selectedMoodDebug=" + (gs.gp(gSobject.scope,"selectedMoodDebug")) + ""); gs.println("[MOOD][submitMood] entry before save=" + (gs.gp(gSobject.scope,"entry")) + ""); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:mood:value", gs.gp(gs.gp(gSobject.scope,"entry"),"value")]),"do",[]); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:mood:url", gs.gp(gs.gp(gSobject.scope,"entry"),"icon")]),"do",[]); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:mood:status", gs.gp(gs.gp(gSobject.scope,"entry"),"status")]),"do",[]); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:mood:thoughts", gs.gp(gs.gp(gSobject.scope,"entry"),"thoughts")]),"do",[]); if (gs.bool(gs.gp(gs.gp(gSobject.scope,"entry"),"_id"))) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"deleteEntry",[gs.gp(gs.gp(gSobject.scope,"entry"),"_id")]),"do",[]); }; var date = gs.date(gs.gp(gs.gp(gSobject.scope,"entry"),"date")); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"addEntryWithFts",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:mood", gs.list(["value"]), gs.map().add("value",gs.gp(gs.gp(gSobject.scope,"entry"),"value")).add("status",gs.gp(gs.gp(gSobject.scope,"entry"),"status")).add("icon",gs.gp(gs.gp(gSobject.scope,"entry"),"icon")).add("thoughts",gs.gp(gs.gp(gSobject.scope,"entry"),"thoughts")).add("date",date)]),"then",[function(it) { gs.println("[MOOD][submitMood] addEntryWithFts success entry=" + (gs.gp(gSobject.scope,"entry")) + ""); gs.mc(gSobject,"updateHomeMoodSnapshot",[]); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"eventListener",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gSobject.scope,"entry")]),"do",[]); gs.mc(gSobject,"saveLastUpdated",[gs.gp(gs.fs('session', this, gSobject),"userId"), "mood"]); return gs.sp(gSobject.scope,"dialog",true); }, function(error) { gs.println("[MOOD][submitMood] addEntryWithFts error=" + (error) + ""); return gs.sp(gSobject.scope,"dialog",true); }]); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"notificationService"),"removeNotification",[gs.gp(gs.fs('session', this, gSobject),"userId"), "trackable:Mood", "Mood"]),"do",[]); return gs.mc(gSobject,"generateAndSaveMotivation",[gs.gp(gs.fs('session', this, gSobject),"userId"), "Mood", "medical:score:mood:value"]); } gSobject['updateHomeMoodSnapshot'] = function(it) { var homeData = gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"homeData"); if (!gs.bool(gs.gp(homeData,"menus",true))) { return null; }; var moodMenu = gs.mc(gs.gp(homeData,"menus"),"find",[function(it) { return (gs.equals(gs.gp(it,"dataPoint",true), "medical:score:mood")) || (gs.equals(gs.gp(it,"name",true), "Mood")); }]); if (!gs.bool(moodMenu)) { return null; }; if (!gs.bool(gs.gp(moodMenu,"data"))) { gs.sp(moodMenu,"data",gs.map()); }; gs.sp(gs.gp(moodMenu,"data"),"status",gs.gp(gs.gp(gSobject.scope,"entry"),"status",true)); gs.sp(gs.gp(moodMenu,"data"),"value",""); return gs.sp(gs.gp(moodMenu,"data"),"valueUrl",gs.gp(gs.gp(gSobject.scope,"entry"),"icon",true)); } gSobject['eventLogMood'] = function(it) { return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"eventLogService"),"event",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.fs('narrative', this, gSobject), "mood", "info"]),"do",[]); } gSobject['popup'] = function(title, message) { if (title === undefined) title = "Title"; if (message === undefined) message = "Info message"; return gs.mc(gSobject.q,"dialog",[gs.map().add("title",title).add("message",message)]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function MoodInsightComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'MoodInsightComponent', simpleName: 'MoodInsightComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/moodInsight"; gSobject.moodMapper = gs.mc(gs.gp(MoodOverviewComponent,"moodMapper"),"clone",[]); gSobject['created'] = function(it) { gs.mc(gSobject,"componentTheme",[]); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.mood.insight"]),"do",[]); gs.sp(gSobject.scope,"moodMapper",gs.execStatic(MoodOverviewComponent,'buildMoodMapperWithIcons', this,[])); return gs.mc(gSobject,"loadCalendarSeries",[]); } gSobject['loadCalendarSeries'] = function(it) { var mapper = gs.elvis(gs.bool(gs.gp(gSobject.scope,"moodMapper")) , gs.gp(gSobject.scope,"moodMapper") , gs.list([])); if ((!gs.bool(mapper)) || (gs.equals(gs.mc(mapper,"size",[]), 0))) { return null; }; var cutoff = gs.mc(gs.mc(gs.mc(gSobject,"moment",[]),"subtract",[30, "days"]),"startOf",["day"]); gs.sp(gSobject.scope,"mostLoggedMood",(gs.mc(gs.mc(mapper[0],"clone",[]),'leftShift', gs.list([gs.map().add("totalCount",0)])))); gs.sp(gSobject.scope,"max",0); gs.mc(mapper,"each",[function(mood) { gs.sp(mood,"totalCount",0); return gs.sp(mood,"barWidth","0%"); }]); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"listEntries",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:mood", gs.map().add("sort","date").add("order","desc").add("limit",500), function(entries) { gs.mc(entries,"each",[function(entry) { var logDate = gs.elvis(gs.bool(gs.gp(entry,"date",true)) , gs.gp(entry,"date",true) , gs.gp(entry,"_dateCreated",true)); if (!gs.bool(logDate)) { return null; }; var mDate = gs.mc(gSobject,"moment",[logDate]); if ((!gs.bool(gs.mc(mDate,"isValid",[], null, true))) || (gs.mc(mDate,"isBefore",[cutoff]))) { return null; }; var moodIndex = gs.mc(gSobject,"resolveMoodIndex",[entry, mapper]); if (gs.equals(moodIndex, null)) { return null; }; var mood = gs.mc(mapper,"find",[function(it) { return gs.equals(gs.gp(it,"index"), moodIndex); }]); if (gs.bool(mood)) { return gs.sp(mood,"totalCount",(gs.plus(gs.elvis(gs.bool(gs.gp(mood,"totalCount")) , gs.gp(mood,"totalCount") , 0), 1))); }; }], null, true); var ranked = gs.mc(mapper,"sort",[function(a, b) { var countCompare = gs.spaceShip(gs.elvis(gs.bool(gs.gp(b,"totalCount")) , gs.gp(b,"totalCount") , 0), gs.elvis(gs.bool(gs.gp(a,"totalCount")) , gs.gp(a,"totalCount") , 0)); if (countCompare != 0) { return countCompare; }; return gs.spaceShip(gs.elvis(gs.bool(gs.gp(a,"index")) , gs.gp(a,"index") , 999), gs.elvis(gs.bool(gs.gp(b,"index")) , gs.gp(b,"index") , 999)); }]); gs.sp(gSobject.scope,"max",(gs.bool(ranked) ? gs.elvis(gs.bool(gs.gp(ranked[0],"totalCount")) , gs.gp(ranked[0],"totalCount") , 0) : 0)); gs.sp(gSobject.scope,"mostLoggedMood",(gs.gp(gSobject.scope,"max") > 0 ? ranked[0] : gs.map().add("label","No mood logged").add("value","none").add("totalCount",0))); gs.mc(mapper,"each",[function(mood) { gs.sp(mood,"barWidth",gs.mc(gSobject,"insightBarWidth",[mood])); if (gs.elvis(gs.bool(gs.gp(mood,"totalCount")) , gs.gp(mood,"totalCount") , 0) > 0) { return gs.println("[MOOD][insight] " + (gs.gp(mood,"label")) + " count=" + (gs.gp(mood,"totalCount")) + " width=" + (gs.gp(mood,"barWidth")) + ""); }; }]); return gs.println("[MOOD][insight] mostLogged=" + (gs.gp(gs.gp(gSobject.scope,"mostLoggedMood"),"label",true)) + " count=" + (gs.gp(gs.gp(gSobject.scope,"mostLoggedMood"),"totalCount",true)) + ""); }]); } gSobject['resolveMoodIndex'] = function(entry, mapper) { var numericValue = null; try { numericValue = ((gs.gp(entry,"value",true) != null) && (gs.mc(gs.mc(gs.gp(entry,"value"),"toString",[]),"trim",[]) != "") ? Math.round(gs.gp(entry,"value")) : null); } catch (all) { numericValue = null; } ; if ((numericValue != null) && (gs.mc(mapper,"find",[function(it) { return gs.equals(gs.gp(it,"index"), numericValue); }]))) { return numericValue; }; var status = gs.mc(gs.mc(gs.gp(entry,"status",true),"toString",[], null, true),"toLowerCase",[], null, true); if (gs.bool(status)) { var moodFromStatus = gs.mc(mapper,"find",[function(it) { return (gs.equals(gs.mc(gs.gp(it,"label"),"toLowerCase",[], null, true), status)) || (gs.equals(gs.mc(gs.gp(it,"value"),"toLowerCase",[], null, true), status)); }]); if (gs.bool(moodFromStatus)) { return gs.gp(moodFromStatus,"index"); }; }; return null; } gSobject['insightBarWidth'] = function(item) { var count = gs.elvis(gs.bool(gs.gp(item,"totalCount",true)) , gs.gp(item,"totalCount",true) , 0); var maxCount = gs.elvis(gs.bool(gs.gp(gSobject.scope,"max")) , gs.gp(gSobject.scope,"max") , 0); if ((count <= 0) || (maxCount <= 0)) { return "0%"; }; var pct = Math.round(gs.multiply((gs.div(count, maxCount)), 100)); if (pct < 18) { pct = 18; }; return "" + (pct) + "%"; } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function ConsentManagerComponent() { var gSobject = VueComponent(); gSobject.clazz = { name: 'ConsentManagerComponent', simpleName: 'ConsentManagerComponent'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.path = "/consentManager"; gSobject['created'] = function(it) { gs.println("ConsentManagerComponent.created()"); gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"pageTitle","Consent Manager"); gs.sp(gSobject.scope,"agreements",gs.list([])); gs.sp(gSobject.scope,"filter",gs.map()); gs.sp(gSobject.scope,"pagination",gs.map().add("page",1).add("rowsPerPage",10).add("rowsNumber",0).add("sortBy","_lastUpdated").add("descending",false)); gs.sp(gSobject.scope,"columns",gs.list([gs.map().add("name","title").add("label","Title").add("field","title").add("align","left").add("sortable",true) , gs.map().add("name","type").add("label","Type").add("field","type").add("align","left").add("sortable",true) , gs.map().add("name","version").add("label","Version").add("field","version").add("align","left").add("sortable",true) , gs.map().add("name","active").add("label","Active").add("field","active").add("align","left").add("sortable",true)])); return gs.mc(gSobject,"loadAgreements",[]); } gSobject['loadAgreements'] = function(callback) { if (callback === undefined) callback = function(it) { }; gs.mc(gSobject,"showLoading",[]); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"agreement"),"findAll",[function(data) { gs.mc(gSobject,"hideLoading",[]); gs.sp(gSobject.scope,"agreements",data); gs.sp(gs.gp(gSobject.scope,"pagination"),"rowsNumber",gs.gp(data,"totalRows")); return gs.execCall(callback, this, []); }]); } gSobject['addAgreement'] = function(it) { var prompt = gs.map().add("model","").add("filled",true); return gs.mc(gs.mc(gSobject.q,"dialog",[gs.map().add("title","Agreement Name").add("prompt",prompt).add("cancel",true)]),"onOk",[function(name) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"agreement"),"create",[name, function(it) { return gs.mc(gSobject,"loadAgreements",[function(it) { return gs.mc(gSobject,"notify",["" + (name) + " Created"]); }]); }]); }]); } gSobject['updatePagination'] = function(pagination) { gs.sp(gSobject.scope,"pagination",pagination); return gs.mc(gSobject,"loadAgreements",[]); } gSobject['selectAgreement'] = function(id) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/consentDetail/" + (id) + ""]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function CordovaBrowser() { var gSobject = gs.init('CordovaBrowser'); gSobject.clazz = { name: 'CordovaBrowser', simpleName: 'CordovaBrowser'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject['openInApp'] = function(url, options) { if (options === undefined) options = gs.map(); if (!gs.bool(CordovaBrowser.browserInstalled())) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["CordovaBrowser: InAppBrowser not installed"]); return null; }; try { return gs.mc(gs.gp(gs.fs('cordova', this, gSobject),"InAppBrowser"),"open",[url, "_blank", gs.mc(gSobject,"optionsString",[options])]); } catch (e) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["openInApp: " + (gs.fs('e', this, gSobject)) + ""]); return null; } ; } gSobject['openSystem'] = function(url) { if (!gs.bool(CordovaBrowser.browserInstalled())) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["CordovaBrowser: InAppBrowser not installed"]); return null; }; try { return gs.mc(gs.gp(gs.fs('cordova', this, gSobject),"InAppBrowser"),"open",[url, "_system"]); } catch (e) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["openSystem: " + (gs.fs('e', this, gSobject)) + ""]); return null; } ; } gSobject['openHidden'] = function(url, onLoad) { if (onLoad === undefined) onLoad = function(it) { }; if (!gs.bool(CordovaBrowser.browserInstalled())) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["CordovaBrowser: InAppBrowser not installed"]); return null; }; try { var ref = gs.mc(gs.gp(gs.fs('cordova', this, gSobject),"InAppBrowser"),"open",[url, "_blank", "hidden=yes"]); gs.mc(ref,"addEventListener",["loadstop", function(event) { gs.execCall(onLoad, this, [event]); try { gs.mc(ref,"close",[]); } catch (e2) { } ; }]); gs.mc(ref,"addEventListener",["loaderror", function(event) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["openHidden loaderror: " + (event) + ""]); try { gs.mc(ref,"close",[]); } catch (e2) { } ; }]); return ref; } catch (e) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["openHidden: " + (gs.fs('e', this, gSobject)) + ""]); return null; } ; } gSobject['open'] = function(url, target, options) { if (target === undefined) target = "_blank"; if (options === undefined) options = gs.map(); if (!gs.bool(CordovaBrowser.browserInstalled())) { return null; }; try { return gs.mc(gs.gp(gs.fs('cordova', this, gSobject),"InAppBrowser"),"open",[url, target, gs.mc(gSobject,"optionsString",[options])]); } catch (e) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["open: " + (gs.fs('e', this, gSobject)) + ""]); return null; } ; } gSobject['optionsString'] = function(opts) { if ((gs.equals(opts, null)) || ((gs.instanceOf(opts, "Map")) && (gs.mc(opts,"isEmpty",[])))) { return ""; }; if (gs.instanceOf(opts, "String")) { return opts; }; var parts = gs.list([]); gs.mc(opts,"each",[function(k, v) { return gs.mc(parts,"add",["" + (k) + "=" + (v) + ""]); }]); return gs.mc(parts,"join",[","]); } gSobject.browserInstalled = function() { return CordovaBrowser.browserInstalled(); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; CordovaBrowser.browserInstalled = function() { return typeof cordova !== 'undefined' && typeof cordova.InAppBrowser !== 'undefined'; } function CordovaBiometrics() { var gSobject = gs.init('CordovaBiometrics'); gSobject.clazz = { name: 'CordovaBiometrics', simpleName: 'CordovaBiometrics'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.disableBackup = false; gSobject.requireStrongBiometrics = false; gSobject.storeKeyName = "com.i3"; gSobject['deviceHasBiometrics'] = function(onSuccess, onError, opts) { if (onError === undefined) onError = function(it) { }; if (opts === undefined) opts = gs.map().add("requireStrongBiometrics",gSobject.requireStrongBiometrics); return gs.mc(gs.fs('Fingerprint', this, gSobject),"isAvailable",[onSuccess, onError, opts]); } gSobject['showBiometricDialog'] = function(onSuccess, onError, params) { if (onError === undefined) onError = function(it) { }; if (params === undefined) params = gs.map().add("title","Biometric Sign On").add("description","Authenticate").add("subtitle","").add("disableBackup",gSobject.disableBackup).add("requireStrongBiometrics",gSobject.requireStrongBiometrics).add("keyName",gSobject.storeKeyName); return gs.mc(gs.fs('Fingerprint', this, gSobject),"show",[params, onSuccess, onError]); } gSobject['registerSecret'] = function(secret, onSuccess, onError, params) { if (onError === undefined) onError = function(it) { }; if (params === undefined) params = gs.map().add("description","Register new biometric").add("invalidateOnEnrollment",true).add("disableBackup",gSobject.disableBackup).add("keyName",gSobject.storeKeyName); gs.sp(params,"secret",secret); return gs.mc(gs.fs('Fingerprint', this, gSobject),"registerBiometricSecret",[params, onSuccess, onError]); } gSobject['loadSecret'] = function(onSuccess, onError, params) { if (onError === undefined) onError = function(it) { }; if (params === undefined) params = gs.map().add("description","Load biometrics").add("disableBackup",gSobject.disableBackup).add("keyName",gSobject.storeKeyName); return gs.mc(gs.fs('Fingerprint', this, gSobject),"loadBiometricSecret",[params, onSuccess, onError]); } gSobject['deleteSecret'] = function(onSuccess, onError, params) { if (onSuccess === undefined) onSuccess = function(it) { }; if (onError === undefined) onError = function(it) { }; if (params === undefined) params = gs.map().add("keyName",gSobject.storeKeyName); return gs.mc(gs.fs('Fingerprint', this, gSobject),"deleteBiometricSecret",[params, onSuccess, onError]); } gSobject.verifyBiometricsPlugin = function() { return CordovaBiometrics.verifyBiometricsPlugin(); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; CordovaBiometrics.verifyBiometricsPlugin = function() { return ( window?.Fingerprint !== undefined) } function RecordComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'RecordComponent', simpleName: 'RecordComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/record"; gSobject['created'] = function(it) { gs.println("RecordComponent.created()"); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "record.landing.page"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); gs.sp(gSobject.scope,"scores",gs.list([44])); gs.sp(gSobject.scope,"graphs",gs.list([gs.list(["weight_circumference_health:weight" , "MY WEIGHT"]) , gs.list(["score_bmi_score:bmi" , "BMI"])])); gs.sp(gSobject.scope,"weigth",65); gs.sp(gSobject.scope,"caloriesConsumed",648); gs.sp(gSobject.scope,"caloriesTarget",2500); gs.sp(gSobject.scope,"caloriesTotal",2181); gs.sp(gSobject.scope,"macros",gs.list([gs.map().add("name","Protein").add("consumed",23).add("target",72) , gs.map().add("name","Fat").add("consumed",15).add("target",20) , gs.map().add("name","Carbs").add("consumed",125).add("target",220)])); gs.sp(gSobject.scope,"statusMessage","You’re on track for your calorie goal today! Keep it up, okay!"); gs.sp(gSobject.scope,"activityType","WALKING"); gs.sp(gSobject.scope,"dateTime","Jun 25, 10:00 AM - 10:30 AM"); gs.sp(gSobject.scope,"duration","30 min"); gs.sp(gSobject.scope,"avgBpm","108 avg bpm"); gs.sp(gSobject.scope,"calories","128 kcal"); gs.sp(gSobject.scope,"score","+3 score"); gs.sp(gSobject.scope,"activityIcon","directions_walk"); gs.sp(gSobject.scope,"completedActivities",2); gs.sp(gSobject.scope,"totalActivities",5); gs.sp(gSobject.scope,"sleepHrs",5); gs.sp(gSobject.scope,"sleepMins",25); gs.sp(gSobject.scope,"sleepScore",25); gs.sp(gSobject.scope,"sleepMsg","You had a positive sleep last night."); gs.sp(gSobject.scope,"sleepData",gs.list([gs.map().add("label","CORE").add("time","41m").add("color","brown-3").add("progress",0.8) , gs.map().add("label","DEEP").add("time","1h 55m").add("color","grey-6").add("progress",0.7) , gs.map().add("label","POST").add("time","59m").add("color","teal-6").add("progress",0.5) , gs.map().add("label","WAKE").add("time","1h 44m").add("color","light-green-4").add("progress",0.1)])); gs.sp(gSobject.scope,"currentValue",null); gs.sp(gSobject.scope,"min",0); gs.sp(gSobject.scope,"max",170); gs.sp(gSobject.scope,"progress",0.95); gs.sp(gSobject.scope,"status","Excellent"); gs.sp(gSobject.scope,"showPopup",true); gs.sp(gSobject.scope,"healthMetrics",gs.list([gs.map().add("title","PHYSICAL HEALTH").add("status","Excellent").add("icon","medical_services").add("progress",0.9).add("color","brown").add("description","Optimal physical health") , gs.map().add("title","MENTAL HEALTH").add("status","Bad").add("icon","psychology").add("progress",0.3).add("color","teal").add("description","Needs a few improvement") , gs.map().add("title","Nutrition").add("status","Good").add("icon","eco").add("progress",0.75).add("color","brown").add("description","You are on track") , gs.map().add("title","Activity Level").add("status","Decent").add("icon","directions_run").add("progress",0.4).add("color","brown").add("description","2 out of 5 activity this week") , gs.map().add("title","Sleep Level").add("status","Insomniac").add("icon","bedtime").add("progress",0.2).add("color","teal").add("description","Critical improvement needed")])); gs.sp(gSobject.scope,"recommendations",gs.list([gs.map().add("image","").add("category","Hydration").add("title","BOOST HYDRATION").add("description","Increase your daily water intake by drinking one extra glass of water daily").add("intake","2,500ml water intake daily").add("score","2 Score Increase").add("icon_1","").add("icon_2","") , gs.map().add("image","").add("category","Activity").add("title","GET ACTIVE, STAY FIT!").add("description","Incorporate leafy greens into at least one meal per day.").add("intake","5 servings of vegetables daily").add("score","3 Score Increase").add("icon_1","").add("icon_2","") , gs.map().add("image","").add("category","Sleep").add("title","MOVE MORE").add("description","Engage in at least 30 minutes of physical activity daily.").add("intake","10,000 steps per day").add("score","5 Score Increase").add("icon_1","").add("icon_2","")])); gs.mc(gSobject,"loadGraphs",[]); return gs.mc(gSobject,"loadScores",[]); } gSobject['handlePopupClick'] = function(it) { return gs.sp(gSobject.scope,"showPopup",false); return gs.mc(gs.fs('console', this, gSobject),"log",["Popup button clicked!"]); } gSobject['remainingActivities'] = function(it) { return gs.minus(gs.gp(gSobject.scope,"totalActivities"), gs.gp(gSobject.scope,"completedActivities")); } gSobject['circleDashArray'] = function(it) { var percentage = gs.multiply((gs.div(gs.gp(gSobject.scope,"caloriesTotal"), gs.gp(gSobject.scope,"caloriesTarget"))), 440); return "" + (percentage) + ", 440"; } gSobject['handleWeightChange'] = function(newWeight) { return gs.sp(gSobject.scope,"weigth",newWeight); } gSobject['loadScores'] = function(it) { gs.sp(gSobject.scope,"healthScore",0); gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"loadScore",[gs.gp(gs.gp(gs.fs('session', this, gSobject),"user"),"_id"), "health:score:main", function(data) { return gs.sp(gSobject.scope,"healthScore",gs.elvis(gs.bool(data) , data , 50)); }]); gs.sp(gSobject.scope,"bmiScore",0); gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"loadScore",[gs.gp(gs.gp(gs.fs('session', this, gSobject),"user"),"_id"), "health:score:bmi", function(data) { return gs.sp(gSobject.scope,"bmiScore",gs.elvis(gs.bool(data) , data , 0)); }]); gs.sp(gSobject.scope,"dietaryScore",0); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"loadScore",[gs.gp(gs.gp(gs.fs('session', this, gSobject),"user"),"_id"), "health:score:dietary", function(data) { gs.println("data"); gs.println(data); return gs.sp(gSobject.scope,"dietaryScore",gs.elvis(gs.bool(data) , data , 1)); }]); } gSobject['loadGraphs'] = function(it) { return gs.mc(gs.gp(gSobject.scope,"graphs"),"each",[function(item) { return gs.mc(gSobject,"loadGraph",[item[0], true, function(it) { return gs.println("" + (item) + " loaded"); }]); }]); } gSobject['loadGraph'] = function(name, newGraph) { if (newGraph === undefined) newGraph = false; return gs.mc(gSobject,"nextTick",[function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"loadTimelineMetrics",[gs.gp(gs.gp(gs.fs('session', this, gSobject),"user"),"_id"), name, function(data) { var labels = gs.gp(data,"labels"); var values = gs.gp(data,"aggAvgValues"); if (gs.bool(newGraph)) { return gs.execStatic(RecordComponent,'paintGraph', this,[name, labels, values]); } else { return gs.execStatic(RecordComponent,'updateData', this,[name, labels, values]); }; }]); }]); } gSobject['navigateToScore'] = function(score) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/score"]); } gSobject.updateData = function(x0,x1,x2) { return RecordComponent.updateData(x0,x1,x2); } gSobject.paintGraph = function(x0,x1,x2,x3) { return RecordComponent.paintGraph(x0,x1,x2,x3); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; RecordComponent.updateData = function(graphId, graphLabels, dataSet) { let chart = Chart.getChart(graphId); chart.data.datasets[0].data = gs.toJavascript(dataSet) chart.data.labels = gs.toJavascript(graphLabels) chart.update() } RecordComponent.paintGraph = function(graphId, graphLabels, dataSet, type) { if (type === undefined) type = "line"; const oldChart = Chart.getChart(graphId) if (oldChart != undefined) oldChart.destroy() const data = { labels: gs.toJavascript(graphLabels), datasets: [{ data: gs.toJavascript(dataSet), borderColor: Quasar.getCssVar('accent'), tension: 0.1, pointStyle: false, pointRadius: 0, }] } const options = { scales: { y: { max: 120, beginAtZero: true, grid: { display: false }, ticks: { display: false }, }, x: { grid: { display: false }, ticks: { display: false }, }, }, plugins: { legend: { display: false }, }, animation: true, responsive: true, } const config = { type: type, data: data, options: options, } const myChart = new Chart( document.getElementById(graphId), config) } function MoveToStateComponent() { var gSobject = VueComponent(); gSobject.clazz = { name: 'MoveToStateComponent', simpleName: 'MoveToStateComponent'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.path = "/moveToStateComponent/:questName/:stateName"; gSobject.roles = gs.list(["ROLE_USER"]); gSobject['created'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"moveToState",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gs.gp(gSobject.route,"params"),"questName"), gs.gp(gs.gp(gSobject.route,"params"),"stateName"), function(it) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/"]); }]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function ResourceShortsComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'ResourceShortsComponent', simpleName: 'ResourceShortsComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/resourceShorts"; gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "resource.shorts.page"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); return gs.mc(gSobject,"componentTheme",[false]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function BloodTestComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'BloodTestComponent', simpleName: 'BloodTestComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/bloodTest"]); gSobject['created'] = function(it) { gs.println("BloodTestComponent.created()"); gs.mc(gSobject,"showHeaderFooter",[]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"batches",gs.list([])); gs.sp(gSobject.scope,"loading",true); return gs.mc(gSobject,"loadBloodResults",[]); } gSobject['loadBloodResults'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeApiDataService"),"loadBloodTestPDFs",[function(results) { if (!gs.bool(results)) { gs.sp(gSobject.scope,"batches",gs.list([])); gs.sp(gSobject.scope,"loading",false); return null; }; gs.sp(gSobject.scope,"batches",results); return gs.sp(gSobject.scope,"loading",false); }]); } gSobject['formatCaption'] = function(batch) { var date = gs.mc(gSobject,"formatDate",[gs.gp(batch,"dateReceived")]); var total = gs.elvis(gs.bool(gs.gp(batch,"total")) , gs.gp(batch,"total") , 0); return "" + (date) + " · " + (total) + " PDF" + ((gs.equals(total, 1) ? "" : "s")) + ""; } gSobject['formatDate'] = function(date) { if (!gs.bool(date)) { return "Invalid date"; }; return gs.mc(gs.mc(gSobject,"moment",[date]),"format",["YYYY-MM-DD"]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function I3Input() { var gSobject = VueComponent(); gSobject.clazz = { name: 'I3Input', simpleName: 'I3Input'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.props = gs.map().add("modelValue",gs.map().add("type",String).add("default","")).add("rules",gs.map().add("type",Array).add("default",gs.list([]))).add("mask",gs.map().add("type",String).add("default","")).add("beforeIcon",gs.map().add("type",String).add("default","")).add("prependIcon",gs.map().add("type",String).add("default","")).add("appendIcon",gs.map().add("type",String).add("default","")).add("afterIcon",gs.map().add("type",String).add("default","")).add("prependBtn",gs.map().add("type",String).add("default","")).add("appendBtn",gs.map().add("type",String).add("default","")); gSobject.defaults = gs.map().add("filled",true).add("dense",false).add("outlined",false).add("rounded",false).add("borderless",false).add("square",false).add("dense",true).add("debounce","500"); gSobject.validationRules = gs.map().add("ruleRequired",function(val) { return gs.mc(gSobject,"ruleRequired",[val]); }).add("ruleEmail",function(val) { return gs.mc(gSobject,"ruleEmail",[val]); }).add("rulePassword",function(val) { return gs.mc(gSobject,"rulePassword",[val]); }).add("rulePhone",function(val) { return gs.mc(gSobject,"rulePhone",[val]); }); gSobject.data = function(it) { return gs.list([]); }; gSobject['created'] = function(it) { var self = this; var appConfig = gs.elvis(gs.bool(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"appConfig")) , gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"appConfig") , gs.map()); var config = (gs.gp(appConfig,"input") != null ? gs.gp(appConfig,"input") : gs.map()); var attrs = (gs.gp(self,"$attrs") != null ? gs.gp(self,"$attrs") : gs.map()); return gs.sp(self,"inputProps",gs.toJavascript(gs.plus((gs.plus(gSobject.defaults, config)), attrs))); } gSobject['update'] = function(val) { var self = this; gs.mc(self,"$emit",["update:modelValue", val]); return gs.mc(self,"$emit",["change"]); } gSobject['onAppendBtnClick'] = function(it) { var self = this; return gs.mc(self,"$emit",["append:click"]); } gSobject['onPrependBtnClick'] = function(it) { var self = this; return gs.mc(self,"$emit",["prepend:click"]); } gSobject['ruleRequired'] = function(val) { return (gs.mc(gs.mc(val,"toString",[], null, true),"trim",[], null, true) ? true : "Field Required"); } gSobject['ruleEmail'] = function(val) { var emailPattern = "^(?=[a-zA-Z0-9@._%+-]{6,254}$)[a-zA-Z0-9._%+-]{1,64}@(?:[a-zA-Z0-9-]{1,63}\.){1,8}[a-zA-Z]{2,63}$"; return (gs.exactMatch(val,emailPattern) ? true : "Invalid Email"); } gSobject['rulePassword'] = function(val) { return (gs.mc(gs.mc(gs.mc(val,"toString",[]),"trim",[]),"size",[]) >= 6 ? true : "Password Error Message"); } gSobject['rulePhone'] = function(val) { if (!gs.bool(gs.mc(gs.mc(val,"toString",[], null, true),"trim",[], null, true))) { return true; }; var cleaned = gs.mc(gs.mc(gs.mc(gs.mc(gs.mc(gs.mc(val,"toString",[]),"trim",[]),"replace",[" ", ""]),"replace",["-", ""]),"replace",["(", ""]),"replace",[")", ""]); if (gs.mc(cleaned,"startsWith",["+"])) { var digits = gs.mc(cleaned,"substring",[1]); return (gs.exactMatch(digits,/^[0-9]{7,15}$/) ? true : "Invalid Phone Number"); }; if (gs.mc(cleaned,"startsWith",["0"])) { return (gs.exactMatch(cleaned,/^[0-9]{10}$/) ? true : "Invalid Phone Number"); }; return "Invalid Phone Number"; } gSobject['calcRules'] = function(rules) { return (gs.bool(rules) ? gs.mc(rules,"collect",[function(ruleName) { return gSobject.validationRules[ruleName]; }]) : gs.list([])); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function RxmeHealthSyncJsService() { var gSobject = gs.init('RxmeHealthSyncJsService'); gSobject.clazz = { name: 'RxmeHealthSyncJsService', simpleName: 'RxmeHealthSyncJsService'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject['runSync'] = function(it) { } gSobject['syncHealthApi'] = function(onComplete) { if (onComplete === undefined) onComplete = null; return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:sync:enabled", function(syncEnabled) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["syncHealthApi: Got sync enabled setting = " + (syncEnabled) + ""]); return gs.mc(gs.fs('cordovaHealth', this, gSobject),"testIsAvailable",[function(available) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["syncHealthApi: Health API available = " + (available) + ""]); if ((gs.bool(available)) && (gs.bool(gs.gp(gs.fs('session', this, gSobject),"userId")))) { try { if (gs.equals(syncEnabled, null)) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["syncHealthApi: syncEnabled is null, prompting user"]); gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"requestHealthSync",true); if (gs.bool(onComplete)) { gs.execCall(onComplete, this, [true]); }; } else { if (gs.equals(syncEnabled, true)) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["syncHealthApi: syncEnabled is true, starting sync"]); gs.mc(gSobject,"checkPermissions",[onComplete]); } else { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["syncHealthApi: syncEnabled is false, doing nothing"]); if (gs.bool(onComplete)) { gs.execCall(onComplete, this, [true]); }; }; }; } catch (e) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["syncHealthApi: Error in conditional block: " + (gs.fs('e', this, gSobject)) + ""]); if (gs.bool(onComplete)) { gs.execCall(onComplete, this, [false]); }; } ; } else { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["syncHealthApi: Health API not available"]); if (gs.bool(onComplete)) { return gs.execCall(onComplete, this, [false]); }; }; }, function(err) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["syncHealthApi: IsAvailable error: " + (err) + ""]); if (gs.bool(onComplete)) { return gs.execCall(onComplete, this, [false]); }; }]); }]); } gSobject['checkPermissions'] = function(onComplete) { if (onComplete === undefined) onComplete = null; gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["checkPermissions: Checking authorization status"]); return gs.mc(gs.fs('cordovaHealth', this, gSobject),"isAuthorizedForHealth",[function(authorized) { if (gs.bool(authorized)) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["checkPermissions: User is authorized - starting sync"]); return gs.mc(gSobject,"performHealthSync",[onComplete]); } else { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["checkPermissions: User is not authorized, requesting permissions"]); return gs.mc(gSobject,"requestHealthPermissions",[onComplete]); }; }, function(err) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["checkPermissions: isAuthorized error: " + (err) + ", requesting permissions anyway"]); return gs.mc(gSobject,"requestHealthPermissions",[onComplete]); }]); } gSobject['requestHealthPermissions'] = function(onComplete) { if (onComplete === undefined) onComplete = null; gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["requestHealthPermissions: Requesting read access for steps"]); return gs.mc(gs.fs('cordovaHealth', this, gSobject),"requestPermissions",[function(result) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["requestHealthPermissions: Permission result = " + (result) + ""]); gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["requestHealthPermissions: Permissions granted - starting sync"]); return gs.mc(gSobject,"performHealthSync",[onComplete]); }, function(err) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["requestHealthPermissions: Permission error: " + (err) + ""]); if (gs.bool(onComplete)) { return gs.execCall(onComplete, this, [false]); }; }]); } gSobject['enableSync'] = function(it) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["enableSync: User enabled health sync"]); var syncEnabledPromise = gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:sync:enabled", true]); var stepsPromise = gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:sync:steps", true]); var bpPromise = gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:sync:bp", true]); var hrPromise = gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:sync:heart_rate", true]); return gs.mc(gs.mc(gs.fs('Promise', this, gSobject),"all",[gs.list([syncEnabledPromise , stepsPromise , bpPromise , hrPromise])]),"then",[function(it) { return gs.mc(gSobject,"checkPermissions",[]); }]); } gSobject['cancelSync'] = function(it) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["cancelSync: User declined health sync"]); return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:sync:enabled", false]),"do",[]); } gSobject['performHealthSync'] = function(onComplete) { if (onComplete === undefined) onComplete = null; gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["performHealthSync: Starting"]); var stepsLastSyncPromise = gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:steps:last_sync"]); var bpLastSyncPromise = gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:bp:last_sync"]); var hrLastSyncPromise = gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:heart_rate:last_sync"]); var stepsSyncEnabledPromise = gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:sync:steps"]); var bpSyncEnabledPromise = gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:sync:bp"]); var hrSyncEnabledPromise = gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:sync:heart_rate"]); return gs.mc(gs.mc(gs.fs('Promise', this, gSobject),"all",[gs.list([stepsLastSyncPromise , bpLastSyncPromise , hrLastSyncPromise , stepsSyncEnabledPromise , bpSyncEnabledPromise , hrSyncEnabledPromise])]),"then",[function(results) { var stepsLastSync = results[0]; var bpLastSync = results[1]; var hrLastSync = results[2]; var stepsSyncEnabled = results[3]; var bpSyncEnabled = results[4]; var hrSyncEnabled = results[5]; gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["performHealthSync: Got steps last sync = " + (stepsLastSync) + ", BP last sync = " + (bpLastSync) + ", HR last sync = " + (hrLastSync) + ""]); gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["performHealthSync: Sync enabled - steps: " + (stepsSyncEnabled) + ", BP: " + (bpSyncEnabled) + ", HR: " + (hrSyncEnabled) + ""]); var now = gs.date(); var stepsStartDate = null; var endDate = now; var bpStartDate = null; var hrStartDate = null; if (gs.bool(stepsLastSync)) { stepsStartDate = gs.date(gs.plus(stepsLastSync, 1000)); } else { stepsStartDate = gs.date(gs.minus(gs.mc(now,"getTime",[]), (gs.multiply((gs.multiply((gs.multiply((gs.multiply((gs.multiply(5, 365)), 24)), 60)), 60)), 1000)))); }; if (gs.bool(bpLastSync)) { bpStartDate = gs.date(gs.plus(bpLastSync, 1000)); } else { bpStartDate = gs.date(gs.minus(gs.mc(now,"getTime",[]), (gs.multiply((gs.multiply((gs.multiply((gs.multiply((gs.multiply(5, 365)), 24)), 60)), 60)), 1000)))); }; if (gs.bool(hrLastSync)) { hrStartDate = gs.date(gs.plus(hrLastSync, 1000)); } else { hrStartDate = gs.date(gs.minus(gs.mc(now,"getTime",[]), (gs.multiply((gs.multiply((gs.multiply((gs.multiply((gs.multiply(5, 365)), 24)), 60)), 60)), 1000)))); }; var finalStepsData = gs.list([]); var finalBpData = gs.list([]); var finalHrData = gs.list([]); var completedQueries = 0; var totalQueries = 0; if (gs.equals(stepsSyncEnabled, true)) { totalQueries++; }; if (gs.equals(bpSyncEnabled, true)) { totalQueries++; }; if (gs.equals(hrSyncEnabled, true)) { totalQueries++; }; if (gs.equals(totalQueries, 0)) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["performHealthSync: No data types enabled for sync"]); if (gs.bool(onComplete)) { gs.execCall(onComplete, this, [true]); }; return null; }; gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["performHealthSync: Querying steps from " + (stepsStartDate) + " to " + (endDate) + ", BP from " + (bpStartDate) + " to " + (endDate) + ", HR from " + (hrStartDate) + " to " + (endDate) + ""]); var checkComplete = function(it) { completedQueries++; gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["performHealthSync: checkComplete called - " + (completedQueries) + " of " + (totalQueries) + " queries done"]); if (gs.equals(completedQueries, totalQueries)) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["performHealthSync: All queries complete. Collected steps: " + (gs.mc(finalStepsData,"size",[])) + ", BP: " + (gs.mc(finalBpData,"size",[])) + ", HR: " + (gs.mc(finalHrData,"size",[])) + ""]); gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["performHealthSync: Calling processHealthData on server"]); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeHealthSyncService"),"processHealthData",[finalStepsData, finalBpData, finalHrData, gs.gp(gs.fs('session', this, gSobject),"userId"), function(it) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["performHealthSync: SUCCESS CALLBACK FIRED"]); if (gs.bool(onComplete)) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["performHealthSync: Calling onComplete with true"]); return gs.execCall(onComplete, this, [true]); }; }, function(it) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["performHealthSync: ERROR CALLBACK FIRED"]); if (gs.bool(onComplete)) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["performHealthSync: Calling onComplete with false"]); return gs.execCall(onComplete, this, [false]); }; }]); }; }; if (gs.equals(stepsSyncEnabled, true)) { gs.mc(gs.fs('cordovaHealth', this, gSobject),"querySteps",[stepsStartDate, endDate, function(stepsData) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["performHealthSync: Got steps data: " + (gs.elvis(gs.mc(stepsData,"size",[], null, true) , gs.mc(stepsData,"size",[], null, true) , 0)) + " records"]); finalStepsData = gs.elvis(gs.bool(stepsData) , stepsData , gs.list([])); return gs.execCall(checkComplete, this, []); }, function(stepsErr) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["performHealthSync: Steps query error: " + (stepsErr) + ""]); return gs.execCall(checkComplete, this, []); }]); }; if (gs.equals(bpSyncEnabled, true)) { gs.mc(gs.fs('cordovaHealth', this, gSobject),"queryBloodPressure",[bpStartDate, endDate, function(bpData) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["performHealthSync: Got BP data: " + (gs.elvis(gs.mc(bpData,"size",[], null, true) , gs.mc(bpData,"size",[], null, true) , 0)) + " records"]); finalBpData = gs.elvis(gs.bool(bpData) , bpData , gs.list([])); return gs.execCall(checkComplete, this, []); }, function(bpErr) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["performHealthSync: BP query error: " + (bpErr) + ""]); return gs.execCall(checkComplete, this, []); }]); }; if (gs.equals(hrSyncEnabled, true)) { return gs.mc(gs.fs('cordovaHealth', this, gSobject),"queryHeartRate",[hrStartDate, endDate, function(hrData) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["performHealthSync: Got heart rate data: " + (gs.elvis(gs.mc(hrData,"size",[], null, true) , gs.mc(hrData,"size",[], null, true) , 0)) + " records"]); finalHrData = gs.elvis(gs.bool(hrData) , hrData , gs.list([])); return gs.execCall(checkComplete, this, []); }, function(hrErr) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["performHealthSync: HR query error: " + (hrErr) + ""]); return gs.execCall(checkComplete, this, []); }]); }; }]); } gSobject['RxmeHealthSyncJsService0'] = function(it) { gs.execStatic(Utils,'setTimeout', this,[function(it) { return gs.mc(gSobject,"runSync",[]); }, 5000]); return this; } if (arguments.length==0) {gSobject.RxmeHealthSyncJsService0(); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function CordovaProblemReporter() { var gSobject = VueComponent(); gSobject.clazz = { name: 'CordovaProblemReporter', simpleName: 'CordovaProblemReporter'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.path = "/reportProblem"; gSobject.roles = gs.list([]); gSobject['created'] = function(it) { gs.sp(gSobject.scope,"userMessage",""); gs.sp(gSobject.scope,"severity","normal"); gs.sp(gSobject.scope,"severities",gs.list(["low" , "normal" , "high" , "critical"])); gs.sp(gSobject.scope,"thumbnailUrl",""); gs.sp(gSobject.scope,"submitting",false); gs.sp(gSobject.scope,"captureCountdown",0); gs.sp(gSobject.scope,"hasCapture",false); gs.sp(gSobject.scope,"userId",gs.elvis(gs.bool(gs.gp(gs.fs('session', this, gSobject),"userId")) , gs.gp(gs.fs('session', this, gSobject),"userId") , "(anonymous)")); gs.sp(gSobject.scope,"deviceUuid",gs.elvis(gs.bool(gs.gp(gs.gp(gs.fs('cordovaDevice', this, gSobject),"device"),"uuid",true)) , gs.gp(gs.gp(gs.fs('cordovaDevice', this, gSobject),"device"),"uuid",true) , "")); gs.sp(gSobject.scope,"platform",gs.elvis(gs.bool(gs.gp(gs.gp(gs.fs('cordovaDevice', this, gSobject),"device"),"platform",true)) , gs.gp(gs.gp(gs.fs('cordovaDevice', this, gSobject),"device"),"platform",true) , "browser")); return gs.mc(gSobject,"loadPendingCapture",[]); } gSobject['loadPendingCapture'] = function(it) { var pending = gs.mc(gSobject,"nativeReadPendingBlob",[]); if ((gs.bool(pending)) && (gs.bool(gs.gp(pending,"blob")))) { gs.sp(gSobject.scope,"hasCapture",true); return gs.sp(gSobject.scope,"thumbnailUrl",gs.mc(gSobject,"nativeBlobToObjectUrl",[gs.gp(pending,"blob")])); }; } gSobject['captureWithCountdown'] = function(it) { gs.sp(gSobject.scope,"captureCountdown",3); return gs.mc(gSobject,"tick",[]); } gSobject['tick'] = function(it) { if (gs.gp(gSobject.scope,"captureCountdown") <= 0) { gs.mc(gSobject,"doCapture",[]); return null; }; return gs.execStatic(Utils,'setTimeout', this,[function(it) { gs.sp(gSobject.scope,"captureCountdown",(gs.minus(gs.gp(gSobject.scope,"captureCountdown"), 1))); return gs.mc(gSobject,"tick",[]); }, 1000]); } gSobject['doCapture'] = function(it) { return gs.mc(gs.fs('cordovaScreenCapture', this, gSobject),"capture",[function(blob, meta) { gs.mc(gSobject,"nativeStashBlob",[blob]); gs.sp(gSobject.scope,"hasCapture",true); return gs.sp(gSobject.scope,"thumbnailUrl",gs.mc(gSobject,"nativeBlobToObjectUrl",[blob])); }, function(err) { return gs.mc(gs.gp(gs.fs('Quasar', this, gSobject),"Notify"),"create",[gs.map().add("type","negative").add("message","Capture failed: " + (err) + "")]); }]); } gSobject['submit'] = function(it) { if (gs.bool(gs.gp(gSobject.scope,"submitting"))) { return null; }; if (!gs.bool(gs.mc(gs.gp(gSobject.scope,"userMessage"),"trim",[], null, true))) { gs.mc(gs.gp(gs.fs('Quasar', this, gSobject),"Notify"),"create",[gs.map().add("type","warning").add("message","Please describe the problem")]); return null; }; gs.sp(gSobject.scope,"submitting",true); var opts = gs.map().add("severity",gs.gp(gSobject.scope,"severity")); return gs.mc(gs.fs('cordovaScreenCapture', this, gSobject),"reportProblem",[gs.gp(gSobject.scope,"userMessage"), opts, function(reportId) { gs.sp(gSobject.scope,"submitting",false); gs.mc(gSobject,"nativeClearPendingBlob",[]); gs.mc(gs.gp(gs.fs('Quasar', this, gSobject),"Notify"),"create",[gs.map().add("type","positive").add("message","Problem reported. Thanks!").add("actions",gs.list([gs.map().add("label","View").add("color","white").add("handler",function(it) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/cordovaErrors"]); })]))]); return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"back",[]); }, function(err) { gs.sp(gSobject.scope,"submitting",false); return gs.mc(gs.gp(gs.fs('Quasar', this, gSobject),"Notify"),"create",[gs.map().add("type","negative").add("message","Failed to send: " + (err) + "")]); }]); } gSobject['cancel'] = function(it) { gs.mc(gSobject,"nativeClearPendingBlob",[]); return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"back",[]); } gSobject.nativeReadPendingBlob = function() { return window._cwPendingReport || null; } gSobject.nativeStashBlob = function(blob) { window._cwPendingReport = { blob: blob, ts: Date.now() }; } gSobject.nativeClearPendingBlob = function() { if (window._cwPendingReport && window._cwPendingReport.thumbnailUrl) { try { URL.revokeObjectURL(window._cwPendingReport.thumbnailUrl); } catch(_) {} } window._cwPendingReport = null; } gSobject.nativeBlobToObjectUrl = function(blob) { try { return URL.createObjectURL(blob); } catch(e) { return ''; } } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function VueAdComponent() { var gSobject = VueComponent(); gSobject.clazz = { name: 'VueAdComponent', simpleName: 'VueAdComponent'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.props = gs.list(["canNavigate" , "rootDomain" , "vertical"]); gSobject.timer = null; gSobject['mounted'] = function(it) { var self = this; if (!gs.bool(gs.gp(self,"canNavigate"))) { gs.sp(self,"canNavigate",true); }; if (!gs.bool(gs.gp(self,"rootDomain"))) { gs.sp(self,"rootDomain",""); }; if (!gs.bool(gs.gp(self,"vertical"))) { return gs.sp(self,"vertical",false); }; } gSobject['created'] = function(it) { gs.sp(gSobject.scope,"adIndex",0); gs.sp(gSobject.scope,"ad",gs.map()); gs.mc(gSobject,"loadAd",[]); if (!gs.bool(gs.mc(gSobject,"isTimerSet",[]))) { return gSobject.timer = gs.execStatic(Utils,'setInterval', this,[function(it) { return gs.mc(gSobject,"loadAd",[]); }, 60000]); }; } gSobject['openAd'] = function(ad) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.gp(gs.fs('session', this, gSobject),"legionUser"),"_id",true), "fitworld.ad.click", gs.gp(ad,"_id")]),"do",[]); if (!gs.bool(gs.gp(ad,"url"))) { return null; }; return gs.mc(gs.gp(gs.fs('cordova', this, gSobject),"InAppBrowser"),"open",[gs.gp(ad,"url"), "_system", "location=yes"]); } gSobject['unmounted'] = function(it) { return gs.mc(gSobject,"killTimer",[]); } gSobject['loadAd'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"vueWrapperService"),"loadAd",[gs.gp(gSobject.scope,"adIndex"), function(result) { gs.sp(gSobject.scope,"adIndex",gs.gp(result,"index")); gs.sp(gSobject.scope,"ad",gs.gp(result,"ad")); return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.gp(gs.fs('session', this, gSobject),"legionUser"),"_id",true), "fitworld.ad.show", gs.gp(gs.gp(result,"ad"),"_id")]),"do",[]); }]); } gSobject['killTimer'] = function(it) { if (gs.equals(gSobject.timer, null)) { return null; }; gs.execStatic(Utils,'clearInterval', this,[gSobject.timer]); return gSobject.timer = null; } gSobject['isTimerSet'] = function(it) { return !gs.equals(gSobject.timer, null); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function RiskScoreComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'RiskScoreComponent', simpleName: 'RiskScoreComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/riskScore/:questionnaireId"; gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "risk.score.page"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[false]); gs.mc(gSobject,"componentTheme",[true]); gs.sp(gSobject.scope,"background","#000000"); gs.sp(gSobject.scope,"score",0); gs.println("RiskScoreComponent.created()"); return gs.mc(gSobject,"loadscoreDetails",[]); } gSobject['loadscoreDetails'] = function(it) { gs.sp(gSobject.scope,"scoreMap",gs.map()); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"loadScoreResult",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gs.gp(gSobject.route,"params"),"questionnaireId"), function(scoreMap) { gs.sp(gSobject.scope,"scoreMap",scoreMap); return gs.sp(gSobject.scope,"background",gs.gp(scoreMap,"background")); }]); } gSobject['toolbar'] = function(it) { return (!gs.bool(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"showFooter"))) || (!gs.bool(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"keyboardShowing"))); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function I3Page() { var gSobject = VueComponent(); gSobject.clazz = { name: 'I3Page', simpleName: 'I3Page'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.props = gs.list([]); gSobject.data = function(it) { return gs.list([]); }; gSobject['created'] = function(it) { var self = this; } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function DevReload() { var gSobject = gs.init('DevReload'); gSobject.clazz = { name: 'DevReload', simpleName: 'DevReload'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; Object.defineProperty(gSobject, 'devMode', { get: function() { return DevReload.devMode; }, set: function(gSval) { DevReload.devMode = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'tagName', { get: function() { return DevReload.tagName; }, set: function(gSval) { DevReload.tagName = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'productIds', { get: function() { return DevReload.productIds; }, set: function(gSval) { DevReload.productIds = gSval; }, enumerable: true }); gSobject.init = function() { return DevReload.init(); } gSobject.reloadCss = function(x0) { return DevReload.reloadCss(x0); } gSobject.reloadViews = function(x0) { return DevReload.reloadViews(x0); } gSobject.patchComponents = function(x0) { return DevReload.patchComponents(x0); } gSobject.reloadGrooscript = function(x0) { return DevReload.reloadGrooscript(x0); } gSobject.reloadFullBundle = function(x0) { return DevReload.reloadFullBundle(x0); } gSobject.forceRemount = function() { return DevReload.forceRemount(); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; DevReload.init = function() { // Guard: only subscribe once per page lifetime. // The jsDynamo bundle is re-executed on every hot reload, so without this // guard each save would create a new setInterval and add duplicate subscriptions. if (window.__devReloadInitDone) return window.__devReloadInitDone = true console.log('DevReload: init(), tag=' + DevReload.tagName + ', devMode=' + DevReload.devMode + ', productIds=' + JSON.stringify(DevReload.productIds)) if (!DevReload.devMode) return function handleMessage(message) { // Spring serialises via Jackson so body arrives JSON-quoted — unwrap first. var body = message.body || '' try { body = JSON.parse(body) } catch(e) {} console.log('DevReload: message received, body=' + body) if (body.indexOf('css:') === 0) { DevReload.reloadCss(body.substring(4)) } else if (body.indexOf('view:') === 0) { DevReload.reloadViews(body.substring(5)) } else if (body.indexOf('grooscript:') === 0) { DevReload.reloadGrooscript(body.substring(11)) } } // Track the last STOMP client we subscribed to. // On WebSocket reconnect, socketConnect() creates a NEW Stomp client and assigns // it to Socket.websocketClient. The old subscriptions are gone. By comparing // the reference we detect the reconnect and re-subscribe automatically. var subscribedClient = null setInterval(function() { if (typeof Socket === 'undefined' || !Socket.websocketClient || !Socket.websocketClient.connected) return if (Socket.websocketClient === subscribedClient) return // still the same connection — nothing to do subscribedClient = Socket.websocketClient var ids = DevReload.productIds || [] ids.forEach(function(pid) { Socket.websocketClient.subscribe('/topic/devReload/' + pid, handleMessage) console.log('DevReload: subscribed to /topic/devReload/' + pid + ' (tag=' + DevReload.tagName + ')') }) }, 500) } DevReload.reloadCss = function(version) { console.log('DevReload: reloading CSS, v=' + version) document.querySelectorAll('link[rel="stylesheet"]').forEach(function(link) { if (!link.href.includes('/resourceBundle/')) return var base = link.href.split('?')[0] link.href = base + '?v=' + version console.log('DevReload: swapped CSS', base) }) } DevReload.reloadViews = function(version) { console.log('DevReload: reloadViews v=' + version) fetch('/resourceBundle/packCode/htmlBody?v=' + version) .then(function(res) { return res.text() }) .then(function(html) { // Parse all x-template blocks and update the DOM var updatedHtmlMap = {} var regex = /]*type="text\/x-template"[^>]*id="([^"]+)"[^>]*>([\s\S]*?)<\/script>/gi var match while ((match = regex.exec(html)) !== null) { var el = document.getElementById(match[1]) if (el) { el.innerHTML = match[2] updatedHtmlMap[match[1]] = match[2] } } console.log('DevReload: updated DOM templates:', Object.keys(updatedHtmlMap)) DevReload.patchComponents(updatedHtmlMap) DevReload.forceRemount() }) .catch(function(err) { console.error('DevReload: reloadViews failed', err) }) } DevReload.patchComponents = function(updatedHtmlMap) { var patched = [] function patchComp(comp) { if (!comp || patched.indexOf(comp) >= 0) return var tid = null // Strategy 1: comp.template is still the '#id' selector if (comp.template && comp.template.charAt(0) === '#') { var sel = comp.template.substring(1) if (updatedHtmlMap[sel]) tid = sel } // Strategy 2: comp.template is inline HTML from a previous reload — // identify by name convention (vueComponentName + 'View') if (!tid && comp.vueComponentName) { var nameId = comp.vueComponentName + 'View' if (updatedHtmlMap[nameId]) tid = nameId } if (!tid) return comp.template = updatedHtmlMap[tid] delete comp.render delete comp.__vccOpts patched.push(comp) console.log('DevReload: patched component', comp.vueComponentName, '(template', tid + ')') } if (vue && vue.componentList) { vue.componentList.forEach(function(c) { patchComp(c) }) } if (vue && vue.router && vue.router.getRoutes) { vue.router.getRoutes().forEach(function(route) { if (!route.components) return Object.keys(route.components).forEach(function(k) { patchComp(route.components[k]) }) }) } console.log('DevReload: patched', patched.length, 'component object(s)') if (patched.length === 0) { console.warn('DevReload: no components matched — possible naming mismatch') } } DevReload.reloadGrooscript = function(payload) { var colonIdx = payload.indexOf(':') var version = colonIdx > 0 ? payload.substring(colonIdx + 1) : payload console.log('DevReload: reloading GrooScript, v=' + version) DevReload.reloadFullBundle(version) } DevReload.reloadFullBundle = function(version) { console.log('DevReload: reloading jsDynamo bundle, v=' + version) vue.componentList.splice(0, vue.componentList.length) var script = document.createElement('script') script.src = '/resourceBundle/pack/jsDynamo?v=' + version script.onload = function() { console.log('DevReload: jsDynamo loaded —', vue.componentList.length, 'components') // Re-register all components globally vue.componentList.forEach(function(comp) { if (comp.vueComponentName) vue.vue.component(comp.vueComponentName, comp) }) // Build name → new component lookup var nameToComp = {} vue.componentList.forEach(function(comp) { if (comp.vueComponentName) nameToComp[comp.vueComponentName] = comp }) // Resync router route records to the new component objects var routesResynced = 0 if (vue && vue.router && vue.router.getRoutes) { vue.router.getRoutes().forEach(function(route) { if (!route.components) return Object.keys(route.components).forEach(function(k) { var oldComp = route.components[k] var name = oldComp && oldComp.vueComponentName if (name && nameToComp[name] && nameToComp[name] !== oldComp) { route.components[k] = nameToComp[name] routesResynced++ } }) }) } console.log('DevReload: resynced', routesResynced, 'router route record(s)') // Re-apply current DOM innerHTML to every new component to preserve // any view edits made before this Grooscript save var domSynced = 0 vue.componentList.forEach(function(comp) { if (!comp.template || comp.template.charAt(0) !== '#') return var el = document.getElementById(comp.template.substring(1)) if (!el) return comp.template = el.innerHTML delete comp.render delete comp.__vccOpts domSynced++ }) console.log('DevReload: re-applied current DOM to', domSynced, 'component(s)') DevReload.forceRemount() } script.onerror = function() { console.error('DevReload: failed to load jsDynamo bundle') } document.head.appendChild(script) } DevReload.forceRemount = function() { if (typeof vue === 'undefined' || !vue.router) return var currentPath = vue.router.currentRoute.value.fullPath console.log('DevReload: remounting', currentPath) vue.router.replace('/__devreload__').then(function() { return vue.router.replace(currentPath) }).then(function() { var matched = vue.router.currentRoute.value.matched for (var i = 0; i < matched.length; i++) { var component = matched[i].components && matched[i].components.default if (component && typeof component.created === 'function') { var name = component.vueComponentName var formattedName = name.charAt(0).toLowerCase() + name.slice(1) eval(formattedName + '.created()') console.log('DevReload: called created() on', formattedName) } } }).catch(function(err) { console.error('DevReload: navigation error', err) }) } DevReload.devMode = null; DevReload.tagName = "dev"; DevReload.productIds = null; function HammerJsZoom() { var gSobject = gs.init('HammerJsZoom'); gSobject.clazz = { name: 'HammerJsZoom', simpleName: 'HammerJsZoom'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.showHammerZoom = function(x0) { return HammerJsZoom.showHammerZoom(x0); } gSobject['HammerJsZoom1'] = function(elmName) { HammerJsZoom.showHammerZoom(elmName); return this; } if (arguments.length==1) {gSobject.HammerJsZoom1(arguments[0]); } return gSobject; }; HammerJsZoom.showHammerZoom = function(name) { var elm = document.getElementById(name); var hammertime = new Hammer(elm, {}); hammertime.get('pinch').set({ enable: true }); console.log('hammertime') console.log(hammertime) var posX = 0, posY = 0, scale = 1, last_scale = 1, last_posX = 0, last_posY = 0, max_pos_x = 0, max_pos_y = 0, transform = "", el = elm; hammertime.on('doubletap pinch pan panend pinchend', function(ev) { console.log('event') console.log(ev) if (ev.type == "doubletap") { console.log('doubletapped') transform = "translate3d(0, 0, 0) " + "sacle3d(2, 2, 1) "; scale = 2; last_sacle = 2; try{ if (window.getComputedStyle(el, null).getPropertyValue('-webkit-transform').toString() != "matrix(1, 0, 0, 1, 0, 0)") { transform = "translate3d(0, 0, 0) " + "scale3d(1, 1, 1) "; scale = 1; last_scale = 1; } } catch (err){} el.style.webkitTransform = transform; transform = "" } //pan if (scale != 1) { console.log('pan') posX = last_posX + ev.deltaX; posY = last_posY + ev.deltaY; max_pos_x = Math.ceil((scale - 1) * el.clientWidth / 2); max_pos_y = Math.ceil((scale - 1) * el.clientHeight / 2); if (posX > max_pos_x) { posX = max_pos_x; } if (posX < -max_pos_x) { posX = -max_pos_x; } if (posY > max_pos_y) { posY = max_pos_y; } if (posY < -max_pos_y) { posY = -max_pos_y; } } //pinch if (ev.type == "pinch") { console.log('pinch') scale = Math.max(.999, Math.min(last_scale * (ev.scale), 4)); } if(ev.type == "pinchend"){last_scale = scale;} //panend if(ev.type == "panend"){ console.log('panend') last_posX = posX < max_pos_x ? posX : max_pos_x; last_posY = posY < max_pos_y ? posY : max_pos_y; } if (scale != 1) { console.log('scale not 1') transform = "translate3d(" + posX + "px," + posY + "px, 0) " + "scale3d(" + scale + ", " + scale + ", 1)"; } if (transform) { console.log('transform') el.style.webkitTransform = transform; } }); } function NotificationsComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'NotificationsComponent', simpleName: 'NotificationsComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/notifications"; gSobject['created'] = function(it) { gs.println("NotificationsComponent.created()"); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "notification.home.page"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"notifications",gs.list([])); return gs.mc(gSobject,"loadNotifications",[]); } gSobject['loadNotifications'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"notificationService"),"notificationsForUser",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(data) { return gs.sp(gSobject.scope,"notifications",data); }]); } gSobject['navigateToNotification'] = function(notification) { gs.println(gs.plus("Navigate to: ", gs.gp(notification,"url"))); gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"replace",[gs.gp(notification,"url")]); return gs.mc(gSobject,"removeNotification",[notification]); } gSobject['removeNotification'] = function(notification) { return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"notificationService"),"removeNotification",[gs.gp(notification,"_id")]),"do",[]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function LoginComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'LoginComponent', simpleName: 'LoginComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/signIn"; gSobject.appleAuth = gs.map(); gSobject['created'] = function(it) { gs.println("LoginComponent.created()"); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "user.login.page"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[false]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"showApple",gs.execStatic(Utils,'isIos', this,[])); gs.sp(gSobject.scope,"showAndroid",gs.execStatic(Utils,'isAndroid', this,[])); gs.sp(gSobject.scope,"email",""); gs.sp(gSobject.scope,"phoneNumber",""); gs.sp(gSobject.scope,"processing",false); return gs.sp(gSobject.scope,"createPortalUser",false); } gSobject['login'] = function(it) { gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"username",gs.elvis(gs.bool(gs.gp(gSobject.scope,"email")) , gs.gp(gSobject.scope,"email") , gs.gp(gSobject.scope,"phoneNumber"))); if (!gs.bool(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"username"))) { gs.mc(gSobject,"notify",["Please enter details", "negative"]); return null; }; gs.sp(gSobject.scope,"processing",true); return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"legionAuthService"),"generatePinForExistingUser",[gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"username"), (gs.bool(gs.gp(gSobject.scope,"phoneNumber")) ? true : false)]),"then",[function(it) { gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/pinAuth"]); return gs.sp(gSobject.scope,"processing",false); }, function(error) { gs.sp(gSobject.scope,"createPortalUser",true); return gs.sp(gSobject.scope,"processing",false); }]); } gSobject['googleSignIn'] = function(it) { if (!gs.bool(gs.execStatic(Utils,'isCordova', this,[]))) { return gs.mc(gSobject,"notify",["Could not complete sign in", "negative"]); }; return gs.mc(gs.fs('cordovaGoogleSignIn', this, gSobject),"googleSignIn",[function(success) { gs.println("cordovaGoogleSignIn"); gs.println(success); var object = gs.mc(gSobject,"toObject",[success]); gs.println(object); return gs.mc(gSobject,"signInWith",[gs.gp(gs.gp(object,"message"),"email"), gs.gp(gs.gp(object,"message"),"id"), function(it) { return gs.mc(gs.fs('legionUserService', this, gSobject),"loadLegionUser",[function(user) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/"]); }]); }, function(error) { gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/signIn"]); return gs.mc(gSobject,"errorNotification",[error]); }]); }, function(error) { gs.println(error); return gs.mc(gSobject,"notify",["Error Signing in with Google", "negative"]); }]); } gSobject['signInWithApple'] = function(it) { if (!gs.bool(gs.execStatic(Utils,'isCordova', this,[]))) { return gs.mc(gSobject,"notify",["Could not complete sign in", "negative"]); }; return LoginComponent.signInWithAppleAuth(function(result) { gs.println("signInWithAppleAuth result:"); gs.println(result); var jwt = gs.execStatic(Utils,'decodeJWT', this,[gs.gp(result,"identityToken")]); var email = gs.gp(jwt,"email"); var password = gs.gp(jwt,"sub"); gSobject.appleAuth = result; return gs.mc(gSobject,"signInWith",[email, password, function(it) { return gs.mc(gs.fs('legionUserService', this, gSobject),"loadLegionUser",[function(user) { gs.mc(gSobject,"saveAppleCustomer",[gs.gp(user,"_id")]); return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/"]); }]); }, function(error) { gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/signIn"]); return gs.mc(gSobject,"errorNotification",[error]); }]); }); } gSobject.signInWithAppleAuth = function(x0) { return LoginComponent.signInWithAppleAuth(x0); } gSobject['saveAppleCustomer'] = function(userId) { var user = gs.map(); if (gs.bool(gs.gp(gs.gp(gSobject.appleAuth,"fullName"),"familyName"))) { gs.sp(user,"surname",gs.gp(gs.gp(gSobject.appleAuth,"fullName"),"familyName")); }; if (gs.bool(gs.gp(gs.gp(gSobject.appleAuth,"fullName"),"givenName"))) { gs.sp(user,"name",gs.gp(gs.gp(gSobject.appleAuth,"fullName"),"givenName")); }; return gs.mc(gs.fs('legionUserService', this, gSobject),"updateUserDetails",[userId, gs.gp(user,"name"), gs.gp(user,"surname")]); } gSobject['signInWith'] = function(email, password, successCallback, failCallback) { return gs.mc(gs.fs('legionUserService', this, gSobject),"auth",[email, password, function(authenticated) { if (gs.bool(authenticated)) { return gs.execCall(successCallback, this, [authenticated]); }; return gs.mc(gs.gp(gs.fs('o', this, gSobject),"legionAuthService"),"repairUser",[email, password, function(result) { if (!gs.bool(gs.gp(result,"success"))) { gs.execCall(failCallback, this, ["Registration Failed"]); }; return gs.mc(gs.fs('legionUserService', this, gSobject),"auth",[email, password, function(isAuthenticated) { if (gs.bool(isAuthenticated)) { return gs.execCall(successCallback, this, [isAuthenticated]); }; return gs.execCall(failCallback, this, ["Login Failed"]); }]); }]); }]); } gSobject['errorNotification'] = function(notification) { return gs.mc(this,"alert",[notification], gSobject); } gSobject['differentLogin'] = function(it) { return gs.mc(gSobject,"notify",["WIP"]); } gSobject['openPortalRegister'] = function(it) { return gs.execStatic(Utils,'open', this,["https://prod.rxme.online/register", "_system"]); } gSobject.toObject = function(data) { return JSON.parse(data) } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; LoginComponent.signInWithAppleAuth = function(callback) { var value window.cordova.plugins.SignInWithApple.signin( { requestedScopes: [0,1] }, function(succ){ value = succ console.log("signInWithAppleAuth----------------------------------") console.log(JSON.stringify(value)) callback(value) }, function(err){ if(err.code == "1001" || err.code == "1003"){ alert('Authentication failed: User cancelled sign in.'); }else if(err.code == "1002"){ alert('Error: Sign in response received an invalid response'); }else{ alert('Error: Authentication failed'); } } ) } function TermsAndConditionsComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'TermsAndConditionsComponent', simpleName: 'TermsAndConditionsComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/terms-conditions"; gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "terms.conditions.page"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[false]); gs.mc(gSobject,"componentTheme",[false]); return gs.sp(gSobject.scope,"appVersion",gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"appVersion")); } gSobject['decline'] = function(it) { return gs.execStatic(Utils,'logout', this,["/"]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function FitnessOverviewComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'FitnessOverviewComponent', simpleName: 'FitnessOverviewComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/fitnessOverview"; gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "tracker.fitness.details"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"batchName","health:fitness:history"); gs.sp(gSobject.scope,"tracker",null); gs.sp(gSobject.scope,"graphPeriod","Day"); gs.sp(gSobject.scope,"fitnessLogs",gs.list([])); gs.sp(gSobject.scope,"fitnessLabels",gs.list([])); gs.sp(gSobject.scope,"fitnessValues",gs.list([])); gs.sp(gSobject.scope,"fitnessGoal",gs.map().add("duration",150)); gs.sp(gSobject.scope,"currentGoalProgress",0); gs.sp(gSobject.scope,"goalProgressText",""); gs.sp(gSobject.scope,"durations",gs.map().add("upperBodyStrength",0).add("lowerBodyStrength",0).add("coreAndStability",0).add("cardioAndHiit",0).add("flexibilityAndMobility",0).add("fullBodyAndFunctional",0)); gs.sp(gSobject.scope,"totalWeekDuration",0); gs.mc(gSobject,"loadTrackerData",["Fitness Tracker", function(tracker) { return gs.sp(gSobject.scope,"tracker",tracker); }]); gs.sp(gSobject.scope,"lastUpdated",""); gs.mc(gSobject,"loadLastUpdated",[gs.gp(gs.fs('session', this, gSobject),"userId"), "fitness", function(lastUpdated) { return gs.sp(gSobject.scope,"lastUpdated",lastUpdated); }]); gs.mc(gSobject,"loadFitnessLogs",[]); return gs.mc(gSobject,"generateChartData",[]); } gSobject['loadFitnessLogs'] = function(it) { var today = gs.mc(gSobject,"moment",[]); var startOfWeek = gs.mc(gs.mc(gs.mc(gSobject,"moment",[today]),"startOf",["week"]),"toDate",[]); var endOfWeek = gs.mc(gs.mc(gs.mc(gSobject,"moment",[today]),"endOf",["week"]),"toDate",[]); var filter = gs.map().add("date",gs.map().add(">=",startOfWeek).add("<=",endOfWeek)); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"listEntries",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gSobject.scope,"batchName"), gs.map().add("sort","date").add("order","desc"), filter, function(logs) { if (!gs.bool(logs)) { gs.sp(gSobject.scope,"currentGoalProgress",0); return null; }; var totalDuration = 0; gs.mc(logs,"each",[function(log) { if (gs.bool(gs.gp(log,"totalDuration"))) { return totalDuration += gs.gp(log,"totalDuration"); }; }]); gs.sp(gSobject.scope,"currentGoalProgress",totalDuration); gs.mc(gSobject,"loadGoal",[]); gs.sp(gSobject.scope,"fitnessLogs",gs.mc(logs,"take",[7])); return gs.mc(gSobject,"calculateDurations",[]); }]); } gSobject['calculateDurations'] = function(it) { var categoryMap = gs.map().add("Upper Body Strength","upperBodyStrength").add("Lower Body Strength","lowerBodyStrength").add("Core and Stability","coreAndStability").add("Cardio and HIIT","cardioAndHiit").add("Flexibility and Mobility","flexibilityAndMobility").add("Full Body and Functional","fullBodyAndFunctional"); gs.mc(categoryMap,"each",[function(category, key) { return (gs.gp(gSobject.scope,"durations")[key]) = gs.elvis(gs.mc(gs.mc(gs.mc(gs.gp(gSobject.scope,"fitnessLogs"),"collectMany",[function(it) { return gs.gp(it,"activities"); }]),"findAll",[function(it) { return gs.equals(gs.gp(it,"category"), category); }]),"sum",[function(it) { return gs.gp(it,"duration"); }]) , gs.mc(gs.mc(gs.mc(gs.gp(gSobject.scope,"fitnessLogs"),"collectMany",[function(it) { return gs.gp(it,"activities"); }]),"findAll",[function(it) { return gs.equals(gs.gp(it,"category"), category); }]),"sum",[function(it) { return gs.gp(it,"duration"); }]) , 0); }]); return gs.sp(gSobject.scope,"totalWeekDuration",gs.elvis(gs.mc(gs.mc(gs.gp(gSobject.scope,"durations"),"values",[]),"sum",[]) , gs.mc(gs.mc(gs.gp(gSobject.scope,"durations"),"values",[]),"sum",[]) , 0)); } gSobject['generateChartData'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"metrics",[gs.gp(gs.fs('session', this, gSobject),"userId"), "health:fitness:history-value", gs.date(), gs.gp(gSobject.scope,"graphPeriod"), function(metricData) { gs.sp(gSobject.scope,"fitnessLabels",gs.mc(gs.gp(metricData,"labels"),"slice",[-7])); return gs.sp(gSobject.scope,"fitnessValues",gs.mc(gs.gp(metricData,"values"),"slice",[-7])); }]); } gSobject['loadGoal'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPointTimelineService"),"listEntries",[gs.gp(gs.fs('session', this, gSobject),"userId"), "health:fitness:goal", gs.map().add("limit",1).add("sort","_lastUpdated").add("order","desc"), function(logs) { if (!gs.bool(logs)) { return null; }; var goal = logs[0]; gs.sp(gs.gp(gSobject.scope,"fitnessGoal"),"duration",gs.elvis(gs.bool(gs.gp(goal,"duration")) , gs.gp(goal,"duration") , 150)); return gs.mc(gSobject,"loadGoalProgressText",[]); }]); } gSobject['loadGoalProgressText'] = function(it) { var goal = gs.elvis(gs.bool(gs.gp(gs.gp(gSobject.scope,"fitnessGoal"),"duration")) , gs.gp(gs.gp(gSobject.scope,"fitnessGoal"),"duration") , 150); var progress = gs.elvis(gs.bool(gs.gp(gSobject.scope,"currentGoalProgress")) , gs.gp(gSobject.scope,"currentGoalProgress") , 0); var percent = (goal > 0 ? Math.round(gs.multiply((gs.div(progress, goal)), 100)) : 0); var gSswitch0 = percent; if (function(it) { if (it === undefined) it = gSswitch0; return it >= 100; }()) { gs.sp(gSobject.scope,"goalProgressText","Amazing! You hit your goal for the week!"); ; } else if (function(it) { if (it === undefined) it = gSswitch0; return it >= 80; }()) { gs.sp(gSobject.scope,"goalProgressText","Almost there! Just a little more to go."); ; } else if (function(it) { if (it === undefined) it = gSswitch0; return it >= 60; }()) { gs.sp(gSobject.scope,"goalProgressText","Great progress! Keep pushing."); ; } else if (function(it) { if (it === undefined) it = gSswitch0; return it >= 40; }()) { gs.sp(gSobject.scope,"goalProgressText","Making steady progress! Keep going."); ; } else if (function(it) { if (it === undefined) it = gSswitch0; return it >= 20; }()) { gs.sp(gSobject.scope,"goalProgressText","Good start! Stay consistent."); ; } else if (function(it) { if (it === undefined) it = gSswitch0; return it > 0; }()) { gs.sp(gSobject.scope,"goalProgressText","Let's get moving! Every minute counts."); ; } else { gs.sp(gSobject.scope,"goalProgressText","No activity logged yet. Start your week strong!"); }; } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function MedicalRecordsComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'MedicalRecordsComponent', simpleName: 'MedicalRecordsComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/medicalRecords"; gSobject.goToUpload = function(it) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/medicalRecordsUpload/upload"]); }; gSobject['created'] = function(it) { gs.println("MedicalRecordsComponent.created()"); gs.mc(gSobject,"showHeaderFooter",[]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"loading",true); gs.sp(gSobject.scope,"sections",gs.list([])); gs.sp(gSobject.scope,"activeTab","Blood Tests"); gs.sp(gSobject.scope,"dialogOpen",false); gs.sp(gSobject.scope,"activePDFs",gs.list([])); gs.sp(gSobject.scope,"getSectionItems",function(type) { var section = gs.mc(gs.gp(gSobject.scope,"sections"),"find",[function(it) { return gs.equals(gs.gp(it,"type"), type); }]); return (gs.bool(section) ? gs.gp(section,"items") : gs.list([])); }); return gs.mc(gSobject,"loadRecords",[]); } gSobject['loadRecords'] = function(it) { gs.sp(gSobject.scope,"loading",true); gs.sp(gSobject.scope,"sections",gs.list([])); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeApiDataService"),"medicalRecords",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(sections) { if ((gs.bool(sections)) && (gs.mc(sections,"size",[]) > 0)) { gs.sp(gSobject.scope,"sections",sections); gs.sp(gSobject.scope,"activeTab",gs.gp(sections[0],"type")); } else { gs.sp(gSobject.scope,"sections",gs.list([])); }; return gs.sp(gSobject.scope,"loading",false); }]); } gSobject['openRecord'] = function(rec) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/medicalRecordViewer/" + (gs.gp(rec,"id")) + ""]); } gSobject['formatDate'] = function(date) { if (!gs.bool(date)) { return "Invalid date"; }; return gs.mc(gs.mc(gSobject,"moment",[date]),"format",["YYYY-MM-DD"]); } gSobject['closeDialog'] = function(it) { return gs.sp(gSobject.scope,"dialogOpen",false); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function MedicalRecordViewerComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'MedicalRecordViewerComponent', simpleName: 'MedicalRecordViewerComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/medicalRecordViewer/:id"; gSobject['created'] = function(it) { gs.mc(gSobject,"showHeaderFooter",[]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"loading",true); gs.sp(gSobject.scope,"entry",null); gs.println("ROUTE"); gs.println(gs.gp(gs.gp(gSobject.route,"params"),"id")); return gs.mc(gSobject,"loadMedicalRecord",[]); } gSobject['loadMedicalRecord'] = function(it) { if (gs.bool(gs.gp(gs.gp(gSobject.route,"params"),"id"))) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeApiDataService"),"loadMedicalRecord",[gs.gp(gs.gp(gSobject.route,"params"),"id"), function(entry) { gs.sp(gSobject.scope,"entry",entry); return gs.sp(gSobject.scope,"loading",false); }]); }; } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function MedicalRecordsUploadComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'MedicalRecordsUploadComponent', simpleName: 'MedicalRecordsUploadComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/medicalRecordsUpload/upload"; gSobject['created'] = function(it) { gs.mc(gSobject,"showHeaderFooter",[]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"image1",gs.map()); gs.sp(gSobject.scope,"entry",gs.map().add("type",null).add("title","").add("description","").add("doctor","").add("date",gs.date())); gs.sp(gSobject.scope,"loading",false); return gs.mc(gSobject,"prepareImages",[]); } gSobject['mapType'] = function(uiType) { return gs.elvis(gs.map().add("Lab Reports","pathology").add("Prescriptions","prescription").add("Referrals","referral").add("Other","doctor_discharge")[uiType] , gs.map().add("Lab Reports","pathology").add("Prescriptions","prescription").add("Referrals","referral").add("Other","doctor_discharge")[uiType] , "doctor_discharge"); } gSobject['prepareImages'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataFile"),"findOrCreate",[gs.map().add("_id",null), function(fileObj) { gs.sp(fileObj,"_path","/rxmeO/protoDataFile/"); return gs.sp(gSobject.scope,"image1",fileObj); }]); } gSobject['savePhotoEntry'] = function(it) { if (!gs.bool(gs.gp(gSobject.scope,"image1"))) { gs.mc(gSobject.q,"dialog",[gs.map().add("title","No Document").add("message","Please upload a document.")]); return null; }; gs.sp(gSobject.scope,"loading",true); gs.println("scope.image1"); gs.println(gs.gp(gSobject.scope,"image1")); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeApiDataService"),"createMedicalRecord",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gSobject.scope,"image1"), gs.mc(gSobject,"mapType",[gs.gp(gs.gp(gSobject.scope,"entry"),"type")]), gs.gp(gs.gp(gSobject.scope,"entry"),"title"), gs.gp(gs.gp(gSobject.scope,"entry"),"description"), gs.gp(gs.gp(gSobject.scope,"entry"),"doctor"), gs.gp(gs.gp(gSobject.scope,"entry"),"date"), function(entry) { gs.sp(gSobject.scope,"loading",false); gs.mc(gSobject,"notify",["Medical record saved successfully."]); return gs.mc(gSobject,"back",[]); }]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function CordovaPushNotification() { var gSobject = gs.init('CordovaPushNotification'); gSobject.clazz = { name: 'CordovaPushNotification', simpleName: 'CordovaPushNotification'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.pushService = null; gSobject.notificationListeners = gs.list([]); gSobject.pushConfig = gs.map().add("android",gs.map().add("icon","ic_notification")).add("ios",gs.map().add("alert","true").add("badge","true").add("sound","true")).add("windows",gs.map()); gSobject['toLocation'] = function(path) { return gs.execStatic(Utils,'setTimeout', this,[function(it) { if (!gs.bool(gs.mc(path,"startsWith",["http"]))) { path = (gs.plus((gs.plus((gs.mc(gs.mc(gs.gp(gs.gp(gs.fs('window', this, gSobject),"location"),"href"),"toString",[]),"split",["#"])[0]), "#")), path)); gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["CordovaPushNotificationService:path:" + (path) + ""]); }; return gs.sp(gs.fs('window', this, gSobject),"location",path); }, 1000]); } gSobject['subscribe'] = function(callback) { return gs.mc(gSobject.notificationListeners,"add",[callback]); } gSobject.pluginInstalled = function() { return CordovaPushNotification.pluginInstalled(); } gSobject.hasNotificationPermission = function(x0) { return CordovaPushNotification.hasNotificationPermission(x0); } gSobject['CordovaPushNotification0'] = function(it) { gs.mc(document,"addEventListener",["deviceready", function(it) { if (!gs.bool(gs.mc(this,"pluginInstalled",[], gSobject))) { return null; }; return gs.mc(gs.fs('legionUserService', this, gSobject),"loadLegionUser",[function(user) { gSobject.pushService = gs.mc(gs.fs('PushNotification', this, gSobject),"init",[gSobject.pushConfig]); gs.mc(gSobject.pushService,"on",["registration", function(data) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["CordovaPushNotificationService:registration:START:" + (gs.gp(user,"_id")) + ":" + (gs.execStatic(Utils,'deviceType', this,[])) + ":" + (gs.gp(data,"registrationId")) + ""]); gs.mc(this,"hasNotificationPermission",[function(status) { return gs.println("CordovaPushNotificationService:registration:STATUS:" + (gs.gp(user,"_id")) + ":" + (status) + ""); }], gSobject); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"cordovaDeviceNotificationService"),"registerDevice",[gs.gp(user,"_id"), gs.gp(data,"registrationId"), gs.execStatic(Utils,'deviceType', this,[]), function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["CordovaPushNotificationService:registration:DONE:" + (gs.gp(user,"_id")) + ":" + (gs.execStatic(Utils,'deviceType', this,[])) + ":" + (gs.gp(data,"registrationId")) + ""]); }]); }]); gs.mc(gSobject.pushService,"on",["error", function(error) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["CordovaPushNotificationService:error:" + (error) + ""]); }]); return gs.mc(gSobject.pushService,"on",["notification", function(data) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["Notification received by device - " + (data) + ""]); gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[data]); gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["CordovaPushNotificationService:notification:1:" + (gs.gp(data,"message")) + ""]); gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["CordovaPushNotificationService:notification:2:" + (gs.gp(gs.gp(data,"additionalData"),"foreground")) + ""]); gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["CordovaPushNotificationService:notification:3:" + (gs.gp(gs.gp(data,"additionalData"),"url")) + ""]); if (gs.bool(gSobject.notificationListeners)) { gs.mc(gSobject.notificationListeners,"each",[function(callback) { return gs.execCall(callback, this, [data]); }]); return null; }; if ((gs.equals(gs.gp(gs.gp(data,"additionalData"),"foreground"), false)) && (gs.bool(gs.gp(gs.gp(data,"additionalData"),"url")))) { return gs.mc(gSobject,"toLocation",[gs.gp(gs.gp(data,"additionalData"),"url")]); }; }]); }]); }, false]); return this; } if (arguments.length==0) {gSobject.CordovaPushNotification0(); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; CordovaPushNotification.pluginInstalled = function() { return ( typeof PushNotification !== 'undefined') } CordovaPushNotification.hasNotificationPermission = function(callback) { if (callback === undefined) callback = function(it) { }; } function VueDocumentViewer() { var gSobject = VueComponent(); gSobject.clazz = { name: 'VueDocumentViewer', simpleName: 'VueDocumentViewer'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.props = gs.list(["oObject" , "oName" , "oPropName" , "download" , "filePreview" , "displayName" , "myStyle"]); gSobject.data = function(it) { return gs.map().add("showFullscreenDialog",false); }; gSobject['mounted'] = function(it) { var self = this; var fileInfo = gs.gp(self,"oObject")[gs.gp(self,"oPropName")]; var lastUpdated = gs.gp(gs.gp(self,"oObject"),"_lastUpdated"); try { lastUpdated = gs.mc(lastUpdated,"getTime",[]); } catch (all) { } ; gs.sp(self,"pdfUrl","/media-cache/file/" + (gs.gp(gs.gp(self,"oObject"),"_id")) + "/" + (gs.gp(self,"oPropName")) + "/" + (lastUpdated) + "/" + (gs.gp(fileInfo,"filename")) + ""); gs.sp(self,"preview","/media-cache/filePreview/" + (gs.gp(gs.gp(self,"oObject"),"_id")) + "/" + (gs.gp(self,"oPropName")) + "/" + (lastUpdated) + "/" + (gs.gp(fileInfo,"filename")) + ""); if (!gs.bool(gs.gp(self,"download"))) { gs.sp(self,"download",false); }; if (!gs.bool(gs.gp(self,"filePreview"))) { gs.sp(self,"filePreview",false); }; if (!gs.bool(gs.gp(self,"displayName"))) { gs.sp(self,"displayName",false); }; return gs.sp(self,"showFullscreenDialog",false); } gSobject['objectLoaded'] = function(it) { var self = this; if (!gs.bool(gs.gp(self,"oObject"))) { return false; }; return true; } gSobject['show'] = function(it) { var self = this; if (!gs.bool(gs.gp(self,"filePreview"))) { return null; }; gs.mc(gs.gp(gs.mc(gSobject,"getRefs",[]),"dialog"),"show",[]); gs.mc(gSobject,"nextTick",[function(it) { PdfJsHandler(gs.gp(self,"pdfUrl")); return HammerJsZoom("pdf_canvas"); }]); if (gs.execStatic(Utils,'isCordova', this,[])) { return gs.mc(gs.gp(gs.fs('screen', this, gSobject),"orientation"),"lock",["any"]); }; } gSobject['hideFullscreenDialog'] = function(it) { gs.sp(gSobject.self,"showFullscreenDialog",false); if (gs.execStatic(Utils,'isCordova', this,[])) { return gs.mc(gs.gp(gs.fs('screen', this, gSobject),"orientation"),"lock",["portrait"]); }; } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function ProtocolQNComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'ProtocolQNComponent', simpleName: 'ProtocolQNComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/protocolQNComponent/:name" , "/protocolQNComponent/:name/:question"]); gSobject.mapStack = gs.list([]); gSobject.signatureMap = gs.map(); gSobject.optionsAlreadyRendered = gs.list([]); gSobject.SORT_TO_END = gs.list(["no" , "none" , "other" , "never"]); Object.defineProperty(gSobject, 'selectionTypes', { get: function() { return ProtocolQNComponent.selectionTypes; }, set: function(gSval) { ProtocolQNComponent.selectionTypes = gSval; }, enumerable: true }); gSobject['created'] = function(it) { gs.println("ProtocolQNComponent.created()"); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "protocol.qn.page"]),"do",[]); gs.mc(gSobject,"showHeader",[false]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"today",gs.mc(gs.mc(gSobject,"moment",[]),"format",["YYYY-MM-DD"])); gs.sp(gSobject.scope,"allowedDates",function(d) { return gs.mc(gs.mc(gSobject,"moment",[d, "YYYY/MM/DD"]),"isSameOrBefore",[gs.mc(gSobject,"moment",[gs.gp(gSobject.scope,"today"), "YYYY/MM/DD"])]); }); gs.sp(gSobject.scope,"contentLoaded",false); gs.sp(gSobject.scope,"optionsClone",gs.list([])); gs.sp(gSobject.scope,"questionMap",gs.map()); gs.sp(gSobject.scope,"questionnaire",gs.map()); gs.sp(gSobject.scope,"loadingNext",false); gs.sp(gSobject.scope,"labelNext","I'm Ready"); gs.sp(gSobject.scope,"menstrualCycleDate",""); gs.sp(gSobject.scope,"cyclePeriod",0); gs.sp(gSobject.scope,"groupModels",gs.map()); gs.sp(gSobject.scope,"qnCompleted",false); gs.sp(gSobject.scope,"showDone",false); gs.mc(gSobject,"animateNext",[]); gs.mc(gSobject,"startQn",[function(it) { return gs.sp(gSobject.scope,"contentLoaded",true); }]); gs.sp(gSobject.scope,"metric",gs.map().add("value",70).add("unit","kg")); gs.sp(gSobject.scope,"min",30); gs.sp(gSobject.scope,"max",250); gs.sp(gSobject.scope,"isWeight",true); gs.sp(gSobject.scope,"moodItems",gs.execStatic(MoodOverviewComponent,'buildMoodMapperWithIcons', this,[])); gs.sp(gSobject.scope,"backgroundColor",null); gs.sp(gSobject.scope,"userGender",""); return gs.mc(gSobject,"loadGender",[]); } gSobject['loadGender'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "person:gender", function(gender) { return gs.sp(gSobject.scope,"userGender",gender); }]); } gSobject['moodUpdate'] = function(option, mood) { if ((!gs.bool(gs.gp(option,"answer",true))) || (!gs.bool(mood))) { return null; }; var resolvedMood = gs.mc(gSobject,"resolveMoodPayload",[mood]); if (!gs.bool(resolvedMood)) { return null; }; gs.sp(gs.gp(option,"answer"),"value",gs.gp(resolvedMood,"index")); gs.sp(gs.gp(option,"answer"),"selected",true); gs.println("[PROTOCOL_QN][moodUpdate] selectedMood=" + (resolvedMood) + ""); gs.println("[PROTOCOL_QN][moodUpdate] answer.value=" + (gs.gp(gs.gp(option,"answer"),"value")) + ""); return gs.sp(gSobject.scope,"backgroundColor","background: " + (gs.elvis(gs.bool(gs.gp(resolvedMood,"color",true)) , gs.gp(resolvedMood,"color",true) , null)) + " ;transition: background 0.4s ease-in-out"); } gSobject['resolveMoodSelection'] = function(rawValue) { if ((gs.equals(rawValue, null)) || (gs.equals(rawValue, ""))) { return null; }; var moods = gs.elvis(gs.bool(gs.gp(gSobject.scope,"moodItems")) , gs.gp(gSobject.scope,"moodItems") , gs.list([])); if (!gs.bool(moods)) { return null; }; var numericValue = null; try { numericValue = parseInt(gs.mc(rawValue,"toString",[])); } catch (all) { numericValue = null; } ; if (numericValue != null) { var byIndex = gs.mc(moods,"find",[function(it) { return gs.equals(gs.gp(it,"index"), numericValue); }]); if (gs.bool(byIndex)) { return byIndex; }; }; var normalized = gs.mc(gs.mc(gs.mc(rawValue,"toString",[]),"trim",[]),"toLowerCase",[]); return gs.mc(moods,"find",[function(it) { return (gs.equals(gs.mc(gs.mc(gs.gp(it,"value"),"toString",[], null, true),"toLowerCase",[], null, true), normalized)) || (gs.equals(gs.mc(gs.mc(gs.gp(it,"label"),"toString",[], null, true),"toLowerCase",[], null, true), normalized)); }]); } gSobject['resolveMoodPayload'] = function(mood) { if (((gs.gp(mood,"index",true) != null) && (gs.bool(gs.gp(mood,"value",true)))) && (gs.bool(gs.gp(mood,"label",true)))) { return gs.map().add("index",gs.gp(mood,"index")).add("value",gs.gp(mood,"value")).add("label",gs.gp(mood,"label")).add("color",gs.gp(mood,"color")).add("icon",gs.gp(mood,"icon")); }; return gs.mc(gSobject,"resolveMoodSelection",[mood]); } gSobject['loadMenstrualCycle'] = function(it) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "menstrual_cycle:start_date", function(startDate) { gs.println("DATE SELECTED"); gs.println(startDate); gs.sp(gSobject.scope,"menstrualCycleDate",startDate); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "cycle_period:cycle_length_days", function(lengthDays) { return gs.sp(gSobject.scope,"cyclePeriod",lengthDays); }]); }]); gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"calculateNextPeriod",[gs.gp(gSobject.scope,"menstrualCycleDate"), gs.gp(gSobject.scope,"cyclePeriod"), function(result) { return gs.println("RESULT: " + (result) + ""); }]); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"saveNextPeriodStart",[gs.gp(gs.fs('session', this, gSobject),"userId"), "medical:score:next_period_start", function(finalDate) { return gs.println("FINAL DATE: " + (finalDate) + ""); }]); } gSobject['markImageSelected'] = function(option) { return gs.sp(gs.gp(option,"answer"),"selected",true); } gSobject['startQn'] = function(callback) { if (callback === undefined) callback = function(it) { }; gSobject.mapStack = gs.list([]); gSobject.signatureMap = gs.map(); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protocolQuestionnaireAppService"),"startQuestionnaire",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gs.gp(gSobject.route,"params"),"name"), function(questionMap) { gs.sp(gSobject.scope,"questionMap",questionMap); gs.mc(gs.gp(gs.gp(gSobject.scope,"questionMap"),"options"),"each",[function(it) { if (gs.equals(gs.gp(it,"type"), "date")) { gs.sp(it,"_showDate",false); }; if (gs.equals(gs.gp(it,"type"), "date-time")) { gs.sp(it,"_showDateTime",false); }; if (gs.equals(gs.gp(it,"type"), "time")) { return gs.sp(it,"_showTime",false); }; }]); gs.sp(gSobject.scope,"questionnaire",gs.gp(questionMap,"questionnaire")); gs.mc(gSobject.mapStack,"add",[gs.gp(gSobject.scope,"questionMap")]); gs.mc(gSobject,"checkNextLabel",[]); gs.mc(gSobject,"resetOptionsAlreadyRendered",[]); gs.mc(gSobject,"markButtonsNotSelected",[]); gs.mc(gSobject,"showFooter",[false]); gs.execCall(callback, this, []); return gs.mc(gSobject,"logQnActivity",["start"]); }]); } gSobject['onSelectPopupClosed'] = function(it) { return gs.sp(gSobject.scope,"showDone",false); } gSobject['nextQuestion'] = function(skip) { if (skip === undefined) skip = false; if ((!gs.bool(skip)) && (!gs.bool(gs.mc(gSobject,"checkRequired",[])))) { return gs.mc(gSobject,"notify",["Please answer required fields", "negative"]); }; gs.mc(gSobject,"animateNext",[]); var sendMap = gs.execStatic(Utils,'deepCopyMap', this,[gs.gp(gSobject.scope,"questionMap")]); gs.mc(gs.gp(sendMap,"options"),"each",[function(it) { gs.sp(it,"listEntries",gs.list([])); gs.sp(it,"listEntriesFiltered",gs.list([])); if (gs.bool(skip)) { gs.sp(gs.gp(it,"answer"),"value",null); gs.sp(gs.gp(it,"answer"),"fileValue",null); return gs.sp(gs.gp(it,"answer"),"selected",true); }; }]); gs.sp(gSobject.scope,"loadingNext",true); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"protocolQuestionnaireAppService"),"recordQuestionAnswer",[gs.gp(gs.fs('session', this, gSobject),"userId"), sendMap, gs.gp(gSobject.scope,"userGender"), function(nextQuestionMap) { if (!gs.bool(gs.gp(nextQuestionMap,"question"))) { gs.sp(gSobject.scope,"qnCompleted",true); gs.mc(gSobject,"onQnComplete",[]); if (gs.bool(gs.gp(gs.gp(gSobject.scope,"questionnaire"),"toPathOnComplete"))) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["" + (gs.gp(gs.gp(gSobject.scope,"questionnaire"),"toPathOnComplete")) + ""]); } else { if (gs.equals(gs.gp(gs.gp(gSobject.scope,"questionnaire"),"code"), "Cycle Assessment")) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/cycleOverview"]); }; }; gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/protocolQNScoreComponent/" + (gs.gp(gs.gp(gSobject.scope,"questionnaire"),"_id")) + ""]); return null; }; gs.println("QUESTION MAP"); gs.println(gs.gp(gSobject.scope,"questionMap")); gs.println(gs.gp(gs.gp(gs.gp(gSobject.scope,"questionMap"),"question"),"_id")); if (gs.equals(gs.gp(gs.gp(gs.gp(gSobject.scope,"questionMap"),"question"),"_id"), "0197545d74b37a95abff4a6ba5959a45")) { var map = gs.gp(gSobject.scope,"questionMap"); var option = gs.gp(map,"options")[0]; var selectedValue = gs.gp(gs.gp(option,"answer",true),"value",true); gs.println("Found value in option:"); gs.println(selectedValue); gs.sp(gSobject.scope,"menstrualCycleDate",selectedValue); }; gs.sp(gSobject.scope,"questionMap",nextQuestionMap); gs.mc(gSobject.mapStack,"add",[gs.gp(gSobject.scope,"questionMap")]); keepOptions = gs.mc(gs.gp(gs.gp(gSobject.scope,"questionMap"),"options"),"clone",[]); gs.mc(gSobject,"checkNextLabel",[]); gs.mc(gSobject,"loadDuplicatesOnOptions",[]); gs.mc(gSobject,"markButtonsNotSelected",[]); gs.mc(gSobject,"resetOptionsAlreadyRendered",[]); gs.sp(gSobject.scope,"backgroundColor",null); return gs.sp(gSobject.scope,"loadingNext",false); }]); } gSobject['onQnComplete'] = function(it) { gs.mc(gs.mc(gs.gp(gs.gp(gSobject.scope,"questionMap"),"options"),"findAll",[function(it) { return ((gs.bool(gs.gp(gs.gp(it,"answer"),"selected",true))) && (gs.bool(gs.gp(it,"badges")))) && (gs.mc(gs.gp(it,"badges"),"size",[]) > 0); }]),"each",[function(option) { return gs.mc(gs.gp(option,"badges"),"each",[function(badge) { if (gs.bool(gs.gp(badge,"code",true))) { return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"questService"),"assignBadge",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(badge,"code")]),"do",[]); }; }]); }]); if (gs.equals(gs.gp(gs.gp(gSobject.scope,"questionnaire"),"code",true), "Initial Questionnaire")) { var genderCode = ""; gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"loadDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "person:gender", function(gender) { if (gs.equals(gender, "Female")) { genderCode = "Female"; } else { genderCode = "Male"; }; if (gs.bool(genderCode)) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"qstBadge"),"findOne",[gs.map().add("code",genderCode), function(genderBadge) { if (gs.bool(genderBadge)) { return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"questService"),"assignBadge",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(genderBadge,"code")]),"do",[]); }; }]); }; }]); }; if (gs.equals(gs.gp(gs.gp(gSobject.scope,"questionnaire"),"code",true), "Full Health Assessment")) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"questService"),"moveStateForwardFromState",[gs.gp(gs.fs('session', this, gSobject),"userId"), "User Onboarding", "Holding Area"]),"do",[]); gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppApiService"),"updatePatientMedical",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(result) { gs.println("result"); return gs.println(result); }]); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "person:fha:complete", true]),"do",[]); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataPlaneUserService"),"saveDataPoint",[gs.gp(gs.fs('session', this, gSobject),"userId"), "person:fha:report:requested", gs.mc(gs.mc(gs.date(),"getTime",[]),"toString",[])]),"do",[]); gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"fhaStatus",true); }; return gs.mc(gSobject,"logQnActivity",["end"]); } gSobject['previousQuestion'] = function(it) { if (gs.mc(gSobject.mapStack,"size",[]) <= 1) { return gs.mc(gSobject,"back",[]); }; gs.mc(gSobject,"animateBack",[]); gSobject.mapStack = (gs.rangeFromList(gSobject.mapStack, 0, -2)); gs.sp(gSobject.scope,"questionMap",gs.mc(gSobject.mapStack,"last",[])); gs.mc(gSobject,"resetOptionsAlreadyRendered",[]); gs.mc(gSobject,"markButtonsNotSelected",[]); gs.sp(gSobject.scope,"backgroundColor",null); return gs.mc(gSobject,"checkNextLabel",[]); } gSobject['resetOptionsAlreadyRendered'] = function(it) { gSobject.optionsAlreadyRendered = gs.list([]); return false; } gSobject['hasRenderedOption'] = function(option) { return gs.mc(gSobject.optionsAlreadyRendered,"any",[function(it) { return gs.equals(gs.gp(it,"_id",true), gs.gp(option,"_id",true)); }]); } gSobject['renderedOption'] = function(option) { gs.mc(gSobject.optionsAlreadyRendered,"add",[option]); return false; } gSobject['renderedGroupOptions'] = function(option) { gs.mc(gs.mc(gSobject,"optionsInGroup",[option]),"each",[function(it) { if (!gs.bool(gs.mc(gSobject,"hasRenderedOption",[it]))) { return gs.mc(gSobject.optionsAlreadyRendered,"add",[it]); }; }]); return false; } gSobject['optionsInGroup'] = function(option) { if (!gs.bool(gs.gp(option,"group"))) { return gs.list([option]); }; var options = gs.mc(gs.gp(gs.gp(gSobject.scope,"questionMap"),"options"),"findAll",[function(it) { return gs.equals(gs.gp(it,"group"), gs.gp(option,"group")); }]); if (gs.equals(gs.gp(gs.gp(option,"type"),"name",true), "toggle-option")) { if (!gs.bool(gs.mc(options,"any",[function(it) { return gs.gp(gs.gp(it,"answer"),"selected"); }]))) { gs.sp(gs.gp(option,"answer"),"selected",true); }; }; if (!gs.bool(gs.gp(option,"unsorted"))) { options = gs.mc(options,"sort",[function(it) { var name = gs.mc(gs.gp(it,"name"),"toLowerCase",[], null, true); if (gs.gSin(name, gSobject.SORT_TO_END)) { return "zzzzz"; }; return name; }]); }; return options; } gSobject['optionsInGroupRender'] = function(option) { var options = gs.mc(gSobject,"optionsInGroup",[option]); return gs.mc(options,"findAll",[function(it) { return gs.gSin(gs.gp(gs.gp(it,"type"),"name",true), ProtocolQNComponent.selectionTypes); }]); } gSobject['optionsInGroupSelected'] = function(option) { if (!gs.bool(gs.gp(option,"group"))) { return gs.list([option]); }; return gs.mc(gs.gp(gs.gp(gSobject.scope,"questionMap"),"options"),"findAll",[function(it) { return (gs.equals(gs.gp(it,"group"), gs.gp(option,"group"))) && (gs.bool(gs.gp(gs.gp(it,"answer"),"selected"))); }]); } gSobject['isOptionsInGroupSelected'] = function(option) { if (!gs.bool(gs.gp(option,"group"))) { return gs.list([option]); }; return gs.gp(gs.mc(gs.gp(gs.gp(gSobject.scope,"questionMap"),"options"),"findAll",[function(it) { return (gs.equals(gs.gp(it,"group"), gs.gp(option,"group"))) && (gs.bool(gs.gp(gs.gp(it,"answer"),"selected"))); }]),"length") > 0; } gSobject['test'] = function(opt) { if (opt === undefined) opt = null; gs.println("test"); gs.println(opt); return gs.println(gs.gp(gs.fs('groupModels', this, gSobject),"C",true)); } gSobject['removeOption'] = function(option) { return gs.sp(gs.gp(option,"answer"),"selected",false); } gSobject['resolveGridSpan'] = function(option) { var columns = gs.gp(option,"gridSize",true); var style = "grid-column-start: span "; if (!gs.bool(columns)) { return gs.plus(style, "6"); }; return gs.plus(style, columns); } gSobject['markButtonsNotSelected'] = function(it) { return gs.mc(gs.gp(gs.gp(gSobject.scope,"questionMap"),"options"),"each",[function(option) { if (gs.gSin(gs.gp(gs.gp(option,"type"),"name"), gs.list(["submit-button" , "navigate-button"]))) { return gs.sp(gs.gp(option,"answer"),"selected",false); }; }]); } gSobject['labelText'] = function(option) { if (gs.gSin(gs.gp(gs.gp(option,"type"),"name"), gs.list(["string" , "multi-line" , "integer" , "float" , "mobile-number" , "email" , "rsa-id" , "other" , "date" , "date-time" , "image-upload" , "file-upload"]))) { return (gs.bool(gs.gp(option,"required")) ? gs.plus(gs.gp(option,"name"), " *") : gs.gp(option,"name")); }; return gs.gp(option,"name"); } gSobject['checkNextLabel'] = function(it) { if ((gs.equals(gs.gp(gs.gp(gs.gp(gSobject.scope,"questionMap"),"question"),"next",true), null)) && (gs.equals(gs.mc(gs.mc(gs.gp(gs.gp(gSobject.scope,"questionMap"),"options"),"findAll",[function(it) { return gs.gp(it,"next") != null; }]),"size",[]), 0))) { return gs.sp(gSobject.scope,"labelNext","Submit"); } else { if (gs.equals(gs.gp(gs.gp(gs.gp(gSobject.scope,"questionMap"),"question"),"order"), 0)) { return gs.sp(gSobject.scope,"labelNext","I'm Ready"); } else { return gs.sp(gSobject.scope,"labelNext","Continue"); }; }; } gSobject['checkRequired'] = function(it) { gs.println("checkRequired:1"); if (!gs.bool(gs.mc(gSobject,"checkRequiredForSelectionGroups",[]))) { return false; }; gs.println("checkRequired:2"); for (_i32 = 0, option = gs.gp(gs.gp(gSobject.scope,"questionMap"),"options")[0]; _i32 < gs.gp(gs.gp(gSobject.scope,"questionMap"),"options").length; option = gs.gp(gs.gp(gSobject.scope,"questionMap"),"options")[++_i32]) { gs.println("checkRequired:3----------"); gs.println(gs.gp(gs.gp(option,"type"),"name")); gs.println(gs.gp(option,"required")); gs.println(gs.gp(option,"answer")); if (gs.gSin(gs.gp(gs.gp(option,"type"),"name"), ProtocolQNComponent.selectionTypes)) { continue; }; gs.println("checkRequired:4"); if ((gs.equals(gs.gp(gs.gp(option,"type"),"name"), "rsa-id")) && (!gs.bool(gs.mc(this,"isValidRsaId",[gs.gp(gs.gp(option,"answer"),"value")], gSobject)))) { gs.mc(this,"notify",["Invalid Id", "negative"], gSobject); return false; }; if ((gs.equals(gs.gp(gs.gp(option,"type"),"name"), "email")) && (!gs.bool(gs.mc(this,"isValidEmail",[gs.gp(gs.gp(option,"answer"),"value")], gSobject)))) { gs.mc(this,"notify",["Invalid Email", "negative"], gSobject); return false; }; gs.println(option); if (((gs.bool(gs.gp(option,"required"))) && (!gs.bool(gs.gp(gs.gp(option,"answer"),"value")))) && (!gs.bool(gs.gp(gs.gp(option,"answer"),"fileValue")))) { return false; }; gs.println("checkRequired:5"); }; return true; } gSobject['checkRequiredForSelectionGroups'] = function(it) { gs.println("checkRequiredForSelectionGroups:1"); var requiredGroups = gs.mc(gs.mc(gs.mc(gs.mc(gs.gp(gs.gp(gSobject.scope,"questionMap"),"options"),"findAll",[function(it) { return ((gs.bool(gs.gp(it,"group"))) && (gs.gSin(gs.gp(gs.gp(it,"type"),"name"), ProtocolQNComponent.selectionTypes))) && (gs.bool(gs.gp(it,"required"))); }]),"collect",[function(it) { return gs.gp(it,"group"); }]),"unique",[]),"sort",[]); gs.println(requiredGroups); if (!gs.bool(requiredGroups)) { return true; }; gs.println(gs.mc(gs.gp(gs.gp(gSobject.scope,"questionMap"),"options"),"collect",[function(it) { return gs.list([gs.gp(gs.gp(it,"type"),"name") , gs.gp(gs.gp(it,"answer"),"selected") , gs.gp(gs.gp(it,"answer"),"value")]); }])); var selectedGroups = gs.mc(gs.mc(gs.mc(gs.mc(gs.gp(gs.gp(gSobject.scope,"questionMap"),"options"),"findAll",[function(it) { return (gs.bool(gs.gp(it,"group"))) && (((gs.gSin(gs.gp(gs.gp(it,"type"),"name"), ProtocolQNComponent.selectionTypes)) && (gs.bool(gs.gp(gs.gp(it,"answer"),"selected")))) || (gs.bool(gs.gp(gs.gp(it,"answer"),"value")))); }]),"collect",[function(it) { return gs.gp(it,"group"); }]),"unique",[]),"sort",[]); gs.println(selectedGroups); gs.println("checkRequiredForSelectionGroups:2"); return gs.execStatic(Utils,'listsEqual', this,[requiredGroups, selectedGroups]); } gSobject['selectSingleOption'] = function(option) { if (gs.bool(gs.gp(gs.gp(option,"answer"),"selected"))) { gs.sp(gs.gp(option,"answer"),"selected",false); return null; }; gs.mc(gs.mc(gs.gp(gs.gp(gSobject.scope,"questionMap"),"options"),"findAll",[function(it) { return (gs.gSin(gs.gp(gs.gp(it,"type"),"name"), gs.list(["single-option" , "multi-option" , "toggle-option"]))) && (gs.equals(gs.gp(it,"group"), gs.gp(option,"group"))); }]),"each",[function(it) { return gs.sp(gs.gp(it,"answer"),"selected",false); }]); return gs.sp(gs.gp(option,"answer"),"selected",true); } gSobject['selectMultiOption'] = function(option) { if (gs.bool(gs.gp(gs.gp(option,"answer"),"selected"))) { gs.sp(gs.gp(option,"answer"),"selected",false); return null; }; var options = gs.mc(gSobject,"optionsInGroup",[option]); var noneLikeNames = gs.list(["none" , "no" , "never"]); var isNoneLike = function(opt) { return gs.mc(noneLikeNames,"contains",[gs.mc(gs.gp(opt,"name"),"toLowerCase",[], null, true)]); }; if (gs.execCall(isNoneLike, this, [option])) { gs.mc(options,"each",[function(it) { return gs.sp(gs.gp(it,"answer"),"selected",false); }]); } else { gs.mc(gs.mc(options,"findAll",[function(it) { return gs.execCall(isNoneLike, this, [it]); }]),"each",[function(it) { return gs.sp(gs.gp(it,"answer"),"selected",false); }]); }; gs.mc(gs.mc(options,"findAll",[function(it) { return (gs.mc(gs.list(["single-option" , "bubble-single-option"]),"contains",[gs.gp(gs.gp(it,"type"),"name")])) && (gs.bool(gs.gp(gs.gp(it,"answer"),"selected"))); }]),"each",[function(it) { return gs.sp(gs.gp(it,"answer"),"selected",false); }]); return gs.sp(gs.gp(option,"answer"),"selected",true); } gSobject['listEntriesFilter'] = function(val, update, listEntries, listEntriesFiltered) { return gs.execCall(update, this, [function(it) { gs.mc(listEntriesFiltered,"clear",[]); return gs.mc(listEntriesFiltered,"addAll",[gs.mc(listEntries,"findAll",[function(it) { return gs.mc(gs.mc(gs.gp(it,"name"),"toLowerCase",[]),"contains",[gs.mc(val,"toLowerCase",[])]); }])]); }]); } gSobject['removeFromListEntries'] = function(list, index) { return gs.mc(list,"splice",[index, 1]); } gSobject['loadDuplicatesOnOptions'] = function(it) { var options = gs.gp(gs.gp(gSobject.scope,"questionMap"),"options"); var dupOptions = gs.mc(options,"findAll",[function(it) { return gs.equals(gs.gp(gs.gp(it,"type"),"name"), "duplicate-group-button"); }]); return gs.mc(dupOptions,"each",[function(dupOption) { if (gs.bool(dupOption)) { if (gs.bool(gs.gp(gs.gp(dupOption,"answer"),"duplicateOptions",true))) { gs.mc(options,"remove",[dupOption]); gs.mc(options,"addAll",[gs.gp(gs.gp(dupOption,"answer"),"duplicateOptions")]); return gs.mc(options,"add",[dupOption]); }; }; }]); } gSobject['deleteDuplicateGroup'] = function(option) { return gs.mc(gs.mc(gSobject.q,"dialog",[gs.map().add("message","Remove the entry?").add("ok","Remove").add("cancel","Cancel")]),"onOk",[function(data) { var dupOptions = gs.mc(gs.gp(gs.gp(gSobject.scope,"questionMap"),"options"),"findAll",[function(it) { return gs.equals(gs.gp(it,"group"), gs.gp(option,"group")); }]); gs.mc(dupOptions,"each",[function(dupItem) { if (gs.gSin(gs.gp(gs.gp(dupItem,"type"),"name",true), gs.list(["image-upload" , "signature" , "file-upload"]))) { return gs.mc(gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataFile"),"getOne",[gs.gp(gs.gp(gs.gp(dupItem,"answer"),"fileValue"),"_id")]),"delete",[]),"do",[]); }; }]); gs.sp(gs.gp(gSobject.scope,"questionMap"),"options",gs.mc(gs.gp(gs.gp(gSobject.scope,"questionMap"),"options"),"findAll",[function(it) { return gs.gp(it,"group") != gs.gp(option,"group"); }])); gs.mc(gSobject,"resetOptionsAlreadyRendered",[]); var dupOption = gs.mc(gs.gp(gs.gp(gSobject.scope,"questionMap"),"options"),"find",[function(it) { return (gs.gp(it,"group") != gs.gp(option,"originalGroup")) && (gs.equals(gs.gp(gs.gp(it,"type"),"name"), "duplicate-group-button")); }]); return gs.sp(gs.gp(dupOption,"answer"),"duplicateOptions",gs.mc(gs.gp(gs.gp(dupOption,"answer"),"duplicateOptions"),"findAll",[function(it) { return gs.gp(it,"group") != gs.gp(option,"group"); }])); }]); } gSobject['duplicateGroup'] = function(option) { var options = gs.gp(gs.gp(gSobject.scope,"questionMap"),"options"); if (!gs.bool(gs.gp(option,"duplicateCount"))) { gs.sp(option,"duplicateCount",0); }; gs.plusPlus(option,"duplicateCount",true,false); var optionsInGroup = gs.mc(options,"findAll",[function(it) { return (gs.equals(gs.gp(it,"group"), gs.gp(option,"group"))) && (gs.gp(it,"_id") != gs.gp(option,"_id")); }]); optionsInGroup = gs.mc(optionsInGroup,"collect",[function(it) { var dupOption = gs.execStatic(Utils,'deepCopyMap', this,[it]); gs.mc(dupOption,"putAll",[gs.map().add("_id",gs.execStatic(Utils,'uuid', this,[])).add("originalOptionId",gs.gp(dupOption,"_id")).add("group","" + (gs.gp(option,"group")) + "-" + (gs.gp(option,"duplicateCount")) + "").add("originalGroup",gs.gp(option,"group")).add("answer",gs.map().add("_id",gs.execStatic(Utils,'uuid', this,[])).add("user",gs.gp(gs.fs('session', this, gSobject),"userId")).add("isDuplicate",true).add("option",gs.gp(dupOption,"_id")).add("question",gs.gp(dupOption,"question")).add("questionnaire",gs.gp(dupOption,"questionnaire")).add("value",null).add("fileValue",gs.map().add("_id",gs.execStatic(Utils,'uuid', this,[])).add("_path","/protocolO/protoAnswerFile/").add("file",null).add("_dateCreated",gs.date()).add("_lastUpdated",gs.date()))).add("duplicateCount",gs.gp(option,"duplicateCount")).add("isDuplicate",true)]); if (gs.gSin(gs.gp(gs.gp(dupOption,"type"),"name",true), gs.list(["image-upload" , "signature" , "file-upload"]))) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataFile"),"save",[gs.map().add("_id",gs.gp(gs.gp(gs.gp(dupOption,"answer"),"fileValue"),"_id"))]),"do",[]); }; return dupOption; }]); gs.mc(optionsInGroup,"add",[gs.map().add("_id",gs.execStatic(Utils,'uuid', this,[])).add("type",gs.map().add("name","delete-duplicate-group")).add("group","" + (gs.gp(option,"group")) + "-" + (gs.gp(option,"duplicateCount")) + "")]); gs.println(optionsInGroup); if (!gs.bool(gs.gp(gs.gp(option,"answer"),"duplicateOptions"))) { gs.sp(gs.gp(option,"answer"),"duplicateOptions",gs.list([])); }; gs.mc(gs.gp(gs.gp(option,"answer"),"duplicateOptions"),"addAll",[optionsInGroup]); options = gs.mc(options,"findAll",[function(it) { return gs.gp(it,"_id") != gs.gp(option,"_id"); }]); gs.mc(options,"addAll",[optionsInGroup]); gs.mc(options,"add",[option]); gs.sp(gs.gp(gSobject.scope,"questionMap"),"options",options); return gs.mc(gSobject,"resetOptionsAlreadyRendered",[]); } gSobject['animateNext'] = function(it) { gs.sp(gSobject.scope,"animateIn","animated fadeInRight faster"); return gs.sp(gSobject.scope,"animateOut","animated fadeOutLeft faster"); } gSobject['animateBack'] = function(it) { gs.sp(gSobject.scope,"animateIn","animated fadeInLeft faster"); return gs.sp(gSobject.scope,"animateOut","animated fadeOutRight faster"); } gSobject['openSignaturePad'] = function(option) { gs.mc(gSobject,"nextTick",[function(it) { gs.mc(option,"putAll",[gs.mc(gSobject,"newSignaturePad",["signature:" + (gs.gp(option,"_id")) + ""])]); gs.mc(gs.gp(option,"signaturePad"),"addEventListener",["endStroke", function(it) { return gs.execStatic(Utils,'dataUrlToBlob', this,[gs.mc(gs.gp(option,"signaturePad"),"toDataURL",[]), function(blob) { return gs.execStatic(Utils,'post', this,[blob, "file", "protoDataFile", gs.gp(gs.gp(gs.gp(option,"answer"),"fileValue"),"_id"), function(data) { return gs.sp(gs.gp(gs.gp(option,"answer"),"fileValue"),"file",gs.map().add("id","" + (gs.gp(gs.gp(gs.gp(option,"answer"),"fileValue"),"_id")) + "_file").add("filename","blob").add("contentType","image/png")); }]); }]); }]); if (gs.bool(gs.gp(gs.gp(gs.gp(option,"answer"),"fileValue"),"file"))) { return gs.mc(gSobject,"loadImageToCanvas",["/post/file/" + (gs.gp(gs.gp(gs.gp(option,"answer"),"fileValue"),"_id")) + "/file/" + (gs.gp(gs.gp(gs.gp(option,"answer"),"fileValue"),"_lastUpdated")) + "/signature.png", gs.gp(option,"canvasCtx")]); }; }]); return true; } gSobject['isValidEmail'] = function(email) { return gs.exactMatch(email,/^(?=[a-zA-Z0-9@._%+-]{6,254}$)[a-zA-Z0-9._%+-]{1,64}@(?:[a-zA-Z0-9-]{1,63}\.){1,8}[a-zA-Z]{2,63}$/); } gSobject['isValidRsaId'] = function(id) { id = gs.mc(id,"toString",[]); if (gs.mc(id,"size",[]) != 13) { return false; }; var year = +(gs.mc(id,"substring",[0, 2])); var month = +(gs.mc(id,"substring",[2, 4])); var day = +(gs.mc(id,"substring",[4, 6])); var genderDigit = +(gs.mc(id,"substring",[6, 7])); var citizenshipDigit = gs.mc(id,"substring",[10, 11]); var currentYear = gs.mod(gs.mc(gs.date(),"getYear",[]), 100); var fullYear = (year <= currentYear ? gs.plus(2000, year) : gs.plus(1900, year)); var date = gs.mc(gSobject,"moment",["" + (fullYear) + "-" + (gs.mc(gs.mc(month,"toString",[]),"padLeft",[2, "0"])) + "-" + (gs.mc(gs.mc(day,"toString",[]),"padLeft",[2, "0"])) + ""]); if (((gs.plus(gs.mc(date,"month",[]), 1)) != month) || (gs.mc(date,"date",[]) != day)) { return false; }; if ((genderDigit < 0) || (genderDigit > 9)) { return false; }; if (!gs.bool(gs.mc(gs.list(["0" , "1"]),"contains",[citizenshipDigit]))) { return false; }; var sum = 0; var index = 0; for (_i33 = 0, d = id[0]; _i33 < id.length; d = id[++_i33]) { d = +(d); if (gs.equals((gs.mod(index, 2)), 1)) { d = (gs.multiply(d, 2)); }; sum += Math.floor(gs.div(d, 10)); sum += (gs.mod(d, 10)); index++; }; if ((gs.mod(sum, 10)) != 0) { return false; }; gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["luhn passed"]); return true; } gSobject['showContinueBtn'] = function(it) { return !gs.gp(gs.gp(gs.fs('questionMap', this, gSobject),"question",true),"hideContinueBtn",true); } gSobject['logQnActivity'] = function(state) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"eventLogService"),"logQnEntry",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gs.gp(gSobject.scope,"questionnaire"),"name"), state]),"do",[]); gs.println("Logging qn activity------"); return gs.println("" + (gs.gp(gs.gp(gSobject.scope,"questionnaire"),"name")) + ": " + (state) + ""); } gSobject.newSignaturePad = function(name) { var canvas = document.getElementById(name) var signaturePad = new SignaturePad(canvas) return {signaturePad:signaturePad, canvasCtx:canvas.getContext("2d")} } gSobject.loadImageToCanvas = function(url, ctx) { var img = new Image() img.src = url img.onload = function () { ctx.drawImage(img, 0, 0) } } gSobject['resolveBottomSpace'] = function(it) { return (gs.bool(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"showFooter")) ? "bottom-spaced" : "bottom-flush"); } gSobject['hasLeftIcon'] = function(option) { if (gs.bool(gs.gp(option,"leftIcon",true))) { return true; }; return false; } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; ProtocolQNComponent.selectionTypes = gs.list(["single-option" , "multi-option" , "toggle-option" , "bubble-multi-option" , "bubble-single-option"]); function PeptideOrdersComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'PeptideOrdersComponent', simpleName: 'PeptideOrdersComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/peptideOrders"; gSobject['created'] = function(it) { gs.sp(gSobject.scope,"pageLoadStartedAt",gs.gp(gs.date(),"time")); gs.sp(gSobject.scope,"patientLoadCount",0); gs.sp(gSobject.scope,"ordersLoadCount",0); gs.println("PeptideOrdersComponent.created()"); gs.println("PeptideOrdersComponent.created(): startedAt=" + (gs.gp(gSobject.scope,"pageLoadStartedAt")) + ""); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "peptide.orders.page"]),"do",[]); gs.mc(gSobject,"componentTheme",[false]); gs.mc(gSobject,"showFooter",[]); gs.sp(gSobject.scope,"can_order",gs.gp(gs.fs('session', this, gSobject),"can_order")); gs.sp(gSobject.scope,"storeError",null); gs.sp(gSobject.scope,"lineItems",gs.list([])); gs.sp(gSobject.scope,"pendingExpanded",true); gs.sp(gSobject.scope,"historyExpanded",true); gs.sp(gSobject.scope,"detailsVisible",false); gs.sp(gSobject.scope,"selectedOrderItem",null); gs.sp(gSobject.scope,"pendingOrderQuotes",gs.list([])); gs.sp(gSobject.scope,"orderHistory",gs.list([])); gs.sp(gSobject.scope,"categories",gs.list([gs.map().add("label","Medication").add("value","medication").add("icon","rxme").add("color","linear-gradient(135deg, #10646e 0%, #083d43 100%)") , gs.map().add("label","PeptoMeal").add("value","peptomeal").add("icon","peptoMeal").add("color","linear-gradient(135deg, #29d3d3 0%, #0bbaba 100%)") , gs.map().add("label","Vitamins").add("value","vitamins").add("icon","medicationIcon").add("color","linear-gradient(135deg, #2fc9aa 0%, #00a887 100%)") , gs.map().add("label","Muscle Nutrition").add("value","muscle_nutrition").add("icon","muscle").add("color","linear-gradient(135deg, #8849c8 0%, #681fb0 100%)") , gs.map().add("label","PeptoCare").add("value","peptides").add("icon","peptoCare").add("color","linear-gradient(135deg, #ff6aa2 0%, #e24884 100%)") , gs.map().add("label","Alopecia").add("value","aesthetic").add("icon","alopecia").add("color","linear-gradient(135deg, #ff9d4d 0%, #ff751f 100%)")])); gs.sp(gSobject.scope,"token",""); gs.sp(gSobject.scope,"patient",gs.map()); gs.sp(gSobject.scope,"hasActiveOrder",null); gs.sp(gSobject.scope,"loading",true); gs.sp(gSobject.scope,"requiresPrescription",false); gs.sp(gSobject.scope,"ordersValid",false); gs.sp(gSobject.scope,"inventory",gs.list([])); gs.println("inventory2: " + (gs.gp(gSobject.scope,"inventory")) + ""); gs.sp(gSobject.scope,"cart",gs.list([])); if (!gs.bool(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"cart"))) { gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"cart",gs.list([])); } else { gs.sp(gSobject.scope,"cart",gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"cart")); }; return gs.mc(gSobject,"loadPatient",[]); } gSobject['loadInventory'] = function(it) { gs.sp(gSobject.scope,"loading",true); return gs.mc(gs.mc(gs.gp(gs.mc(gs.fs('o', this, gSobject),"localAndRemote",[]),"rxmeAppApiService"),"xeroInventory",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gs.gp(gSobject.scope,"patient"),"id")]),"then",[function(result) { gs.println("inventory: " + (result) + ""); if (gs.bool(result)) { var inventory = result; var deliveryItems = gs.mc(inventory,"findAll",[function(it) { return gs.equals(gs.gp(it,"isDeliveryCharge"), true); }]); var productItems = gs.mc(inventory,"findAll",[function(it) { return !gs.equals(gs.gp(it,"isDeliveryCharge"), true); }]); gs.sp(gSobject.scope,"inventory",productItems); gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"inventory",productItems); gs.println(">>> Loaded " + (gs.mc(productItems,"size",[])) + " product items and " + (gs.mc(deliveryItems,"size",[])) + " delivery options."); gs.mc(gSobject,"updateInventoryWithCart",[]); }; gs.sp(gSobject.scope,"ordersValid",true); return gs.sp(gSobject.scope,"loading",false); }, function(error) { gs.println("Store error: " + (error) + ""); gs.sp(gSobject.scope,"storeError",gs.gp(error,"message")); return gs.sp(gSobject.scope,"loading",false); }]); } gSobject['loadPatient'] = function(it) { gs.sp(gSobject.scope,"patientLoadCount",(gs.plus(gs.elvis(gs.bool(gs.gp(gSobject.scope,"patientLoadCount")) , gs.gp(gSobject.scope,"patientLoadCount") , 0), 1))); var startedAt = gs.gp(gs.date(),"time"); gs.println("PeptideOrdersComponent.loadPatient(): start count=" + (gs.gp(gSobject.scope,"patientLoadCount")) + ""); var handlePatient = function(resp, source) { gs.sp(gSobject.scope,"patient",gs.elvis(gs.bool(resp) , resp , gs.map())); gs.sp(gSobject.scope,"can_order",(gs.equals(gs.gp(resp,"can_order",true), true))); gs.sp(gs.fs('session', this, gSobject),"can_order",gs.gp(gSobject.scope,"can_order")); gs.println("PeptideOrdersComponent.loadPatient(): done in " + (gs.minus(gs.gp(gs.date(),"time"), startedAt)) + "ms source=" + (source) + " patient=" + (gs.gp(gs.gp(gSobject.scope,"patient"),"id",true)) + " can_order=" + (gs.gp(gSobject.scope,"can_order")) + ""); return gs.mc(gSobject,"loadOrders",[]); }; return gs.mc(gs.gp(gs.mc(gs.fs('o', this, gSobject),"localAndRemote",[]),"rxmeAppApiService"),"portalPatientRead",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(resp) { if (gs.bool(gs.gp(resp,"id",true))) { gs.execCall(handlePatient, this, [resp, "portalPatientRead"]); return null; }; }]); } gSobject['loadOrders'] = function(it) { gs.sp(gSobject.scope,"ordersLoadCount",(gs.plus(gs.elvis(gs.bool(gs.gp(gSobject.scope,"ordersLoadCount")) , gs.gp(gSobject.scope,"ordersLoadCount") , 0), 1))); var startedAt = gs.gp(gs.date(),"time"); gs.println("PeptideOrdersComponent.loadOrders(): start count=" + (gs.gp(gSobject.scope,"ordersLoadCount")) + ""); gs.sp(gSobject.scope,"errorMessage",null); gs.sp(gSobject.scope,"invoices",gs.list([])); gs.sp(gSobject.scope,"quotes",gs.list([])); gs.sp(gSobject.scope,"orders",gs.list([])); gs.sp(gSobject.scope,"ordersValid",false); gs.sp(gSobject.scope,"loading",true); gs.sp(gSobject.scope,"inventory",gs.list([])); return gs.mc(gs.mc(gs.gp(gs.mc(gs.fs('o', this, gSobject),"localAndRemote",[]),"rxmeAppApiService"),"orders",[gs.gp(gs.fs('session', this, gSobject),"userId")]),"then",[function(data) { gs.println("loadOrders"); gs.println(data); gs.println("PeptideOrdersComponent.loadOrders(): api returned in " + (gs.minus(gs.gp(gs.date(),"time"), startedAt)) + "ms"); gs.sp(gSobject.scope,"errorMessage",gs.gp(data,"message")); var msg = gs.mc(gs.elvis(gs.bool(gs.gp(data,"message",true)) , gs.gp(data,"message",true) , ""),"toString",[]); if (gs.mc(gs.mc(msg,"toLowerCase",[], null, true),"contains",["xero contact"], null, true)) { gs.sp(gSobject.scope,"loading",false); gs.sp(gSobject.scope,"errorMessage",gs.gp(data,"message")); gs.sp(gSobject.scope,"accountError","XERO_CONTACT_MISSING"); gs.mc(gSobject,"logPageReady",["xero contact missing", startedAt]); }; if (gs.mc(gs.mc(msg,"toLowerCase",[], null, true),"contains",["prescription"], null, true)) { gs.sp(gSobject.scope,"requiresPrescription",true); gs.sp(gSobject.scope,"hasActiveOrder",false); gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"hasActiveOrder",false); gs.sp(gSobject.scope,"ordersValid",false); gs.sp(gSobject.scope,"loading",false); gs.mc(gSobject,"logPageReady",["requires prescription", startedAt]); return null; }; gs.sp(gSobject.scope,"invoices",gs.elvis(gs.bool(gs.gp(data,"invoices",true)) , gs.gp(data,"invoices",true) , gs.list([]))); gs.sp(gSobject.scope,"quotes",gs.mc(gSobject,"sortQuotesByDate",[gs.elvis(gs.bool(gs.gp(data,"quotes",true)) , gs.gp(data,"quotes",true) , gs.list([]))])); gs.sp(gSobject.scope,"orders",gs.mc(gSobject,"sortOrdersByDate",[gs.elvis(gs.bool(gs.gp(data,"orders",true)) , gs.gp(data,"orders",true) , gs.list([]))])); gs.sp(gSobject.scope,"pendingOrderQuotes",gs.mc(gSobject,"pendingQuotes",[])); gs.sp(gSobject.scope,"orderHistory",gs.mc(gSobject,"orderHistoryItems",[])); if ((!gs.bool(gs.gp(gSobject.scope,"orders"))) || (gs.mc(gs.gp(gSobject.scope,"orders"),"isEmpty",[]))) { gs.println("User has no orders → show orders screen without waiting for inventory"); gs.sp(gSobject.scope,"hasActiveOrder",false); gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"hasActiveOrder",false); gs.sp(gSobject.scope,"ordersValid",true); gs.sp(gSobject.scope,"loading",false); gs.mc(gSobject,"logPageReady",["no orders", startedAt]); return null; }; if (gs.mc(gSobject,"hasAnyActiveOrder",[])) { gs.println("At least one active order exists → stay on orders dashboard"); gs.sp(gSobject.scope,"hasActiveOrder",true); gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"hasActiveOrder",true); gs.sp(gSobject.scope,"ordersValid",true); gs.sp(gSobject.scope,"loading",false); gs.mc(gSobject,"logPageReady",["active order", startedAt]); return null; }; gs.println("No active orders"); gs.sp(gSobject.scope,"hasActiveOrder",false); gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"hasActiveOrder",false); gs.sp(gSobject.scope,"ordersValid",true); gs.sp(gSobject.scope,"loading",false); return gs.mc(gSobject,"logPageReady",["no active orders", startedAt]); }, function(error) { gs.println("ORDERS ERROR → " + (error) + ""); var rawMsg = gs.mc(gs.elvis(gs.bool(gs.gp(error,"message",true)) , gs.gp(error,"message",true) , ""),"toString",[]); var safeMsg = "We couldn't load the store. Please try again."; if ((gs.mc(gs.mc(rawMsg,"toLowerCase",[]),"contains",["timeout"])) || (gs.mc(gs.mc(rawMsg,"toLowerCase",[]),"contains",["read timed out"]))) { safeMsg = "The store is taking too long to respond. Please check your connection and try again."; }; gs.sp(gSobject.scope,"storeError",safeMsg); gs.sp(gSobject.scope,"ordersValid",false); gs.sp(gSobject.scope,"loading",false); return gs.mc(gSobject,"logPageReady",["orders error", startedAt]); }]); } gSobject['logPageReady'] = function(reason, loadOrdersStartedAt) { if (loadOrdersStartedAt === undefined) loadOrdersStartedAt = 0; var now = gs.gp(gs.date(),"time"); var pageStartedAt = gs.elvis(gs.bool(gs.gp(gSobject.scope,"pageLoadStartedAt")) , gs.gp(gSobject.scope,"pageLoadStartedAt") , now); var ordersElapsed = (gs.bool(loadOrdersStartedAt) ? gs.minus(now, loadOrdersStartedAt) : null); return gs.println("PeptideOrdersComponent.ready(): reason=" + (reason) + ", totalElapsed=" + (gs.minus(now, pageStartedAt)) + "ms, loadOrdersElapsed=" + (ordersElapsed) + "ms, patientLoadCount=" + (gs.gp(gSobject.scope,"patientLoadCount")) + ", ordersLoadCount=" + (gs.gp(gSobject.scope,"ordersLoadCount")) + ""); } gSobject['retryStore'] = function(it) { gs.sp(gSobject.scope,"storeError",null); gs.sp(gSobject.scope,"loading",true); return gs.mc(gSobject,"loadOrders",[]); } gSobject['addToCart'] = function(product, qty) { var desired = gs.mc(gSobject,"sanitizeQty",[gs.gp(product,"InventoryID"), qty]); if (desired <= 0) { var existing = gs.mc(gs.elvis(gs.bool(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"cart")) , gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"cart") , gs.list([])),"find",[function(it) { return gs.equals(gs.gp(it,"InventoryID"), gs.gp(product,"InventoryID")); }]); if (gs.bool(existing)) { gs.mc(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"cart"),"remove",[existing]); gs.mc(gSobject,"notify",["Removed '" + (gs.gp(product,"Name")) + "' from cart", "warning"]); gs.sp(gSobject.scope,"cart",gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"cart")); gs.mc(gSobject,"updateInventoryWithCart",[]); return null; }; gs.mc(gSobject,"notify",["Please select a quantity before adding to cart.", "warning"]); return null; }; var stock = gs.mc(gSobject,"getStockFor",[gs.gp(product,"InventoryID")]); if (desired > stock) { desired = stock; gs.mc(gSobject,"notify",["Limited to available stock (" + (stock) + "). Quantity adjusted.", "warning"]); }; if (!gs.bool(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"cart"))) { gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"cart",gs.list([])); }; var existingCartItem = gs.mc(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"cart"),"find",[function(it) { return gs.equals(gs.gp(it,"InventoryID"), gs.gp(product,"InventoryID")); }]); if (gs.bool(existingCartItem)) { gs.sp(existingCartItem,"quantity",desired); gs.mc(gSobject,"notify",["Updated '" + (gs.gp(product,"Name")) + "' quantity in cart to " + (desired) + "", "info"]); } else { var productWithQty = gs.mc(product,"clone",[]); gs.sp(productWithQty,"quantity",desired); gs.mc(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"cart"),"add",[productWithQty]); gs.mc(gSobject,"notify",["'" + (gs.gp(product,"Name")) + "' added to cart (x" + (desired) + ")", "positive"]); }; gs.sp(gSobject.scope,"cart",gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"cart")); return gs.mc(gSobject,"updateInventoryWithCart",[]); } gSobject['updateInventoryWithCart'] = function(it) { if ((!gs.bool(gs.gp(gSobject.scope,"cart"))) || (gs.mc(gs.gp(gSobject.scope,"cart"),"isEmpty",[]))) { gs.println("Cart is empty, nothing to update."); return null; }; if ((!gs.bool(gs.gp(gSobject.scope,"inventory"))) || (gs.mc(gs.gp(gSobject.scope,"inventory"),"isEmpty",[]))) { gs.println("Inventory is empty, nothing to update."); return null; }; return gs.mc(gs.gp(gSobject.scope,"cart"),"each",[function(cartItem) { var cartItemId = gs.gp(cartItem,"InventoryID"); var cartQty = gs.elvis(gs.bool(gs.gp(cartItem,"quantity")) , gs.gp(cartItem,"quantity") , 0); var matchingInventoryItem = gs.mc(gs.gp(gSobject.scope,"inventory"),"find",[function(invItem) { return gs.equals(gs.gp(invItem,"InventoryID"), cartItemId); }]); if (gs.bool(matchingInventoryItem)) { var currentQtyOnHand = gs.elvis(gs.bool(gs.gp(matchingInventoryItem,"QuantityOnHand")) , gs.gp(matchingInventoryItem,"QuantityOnHand") , 0); var updatedQty = gs.minus(currentQtyOnHand, cartQty); if (updatedQty < 0) { updatedQty = 0; }; gs.sp(matchingInventoryItem,"QuantityOnHand",updatedQty); return gs.println("Updated inventory: " + (gs.gp(matchingInventoryItem,"Name")) + " (" + (gs.gp(matchingInventoryItem,"InventoryID")) + ") → " + (currentQtyOnHand) + " + " + (cartQty) + " = " + (updatedQty) + ""); }; }]); } gSobject['cartQuantityForProduct'] = function(itemId) { var item = gs.mc(gs.gp(gSobject.scope,"cart"),"find",[function(i) { return gs.gp(i,"InventoryID") === itemId; }]); return (gs.bool(item) ? gs.gp(item,"quantity") : 0); } gSobject['formattedText'] = function(date, invoiceRef) { if ((!gs.bool(invoiceRef)) || (!gs.bool(date))) { return null; }; return "" + (gs.mc(gs.date(date),"format",["yy-MM-dd"])) + " - " + (invoiceRef) + ""; } gSobject['transformText'] = function(input) { if (!gs.bool(input)) { return null; }; return "" + (gs.mc(input,"toLowerCase",[])) + ""; } gSobject['shoppingCart'] = function(it) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/peptideOrdersCart"]); } gSobject['selectCategory'] = function(categoryValue) { return gs.mc(gSobject,"openCatalog",[categoryValue]); } gSobject['openCatalog'] = function(categoryValue) { if (categoryValue === undefined) categoryValue = "all"; var selectedCategory = gs.elvis(gs.bool(categoryValue) , categoryValue , "all"); if (gs.equals(selectedCategory, "all")) { gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/peptideOrderCatalog"]); return null; }; return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/peptideOrderCatalog/" + (selectedCategory) + ""]); } gSobject['pendingQuotes'] = function(it) { var activeOrderQuotes = gs.mc(gs.mc(gs.mc(gs.elvis(gs.bool(gs.gp(gSobject.scope,"orders")) , gs.gp(gSobject.scope,"orders") , gs.list([])),"findAll",[function(order) { return gs.mc(gSobject,"isActiveOrderStatus",[gs.gp(order,"status",true)]); }]),"collect",[function(order) { var quote = gs.elvis(gs.bool(gs.gp(gs.gp(order,"meta",true),"quote",true)) , gs.gp(gs.gp(order,"meta",true),"quote",true) , gs.map()); var orderRef = gs.elvis(gs.bool(gs.gp(order,"xero_quote_number",true)) , gs.gp(order,"xero_quote_number",true) , gs.mc(gSobject,"quoteReferenceValue",[quote])); var matchedQuote = gs.mc(gs.elvis(gs.bool(gs.gp(gSobject.scope,"quotes")) , gs.gp(gSobject.scope,"quotes") , gs.list([])),"find",[function(existingQuote) { return gs.equals(gs.mc(gSobject,"quoteReferenceValue",[existingQuote]), orderRef); }]); var fullQuote = gs.elvis(gs.bool(matchedQuote) , matchedQuote , quote); return gs.map().add("kind","quote").add("QuoteID",gs.elvis(gs.bool(gs.gp(matchedQuote,"QuoteID",true)) , gs.gp(matchedQuote,"QuoteID",true) , gs.elvis(gs.bool(gs.gp(quote,"QuoteID",true)) , gs.gp(quote,"QuoteID",true) , gs.gp(order,"id",true)))).add("QuoteNumber",gs.elvis(gs.bool(gs.gp(matchedQuote,"QuoteNumber",true)) , gs.gp(matchedQuote,"QuoteNumber",true) , gs.elvis(gs.bool(gs.gp(quote,"QuoteNumber",true)) , gs.gp(quote,"QuoteNumber",true) , gs.gp(order,"xero_quote_number",true)))).add("Reference",gs.elvis(gs.bool(gs.gp(matchedQuote,"Reference",true)) , gs.gp(matchedQuote,"Reference",true) , gs.elvis(gs.bool(gs.gp(quote,"Reference",true)) , gs.gp(quote,"Reference",true) , gs.gp(order,"xero_quote_number",true)))).add("DateString",gs.elvis(gs.bool(gs.gp(matchedQuote,"DateString",true)) , gs.gp(matchedQuote,"DateString",true) , gs.elvis(gs.bool(gs.gp(quote,"DateString",true)) , gs.gp(quote,"DateString",true) , gs.gp(order,"created_at",true)))).add("Date",gs.elvis(gs.bool(gs.gp(matchedQuote,"Date",true)) , gs.gp(matchedQuote,"Date",true) , gs.elvis(gs.bool(gs.gp(quote,"Date",true)) , gs.gp(quote,"Date",true) , gs.gp(order,"created_at",true)))).add("Status",gs.elvis(gs.bool(gs.gp(matchedQuote,"Status",true)) , gs.gp(matchedQuote,"Status",true) , gs.elvis(gs.bool(gs.gp(quote,"Status",true)) , gs.gp(quote,"Status",true) , ""))).add("OrderStatus",gs.gp(order,"status",true)).add("Total",gs.elvis(gs.bool(gs.gp(matchedQuote,"Total",true)) , gs.gp(matchedQuote,"Total",true) , gs.elvis(gs.bool(gs.gp(quote,"Total",true)) , gs.gp(quote,"Total",true) , gs.elvis(gs.bool(gs.gp(matchedQuote,"SubTotal",true)) , gs.gp(matchedQuote,"SubTotal",true) , gs.elvis(gs.bool(gs.gp(quote,"SubTotal",true)) , gs.gp(quote,"SubTotal",true) , 0))))).add("popUploaded",gs.equals(gs.gp(gs.gp(order,"meta",true),"pop",true), true)).add("raw",fullQuote); }]),"findAll",[function(it) { return gs.mc(gSobject,"quoteReferenceValue",[it]); }]); if ((gs.bool(activeOrderQuotes)) && (!gs.bool(gs.mc(activeOrderQuotes,"isEmpty",[])))) { return gs.mc(gSobject,"dedupeQuotesByReference",[activeOrderQuotes]); }; return gs.mc(gSobject,"dedupeQuotesByReference",[gs.mc(gs.elvis(gs.bool(gs.gp(gSobject.scope,"quotes")) , gs.gp(gSobject.scope,"quotes") , gs.list([])),"findAll",[function(quote) { var status = gs.mc(gs.elvis(gs.bool(gs.gp(quote,"Status",true)) , gs.gp(quote,"Status",true) , ""),"toLowerCase",[]); if (gs.gSin(status, gs.list(["accepted" , "declined" , "deleted" , "cancelled" , "canceled" , "invoiced"]))) { return false; }; return !gs.mc(gSobject,"hasFinalizedOrderForQuote",[quote]); }])]); } gSobject['hasFinalizedOrderForQuote'] = function(quote) { var quoteRef = gs.mc(gSobject,"quoteReferenceValue",[quote]); if (!gs.bool(quoteRef)) { return false; }; return gs.mc(gs.elvis(gs.bool(gs.gp(gSobject.scope,"orders")) , gs.gp(gSobject.scope,"orders") , gs.list([])),"any",[function(order) { if (gs.mc(gSobject,"isActiveOrderStatus",[gs.gp(order,"status",true)])) { return false; }; var orderQuote = gs.elvis(gs.bool(gs.gp(gs.gp(order,"meta",true),"quote",true)) , gs.gp(gs.gp(order,"meta",true),"quote",true) , gs.map()); return gs.equals(gs.mc(gSobject,"quoteReferenceValue",[orderQuote]), quoteRef); }]); } gSobject['quoteReferenceValue'] = function(quote) { return gs.elvis(gs.bool(gs.gp(quote,"QuoteNumber",true)) , gs.gp(quote,"QuoteNumber",true) , gs.elvis(gs.bool(gs.gp(quote,"Reference",true)) , gs.gp(quote,"Reference",true) , gs.elvis(gs.bool(gs.gp(quote,"QuoteID",true)) , gs.gp(quote,"QuoteID",true) , gs.elvis(gs.bool(gs.gp(quote,"InvoiceNumber",true)) , gs.gp(quote,"InvoiceNumber",true) , gs.gp(quote,"InvoiceID",true))))); } gSobject['orderHistoryItems'] = function(it) { return gs.mc(gs.mc(gs.mc(gs.elvis(gs.bool(gs.gp(gSobject.scope,"orders")) , gs.gp(gSobject.scope,"orders") , gs.list([])),"findAll",[function(order) { return !gs.mc(gSobject,"isActiveOrderStatus",[gs.gp(order,"status",true)]); }]),"collect",[function(order) { var quote = gs.elvis(gs.bool(gs.gp(gs.gp(order,"meta",true),"quote",true)) , gs.gp(gs.gp(order,"meta",true),"quote",true) , gs.map()); var status = gs.mc(gs.elvis(gs.bool(gs.gp(order,"status",true)) , gs.gp(order,"status",true) , ""),"toLowerCase",[]); return gs.map().add("kind","order").add("date",gs.elvis(gs.bool(gs.gp(order,"created_at",true)) , gs.gp(order,"created_at",true) , gs.elvis(gs.bool(gs.gp(quote,"DateString",true)) , gs.gp(quote,"DateString",true) , gs.gp(quote,"Date",true)))).add("ref",gs.elvis(gs.mc(gSobject,"quoteReferenceValue",[quote]) , gs.mc(gSobject,"quoteReferenceValue",[quote]) , gs.gp(order,"id",true))).add("amount",gs.elvis(gs.bool(gs.gp(quote,"Total",true)) , gs.gp(quote,"Total",true) , 0)).add("status",(gs.mc(status,"contains",["cancel"]) ? "Order cancelled" : "Order complete")).add("type",(gs.mc(status,"contains",["cancel"]) ? "Quotation" : "Sales")).add("raw",order); }]),"sort",[function(a, b) { return gs.spaceShip(gs.mc(gSobject,"safeDateValue",[gs.gp(b,"date",true)]), gs.mc(gSobject,"safeDateValue",[gs.gp(a,"date",true)])); }]); } gSobject['safeDateValue'] = function(dateValue) { if (!gs.bool(dateValue)) { return 0; }; try { if (gs.instanceOf(dateValue, "Date")) { return gs.gp(dateValue,"time"); }; var txt = gs.mc(dateValue,"toString",[]); if (gs.mc(txt,"contains",["/Date("])) { return gs.mc(gs.mc(txt,"replaceAll",["[^0-9]", ""]),"toLong",[]); }; return gs.gp(gs.date(txt),"time"); } catch (ignored) { return 0; } ; } gSobject['formatOrderDate'] = function(dateValue) { if (!gs.bool(dateValue)) { return ""; }; try { return gs.mc(gs.mc(gSobject,"moment",[dateValue]),"format",["YYYY-MM-DD"]); } catch (ignored) { return gs.elvis(gs.mc(dateValue,"toString",[], null, true) , gs.mc(dateValue,"toString",[], null, true) , ""); } ; } gSobject['formatMoney'] = function(amount) { try { return "R" + (gs.execStatic(String,'format', this,["%.0f", gs.elvis(gs.bool(amount) , amount , 0)])) + ""; } catch (ignored) { return "R" + (gs.elvis(gs.bool(amount) , amount , 0)) + ""; } ; } gSobject['pendingOrderStatusLabel'] = function(quote) { var orderStatus = gs.mc(gs.elvis(gs.bool(gs.gp(quote,"OrderStatus",true)) , gs.gp(quote,"OrderStatus",true) , ""),"toLowerCase",[]); if (gs.mc(gSobject,"isActiveOrderStatus",[orderStatus])) { return "Order received"; }; var quoteStatus = gs.mc(gs.elvis(gs.bool(gs.gp(quote,"Status",true)) , gs.gp(quote,"Status",true) , ""),"toLowerCase",[]); if (gs.gSin(quoteStatus, gs.list(["draft" , "sent"]))) { return "Order received"; }; return gs.elvis(gs.bool(gs.gp(quote,"OrderStatus",true)) , gs.gp(quote,"OrderStatus",true) , gs.elvis(gs.bool(gs.gp(quote,"Status",true)) , gs.gp(quote,"Status",true) , "Pending")); } gSobject['pendingOrderAmountLabel'] = function(quote) { return gs.mc(gSobject,"formatMoney",[gs.elvis(gs.bool(gs.gp(quote,"Total",true)) , gs.gp(quote,"Total",true) , 0)]); } gSobject['showPaymentDueBadge'] = function(quote) { if (gs.equals(gs.gp(quote,"popUploaded",true), true)) { return false; }; var quoteStatus = gs.mc(gs.elvis(gs.bool(gs.gp(quote,"Status",true)) , gs.gp(quote,"Status",true) , ""),"toLowerCase",[]); return gs.gSin(quoteStatus, gs.list(["draft" , "sent"])); } gSobject['orderHistoryStatusColor'] = function(item) { var status = gs.mc(gs.elvis(gs.bool(gs.gp(item,"status",true)) , gs.gp(item,"status",true) , ""),"toLowerCase",[]); if (gs.mc(status,"contains",["cancel"])) { return "negative"; }; if (((gs.mc(status,"contains",["complete"])) || (gs.mc(status,"contains",["paid"]))) || (gs.mc(status,"contains",["accepted"]))) { return "positive"; }; return "warning"; } gSobject['showOrderDetails'] = function(item) { gs.sp(gSobject.scope,"selectedOrderItem",item); return gs.sp(gSobject.scope,"detailsVisible",true); } gSobject['selectedOrderQuote'] = function(it) { if (!gs.bool(gs.gp(gSobject.scope,"selectedOrderItem"))) { return gs.map(); }; if (gs.equals(gs.gp(gs.gp(gSobject.scope,"selectedOrderItem"),"kind",true), "order")) { return gs.elvis(gs.bool(gs.gp(gs.gp(gs.gp(gs.gp(gSobject.scope,"selectedOrderItem"),"raw",true),"meta",true),"quote",true)) , gs.gp(gs.gp(gs.gp(gs.gp(gSobject.scope,"selectedOrderItem"),"raw",true),"meta",true),"quote",true) , gs.map()); }; if (gs.bool(gs.gp(gs.gp(gSobject.scope,"selectedOrderItem"),"raw",true))) { return gs.gp(gs.gp(gSobject.scope,"selectedOrderItem"),"raw"); }; return gs.gp(gSobject.scope,"selectedOrderItem"); } gSobject['selectedOrderContactName'] = function(it) { var quote = gs.mc(gSobject,"selectedOrderQuote",[]); var first = gs.elvis(gs.bool(gs.gp(gs.gp(quote,"Contact",true),"FirstName",true)) , gs.gp(gs.gp(quote,"Contact",true),"FirstName",true) , ""); var last = gs.elvis(gs.bool(gs.gp(gs.gp(quote,"Contact",true),"LastName",true)) , gs.gp(gs.gp(quote,"Contact",true),"LastName",true) , ""); var full = gs.mc("" + (first) + " " + (last) + "","trim",[]); return gs.elvis(gs.bool(full) , full , gs.elvis(gs.bool(gs.gp(gs.gp(quote,"Contact",true),"Name",true)) , gs.gp(gs.gp(quote,"Contact",true),"Name",true) , "")); } gSobject['selectedOrderReference'] = function(it) { var quote = gs.mc(gSobject,"selectedOrderQuote",[]); return gs.elvis(gs.mc(gSobject,"quoteReferenceValue",[quote]) , gs.mc(gSobject,"quoteReferenceValue",[quote]) , ""); } gSobject['selectedOrderStatus'] = function(it) { return gs.elvis(gs.bool(gs.gp(gs.gp(gSobject.scope,"selectedOrderItem"),"status",true)) , gs.gp(gs.gp(gSobject.scope,"selectedOrderItem"),"status",true) , gs.elvis(gs.bool(gs.gp(gs.gp(gSobject.scope,"selectedOrderItem"),"OrderStatus",true)) , gs.gp(gs.gp(gSobject.scope,"selectedOrderItem"),"OrderStatus",true) , gs.elvis(gs.bool(gs.gp(gs.mc(gSobject,"selectedOrderQuote",[]),"Status",true)) , gs.gp(gs.mc(gSobject,"selectedOrderQuote",[]),"Status",true) , ""))); } gSobject['selectedOrderDisplayDate'] = function(it) { var quote = gs.mc(gSobject,"selectedOrderQuote",[]); return gs.mc(gSobject,"formatOrderDate",[gs.elvis(gs.bool(gs.gp(gs.gp(gSobject.scope,"selectedOrderItem"),"date",true)) , gs.gp(gs.gp(gSobject.scope,"selectedOrderItem"),"date",true) , gs.elvis(gs.bool(gs.gp(gs.gp(gSobject.scope,"selectedOrderItem"),"DateString",true)) , gs.gp(gs.gp(gSobject.scope,"selectedOrderItem"),"DateString",true) , gs.elvis(gs.bool(gs.gp(gs.gp(gSobject.scope,"selectedOrderItem"),"Date",true)) , gs.gp(gs.gp(gSobject.scope,"selectedOrderItem"),"Date",true) , gs.elvis(gs.bool(gs.gp(quote,"DateString",true)) , gs.gp(quote,"DateString",true) , gs.gp(quote,"Date",true)))))]); } gSobject['selectedOrderDateTime'] = function(it) { var quote = gs.mc(gSobject,"selectedOrderQuote",[]); return gs.mc(gSobject,"formatOrderDateTime",[gs.elvis(gs.bool(gs.gp(gs.gp(gSobject.scope,"selectedOrderItem"),"date",true)) , gs.gp(gs.gp(gSobject.scope,"selectedOrderItem"),"date",true) , gs.elvis(gs.bool(gs.gp(gs.gp(gSobject.scope,"selectedOrderItem"),"DateString",true)) , gs.gp(gs.gp(gSobject.scope,"selectedOrderItem"),"DateString",true) , gs.elvis(gs.bool(gs.gp(gs.gp(gSobject.scope,"selectedOrderItem"),"Date",true)) , gs.gp(gs.gp(gSobject.scope,"selectedOrderItem"),"Date",true) , gs.elvis(gs.bool(gs.gp(quote,"Date",true)) , gs.gp(quote,"Date",true) , gs.gp(quote,"DateString",true)))))]); } gSobject['formatOrderDateTime'] = function(dateValue) { if (!gs.bool(dateValue)) { return ""; }; try { return gs.mc(gs.mc(gSobject,"moment",[dateValue]),"format",["YYYY MMM DD | HH:mm"]); } catch (ignored) { return gs.elvis(gs.mc(dateValue,"toString",[], null, true) , gs.mc(dateValue,"toString",[], null, true) , ""); } ; } gSobject['selectedOrderLineItems'] = function(it) { return gs.elvis(gs.bool(gs.gp(gs.mc(gSobject,"selectedOrderQuote",[]),"LineItems",true)) , gs.gp(gs.mc(gSobject,"selectedOrderQuote",[]),"LineItems",true) , gs.list([])); } gSobject['selectedOrderAddress'] = function(it) { var quote = gs.mc(gSobject,"selectedOrderQuote",[]); return gs.elvis(gs.bool(gs.gp(quote,"Summary",true)) , gs.gp(quote,"Summary",true) , "pickup"); } gSobject['selectedOrderEmail'] = function(it) { return gs.elvis(gs.bool(gs.gp(gs.gp(gs.mc(gSobject,"selectedOrderQuote",[]),"Contact",true),"EmailAddress",true)) , gs.gp(gs.gp(gs.mc(gSobject,"selectedOrderQuote",[]),"Contact",true),"EmailAddress",true) , ""); } gSobject['selectedOrderContactNumber'] = function(it) { return gs.elvis(gs.bool(gs.gp(gs.gp(gs.fs('session', this, gSobject),"user",true),"cellphone",true)) , gs.gp(gs.gp(gs.fs('session', this, gSobject),"user",true),"cellphone",true) , ""); } gSobject['selectedOrderAccountNumber'] = function(it) { return gs.elvis(gs.bool(gs.gp(gs.gp(gs.mc(gSobject,"selectedOrderQuote",[]),"Contact",true),"AccountNumber",true)) , gs.gp(gs.gp(gs.mc(gSobject,"selectedOrderQuote",[]),"Contact",true),"AccountNumber",true) , ""); } gSobject['hasAnyActiveOrder'] = function(it) { return gs.mc(gs.elvis(gs.bool(gs.gp(gSobject.scope,"orders")) , gs.gp(gSobject.scope,"orders") , gs.list([])),"any",[function(order) { return gs.mc(gSobject,"isActiveOrderStatus",[gs.gp(order,"status",true)]); }]); } gSobject['isActiveOrderStatus'] = function(statusValue) { var status = gs.mc(gs.elvis(gs.bool(statusValue) , statusValue , ""),"toLowerCase",[]); return gs.gSin(status, gs.list(["pending" , "sent" , "processing" , "combined" , "duplicate" , "no-answer"])); } gSobject['sortOrdersByDate'] = function(orders) { return gs.mc(gs.elvis(gs.bool(orders) , orders , gs.list([])),"sort",[function(a, b) { return gs.spaceShip(gs.mc(gSobject,"orderDateValue",[b]), gs.mc(gSobject,"orderDateValue",[a])); }]); } gSobject['sortQuotesByDate'] = function(quotes) { return gs.mc(gs.elvis(gs.bool(quotes) , quotes , gs.list([])),"sort",[function(a, b) { return gs.spaceShip(gs.mc(gSobject,"safeDateValue",[gs.elvis(gs.bool(gs.gp(b,"DateString",true)) , gs.gp(b,"DateString",true) , gs.gp(b,"Date",true))]), gs.mc(gSobject,"safeDateValue",[gs.elvis(gs.bool(gs.gp(a,"DateString",true)) , gs.gp(a,"DateString",true) , gs.gp(a,"Date",true))])); }]); } gSobject['orderDateValue'] = function(order) { return gs.mc(gSobject,"safeDateValue",[gs.elvis(gs.bool(gs.gp(order,"created_at",true)) , gs.gp(order,"created_at",true) , gs.elvis(gs.bool(gs.gp(order,"updated_at",true)) , gs.gp(order,"updated_at",true) , gs.elvis(gs.bool(gs.gp(gs.gp(gs.gp(order,"meta",true),"quote",true),"DateString",true)) , gs.gp(gs.gp(gs.gp(order,"meta",true),"quote",true),"DateString",true) , gs.gp(gs.gp(gs.gp(order,"meta",true),"quote",true),"Date",true))))]); } gSobject['dedupeQuotesByReference'] = function(quotes) { var seen = gs.set(gs.list([])); return gs.mc(gs.mc(gSobject,"sortQuotesByDate",[quotes]),"findAll",[function(quote) { var ref = gs.mc(gSobject,"quoteReferenceValue",[quote]); if (!gs.bool(ref)) { return false; }; if (gs.mc(seen,"contains",[ref])) { return false; }; gs.mc(seen,'leftShift', gs.list([ref])); return true; }]); } gSobject['isActiveOrder'] = function(order) { var s = gs.mc(gs.elvis(gs.bool(gs.gp(order,"status",true)) , gs.gp(order,"status",true) , ""),"toLowerCase",[]); return !gs.gSin(s, gs.list(["completed" , "cancelled"])); } gSobject['getStockFor'] = function(itemId) { var inv = gs.elvis(gs.bool(gs.gp(gSobject.scope,"inventory")) , gs.gp(gSobject.scope,"inventory") , gs.list([])); return gs.elvis(gs.bool(gs.gp(gs.mc(inv,"find",[function(it) { return gs.equals(gs.gp(it,"InventoryID"), itemId); }]),"QuantityOnHand",true)) , gs.gp(gs.mc(inv,"find",[function(it) { return gs.equals(gs.gp(it,"InventoryID"), itemId); }]),"QuantityOnHand",true) , 0); } gSobject['sanitizeQty'] = function(itemId, qty) { var q = gs.elvis(gs.bool(qty) , qty , 0); if (q < 0) { q = 0; }; var stock = gs.mc(gSobject,"getStockFor",[itemId]); if (q > stock) { q = stock; }; return q; } gSobject['isNotAccepted'] = function(order) { var s = gs.mc(gs.elvis(gs.bool(gs.gp(order,"status",true)) , gs.gp(order,"status",true) , ""),"toLowerCase",[]); return (gs.bool(s)) && (s != "accepted"); } gSobject['isOutOfStock'] = function(product) { return gs.elvis(gs.bool(gs.gp(product,"QuantityOnHand",true)) , gs.gp(product,"QuantityOnHand",true) , 0) <= 0; } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function PeptideOrderDetailComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'PeptideOrderDetailComponent', simpleName: 'PeptideOrderDetailComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/peptideOrderDetail" , "/peptideOrderDetail/:id"]); gSobject['created'] = function(it) { gs.println("PeptideOrderDetailComponent.created()"); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "peptide.detail.page"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[]); gs.mc(gSobject,"componentTheme",[false]); if (!gs.bool(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"cart"))) { gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"cart",gs.list([])); }; gs.sp(gSobject.scope,"cart",gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"cart")); gs.sp(gSobject.scope,"product",gs.map()); gs.sp(gSobject.scope,"productQuantity",0); return gs.mc(gSobject,"loadProduct",[]); } gSobject['loadProduct'] = function(it) { var inventory = gs.elvis(gs.bool(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"inventory")) , gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"inventory") , gs.list([])); var matchedProduct = gs.mc(inventory,"find",[function(it) { return gs.equals(gs.gp(it,"InventoryID"), gs.gp(gs.gp(gSobject.route,"params"),"id")); }]); if (gs.bool(matchedProduct)) { gs.sp(gSobject.scope,"product",matchedProduct); var cartItem = gs.mc(gs.gp(gSobject.scope,"cart"),"find",[function(it) { return gs.equals(gs.gp(it,"InventoryID"), gs.gp(matchedProduct,"InventoryID")); }]); return gs.sp(gSobject.scope,"productQuantity",(gs.bool(cartItem) ? gs.gp(cartItem,"quantity") : 0)); } else { gs.mc(gSobject,"notify",["Product not found", "negative"]); return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/peptideOrders"]); }; } gSobject['isOutOfStock'] = function(it) { var qty = gs.elvis(gs.bool(gs.gp(gs.gp(gSobject.scope,"product"),"QuantityOnHand",true)) , gs.gp(gs.gp(gSobject.scope,"product"),"QuantityOnHand",true) , 0); return (qty <= 0 ? "Out of stock" : "In stock (" + (qty) + ")"); } gSobject['increaseStep'] = function(it) { var maxQty = gs.elvis(gs.bool(gs.gp(gs.gp(gSobject.scope,"product"),"QuantityOnHand")) , gs.gp(gs.gp(gSobject.scope,"product"),"QuantityOnHand") , 0); if (gs.gp(gSobject.scope,"productQuantity") < maxQty) { return gs.sp(gSobject.scope,"productQuantity",gs.gp(gSobject.scope,"productQuantity") + 1); } else { return gs.mc(gSobject,"notify",["Cannot exceed available stock (" + (maxQty) + ")", "warning"]); }; } gSobject['decreaseStep'] = function(it) { if (gs.gp(gSobject.scope,"productQuantity") > 0) { return gs.sp(gSobject.scope,"productQuantity",gs.gp(gSobject.scope,"productQuantity") - 1); }; } gSobject['updateCart'] = function(it) { var qty = gs.elvis(gs.bool(gs.gp(gSobject.scope,"productQuantity")) , gs.gp(gSobject.scope,"productQuantity") , 0); var product = gs.gp(gSobject.scope,"product"); if (gs.equals(qty, 0)) { gs.mc(gSobject,"notify",["Quantity is zero. Nothing added to cart.", "warning"]); return null; }; var existingCartItem = gs.mc(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"cart"),"find",[function(it) { return gs.equals(gs.gp(it,"InventoryID"), gs.gp(product,"InventoryID")); }]); if (gs.bool(existingCartItem)) { gs.sp(existingCartItem,"quantity",qty); return gs.mc(gSobject,"notify",["Updated '" + (gs.gp(product,"Name")) + "' quantity in cart to " + (qty) + "", "info"]); } else { var productWithQty = gs.mc(product,"clone",[]); gs.sp(productWithQty,"quantity",qty); gs.mc(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"cart"),"add",[productWithQty]); return gs.mc(gSobject,"notify",["" + (gs.gp(product,"Name")) + " added to cart with quantity " + (qty) + "", "positive"]); }; } gSobject['shoppingCart'] = function(it) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/peptideOrdersCart"]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function PeptideOrderCatalogComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'PeptideOrderCatalogComponent', simpleName: 'PeptideOrderCatalogComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = gs.list(["/peptideOrderCatalog" , "/peptideOrderCatalog/:category"]); gSobject['created'] = function(it) { gs.println("PeptideOrderCatalogComponent.created()"); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "peptide.catalog.page"]),"do",[]); gs.mc(gSobject,"componentTheme",[false]); gs.mc(gSobject,"showFooter",[false]); gs.sp(gSobject.scope,"can_order",gs.gp(gs.fs('session', this, gSobject),"can_order")); gs.sp(gSobject.scope,"storeError",null); gs.sp(gSobject.scope,"loading",true); gs.sp(gSobject.scope,"patient",gs.map()); gs.sp(gSobject.scope,"inventory",gs.list([])); gs.sp(gSobject.scope,"cart",gs.elvis(gs.bool(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"cart")) , gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"cart") , gs.list([]))); gs.sp(gSobject.scope,"selectedCategory",gs.elvis(gs.bool(gs.gp(gs.gp(gSobject.route,"params",true),"category",true)) , gs.gp(gs.gp(gSobject.route,"params",true),"category",true) , "all")); gs.sp(gSobject.scope,"categoryExpanded",gs.map()); gs.sp(gSobject.scope,"categories",gs.list([gs.map().add("label","Medication").add("catalogLabel","Prescription").add("value","medication").add("icon","rxme").add("color","linear-gradient(135deg, #10646e 0%, #083d43 100%)") , gs.map().add("label","PeptoMeal").add("value","peptomeal").add("icon","peptoMeal").add("color","linear-gradient(135deg, #29d3d3 0%, #0bbaba 100%)") , gs.map().add("label","Vitamins").add("value","vitamins").add("icon","medicationIcon").add("color","linear-gradient(135deg, #2fc9aa 0%, #00a887 100%)") , gs.map().add("label","Muscle Nutrition").add("value","muscle_nutrition").add("icon","muscle").add("color","linear-gradient(135deg, #8849c8 0%, #681fb0 100%)") , gs.map().add("label","PeptoCare").add("value","peptides").add("icon","peptoCare").add("color","linear-gradient(135deg, #ff6aa2 0%, #e24884 100%)") , gs.map().add("label","Alopecia").add("value","aesthetic").add("icon","alopecia").add("color","linear-gradient(135deg, #ff9d4d 0%, #ff751f 100%)")])); gs.mc(gSobject,"initializeExpandedCategories",[]); return gs.mc(gSobject,"loadPatient",[]); } gSobject['loadPatient'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppApiService"),"portalPatient",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(resp) { gs.sp(gSobject.scope,"patient",resp); gs.sp(gSobject.scope,"can_order",(gs.equals(gs.gp(resp,"can_order",true), true))); gs.sp(gs.fs('session', this, gSobject),"can_order",gs.gp(gSobject.scope,"can_order")); return gs.mc(gSobject,"loadInventory",[]); }]); } gSobject['loadInventory'] = function(it) { gs.sp(gSobject.scope,"loading",true); return gs.mc(gs.mc(gs.gp(gs.mc(gs.fs('o', this, gSobject),"localAndRemote",[]),"rxmeAppApiService"),"xeroInventory",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gs.gp(gSobject.scope,"patient"),"id")]),"then",[function(result) { var inventory = gs.elvis(gs.bool(result) , result , gs.list([])); var productItems = gs.mc(inventory,"findAll",[function(it) { return !gs.equals(gs.gp(it,"isDeliveryCharge"), true); }]); gs.sp(gSobject.scope,"inventory",productItems); gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"inventory",productItems); gs.mc(gSobject,"updateInventoryWithCart",[]); gs.mc(gSobject,"initializeExpandedCategories",[]); return gs.sp(gSobject.scope,"loading",false); }, function(error) { gs.println("Store error: " + (error) + ""); gs.sp(gSobject.scope,"storeError",gs.elvis(gs.bool(gs.gp(error,"message",true)) , gs.gp(error,"message",true) , "Unable to load inventory.")); return gs.sp(gSobject.scope,"loading",false); }]); } gSobject['shoppingCart'] = function(it) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/peptideOrdersCart"]); } gSobject['selectCategory'] = function(categoryValue) { gs.sp(gSobject.scope,"selectedCategory",gs.elvis(gs.bool(categoryValue) , categoryValue , "all")); return gs.mc(gSobject,"initializeExpandedCategories",[]); } gSobject['openProduct'] = function(product) { if (!gs.bool(gs.gp(product,"InventoryID",true))) { return null; }; return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/peptideOrderDetail/" + (gs.gp(product,"InventoryID")) + ""]); } gSobject['filteredInventory'] = function(it) { var inventory = gs.elvis(gs.bool(gs.gp(gSobject.scope,"inventory")) , gs.gp(gSobject.scope,"inventory") , gs.list([])); if ((!gs.bool(gs.gp(gSobject.scope,"selectedCategory"))) || (gs.equals(gs.gp(gSobject.scope,"selectedCategory"), "all"))) { return inventory; }; return gs.mc(inventory,"findAll",[function(product) { return gs.mc(gSobject,"categoryMatches",[product, gs.gp(gSobject.scope,"selectedCategory")]); }]); } gSobject['selectedCategoryLabel'] = function(it) { if ((!gs.bool(gs.gp(gSobject.scope,"selectedCategory"))) || (gs.equals(gs.gp(gSobject.scope,"selectedCategory"), "all"))) { return "All products"; }; return gs.elvis(gs.bool(gs.gp(gs.mc(gs.elvis(gs.bool(gs.gp(gSobject.scope,"categories")) , gs.gp(gSobject.scope,"categories") , gs.list([])),"find",[function(it) { return gs.equals(gs.gp(it,"value"), gs.gp(gSobject.scope,"selectedCategory")); }]),"label",true)) , gs.gp(gs.mc(gs.elvis(gs.bool(gs.gp(gSobject.scope,"categories")) , gs.gp(gSobject.scope,"categories") , gs.list([])),"find",[function(it) { return gs.equals(gs.gp(it,"value"), gs.gp(gSobject.scope,"selectedCategory")); }]),"label",true) , "Products"); } gSobject['initializeExpandedCategories'] = function(it) { gs.sp(gSobject.scope,"categoryExpanded",gs.map()); return gs.mc(gs.mc(gSobject,"visibleCategories",[]),"eachWithIndex",[function(category, index) { var shouldOpen = (gs.equals(gs.gp(gSobject.scope,"selectedCategory"), "all") ? gs.equals(index, 0) : gs.equals(gs.gp(category,"value",true), gs.gp(gSobject.scope,"selectedCategory"))); return (gs.gp(gSobject.scope,"categoryExpanded")[gs.gp(category,"value")]) = shouldOpen; }]); } gSobject['visibleCategories'] = function(it) { var categories = gs.elvis(gs.bool(gs.gp(gSobject.scope,"categories")) , gs.gp(gSobject.scope,"categories") , gs.list([])); if ((gs.bool(gs.gp(gSobject.scope,"selectedCategory"))) && (gs.gp(gSobject.scope,"selectedCategory") != "all")) { return gs.mc(categories,"findAll",[function(it) { return gs.equals(gs.gp(it,"value"), gs.gp(gSobject.scope,"selectedCategory")); }]); }; return gs.mc(categories,"findAll",[function(it) { return gs.mc(gs.mc(gSobject,"categoryProducts",[gs.gp(it,"value")]),"size",[]) > 0; }]); } gSobject['categoryProducts'] = function(categoryValue) { return gs.mc(gs.elvis(gs.bool(gs.gp(gSobject.scope,"inventory")) , gs.gp(gSobject.scope,"inventory") , gs.list([])),"findAll",[function(product) { return gs.mc(gSobject,"categoryMatches",[product, categoryValue]); }]); } gSobject['categoryDisplayLabel'] = function(category) { return gs.elvis(gs.bool(gs.gp(category,"catalogLabel",true)) , gs.gp(category,"catalogLabel",true) , gs.elvis(gs.bool(gs.gp(category,"label",true)) , gs.gp(category,"label",true) , "")); } gSobject['categoryMatches'] = function(product, categoryValue) { if (((!gs.bool(product)) || (!gs.bool(categoryValue))) || (gs.equals(categoryValue, "all"))) { return true; }; var normalizedCategoryName = gs.mc(gSobject,"normalizeCategoryName",[gs.gp(product,"CategoryName",true)]); var categoryMap = gs.map().add("medication",gs.list(["medication" , "prescription"])).add("peptomeal",gs.list(["peptomeal"])).add("vitamins",gs.list(["vitamins" , "vitamin" , "supplements"])).add("muscle_nutrition",gs.list(["muscle nutrition"])).add("peptides",gs.list(["peptides" , "prescribed peptides" , "injection"])).add("aesthetic",gs.list(["aesthetic" , "alopecia"])); return gs.mc(gs.elvis(categoryMap[categoryValue] , categoryMap[categoryValue] , gs.list([])),"contains",[normalizedCategoryName]); } gSobject['normalizeCategoryName'] = function(categoryName) { return gs.mc(gs.mc(gs.mc(gs.elvis(gs.bool(categoryName) , categoryName , ""),"toString",[]),"trim",[]),"toLowerCase",[]); } gSobject['addToCart'] = function(product) { return gs.mc(gSobject,"updateProductQuantity",[product, gs.plus(gs.mc(gSobject,"cartQuantityForProduct",[gs.gp(product,"InventoryID",true)]), 1)]); } gSobject['cartQuantityForProduct'] = function(itemId) { var item = gs.mc(gs.elvis(gs.bool(gs.gp(gSobject.scope,"cart")) , gs.gp(gSobject.scope,"cart") , gs.list([])),"find",[function(it) { return gs.equals(gs.gp(it,"InventoryID"), itemId); }]); return (gs.bool(item) ? gs.elvis(gs.bool(gs.gp(item,"quantity")) , gs.gp(item,"quantity") , 0) : 0); } gSobject['updateProductQuantity'] = function(product, qty) { if (!gs.bool(product)) { return null; }; var safeQty = qty; if (safeQty < 0) { safeQty = 0; }; var available = gs.mc(gSobject,"availableStockForProduct",[product]); if (safeQty > available) { safeQty = available; gs.mc(gSobject,"notify",["Limited to available stock (" + (available) + "). Quantity adjusted.", "warning"]); }; if (!gs.bool(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"cart"))) { gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"cart",gs.list([])); }; var existingCartItem = gs.mc(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"cart"),"find",[function(it) { return gs.equals(gs.gp(it,"InventoryID"), gs.gp(product,"InventoryID")); }]); if (safeQty <= 0) { if (gs.bool(existingCartItem)) { gs.mc(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"cart"),"remove",[existingCartItem]); }; } else { if (gs.bool(existingCartItem)) { gs.sp(existingCartItem,"quantity",safeQty); } else { var productWithQty = gs.mc(product,"clone",[]); gs.sp(productWithQty,"quantity",safeQty); gs.mc(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"cart"),"add",[productWithQty]); }; }; gs.sp(gSobject.scope,"cart",gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"cart")); return gs.mc(gSobject,"updateInventoryWithCart",[]); } gSobject['availableStockForProduct'] = function(product) { return gs.elvis(gs.bool(gs.gp(product,"_originalQuantityOnHand",true)) , gs.gp(product,"_originalQuantityOnHand",true) , gs.elvis(gs.bool(gs.gp(product,"QuantityOnHand",true)) , gs.gp(product,"QuantityOnHand",true) , 0)); } gSobject['updateInventoryWithCart'] = function(it) { if (!gs.bool(gs.gp(gSobject.scope,"inventory"))) { return null; }; return gs.mc(gs.gp(gSobject.scope,"inventory"),"each",[function(product) { var originalQty = gs.elvis(gs.bool(gs.gp(product,"_originalQuantityOnHand",true)) , gs.gp(product,"_originalQuantityOnHand",true) , gs.elvis(gs.bool(gs.gp(product,"QuantityOnHand",true)) , gs.gp(product,"QuantityOnHand",true) , 0)); gs.sp(product,"_originalQuantityOnHand",originalQty); var cartQty = gs.elvis(gs.bool(gs.gp(gs.mc(gs.elvis(gs.bool(gs.gp(gSobject.scope,"cart")) , gs.gp(gSobject.scope,"cart") , gs.list([])),"find",[function(it) { return gs.equals(gs.gp(it,"InventoryID"), gs.gp(product,"InventoryID")); }]),"quantity",true)) , gs.gp(gs.mc(gs.elvis(gs.bool(gs.gp(gSobject.scope,"cart")) , gs.gp(gSobject.scope,"cart") , gs.list([])),"find",[function(it) { return gs.equals(gs.gp(it,"InventoryID"), gs.gp(product,"InventoryID")); }]),"quantity",true) , 0); return gs.sp(product,"QuantityOnHand",Math.max(gs.minus(originalQty, cartQty), 0)); }]); } gSobject['isOutOfStock'] = function(product) { return gs.mc(gSobject,"availableStockForProduct",[product]) <= 0; } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function PeptideOrdersCartComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'PeptideOrdersCartComponent', simpleName: 'PeptideOrdersCartComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/peptideOrdersCart"; gSobject['created'] = function(it) { gs.println("peptideOrdersCart.created()"); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "peptide.cart.page"]),"do",[]); gs.mc(gSobject,"componentTheme",[false]); gs.mc(gSobject,"showFooter",[false]); gs.sp(gSobject.scope,"selectedDeliveryOption",null); gs.sp(gSobject.scope,"deliveryOptions",gs.list([])); gs.sp(gSobject.scope,"btnLoading",false); gs.sp(gSobject.scope,"loading",false); gs.sp(gSobject.scope,"rxmeUser",gs.map()); gs.sp(gSobject.scope,"patient",gs.map()); if (!gs.bool(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"cart"))) { gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"cart",gs.list([])); }; gs.sp(gSobject.scope,"products",gs.list([])); if (gs.bool(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"cart"))) { gs.sp(gSobject.scope,"products",gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"cart")); }; gs.mc(gSobject,"loadRxmeUser",[]); return gs.mc(gSobject,"loadPatient",[]); } gSobject['loadRxmeUser'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"loadRxmeUser",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(user) { return gs.sp(gSobject.scope,"rxmeUser",user); }]); } gSobject['loadInventory'] = function(it) { gs.sp(gSobject.scope,"loading",true); return gs.mc(gs.mc(gs.gp(gs.mc(gs.fs('o', this, gSobject),"localAndRemote",[]),"rxmeAppApiService"),"xeroInventory",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gs.gp(gSobject.scope,"patient"),"id")]),"then",[function(result) { gs.println("inventory: " + (result) + ""); if (gs.bool(result)) { var inventory = result; var deliveryItems = gs.mc(inventory,"findAll",[function(it) { return gs.equals(gs.gp(it,"isDeliveryCharge"), true); }]); gs.println(">>> Delivery options built: " + (deliveryItems) + ""); deliveryItems = gs.mc(deliveryItems,"findAll",[function(it) { return (gs.gp(it,"Code") != "DEL-MED") && (gs.gp(it,"Code") != "DEL-OVERNIGHT"); }]); gs.sp(gSobject.scope,"deliveryOptions",gs.mc(deliveryItems,"collect",[function(d) { return gs.map().add("label","" + (gs.gp(d,"Name")) + " (R" + (gs.elvis(gs.bool(gs.gp(d,"SalePrice")) , gs.gp(d,"SalePrice") , 0)) + ")").add("value",gs.gp(d,"Code")).add("amount",gs.elvis(gs.bool(gs.gp(d,"SalePrice")) , gs.gp(d,"SalePrice") , 0)).add("code",gs.gp(d,"Code")); }])); gs.sp(gSobject.scope,"deliveryOptions",gs.mc(gs.gp(gSobject.scope,"deliveryOptions"),"sort",[function(a, b) { return gs.spaceShip(gs.mc(gSobject,"randInt",[gs.gp(a,"amount",true)]), gs.mc(gSobject,"randInt",[gs.gp(b,"amount",true)])); }])); gs.println(">>> Delivery options built: " + (gs.gp(gSobject.scope,"deliveryOptions")) + ""); }; return gs.sp(gSobject.scope,"loading",false); }, function(error) { gs.println("Store error: " + (error) + ""); gs.sp(gSobject.scope,"storeError",gs.gp(error,"message")); return gs.sp(gSobject.scope,"loading",false); }]); } gSobject['loadPatient'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppApiService"),"portalPatient",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(resp) { gs.sp(gSobject.scope,"patient",resp); gs.sp(gSobject.scope,"can_order",(gs.equals(gs.gp(resp,"can_order",true), true))); gs.sp(gs.fs('session', this, gSobject),"can_order",gs.gp(gSobject.scope,"can_order")); "patient loaded"; return gs.mc(gSobject,"loadInventory",[]); }]); } gSobject['continueToDeliveryDetails'] = function(it) { gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"peptideDeliverySubtotal",gs.mc(gSobject,"cartSubtotal",[])); gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"peptideDeliveryCharge",gs.mc(gSobject,"deliveryChargeAmount",[])); gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"peptideDeliveryVat",gs.mc(gSobject,"vatAmount",[])); gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"peptideDeliveryTotal",gs.mc(gSobject,"grandTotal",[])); return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/peptideDeliveryDetails"]); } gSobject['orderPeptide'] = function(it) { if (gs.bool(gs.gp(gSobject.scope,"btnLoading"))) { return null; }; gs.sp(gSobject.scope,"btnLoading",true); if (gs.bool(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"hasActiveOrder",true))) { gs.mc(gSobject,"notify",["You already have a pending order. Please wait for the active order to complete before creating another one.", "warning"]); gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/peptideOrder"]); gs.sp(gSobject.scope,"btnLoading",false); return null; }; var items = gs.mc(gs.elvis(gs.bool(gs.gp(gSobject.scope,"products")) , gs.gp(gSobject.scope,"products") , gs.list([])),"findAll",[function(it) { return gs.elvis(gs.bool(gs.gp(it,"quantity",true)) , gs.gp(it,"quantity",true) , 0) > 0; }]); if (gs.mc(items,"isEmpty",[])) { gs.mc(gSobject,"notify",["Your cart is empty. Please add at least one item before checking out.", "warning"]); gs.sp(gSobject.scope,"btnLoading",false); return null; }; var user = gs.gp(gSobject.scope,"rxmeUser"); var orderPayload = gs.map().add("DeliveryRegion","local").add("PleaseConfirmYourDeliveryAddress","" + (gs.gp(user,"streetAddress")) + "\n" + (gs.gp(user,"city")) + "\n" + (gs.gp(user,"province")) + "\n" + (gs.gp(user,"postalCode")) + ""); gs.mc(items,"each",[function(product) { if ((gs.bool(gs.gp(product,"QtyName",true))) && (gs.gp(product,"quantity",true) > 0)) { return (orderPayload[gs.gp(product,"QtyName")]) = gs.mc(gs.gp(product,"quantity"),"toString",[]); }; }]); var hasInj = gs.mc(gSobject,"hasInjections",[]); var hasNonInj = gs.mc(gSobject,"hasNonInjections",[]); if ((gs.bool(hasInj)) && (!gs.bool(hasNonInj))) { (orderPayload["DeliveryOption"]) = "DEL-MED"; }; if ((!gs.bool(hasInj)) && (gs.bool(hasNonInj))) { (orderPayload["DeliveryOption"]) = gs.mc(gSobject,"effectiveDeliveryOptionCode",[]); }; if ((gs.bool(hasInj)) && (gs.bool(hasNonInj))) { (orderPayload["DeliveryOption"]) = gs.mc(gSobject,"effectiveDeliveryOptionCode",[]); }; gs.println(gs.plus((gs.multiply("=", 20)), " ORDER PAYLOAD ")); gs.println(orderPayload); return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppApiService"),"createOrder",[gs.gp(gs.fs('session', this, gSobject),"userId"), orderPayload]),"then",[function(response) { gs.println(gs.plus((gs.multiply("=", 20)), "RESPONSE")); gs.println(response); gs.mc(gSobject,"notify",["Order Placed"]); gs.sp(gSobject.scope,"products",gs.list([])); gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"cart",gs.list([])); gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/peptideOrderQuote"]); return gs.sp(gSobject.scope,"btnLoading",false); }, function(error) { gs.println(error); gs.mc(gSobject,"notify",[gs.plus("Order Failed: ", gs.gp(error,"message"))]); return gs.sp(gSobject.scope,"btnLoading",false); }]); } gSobject['cartTotal'] = function(it) { return gs.plus(gs.mc(gSobject,"cartSubtotal",[]), gs.mc(gSobject,"summaryMedicalDeliveryCharge",[])); } gSobject['cartSubtotal'] = function(it) { return gs.elvis(gs.mc(gs.elvis(gs.bool(gs.gp(gSobject.scope,"products")) , gs.gp(gSobject.scope,"products") , gs.list([])),"sum",[function(p) { return gs.multiply(gs.mc(gSobject,"randInt",[gs.gp(p,"SalePrice",true)]), gs.elvis(gs.bool(gs.gp(p,"quantity",true)) , gs.gp(p,"quantity",true) , 0)); }]) , gs.mc(gs.elvis(gs.bool(gs.gp(gSobject.scope,"products")) , gs.gp(gSobject.scope,"products") , gs.list([])),"sum",[function(p) { return gs.multiply(gs.mc(gSobject,"randInt",[gs.gp(p,"SalePrice",true)]), gs.elvis(gs.bool(gs.gp(p,"quantity",true)) , gs.gp(p,"quantity",true) , 0)); }]) , 0); } gSobject['deliveryChargeAmount'] = function(it) { return 0; } gSobject['medicalDeliveryAmount'] = function(it) { var medDelivery = gs.mc(gs.plus(gs.gp(gSobject.scope,"deliveryOptions"), gs.elvis(gs.bool(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"inventory")) , gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"inventory") , gs.list([]))),"find",[function(it) { return (gs.equals(gs.gp(it,"code"), "DEL-MED")) || (gs.equals(gs.gp(it,"Code"), "DEL-MED")); }]); return gs.mc(gSobject,"randInt",[gs.elvis(gs.bool(gs.gp(medDelivery,"SalePrice",true)) , gs.gp(medDelivery,"SalePrice",true) , 195)]); } gSobject['summaryMedicalDeliveryCharge'] = function(it) { if (!gs.bool(gs.mc(gSobject,"hasInjections",[]))) { return 0; }; return gs.mc(gSobject,"medicalDeliveryAmount",[]); } gSobject['vatAmount'] = function(it) { return gs.multiply(gs.mc(gSobject,"cartTotal",[]), (gs.div(15.0, 115.0))); } gSobject['grandTotal'] = function(it) { return gs.mc(gSobject,"cartTotal",[]); } gSobject['productLineTotal'] = function(product) { return gs.multiply(gs.mc(gSobject,"randInt",[gs.gp(product,"SalePrice",true)]), gs.elvis(gs.bool(gs.gp(product,"quantity",true)) , gs.gp(product,"quantity",true) , 0)); } gSobject['orderSummaryDate'] = function(it) { return gs.mc(gs.date(),"format",["yyyy-MM-dd"]); } gSobject['orderSummaryName'] = function(it) { var first = gs.elvis(gs.bool(gs.gp(gs.gp(gSobject.scope,"rxmeUser"),"firstName",true)) , gs.gp(gs.gp(gSobject.scope,"rxmeUser"),"firstName",true) , gs.elvis(gs.bool(gs.gp(gs.gp(gs.fs('session', this, gSobject),"user",true),"name",true)) , gs.gp(gs.gp(gs.fs('session', this, gSobject),"user",true),"name",true) , "")); var last = gs.elvis(gs.bool(gs.gp(gs.gp(gSobject.scope,"rxmeUser"),"lastName",true)) , gs.gp(gs.gp(gSobject.scope,"rxmeUser"),"lastName",true) , ""); var full = gs.mc("" + (first) + " " + (last) + "","trim",[]); return gs.elvis(gs.bool(full) , full , gs.elvis(gs.bool(gs.gp(gs.gp(gSobject.scope,"rxmeUser"),"name",true)) , gs.gp(gs.gp(gSobject.scope,"rxmeUser"),"name",true) , gs.elvis(gs.bool(gs.gp(gs.gp(gs.fs('session', this, gSobject),"user",true),"name",true)) , gs.gp(gs.gp(gs.fs('session', this, gSobject),"user",true),"name",true) , "Patient"))); } gSobject['orderSummaryAccountName'] = function(it) { return gs.gp(gs.gp(gSobject.scope,"patient"),"account_number",true); } gSobject['orderSummaryEmail'] = function(it) { return gs.elvis(gs.bool(gs.gp(gs.gp(gSobject.scope,"rxmeUser"),"email",true)) , gs.gp(gs.gp(gSobject.scope,"rxmeUser"),"email",true) , gs.elvis(gs.bool(gs.gp(gs.gp(gs.fs('session', this, gSobject),"user",true),"email",true)) , gs.gp(gs.gp(gs.fs('session', this, gSobject),"user",true),"email",true) , "")); } gSobject['orderSummaryCategory'] = function(product) { var category = gs.mc(gs.mc(gs.elvis(gs.bool(gs.gp(product,"CategoryName",true)) , gs.gp(product,"CategoryName",true) , ""),"toString",[]),"trim",[]); return gs.elvis(gs.bool(category) , category , "Product"); } gSobject['orderSummaryProductName'] = function(product) { var name = gs.mc(gs.mc(gs.elvis(gs.bool(gs.gp(product,"Name",true)) , gs.gp(product,"Name",true) , ""),"toString",[]),"trim",[]); var category = gs.mc(gs.mc(gSobject,"orderSummaryCategory",[product]),"toLowerCase",[]); if ((gs.equals(category, "peptomeal")) && (gs.mc(gs.mc(name,"toLowerCase",[]),"startsWith",["peptomeal "]))) { return gs.mc(gs.mc(name,"substring",[gs.mc("PeptoMeal ","length",[])]),"trim",[]); }; return name; } gSobject['removeFromCart'] = function(product) { gs.mc(gSobject,"notify",["" + (gs.gp(product,"Name")) + " removed from cart", "positive"]); gs.mc(gs.gp(gSobject.scope,"products"),"remove",[product]); return gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"cart",gs.gp(gSobject.scope,"products")); } gSobject['updateCartQuantity'] = function(product, newQty) { var item = gs.mc(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"cart"),"find",[function(p) { return gs.equals(gs.gp(p,"InventoryID"), gs.gp(product,"InventoryID")); }]); if (gs.bool(item)) { return gs.sp(item,"quantity",newQty); }; } gSobject['hasInjections'] = function(it) { return gs.mc(gs.elvis(gs.bool(gs.gp(gSobject.scope,"products")) , gs.gp(gSobject.scope,"products") , gs.list([])),"any",[function(it) { return gs.equals(gs.mc(gs.elvis(gs.bool(gs.gp(it,"CategoryName",true)) , gs.gp(it,"CategoryName",true) , ""),"toLowerCase",[]), "injection"); }]); } gSobject['hasNonInjections'] = function(it) { return gs.mc(gs.elvis(gs.bool(gs.gp(gSobject.scope,"products")) , gs.gp(gSobject.scope,"products") , gs.list([])),"any",[function(it) { return gs.mc(gs.elvis(gs.bool(gs.gp(it,"CategoryName",true)) , gs.gp(it,"CategoryName",true) , ""),"toLowerCase",[]) != "injection"; }]); } gSobject['allPeptoMeals'] = function(it) { return gs.mc(gs.elvis(gs.bool(gs.gp(gSobject.scope,"products")) , gs.gp(gSobject.scope,"products") , gs.list([])),"every",[function(it) { return gs.equals(gs.mc(gs.gp(it,"CategoryName",true),"toLowerCase",[], null, true), "peptomeals"); }]); } gSobject['hasAlopecia'] = function(it) { return gs.mc(gs.elvis(gs.bool(gs.gp(gSobject.scope,"products")) , gs.gp(gSobject.scope,"products") , gs.list([])),"any",[function(it) { return gs.equals(gs.mc(gs.gp(it,"CategoryName",true),"toLowerCase",[], null, true), "alopecia"); }]); } gSobject['selectedDeliveryAmount'] = function(it) { var opt = gs.mc(gSobject,"effectiveDeliveryOption",[]); return gs.mc(gSobject,"randInt",[gs.gp(opt,"amount",true)]); } gSobject['deliveryCostIfDelivered'] = function(it) { var extra = 0; var medDelivery = gs.mc(gs.plus(gs.gp(gSobject.scope,"deliveryOptions"), gs.elvis(gs.bool(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"inventory")) , gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"inventory") , gs.list([]))),"find",[function(it) { return (gs.equals(gs.gp(it,"code"), "DEL-MED")) || (gs.equals(gs.gp(it,"Code"), "DEL-MED")); }]); if (gs.mc(gSobject,"hasInjections",[])) { extra += gs.mc(gSobject,"randInt",[gs.elvis(gs.bool(gs.gp(medDelivery,"SalePrice",true)) , gs.gp(medDelivery,"SalePrice",true) , 195)]); }; if (gs.mc(gSobject,"hasNonInjections",[])) { extra += gs.mc(gSobject,"selectedDeliveryAmount",[]); }; return extra; } gSobject['effectiveDeliveryOption'] = function(it) { var options = gs.elvis(gs.bool(gs.gp(gSobject.scope,"deliveryOptions")) , gs.gp(gSobject.scope,"deliveryOptions") , gs.list([])); if ((!gs.bool(options)) || (gs.mc(options,"isEmpty",[]))) { return null; }; var selected = gs.mc(options,"find",[function(it) { return gs.equals(gs.gp(it,"value"), gs.gp(gSobject.scope,"selectedDeliveryOption")); }]); return gs.elvis(gs.bool(selected) , selected , options[0]); } gSobject['effectiveDeliveryOptionCode'] = function(it) { var option = gs.mc(gSobject,"effectiveDeliveryOption",[]); return gs.elvis(gs.bool(gs.gp(option,"value",true)) , gs.gp(option,"value",true) , gs.elvis(gs.bool(gs.gp(option,"code",true)) , gs.gp(option,"code",true) , "")); } gSobject['randInt'] = function(value) { var raw = gs.mc((gs.equals(value, null) ? "0" : gs.mc(value,"toString",[])),"trim",[]); if (!gs.bool(raw)) { return 0; }; return gs.mc(gs.mc(raw,"tokenize",["."])[0],"toInteger",[]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function PeptideDeliveryDetailsComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'PeptideDeliveryDetailsComponent', simpleName: 'PeptideDeliveryDetailsComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/peptideDeliveryDetails"; gSobject['created'] = function(it) { gs.println("peptideDeliveryDetails.created()"); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "peptide.delivery.details.page"]),"do",[]); gs.mc(gSobject,"componentTheme",[false]); gs.mc(gSobject,"showFooter",[false]); gs.sp(gSobject.scope,"selectedDeliveryMethod","delivery"); gs.sp(gSobject.scope,"deliveryOptions",gs.list([])); gs.sp(gSobject.scope,"provinces",gs.list(["Eastern Cape" , "Free State" , "Gauteng" , "KwaZulu-Natal" , "Limpopo" , "Mpumalanga" , "Northern Cape" , "North West" , "Western Cape"])); gs.sp(gSobject.scope,"confirmDeliveryDetails",false); gs.sp(gSobject.scope,"showSubmitOrderDialog",false); gs.sp(gSobject.scope,"deliveryFieldErrors",gs.map()); gs.sp(gSobject.scope,"btnLoading",false); gs.sp(gSobject.scope,"loading",false); gs.sp(gSobject.scope,"initialSubtotal",gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"peptideDeliverySubtotal")); gs.sp(gSobject.scope,"initialDelivery",gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"peptideDeliveryCharge")); gs.sp(gSobject.scope,"initialVat",gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"peptideDeliveryVat")); gs.sp(gSobject.scope,"initialTotal",gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"peptideDeliveryTotal")); gs.mc(gSobject,"applySavedDeliveryDetails",[gs.elvis(gs.bool(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"peptideDeliveryDetails")) , gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"peptideDeliveryDetails") , gs.map())]); gs.sp(gSobject.scope,"rxmeUser",gs.map()); gs.sp(gSobject.scope,"patient",gs.map()); gs.sp(gSobject.scope,"products",gs.elvis(gs.bool(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"cart")) , gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"cart") , gs.list([]))); gs.sp(gSobject.scope,"orderWarning",false); gs.mc(gSobject,"loadRxmeUser",[]); return gs.mc(gSobject,"loadPatient",[]); } gSobject['loadRxmeUser'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppService"),"loadRxmeUser",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(user) { return gs.sp(gSobject.scope,"rxmeUser",user); }]); } gSobject['loadInventory'] = function(it) { gs.sp(gSobject.scope,"loading",true); return gs.mc(gs.mc(gs.gp(gs.mc(gs.fs('o', this, gSobject),"localAndRemote",[]),"rxmeAppApiService"),"xeroInventory",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gs.gp(gSobject.scope,"patient"),"id")]),"then",[function(result) { if (gs.bool(result)) { var deliveryItems = gs.mc(result,"findAll",[function(it) { return gs.equals(gs.gp(it,"isDeliveryCharge"), true); }]); deliveryItems = gs.mc(deliveryItems,"findAll",[function(it) { return ((gs.gp(it,"Code") != "DEL-MED") && (gs.gp(it,"Code") != "DEL-OVERNIGHT")) && (gs.gp(it,"Code") != "PICKUP"); }]); gs.sp(gSobject.scope,"deliveryOptions",gs.mc(deliveryItems,"collect",[function(d) { return gs.map().add("label","" + (gs.gp(d,"Name")) + " (R" + (gs.elvis(gs.bool(gs.gp(d,"SalePrice")) , gs.gp(d,"SalePrice") , 0)) + ")").add("value",gs.gp(d,"Code")).add("amount",gs.elvis(gs.bool(gs.gp(d,"SalePrice")) , gs.gp(d,"SalePrice") , 0)).add("code",gs.gp(d,"Code")); }])); gs.sp(gSobject.scope,"deliveryOptions",gs.mc(gs.gp(gSobject.scope,"deliveryOptions"),"sort",[function(a, b) { return gs.spaceShip(gs.mc(gSobject,"randInt",[gs.gp(a,"amount",true)]), gs.mc(gSobject,"randInt",[gs.gp(b,"amount",true)])); }])); }; return gs.sp(gSobject.scope,"loading",false); }, function(error) { gs.sp(gSobject.scope,"storeError",gs.gp(error,"message")); return gs.sp(gSobject.scope,"loading",false); }]); } gSobject['loadPatient'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppApiService"),"portalPatient",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(resp) { gs.sp(gSobject.scope,"patient",resp); gs.sp(gSobject.scope,"can_order",(gs.equals(gs.gp(resp,"can_order",true), true))); gs.sp(gs.fs('session', this, gSobject),"can_order",gs.gp(gSobject.scope,"can_order")); return gs.mc(gSobject,"loadInventory",[]); }]); } gSobject['requestContinueToBankingDetails'] = function(it) { if (gs.bool(gs.gp(gSobject.scope,"btnLoading"))) { return null; }; if (gs.bool(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"hasActiveOrder",true))) { gs.mc(gSobject,"notify",["You already have a pending order. Please wait for the active order to complete before creating another one.", "warning"]); gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/peptideOrders"]); return null; }; if ((gs.mc(gSobject,"requiresDeliveryDetails",[])) && (!gs.bool(gs.gp(gSobject.scope,"confirmDeliveryDetails")))) { gs.mc(gSobject,"notify",["Please confirm your delivery details before continuing.", "warning"]); return null; }; var items = gs.mc(gs.elvis(gs.bool(gs.gp(gSobject.scope,"products")) , gs.gp(gSobject.scope,"products") , gs.list([])),"findAll",[function(it) { return gs.elvis(gs.bool(gs.gp(it,"quantity",true)) , gs.gp(it,"quantity",true) , 0) > 0; }]); if (gs.mc(items,"isEmpty",[])) { gs.mc(gSobject,"notify",["Your cart is empty. Please add at least one item before checking out.", "warning"]); return null; }; if ((gs.mc(gSobject,"requiresDeliveryDetails",[])) && (!gs.bool(gs.mc(gSobject,"validateDeliveryDetails",[])))) { gs.mc(gSobject,"notify",["Please complete the required delivery details.", "warning"]); return null; }; return gs.sp(gSobject.scope,"showSubmitOrderDialog",true); } gSobject['continueToBankingDetails'] = function(it) { if (gs.bool(gs.gp(gSobject.scope,"btnLoading"))) { return null; }; gs.sp(gSobject.scope,"showSubmitOrderDialog",false); gs.sp(gSobject.scope,"btnLoading",true); if (gs.bool(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"hasActiveOrder",true))) { gs.mc(gSobject,"notify",["You already have a pending order. Please wait for the active order to complete before creating another one.", "warning"]); gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/peptideOrders"]); gs.sp(gSobject.scope,"btnLoading",false); return null; }; if ((gs.mc(gSobject,"requiresDeliveryDetails",[])) && (!gs.bool(gs.gp(gSobject.scope,"confirmDeliveryDetails")))) { gs.mc(gSobject,"notify",["Please confirm your delivery details before continuing.", "warning"]); gs.sp(gSobject.scope,"btnLoading",false); return null; }; var items = gs.mc(gs.elvis(gs.bool(gs.gp(gSobject.scope,"products")) , gs.gp(gSobject.scope,"products") , gs.list([])),"findAll",[function(it) { return gs.elvis(gs.bool(gs.gp(it,"quantity",true)) , gs.gp(it,"quantity",true) , 0) > 0; }]); if (gs.mc(items,"isEmpty",[])) { gs.mc(gSobject,"notify",["Your cart is empty. Please add at least one item before checking out.", "warning"]); gs.sp(gSobject.scope,"btnLoading",false); return null; }; if ((gs.mc(gSobject,"requiresDeliveryDetails",[])) && (!gs.bool(gs.mc(gSobject,"validateDeliveryDetails",[])))) { gs.mc(gSobject,"notify",["Please complete the required delivery details.", "warning"]); gs.sp(gSobject.scope,"btnLoading",false); return null; }; gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"peptideDeliveryMethod",gs.gp(gSobject.scope,"selectedDeliveryMethod")); gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"peptideDeliveryDetails",gs.map().add("contactPerson",gs.gp(gSobject.scope,"contactPerson")).add("contactNumber",gs.gp(gSobject.scope,"contactNumberValue")).add("alternativeContactNumber",gs.gp(gSobject.scope,"alternativeContactNumber")).add("addressLine1",gs.gp(gSobject.scope,"addressLine1")).add("suburb",gs.gp(gSobject.scope,"suburb")).add("city",gs.gp(gSobject.scope,"city")).add("province",gs.gp(gSobject.scope,"province")).add("postalCode",gs.gp(gSobject.scope,"postalCode")).add("instructions",gs.gp(gSobject.scope,"deliveryInstructions"))); gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"peptideDeliveryAddress",gs.mc(gSobject,"deliveryAddress",[])); gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"peptideDeliveryContactName",gs.mc(gSobject,"contactName",[])); gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"peptideDeliveryContactNumber",gs.mc(gSobject,"contactNumber",[])); gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"peptideDeliveryConfirmed",gs.gp(gSobject.scope,"confirmDeliveryDetails")); gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"peptideDeliveryCharge",gs.mc(gSobject,"deliveryChargeAmount",[])); gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"peptideDeliveryVat",gs.mc(gSobject,"vatAmount",[])); gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"peptideDeliveryTotal",gs.mc(gSobject,"totalAmount",[])); var orderPayload = gs.mc(gSobject,"buildOrderPayload",[items]); return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppApiService"),"createOrder",[gs.gp(gs.fs('session', this, gSobject),"userId"), orderPayload]),"then",[function(response) { gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"quote",gs.elvis(gs.bool(gs.gp(gs.gp(response,"meta",true),"quote",true)) , gs.gp(gs.gp(response,"meta",true),"quote",true) , gs.elvis(gs.bool(gs.gp(response,"quote",true)) , gs.gp(response,"quote",true) , gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"quote")))); gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/peptideBankingDetails"]); return gs.sp(gSobject.scope,"btnLoading",false); }, function(error) { gs.mc(gSobject,"notify",[gs.plus("Order Failed: ", gs.gp(error,"message"))]); return gs.sp(gSobject.scope,"btnLoading",false); }]); } gSobject['buildOrderPayload'] = function(items) { var hasInj = gs.mc(gSobject,"hasInjections",[]); var hasNonInj = gs.mc(gSobject,"hasNonInjections",[]); var pickup = gs.equals(gs.gp(gSobject.scope,"selectedDeliveryMethod"), "pickup"); var physicalAddress = (gs.bool(pickup) ? gs.map() : gs.map().add("zip",gs.elvis(gs.bool(gs.gp(gSobject.scope,"postalCode")) , gs.gp(gSobject.scope,"postalCode") , "")).add("city",gs.elvis(gs.bool(gs.gp(gSobject.scope,"city")) , gs.gp(gSobject.scope,"city") , "")).add("state",gs.elvis(gs.bool(gs.gp(gSobject.scope,"province")) , gs.gp(gSobject.scope,"province") , "")).add("suburb",gs.elvis(gs.bool(gs.gp(gSobject.scope,"suburb")) , gs.gp(gSobject.scope,"suburb") , "")).add("address",gs.elvis(gs.bool(gs.gp(gSobject.scope,"addressLine1")) , gs.gp(gSobject.scope,"addressLine1") , ""))); var orderPayload = gs.map().add("DeliveryRegion",(gs.bool(pickup) ? "pickup" : "local")).add("PleaseConfirmYourDeliveryAddress",(gs.bool(pickup) ? "pickup" : gs.mc(gSobject,"deliveryAddress",[]))).add("physical_address",physicalAddress).add("additional_instructions",(gs.bool(pickup) ? "" : gs.elvis(gs.bool(gs.gp(gSobject.scope,"deliveryInstructions")) , gs.gp(gSobject.scope,"deliveryInstructions") , ""))); gs.mc(items,"each",[function(product) { if ((gs.bool(gs.gp(product,"QtyName",true))) && (gs.gp(product,"quantity",true) > 0)) { return (orderPayload[gs.gp(product,"QtyName")]) = gs.mc(gs.gp(product,"quantity"),"toString",[]); }; }]); if ((!gs.bool(pickup)) && (gs.bool(hasInj))) { (orderPayload["DeliveryOption"]) = "DEL-MED"; }; if (((!gs.bool(pickup)) && (!gs.bool(hasInj))) && (gs.bool(hasNonInj))) { (orderPayload["DeliveryOption"]) = gs.mc(gSobject,"effectiveDeliveryOptionCode",[]); }; return orderPayload; } gSobject['totalAmount'] = function(it) { if ((gs.gp(gSobject.scope,"initialTotal") != null) && (!gs.bool(gs.mc(gSobject,"hasNonInjections",[])))) { return gs.gp(gSobject.scope,"initialTotal"); }; return gs.mc(gSobject,"cartTotal",[]); } gSobject['cartTotal'] = function(it) { var base = gs.mc(gs.gp(gSobject.scope,"products"),"sum",[function(p) { return gs.multiply(gs.mc(gSobject,"randInt",[gs.gp(p,"SalePrice",true)]), gs.elvis(gs.bool(gs.gp(p,"quantity",true)) , gs.gp(p,"quantity",true) , 0)); }]); return gs.plus(base, gs.mc(gSobject,"deliveryChargeAmount",[])); } gSobject['deliveryChargeAmount'] = function(it) { if (gs.equals(gs.gp(gSobject.scope,"selectedDeliveryMethod"), "pickup")) { return 0; }; if (gs.mc(gSobject,"hasInjections",[])) { var medDelivery = gs.mc(gs.plus(gs.gp(gSobject.scope,"deliveryOptions"), gs.elvis(gs.bool(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"inventory")) , gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"inventory") , gs.list([]))),"find",[function(it) { return (gs.equals(gs.gp(it,"code"), "DEL-MED")) || (gs.equals(gs.gp(it,"Code"), "DEL-MED")); }]); return gs.mc(gSobject,"randInt",[gs.elvis(gs.bool(gs.gp(medDelivery,"SalePrice",true)) , gs.gp(medDelivery,"SalePrice",true) , 195)]); }; if (gs.mc(gSobject,"hasNonInjections",[])) { return gs.mc(gSobject,"selectedDeliveryAmount",[]); }; return 0; } gSobject['vatAmount'] = function(it) { return Math.round(gs.multiply(gs.mc(gSobject,"cartTotal",[]), (gs.div(15.0, 115.0)))); } gSobject['formatStoreCurrency'] = function(value) { return "R" + (gs.mc(gSobject,"randInt",[value])) + ".00"; } gSobject['hasInjections'] = function(it) { return gs.mc(gs.elvis(gs.bool(gs.gp(gSobject.scope,"products")) , gs.gp(gSobject.scope,"products") , gs.list([])),"any",[function(it) { return gs.equals(gs.mc(gs.elvis(gs.bool(gs.gp(it,"CategoryName",true)) , gs.gp(it,"CategoryName",true) , ""),"toLowerCase",[]), "injection"); }]); } gSobject['hasNonInjections'] = function(it) { return gs.mc(gs.elvis(gs.bool(gs.gp(gSobject.scope,"products")) , gs.gp(gSobject.scope,"products") , gs.list([])),"any",[function(it) { return gs.mc(gs.elvis(gs.bool(gs.gp(it,"CategoryName",true)) , gs.gp(it,"CategoryName",true) , ""),"toLowerCase",[]) != "injection"; }]); } gSobject['selectedDeliveryAmount'] = function(it) { var opt = gs.mc(gSobject,"effectiveDeliveryOption",[]); return gs.mc(gSobject,"randInt",[gs.gp(opt,"amount",true)]); } gSobject['deliveryCostIfDelivered'] = function(it) { if (gs.mc(gSobject,"hasInjections",[])) { var medDelivery = gs.mc(gs.plus(gs.gp(gSobject.scope,"deliveryOptions"), gs.elvis(gs.bool(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"inventory")) , gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"inventory") , gs.list([]))),"find",[function(it) { return (gs.equals(gs.gp(it,"code"), "DEL-MED")) || (gs.equals(gs.gp(it,"Code"), "DEL-MED")); }]); return gs.mc(gSobject,"randInt",[gs.elvis(gs.bool(gs.gp(medDelivery,"SalePrice",true)) , gs.gp(medDelivery,"SalePrice",true) , 195)]); }; if (gs.mc(gSobject,"hasNonInjections",[])) { return gs.mc(gSobject,"selectedDeliveryAmount",[]); }; return 0; } gSobject['effectiveDeliveryOption'] = function(it) { var options = gs.elvis(gs.bool(gs.gp(gSobject.scope,"deliveryOptions")) , gs.gp(gSobject.scope,"deliveryOptions") , gs.list([])); if ((!gs.bool(options)) || (gs.mc(options,"isEmpty",[]))) { return null; }; return options[0]; } gSobject['effectiveDeliveryOptionCode'] = function(it) { var option = gs.mc(gSobject,"effectiveDeliveryOption",[]); return gs.elvis(gs.bool(gs.gp(option,"value",true)) , gs.gp(option,"value",true) , gs.elvis(gs.bool(gs.gp(option,"code",true)) , gs.gp(option,"code",true) , "")); } gSobject['deliveryAddress'] = function(it) { if (!gs.bool(gs.mc(gSobject,"requiresDeliveryDetails",[]))) { return ""; }; var parts = gs.mc(gs.list([gs.gp(gSobject.scope,"addressLine1") , gs.gp(gSobject.scope,"suburb") , gs.gp(gSobject.scope,"city") , gs.gp(gSobject.scope,"province") , gs.gp(gSobject.scope,"postalCode")]),"findAll",[function(it) { return gs.mc(gs.mc(it,"toString",[], null, true),"trim",[], null, true); }]); return gs.mc(parts,"join",["\n"]); } gSobject['contactName'] = function(it) { if (!gs.bool(gs.mc(gSobject,"requiresDeliveryDetails",[]))) { return ""; }; return gs.elvis(gs.bool(gs.gp(gSobject.scope,"contactPerson")) , gs.gp(gSobject.scope,"contactPerson") , ""); } gSobject['contactEmail'] = function(it) { return gs.elvis(gs.bool(gs.gp(gs.gp(gSobject.scope,"rxmeUser"),"email",true)) , gs.gp(gs.gp(gSobject.scope,"rxmeUser"),"email",true) , gs.elvis(gs.bool(gs.gp(gs.gp(gs.fs('session', this, gSobject),"user",true),"email",true)) , gs.gp(gs.gp(gs.fs('session', this, gSobject),"user",true),"email",true) , "")); } gSobject['contactNumber'] = function(it) { if (!gs.bool(gs.mc(gSobject,"requiresDeliveryDetails",[]))) { return ""; }; return gs.elvis(gs.bool(gs.gp(gSobject.scope,"contactNumberValue")) , gs.gp(gSobject.scope,"contactNumberValue") , ""); } gSobject['accountNumber'] = function(it) { return gs.elvis(gs.bool(gs.gp(gs.gp(gSobject.scope,"patient"),"accountNumber",true)) , gs.gp(gs.gp(gSobject.scope,"patient"),"accountNumber",true) , gs.elvis(gs.bool(gs.gp(gs.gp(gSobject.scope,"rxmeUser"),"accountNumber",true)) , gs.gp(gs.gp(gSobject.scope,"rxmeUser"),"accountNumber",true) , gs.elvis(gs.bool(gs.gp(gs.gp(gSobject.scope,"rxmeUser"),"_id",true)) , gs.gp(gs.gp(gSobject.scope,"rxmeUser"),"_id",true) , ""))); } gSobject['applySavedDeliveryDetails'] = function(savedDeliveryDetails) { gs.sp(gSobject.scope,"contactPerson",gs.elvis(gs.bool(gs.gp(savedDeliveryDetails,"contactPerson")) , gs.gp(savedDeliveryDetails,"contactPerson") , "")); gs.sp(gSobject.scope,"contactNumberValue",gs.elvis(gs.bool(gs.gp(savedDeliveryDetails,"contactNumber")) , gs.gp(savedDeliveryDetails,"contactNumber") , "")); gs.sp(gSobject.scope,"alternativeContactNumber",gs.elvis(gs.bool(gs.gp(savedDeliveryDetails,"alternativeContactNumber")) , gs.gp(savedDeliveryDetails,"alternativeContactNumber") , "")); gs.sp(gSobject.scope,"addressLine1",gs.elvis(gs.bool(gs.gp(savedDeliveryDetails,"addressLine1")) , gs.gp(savedDeliveryDetails,"addressLine1") , "")); gs.sp(gSobject.scope,"suburb",gs.elvis(gs.bool(gs.gp(savedDeliveryDetails,"suburb")) , gs.gp(savedDeliveryDetails,"suburb") , "")); gs.sp(gSobject.scope,"city",gs.elvis(gs.bool(gs.gp(savedDeliveryDetails,"city")) , gs.gp(savedDeliveryDetails,"city") , "")); gs.sp(gSobject.scope,"province",gs.elvis(gs.bool(gs.gp(savedDeliveryDetails,"province")) , gs.gp(savedDeliveryDetails,"province") , "")); gs.sp(gSobject.scope,"postalCode",gs.elvis(gs.bool(gs.gp(savedDeliveryDetails,"postalCode")) , gs.gp(savedDeliveryDetails,"postalCode") , "")); return gs.sp(gSobject.scope,"deliveryInstructions",gs.elvis(gs.bool(gs.gp(savedDeliveryDetails,"instructions")) , gs.gp(savedDeliveryDetails,"instructions") , "")); } gSobject['orderSummaryName'] = function(it) { var first = gs.elvis(gs.bool(gs.gp(gs.gp(gSobject.scope,"rxmeUser"),"firstName",true)) , gs.gp(gs.gp(gSobject.scope,"rxmeUser"),"firstName",true) , gs.elvis(gs.bool(gs.gp(gs.gp(gs.fs('session', this, gSobject),"user",true),"name",true)) , gs.gp(gs.gp(gs.fs('session', this, gSobject),"user",true),"name",true) , "")); var last = gs.elvis(gs.bool(gs.gp(gs.gp(gSobject.scope,"rxmeUser"),"lastName",true)) , gs.gp(gs.gp(gSobject.scope,"rxmeUser"),"lastName",true) , ""); var full = gs.mc("" + (first) + " " + (last) + "","trim",[]); return gs.elvis(gs.bool(full) , full , gs.elvis(gs.bool(gs.gp(gs.gp(gSobject.scope,"rxmeUser"),"name",true)) , gs.gp(gs.gp(gSobject.scope,"rxmeUser"),"name",true) , gs.elvis(gs.bool(gs.gp(gs.gp(gs.fs('session', this, gSobject),"user",true),"name",true)) , gs.gp(gs.gp(gs.fs('session', this, gSobject),"user",true),"name",true) , "Patient"))); } gSobject['validateDeliveryDetails'] = function(it) { gs.sp(gSobject.scope,"deliveryFieldErrors",gs.map()); if (!gs.bool(gs.mc(gSobject,"requiresDeliveryDetails",[]))) { return true; }; if (!gs.bool(gs.mc(gs.gp(gSobject.scope,"contactPerson"),"trim",[], null, true))) { gs.sp(gs.gp(gSobject.scope,"deliveryFieldErrors"),"contactPerson","Contact person is required."); }; if (!gs.bool(gs.mc(gs.gp(gSobject.scope,"contactNumberValue"),"trim",[], null, true))) { gs.sp(gs.gp(gSobject.scope,"deliveryFieldErrors"),"contactNumberValue","Contact number is required."); }; if (!gs.bool(gs.mc(gs.gp(gSobject.scope,"addressLine1"),"trim",[], null, true))) { gs.sp(gs.gp(gSobject.scope,"deliveryFieldErrors"),"addressLine1","Delivery address is required."); }; if (!gs.bool(gs.mc(gs.gp(gSobject.scope,"province"),"trim",[], null, true))) { gs.sp(gs.gp(gSobject.scope,"deliveryFieldErrors"),"province","Province is required."); }; if (!gs.bool(gs.mc(gs.gp(gSobject.scope,"postalCode"),"trim",[], null, true))) { gs.sp(gs.gp(gSobject.scope,"deliveryFieldErrors"),"postalCode","Postal code is required."); }; return gs.mc(gs.gp(gSobject.scope,"deliveryFieldErrors"),"isEmpty",[]); } gSobject['clearDeliveryFieldError'] = function(fieldName) { if (!gs.bool(gs.gp(gSobject.scope,"deliveryFieldErrors"))) { return null; }; return gs.mc(gs.gp(gSobject.scope,"deliveryFieldErrors"),"remove",[fieldName]); } gSobject['requiresDeliveryDetails'] = function(it) { return gs.equals(gs.gp(gSobject.scope,"selectedDeliveryMethod"), "delivery"); } gSobject['randInt'] = function(value) { var raw = gs.mc((gs.equals(value, null) ? "0" : gs.mc(value,"toString",[])),"trim",[]); if (!gs.bool(raw)) { return 0; }; return gs.mc(gs.mc(raw,"tokenize",["."])[0],"toInteger",[]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function PeptideOrdersQuoteComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'PeptideOrdersQuoteComponent', simpleName: 'PeptideOrdersQuoteComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/peptideOrderQuote"; gSobject['created'] = function(it) { gs.println("component created"); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "peptide.quote.page"]),"do",[]); gs.mc(gSobject,"componentTheme",[false]); gs.mc(gSobject,"showFooter",[false]); gs.sp(gSobject.scope,"loading",false); gs.mc(gSobject,"loadOrders",[]); gs.sp(gSobject.scope,"quoteId",""); gs.sp(gSobject.scope,"quote",null); gs.sp(gSobject.scope,"quoteError",false); gs.sp(gSobject.scope,"fileObj",gs.map()); if (gs.bool(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"cart"))) { gs.sp(gSobject.scope,"products",gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"cart")); }; gs.mc(gs.gp(gs.fs('o', this, gSobject),"protoDataFile"),"findOrCreate",[gs.map().add("_id",gs.gp(gs.gp(gSobject.scope,"fileObj"),"_id")), function(fileObj) { return gs.sp(gSobject.scope,"fileObj",fileObj); }]); return gs.sp(gSobject.scope,"columns",gs.list([gs.map().add("name","Description").add("label","Description").add("field","Description").add("align","left") , gs.map().add("name","Quantity").add("label","Qty").add("field","Quantity").add("align","center") , gs.map().add("name","LineAmount").add("label","Total").add("field","LineAmount").add("align","right")])); } gSobject['loadOrders'] = function(it) { gs.sp(gSobject.scope,"invoices",gs.list([])); gs.sp(gSobject.scope,"quotes",gs.list([])); gs.sp(gSobject.scope,"orders",gs.list([])); gs.sp(gSobject.scope,"loading",true); return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppApiService"),"orders",[gs.gp(gs.fs('session', this, gSobject),"userId")]),"then",[function(data) { gs.println("loadOrders"); gs.println(data); var allOrders = gs.elvis(gs.bool(gs.gp(data,"orders",true)) , gs.gp(data,"orders",true) , gs.list([])); gs.sp(gSobject.scope,"orders",allOrders); var latestOrder = (gs.mc(allOrders,"size",[]) > 0 ? allOrders[(gs.minus(gs.mc(allOrders,"size",[]), 1))] : null); var latestQuote = gs.gp(gs.gp(latestOrder,"meta",true),"quote",true); if (gs.bool(latestQuote)) { gs.sp(gSobject.scope,"quote",latestQuote); gs.sp(gSobject.scope,"quoteError",false); } else { gs.sp(gSobject.scope,"quote",null); gs.sp(gSobject.scope,"quoteError",true); }; gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"quote",gs.gp(gSobject.scope,"quote")); return gs.sp(gSobject.scope,"loading",false); }, function(error) { return gs.sp(gSobject.scope,"loading",false); }]); } gSobject['formatStoreCurrency'] = function(value) { return gs.mc(value,"toFixed",[2], null, true); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function PeptideBankingDetailsComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'PeptideBankingDetailsComponent', simpleName: 'PeptideBankingDetailsComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/peptideBankingDetails"; gSobject['created'] = function(it) { gs.println("component created"); gs.mc(gSobject,"componentTheme",[false]); gs.mc(gSobject,"showFooter",[false]); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "peptide.banking.page"]),"do",[]); gs.sp(gSobject.scope,"quote",null); if (gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"peptideDeliveryTotal") != null) { gs.sp(gSobject.scope,"quote",gs.map().add("Total",gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"peptideDeliveryTotal"))); } else { if (gs.bool(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"quote"))) { gs.sp(gSobject.scope,"quote",gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"quote")); }; }; return gs.mc(gSobject,"loadBankingDetails",[]); } gSobject['loadBankingDetails'] = function(it) { gs.sp(gSobject.scope,"bankingDetails",gs.map()); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppApiService"),"bankDetails",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(result) { return gs.sp(gSobject.scope,"bankingDetails",result); }]); } gSobject['copy'] = function(text) { if (!gs.bool(text)) { return null; }; return gs.mc(gs.mc(gs.gp(gs.gp(gs.fs('window', this, gSobject),"navigator"),"clipboard"),"writeText",[gs.mc(text,"toString",[])]),"then",[function(it) { return gs.mc(gSobject.q,"notify",[gs.map().add("message","Copied to clipboard").add("color","positive").add("icon","check").add("timeout",2000).add("position","bottom")]); }, function(error) { return gs.mc(this,"popup",["Copy Failed", "Please manually select and copy the text."], gSobject); }]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function PeptideOrdersPoPComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'PeptideOrdersPoPComponent', simpleName: 'PeptideOrdersPoPComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/peptideOrderPoP"; gSobject['created'] = function(it) { gs.println("component created"); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "peptide.pop.page"]),"do",[]); gs.mc(gSobject,"componentTheme",[false]); gs.mc(gSobject,"showFooter",[false]); gs.sp(gSobject.scope,"quoteId",""); gs.sp(gSobject.scope,"peptide",""); gs.sp(gSobject.scope,"fileObj",gs.map()); gs.sp(gSobject.scope,"btnLoading",false); return gs.mc(gSobject,"loadOrders",[]); } gSobject['loadOrders'] = function(it) { gs.sp(gSobject.scope,"invoices",gs.list([])); gs.sp(gSobject.scope,"quotes",gs.list([])); gs.sp(gSobject.scope,"orders",gs.list([])); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppApiService"),"orders",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(data) { gs.println("loadOrders"); gs.println(data); var allOrders = gs.elvis(gs.bool(gs.gp(data,"orders",true)) , gs.gp(data,"orders",true) , gs.list([])); gs.sp(gSobject.scope,"orders",allOrders); var latestOrder = (gs.mc(allOrders,"size",[]) > 0 ? allOrders[(gs.minus(gs.mc(allOrders,"size",[]), 1))] : null); var latestQuote = gs.gp(gs.gp(latestOrder,"meta",true),"quote",true); if (gs.bool(latestQuote)) { gs.sp(gSobject.scope,"quote",latestQuote); gs.sp(gSobject.scope,"quoteId",gs.gp(latestQuote,"QuoteID")); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppApiService"),"loadPop",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(latestQuote,"QuoteID"), function(fileObj) { gs.println("FILE OBJECT"); gs.println(fileObj); return gs.sp(gSobject.scope,"fileObj",fileObj); }]); } else { gs.sp(gSobject.scope,"quote",null); return gs.sp(gSobject.scope,"fileObj",gs.map()); }; }]); } gSobject['acceptQuote'] = function(it) { if (gs.bool(gs.gp(gSobject.scope,"btnLoading"))) { return null; }; if (!gs.bool(gs.gp(gs.gp(gSobject.scope,"fileObj"),"file",true))) { gs.mc(gSobject,"notify",["Please wait for the proof of payment upload to finish before submitting.", "warning"]); return null; }; gs.sp(gSobject.scope,"btnLoading",true); return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"rxmeAppApiService"),"acceptQuote",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gs.gp(gSobject.scope,"quote"),"QuoteID")]),"then",[function(response) { gs.println(gs.plus((gs.multiply("=", 20)), "RESPONSE")); gs.println(response); gs.mc(gSobject,"notify",["Proof of Payment Submitted", "positive"]); gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"cart",gs.list([])); gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"quote",null); gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"peptideDeliveryMethod",null); gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"peptideDeliveryDetails",null); gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"peptideDeliveryAddress",null); gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"peptideDeliveryContactName",null); gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"peptideDeliveryContactNumber",null); gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"peptideDeliveryConfirmed",null); gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"peptideDeliverySubtotal",null); gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"peptideDeliveryCharge",null); gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"peptideDeliveryVat",null); gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"peptideDeliveryTotal",null); gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/peptideOrders"]); return gs.sp(gSobject.scope,"btnLoading",false); }, function(error) { gs.println("ACCEPT QUOTE ERROR → " + (error) + ""); var safeMsg = "Something went wrong while submitting your proof of payment."; var backendMsg = gs.mc(gs.elvis(gs.bool(gs.gp(error,"message",true)) , gs.gp(error,"message",true) , ""),"toString",[]); if (gs.mc(backendMsg,"contains",["isEmpty() on null"])) { safeMsg = "The proof of payment could not be processed. Please try again or upload a different file."; } else { if (gs.mc(backendMsg,"contains",["Invalid base64"])) { safeMsg = "The uploaded file is not valid. Please upload a valid PDF or image."; } else { if (gs.mc(backendMsg,"contains",["quote"])) { safeMsg = "This quote can no longer be accepted. Please request a new one."; }; }; }; gs.mc(gSobject,"notify",[safeMsg, "negative"]); return gs.sp(gSobject.scope,"btnLoading",false); }]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function TrackableReminderComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'TrackableReminderComponent', simpleName: 'TrackableReminderComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/trackableReminder/:type"; gSobject['created'] = function(it) { gs.mc(gSobject,"showHeaderFooter",[]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"daysOfWeek",gs.list(["Monday" , "Tuesday" , "Wednesday" , "Thursday" , "Friday" , "Saturday" , "Sunday"])); gs.sp(gSobject.scope,"header",""); return gs.mc(gSobject,"loadSchedule",[]); } gSobject['loadSchedule'] = function(it) { gs.sp(gSobject.scope,"schedule",gs.map().add("days",gs.list([])).add("time",null).add("type",gs.gp(gs.gp(gSobject.route,"params"),"type"))); gs.sp(gSobject.scope,"header",(gs.plus((gs.plus(gs.mc(gs.gp(gs.gp(gSobject.route,"params"),"type"),"capitalize",[]), " ")), "Reminder"))); gs.mc(gs.gp(gs.fs('o', this, gSobject),"scheduleService"),"loadTrackable",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gs.gp(gSobject.route,"params"),"type"), function(schedule) { gs.println(gs.plus((gs.plus((gs.multiply("=", 20)), "SCHEDULE")), (gs.multiply("=", 20)))); gs.println(gs.gp(schedule,"time")); gs.sp(gSobject.scope,"schedule",schedule); return gs.sp(gs.gp(gSobject.scope,"schedule"),"time",(gs.bool(gs.gp(schedule,"time")) ? gs.mc(gSobject,"moment",[gs.gp(schedule,"time")]) : gs.mc(gSobject,"moment",[]))); }]); return gs.println("LOADED TIME: " + (gs.mc(gs.gp(gs.gp(gSobject.scope,"schedule"),"time"),"format",["HH:mm"])) + ""); } gSobject['handleDayClick'] = function(day) { if (gs.gSin(day, gs.gp(gs.gp(gSobject.scope,"schedule"),"days"))) { return gs.mc(gs.gp(gs.gp(gSobject.scope,"schedule"),"days"),"remove",[day]); }; return gs.mc(gs.gp(gs.gp(gSobject.scope,"schedule"),"days"),"push",[day]); } gSobject['isSelected'] = function(day) { return gs.gSin(day, gs.gp(gs.gp(gSobject.scope,"schedule"),"days")); } gSobject['save'] = function(it) { gs.sp(gs.gp(gSobject.scope,"schedule"),"time",gs.date(gs.gp(gs.gp(gSobject.scope,"schedule"),"time"))); gs.println(gs.plus((gs.plus((gs.multiply("=", 20)), "SCHEDULE TIME")), (gs.multiply("=", 20)))); gs.println(gs.gp(gs.gp(gSobject.scope,"schedule"),"time")); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"scheduleService"),"saveTrackable",[gs.gp(gSobject.scope,"schedule"), function(it) { gs.mc(gSobject,"notify",["Reminder Saved"]); if (gs.equals(gs.gp(gs.gp(gSobject.scope,"schedule"),"type"), "Motivation")) { gs.println("Generating daily motivational text because reminder was saved"); gs.mc(gSobject,"generateAndSaveMotivation",[gs.gp(gs.fs('session', this, gSobject),"userId"), "Daily"]); }; return gs.mc(gSobject,"back",[]); }]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function ConsentComponent2() { var gSobject = RootComponent(); gSobject.clazz = { name: 'ConsentComponent2', simpleName: 'ConsentComponent2'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/terms&condition"; gSobject['created'] = function(it) { gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"add",[gs.gp(gs.fs('session', this, gSobject),"userId"), "consent.policy.page"]),"do",[]); gs.mc(gSobject,"showHeaderFooter",[false]); gs.mc(gSobject,"componentTheme",[false]); gs.sp(gSobject.scope,"appVersion",gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"appVersion")); gs.sp(gSobject.scope,"agreements",gs.list([])); gs.sp(gSobject.scope,"active",gs.map()); gs.sp(gSobject.scope,"isSubmitting",false); gs.sp(gSobject.scope,"signaturePad",null); gs.sp(gSobject.scope,"hasUploadedSignature",false); return gs.mc(gSobject,"loadAgreements",[]); } gSobject['loadAgreements'] = function(it) { gs.mc(gSobject,"showLoading",[]); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"consentService"),"unconsentedAgreements",[gs.gp(gs.fs('session', this, gSobject),"userId"), function(data) { gs.mc(gSobject,"hideLoading",[]); if (!gs.bool(data)) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/home"]); }; gs.sp(gSobject.scope,"agreements",data); gs.sp(gSobject.scope,"active",(gs.gp(gSobject.scope,"agreements")[0])); return gs.mc(gSobject,"openSignaturePad",[]); }]); } gSobject['onSubmit'] = function(it) { if (!gs.bool(gs.gp(gSobject.scope,"hasUploadedSignature"))) { return gs.mc(gSobject,"notify",["Please Sign", "negative"]); }; gs.sp(gSobject.scope,"isSubmitting",true); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"consentService"),"consentToAgreement",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gs.gp(gSobject.scope,"active"),"_id"), function(it) { gs.sp(gSobject.scope,"isSubmitting",false); gs.mc(gs.gp(gSobject.scope,"agreements"),"remove",[0]); if (gs.equals(gs.gp(gs.gp(gSobject.scope,"agreements"),"length"), 0)) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/home"]); }; gs.sp(gSobject.scope,"signaturePad",null); gs.sp(gSobject.scope,"hasUploadedSignature",false); gs.mc(gSobject,"openSignaturePad",[]); return gs.sp(gSobject.scope,"active",(gs.gp(gSobject.scope,"agreements")[0])); }]); } gSobject['logout'] = function(it) { return gs.execStatic(Utils,'logout', this,["/"]); } gSobject['openSignaturePad'] = function(it) { return gs.mc(gSobject,"nextTick",[function(it) { gs.sp(gSobject.scope,"signaturePad",gs.gp(gs.mc(gSobject,"newSignaturePad",["signature"]),"signaturePad")); return gs.mc(gs.gp(gSobject.scope,"signaturePad"),"addEventListener",["endStroke", function(it) { return gs.execStatic(Utils,'dataUrlToBlob', this,[gs.mc(gs.gp(gSobject.scope,"signaturePad"),"toDataURL",[]), function(blob) { return gs.execStatic(Utils,'post', this,[blob, "signature", "legionUser", gs.gp(gs.fs('session', this, gSobject),"userId"), function(data) { gs.println("Signature Uplaoded"); return gs.sp(gSobject.scope,"hasUploadedSignature",true); }]); }]); }]); }]); } gSobject.newSignaturePad = function(name) { var canvas = document.getElementById(name) var signaturePad = new SignaturePad(canvas) return {signaturePad:signaturePad, canvasCtx:canvas.getContext("2d")} } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function I3PageHeader() { var gSobject = VueComponent(); gSobject.clazz = { name: 'I3PageHeader', simpleName: 'I3PageHeader'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.props = gs.map().add("backBtn",Boolean); gSobject.data = function(it) { return gs.list([]); }; gSobject['created'] = function(it) { var self = this; } gSobject['back'] = function(it) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"back",[]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function ToolbarComponent() { var gSobject = VueComponent(); gSobject.clazz = { name: 'ToolbarComponent', simpleName: 'ToolbarComponent'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.props = gs.map().add("label",String).add("path",String).add("info",String).add("noBack",Boolean).add("home",Boolean).add("rightIcon",String).add("rightBadge",Number).add("rightTo",String); gSobject['created'] = function(it) { var self = this; return gs.sp(gSobject.scope,"isScrolled",false); } gSobject['mounted'] = function(it) { var self = this; var scrollContainer = gs.mc(gs.fs('document', this, gSobject),"querySelector",[".q-scrollarea__container"]); if (gs.bool(scrollContainer)) { gs.sp(gSobject.scope,"isScrolled",(gs.gp(scrollContainer,"scrollTop") > 0)); return gs.mc(scrollContainer,"addEventListener",["scroll", function(it) { if (gs.gp(scrollContainer,"scrollTop") >= 5) { return gs.sp(gSobject.scope,"isScrolled",true); } else { if (gs.gp(scrollContainer,"scrollTop") <= 0) { return gs.sp(gSobject.scope,"isScrolled",false); }; }; }]); }; } gSobject['back'] = function(it) { if ((!gs.bool(gs.gp(gSobject.self,"noBack"))) && (!gs.bool(gs.gp(gSobject.self,"home")))) { gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"back",[]); }; if (gs.bool(gs.gp(gSobject.self,"home"))) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/home"]); }; } gSobject['popup'] = function(it) { return gs.mc(gSobject.q,"dialog",[gs.map().add("title","More Information").add("message",gs.gp(gSobject.self,"info"))]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function CordovaScreenCapture() { var gSobject = gs.init('CordovaScreenCapture'); gSobject.clazz = { name: 'CordovaScreenCapture', simpleName: 'CordovaScreenCapture'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject['capture'] = function(success, error, opts) { if (success === undefined) success = function(it) { }; if (error === undefined) error = function(it) { }; if (opts === undefined) opts = gs.map(); return gs.mc(gSobject,"nativeCaptureSvgToPng",[gs.elvis(gs.bool(gs.gp(opts,"maxWidth")) , gs.gp(opts,"maxWidth") , 1280), success, error]); } gSobject['openProblemReport'] = function(it) { return gs.mc(gSobject,"capture",[function(blob, meta) { gs.mc(gSobject,"nativeStashBlob",[blob]); return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/reportProblem"]); }, function(err) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"error",["openProblemReport: capture failed: " + (err) + ""]); gs.mc(gSobject,"nativeStashBlob",[null]); return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/reportProblem"]); }]); } gSobject['reportProblem'] = function(userMessage, opts, success, error) { if (opts === undefined) opts = gs.map(); if (success === undefined) success = function(it) { }; if (error === undefined) error = function(it) { }; var stashed = gs.mc(gSobject,"nativeReadStashedBlob",[]); if (gs.bool(stashed)) { gs.mc(gSobject,"uploadAndCreateReport",[userMessage, opts, stashed, gs.map().add("type","image/png").add("width",0).add("height",0).add("fallback",false), success, error]); return null; }; return gs.mc(gSobject,"capture",[function(blob, meta) { return gs.mc(gSobject,"uploadAndCreateReport",[userMessage, opts, blob, meta, success, error]); }, function(captureErr) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"error",["CordovaScreenCapture:reportProblem:capture failed: " + (captureErr) + ""]); return gs.mc(gSobject,"uploadAndCreateReport",[userMessage, opts, null, gs.map(), success, error]); }]); } gSobject['uploadAndCreateReport'] = function(userMessage, opts, blob, meta, success, error) { var report = gs.mc(gSobject,"buildReportContext",[userMessage, opts, meta]); gs.sp(report,"hasScreenshot",(blob != null)); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"cordovaService"),"userProblem",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gs.gp(gs.fs('cordovaDevice', this, gSobject),"device"),"uuid"), report, function(result) { if (!gs.bool(gs.gp(result,"id",true))) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"error",["CordovaScreenCapture:reportProblem:userProblem returned no id"]); return gs.execCall(error, this, ["Failed to create problem report"]); }; if (!gs.bool(blob)) { return gs.execCall(success, this, [gs.gp(result,"id")]); }; return gs.execStatic(Utils,'post', this,[blob, "screenshot", "userError", gs.gp(result,"id"), function(uploadResult) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["CordovaScreenCapture:reportProblem:uploaded screenshot for " + (gs.gp(result,"id")) + ""]); return gs.execCall(success, this, [gs.gp(result,"id")]); }, function(uploadErr) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"error",["CordovaScreenCapture:reportProblem:screenshot upload failed: " + (uploadErr) + ""]); return gs.execCall(success, this, [gs.gp(result,"id")]); }]); }]); } gSobject['buildReportContext'] = function(userMessage, opts, meta) { var ctx = gs.mc(gSobject,"nativeGatherContext",[]); return gs.map().add("userMessage",gs.elvis(gs.bool(userMessage) , userMessage , "")).add("severity",gs.elvis(gs.bool(gs.gp(opts,"severity")) , gs.gp(opts,"severity") , "normal")).add("message",gs.elvis(gs.bool(userMessage) , userMessage , "(no description)")).add("route",gs.gp(ctx,"route")).add("pageTitle",gs.gp(ctx,"pageTitle")).add("appPath",gs.gp(ctx,"appPath")).add("viewport",gs.gp(ctx,"viewport")).add("orientation",gs.gp(ctx,"orientation")).add("locale",gs.gp(ctx,"locale")).add("tz",gs.gp(ctx,"tz")).add("consoleTail",gs.gp(ctx,"consoleTail")).add("routeHistory",gs.gp(ctx,"routeHistory")).add("userAgent",gs.gp(ctx,"userAgent")).add("platform",gs.elvis(gs.bool(gs.gp(gs.gp(gs.fs('cordovaDevice', this, gSobject),"device"),"platform")) , gs.gp(gs.gp(gs.fs('cordovaDevice', this, gSobject),"device"),"platform") , "browser")).add("appVersion",gs.elvis(gs.bool(gs.gp(gs.gp(gs.fs('cordovaDevice', this, gSobject),"device"),"version")) , gs.gp(gs.gp(gs.fs('cordovaDevice', this, gSobject),"device"),"version") , "")).add("appBuild",gs.elvis(gs.bool(gs.gp(gs.gp(gs.fs('cordovaDevice', this, gSobject),"device"),"cordova")) , gs.gp(gs.gp(gs.fs('cordovaDevice', this, gSobject),"device"),"cordova") , "")).add("clientReportedAt",gs.mc(gs.date(),"getTime",[])); } gSobject.nativeGatherContext = function() { var route = ''; var routeHistory = ''; try { if (window.vue && window.vue.router && window.vue.router.currentRoute) { route = window.vue.router.currentRoute.value ? window.vue.router.currentRoute.value.fullPath : window.vue.router.currentRoute.fullPath || ''; } } catch(e) {} try { if (window._cwRouteHistory) routeHistory = window._cwRouteHistory.slice(-5).join(' -> '); } catch(e) {} var tail = ''; try { if (window._cwConsoleTail) tail = window._cwConsoleTail.join('\n'); } catch(e) {} return { route : route, pageTitle : (typeof document !== 'undefined') ? (document.title || '') : '', appPath : (typeof window !== 'undefined' && window.location) ? window.location.pathname : '', viewport : (window.innerWidth + 'x' + window.innerHeight + ' @ ' + (window.devicePixelRatio || 1) + 'x'), orientation : (screen && screen.orientation) ? (screen.orientation.type || '') : '', locale : (navigator && navigator.language) ? navigator.language : '', tz : (Intl && Intl.DateTimeFormat) ? Intl.DateTimeFormat().resolvedOptions().timeZone : '', consoleTail : tail, routeHistory: routeHistory, userAgent : (navigator && navigator.userAgent) ? navigator.userAgent : '' }; } gSobject.nativeStashBlob = function(blob) { if (blob) window._cwPendingReport = { blob: blob, ts: Date.now() }; else window._cwPendingReport = null; } gSobject.nativeReadStashedBlob = function() { return window._cwPendingReport ? window._cwPendingReport.blob : null; } gSobject.nativeCaptureSvgToPng = function(maxWidth, success, error) { try { var node = document.documentElement; var w = Math.max(node.scrollWidth, document.body ? document.body.scrollWidth : 0, window.innerWidth); var h = Math.max(node.scrollHeight, document.body ? document.body.scrollHeight : 0, window.innerHeight); // Clone so we can inline computed styles without mutating the live DOM. var clone = node.cloneNode(true); // Strip