SSJS Enablement - Session 2


 SSJS Enablement - Session 2





        Example 1 :

                Write SSJS Script to retrieve Account Details and store them in a data extension :

        Solution :

                  To store the details, we need to know the Account (Object) properties, you can get those properties here.

Based on these properties, we would create a data extension.



            Now, let us create an SSJS Script to retrieve Account object details :


<script runat="server" language="Javascript">
  Platform.Load("Core","1");
  try{
   
    //Retrieve Account Details
    var getAcct = Account.Retrieve();
   
   // Write(Stringify(getAcct));
    Write('\n' + 'Get the account name \n')
   
    Write('Name :'+getAcct[0].Name +'\n' );
    Write('ID :'+getAcct[0].ID +'\n' );
    Write('AccountType :'+getAcct[0].AccountType +'\n' );
    Write('BusinessName :'+getAcct[0].BusinessName +'\n' );
    Write('CustomerKey :'+getAcct[0].CustomerKey + '\n' );
    Write('Address :'+getAcct[0].Address + '\n' );
    Write('City :'+getAcct[0].City + '\n' );
    Write('State :'+getAcct[0].State + '\n' );
    Write('Country :'+getAcct[0].Country + '\n' );
   
  }
  catch(ex){
    Write(ex.message);
  }
</script>

    Let's create an email, paste this code and try to  preview test :

   


    An exception is caught. We can't use the "Retrieve" function in emails especially when we try to preview & test.


So, let's create a code resource of type Javascript and paste the above code snippet. Also, let's save and publish it. Hit the code resource URL and validate if it works.


Bingo! it works! Now, let's update our code to store the account details we retrieved into a data extension:

<script runat="server" language="Javascript">
  Platform.Load("Core","1");
  try{
   
    //Retrieve Account Details
    var getAcct = Account.Retrieve();
   
   // Write(Stringify(getAcct));
    Write('\n' + 'Get the account name \n')
   
    Write('Name :'+getAcct[0].Name +'\n' );
    Write('ID :'+getAcct[0].ID +'\n' );
    Write('AccountType :'+getAcct[0].AccountType +'\n' );
    Write('BusinessName :'+getAcct[0].BusinessName +'\n' );
    Write('CustomerKey :'+getAcct[0].CustomerKey + '\n' );
    Write('Address :'+getAcct[0].Address + '\n' );
    Write('City :'+getAcct[0].City + '\n' );
    Write('State :'+getAcct[0].State + '\n' );
    Write('Country :'+getAcct[0].Country + '\n' );
   
    //Store the details in a data extension
    var accountDE = DataExtension.Init("DataExtensionExternalKey");
    accountDE.Rows.Add(
                         {
                            Name:getAcct[0].Name
                           ,ID:getAcct[0].ID
                           ,AccountType:getAcct[0].AccountType
                           ,BusinessName:+getAcct[0].BusinessName
                           ,CustomerKey:getAcct[0].CustomerKey
                           ,Address:getAcct[0].Address
                           ,City:getAcct[0].City
                           ,State:getAcct[0].State
                           ,Country:getAcct[0].Country
                         }
    );
   
  }
  catch(ex){
    Write(ex.message);
  }
</script>

Save and Publish the code resource, and validate the code by hitting the URL.

You may also create a script activity and add the script activity in your automation and validate.




 Example 2 :

                Write SSJS Script to retrieve Account User Details and store them in a data extension :



            <script runat="server" language="Javascript">

          Platform.Load("Core","1");
  try{
   
    //Retrieve Account User Details
    var getAcctUser = AccountUser.Retrieve();
    var accountUserDE = DataExtension.Init("AccountUserDetailsDE");
   
    //Write(Stringify(getAcctUser));
   
    Write('\n' + 'Get the account user details : \n \n')
    for(var i=0; i<getAcctUser.length; i++) {
      Write('Name :'+getAcctUser[i].Name +'\n' );
      Write('MID :'+getAcctUser[i].ID +'\n' );
      Write('AccountUserID :'+getAcctUser[i].AccountUserID +'\n' );
      Write('CustomerKey :'+getAcctUser[i].CustomerKey +'\n' );
      Write('UserID :'+getAcctUser[i].UserID +'\n' );
      Write('MustChangePassword :'+getAcctUser[i].MustChangePassword +'\n' );
      Write('IsAPIUser :'+getAcctUser[i].IsAPIUser +'\n' );
      Write('CreatedDate :'+getAcctUser[i].CreatedDate +'\n' );
      Write('ModifiedDate :'+getAcctUser[i].ModifiedDate +'\n' );
      Write('------------------------------------------------\n');
     
       //Store the details into a data extension
       accountUserDE.Rows.Add(
                         {
                            Name:getAcctUser[i].Name
                           ,MID:getAcctUser[i].ID
                           ,AccountUserID:getAcctUser[i].AccountUserID
                           ,CustomerKey:+getAcctUser[i].CustomerKey
                           ,UserID:getAcctUser[i].UserID
                           ,MustChangePassword:getAcctUser[i].MustChangePassword
                           ,IsAPIUser:getAcctUser[i].IsAPIUser
                           ,CreatedDate:getAcctUser[i].CreatedDate
                           ,ModifiedDate:getAcctUser[i].ModifiedDate
                         }
    );
  }
   
   
  }
  catch(ex){
    Write(ex.message);
  }
</script>


 Example 3 :

          Write SSJS Script to retrieve Data Extension Details and store them in a data extension :

            <script runat="server" language="Javascript">
  Platform.Load("Core","1");
  try{
   
    //Retrieve Data Extension  Details
    var dataExtensions = DataExtension.Retrieve();
    var dataExtensionsDE = DataExtension.Init("Data Extension Details DE");
   
       //Write(Stringify(dataExtensions));
      for(var i=0; i<dataExtensions.length; i++) {
      Write('Name :'+dataExtensions[i].Name +'\n' );
      Write('Description :'+dataExtensions[i].Description +'\n' );
      Write('IsSendable :'+dataExtensions[i].IsSendable +'\n' );
      Write('IsTestable :'+dataExtensions[i].IsTestable +'\n' );
      Write('CategoryID :'+dataExtensions[i].CategoryID +'\n' );
      Write('IsPlatformObject :'+dataExtensions[i].IsPlatformObject +'\n' );
      Write('CustomerKey :'+dataExtensions[i].CustomerKey +'\n' );
      Write('CreatedDate :'+dataExtensions[i].CreatedDate +'\n' );
      Write('ModifiedDate :'+dataExtensions[i].ModifiedDate +'\n' );
      Write('ObjectID :'+dataExtensions[i].ObjectID +'\n' );
      Write('SendableDataExtensionField :'+
            Stringify(dataExtensions[i].SendableDataExtensionField) +'\n' );
      Write('SendableSubscriberField :'+
                Stringify(dataExtensions[i].SendableSubscriberField) +'\n' );
      Write('------------------------------------------------\n');
     
       //Store the details into a data extension
       dataExtensionsDE.Rows.Add(
                         {
                            Name:dataExtensions[i].Name
                           ,Description:dataExtensions[i].Description
                           ,IsSendable:dataExtensions[i].IsSendable
                           ,IsTestable:dataExtensions[i].IsTestable
                           ,CategoryID:dataExtensions[i].CategoryID
                           ,IsPlatformObject:dataExtensions[i].IsPlatformObject
                           ,CustomerKey:dataExtensions[i].CustomerKey
                           ,CreatedDate:dataExtensions[i].CreatedDate
                           ,ModifiedDate:dataExtensions[i].ModifiedDate
                           ,ObjectID:dataExtensions[i].ObjectID
                           ,SendableDataExtensionField:
                            Stringify(dataExtensions[i].SendableDataExtensionField)
                           ,SendableSubscriberField:
                            Stringify(dataExtensions[i].SendableSubscriberField)
                         }
    );
  }
   
  }
  catch(ex){
    Write(ex.message);
  }
</script>

 Example 4 :

            Write SSJS Script to retrieve Data Extension Fields

<script runat="server" language="Javascript">
  Platform.Load("Core","1");
  try{
   
    //Retrieve Data Extension  Details
    var myDE = DataExtension.Init("DD0DC615-2A64-4F4E-A7D3-781449B14CF8");
    var fields =  myDE.Fields.Retrieve();
   
   // Write(Stringify(fields));
    for(var i=0; i<fields.length; i++) {
      Write('Name :'+fields[i].Name +'\n' );
      Write('ObjectID :'+fields[i].ObjectID +'\n' );
      Write('FieldType :'+fields[i].FieldType +'\n' );
      Write('IsPrimaryKey :'+fields[i].IsPrimaryKey +'\n' );
      Write('MaxLength :'+fields[i].MaxLength +'\n' );
      Write('Ordinal :'+fields[i].Ordinal +'\n' );
      Write('DefaultValue :'+fields[i].DefaultValue +'\n' );
      Write('StorageType :'+fields[i].StorageType +'\n' );
      Write('------------------------------------------------\n');
    }
  }
  catch(ex){
    Write(ex.message);
  }
</script>

 Example 5: Write an SSJS to retrieve tracking information about the Business Unit 

<script runat="server" language="Javascript">
  Platform.Load("Core","1");
  try{
    var filter={
      Property:"CustomerKey"
      ,SimpleOperator:"equals"
      ,Value:"XXXX-XXXX-XXX-XXX-XXXXXXX"
    };
    var acctTracking = Account.Tracking.Retrieve(filter);
    //Write(Stringify(acctTracking));
   
    Write('\n \n Write Tracking information about the account :\n \n');
    var trackingDE = DataExtension.Init("Tracking");
   
    for(var i=0;i<acctTracking.length;i++)
    {
      Write("Sends :  \n");
      Write("\t \t Total :" + acctTracking[i].Sends.Total +"\n");
      Write("Bounces :  \n");
      Write("\t \t Total :" + acctTracking[i].Bounces.Total +"\n");
      Write("\t \t HardBounces :" + acctTracking[i].Bounces.HardBounces +"\n");
      Write("\t \t SoftBounces :" + acctTracking[i].Bounces.SoftBounces +"\n");
      Write("\t \t BlockBounces :" + acctTracking[i].Bounces.BlockBounces +"\n");
      Write("\t \t TechnicalBounces:" +acctTracking[i].Bounces.TechnicalBounces +"\n");
      Write("\t \t UnknownBounces :" + acctTracking[i].Bounces.UnknownBounces +"\n");
      Write("Clicks :  \n");
      Write("\t \t Total :" + acctTracking[i].Clicks.Total +"\n");
      Write("\t \t Unique :" + acctTracking[i].Clicks.Unique +"\n");
      Write("Opens :  \n");
      Write("\t \t Total :" + acctTracking[i].Opens.Total +"\n");
      Write("\t \t Unique :" + acctTracking[i].Opens.Unique +"\n");
      Write("Unsubscribes :  \n");
      Write("\t \t Unique :" + acctTracking[i].Unsubscribes.Unique +"\n");
     
       //Store the details into a data extension
       trackingDE.Rows.Add(
                         {
                            TotalSends:acctTracking[i].Sends.Total
                           ,HardBounces:acctTracking[i].Bounces.HardBounces
                           ,SoftBounces:acctTracking[i].Bounces.SoftBounces
                           ,BlockBounces:+acctTracking[i].Bounces.BlockBounces
                           ,TechnicalBounces: acctTracking[i].Bounces.TechnicalBounces
                           ,TotalClicks:acctTracking[i].Clicks.Total
                           ,UniqueClicks:acctTracking[i].Clicks.Unique
                           ,TotalOpens:acctTracking[i].Opens.Total
                           ,UniqueOpens:acctTracking[i].Opens.Unique
                           ,Unsubscribes:acctTracking[i].Unsubscribes.Unique
                         }
    );
    }
  }
  catch(ex){
    Write(ex.message);
  }
</script>


Example 6:  Write an SSJS to retrieve all timezones


<script runat="server" language="Javascript">
    Platform.Load("core","1");
    try{
    var timezones =DateTime.TimeZone.Retrieve();
    //Write(Stringify(timezones)+'\n');
    Write(' All timezones : \n \n' );
    for(var i=0;i<timezones.length;i++)
    {
        Write('\n');
    Write('Name :' + timezones[i].Name + '\n');
    }
  }
    catch(ex){
        Write(ex.message);
  }
</script>

Example 7:  SSJS Enablement Session 2 Level Up


<script runat="server" language="Javascript">
  Platform.Load("Core","1");
 
  // * ==== Retrieve functions for Salesforce Marketing Cloud Starts here ===== *//
  function RetrieveAccount()
  {
    var getAcct = Account.Retrieve();
    return getAcct;
  }
 
 
  function RetrieveAccountUser()
  {
    var getAcctUser = AccountUser.Retrieve();
    return getAcctUser;
  }
 
   function RetrieveDataExtensions()
  {
    var dataExtensions = DataExtension.Retrieve();
    return dataExtensions;
  }
  // * == Retrieve functions for Salesforce Marketing Cloud ends here =============*//
  // * ============================================================================*//
 
 
 
  // * ============================================================================*//
  // * Data Extension Add Row functions for Salesforce Marketing Cloud Starts here *//
 
  function AddAccountRecords(customerKey,records)
  {
    var accountDE = DataExtension.Init(customerKey);
    accountDE.Rows.Add(
                         {
                            Name:records[0].Name
                           ,ID:records[0].ID
                           ,AccountType:records[0].AccountType
                           ,BusinessName:+records[0].BusinessName
                           ,CustomerKey:records[0].CustomerKey
                           ,Address:records[0].Address
                           ,City:records[0].City
                           ,State:records[0].State
                           ,Country:records[0].Country
                         }
    );
  }
 
  function AddAccountUserRecords(customerKey,records)
  {
    var accountUserDE = DataExtension.Init(customerKey);
   
    for(var i=0; i<records.length; i++) {
    accountUserDE.Rows.Add(
                         {
                            Name:records[i].Name
                           ,MID:records[i].ID
                           ,AccountUserID:records[i].AccountUserID
                           ,CustomerKey:+records[i].CustomerKey
                           ,UserID:records[i].UserID
                           ,MustChangePassword:records[i].MustChangePassword
                           ,IsAPIUser:records[i].IsAPIUser
                           ,CreatedDate:records[i].CreatedDate
                           ,ModifiedDate:records[i].ModifiedDate
                         }
                       );
    }
  }
 
  function AddDataExtensionProperties(customerKey,records)
  {
    var dataExtensionsDE = DataExtension.Init(customerKey);
    for(var i=0; i<records.length; i++) {
       dataExtensionsDE.Rows.Add(
                         {
                            Name:records[i].Name
                           ,Description:records[i].Description
                           ,IsSendable:records[i].IsSendable
                           ,IsTestable:records[i].IsTestable
                           ,CategoryID:records[i].CategoryID
                           ,IsPlatformObject:records[i].IsPlatformObject
                           ,CustomerKey:records[i].CustomerKey
                           ,CreatedDate:records[i].CreatedDate
                           ,ModifiedDate:records[i].ModifiedDate
                           ,ObjectID:records[i].ObjectID
                           ,SendableDataExtensionField:
                            Stringify(records[i].SendableDataExtensionField)
                           ,SendableSubscriberField:
                             Stringify(records[i].SendableSubscriberField)
                         }
    );
    }
  }
 
  // * Data Extension Add Row functions for Salesforce Marketing Cloud Ends here *//
  // * ===-========================================================================*//
 
 
 
  // * ============================================================================*//
  // * Demonstrate how we can level up and build a use case for SSJS   *//
  // * SSJS Enablement Session 2                                                   *//
  // * Date : 10th June 2023                                                      *//
  // * ============================================================================*//
 
  try{
    var getAcct=RetrieveAccount();
    var acctCustomerKey = Platform.Function.Lookup(
                                                    'ObjectsConfig'
                                                    ,'CustomerKey'
                                                    ,'ObjectName'
                                                    ,'Account'
                                                );
    AddAccountRecords(acctCustomerKey,getAcct);
   
    var getAcctUser=RetrieveAccountUser();
    var acctUserCustomerKey = Platform.Function.Lookup(
                                                        'ObjectsConfig'
                                                        ,'CustomerKey'
                                                        ,'ObjectName'
                                                        ,'AccountUser'
                                                       );
    AddAccountUserRecords(acctUserCustomerKey,getAcctUser);
   
    var dataExtensions=RetrieveDataExtensions();
    var dataExtensionsCustomerKey = Platform.Function.Lookup(
                                                             'ObjectsConfig'
                                                             ,'CustomerKey'
                                                             ,'ObjectName'
                                                             ,'DataExtension'
                                                             );
    AddDataExtensionProperties(dataExtensionsCustomerKey,dataExtensions)
   
    Write("Operation compelted successfully");
  }
  catch(ex){
    Write(ex.message +'\n');
    Write(ex.description +'\n');
  }
</script>




Next Session 3 Coming soon .....

Preference Center





Comments

Most Viewed

CLOUD PAGE ENABLEMENT - PART 1

EMAIL NOT SENT IN JOURNEY BUILDER

CONSIDERATIONS FOR JOURNEY BUILDER

Understanding Transactional Messaging

Preference Center Demystified


Knowledge Article

Popular Posts

CLOUD PAGE ENABLEMENT - PART 1

EMAIL NOT SENT IN JOURNEY BUILDER

CONSIDERATIONS FOR JOURNEY BUILDER

Understanding Transactional Messaging

Preference Center Demystified

Journey Builder REST API Documentation

Share with Friends

Disclaimer:

The information provided on this technical blog is for general informational purposes only. As a SFMC (Salesforce Marketing Cloud) Technical Architect, I strive to offer accurate and up-to-date content related to SFMC and its associated technologies. However, please note that technology is constantly evolving, and the information provided may become outdated or inaccurate over time.

The content published on this blog represents my personal views and experiences as a SFMC Technical Architect and does not necessarily reflect the official views or opinions of any organization or employer I may be affiliated with.

While I make every effort to ensure the accuracy and reliability of the information presented, I cannot guarantee its completeness, suitability, or applicability to your specific circumstances. Therefore, it is essential to verify any information provided and make your own independent assessments or seek professional advice if needed.

Furthermore, any actions taken based on the information provided on this blog are at your own risk. I shall not be held liable for any damages, losses, or inconveniences arising from the use of the information presented here.

Please keep in mind that SFMC and its associated technologies are complex and require technical expertise for proper implementation and management. It is recommended to consult with qualified professionals or official SFMC documentation for comprehensive guidance.

Finally, please note that any product or company names mentioned on this blog are trademarks or registered trademarks of their respective owners. The mention of these trademarks or registered trademarks does not imply any endorsement or affiliation with the blog.

By accessing and using this blog, you agree to the terms of this disclaimer. If you do not agree with any part of this disclaimer, please refrain from using this blog.