# Product Sorting

## Product Sorting API Methods

The `SortingAlgorithm` model ensures that the products in the categories and collections are sorted according to a certain algorithm. Sorting types can be `static`, `dynamic` or `external`. When the static sorting algorithms are used for the catalog or collection, the products are sorted statically without depending on other conditions. In dynamic sorting algorithms, a sorting rule set is created by using certain filters so that the products in the catalog or collection are renewed and sorted according to the determined rule set. External sorting algorithms sort by the saved rules with a file.

### `GET` Sorting Algorithms

Sample HTTP request to retrieve all sorting algorithm lists from the system with their details.

‘content\_type’ header represents the response type.

The "Authorization" header is required for authentication. You can retrieve api\_token by logging in.

Path: `/api/v1/sorting_algorithms/`

**Request**

```python
import requests

url = "https://{customer_api_url}/api/v1/sorting_algorithms/"
api_token = "API TOKEN"

headers = {
    'content-type': 'application/json',
    'Authorization': 'Token {}'.format(api_token)
}

response = requests.get(url, headers=headers)
print(response.text)
```

**Response**

In response, it returns the sorting algorithm details. The rule set that comes in the response also contains the rules of the relevant dynamic sorting.

```json

{
    "count": n,
    "next": "/api/v1/sorting_algorithms/?limit=1&page=2",
    "previous": null,
    "results": [
        {
            "pk": 1,
            "code": "a0001",
            "name": "Default",
            "sorting_type": "dynamic",
            "ruleset": [
                {
                    "rule_type": "sorter",
                    "exp": [
                        {
                            "field": "priority"
                        }
                    ],
                    "order": "desc",
                    "mode": "max",
                    "path": "r0001"
                },
                {
                    "rule_type": "sorter",
                    "exp": [
                        {
                            "field": "listed_id"
                        }
                    ],
                    "order": "desc",
                    "mode": "max",
                    "path": "r0002"
                }
            ],
            "config": {},
            "is_visible": true,
            "catalog": 1
        }
    ]
}

```

### `POST` Create Sorting Algorithm

Records new objects in the `SortingAlgorithm` table. The `SortingAlgorithmSerializer` class defined at `omnitron.search.resources.serializers` is used to validate the data.

**Request**

Path: `/api/v1/sorting_algorithms/`

```python
import requests

url = "https://{customer_api_url}/api/v1/sorting_algorithms/"
api_token = "API TOKEN"

headers = {
    'content-type': 'application/json',
    'Authorization': 'Token {}'.format(api_token)
}

data = {
    "sorting_type":"dynamic",
    "is_visible":False,
    "name":"test algorithm",
    "catalog":{catalog-id},
    "ruleset":[
        {
            "rule_type":"sorter",
            "exp":[{"field":"attributes__max_installment"}],
            "order":"desc"
        },
        {
            "rule_type":"sorter",
            "exp":[{"field":"stock"}],
            "order":"desc"
        }]
}

response = requests.post(url, headers=headers, data=data)
print(response.text)


```

**Response**

Returns the created sorting algorithm items properties. Response Status Code: 201

```json
{
    "pk": 41,
    "code": "a0009",
    "name": "test algorithm",
    "sorting_type": "dynamic",
    "ruleset": [
        {
            "rule_type": "sorter",
            "exp": [
                {
                    "field": "attributes__max_installment"
                }
            ],
            "order": "desc",
            "mode": "max",
            "path": "r0001"
        },
        {
            "rule_type": "sorter",
            "exp": [
                {
                    "field": "stock"
                }
            ],
            "order": "desc",
            "mode": "sum",
            "path": "r0002"
        }
    ],
    "config": {},
    "is_visible": false,
    "catalog": {catalog-id},
    "modified_date": "2022-12-22T09:54:31.076718Z",
    "created_date": "2022-12-22T09:54:31.076685Z"
}
```

### `PATCH` Update Sorting Algorithm

Update the object specified with the primary key in the `SortingAlgorithm` table.

‘content\_type’ header represents the response type.

The ‘Authorization’ header is required for authentication. You can retrieve `api_token` by logging in.

Path: `/api/v1/sorting_algorithms/{sorting-algorithm-pk}`

```python

import requests

url = "https://{customer_api_url}/api/v1/sorting_algorithms/{PK}/"
api_token = "API TOKEN"

headers = {
    'content-type': 'application/json',
    'Authorization': 'Token {}'.format(api_token)
}

data = {
    "sorting_type":"static",
    "is_visible":True,
    "name": "Test Updated"
}

response = requests.patch(url, headers=headers, data=data)
print(response.text)
```

**Response**

```json
{
    "pk": 41,
    "code": "a0009",
    "name": "Test Updated",
    "sorting_type": "static",
    "ruleset": [
        {
            "rule_type": "sorter",
            "exp": [
                {
                    "field": "attributes__max_installment"
                }
            ],
            "order": "desc",
            "mode": "max",
            "path": "r0001"
        },
        {
            "rule_type": "sorter",
            "exp": [
                {
                    "field": "stock"
                }
            ],
            "order": "desc",
            "mode": "sum",
            "path": "r0002"
        }
    ],
    "config": {},
    "is_visible": true,
    "catalog": 1,
    "modified_date": "2022-12-22T10:14:56.911146Z",
    "created_date": "2022-12-22T09:54:31.076685Z"
}

```

### `GET` List All Addable Products for the Algorithm

Path: `/api/v1/sorting_algorithms/{sorting-algorithm-pk}/product_list/`

The endpoint where the products that can be added to the algorithm are listed. Essentially, it returns products added for static sorting.

**Response**

```json

{
    "count": n,
    "next": "/api/v1/sorting_algorithms/{sorting-algorithm-pk}/product_list/?limit=1&page=2",
    "previous": null,
    "results": [
        {
            "pk": 468,
            "name": "VEST / SWEATER",
            "base_code": "1182701",
            "sku": "1182701040",
            "product_type": "0",
            "is_active": true,
            "parent": 210347,
            "attributes": {
                "erp_ProductDetailName": "NYLON",
                "integration_MainColour": "EVERGREEN"
            },
            "attributes_kwargs": {},
            "extra_attributes": {},
            "group_products": [],
            "productimage_set": []
            ...
        }
    ]
}

```

### `GET` List All Products in an Algorithm

Sample HTTP request to return the entire list of items linked to sorting algorithms.

‘content\_type’ header represents the response type.

The ‘Authorization’ header is required for authentication. You can retrieve `api_token` by logging in.

**Request**

Path: `/api/v1/sorting_algorithms/{sorting-algorithm-pk}/item_list/`

The endpoint where the products in the algorithm are listed.

```python

import requests

url = "https://{customer_api_url}/api/v1/sorting_algorithms/{PK}/item_list/"
api_token = "API TOKEN"

headers = {
    'content-type': 'application/json',
    'Authorization': 'Token {}'.format(api_token)
}

response = requests.get(url, headers=headers)
print(response.text)

```

**Response**

```json
{
    "count": n,
    "next": "/api/v1/sorting_algorithms/{sorting-algorithm-pk}/item_list/?limit=1&page=2",
    "previous": null,
    "results": [
        {
            "pk": 468,
            "name": "VEST / SWEATER",
            "base_code": "1182701",
            "sku": "1182701040",
            "product_type": "0",
            "is_active": true,
            "parent": 210347,
            "attributes": {
                "erp_ProductDetailName": "NYLON",
                "integration_MainColour": "EVERGREEN"
            },
            "attributes_kwargs": {},
            "extra_attributes": {},
            "group_products": [],
            "productimage_set": []
            ...
        }
    ]
}

```

## Sort Option API Methods

By saving the sorting score produced by the Sorting Algorithm, it allows Elasticsearch to sort according to this value for the shop.

### `GET` Sort Options

Sample HTTP request to get all sort options lists with its details from the system.

‘content\_type’ header represents the response type.

The ‘Authorization’ header is required for authentication. You can retrieve `api_token` by logging in.

Path: `/api/v1/sort_options/`

**Request**

```python
import requests

url = "https://{customer_api_url}/api/v1/sort_options"
api_token = "API TOKEN"

headers = {
    'content-type': 'application/json',
    'Authorization': 'Token {}'.format(api_token)
}

response = requests.patch(url, headers=headers)
print(response.text)

```

**Response**

Returns the sort options details. Sorting algorithm ID values are kept in the responses, and optional channel information can be added.

```json
{
    "count": n,
    "next": "/api/v1/sort_options/?limit=1&page=2",
    "previous": null,
    "results": [
        {
            "pk": 12,
            "channel": null,
            "sorting_algorithms": [
                25,
                703,
                40
            ],
            "label": "Demo Sub Category",
            "value": "6d9fe140-a02f-4470-9989-f8e4303c9751",
            "order": null,
            "is_default": false,
            "is_visible": false,
            "translations": null,
            "catalog": {catalog-id},
            "disable_score": false
        }
    ]
}
```

### `POST` Create Sort Option

Records new objects in the `SortOption` table. The `SortOptionSerializer` class defined at `omnitron.search.resources.serializers` is used to validate the data.

**Request**

Path: `/api/v1/sort_options/`

```json
{
    "channel": null,
    "sorting_algorithms": [
        {sorting-algorithm-pk},
        ...
    ],
    "label": "label",
    "order": null,
    "is_default": false,
    "is_visible": false,
    "catalog": {catalog-pk},
    "disable_score": false
}

```

**Response**

```json
{
    "pk": 12,
    "channel": null,
    "sorting_algorithms": [
        {sorting-algorithm-pk},
        ...
    ],
    "label": "label",
    "order": null,
    "is_default": false,
    "is_visible": false,
    "catalog": {catalog-pk},
    "disable_score": false
}
```

### `POST` Add Sorting Algorithms to Sort Option

To add an extra sorting algorithm to the sorting options, the relevant endpoint is used and the `sorting_algorithm` and options IDs to be added must be entered. The sent data information list should be sent. In addition, a sort option can only have one static algorithm.

**Request**

Path: `/api/v1/sort_options/{sort-option-pk}/add_sorting_algorithms/`

**Data**

```json
[
    {
        "algorithm": {sorting-algorithm-pk},
        "option": {sort-option-pk}
    }
]
```

**Response**

```json
{
    "pk": 12,
    "channel": null,
    "sorting_algorithms": [
        {sorting-algorithm-pk},
        ...
    ],
    "label": "label",
    "order": null,
    "is_default": false,
    "is_visible": false,
    "catalog": {catalog-pk},
    "disable_score": false
}

```

**Bad Response**

If a static algorithm is not entered, it will throw an error as follows:

Static code is 400 (Bad Response)

```json
[
    {
        "non_field_errors": [
            "A sort option can only have one static algorithm!"
        ]
    }
]
```

## Product Sorting Item API Methods

It is the model with the score calculated by the sorting algorithm of the product. The sorting score is calculated by the linked algorithm.

### `GET` Product Sorting Items

Sample HTTP request to get all product sorting items lists from the system.

‘content\_type’ header represents the response type.

The ‘Authorization’ header is required for authentication. You can retrieve api\_token by logging in.

**Request**

Path: `/api/v1/product_sorting_items/`

```python

import requests

url = "https://{customer_api_url}/api/v1/product_sorting_items"
api_token = "API TOKEN"

headers = {
    'content-type': 'application/json',
    'Authorization': 'Token {}'.format(api_token)
}

response = requests.get(url, headers=headers)
print(response.text)
```

**Response**

```json

{
    "count": n,
    "next": "/api/v1/product_sorting_items/"
    "previous": null,
    "results": [
        {
            "pk": 8769,
            "catalog_item": {catalog-item-pk},
            "sorting_algorithm": {sorting-algorithm-pk},
            "modified_date": "2021-10-15T07:21:14.937432Z",
            "created_date": "2021-10-15T07:21:14.937362Z"
        },
        ...
    ]
}

```

### `POST` Create Product Sorting Items

Records new objects in the ProductSortingItem table. The ProductSortingItemSerializer class defined at omnitron.resources.serializers is used to validate the data.

‘content\_type’ header represents the response type.

The ‘Authorization’ header is required for authentication. You can retrieve `api_token` by logging in.

**Request**

Path: `/api/v1/product_sorting_items/`

```python

import requests

url = "https://{customer_api_url}/api/v1/product_sorting_items"
api_token = "API TOKEN"

headers = {
    'content-type': 'application/json',
    'Authorization': 'Token {}'.format(api_token)
}

data = {
    "catalog_item": {catalog-item-pk},
    "sorting_algorithm": {sorting-algorithm-pk}
}


response = requests.post(url, headers=headers, data=data)
print(response.text)
```

**Response**

```json

{
    "pk":12,
    "catalog_item":{catalog-item-pk},
    "sorting_algorithm":{sorting-algorithm-pk}
}

```

### `DELETE` Product Sorting Items

Allows users to completely remove certain product sorting items. Returns "204 No Content"

Path: `/api/v1/product_sorting_items/{product-sorting-item-pk}/`

**Response Status Code:** 204


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://apidocs.akinon.com/omnitron/catalogue/product-sorting.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
