Introduction
In NetSuite, automation of business processes is crucial for maintaining an efficient workflow. One such use case involves triggering a User Event Script when a customer record changes from a lead or prospect stage to a customer stage, specifically during conversions that indicate a business deal (e.g., “Closed Won” status).
This article will walk you through a NetSuite Scheduled Script that automatically triggers the User Event Script for customers who have recently been converted from leads or prospects to fully qualified customers. We’ll discuss the purpose, how it works, and the code implementation.
Purpose of the Script
When a lead or prospect is converted to a customer in NetSuite, some additional processes, like syncing data with external systems or updating internal statuses, need to be executed. These are usually handled by a User Event Script that triggers upon record changes.
However, NetSuite’s User Event Scripts do not automatically run on historical records or changes that have already occurred. To address this, a Scheduled Script can be employed to periodically check for recently converted leads and prospects and then programmatically trigger the User Event Script for further processing.
Components of the Script
1. Scheduled Script
A Scheduled Script is a server-side script that runs automatically on a schedule (daily, weekly, or at any specified time). It can process multiple records in bulk, making it ideal for tasks like checking for recently converted customers.
2. Search for Recently Converted Customers
The script performs a saved search to find customers who were converted from lead or prospect statuses to customers on the current day. The search filters customer records based on their system notes (tracking changes in the status field).
3. Triggering the User Event Script
Once the relevant customers are found, the script uses the submitFields function to trigger the User Event Script. This works by submitting an update on the customer record (even without modifying any fields), causing the User Event Script to fire.
Key Concepts in the Script
1. Search Object
The search.create API is used to find customer records where the entity status has changed from any other status to “Closed Won” (indicating the customer conversion) on the current date.
2. Submit Fields
The record.submitFields API allows you to update fields on the record without loading the entire record into memory. This efficiently triggers the User Event Script associated with the record, even if no actual changes are made.
The Code
Here is the complete code for the Scheduled Script:
/**
* @NApiVersion 2.1
* @NScriptType ScheduledScript
* @NModuleScope SameAccount
*/
define(['N/search', 'N/record', 'N/runtime'],
(search, record, runtime) => {
const execute = (scriptContext) => {
try {
log.debug('Scheduled Script Executed', '');
// Search for customers where sync status is unchecked
let customerSearch = search.create({
type: "customer",
filters: [
["stage", "anyof", "CUSTOMER"],
"AND",
["systemnotes.oldvalue", "isnot", "CUSTOMER-Closed Won(100%)"],
"AND",
["systemnotes.newvalue", "is", "CUSTOMER-Closed Won(100%)"],
"AND",
["systemnotes.date", "on", "today"]
],
columns: [
search.createColumn({ name: "internalid", label: "Internal ID" }),
search.createColumn({ name: "entitystatus", label: "Status" }),
search.createColumn({ name: "datecreated", label: "Date Created" }),
search.createColumn({ name: "lastmodifieddate", label: "Last Modified" })
]
});
let searchResults = customerSearch.run().getRange({ start: 0, end: 1000 });
if (searchResults.length > 0) {
searchResults.forEach((result) => {
let customerInternalId = result.getValue({ name: 'internalid' });
log.debug('Processing Customer', `Internal ID: ${customerInternalId}, Sync Status: ${syncStatus}`);
// Submit the record fields to trigger User Event Script
triggerUserEventViaSubmitFields(customerInternalId);
});
} else {
log.debug('No customers found to process.');
}
} catch (error) {
log.error("Error in Scheduled Script", error);
}
};
/**
* Submit fields on the customer record to trigger the User Event Script
*/
function triggerUserEventViaSubmitFields(customerInternalId) {
try {
// Submit an empty field update to trigger User Event Script
record.submitFields({
type: 'customer',
id: customerInternalId,
values: {}, // No actual fields need to be updated
options: {
enableSourcing: true,
ignoreMandatoryFields: true
}
});
log.debug('Record Submitted via submitFields', `Customer Internal ID: ${customerInternalId}`);
} catch (error) {
log.error('Error submitting customer record via submitFields', error);
}
}
return { execute };
}
);
How the Script Works
- Search for Customer Changes: The script uses a saved search to identify customers whose status has changed to “Closed Won” today. It ensures that only newly converted customers are processed by checking the
systemnotesfield for changes to the status. - Processing Customers: Once a customer is found, the script retrieves the internal ID and processes each one individually. It logs the details of the customer and prepares the record for further processing.
- Triggering the User Event Script: The
submitFieldsfunction is called for each customer, which triggers the associated User Event Script. This ensures that any logic related to customer conversion (e.g., data syncing with external systems) is executed. - Error Handling: The script includes try-catch blocks to handle and log errors that may occur during execution, ensuring that any issues are caught and handled appropriately.
Conclusion
This Scheduled Script is a highly effective way to ensure that business logic tied to customer conversion is automatically triggered, even for historical data or records that were converted outside of a live session. By leveraging NetSuite’s submitFields method, we can efficiently trigger User Event Scripts without making unnecessary updates to records.
This script can be scheduled to run daily, ensuring that all converted customers are processed in a timely manner, keeping your business workflows efficient and in sync.