How to Restrict duplicate customers using user event script based on subsidiary.

By using this script, we can restrict the duplicate customers in the NetSuite and webstore based on the subsidiary.

/**
 * @NApiVersion 2.x
 * @NScriptType UserEventScript
 * @NModuleScope SameAccount
 */
define(['N/search', 'N/runtime'], function (search, runtime) {

  function beforeSubmit(context) {
      log.debug('************', context.type)
    if (context.type === context.UserEventType.CREATE ) {
      var customerRecord = context.newRecord;
      log.debug({
        title: 'customerRecord**********',
        details: customerRecord
      });

      var email = customerRecord.getValue('email');

      log.debug({
        title: 'email*****',
        details: email
      });

      var subsidiary = customerRecord.getValue('custentity_thr_websitesubsidiary');

      log.debug({
        title: 'subsidiary********',
        details: subsidiary
      });
      if (email && subsidiary) {
        var existingCustomer = searchExistingCustomer(email, subsidiary);
        log.debug({
          title: 'Debug existingCustomer *******',
          details: existingCustomer
        });
        if (existingCustomer > 0) {
          log.debug('condition satisfied')
          // Customer already exists in the same subsidiary, prevent registration
          throw new Error('Duplicate customer with the same email already exists in this subsidiary.');
        }
      }
    }
  }

  function searchExistingCustomer(email, subsidiary) {
    try {
      var customerSearchObj = search.create({
        type: "customer",
        filters:
          [
            ["stage", "anyof", "CUSTOMER", "LEAD", "PROSPECT"],
            "AND",
            ["subsidiary", "anyof", subsidiary],
            "AND",
            ["email", "is", email]
          ],
        columns:
          [
            search.createColumn({ name: "internalid", label: "Internal ID" }),
            search.createColumn({ name: "entityid", sort: search.Sort.ASC, label: "Name" })
          ]
      });
      var searchResultCount = customerSearchObj.runPaged().count;
      log.debug("customerSearchObj result count", searchResultCount);
      var customer = [];
      customerSearchObj.run().each(function (result) {
        var internalIdObj = {};
        internalIdObj.id = result.getValue({ name: "internalid", label: "Internal ID" });
        customer.push(internalIdObj)
        return true;
      });
      log.debug('customer', customer)
      return searchResultCount;

    } catch (error) {
       log.debug('error @ searchExistingCustomer', error)
    }
  }

  return {
    beforeSubmit: beforeSubmit
  };

});

Leave a comment

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