Account Hold Set up on Sales Order

/**

 * @NApiVersion 2.x

 * @NScriptType UserEventScript

 * @NModuleScope SameAccount

 */

/*******************************************************************************

 * Task No: MAR – 214

 *

 ******************************************************************************

 * Date: 03-04-2020

 * Author: Jobin & Jismi IT Services LLP

 * This script help to Account Hold set up on Sales Order creation.

 ******************************************************************************/

define([‘N/search’, ‘N/record’, ‘N/runtime’, ‘N/format’, ‘N/error’, ‘N/ui/serverWidget’],

  function(search, record, runtime, format, error, serverWidget) {

    var main = {

      /*******************************************************************************

       * afterSubmit triger for setting the True value in Account hold checkbox on SO

       creation MAR-224.

       * .

       *******************************************************************************/

      afterSubmit: function(scriptContext) {

        var newRecord = scriptContext.newRecord;

        var soId = newRecord.id;

        var scriptContextVal = runtime.executionContext;

        log.debug(“scriptContextVal”, scriptContextVal)

        log.debug(“soId”, soId)

        var customerTermObj = main.checkCustomerType(soId);

        log.debug(“customerTermObj”, customerTermObj)

        // var oldRecordVal = scriptContext.oldRecord;

        var totalamt = newRecord.getValue(‘total’);

        if (scriptContext.type == “create”) {

          if ((customerTermObj != false) && (customerTermObj[0].type == false)) {

            log.debug(“enter”)

            var paymentCount = main.emptyCardAccountValid(soId);

            log.debug(“paymentCount”, paymentCount)

            main.setAccountOnHold(soId, customerTermObj, paymentCount, totalamt)

          }

          /**********************************************************************************

           * afterSubmit triger for setting the Default value on SO record on web store orders

           *

           ***********************************************************************************/

          if (scriptContextVal == “WEBSTORE”) {

            /*** SET DEFAULT VALUES IN TO THE SO RECORD ***/

            log.debug(“webstore enter”)

            var formateddate = new Date();

            formateddate = format.format({ value: formateddate, type: format.Type.DATETIME, timezone: format.Timezone.AMERICA_LOS_ANGELES });

            formateddate = formateddate.split(” “)[0];

            record.submitFields({ type: record.Type.SALES_ORDER, id: soId, values: { memo: ‘Web Order’, custbody_created_by: 27619, shipdate: formateddate, custbody_lux_emailqueue: ‘F’ } });

            /*** APPROVAL CHECKING CONDITION ***/

            if ((customerTermObj[0].total > 300 || customerTermObj[0].addressChk == 0 || (customerTermObj[0].payStatus == “HOLD” && customerTermObj[0].holdReason == “AUTHORIZATION DECLINE”)) && customerTermObj[0].terms == 24) {

              log.debug(“Pending Approval”)

              record.submitFields({ type: record.Type.SALES_ORDER, id: soId, values: { orderstatus: ‘A’, custbody_mei_so_accounting_hold: ‘T’ } });

            } else if (customerTermObj[0].total < 300 || customerTermObj[0].addressChk == 1 || customerTermObj[0].payStatus == “ACCEPT”) {

              log.debug(“Pending Fulfillment”)

              record.submitFields({ type: record.Type.SALES_ORDER, id: soId, values: { orderstatus: ‘B’ } });

            }

            /**********************************************/

          }

        } else if (scriptContext.type == “edit”) {

          /***********************************************************************************

           * afterSubmit triger for setting the Default value on SO record on UI edit context.

           *

           ***********************************************************************************/

          //var userID = runtime.getCurrentUser().id;

          //var accountHoldBtnVal = oldRecordVal.getValue({ fieldId: “custbody_mei_so_accounting_hold” })

          // log.debug(“userID”, userID)

          //if (userID == 17351 || userID == 27064 || userID == 19663 || userID == 26359) {

          var oldRecord = scriptContext.oldRecord;

          var newRecord = scriptContext.newRecord;

          var oldRecLineCount = oldRecord.getLineCount({

            sublistId: ‘item’

          });

          log.debug(‘oldRecLineCount’, oldRecLineCount)

          var newRecLineCount = newRecord.getLineCount({

            sublistId: ‘item’

          });

          log.debug(‘newRecLineCount’, newRecLineCount)

          var oldAmount = oldRecord.getValue(‘total’)

          var newAmount = newRecord.getValue(‘total’)

          log.debug(‘oldAmount’, oldAmount)

          log.debug(‘newAmount’, newAmount)

          if ((customerTermObj != false) && (customerTermObj[0].type == false)) {

            log.debug(“enter edit”)

            var paymentCount = main.emptyCardAccountValid(soId);

            log.debug(“paymentCount”, paymentCount)

            if (newRecLineCount != oldRecLineCount || newAmount != oldAmount) {

              log.debug(“enter edit process”)

              main.editSetAccountOnHold(soId, customerTermObj, paymentCount, totalamt);

            }

          }

          //}

        }

      },

      /*******************************************************************************

       * beforeLoad triger for setting the value in account hold check box.

       * .

       *******************************************************************************/

      beforeLoad: function(scriptContext) {

        var CLIENT_SCRIPT_ID = 160708;

        var CustRec = scriptContext.form;

        var userRole = runtime.getCurrentUser().role;

        var chkValAccHold = scriptContext.newRecord.getValue({ fieldId: ‘custbody_mei_so_accounting_hold’ });

        log.debug(“chkValAccHold”, chkValAccHold)

        if (scriptContext.type == ‘view’) {

          CustRec.clientScriptFileId = CLIENT_SCRIPT_ID;

          if ((userRole == 1036 || userRole == 1035 || userRole == 1032 || userRole == 1063 || userRole == 1045 || userRole == 3) && (chkValAccHold == true)) {

            CustRec.addButton({

              id: ‘custpage_account_hold_btn’,

              label: ‘Change Accounting Hold’,

              functionName: ‘accHoldFun’

            });

          }

        }

        /**On edit, The Get Authorisation checkbox is making HIDDEN on certain criteria

         *************  MAR 736   ******************/

        /*if(scriptContext.type == ‘edit’)

        {

          var Cuser=runtime.getCurrentUser();

         var user=Cuser.id;

         // log.debug(“user”,user)

          if(user==19663||user==26359)

          {

            var Srecord=scriptContext.newRecord;

            var cus=Srecord.getValue({fieldId:’entity’});

            var cusSearch=search.lookupFields({

              type:search.Type.CUSTOMER,

              id:cus,

              columns:[‘custentity_naw_trans_need_approval’,’custentity_blocked_hold’]

            });

            var salesOps=cusSearch.custentity_naw_trans_need_approval;

            var accHold=cusSearch.custentity_blocked_hold;

            var byepass=Srecord.getValue({fieldId:’custbodybypassaccounthold’});

           

            var getAuth=CustRec.getField({id:’getauth’});

           //log.debug(“GETAUTH”,getAuth)

            if(getAuth) {

              if (salesOps == true || accHold == true)

              {

               if(byepass == false)

                {

                getAuth.updateDisplayType({

  displayType: serverWidget.FieldDisplayType.HIDDEN

});

                }

              }

            }

          }

        }*/

      },

      /***************************************************************************

       * MAR-214

       * sales order search for set accounting hold while credit card is empty.

       *

       * **************************************************************************/

      emptyCardAccountValid: function(soId) {

        var salesorderSearchObj = search.create({

          type: “salesorder”,

          filters: [

            [“type”, “anyof”, “SalesOrd”],

            “AND”,

            [“internalid”, “anyof”, soId],

            “AND”,

            [“mainline”, “is”, “T”],

            “AND”,

            [“paymentevent.internalid”, “noneof”, “@NONE@”]

          ],

          columns: [

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

          ]

        });

        var searchResultCount = salesorderSearchObj.runPaged().count;

        return searchResultCount;

      },

      /***************************************************************************

       * MAR-214

       * sales order search for creating object for checking condition.

       *

       * **************************************************************************/

      checkCustomerType: function(soId) {

        var validateTerm = [];

        var salesorderSearchObj = search.create({

          type: “salesorder”,

          filters: [

            [“type”, “anyof”, “SalesOrd”],

            “AND”,

            [“internalid”, “anyof”, soId]

          ],

          columns: [

            search.createColumn({

              name: “isperson”,

              join: “customerMain”,

              label: “Is Individual”

            }),

            search.createColumn({

              name: “terms”,

              join: “customerMain”,

              label: “Terms”

            }),

            search.createColumn({

              name: “creditlimit”,

              join: “customerMain”,

              label: “Credit Limit”

            }),

            search.createColumn({

              name: “consoldaysoverdue”,

              join: “customerMain”,

              label: “Consolidated Days Overdue”

            }),

            search.createColumn({

              name: “balance”,

              join: “customerMain”,

              label: “Balance”

            }),

            search.createColumn({

              name: “custentity_naw_trans_need_approval”,

              join: “customerMain”,

              label: “Tran approval”

            }),

            search.createColumn({

              name: “custentity_blocked_hold”,

              join: “customerMain”,

              label: “block hold”

            }),

            search.createColumn({ name: “paymenteventresult”, label: “Payment Event Result” }),

            search.createColumn({

              name: “date”,

              join: “paymentEvent”,

              label: “Date”

            }),

            search.createColumn({

              name: “internalid”,

              join: “paymentEvent”,

              sort: search.Sort.DESC,

              label: “Internal ID”

            }),

            /* this part is part of mar-222 for getting SO total and campare ship and bill address*/

            search.createColumn({ name: “total”, label: “Amount (Transaction Total)” }),

            search.createColumn({

              name: “formulanumeric”,

              formula: “CASE WHEN {billaddress} = {shipaddress} THEN 1 ELSE 0 END”,

              label: “Formula (Numeric)”

            }),

            search.createColumn({

              name: “holdreason”,

              join: “paymentEvent”,

              label: “Hold Reason”

            }),

            search.createColumn({

              name: “processedexternally”,

              join: “paymentEvent”,

              label: “Processed Externally”

            })

            /***************************************************************************************/

          ]

        });

        var salesResultCount = salesorderSearchObj.runPaged().count;

        log.debug(“salesResultCount”, salesResultCount)

        if (salesResultCount) {

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

            var validateTermObj = {};

            validateTermObj.type = result.getValue({ name: “isperson”, join: “customerMain”, label: “Is Individual” });

            validateTermObj.terms = result.getValue({ name: “terms”, join: “customerMain”, label: “Terms” });

            validateTermObj.limit = result.getValue({ name: “creditlimit”, join: “customerMain”, label: “Credit Limit” });

            validateTermObj.overDue = result.getValue({ name: “consoldaysoverdue”, join: “customerMain”, label: “Consolidated Days Overdue” });

            validateTermObj.balance = result.getValue({ name: “balance”, join: “customerMain”, label: “Balance” });

            validateTermObj.payStatus = result.getValue({ name: “paymenteventresult”, label: “Payment Event Result” });

            validateTermObj.date = result.getValue({ name: “date”, join: “paymentEvent”, label: “Date” });

            validateTermObj.needAproval = result.getValue({ name: “custentity_naw_trans_need_approval”, join: “customerMain”, label: “Tran approval” });

            validateTermObj.blockedHold = result.getValue({ name: “custentity_blocked_hold”, join: “customerMain”, label: “block hold” });

            validateTermObj.internalId = result.getValue({ name: “internalid”, join: “paymentEvent”, sort: search.Sort.DESC, label: “Internal ID” });

            /* this part is part of mar-222 for getting SO total and campare ship and bill address*/

            validateTermObj.total = result.getValue({ name: “total”, label: “Amount (Transaction Total)” });

            validateTermObj.addressChk = result.getValue({ name: “formulanumeric”, formula: “CASE WHEN {billaddress} = {shipaddress} THEN 1 ELSE 0 END”, label: “Formula (Numeric)” });

            validateTermObj.holdReason = result.getValue({ name: “holdreason”, join: “paymentEvent”, label: “Hold Reason” });

            validateTermObj.processExternally = result.getValue({ name: “processedexternally”, join: “paymentEvent”, label: “Processed Externally” });

            /***************************************************************************************/

            validateTerm.push(validateTermObj);

            return false;

          });

          log.debug(“validateTerm”, validateTerm)

          return validateTerm;

        } else {

          return false;

        }

      },

      /***************************************************************************

       * MAR-214

       * Make TRUE the ACCOUNTING HOLD check box according to the condition.

       *

       * **************************************************************************/

      setAccountOnHold: function(soId, customerTermObj, paymentCount, totalamt) {

        if (customerTermObj[0].terms == 20) {

          log.debug(“reach”)

          record.submitFields({ type: record.Type.SALES_ORDER, id: soId, values: { custbody_mei_so_accounting_hold: ‘T’ } });

        }

        /* else if ((customerTermObj[0].terms == 24) && (customerTermObj[0].payStatus == “HOLD”)) {

                  log.debug(“reach2”)

                  record.submitFields({ type: record.Type.SALES_ORDER, id: soId, values: { custbody_mei_so_accounting_hold: ‘T’ } });

                } else if ((customerTermObj[0].terms == 24) && (paymentCount == 0)) {

                  log.debug(“reach3”)

                  record.submitFields({ type: record.Type.SALES_ORDER, id: soId, values: { custbody_mei_so_accounting_hold: ‘T’ } });

                } else if ((customerTermObj[0].terms == 24) && (customerTermObj[0].processExternally == false) && (customerTermObj[0].payStatus == “ACCEPT”)) {

                  log.debug(“reach4”)

                  record.submitFields({ type: record.Type.SALES_ORDER, id: soId, values: { custbody_mei_so_accounting_hold: ‘T’ } });

                } */

        else if ((customerTermObj[0].needAproval == true) || (customerTermObj[0].blockedHold == true)) {

          log.debug(“reach5”)

          record.submitFields({ type: record.Type.SALES_ORDER, id: soId, values: { custbody_mei_so_accounting_hold: ‘T’ } });

        } else if ((customerTermObj[0].terms == 5 || customerTermObj[0].terms == 15 || customerTermObj[0].terms == 6 || customerTermObj[0].terms == 22 || customerTermObj[0].terms == 16 || customerTermObj[0].terms == 17 || customerTermObj[0].terms == 1 || customerTermObj[0].terms == 18 || customerTermObj[0].terms == 2 || customerTermObj[0].terms == 9 || customerTermObj[0].terms == 19 || customerTermObj[0].terms == 3 || customerTermObj[0].terms == 23 || customerTermObj[0].terms == 10 || customerTermObj[0].terms == 29 || customerTermObj[0].terms == 28 || customerTermObj[0].terms == 27) && (Number(customerTermObj[0].balance) > Number(customerTermObj[0].limit) || Number(customerTermObj[0].overDue) > 15)) {

          log.debug(“reach6”)

          record.submitFields({ type: record.Type.SALES_ORDER, id: soId, values: { custbody_mei_so_accounting_hold: ‘T’ } });

        } else if (customerTermObj[0].terms == 30 || customerTermObj[0].terms == 26 || customerTermObj[0].terms == 25 || customerTermObj[0].terms == 32 || customerTermObj[0].terms == 31) {

          log.debug(“reach7”)

          record.submitFields({ type: record.Type.SALES_ORDER, id: soId, values: { custbody_mei_so_accounting_hold: ‘T’ } });

        } else if ((Number(totalamt) > Number(customerTermObj[0].limit) && customerTermObj[0].terms != 24)) {

          log.debug(“reach8”)

          record.submitFields({ type: record.Type.SALES_ORDER, id: soId, values: { custbody_mei_so_accounting_hold: ‘T’ } });

        }

        /***************************************************************************

         * MAR-651

         * Make TRUE the ACCOUNTING HOLD check box according to credit card condition.

         *

         * **************************************************************************/

        // var userId = runtime.getCurrentUser().id;

        // log.debug(‘userId’, userId);

        // if (userId == 17351 || userId == 19663 || userId == 26359) {

        // log.debug(‘userId1’, userId);

        if ((customerTermObj[0].terms == 24) && (paymentCount == 0)) {

          log.debug(“reach1111”)

          record.submitFields({ type: record.Type.SALES_ORDER, id: soId, values: { custbody_mei_so_accounting_hold: ‘T’ } });

        } else if ((customerTermObj[0].terms == 24) && (customerTermObj[0].payStatus == “HOLD”)) {

          log.debug(“reach222”)

          record.submitFields({ type: record.Type.SALES_ORDER, id: soId, values: { custbody_mei_so_accounting_hold: ‘T’ } });

        }

        //};

        /***************************************************************************/

      },

      editSetAccountOnHold: function(soId, customerTermObj, paymentCount, totalamt /*, accountHoldBtnVal*/ ) {

        if ((customerTermObj[0].needAproval == true) || (customerTermObj[0].blockedHold == true)) {

          log.debug(“reach”)

          record.submitFields({ type: record.Type.SALES_ORDER, id: soId, values: { custbody_mei_so_accounting_hold: ‘T’ } });

        } else if ((Number(totalamt) > Number(customerTermObj[0].limit) && customerTermObj[0].terms != 24)) {

          log.debug(“reach2”)

          record.submitFields({ type: record.Type.SALES_ORDER, id: soId, values: { custbody_mei_so_accounting_hold: ‘T’ } });

        }

        // if (customerTermObj[0].terms == 24) {

        //   //if (accountHoldBtnVal == true) {

        //   if ((customerTermObj[0].terms == 24) && (customerTermObj[0].payStatus == “HOLD”)) {

        //     log.debug(“reach1”)

        //     record.submitFields({ type: record.Type.SALES_ORDER, id: soId, values: { custbody_mei_so_accounting_hold: ‘T’ } });

        //   } else if ((customerTermObj[0].terms == 24) && (paymentCount == 0)) {

        //     log.debug(“reach2”)

        //     record.submitFields({ type: record.Type.SALES_ORDER, id: soId, values: { custbody_mei_so_accounting_hold: ‘T’ } });

        //   } else if ((customerTermObj[0].terms == 24) && (customerTermObj[0].processExternally == false) && (customerTermObj[0].payStatus == “ACCEPT”)) {

        //     log.debug(“reach4”)

        //     record.submitFields({ type: record.Type.SALES_ORDER, id: soId, values: { custbody_mei_so_accounting_hold: ‘T’ } });

        //   } else {

        //     log.debug(“reach4”)

        //     record.submitFields({ type: record.Type.SALES_ORDER, id: soId, values: { custbody_mei_so_accounting_hold: ‘F’ } });

        //   }

        //   // }

        // }

      },

    };

    for (var key in main) {

      if (typeof main[key] === ‘function’) {

        main[key] = trycatch(main[key], key);

      }

    }

    function trycatch(myfunction, key) {

      return function() {

        try {

          return myfunction.apply(this, arguments);

        } catch (e) {

          log.debug(“e in ” + key, e);

        }

      }

    };

    function searchAny(id, parent) {

      try {

        var customerSearchObj = search.create({

          type: “customer”,

          filters: [

            [“parentcustomer.internalid”, “anyof”, parent], ‘AND’, [“internalid”, “anyof”, id]

          ],

          columns: [

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

          ]

        });

        return customerSearchObj.runPaged().count > 0;

      } catch (err) {

        log.debug(‘searchAny’, err);

        return false;

      }

    }

    /*********************************************************************************************

     *

     * MAR-327 https://jobinandjismi.atlassian.net/browse/MAR-327

     * Script/workflow update to include Amount Validation

     *

     * The proposed script will validate the Amount when creating a new sales order for the customer under Online Orders (internal ID: 15130) if the user’s role is other than Administrator and Sales Operations Manager. And the script will not allow the user to save the record by redirecting to an error page if the total amount is greater than $1000.

     *

     *

     * @param scriptContext

     */

    function beforeSubmit(scriptContext) {

     /**Get Authorisation Validation MAR 736**/

     if(scriptContext.type==’edit’||scriptContext.type==’create’)

      {

      var Cuser = runtime.getCurrentUser();

      var user = Cuser.id;

      log.debug(“user”,user)

     

        var Srecord = scriptContext.newRecord;

        var cus = Srecord.getValue({ fieldId: ‘entity’ });

       log.debug(“CUSid”,cus);

        var cusSearch = search.lookupFields({

          type: search.Type.CUSTOMER,

          id: cus,

          columns: [‘custentity_naw_trans_need_approval’, ‘custentity_blocked_hold’]

        });

       

        var salesOps = cusSearch.custentity_naw_trans_need_approval;

        var accHold = cusSearch.custentity_blocked_hold;

        var byepass = Srecord.getValue({ fieldId: ‘custbodybypassaccounthold’ });

       log.debug(“Byepass”,byepass);

        if (salesOps == true || accHold == true) {

          if (byepass == false) {

            var getAuth = Srecord.setValue({ fieldId: ‘getauth’, value: false, ignoreFieldChange: true });

          }

        }

       // var get=Srecord.getValue({fieldId:’getauth’});

      // log.debug(“GetAuth”,get);

       

      }

      

      var userRole = runtime.getCurrentUser().role;

      if (userRole == 3 || userRole == 1045) return;

      var onlineCustomerId = runtime.getCurrentScript().getParameter({ name: ‘custscript_online_customer’ });

      var customer = scriptContext.newRecord.getValue(‘entity’) || scriptContext.oldRecord.getValue(‘entity’);

      //log.debug(‘customer != onlineCustomerId’,customer != onlineCustomerId);

      if (customer != onlineCustomerId) {

        var exists = searchAny(customer, onlineCustomerId);

        log.debug(‘exists’, exists);

        if (!exists) return;

      }

      var preferedLimit = runtime.getCurrentScript().getParameter({ name: ‘custscript_so_limit_total’ }) || 1000;

      var orderTotal = parseFloat(scriptContext.newRecord.getValue(‘total’));

      if (orderTotal > preferedLimit) {

        var custom_error = error.create({

          name: ‘AMOUNT_LIMIT_EXCEEDED’,

          message: ‘You are not allowed to create salesorder more than $’ + preferedLimit,

          notifyOff: true

        });

        throw custom_error;

      }

      

    }

    main.beforeSubmit = beforeSubmit;

    return main;

  });

Leave a comment

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