IONModule.psm1

#Region './Private/Connect-API.ps1' -1

<#
.SYNOPSIS
Connects to the ION API using a refresh token.

.DESCRIPTION
The Connect-API function connects to the API by requesting a new access token using a refresh token. It also provides the option to update a KeyVault with the new refresh token.

.PARAMETER RefreshToken
The refresh token used to request a new access token. If not provided, the function will attempt to retrieve the refresh token from the script's global scope.

.PARAMETER AzureSubscriptionId
The Azure subscription ID used to update the KeyVault with the new refresh token. This parameter is optional.

.PARAMETER KeyVaultName
The name of the KeyVault used to store the refresh token. This parameter is optional.

.PARAMETER KeyVaultSecretName
The name of the secret in the KeyVault that stores the refresh token. This parameter is optional.

.EXAMPLE
Connect-API -RefreshToken "abc123" -AzureSubscriptionId "12345678-1234-1234-1234-1234567890ab" -KeyVaultName "MyKeyVault" -KeyVaultSecretName "RefreshTokenSecret"

Connects to the API using the provided refresh token and updates the specified KeyVault with the new refresh token.

#>


function Connect-API {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $false)]
        [string]$RefreshToken = $Script:RefreshToken,
        [Parameter(Mandatory = $false)]
        [string]$AzureSubscriptionId = $Script:AzureSubscriptionId,
        [Parameter(Mandatory = $false)]
        [string]$KeyVaultName = $Script:KeyVaultName,
        [Parameter(Mandatory = $false)]
        [string]$KeyVaultSecretName = $Script:KeyVaultSecretName

    )
    if ($Script:AzureSubscriptionId) {
        Write-Verbose "RefreshToken not provided. Connecting to KeyVault to retrieve RefreshToken"
        try {
        $refreshToken = (Get-AzKeyVaultSecret -VaultName $keyVaultName -Name $KeyVaultSecretName -AsPlainText -ErrorAction Stop)
        } catch {
            Connect-AzAccount | Out-Null
            $refreshToken = (Get-AzKeyVaultSecret -VaultName $keyVaultName -Name $KeyVaultSecretName -AsPlainText -ErrorAction Stop)
        }
    }

    $Script:formData = @{
        grant_type = "refresh_token"
        refresh_token = $refreshToken
    }

    $url = $script:baseurl + "/oauth/token"
    
    Write-Verbose "Requesting new token from $url"
    $token = Invoke-RestMethod -Uri $url -Method Post -Form $Script:formData -ContentType "application/x-www-form-urlencoded"


    if ($KeyVaultName -and $KeyVaultSecretName -and $AzureSubscriptionId) {
        Write-Verbose "Updating KeyVault with new RefreshToken"
        Update-KeyVaultSecret -SecretName $KeyVaultSecretName -SecretValue $token.refresh_token -AzureSubscriptionId $AzureSubscriptionId -keyVaultName $KeyVaultName
    }

    $script:AuthHeader = @{ Authorization = "Bearer $($token.access_token)" }
    $script:TokenAcquiredTime = Get-Date
    $script:ExpiresIn = $token.expires_in
    $script:refreshToken = $token.refresh_token

}
#EndRegion './Private/Connect-API.ps1' 72
#Region './Private/Get-TokenExpiry.ps1' -1

<#
.SYNOPSIS
Calculates the expiry date and time for a token.

.DESCRIPTION
The Get-TokenExpiry function calculates the expiry date and time for a token based on the token's expiration time in seconds.

.PARAMETER ExpiresIn
Specifies the expiration time of the token in seconds. If not provided, the function uses the value stored in the $script:ExpiresIn variable.

.OUTPUTS
System.DateTime
The calculated expiry date and time for the token.

.EXAMPLE
Get-TokenExpiry -ExpiresIn 3600
Calculates the expiry date and time for a token that expires in 3600 seconds (1 hour).

.NOTES
This function requires the $script:TokenAcquiredTime and $script:ExpiresIn variables to be set before calling the function.
#>


function Get-TokenExpiry {
    [CmdletBinding()]
    [OutputType([DateTime])]
    param (
        [Parameter(Mandatory = $false)]
        [int64]$ExpiresIn = $script:ExpiresIn
    )
    if ($script:ExpiresIn -eq $null) {
        return
    } else {
        $Script:ExpiryDateTime = $script:TokenAcquiredTime.AddSeconds($script:ExpiresIn)
        Write-Verbose "Calculated token expiry as $Script:ExpiryDateTime"
    }
}
#EndRegion './Private/Get-TokenExpiry.ps1' 37
#Region './Private/Helpers/Update-KeyVaultSecret.ps1' -1

<#
.SYNOPSIS
Updates a secret in Azure Key Vault.

.DESCRIPTION
The Update-KeyVaultSecret function is used to update a secret in Azure Key Vault. It sets the Azure subscription, and then updates the specified secret in the specified Key Vault with a new secret value.

.PARAMETER SecretName
The name of the secret to be updated.

.PARAMETER SecretValue
The new value for the secret.

.PARAMETER AzureSubscriptionId
The ID of the Azure subscription to use.

.PARAMETER keyVaultName
The name of the Key Vault where the secret is stored.

.EXAMPLE
Update-KeyVaultSecret -SecretName "MySecret" -SecretValue "NewSecretValue" -AzureSubscriptionId "12345678-1234-1234-1234-1234567890AB" -keyVaultName "MyKeyVault"

This example updates the secret named "MySecret" in the Key Vault named "MyKeyVault" with the value "NewSecretValue" using the Azure subscription with the ID "12345678-1234-1234-1234-1234567890AB".

#>


function Update-KeyVaultSecret {
    param (
        [string]$SecretName,
        [string]$SecretValue,
        [guid]$AzureSubscriptionId,
        [string]$keyVaultName
    )
    Write-Verbose "Updating KeyVault with new secret"
    Write-Verbose "Setting Azure Subscription"
    Set-AzContext -Subscription $AzureSubscriptionId | Out-Null
    Write-Verbose "Setting KeyVault Secret"
    try {
        $null = Set-AzKeyVaultSecret -VaultName $keyVaultName -Name $SecretName -SecretValue (ConvertTo-SecureString $SecretValue -AsPlainText -Force)
    } catch {
        Write-Error "Failed to update KeyVault secret"
    }
}
#EndRegion './Private/Helpers/Update-KeyVaultSecret.ps1' 44
#Region './Private/Invoke-PreFlightCheck.ps1' -1

<#
.SYNOPSIS
    Performs pre-flight checks before executing the main logic of the script.

.DESCRIPTION
    The Invoke-PreFlightCheck function is responsible for performing pre-flight checks before executing the main logic of the script. It checks if the required information, such as the refresh token and KeyVault name, is available. If any of the required information is missing, an exception is thrown. It also checks if the token has expired or not found, and connects to the API if necessary.

.PARAMETER None
    This function does not accept any parameters.

.EXAMPLE
    Invoke-PreFlightCheck
    
    This example Performs pre-flight checks before executing the main logic of the script.
#>


function Invoke-PreFlightCheck {
    [CmdletBinding()]
    param ()

    if ($null -eq $Script:refreshToken -and $null -eq $Script:KeyVaultName) {
        if ($null -eq $Script:refreshToken) {
            throw "RefreshToken information not found"
            break
        } else {
            throw "KeyVault information not found"
            break
        }
    }

    Get-TokenExpiry

    if ((-not $Script:ExpiryDateTime) -or ($script:ExpiryDateTime -lt (Get-Date))) {
        write-Verbose "Token expired or not found. Connecting to API"

        Connect-API
    }
}
#EndRegion './Private/Invoke-PreFlightCheck.ps1' 39
#Region './Public/Access-Authentication/Get-AccessTokenExpiry.ps1' -1

<#
.SYNOPSIS
Retrieves the expiry time of an access token.

.DESCRIPTION
The Get-AccessTokenExpiry function is used to retrieve the expiry time of an access token by making a request to the "/oauth/validateAccess" endpoint.

.PARAMETER None
This function does not have any parameters.

.EXAMPLE
Get-AccessTokenExpiry

This example gets the expiry time of an access token.

#>


function Get-AccessTokenExpiry {
    [CmdletBinding()]
    param (
    )

    $Endpoint = "/oauth/validateAccess"

    Invoke-TDRestMethod -Endpoint $Endpoint
}
#EndRegion './Public/Access-Authentication/Get-AccessTokenExpiry.ps1' 27
#Region './Public/Catalog/Get-Categories.ps1' -1

<#
.SYNOPSIS
Retrieves the categories of products from the specified account.

.DESCRIPTION
The Get-Categories function retrieves the categories of products from the specified account using the TDRestMethod cmdlet.

.PARAMETER None
This function does not have any parameters.

.EXAMPLE
Get-Categories

This example retrieves the categories of products from the current account.

#>
 
function Get-Categories {
    [CmdletBinding()]
    param (
    )

    $Endpoint = "/api/v3/accounts/$script:AccountID/products/categories"

    Invoke-TDRestMethod -Endpoint $Endpoint
}
#EndRegion './Public/Catalog/Get-Categories.ps1' 26
#Region './Public/Catalog/Get-Charges.ps1' -1

<#
.SYNOPSIS
Retrieves charges for a specific account.

.DESCRIPTION
The Get-Charges function retrieves charges for a specific account by making a REST API call to the endpoint "/api/v3/accounts/{AccountID}/products/charges".

.PARAMETER None
This function does not have any parameters.

.EXAMPLE
Get-Charges

This example retrieves charges for the current account.

#>


function Get-Charges {
    [CmdletBinding()]
    param (
    )

    $Endpoint = "/api/v3/accounts/$script:AccountID/products/charges"

    Invoke-TDRestMethod -Endpoint $Endpoint
}
#EndRegion './Public/Catalog/Get-Charges.ps1' 27
#Region './Public/Catalog/Get-Product.ps1' -1

<#
.SYNOPSIS
    Retrieves product information based on the provided parameters.

.DESCRIPTION
    The Get-Product function retrieves product information from the specified API endpoint. It allows you to specify various parameters to customize the request.

.PARAMETER ProductID
    Specifies the ID of the product to retrieve. This parameter is mandatory.

.PARAMETER Language
    Specifies the language for the product information. This parameter is optional.

.PARAMETER PriceBookCustomerID
    Specifies the customer ID for the price book. This parameter is optional.

.PARAMETER ProductVersion
    Specifies the version of the product. This parameter is optional.

.PARAMETER ClientRole
    Specifies the client role for the product. This parameter is optional.

.PARAMETER ExcludePricing
    Specifies whether to exclude pricing information from the product response. This parameter is optional.

.PARAMETER ExcludeMarketing
    Specifies whether to exclude marketing information from the product response. This parameter is optional.

.PARAMETER ExcludeDefinition
    Specifies whether to exclude definition information from the product response. This parameter is optional.

.PARAMETER ExcludeVersionHistory
    Specifies whether to exclude version history information from the product response. This parameter is optional.

.PARAMETER ExcludeDeployment
    Specifies whether to exclude deployment information from the product response. This parameter is optional.

.EXAMPLE
    Get-Product -ProductID "12345" -ExcludePricing $true
    
    This example retrieves the product information for the product with ID "12345" excluding pricing information.

#>


function Get-Product {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]$ProductID,
        [Parameter(Mandatory = $false)]
        [string]$language,
        [Parameter(Mandatory = $false)]
        [string]$PriceBookCustomerID,
        [Parameter(Mandatory = $false)]
        [string]$productVersion,
        [Parameter(Mandatory = $false)]
        [string]$clientRole,
        [Parameter(Mandatory = $false)]
        [bool]$excludePricing,
        [Parameter(Mandatory = $false)]
        [bool]$excludeMarketing,
        [Parameter(Mandatory = $false)]
        [bool]$excludeDefinition,
        [Parameter(Mandatory = $false)]
        [bool]$excludeVersionHistory,
        [Parameter(Mandatory = $false)]
        [bool]$excludeDeployment
    )

    $Endpoint = "/api/v3/accounts/$script:AccountID/products/$ProductID"

    $Params = @{
        language                    = $language
        priceBookCustomerId         = $PriceBookCustomerID
        productVersion              = $productVersion
        clientRole                  = $clientRole
    }

    if ($excludePricing) {
        $Params.Add("excludeFilter.excludePricing", $excludePricing)
    }
    if ($excludeMarketing) {
        $Params.Add("excludeFilter.excludeMarketing", $excludeMarketing)
    }
    if ($excludeDefinition) {
        $Params.Add("excludeFilter.excludeDefinition", $excludeDefinition)
    }
    if ($excludeVersionHistory) {
        $Params.Add("excludeFilter.excludeVersionHistory", $excludeVersionHistory)
    }
    if ($excludeDeployment) {
        $Params.Add("excludeFilter.excludeDeployment", $excludeDeployment)
    }

    Invoke-TDRestMethod -Endpoint $Endpoint -params $Params
}
#EndRegion './Public/Catalog/Get-Product.ps1' 97
#Region './Public/Catalog/Get-Products.ps1' -1

<#
.SYNOPSIS
Retrieves products based on specified filters.

.DESCRIPTION
The Get-Products function retrieves products from the ION API based on the specified filters. It allows filtering by various parameters such as name, SKU external ID, addon external ID, SKU ID, addon ID, SKU display name, addon display name, and category.

.PARAMETER PageSize
Specifies the number of products to retrieve per page. The default value is 1000.

.PARAMETER Name
Specifies the name of the product to filter by.

.PARAMETER SKUExternalID
Specifies the SKU external ID of the product to filter by.

.PARAMETER AddonExternalID
Specifies the addon external ID of the product to filter by.

.PARAMETER SkuID
Specifies the SKU ID of the product to filter by.

.PARAMETER AddonID
Specifies the addon ID of the product to filter by.

.PARAMETER SkuDisplayName
Specifies the SKU display name of the product to filter by.

.PARAMETER AddonDisplayName
Specifies the addon display name of the product to filter by.

.PARAMETER Category
Specifies the category of the product to filter by.

.EXAMPLE
Get-Products -Name "Widget" -Category "Electronics"
Retrieves products with the name "Widget" and category "Electronics".

.EXAMPLE
Get-Products -SKUExternalID "SKU123"

This example retrieves products with the SKU external ID "SKU123".

#>


function Get-Products {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $false)]
        [string]$PageSize = 1000,
        [Parameter(Mandatory = $false)]
        [string]$Name,
        [Parameter(Mandatory = $false)]
        [string]$SKUExternalID,
        [Parameter(Mandatory = $false)]
        [string]$AddonExternalID,
        [Parameter(Mandatory = $false)]
        [string]$SkuID,
        [Parameter(Mandatory = $false)]
        [string]$AddonID,
        [Parameter(Mandatory = $false)]
        [string]$SkuDisplayName,
        [Parameter(Mandatory = $false)]
        [string]$AddonDisplayName,
        [Parameter(Mandatory = $false)]
        [string]$Category
    )

    $Endpoint = "/api/v3/accounts/$script:AccountID/products"

    $Params = @{
        pageSize                    = $PageSize
        'filter.name'               = $Name
        'filter.skuExternalId'      = $SKUExternalID
        'filter.addonExternalId'    = $AddonExternalID
        'filter.skuId'              = $SkuID
        'filter.addonId'            = $AddonID
        'filter.skuDisplayName'     = $SkuDisplayName
        'filter.addonDisplayName'   = $AddonDisplayName
        #'filter.category' = $Category - This does not work
    }

    Invoke-TDRestMethod -Endpoint $Endpoint -params $Params
}
#EndRegion './Public/Catalog/Get-Products.ps1' 85
#Region './Public/Catalog/Get-Verticals.ps1' -1

<#
.SYNOPSIS
Retrieves the verticals from the API.

.DESCRIPTION
The Get-Verticals function retrieves the verticals from the API by making a REST API call to the specified endpoint. It does not require any parameters.

.PARAMETER None
This function does not have any parameters.

.EXAMPLE
Get-Verticals

This example demonstrates how to use the Get-Verticals function to retrieve the verticals from the API.

#>


function Get-Verticals {
    [CmdletBinding()]
    param (
    )

    $Endpoint = "/api/v3/accounts/$script:AccountID/products/verticals"

    Invoke-TDRestMethod -Endpoint $Endpoint
}
#EndRegion './Public/Catalog/Get-Verticals.ps1' 27
#Region './Public/Catalog/Set-Product.ps1' -1

<#
.SYNOPSIS
Sets the status of a product.

.DESCRIPTION
The Set-Product function is used to set the status of a product in the catalog. It sends a POST request to the specified API endpoint to update the product status.

.PARAMETER ProductID
The ID of the product to be updated.

.PARAMETER Status
The status to set for the product. Valid values are 'enable' and 'disable'.

.EXAMPLE
Set-Product -ProductID "12345" -Status "enable"
Sets the status of the product with ID "12345" to "enable".

.EXAMPLE
Set-Product -ProductID "67890" -Status "disable"
Sets the status of the product with ID "67890" to "disable".
#>


function Set-Product {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]$ProductID,
        [Parameter(Mandatory = $true)]
        [ValidateSet('enable', 'disable')]
        [string]$Status
    )

    $Endpoint = "/api/v3/accounts/$script:AccountID/products/$($ProductID):$($Status)"

    Invoke-TDRestMethod -Endpoint $Endpoint -Method POST
}
#EndRegion './Public/Catalog/Set-Product.ps1' 37
#Region './Public/Customer/Add-Customer.ps1' -1

<#
.SYNOPSIS
Adds a new customer to ION.

.DESCRIPTION
The Add-Customer function adds a new customer to ION by constructing a request body and sending a POST request to the specified endpoint. It requires parameters such as customer organization, address details, customer name, email, language code, and more.

.PARAMETER customerOrganization
The name of the customer organization.

.PARAMETER street
The street address of the customer.

.PARAMETER suite
(Optional) The suite or apartment number of the customer.

.PARAMETER city
The city of the customer.

.PARAMETER state
The state or province of the customer.

.PARAMETER zip
The ZIP or postal code of the customer.

.PARAMETER country
The country of the customer, formatted as an ISO 3166-1 alpha-2 code (e.g., "US" for United States or "GB" for the United Kindom).

.PARAMETER customerName
The full name of the customer.

.PARAMETER customerEmail
The email address of the customer.

.PARAMETER customerTitle
(Optional) The title of the customer (e.g., Mr., Mrs., Dr.).

.PARAMETER customerPhone
(Optional) The phone number of the customer.

.PARAMETER alternateEmail
(Optional) An alternate email address for the customer.

.PARAMETER customerDomain
(Optional) The domain associated with the customer.

.PARAMETER primaryContactFirstName
(Optional) The first name of the primary contact person.

.PARAMETER primaryContactLastName
(Optional) The last name of the primary contact person.

.PARAMETER languageCode
The language code for the customer, formatted as an ISO 639-1 code (e.g., "EN" for English).

.EXAMPLE
Add-Customer -customerOrganization "ABC Corp" -street "123 Main St" -city "New York" -state "NY" -zip "10001" -country "US" -customerName "John Doe" -customerEmail "johndoe@example.com" -languageCode "EN"

This example adds a new customer with the specified details.

#>


function Add-Customer {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]$customerOrganization,
        [Parameter(Mandatory = $true)]
        [string]$street,
        [Parameter(Mandatory = $false)]
        [string]$suite,
        [Parameter(Mandatory = $true)]
        [string]$city,
        [Parameter(Mandatory = $true)]
        [string]$state,
        [Parameter(Mandatory = $true)]
        [string]$zip,
        [Parameter(Mandatory = $true)]
        [string]$country,
        [Parameter(Mandatory = $true)]
        [string]$customerName,
        [Parameter(Mandatory = $true)]
        [string]$customerEmail,
        [Parameter(Mandatory = $false)]
        [string]$customerTitle,
        [Parameter(Mandatory = $false)]
        [string]$customerPhone,
        [Parameter(Mandatory = $false)]
        [string]$alternateEmail,
        [Parameter(Mandatory = $false)]
        [string]$customerDomain,
        [Parameter(Mandatory = $false)]
        [string]$primaryContactFirstName,
        [Parameter(Mandatory = $false)]
        [string]$primaryContactLastName,
        [Parameter(Mandatory = $false)]
        [string]$languageCode = "EN"
    )

    $Endpoint = "/api/v3/accounts/$script:AccountID/customers"

    $body = @{
        customerOrganization = $customerOrganization
        customerAddress = @{
            street = $street
            city = $city
            state = $state
            zip = $zip
            country = $country
        }
        customerName = $customerName
        customerEmail = $customerEmail
        languageCode = $languageCode
    }

    foreach ($key in $PSBoundParameters.Keys) {
        if ($key -notin @('customerOrganization', 'street', 'city', 'state', 'zip', 'country', 'customerName', 'customerEmail', 'languageCode')) {
            if ($key -eq 'suite') {
                $body.customerAddress.suite = $PSBoundParameters[$key]
            } else {
                $body[$key] = $PSBoundParameters[$key]
            }
        }
    }

    Invoke-TDRestMethod -Endpoint $Endpoint -Body $body -Method POST
}
#EndRegion './Public/Customer/Add-Customer.ps1' 128
#Region './Public/Customer/Get-AllCustomers.ps1' -1

<#
.SYNOPSIS
Retrieves a list of customers based on specified filters.

.DESCRIPTION
The Get-AllCustomers function retrieves a list of customers from the specified API endpoint. It allows you to filter the results based on various parameters such as page size, customer email, customer domain, customer status, and customer name.

.PARAMETER PageSize
Specifies the maximum number of customers to retrieve per page. The default value is 1000.

.PARAMETER CustomerEmail
Specifies the email address of the customer to filter the results. This parameter is optional.

.PARAMETER CustomerDomain
Specifies the domain of the customer to filter the results. This parameter is optional.

.PARAMETER CustomerStatus
Specifies the status of the customer to filter the results. Valid values are "ACTIVE", "INACTIVE", and "CUSTOMER_STATUS_UNSPECIFIED". The default value is "CUSTOMER_STATUS_UNSPECIFIED".

.PARAMETER CustomerName
Specifies the name of the customer to filter the results. This parameter is optional.

.EXAMPLE
Get-AllCustomers -PageSize 500 -CustomerEmail "example@example.com" -CustomerStatus "ACTIVE"

This example retrieves a list of active customers with a page size of 500 and filters the results based on the customer email address.

#>


function Get-AllCustomers {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $false)]
        [string]$PageSize = 1000,
        [Parameter(Mandatory = $false)]
        [string]$CustomerEmail,
        [Parameter(Mandatory = $false)]
        [string]$CustomerDomain,
        [Parameter(Mandatory = $false)]
        [ValidateSet(
            "ACTIVE",
            "INACTIVE",
            "CUSTOMER_STATUS_UNSPECIFIED")]
        [string]$CustomerStatus = "CUSTOMER_STATUS_UNSPECIFIED",
        [Parameter(Mandatory = $false)]
        [string]$CustomerName
    )

    $Endpoint = "/api/v3/accounts/$script:AccountID/customers"

    $Params = @{
        pageSize                  = $PageSize
        'filter.customerEmail'    = $CustomerEmail
        'filter.customerDomain'   = $CustomerDomain
        'filter.customerStatus'   = $CustomerStatus
        'filter.customerName'     = $CustomerName
    }

    Invoke-TDRestMethod -Endpoint $Endpoint -params $Params
}
#EndRegion './Public/Customer/Get-AllCustomers.ps1' 61
#Region './Public/Customer/Get-Customer.ps1' -1

<#
.SYNOPSIS
Retrieves customer information based on the provided CustomerID.

.DESCRIPTION
The Get-Customer function retrieves customer information from an API endpoint based on the provided CustomerID. It requires the CustomerID parameter to be specified.

.PARAMETER CustomerID
Specifies the ID of the customer for which to retrieve information.

.EXAMPLE
Get-Customer -CustomerID "12345"

This example retrieves customer information for the customer with ID "12345".

#>

function Get-Customer {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]$CustomerID
    )

    $Endpoint = "/api/v3/accounts/$script:AccountID/customers/$CustomerID"

    Invoke-TDRestMethod -Endpoint $Endpoint
}
#EndRegion './Public/Customer/Get-Customer.ps1' 28
#Region './Public/Customer/Get-CustomerCloudProfiles.ps1' -1

<#
.SYNOPSIS
Retrieves the cloud profiles for a specific customer.

.DESCRIPTION
The Get-CustomerCloudProfiles function retrieves the cloud profiles associated with a specific customer. It makes use of the Invoke-TDRestMethod function to send a request to the appropriate API endpoint.

.PARAMETER CustomerID
The ID of the customer for which to retrieve the cloud profiles.

.PARAMETER ProviderID
(Optional) The ID of the provider for which to filter the cloud profiles.

.EXAMPLE
Get-CustomerCloudProfiles -CustomerID "12345"

This example retrieves all cloud profiles for the customer with ID "12345".

.EXAMPLE
Get-CustomerCloudProfiles -CustomerID "12345" -ProviderID "67890"

This example retrieves the cloud profiles for the customer with ID "12345" that are associated with the provider with ID "67890".

#>

function Get-CustomerCloudProfiles {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]$CustomerID,
        [Parameter(Mandatory = $false)]
        [string]$ProviderID
    )

    $Endpoint = "/api/v3/accounts/$script:AccountID/customers/$CustomerID/cloudProfiles"

    $Params = @{
        providerId      = $ProviderID
    }

    Invoke-TDRestMethod -Endpoint $Endpoint -params $Params
}
#EndRegion './Public/Customer/Get-CustomerCloudProfiles.ps1' 42
#Region './Public/Customer/Set-Customer.ps1' -1

<#
.SYNOPSIS
Updates the details of a customer.

.DESCRIPTION
The Set-Customer function is used to update the details of a customer in the system. It retrieves the existing customer details using the Get-Customer function and then updates the specified properties with the provided values.

.PARAMETER CustomerID
The unique identifier of the customer.

.PARAMETER customerOrganization
The organization name of the customer.

.PARAMETER street
The street address of the customer.

.PARAMETER suite
The suite or apartment number of the customer.

.PARAMETER city
The city of the customer.

.PARAMETER state
The state or province of the customer.

.PARAMETER zip
The postal or zip code of the customer.

.PARAMETER country
The country of the customer, formatted as an ISO 3166-1 alpha-2 code (e.g., "US" for United States or "GB" for the United Kindom).

.PARAMETER customerName
The name of the customer.

.PARAMETER customerEmail
The email address of the customer.

.PARAMETER customerTitle
The title or position of the customer.

.PARAMETER customerPhone
The phone number of the customer.

.PARAMETER alternateEmail
An alternate email address for the customer.

.PARAMETER customerDomain
The domain associated with the customer.

.PARAMETER primaryContactFirstName
The first name of the primary contact person for the customer.

.PARAMETER primaryContactLastName
The last name of the primary contact person for the customer.

.PARAMETER languageCode
The language code for the customer, formatted as an ISO 639-1 code (e.g., "EN" for English)

.EXAMPLE
Set-Customer -CustomerID "12345" -customerName "John Doe" -customerEmail "john.doe@example.com" -languageCode "en-US"
Updates the name and email address of the customer with ID "12345" to "John Doe" and "john.doe@example.com" respectively, and sets the language code to "en-US".

.NOTES
This function requires the Get-Customer and Invoke-TDRestMethod functions to be available in the current session.
#>


function Set-Customer {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]$CustomerID,
        [Parameter(Mandatory = $false)]
        [string]$customerOrganization,
        [Parameter(Mandatory = $false)]
        [string]$street,
        [Parameter(Mandatory = $false)]
        [string]$suite,
        [Parameter(Mandatory = $false)]
        [string]$city,
        [Parameter(Mandatory = $false)]
        [string]$state,
        [Parameter(Mandatory = $false)]
        [string]$zip,
        [Parameter(Mandatory = $false)]
        [string]$country,
        [Parameter(Mandatory = $false)]
        [string]$customerName,
        [Parameter(Mandatory = $false)]
        [string]$customerEmail,
        [Parameter(Mandatory = $false)]
        [string]$customerTitle,
        [Parameter(Mandatory = $false)]
        [string]$customerPhone,
        [Parameter(Mandatory = $false)]
        [string]$alternateEmail,
        [Parameter(Mandatory = $false)]
        [string]$customerDomain,
        [Parameter(Mandatory = $false)]
        [string]$primaryContactFirstName,
        [Parameter(Mandatory = $false)]
        [string]$primaryContactLastName,
        [Parameter(Mandatory = $true)]
        [string]$languageCode
    )

    $ExistingDetails = Get-Customer -CustomerID $CustomerID

    $Endpoint = "/api/v3/accounts/$script:AccountID/customers/$CustomerID"

    $body = @{
        customerOrganization = $customerOrganization ? $customerOrganization : $ExistingDetails.customerOrganization
        customerAddress = @{
            street = $street ? $street : $ExistingDetails.customerAddress.street
            city = $city ? $city : $ExistingDetails.customerAddress.city
            state = $state ? $state : $ExistingDetails.customerAddress.state
            zip = $zip ? $zip : $ExistingDetails.customerAddress.zip
            country = $country ? $country : $ExistingDetails.customerAddress.country
        }
        customerName = $customerName ? $customerName : $ExistingDetails.customerName
        customerEmail = $customerEmail ? $customerEmail : $ExistingDetails.customerEmail
        languageCode = $languageCode ? $languageCode : $ExistingDetails.languageCode
    }

    foreach ($key in $PSBoundParameters.Keys) {
        if ($key -notin @('customerOrganization', 'street', 'city', 'state', 'zip', 'country', 'customerName', 'customerEmail', 'languageCode', 'Verbose')) {
            if ($key -eq 'suite') {
                $body.customerAddress.suite = $PSBoundParameters[$key] ? $PSBoundParameters[$key] : $ExistingDetails.customerAddress.suite
            } else {
                $body[$key] = $PSBoundParameters[$key] ? $PSBoundParameters[$key] : $ExistingDetails.$key
            }
        }
    }

    Invoke-TDRestMethod -Endpoint $Endpoint -Body $body -Method PUT
}
#EndRegion './Public/Customer/Set-Customer.ps1' 136
#Region './Public/Invoke-TDRestMethod.ps1' -1

<#
.SYNOPSIS
    Invokes a REST method using the specified parameters.

.DESCRIPTION
    The Invoke-TDRestMethod function is used to send HTTP requests to a RESTful API endpoint. It supports various HTTP methods, such as GET, POST, PUT, and DELETE. The function assembles the request parameters, including the endpoint URL, query parameters, request body, and headers, and then sends the request using the Invoke-RestMethod cmdlet.

.PARAMETER Endpoint
    The URL of the RESTful API endpoint.

.PARAMETER Params
    A hashtable containing the query parameters to be included in the request URL. The keys represent the parameter names, and the values represent the parameter values.

.PARAMETER Method
    The HTTP method to be used for the request. The default value is 'GET'.

.PARAMETER Body
    A hashtable representing the request body. The hashtable will be converted to JSON format before sending the request.

.PARAMETER ContentType
    The content type of the request body. The default value is 'application/json'.

.EXAMPLE
    Invoke-TDRestMethod -Endpoint '"/api/v3/accounts/$script:AccountID/customers' -Method 'GET' -Params @{ pagesize = 1000 }

    This example sends a GET request to the '/api/v3/accounts/$script:AccountID/customers' endpoint with query parameters 'pagesize=1000'.

.OUTPUTS
    The function returns the response received from the RESTful API endpoint.

.NOTES
    This function requires the Invoke-PreFlightCheck function to be defined in the same script or module. The Invoke-PreFlightCheck function can be used to perform any necessary pre-flight checks before sending the request.

#>

function Invoke-TDRestMethod {
    param (
        [string]$Endpoint,
        [hashtable]$Params = @{},
        [string]$Method = 'GET',
        [hashtable]$Body = @{},
        [string]$ContentType = 'application/json'
    )

    try {
        Invoke-PreFlightCheck
    } catch {
        Write-Error "$($_.Exception.Message)"
        break
    }

    # Assemble parameters
    $ParamCollection = [System.Web.HttpUtility]::ParseQueryString([String]::Empty)

    $Params.GetEnumerator() | ForEach-Object {
        $ParamCollection.Add($_.Key, $_.Value)
    }
    $Request = $ParamCollection.ToString()

    $UriBuilder = [System.UriBuilder]('{0}{1}' -f $script:baseUrl, $Endpoint)
    $UriBuilder.Query = $Request

    $BodyJson = $Body | ConvertTo-Json -Depth 10

    $Request = @{
        Uri         = $UriBuilder.ToString()
        Method      = $Method
        Headers     = $script:AuthHeader
        ContentType = $ContentType
    }

    if ($Body.Count -gt 0) {
        $Request.Add('Body', $BodyJson)
    }
    
    Write-Verbose "$Method [ $($UriBuilder.ToString()) ]"
    
    $response = Invoke-RestMethod @Request
    return $response

}
#EndRegion './Public/Invoke-TDRestMethod.ps1' 81
#Region './Public/Order/Get-CustomerOrders.ps1' -1

<#
.SYNOPSIS
Retrieves customer orders from the API.

.DESCRIPTION
The Get-CustomerOrders function retrieves customer orders from the API based on the provided parameters. It sends a request to the specified endpoint and returns the response.

.PARAMETER CustomerID
The ID of the customer for which to retrieve orders. This parameter is mandatory.

.PARAMETER SubscriptionStatus
The status of the subscriptions to filter the orders. This parameter is optional.

.PARAMETER PageSize
The maximum number of orders to retrieve per page. The default value is 1000.

.EXAMPLE
Get-CustomerOrders -CustomerID "12345" -SubscriptionStatus "Active" -PageSize 500

This example retrieves active orders for the customer with ID "12345" and sets the page size to 500.

#>


function Get-CustomerOrders {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]$CustomerID,
        [Parameter(Mandatory = $false)]
        [string]$SubscriptionStatus,
        [Parameter(Mandatory = $false)]
        [int]$PageSize = 1000

    )

    $Endpoint = "/api/v3/accounts/$script:AccountID/customers/$CustomerID/orders"

    $Params = @{
        pageSize                            = $PageSize
        status                              = $SubscriptionStatus
    }

    Invoke-TDRestMethod -Endpoint $Endpoint -params $Params

}
#EndRegion './Public/Order/Get-CustomerOrders.ps1' 46
#Region './Public/Order/New-Order.ps1' -1

<#
.SYNOPSIS
Creates a new order for a customer.

.DESCRIPTION
The New-Order function creates a new order for a customer in the system. It takes various parameters such as customer ID, product ID, SKU ID, plan ID, subscription ID, quantity, reference ID, display name, domain name, auto-renew setting, and optional parameters for end customer PO, reseller PO, agreement details, and custom term end date.

.PARAMETER customerID
The ID of the customer for whom the order is being created.

.PARAMETER ProductId
The ID of the product associated with the order.

.PARAMETER SkuID
The ID of the SKU associated with the order.

.PARAMETER PlanID
The ID of the plan associated with the order.

.PARAMETER SubscriptionID
The ID of the subscription associated with the order.

.PARAMETER Quantity
The quantity of the product being ordered.

.PARAMETER ReferenceID
A unique reference ID for the order.

.PARAMETER DisplayName
The display name of the order.

.PARAMETER DomainName
The domain name associated with the order.

.PARAMETER AutoRenew
The auto-renew setting for the order. Valid values are "auto-off" and "auto-on".

.PARAMETER endcustomerPO
(Optional) The end customer purchase order number.

.PARAMETER ResellerPO
(Optional) The reseller purchase order number.

.PARAMETER agreementDateAgreed
(Optional) The date when the agreement was agreed.

.PARAMETER agreementUserId
(Optional) The user ID associated with the agreement.

.PARAMETER agreementEmail
(Optional) The email address associated with the agreement.

.PARAMETER agreementFirstName
(Optional) The first name associated with the agreement.

.PARAMETER agreementLastName
(Optional) The last name associated with the agreement.

.PARAMETER agreementPhoneNumber
(Optional) The phone number associated with the agreement.

.PARAMETER customTermEndDate
(Optional) The custom term end date for the order.

.EXAMPLE
New-Order -customerID "12345" -ProductId "67890" -SkuID "SKU123" -PlanID "PLAN123" -SubscriptionID "SUB123" -Quantity 1 -ReferenceID "REF123" -DisplayName "Order 1" -DomainName "example.com" -AutoRenew "auto-on"

This example creates a new order for a customer with the specified parameters.

#>

function New-Order {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]$customerID,
        [Parameter(Mandatory = $true)]
        [string]$ProductId,
        [Parameter(Mandatory = $true)]
        [string]$SkuID,
        [Parameter(Mandatory = $true)]
        [string]$PlanID,
        [Parameter(Mandatory = $true)]
        [string]$SubscriptionID,
        [Parameter(Mandatory = $true)]
        [int]$Quantity,
        [Parameter(Mandatory = $true)]
        [string]$ReferenceID,
        [Parameter(Mandatory = $true)]
        [string]$DisplayName,
        [Parameter(Mandatory = $true)]
        [string]$DomainName,
        [Parameter(Mandatory = $true)]
        [validateset(
            "auto-off",
            "auto-on"
            )]
        [string]$AutoRenew,
        [Parameter(Mandatory = $false)]
        [string]$endcustomerPO,
        [Parameter(Mandatory = $false)]
        [string]$ResellerPO,
        [Parameter(Mandatory = $false)]
        [string]$agreementDateAgreed,
        [Parameter(Mandatory = $false)]
        [string]$agreementUserId,
        [Parameter(Mandatory = $false)]
        [string]$agreementEmail,
        [Parameter(Mandatory = $false)]
        [string]$agreementFirstName,
        [Parameter(Mandatory = $false)]
        [string]$agreementLastName,
        [Parameter(Mandatory = $false)]
        [string]$agreementPhoneNumber,
        [Parameter(Mandatory = $false)]
        [string]$customTermEndDate
    )

    $Endpoint = "/api/v3/accounts/$script:AccountID/customers/$CustomerID/orders"

    $body = @{
        referenceId = $ReferenceID
        displayName = $DisplayName
        orderItems = @(
            @{
                referenceId = $ReferenceID
                action = "CREATE"
                resourceId = $SubscriptionID
                productId = $ProductID
                skuId = $SkuID
                planId = $PlanID
                quantity = $Quantity
                attributes = @(
                    @{
                        name = "domainName"
                        value = $DomainName
                    }
                    @{
                        name = "renewalSetting"
                        value = $AutoRenew
                    }
                )
            }
        )
    }

    if ($endcustomerPO) {
        $body.orderItems[0].endCustomerPO = $endcustomerPO
    }
    if ($ResellerPO) {
        $body.orderItems[0].resellerPO = $ResellerPO
    }

    foreach ($key in $PSBoundParameters.Keys) {
        if ($key -notin @('customerID', 'ProductId', 'SkuID', 'PlanID', 'SubscriptionID', 'Quantity', 'ReferenceID', 'DisplayName', 'DomainName', 'endcustomerPO', 'ResellerPO', 'Verbose')) {
            if ($PSBoundParameters[$key]) {
                $body.orderItems[0].attributes += @{
                    name = $key
                    value = $PSBoundParameters[$key]
                }
            }
        }
    }

    Invoke-TDRestMethod -Endpoint $Endpoint -Body $body -Method 'POST'
}
#EndRegion './Public/Order/New-Order.ps1' 166
#Region './Public/Order/Set-Subscription.ps1' -1

<#
.SYNOPSIS
Sets the subscription details for a customer.

.DESCRIPTION
The Set-Subscription function is used to set the subscription details for a customer. It creates or updates a subscription order with the specified parameters.

.PARAMETER customerID
The ID of the customer for whom the subscription is being set.

.PARAMETER ProductId
The ID of the product associated with the subscription.

.PARAMETER SkuID
The ID of the SKU associated with the subscription.

.PARAMETER PlanID
The ID of the plan associated with the subscription.

.PARAMETER SubscriptionID
The ID of the subscription.

.PARAMETER Quantity
The quantity of the subscription.

.PARAMETER SubscriptionName
The name of the subscription.

.PARAMETER AutoRenew
(Optional) Specifies the auto-renewal setting for the subscription. Valid values are "auto-off" and "auto-on".

.PARAMETER StatusUpdate
(Optional) Specifies the status update for the subscription. Valid values are "active", "suspended", and "deleted".

.EXAMPLE
Set-Subscription -customerID "12345" -ProductId "Microsoft365EandFNCE-uknce" -SkuID "USCFQ7TTC0LH180001" -PlanID "Microsoft-365-Business-Basic" -SubscriptionID "b9bd9b30-6ae3-4d15-c438-f3cde89888ea" -Quantity 1 -AutoRenew "auto-on" -SubscriptionName "Microsoft 365 Business Basic"

This example sets the renewal settings for a subscription with the specified parameters.

.EXAMPLE
Set-Subscription -customerID "12345" -ProductId "Microsoft365EandFNCE-uknce" -SkuID "USCFQ7TTC0LH180001" -PlanID "Microsoft-365-Business-Basic" -SubscriptionID "b9bd9b30-6ae3-4d15-c438-f3cde89888ea" -Quantity 1 -SubscriptionName "Microsoft 365 Business Basic" -StatusUpdate "suspended"

This example sets the status for a subscription to Paused.

.EXAMPLE
Set-Subscription -customerID "12345" -ProductId "Microsoft365EandFNCE-uknce" -SkuID "USCFQ7TTC0LH180001" -PlanID "Microsoft-365-Business-Basic" -SubscriptionID "b9bd9b30-6ae3-4d15-c438-f3cde89888ea" -Quantity 1 -SubscriptionName "Microsoft 365 Business Basic" -StatusUpdate "deleted"

This example sets the status for a subscription to Deleted/Cancelled.

#>


function Set-Subscription {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]$customerID,
        [Parameter(Mandatory = $true)]
        [string]$ProductId,
        [Parameter(Mandatory = $true)]
        [string]$SkuID,
        [Parameter(Mandatory = $true)]
        [string]$PlanID,
        [Parameter(Mandatory = $true)]
        [string]$SubscriptionID,
        [Parameter(Mandatory = $true)]
        [int]$Quantity,
        [Parameter(Mandatory = $true)]
        [string]$SubscriptionName,
        [Parameter(Mandatory = $false)]
        [validateset(
            "auto-off",
            "auto-on"
            )]
        [string]$AutoRenew,
        [Parameter(Mandatory = $false)]
        [ValidateSet(
            "active",
            "suspended",
            "deleted"
        )]
        [string]$StatusUpdate
    )

    $Endpoint = "/api/v3/accounts/$script:AccountID/customers/$CustomerID/orders"

    $Body = @{
        displayName = $SubscriptionName
        orderItems = @(
            @{
                productId = $ProductId
                skuId = $SkuID
                planId = $PlanID
                action = "UPDATE"
                quantity = $Quantity
                resourceId = $SubscriptionID
                attributes = @(
                    @{
                        name = "operations"
                        value = "updateSubscription"
                    }
                )
            }
        )
    }

    if ($AutoRenew) {
        $Body.orderItems[0].attributes += @{
            name = "renewalSetting"
            value = $AutoRenew
        }
    }

    if ($StatusUpdate) {
        $Body.orderItems[0].attributes += @{
            name = "statusUpdate"
            value = $StatusUpdate
        }
    }

    Invoke-TDRestMethod -Endpoint $Endpoint -Body $Body -Method 'POST'
}
#EndRegion './Public/Order/Set-Subscription.ps1' 122
#Region './Public/Provisioning-Template/Get-ProvisioningTemplates.ps1' -1

<#
.SYNOPSIS
Retrieves provisioning templates based on specified parameters.

.DESCRIPTION
The Get-ProvisioningTemplates function retrieves provisioning templates based on the specified parameters. It allows you to filter templates by vendor, provider, action, and template ID.

.PARAMETER vendor
Specifies the vendor of the provisioning templates. Valid values are "MICROSOFT", "GOOGLE", "IBM", and "SOPHOS". The default value is "MICROSOFT".

.PARAMETER Provider
Specifies the provider of the provisioning templates.

.PARAMETER Action
Specifies the action associated with the provisioning templates. Valid values are "CREATE", "UPDATE", and "ACTION_NOT_SPECIFIED". The default value is "ACTION_NOT_SPECIFIED".

.PARAMETER TemplateID
Specifies the ID of a specific provisioning template to retrieve.

.EXAMPLE
Get-ProvisioningTemplates -vendor "MICROSOFT" -Provider "SomeProvider" -Action "CREATE"
Retrieves all provisioning templates from the "MICROSOFT" vendor, with the provider set to "SomeProvider" and the action set to "CREATE".

.EXAMPLE
Get-ProvisioningTemplates -TemplateID "12345"
Retrieves the provisioning template with the specified ID.

#>

function Get-ProvisioningTemplates {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $false)]
        [ValidateSet(
            "MICROSOFT",
            "GOOGLE",
            "IBM",
            "SOPHOS"
        )]
        [string]$vendor = "MICROSOFT",
        [Parameter(Mandatory = $false)]
        [string]$Provider,
        [Parameter(Mandatory = $false)]
        [ValidateSet(
            "CREATE",
            "UPDATE",
            "ACTION_NOT_SPECIFIED"
        )]
        [string]$Action = "ACTION_NOT_SPECIFIED",
        [Parameter(Mandatory = $false)]
        [string]$TemplateID
    )

    $Endpoint = "/api/v3/accounts/$script:AccountID/provisionTemplates"

    $Params = @{
        vendor = $vendor
        provider = $Provider
        action = $Action
    }

    if ($TemplateID) {
        $Endpoint = "/api/v3/accounts/$script:AccountID/provisionTemplates/$TemplateID"
        Invoke-TDRestMethod -Endpoint $Endpoint
    } else {
        Invoke-TDRestMethod -Endpoint $Endpoint -Method GET -Params $Params
    }
}
#EndRegion './Public/Provisioning-Template/Get-ProvisioningTemplates.ps1' 68
#Region './Public/Set-APIDetails.ps1' -1

<#
.SYNOPSIS
Sets the API details for the module.

.DESCRIPTION
The Set-APIDetails function is used to set the API details required for the script to interact with the API.

.PARAMETER refreshToken
The refresh token required for authentication.

.PARAMETER AccountID
The account ID associated with the API.

.EXAMPLE
Set-APIDetails -refreshToken "your_refresh_token" -AccountID "your_account_id"

This example sets the API details using the provided refresh token and account ID.

#>

function Set-APIDetails {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $true)]
        [string]$refreshToken,
        [Parameter(Mandatory = $true)]
        [string]$AccountID
    )
    write-Verbose "Setting API Info"
    $script:refreshToken = $refreshToken
    $script:baseurl = "https://ion.tdsynnex.com"
    $Script:AccountID = $AccountID
}
#EndRegion './Public/Set-APIDetails.ps1' 33
#Region './Public/Set-KeyVaultDetails.ps1' -1

<#
.SYNOPSIS
Sets the details for a Key Vault.

.DESCRIPTION
This function sets the details for a Key Vault, including the Azure subscription ID, Key Vault name, Key Vault secret name, and account ID.

.PARAMETER AzureSubscriptionId
The Azure subscription ID to associate with the Key Vault.

.PARAMETER KeyVaultName
The name of the Key Vault.

.PARAMETER KeyVaultSecretName
The name of the secret in the Key Vault.

.PARAMETER AccountID
The account ID to associate with the Key Vault.

.EXAMPLE
Set-KeyVaultDetails -AzureSubscriptionId "12345678-1234-1234-1234-1234567890AB" -KeyVaultName "MyKeyVault" -KeyVaultSecretName "MySecret" -AccountID "MyAccount"

This example sets the details for a Key Vault with the specified Azure subscription ID, Key Vault name, Key Vault secret name, and account ID.

#>


function Set-KeyVaultDetails {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $true)]
        [guid]$AzureSubscriptionId,
        [Parameter(Mandatory = $true)]
        [string]$KeyVaultName,
        [Parameter(Mandatory = $true)]
        [string]$KeyVaultSecretName,
        [parameter(Mandatory = $true)]
        [string]$AccountID
    )
    write-Verbose "Setting Keyvault Info"
    $Script:AzureSubscriptionId = $AzureSubscriptionId
    $Script:KeyVaultName = $KeyVaultName
    $Script:KeyVaultSecretName = $KeyVaultSecretName
    $Script:AccountID = $AccountID
    $script:baseurl = "https://ion.tdsynnex.com"
}
#EndRegion './Public/Set-KeyVaultDetails.ps1' 46
#Region './Public/Subscription/Get-SubscriptionDetails.ps1' -1

<#
.SYNOPSIS
Retrieves the details of a specific subscription for a given customer.

.DESCRIPTION
The Get-SubscriptionDetails function calls the TDRestMethod to retrieve details of a subscription
for a specified customer using the provided CustomerID and subscription ID.

.PARAMETER CustomerID
The unique identifier of the customer whose subscription details are to be retrieved. This parameter is mandatory.

.PARAMETER ID
The unique identifier of the subscription whose details are to be retrieved. This parameter is mandatory.

.EXAMPLE
PS> Get-SubscriptionDetails -CustomerID "12345" -ID "67890"
This command retrieves the details of the subscription with ID "67890" for the customer with ID "12345".

#>

function Get-SubscriptionDetails {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]$CustomerID,
        [Parameter(Mandatory = $true)]
        [string]$ID
    )

    $Endpoint = "/api/v3/accounts/$script:AccountID/customers/$CustomerID/subscriptions/$ID"

    $Params = @{
        refresh                             = $true
    }

    Invoke-TDRestMethod -Endpoint $Endpoint -params $Params
}

#EndRegion './Public/Subscription/Get-SubscriptionDetails.ps1' 38
#Region './Public/Subscription/Get-Subscriptions.ps1' -1

<#
.SYNOPSIS
    Retrieves subscriptions based on specified criteria.

.DESCRIPTION
    The Get-Subscriptions function retrieves subscriptions based on the specified criteria such as customer ID, subscription ID, reseller ID, provider ID, subscription status, date range, billing term, billing cycle, customer name, and pagination limit.

.PARAMETER CustomerID
    Specifies the customer ID for filtering subscriptions.

.PARAMETER SubscriptionID
    Specifies the subscription ID for filtering subscriptions.

.PARAMETER ResellerID
    Specifies the reseller ID for filtering subscriptions.

.PARAMETER ProviderID
    Specifies the provider ID for filtering subscriptions.

.PARAMETER SubscriptionStatus
    Specifies the subscription status for filtering subscriptions. Valid values are:
    - ACCEPTED
    - ACTIVE
    - AVAILABLE
    - CANCELLED
    - COMPLETE
    - CONFIRMED
    - DELETED
    - DISABLED
    - ENABLED
    - ERROR
    - EXPIRED
    - FAILED
    - IN_PROGRESS
    - PAUSED
    - PENDING
    - RUNNING
    - STOPPED
    - SUSPENDED

.PARAMETER Range
    Specifies the date range for filtering subscriptions. Valid values are:
    - TODAY
    - MONTH_TO_DATE
    - QUARTER_TO_DATE
    - YEAR_TO_DATE
    - LAST_MONTH
    - LAST_365_DAYS
    - LAST_QUARTER
    - LAST_YEAR
    - LATEST_MONTH
    - WEEK_TO_DATE
    - LAST_WEEK
    - TWO_MONTHS_AGO

.PARAMETER Term
    Specifies the billing term for filtering subscriptions. Valid values are:
    - MONTHLY
    - ANNUAL

.PARAMETER BillingCycle
    Specifies the billing cycle for filtering subscriptions. Valid values are:
    - MONTHLY
    - ANNUAL

.PARAMETER CustomerName
    Specifies the customer name for filtering subscriptions.

.PARAMETER PaginationLimit
    Specifies the maximum number of subscriptions to retrieve per page.

.EXAMPLE
    Get-Subscriptions -CustomerID "12345" -SubscriptionStatus "ACTIVE" -Range "LAST_MONTH" -Term "MONTHLY" -BillingCycle "MONTHLY" -PaginationLimit 10
    
    This example retrieves active subscriptions for the customer with ID "12345" that were created in the last month, have a monthly billing term and cycle, and limits the result to 10 subscriptions per page.

#>

function Get-Subscriptions {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $false)]
        [string]$CustomerID,
        [Parameter(Mandatory = $false)]
        [guid]$SubscriptionID,
        [Parameter(Mandatory = $false)]
        [string]$ResellerID,
        [Parameter(Mandatory = $false)]
        [string]$ProviderID,
        [Parameter(Mandatory = $false)]
        [ValidateSet(
            "ACCEPTED",
            "ACTIVE",
            "AVAILABLE",
            "CANCELLED",
            "COMPLETE",
            "CONFIRMED",
            "DELETED",
            "DISABLED",
            "ENABLED",
            "ERROR",
            "EXPIRED",
            "FAILED",
            "IN_PROGRESS",
            "PAUSED",
            "PENDING",
            "RUNNING",
            "STOPPED",
            "SUSPENDED"
            )]
        [string]$SubscriptionStatus,
        [Parameter(Mandatory = $false)]
        [ValidateSet(
            "TODAY",
            "MONTH_TO_DATE",
            "QUARTER_TO_DATE",
            "YEAR_TO_DATE",
            "LAST_MONTH",
            "LAST_365_DAYS",
            "LAST_QUARTER",
            "LAST_YEAR",
            "LATEST_MONTH",
            "WEEK_TO_DATE",
            "LAST_WEEK",
            "TWO_MONTHS_AGO"
            )]
        [string]$Range,
        [Parameter(Mandatory = $false)]
        [ValidateSet(
            "P1Y",
            "P1M"
            )]
        [string]$Term,
        [Parameter(Mandatory = $false)]
        [ValidateSet(
            "MONTHLY",
            "ANNUAL"
            )]
        [string]$BillingCycle,
        [Parameter(Mandatory = $false)]
        [string]$CustomerName,
        [Parameter(Mandatory = $false)]
        [int]$PaginationLimit,
        [Parameter(Mandatory = $false)]
        [string]$PaginationOffset,
        [Parameter(Mandatory = $false)]
        [ValidateSet(
            "ASC",
            "DESC"
            )]
        [string]$SortOrder
    )

    $Endpoint = "/api/v3/accounts/$script:AccountID/subscriptions"

    $Params = @{
        customerId                          = $CustomerID
        subscription_id                     = $SubscriptionID
        resellerId                          = $ResellerID
        providerId                          = $ProviderID 
        subscriptionStatus                  = $SubscriptionStatus
        'startDateRange.relativeDateRange'  = $Range
        billingTerm                         = $Term
        billingCycle                        = $BillingCycle
        customerName                        = $CustomerName
    }

    if ($PaginationLimit) {
        $Params.Add("pagination.limit", $PaginationLimit)
    }
    if ($PaginationOffset) {
        $Params.Add("pagination.offset", $PaginationOffset)
    }
    if ($SortOrder) {
        $Params.Add("pagination.sortOrder", $SortOrder)
    }

    Invoke-TDRestMethod -Endpoint $Endpoint -params $Params
}

#EndRegion './Public/Subscription/Get-Subscriptions.ps1' 180