|
| 1 | +# Objective |
| 2 | +This ServiceNow business rule script is designed to automatically calculate the due date for a task based on its priority. It executes before the record is saved (Before Business Rule) and calculates the due date in hours, depending on the priority level of the task. |
| 3 | + |
| 4 | +# Priority-to-Due-Date Mapping |
| 5 | +``` |
| 6 | +var priorityToDueDate = { |
| 7 | + 1: 4, // High priority: Due in 4 hours |
| 8 | + 2: 24, // Medium priority: Due in 24 hours |
| 9 | + 3: 72 // Low priority: Due in 72 hours |
| 10 | +}; |
| 11 | +``` |
| 12 | +This section defines a JavaScript object called priorityToDueDate that maps priority values to due date intervals in hours. For example, if the task has a priority of 1 (High), its due date will be set to 4 hours from the current date and time. |
| 13 | +Alternatively, we can store these mapping values in a custom table, allowing us to update them as necessary. |
| 14 | + |
| 15 | +# Get Priority Value |
| 16 | +``` |
| 17 | +var priority = current.priority; |
| 18 | +``` |
| 19 | +This line retrieves the priority value from the current record and stores it in a variable called priority. |
| 20 | + |
| 21 | +# Check Priority Validity and Mapping |
| 22 | +``` |
| 23 | +if (priority && priorityToDueDate.hasOwnProperty(priority)) { |
| 24 | + // Code goes here |
| 25 | +} |
| 26 | +``` |
| 27 | +This if statement checks if the priority variable is defined (not null or undefined) and if it exists as a key in the priorityToDueDate mapping. This ensures that the priority value is valid and has a corresponding due date interval. |
| 28 | + |
| 29 | +# Calculate Due Date |
| 30 | +``` |
| 31 | +var dueDate = new GlideDateTime(); |
| 32 | +dueDate.addHours(priorityToDueDate[priority]); |
| 33 | +``` |
| 34 | +If the priority is valid, a new GlideDateTime object is created, and the addHours method is used to add the appropriate number of hours (based on the priority) to the current date and time. This calculates the due date. |
| 35 | + |
| 36 | +# Update Due Date Field |
| 37 | +``` |
| 38 | +current.due_date = dueDate; |
| 39 | +``` |
| 40 | +Finally, the due_date field in the current record is updated with the calculated due date. |
0 commit comments