From c8f845c6e3f6af9c13f7bbcf666312b41c93175a Mon Sep 17 00:00:00 2001 From: Matias Date: Wed, 29 May 2019 11:31:44 -0300 Subject: [PATCH] Integration with saweb-api --- Dashboard.js | 56 +--- Exchange/ExchangeAPI.js | 131 -------- FloatingSpace/CodeEditor.js | 4 +- StrategySpace/StrategizerGateway.js | 16 +- TopSpace/EndUser.js | 84 ----- TopSpace/Login.js | 490 ++++++++-------------------- 6 files changed, 144 insertions(+), 637 deletions(-) delete mode 100644 Exchange/ExchangeAPI.js delete mode 100644 TopSpace/EndUser.js diff --git a/Dashboard.js b/Dashboard.js index 773606797..46d5dd536 100644 --- a/Dashboard.js +++ b/Dashboard.js @@ -91,61 +91,7 @@ function newDashboard () { function loadImages (callBack) { try { const accessToken = '' - - /* - Soon, we will need to get images from the Financial Beings Module. I live this core here as a sample for that: - - const apolloClient = new Apollo.lib.ApolloClient({ - networkInterface: Apollo.lib.createNetworkInterface({ - uri: window.canvasApp.graphQL.masterAppApiUrl, - transportBatching: true, - }), - connectToDevTools: true, - }) - - const QUERY = Apollo.gql` - query($authId: String){ - users_UserByAuthId (authId: $authId){ - id - referrerId - alias - firstName - middleName - lastName - bio - email - emailVerified - isDeveloper - isDataAnalyst - isTrader - avatarHandle - avatarChangeDate - role { - id - } - } - } - ` - const getUser = () => { - return new Promise((resolve, reject) => { - apolloClient.query({ - query: QUERY, - variables: { - authId: authId - } - }) - .then(response => { - window.localStorage.setItem('loggedInUser', JSON.stringify(response.data.users_UserByAuthId)); - resolve({ user: response.data.users_UserByAuthId }) - }) - .catch(error => { - console.log("apolloClient error getting user query", error) - reject(error) - }); - }); - } - - */ + // Soon, we will need to get images from the Financial Beings Module. const networkInterfaceTeams = Apollo.lib.createNetworkInterface({ uri: window.canvasApp.graphQL.masterAppApiUrl diff --git a/Exchange/ExchangeAPI.js b/Exchange/ExchangeAPI.js deleted file mode 100644 index f72cfa729..000000000 --- a/Exchange/ExchangeAPI.js +++ /dev/null @@ -1,131 +0,0 @@ - function newExchangeAPI () { - const INFO_LOG = true - const LOG_FILE_CONTENT = true - - const MODULE_NAME = 'CloudVM -> Exchange API' - - const SERVER_URL = window.canvasApp.urlPrefix + 'ExchangeAPI/' - - let thisObject = { - initialize: initialize, - getTicker: getTicker, - getOpenPositions: getOpenPositions, - getExecutedTrades: getExecutedTrades, - putPosition: putPosition, - movePosition: movePosition, - getPublicTradeHistory: getPublicTradeHistory - } - - return thisObject - - function initialize (callBackFunction) { - /* When this initialized is called from the Browser, there is no need to send it to the server since the server will - anyways initialize this library at each method call. */ - - callBackFunction(window.DEFAULT_OK_RESPONSE) - } - - function getTicker (pMarket, callBackFunction) { - let authToken = window.localStorage.getItem('access_token') - - let path = SERVER_URL - + "getTicker" + "/" - + authToken - - callServer(undefined, path + '/NO-LOG', onServerResponse) - - function onServerResponse (pServerResponse) { - let response = JSON.parse(pServerResponse) - if (response.result === window.DEFAULT_FAIL_RESPONSE.result) { - callBackFunction(window.DEFAULT_FAIL_RESPONSE) - } else { - callBackFunction(window.DEFAULT_OK_RESPONSE, response) - } - } - } - - function getOpenPositions (pMarket, callBackFunction) { - let authToken = window.localStorage.getItem('access_token'); - - let path = SERVER_URL - + "getOpenPositions" + "/" - + authToken - - callServer(undefined, path + '/NO-LOG', onServerResponse) - - function onServerResponse(pServerResponse) { - let response = JSON.parse(pServerResponse); - if (response.result === window.DEFAULT_FAIL_RESPONSE.result) - callBackFunction(window.DEFAULT_FAIL_RESPONSE); - else - callBackFunction(window.DEFAULT_OK_RESPONSE, response); - } - } - - function getExecutedTrades(pPositionId, callBackFunction) { - - let authToken = window.localStorage.getItem('access_token'); - - let path = SERVER_URL - + "getExecutedTrades" + "/" - + authToken + "/" - + pPositionId - ; - - callServer(undefined, path + "/NO-LOG", onServerResponse); - - function onServerResponse(pServerResponse) { - let response = JSON.parse(pServerResponse); - if (response.result === window.DEFAULT_FAIL_RESPONSE.result) - callBackFunction(window.DEFAULT_FAIL_RESPONSE); - else - callBackFunction(window.DEFAULT_OK_RESPONSE, response); - } - } - - function putPosition(pMarket, pType, pRate, pAmountA, pAmountB, callBackFunction) { - - let authToken = window.localStorage.getItem('access_token'); - - let path = SERVER_URL - + "putPosition" + "/" - + authToken + "/" - + pType + "/" - + pRate + "/" - + pAmountA + "/" - + pAmountB - ; - - callServer(undefined, path + '/NO-LOG', onServerResponse) - - function onServerResponse (pServerResponse) { - let response = JSON.parse(pServerResponse) - if (response.result === window.DEFAULT_FAIL_RESPONSE.result) { - callBackFunction(window.DEFAULT_FAIL_RESPONSE) - } else { - callBackFunction(window.DEFAULT_OK_RESPONSE, response) - } - } - } - - function getPublicTradeHistory (pMarket, startTime, endTime, callBackFunction) { - let authToken = window.localStorage.getItem('access_token') - - let path = SERVER_URL - + CURRENT_BOT_CODE_NAME + '/' - + 'getPublicTradeHistory' + '/' - + authToken + '/' - + startTime + '/' - + endTime - - callServer(undefined, path + '/NO-LOG', onServerResponse) - - function onServerResponse(pServerResponse) { - let response = JSON.parse(pServerResponse); - if (response.result === window.DEFAULT_FAIL_RESPONSE.result) - callBackFunction(window.DEFAULT_FAIL_RESPONSE); - else - callBackFunction(window.DEFAULT_OK_RESPONSE, response); - } - } -} diff --git a/FloatingSpace/CodeEditor.js b/FloatingSpace/CodeEditor.js index 8df2e4311..9b910f842 100644 --- a/FloatingSpace/CodeEditor.js +++ b/FloatingSpace/CodeEditor.js @@ -61,8 +61,8 @@ function newCodeEditor () { } thisObject.iconNOT_OK.src = window.canvasApp.urlPrefix + thisObject.imagePathNOT_OK } - thisObject.iconOK.src = window.canvasApp.urlPrefix + thisObject.imagePathOK - thisObject.icon = thisObject.iconOK // The default value is ON. + // thisObject.iconOK.src = window.canvasApp.urlPrefix + thisObject.imagePathOK + // thisObject.icon = thisObject.iconOK // The default value is ON. } function deactivate () { diff --git a/StrategySpace/StrategizerGateway.js b/StrategySpace/StrategizerGateway.js index 1e06d799b..2f2ad4195 100644 --- a/StrategySpace/StrategizerGateway.js +++ b/StrategySpace/StrategizerGateway.js @@ -275,18 +275,14 @@ function newStrategizerGateway () { /* Getting the FB that own the Strategies */ let teamtradingSystemSimulationFB = '' - let teams = window.localStorage.getItem('userTeams') - if (teams === null || teams === '' || teams === []) { - if (ERROR_LOG === true) { logger.write('[ERROR] loadFromStrategyzer -> no user teams found at local storage. Can not get Strategies without them. ') } - return - } - teams = JSON.parse(teams) + let ecosystem = JSON.parse(window.localStorage.getItem('ecosystem')) + let teams = ecosystem.devTeams for (let i = 0; i < teams.length; i++) { let team = teams[i] - for (let j = 0; j < team.fb.length; j++) { - let fb = team.fb[j] - if (fb.slug.indexOf('simulator') >= 0) { - teamtradingSystemSimulationFB = fb.slug + for (let j = 0; j < team.bots.length; j++) { + let bot = team.bots[j] + if (bot.codeName.indexOf('simulator') >= 0) { + teamtradingSystemSimulationFB = bot.codeName } } } diff --git a/TopSpace/EndUser.js b/TopSpace/EndUser.js deleted file mode 100644 index b8699eb69..000000000 --- a/TopSpace/EndUser.js +++ /dev/null @@ -1,84 +0,0 @@ -  -function newEndUser () { - let thisObject = { - container: undefined, - draw: draw, - getContainer: getContainer, - initialize: initialize - } - - let container = newContainer() - container.initialize() - thisObject.container = container - - thisObject.container.frame.width = 200 - thisObject.container.frame.height = COCKPIT_SPACE_HEIGHT - - container.frame.position.x = viewPort.visibleArea.topRight.x - thisObject.container.frame.width * 5 - container.frame.position.y = viewPort.visibleArea.bottomLeft.y + BREAKPOINT_HEIGHT - - container.isDraggeable = false - - return thisObject - - function initialize () { - let storedUser = window.localStorage.getItem('loggedInUser') - - if (storedUser === null || storedUser === '') { - // User is currently not logged in. - window.USER_LOGGED_IN = '' - return - } - - let loggedInUser = JSON.parse(storedUser) - - window.USER_LOGGED_IN = loggedInUser.alias - - /* Here we will rearrange the storage permissions array into a map, so that it can be easily consumed when needed. */ - - let permissionsMap = new Map() - - for (i = 0; i < window.USER_PROFILE.storagePermissions.length; i++) { - let permission = window.USER_PROFILE.storagePermissions[i] - - permissionsMap.set(permission[0], permission[1]) - } - - window.USER_PROFILE.storagePermissions = permissionsMap - } - - function getContainer (point) { - let container - - /* First we check if this point is inside this object UI. */ - - if (thisObject.container.frame.isThisPointHere(point, true) === true) { - return this.container - } else { - /* This point does not belong to this space. */ - - return undefined - } - } - - function draw () { - return // nothing to show - - thisObject.container.frame.draw(false, false) - - let fontSize = 12 - let label = window.USER_LOGGED_IN - if (label === undefined) { label = '' }; - - let point = { - x: thisObject.container.frame.width * 1 / 3, - y: (thisObject.container.frame.height / 2) + 4 - } - - point = thisObject.container.frame.frameThisPoint(point) - - browserCanvasContext.font = fontSize + 'px ' + UI_FONT.PRIMARY - browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.WHITE + ', 1)' - browserCanvasContext.fillText(label, point.x, point.y) - } -} diff --git a/TopSpace/Login.js b/TopSpace/Login.js index c5a8a58af..099176916 100644 --- a/TopSpace/Login.js +++ b/TopSpace/Login.js @@ -1,8 +1,6 @@ -function newLogin () { +function newLogin() { const MODULE_NAME = 'Login' - const INFO_LOG = false - const INTENSIVE_LOG = false const ERROR_LOG = true const logger = newWebDebugLog() logger.fileName = MODULE_NAME @@ -27,381 +25,163 @@ function newLogin () { container.isDraggeable = false container.isClickeable = true - let currentLabel - - let userAuthorization - return thisObject - async function initialize (pSharedStatus) { + async function initialize(sharedStatus) { try { const accessToken = window.localStorage.getItem('access_token') - let user = window.localStorage.getItem('user') - sharedStatus = pSharedStatus - - if (user === null) { - // if there is no user that means that we are logged off, which means it is time to clean the local storage of things from the last log in. - - window.localStorage.removeItem('loggedInUser') - return + if (accessToken) { + await getEvents(accessToken, sharedStatus) + await getClones(accessToken) } - user = JSON.parse(user) - - const authId = user.authId - - const apolloClient = new Apollo.lib.ApolloClient({ - networkInterface: Apollo.lib.createNetworkInterface({ - uri: window.canvasApp.graphQL.masterAppApiUrl, - transportBatching: true - }), - connectToDevTools: true - }) - - const USERS_QUERY = Apollo.gql` - query($authId: String){ - users_UserByAuthId (authId: $authId){ - id - referrerId - alias - firstName - middleName - lastName - bio - email - emailVerified - isDeveloper - isDataAnalyst - isTrader - avatarHandle - avatarChangeDate - role { - id - } - } - } - ` - const getUser = () => { - return new Promise((resolve, reject) => { - apolloClient.query({ - query: USERS_QUERY, - variables: { - authId: authId - } - }) - .then(response => { - window.localStorage.setItem('loggedInUser', JSON.stringify(response.data.users_UserByAuthId)) - resolve({ user: response.data.users_UserByAuthId}) - }) - .catch(error => { - console.log('apolloClient error getting user query', error.graphQLErrors, error.stack) - reject(error) - }) - }) - } - - /* Getting all Teams */ - - const networkInterfaceTeams = Apollo.lib.createNetworkInterface({ - uri: window.canvasApp.graphQL.masterAppApiUrl - }) - - networkInterfaceTeams.use([{ - applyMiddleware (req, next) { - req.options.headers = { - authorization: `Bearer ${accessToken}` - } - next() - } - }]) - - const apolloClientTeams = new Apollo.lib.ApolloClient({ - networkInterface: networkInterfaceTeams, - connectToDevTools: true - }) - - const TEAM_BY_OWNER_QUERY = Apollo.gql` - query teamsByOwnerQuery { - teams_TeamsByOwner { - id - name - slug - profile { - avatar - banner - description - motto - updatedAt - } - members { - member { - alias - } - } - fb { - id - name - slug - avatar - kind - status { - status - reason - createdAt - } - } - } - } - ` - - const getTeamByOwner = () => { - return new Promise((resolve, reject) => { - apolloClientTeams.query({ - query: TEAM_BY_OWNER_QUERY - }) - .then(response => { - window.localStorage.setItem('userTeams', JSON.stringify(response.data.teams_TeamsByOwner)) - resolve({ teams: response.data.teams_TeamsByOwner}) - }) - .catch(error => { - console.log('apolloClient error getting user teams', error.graphQLErrors, error.stack) - reject(error) - }) - }) - } - - /* Gettings All Events */ - - const networkInterfaceEvents = Apollo.lib.createNetworkInterface({ - uri: window.canvasApp.graphQL.masterAppApiUrl - }) - - const apolloClientEvents = new Apollo.lib.ApolloClient({ - networkInterface: networkInterfaceEvents, - connectToDevTools: true, - addTypename: false - }) - - const EVENTS_QUERY = Apollo.gql` - query events($maxStartDate: Int, $minEndDate: Int){ - events_Events(maxStartDate: $maxStartDate, minEndDate: $minEndDate){ - id - title - startDatetime - endDatetime - participants{ - clone{ - id - team{ - slug - } - bot{ - slug - } - } - } - } - } - ` - - const getCurrentEvents = () => { - var d = new Date() - var nowSeconds = Math.round(d.getTime() / 1000) - var twoWeeksAgoSeconds = nowSeconds - 1209600 - return new Promise((resolve, reject) => { - apolloClientEvents.query({ - query: EVENTS_QUERY, - variables: { maxStartDate: nowSeconds, minEndDate: twoWeeksAgoSeconds } - }) - .then(response => { - window.localStorage.setItem('currentEvents', JSON.stringify(response.data.events_Events)) - currentEvent = window.localStorage.getItem('currentEventObject') - if (currentEvent === null || currentEvent === '[]' || currentEvent === '') { - sharedStatus.currentEventIndex = -1 - } else { - currentEvent = JSON.parse(currentEvent) - sharedStatus.currentEventIndex = response.data.events_Events.findIndex(function (element) { - return element.id == currentEvent.id - }) - } - resolve({ currentEvents: response.data.events_Events}) - }) - .catch(error => { - console.log('apolloClient error getting current events', error.graphQLErrors, error.stack) - reject(error) - }) - }) - } - - /* Getting all Clones */ - - const networkInterfaceClones = Apollo.lib.createNetworkInterface({ - uri: window.canvasApp.graphQL.masterAppApiUrl - }) - - networkInterfaceClones.use([{ - applyMiddleware (req, next) { - req.options.headers = { - authorization: `Bearer ${accessToken}` - } - next() - } - }]) - - const apolloClientClones = new Apollo.lib.ApolloClient({ - networkInterface: networkInterfaceClones, - connectToDevTools: true - }) - - const CLONES_QUERY = Apollo.gql` - query Operations_Clones{ - operations_Clones { - id - authId - teamId - botId - mode - resumeExecution - beginDatetime - endDatetime - waitTime - state - stateDatetime - createDatetime - lastLogs - runAsTeam - summaryDate - buyAverage - sellAverage - marketRate - combinedProfitsA - combinedProfitsB - assetA - assetB - botType - teamName - botName - botAvatar - teamAvatar - processName - keyId - botSlug - } - } - ` - - const getClones = () => { - return new Promise((resolve, reject) => { - apolloClientClones.query({ - query: CLONES_QUERY - }) - .then(response => { - window.localStorage.setItem('userClones', JSON.stringify(response.data.operations_Clones)) - let clones = response.data.operations_Clones - for (let i = 0; i < clones.length; i++) { - let clone = clones[i] - if (clone.botType === 'Trading') { - let teamSlug = clone.teamName.toLowerCase() - teamSlug = teamSlug.replace(' ', '-') - let devTeam = ecosystem.getTeam(teamSlug) - let bot = ecosystem.getBot(devTeam, clone.botSlug) - if (bot !== undefined) { - bot.cloneId = clone.id - } - } - } - - resolve({ clones: response.data.operations_Clones}) - }) - .catch(error => { - console.log('apolloClient error getting user clones', error.graphQLErrors, error.stack) - reject(error) - }) - }) - } - - // To avoid race conditions, add asynchronous fetches to array - let fetchDataPromises = [] - - fetchDataPromises.push(getUser(), getTeamByOwner(), getCurrentEvents(), getClones(), authenticateUser()) - - // When all asynchronous fetches resolve, authenticate user or throw error. - await Promise.all(fetchDataPromises).then(result => { - - }, err => { - console.error('[ERROR] Login -> GraphQL Fetch Error -> err = ', err) - }) - thisObject.container.eventHandler.listenToEvent('onMouseClick', onClick) - async function authenticateUser () { - // TODO USER_PROFILE should be retrieved from saweb-api ecosystem - return - - let path = window.canvasApp.urlPrefix + 'AABrowserAPI/authenticateUser/' - - return new Promise( - function (resolve, reject) { - callServer(undefined, path, (result) => { - let responseFromServer = JSON.parse(result) - - err = responseFromServer.err - - if (err.result !== GLOBAL.DEFAULT_OK_RESPONSE.result) { - console.log('Please make sure you create a new team!') - reject(err) - } - - window.USER_PROFILE = responseFromServer.userProfile - - currentLabel = 'Logged In' - resolve() - }) - } - ) - } } catch (err) { - if (ERROR_LOG === true) { logger.write('[ERROR] initialize -> err = ' + err.stack) } + if (ERROR_LOG === true) { logger.write('[ERROR] initialize -> err = ' + err) } + if (ERROR_LOG === true) { logger.write('[ERROR] initialize -> err.stack = ' + err.stack) } } } - function onClick () { + async function getEvents(accessToken, sharedStatus) { + var d = new Date() + var nowSeconds = Math.round(d.getTime() / 1000) + var twoWeeksAgoSeconds = nowSeconds - 1209600 + + let response = await axios({ + url: window.canvasApp.graphQL.masterAppApiUrl, + method: 'post', + data: { + query: + `query events($maxStartDate: Int, $minEndDate: Int){ + events_Events(maxStartDate: $maxStartDate, minEndDate: $minEndDate){ + id + title + startDatetime + endDatetime + participants{ + clone{ + id + team{ + slug + } + bot{ + slug + } + } + } + } + }`, + }, + variables: { + variables: { maxStartDate: nowSeconds, minEndDate: twoWeeksAgoSeconds } + }, + headers: { + authorization: 'Bearer ' + accessToken + } + }) + + if (response.data.errors) { + console.log('Error getting events: ' + JSON.stringify(response.data.errors)) + throw 'Error getting events: ' + JSON.stringify(response.data.errors) + } else { + window.localStorage.setItem('currentEvents', JSON.stringify(response.data.data.events_Events)) + currentEvent = window.localStorage.getItem('currentEventObject') + if (currentEvent === null || currentEvent === '[]' || currentEvent === '') { + sharedStatus.currentEventIndex = -1 + } else { + currentEvent = JSON.parse(currentEvent) + sharedStatus.currentEventIndex = response.data.data.events_Events.findIndex(function (element) { + return element.id == currentEvent.id + }) + } + } + } + + async function getClones(accessToken) { + let response = await axios({ + url: window.canvasApp.graphQL.masterAppApiUrl, + method: 'post', + data: { + query: + `query Operations_Clones{ + operations_Clones { + id + authId + teamId + botId + mode + resumeExecution + beginDatetime + endDatetime + waitTime + state + stateDatetime + createDatetime + lastLogs + runAsTeam + summaryDate + buyAverage + sellAverage + marketRate + combinedProfitsA + combinedProfitsB + assetA + assetB + botType + teamName + botName + botAvatar + teamAvatar + processName + keyId + botSlug + } + } + ` + }, + headers: { + authorization: 'Bearer ' + accessToken + } + }) + + if (response.data.errors) { + console.log('Error getting clones: ' + JSON.stringify(response.data.errors)) + throw 'Error getting clones: ' + JSON.stringify(response.data.errors) + } else { + window.localStorage.setItem('userClones', JSON.stringify(response.data.data.operations_Clones)) + let clones = response.data.data.operations_Clones + for (let i = 0; i < clones.length; i++) { + let clone = clones[i] + if (clone.botType === 'Trading') { + let teamSlug = clone.teamName.toLowerCase() + teamSlug = teamSlug.replace(' ', '-') + let devTeam = ecosystem.getTeam(teamSlug) + let bot = ecosystem.getBot(devTeam, clone.botSlug) + if (bot !== undefined) { + bot.cloneId = clone.id + } + } + } + } + } + + function onClick() { } - function getContainer (point) { - let container - - /* First we check if this point is inside this object UI. */ - + function getContainer(point) { + /* First we check if this point is inside this object UI. */ if (thisObject.container.frame.isThisPointHere(point, true) === true) { return this.container } else { - /* This point does not belong to this space. */ - + /* This point does not belong to this space. */ return undefined } } - function draw () { + function draw() { return // nothing to show. - - thisObject.container.frame.draw(false, false) - - let fontSize = 12 - let label = currentLabel - if (label === undefined) { label = '' }; - - let point = { - x: thisObject.container.frame.width * 1 / 3, - y: (thisObject.container.frame.height / 2) + 4 - } - - point = thisObject.container.frame.frameThisPoint(point) - - browserCanvasContext.font = fontSize + 'px ' + UI_FONT.PRIMARY - browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.WHITE + ', 1)' - browserCanvasContext.fillText(label, point.x, point.y) } }