Public/Assistance/Tickets/New-GlpiToolsTicket.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
<#
.SYNOPSIS
    Function is creating new ticket in GLPI
.DESCRIPTION
    This will create new ticket
 
.PARAMETER name
    Provide the name/subject of the new ticket
 
.PARAMETER content
    Provide the body/content of the new ticket
 
.PARAMETER Type
    Specifies if the ticket will be an Incident or a Request.
    Defaults to Incident
 
.PARAMETER itilcategories_id
    Provide the ID of the itil category
 
.PARAMETER urgency
    Specify the urgency.
    Possible values are "Very low", "Low", "Medium", "High" and "Very High"
 
.PARAMETER impact
    Specify the impact.
    Possible values are "Very low", "Low", "Medium", "High" and "Very High"
 
.PARAMETER priority
    Specify the priority.
    Possible values are "Very low", "Low", "Medium", "High" and "Very High"
 
.PARAMETER ApprovalRequired
    Sets the request as waiting for Approval.
    Only valid on type Request
 
.PARAMETER requester_id
    The user ID that is the requester
 
.PARAMETER technician_id
    Specify the id of the technician
 
.PARAMETER DisableNotification
    Disables notification
    Defaults to False
 
.PARAMETER requesttypes_id
    Provide the ID of the request type
    ***** I need to figure this one out *****
 
.PARAMETER item_id
    Provide the id of an item to be associated to this ticket
    Requires item_type to be also specified.
 
.PARAMETER item_type
    The item type that is added.
    These are the default types GLPI provides
 
.EXAMPLE
    PS C:\> New-GlpiToolsTicket -Name 'New ticket subject' -Content 'Ticket text' -Priority High -Impact Low
    Example creates a incident ticket with High Priority and low Impact
 
.EXAMPLE
    PS C:\> New-GlpiToolsTicket -Name 'New ticket subject' -Content 'Ticket text' -item_id 4609 -item_type Computer
    Example creates a incident ticket and associates computer 4609
 
.EXAMPLE
    PS C:\> New-GlpiToolsTicket -Name 'New ticket subject' -Content 'Ticket text' -Type Request -ApprovalRequired -Requester_id 2
    Example creates a request ticket waiting on validation for the user with id 2
 
.OUTPUTS
    Function returns PSCustomObject with id's and messages from the GLPI API
.NOTES
    Author: Ron Peeters
    Date: 20200708
    Version: 1.0.0
#>


function New-GlpiToolsTicket {
    [CmdletBinding()]
    param (
        [parameter(
            Mandatory = $true,
            Position = 0,
            ValueFromPipelineByPropertyName = $true,
            HelpMessage = "ticket subject")]
        [alias('Subject')]
        [string]$name,
        
        [parameter(
            Mandatory = $true,
            Position = 1,
            ValueFromPipelineByPropertyName = $true,
            HelpMessage = "ticket content")]
        [alias('Body')]
        [string]$content,
        
        [parameter(
            Mandatory = $false,
            ValueFromPipelineByPropertyName = $true,
            HelpMessage = "ticket id from GLPI")]
        [int]$itilcategories_id,
        
        [parameter(
            Mandatory = $false,
            ValueFromPipelineByPropertyName = $true,
            HelpMessage = "Ticket urgency value"
        )]
        [ValidateSet("Very low", "Low", "Medium", "High", "Very High")]
        [string]$urgency = "Low",
        
        [parameter(
            Mandatory = $false,
            ValueFromPipelineByPropertyName = $true,
            HelpMessage = "Ticket impact value"
        )]
        [ValidateSet("Very low", "Low", "Medium", "High", "Very High")]
        [string]$impact = "Low",
        
        [parameter(
            Mandatory = $false,
            ValueFromPipelineByPropertyName = $true,
            HelpMessage = "Ticket priority value"
        )]
        [ValidateSet("Very low", "Low", "Medium", "High", "Very High")]
        [string]$priority = "Low",
        
        # [parameter(Mandatory = $false,
        # ParameterSetName = "Default")]
        # [ValidateSet("Incident", "Request")]
        # [string]$type = "Incident",
        
        [parameter(Mandatory = $false,
            #ParameterSetName = "Request",
            ValueFromPipelineByPropertyName = $true,
            HelpMessage = "Ticket type"
        )]
        [ValidateSet("Incident", "Request")]
        [string]$Type = "Incident",

        [parameter(
            Mandatory = $false,
            #ParameterSetName = "Request",
            ValueFromPipelineByPropertyName = $true,
            HelpMessage = "request type id"
        )]
        [int]$requesttypes_id,

        [parameter(
            Mandatory = $false,
            #ParameterSetName = "Request",
            ValueFromPipelineByPropertyName = $true,
            HelpMessage = "Approval required. Defaults to False"
        )]
        [switch]$ApprovalRequired,

        [parameter(
            Mandatory = $false,
            ValueFromPipelineByPropertyName = $true,
            HelpMessage = "Item ID to be linked to this new ticket"
        )]
        [int]$item_id = $null,

        [parameter(
            Mandatory = $false,
            ValueFromPipelineByPropertyName = $true,
            HelpMessage = "Item type to be added."
        )]
        [ValidateScript( {
                $ModulePath = Split-Path (Get-Module -Name GlpiTools).Path -Parent
                $Values = (Get-Content "$($ModulePath)\Private\Parameters.json" | ConvertFrom-Json).GlpiComponents
                If ($Values -notcontains $_) {
                    Write-Warning -Message "Invalid item type specified. Possible values for item_type are: $Values"
                    throw "Invalid item type specified."
                } else {
                    $true
                }
            })]
        [string]$item_type = $null,
        
        [parameter(
            Mandatory = $false,
            ValueFromPipelineByPropertyName = $true,
            HelpMessage = "user id of the technician to be assigned"
        )]
        [int]$technician_id,

        [parameter(
            Mandatory = $false,
            ValueFromPipelineByPropertyName = $true,
            HelpMessage = "Disables notification"
        )]
        [switch]$DisableNotification = $false,

        [parameter(
            Mandatory = $false,
            ValueFromPipelineByPropertyName = $true,
            HelpMessage = "user id of the requester"
        )]
        [int]$requester_id = 2

    )
    
    begin {

        If ($null -ne $PSBoundParameters['Item_id'] -and $null -eq $PSBoundParameters['Item_type']) {
            Write-Warning "[INVALID PARAMETERS] If item_id is specified, item_type needs to be specified accordingly"
            Exit
        }
        If ($PSBoundParameters['Type'] -ne 'Request' -and $PSBoundParameters['ApprovalRequired']) {
            Write-Warning "[INVALID PARAMETERS] Approval required specified but type is not a request."
            Exit
        }


        $AppToken = $Script:AppToken
        $PathToGlpi = $Script:PathToGlpi
        $SessionToken = $Script:SessionToken

        $AppToken = Get-GlpiToolsConfig -Verbose:$false | Select-Object -ExpandProperty AppToken
        $PathToGlpi = Get-GlpiToolsConfig -Verbose:$false | Select-Object -ExpandProperty PathToGlpi
        $SessionToken = Set-GlpiToolsInitSession -Verbose:$false | Select-Object -ExpandProperty SessionToken

        #$ChoosenParam = ($PSCmdlet.MyInvocation.BoundParameters).Keys

        switch ($urgency) {
            "Very low" { $urgency_id = 1 }
            "Low" { $urgency_id = 2 }
            "Medium" { $urgency_id = 3 }
            "High" { $urgency_id = 4 }
            "Very High" { $urgency_id = 5 }
            Default { $urgency_id = 2 }
        }
        switch ($impact) {
            "Very low" { $impact_id = 1 }
            "Low" { $impact_id = 2 }
            "Medium" { $impact_id = 3 }
            "High" { $impact_id = 4 }
            "Very High" { $impact_id = 5 }
            Default { $impact_id = 2 }
        }
        switch ($priority) {
            "Very low" { $priority_id = 1 }
            "Low" { $priority_id = 2 }
            "Medium" { $priority_id = 3 }
            "High" { $priority_id = 4 }
            "Very High" { $priority_id = 5 }
            Default { $priority_id = 2 }
        }

        switch ($Type) {
            "Incident" { $type_id = 1 }
            "Request" { $type_id = 2 }
        }


        $Output = [System.Collections.Generic.List[PSObject]]::New()
    }
    
    process {

        $hashNewTicket = @{
            name                = $name
            content             = $content
            type                = $type_id
            _users_id_requester = 0
        }

        If ($PSBoundParameters['Urgency']) {
            $hashNewTicket["urgency"] = $urgency_id
        }
        If ($PSBoundParameters['Impact']) {
            $hashNewTicket["impact"] = $impact_id
        }
        If ($PSBoundParameters['Priority']) {
            $hashNewTicket["priority"] = $priority_id
        }
        # If ($PSBoundParameters['ApprovalRequired']) {
        # $hashNewTicket["global_validation"] = 2
        # }
        If ($PSBoundParameters['Type'] -eq 'Request' -and $PSBoundParameters['ApprovalRequired']) {
            $hashNewTicket["global_validation"] = 2
        }
        If ($PSBoundParameters['requester_id']) {
            #$hashNewTicket["_users_id_requester"] = $requester_id
            $hashAddRequester = @{
                tickets_id       = $null
                users_id         = $requester_id
                type             = 1 # 1 = requester, 2 = assign, 3 = observer
                use_notification = 1
            }
        }
        If ($PSBoundParameters['technician_id']) {
            $hashNewTicket["technician"] = $technician_id #3031 # The ID of the GLPI SelfServicePortal User account
        }
        If ($PSBoundParameters['itilcategories_id']) {
            $hashNewTicket["itilcategories_id"] = $itilcategories_id
        }
        If ($PSBoundParameters['DisableNotification'] -and $DisableNotification -eq $true) {
            $hashNewTicket["_disablenotif"] = 'true'
            #$hashNewTicket["_users_id_requester_notif[use_notification][0]"] = 0
            #$hashNewTicket["use_notif"] = 0

            if ($hashAddRequester) {
                $hashAddRequester["use_notification"] = 0
            }
        }

        Write-Verbose ($hashNewTicket | Out-String)

        $GlpiUpload = $hashNewTicket | ConvertTo-Json
        $Upload = '{ "input" : ' + $GlpiUpload + '}'

        $params = @{
            headers = @{
                'Content-Type'  = 'application/json'
                'App-Token'     = $AppToken
                'Session-Token' = $SessionToken
            }
            method  = 'post'
            uri     = "$($PathToGlpi)/Ticket/"
            body    = ([System.Text.Encoding]::UTF8.GetBytes($Upload))
        }

        Try {
            Write-Verbose "Invoking API to create new ticket"
            $GlpiTicket = Invoke-RestMethod @params -ErrorAction Stop

            If ($GlpiTicket -match "</body>") {
                $GLPITicket = $GlpiTicket.split(">")[-1] | ConvertFrom-JSON
            } else {
                #Do nothing
            }

            $Output.Add($GLPITicket)

            Write-Verbose "New ticket created with ID $($GLPITicket.id)"

            #Adding requester if specified
            If ($PSBoundParameters['requester_id']) {
                $hashAddRequester["tickets_id"] = $GlpiTicket.ID

                Write-Verbose "Invoking API to add requester with ID $requester_id to newly created ticket $($glpiticket.ID)"
                $GlpiUpload = $hashAddRequester | ConvertTo-Json
                $Upload = '{ "input" : ' + $GlpiUpload + '}'

                $params = @{
                    headers = @{
                        'Content-Type'  = 'application/json'
                        'App-Token'     = $AppToken
                        'Session-Token' = $SessionToken
                    }
                    method  = 'post'
                    uri     = "$($PathToGlpi)/Ticket/$($GlpiTicket.id)/Ticket_User/"
                    body    = ([System.Text.Encoding]::UTF8.GetBytes($Upload))
                }

                $GlpiTicketAddRequester = Invoke-RestMethod @params -ErrorAction Stop
                Write-Verbose $GlpiTicketAddRequester

            }

            
            If ($PSBoundParameters['Item_id'] -and $PSBoundParameters['Item_type']) {
               
                Try {
                    Write-Verbose "Invoking API to add Item with id $($Item_id) to newly created ticket"
                    # "items_id":'.$Itemid.',"itemtype":"Item","tickets_id":'.$ticketid.'}

                    $hashAddItemtoTicket = @{
                        items_id   = $item_id
                        itemtype   = $item_type
                        tickets_id = $GlpiTicket.id
                
                    }
                    $GlpiUpload = $hashAddItemtoTicket | ConvertTo-Json
                    $Upload = '{ "input" : ' + $GlpiUpload + '}'

                    $params = @{
                        headers = @{
                            'Content-Type'  = 'application/json'
                            'App-Token'     = $AppToken
                            'Session-Token' = $SessionToken
                        }
                        method  = 'post'
                        uri     = "$($PathToGlpi)/Ticket/$($GlpiTicket.id)/Item_ticket/"
                        body    = ([System.Text.Encoding]::UTF8.GetBytes($Upload))
                    }

                    $GlpiTicketAddItem = Invoke-RestMethod @params -ErrorAction Stop
                    Write-Verbose $GlpiTicketAddItem

                    If ($GlpiTicketAddItem -match "</body>") {
                        $GlpiTicketAddItem = $GlpiTicketAddItem.split(">")[-1] | ConvertFrom-JSON
                    } else {
                        #Do nothing
                    }

                    $Output.Add($GlpiTicketAddItem)


                } Catch {
                    Write-Error "Unable to add Item to ticket"
                    Write-Error $_
                    # Write-Error ($params.GetEnumerator() | Out-string)
                    # Write-Error $Upload
                }
            }


        } Catch {
            Write-Error -Message "Unable to create new ticket."
            Write-Error $_
        }
    }
    
    end {
        $Output
        $Output = [System.Collections.Generic.List[PSObject]]::New()
        Set-GlpiToolsKillSession -SessionToken $SessionToken -Verbose:$false
    }
}

$ItemTypeValidate = {
    param ($commandName, $parameterName, $stringMatch)
    $ModulePath = Split-Path (Get-Module -Name GlpiTools).Path -Parent
    (Get-Content "$($ModulePath)\Private\Parameters.json" | ConvertFrom-Json).GlpiComponents | Where-Object { $_ -match "$stringMatch" }
}
Register-ArgumentCompleter -CommandName New-GlpiToolsTicket -ParameterName item_type -ScriptBlock $ItemTypeValidate