Skip to content

Commit 48f9b74

Browse files
authored
Merge branch 'ServiceNowDevProgram:main' into Hactoberfest-2025-1st-pull-request
2 parents 598bfd9 + 81b587d commit 48f9b74

File tree

25 files changed

+1041
-0
lines changed

25 files changed

+1041
-0
lines changed
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
Date Range Validation (Within 30 Days) in Client Side
2+
3+
This ServiceNow client script provides real-time date validation for form fields, ensuring users can only select dates within a specific 30-day window from today's date. The script runs automatically when a user changes a date field value, providing immediate feedback and preventing invalid date submissions.
4+
5+
The script validates that any date entered in a form field meets these criteria:
6+
Minimum Date: Today's date (no past dates allowed)
7+
Maximum Date: 30 days from today's date
8+
Real-time Validation: Instant feedback as users type or select dates
9+
User-friendly Errors: Clear error messages explaining the valid date range
10+
Automatic Field Clearing: Invalid dates are automatically cleared to prevent submission
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
2+
if (isLoading || newValue === '') {
3+
return;
4+
}
5+
6+
var todayDate = new Date();
7+
var futureDate = new Date();
8+
futureDate.setDate(futureDate.getDate() + 30);
9+
10+
var todayDateStr = formatDate(todayDate, g_user_date_format);
11+
var futureDateStr = formatDate(futureDate, g_user_date_format);
12+
13+
var selectedDateNum = getDateFromFormat(newValue, g_user_date_format);
14+
var todayDateNum = getDateFromFormat(todayDateStr, g_user_date_format);
15+
var futureDateNum = getDateFromFormat(futureDateStr, g_user_date_format);
16+
17+
if (selectedDateNum < todayDateNum || selectedDateNum > futureDateNum) {
18+
g_form.showFieldMsg(control, 'Date must be between today and 30 days from today', 'error');
19+
g_form.clearValue(control);
20+
} else {
21+
g_form.hideFieldMsg(control);
22+
}
23+
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
An `onLoad` client script that validates required fields in specific ServiceNow form views.
2+
3+
This ServiceNow client script provides automatic validation of required form fields when users access specific form views. The script runs immediately when a form loads and checks that critical fields are populated, displaying user-friendly error messages for any missing required information. This ensures data completeness and improves form submission success rates by catching validation issues early in the user workflow.
4+
5+
What This Script Does:
6+
The onLoad client script performs comprehensive field validation with these key capabilities:
7+
View-Specific Validation: Only triggers validation when accessing a designated form view
8+
Multiple Field Support: Validates multiple required fields simultaneously in a single operation
9+
Smart Field Detection: Uses field labels (not technical names) in error messages for better user experience
10+
Consolidated Error Display: Shows all missing required fields in a single, clear error message
11+
Immediate Feedback: Provides instant validation results as soon as the form loads
12+
Non-Intrusive Design: Displays informational errors without blocking form interaction
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
function onLoad(){
2+
var targetViewName = 'your_target_view_name';
3+
var requiredFields = ['field1', 'field2', 'field3'];
4+
5+
var currentViewName = g_form.getViewName();
6+
7+
if (currentViewName === targetViewName) {
8+
var emptyFields = [];
9+
10+
for (var i = 0; i < requiredFields.length; i++) {
11+
var fieldValue = g_form.getValue(requiredFields[i]);
12+
if (!fieldValue || fieldValue.trim() === '') {
13+
emptyFields.push(g_form.getLabelOf(requiredFields[i]));
14+
}
15+
}
16+
17+
if (emptyFields.length > 0) {
18+
var errorMessage = "The following required fields cannot be empty: " +
19+
emptyFields.join(', ');
20+
g_form.addErrorMessage(errorMessage);
21+
}
22+
}
23+
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
ServiceNow Script: Find Oldest Open Incidents per Group
2+
This script leverages GlideAggregate to efficiently find the oldest active incident for each assignment group. This is a powerful tool for monitoring and reporting on potential service level agreement (SLA) risks and improving incident management processes.
3+
Overview
4+
The script performs the following actions:
5+
Initializes GlideAggregate: Creates an aggregate query on the incident table.
6+
Filters Active Incidents: Uses addActiveQuery() to restrict the search to only open (active) incidents.
7+
Aggregates by Minimum Date: Finds the minimum (MIN) opened_at date, which represents the oldest record.
8+
Groups by Assignment Group: Groups the results by the assignment_group to get a separate result for each team.
9+
Iterates and Logs: Loops through the query results and logs the assignment group and the opening date of its oldest open incident.
10+
How to use
11+
This script is intended to be used in a server-side context within a ServiceNow instance. Common use cases include:
12+
Scheduled Job: Run this script on a regular schedule (e.g., daily) to generate a report on aging incidents.
13+
Script Include: Incorporate the logic into a reusable function within a Script Include, allowing other scripts to call it.
14+
15+
Use code with caution.
16+
17+
Installation
18+
As a Scheduled Job
19+
Navigate to System Definition > Scheduled Jobs.
20+
Click New and select Automatically run a script of your choosing.
21+
Name the job (e.g., Find Oldest Open Incidents).
22+
Set your desired frequency and time.
23+
Paste the script into the Run this script field.
24+
Save and activate the job.
25+
As a Script Include
26+
Navigate to System Definition > Script Includes.
27+
Click New.
28+
Name it (e.g., IncidentHelper).
29+
API Name: global.IncidentHelper
30+
31+
32+
Customization
33+
Change the output: Modify the gs.info() line to instead write to a custom log, send an email, or create a report.
34+
Refine the query: Add more addQuery() statements to filter incidents by other criteria, such as priority or category.
35+
Change the aggregate: Use MAX instead of MIN to find the newest incident in each group.
36+
Get incident details: To get the actual incident record (e.g., its number), you would need to perform a secondary GlideRecord query based on the aggregated data.
37+
Dependencies
38+
This script uses standard ServiceNow APIs (GlideAggregate, gs). No external libraries are required.
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
var ga = new GlideAggregate('incident');
2+
ga.addActiveQuery();
3+
ga.addAggregate('MIN', 'opened_at');
4+
ga.groupBy('assignment_group');
5+
ga.query();
6+
7+
while (ga.next()) {
8+
var group = ga.assignment_group.getDisplayValue();
9+
var oldestIncidentDate = ga.getAggregate('MIN', 'opened_at');
10+
gs.info("Oldest open incident for " + group + " was created on: " + oldestIncidentDate);
11+
}
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# Integrate ServiceNow with External ML Model API
2+
3+
## Overview
4+
Call an external ML API from ServiceNow to get AI predictions for incidents and auto-update records.
5+
6+
## What It Does
7+
- Sends incident data to external ML API via REST call
8+
- Receives predictions (resolution time, category, priority, etc.)
9+
- Automatically updates incident record with predictions
10+
- Includes error handling and logging
11+
12+
## Use Cases
13+
- Predict how long an incident will take to resolve
14+
- Auto-suggest the right category/priority
15+
- Recommend best assignment group
16+
- Get risk scores for changes
17+
18+
## Files
19+
- `ml_prediction_script_include.js` - Script Include that calls ML API
20+
21+
## How to Use
22+
1. Create Script Include in ServiceNow named `MLPredictionClient`
23+
2. Copy code from `ml_prediction_script_include.js`
24+
3. Update `ML_API_URL` and `API_KEY` with your ML service details
25+
4. Call it from a Business Rule or Client Script to get predictions
26+
5. Store results back in incident fields
27+
28+
## Example Usage
29+
```javascript
30+
var mlClient = new MLPredictionClient();
31+
var prediction = mlClient.predictIncident({
32+
description: incident.description,
33+
category: incident.category,
34+
priority: incident.priority
35+
});
36+
37+
incident.estimated_resolution_time = prediction.predicted_resolution_time;
38+
incident.update();
39+
```
40+
41+
## Requirements
42+
- ServiceNow instance
43+
- External ML API endpoint (REST)
44+
- API key or token
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
// Script Include: MLPredictionClient
2+
// Calls external ML API to get incident predictions
3+
4+
var MLPredictionClient = Class.create();
5+
MLPredictionClient.prototype = {
6+
initialize: function() {
7+
this.ML_API_URL = 'https://your-ml-api.com/predict';
8+
this.API_KEY = 'your-api-key-here';
9+
},
10+
11+
predictIncident: function(incidentData) {
12+
try {
13+
var request = new RESTMessageV2();
14+
request.setEndpoint(this.ML_API_URL);
15+
request.setHttpMethod('POST');
16+
request.setRequestHeader('Authorization', 'Bearer ' + this.API_KEY);
17+
request.setRequestHeader('Content-Type', 'application/json');
18+
19+
// Send incident details to ML API
20+
var payload = {
21+
description: incidentData.description,
22+
category: incidentData.category,
23+
priority: incidentData.priority
24+
};
25+
request.setRequestBody(JSON.stringify(payload));
26+
27+
// Get prediction from external ML service
28+
var response = request.execute();
29+
var result = JSON.parse(response.getBody());
30+
31+
return {
32+
estimated_hours: result.estimated_hours,
33+
predicted_category: result.category,
34+
confidence: result.confidence
35+
};
36+
} catch (error) {
37+
gs.log('ML API Error: ' + error, 'MLPredictionClient');
38+
return null;
39+
}
40+
},
41+
42+
type: 'MLPredictionClient'
43+
};
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
Scheduled Job Update Set Capture Script
2+
3+
This ServiceNow background script addresses a critical deployment challenge by programmatically capturing scheduled jobs in update sets.
4+
By default, ServiceNow scheduled jobs are not automatically captured in update sets, making them difficult to migrate between environments.
5+
This script uses the GlideUpdateManager2 API to force a scheduled job record into the current update set, enabling seamless deployment through standard update set processes.
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
var gr = new GlideRecord('sysauto_script');
2+
gr.get('<sys_id of your scheduled job>');
3+
var gum = new GlideUpdateManager2();
4+
gum.saveRecord(gr);

0 commit comments

Comments
 (0)