From 6d8a7ae24b2d8237423a7a214cba205ced20d3ae Mon Sep 17 00:00:00 2001 From: rhouthuijzen <116062840+rhouthuijzen@users.noreply.github.com> Date: Mon, 24 Jun 2024 14:14:32 +0200 Subject: [PATCH] Feature fieldmapping readme (PSv2) (#12) * Fix: moved throw to try/catch * Fix: throw to try/catch and throw when aref empty * Feat: added verbose message for update on update * Feat: add fieldMapping and updated readme * Feat: added example how to update custom field * Feat: added forum post in readme * Fix: removed mapping folder * Fix: Update Logo URL * Fix: Now correctly explain custom field mapping * fix: updateOnupdate to onlyUpdateOnCorrelate * fix: user to employee * fix: onlyUpdateOnCorrelate toggle was flipped --------- Co-authored-by: Rick Jongbloed --- Mapping/EmAd.js | 11 -- README.md | 250 ++++++++++++++++++++++++++++++--------------- configuration.json | 8 +- create.ps1 | 47 +++++---- delete.ps1 | 72 +++++++------ fieldMapping.json | 66 ++++++++++++ update.ps1 | 77 +++++++------- 7 files changed, 342 insertions(+), 189 deletions(-) delete mode 100644 Mapping/EmAd.js create mode 100644 fieldMapping.json diff --git a/Mapping/EmAd.js b/Mapping/EmAd.js deleted file mode 100644 index 9a77efa..0000000 --- a/Mapping/EmAd.js +++ /dev/null @@ -1,11 +0,0 @@ -function getEmAd() { - let mail = ''; - - if (typeof Person.Accounts.MicrosoftActiveDirectory.mail !== 'undefined' && Person.Accounts.MicrosoftActiveDirectory.mail) { - mail = Person.Accounts.MicrosoftActiveDirectory.mail; - } - - return mail; -} - -getEmAd() \ No newline at end of file diff --git a/README.md b/README.md index ee065fe..e1aec64 100644 --- a/README.md +++ b/README.md @@ -1,58 +1,52 @@ -# HelloID-Conn-Prov-Target-AFAS-Profit-Employees -Repository for HelloID Provisioning Target Connector to AFAS Employees - -Forks Badge -Pull Requests Badge -Issues Badge -GitHub contributors -| :warning: Warning | -| :---------------- | -| This script is for the new powershell connector. Make sure to use the mapping and correlation keys like mentionded in this readme. For more information, please read our [documentation](https://docs.helloid.com/en/provisioning/target-systems/powershell-v2-target-systems.html) | +# HelloID-Conn-Prov-Target-AFAS-Profit-Employees +> [!IMPORTANT] +> This repository contains the connector and configuration code only. The implementer is responsible to acquire the connection details such as username, password, certificate, etc. You might even need to sign a contract or agreement with the supplier before implementing this connector. Please contact the client's application manager to coordinate the connector requirements. -| :information_source: Information | -|:---------------------------| -| This repository contains the connector and configuration code only. The implementer is responsible to acquire the connection details such as username, password, certificate, etc. You might even need to sign a contract or agreement with the supplier before implementing this connector. Please contact the client's application manager to coordinate the connector requirements. | -

- +

- -## Table of Contents +## Table of contents + - [HelloID-Conn-Prov-Target-AFAS-Profit-Employees](#helloid-conn-prov-target-afas-profit-employees) - - [Table of Contents](#table-of-contents) + - [Table of contents](#table-of-contents) - [Introduction](#introduction) - - [Getting Started](#getting-started) + - [Getting started](#getting-started) + - [Provisioning PowerShell V2 connector](#provisioning-powershell-v2-connector) + - [Correlation configuration](#correlation-configuration) + - [Field mapping](#field-mapping) - [Connection settings](#connection-settings) - [Prerequisites](#prerequisites) - - [GetConnector](#getconnector) - - [Remarks](#remarks) + - [Remarks](#remarks) - [Scope](#scope) - - [UpdateConnector](#updateconnector) - - [Mapping](#mapping) - - [Correlation](#correlation) + - [Setup the connector](#setup-the-connector) + - [Updating a custom field for AFAS employee](#updating-a-custom-field-for-afas-employee) - [Getting help](#getting-help) - [HelloID docs](#helloid-docs) - ## Introduction -The interface to communicate with Profit is through a set of GetConnectors, which is component that allows the creation of custom views on the Profit data. GetConnectors are based on a pre-defined 'data collection', which is an existing view based on the data inside the Profit database. -For this connector we have created a default set, which can be imported directly into the AFAS Profit environment. -The HelloID connector consists of the template scripts shown in the following table. +_HelloID-Conn-Prov-Target-AFAS-Profit-Employees is a _target_ connector. _AFAS-Profit-Employees_ provides a interface to communicate with Profit through a set of GetConnectors, which is component that allows the creation of custom views on the Profit data. GetConnectors are based on a pre-defined 'data collection', which is an existing view based on the data inside the Profit database. + +| Endpoint | Description | +| ----------------------------- | ----------- | +| profitrestservices/connectors | | -| Action | Action(s) Performed | Comment | -| ------------------------------- | --------------------- | --------- | -| create.ps1 | Update AFAS employee | Correlates AFAS employee | -| update.ps1 | Update AFAS employee | Update on correlate and update on update | -| delete.ps1 | Update AFAS employee | Clear the unique fields, since the values have to be unique over all AFAS environments | +The following lifecycle actions are available: - -## Getting Started +| Action | Description | +| ------------------ | --------------------------------------------------------------------------------------------------------------- | +| create.ps1 | PowerShell _correlate_ lifecycle action. Correlates | +| delete.ps1 | PowerShell _delete_ lifecycle action. Update on correlate and update on update | +| update.ps1 | PowerShell _update_ lifecycle action. Clear the unique fields, since the values have to be unique over all AFAS | +| configuration.json | Default _configuration.json_ | +| fieldMapping.json | Default _fieldMapping.json_ | -By using this connector you will have the ability to retrieve employee and contract data from the AFAS Profit HR system. +## Getting started + +By using this connector you will have the ability to update employees in the AFAS Profit system. Connecting to Profit is done using the app connector system. Please see the following pages from the AFAS Knowledge Base for more information. @@ -63,74 +57,166 @@ Please see the following pages from the AFAS Knowledge Base for more information [Manual add a token to the APP connector](https://help.afas.nl/help/NL/SE/App_Apps_Custom_Tokens_Manual.htm) +### Provisioning PowerShell V2 connector + +#### Correlation configuration + +The correlation configuration is used to specify which properties will be used to match an existing account within _{connectorName}_ to a person in _HelloID_. + +To properly setup the correlation: + +1. Open the `Correlation` tab. + +2. Specify the following configuration: + + | Setting | Value | + | ------------------------- | ------------ | + | Enable correlation | `True` | + | Person correlation field | `` | + | Account correlation field | `Medewerker` | + +> [!TIP] +> _For more information on correlation, please refer to our correlation [documentation](https://docs.helloid.com/en/provisioning/target-systems/powershell-v2-target-systems/correlation.html) pages_. + +#### Field mapping + +The field mapping can be imported by using the [_fieldMapping.json_](./fieldMapping.json) file. + +> [!TIP] +> `EmailPortal`, `TeNr` and `MbNr` are fields that can be mapped. Typically these are not fields that HelloID Provisioning needs to write back. + ### Connection settings The following settings are required to connect to the API. -| Setting | Description | Mandatory | -| --------------------------- | ----------- | --------- | -| Base Uri | The URL to the AFAS environment REST services | Yes | -| Token in XML format | The AppConnector token to connect to AFAS | Yes | -| Get Connector | The GetConnector in AFAS to query the user with | Yes | -| Update Connector | The UpdateConnector in AFAS to update the user with | Yes | -| Update on update | When toggled, if the mapped data differs from data in AFAS, the AFAS user will be updated when a update is triggerd. | No | -| Toggle debug logging | When toggled, extra logging is shown. Note that this is only meant for debugging, please switch this off when in production. | No | +| Setting | Description | Mandatory | +| ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | --------- | +| Base Uri | The URL to the AFAS environment REST services | Yes | +| Token in XML format | The AppConnector token to connect to AFAS | Yes | +| Get Connector | The GetConnector in AFAS to query the employee with | Yes | +| Update Connector | The UpdateConnector in AFAS to update the employee with | Yes | +| Create account when not found | When toggled, if the employee account is not found, a new the AFAS employee account will be created in the create action (only in the create action). | | +| Update on update | When toggled, if the mapped data differs from data in AFAS, the AFAS employee will be updated when a update is triggerd. | | +| Toggle debug logging | When toggled, extra logging is shown. Note that this is only meant for debugging, please switch this off when in production. | | ### Prerequisites - [ ] HelloID Provisioning agent (cloud or on-prem). - [ ] Loaded and available AFAS GetConnectors. +- [ ] In addition to use to the above get-connector, the connector also uses the following build-in Profit update-connectors: +* KnEmployee - [ ] AFAS App Connector with access to the GetConnectors and associated views. - [ ] Token for this AppConnector -### GetConnector -When the connector is defined as target system, only the following GetConnector is used by HelloID: +> [!TIP] +> For this connector we have created a default set [Tools4ever - HelloID - T4E_HelloID_Users_v2.gcn], which can be imported directly into the AFAS Profit environment. + +> [!NOTE] +> When the connector is defined as target system, only the following GetConnector is used by HelloID: +> * Tools4ever - HelloID - T4E_HelloID_Users_v2 + +### Remarks -* Tools4ever - HelloID - T4E_HelloID_Users_v2 +> [!IMPORTANT] +> In view of GDPR, the persons private data, such as private email address and birthdate are not in the data collection by default. When needed for the implementation (e.g. set emailaddress with private email address on delete), these properties will have to be added. -#### Remarks - - In view of GDPR, the persons private data, such as private email address and birthdate are not in the data collection by default. When needed for the implementation (e.g. set emailaddress with private email address on delete), these properties will have to be added. +> [!IMPORTANT] +> We never delete employees in AFAS, we only clear the unique fields. #### Scope The data collection retrieved by the set of GetConnector's is sufficient for HelloID to provision persons. The data collection can be changed by the customer itself to meet their requirements. -| Connector | Field | Default filter | -| ----------------------------------------------------- | ------------------- | ------------------------- | -| __Tools4ever - HelloID - T4E_HelloID_Users_v2__ | contract start date | <[Vandaag + 3 maanden] | -| | contract end date | >[Vandaag - 3 maanden];[] | - -### UpdateConnector -In addition to use to the above get-connector, the connector also uses the following build-in Profit update-connectors: - -* knEmployee - -### Mapping -The mandatory and recommended field mapping is listed below. - -| Name | Create | Enable | Update | Disable | Delete | Store in account data | Default mapping | Mandatory | Comment | -| -------------- | ------ | ------ | ------ | ------- | ------ | --------------------- | ------------------------------------------ | --------- | ---------------------------------------------- | -| Medewerker | X | | X | | | Yes | Field: ExternalId | Yes | Used for Correlation and to store account data | -| Persoonsnummer | X | | X | | | Yes | None | Yes | Used to store account data | -| EmAd | | | X | | X | Yes | Update: Complex EmAd.js Delete Fixed empty | | E-Mail werk | - -The fields listed below are examples of available fields for mapping but are typically not used. - -| Name | Create | Enable | Update | Disable | Delete | Store in account data | Default mapping | Mandatory | Comment | -| ----------- | ------ | ------ | ------ | ------- | ------ | --------------------- | -------------------------------------- | --------- | ---------------------------------------------------------------------- | -| EmailPortal | | | X | | X | Yes | for example UPN | | E-mail toegang - Check with AFAS Administrator if this needs to be set | -| TeNr | | | X | | X | Yes | | | Telefoonnr. werk | -| MbNr | | | X | | X | Yes | | | Mobiel werk | - - -### Correlation -It is mandatory to enable the correlation in the correlation tab. The default value for "person correlation field" is " ExternalId". The default value for "Account Correlation field" is "Medewerker". - +| Connector | Field | Default filter | +| ----------------------------------------------- | ------------------- | ------------------------- | +| __Tools4ever - HelloID - T4E_HelloID_Users_v2__ | contract start date | <[Vandaag + 3 maanden] | +| | contract end date | >[Vandaag - 3 maanden];[] | + + + +## Setup the connector + +> [!TIP] +> `EmailPortal` is typically set on the AFAS user. We have a separate [target connector](https://github.com/Tools4everBV/HelloID-Conn-Prov-Target-AFAS-Profit-Users) for managing AFAS users + +### Updating a custom field for AFAS employee +In certain situations, you want to write certain information back to a custom field in AFAS. The example below explains how to add this to the code. + +For more information about updating a custom field for AFAS employees. Please check the [AFAS documentation](https://help.afas.nl/help/NL/SE/App_Cnnctr_Update_050.htms) + +If you want to compare the custom field with your field mapping. The custom field needs to be added to the `T4E_HelloID_Users_v2` GetConnector, + +```powershell +$updateAccount = [PSCustomObject]@{ + 'AfasEmployee' = @{ + 'Element' = @{ + '@EmId' = $currentAccount.Medewerker + 'Fields' = @{ + '' = $account.fieldNameAFAS + } + 'Objects' = @(@{ + 'KnPerson' = @{ + 'Element' = @{ + 'Fields' = @{ + # Zoek op BcCo (Persoons-ID) + 'MatchPer' = 0 + # Nummer + 'BcCo' = $currentAccount.Persoonsnummer + } + } + } + }) + } + } +} +``` +> [!NOTE] +> Because mapped values are typically added in the body of 'KnPerson' you need to skip the `$account.fieldNameAFAS` from adding it to the `$AfasEmployee` body. Also, you need to add the field to `$updateAccountFields` and `$previousAccount`. Example: + +```powershell +$updateAccountFields = @() +if ($account.PSObject.Properties.Name -Contains 'fieldNameAFAS') { + $updateAccountFields += "fieldNameAFAS" +} +``` + +```powershell +# 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 + # Overtime + 'fieldNameAFAS' = $currentAccount.Overtime +} +``` + +```powershell +foreach ($newProperty in $newProperties ) { + if ($newProperty.name -ne 'fieldNameAFAS') { + $updateAccount.AfasEmployee.Element.Objects[0].KnPerson.Element.Fields.$($newProperty.Name) = $newProperty.Value + } +} +``` + + + +> [!TIP] +> If you need more information please check out our [forum post](https://forum.helloid.com/forum/helloid-provisioning/1261-updating-a-custom-field-for-afas-employee). ## Getting help -> _For more information on how to configure a HelloID PowerShell connector, please refer to our [documentation](https://docs.helloid.com/hc/en-us/articles/360012558020-Configure-a-custom-PowerShell-target-system) pages_ -> _If you need help, feel free to ask questions on our [forum](https://forum.helloid.com)_ +> [!TIP] +> _For more information on how to configure a HelloID PowerShell connector, please refer to our [documentation](https://docs.helloid.com/en/provisioning/target-systems/powershell-v2-target-systems.html) pages_. + +> [!TIP] +> _If you need help, feel free to ask questions on our [forum](https://forum.helloid.com)_. ## HelloID docs + The official HelloID documentation can be found at: https://docs.helloid.com/ diff --git a/configuration.json b/configuration.json index bb40485..a324e59 100644 --- a/configuration.json +++ b/configuration.json @@ -42,13 +42,13 @@ } }, { - "key": "updateOnUpdate", + "key": "onlyUpdateOnCorrelate", "type": "checkbox", "defaultValue": false, "templateOptions": { - "label": "Update on update", + "label": "Only update on correlate", "required": false, - "description": "When toggled, if the mapped data differs from data in AFAS, the AFAS user will be updated when a update is triggerd" + "description": "When toggled, the AFAS employee will only be updated when the account is correlated" } }, { @@ -61,4 +61,4 @@ "required": false } } -] \ No newline at end of file +] diff --git a/create.ps1 b/create.ps1 index 747d704..d1eeb65 100644 --- a/create.ps1 +++ b/create.ps1 @@ -1,7 +1,6 @@ ##################################################### # HelloID-Conn-Prov-Target-AFAS-Profit-Employees-Create -# -# Version: 3.0.0 | new-powershell-connector +# PowerShell V2 ##################################################### # Set to true at start, because only when an error occurs it is set to false @@ -19,28 +18,6 @@ switch ($($actionContext.Configuration.isDebug)) { # Enable TLS1.2 [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor [System.Net.SecurityProtocolType]::Tls12 -if ($actionContext.CorrelationConfiguration.Enabled) { - $correlationProperty = $actionContext.CorrelationConfiguration.accountField - $correlationValue = $actionContext.CorrelationConfiguration.accountFieldValue - - if ([string]::IsNullOrEmpty($correlationProperty)) { - Write-Warning "Correlation is enabled but not configured correctly." - Throw "Correlation is enabled but not configured correctly." - } - - if ([string]::IsNullOrEmpty($correlationValue)) { - Write-Warning "The correlation value for [$correlationProperty] is empty. This is likely a scripting issue." - Throw "The correlation value for [$correlationProperty] is empty. This is likely a scripting issue." - } -} -else { - $outputContext.AuditLogs.Add([PSCustomObject]@{ - Message = "Configuration of correlation is mandatory." - IsError = $true - }) - Throw "Configuration of correlation is mandatory." -} - #region functions function Resolve-HTTPError { [CmdletBinding()] @@ -137,6 +114,28 @@ function Get-ErrorMessage { # Get current account and verify if there are changes try { + if ($actionContext.CorrelationConfiguration.Enabled) { + $correlationProperty = $actionContext.CorrelationConfiguration.accountField + $correlationValue = $actionContext.CorrelationConfiguration.accountFieldValue + + if ([string]::IsNullOrEmpty($correlationProperty)) { + Write-Warning "Correlation is enabled but not configured correctly." + Throw "Correlation is enabled but not configured correctly." + } + + if ([string]::IsNullOrEmpty($correlationValue)) { + Write-Warning "The correlation value for [$correlationProperty] is empty. This is likely a scripting issue." + Throw "The correlation value for [$correlationProperty] is empty. This is likely a scripting issue." + } + } + else { + $outputContext.AuditLogs.Add([PSCustomObject]@{ + Message = "Configuration of correlation is madatory." + IsError = $true + }) + Throw "Configuration of correlation is madatory." + } + Write-Verbose "Querying AFAS employee where [$($correlationProperty)] = [$($correlationValue)]" # Create authorization headers diff --git a/delete.ps1 b/delete.ps1 index d938643..886eb54 100644 --- a/delete.ps1 +++ b/delete.ps1 @@ -1,7 +1,6 @@ ##################################################### # HelloID-Conn-Prov-Target-AFAS-Profit-Employees-Delete -# -# Version: 3.0.0 | new-powershell-connector +# PowerShell V2 ##################################################### # Set to true at start, because only when an error occurs it is set to false @@ -16,35 +15,6 @@ switch ($($actionContext.Configuration.isDebug)) { # Enable TLS1.2 [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor [System.Net.SecurityProtocolType]::Tls12 -$account = $actionContext.Data - -$correlationProperty = $actionContext.CorrelationConfiguration.accountField -$correlationValue = $actionContext.References.Account.Medewerker # Has to match the AFAS value of the specified filter field ($filterfieldid) - -if ([string]::IsNullOrEmpty($correlationProperty)) { - Write-Warning "Correlation is enabled but not configured correctly." - Throw "Correlation is enabled but not configured correctly." -} - -if ([string]::IsNullOrEmpty($correlationValue)) { - Write-Warning "The correlation value for [$correlationProperty] is empty. Account Refference is empty." - Throw "The correlation value for [$correlationProperty] is empty. Account Refference is empty." -} - -$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" -} - #region functions function Resolve-HTTPError { [CmdletBinding()] @@ -141,6 +111,37 @@ function Get-ErrorMessage { # Get current account and verify if there are changes 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' + } + + try { Write-Verbose "Querying AFAS employee where [$($correlationProperty)] = [$($correlationValue)]" @@ -218,7 +219,7 @@ try { } # Skip further actions, as this is a critical error - continue + throw "Error querying AFAS employee" } switch ($updateAction) { @@ -310,8 +311,9 @@ try { 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' { @@ -338,6 +340,10 @@ try { } } } +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) { diff --git a/fieldMapping.json b/fieldMapping.json new file mode 100644 index 0000000..da0faa5 --- /dev/null +++ b/fieldMapping.json @@ -0,0 +1,66 @@ +{ + "Version": "v1", + "MappingFields": [ + { + "Name": "Medewerker", + "Description": "[Mandatory]", + "Type": "Text", + "MappingActions": [ + { + "MapForActions": [ + "Create", + "Update" + ], + "MappingMode": "Field", + "Value": "\"Person.ExternalId\"", + "UsedInNotifications": false, + "StoreInAccountData": true + } + ] + }, + { + "Name": "Persoonsnummer", + "Description": "[Mandatory]", + "Type": "Text", + "MappingActions": [ + { + "MapForActions": [ + "Create", + "Update" + ], + "MappingMode": "None", + "Value": "\"\"", + "UsedInNotifications": false, + "StoreInAccountData": true + } + ] + }, + { + "Name": "EmAd", + "Description": "", + "Type": "Text", + "MappingActions": [ + { + "MapForActions": [ + "Create", + "Update" + ], + "MappingMode": "Complex", + "Value": "\"function getEmail() {\\r\\n let mail = '';\\r\\n\\r\\n if (typeof Person.Accounts.MicrosoftActiveDirectory.mail !== 'undefined' && Person.Accounts.MicrosoftActiveDirectory.mail) {\\r\\n mail = Person.Accounts.MicrosoftActiveDirectory.mail;\\r\\n }\\r\\n\\r\\n return mail;\\r\\n}\\r\\n\\r\\ngetEmail()\"", + "UsedInNotifications": false, + "StoreInAccountData": true + }, + { + "MapForActions": [ + "Delete" + ], + "MappingMode": "Fixed", + "Value": "\"\"", + "UsedInNotifications": false, + "StoreInAccountData": false + } + ] + } + ], + "UniqueFieldNames": [] +} \ No newline at end of file diff --git a/update.ps1 b/update.ps1 index a4e7ce4..258d91b 100644 --- a/update.ps1 +++ b/update.ps1 @@ -1,7 +1,6 @@ ##################################################### # HelloID-Conn-Prov-Target-AFAS-Profit-Employees-Update -# -# Version: 3.0.0 | new-powershell-connector +# PowerShell V2 ##################################################### # Set to true at start, because only when an error occurs it is set to false @@ -19,35 +18,6 @@ switch ($($actionContext.Configuration.isDebug)) { # Enable TLS1.2 [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor [System.Net.SecurityProtocolType]::Tls12 -$account = $actionContext.Data - -$correlationProperty = $actionContext.CorrelationConfiguration.accountField -$correlationValue = $actionContext.References.Account.Medewerker # Has to match the AFAS value of the specified filter field ($filterfieldid) - -if ([string]::IsNullOrEmpty($correlationProperty)) { - Write-Warning "Correlation is enabled but not configured correctly." - Throw "Correlation is enabled but not configured correctly." -} - -if ([string]::IsNullOrEmpty($correlationValue)) { - Write-Warning "The correlation value for [$correlationProperty] is empty. Account Refference is empty." - Throw "The correlation value for [$correlationProperty] is empty. Account Refference is empty." -} - -$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" -} - #region functions function Resolve-HTTPError { [CmdletBinding()] @@ -140,9 +110,39 @@ function Get-ErrorMessage { Write-Output $errorMessage } } +#endregion functions try { - #endregion functions - if (($actionContext.Configuration.updateOnUpdate -eq $true) -or ($actionContext.AccountCorrelated -eq $true)) { + $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)]" @@ -214,7 +214,7 @@ try { }) # Skip further actions, as this is a critical error - continue + throw "Error querying AFAS employee" } switch ($updateAction) { @@ -306,6 +306,8 @@ try { 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 @@ -336,8 +338,13 @@ try { } 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) { @@ -354,4 +361,4 @@ finally { $outputContext.AccountReference = $aRef $outputContext.Data = $exportData $outputContext.PreviousData = $previousAccount -} \ No newline at end of file +}