Anywhere365 script include
Wed Dec 01 2021 08:40:35 GMT+0000 (Coordinated Universal Time)
Saved by @mathiasVDD #javascript
var AnywhereCTIService = Class.create(); AnywhereCTIService.prototype = { // This is just for the developers reference, not used in the code BODY_EXAMPLE: { 'callerNumber': '+12345678901', 'agentSip': 'test@example.com' }, // List of properties that should be present in the request body MANDATORY_BODY_PROPERTIES: ['callerNumber', 'agentSip'], INTERATCION_FIELDS_DEFAULTS: { 'state': 'work_in_progress', 'type': 'phone', 'short_description': 'Received a call', }, // Fields that should be included in the response INTERACTION_FIELDS_RESPONSE: [ 'sys_id', 'number', 'short_description', 'account', 'contact', 'consumer', 'assigned_to', ], // Fields that should have their display value included in the response INTERACTION_FIELDS_DISPLAY_RESPONSE: [ 'account', 'contact', 'consumer', 'assigned_to', ], // Fields that should have their display value included in the response INTERACTION_DEPARTMENT: { 'C_Open_Fleet' : '1', 'S_Open':'', 'C_Open_Finance':'', 'C_Open_IT':'', 'C_Open_ComplianceHelpdesk':'', 'C_Open_ComplinaceSupport':'', 'C_Open_ComplianceRisk':'', 'S_Open_FR':'', 'C_Open_Marketing':'', 'C_Open_HR':'' }, /** * Initialize the variables * @param {RESTAPIRequest} request * @param {RESTAPIResponse} response */ initialize: function (request, response) { this.logger = new global.GSLog('pl4.csm.anywhere365.log', this.type); this.logger.includeTimestamp(); this.request = request; this.response = response; this.validated = false; this.error = false; this.errorObj = { 'statusCode': '', 'message': '', 'details': '' }; this.interactionGr = false; }, /** * Main function that is executed in the Scripted REST API */ process: function () { try { this.validated = this.validateRequest(); if (this.validated !== true) { this._setResponse(); } this.interactionGr = this._createInteraction(); this._setResponse(); } catch (e) { this.logErr('[process] caught an error: ' + e + '\nstack:\n' + e.stack); this._setError(500, 'Internal server error', ''); this._setResponse(); } }, /** * Populates the default interaction fields and makes data lookup for Caller and Agent * @returns {Object} */ _getInteractionFields: function () { var fields = { 'assigned_to': '', 'account': '', 'contact': '', 'consumer': '', 'opened_by': '', 'opened_for': '', 'u_assignment_type': '' }; for (var defaultField in this.INTERATCION_FIELDS_DEFAULTS) { if (Object.hasOwnProperty.call(this.INTERATCION_FIELDS_DEFAULTS, defaultField)) { var defaultFieldValue = this.INTERATCION_FIELDS_DEFAULTS[defaultField]; fields[defaultField] = defaultFieldValue; } } // lookup assignment type var assignmentType = this._getAssignmentType(this.bodyData.ucc); if(assignmentType){ fields.u_assignment_type = assignmentType.join(','); this.logDebug('[_getInteractionFields] assignmenttype(s) found: ' + assignmentType.join(',')); } // Lookup the agent var agentEmail = this._getAgentEmail(); var agentGr = this._lookupAgentByEmail(agentEmail); if (agentGr !== false) { fields.assigned_to = agentGr && agentGr.getUniqueValue(); this.logDebug('[_getInteractionFields] found agent: ' + agentGr.getUniqueValue() + ' ' + agentGr.getDisplayValue()); } // Lookup the caller var callerNumber = this._getCallerNumber(); var contactGr; var consumerGr; var userGr; // Try to lookup Contact by mobile phone first contactGr = this._lookupUserByPhone('customer_contact', 'mobile_phone', callerNumber); if (contactGr === false) contactGr = this._lookupUserByPhone('customer_contact', 'phone', callerNumber); if (contactGr !== false) { // We found the contact, now we can get the account fields.contact = contactGr.getUniqueValue(); fields.account = contactGr.getValue('account'); this.logDebug('[_getInteractionFields] found contact: ' + contactGr.getUniqueValue() + ' ' + contactGr.getDisplayValue()); } if (contactGr === false) { // Did not find Contact, look for consumers consumerGr = this._lookupUserByPhone('csm_consumer', 'mobile_phone', callerNumber); if (consumerGr === false) consumerGr = this._lookupUserByPhone('csm_consumer', 'business_phone', callerNumber); if (consumerGr === false) consumerGr = this._lookupUserByPhone('csm_consumer', 'home_phone', callerNumber); if (consumerGr !== false) { fields.consumer = consumerGr.getUniqueValue(); this.logDebug('[_getInteractionFields] found consumer: ' + consumerGr.getUniqueValue() + ' ' + consumerGr.getDisplayValue()); } if(consumerGr === false){ userGr = this._lookupUserByPhone('sys_user','phone', callerNumber); if(userGr === false) userGr = this._lookupUserByPhone('sys_user','mobile_phone', callerNumber); if(userGr === false) userGr = this._lookupUserByPhone('sys_user','u_ip_phone', callerNumber); if(userGr !== false){ fields.opened_for = userGr.getUniqueValue(); this.logDebug('[_getInteractionFields] found internal user: ' + userGr.getUniqueValue() + ' ' + userGr.getDisplayValue()); } } } // Add variables to short description fields.short_description += ' from ' + callerNumber; this.logDebug('[_getInteractionFields] fields result: ' + global.JSON.stringify(fields)); return fields; }, /** * Get the caller phone from the body * @returns {String} */ _getCallerNumber: function () { return String(this.bodyData.callerNumber); }, /** * Get the assignment type from the ucc * @returns */ _getAssignmentType: function(ucc) { var group = new GlideRecord('sys_user_group'); group.get('u_ucc', ucc); var assTypes = new DataSeparationUtils().getAssignmentTypes(group.u_business_group); gs.log('assignment type function: ' + assTypes); return assTypes; }, /** * Get the agent sip from the body * @returns {String} */ _getAgentEmail: function () { return String(this.bodyData.agentSip).replace('sip:', ''); }, /** * Lookup the user by specified phone number * Note that the number format should match exactly * @param {String} table table where user should be looked up * @param {String} phoneField field that contains the phone number * @param {String} phone phone number received by the REST API * @returns {GlideRecord|boolean} */ _lookupUserByPhone: function (table, phoneField, phone) { var contactGr = new GlideRecord(table); if (!contactGr.isValid()) return false; if (!contactGr.isValidField(phoneField)) return false; if(table == 'sys_user') contactGr.addQuery('sys_class_name', 'sys_user'); contactGr.addQuery(phoneField, phone); contactGr.orderBy('sys_created_on'); contactGr.setLimit(1); contactGr.query(); if (contactGr.next()) { return contactGr; } this.logDebug('[_lookupUserByPhone] Could not find a user, table: ' + table + ' field: ' + phoneField + ' phone: ' + phone); return false; }, /** * Lookup the sys_user record by email * @param {String} agentEmail email of the agent * @returns {GlideRecord|boolean} */ _lookupAgentByEmail: function (agentEmail) { var userGr = new GlideRecord('sys_user'); userGr.addQuery('email', agentEmail); userGr.orderBy('sys_created_on'); userGr.setLimit(1); userGr.query(); if (userGr.next()) { return userGr; } this.logDebug('[_lookupAgentByEmail] Could not find a user, agentEmail: ' + agentEmail); return false; }, /** * Validate the request * @returns {sn_ws_err.ServiceError|boolean} */ validateRequest: function () { try { this.bodyData = request.body.data; if (gs.nil(this.bodyData)) { this.logWarning('[validateRequest] Body data is missing: ' + this.bodyData); this._setError(400, "Body is missing", "Expecting a body with properties."); return false; } for (var i = 0; i < this.MANDATORY_BODY_PROPERTIES.length; i++) { var mandatoryProperty = this.MANDATORY_BODY_PROPERTIES[i]; if (gs.nil(this.bodyData[mandatoryProperty])) { this.logWarning('[validateRequest] Mandatory body property is missing: ' + mandatoryProperty); this._setError(400, "Mandatory body property is missing", "Expecting a body propertiy to be in the body: " + mandatoryProperty); return false; } } // All checkes have passed return true; } catch (e) { this.logErr('[validateRequest] caught an error: ' + e.message + '\nstack: ' + e.stack); } }, /** * Create an interaction record * @returns {GlideRecord|boolean} */ _createInteraction: function () { var interactionFields = this._getInteractionFields(); if (this.error !== false) { // There was an error during data lookup this.logErr('[_createInteraction] There was an error during data lookup'); return false; } var interactionGr = new GlideRecord('interaction'); interactionGr.newRecord(); for (var fieldName in interactionFields) { if (Object.hasOwnProperty.call(interactionFields, fieldName)) { if (interactionGr.isValidField(fieldName)) { var fieldValue = interactionFields[fieldName]; interactionGr.setValue(fieldName, fieldValue); // this.logDebug('[_createInteraction] setting interaction field ' + fieldName + ' to: ' + fieldValue); } } } var interactionId = interactionGr.insert(); if (gs.nil(interactionId)) { //Failed to insert the record this.logErr('[_createInteraction] Failed to create an interaction'); return false; } this.logDebug('[_createInteraction] Created an interaction, sys_id: ' + interactionId + ' number: ' + interactionGr.getValue('number')); return interactionGr; }, /** * Construct and set the error object * @param {number} statusCode * @param {String} message * @param {String} details */ _setError: function (statusCode, message, details) { this.errorObj = { 'statusCode': statusCode, 'message': message, 'details': details, }; var serviceError = new sn_ws_err.ServiceError(); serviceError.setStatus(statusCode); serviceError.setMessage(message); serviceError.setDetail(details); this.error = serviceError; }, /** * Set the status code, messages and response body based on this.error varialbe * */ _setResponse: function () { if (this.error !== false) { this.response.setError(this.error); this.logDebug('[_setResponse] set error with code: ' + this.errorObj.statusCode); return; } if (this.interactionGr !== false) { this.logDebug('[_setResponse] set successful resposne with code: 201, interaction number: ' + this.interactionGr.getValue('number')); this.response.setStatus(201); var responseBody = this._constructResponseBody(); this.response.setBody(responseBody); } }, /** * Construct the Response body, include required interaction fields * @returns {Object} */ _constructResponseBody: function () { var responseBody = {}; for (var i = 0; i < this.INTERACTION_FIELDS_RESPONSE.length; i++) { var field = this.INTERACTION_FIELDS_RESPONSE[i]; responseBody[field] = this.interactionGr.getValue(field); } for (var j = 0; j < this.INTERACTION_FIELDS_DISPLAY_RESPONSE.length; j++) { var fieldDisplay = this.INTERACTION_FIELDS_DISPLAY_RESPONSE[j]; responseBody[fieldDisplay] = this.interactionGr[fieldDisplay] && this.interactionGr[fieldDisplay].getDisplayValue(); } this.logDebug('[_constructResponseBody] responseBody:\n' + global.JSON.stringify(responseBody)); return responseBody; }, logDebug: function (msg) { this.logger.logDebug(msg); }, logInfo: function (msg) { this.logger.logInfo(msg); }, logWarning: function (msg) { this.logger.logWarning(msg); }, logErr: function (msg) { this.logger.logErr(msg); }, type: 'AnywhereCTIService' };
Comments