Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CHI-2763 Check for an active contact & complete task #698

Merged
merged 7 commits into from
Oct 4, 2024
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
84 changes: 84 additions & 0 deletions functions/checkTaskAssignment.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
/**
* 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/.
*/
import '@twilio-labs/serverless-runtime-types';
import { Context, ServerlessCallback } from '@twilio-labs/serverless-runtime-types/types';
import {
responseWithCors,
bindResolve,
error400,
error500,
success,
functionValidator as TokenValidator,
} from '@tech-matters/serverless-helpers';

type EnvVars = {
TWILIO_WORKSPACE_SID: string;
};

export type Body = {
request: { cookies: {}; headers: {} };
} & { taskSid: string };

type ContactType = {
taskSid: string;
};

const isTaskAssigned = async (
context: Context<EnvVars>,
event: Required<Pick<ContactType, 'taskSid'>>,
): Promise<boolean> => {
const client = context.getTwilioClient();

try {
const task = await client.taskrouter
.workspaces(context.TWILIO_WORKSPACE_SID)
.tasks(event.taskSid)
.fetch();

const { assignmentStatus } = task;

return assignmentStatus === 'assigned' || assignmentStatus === 'wrapping';
} catch (err) {
console.error('Error fetching task:', err);
return false;
}
};

export const handler = TokenValidator(
async (context: Context<EnvVars>, event: Body, callback: ServerlessCallback) => {
const response = responseWithCors();
const resolve = bindResolve(callback)(response);

console.log('event', event);

try {
const { taskSid } = event;

if (taskSid === undefined) {
resolve(error400('taskSid'));
return;
}

const result = await isTaskAssigned(context, {
taskSid,
});

resolve(success({ isAssigned: result }));
} catch (err: any) {
resolve(error500(err));
}
},
);
139 changes: 139 additions & 0 deletions functions/completeTaskAssignment.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
// Close task as a supervisor
/**
* 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/.
*/
import '@twilio-labs/serverless-runtime-types';
import { validator } from 'twilio-flex-token-validator';
import { Context, ServerlessCallback } from '@twilio-labs/serverless-runtime-types/types';
import {
responseWithCors,
bindResolve,
error400,
error500,
success,
functionValidator as TokenValidator,
} from '@tech-matters/serverless-helpers';

type EnvVars = {
TWILIO_WORKSPACE_SID: string;
ACCOUNT_SID: string;
AUTH_TOKEN: string;
};

type TaskInstance = Awaited<
ReturnType<
ReturnType<
ReturnType<ReturnType<Context['getTwilioClient']>['taskrouter']['workspaces']>['tasks']
>['fetch']
>
>;

type ContactComplete = {
action: 'complete';
taskSid: string;
targetSid: string;
finalTaskAttributes: TaskInstance['attributes'];
Copy link
Collaborator

Choose a reason for hiding this comment

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

Where do this finalTaskAttributes come from? 🤔 Is that from the supervisor Flex instance? If so, how are those computed? (Maybe I'll answer this question after reviewing the other PR).

};

export type Body = {
request: { cookies: {}; headers: {} };
Token?: string;
} & ContactComplete;

type AssignmentResult =
| {
type: 'error';
payload: { message: string; attributes?: string };
}
| { type: 'success'; completedTask: TaskInstance };

const closeTaskAssignment = async (
context: Context<EnvVars>,
event: Required<Pick<ContactComplete, 'taskSid' | 'finalTaskAttributes'>>,
): Promise<AssignmentResult> => {
const client = context.getTwilioClient();

try {
const task = await client.taskrouter
.workspaces(context.TWILIO_WORKSPACE_SID)
.tasks(event.taskSid)
.fetch();

await task.update({ attributes: event.finalTaskAttributes });

const completedTask = await task.update({ assignmentStatus: 'completed' });

return { type: 'success', completedTask } as const;
} catch (err) {
return {
type: 'error',
payload: { message: String(err) },
};
}
};

export type TokenValidatorResponse = { worker_sid?: string; roles?: string[] };

const isSupervisor = (tokenResult: TokenValidatorResponse) =>
Array.isArray(tokenResult.roles) && tokenResult.roles.includes('supervisor');

export const handler = TokenValidator(
async (context: Context<EnvVars>, event: Body, callback: ServerlessCallback) => {
const response = responseWithCors();
const resolve = bindResolve(callback)(response);

const accountSid = context.ACCOUNT_SID;
const authToken = context.AUTH_TOKEN;
const token = event.Token;

if (!token || token === undefined) {
resolve(error400('token'));
return;
}

try {
const tokenResult: TokenValidatorResponse = await validator(
token as string,
accountSid,
authToken,
);
Comment on lines +101 to +111
Copy link
Collaborator

Choose a reason for hiding this comment

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

This all looks great, but have you checked if tokenResult is not included in the event?


const isSupervisorToken = isSupervisor(tokenResult);

if (!isSupervisorToken) {
resolve(
error400(`Unauthorized: endpoint not open to non supervisors. ${isSupervisorToken}`),
);
return;
}

const { taskSid } = event;

if (taskSid === undefined) {
resolve(error400('taskSid is undefined'));
return;
}

const result = await closeTaskAssignment(context, {
taskSid,
finalTaskAttributes: JSON.stringify({}),
});

resolve(success(result));
} catch (err: any) {
resolve(error500(err));
}
},
);