서버 측 스크립트 사용 사례
서버 측 스크립트의 사용 사례에는 로깅 출력, 사용자 객체 가져오기 및 날짜/시간 값 수정이 포함됩니다.
비즈니스 규칙에서 워크플로우 스크래치패드에 액세스
카탈로그 항목이 요청되었으며, 첨부된 워크플로우에 스크래치패드의 값을 채우는 스크립트 실행 활동이 포함되어 있습니다. 요청된 항목에서 실행되는 비즈니스 규칙에서 스크래치패드 값을 검색하거나 설정하려고 합니다.
필수 구성요소
필요한 역할: admin.
이름: 비즈니스 규칙에서 워크플로우 스크래치패드에 액세스합니다.
유형: 비즈니스 규칙
테이블: sc_req_item(요청된 항목)
설명: 카탈로그 항목이 요청되었습니다. 첨부된 워크플로우에 스크래치패드의 값을 채우는 스크립트 실행 활동이 포함되어 있습니다. 요청된 항목에서 실행되는 비즈니스 규칙에서 스크래치패드 값을 검색하거나 설정하려고 합니다.
매개변수: n/a.
//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();
}제공 계획 작업에 따라 그룹에 카탈로그 항목 할당
데스크톱 그룹에 할당된 카탈로그 작업이 있는 배달 계획을 사용하는 경우 데이터베이스 그룹에 서비스 카탈로그 항목을 할당합니다.
필수 조건
필요한 역할: 관리자
이름: 제공 계획 작업에 따라 그룹에 카탈로그 항목을 할당합니다.
유형: 할당 규칙.
설명: 이 할당 규칙은 데스크톱 그룹에 할당된 카탈로그 작업이 있는 배달 계획을 사용하는 경우 데이터베이스 그룹에 서비스 카탈로그 항목을 할당합니다.
스크립트:
//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시까지" 또는 "영업일 기준 2일 오전 10시 30분까지" 등이 있습니다.
- 월요일 오후 12시인 경우: 다음 영업일 오후 4시 = > 화요일 오후 4시
- 금요일 오후 2시인 경우: 다음 영업일 오후 4시 = 다음 월요일 오후 4시까지 >
상대 기간에 대한 자세한 내용은 다음 문서를 참조하십시오 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시까지").
- 상대 기간을 지원하기 위해 SLA 테이블에 필요한 필드를 추가합니다.
- SLA에 대한 기간 계산을 수정합니다.
- SLA에 대한 SLA 백분율 타이머 계산을 수정합니다(work_seconds 사용해야 함).
- 워크플로우에 일정 필드, 일정 및 시간대(워크플로우 테이블의 필드를 기준으로 선택됨)를 추가합니다.
- 워크플로우 작업 활동에 기간 지원 필드를 추가합니다.
- 작업 활동에 대한 기간 계산 스크립트를 구현합니다.
상대 기간 테이블 및 DurationCalculator 메서드
cmn_relative_duration 테이블은 기한을 기간 또는 상대적 기간으로 정의할 수 있도록 지원합니다.
이 테이블은 "이름"과 "스크립트"라는 두 개의 필드로 구성됩니다. "스크립트" 필드에는 상대 기간 계산 스크립트가 포함되어 있습니다. 이 스크립트에는 기한을 계산하는 데 사용되는 "calculator" 변수가 포함되어 있습니다.
DurationCalculator 스크립트 포함을 사용하여 기간 계산을 수행할 수 있습니다. 다음은 이 스크립트 포함에서 사용할 수 있는 메서드입니다.
| 방법 | 설명 |
|---|---|
| setSchedule (String schedID, [문자열 시간대]) | 기한을 계산하는 데 사용할 일정과 시간대를 설정합니다. |
| setStartDateTime(GlideDateTime 시작) | 기간 계산의 시작 시간을 설정합니다. "start"가 비어 있으면 현재 날짜/시간을 사용합니다. |
| calcDuration(int 초) | 종료 날짜 및 시간을 계산합니다. 완료 시 계산 결과를 나타내도록 this.endDateTime 및 this.seconds 속성이 설정됩니다. |
| calcRelativeDuration(문자열 relativeDurationID) | 지정된 상대 기간 스크립트를 사용하여 기간을 계산합니다. 완료 시 계산 결과를 나타내도록 this.endDateTime 및 this.seconds 속성이 설정됩니다. |
| getEndDateTime() | 해당 기간의 종료 날짜 및 시간을 나타내는 calcDuration/calcRelativeDuration에 의해 설정된 this.endDateTime 속성을 가져옵니다. |
| getSeconds() | 해당 기간 동안 수행할 총 작업 시간(초)을 나타내는 calcDuration/calcRelativeDuration에 의해 설정된 this.seconds 속성을 가져옵니다. 주: 시작 시간과 종료 시간 사이의 총 시간이 아니라 총 작업 시간이며 작업 시간의 백분율을 결정하는 데 사용할 수 있습니다. |
| getTotalSeconds() | 기간의 시작 시간과 종료 시간 사이의 총 시간(초)을 나타내는 calcDuration/calcRelativeDuration에 의해 설정된 this.totalSeconds 속성을 가져옵니다. |
상대 기간 스크립트에 사용되는 함수는 다음과 같습니다.
| 함수 | 설명 |
|---|---|
| 부울 isAfter(GlideDateTime dt, 문자열 시간) | 'dt'로 지정된 시간 이후의 '시간'이 있습니까? dt는 공백인 경우 현재 날짜/시간을 사용합니다. 시간은 24시간 형식의 "hh:mm:ss"입니다. |
| calcRelativeDueDate(GlideDateTime 시작, int 일, 문자열 endTime) | "시작"에서 시작하여 일정과 시간대를 사용하여 "일"을 더하는 기한을 계산합니다. 업무 기한이 되는 날을 찾으면 시간을 해당 날짜의 'endTime'으로 설정합니다. 완료 시 계산 결과를 나타내도록 this.endDateTime 및 this.seconds 속성이 설정됩니다. endTime이 비어 있으면 종료 근무일 종료를 사용합니다. |
사용자 객체 가져오기
비즈니스 규칙이나 다른 서버 스크립트에서 gs.getUser() 메서드는 사용자 객체를 반환합니다. 사용자 개체는 현재 로그인한 사용자의 내부 표현이며 사용자 및 다양한 유틸리티 기능에 대한 정보를 제공합니다.
이 태스크 정보
프로시저
로그 출력
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();
//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());
참조:
사용자 지정 큐를 사용하여 이벤트 처리
대량의 이벤트를 생성하거나 처리하는 데 시간이 오래 걸리는 이벤트에 대해 사용자 지정 큐를 사용할 수 있습니다. 이 작업은 사용자 지정 큐와 해당 모니터링 프로세스를 만들고 스크립트를 사용하여 이벤트를 큐에 보내는 방법을 보여줍니다.
시작하기 전에
필요한 역할: 관리자