-
Notifications
You must be signed in to change notification settings - Fork 0
/
update.ps1
364 lines (317 loc) · 16.4 KB
/
update.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
#####################################################
# HelloID-Conn-Prov-Target-AFAS-Profit-Employees-Update
# PowerShell V2
#####################################################
# Set to true at start, because only when an error occurs it is set to false
$outputContext.Success = $true
# AccountReference must have a value for dryRun
$aRef = $actionContext.References.Account
# Set debug logging
switch ($($actionContext.Configuration.isDebug)) {
$true { $VerbosePreference = 'Continue' }
$false { $VerbosePreference = 'SilentlyContinue' }
}
# Enable TLS1.2
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor [System.Net.SecurityProtocolType]::Tls12
#region functions
function Resolve-HTTPError {
[CmdletBinding()]
param (
[Parameter(Mandatory,
ValueFromPipeline
)]
[object]$ErrorObject
)
process {
$httpErrorObj = [PSCustomObject]@{
FullyQualifiedErrorId = $ErrorObject.FullyQualifiedErrorId
MyCommand = $ErrorObject.InvocationInfo.MyCommand
RequestUri = $ErrorObject.TargetObject.RequestUri
ScriptStackTrace = $ErrorObject.ScriptStackTrace
ErrorMessage = ''
}
if ($ErrorObject.Exception.GetType().FullName -eq 'Microsoft.PowerShell.Commands.HttpResponseException') {
$httpErrorObj.ErrorMessage = $ErrorObject.ErrorDetails.Message
}
elseif ($ErrorObject.Exception.GetType().FullName -eq 'System.Net.WebException') {
$httpErrorObj.ErrorMessage = [System.IO.StreamReader]::new($ErrorObject.Exception.Response.GetResponseStream()).ReadToEnd()
}
Write-Output $httpErrorObj
}
}
function Resolve-AFASErrorMessage {
[CmdletBinding()]
param (
[Parameter(Mandatory,
ValueFromPipeline
)]
[object]$ErrorObject
)
process {
try {
$errorObjectConverted = $ErrorObject | ConvertFrom-Json -ErrorAction Stop
if ($null -ne $errorObjectConverted.externalMessage) {
$errorMessage = $errorObjectConverted.externalMessage
}
else {
$errorMessage = $errorObjectConverted
}
}
catch {
$errorMessage = "$($ErrorObject.Exception.Message)"
}
Write-Output $errorMessage
}
}
function Get-ErrorMessage {
[CmdletBinding()]
param (
[Parameter(Mandatory,
ValueFromPipeline
)]
[object]$ErrorObject
)
process {
$errorMessage = [PSCustomObject]@{
VerboseErrorMessage = $null
AuditErrorMessage = $null
}
if ( $($ErrorObject.Exception.GetType().FullName -eq 'Microsoft.PowerShell.Commands.HttpResponseException') -or $($ErrorObject.Exception.GetType().FullName -eq 'System.Net.WebException')) {
$httpErrorObject = Resolve-HTTPError -ErrorObject $ErrorObject
if (-not[String]::IsNullOrEmpty($httpErrorObject.ErrorMessage)) {
$errorMessage.VerboseErrorMessage = $httpErrorObject.ErrorMessage
$errorMessage.AuditErrorMessage = Resolve-AFASErrorMessage -ErrorObject $httpErrorObject.ErrorMessage
}
else {
$errorMessage.VerboseErrorMessage = $ErrorObject.Exception.Message
$errorMessage.AuditErrorMessage = $ErrorObject.Exception.Message
}
}
# If error message empty, fall back on $ex.Exception.Message
if ([String]::IsNullOrEmpty($errorMessage.VerboseErrorMessage)) {
$errorMessage.VerboseErrorMessage = $ErrorObject.Exception.Message
}
if ([String]::IsNullOrEmpty($errorMessage.AuditErrorMessage)) {
$errorMessage.AuditErrorMessage = $ErrorObject.Exception.Message
}
Write-Output $errorMessage
}
}
#endregion functions
try {
$account = $actionContext.Data
$correlationProperty = $actionContext.CorrelationConfiguration.accountField
$correlationValue = $actionContext.References.Account.Medewerker # Has to match the AFAS value of the specified filter field ($filterfieldid)
$updateAccountFields = @()
if ($account.PSObject.Properties.Name -Contains 'EmAd') {
$updateAccountFields += "EmAd"
}
if ($account.PSObject.Properties.Name -Contains 'EmailPortal') {
$updateAccountFields += "EmailPortal"
}
if ($account.PSObject.Properties.Name -Contains 'TeNr') {
$updateAccountFields += "TeNr"
}
if ($account.PSObject.Properties.Name -Contains 'MbNr') {
$updateAccountFields += "MbNr"
}
# Verify if [aRef] has a value
if ([string]::IsNullOrEmpty($($actionContext.References.Account))) {
$outputContext.AuditLogs.Add([PSCustomObject]@{
Action = "UpdateAccount"
Message = "The account reference could not be found"
IsError = $true
})
throw 'The account reference could not be found'
}
if (($actionContext.Configuration.onlyUpdateOnCorrelate -eq $false) -or ($actionContext.AccountCorrelated -eq $true)) {
# Get current account and verify if there are changes
try {
Write-Verbose "Querying AFAS employee where [$($correlationProperty)] = [$($correlationValue)]"
# Create authorization headers
$encodedToken = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($actionContext.Configuration.Token))
$authValue = "AfasToken $encodedToken"
$Headers = @{ Authorization = $authValue }
$Headers.Add("IntegrationId", "45963_140664") # Fixed value - Tools4ever Partner Integration ID
$splatWebRequest = @{
Uri = "$($actionContext.Configuration.BaseUri)/connectors/$($actionContext.Configuration.GetConnector)?filterfieldids=$($correlationProperty)&filtervalues=$($correlationValue)&operatortypes=1"
Headers = $headers
Method = 'GET'
ContentType = "application/json;charset=utf-8"
UseBasicParsing = $true
}
$currentAccount = (Invoke-RestMethod @splatWebRequest -Verbose:$false).rows
if ($null -eq $currentAccount.Medewerker) {
throw "No AFAS employee found AFAS employee where [$($correlationProperty)] = [$($correlationValue)]"
}
# Retrieve current account data for properties to be updated
$previousAccount = [PSCustomObject]@{
# E-Mail werk
'EmAd' = $currentAccount.Email_werk
# E-mail toegang
'EmailPortal' = $currentAccount.Email_portal
# Telefoonnr. werk
'TeNr' = $currentAccount.Telefoonnr_werk
# Mobiel werk
'MbNr' = $currentAccount.Mobielnr_werk
}
# Calculate changes between current data and provided data
$splatCompareProperties = @{
ReferenceObject = @($previousAccount.PSObject.Properties | Where-Object { $_.Name -in $updateAccountFields }) # Only select the properties to update
DifferenceObject = @($account.PSObject.Properties | Where-Object { $_.Name -in $updateAccountFields }) # Only select the properties to update
}
$changedProperties = $null
$changedProperties = (Compare-Object @splatCompareProperties -PassThru)
$oldProperties = $changedProperties.Where( { $_.SideIndicator -eq '<=' })
$newProperties = $changedProperties.Where( { $_.SideIndicator -eq '=>' })
if (($newProperties | Measure-Object).Count -ge 1) {
Write-Verbose "Changed properties: $($changedProperties | ConvertTo-Json)"
$updateAction = 'Update'
}
else {
Write-Verbose "No changed properties"
$updateAction = 'NoChanges'
}
}
catch {
$ex = $PSItem
$errorMessage = Get-ErrorMessage -ErrorObject $ex
Write-Verbose "Error at Line [$($ex.InvocationInfo.ScriptLineNumber)]: $($ex.InvocationInfo.Line). Error: $($errorMessage.VerboseErrorMessage)"
$outputContext.AuditLogs.Add([PSCustomObject]@{
Action = "UpdateAccount"
Message = "Error querying AFAS employee where [$($correlationProperty)] = [$($correlationValue)]. Error Message: $($errorMessage.AuditErrorMessage)"
IsError = $true
})
# Skip further actions, as this is a critical error
throw "Error querying AFAS employee"
}
switch ($updateAction) {
'Update' {
# Update AFAS Employee
try {
# Create custom object with old and new values
$changedPropertiesObject = [PSCustomObject]@{
OldValues = @{}
NewValues = @{}
}
# Add the old properties to the custom object with old and new values
foreach ($oldProperty in ($oldProperties | Where-Object { $_.Name -in $newProperties.Name })) {
$changedPropertiesObject.OldValues.$($oldProperty.Name) = $oldProperty.Value
}
# Add the new properties to the custom object with old and new values
foreach ($newProperty in $newProperties) {
$changedPropertiesObject.NewValues.$($newProperty.Name) = $newProperty.Value
}
Write-Verbose "Changed properties: $($changedPropertiesObject | ConvertTo-Json)"
# Create custom account object for update and set with default properties and values
$updateAccount = [PSCustomObject]@{
'AfasEmployee' = @{
'Element' = @{
'@EmId' = $currentAccount.Medewerker
'Objects' = @(@{
'KnPerson' = @{
'Element' = @{
'Fields' = @{
# Zoek op BcCo (Persoons-ID)
'MatchPer' = 0
# Nummer
'BcCo' = $currentAccount.Persoonsnummer
}
}
}
})
}
}
}
# Add the updated properties to the custom account object for update - Only add changed properties. AFAS will throw an error when trying to update this with the same value
foreach ($newProperty in $newProperties ) {
$updateAccount.AfasEmployee.Element.Objects[0].KnPerson.Element.Fields.$($newProperty.Name) = $newProperty.Value
}
$body = ($updateAccount | ConvertTo-Json -Depth 10)
$splatWebRequest = @{
Uri = "$($actionContext.Configuration.BaseUri)/connectors/$($actionContext.Configuration.UpdateConnector)"
Headers = $headers
Method = 'PUT'
Body = ([System.Text.Encoding]::UTF8.GetBytes($body))
ContentType = "application/json;charset=utf-8"
UseBasicParsing = $true
}
if (-Not($actionContext.DryRun -eq $true)) {
Write-Verbose "Updating AFAS employee [$($currentAccount.Medewerker)]. Old values: $($changedPropertiesObject.oldValues | ConvertTo-Json -Depth 10). New values: $($changedPropertiesObject.newValues | ConvertTo-Json -Depth 10)"
$updatedAccount = Invoke-RestMethod @splatWebRequest -Verbose:$false
# Set aRef object for use in futher actions
$aRef = [PSCustomObject]@{
Medewerker = $currentAccount.Medewerker
Persoonsnummer = $currentAccount.Persoonsnummer
}
$outputContext.AuditLogs.Add([PSCustomObject]@{
Action = "UpdateAccount"
Message = "Successfully updated AFAS employee [$($currentAccount.Medewerker)]. Old values: $($changedPropertiesObject.oldValues | ConvertTo-Json -Depth 10). New values: $($changedPropertiesObject.newValues | ConvertTo-Json -Depth 10)"
IsError = $false
})
}
else {
Write-Warning "DryRun: Would update AFAS employee [$($currentAccount.Medewerker)]. Old values: $($changedPropertiesObject.oldValues | ConvertTo-Json -Depth 10). New values: $($changedPropertiesObject.newValues | ConvertTo-Json -Depth 10)"
}
}
catch {
$ex = $PSItem
$errorMessage = Get-ErrorMessage -ErrorObject $ex
Write-Verbose "Error at Line '$($ex.InvocationInfo.ScriptLineNumber)': $($ex.InvocationInfo.Line). Error: $($errorMessage.VerboseErrorMessage)"
$outputContext.AuditLogs.Add([PSCustomObject]@{
Action = "UpdateAccount"
Message = "Error updating AFAS employee [$($currentAccount.Medewerker)]. Error Message: $($errorMessage.AuditErrorMessage). Old values: $($changedPropertiesObject.oldValues | ConvertTo-Json -Depth 10). New values: $($changedPropertiesObject.newValues | ConvertTo-Json -Depth 10)"
IsError = $true
})
# Skip further actions, as this is a critical error
throw "Error updating AFAS employee"
}
break
}
'NoChanges' {
Write-Verbose "No changes needed for AFAS employee [$($currentAccount.Medewerker)]"
if (-Not($actionContext.DryRun -eq $true)) {
# Set aRef object for use in futher actions
$aRef = [PSCustomObject]@{
Medewerker = $currentAccount.Medewerker
Persoonsnummer = $currentAccount.Persoonsnummer
}
$outputContext.AuditLogs.Add([PSCustomObject]@{
Action = "UpdateAccount"
Message = "No changes needed for AFAS employee [$($currentAccount.Medewerker)]"
IsError = $false
})
}
else {
Write-Warning "DryRun: No changes needed for AFAS employee [$($currentAccount.Medewerker)]"
}
break
}
}
}
else {
$previousAccount = $account
Write-Verbose "The configuration parameter only update on correlate is [$($actionContext.Configuration.onlyUpdateOnCorrelate)]"
}
}
catch {
$ex = $PSItem
Write-Verbose "ERROR: $ex"
}
finally {
# Check if auditLogs contains errors, if errors are found, set succes to false
if ($outputContext.AuditLogs.IsError -contains $true) {
$outputContext.Success = $false
}
# Define ExportData with account fields and correlation property
$exportData = $account.PsObject.Copy()
# Add correlation property to exportdata
$exportData | Add-Member -MemberType NoteProperty -Name $correlationProperty -Value $correlationValue -Force
# Add aRef properties to exportdata
foreach ($aRefProperty in $aRef.PSObject.Properties) {
$exportData | Add-Member -MemberType NoteProperty -Name $aRefProperty.Name -Value $aRefProperty.Value -Force
}
$outputContext.AccountReference = $aRef
$outputContext.Data = $exportData
$outputContext.PreviousData = $previousAccount
}