MyInsights v2.0

Users who are upgrading from an older version of MyInsights need the following Javascript library Download Input File

See MyInsights Visualizations for more information.

The MyInsights library is dependent on the Q library which enables users to work with promises as returns from the MyInsights library methods. Include the Q library as a script in the custom report package.

When requesting a Salesforce Field using a MyInsights method, the field must be case sensitive.

DataService

The DataService provides the primary interface for interacting with the Salesforce data. The DataService is a primary singleton instantiating itself upon execution of this script and is available in the global scope as 'ds', for example: 'window.ds'. The aim of the DataService is to simplify querying of Salesforce data from within your custom HTML-based application. The primary function of the DataService queries a set of records for you according to the config object you pass in. It provides a record set that is data-typed, properly labeled, with recordtype and picklist labels returned conveniently for you.

Methods

getDataForCurrentObject(object, field)

Copy

Request

/* This example comes from the Account Profile Override entrypoint*/

function start() {
queryCRMData();
}

function queryCRMData() {
ds.getDataForCurrentObject('Account', 'Credentials_vod__c').then(
function(resp) {
console.log(resp);
printToScreen(resp);
},
function(err) {
console.log(err);
}
);
}

function printToScreen(jsonObj) {
var test = document.getElementById("test");
test.innerHTML = JSON.stringify(jsonObj);
}

document.addEventListener("DOMContentLoaded", function(event) {
start();
});
Copy

Response

{
"Account":{
"Credentials_vod__c":"DO"
},
"success":true
}

Returns the value of a field for a specific record related to the current object.

Parameters:

Name Type Description
object string The API Name of the object you wish to query.
field string The API Name of the field for which you wish to retreive a value.

Returns:

The promise returned when resolved will return the results of the query.

Type

object

Keywords supported by entry point:

Order: Account, TSF, User, Order, HTMLReport
Account: Account, TSF, User, HTMLReport
Homepage: User, HTMLReport
Account Plan: AccountPlan, Account, User, HTMLReport
Inventory Monitoring: Account, TSF, User, InventoryMonitoring, HTMLReport

getFeedbackData()

Copy

Request

ds.getFeedbackData();
Copy

Response

{
  "accountDetailMetadata" : [
    {
      "label" : "Name",
      "name" : "account__aln.name__v",
      "type" : "STRING"
    },
   {
      "label" : "ID",
      "name" : "account__aln.id",
      "type" : "STRING"
    },

  ],
  "addedAccounts" : 48,
  "droppedAccounts" : 0,
  "addedBrickCodes" : [ "9455", "90210" ],
  "droppedBrickCodes" : [ "92184" ],
  "addedZipcodes" : [ "12345"  ],
  "droppedZipCodes" : [ "94555" ],
  "approvedChallengeAccounts" : 0,
  "businessAccounts" : 0,
  "canChallenge" : false,
  "canReview" : false,
  "dueDate" : "25\/08\/2022",
  "endDate" : "30\/09\/2022",
  "goalMetadata" : [
    {
      "channelOrProductName" : "Face to Face",
      "dailyActivityGoal" : 6,
      "defaultGoal" : 3,
      "defaultMaxGoal" : 6,
      "id" : "OPG000000021001",
      "products" : [
        {
          "channelOrProductName" : "Cholecap",
          "dailyActivityGoal" : null,
          "defaultGoal" : 3,
          "defaultMaxGoal" : 6,
          "id" : "OPK00000001O001",
          "products" : [

          ]
        },
       ]
    }
  ],
  "instructions" : "Test Team Goals",
  "manager" : false,
  "modelDescription" : "Test Team Goals",
  "pendingChallengeAccounts" : 1,
  "personAccounts" : 48,
  "productMetricMetadata" : {
    "metrics" : [
       {
        "apiName" : "trx__aln",
        "label" : "TRx",
        "type" : "NUMBER"
      },
      {
        "apiName" : "pmetricnum__c",
        "label" : "pmetricNum",
        "type" : "NUMBER"
      },

    ],
    "products" : [
      "CatPro",
      "Cholecap",
      "Labrinone",
      "Restolar"
    ]
  },
  "readOnly" : false,
  "rejectedChallengeAccounts" : 0,
  "startDate" : "1\/1\/2023",
  "status" : "Feedback",
  "targetAccounts" : 48,
  "targetingEnabled" : true,
  "teamSellingEnabled" : true,
  "territoryDescription" : "VT, MA",
  "territoryId" : "OP2000000001002",
  "territoryName" : "Feedback1 Territory",
  "totalGoals" : [
    {
      "channelOrProductId" : "OPG000000002001",
      "label" : "Multichannel Activity",
      "products" : [
        {
          "channelOrProductId" : "OPK000000002001",
          "label" : "Cholecap",
          "totalGoal" : "126"
        },
      ],
      "totalGoal" : "288"
    }
  ],
  "workingDays" : 260,
  "accountData" : [
   {
   "accountChallengeReasons" : [ ],
   "accountChallengeStatus" : null,
   "accountChallengeType" : null,
   "accountDetails" : {
      "account__aln.name__v" : "Coireall Abraham",
      "account__aln.source__aln" : "Crm",
    }
   "addresses" : [
        "Short Address, Stuttgart",
        "A really long address"
    ],
   "firstName" : "Coireall",
   "formattedName" : "Abraham, , Coireall",
   "goalDetails" : [
     {
      "channelOrProductId" : "OPG00002002",
      "feedbackGoal" : 7,
      "goal" : 6,
      "maxGoal" : 8,
      "productGoals" : [
        {
         "channelOrProductId" : "OPK1O001",
         "feedbackGoal" : null,
         "goal" : 2,
         "maxGoal" : 3,
         "productGoals" : [],
         "segment" : "Cholecap",
         "teamGoal" : 4
        },
      ],
     "segment" : "Calls Activity",
     "teamGoal" : 26
    },
  ]
  "id" : "A0C000000007311",
  "lastName" : "Abraham",
  "person" : true,
  "productMetricDetails" : [
    {
     "metric" : "name__v",
      "productMetricValues" : {
        "CatPro" : "PM-0327",
        "Cholecap" : "PM-0258",
        "Labrinone" : "PM-0257"
       }
     },
   "target" : true,
   "targetChallengeReasons" : [ ],
   "targetChallengeStatus" :  "Challenged",
   "targetChallengeType" : "GoalEdit",
   "team" : [
     {
      "teamMemberGoals" : [
        {
          "channelOrProductId" : "",
          "feedbackGoal" : null,
          "goal" : 3,
          "maxGoal" : null,
          "productGoals" : [
           {
             "channelOrProductId" : "",
             "feedbackGoal" : null,
             "goal" : 2,
             "maxGoal" : null,
             "productGoals" : [],
             "segment" : null,
             "teamGoal" : null
           },
     ],
     "teamMemberName" : "April Levine",
     "teamMemberTerritoryDescription" : "Greater Boston",
     "teamMemberTerritoryName" : "US Cardio Sales East NE 2"
     }
   ]
}

This method retrieves data about upcoming changes to the current territory.

This method will be available in the CRM 22R2.1 sandbox release, currently scheduled for August 25, 2022.

Parameters:

The default behavior of the method returns the full set of data.

Returns:

When the request is successful, the method returns feedback data in JSON format, which can then be leveraged by content creators:

Field

Description

accountDetailMetadata

Metadata of the labels used to identify account detail information.

Contains the following attributes:

  • label – Detail label
  • Name – The API name from Align
  • type – The type of data, for example, Boolean, Number, DateTime
addedAccounts

The total number of accounts that have been added to the territory.

droppedAccounts

The total number of accounts that have been dropped from the territory.

addedBrickCodes

List of brick codes that have been added.

droppedBrickCodes

List of brick codes that have been dropped.

addedZipCodes

List of zip codes that have been added.

droppedZipCodes

List of zip codes that have been dropped.

approvedChallengeAccounts

The total number of accounts with approved challenge statuses.

businessAccounts

The total number of business accounts in the territory.

canChallenge

Determines if the user can make challenges.

canReview

Determines if the user can review the territory.

dueDate

Date that the data for territory must be submitted by.

endDate

End date of the cycle. If no cycle exists this field represents the end date of the territory.

goalMetadata

Contains information about goals in the territory:

  • channelOrProductName – The name of the channel or product
  • dailyActivityGoal – The daily activity goal
  • defaultGoal – The default goal for a channel or product
  • defaultMaxGoal – The default max goal for a channel or product id – Refers to the ID associated with a specific channel or product
  • products[ ] – A list of products associated with the current channel. Contains the following sub-attributes:
  • defaultGoal
  • defaultMaxGoal
  • id
  • products
instructions

Instructions listed specifically for the territory.

manager

Determines if the current user a manager.

modelDescription

Description of the model.

pendingChallengeAccounts

The total number of accounts with pending challenge status.

personAccounts

The total number of person accounts in the territory.

productMetricMetadata

Contains information about product metrics associated with the territory:

  • metrics – Contains the following sub-attributes:
  • apiName – The formatted name from Align
  • label – The label of the apiName
  • fieldtype – The type of the apiName field
  • products
readOnly

Determines if the territory is in read-only mode.

rejectedChallengeAccounts

Total number of accounts with rejected challenge statuses.

startDate

Start date of the cycle. If no cycle exists this field represents the start date of the territory.

status

The current feedback state of the territory.

targetAccounts

The total number of targets in the territory.

targetingEnabled

Determines if the territory has targeting enabled.

teamSellingEnabled

Determines if Team Selling is enabled.

territoryDescription

The description of the territory.

territoryId

The ID of the territory.

territoryName

The name of the territory.

totalGoals

Represents the total goals calculated for each channel and product.

Contains the following attributes:

  • channelOrProductId – The ID for a given channel or product
  • label – The name of the channel or product
  • products – Lists the products associated with a given channel
  • totalGoal – The calculated total goal value
workingDays

The number of working days in the territory.

accountData

Details data about each account in the territory.

Contains the following attributes:

  • accountChallengeReasons – Array of selected reasons for an account challenge
  • accountChallengeStatus – The current status for an account challenge
  • accountChallengeType – The type of account challenge
  • accountDetails – List of details for each individual account, formatted by mapping each field and its given value
  • addresses – Array of addresses associated with the account
  • firstName – The account’s first name
  • formattedName – The account’s formatted name
  • goalDetails – Details the goals associated with the account. Contains the following sub-attributes:
  • channelOrProductId
  • feedbackGoal
  • goal
  • maxGoal
  • productGoals
  • segment
  • teamGoal
  • id – The account’s ID
  • lastName – The account’s last name
  • person – Determines if the account is a Person Account
  • productMetricDetails – Details the product metrics associated with the account. Contains the following sub-attributes:
  • metric
  • productMetricValues
  • target – Determines if the account is a target
  • targetChallengeReasons – Array of selected reasons for a target challenge
  • targetChallengeStatus – Current status of a target challenge
  • targetChallengeType – The type of target challenge made
  • team – Array of team related data. Only populates if teamSellingEnabled is true. Contains the following sub-attributes:
  • teamMemberGoals – The goals for the associated team members. Contains the same sub-attributes as the goals attribute.
  • teamMemberName
  • teamMemberTerritoryDescription
  • teamMemberTerritoryName

getFieldLabels(queryConfig)

Copy

Request

function start() {
queryCRMData();
}

function queryCRMData() {
var queryConfig = {
object: "Clinical_Trial__c",
fields: ["Name", "Display"],
};

ds.getFieldLabels(queryConfig).then(
function(resp) {
console.log(resp);
printToScreen(resp);
},
function(err) {
console.log(err);
}
);
}

function printToScreen(jsonObj) {
var test = document.getElementById("test");
test.innerHTML = JSON.stringify(jsonObj);
}

document.addEventListener("DOMContentLoaded", function(event) {
start();
});
Copy

Response

{
"Clinical_Trial__c":{
"display":"Start Date",
"name":"Start_Date_vod__c"
}
}

Return the labels for the list of fields passed in.

Parameters:

Name Type Description
queryConfig object {object: String, fields: Array}

Properties

Name Type Description
object string Name of the object to query
fields array An array of field Labels to return.

Returns:

The promise returned when resolved will return the results of the query.

Type

promise

getInStatement(ids)

Copy

Request

ds.getInStatement(ids)

// input looks like
[idOne, idTwo, idThree]
Copy

Response

// output format
('idOne','idTwo','idThree')
//or
{'idOne','idTwo','idThree'}
//depends on the online version or not

Generate an 'IN' statement for the where clause of a query.

Parameters:

Name Type Description
ids array An array of ids to use in the 'IN' statement.

Returns:

A string 'IN' statement for including in the 'WHERE' statement of query.

Type

string

getObjectLabels(object)

Returns the labels for the list of object names passed in.

Copy

Request

function start() {
queryCRMData();
}

function queryCRMData() {
var queryConfig = ["Medical_Event_vod__c"]

ds.getObjectLabels(queryConfig).then(
function(resp) {
console.log(resp);
printToScreen(resp);
},
function(err) {
console.log(err);
}
);
}

function printToScreen(jsonObj) {
var test = document.getElementById("test");
test.innerHTML = JSON.stringify(jsonObj);
}

document.addEventListener("DOMContentLoaded", function(event) {
start();
});
Copy

Response

{
"success":true,
"Medical_Event_vod__c":[
{
"plural":"Medical Events",
"singular":"Medical Event"
}
]
}

Parameters:

Name Type Description
object array A list of object names for which to retrieve labels.

Returns:

The promise returned when resolved will return the results of the query.

Type

object

getPicklistValueLabels(object, field)

Copy

Request

ds.getPicklistValueLabels(object, field){
"Account" (which is object),  "Career_Status_vod__c" (which is field)
Copy

Response

{
"Account":{
"Career_Status_vod__c":{
"Emerging_vod": "Emerging",
"Peak_vod": "Peak",
"Retired_vod": "Retired"
}
},
    
"command": "queryReturn",
"deferredId": "callback_1482531900000"
}

The getPicklistValueLabels returns the translated label for each of the picklist values of the specified field.

Parameters:

Name Type Description
object string The API Name of the object you wish to query.
field string API Name of the picklist field.

Returns:

The promise returned when resolved will return the results of the query.

Type

promise

getVeevaMessagesWithDefault(tokens, localeKey)

Copy

Request

function start() {
queryCRMData();
}

function queryCRMData() {
var tokens = [
{ msgCategory:"Common", msgName:"UPCOMING"},
]
        
var languageLocaleKey = "en_US";

ds.getVeevaMessagesWithDefault(tokens,languageLocaleKey).then(function(resp){
console.log(resp);
printToScreen(resp);
}, function(err) {
console.log(err);
printToScreen(err);
});
}

function printToScreen(jsonObj) {
var test = document.getElementById("test");
test.innerHTML = JSON.stringify(jsonObj);
}

document.addEventListener("DOMContentLoaded", function(event) {
start();
});
Copy

Response

[
{
"Language_vod__c":{
"value":"en_US",
"display":"en_US",
"dataType":"string",
"label":"Language"
},
"Name":{
"value":"UPCOMING",
"display":"UPCOMING",
"dataType":"string",
"label":"Message Name"
},
"Text_vod__c":{
"value":"Upcoming",
"display":"Upcoming",
"dataType":"string",
"label":"Text"
},
"Category_vod__c":{
"value":"Common",
"display":"Common",
"dataType":"string",
"label":"Category"
}
}
]

The getVeevaMessagesWithDefault method returns the translated value of each of the tokens passed in to the language specified by the localeKey. The tokens must be case sensitive and exactly match the Salesforce record.

Parameters:

Name Type Description
tokens array A list of string tokens to be translated.
localeKey string The name of the locale.

Returns:

The promise returned when resolved will return the results of the query.

Type

object

joinQueries(q1, q2, keyForID, fieldsLabelsToExclude, primaryObjectName)

Copy

Request

// Input
var q1 = {
data: [
{
ID: {
value: "abc",
display: "abc",
dataType: "string",
label: "Record ID"
},
Name: {
value: "productA",
display: "product A",
dataType: "string",
label: "Product Name"
}
}
],
object: {
plural: "Product Catalog",
singular: "Product Catalog",
name: "Product_vod__c"
},
name: "Product_vod__c",
fieldLabels: [
{
name: "ID",
display: "Record ID"
},
{
name: "Name",
display: "Product Name"
}
]
};

var q2 = {
data: [
{
ID: {
value: "1234",
display: "1234",
dataType: "string",
label: "Record ID"
},
Product_vod__c: {
value: "abc",
display: "abc",
dataType: "string",
label: "Product"
}
}
],
object: {
plural: "Sent Email",
singular: "Sent Email",
name: "Sent_Email_vod__c"
},
name: "Sent_Email_vod__c",
fieldLabels: [
{
name: "ID",
display: "Record ID"
},
{
name: "Product_vod__c",
display: "Product"
}
]
};

var keyForID = 'Product_vod__c';

var fieldsLabelsToExclude = {
ID: true,
Product_vod__c: true
};

var primaryObjectName = 'Sent_Email_vod__c';
//input format
Copy

Response

{
data: [
{
ID: {
value: "1234",
display: "1234",
dataType: "string",
label: "Record ID"
},
Product_vod__c: {
value: "abc",
display: "abc",
dataType: "string",
label: "Product"
},
Product_vod__c.ID: {
value: "abc",
display: "abc",
dataType: "string",
label: "Record ID"
},
Product_vod__c.Name: {
value: "productA",
display: "product A",
dataType: "string",
label: "Product Name"
}
}
],
  
fieldLabels: [
{
name: "Product_vod__c.Name",
display: "Product Name"
}
],
  
name: 'Sent_Email_vod__c',
object: {
plural: "Sent Email",
singular: "Sent Email",
name: "Sent_Email_vod__c"
}
}

Join two queries similarly to an SQL outer join.

Parameters:

Name Type Description
q1 object One of the query responses that needs to be joined.
q2 object One of the query responses that needs to be joined.
keyForID string The field name inside the primary query response in which the query response joins based on the ID value.
fieldsLabelsToExclude object A map that contains the API names to exclude from the join result's field labels.
primaryObjectName string The name of the object to indicate the primary query response between q1 and q2.

Returns:

A new object containing the joined queries as a single result set.

Type

object

runQuery(queryConfig)

Copy

Request

function start() {
queryCRMData();
}

function queryCRMData() {
var queryConfig = {
object: "Account",
fields: ["Name"],
limit: 1
};

ds.runQuery(queryConfig).then(
function(resp) {
console.log(resp);
printToScreen(resp);
},
function(err) {
console.log(err);
}
);
}

function printToScreen(jsonObj) {
var test = document.getElementById("test");
test.innerHTML = JSON.stringify(jsonObj);
}

document.addEventListener("DOMContentLoaded", function(event) {
start();
});
Copy

Response

{
"data":[
{
"Name":{
"value":"Morris Area Integrated Phys, Ipa",
"display":"Morris Area Integrated Phys, Ipa",
"dataType":"string",
"label":"Name"
}
}
],
"object":{
"plural":"Accounts",
"singular":"Account",
"name":"Account"
},
"name":"Account",
"fieldLabels":[
{
"name":"Name",
"display":"Name"
}
]
}

Run a query. Fields must only be specified once per query or an error is returned.

Since queries are executed differently on each platform, results may vary for the same query. For more information, see SOQL Condition Expression Syntax for queries on the Online platform and Core Data Predicate Format String Syntax for queries on the iPad and iPhone platforms.

Parameters:

Name Type Description
queryConfig object {object: String, fields: array, where: String, sort: array, limit: String}

Properties

Name Type Description
object string API name of the object to query.
fields array of strings An array of field API Names to return.
where string The where statement without the "where" string. Do not include if empty. Strings are case sensitive in content deployed to iPad. ex: where: "Name = 'Accessing My Insights'"
sort array An array of sort statements without the "order by" string. Do not include if empty. ex: sort: ['LastModifiedDate DESC']
limit number The maximum number of records to return.

Returns:

When resolved, the promise will return the results of the query.

Type

Promise resolves to an object

runQuery(SalesData)

Run a query for Sales Data.

Ensure your administrator deactivates the Contains Goals and Payer Plan Mapped fields, and adds unique column labels on the Data Map Template before configuring, uploading, and syncing the sales data files. This ensures that the appropriate account level sales data is retrieved.

Copy

Request

function start() {
queryCRMData();
}

function queryCRMData() {
var queryConfig = {
object: "Account_Sales_Summary_Insights",
fields: ["Account_Id_vod", "Market_vod", "Product_Group_vod"],
where: "'scale = 'week_vod' AND 'dataType' ='NRx' AND AccountId in {'id1', 'id2', 'id3']",
sort: [],
limit: 1
};

ds.runQuery(queryConfig).then(
function(resp) {
console.log(resp);
printToScreen(resp);
},
function(err) {
console.log(err);
}
);
}

function printToScreen(jsonObj) {
var test = document.getElementById("test");
test.innerHTML = JSON.stringify(jsonObj);
}

document.addEventListener("DOMContentLoaded", function(event) {
start();
});
Copy

Response

{
"Account_Sales_Summary_Insights": [
{
"Account_Id_vod": {
"value": "a00i0000001F4tMAAS",
"display": "a00i0000001F4tMAAS",
"dataType": "string",
"label": "Account Sales Summary Insights"
},
"Market_vod": {
"value": "Cardiology",
"display": "Cardiology",
"dataType": "string",
"label": "Account Sales Summary Insights"
}
},
{
"Product_Group_vod": {
"value": "Cholecap 10mg",
"display": "Cholecap 10mg",
"dataType": "string",
"label": "Account Sales Data Insights"
},
"Sales_Date_vod": {
"value": "201705",
"display": "201705",
"dataType": "string",
"label": "Account Sales Summary Insights"
},
"Sales_Data_vod": {
"value": "101",
"display": "101",
"dataType": "string",
"label": "Account Sales Summary Insights"
}
},
"fieldLabels": [
{
"name": "Product_Group_vod",
"display": "Product Group"
},
{
"name": "Market_vod",
"display": "Market"
},
],
"name": "Account_Sales_Summary_Insights",
"object": {
"plural": "Account Sales Summary Insights'",
"singular": "Account Sales Summary Insights",
"name": "Account_Sales_Summary_Insights_vod"
}
]
}

Object

Name Description
Account_Sales_Summary_Insights Represents the object that contains the Account-level Sales Data.

Where Clause Parameters:

Name Values Description
Scale

required

week_vod or month_vod Defines the time frame that the sales data is aggregated.
DataType

required

TRx or NRx Locates the sales data. Sales data is organized using columns. Column_Label_vod for instance being NRx. However, if the Column_Label_vod is changed to any other value, the datatype query also changes.
Account_ID_vod

required

AccountId Represents the Account ID_vod that links the Account to the Account Object.
Start Date

optional

yyyy-MM-dd Represents the Start Date of the period to query.
End Date

optional

yyyy-MM-dd Represents the End Date of the period to query.
Market Products

optional

Market_vod Represents the Market that the products are grouped. These groups can be queried using their SFDC IDs.
Product Group

optional

Product_Group_vod Represents the Product Name. This can be queried using the SFDC IDs.

Where Clause Requirements:

  • Only the AND operator is supported when defining Scale and Data Type.

  • Only one value is supported when defining Scale, Data Type, startDate and endDate.

Fields (Included, but are not limited to) :

Name API Name
Account ID Account_ID_vod__c
ID ID_vod__c
Market Market_vod__c
Market Salesforce ID Market_Id_vod__c
Product Group Product_Group_vod__c
Product Group Salesforce ID Product_Group_Id_vod__c

Additional fields can be found in the Data_Map_Template_vod and the Sales_Transaction_vod objects.

Output

When the object Account_Sales_Summary_Insights is queried, the system identfies the Sales Data based on the parameters of the where clause. In this instance, the where clause uses Weeks as a scale, NRx as a dataType and id1, id2 and id3 as the Account ID.

The system uses the Data Map Template and the corresponding Analytics File to query the Sales Data table using the Where Clause as a filter.

Users can only use the Account Sales Summary Insights object to query for Sales Data.

querySalesData(queryConfig)

The querySalesdata method returns a promise that is resolved with that single record. This method can only query Account_Sales_Summary_Insights_vod.

Ensure your administrator deactivates the Contains Goals and Payer Plan Mapped fields, and adds unique column labels on the Data Map Template before configuring, uploading, and syncing the sales data files. This ensures that the appropriate account level sales data is retrieved.

The default list of fields returned if user does not specify any fields in the request is: Account_Id_vod__c, ID_vod__c, Market_vod__c, Market_Id_vod__c, Product_Group_vod__c, Product_Group_Id_vod__c, Sales_Date_vod__c, Sales_Data_vod__c.

Copy

Request

function start() {
queryCRMData();
}

function queryCRMData() {
var queryConfig = {
object: "Account_Sales_Summary_Insights",
fields: ["Account_Id_vod__c", "Market_vod__c", "Market_ID_vod__c", "Product_Group_vod__c", "Product_Group_Id_vod__c", "Sales_Date_vod__c", "Sales_Data_vod__c"],
limit: 3
};

ds.querySalesData(queryConfig).then(
function(resp) {
console.log(resp);
printToScreen(resp);
},
function(err) {
console.log(err);
}
);
}

function printToScreen(jsonObj) {
var test = document.getElementById("test");
test.innerHTML = JSON.stringify(jsonObj);
}

document.addEventListener("DOMContentLoaded", function(event) {
start();
});
Copy

Response

{
"success": "true",
"record_count": "2",
"Account_Sales_Summary_Insights": [
{
"Account_Id_vod__c": "0013600000ILOftAAH",
"Market_Id_vod__c": "a0u3600000116RtAAI",
"Market_vod__c": "Mkt1Lvl",
"Product_Group_Id_vod__c": "a0l36000000vV0bAAE",
"Product_Group_vod__c": "Mkt1Lvl-CompetitorProduct_5-NoBDL",
"Sales_Date_vod__c": "2016-06-01",
"Sales_Data_vod__c": "834.042"
},
{
"Account_Id_vod__c": "0013600000ILOftAAH",
"Market_Id_vod__c": "a0u3600000116RtAAI",
"Market_vod__c": "Mkt1Lvl",
"Product_Group_Id_vod__c": "a0l36000000vV0bAAE",
"Product_Group_vod__c": "Mkt1Lvl-CompetitorProduct_5-NoBDL",
"Sales_Date_vod__c": "2017-05-01",
"Sales_Data_vod__c": "908.053"
}
]
}

Parameters:

Name Type Description
queryConfig object {object: String, fields: array, where: String, sort: array, limit: String}

Properties

Name Type Description
object string Name of the object to query
fields array An array of field API Names to return
sort array The sort statement without the “order by” string. Do not include if empty. ex: sort: ['Call_Date_vod__c DESC']
where string The where statement without the "where" string. Do not include if empty. ex: where: "Name = 'Accessing MyInsights'"
limit number The maximum number of records to return

Returns:

The promise returned when resolved returns the results of the query.

Type

promise

queryRecord (queryConfig)

The queryRecord returns a promise that is resolved with that single record. This method returns the rawdata as key value pairs without adding additional metadata (e.x., object labels, field labels etc.) in the returned results. Fields must only be specified once per query or an error is returned.

Since queries are executed differently on each platform, results may vary for the same query. For more information, see SOQL Condition Expression Syntax for queries on the Online platform and Core Data Predicate Format String Syntax for queries on the iPad and iPhone platforms.

Copy

Request

function start() {
queryCRMData();
}

function queryCRMData() {
var queryConfig = {
object: "Account",
fields: ["Name", "Phone", "Fax"],
limit: 3
};

ds.queryRecord(queryConfig).then(
function(resp) {
console.log(resp);
printToScreen(resp);
},
function(err) {
console.log(err);
}
);
}

function printToScreen(jsonObj) {
var test = document.getElementById("test");
test.innerHTML = JSON.stringify(jsonObj);
}

document.addEventListener("DOMContentLoaded", function(event) {
start();
});
Copy

Response

{
"Account":[
{
"Phone":"(973) 586-3400",
"Name":"Morris Area Integrated Phys, Ipa",
"Fax":""
},
{
"Phone":"",
"Name":"Deborah Farabee",
"Fax":""
},
{
"Phone":"",
"Name":"Virginia Krieg",
"Fax":""
}
],
"success":true,
"record_count":3
}

Parameters:

Name Type Description
queryConfig object {object: String, fields: array, where: String, sort: array, limit: String}

Properties

Name Type Description
object string API Name of the object to query
fields array of strings An array of field API Names to return
where string The where statement without the "where" string. Do not include if empty. Strings are case sensitive in content deployed to iPad. ex: where: "Name = 'Accessing MyInsights'"
sort array of strings The sort statement without the “order by” string. Do not include if empty. ex: sort: ['Call_Date_vod__c DESC']
limit number The maximum number of records to return

Returns:

When resolved, the promise will return the results of the query.

Type

Promise resolves to an object

newRecord(configObject)

The newRecord method displays the native interface of the object within Veeva CRM.

Developers can use the newRecord method to create and send Approved Emails (Sent_Email_vod records) from MyInsights. However, only the Account_vod, Approved_Email_Template_vod, and Email_Fragments_vod fields are supported.

HTML

Copy

HTML

<button id="demo" onclick="queryCRMData()"> Launch Call </button>
Copy
Request
function start() {
queryCRMData();
}

function queryCRMData() {
var configObject = {
object: "Call2_vod__c",
fields: {
Account_vod__c: "00161000004vuXMAAY"
}
};

ds.newRecord(configObject).then(
function(resp) {
printToScreen(resp);
},
function(err) {
console.log(err);
}
);
}

function printToScreen(jsonObj) {
var test = document.getElementById("test");
test.innerHTML = JSON.stringify(jsonObj);
}

document.addEventListener("DOMContentLoaded", function(event) {
start();
});

As a useful tip, developers can leverage the getDataForCurrentObject method to pass in the Account ID, ds.getDataForCurrentObject('Account').

Parameters:

Name Type Description
configObject object A configuration object used to pass in required values

Properties

Name Type Description
object string API name of the target object
fields array of strings Object of field API names required to pass in for the application to bring up specified action

Returns:

When the request is successful, the application displays the native interface

viewRecord(configObject)

The viewRecord method navigates to the detail page in Veeva CRM.

When users open the detail page, they can navigate back to their MyInsights report by selecting back, returning to their last viewed screed.

When navigating to MyInsights reports for the first time, the last modified report displays.

Developers can use the viewRecord method to view Sent_Email_vod records from MyInsights.

HTML

Copy

HTML

<button id="demo" onclick="queryCRMData()"> Launch Call </button>
Copy

Request

function start() {
queryCRMData();
}

function queryCRMData() {
var configObject = {
object: "Call2_vod__c",
fields: {Id: "a040U000000UJPUQA4"
};

ds.viewRecord(configObject).then(
function (resp) {
printToScreen(resp);
}, function(err) {
console.log(err);
}
);
}

function printToScreen(jsonObj) {
var test = document.getElementById("test");
test.innerHTML = JSON.stringify(jsonObj);
}

document.addEventListener("DOMContentLoaded", function(event) {
start();
});

Parameters:

Name Type Description
configObject object A configuration object used to pass in required values

Properties

Name Type Description
object string API name of the target object
fields array of strings Object of field API names required to pass in for the application to bring up specified action

Returns:

When the request is successful, the application displays the native interface

getAvailableObjects()

This method retrieves a list of objects for which the user has Read permissions to in their org.

Copy

Request

function start() {
queryCRMData();
}

function queryCRMData() {
ds.getAvailableObjects().then(
function(resp) {
printToScreen(resp);
},
function(err) {
console.log(err);
}
);
}

function printToScreen(jsonObj) {
var test = document.getElementById("test");
test.innerHTML = JSON.stringify(jsonObj);
}

document.addEventListener("DOMContentLoaded", function(event) {
start();
});
Copy

Response

{
"success":true,
"data":{
"Sample_Lot_vod__c":{

},
"User":{

},
"Assortment_vod__c":{

},
"Event_Attendee_vod__c":{

}
},
"record_count":0
}

Parameters:

The default behavior of the method returns a full list of available objects.

Returns:

When the request is successful, the application displays a list of available end-user objects

getObjectMetadata(configObject)

The getObjectMetadata method retrieves the list of fields the user has Read permissions to in a specific object.

Copy

Request

function start() {
queryCRMData();
}

function queryCRMData() {
var configObject = {
object: "Account",
};

ds.getObjectMetadata(configObject).then(
function(resp) {
printToScreen(resp);
},
function(err) {
console.log(err);
}
);
}

function printToScreen(jsonObj) {
var test = document.getElementById("test");
test.innerHTML = JSON.stringify(jsonObj);
}

document.addEventListener("DOMContentLoaded", function(event) {
start();
});
Copy

Response

{
"success":true,
"data":{
"object":"Account",
"fields":[
{
"name":"AHA__c",
"dataType":"string"
},
{
"name":"AccountSource",
"dataType":"picklist"
},
{
"name":"Total_Physicians_Enrolled__c",
"dataType":"double"
},
{
"name":"Total_Revenue_000__c",
"dataType":"currency"
},
{
"name":"Website",
"dataType":"url"
}
]
},
"record_count":153
}

Parameters:

Name Type Description
configObject object

Properties

Name Type Description
object string API name of the target object

Returns:

When the request is successful, the Object API Name, Field API Name and the field type of the Field displays.

getRecordTypeLabels()

The getRecordTypeLabels method returns the record type's API name and record type translated label.

Copy

Request

var objectName = "Account";

ds.getRecordTypeLabels(objectName).then(
function(response){
console.log(response);//example of logging the response
},
function(error){
console.log(error);//example of logging the error 
}
);
Copy

Response


"Account":{
"recordtype_name1":"recordtype_label1"
"recordtype_name2":"recordtype_label2"
}
}

Parameters:

Name Type Description
objectName string API name of the target object

Returns:

When the request is successful, the record type's API name and record type displays.

executeSuggestionAction(SuggestionId,actionType)

The executeSuggestionAction method enables the execution, completion, and dismissal of suggestions.

Example

Copy

Example

ds.executeSuggestionAction(suggestionId, actionType).then(function(resp) {
// success callback
if(resp && resp.success) {
// The operation is completed. The following is an example of refreshing the UI after success:
ds.queryRecord({
object: "Suggestion_vod__c",
fields: ["Title_vod__c", "RecordTypeId", "Posted_Date_vod__c"],
where: "Account_vod__c = _accountId"
}).then(function(resp) {
// Update UI with lastest suggestion response
});
} else {
// The operation is cancelled
}
}, function(error) {
// The operation was interrupted due to an internal error 
});

Parameters:

Name Type Description
SuggestionId string 18-character SFDC ID of the Suggestion record
actionType string Supports the following values:
  • complete - Marks the suggestion as complete
  • dismiss - Dismisses the suggestion
  • execute - The default action, if left blank. Executes the suggestion based on the Suggestion Type. Supported Types are:
    • Call_Objective_vod
    • Call2_vod
    • Email_vod

Returns:

When the request is successful, the desired action is made against the specified suggestion.

The list of suggestions displayed to the user should be active suggestions that have not yet been dismissed, executed, or marked as complete.

launchMediaForAccount(account, presentationId, keyMessageMediaFileName)

The launchMediaForAccount method enables launching a specific key message in a CLM presentation directly from MyInsights content or launching the CLM media library.

Launching a CLM Presentation to a Specific Slide

Copy

Launching a CLM Presentation to a Specific Slide

ds.launchMediaForAccount("acct","MyPresentation","HomePage");
//Launches the CLM presentation with a Presentation_Id_vod field of "MyPresentation"
//and goes directly to the Key Message in that presentation with a Media_File_Name_vod of "HomePage".
//The presentation is logged against the Account with an SFC ID of "acct".

Launching the CLM Library

Copy

Launching the CLM Library

ds.launchMediaForAccount("acct");
//Navigates to the CLM library to select the appropriate CLM presentation.
//The presentation is logged against the Account with an SFDC ID of "acct".

Parameters:

Name Type Description
account string ID of the Account
presentationId string Enter the Presentation_Id_vod field of the CLM_Presentation_vod record you want to launch
keyMessageMediaFileName string Enter the Media_File_Name_vod field of the Key_Message_vod record to directly open

The presentationId and keyMessageFileName parameters must be used together. Either both are populated or both are blank.

Returns:

When the request is successful, the specified CLM presentation displays. If the keyMessageMediaFileName parameter is populated with a valid Key Message, the presentation opens directly to that Key Message.

If the presentationId and keyMessageMediaFileName parameters are blank, a successful request displays the CLM Library instead, enabling users to select the presentation to display.

getCurrentPosition()

Returns the geographic location of the user’s device, enabling developers to use the location values to create content which help users plan activities, for example, by marking the device’s location on a map (for example, Google Maps), comparing and displaying distances to account locations, or creating a location log. See Requesting Location via MyInsights for more information.

This method supports asynchronous calls.

For iPad and iPhone devices, location data returned from this method remains cached for 2 minutes. If a request is made within 2 minutes of the previous request, the method returns the cached location data.

Copy

Request

ds.getCurrentPosition();
//Queries the device's current location coordinates from Veeva CRM
//CRM returns location data received from the device's internal GPS
Copy

Success Response

{
"success": true,
"coordinates": {
"latitude": 37.804363,
"longitude":-122.271111,
"accuracy": 4},
"timestamp": 1533729980953.91
}
Copy

Failure Response

{
"success": false,
"message": "No Access Granted",
"code": 61
}

Returns:

When the request is successful, the promise returns the results of the query, including:

  • Timestamp
  • Latitude
  • Longitude
  • Accuracy

Error Messages:

Error Message Code Scenario
Request Failed 0 The location request failed due to a system error.
No Access Granted 61 The user has not granted access to the app to use the location or access is denied.
Location Unavailable 62 GPS is not enabled or the location is unavailable for other reasons including poor cellular connection.

createRecord(configObject)

Creates a record for the specified object directly from MyInsights content. See Inline Editing for MyInsights Content for more information.

Note: The following fields cannot be created on a record for any object:

  • Last_Device_vod__c

  • Mobile_Created_Datetime_vod__c

  • Mobile_Last_Modified_Datetime_vod__c

  • MyInsights_Modified_By_vod__c

  • OwnerId

Example

Copy

createRecord(configObject)

function start() {
queryCRMData();
}

function queryCRMData() {
var configObject = {
object: "MyInsights_Data_vod__c",
fields: {
"HTML_Report_vod__c": "a060U000000ERGFQA8",
"Mobile_ID_vod__c": "a040U000000UJPUQA4",
"Custom_Field__c": "value"
}
};

ds.createRecord(configObject).then(
function(resp) {
console.log(resp);
printToScreen(resp);
},
function(err) {
console.log(err);
}
);
}

function printToScreen(jsonObj) {
var test = document.getElementById("test");
test.innerHTML = JSON.stringify(jsonObj);
}

document.addEventListener("DOMContentLoaded", function(event) {
start();
});

Parameters:

Name Type Description
configObject object {object: string, fields: object}

Properties:

Name Type Description
object string The API name of the object to create.
fields object Key-values pair of the API names of fields and the values to store in each field.

Returns:

When the request is successful, the method returns the ID of the created record.

updateRecord(configObject)

Updates fields on the specified record directly from MyInsights content. See Inline Editing for MyInsights Content for more information.

On the online platform, calling updateRecord always updates the Last Modified and Last Modified By fields on the record. The Last Modified time matches the time of the update.

On offline platforms, calling updateRecord only updates the Last Modified and Last Modified By fields when data on the record is changed. The Last Modified time matches the time of the sync.

Note: The following fields cannot be updated on a record for any object:

  • Last_Device_vod__c

  • Mobile_Created_Datetime_vod__c

  • Mobile_Last_Modified_Datetime_vod__c

  • MyInsights_Modified_By_vod__c

  • OwnerId

Example

Copy

updateRecord(configObject)

function start() {
queryCRMData();
}

function queryCRMData() {
var configObject = {
object: "MyInsights_Data_vod__c",
id: "a040U000000UJPUQA4",
fields: {
"Custom_Field1__c": "newValue1",
"Custom_Field2__c": "newValue2"
}
};

ds.updateRecord(configObject).then(
function(resp) {
console.log(resp);
printToScreen(resp);
},
function(err) {
console.log(err);
}
);
}

function printToScreen(jsonObj) {
var test = document.getElementById("test");
test.innerHTML = JSON.stringify(jsonObj);
}

document.addEventListener("DOMContentLoaded", function(event) {
start();
});

Parameters:

Name Type Description
configObject object {object: string, fields: object}

Properties:

Name Type Description
object string The API name of the object to update. Ignored by Lightning.
id string The Mobile ID or Salesforce ID of the record to update. Used by Lightning to determine the object.
fields object Key-values pair of the API names of fields and the values to store in each field.

Returns:

When the request is successful, the method returns the ID of the updated record.

getSFDCSessionID()

Returns data about the current Salesforce session and org, including a valid Salesforce session ID. This ID cannot be used to authenticate to an external application. Developers must pass this ID into a customer-defined authentication process accepted by the specified external application. See Integrating External Data with MyInsights for more information.

For customers using OAuth to sign into Salesforce, this method can also be used to retrieve OAuth access tokens. Customers should ensure their IDPs are configured to allow access tokens to directly access external applications.

Example

Copy

getSFDCSessionID( )

ds.getSFDCSessionID();
Copy

Success Response

{
"success": true,
"messageId": 42,
"data": {
"sessionId": "The SFDC Session ID as a text string",
"instanceURL": "https://CSXXX.salesforce.com",
"isSandbox": false
}
}
Copy

Failure Response

{
"success": false,
"messageId": 42,
"code": 72,
"message": "The request returned an invalid Session ID and the system did not provide a new one."
}

Error Messages:

Message Code Description
Unable to Refresh Token 52 Refresh token expired or system is unable to provide new token due to any external reasons.
No Internet Connection. Unable to Refresh Token. 53 System is unable to establish connection with IDP.
Unable to obtain valid Session ID 72 The request returned an invalid Session ID and the system did not provide a new one.
No Internet connection. Unable to validate Session ID 73 The device is not connected to the internet and the Session ID cannot be validated.

Returns:

When the request is successful, the promise returns a JSON object containing the valid Salesforce session ID as a string, the Salesforce instance URL, and a boolean value to determine if the org is a sandbox.

request(configObject)

Returns data requested from the specified external application. This method can be called multiple times to send parallel requests. See Integrating External Data with MyInsights for more information.

To successfully request data online, developers must ensure the specified external application allows cross-origin requests from SFDC.

On the Windows platform, using this method to download large files in MyInsights content may cause an error.

On the Online platform, the object passed in as the argument must be a string. Developers can use JSON.stringify to convert objects into strings.

Example

Copy

request(configObject)

function start() {
queryExtData();
}

function queryExtData() {
var configObject = {
url: "http://example.com",
method: "GET",
headers: {
"Accept-Language": "en-US",
"Other-Header": "etc"
},
body: "example body",
timeout: 30,
expect: "text"
};

ds.request(configObject).then(
function(resp) {
console.log(resp);
printToScreen(resp);
},
function(err) {
console.log(err);
});
}

function printToScreen(jsonObj) {
var test = document.getElementById("test");
test.innerHTML = JSON.stringify(jsonObj);
}

document.addEventListener("DOMContentLoaded", function(event) {
start();
});

Parameters:

Name Type Description
configObject object A configuration object used to pass in required values for the defined properties.

Properties:

Name Type Description
url string The URL to which to send the request. Required.
method string The HTTP method to use for the request. Default is GET. The TRACE method cannot be used for the Windows platform. Optional.
headers object A list of HTTP headers to include with the request. All values must be strings. Optional.
body string, object The body data to include with the request. Optional.
timeout number The number of seconds to wait for a response before expiring the request. Default is 30. Optional.
expect "text", "blob" Defines whether the response body should be interpreted as text or a binary file. Default is text. If the expect value is text but the returned value is not text, the Windows and Online platforms return nonsense text. Optional.

Returns:

When the request is successful, the promise returns a JSON object containing the requested data as a string.

queryVDSRecord(queryConfig)

Returns data records from Nitro.

When querying Nitro data from MyInsights content for Lightning, date fields are returned as Unix timestamps, not ISO8601 date strings.

Since queries are executed differently on each platform, results may vary for the same query. For more information, see SOQL Condition Expression Syntax for queries on the Online platform and Core Data Predicate Format String Syntax for queries on the iPad and iPhone platforms.

Example

Copy
queryVDSRecord(queryConfig)
var queryConfig = {
object: "name_of_some_nitro_table",
fields: ["a_field", "another_field"],
limit: 100,
sort: ["a_third_field ASC"],
where: "example_rolling_week_num < 2"
};

ds.queryVDSRecord(queryConfig).then(handleSuccess,handleFailure);

Parameters:

Name Type Description
queryConfig object {object: String, fields: array, where: String, sort: array, limit: String}

Properties

Name Type Description
object string API Name of the data table to query
fields array of strings An array of column API Names to return
where string The where statement without the "where" string. Do not include if empty.
sort array of strings The sort statement without the “order by” string. Do not include if empty.
limit number The maximum number of records to return

Returns:

When the query is successful, the promise returns the results of the query.