Create Sitecore Commerce items with a script – Part 2 (Catalog)

In the last article, we created the utility functions to get the authorization token and to build the request headers.

Now let the fun begin and let’s create some items.

In a new Sitecore Commerce repository, we’ll need a Catalog to begin with. We can check in the Postman API collection if there is a CreateCatalog request (there is one), but I recommand vividly to trust more the debugging tool of Chrome while you create a dummy object in XC than the Postman API Collection. I have already seen errors in the latter, and if you succeed in creating a XC item in the Business Tool, then the request send from Chrome to XC will definitively work as well in a script.

So, browse to your Business Tools server, Merchandising page, open Chrome’s debugging tool and create a dummy catalog. Look for the DoAction() call and see what is in the payload request.

The payload request has the following JSON:


{
  "Name": "Details",
  "DisplayName": "Details",
  "EntityId": "",
  "EntityVersion": 1,
  "Action": "AddCatalog",
  "ItemId": "Entity-Catalog-JSSCatalog",
  "VersionedItemId": "Entity-Catalog-JSSCatalog-1",
  "DisplayRank": 500,
  "UiHint": "Flat",
  "Icon": "chart_column_stacked",
  "Policies": [],
  "SelectedChildView": {
    "Name": "",
    "Policies": []
  },
  "Properties": [
    {
      "Name": "Version",
      "DisplayName": "Version",
      "Value": "11",
      "IsHidden": true,
      "OriginalType": "System.Int32",
      "IsReadOnly": true,
      "UiType": "",
      "IsRequired": true,
      "Policies": []
    },
    {
      "Name": "Name",
      "DisplayName": "Name",
      "Value": "JeSuisSitecore",
      "IsHidden": false,
      "OriginalType": "System.String",
      "IsReadOnly": false,
      "UiType": "",
      "IsRequired": true,
      "Policies": []
    },
    {
      "Name": "DisplayName",
      "DisplayName": "Display Name",
      "Value": "Je Suis Sitecore",
      "IsHidden": false,
      "OriginalType": "System.String",
      "IsReadOnly": false,
      "UiType": "",
      "IsRequired": true,
      "Policies": []
    }
  ],
  "ChildViews": [],
  "@odata.type": "#Sitecore.Commerce.EntityViews.EntityView"
}

You won’t need to create all this JSON. After some experience, here is the minimal JSON you’ll need to create a Catalog:

{
  "Name": "Details",
  "DisplayName": "Details",
  "EntityId": "",
  "Action": "AddCatalog",
  "ItemId": "",
  "DisplayRank": 500,
  "UiHint": "Flat",
  "Properties": [
    {
      "Name": "Name",
      "DisplayName": "Name",
      "Value": "JeSuisSitecore",
      "IsHidden": false,
      "OriginalType": "System.String",
      "IsReadOnly": false,
      "UiType": "",
      "IsRequired": true,
      "Policies": []
    },
    {
      "Name": "DisplayName",
      "DisplayName": "Display Name",
      "Value": "Je Suis Sitecore",
      "IsHidden": false,
      "OriginalType": "System.String",
      "IsReadOnly": false,
      "UiType": "",
      "IsRequired": true,
      "Policies": []
    }
  ]
}

The function to create a Calalog can now be developped:

Function AddCatalog {
    [CmdletBinding()]
    PARAM
    (
    [string][parameter(Mandatory = $true)][ValidateNotNullOrEmpty()]$Token,
    [string][parameter(Mandatory = $true)][ValidateNotNullOrEmpty()]$IdentityServiceUri,
    [string] $Catalog,
    [string] $DisplayName
    )

    $body = @{entityView=@{Name="Details";DisplayName="Details";EntityId="";Action="AddCatalog";ItemId="";Properties=@( `
    [pscustomobject]@{Name="Name";DisplayName="Name";Value=$Catalog;IsHidden=$False;OriginalType="System.String";IsReadOnly=$False;IsRequired=$True},`
    [pscustomobject]@{Name="DisplayName";DisplayName="Display Name";Value=$DisplayName;IsHidden=$False;OriginalType="System.String";IsReadOnly=$False;IsRequired=$True}`
    );DisplayRank=500;UiHint="Flat"}} | ConvertTo-Json -Depth 100

    
    $contentType = 'application/json'
    $headers = BuildHeaders($token)
    $uri = "$IdentityServiceUri/api/DoAction()"
    $Res = Invoke-RestMethod -Uri $uri -ContentType $contentType -Method Post -Headers $headers -Body $body

    return $Res.ResponseCode

}

A catalog needs to be only create once, so we’ll need a way to check if the catalog we want to create is already in the XC database or not. In the Postman API Collection, we have a request called Catalogs, that is used to list all the catalogs in the XC database:

We can use this call to get the CatalogVersion number, which will be useful for later.

As you can see this Catalogs request is a GET. We’ll create a function that returns the catalog version nummer of a catalog (catalog name is given in the function’s parameter). If the catalog does not exist in the XC database, the function will return a version number of 0.

Function GetCatalogVersion {
    [CmdletBinding()]
    PARAM
    (
        [string][parameter(Mandatory = $true)][ValidateNotNullOrEmpty()]$Token,
        [string][parameter(Mandatory = $true)][ValidateNotNullOrEmpty()]$Catalog,
        [string][parameter(Mandatory = $true)][ValidateNotNullOrEmpty()]$IdentityServiceUri
    )

    $contentType = 'application/json'
    $headers = BuildHeaders($token)
    $uri = "$IdentityServiceUri/api/Catalogs"
    $Res = Invoke-RestMethod -Uri $uri -ContentType $contentType -Method Get -Headers $headers

    $catVersion = ($Res.value | Where-Object { $_.FriendlyId -eq $Catalog} | Select-Object Version)

    if ($null -eq $catVersion -or $catVersion.Count -eq 0) {
        return 0
    }

    return $catVersion[0].Version

}

Note the use of our function BuildHeader that we build in the first article.

Those two functions needs now to work together in another function who will first check the existence of the catalog before eventually creating it.

Function CreateCatalog {
    [CmdletBinding()]
    PARAM
    (
    [string][parameter(Mandatory = $true)][ValidateNotNullOrEmpty()]$Token,
    [string][parameter(Mandatory = $true)][ValidateNotNullOrEmpty()]$IdentityServiceUri,
    [pscustomobject] $Data
    )

    $catalog = $Data.Catalog
    
    $versionCatalog = GetCatalogVersion -Token $token -Catalog $catalog -IdentityServiceUri $IdentityServiceUri


    if ($versionCatalog -eq 0) {
        $result = AddCatalog -Token $token -Catalog $catalog -DisplayName $catalog -IdentityServiceUri $IdentityServiceUri
        if ($result -ne "Ok") {
            Write-Host("Error adding catalog $catalog : $result")
            Exit 1
        }
        $versionCatalog = GetCatalogVersion -Token $token -Catalog $catalog -IdentityServiceUri $IdentityServiceUri
        Write-Host("Created catalog $catalog")
    } else {
		Write-Host("Already existing catalog $catalog")
	}
}

And now, a catalog can be created with a one-liner of code. See the previous article to create the $token variable.

CreateCatalog -Token $token -Data @{Catalog="JSSCatalog"} -IdentityServiceUri "https://$authoringAlias"

Each XC item will be create the same way. We’ll check in Business Toolswhat request is used to create an item and we’ll transform the request and the payload into a Powershell script. In the next article we’ll see how to create a category inside our new catalog.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: