Schedule Script for Invoke the Existing Saved CSV Import

/**

 * @NApiVersion 2.1

 * @NScriptType ScheduledScript

 */

define([‘N/search’,’N/record’,’N/file’,’N/task’,’N/email’,’N/runtime’],

 function (search,record,file,task,email,runtime) {

   

  function execute(scriptContext) {

   try {

        log.debug(“scriptContext.params”,scriptContext)

         

        let script = runtime.getCurrentScript();

         

         

        let recId = script.getParameter({

          name: ‘custscript_jj_custom_rec_id_apun_154’ // Replace with your script parameter ID

        });

         

        log.debug(“recId”,recId)

        let customRecDetails = CustomerPriceListDetails.getCustomerPriceListDetails(recId);

        customRecDetails.recId = recId;

        CustomerPriceListDetails.updateCustomerPriceList(customRecDetails);

         

   } catch (error) {

    log.error({title: ‘execute Error’, details: error.toString()});

   }

  }

   /**

   * @description realted to create folder for each record type and migrate files to the folder.

   */

   const CustomerPriceListDetails = {

    /**

    * @description fetch customer price list update custom record emtries where status is approved.

    */

   getCustomerPriceListDetails(recId){

    try{

      let customrecord_jj_cus_price_list_apun_154SearchObj = search.create({

        type: “customrecord_jj_cus_price_list_apun_154”,

        filters:

        [

          [“isinactive”,”is”,”F”],

          “AND”,

          [“internalid”,”anyof”,recId]

        ],

        columns:

        [

          search.createColumn({name: “custrecord_jj_price_list_file_apun_154”, label: “Price List File “}),

          search.createColumn({name: “custrecord_jj_price_list_status_apun_154”, label: “Status”}),

          search.createColumn({name: “owner”, label: “Owner”}),

          search.createColumn({name: “custrecord_jj_file_approver_apun_154”, label: “Approver”}),

          search.createColumn({name: “custrecord_jj_reject_reason_apun_154”, label: “Reject Reason/Approval Comments”}),

          search.createColumn({name: “internalid”, label: “Internal ID”})

        ]

       });

       let searchResultCount = customrecord_jj_cus_price_list_apun_154SearchObj.runPaged().count;

       log.debug(“customrecord_jj_cus_price_list_apun_154SearchObj result count”,searchResultCount);

       let custRecDetailObj ={}

       if(searchResultCount >0){

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

          let priceListFileId = result.getValue(customrecord_jj_cus_price_list_apun_154SearchObj.columns[0]);

          let approverId = result.getValue(customrecord_jj_cus_price_list_apun_154SearchObj.columns[3]);

          let approverName = result.getText(customrecord_jj_cus_price_list_apun_154SearchObj.columns[3]);

          custRecDetailObj.priceListFileId = priceListFileId;

          custRecDetailObj.approverId = approverId;

          custRecDetailObj.approverName = approverName;

          return true;

         });

       }

       return custRecDetailObj; 

    }

    catch (e) {

      log.error(‘Error in CustomerPriceListDetails.getCustomerPriceListDetails’, e.message);

    }

  },

    /**

     * @description update the customer pricelist by fetching the data from uploaded csv file.

     * @param {*} customRecDetails 

     */

    updateCustomerPriceList(customRecDetails){

      try{

        log.debug(“customRecDetails”,customRecDetails);

        let fileId = customRecDetails.priceListFileId;

        let recId = customRecDetails.recId;

        log.debug(“recId”,recId);

        // Load the CSV file

        let importFile = file.load({

        id: fileId

       });

      // Create CSV Import Task

      let csvTask = task.create({

        taskType: task.TaskType.CSV_IMPORT,

        mappingId: 117, // Replace with your mapping ID

        importFile: importFile

      });

      // Submit the task to run the CSV import

      let taskId = csvTask.submit();

      log.debug(“CSV Import Task Submitted”, “Task ID: ” + taskId);

      let summary = task.checkStatus({

        taskId: taskId

        });

        log.debug(“summary”,summary);

        log.debug(“updated successfully”);

        record.submitFields({

         type: ‘customrecord_jj_cus_price_list_apun_154’,  

         id: recId, 

         values: {

           ‘custrecord_jj_file_processed_apun_154’: true 

         }

       });

       if (summary.status === task.TaskStatus.FAILED){

         

         CustomerPriceListDetails.sendFailureEmail(customRecDetails);

         log.error(“CSV import task failed for file: ” + fileId);

       }

      }

      catch (error) {

        log.error({title: ‘error@updateCustomerPriceList’, details: error.toString()});         

        CustomerPriceListDetails.sendFailureEmail(customRecDetails);

      }

    },

 /**

  * @description Send an email to the approver when the CSV import fails.

  * @param customRecDetails 

  */

   sendFailureEmail(customRecDetails) {

    try {

      let customRecIdArr = []

      customRecIdArr.push(customRecDetails.recId);

      customRecIdArr = customRecIdArr.flat()

      log.debug(“customRecIdArr”,customRecIdArr);

      log.debug(“customRecIdArr.flat()”,customRecIdArr.flat());

      

      let approverId = customRecDetails.approverId;

      //let approverName = approverObj.text;

      let employeeFields = search.lookupFields({

        type: search.Type.EMPLOYEE,

        id: approverId, 

        columns: [‘firstname’]

      });

      let approverName = employeeFields.firstname;

      log.debug(“Employee First Name”, approverName);     

      if(approverId != “”){

        log.debug(“approver id is not null”)

         // Send email notification

        email.send({

          author: -5, // -5 represents the system’s internal ID

          recipients: approverId,

          subject: ‘Customer Price List Processing Failed’,

          body: `Dear ${approverName},<br />

     

              The customer price list import task for the file with ID: ${customRecDetails.priceListFileId} has failed. <br /> <br />

               

              Custom record ID: ${customRecDetails.recId}<br /> <br />

               

              You can review and take appropriate action by visiting the following link:<br />

              ${customRecIdArr.map(function(customRecordId) {

                return `<a href=”https://4901021-sb1.app.netsuite.com/app/common/custom/custrecordentry.nl?id=${customRecordId}&rectype=349″ target=”_blank” style=”font-weight: bold; color: #FF5733; text-decoration: underline;”>View Custom Record</a> <br /><br />`;

              }).join(‘n’)}

              Thank you`

        });

     

        log.debug(“Failure email sent to approver: ” + approverName);

      }

  

     

    } catch (e) {

     log.error(‘Error sending failure email’, e.message);

    }

   }

    

   

 }

  return {execute: execute}

 });

Leave a comment

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