├── .gitignore ├── LICENSE ├── README.md ├── functions ├── realtimestats-deleteSyncMap.js └── realtimestats-updateQueueStatistics.js ├── package-lock.json ├── package.json ├── public ├── appConfig.example.js ├── index.html ├── plugins.json └── plugins.local.build.json ├── screenshots ├── stats-view.gif └── stats-view.png └── src ├── FlexRealtimeStatsDashboardPlugin.js ├── components └── RealTimeStats │ ├── CumulativeStatsCard │ ├── CumulativeStatsCard.js │ └── index.js │ ├── MainView │ ├── MainView.js │ └── index.js │ ├── QueueRow │ ├── QueueRow.js │ └── index.js │ └── RealTimeStatsCard │ ├── RealTimeStatsCard.js │ └── index.js ├── index.js └── notifications └── CustomNotifications.js /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | .DS_Store 8 | 9 | # Runtime data 10 | pids 11 | *.pid 12 | *.seed 13 | *.pid.lock 14 | 15 | # Directory for instrumented libs generated by jscoverage/JSCover 16 | lib-cov 17 | 18 | # Coverage directory used by tools like istanbul 19 | coverage 20 | 21 | # nyc test coverage 22 | .nyc_output 23 | 24 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 25 | .grunt 26 | 27 | # Bower dependency directory (https://bower.io/) 28 | bower_components 29 | 30 | # node-waf configuration 31 | .lock-wscript 32 | 33 | # Compiled binary addons (https://nodejs.org/api/addons.html) 34 | build/Release 35 | 36 | # Dependency directories 37 | node_modules/ 38 | jspm_packages/ 39 | 40 | # TypeScript v1 declaration files 41 | typings/ 42 | 43 | # Optional npm cache directory 44 | .npm 45 | 46 | # Optional eslint cache 47 | .eslintcache 48 | 49 | # Optional REPL history 50 | .node_repl_history 51 | 52 | # Output of 'npm pack' 53 | *.tgz 54 | 55 | # Yarn Integrity file 56 | .yarn-integrity 57 | 58 | # dotenv environment variables file 59 | .env 60 | 61 | # next.js build output 62 | .next 63 | 64 | # Flex related ignore 65 | appConfig.js 66 | build/ 67 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # plugin-flex-realtime-stats-dashboard 2 | 3 | This plugin is intended to demonstrate how a realtime dashboard might be setup using a backend service with websocket approach. The backend service can poll the statistics APIs and then clients can subscribe to the updates via a websocket managed by the backend. In a large system this could scale out using a persistence layer that stores the updates with multiple nodes providing access to websockets that retrieve from this persistence layer. 4 | 5 | The backend system is available [here](https://github.com/twilio-labs/twilio-flex-sample-backend) and can rapidly be deployed to Heroku using the link provided or setup locally with ngrok. 6 | 7 | It also supports toggling to a twilio functions and twilio sync "backend" instead of the websocket backend, but this is less scalable and doesn't support reliable continuous updates for task aging. At most it will support 20 queues with no channel specific data, or 5 queues with channel specific data for voice, chat, video and all channels (5x4=20). The limit is enforced by the concurrent updates that can be pushed to the sync service. 8 | 9 | # screenshot 10 | 11 | ![alt text](https://github.com/twilio-labs/plugin-flex-realtime-stats-dashboard/blob/master/screenshots/stats-view.gif) 12 | 13 | # use 14 | 15 | This plugin can be used with either 16 | (a) A custom backend solution written in node.js that supports a websocket with authentication - this design is suitable for production but relies on the provided backend being available 17 | 18 | (b) twilio functions and twilio sync - this has scalability limitations and without an external scheduler can't ensure changes to dashboard as tasks age - this is not suitable for production without an external scheduler instead of task router event call back 19 | 20 | # Setting up with a custom backend (recommended) 21 | 22 | 1. Create backend system by following the instructions provided [here](https://github.com/twilio-labs/twilio-flex-sample-backend/blob/master/README.md) 23 | 2. Create a clone of this repository and update 24 | - the line referencing the [backend](https://github.com/twilio-labs/plugin-flex-realtime-stats-dashboard/blob/eea37c0a838c5e0f60a20098cc67002b3b8444af/src/FlexRealtimeStatsDashboardPlugin.js#L13) 25 | 3. Run `npm install` 26 | 4. Create your own public/appConfig.js based on the public/appConfig.example.js and include your own account number 27 | 5. Run `npm start` 28 | 29 | # Setting up with Twilio Functions and Twilio Sync 30 | 31 | 1. Create a twilio function on your flex twilio account and name it realtimestats-updateQueueStatistics. Copy the contents of [this](https://github.com/twilio-labs/plugin-flex-realtime-stats-dashboard/blob/master/functions/realtimestats-updateQueueStatistics.js) function into it 32 | - Uncheck the box that says "Check for valid Twilio Signature" and save it. 33 | - You should now have a function path like https://\/realtimestats-updateQueueStatistics 34 | 2. Execute your function from the browser with the parameter checkMap=true 35 | e.g. https://\/realtimestats-updateQueueStatistics?checkMap=true 36 | - you can now optionally enable "check for valid twilio signature" again 37 | 3. Head to twilio/console -> task router -> select your flex workspace -> select settings 38 | - Under "EVENT CALLBACK URL" copy the path of your twilio function e.g. 39 | https://\/realtimestats-updateQueueStatistics 40 | - Select all call back events 41 | - Save 42 | 4. Create a clone of this repository and update the variable USE_TWILIO_FUNCTIONS to true, this is in FlexRealTimeStatsDashboardPlugin.js 43 | 5. Run `npm install` 44 | 6. Create your own public/appConfig.js based on the public/appConfig.example.js and include your own account number 45 | 7. Run `npm start` 46 | 47 | # change log 48 | 49 | v1.2 - updated to support optional use of twilio functions with sync map instead of a backend. 50 | 51 | v1.1 - updated to flexui 1.9.1, fixed bug where adding a queue caused a fatal error 52 | 53 | v1.0 - initial release with flex-ui 1.8.2 (material-ui v 1.5.2) 54 | 55 | ## Code of Conduct 56 | 57 | Please be aware that this project has a [Code of Conduct](https://github.com/twilio-labs/.github/blob/master/CODE_OF_CONDUCT.md). The tldr; is to just be excellent to each other ❤️ 58 | 59 | # TODOs 60 | -------------------------------------------------------------------------------- /functions/realtimestats-deleteSyncMap.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Written By: Jared Hunter 3 | * 4 | * This function was written as a convenience function for tidying up a sync map 5 | * e.g 6 | * https://domain-runtime/realtimestats-deleteSyncMap?syncMapName=queueStats 7 | * 8 | * DEPENDENCIES: After creating function ensure environment variable is added 9 | * TWILIO_FLEX_WORKSPACE_SID assign the value of your flex workspace 10 | * TWILIO_FLEX_SYNC_SID assign the value of the sync service to map stats 11 | */ 12 | 13 | exports.handler = function(context, event, callback) { 14 | const client = context.getTwilioClient(); 15 | const syncService = client.sync.services(context.TWILIO_FLEX_SYNC_SID); 16 | const response = new Twilio.Response(); 17 | var errorMessages; 18 | 19 | response.appendHeader("Access-Control-Allow-Origin", "*"); 20 | response.appendHeader("Access-Control-Allow-Methods", "OPTIONS POST"); 21 | response.appendHeader("Content-Type", "application/json"); 22 | response.appendHeader("Access-Control-Allow-Headers", "Content-Type"); 23 | 24 | const validateParameters = function(context, event) { 25 | errorMessages = ""; 26 | errorMessages += context.TWILIO_FLEX_WORKSPACE_SID 27 | ? "" 28 | : "Missing TWILIO_FLEX_WORKSPACE_SID from context environment variables, "; 29 | errorMessages += context.TWILIO_FLEX_SYNC_SID 30 | ? "" 31 | : "Missing TWILIO_FLEX_SYNC_SID from context environment variables"; 32 | errorMessages += event.syncMapName 33 | ? "" 34 | : "Missing parameter syncMapName: name of syncMap to delete"; 35 | 36 | if (errorMessages === "") { 37 | return true; 38 | } else { 39 | return false; 40 | } 41 | }; 42 | 43 | //log function parameters 44 | const entries = Object.entries(event); 45 | 46 | for (const [field, value] of entries) { 47 | console.log(`${field}, ${value}`); 48 | } 49 | 50 | if (validateParameters(context, event)) { 51 | syncService 52 | .syncMaps(event.syncMapName) 53 | .remove() 54 | .then(map => { 55 | console.log("Succesfully deleted map: " + event.syncMapName); 56 | response.setBody({ success: true }); 57 | callback(null, response); 58 | }) 59 | .catch(error => { 60 | console.log("error deleting map: " + event.syncMapName); 61 | response.setBody(error); 62 | callback(null, response); 63 | }); 64 | } else { 65 | callback(null, { success: false, message: errorMessages }); 66 | } 67 | }; 68 | -------------------------------------------------------------------------------- /functions/realtimestats-updateQueueStatistics.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Written By: Jared Hunter 3 | * 4 | * This function was written to list all queue stats for a flex workspace 5 | * and push them to a sync map 6 | * 7 | * on first run execute function with parameter checkMap=true e.g. 8 | * 9 | * https:///realtimestats-updateQueueStatistics?checkMap=true 10 | * 11 | * DEPENDENCIES: After creating function ensure environment variable is added 12 | * TWILIO_FLEX_WORKSPACE_SID assign the value of your flex workspace 13 | * TWILIO_FLEX_SYNC_SID assign the value of the sync service to map stats 14 | */ 15 | 16 | exports.handler = function(context, event, callback) { 17 | const client = context.getTwilioClient(); 18 | const syncService = client.sync.services(context.TWILIO_FLEX_SYNC_SID); 19 | const response = new Twilio.Response(); 20 | const MAP_NAME = "queueStats"; 21 | var errorMessages; 22 | 23 | response.appendHeader("Access-Control-Allow-Origin", "*"); 24 | response.appendHeader("Access-Control-Allow-Methods", "OPTIONS POST"); 25 | response.appendHeader("Content-Type", "application/json"); 26 | response.appendHeader("Access-Control-Allow-Headers", "Content-Type"); 27 | 28 | const validateParameters = function(context, event) { 29 | errorMessages = ""; 30 | errorMessages += context.TWILIO_FLEX_WORKSPACE_SID 31 | ? "" 32 | : "Missing TWILIO_FLEX_WORKSPACE_SID from context environment variables, "; 33 | errorMessages += context.TWILIO_FLEX_SYNC_SID 34 | ? "" 35 | : "Missing TWILIO_FLEX_SYNC_SID from context environment variables"; 36 | 37 | if (errorMessages === "") { 38 | return true; 39 | } else { 40 | return false; 41 | } 42 | }; 43 | 44 | const ensureSyncMapExists = function() { 45 | return new Promise(function(resolve, reject) { 46 | if (event.checkMap == "true") { 47 | syncService 48 | .syncMaps(MAP_NAME) 49 | .fetch() 50 | .then(() => { 51 | console.log("sync map existence confirmed"), resolve(); 52 | }) 53 | .catch(err => { 54 | console.log(err.message); 55 | console.log("creating sync map %s", MAP_NAME); 56 | syncService.syncMaps 57 | .create({ uniqueName: MAP_NAME }) 58 | .then(sync_map => { 59 | console.log("sync map crated: " + sync_map.sid); 60 | resolve(); 61 | }) 62 | .catch(err => { 63 | console.log(err.message); 64 | resolve(); 65 | }); 66 | }); 67 | } else { 68 | console.log("skipped check map"); 69 | resolve(); 70 | } 71 | }); 72 | }; 73 | 74 | function listQueues(twilioClient) { 75 | return new Promise(function(resolve, reject) { 76 | twilioClient.taskrouter 77 | .workspaces(process.env.TWILIO_FLEX_WORKSPACE_SID) 78 | .taskQueues.list() 79 | .then(result => { 80 | var queueArray = []; 81 | result.forEach(arrayItem => { 82 | queueArray.push({ 83 | sid: arrayItem.sid, 84 | friendlyName: arrayItem.friendlyName 85 | }); 86 | }); 87 | resolve({ success: true, queueArray: queueArray }); 88 | }) 89 | .catch(err => { 90 | console.log("err message: ", err.message); 91 | resolve({ success: false, message: err.message }); 92 | }); 93 | }); 94 | } 95 | 96 | function populateRealTimeStatsForQueueItem( 97 | twilioClient, 98 | queueItem, 99 | taskChannel 100 | ) { 101 | return new Promise(function(resolve, reject) { 102 | twilioClient.taskrouter 103 | .workspaces(process.env.TWILIO_FLEX_WORKSPACE_SID) 104 | .taskQueues(queueItem.sid) 105 | .realTimeStatistics() 106 | .fetch({ taskChannel: taskChannel ? taskChannel : undefined }) 107 | .then(result => { 108 | taskChannel = !taskChannel ? "all" : taskChannel; 109 | var realTimeStats = minimizeRealTimeStats(result); 110 | queueItem["realTimeStats_" + taskChannel] = realTimeStats; 111 | resolve(queueItem); 112 | }) 113 | .catch(err => { 114 | queueItem.realTimeStatsMessage = err.message; 115 | resolve(queueItem); 116 | }); 117 | }); 118 | } 119 | 120 | function populateCumulativeStatsForQueueItem( 121 | twilioClient, 122 | queueItem, 123 | taskChannel 124 | ) { 125 | var todaysDate = new Date(); 126 | todaysDate.setHours(0, 0, 0, 0); 127 | return new Promise(function(resolve, reject) { 128 | twilioClient.taskrouter 129 | .workspaces(process.env.TWILIO_FLEX_WORKSPACE_SID) 130 | .taskQueues(queueItem.sid) 131 | .cumulativeStatistics() 132 | .fetch({ 133 | taskChannel: taskChannel ? taskChannel : undefined, 134 | startDate: todaysDate, 135 | splitByWaitTime: "30,60,120" 136 | }) 137 | .then(result => { 138 | taskChannel = !taskChannel ? "all" : taskChannel; 139 | queueItem["cumulativeStats_" + taskChannel] = minimizeCumulativeStats( 140 | result 141 | ); 142 | resolve(queueItem); 143 | }) 144 | .catch(err => { 145 | queueItem.cumulativeStatsMessage = err.message; 146 | resolve(queueItem); 147 | }); 148 | }); 149 | } 150 | 151 | function minimizeRealTimeStats(realTimeStats) { 152 | if (realTimeStats) { 153 | var result = {}; 154 | result.activityStatistics = []; 155 | 156 | realTimeStats.activityStatistics.forEach(activity => { 157 | result.activityStatistics.push({ 158 | friendly_name: activity.friendly_name, 159 | workers: activity.workers 160 | }); 161 | }); 162 | 163 | result.oldestTask = realTimeStats.longestTaskWaitingAge; 164 | result.tasksByPriority = realTimeStats.tasksByPriority; 165 | result.tasksByStatus = realTimeStats.tasksByStatus; 166 | result.availableWorkers = realTimeStats.totalAvailableWorkers; 167 | result.eligibleWorkers = realTimeStats.totalEligibleWorkers; 168 | result.totalTasks = realTimeStats.totalTasks; 169 | 170 | return result; 171 | } else { 172 | return null; 173 | } 174 | } 175 | 176 | function minimizeCumulativeStats(cumulativeStatistics) { 177 | if (cumulativeStatistics) { 178 | var minimizedCumulativeStats = { 179 | rCreated: cumulativeStatistics.reservationsCreated, 180 | rRej: cumulativeStatistics.reservationsRejected, 181 | rAccepted: cumulativeStatistics.reservationsAccepted, 182 | rTimedOut: cumulativeStatistics.reservationsTimedOut, 183 | rCancel: cumulativeStatistics.reservationsCanceled, 184 | rRescind: cumulativeStatistics.reservationsRescinded, 185 | 186 | tCompl: cumulativeStatistics.tasksCompleted, 187 | tMoved: cumulativeStatistics.tasksMoved, 188 | tEnter: cumulativeStatistics.tasksEntered, 189 | tCanc: cumulativeStatistics.tasksCanceled, 190 | tDel: cumulativeStatistics.tasksDeleted, 191 | 192 | waitUntilCancel: cumulativeStatistics.waitDurationUntilCanceled, 193 | waitUntilAccept: cumulativeStatistics.waitDurationUntilAccepted, 194 | splitByWaitTime: cumulativeStatistics.splitByWaitTime, 195 | 196 | endTime: cumulativeStatistics.endTime, 197 | startTime: cumulativeStatistics.startTime, 198 | 199 | avgTaskAcceptanceTime: cumulativeStatistics.avgTaskAcceptanceTime 200 | }; 201 | 202 | return minimizedCumulativeStats; 203 | } else { 204 | return null; 205 | } 206 | } 207 | 208 | const updateSyncMapItem = function(queueItem) { 209 | return new Promise(function(resolve, reject) { 210 | syncService 211 | .syncMaps(MAP_NAME) 212 | .syncMapItems(queueItem.sid) 213 | .update({ data: queueItem }) 214 | .then(item => { 215 | //console.log("Item updated: " + queueItem.sid); 216 | resolve(); 217 | }) 218 | .catch(err => { 219 | console.log("retrying as create item"); 220 | 221 | //retry the item as a create 222 | syncService 223 | .syncMaps(MAP_NAME) 224 | .syncMapItems.create({ 225 | key: queueItem.sid, 226 | data: queueItem 227 | }) 228 | .then(item => { 229 | console.log("Item created " + queueItem.sid); 230 | resolve(); 231 | }) 232 | .catch(err => { 233 | console.log(err.message); 234 | resolve(); 235 | }); 236 | }); 237 | }); 238 | }; 239 | 240 | function fetchAllQueueStatistics(twilioClient) { 241 | // retrieves all queues for the environment configured workspace 242 | // then proceeds to fetch all stats data for them 243 | // returns an array of queue objects populated with the relevant stats nested on 244 | // the object 245 | return new Promise(function(resolve, reject) { 246 | listQueues(twilioClient).then(result => { 247 | if (result.success) { 248 | var queueResultsArray = result.queueArray; 249 | var getStatsPromiseArray = []; 250 | queueResultsArray.forEach(queueItem => { 251 | // Every cycle retreive realtime stats for all known channels 252 | // comment out the channel if it is not used, 253 | // to save on redundent calls to backend 254 | getStatsPromiseArray.push( 255 | populateRealTimeStatsForQueueItem(twilioClient, queueItem, null) 256 | ); 257 | 258 | //get stats filtered by channel 259 | getStatsPromiseArray.push( 260 | populateRealTimeStatsForQueueItem( 261 | twilioClient, 262 | queueItem, 263 | "voice" 264 | ) 265 | ); 266 | getStatsPromiseArray.push( 267 | populateRealTimeStatsForQueueItem(twilioClient, queueItem, "chat") 268 | ); 269 | getStatsPromiseArray.push( 270 | populateRealTimeStatsForQueueItem( 271 | twilioClient, 272 | queueItem, 273 | "video" 274 | ) 275 | ); 276 | 277 | //Now get cumulative stats for each queue, broken down by channel 278 | getStatsPromiseArray.push( 279 | populateCumulativeStatsForQueueItem(twilioClient, queueItem, null) 280 | ); 281 | 282 | getStatsPromiseArray.push( 283 | populateCumulativeStatsForQueueItem( 284 | twilioClient, 285 | queueItem, 286 | "voice" 287 | ) 288 | ); 289 | 290 | getStatsPromiseArray.push( 291 | populateCumulativeStatsForQueueItem( 292 | twilioClient, 293 | queueItem, 294 | "chat" 295 | ) 296 | ); 297 | 298 | getStatsPromiseArray.push( 299 | populateCumulativeStatsForQueueItem( 300 | twilioClient, 301 | queueItem, 302 | "video" 303 | ) 304 | ); 305 | }); 306 | 307 | Promise.all(getStatsPromiseArray).then(values => { 308 | // execute all calls for stats in parallel 309 | resolve(queueResultsArray); 310 | }); 311 | } 312 | }); 313 | }); 314 | } 315 | 316 | if (validateParameters(context, event)) { 317 | ensureSyncMapExists().then(() => { 318 | fetchAllQueueStatistics(client).then(queueStatsArray => { 319 | var updateSyncMapPromiseArray = []; 320 | queueStatsArray.forEach(queueItem => { 321 | updateSyncMapPromiseArray.push(updateSyncMapItem(queueItem)); 322 | }); 323 | 324 | Promise.all(updateSyncMapPromiseArray).then(values => { 325 | response.setBody(queueStatsArray); 326 | callback(null, response); 327 | }); 328 | }); 329 | }); 330 | } else { 331 | callback(null, { success: false, message: errorMessages }); 332 | } 333 | }; 334 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "plugin-flex-realtime-stats-dashboard", 3 | "description": "Example front end implementation of real time dashboard that recieves data from a websocket", 4 | "version": "1.2.0", 5 | "author": "Jared Hunter ", 6 | "private": true, 7 | "scripts": { 8 | "postinstall": "flex-check-start", 9 | "prestart": "flex-check-start", 10 | "start": "react-app-rewired start", 11 | "build": "react-app-rewired build", 12 | "test": "react-app-rewired test --env=jsdom", 13 | "eject": "react-app-rewired eject" 14 | }, 15 | "devDependencies": { 16 | "@twilio/flex-ui": "^1.9.1", 17 | "react-app-rewire-flex-plugin": "^1", 18 | "react-app-rewired": "^1.6.2" 19 | }, 20 | "dependencies": { 21 | "flex-plugin": "1.3.4", 22 | "prop-types": "^15.7.2", 23 | "react": "16.5.2", 24 | "react-dom": "16.5.2", 25 | "react-scripts": "1.1.5", 26 | "react-table": "^6.10.0" 27 | }, 28 | "config-overrides-path": "node_modules/react-app-rewire-flex-plugin" 29 | } 30 | -------------------------------------------------------------------------------- /public/appConfig.example.js: -------------------------------------------------------------------------------- 1 | // your account sid 2 | var accountSid = 'accountSid'; 3 | 4 | // set to /plugins.json for local dev 5 | // set to /plugins.local.build.json for testing your build 6 | // set to "" for the default live plugin loader 7 | var pluginServiceUrl = '/plugins.json'; 8 | 9 | var appConfig = { 10 | pluginService: { 11 | enabled: true, 12 | url: pluginServiceUrl, 13 | }, 14 | sso: { 15 | accountSid: accountSid 16 | }, 17 | ytica: false, 18 | logLevel: 'info', 19 | showSupervisorDesktopView: true, 20 | }; 21 | -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | Twilio Flex 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /public/plugins.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "name": "FlexRealtimeStatsDashboardPlugin", 4 | "version": "0.0.0", 5 | "class": "FlexRealtimeStatsDashboardPlugin", 6 | "requires": [ 7 | { 8 | "@twilio/flex-ui": "^1" 9 | } 10 | ], 11 | "src": "http://localhost:8080/plugin-flex-realtime-stats-dashboard.js" 12 | } 13 | ] 14 | -------------------------------------------------------------------------------- /public/plugins.local.build.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "name": "FlexRealtimeStatsDashboardPlugin", 4 | "version": "0.0.0", 5 | "class": "FlexRealtimeStatsDashboardPlugin", 6 | "requires": [ 7 | { 8 | "@twilio/flex-ui": "^1" 9 | } 10 | ], 11 | "src": "http://127.0.0.1:8085" 12 | } 13 | ] 14 | -------------------------------------------------------------------------------- /screenshots/stats-view.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/twilio-labs/plugin-flex-realtime-stats-dashboard/893c030377e8efa45ed1bd306b1955afdf6ce449/screenshots/stats-view.gif -------------------------------------------------------------------------------- /screenshots/stats-view.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/twilio-labs/plugin-flex-realtime-stats-dashboard/893c030377e8efa45ed1bd306b1955afdf6ce449/screenshots/stats-view.png -------------------------------------------------------------------------------- /src/FlexRealtimeStatsDashboardPlugin.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { FlexPlugin } from "flex-plugin"; 3 | import { SideLink, Actions } from "@twilio/flex-ui"; 4 | import { MainView } from "./components/RealTimeStats/MainView"; 5 | 6 | import "./notifications/CustomNotifications"; 7 | 8 | const PLUGIN_NAME = "FlexRealtimeStatsDashboardPlugin"; 9 | const USE_TWILIO_FUNCTIONS = false; 10 | const QUEUE_STATS_SYNC_MAP_NAME = "queueStats"; 11 | 12 | export default class FlexRealtimeStatsDashboardPlugin extends FlexPlugin { 13 | constructor() { 14 | super(PLUGIN_NAME); 15 | this.backendHostname = "twilio-flex-sample-backend.herokuapp.com"; 16 | } 17 | 18 | /** 19 | * This code is run when your plugin is being started 20 | * Use this to modify any UI components or attach to the actions framework 21 | * 22 | * @param flex { typeof import('@twilio/flex-ui') } 23 | * @param manager { import('@twilio/flex-ui').Manager } 24 | */ 25 | init(flex, manager) { 26 | flex.ViewCollection.Content.add( 27 | 28 | 34 | 35 | ); 36 | 37 | flex.SideNav.Content.add( 38 | 42 | Actions.invokeAction("NavigateToView", { 43 | viewName: "RealTimeStatsView" 44 | }) 45 | } 46 | > 47 | Real Time Queue Stats 48 | 49 | ); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/components/RealTimeStats/CumulativeStatsCard/CumulativeStatsCard.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import PropTypes from "prop-types"; 3 | 4 | import CardContent from "@material-ui/core/CardContent"; 5 | import Typography from "@material-ui/core/Typography"; 6 | 7 | export class CumulativeStatsCard extends React.PureComponent { 8 | static propTypes = { 9 | avgTaskAcceptanceTime: PropTypes.number.isRequired, 10 | waitUntilCancel: PropTypes.shape({ 11 | avg: PropTypes.number.isRequired 12 | }).isRequired, 13 | splitByWaitTime: PropTypes.objectOf( 14 | PropTypes.shape({ 15 | above: PropTypes.shape({ 16 | reservations_accepted: PropTypes.number.isRequired, 17 | tasks_canceled: PropTypes.number.isRequired 18 | }), 19 | below: PropTypes.shape({ 20 | reservations_accepted: PropTypes.number.isRequired, 21 | tasks_canceled: PropTypes.number.isRequired 22 | }) 23 | }) 24 | ).isRequired, 25 | tEnter: PropTypes.number.isRequired, 26 | tCompl: PropTypes.number.isRequired, 27 | tCanc: PropTypes.number.isRequired, 28 | tMoved: PropTypes.number.isRequired, 29 | classes: PropTypes.object.isRequired 30 | }; 31 | 32 | render() { 33 | const { 34 | classes, 35 | splitByWaitTime, 36 | avgTaskAcceptanceTime, 37 | waitUntilCancel, 38 | tEnter, 39 | tCompl, 40 | tCanc, 41 | tMoved 42 | } = this.props; 43 | 44 | let measuredTime = new Date(null); 45 | measuredTime.setSeconds(avgTaskAcceptanceTime); 46 | const averageAcceptTime = measuredTime.toISOString().substr(11, 8); 47 | 48 | measuredTime = new Date(null); 49 | measuredTime.setSeconds(waitUntilCancel.avg); 50 | const averageCancelTime = measuredTime.toISOString().substr(11, 8); 51 | 52 | // setup a more dynamically usable splitbywaittime 53 | // percentage is calls Acceptedbelow / ( CallsAccepted(below + above) + CallsAbandoned Above threshold) 54 | const splitByWait = Object.keys(splitByWaitTime).map(threshold => { 55 | const value = splitByWaitTime[threshold]; 56 | const { above, below } = value; 57 | const totalAccepted = 58 | above.reservations_accepted + 59 | below.reservations_accepted + 60 | above.tasks_canceled; 61 | 62 | return { 63 | threshold, 64 | value, 65 | acceptedPercentage: 66 | totalAccepted > 0 67 | ? `${Math.round( 68 | (value.below.reservations_accepted / totalAccepted) * 100 69 | )}%` 70 | : "-" 71 | }; 72 | }); 73 | 74 | return ( 75 | 76 |
77 |
78 |
79 |
80 | CREATED : 81 | COMPLETED: 82 | ABANDONED: 83 | MOVED : 84 |
85 |
86 | {tEnter} 87 | {tCompl} 88 | {tCanc} 89 | {tMoved} 90 |
91 |
92 |
93 |
94 | AVG ACCEPT 95 | 96 | {averageAcceptTime} 97 | 98 | AVG ABANDON 99 | 100 | {averageCancelTime} 101 | 102 |
103 |
104 | SLA 105 |
106 | {splitByWait.map((item, index) => ( 107 | 108 | {item.threshold} sec{" "} 109 | 110 | ))} 111 |
112 |
113 | {splitByWait.map((item, index) => ( 114 | 115 | {item.acceptedPercentage} 116 | 117 | ))} 118 |
119 |
120 |
121 |
122 | ); 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /src/components/RealTimeStats/CumulativeStatsCard/index.js: -------------------------------------------------------------------------------- 1 | export { CumulativeStatsCard } from "./CumulativeStatsCard"; -------------------------------------------------------------------------------- /src/components/RealTimeStats/MainView/MainView.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import PropTypes from "prop-types"; 3 | import { withStyles } from "@material-ui/core/styles"; 4 | 5 | import Table from "@material-ui/core/Table"; 6 | import TableBody from "@material-ui/core/TableBody"; 7 | import TableCell from "@material-ui/core/TableCell"; 8 | import TableHead from "@material-ui/core/TableHead"; 9 | import TableRow from "@material-ui/core/TableRow"; 10 | import Paper from "@material-ui/core/Paper"; 11 | 12 | import { Notifications, Manager } from "@twilio/flex-ui"; 13 | import { SyncClient } from "twilio-sync"; 14 | import { QueueRow } from "../QueueRow"; 15 | 16 | const styles = theme => ({ 17 | //table 18 | tableroot: { 19 | width: "100%", 20 | margin: theme.spacing.unit * 1, 21 | overflowX: "auto" 22 | }, 23 | tableCellHeader: { 24 | backgroundColor: theme.colors.base9, 25 | color: theme.colors.base1, 26 | variant: "head", 27 | border: "1px solid " + theme.colors.base1, 28 | position: "sticky", 29 | top: 0, 30 | paddingTop: "12px", 31 | paddingBottom: "12px" 32 | }, 33 | table: { 34 | minWidth: 1050 35 | }, 36 | tableCell: { 37 | border: "1px solid " + theme.colors.base6, 38 | color: "inherit" 39 | }, 40 | tableRow: { 41 | minHeight: "124px", 42 | cursor: "pointer", 43 | transition: "background-color 0.1s", 44 | "&:hover": { 45 | backgroundColor: theme.colors.base4, 46 | color: theme.colors.base10 47 | } 48 | }, 49 | tableRowChannel: { 50 | minHeight: "100px", 51 | cursor: "default", 52 | transition: "background-color 0.1s", 53 | "&:hover": { 54 | backgroundColor: theme.colors.base4, 55 | color: theme.colors.base10 56 | } 57 | }, 58 | //rts 59 | cardrow: { 60 | minWidth: "145px", 61 | display: "flex", 62 | justifyContent: "space-between" 63 | }, 64 | cardcolumn: { 65 | marginRight: "8px", 66 | marginLeft: "8px", 67 | flexDirection: "column" 68 | } 69 | }); 70 | 71 | export class MainViewImpl extends React.Component { 72 | static propTypes = { 73 | classes: PropTypes.object.isRequired 74 | }; 75 | 76 | state = { 77 | websocketStatus: "closed", 78 | queueStats: [] 79 | }; 80 | retryInterval; 81 | /** @type WebSocket */ 82 | webSocket = null; 83 | rowsExpandedMap = new Map(); 84 | 85 | componentDidMount() { 86 | const { useTwilioFunctions, queueStatsSyncMapName } = this.props; 87 | if (useTwilioFunctions) { 88 | console.log("mounting realtimeStats with twilio sync"); 89 | this.initSyncMapClient(queueStatsSyncMapName); 90 | } else { 91 | console.log("mounting realtimeStats with websocket"); 92 | this.initWebSocket(); 93 | this.retryInterval = setInterval(() => { 94 | if ( 95 | this.webSocket && 96 | this.webSocket.readyState === this.webSocket.CLOSED 97 | ) { 98 | this.initWebSocket(); 99 | } 100 | }, 10000); 101 | } 102 | } 103 | 104 | componentWillUnmount() { 105 | const { useTwilioFunctions } = this.props; 106 | if (useTwilioFunctions) { 107 | this.syncClient = null; 108 | } else { 109 | this.webSocket.close(); 110 | clearTimeout(this.retryInterval); 111 | } 112 | } 113 | 114 | initWebSocket() { 115 | const { backendHostname } = this.props; 116 | 117 | this.webSocket = new WebSocket( 118 | "wss://" + backendHostname + "/websocket/realtimeStats", 119 | Manager.getInstance().user.token 120 | ); 121 | 122 | this.webSocket.onerror = function() { 123 | Notifications.showNotification("WebsocketError", { 124 | url: backendHostname 125 | }); 126 | }; 127 | 128 | this.webSocket.onopen = function() { 129 | this.setState({ websocketStatus: "open" }); 130 | }.bind(this); 131 | 132 | this.webSocket.onclose = function() { 133 | this.setState({ websocketStatus: "closed" }); 134 | }.bind(this); 135 | 136 | this.webSocket.onmessage = function(message) { 137 | try { 138 | const data = JSON.parse(message.data); 139 | this.setState({ 140 | queueStats: data 141 | }); 142 | } catch (error) { 143 | console.log(error); 144 | console.warn("Unrecognized payload: ", message.data); 145 | } 146 | }.bind(this); 147 | } 148 | 149 | syncMapPageHandler(paginator) { 150 | paginator.items.forEach(item => { 151 | this.syncMapHandleItemUpdate(item); 152 | }); 153 | return paginator.hasNextPage 154 | ? paginator.nextPage().then(this.syncMapPageHandler) 155 | : null; 156 | } 157 | 158 | syncMapHandleItemUpdate(mapItem) { 159 | var dataMap = this.state.queueStats; 160 | var updated = false; 161 | console.log("DATAMAP", dataMap); 162 | console.log("mapItem", mapItem); 163 | dataMap.forEach((item, index) => { 164 | if (item.sid === mapItem.value.sid) { 165 | dataMap[index] = mapItem.value; 166 | updated = true; 167 | } 168 | }); 169 | if (!updated) { 170 | dataMap.push(mapItem.value); 171 | } 172 | 173 | this.setState({ queueStats: dataMap }); 174 | } 175 | 176 | initSyncMapClient(queueStatsSyncMapName) { 177 | // create syncClient on component mount 178 | this.syncClient = new SyncClient(Manager.getInstance().user.token); 179 | 180 | // fetch initial data map 181 | this.syncClient 182 | .map(queueStatsSyncMapName) 183 | .then(map => { 184 | map 185 | .getItems() 186 | .then(paginator => { 187 | this.syncMapPageHandler(paginator); 188 | }) 189 | .catch(function(error) { 190 | console.error("Map getItems() failed", error); 191 | }); 192 | }) 193 | .catch(function(error) { 194 | Notifications.showNotification("SyncMapNotAvailable", { 195 | message: queueStatsSyncMapName 196 | }); 197 | }); 198 | 199 | // Add listener for future updates to existing items 200 | this.syncClient.map(queueStatsSyncMapName).then(map => { 201 | map.on("itemUpdated", args => { 202 | this.syncMapHandleItemUpdate(args.item); 203 | }); 204 | }); 205 | 206 | // Add listener for future additions to map 207 | this.syncClient.map(queueStatsSyncMapName).then(map => { 208 | map.on("itemAdded", args => { 209 | this.syncMapHandleItemUpdate(args.item); 210 | }); 211 | }); 212 | 213 | //TODO : add listener for removal of queue 214 | // need to handle removal from the sync map in the function first 215 | } 216 | 217 | handleRowClick = queueItem => { 218 | const expanded = this.rowsExpandedMap.get(queueItem.sid); 219 | 220 | if (expanded) { 221 | this.rowsExpandedMap.set(queueItem.sid, false); 222 | } else { 223 | this.rowsExpandedMap.set(queueItem.sid, true); 224 | } 225 | 226 | this.forceUpdate(); 227 | }; 228 | 229 | render() { 230 | const { classes } = this.props; 231 | return ( 232 | 233 | 234 | 235 | 236 | 237 | Queue Name 238 | 239 | 244 | Tasks (In Queue) 245 | 246 | 251 | Tasks (Today) 252 | 253 | 258 | Agents 259 | 260 | 261 | 262 | {this.renderChannelRows()} 263 |
264 |
265 | ); 266 | } 267 | 268 | renderChannelRows() { 269 | const { classes } = this.props; 270 | return this.state.queueStats.map(queueItem => { 271 | const sharedProps = { 272 | queueItem, 273 | classes, 274 | handleClick: this.handleRowClick 275 | }; 276 | const tableArray = []; 277 | if (this.rowsExpandedMap.get(queueItem.sid)) { 278 | tableArray.push( 279 | , 280 | , 281 | 282 | ); 283 | } 284 | return tableArray; 285 | }); 286 | } 287 | } 288 | 289 | export const MainView = withStyles(styles)(MainViewImpl); 290 | -------------------------------------------------------------------------------- /src/components/RealTimeStats/MainView/index.js: -------------------------------------------------------------------------------- 1 | export { MainView } from "./MainView" -------------------------------------------------------------------------------- /src/components/RealTimeStats/QueueRow/QueueRow.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import PropTypes from "prop-types"; 3 | 4 | import CardContent from "@material-ui/core/CardContent"; 5 | import Typography from "@material-ui/core/Typography"; 6 | import TableCell from "@material-ui/core/TableCell"; 7 | import TableRow from "@material-ui/core/TableRow"; 8 | import { RealTimeStatsCard } from "../RealTimeStatsCard"; 9 | import { CumulativeStatsCard } from "../CumulativeStatsCard"; 10 | 11 | export class QueueRow extends React.PureComponent { 12 | static propTypes = { 13 | queueItem: PropTypes.object.isRequired, 14 | classes: PropTypes.object.isRequired, 15 | channel: PropTypes.string.isRequired, 16 | handleClick: PropTypes.func.isRequired, 17 | index: PropTypes.number.isRequired 18 | }; 19 | render() { 20 | const { classes, queueItem, channel, index, handleClick } = this.props; 21 | 22 | const clickCallback = () => handleClick(queueItem, index); 23 | 24 | if (queueItem.sid) { 25 | const realTimeStats = queueItem["realTimeStats_" + channel]; 26 | const cumulativeStats = queueItem["cumulativeStats_" + channel]; 27 | const activities = realTimeStats.activityStatistics.reduce( 28 | (acc, activity) => { 29 | acc[activity.friendly_name] = activity.workers; 30 | return acc; 31 | }, 32 | {} 33 | ); 34 | 35 | return ( 36 | 42 | 43 | {channel === "all" ? ( 44 | 45 | 46 | {queueItem.friendlyName} 47 | 48 | 49 | ) : ( 50 | 51 | 57 | {" "} 58 | - {channel} 59 | 60 | 61 | )} 62 | 63 | 64 | 65 | 66 | 67 | {cumulativeStats ? ( 68 | 69 | ) : ( 70 | 71 |
72 | NO DATA 73 |
74 |
75 | )} 76 |
77 | 78 | 79 |
80 |
81 | {Object.keys(activities).map(key => ( 82 | 83 | {key.toUpperCase()} : 84 | 85 | ))} 86 | ELIGIBLE: 87 |
88 |
89 | {Object.values(activities).map(value => ( 90 | {value} 91 | ))} 92 | 93 | {queueItem["realTimeStats_" + channel].eligibleWorkers} 94 | 95 |
96 |
97 |
98 |
99 |
100 | ); 101 | } else { 102 | return ( 103 | 104 | 105 | Loading .... 106 | 107 | 108 | ); 109 | } 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /src/components/RealTimeStats/QueueRow/index.js: -------------------------------------------------------------------------------- 1 | export { QueueRow } from "./QueueRow"; 2 | -------------------------------------------------------------------------------- /src/components/RealTimeStats/RealTimeStatsCard/RealTimeStatsCard.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import PropTypes from "prop-types"; 3 | 4 | import CardContent from "@material-ui/core/CardContent"; 5 | import Typography from "@material-ui/core/Typography"; 6 | 7 | export class RealTimeStatsCard extends React.PureComponent { 8 | static propTypes = { 9 | tasksByStatus: PropTypes.shape({ 10 | pending: PropTypes.number.isRequired, 11 | assigned: PropTypes.number.isRequired, 12 | reserved: PropTypes.number.isRequired, 13 | wrapping: PropTypes.number.isRequired 14 | }).isRequired, 15 | oldestTask: PropTypes.number.isRequired, 16 | classes: PropTypes.object.isRequired 17 | }; 18 | 19 | render() { 20 | const { classes, tasksByStatus, oldestTask } = this.props; 21 | 22 | // total tasks needs to be calculated because the total tasks returned 23 | // from the API includes tasks the have been cancelled / abanonded and 24 | // sit around for 5 minutes before being cleared up 25 | const totalTasks = 26 | tasksByStatus.pending + 27 | tasksByStatus.assigned + 28 | tasksByStatus.reserved + 29 | tasksByStatus.wrapping; 30 | 31 | return ( 32 | 33 |
34 |
35 |
36 |
37 | PENDING : 38 | ASSIGNED: 39 | RESERVED: 40 | WRAPPING: 41 |
42 |
43 | {tasksByStatus.pending} 44 | 45 | {tasksByStatus.assigned} 46 | 47 | 48 | {tasksByStatus.reserved} 49 | 50 | 51 | {tasksByStatus.wrapping} 52 | 53 |
54 |
55 |
56 |
57 | TOTAL 58 | 59 | {totalTasks} 60 | 61 | OLDEST 62 | 63 | {oldestTask} 64 | 65 |
66 |
67 |
68 | ); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/components/RealTimeStats/RealTimeStatsCard/index.js: -------------------------------------------------------------------------------- 1 | export { RealTimeStatsCard } from "./RealTimeStatsCard"; -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import * as FlexPlugin from 'flex-plugin'; 2 | import FlexRealtimeStatsDashboardPlugin from './FlexRealtimeStatsDashboardPlugin'; 3 | 4 | FlexPlugin.loadPlugin(FlexRealtimeStatsDashboardPlugin); 5 | -------------------------------------------------------------------------------- /src/notifications/CustomNotifications.js: -------------------------------------------------------------------------------- 1 | import { Notifications, NotificationType, Manager } from "@twilio/flex-ui"; 2 | 3 | const manager = Manager.getInstance(); 4 | 5 | // To avoid collision with other plugin using same notification 6 | if (!manager.strings.websocketError) { 7 | manager.strings.websocketError = 8 | "Unable to open websocket to backend: {{url}}"; 9 | Notifications.registerNotification({ 10 | id: "WebsocketError", 11 | content: "websocketError", 12 | type: NotificationType.error 13 | }); 14 | } 15 | 16 | if (!manager.strings.backendError) { 17 | manager.strings.backendError = "Could not complete operation: {{message}}"; 18 | 19 | Notifications.registerNotification({ 20 | id: "BackendError", 21 | content: "backendError", 22 | type: NotificationType.error 23 | }); 24 | } 25 | 26 | if (!manager.strings.syncMapNotAvailable) { 27 | manager.strings.syncMapNotAvailable = "Could not find sync map: {{message}}"; 28 | 29 | Notifications.registerNotification({ 30 | id: "SyncMapNotAvailable", 31 | content: "syncMapNotAvailable", 32 | type: NotificationType.error 33 | }); 34 | } 35 | --------------------------------------------------------------------------------