in servicenow, Does anyone have any insight on how to use a business rule to get the…
- User
in servicenow, Does anyone have any insight on how to use a business rule to get the Business Elapsed Time value and store it in a custom field, Test Elapsed Time?
- Assistant
In ServiceNow, you can use a business rule to calculate the Business Elapsed Time and store it in a custom field such as "Test Elapsed Time." Below is a step-by-step guide on how to accomplish this:
-
Create Custom Field:
- First, create a custom field "Test Elapsed Time" of type
Duration(orStringif you prefer) in your target table.
- First, create a custom field "Test Elapsed Time" of type
-
Create the Business Rule:
- Go to
System Definition > Business Rulesand click onNew.
- Go to
-
Configure the Basic Information:
- Name: Set a name for your Business Rule, for example, "Set Test Elapsed Time".
- Table: Select the table where you want to run this Business Rule, e.g.,
Incident. - Active: Ensure this checkbox is selected.
- Advanced: Check this box to access the script editor.
-
When to Run:
- In the
When to runsection, set up the conditions for when the Business Rule should execute. - You can decide to run it
beforeorafterrecord insert/update, depending on your requirement. - For example, you might set the filter conditions for when a specific field changes or certain criteria are met.
- In the
-
Add Script:
- Below is an example of a script that calculates the Business Elapsed Time and stores it in the custom "Test Elapsed Time" field:
(function executeRule(current, previous /*null when async*/) { // Load the GlideSLA API var SLA = new GlideSLA(); // Get the Business Elapsed Time for the current record var elapsedTime = SLA.calculateBusinessElapsedTime(current.sys_id, current.sys_updated_on); // Store the Business Elapsed Time in the custom field "u_test_elapsed_time" current.u_test_elapsed_time = elapsedTime; // Optionally, you can format the elapsed time as you need (e.g., in hours, minutes, seconds) // Here is a simple example to convert milliseconds to hours var elapsedHours = Math.floor(elapsedTime / (1000 * 60 * 60)); current.u_test_elapsed_time = elapsedHours; })(current, previous);- Save and Activate Business Rule:
- Click on
Submitto save your business rule. - Ensure your rule is active and tests it to see if it correctly updates the "Test Elapsed Time" field as expected.
Notes:
-
GlideSLA: This API is used to manage SLA (Service Level Agreement) metrics in ServiceNow. The method
calculateBusinessElapsedTimemight need to be modified, or a more specific method may be used depending on your specific business logic and requirements. The example provided here might need adjustments based on the exact methods available and how you've set up SLAs in ServiceNow. -
Testing: Make sure to thoroughly test your business rule in a development environment before deploying it to production. Verify that it properly calculates and stores the elapsed time under various scenarios.
-
Documentation: Always document your business rules, including when they run, why they are necessary, and any specific configurations or calculations they perform. This will make maintenance and updates easier in the future.
If exact methods or utilities are not available or need different parameters, refer to the ServiceNow documentation or contact ServiceNow support for exact API specifications and guidance.
-
- User
not working give me accurate business rule that store sla bussiness elapsed time in u_test_elapsed_time custom field String
- Assistant
To capture the SLA Business Elapsed Time and store it in a custom field called
u_test_elapsed_time, you can use the GlideRecord and GlideAggregate APIs. Here's a practical example of how to achieve that with a business rule:Steps:
-
Create Custom Field
- Navigate to your target table (e.g.,
Incident). - Create a new field called
u_test_elapsed_timeof typeString.
- Navigate to your target table (e.g.,
-
Create the Business Rule
- Go to
System Definition > Business Rulesand clickNew.
- Go to
-
Configure the Basic Information:
- Name: Set a name for your Business Rule, for example, "Update Test Elapsed Time".
- Table: Select the table where you want to apply this Business Rule, e.g.,
Incident. - Active: Ensure this checkbox is selected.
- Advanced: Check this box to enable the script editor.
-
When to Run:
- When: Choose
After. - Insert: Select if you want it to run after record insertion.
- Update: Select if you want it to run after record updates.
- Filter Conditions: Set the filter condition if needed (e.g., when a specific field is updated).
- When: Choose
-
Add Script:
- Below is an example script that calculates the SLA Business Elapsed Time and stores it in the custom field
u_test_elapsed_time:
- Below is an example script that calculates the SLA Business Elapsed Time and stores it in the custom field
(function executeRule(current, previous /*null when async*/) { // Check if there's an active SLA for the current record var slaGR = new GlideRecord('task_sla'); // task_sla is the table that tracks SLA records slaGR.addQuery('task', current.sys_id); slaGR.addQuery('active', true); slaGR.query(); if (slaGR.next()) { // Get the business elapsed time in milliseconds var businessElapsedTime = slaGR.business_time; // Optionally convert the time to a human-readable format var seconds = Math.floor(businessElapsedTime / 1000) % 60; var minutes = Math.floor(businessElapsedTime / (1000 * 60)) % 60; var hours = Math.floor(businessElapsedTime / (1000 * 60 * 60)) % 24; var days = Math.floor(businessElapsedTime / (1000 * 60 * 60 * 24)); // Format the elapsed time as a string var elapsedTimeStr = days + "d " + hours + "h " + minutes + "m " + seconds + "s"; // Store the formatted elapsed time in the custom field current.u_test_elapsed_time = elapsedTimeStr; } })(current, previous);- Save and Activate the Business Rule:
- Click
Submitto save your Business Rule. - Ensure the Business Rule is active.
- Click
Explanation:
- task_sla Table: The
task_slatable tracks the SLA records associated with tasks. Thebusiness_timefield in this table stores the business elapsed time in milliseconds. - Query: This script queries the
task_slatable for SLA records that are active for the current task. - Elapsed Time Calculation: The script converts the elapsed time from milliseconds to a human-readable format (days, hours, minutes, seconds) and stores it in the
u_test_elapsed_timefield.
Notes:
- Testing: Make sure to test this business rule in a development or test environment extensively to ensure it works correctly.
- Performance: Be cautious of the performance impact. If the table (e.g., Incident) is very large, querying the
task_slatable could be resource-intensive. Optimize your queries and conditions as necessary. - Edge Cases: Consider edge cases such as tasks with no active SLA or SLAs that have been cancelled.
By following these steps, you should be able to capture the SLA Business Elapsed Time and store it in your custom field
u_test_elapsed_time. -
- User
how to store Business elapsed time from current running in progress SLA in incident to custom field test time
- Assistant
To store the Business Elapsed Time from the current running in-progress SLA into a custom field called
u_test_elapsed_timeon theincidenttable, you can create a business rule in ServiceNow. Here’s a step-by-step guide to achieve this:Steps:
-
Create Custom Field:
- Navigate to your
Incidenttable. - Create a new field called
u_test_elapsed_timeof typeString.
- Navigate to your
-
Create the Business Rule:
- Navigate to
System Definition > Business Rulesand click onNew.
- Navigate to
-
Configure the Basic Information:
- Name: Give your business rule a name, for example, "Update Business Elapsed Time".
- Table: Select
Incident. - Active: Make sure this box is checked.
- Advanced: Check both the
AdvancedandWhen to Runcheckboxes to enable scripting and control when the rule executes.
-
When to Run:
- When: Choose
After. - Insert: Check this box if you want it to run after record insertion.
- Update: Check this box if you want it to run after record updates.
- Filter Conditions: Set filter conditions if needed (e.g., when a specific field is updated).
- When: Choose
-
Script:
- Add a script to calculate the Business Elapsed Time for the current SLA and store it in
u_test_elapsed_time.
- Add a script to calculate the Business Elapsed Time for the current SLA and store it in
(function executeRule(current, previous /*null when async*/) { // Query to find active SLA records associated with the current incident var taskSlaGR = new GlideRecord('task_sla'); taskSlaGR.addQuery('task', current.sys_id); taskSlaGR.addQuery('stage', 'in_progress'); // Ensuring it's the in-progress SLA taskSlaGR.query(); // Check if SLA in progress is found if (taskSlaGR.next()) { // Get the business elapsed time from the SLA in milliseconds var businessElapsedTime = taskSlaGR.business_time; // Convert the milliseconds to a human-readable format (optional) var seconds = Math.floor(businessElapsedTime / 1000) % 60; var minutes = Math.floor(businessElapsedTime / (1000 * 60)) % 60; var hours = Math.floor(businessElapsedTime / (1000 * 60 * 60)) % 24; var days = Math.floor(businessElapsedTime / (1000 * 60 * 60 * 24)); // Format the business elapsed time as a string var elapsedTimeStr = days + "d " + hours + "h " + minutes + "m " + seconds + "s"; // Store the formatted elapsed time in the custom field current.u_test_elapsed_time = elapsedTimeStr; } // Optional: Update the incident record // current.update(); // This line can be skipped because it's an "after" business rule })(current, previous);- Save and Activate the Business Rule:
- Click
Submitto save your Business Rule. - Ensure the Business Rule is active.
- Click
Explanation:
- Querying the task_sla Table: This script queries the
task_slatable to find SLA records that are related to the current incident record and are in the "in_progress" stage. - Calculating Business Elapsed Time: The
business_timefield in thetask_slatable holds the elapsed time in milliseconds which is then converted to a human-readable format (days, hours, minutes, seconds) for storage inu_test_elapsed_time. - Updating the Field: The formatted elapsed time string is stored in the
u_test_elapsed_timecustom field.
Notes:
- Testing: Thoroughly test this business rule in a development or test environment to ensure it behaves as expected under different scenarios.
- Performance: Be mindful of performance implications, especially if the table has a large number of records or if the business rule executes frequently.
- Edge Cases: Handle edge cases such as incidents with no active SLA or multiple SLAs to ensure the script works correctly and efficiently.
By following these steps, you will be able to store the Business Elapsed Time from the current in-progress SLA into your custom field
u_test_elapsed_time. -
- User
sla field name is business_duration
- Assistant
If the field that holds the business elapsed time for the SLA in your
task_slatable is calledbusiness_duration, you need to adjust the script accordingly. Here’s an updated and accurate guide on how to create a business rule to store the business elapsed time from the current in-progress SLA into the custom fieldu_test_elapsed_timeon theincidenttable.Steps:
-
Create Custom Field:
- Navigate to your
Incidenttable. - Create a new field called
u_test_elapsed_timeof typeString.
- Navigate to your
-
Create the Business Rule:
- Navigate to
System Definition > Business Rulesand clickNew.
- Navigate to
-
Configure the Basic Information:
- Name: Give your business rule a name, for example, "Update Business Elapsed Time".
- Table: Select
Incident. - Active: Ensure this checkbox is selected.
- Advanced: Check both the
AdvancedandWhen to Runcheckboxes to enable scripting and control when the rule executes.
-
When to Run:
- When: Choose
After. - Insert: Check this box if you want it to run after record insertion.
- Update: Check this box if you want it to run after record updates.
- Filter Conditions: Set filter conditions if needed (e.g., when a specific field is updated).
- When: Choose
-
Script:
- Add the following script to calculate the Business Elapsed Time for the current SLA and store it in
u_test_elapsed_time.
- Add the following script to calculate the Business Elapsed Time for the current SLA and store it in
(function executeRule(current, previous /*null when async*/) { // Query to find active SLA records associated with the current incident var taskSlaGR = new GlideRecord('task_sla'); taskSlaGR.addQuery('task', current.sys_id); taskSlaGR.addQuery('stage', 'in_progress'); // Ensuring it's the in-progress SLA taskSlaGR.query(); // Check if an SLA in progress is found if (taskSlaGR.next()) { // Get the business duration (elapsed time) from the SLA in milliseconds var businessDuration = taskSlaGR.business_duration; // Convert the milliseconds to a human-readable format (optional) var seconds = Math.floor(businessDuration / 1000) % 60; var minutes = Math.floor(businessDuration / (1000 * 60)) % 60; var hours = Math.floor(businessDuration / (1000 * 60 * 60)) % 24; var days = Math.floor(businessDuration / (1000 * 60 * 60 * 24)); // Format the business duration as a string var elapsedTimeStr = days + "d " + hours + "h " + minutes + "m " + seconds + "s"; // Store the formatted elapsed time in the custom field current.u_test_elapsed_time = elapsedTimeStr; } // Optionally: Update the incident record // current.update(); // This line is generally not needed because it's an "after" business rule })(current, previous);- Save and Activate the Business Rule:
- Click
Submitto save your Business Rule. - Ensure the Business Rule is active.
- Click
Explanation:
- Querying the task_sla Table: The script queries the
task_slatable to find SLA records that are related to the current incident record and are in the "in_progress" stage. - Calculating Business Duration: The script extracts the
business_durationfield (which holds the elapsed time in milliseconds) from the task_sla record. - Formatting Elapsed Time: The milliseconds are converted into a more human-readable format (optional) and stored in the
u_test_elapsed_timefield. - Updating the Field: The formatted elapsed time string is stored in the
u_test_elapsed_timecustom field.
Notes:
- Testing: Test the business rule in a development or test environment to make sure it functions as expected.
- Performance: Be cautious of performance impacts, particularly if the table has a large number of records or if the business rule runs frequently.
- Edge Cases: Consider handling cases where no active SLA is found or multiple SLAs are associated with a single incident.
With these steps, you should be able to accurately fetch the business elapsed time from the
business_durationfield of the current in-progress SLA and store it in your custom fieldu_test_elapsed_time. -
- User
in incident business duration it shows 22 minutes, i need to see ecaxt 22 minutes in custom string field , not in dmt format
- Assistant
To store the exact business duration (in minutes) from the
business_durationfield in thetask_slatable into your custom fieldu_test_elapsed_timein theincidenttable without converting it to a more complex time format, you can directly extract and convert this duration to minutes. Here's how you can do it:Steps:
-
Create Custom Field:
- Navigate to your
Incidenttable. - Create a new field called
u_test_elapsed_timeof typeString.
- Navigate to your
-
Create the Business Rule:
- Navigate to
System Definition > Business Rulesand clickNew.
- Navigate to
-
Configure the Basic Information:
- Name: Give your business rule a name, for example, "Update Business Elapsed Time".
- Table: Select
Incident. - Active: Ensure this checkbox is selected.
- Advanced: Check both the
AdvancedandWhen to Runcheckboxes to enable scripting and control when the rule executes.
-
When to Run:
- When: Choose
After. - Insert: Check this box if you want it to run after record insertion.
- Update: Check this box if you want it to run after record updates.
- Filter Conditions: Set filter conditions if needed (e.g., when a specific field is updated).
- When: Choose
-
Script:
- Add the following script to calculate the Business Duration in minutes for the current SLA and store it in
u_test_elapsed_time.
- Add the following script to calculate the Business Duration in minutes for the current SLA and store it in
(function executeRule(current, previous /*null when async*/) { // Query to find active SLA records associated with the current incident var taskSlaGR = new GlideRecord('task_sla'); taskSlaGR.addQuery('task', current.sys_id); taskSlaGR.addQuery('stage', 'in_progress'); // Ensuring it's the in-progress SLA taskSlaGR.query(); // Check if an in-progress SLA is found if (taskSlaGR.next()) { // Get the business duration (elapsed time) from the SLA in milliseconds var businessDurationMs = taskSlaGR.business_duration; // Convert milliseconds to minutes var businessDurationMinutes = Math.floor(businessDurationMs / (1000 * 60)); // Store the exact duration in minutes in the custom field as a string current.u_test_elapsed_time = businessDurationMinutes + " minutes"; } })(current, previous);- Save and Activate the Business Rule:
- Click
Submitto save your Business Rule. - Ensure the Business Rule is active.
- Click
Explanation:
- Querying the task_sla Table: The script queries the
task_slatable for the SLA records that are related to the current incident record and are in the "in_progress" stage. - Calculating Business Duration in Minutes: The script extracts the
business_durationfield which contains the elapsed time in milliseconds. It then converts this duration from milliseconds to minutes usingMath.floor(businessDurationMs / (1000 * 60)). - Storing Business Duration: The calculated duration in minutes is stored in the custom field
u_test_elapsed_timeas a string formatted as "XX minutes".
Notes:
- Testing: Test the business rule in a development or test environment thoroughly to make sure it functions as expected under various scenarios.
- Performance: Be aware of the performance implications, especially if querying large tables or running the rule frequently.
- Edge Cases: Consider handling cases where no active SLA is found or multiple SLAs are associated with a single incident.
By following these steps, you should be able to store the exact business duration in minutes from the
business_durationfield of the current in-progress SLA into the custom fieldu_test_elapsed_timeon theincidenttable. -
- User
it shows NaN minutes
- Assistant
The issue with
NaN(Not a Number) minutes may occur if thebusiness_durationfield is not properly converted or if the field is not found correctly. To ensure we're correctly getting thebusiness_durationin milliseconds and converting it to minutes, let's add a few more checks and debug outputs to the script.Updated Script with Debugging:
-
Ensure the Custom Field Exists:
- Make sure you have a
Stringtype custom field namedu_test_elapsed_timein theincidenttable.
- Make sure you have a
-
Modify the Business Rule Script:
(function executeRule(current, previous /*null when async*/) { // Query to find active SLA records associated with the current incident var taskSlaGR = new GlideRecord('task_sla'); taskSlaGR.addQuery('task', current.sys_id); taskSlaGR.addQuery('stage', 'in_progress'); // Ensuring it's the in-progress SLA taskSlaGR.query(); // Check if an in-progress SLA is found if (taskSlaGR.next()) { // Get the business duration (elapsed time) from the SLA in milliseconds var businessDurationMs = taskSlaGR.business_duration; // Ensure businessDurationMs is not null or undefined if (!businessDurationMs) { gs.log("No business duration found for task " + current.sys_id); return; } // Convert milliseconds to minutes var businessDurationMinutes = Math.floor(businessDurationMs / (1000 * 60)); // Check if businessDurationMinutes is a valid number if (isNaN(businessDurationMinutes)) { gs.log("Calculated business duration in minutes is NaN for task " + current.sys_id); return; } // Store the exact duration in minutes in the custom field as a string current.u_test_elapsed_time = businessDurationMinutes + " minutes"; } else { gs.log("No in-progress SLA found for task " + current.sys_id); } })(current, previous);Explanation and Debugging Steps:
-
Verify
business_durationField:- Ensure that the
business_durationfield exists in thetask_slatable and contains values in milliseconds.
- Ensure that the
-
Debug Logging:
- Added checks and log statements to debug the values:
- Check if
businessDurationMsis undefined or null. - Check if converting
businessDurationMsto minutes results in a valid number.
- Check if
- These log statements will help identify where the issue is occurring.
- Added checks and log statements to debug the values:
-
Query and Conversion:
- Ensure the
queryandconversionlogic is correct and thatbusiness_durationholds the expected data.
- Ensure the
-
Activator Business Rule Logging:
- Check the logs in
System Logs > Allfor messages from thegs.logstatements to see if there are any hints why theNaNvalue appears.
- Check the logs in
Additional Notes:
- Testing:
- Perform thorough testing in a development or test environment after making these changes.
- Incident with No Active SLA:
- The log will indicate if there are no active SLAs, helping you address any missing data issues.
- Data Verification:
- Double-check that
business_durationis populated correctly in thetask_slatable for the relevant SLA records.
- Double-check that
By following these steps, you should be able to troubleshoot and fix the issue with
NaNminutes and ensure the exact business duration from the current running in-progress SLA is stored correctly in theu_test_elapsed_timecustom field. -
- User
custom field is also duration field
- Assistant
If your custom field
u_test_elapsed_timeis of typeDuration, you can assign the calculated duration directly to this field without needing to format it as a string. Here’s an updated and simplified business rule script to achieve this:Steps:
-
Ensure the Custom Field:
- Ensure you have a custom field named
u_test_elapsed_timein theIncidenttable and that it is of typeDuration.
- Ensure you have a custom field named
-
Modify the Business Rule Script:
Here's the updated script to extract the
business_durationfrom the in-progresstask_slarecord and set it to theu_test_elapsed_timefield:(function executeRule(current, previous /*null when async*/) { // Query to find active SLA records associated with the current incident var taskSlaGR = new GlideRecord('task_sla'); taskSlaGR.addQuery('task', current.sys_id); taskSlaGR.addQuery('stage', 'in_progress'); // Ensuring it's the in-progress SLA taskSlaGR.query(); // Check if an in-progress SLA is found if (taskSlaGR.next()) { // Get the business duration (elapsed time) from the SLA in milliseconds var businessDurationMs = taskSlaGR.business_duration; // Ensure businessDurationMs is not null or undefined if (!businessDurationMs) { gs.log("No business duration found for task " + current.sys_id); return; } // Store the exact duration in milliseconds in the custom duration field current.u_test_elapsed_time.setValue(businessDurationMs); } else { gs.log("No in-progress SLA found for task " + current.sys_id); } })(current, previous);Explanation:
- Querying the
task_slaTable: The script queries thetask_slatable to find SLA records associated with the current incident record and are in thein_progressstage. - Extracting Business Duration: The script retrieves the
business_durationfield, which is in milliseconds. - Setting Duration Field:
- Instead of converting the milliseconds to a string, it directly assigns the duration to the
u_test_elapsed_timefield usingsetValue.
- Instead of converting the milliseconds to a string, it directly assigns the duration to the
- Log Statements: Added log statements to help with debugging if needed.
Notes:
- Testing: Perform thorough testing in a development or test environment to make sure this works correctly under various scenarios.
- Incident with No Active SLA: The logs will indicate if no active SLAs are found, helping you address any missing data issues.
- Debugging: Check
System Logs > Allfor any potential log messages that help troubleshoot issues.
By following these steps, you should be able to directly store the exact business elapsed time in the custom
u_test_elapsed_timeduration field on theIncidenttable. This approach ensures the duration is stored in the correct format and avoids formatting as a string. -