Sales order Customization

Jira : BP-33

This task summarizes the email sending process while placing an order from the webstore.

When a customer reaches the checkout page, the shipping cost will be taken as zero for all the customers. Website checkout page will show a message like ‘There will be a shipping cost and our sales rep will contact you sooner regarding thislater and will send an order confirmation email’.Once the sales order is created inNetsuite, the customer service staff will receive an email regarding the order creation for the customer. The customers are not receiving the order confirmation email by that time.

  • First thing we need to do is block the default email send to customer when order is placed from the web store.
  • Instead of the customer, the mail should be sent to service staff (the id will be given later).
  • The mail should have the order details, customer name, item details.
  • When the shipping cost is calculated, a button “shipping cost updated“ should appear in the SO . While clicking on that button the mail should send to the customer . This template will be different from the template used in service staff mail.
  • After the button click we are not making the button disable. Because there are cases like changes in shipping cost ,where we need to send email again to customer.
  • During the second button click, a popup with 2 buttons “ok” and  “cancel” should be shown to indicate that the  “mail is already sent , do you want to sent again ? “ by checking on the checkbox “mail sent to customer” . And also notify the service staff by sending a mail regarding the second click.
  • In the mail send to customer has 2 buttons. If the customer accepted the order then mail will be send to service staff to acknowledge the order is accepted and there should be a checkbox field “APPROVED BY CUSTOMER” under custom subtab in SO. It should be checked.
  • If the customer rejects the order, then  checkbox field “REJECTED BY CUSTOMER” under custom subtab in SO, it should be checked.

Block mail to customer:

  • To block the mail to customer→ uncheck the checkbox in website setup under email subtab for order received..
  • Send email to sales staff:
  • Created a workflow that works  on UI context when an order is created.
  • Using this workflow an email will be sent to the recipient: sales rep (“sales rep info is not given now, soI used a test id“) with a template having order details.

Workflow:

Workflow:

User event to add button after shipping cost updation

/**
 *@NApiVersion 2.x
 *@NScriptType UserEventScript
 */
 define(['N/record', 'N/log', 'N/ui/serverWidget'],
 function (record, log, serverWidget) {

     function beforeLoad(context) {
         try {

             if (context.type == context.UserEventType.EDIT || context.type == context.UserEventType.VIEW) {

                 // log.debug('state2');
                 var newRecord = context.newRecord;

                 var shippingcostUpdated = newRecord.getValue({
                     fieldId: 'custbody_jj_shipping_cost_updated'
                 });
                 log.debug('shippingcostUpdated', shippingcostUpdated);

                 if (shippingcostUpdated == true) {
                     context.form.addButton({
                         id: "custpage_shipcost_updated_button",
                         label: "Shipping Cost Updated",
                         functionName: "onButtonClick"
                     });
                 }
                 context.form.clientScriptFileId = 11228989;

             }

         } catch (e) {
             log.error('error on beforeload');
         }

     }

     

     function afterSubmit(context) {

         try {

             if (context.type == context.UserEventType.EDIT) {

                 var oldRecord = context.oldRecord;
                 log.debug('oldRecord', oldRecord);

                 var newRecord = context.newRecord;
                 log.debug('newRecord', newRecord);

                 var shippingCost = oldRecord.getValue({
                     fieldId: 'shippingcost'
                 });
                 log.debug('shippingcost', shippingCost);

                 var oldshippingMethod = oldRecord.getValue({
                     fieldId: 'shippingmethod'
                 });
                 log.debug('oldshippingMethod', oldshippingMethod);

                 var newshippingCost = newRecord.getValue({
                     fieldId: 'shippingcost'
                 });
                 log.debug('newshippingCost', newshippingCost);

                 var newshippingMethod = newRecord.getValue({
                     fieldId: 'shippingmethod'
                 });
               log.debug('newshippingmethod', newshippingMethod);
               var oldshippingMethod2 = newRecord.getValue({
                     fieldId: 'shipmethod'
                 });
                 log.debug('oldshippingmethod2', oldshippingMethod2);
                 var newshippingMethod2 = newRecord.getValue({
                     fieldId: 'shipmethod'
                 });
                 log.debug('newshippingmethod2', newshippingMethod2);

                 if (((shippingCost || newshippingCost) && shippingCost != newshippingCost)  || ((newshippingCost == 0 && newshippingMethod2) && shippingCost=="")){

                     var shippingcostCheckbox = newRecord.getField({
                         fieldId: 'custbody_jj_shipping_cost_updated'
                     });
                     shippingcostCheckbox.isDisabled = false;
                     var recordId=context.newRecord.id;

log.debug('recordId', recordId);





                     log.debug('shipping cost varied');
                     var recordObj = record.load({
                                type: record.Type.SALES_ORDER,
                                id: recordId
                            })
                            log.debug('recordObj', recordObj);

                            recordObj.setValue({
                         fieldId: 'custbody_jj_shipping_cost_updated',
                         value: true
                     });
                     recordObj.save();

                 }

             }

         } catch (e) {
             log.error('error on before submit');
         }

     }

     return {

         beforeLoad: beforeLoad,
         // beforeSubmit: beforeSubmit,
         afterSubmit: afterSubmit

     };
 });

Client script

/**
 *@NApiVersion 2.x
 *@NScriptType ClientScript
 */
 define(['N/ui/dialog', 'N/currentRecord', 'N/record', 'N/email', 'N/url', 'N/https'],
 function (dialog, currentRecord, record, email, url, https) {
   function pageInit(context) {
     console.log('cs-state1');
   }

   function onButtonClick(context) {
     try {
      var rec=currentRecord.get()
      var soid= rec.id
console.log('soid', soid);

var objRecord = record.load({
  type: record.Type.SALES_ORDER,
  id: soid,
  isDynamic: true,
});
console.log('objRecord', objRecord);
var mailtoCustomer = objRecord.getValue({
  fieldId: 'custbody_jj_mail_to_customer'
});
console.log('mailtoCustomer', mailtoCustomer);
if (mailtoCustomer == true) {
  dialog.confirm({
    title: "Mail is already sent to customer",
    message: "Click OK to send again!"
  }).then(success).catch(fail);

  function success(result) {

    if (result == true) {
      var checkApprove = objRecord.getValue({
        fieldId: 'custbody_jj_so_approved'
      });
      console.log('checkApprove', checkApprove);
      var checkReject = objRecord.getValue({
        fieldId: 'custbody_jj_so_rejected'
      });
      console.log('checkReject', checkReject);
      if(checkApprove == true){
        
        objRecord.setValue({
          fieldId: 'custbody_jj_so_approved',
          value: false
      });
      objRecord.save();
      }
      if(checkReject == true){
        
        objRecord.setValue({
          fieldId: 'custbody_jj_so_rejected',
          value: false
      });
      objRecord.save();
      }
        var currenturl = url.resolveScript({
            scriptId: "customscript_jj_sl_addbutton_so_bp_42",
            deploymentId: "customdeploy1",
            returnExternalUrl: false
           })
           console.log('currenturl', currenturl);
           var URL = currenturl + "&soid=" + soid;
           var response = https.get({
            url: URL
            
        }); 

    }
  }

  
} else {
  console.log('mail to customer sending');
  
  
      var currenturl = url.resolveScript({
      scriptId: "customscript_jj_sl_addbutton_so_bp_42",
      deploymentId: "customdeploy1",
      returnExternalUrl: false
     })
     console.log('currenturl', currenturl);
     var URL = currenturl + "&soid=" + soid;
     var response = https.get({
      url: URL
      
  }); 
    //  window.open (currenturl + "&soid=" + soid)
     objRecord.setValue({
        fieldId: 'custbody_jj_mail_to_customer',
        value: true
      });
      objRecord.save();
      window.location.reload(); 
     } }
     catch (e) {
       log.error({
         title: e.name,
         details: e.message
       });
     }
   }

   return {
     pageInit: pageInit,
     onButtonClick: onButtonClick
   };
 });

Suitelet to send email to customer

/**
 * @NApiVersion 2.x
 * @NScriptType Suitelet
 */

 
  


 define(['N/record','N/email', 'N/render'], function (record, email, render) {
    function onRequest(context) {
        try{
    //    if (context.request.method === 'GET') {
    //     var salesOrderID = context.request.parameters.soid;
    //     log.debug('salesOrderID', salesOrderID);

    //     var recordObj = record.load({
    //         type: record.Type.SALES_ORDER,
    //         id: salesOrderID
    //     })
    //     log.debug('recordObj', recordObj);
    //     var customer = recordObj.getValue({ fieldId: 'entity' });
    //     log.debug('customer', customer);
       
    //    }

    if (context.request.method === 'GET') {
        var salesOrderID = context.request.parameters.soid;
        log.debug('salesOrderID', salesOrderID);

        var recordObj = record.load({
            type: record.Type.SALES_ORDER,
            id: salesOrderID
        })
        log.debug('recordObj', recordObj);
       var customer = recordObj.getValue({ fieldId: 'entity' });
        log.debug('customer', customer);

    var mergeResult = render.mergeEmail({
        templateId: 168,
        entity:null,
        recipient: null ,
        supportCaseId: null,
        transactionId: Number(salesOrderID),
        customRecord: null
    });
    
    var emailSubject = mergeResult.subject;
    var emailBody = mergeResult.body;
                                
    email.send({
        author : 166677,
        recipients : customer,
        subject : emailSubject,
        body : emailBody,
        relatedRecords : {
            transactionId : Number(salesOrderID)
        }
    });
        }
        }
        catch(e){
            log.debug("error@mail",e)
        }
    }
    
return {
        onRequest: onRequest
    };
}); 
       
    
   

suitelet for approve and reject functionalities

/**
 * @NApiVersion 2.x
 * @NScriptType Suitelet
 */





 define(['N/record', 'N/email', 'N/render', 'N/search'], function (record, email, render, search) {
    var emailId;

    function onRequest(context) {
        try {


            if (context.request.method === 'GET') {

                var action_Type = context.request.parameters.actionType;
                log.debug('action_Type', action_Type);
                var soId = context.request.parameters.recId;
                log.debug('soId', soId);
                var cust_Name = context.request.parameters.cusName;
                log.debug('cust_Name', cust_Name);
                var cusEmail = findCustomerEmail(cust_Name);
                log.debug('cusEmail', cusEmail);
                if (action_Type == "APPROVE") {

                    var result = approveOrder(soId, cusEmail);
                    log.debug('result', result);
                    if (result == 1) {
                        var html = '<p style="text-align:center;margin-top:50px;font-size:24px;">Your Order is Approved Successfully.</p><p style="text-align:center;"><input style="color:azure;background-color:cadetblue;height:35px;width:190px;text-align:center;outline:none;border-radius:5px;font-size:20px;border:none;" type="button" id="close" onclick="window.close()" value="Close the window"/></p>';
                        context.response.write({
                            output: html
                        });
                    } else if (result == 2) {
                        var html = '<p style="text-align:center;margin-top:50px;font-size:24px;">Sorry! Failed to Approve the Order.</p><p style="text-align:center;"><input style="color:azure;background-color:cadetblue;height:35px;width:195px;text-align:center;outline:none;border-radius:5px;font-size:20px;border:none;" type="button" id="close" onclick="window.close()" value="Close the window"/></p>';
                        context.response.write({
                            output: html
                        });
                    }

                } else if (action_Type == "REJECT") {

                    var result = rejectOrder(soId, cusEmail);
                    log.debug('result', result);
                    if (result == 3) {
                        var html = '<p style="text-align:center;margin-top:50px;font-size:24px;">Your Order is Rejected Successfully.</p><p style="text-align:center;"><input style="color:azure;background-color:cadetblue;height:35px;width:195px;text-align:center;outline:none;border-radius:5px;font-size:20px;border:none;" type="button" id="close" onclick="window.close()" value="Close the window"/></p>';
                        context.response.write({
                            output: html
                        });
                    } else if (result == 4) {
                        var html = '<p style="text-align:center;margin-top:50px;font-size:24px;">Sorry! Failed to Reject the Order.</p><p style="text-align:center;"><input style="color:azure;background-color:cadetblue;height:35px;width:195px;text-align:center;outline:none;border-radius:5px;font-size:20px;border:none;" type="button" id="close" onclick="window.close()" value="Close the window"/></p>';
                        context.response.write({
                            output: html
                        });
                    }
                }

            }
        } catch (e) {
            log.debug("error@mail", e)
        }
    }

    function findCustomerEmail(cust_Name) {
        var customerSearchObj = search.create({
            type: "customer",
            filters: [
                ["entityid", "is", cust_Name]
            ],
            columns: [
                search.createColumn({
                    name: "altname",
                    label: "Name"
                }),
                search.createColumn({
                    name: "email",
                    label: "Email"
                })
            ]
        });
        var searchResultCount = customerSearchObj.runPaged().count;
        log.debug("customerSearchObj result count", searchResultCount);
        customerSearchObj.run().each(function (result) {
            // .run().each has a limit of 4,000 results
            // return true;
            emailId = result.getValue({
                name: "email",
                label: "Email"
            });
            log.debug('emailId', emailId);
        });
        return emailId;
    }

    function approveOrder(soId, cusEmail) {
        try {

            var recordObj = record.load({
                type: record.Type.SALES_ORDER,
                id: soId
            })
            log.debug('recordObj', recordObj);
            var checkMail = recordObj.getValue({
                fieldId: 'custbody_jj_mail_to_customer'
            });
            log.debug('checkMail', checkMail);
            var checkApproved = recordObj.getValue({
                fieldId: 'custbody_jj_so_approved'
            });
            log.debug('checkApproved', checkApproved);
            var checkRejected = recordObj.getValue({
                fieldId: 'custbody_jj_so_rejected'
            });
            log.debug('checkRejected', checkRejected);
            var mergeResult = render.mergeEmail({
                templateId: 170,
                entity: null,
                recipient: null,
                supportCaseId: null,
                transactionId: Number(soId),
                customRecord: null
            });

            var emailSubject = mergeResult.subject;
            var emailBody = mergeResult.body;
            if (checkApproved == false && checkMail == true && checkRejected == false) {
                log.debug('approving');
                email.send({
                    author: 166677,
                    recipients: 166680,
                    subject: emailSubject,
                    body: emailBody,
                    relatedRecords: {
                        transactionId: Number(soId)
                    }
                });


                recordObj.setValue({
                    fieldId: 'custbody_jj_so_approved',
                    value: true
                });
                recordObj.save();
                var retValue = 1;
                return retValue;
            } else {
                log.debug('not approving');
                //    email.send({
                //        author : 120214,
                //        recipients : cusEmail,
                //        subject : "Failed approval",
                //        body : "failed",
                //        relatedRecords : {
                //            transactionId : Number(soId)
                //        }
                //    });
                var retValue = 2;
                return retValue;

            }
        } catch (e) {
            log.debug("error@approveBill", e)

        }
    }

    function rejectOrder(soId, cusEmail) {
        try {

            var recordObj = record.load({
                type: record.Type.SALES_ORDER,
                id: soId
            })
            log.debug('recordObj', recordObj);
            var checkMail = recordObj.getValue({
                fieldId: 'custbody_jj_mail_to_customer'
            });
            log.debug('checkMail', checkMail);
            var checkApproved = recordObj.getValue({
                fieldId: 'custbody_jj_so_approved'
            });
            log.debug('checkApproved', checkApproved);
            var checkRejected = recordObj.getValue({
                fieldId: 'custbody_jj_so_rejected'
            });
            log.debug('checkRejected', checkRejected);

            var mergeResult = render.mergeEmail({
                templateId: 171,
                entity: null,
                recipient: null,
                supportCaseId: null,
                transactionId: Number(soId),
                customRecord: null
            });

            var emailSubject = mergeResult.subject;
            var emailBody = mergeResult.body;
            if (checkApproved == false && checkMail == true && checkRejected == false) {
                log.debug('reject working');
                email.send({
                    author: 166677,
                    recipients: 166680,
                    subject: emailSubject,
                    body: emailBody,
                    relatedRecords: {
                        transactionId: Number(soId)
                    }
                });


                recordObj.setValue({
                    fieldId: 'custbody_jj_so_rejected',
                    value: true
                });
                recordObj.save();
                var retValue = 3;
                return retValue;
            } else {
                log.debug('not rejecting');
                //    email.send({
                //        author : 120214,
                //        recipients : cusEmail,
                //        subject : "Failed rejection",
                //        body : "failed",
                //        relatedRecords : {
                //            transactionId : Number(soId)
                //        }
                //    });
                var retValue = 4;
                return retValue;
            }
        } catch (e) {
            log.debug("error@rejectBill", e)

        }

    }

    return {
        onRequest: onRequest
    };
});

Leave a comment

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