サーバーサイドスクリプトのユースケース
サーバーサイドスクリプトのユースケースには、出力のログ記録、ユーザーオブジェクトの取得、日付/時刻値の変更などがあります。
ビジネスルールからワークフロースクラッチパッドへのアクセス
カタログアイテムが要求されました。添付されたワークフローには、スクラッチパッドに値を入力するスクリプト実行アクティビティが含まれています。要求アイテムで実行されているビジネスルールから、スクラッチパッドの値を取得または設定します。
必須条件
必要なロール:admin。
名前:ビジネスルールからのワークフロースクラッチパッドへのアクセス。
タイプ:ビジネスルール。
テーブル:sc_req_item (要求アイテム)。
説明:カタログアイテムが要求されました。添付されたワークフローには、スクラッチパッドに値を入力するスクリプト実行アクティビティが含まれています。要求アイテムで実行されているビジネスルールから、スクラッチパッドの値を取得または設定します。
パラメーター:適用外。
//the run script activity sets a value in the scratchpad
workflow.scratchpad.important_msg = "scratch me";
//get the workflow script include helper
var workflow = new Workflow();
//get the requested items workflow context
//this will get all contexts so you will need to get the proper one if you have multiple workflows for a record
var context = workflow.getContexts(current);
//make sure we have a valid context
if (context.next()) {
//get a value from the scratchpad
var msg = context.scratchpad.important_msg;
//msg now equals "scratch me", that was set in the run script activity
//add or modify a scratchpad value
context.scratchpad.status = "completed";
//we need to save the context record to save the scratchpad
context.update();
}配送計画タスクに基づいたカタログアイテムのグループへのアサイン
デスクトップグループにアサインされたカタログタスクを持つ配送計画を使用する場合に、サービスカタログアイテムをデータベースグループにアサインします。
必須条件
必要なロール:admin
名前:配送計画タスクに基づいたカタログアイテムのグループへのアサイン。
タイプ:アサインルール。
説明:このアサインルールは、デスクトップグループにアサインされたカタログタスクを持つ配送計画を使用する場合に、サービスカタログアイテムをデータベースグループにアサインします。
スクリプト:
//Return catalog items that have no group but do have a delivery plan assigned var ri = new GlideRecord ( "sc_cat_item" ) ;
ri.addQuery("group", "=", null);
ri.addQuery("delivery_plan", "!=", null);
ri.query();
while(ri.next()) {
gs.log("Found an item");
//Return tasks that point to the same delivery plan as the above item
var dptask = new GlideRecord("sc_cat_item_delivery_task");
dptask.addQuery("delivery_plan", "=", ri. delivery_plan);
dptask.query();
while(dptask.next()) {
gs.log("Found a task");
var gp = dptask.group.getDisplayValue();
gs.log(gp);
//If the task is assigned to desktop, assign the item's group to desktop
if (dptask.group.getDisplayValue() == "Desktop") {
ri.group.setDisplayValue("Desktop");
gs.log("updating " + ri.getDisplayValue());
ri.update();
break; } } }期間の計算
タスクまたはプロセスの期限を指定する方法のユーザーへの提供が必要になることがよくあります。DurationCalculator スクリプトインクルードを使用すると、単純な期間または相対期間を使用して期日を計算できます。
10am-5pm on Monday (6 hours) + 8am-12pm on Tuesday (4 hours)DurationCalculator メソッドへの入力として使用できるスケジュールについては、「スケジュールの作成と使用」を参照してください。
このスクリプトは、DurationCalculator を使用して期日を計算する方法を示しています。
/**
* Demonstrate the use of DurationCalculator to compute a due date.
*
* You must have a start date and a duration. Then you can compute a
* due date using the constraints of a schedule.
*/
gs.include('DurationCalculator');
executeSample();
/**
* Function to house the sample script.
*/function executeSample(){
// First we need a DurationCalculator object.var dc =new DurationCalculator();
// --------------- No schedule examples ------------------
// Simple computation of a due date without using a schedule. Seconds// are added to the start date continuously to get to a due date.
dc.setStartDateTime("5/1/2012");if(!dc.calcDuration(2*24*3600)){// 2 days
gs.log("*** Error calculating duration");return;}
gs.log("calcDuration no schedule: "+ dc.getEndDateTime());// "2012-05-03 00:00:00" two days later
// Start in the middle of the night (2:00 am) and compute a due date 1 hour in the future// Without a schedule this yields 3:00 am.
dc.setStartDateTime("5/3/2012 02:00:00");if(!dc.calcDuration(3600)){
gs.log("*** Error calculating duration");return;}
gs.log("Middle of night + 1 hour (no schedule): "+ dc.getEndDateTime());// No scheduled start date, just add 1 hour
// -------------- Add a schedule to the date calculator ---------------------
addSchedule(dc);
// Start in the middle of the night and compute a due date 1 hour in the future.// Since we start at 2:00 am the computation adds the 1 hour from the start// of the day, 8:00am to get to 9:00am
dc.setStartDateTime("5/3/2012 02:00:00");if(!dc.calcDuration(3600)){//
gs.log("*** Error calculating duration");return;}
gs.log("Middle of night + 1 hour (with 8-5 schedule): "+ dc.getEndDateTime());// 9:00 am
// Start in the afternoon and add hours beyond quiting time. Our schedule says the work day// ends at 5:00pm, if the duration extends beyond that, we roll over to the next work day.// In this example we are adding 4 hours to 3:00pm which gives us 10:00 am the next day.
dc.setStartDateTime("5/3/2012 15:00:00");if(!dc.calcDuration(4*3600)){//
gs.log("*** Error calculating duration");return;}
gs.log("Afternoon + 4 hour (with 8-5 schedule): "+ dc.getEndDateTime());// 10:00 am.
// This is a demo of adding 2 hours repeatedly and examine the result. This// is a good way to visualize the result of a due date calculation.
dc.setStartDateTime("5/3/2012 15:00:00");// for(var i=2; i<24; i+=1){if(!dc.calcDuration(i*3600)){//
gs.log("*** Error calculating duration");return;}
gs.log("add "+ i +" hours gives due date: "+ dc.getEndDateTime());}
// Setting the timezone causes the schedule to be interpreted in the specified timezone.// Run the same code as above with different timezone. Note that the 8 to 5 workday is// offset by the two hours as specified in our timezone.
dc.setTimeZone("GMT-2");
dc.setStartDateTime("5/3/2012 15:00:00");for(var i=2; i<24; i+=1){if(!dc.calcDuration(i*3600)){//
gs.log("*** Error calculating duration");return;}
gs.log("add "+ i +" hours gives due date (GMT-2): "+ dc.getEndDateTime());}}
/**
* Add a specific schedule to the DurationCalculator object.
*
* @param durationCalculator An instance of DurationCalculator
*/function addSchedule(durationCalculator){// Load the "8-5 weekdays excluding holidays" schedule into our duration calculator.var scheduleName ="8-5 weekdays excluding holidays";var grSched =new GlideRecord('cmn_schedule');
grSched.addQuery('name', scheduleName);
grSched.query();if(!grSched.next()){
gs.log('*** Could not find schedule "'+ scheduleName +'"');return;}
durationCalculator.setSchedule(grSched.getUniqueValue(),"GMT");}単純な期間と相対期間
タスクを完了するために必要な作業量を「相対期間」で表すことができます。
相対期間では、開始時間との相対関係で予想できる期限となる日時が決定されます。相対期間の例としては、「翌営業日の 4 pm まで」や「2 営業日後の 10:30 am まで」などがあります。
- 開始が月曜日の 12 pm の場合:翌営業日の 4 pm => 火曜日の 4 pm
- 開始が金曜日の 2 pm の場合:翌営業日の 4 pm => 次の月曜日の 4 pm
相対期間の詳細については、「 Define a relative duration」を参照してください。
単純な期間の計算
このビジネスルールとスクリプトの例は、単純な期間を計算する方法を示しています。
var dur =new DurationCalculator();
dur.setSchedule(current.schedule);
dur.setStartDateTime("");
if(current.duration_type==""){
dur.calcDuration(current.duration.getGlideObject().getNumericValue()/1000);}else{
dur.calcRelativeDuration(current.duration_type);}
current.end_date_time= dur.getEndDateTime();
current.work_seconds= dur.getSeconds();このスクリプトは、DurationCalculator を使用して単純な期間を計算する方法を示しています。
/**
* Sample script demonstrating use of DurationCalculator to compute simple durations
*
*/
gs.include('DurationCalculator');
executeSample();
/**
* Function to house the sample script.
*/
function executeSample(){
// First we need a DurationCalculator object.
var dc =new DurationCalculator();
// Compute a simple duration without any schedule. The arguments
// can also be of type GlideDateTime, such as fields from a GlideRecord.
var dur = dc.calcScheduleDuration("5/1/2012","5/2/2012");
gs.log("calcScheduleDuration no schedule: "+ dur);
// 86400 seconds (24 hours)
// The above sample is useful in limited cases. We almost always want to
// use some schedule in a duration computation, let's load a schedule.
addSchedule(dc);
// Compute a duration using the schedule. The schedule
// specifies a nine hour work day. The output of this is 32400 seconds, or
// a nine hour span.
dur = dc.calcScheduleDuration("5/23/2012 12:00","5/24/2012 12:00");
gs.log("calcScheduleDuration with schedule: "+ dur);
// 32400 seconds (9 hours)
// Compute a duration that spans a weekend and holiday. Even though this
// spans three days, it only spans 9 work hours based on the schedule.
dur = dc.calcScheduleDuration("5/25/2012 12:00","5/29/2012 12:00");
gs.log("calcScheduleDuration with schedule spaning holiday: "+ dur);
// 32400 seconds (9 hours)
// Use the current date time in a calculation. The output of this is
// dependent on when you run it.
var now =new Date();
dur = dc.calcScheduleDuration("5/15/2012",new GlideDateTime());
gs.log("calcScheduleDuration with schedule to now: "+ dur);
// Different on every run.}
/**
* Add a specific schedule to the DurationCalculator object.
*
* @param durationCalculator An instance of DurationCalculator
*/
function addSchedule(durationCalculator){
// Load the "8-5 weekdays excluding holidays" schedule into our duration calculator.
var scheduleName ="8-5 weekdays excluding holidays";
var grSched =new GlideRecord('cmn_schedule');
grSched.addQuery('name', scheduleName);
grSched.query();if(!grSched.next()){
gs.log('*** Could not find schedule "'+ scheduleName +'"');
return;}
durationCalculator.setSchedule(grSched.getUniqueValue());}相対期間の計算
相対期間計算スクリプトの例。
// Next day at 4pm if before 10am
var days =1;
if(calculator.isAfter(calculator.startDateTime,"10:00:00"))
days++;
calculator.calcRelativeDueDate(calculator.startDateTime, days,"16:00:00");このスクリプトは、DurationCalculator を使用して相対期間を計算する方法を示しています。
/**
* Sample use of relative duration calculation.
*
*/
gs.include('DurationCalculator');
executeSample();
/**
* Function to house the sample script.
*/
function executeSample(){
// First we need a DurationCalculator object. We will also use
// the out-of-box relative duration "2 bus days by 4pm"
var dc =new DurationCalculator();
var relDur ="3bf802c20a0a0b52008e2859cd8abcf2";
// 2 bus days by 4pm if before 10am
addSchedule(dc);
// Since our start date is before 10:00am our result is two days from
// now at 4:00pm.
dc.setStartDateTime("5/1/2012 09:00:00");
if(!dc.calcRelativeDuration(relDur)){
gs.log("*** calcRelativeDuration failed");
return;}
gs.log("Two days later 4:00pm: "+ dc.getEndDateTime());
// Since our start date is after 10:00am our result is three days from
// now at 4:00pm.
dc.setStartDateTime("5/1/2012 11:00:00");
if(!dc.calcRelativeDuration(relDur)){
gs.log("*** calcRelativeDuration failed");
return;}
gs.log("Three days later 4:00pm: "+ dc.getEndDateTime());}
/**
* Add a specific schedule to the DurationCalculator object.
*
* @param durationCalculator An instance of DurationCalculator
*/
function addSchedule(durationCalculator){
// Load the "8-5 weekdays excluding holidays" schedule into our duration calculator.
var scheduleName ="8-5 weekdays excluding holidays";
var grSched =new GlideRecord('cmn_schedule');
grSched.addQuery('name', scheduleName);
grSched.query();
if(!grSched.next()){
gs.log('*** Could not find schedule "'+ scheduleName +'"');
return;}
durationCalculator.setSchedule(grSched.getUniqueValue(),"GMT");}相対期間の実装方法
cmn_relative_duration テーブルと DurationCalculator スクリプトインクルードを作成することで、相対期間を実装できます。
始める前に
手順
- cmn_relative_duration テーブルを作成します。
- DurationCalculator スクリプトインクルードを作成します。
- サンプルの相対期間エントリを作成します (たとえば、「4 pm までであれば翌営業日」)。
- 相対期間をサポートするために必要なフィールドを SLA テーブルに追加します。
- SLA の期間計算を変更します。
- SLA の SLA パーセンテージタイマー計算を変更します (これは work_seconds を使用する必要があります)。
- ワークフローにスケジュールフィールドを追加します: スケジュールとタイムゾーン (ワークフローテーブルのフィールドに基づいて選択)。
- 期間サポートフィールドをワークフロータスクアクティビティに追加します。
- タスクアクティビティの期間計算スクリプトを実装します。
相対期間テーブルと DurationCalculator メソッド
cmn_relative_duration テーブルは、期間または相対期間のどちらかでの期日の定義をサポートしています。
このテーブルは、[名前] と [スクリプト] の 2 つのフィールドで構成されています。[スクリプト] フィールドには、相対期間計算スクリプトが含まれています。このスクリプトには、期日の計算に使用される「calculator」変数が含まれています。
DurationCalculator スクリプトインクルードを使用して、期間の計算を実行できます。このスクリプトインクルードで使用できるメソッドは次のとおりです。
| メソッド | 説明 |
|---|---|
| setSchedule(String schedID, [String timezone]) | 期日の計算に使用するスケジュールとタイムゾーンを設定します。 |
| setStartDateTime(GlideDateTime start) | 期間計算のための開始時刻を設定します。[開始] が空の場合、現在の日付/時刻が使用されます。 |
| calcDuration(int seconds) | 終了日時を計算します。完了すると、this.endDateTime および this.seconds プロパティは、計算の結果を示すように設定されます。 |
| calcRelativeDuration(String relativeDurationID) | 指定された相対期間スクリプトを使用して期間を計算します。完了すると、this.endDateTime および this.seconds プロパティは、計算の結果を示すように設定されます。 |
| getEndDateTime() | 期間の終了日時を示す、calcDuration/calcRelativeDuration によって設定された this.endDateTime プロパティを取得します。 |
| getSeconds() | 期間中に実行される作業の合計秒数を示す、calcDuration/calcRelativeDuration によって設定された this.seconds プロパティを取得します。 注: これは、開始時間と終了時間の合計時間ではなく、合計作業時間であり、作業時間のパーセンテージを決定するために使用されます。 |
| getTotalSeconds() | 期間の開始時刻から終了時刻までの合計秒数を示す、calcDuration/calcRelativeDuration によって設定された this.totalSeconds プロパティを取得します。 |
相対期間スクリプトでは、次の関数が使用されます。
| 関数 | 説明 |
|---|---|
| boolean isAfter(GlideDateTime dt, String time) | 「time」は「dt」で指定された時刻より後になっているかどうか。dt が空白の場合、現在の日付/時刻が使用されます。時間は 24 時間形式の「hh:mm:ss」で表されます。 |
| calcRelativeDueDate(GlideDateTime start, int days, String endTime) | 「start」で始まり、スケジュールとタイムゾーンを使用して「days」を追加して、期日を計算します。作業の期日を特定できたら、その日の「endTime」に時間を設定します。完了すると、this.endDateTime および this.seconds プロパティは、計算の結果を示すように設定されます。「endTime」が空白の場合は、作業終了日の終了時間を使用します。 |
ユーザーオブジェクトを取得する
ビジネスルールやその他のサーバースクリプトでは、gs.getUser() メソッドがユーザーオブジェクトを返します。ユーザーオブジェクトは、現在ログインしているユーザーの内部表現であり、ユーザーやさまざまなユーティリティ機能に関する情報を提供します。
このタスクについて
手順
ログ出力
GSLog は、呼び出し元ごとに識別される sys_properties 値によって選択可能なログ出力のレベルを実装することで、スクリプトのログ記録とデバッグを簡素化するスクリプトインクルードです。
ログレベル
ログは、debug、info、notice、warning、err、または crit のレベルを指定できます (BSD syslog.h 以降とフォロワー)。デフォルトのログ記録レベルは notice であるため、状況に応じてレベルを選択する必要があります。
使用する状況
イベントログ記録を実装するサーバー側スクリプトに使用します。
API リファレンスについては、「GSLog()」を参照してください。
詳細については、「スクリプトのデバッグ」を参照してください。
GlideDateTime フィールド値の変更
この例では、サーバーサイドスクリプトを使用して GlideDateTime フィールド値を変更する方法を示します。
//You first need a GlideDateTime object
//this can be from instantiating a new object "var gdt = new GlideDateTime()"
//or getting the object from a GlideDateTime field
//getting the field value (for example: var gdt = current.start_date) only returns the string value, not the object
//to get the object use var gdt = current.start_date.getGlideObject(); (GlideElement)
//now gdt is a GlideDateTime object
var gdt = current.start_date.getGlideObject();
//All methods can use negative values to subtract intervals
//add 1 hour (60 mins * 60 secs)
gdt.addSeconds(3600);
//add 1 day
gdt.addDaysLocalTime(1);
//subtract 1 day
gdt.addDaysLocalTime(-1);
//add 3 weeks
gdt.addWeeksLocalTime(3);
//subtract 6 months
gdt.addMonthsLocalTime(-6);
//add 1 year, representing the date and time using the UTC timezone instead of the local user's timezone.
gdt.addYearsUTC(1);
//set the value of the GlideDateTime object to the current session timezone/format
GlideSession.get().setTimeZoneName('US/Eastern');
gdt.setDisplayValue('2018-2-28 00:00:00');
gs.info('In ' + GlideSession.get().getTimeZoneName() + ": " + gdt.getDisplayValue());関連項目:
カスタムキューを使用してイベントを処理する
大量のイベントや処理に時間がかかるイベントを作成するアプリケーションには、カスタムキューを使用できます。このタスクでは、カスタムキューとその監視プロセスを作成し、スクリプトを使用してキューにイベントを送信する方法を示します。
始める前に
必要なロール:admin