Service Manager

Service Manager By Micro Focus (Formerly HPE Software).

Case Management · Micro Focus Service Manager

Details

IDService Manager
ProviderOpenText
CategoryCase Management
From Version5.0.0
Supported ModulesAgentix XSIAM

README

Service Manager By Micro Focus (Formerly HPE Software).

Configure Micro Focus Service Manager in Cortex

Parameter Required
Server URL (e.g. https://192.168.0.1:13080) True
Username True
Password True
Trust any certificate (not secure) False
Use system proxy settings False

Commands

You can execute these commands from the CLI, as part of an automation, or in a playbook.
After you successfully execute a command, a DBot message appears in the War Room with the command details.

hpsm-update-incident


Updates existing incident (beta).

Base Command

hpsm-update-incident

Input

Argument Name Description Required
incidentId The ID of the incident. For example: “IM10013”. Required
title The title of the incident. Optional
description The description of the incident. Optional
service The service. For example: “CI1001060”, “CI1001030”. Optional
impact The impact. Default is 4. Should be a number like 3 or 4. Optional
urgency The urgency. Default is 4. Should be a number like 3 or 4. Optional
alertStatus The alert status. For example: “SLA BREACH”. Optional
area The area. For example: “performance”, “failure”, “hardware”, “access”. . Optional
assignmentGroup The assignment group. For example: “Office Supplies (North America)”. Optional
affectedCI The affected CI. For example: “CI1000783”. Optional
category Category of the incident. For example: “incident”, “complaint”. Optional
company The company. For example: “advantage”. Optional
phase The phase. For example: “Categorization”. Optional
status The status. For example: “Categorize”. Optional
subarea The sub-area. For example: system or application hangs, function or feature not working, error message, job failed, hardware failure, etc. Optional
customFields Custom fields in JSON format. For example: {“businessUnit”:”5”}. Field name is case-sensitive. Optional

Context Output

Path Type Description
Ticket.ID unknown The ID of the ticket.
Ticket.Creator unknown The name of the user who created/opened the ticket.
Ticket.Assignee unknown To whom the ticket is assigned.
Ticket.State unknown The state of the ticket (open, closed, on hold).
HPSM.Incidents.IncidentID unknown The ID of the incident.
HPSM.Incidents.Service unknown Service/device number (For example: CI1001030).
HPSM.Incidents.Area unknown Incident area.
HPSM.Incidents.Assignee unknown Incident assignee.
HPSM.Incidents.AssignmentGroup unknown Incident assignment group.
HPSM.Incidents.Category unknown Incident category.
HPSM.Incidents.ClosedBy unknown The user who closed the incident.
HPSM.Incidents.ClosedTime unknown Incident close time.
HPSM.Incidents.ClosureCode unknown Incident closure code.
HPSM.Incidents.Company unknown Incident company.
HPSM.Incidents.Contact unknown Incident contact details.
HPSM.Incidents.Description unknown Incident description.
HPSM.Incidents.Impact unknown Incident impact.
HPSM.Incidents.JournalUpdates unknown Incident journal updates.
HPSM.Incidents.OpenTime unknown Incident open time.
HPSM.Incidents.OpenedBy unknown The user who opened the incident.
HPSM.Incidents.Phase unknown Incident phase.
HPSM.Incidents.Solution unknown Incident solution.
HPSM.Incidents.Status unknown Incident status.
HPSM.Incidents.Subarea unknown Incident sub-area.
HPSM.Incidents.Title unknown Incident title.
HPSM.Incidents.UpdatedBy unknown The last user who updated the incident.
HPSM.Incidents.UpdatedTime unknown Incident update time.
HPSM.Incidents.Urgency unknown Incident urgency.

hpsm-create-incident


Creates a new incident.

Base Command

hpsm-create-incident

Input

Argument Name Description Required
title The title of the incident. Required
description The description of the incident. Required
service The service. For example: “CI1001060”, “CI1001030”. Required
impact The impact. Default is 4. Should be a number like 3 or 4. Optional
urgency The impact. Default is 4. Should be a number like 3 or 4. Optional
alertStatus The alert status. For example: “SLA BREACH”. Optional
area The area. For example: “performance”, “failure”, “hardware”, “access”. Optional
assignmentGroup The assignment group. For example: “Office Supplies (North America)”. Optional
affectedCI The affected CI. For example: “CI1000783”. Optional
category Category of the incident. For example: “incident”, “complaint”. Required
company The company. For example: “advantage”. Optional
phase The phase. For example: “Categorization”. Optional
status The status. For example: “Categorize”. Optional
subarea The sub-area. For example: system or application hangs, function or feature not working, error message, job failed, hardware failure, etc. Optional
customFields Custom fields in JSON format. For example: {“businessUnit”:”5”}. Field name is case-sensitive. Optional

Context Output

Path Type Description
Ticket.ID unknown The ID of the ticket.
Ticket.Creator unknown The user who created/opened the ticket.
Ticket.Assignee unknown To whom the ticket is assigned.
Ticket.State unknown The state of the ticket (open, closed, on hold).
HPSM.Incidents.IncidentID unknown The ID of the incident.
HPSM.Incidents.Service unknown Service/device number.
HPSM.Incidents.Area unknown Incident area.
HPSM.Incidents.Assignee unknown Incident assignee.
HPSM.Incidents.AssignmentGroup unknown Incident assignment group.
HPSM.Incidents.Category unknown Incident category.
HPSM.Incidents.ClosedBy unknown The user who closed the incident.
HPSM.Incidents.ClosedTime unknown Incident close time.
HPSM.Incidents.ClosureCode unknown Incident closure code.
HPSM.Incidents.Company unknown Incident company.
HPSM.Incidents.Contact unknown Incident contact details.
HPSM.Incidents.Description unknown Incident description.
HPSM.Incidents.Impact unknown Incident impact.
HPSM.Incidents.JournalUpdates unknown Incident journal updates.
HPSM.Incidents.OpenTime unknown Incident open time.
HPSM.Incidents.OpenedBy unknown The user who opened the incident.
HPSM.Incidents.Phase unknown Incident phase.
HPSM.Incidents.Solution unknown Incident solution.
HPSM.Incidents.Status unknown Incident status.
HPSM.Incidents.Subarea unknown Incident sub-area.
HPSM.Incidents.Title unknown Incident title.
HPSM.Incidents.UpdatedBy unknown The last user who updated the incident.
HPSM.Incidents.UpdatedTime unknown Incident update time.
HPSM.Incidents.Urgency unknown Incident urgency.

hpsm-list-incidents


Returns all incidents.

Base Command

hpsm-list-incidents

Input

Argument Name Description Required
query The query by which to limit the returned list of incidents. For example: field1=value1&field2=value2. For more information, see https://docs.microfocus.com/SM/9.41/Codeless/Content/Resources/PDF_PD/HP_Service_Manager_Web_Services_codeless.pdf. Optional

Context Output

Path Type Description
HPSM.IncidentIDs unknown An array of incident IDs.

hpsm-get-incident-by-id


Returns a single incident by ID. If no incident exists with the specified ID, an error will be returned.

Base Command

hpsm-get-incident-by-id

Input

Argument Name Description Required
incidentId The ID of an incident. For exampleJ: “IM10013”. Required

Context Output

Path Type Description
Ticket.ID unknown The ID of the ticket.
Ticket.Creator unknown The user who created/opened the ticket.
Ticket.Assignee unknown To whom the ticket is assigned.
Ticket.State unknown The state of the ticket (open, closed, on hold).
HPSM.Incidents.IncidentID unknown The ID of the incident.
HPSM.Incidents.Service unknown Service/device number.
HPSM.Incidents.Area unknown Incident area.
HPSM.Incidents.Assignee unknown Incident assignee.
HPSM.Incidents.AssignmentGroup unknown Incident assignment group.
HPSM.Incidents.Category unknown Incident category.
HPSM.Incidents.ClosedBy unknown The user who closed the incident.
HPSM.Incidents.ClosedTime unknown Incident close time.
HPSM.Incidents.ClosureCode unknown Incident closure code.
HPSM.Incidents.Company unknown Incident company.
HPSM.Incidents.Contact unknown Incident contact details.
HPSM.Incidents.Description unknown Incident description.
HPSM.Incidents.Impact unknown Incident impact.
HPSM.Incidents.JournalUpdates unknown Incident journal updates.
HPSM.Incidents.OpenTime unknown Incident open time.
HPSM.Incidents.OpenedBy unknown The user who opened the incident.
HPSM.Incidents.Phase unknown Incident phase.
HPSM.Incidents.Solution unknown Incident solution.
HPSM.Incidents.Status unknown Incident status.
HPSM.Incidents.Subarea unknown Incident sub-area.
HPSM.Incidents.Title unknown Incident title.
HPSM.Incidents.UpdatedBy unknown The last user who updated the incident.
HPSM.Incidents.UpdatedTime unknown Incident update time.
HPSM.Incidents.Urgency unknown Incident urgency.

hpsm-create-resource


Updates the existing resource (beta).

Base Command

hpsm-create-resource

Input

Argument Name Description Required
title The title of the resource. Required
description The description of the resource. Required
service The service. For example: “CI1001060”, “CI1001030”. Required
impact The impact. Default is 4. Should be a number like 3 or 4. Optional
urgency The urgency. Default is 4. Should be a number like 3 or 4. Optional
alertStatus The alert status. For example: “SLA BREACH”. Optional
area The area. For example: performance, failure, hardware, access”. Optional
assignmentGroup The assignment group. For example: “Office Supplies (North America)”. Optional
affectedCI The affected CI. For example: “CI1000783”. Optional
category Category of resource. For example: “resource”, “complaint”. Required
company The company. For example: “advantage”. Optional
phase The phase. For example: “Categorization”. Optional
status The status. For example: “Categorize”. Optional
subarea The sub-area. For example: system or application hangs, function or feature not working, error message, job failed, hardware failure, etc. Optional
customFields Custom fields in JSON format. For example: {“businessUnit”:”5”}. Field name is case-sensitive. Optional
resourceName The resource name (API URI) that will be used. For example: “incidents”. Required
resourceKey The resource key that will be used. For example: “InteractionID”. Required

Context Output

Path Type Description
Ticket.ID unknown The ID of the ticket.
Ticket.Creator unknown The user who created/opened the ticket.
Ticket.Assignee unknown To whom the ticket is assigned.
Ticket.State unknown The state of the ticket (open, closed, on hold).
HPSM.Resources.ResourceID unknown The ID of the resource.
HPSM.Resources.Service unknown Service/device number.
HPSM.Resources.Area unknown Resource area.
HPSM.Resources.Assignee unknown Resource assignee.
HPSM.Resources.AssignmentGroup unknown Resource assignment group.
HPSM.Resources.Category unknown Resource category.
HPSM.Resources.ClosedBy unknown The user who closed the resource.
HPSM.Resources.ClosedTime unknown Resource close time.
HPSM.Resources.ClosureCode unknown Resource closure code.
HPSM.Resources.Company unknown Resource company.
HPSM.Resources.Contact unknown Resource contact details.
HPSM.Resources.Description unknown Resource description.
HPSM.Resources.Impact unknown Resource impact.
HPSM.Resources.JournalUpdates unknown Resource journal updates.
HPSM.Resources.OpenTime unknown Resource open time.
HPSM.Resources.OpenedBy unknown The user who opened the resource.
HPSM.Resources.Phase unknown Resource phase.
HPSM.Resources.Solution unknown Resource solution.
HPSM.Resources.Status unknown Resource status.
HPSM.Resources.Subarea unknown Resource sub-area.
HPSM.Resources.Title unknown Resource title.
HPSM.Resources.UpdatedBy unknown The last user who updated the resource.
HPSM.Resources.UpdatedTime unknown Resource update time.
HPSM.Resources.Urgency unknown Resource urgency.

hpsm-update-resource


Creates a new resource.

Base Command

hpsm-update-resource

Input

Argument Name Description Required
title The title of the resource. Required
description The description of the resource. Required
service The service. For example: “CI1001060”, “CI1001030”. Required
impact The impact. Default is 4. Should be a number like 3 or 4. Optional
urgency The urgency. Default is 4. Should be a number like 3 or 4. Optional
alertStatus The alert status. For example: “SLA BREACH”. Optional
area The area. For example: “performance”, “failure”, “hardware”, “access”. Optional
assignmentGroup The assignment group. For example: “Office Supplies (North America)”. Optional
affectedCI The affected CI. For example: “CI1000783”. Optional
category Category of resource. For example: “resource”, “complaint”. Required
company The company. For example: “advantage”. Optional
phase The phase. For example: “Categorization”. Optional
status The status. For example: “Categorize”. Optional
subarea The sub-area. For example: system or application hangs, function or feature not working, error message, job failed, hardware failure, etc. Optional
customFields Custom fields in JSON format. For example: {“businessUnit”:”5”}. Field name is case-sensitive. Optional
resourceName The resource name (API URI) that will be used. For example: “incidents”. Required
resourceKey The resource key that will be used. For example: “InteractionID”. Required

Context Output

Path Type Description
Ticket.ID unknown The ID of the ticket.
Ticket.Creator unknown The user who created/opened the ticket.
Ticket.Assignee unknown To whom the ticket is assigned.
Ticket.State unknown The state of the ticket (open, closed, on hold).
HPSM.Resources.ResourceID unknown The ID of the resource.
HPSM.Resources.Service unknown Service/device number.
HPSM.Resources.Area unknown Resource area.
HPSM.Resources.Assignee unknown Resource assignee.
HPSM.Resources.AssignmentGroup unknown Resource assignment group.
HPSM.Resources.Category unknown Resource category.
HPSM.Resources.ClosedBy unknown The user who closed the resource.
HPSM.Resources.ClosedTime unknown Resource close time.
HPSM.Resources.ClosureCode unknown Resource closure code.
HPSM.Resources.Company unknown Resource company.
HPSM.Resources.Contact unknown Resource contact details.
HPSM.Resources.Description unknown Resource description.
HPSM.Resources.Impact unknown Resource impact.
HPSM.Resources.JournalUpdates unknown Resource journal updates.
HPSM.Resources.OpenTime unknown Resource open time.
HPSM.Resources.OpenedBy unknown The user who opened the resource.
HPSM.Resources.Phase unknown Resource phase.
HPSM.Resources.Solution unknown Resource solution.
HPSM.Resources.Status unknown Resource status.
HPSM.Resources.Subarea unknown Resource sub-area.
HPSM.Resources.Title unknown Resource title.
HPSM.Resources.UpdatedBy unknown The last user who updated the resource.
HPSM.Resources.UpdatedTime unknown Resource update time.
HPSM.Resources.Urgency unknown Resource urgency.

hpsm-list-resources


Returns all resources (beta).

Base Command

hpsm-list-resources

Input

Argument Name Description Required
query The query by which to limit the returned list of incidents. For example: field1=value1&field2=value2. For more information, see https://docs.microfocus.com/SM/9.41/Codeless/Content/Resources/PDF_PD/HP_Service_Manager_Web_Services_codeless.pdf. Optional
resourceName The resource name (API URI) that will be used. For example: “incidents”. Required

Context Output

Path Type Description
HPSM.ResourceIDs unknown An array of resource IDs.

hpsm-get-resource-by-id


Returns a single resource by ID. If no resource exists with the specified ID, an error will be returned (beta).

Base Command

hpsm-get-resource-by-id

Input

Argument Name Description Required
resourceId The ID of the resource. For example: “IM10013”. Required
resourceName The resource name (API URI) that will be used. For example: “incidents”. Required

Context Output

Path Type Description
Ticket.ID unknown The ID of the ticket.
Ticket.Creator unknown The user who created/opened the ticket.
Ticket.Assignee unknown To whom the ticket is assigned.
Ticket.State unknown The state of the ticket (open, closed, on hold).
HPSM.Resources.ResourceID unknown The ID of the resource.
HPSM.Resources.Service unknown Service/device number.
HPSM.Resources.Area unknown Resource area.
HPSM.Resources.Assignee unknown Resource assignee.
HPSM.Resources.AssignmentGroup unknown Resource assignment group.
HPSM.Resources.Category unknown Resource category.
HPSM.Resources.ClosedBy unknown The user who closed the resource.
HPSM.Resources.ClosedTime unknown Resource close time.
HPSM.Resources.ClosureCode unknown Resource closure code.
HPSM.Resources.Company unknown Resource company.
HPSM.Resources.Contact unknown Resource contact details.
HPSM.Resources.Description unknown Resource description.
HPSM.Resources.Impact unknown Resource impact.
HPSM.Resources.JournalUpdates unknown Resource journal updates.
HPSM.Resources.OpenTime unknown Resource open time.
HPSM.Resources.OpenedBy unknown The user who opened the resource.
HPSM.Resources.Phase unknown Resource phase.
HPSM.Resources.Solution unknown Resource solution.
HPSM.Resources.Status unknown Resource status.
HPSM.Resources.Subarea unknown Resource sub-area.
HPSM.Resources.Title unknown Resource title.
HPSM.Resources.UpdatedBy unknown The last user who updated the resource.
HPSM.Resources.UpdatedTime unknown Resource update time.
HPSM.Resources.Urgency unknown Resource urgency.

hpsm-list-devices


Returns a list of devices, filtered according to query.

Base Command

hpsm-list-devices

Input

Argument Name Description Required
query The query by which to limit the returned list of incidents. For example: field1=value1&field2=value2. For more information, see https://docs.microfocus.com/SM/9.41/Codeless/Content/Resources/PDF_PD/HP_Service_Manager_Web_Services_codeless.pdf. Optional

Context Output

Path Type Description
HPSM.DeviceIDs unknown The IDs (configuration items) of the devices.

hpsm-get-device


Find and return a device by ID.

Base Command

hpsm-get-device

Input

Argument Name Description Required
configurationItem ID of the configuration item of the device. For example: “CI1000011”. Required

Context Output

Path Type Description
HPSM.Devices.AssignmentGroup unknown Device assignment group.
HPSM.Devices.Company unknown Device company.
HPSM.Devices.ConfigurationItem unknown Device configuration item.
HPSM.Devices.ConfigurationItemSubType unknown Device configurationItem sub-type.
HPSM.Devices.ConfigurationItemType unknown Device configuration item type.
HPSM.Devices.Department unknown Device department.
HPSM.Devices.DisplayName unknown Device display name.
HPSM.Devices.Location unknown Device location.
HPSM.Devices.LocationCode unknown Device location code.
HPSM.Devices.Model unknown Device model.
HPSM.Devices.PartNumber unknown Device part number.
HPSM.Devices.Status unknown Device status.
HPSM.Devices.UpdatedBy unknown The last user who updated the device.

hpsm-create-request


Creates a new service request

Base Command

hpsm-create-request

Input

Argument Name Description Required
title The title of the request. Required
purpose The purpose of the request. Required
callbackcontactname Who created/opened the service request. Optional
contactname Incident contact details. Required
resourceName The resource name (API URI) that will be used. For example: “incidents”. Required

Context Output

Path Type Description
HPSM.ServiceRequest.ContactName unknown Who created/opened the service request
HPSM.ServiceRequest.ID unknown The id of the service request
HPSM.ServiceRequest.CallbackContactName unknown Incident contact details
HPSM.ServiceRequest.Title unknown Incident title

Configuration parameters

  • url — Server URL (e.g. https://192.168.0.1:13080) (required)
  • username — Username (required)
  • insecure — Trust any certificate (not secure)
  • proxy — Use system proxy settings

Commands (11)

  • hpsm-create-incident

    Creates a new incident.

  • hpsm-create-request

    Creates a new service request.

  • hpsm-create-resource

    Updates the existing resource (beta).

  • hpsm-get-device

    Find and return a device by ID.

  • hpsm-get-incident-by-id

    Returns a single incident by ID. If no incident exists with the specified ID, an error will be returned.

  • hpsm-get-resource-by-id

    Returns a single resource by ID. If no resource exists with the specified ID, an error will be returned (beta).

  • hpsm-list-devices

    Returns a list of devices, filtered according to query.

  • hpsm-list-incidents

    Returns all incidents.

  • hpsm-list-resources

    Returns all resources (beta).

  • hpsm-update-incident

    Updates existing incident (beta).

  • hpsm-update-resource

    Creates a new resource.

var url = params.url + '/SM/9/rest';

// handle '/' at the end of the url
if (url[url.length - 1] === '/') {
    url = url.substring(0, url.length - 1);
}

var token = Base64.encode(params.username.identifier + ':' + params.username.password);

var result;
// The command input arg holds the command sent from the user.
switch (command) {
    case 'test-module':
        listDevices();
        result = 'ok';
        break;
    case 'hpsm-create-incident':
        result = createIncident();
        break;
    case 'hpsm-create-request':
        result = createRequest();
        break;
    case 'hpsm-update-incident':
        result = updateIncident();
        break;
    case 'hpsm-list-incidents':
        result = listIncidents();
        break;
    case 'hpsm-get-incident-by-id':
        result = getIncidentById();
        break;
    case 'hpsm-create-resource':
        result = createResource();
        break;
    case 'hpsm-update-resource':
        result = updateResource();
        break;
    case 'hpsm-list-resource':
        result = listResources();
        break;
    case 'hpsm-get-resource-by-id':
        result = getResourceById();
        break;
    case 'hpsm-list-devices':
        result = listDevices();
        break;
    case 'hpsm-get-device':
        result = getDeviceById();
        break;
    default:
}
return result;
function updateIncident() {
    var newIncident = {
        Incident: {
            Category: args.category,
            Description: [
                args.description
            ],
            Service: args.service,
            Title: args.title,
        }
    };
    if (args.customFields !== undefined){
        fields = parseCustomFields(args.customFields);
        for (var field in fields) {
            newIncident['Incident'][field] = fields[field]
        }
    }
    if (args.impact) {
        newIncident.Incident.Impact = args.impact;
    }
    if (args.urgency) {
        newIncident.Incident.Urgency = args.urgency;
    }
    if (args.alertStatus) {
        newIncident.Incident.AlertStatus = args.alertStatus;
    }
    if (args.area) {
        newIncident.Incident.Area = args.area;
    }
    if (args.assignmentGroup) {
        newIncident.Incident.AssignmentGroup = args.assignmentGroup;
    }
    if (args.affectedCI) {
        newIncident.Incident.AffectedCI = args.affectedCI;
    }
    if (args.company) {
        newIncident.Incident.Company = args.company;
    }
    if (args.category) {
        newIncident.Incident.Category = args.category;
    }
    if (args.phase) {
        newIncident.Incident.Phase = args.phase;
    }
    if (args.status) {
        newIncident.Incident.Status = args.status;
    }
    if (args.subarea) {
        newIncident.Incident.Subarea = args.subarea;
    }
    var res = doPost('/incidents/'+args.incidentId, newIncident);
    var parsedRes = JSON.parse(res);
    if (parsedRes.ReturnCode !== 0) {
        throw 'Failed to update incident. Error Response: ' + res.Messages;
    }
    hrIncident = parsedRes.Incident;
    var entryContext = {
        'HPSM.Incidents': [parsedRes.Incident],
        Ticket: [
            {
                ID: parsedRes.Incident.IncidentID,
                Creator: parsedRes.Incident.OpenedBy,
                Assignee: parsedRes.Incident.Assignee,
                State: parsedRes.Incident.Status
            }
        ]
    };
    return {
        Type: entryTypes.note,
        ContentsFormat: formats.json,
        Contents: parsedRes,
        ReadableContentsFormat: formats.markdown,
        HumanReadable: tableToMarkdown('Updated Incident ' + parsedRes.Incident.IncidentID, hrIncident),
        EntryContext: entryContext
    };
} // queryToObject takes query of format field1=value1&field2=value2 and return query object like: { "field1": "value1", "field2": "value2" }

function createRequest() {
    var resourceName = args.resourceName;
    var newRequest = {
        [resourceName]: {
            Purpose: [
                args.purpose
            ],
            Title: args.title,
            CallbackContactName: args.callbackcontactname,
            ContactName: args.contactname,
            cartItems: [{ 'ItemName': args.title , 'Quantity': '1', 'RequestedFor': args.callbackcontactname }]
        }
    };
    //throw JSON.stringify(newRequest)
    var res = doPost('/'+ resourceName, newRequest);
    var parsedRes = JSON.parse(res);
    if (parsedRes.ReturnCode !== 0) {
        throw 'Failed to create request. Error Response: ' + res.Messages;
    }
    req = parsedRes['Messages'][2];
    request = req.split('"');
    var srHPSM = {};
    var lstHPSM = [];
    srHPSM['ID'] = request[1];
    srHPSM['CallbackContactName'] = parsedRes[resourceName]['CallbackContactName'];
    srHPSM['Title'] = parsedRes[resourceName]['Title'];
    srHPSM['Purpose'] = parsedRes[resourceName]['Purpose'][0];
    srHPSM['ContactName'] = parsedRes[resourceName]['ContactName'];
    lstHPSM.push(srHPSM);
    var entryContext = {
        'HPSM.ServiceRequest': lstHPSM,
    };
    return {
        Type: entryTypes.note,
        ContentsFormat: formats.json,
        Contents: parsedRes,
        ReadableContentsFormat: formats.markdown,
        HumanReadable: tableToMarkdown('Created Service Request ', lstHPSM),
        EntryContext: entryContext
    };
}

function createIncident() {
    var newIncident = {
        Incident: {
            Category: args.category,
            Description: [
                args.description
            ],
            Service: args.service,
            Title: args.title,
        }
    };
    if (args.customFields !== undefined){
        fields = parseCustomFields(args.customFields);
        for (var field in fields) {
            newIncident['Incident'][field] = fields[field]
        }
    }

    if (args.impact) {
        newIncident.Incident.Impact = args.impact;
    }
    if (args.urgency) {
        newIncident.Incident.Urgency = args.urgency;
    }
    if (args.alertStatus) {
        newIncident.Incident.AlertStatus = args.alertStatus;
    }
    if (args.area) {
        newIncident.Incident.Area = args.area;
    }
    if (args.assignmentGroup) {
        newIncident.Incident.AssignmentGroup = args.assignmentGroup;
    }
    if (args.affectedCI) {
        newIncident.Incident.AffectedCI = args.affectedCI;
    }
    if (args.company) {
        newIncident.Incident.Company = args.company;
    }
    if (args.category) {
        newIncident.Incident.Category = args.category;
    }

    if (args.phase) {
        newIncident.Incident.Phase = args.phase;
    }
    if (args.status) {
        newIncident.Incident.Status = args.status;
    }
    if (args.subarea) {
        newIncident.Incident.Subarea = args.subarea;
    }

    var res = doPost('/incidents', newIncident);
    var parsedRes = JSON.parse(res);
    if (parsedRes.ReturnCode !== 0) {
        throw 'Failed to create incident. Error Response: ' + res.Messages;
    }

    hrIncident = parsedRes.Incident;

    var entryContext = {
        'HPSM.Incidents': [parsedRes.Incident],
        Ticket: [
            {
                ID: parsedRes.Incident.IncidentID,
                Creator: parsedRes.Incident.OpenedBy,
                Assignee: parsedRes.Incident.Assignee,
                State: parsedRes.Incident.Status
            }
        ]
    };
    return {
        Type: entryTypes.note,
        ContentsFormat: formats.json,
        Contents: parsedRes,

        ReadableContentsFormat: formats.markdown,
        HumanReadable: tableToMarkdown('Created Incident ' + parsedRes.Incident.IncidentID, hrIncident),

        EntryContext: entryContext
    };
}

// queryToObject takes query of format field1=value1&field2=value2 and return query object like: { "field1": "value1", "field2": "value2" }
function queryToObject(query) {
    if (!query) {
        return null;
    }

    var queryObj = {};
    var queryArr = query.split('&');
    queryArr.forEach(function(keyValuePair) {
        var a = keyValuePair.split('=');
        var key = a[0];
        var value = a[1];
        queryObj[key] = value;
    });

    return queryObj;
}

function listIncidents() {
    var incidents = doGet('/incidents', args.query);
    incidents = JSON.parse(incidents);

    var hrIncidents = [];
    var incidentIds = [];
    if (incidents.content && incidents.content.length > 0) {
        incidents.content.forEach(function(inc) {
            hrIncidents.push(inc.Incident);
            incidentIds.push(inc.Incident.IncidentID);
        });
    }

    var entryContext = {
        'HPSM.IncidentIDs': incidentIds
    };

    return {
        Type: entryTypes.note,
        ContentsFormat: formats.json,
        Contents: incidents,

        ReadableContentsFormat: formats.markdown,
        HumanReadable: tableToMarkdown('Incidents List', hrIncidents),

        EntryContext: entryContext
    };
}

function getIncidentById() {
    var incident = doGet('/incidents/' + args.incidentId);
    incident = JSON.parse(incident);

    hrIncident = incident.Incident;
    var entryContext = {
        'HPSM.Incidents': [incident.Incident],
        Ticket: [
            {
                ID: incident.Incident.IncidentID,
                Creator: incident.Incident.OpenedBy,
                Assignee: incident.Incident.Assignee,
                State: incident.Incident.Status
            }
        ]
    };
    return {
        Type: entryTypes.note,
        ContentsFormat: formats.json,
        Contents: incident,

        ReadableContentsFormat: formats.markdown,
        HumanReadable: tableToMarkdown('Incident ' + args.incidentId, hrIncident),

        EntryContext: entryContext
    };
}

function listDevices() {
    var devices = doGet('/devices', args.query);
    devices = JSON.parse(devices);

    var hrDevices = [];
    var deviceIds = [];
    if (devices.content && devices.content.length > 0) {
        devices.content.forEach(function(dev) {
            hrDevices.push(dev.Device);
            deviceIds.push(dev.Device.ConfigurationItem);
        });
    }

    var entryContext = {
        'HPSM.DeviceIDs': deviceIds
    };

    return {
        Type: entryTypes.note,
        ContentsFormat: formats.json,
        Contents: devices,

        ReadableContentsFormat: formats.markdown,
        HumanReadable: tableToMarkdown('Devices List', hrDevices),

        EntryContext: entryContext
    };
}
function updateResource() {
    var resourceName = args.resourceName;
    var newResource = {};
    newResource[resourceName] = {
            Category: args.category,
            Description: [
                args.description
            ],
            Service: args.service,
            Title: args.title,
        }

    if (args.customFields !== undefined){
        fields = parseCustomFields(args.customFields);
        for (var field in fields) {
            newResource[resourceName][field] = fields[field]
        }
    }
    if (args.impact) {
        newResource[resourceName]['Impact'] = args.impact;
    }
    if (args.urgency) {
        newResource[resourceName]['Urgency'] = args.urgency;
    }
    if (args.alertStatus) {
        newResource[resourceName]['AlertStatus'] = args.alertStatus;
    }
    if (args.area) {
        newResource[resourceName]['Area'] = args.area;
    }
    if (args.assignmentGroup) {
        newResource[resourceName]['AssignmentGroup'] = args.assignmentGroup;
    }
    if (args.affectedCI) {
        newResource[resourceName]['AffectedCI'] = args.affectedCI;
    }
    if (args.company) {
        newResource[resourceName]['Company'] = args.company;
    }
    if (args.category) {
        newResource[resourceName]['Category'] = args.category;
    }
    if (args.phase) {
        newResource[resourceName]['Phase'] = args.phase;
    }
    if (args.status) {
        newResource[resourceName]['Status'] = args.status;
    }
    if (args.subarea) {
        newResource[resourceName]['Subarea'] = args.subarea;
    }
    var res = doPost('/'+resourceName+'/'+args.incidentId, newResource);
    var parsedRes = JSON.parse(res);
    if (parsedRes.ReturnCode !== 0) {
        throw 'Failed to update resource. Error Response: ' + res.Messages;
    }
    hrResource = parsedRes[resourceName];

    var entryContext = {
        'HPSM.Resources': [parsedRes[resourceName]],
        Ticket: [
            {
                ID: parsedRes[resourceName][args.resourceKey],
                Creator: parsedRes[resourceName]['OpenedBy'],
                Assignee: parsedRes[resourceName]['Assignee'],
                State: parsedRes[resourceName]['Status']
            }
        ]
    };
    return {
        Type: entryTypes.note,
        ContentsFormat: formats.json,
        Contents: parsedRes,
        ReadableContentsFormat: formats.markdown,
        HumanReadable: tableToMarkdown('Updated Resource ' + parsedRes[resourceName][args.resourceKey], hrResource),
        EntryContext: entryContext
    };
} // queryToObject takes query of format field1=value1&field2=value2 and return query object like: { "field1": "value1", "field2": "value2" }
function createResource() {
    var resourceName = args.resourceName;
    var newResource = {};
    newResource[resourceName] = {
            Category: args.category,
            Description: [
                args.description
            ],
            Service: args.service,
            Title: args.title,
        }
    if (args.customFields !== undefined){
        fields = parseCustomFields(args.customFields);
        for (var field in fields) {
            newResource[resourceName][field] = fields[field]
        }
    }
    if (args.impact) {
        newResource[resourceName]['Impact'] = args.impact;
    }
    if (args.urgency) {
        newResource[resourceName]['Urgency'] = args.urgency;
    }
    if (args.alertStatus) {
        newResource[resourceName]['AlertStatus'] = args.alertStatus;
    }
    if (args.area) {
        newResource[resourceName]['Area'] = args.area;
    }
    if (args.assignmentGroup) {
        newResource[resourceName]['AssignmentGroup'] = args.assignmentGroup;
    }
    if (args.affectedCI) {
        newResource[resourceName]['AffectedCI'] = args.affectedCI;
    }
    if (args.company) {
        newResource[resourceName]['Company'] = args.company;
    }
    if (args.category) {
        newResource[resourceName]['Category'] = args.category;
    }
    if (args.phase) {
        newResource[resourceName]['Phase'] = args.phase;
    }
    if (args.status) {
        newResource[resourceName]['Status'] = args.status;
    }
    if (args.subarea) {
        newResource[resourceName]['Subarea'] = args.subarea;
    }
    var res = doPost('/'+resourceName, newResource);
    var parsedRes = JSON.parse(res);
    if (parsedRes.ReturnCode !== 0) {
        throw 'Failed to create resource. Error Response: ' + res.Messages;
    }
    hrResource = parsedRes[resourceName];

    var entryContext = {
        'HPSM.Resources': [parsedRes[resourceName]],
        Ticket: [
            {
                ID: parsedRes[resourceName][args.resourceKey],
                Creator: parsedRes[resourceName]['OpenedBy'],
                Assignee: parsedRes[resourceName]['Assignee'],
                State: parsedRes[resourceName]['Status']
            }
        ]
    };
    return {
        Type: entryTypes.note,
        ContentsFormat: formats.json,
        Contents: parsedRes,
        ReadableContentsFormat: formats.markdown,
        HumanReadable: tableToMarkdown('Created Resource ' + parsedRes[resourceName][args.resourceKey], hrResource),
        EntryContext: entryContext
    };
} // queryToObject takes query of format field1=value1&field2=value2 and return query object like: { "field1": "value1", "field2": "value2" }
function listResources() {
    var resourceName = args.resourceName;
    var incidents = doGet('/'+resourceName, args.query);
    incidents = JSON.parse(incidents);
    var hrIncidents = [];
    var incidentIds = [];
    if (incidents.content && incidents.content.length > 0) {
        incidents.content.forEach(function(inc) {
            hrIncidents.push(inc[resourceName]);
            incidentIds.push(inc[resourceName][args.resourceKey]);
        });
    }
    var entryContext = {
        'HPSM.ResourceIDs': incidentIds
    };
    return {
        Type: entryTypes.note,
        ContentsFormat: formats.json,
        Contents: incidents,
        ReadableContentsFormat: formats.markdown,
        HumanReadable: tableToMarkdown('Resources List', hrIncidents),
        EntryContext: entryContext
    };
}
function getResourceById() {
    var resourceName = args.resourceName;
    var resource = doGet('/'+resourceName+'/'+ args.resourceId);
    resource = JSON.parse(resource);
    hrResource = resource[resourceName];

    var entryContext = {
        'HPSM.Resources': [resource[resourceName]],
        Ticket: [
            {
                ID: resource[resourceName]['IncidentID'],
                Creator: resource[resourceName]['OpenedBy'],
                Assignee: resource[resourceName]['Assignee'],
                State: resource[resourceName]['Status']
            }
        ]
    };
    return {
        Type: entryTypes.note,
        ContentsFormat: formats.json,
        Contents: resource,
        ReadableContentsFormat: formats.markdown,
        HumanReadable: tableToMarkdown('Resource ' + args.resourceId, hrResource),
        EntryContext: entryContext
    };
}
function getDeviceById() {
    var device = doGet('/devices/' + args.configurationItem);
    device = JSON.parse(device);

    hrDevice = device.Device;
    var entryContext = {
        'HPSM.Devices': [device.Device],
    };
    return {
        Type: entryTypes.note,
        ContentsFormat: formats.json,
        Contents: device,

        ReadableContentsFormat: formats.markdown,
        HumanReadable: tableToMarkdown('Device ' + args.configurationItem, hrDevice),

        EntryContext: entryContext
    };
}

function doPost(queryPath, body) {
    return doRequest('POST', queryPath, body);
}

function doPut(queryPath, body) {
    return doRequest('PUT', queryPath, body);
}

function doRequest(method, queryPath, body) {
    var requestUrl = url + queryPath;
    var res = http(
        requestUrl,
        {
            Method: method,
            Headers: {
                Authorization: ['Basic ' + token],
                Connecion: ['Closed'],
                'Content-Type': ['application/json']
            },
            Body: JSON.stringify(body)
        },
        params.insecure,
        params.proxy
    );

    if (res.StatusCode < 200 || res.StatusCode >= 300) {
        var parsedRes;
        try {
            parsedRes = JSON.parse(res.Body);
        } catch (err) {}

        if (res.Body && parsedRes && parsedRes.ReturnCode !== 0 && parsedRes.Messages) {
            throw method + ' Request Failed to ' + requestUrl + '.\nStatus code: ' + res.StatusCode + '.\nError from Service Manager: ' + parsedRes.Messages;
        }

        throw method + ' Request Failed to ' + requestUrl + '.\nStatus code: ' + res.StatusCode + '.\nBody: ' + JSON.stringify(res.Body) + '.';
    }

    return res.Body;
}

function doGet(queryPath, queryParams) {
    var requestUrl = url + queryPath;
    if (queryParams && typeof queryParams === 'string') {
        // in case query is a string, then we convert it obj and then encode it to URL query
        // we also convert every \" to " and after encoding URI, the encodeURI encodes " to %22. We decode it to its original form
        requestUrl += '?' + encodeURI(queryParams.replace(/\\"/g,'"')).replace(/%22/g,"\"");
    } else if (queryParams) {
        // if the query is object then we encode it
        requestUrl += encodeToURLQuery(queryParams);
    }

    var res = http(
        requestUrl,
        {
            Method: 'GET',
            Headers: {
                Authorization: ['Basic ' + token],
                Connecion: ['Closed'],
                'Content-Type': ['application/json']
            }
        },
        params.insecure,
        params.proxy
    );

    if (res.StatusCode < 200 || res.StatusCode >= 300) {
        throw 'GET Request Failed to ' + requestUrl + '.\nStatus code: ' + res.StatusCode + '.\nBody: ' + JSON.stringify(res) + '.';
    }

    return res.Body;
}

function parseCustomFields(customFields) {
    try {
        return JSON.parse(customFields);
    } catch (err) {
        throw `Failed to parse customFields argument (expected a JSON string): ${customFields}\nError: ${err}`;
    }
}