This repository was archived by the owner on Feb 9, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathinbound-conversation.protected.js
95 lines (91 loc) · 3.97 KB
/
inbound-conversation.protected.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
const sfdcAuthenticatePath = Runtime.getFunctions()['auth/sfdc-authenticate'].path;
const { sfdcAuthenticate } = require(sfdcAuthenticatePath);
exports.handler = async function (context, event, callback) {
const twilioClient = context.getTwilioClient();
let response = new Twilio.Response();
response.appendHeader('Content-Type', 'application/json');
const customerNumber = (event['MessagingBinding.Address'] && event['MessagingBinding.Address'].startsWith('whatsapp:'))
? event['MessagingBinding.Address'].substring(9)
: event['MessagingBinding.Address'];
const conversationSid = event.ConversationSid;
switch (event.EventType) {
case 'onConversationAdded': {
const isIncomingConversation = !!customerNumber;
if (isIncomingConversation) {
const sfdcConnectionIdentity = await sfdcAuthenticate(context, null); // this is null due to no user context, default to env. var SF user
const { connection } = sfdcConnectionIdentity;
const customerDetails = await getCustomerByNumber(customerNumber, connection) || {};
await twilioClient.conversations
.conversations(conversationSid)
.update({friendlyName: customerDetails.display_name || customerNumber});
}
break;
} case 'onParticipantAdded': {
const participantSid = event.ParticipantSid;
const isCustomer = customerNumber && !event.Identity;
if (isCustomer) {
const customerParticipant = await twilioClient.conversations
.conversations(conversationSid)
.participants
.get(participantSid)
.fetch();
const sfdcConnectionIdentity = await sfdcAuthenticate(context, null);
const { connection } = sfdcConnectionIdentity;
const customerDetails = await getCustomerByNumber(customerNumber, connection) || {};
await setCustomerParticipantProperties(customerParticipant, customerDetails);
}
break;
} default: {
console.log('Unknown event type: ', event.EventType);
response.setStatusCode(422);
}
}
return callback(null, response);
};
const getCustomerByNumber = async (number, sfdcConn) => {
console.log('Getting Customer details by #: ', number);
let sfdcRecords = [];
try {
sfdcRecords = await sfdcConn.sobject("Contact")
.find(
{
'MobilePhone': number
},
{
Id: 1,
Name: 1,
}
)
.sort({ LastModifiedDate: -1 })
.limit(1)
.execute();
console.log("Fetched # SFDC records for contact by #: " + sfdcRecords.length);
if (sfdcRecords.length === 0) {
return;
}
const sfdcRecord = sfdcRecords[0];
return {
display_name: sfdcRecord.Name,
customer_id: sfdcRecord.Id
}
} catch (err) {
console.error(err);
}
};
const setCustomerParticipantProperties = async (customerParticipant, customerDetails) => {
const participantAttributes = JSON.parse(customerParticipant.attributes);
const customerProperties = {
attributes: JSON.stringify({
...participantAttributes,
customer_id: participantAttributes.customer_id || customerDetails.customer_id,
display_name: participantAttributes.display_name || customerDetails.display_name
})
};
// If there is difference, update participant
if (customerParticipant.attributes !== customerProperties.attributes) {
// Update attributes of customer to include customer_id
updatedParticipant = await customerParticipant
.update(customerProperties)
.catch(e => console.log("Update customer participant failed: ", e));
}
}