Understanding sn_sc.CartJS() in ServiceNow: Its Importance and Use Cases
New article articles in ServiceNow Community
·
Jan 03, 2025
·
article
Understanding sn_sc.CartJS() in ServiceNow: Its Importance and Use Cases
Introduction:
In ServiceNow, the sn_sc.CartJS() is a powerful API that helps automate the management of catalog items within the Service Catalog. It allows developers to interact programmatically with the catalog, enabling tasks like adding items, populating variables, proceeding to checkout, and handling the request creation process. By leveraging this API, complex workflows involving catalog items and service requests can be streamlined, leading to increased efficiency and accuracy.
Importance of sn_sc.CartJS():
The sn_sc.CartJS() API is essential when you need to programmatically manage the Service Catalog, especially when items need to be added dynamically based on business logic or external data. Some common scenarios where the API was beneficial for our UseCase:
- Automating catalog item creation: Automatically creating requests and associated tasks based on predefined data.
- Pre-filling catalog variables: Automatically populating fields based on dynamic information, such as asset details or user input.
- Integrating workflows: Simplifying Service Catalog integration with other processes, such as asset management or incident management, by leveraging the cart and checkout process.
The CartJS API provides methods that enable you to access a user's shopping cart. This API runs in the sn_sc namespace and requires the Service Catalog Scoped API plugin (ID: com.glideapp.servicecatalog.scoped.api), which is enabled by default, to access the CartJS API.
Use Case: Automating the Creation of Evergreen Refresh Tickets for Asset Management
The Challenge:
Previously, our Asset Team manually created Service Catalog Tasks (sc_tasks) for assets nearing the end of life (EOL). The process was time-consuming and error-prone, as it involved selecting a Miscellaneous Request catalog item and manually copying and pasting details from the Asset record, such as:
- Configuration Item (CI) details
- Asset Information
- Serial Numbers
- Device Information
This manual approach became increasingly inefficient, especially with a large volume of assets needing to be refreshed before EOL. The Asset Team sought to automate this process to generate request tickets quickly through a technical catalog item, as well as via a UI Action from the Asset Record, without manually filling out each field.
Solution Using sn_sc.CartJS():
To address the challenge, we implemented an automated solution using sn_sc.CartJS() within a UI Action. The goal was to enable the Asset Team to generate an Evergreen Refresh ticket directly from the Asset record via a UI Action button. When clicked, the UI Action would:
- Automatically Add a Catalog Item: A predefined catalog item for the Evergreen Refresh request would be added to the cart.
- Populate Variables Dynamically: The necessary fields—such as CI, serial number, asset details, and requester information—would be automatically populated based on the information from the Asset record.
- Proceed to Checkout: The item would be added to the cart and checked out, creating a Service Catalog Request (REQ).
- Automatically Generate and Assign an sc_task: Once the request is created, the associated sc_task would be generated and assigned to the Evergreen Team with all relevant asset details for further evaluation.
This automation helped the Asset Team save time, reduce errors, and ensure that Evergreen Refresh tickets were created accurately and consistently.
Code Overview
Here is the implementation of the solution using sn_sc.CartJS():
var cart = new sn_sc.CartJS();
var newItem = {
"sysparm_id": "48ef0e6e2bca12d444a0f1996e91bf30", // Catalog Item ID
"sysparm_quantity": "1",
"variables": {
"configuration_item": ci.toString(), // Passing CI sys_id
"requested_by": assignedTo.toString(), // Using assignedTo as the requester
"recipient": assignedTo.toString(), // Assigning the ticket to the same user
"short_description_new": shortDescription, // Custom short description
"description": descriptionValue, // Detailed description for the request
"serial_number": serialNumber.toString(),
"device_name": deviceName.toString(),
"model": model.toString(),
"assigned_to_user": assignedToUser.toString(),
"last_scan_user": lastScanUser.toString(),
"last_scan_date": lastScanDate
}
};
gs.log("New Item: " + JSON.stringify(newItem)); // Show the new item details
// Add the item to the cart and proceed to checkout
var cartDetails = cart.addToCart(newItem);
gs.log('Cart details added: ' + JSON.stringify(cartDetails)); // Show the cart details
// Proceed to checkout
var checkoutInfo = cart.checkoutCart();
gs.log('Evergreen Refresh ticket checkout info: ' + JSON.stringify(checkoutInfo)); // Show checkout info
// Now we use the request_id from checkoutInfo directly, no need to parse it as JSON
var requestId = checkoutInfo ? checkoutInfo.request_id : null;
gs.log('Newly created Request ID: ' + requestId); // Show the new REQ ID
if (requestId) {
// Now find the related sc_task for the newly created request
var taskGR = new GlideRecord('sc_task');
taskGR.addQuery('request', requestId); // Use the newly created request_id to find related tasks
taskGR.query();
if (taskGR.next()) {
// If a related sc_task is found, output to the log
gs.log('Redirecting to SC Task: ' + taskGR.number); // Show the SC Task number
// Construct the redirect URL with the sys_id of the sc_task
var redirectUrl = 'https://instancename.service-now.com/now/nav/ui/classic/params/target/sc%5Ftask.do%3Fsys%5Fid%3D' + taskGR.sys_id + '%26sysparm_stack%3D%26sysparm_view%3D';
gs.print('Redirect URL: ' + redirectUrl); // Show the redirect URL
// Redirect the user to the SC Task
action.setRedirectURL(redirectUrl);
} else {
// If no task is found, output to the log
gs.log('No related SC Task found for the newly created REQ.'); // Inform the user that no related task was found
}
} else {
gs.log('No request ID found in checkout response.');
}
Outcome:
By using sn_sc.CartJS(), the Asset Team was able to streamline the process of generating Evergreen Refresh tickets. The key benefits of this automation include:
- No Manual Copy-Pasting: Information from the Asset record (such as CI, serial number, and asset details) is automatically passed to the catalog item, eliminating manual data entry.
- Reduced Errors: Automated population of fields reduces the chance of human error during ticket creation.
- Faster Processing: Evergreen Refresh tickets are now created and assigned with a single click, saving time for the Asset Team.
- Consistency: The process ensures uniformity in the format and structure of requests, helping maintain consistency in asset management.
Conclusion:
The sn_sc.CartJS() API in ServiceNow is a powerful tool for automating catalog item workflows, especially in cases where variables need to be pre-filled or requests must be created dynamically based on asset or user information. In this case, it enabled the Asset Team to automate the creation of Evergreen Refresh tickets, replacing the manual and error-prone process. With the use of a UI Action, the team can now efficiently generate requests and associated tasks, improving workflow, accuracy, and reducing operational overhead.
This solution not only saved valuable time but also enhanced accuracy and consistency, allowing the Asset Team to focus on more strategic tasks.
For more information, please check the document below:
Product Documentation | ServiceNow
If you believe the solution provided has adequately addressed your query, could you please **mark it as 'Helpful'** and **'Accept it as a Solution'**? This will help other community members who might have the same question find the answer more easily. Please feel free to comment if I have missed anything, if something needs correction, or if you have a better solution.
Thank you for your consideration.
Selva
https://www.servicenow.com/community/developer-articles/understanding-sn-sc-cartjs-in-servicenow-its-importance-and-use/ta-p/3140672