Skip to content
The Chat Archive
gpt-4o-2024-05-13· OpenAI WildChat-4.8M (AI2)

in servicenow, Does anyone have any insight on how to use a business rule to get the…

  1. 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?

  2. 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:

    1. Create Custom Field:

      • First, create a custom field "Test Elapsed Time" of type Duration (or String if you prefer) in your target table.
    2. Create the Business Rule:

      • Go to System Definition > Business Rules and click on New.
    3. 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.
    4. When to Run:

      • In the When to run section, set up the conditions for when the Business Rule should execute.
      • You can decide to run it before or after record 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.
    5. 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);
    
    1. Save and Activate Business Rule:
    • Click on Submit to 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 calculateBusinessElapsedTime might 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.

  3. User

    not working give me accurate business rule that store sla bussiness elapsed time in u_test_elapsed_time custom field String

  4. 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:

    1. Create Custom Field

      • Navigate to your target table (e.g., Incident).
      • Create a new field called u_test_elapsed_time of type String.
    2. Create the Business Rule

      • Go to System Definition > Business Rules and click New.
    3. 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.
    4. 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).
    5. 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:
    (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);
    
    1. Save and Activate the Business Rule:
      • Click Submit to save your Business Rule.
      • Ensure the Business Rule is active.

    Explanation:

    • task_sla Table: The task_sla table tracks the SLA records associated with tasks. The business_time field in this table stores the business elapsed time in milliseconds.
    • Query: This script queries the task_sla table 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_time field.

    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_sla table 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.

  5. User

    how to store Business elapsed time from current running in progress SLA in incident to custom field test time

  6. Assistant

    To store the Business Elapsed Time from the current running in-progress SLA into a custom field called u_test_elapsed_time on the incident table, you can create a business rule in ServiceNow. Here’s a step-by-step guide to achieve this:

    Steps:

    1. Create Custom Field:

      • Navigate to your Incident table.
      • Create a new field called u_test_elapsed_time of type String.
    2. Create the Business Rule:

      • Navigate to System Definition > Business Rules and click on New.
    3. 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 Advanced and When to Run checkboxes to enable scripting and control when the rule executes.
    4. 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).
    5. Script:

      • Add a script to calculate the Business Elapsed Time for the current SLA and store it in u_test_elapsed_time.
    (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);
    
    1. Save and Activate the Business Rule:
      • Click Submit to save your Business Rule.
      • Ensure the Business Rule is active.

    Explanation:

    • Querying the task_sla Table: This script queries the task_sla table 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_time field in the task_sla table holds the elapsed time in milliseconds which is then converted to a human-readable format (days, hours, minutes, seconds) for storage in u_test_elapsed_time.
    • Updating the Field: The formatted elapsed time string is stored in the u_test_elapsed_time custom 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.

  7. User

    sla field name is business_duration

  8. Assistant

    If the field that holds the business elapsed time for the SLA in your task_sla table is called business_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 field u_test_elapsed_time on the incident table.

    Steps:

    1. Create Custom Field:

      • Navigate to your Incident table.
      • Create a new field called u_test_elapsed_time of type String.
    2. Create the Business Rule:

      • Navigate to System Definition > Business Rules and click New.
    3. 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 Advanced and When to Run checkboxes to enable scripting and control when the rule executes.
    4. 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).
    5. Script:

      • Add the following script to calculate the Business Elapsed Time for the current SLA and store it in u_test_elapsed_time.
    (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);
    
    1. Save and Activate the Business Rule:
      • Click Submit to save your Business Rule.
      • Ensure the Business Rule is active.

    Explanation:

    • Querying the task_sla Table: The script queries the task_sla table 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_duration field (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_time field.
    • Updating the Field: The formatted elapsed time string is stored in the u_test_elapsed_time custom 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_duration field of the current in-progress SLA and store it in your custom field u_test_elapsed_time.

  9. User

    in incident business duration it shows 22 minutes, i need to see ecaxt 22 minutes in custom string field , not in dmt format

  10. Assistant

    To store the exact business duration (in minutes) from the business_duration field in the task_sla table into your custom field u_test_elapsed_time in the incident table 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:

    1. Create Custom Field:

      • Navigate to your Incident table.
      • Create a new field called u_test_elapsed_time of type String.
    2. Create the Business Rule:

      • Navigate to System Definition > Business Rules and click New.
    3. 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 Advanced and When to Run checkboxes to enable scripting and control when the rule executes.
    4. 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).
    5. Script:

      • Add the following script to calculate the Business Duration in minutes for the current SLA and store it in u_test_elapsed_time.
    (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);
    
    1. Save and Activate the Business Rule:
      • Click Submit to save your Business Rule.
      • Ensure the Business Rule is active.

    Explanation:

    • Querying the task_sla Table: The script queries the task_sla table 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_duration field which contains the elapsed time in milliseconds. It then converts this duration from milliseconds to minutes using Math.floor(businessDurationMs / (1000 * 60)).
    • Storing Business Duration: The calculated duration in minutes is stored in the custom field u_test_elapsed_time as 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_duration field of the current in-progress SLA into the custom field u_test_elapsed_time on the incident table.

  11. User

    it shows NaN minutes

  12. Assistant

    The issue with NaN (Not a Number) minutes may occur if the business_duration field is not properly converted or if the field is not found correctly. To ensure we're correctly getting the business_duration in milliseconds and converting it to minutes, let's add a few more checks and debug outputs to the script.

    Updated Script with Debugging:

    1. Ensure the Custom Field Exists:

      • Make sure you have a String type custom field named u_test_elapsed_time in the incident table.
    2. 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:

    1. Verify business_duration Field:

      • Ensure that the business_duration field exists in the task_sla table and contains values in milliseconds.
    2. Debug Logging:

      • Added checks and log statements to debug the values:
        • Check if businessDurationMs is undefined or null.
        • Check if converting businessDurationMs to minutes results in a valid number.
      • These log statements will help identify where the issue is occurring.
    3. Query and Conversion:

      • Ensure the query and conversion logic is correct and that business_duration holds the expected data.
    4. Activator Business Rule Logging:

      • Check the logs in System Logs > All for messages from the gs.log statements to see if there are any hints why the NaN value appears.

    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_duration is populated correctly in the task_sla table for the relevant SLA records.

    By following these steps, you should be able to troubleshoot and fix the issue with NaN minutes and ensure the exact business duration from the current running in-progress SLA is stored correctly in the u_test_elapsed_time custom field.

  13. User

    custom field is also duration field

  14. Assistant

    If your custom field u_test_elapsed_time is of type Duration, 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:

    1. Ensure the Custom Field:

      • Ensure you have a custom field named u_test_elapsed_time in the Incident table and that it is of type Duration.
    2. Modify the Business Rule Script:

    Here's the updated script to extract the business_duration from the in-progress task_sla record and set it to the u_test_elapsed_time field:

    (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_sla Table: The script queries the task_sla table to find SLA records associated with the current incident record and are in the in_progress stage.
    • Extracting Business Duration: The script retrieves the business_duration field, 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_time field using setValue.
    • 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 > All for 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_time duration field on the Incident table. This approach ensures the duration is stored in the correct format and avoids formatting as a string.