Pipedrive.psm1

$baseUrl = "https://api.pipedrive.com/v1";

<#
.SYNOPSIS
Connects to Pipedrive.
 
.DESCRIPTION
Credentials can be persisted using https://www.powershellgallery.com/packages/CredentialsManager/ by setting the parameter UseCredentialsManager to $True.
o $Credential -eq $Null -and $UseCredentialsManager -eq $Null -> credentials are requested and are not persisted
o $Credential -ne $Null -and $UseCredentialsManager -eq $Null -> passed credentials are used and not persisted
o $Credential -ne $Null -and $UseCredentialsManager -ne $Null -> passed credentials are used and persisted
o $Credential -eq $Null -and $UseCredentialsManager -ne $Null -> Persisted credentials are used
 
.PARAMETER Credential
Credential to access Pipedrive with. I not provided they get requested.
 
.PARAMETER UseCredentialsManager
If $True, credentials are read and written using the CredentialsManager. Only Password part, containing the Token, is used.
#>

function Connect-PD
{
    [CmdletBinding()]
    Param(
       [PSCredential]$Credential,
       [Boolean]$UseCredentialsManager = $False
    ) #end param

    # check module prerequisites
    if($UseCredentialsManager)
    {
        $module = Get-Module -ListAvailable -Name "CredentialsManager";
        if (!$module) { throw "Module 'CredentialsManager' needed. Please install executing 'Install-Module -Name CredentialsManager' as Administrator."; }
    }
    
    if($UseCredentialsManager -and $Credential -eq $Null)
    {
        $Credential = Read-Credential -ListAvailable | Where { $_.Environment -eq "Pipedrive" }
    }
    if(!$Credential) { $Credential = Get-Credential -Message "Please enter Token for Pipedrive as password (username can be anything)."; }
    if($UseCredentialsManager) 
    { 
        Write-Credential "Pipedrive" -Credential $Credential; 
    }

    $script:token = $Credential.GetNetworkCredential().password ;
}

<#
.SYNOPSIS
Adds a deal to a Pipeline
 
.DESCRIPTION
 
.PARAMETER Title
Title of deal
 
.PARAMETER Organisation
Name of Organisation to assign Deal to
 
.PARAMETER Pipeline
Name of Pipeline to assign Deal to. If omitted, the deal will be placed in the default pipeline.
 
.PARAMETER Stage
Name of Stage to assign Deal to. If omitted, the deal will be placed in the first stage of the pipeline.
 
.PARAMETER Value
Value of the deal. If omitted, value will be set to 0.
#>

function Add-PDDeal
{
    [CmdletBinding()]
    Param(
       [Parameter(Mandatory=$true)][string]$Title,
       [string]$Organisation,
       [string]$Pipeline,
       [string]$Stage,
       [float]$Value = 0
    ) #end param

    if(!$script:token) { Connect-PD -UseCredentialsManager $True; }
    
    $bodyAsJson = ConvertTo-JSON( @{ title=$Title; value=$Value; });

    return $(Invoke-RestMethod -Uri "${baseUrl}/deals?api_token=${script:token}" -Method Post -Body $bodyAsJson -ContentType "application/json; charset=utf-8");
}

<#
.SYNOPSIS
Get Organizations from Pipedrive
 
.DESCRIPTION
 
.PARAMETER Term
Search Term to look for
 
#>

function Get-PDOrganization
{
    [CmdletBinding()]
    Param(
       [Parameter(Mandatory=$true)][string]$Term
    )

    if(!$script:token) { Connect-PD -UseCredentialsManager $True; }

    return $(Invoke-RestMethod -Uri "${baseUrl}/organizations/find?term=${Term}&api_token=${script:token}" -Method Get -ContentType "application/json; charset=utf-8");
}

<#
.SYNOPSIS
Adds an Organization
 
.DESCRIPTION
 
.PARAMETER Name
Name of Organization
 
#>

function Add-PDOrganization
{
    [CmdletBinding()]
    Param(
       [Parameter(Mandatory=$true)][string]$Name
    ) #end param

    if(!$script:token) { Connect-PD -UseCredentialsManager $True; }
    
    $bodyAsJson = ConvertTo-JSON( @{ name=$Name; });

    return $(Invoke-RestMethod -Uri "${baseUrl}/organizations?api_token=${script:token}" -Method Post -Body $bodyAsJson -ContentType "application/json; charset=utf-8");
}

<#
.SYNOPSIS
Gets a Person
 
.DESCRIPTION
 
.PARAMETER Term
Search term to look for
 
.PARAMETER OrganizationName
Name of the Organization. Can be omitted to search all persons.
 
#>

function Get-PDPerson
{
    [CmdletBinding()]
    Param(
       [Parameter(Mandatory=$true)][string]$Term,
       [string]$OrganizationName
    ) #end param

    if(!$script:token) { Connect-PD -UseCredentialsManager $True; }
    
    $parameters = @{ term=$Term; api_token=$script:token; }
    if($OrganizationName)
    {
        $organization = Get-PDOrganization -Term $OrganizationName
        if($organization.data.count -eq 0)
        {
            throw "No Organization having Name ${OrganizationName} found."
        }
        $parameters.Add("org_id", $organization.data.id)
    }
    $uri = New-HttpQueryString "${baseUrl}/persons/find" $parameters
    
    return $(Invoke-RestMethod -Uri $uri -Method Get -ContentType "application/json; charset=utf-8");
}

<#
.SYNOPSIS
Adds a Person
 
.DESCRIPTION
 
.PARAMETER Name
Name of Person
 
.PARAMETER OrganizationName
Name of the Organization. If omitted, the person is assigned to no organization.
 
#>

function Add-PDPerson
{
    [CmdletBinding()]
    Param(
       [Parameter(Mandatory=$true)][string]$Name,
       [string]$OrganizationName
    ) #end param

    if(!$script:token) { Connect-PD -UseCredentialsManager $True; }
    
    $body = @{ name=${Name} };
    if($OrganizationName)
    {
        $organization = Get-PDOrganization -Term $OrganizationName
        if($organization.data.count -eq 0)
        {
            throw "No Organization having Name ${OrganizationName} found."
        }
        $body.Add("org_id", $organization.data.id)
    }
    $bodyAsJson = ConvertTo-JSON($body);

    return $(Invoke-RestMethod -Uri "${baseUrl}/persons?api_token=${script:token}" -Method Post -Body $bodyAsJson -ContentType "application/json; charset=utf-8");
}

## Private Functions

function New-HttpQueryString
{
    [CmdletBinding()]
    param 
    (
        [Parameter(Mandatory = $true)][String]$Uri,
        [Parameter(Mandatory = $true)][Hashtable]$QueryParameter
    )
 
    # Add System.Web
    Add-Type -AssemblyName System.Web
 
    # Create a http name value collection from an empty string
    $nvCollection = [System.Web.HttpUtility]::ParseQueryString([String]::Empty)
 
    foreach ($key in $QueryParameter.Keys)
    {
        $nvCollection.Add($key, $QueryParameter.$key)
    }
 
    # Build the uri
    $uriRequest = [System.UriBuilder]$uri
    $uriRequest.Query = $nvCollection.ToString()
 
    return $uriRequest.Uri.OriginalString
}