Skip to content

createMessageLog

This interface is responsible for creating a new messaging log record in the associated CRM. The message or messages must be associated with the contact passed in as a request parameter. Other associations may be made depending upon the CRM and the connector. This interface is always invoked for a single SMS message.

Creating daily digests of an SMS conversation

To prevent SMS conversations with a customer from overwhelming the CRM with a multitude of log entries for each SMS message, App Connect creates a daily digest for each SMS conversation with a customer into which all SMS messages for a 24 hour period are aggregated.

Therefore, this interface is only invoked when the daily digest is created. The updateMessageLog interface is invoked for all subsequent SMS messages in that 24 hour period.

Input parameters

Parameter Description
user An object describing the Chrome extension user associated with the action that triggered this interface.
contactInfo An associative array describing the contact a call is associated with.
authHeader The HTTP Authorization header to be transmitted with the API request to the target CRM.
message All the metadata associated with the message to be logged. SMS message schema is described in our API Reference.
additionalSubmission All of the additional custom fields defined in the manifest and submitted by the user.
recordingLink If the call was a voicemail, then this field will contain a link to the voicemail.
faxDocLink The link to view fax document
faxDownloadLink The link to download fax document file
imageLink The link to view image attachment
videoLink The link to view video attachment

message

{
  "uri" : "https://platform.ringcentral.com/restapi/xxxxxxx/message-store/60279564004",
  "id" : 60279564004,
  "to" : [ {
    "phoneNumber" : "+16505553204",
    "location" : "San Mateo, CA"
  } ],
  "from" : {
    "phoneNumber" : "+18885550052"
  },
  "type" : "SMS",
  "creationTime" : "2015-02-18T13:24:50.000Z",
  "readStatus" : "Read",
  "priority" : "Normal",
  "attachments" : [ {
    "id" : 60279564004,
    "uri" : "https://media.ringcentral.com/restapi/xxxxxxxxxxxx/content/60279564004",
    "type" : "Text",
    "contentType" : "text/plain"
  } ],
  "direction" : "Outbound",
  "availability" : "Alive",
  "subject" : "Flight information",
  "messageStatus" : "Sent",
  "smsSendingAttemptsCount" : 1,
  "conversationId" : 5578984350117917661,
  "lastModifiedTime" : "2015-02-18T13:24:50.300Z"
}

Return value(s)

An object with following properties:

Parameter Description
logId ID of the log entry created within the CRM
returnMessage message, messageType and ttl

Example

  return {
    logId: "xxxx-xxx", // ID of log entity on CRM platform
    returnMessage:{
      message: 'Logged',
      messageType: 'success', // 'success', 'warning' or 'danger'
      ttl: 30000 // in miliseconds
    }
  }

Reference

// message : same as in https://developers.ringcentral.com/api-reference/Message-Store/readMessage
async function createMessageLog({ user, contactInfo, authHeader, message, additionalSubmission, recordingLink, faxDocLink }) {
    const messageType = recordingLink ? 'Voicemail' : (faxDocLink ? 'Fax' : 'SMS');
    console.log(`adding message log... \n\n${JSON.stringify(message, null, 2)}`);
    const newMessageLog = {
        id:  `CRM message log id ${Date.now()}`
    }

    // Using mock JSON as CRM response
    const fs = require('fs');
    const path = require('path');
    const mockMessageLogsPath = path.join(__dirname, '..', 'mockMessageLogs.json');
    const mockMessageLogs = require(mockMessageLogsPath);
    mockMessageLogs.push(newMessageLog);
    fs.writeFileSync(mockMessageLogsPath, JSON.stringify(mockMessageLogs, null, 2));
    //-------------------------------------------------------------------------------------------------------------
    //--- CHECK: For single message logging, open db.sqlite and JSON file to check if message logs are saved ------
    //-------------------------------------------------------------------------------------------------------------

    //--------------------------------------
    //--- TODO: Add CRM API call here ------
    //--------------------------------------
    // const postBody = {
    //     data: {
    //         subject: `[SMS] ${message.direction} SMS - ${message.from.name ?? ''}(${message.from.phoneNumber}) to ${message.to[0].name ?? ''}(${message.to[0].phoneNumber})`,
    //         body: `${message.direction} SMS - ${message.direction == 'Inbound' ? `from ${message.from.name ?? ''}(${message.from.phoneNumber})` : `to ${message.to[0].name ?? ''}(${message.to[0].phoneNumber})`} \n${!!message.subject ? `[Message] ${message.subject}` : ''} ${!!recordingLink ? `\n[Recording link] ${recordingLink}` : ''}\n\n--- Created via RingCentral App Connect`,
    //         type: 'Message'
    //     }
    // }
    // const addLogRes = await axios.post(
    //     `https://api.crm.com/activity`,
    //     postBody,
    //     {
    //         headers: { 'Authorization': authHeader }
    //     });
    return {
        logId: newMessageLog.id,
        returnMessage: {
            message: 'Message logged',
            messageType: 'success',
            ttl: 1000
        }
    };
}

module.exports = createMessageLog;
async function createMessageLog({ user, contactInfo, authHeader, message, additionalSubmission, recordingLink, faxDocLink }) {
    let extraDataTracking = {};
    const userInfoResponse = await axios.get(`https://${user.hostname}/v1/users/me`, {
        headers: {
            'Authorization': authHeader
        }
    });
    const personResponse = await axios.get(`https://${user.hostname}/api/v2/persons/${contactInfo.id}`, { headers: { 'Authorization': authHeader } });

    const userName = userInfoResponse.data.data.name;
    const dealId = additionalSubmission ? additionalSubmission.deals : '';
    const leadId = additionalSubmission ? additionalSubmission.leads : '';
    const orgId = personResponse.data.data.org_id ?? '';
    const timeUtc = moment(message.creationTime).utcOffset(0).format('HH:mm')
    const dateUtc = moment(message.creationTime).utcOffset(0).format('YYYY-MM-DD');
    const activityTypesResponse = await axios.get(`https://${user.hostname}/v1/activityTypes`, { headers: { 'Authorization': authHeader } });
    const smsType = activityTypesResponse.data.data.find(t => t.name === 'SMS' && t.active_flag);

    const messageType = recordingLink ? 'Voicemail' : (faxDocLink ? 'Fax' : 'SMS');
    let subject = '';
    let note = '';
    switch (messageType) {
        case 'SMS':
            subject = `SMS conversation with ${contactInfo.name} - ${moment(message.creationTime).utcOffset(user.timezoneOffset).format('YY/MM/DD')}`;
            note =
                `<br><b>${subject}</b><br>` +
                '<b>Conversation summary</b><br>' +
                `${moment(message.creationTime).utcOffset(user.timezoneOffset).format('dddd, MMMM DD, YYYY')}<br>` +
                'Participants<br>' +
                `<ul><li><b>${userName}</b><br></li>` +
                `<li><b>${contactInfo.name}</b></li></ul><br>` +
                'Conversation(1 messages)<br>' +
                'BEGIN<br>' +
                '------------<br>' +
                '<ul>' +
                `<li>${message.direction === 'Inbound' ? `${contactInfo.name} (${contactInfo.phoneNumber})` : userName} ${moment(message.creationTime).utcOffset(user.timezoneOffset).format('hh:mm A')}<br>` +
                `<b>${message.subject}</b></li>` +
                '</ul>' +
                '------------<br>' +
                'END<br><br>' +
                '--- Created via RingCentral App Connect';
            break;
        case 'Voicemail':
            subject = `Voicemail left by ${contactInfo.name} - ${moment(message.creationTime).utcOffset(user.timezoneOffset).format('YY/MM/DD')}`;
            note = `<br><b>${subject}</b><br>Voicemail recording link: ${recordingLink} <br><br>--- Created via RingCentral App Connect`;
            break;
        case 'Fax':
            subject = `Fax document sent from ${contactInfo.name} - ${moment(message.creationTime).utcOffset(user.timezoneOffset).format('YY/MM/DD')}`;
            note = `<br><b>${subject}</b><br>Fax document link: ${faxDocLink} <br><br>--- Created via RingCentral App Connect`;
            break;
    }
    const postBody = {
        owner_id: Number(user.id.split('-')[0]),
        subject,
        deal_id: dealId,
        note,
        done: true,
        due_date: dateUtc,
        due_time: timeUtc,
        type: smsType ? smsType.key_string : 'call',
        participants: [
            {
                person_id: Number(contactInfo.id),
                primary: true
            }
        ]
    }
    if (!dealId && leadId) {
        postBody.lead_id = leadId;
    }
    if (orgId) {
        postBody.org_id = orgId;
    }
    const addLogRes = await axios.post(
        `https://${user.hostname}/api/v2/activities`,
        postBody,
        {
            headers: { 'Authorization': authHeader }
        });
    extraDataTracking = {
        ratelimitRemaining: addLogRes.headers['x-ratelimit-remaining'],
        ratelimitAmount: addLogRes.headers['x-ratelimit-limit'],
        ratelimitReset: addLogRes.headers['x-ratelimit-reset']
    };
    return {
        logId: addLogRes.data.data.id,
        returnMessage: {
            message: 'Message logged',
            messageType: 'success',
            ttl: 1000
        },
        extraDataTracking
    };
}