RESTlet Script

Retslets are activate when external application calls it 

get, put, post, delete 

requires authorization  

  

Restlet entry points 

post-create 

put-update 

  

get, delete -parameters is sent through url 

  

function get(requestParams) 

requestParams is form external apk 

  

tba 

ceate a new role 

give permissions 

assign the role to user 

creaye an integration record 

create token and token secret 

  

u can create an environment in postman to save the keys for future use 

 

๐Ÿงพ RESTlet Script Overview 

๐Ÿ”— Activation 

  • RESTlets are activated when an external application calls them. 
  • Supported HTTP methods: GET, PUT, POST, DELETE. 
  • Requires authorization. 

 

๐Ÿšช RESTlet Entry Points 

  • POST โ†’ Create 
  • PUT โ†’ Update 
  • GET, DELETE โ†’ Parameters are sent through the URL 

 

๐Ÿง  Function Signature 

function get(requestParams) 

 

  • requestParams is from external application (APK) 

 

๐Ÿ” Token-Based Authentication (TBA) Setup 

  1. Create a new role. 
  2. Give necessary permissions. 
  3. Assign the role to the user. 
  4. Create an integration record. 
  5. Create token and token secret. 
  6. Setup Postman  

 

Give the external URL of the restlet deployment into the get URL. 

Example: 

Create a POST API endpoint for generating customer statement PDFs in the file cabinet. 

Execution model: 

Create a POST Restlet API endpoint with the following request body: 

“folder name”: {unique value}, 

“email address”: {email address}, 

“startDate”: {Date value} 

When performing the API request from a third-party application, the Restlet code needs to fetch the request body first, then check for duplicate folder names. If the folder name already exists, return a response stating that the folder name already exists. 

If the folder with the name does not exist, create a new folder and identify all customers in the NetSuite account. Prepare the customer statement PDF using the start date from the request body field for each customer. Each customer’s customer statement PDF file needs to be stored in the newly created folder with a filename. The filename will be “customer’s-internalid_timestamp”. 

After performing the all customer’s customer statement PDF creations in the background, send an email notification to the given email address in the API request body. The email author must be the admin of the account. The subject and body can be used valid sentence. 

/** 

 * @NApiVersion 2.1 

 * @NScriptType Restlet 

 */ 

define([‘N/email’, ‘N/runtime’, ‘N/search’, ‘N/record’, ‘N/render’, ‘N/format’], 

 

    (email, runtime, search, record, render, format) =>

        /** 

         * Defines the function that is executed when a POST request is sent to a RESTlet. 

         * @param {string | Object} requestBody – The HTTP request body; request body is passed as a string when request 

         *     Content-Type is ‘text/plain’ or parsed into an Object when request Content-Type is ‘application/json’ (in which case 

         *     the body must be a valid JSON) 

         * @returns {string | Object} HTTP response body; returns a string when request Content-Type is ‘text/plain’; returns an 

         *     Object when request Content-Type is ‘application/json’ or ‘application/xml’ 

         * @since 2015.2 

         */ 

        const post = (requestBody) =>

            try

                var folderName = requestBody[‘folder name’]; 

                var emailAddress = requestBody[’email address’]; 

                var startDateStr = requestBody[‘startDate’]; 

 

                if (!folderName || !emailAddress || !startDateStr) { 

                    return { status: ‘error’, message: ‘Missing required fields.’ }; 

                } 

 

                // Check for duplicate folder 

                var folderSearch = search.create({ 

                    type: search.Type.FOLDER

                    filters: [[‘name’, ‘is’, folderName]], 

                    columns: [‘internalid’

                }); 

 

                var folderExists = false

                var folderId

 

                folderSearch.run().each(function (result) { 

                    folderExists = true

                    folderId = result.getValue(‘internalid’); 

                    return false

                }); 

 

                if (folderExists) { 

                    return { status: ‘error’, message: ‘Folder name already exists.’ }; 

                } 

 

                // Create new folder 

                var newFolder = record.create({ type: record.Type.FOLDER }); 

                newFolder.setValue({ fieldId: ‘name’, value: folderName }); 

                folderId = newFolder.save(); 

 

                // Search all customers (limited to 5) 

                var customerSearch = search.create({ 

                    type: search.Type.CUSTOMER

                    filters: [[‘isinactive’, ‘is’, ‘F’]], 

                    columns: [‘internalid’

                }); 

 

                // Ensure timestamp and startDate are in MMDDYYYY format 

                function formatMMDDYYYY(d) { 

                    // Accept a Date object or a parsable date string; convert to Date if necessary 

                    if (!(d instanceof Date)) { 

                        d = new Date(d); 

                    } 

                    // If conversion failed, fallback to current date 

                    if (isNaN(d.getTime())) { 

                        d = new Date(); 

                    } 

                    var mm = String(d.getMonth() + 1).padStart(2, ‘0’); 

                    var dd = String(d.getDate()).padStart(2, ‘0’); 

                    var yyyy = d.getFullYear(); 

                    return mm + ‘/’ + dd + ‘/’ + yyyy

                } 

 

                var timestamp = formatMMDDYYYY(new Date()); 

                var startDate = formatMMDDYYYY(startDateStr); 

 

                var processed = 0

                customerSearch.run().each(function (result) { 

                    if (processed >= 5) return false

                    processed++

 

                    var customerId = Number(result.getValue(‘internalid’)); 

 

                    // Generate statement PDF using render.statement 

                    // ensure statementDate is passed as a formatted string (expected by render.statement) 

                    var statementDateStr = format.format({ value: new Date(), type: format.Type.DATE }); 

                    var statementPdf = render.statement({ 

                        entityId: customerId

                        printMode: render.PrintMode.PDF

                        inCustLocale: true

                        consolidateStatements: false

                        startDate: startDate

                        statementDate: timestamp 

                    }); 

 

                    statementPdf.folder = folderId

                    statementPdf.save(); 

 

                    return true

                }); 

 

                // Send email notification 

                var adminId = runtime.getCurrentUser().id

 

                email.send({ 

                    author: adminId

                    recipients: emailAddress

                    subject: ‘Customer Statements Generated’

                    body: ‘All customer statements have been generated and saved in the folder: ‘ + folderName 

                }); 

 

                return { status: ‘success’, message: ‘Statements generated and email sent.’ }; 

 

            } catch (e) { 

                log.error(‘Error in doPost’, e); 

                return { status: ‘error’, message: e.message }; 

            } 

        } 

 

        return { post

 

    }); 

 

 

๐Ÿงพ Purpose 

Generates customer statement PDFs for up to 5 active customers, saves them in a newly created folder, and sends an email notification. 

 

๐Ÿ”ง Workflow Summary 

  1. Input Validation  
  2. Checks for required fields in the POST request: 
  3. folder name 
  4. email address 
  5. startDate 
  6. Folder Handling 
  7. Searches for an existing folder with the same name. 
  8. If found, returns an error. 
  9. If not, creates a new folder and stores its ID. 
  10. Customer Search 
  11. Retrieves up to 5 active customers (isinactive = F). 
  12. Date Formatting 
  13. Converts startDate and current date to MM/DD/YYYY format for use in statements. 
  14. Statement Generation 
  15. For each customer:  
  16. Generates a PDF statement using render.statement. 
  17. Saves the PDF to the newly created folder. 
  18. Email Notification 
  19. Sends an email to the provided address confirming the statements were generated and saved. 

 

Leave a comment

Your email address will not be published. Required fields are marked *