-
Notifications
You must be signed in to change notification settings - Fork 10
New issue
Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? # to your account
CHI-3069: HRM create lambda #2669
Merged
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
f17e8cf
WIP - first version of lambda HRM contact creation
stephenhand 2b3170a
Fix slack message for Twilio Lambda deploy
stephenhand 207cb3c
Ensure task router handler registrations are imported
stephenhand 9ec2bc7
Liocence header
stephenhand cbc517f
Lodash import
stephenhand 9ba8174
Logging
stephenhand 17a9240
Fix contact HRM URL
stephenhand c21a523
Align contact HRM URL
stephenhand e318782
Merge branch 'master' into CHI-3069-hrm_create_lambda
stephenhand b6e1dbf
Fix e2e tests
stephenhand File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
175 changes: 175 additions & 0 deletions
175
lambdas/account-scoped/src/hrm/createHrmContactTaskRouterListener.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,175 @@ | ||
/** | ||
* Copyright (C) 2021-2023 Technology Matters | ||
* This program is free software: you can redistribute it and/or modify | ||
* it under the terms of the GNU Affero General Public License as published | ||
* by the Free Software Foundation, either version 3 of the License, or | ||
* (at your option) any later version. | ||
* | ||
* This program is distributed in the hope that it will be useful, | ||
* but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
* GNU Affero General Public License for more details. | ||
* | ||
* You should have received a copy of the GNU Affero General Public License | ||
* along with this program. If not, see https://www.gnu.org/licenses/. | ||
*/ | ||
|
||
/* eslint-disable global-require */ | ||
/* eslint-disable import/no-dynamic-require */ | ||
import { | ||
HrmContact, | ||
populateHrmContactFormFromTask, | ||
} from './populateHrmContactFormFromTask'; | ||
import { registerTaskRouterEventHandler } from '../taskrouter/taskrouterEventHandler'; | ||
import { EventType, RESERVATION_ACCEPTED } from '../taskrouter/eventTypes'; | ||
import type { EventFields } from '../taskrouter'; | ||
import twilio from 'twilio'; | ||
import { AccountSID } from '../twilioTypes'; | ||
import { getSsmParameter } from '../ssmCache'; | ||
|
||
export const eventTypes: EventType[] = [RESERVATION_ACCEPTED]; | ||
|
||
// Temporarily copied to this repo, will share the flex types when we move them into the same repo | ||
|
||
const BLANK_CONTACT: HrmContact = { | ||
id: '', | ||
timeOfContact: new Date().toISOString(), | ||
taskId: null, | ||
helpline: '', | ||
rawJson: { | ||
childInformation: {}, | ||
callerInformation: {}, | ||
caseInformation: {}, | ||
callType: '', | ||
contactlessTask: { | ||
channel: 'web', | ||
date: '', | ||
time: '', | ||
createdOnBehalfOf: '', | ||
helpline: '', | ||
}, | ||
categories: {}, | ||
}, | ||
channelSid: '', | ||
serviceSid: '', | ||
channel: 'default', | ||
createdBy: '', | ||
createdAt: '', | ||
updatedBy: '', | ||
updatedAt: '', | ||
queueName: '', | ||
number: '', | ||
conversationDuration: 0, | ||
csamReports: [], | ||
conversationMedia: [], | ||
}; | ||
|
||
export const handleEvent = async ( | ||
{ | ||
TaskAttributes: taskAttributesString, | ||
TaskSid: taskSid, | ||
WorkerSid: workerSid, | ||
}: EventFields, | ||
accountSid: AccountSID, | ||
client: twilio.Twilio, | ||
): Promise<void> => { | ||
const taskAttributes = taskAttributesString ? JSON.parse(taskAttributesString) : {}; | ||
const { channelSid, isContactlessTask, transferTargetType } = taskAttributes; | ||
|
||
if (isContactlessTask) { | ||
console.debug( | ||
`Task ${taskSid} is a contactless task, contact was already created in Flex.`, | ||
); | ||
return; | ||
} | ||
|
||
if (transferTargetType) { | ||
console.debug( | ||
`Task ${taskSid} was created to receive a ${transferTargetType} transfer. The original contact will be used so a new one will not be created.`, | ||
); | ||
return; | ||
} | ||
|
||
const serviceConfig = await client.flexApi.v1.configuration.get().fetch(); | ||
|
||
const { | ||
definitionVersion, | ||
hrm_api_version: hrmApiVersion, | ||
form_definitions_version_url: configFormDefinitionsVersionUrl, | ||
assets_bucket_url: assetsBucketUrl, | ||
helpline_code: helplineCode, | ||
channelType, | ||
customChannelType, | ||
feature_flags: { | ||
enable_backend_hrm_contact_creation: enableBackendHrmContactCreation, | ||
}, | ||
} = serviceConfig.attributes; | ||
const formDefinitionsVersionUrl = | ||
configFormDefinitionsVersionUrl || | ||
`${assetsBucketUrl}/form-definitions/${helplineCode}/v1`; | ||
if (!enableBackendHrmContactCreation) { | ||
console.debug( | ||
`enable_backend_hrm_contact_creation is not set, the contact associated with task ${taskSid} will be created from Flex.`, | ||
); | ||
return; | ||
} | ||
|
||
const [hrmStaticKey, twilioWorkspaceSid] = await Promise.all([ | ||
getSsmParameter(`/${process.env.NODE_ENV}/twilio/${accountSid}/static_key`), | ||
getSsmParameter(`/${process.env.NODE_ENV}/twilio/${accountSid}/workspace_sid`), | ||
]); | ||
const contactUrl = `${process.env.INTERNAL_HRM_URL}/internal/${hrmApiVersion}/accounts/${accountSid}/contacts`; | ||
|
||
console.debug('Creating HRM contact for task', taskSid, contactUrl); | ||
|
||
const newContact: HrmContact = { | ||
...BLANK_CONTACT, | ||
channel: (customChannelType || channelType) as HrmContact['channel'], | ||
rawJson: { | ||
definitionVersion, | ||
...BLANK_CONTACT.rawJson, | ||
}, | ||
twilioWorkerId: workerSid as HrmContact['twilioWorkerId'], | ||
taskId: taskSid as HrmContact['taskId'], | ||
channelSid: channelSid ?? '', | ||
serviceSid: (channelSid && serviceConfig.chatServiceInstanceSid) ?? '', | ||
// We set createdBy to the workerSid because the contact is 'created' by the worker who accepts the task | ||
createdBy: workerSid as HrmContact['createdBy'], | ||
}; | ||
|
||
const populatedContact = await populateHrmContactFormFromTask( | ||
taskAttributes, | ||
newContact, | ||
formDefinitionsVersionUrl, | ||
); | ||
const options: RequestInit = { | ||
method: 'POST', | ||
body: JSON.stringify(populatedContact), | ||
headers: { | ||
'Content-Type': 'application/json', | ||
Authorization: `Basic ${hrmStaticKey}`, | ||
}, | ||
}; | ||
const response = await fetch(contactUrl, options); | ||
if (!response.ok) { | ||
console.error( | ||
`Failed to create HRM contact for task ${taskSid} - status: ${response.status} - ${response.statusText}`, | ||
await response.text(), | ||
); | ||
return; | ||
} | ||
const { id } = (await response.json()) as HrmContact; | ||
console.info(`Created HRM contact with id ${id} for task ${taskSid}`); | ||
|
||
const taskContext = client.taskrouter.v1.workspaces | ||
.get(twilioWorkspaceSid) | ||
.tasks.get(taskSid); | ||
const currentTaskAttributes = (await taskContext.fetch()).attributes; // Less chance of race conditions if we fetch the task attributes again, still not the best... | ||
const updatedAttributes = { | ||
...JSON.parse(currentTaskAttributes), | ||
contactId: id.toString(), | ||
}; | ||
await taskContext.update({ attributes: JSON.stringify(updatedAttributes) }); | ||
}; | ||
|
||
registerTaskRouterEventHandler([RESERVATION_ACCEPTED], handleEvent); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧹?