Private/ConvertTo-AtwsFilter.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
<#
 
    .COPYRIGHT
    Copyright (c) ECIT Solutions AS. All rights reserved. Licensed under the MIT license.
    See https://github.com/ecitsolutions/Autotask/blob/master/LICENSE.md for license information.
 
#>


Function ConvertTo-AtwsFilter {
    <#
            .SYNOPSIS
            This function converts a parameter set of a Get-function to a parsable approximation of a PowerShell
            filter.
            .DESCRIPTION
            This function converts a parameter set of a Get-function to a parsable approximation of a PowerShell
            filter. Due to internal scope contraints the function needs to be dot.sourced in the calling function.
            This function is not stand alone. It uses several variables that only exist in the calling scope,
            another reason it needs to be dot.sourced. This is not best practice, but it is still by design.
            .INPUTS
            System.Collections.Generic.Dictionary`2[System.string,System.Object]]
            .OUTPUTS
            [string[]]
            .EXAMPLE
            $Element | ConvertTo-AtwsDate -ParameterName <ParameterName>
            Converts variable $Element with must contain a single DateTime value to a string representation of the
            Date or the DateTime, based on the parameter name.
            .NOTES
            NAME: ConvertTo-AtwsFilter
       
    #>

    [cmdletbinding()]
    Param
    (
        [Parameter(
            Mandatory = $true,
            ValueFromPipeline = $true
        )]
        [System.Collections.Generic.Dictionary`2[System.string, System.Object]]
        $BoundParameters,
    
        [Parameter(
            Mandatory = $true
        )]
        [ValidateScript( { $Script:FieldInfoCache.Keys -contains $_ })]
        [string]
        $entityName
    )

    begin {
        # Enable modern -Debug behavior
        if ($PSCmdlet.MyInvocation.BoundParameters['Debug'].IsPresent) { $DebugPreference = 'Continue' }
    
        Write-Debug ('{0}: Begin of function' -F $MyInvocation.MyCommand.Name)
            
        $fields = Get-AtwsFieldInfo -Entity $entityName
        
        [string[]]$Filter = @()
    }

    process {
        Write-Debug ('{0}: Query based on parameters, parsing' -F $MyInvocation.MyCommand.Name)
      
        
 
        foreach ($parameter in $BoundParameters.GetEnumerator()) {
            $field = $fields | Where-Object { $_.Name -eq $parameter.Key }
      
            # If Parameter value is null or an empty string for string types, add name to $IsNull array
            # and continue
            if (($field.Type -ne 'string' -and $null -eq $parameter.Value) -or ($field.Type -eq 'string' -and $parameter.Value.Length -eq 0)) {
                if ($IsNull -notcontains $parameter.Key) { 
                    [Array]$IsNull += $parameter.Key
                }
                Continue
            }
      
            if ($field -or $parameter.Key -eq 'UserDefinedField') { 
                if ($parameter.Value.Count -gt 1) {
                    $Filter += '-begin'
                }
                foreach ($parameterValue in $parameter.Value) {   
                    $Operator = '-or'
                    $parameterName = $parameter.Key
                    if ($field.IsPickList) {
                        if ($field.PickListParentValueField) {
                            $parentField = $fields.Where{ $_.Name -eq $field.PickListParentValueField }
                            $parentLabel = $PSBoundParameters.$($parentField.Name)
                            $parentValue = $parentField.PickListValues | Where-Object { $_.Label -eq $parentLabel }
                            $pickListValue = $field.PickListValues | Where-Object { $_.Label -eq $parameterValue -and $_.ParentValue -eq $parentValue.Value }                
                        }
                        else { 
                            $pickListValue = $field.PickListValues | Where-Object { $_.Label -eq $parameterValue }
                        }
                        $value = $pickListValue.Value
                    }
                    elseif ($parameterName -eq 'UserDefinedField') {
                        $Filter += '-udf'              
                        $parameterName = $parameterValue.Name
                        
                        if ($null -eq $parameter.Value -or $parameter.Value.Length -eq 0) {
                            [Array]$IsNull += 'UserDefinedField'
                        }
                        
                        $value = $parameterValue.Value
                        
                    }
                    elseif (($parameterValue.GetType().Name -eq 'DateTime') -and -not ($parameter.Value.Count -gt 1)) {
                        if ($parameterValue -eq $parameterValue.Date -and 
                            $parameter.Key -notin $GreaterThan -and 
                            $parameter.Key -notin $GreaterThanOrEquals -and 
                            $parameter.Key -notin $LessThan -and 
                            $parameter.Key -notin $LessThanOrEquals) {

                            # User is searching for a date, not a specific datetime
                            $Filter += $parameterName
                            $Filter += '-ge'
                            $Filter += ConvertTo-AtwsDate -DateTime $parameterValue

                            # Force array, or the next time around we'll get a concatenated string
                            [Array]$LessThanOrEquals += $parameterName
                            $value = ConvertTo-AtwsDate -DateTime $parameterValue.AddDays(1)
                        }
                        else { 
                            $value = ConvertTo-AtwsDate -DateTime $parameterValue
                        }
                    }  
                    elseif ($field.Type -eq 'boolean') {
                        $value = switch ($parameterValue) {
                            { @('1', 'true') -contains $_ } { 1 }
                            { @('0', 'false') -contains $_ } { 0 }
                        }          
                    }
                    else {
                        $value = $parameterValue
                    }
                    $Filter += $parameterName
                    if ($parameter.Key -in $NotEquals) { 
                        $Filter += '-ne'
                        $Operator = '-and'
                    }
                    elseif ($parameter.Key -in $GreaterThan)
                    { $Filter += '-gt' }
                    elseif ($parameter.Key -in $GreaterThanOrEquals)
                    { $Filter += '-ge' }
                    elseif ($parameter.Key -in $LessThan)
                    { $Filter += '-lt' }
                    elseif ($parameter.Key -in $LessThanOrEquals)
                    { $Filter += '-le' }
                    elseif ($parameter.Key -in $Like) { 
                        $Filter += '-like'
                        $value = $value -replace '\*', '%'
                    }
                    elseif ($parameter.Key -in $NotLike) { 
                        $Filter += '-notlike'
                        $value = $value -replace '\*', '%'
                    }
                    elseif ($parameter.Key -in $BeginsWith)
                    { $Filter += '-beginswith' }
                    elseif ($parameter.Key -in $EndsWith)
                    { $Filter += '-endswith' }
                    elseif ($parameter.Key -in $Contains)
                    { $Filter += '-contains' }
                    elseif ($parameter.Key -in $IsThisDay)
                    { $Filter += '-isthisday' }
                    elseif ($parameter.Key -in $IsNull -and $parameter.Key -eq 'UserDefinedField') {
                        $Filter += '-IsNull'
                        $IsNull = $IsNull.Where( { $_ -ne 'UserDefinedField' })
                    }
                    elseif ($parameter.Key -in $IsNotNull -and $parameter.Key -eq 'UserDefinedField') {
                        $Filter += '-IsNotNull'
                        $IsNotNull = $IsNotNull.Where( { $_ -ne 'UserDefinedField' })
                    }
                    else
                    { $Filter += '-eq' }
            
                    # Add Value to expression, unless this is a UserDefinedfield AND UserDefinedField has been
                    # specified for -IsNull or -IsNotNull
                    if ($Filter[-1] -notin @('-IsNull', '-IsNotNull'))
                    { $Filter += $value }

                    if ($parameter.Value.Count -gt 1 -and $parameterValue -ne $parameter.Value[-1]) {
                        $Filter += $Operator
                    }
                    elseif ($parameter.Value.Count -gt 1) {
                        $Filter += '-end'
                    }
            
                }
            
            }
        }
        # IsNull and IsNotNull are special. They are the only operators that does not require a value to work
        if ($IsNull.Count -gt 0) {
            if ($Filter.Count -gt 0) {
                $Filter += '-and'
            }
            foreach ($PropertyName in $IsNull) {
                $Filter += $PropertyName
                $Filter += '-isnull'
            }
        }
        if ($IsNotNull.Count -gt 0) {
            if ($Filter.Count -gt 0) {
                $Filter += '-and'
            }
            foreach ($PropertyName in $IsNotNull) {
                $Filter += $PropertyName
                $Filter += '-isnotnull'
            }
        }  
 
    }

    end {
        Return $Filter
    }
}