Skip to content
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 10 commits into from
Jan 14, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .github/actions/run-e2e-tests/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,8 @@ runs:
shell: bash

- name: Setup dependencies for playwright/browsers
uses: microsoft/playwright-github-action@v1
shell: bash
run: npx playwright install --with-deps chromium

- name: Install Playwright Browsers
run: npm run postinstall
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/twilio-lambda-deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ jobs:
uses: slackapi/slack-github-action@v1.25.0
with:
channel-id: ${{ env.ASELO_DEPLOYS_CHANNEL_ID }}
slack-message: '`[HRM lambdas - ${{ matrix.lambda_path }}]` Deployment of ${{ github.ref_type }} `${{ github.ref_name }}` requested by `${{ github.triggering_actor }}` completed with SHA ${{ github.sha }} to region `${{ inputs.region }}`, environment `${{ inputs.environment }}` :rocket:.'
slack-message: '`[Twilio lambdas - ${{ matrix.lambda_path }}]` Deployment of ${{ github.ref_type }} `${{ github.ref_name }}` requested by `${{ github.triggering_actor }}` completed with SHA ${{ github.sha }} to region `${{ inputs.region }}`, environment `${{ inputs.environment }}` :rocket:.'
env:
SLACK_BOT_TOKEN: ${{ env.GITHUB_ACTIONS_SLACK_BOT_TOKEN }}
if: ${{ inputs.send-slack-message != 'false' }}
4 changes: 4 additions & 0 deletions lambdas/account-scoped/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"version": "1.0.0",
"devDependencies": {
"@types/aws-lambda": "^8.10.108",
"@types/lodash": "^4.17.13",
"@types/node": "^18.16.2",
"jest-each": "^29.5.0",
"ts-node": "^10.9.1",
Expand All @@ -15,6 +16,9 @@
},
"dependencies": {
"@aws-sdk/client-ssm": "^3.716.0",
"@twilio-labs/serverless-runtime-types": "^4.0.1",
"date-fns": "^4.1.0",
"lodash": "^4.17.21",
"twilio": "^5.4.0"
}
}
175 changes: 175 additions & 0 deletions lambdas/account-scoped/src/hrm/createHrmContactTaskRouterListener.ts
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
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹?


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);
Loading
Loading