forked from cweems/function-frontline-salesforce
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathoutgoing-conversation.protected.js
67 lines (65 loc) · 2.44 KB
/
outgoing-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
const sfdcAuthenticatePath = Runtime.getFunctions()['auth/sfdc-authenticate'].path;
const { sfdcAuthenticate } = require(sfdcAuthenticatePath);
exports.handler = async function (context, event, callback) {
let response = new Twilio.Response();
response.appendHeader('Content-Type', 'application/json');
try {
console.log('Frontline user identity: ' + event.Worker);
const sfdcConnectionIdentity = await sfdcAuthenticate(context, event.Worker);
const { connection } = sfdcConnectionIdentity;
const outboundNumber = await getWorkerOutboundNumber(event.Worker, connection);
switch (event.Location) {
case 'GetProxyAddress': {
if (event.ChannelType === 'whatsapp') {
response.setBody({
proxy_address: outboundNumber ?
`whatsapp:${outboundNumber}` :
context.WHATSAPP_NUMBER
});
} else {
response.setBody({
proxy_address: outboundNumber || context.SMS_NUMBER
})
}
break;
}
default: {
console.log('Unknown Location: ', event.Location);
response.setStatusCode(422);
}
}
return callback(null, response);
} catch (e) {
console.error(e);
response.setStatusCode(500);
return callback(null, response);
}
};
const getWorkerOutboundNumber = async (workerIdentity, sfdcConn) => {
console.log('Getting Worker # for user: ', workerIdentity);
let sfdcRecords = [];
try {
sfdcRecords = await sfdcConn.sobject("User")
.find(
{
'Username': workerIdentity
},
{
'MobilePhone': 1,
}
)
.sort({ LastModifiedDate: -1 })
.limit(1)
.execute();
console.log("Fetched # SFDC records for worker # by identity: " + sfdcRecords.length);
if (sfdcRecords.length === 0) {
console.log('Did not find outbound number for worker: ' + workerIdentity);
return;
}
const sfdcRecord = sfdcRecords[0];
console.log('Matched to worker number: ' + sfdcRecord.MobilePhone);
return sfdcRecord.MobilePhone;
} catch (err) {
console.error(err);
}
};