# Result builder

{% hint style="success" %}
This is the official documentation of the `forestadmin-agent-django` and `forestadmin-agent-flask` Python agents.
{% endhint %}

Actions can be configured to achieve different results in the GUI.

Most actions will simply perform work and display the default notification, however, other behaviors are possible:

* [Displaying a notification with a custom message](#custom-notifications)
* [Displaying HTML content in a side panel](#html-result)
* [Generating a file download](#file-generation)
* [Redirecting the user to another page](#redirections)
* [Calling a webhook from the user's browser](#webhooks) (for instance to trigger a login in a third-party application)
* [Setting up response headers](#response-headers)
* [Invalidating related data](https://docs.forestadmin.com/developer-guide-agents-python/agent-customization/actions/related-data-invalidation)

### Default behavior

The default behavior, when no exception is thrown in the handler is to display a generic notification.

![](https://2921382565-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2HgnlEINLUAEQC1KgN48%2Fuploads%2Fgit-blob-f59d253e5e82226722ee7974f0b0050a93366140%2Factions-default-success-result.png?alt=media)

```python
from typing import Union
from forestadmin.datasource_toolkit.decorators.action.result_builder import ResultBuilder
from forestadmin.datasource_toolkit.decorators.action.context.single import ActionContextSingle
from forestadmin.datasource_toolkit.interfaces.actions import ActionResult

import requests

async def execute(
    context: ActionContextSingle, result_builder: ResultBuilder
) -> Union[None, ActionResult]:
    # Not using the resultBuilder here will display the generic success notification.
    # (as long as no exception is thrown)

agent.customize_collection("Company").add_action("Mark as live", {
    "scope": "Single",
    "execute": execute,
})
```

### Custom notifications

When customizing the notification message, you can use the to generate different types of responses.

![](https://2921382565-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2HgnlEINLUAEQC1KgN48%2Fuploads%2Fgit-blob-4820e3a153856f1a2b05aa68e871e3fdec009f45%2Factions-custom-success-result.png?alt=media) ![](https://2921382565-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2HgnlEINLUAEQC1KgN48%2Fuploads%2Fgit-blob-c42150ac5f8c3e2244461544b54742f0b753f71b%2Factions-custom-error-result.png?alt=media)

```python
from typing import Union
from forestadmin.datasource_toolkit.decorators.action.result_builder import ResultBuilder
from forestadmin.datasource_toolkit.decorators.action.context.single import ActionContextSingle
from forestadmin.datasource_toolkit.interfaces.actions import ActionResult

async def execute(
    context: ActionContextSingle, result_builder: ResultBuilder
) -> Union[None, ActionResult]:
    is_not_live_company = # Company is not live
    if is_not_live_company:
        return result_builder.success("Company is now live!")
    else:
        return result_builder.error("The company was already live!")

agent.customize_collection("Company").add_action("Mark as live", {
    "scope": "Single",
    "execute": execute,
})
```

### HTML result

You can also return an HTML page to give more feedback to the user who triggered the Action.

![](https://2921382565-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2HgnlEINLUAEQC1KgN48%2Fuploads%2Fgit-blob-79ca2b8c754ae504c735704e3d0e115dd087e8ff%2Factions-html-result-success.png?alt=media)

```python
from typing import Union
from forestadmin.datasource_toolkit.decorators.action.result_builder import ResultBuilder
from forestadmin.datasource_toolkit.decorators.action.context.single import ActionContextSingle
from forestadmin.datasource_toolkit.interfaces.actions import ActionResult

async def execute(
    context: ActionContextSingle, result_builder: ResultBuilder
) -> Union[None, ActionResult]:
    # ... charge the credit card ...
    record = context.get_record(['amount', 'source:last4'])
    if credit_card_successfully_charged:
        return result_builder.success(
            '<p class="c-clr-1-4 l-mt l-mb">{record["amount"] / 100}  USD has been '
            + 'successfully charged.</p>'
            + '<strong class="c-form__label--read c-clr-1-2">Credit card</strong>'
            + '<p class="c-clr-1-4 l-mb">**** **** **** {record["source"]["last4"]} '
            + '</p>',
            {"type": "html"}
        )
    else:
        return result_builder.error(
            '<p class="c-clr-1-4 l-mt l-mb">{record["amount"] / 100} USD has not '
            + 'been charged.</p>'
            + '<strong class="c-form__label--read c-clr-1-2">Credit card</strong>'
            + '<p class="c-clr-1-4 l-mb">**** **** **** {$record["source"]["last4"]}'
            + '</p>'
            + '<strong class="c-form__label--read c-clr-1-2">Reason</strong>'
            + '<p class="c-clr-1-4 l-mb">You can not charge this credit card. The '
            + 'card is marked as blocked</p>',
            {"type": "html"}
        )

agent.customize_collection("Company").add_action("Charge credit card", {
    "scope": "Single",
    "execute": execute,
})
```

### File generation

{% hint style="warning" %}
Because of technical limitations, Smart Actions that generate files should be flagged as such with the `generateFile` option.

This will cause the GUI to download the output of the action, but will also prevent from being able to use the `resultBuilder` to display notifications, errors, or HTML content.
{% endhint %}

Smart actions can be used to generate or download files.

The example code below will trigger a file download (with the file named `filename.txt`, containing `StringThatWillBeInTheFile` using `text/plain` mime-type).

```python
from typing import Union
from forestadmin.datasource_toolkit.decorators.action.result_builder import ResultBuilder
from forestadmin.datasource_toolkit.decorators.action.context.single import ActionContextSingle
from forestadmin.datasource_toolkit.interfaces.actions import ActionResult

async def execute(
    context: ActionContextSingle, result_builder: ResultBuilder
) -> Union[None, ActionResult]:
    return result_builder.file(
        io.BytesIO("StringThatWillBeInTheFile"
    ).encode("utf-8"), "filename.txt", "text/plain")

agent.customize_collection("Company").add_action("Download a file", {
    "scope": "Single",
    "generate_file": True,
    "execute": execute,
})
```

### Redirections

To streamline your operation workflow, it could make sense to redirect to another page after an Action has successfully been executed.

It is possible using the `redirectTo` function.

The redirection works both for internal (`\*.forestadmin.com` pages) and external links.

{% tabs %}
{% tab title="Internal link" %}

```python
from typing import Union
from forestadmin.datasource_toolkit.decorators.action.result_builder import ResultBuilder
from forestadmin.datasource_toolkit.decorators.action.context.single import ActionContextSingle

async def execute(
    context: ActionContextSingle, result_builder: ResultBuilder
) -> Union[None, ActionResult]:
    return result_builder.redirect(
        "/MyProject/MyEnvironment/MyTeam/data/20/index/record/20/108/activity"
    )

agent.customize_collection("Company").add_action("Mark as live", {
    "scope": "Single",
    "execute": execute,
})
```

{% endtab %}

{% tab title="External link" %}

```python
from typing import Union
from forestadmin.datasource_toolkit.decorators.action.result_builder import ResultBuilder
from forestadmin.datasource_toolkit.decorators.action.context.single import ActionContextSingle
from forestadmin.datasource_toolkit.interfaces.actions import ActionResult

async def execute(
    context: ActionContextSingle, result_builder: ResultBuilder
) -> Union[None, ActionResult]:
    return result_builder.redirect(
        "https://www.royalmail.com/portal/rm/track?trackNumber=ZW924750388GB"
    )

agent.customize_collection("Company").add_action("Mark as live", {
    "scope": "Single",
    "execute": execute,
})
```

{% endtab %}
{% endtabs %}

### Webhooks

After an action you can set up an HTTP (or HTTPS) callback - a webhook - to forward information to other applications.

Note that the webhook will be triggered from the user's browser, so it will be subject to CORS restrictions.

Its intended use is often to perform a login on a third-party application or to trigger a background job on the current user's behalf.

```python
from typing import Union
from forestadmin.datasource_toolkit.decorators.action.context.single import ActionContextSingle
from forestadmin.datasource_toolkit.decorators.action.result_builder import ResultBuilder
from forestadmin.datasource_toolkit.interfaces.actions import ActionResult

async def execute(
    context: ActionContextSingle, result_builder: ResultBuilder
) -> Union[None, ActionResult]:
    return result_builder.webhook(
        "http://my-company-name",  # The url of the company providing the service.
        "POST",  # The method you would like to use (typically a POST).
        {},  # You can add some headers if needed.
        {"adminToken": "your-admin-token"}  # A body to send to the url.
    )

agent.customize_collection("Company").add_action("Mark as live", {
    "scope": "Single",
    "execute": execute,
})
```

{% hint style="warning" %}
Please note that the webhook function and the setHeader function operate independently and do not modify the same HTTP call. Webhook headers will be sent along with the webhook call, while setHeaders will modify directly the Action response headers.
{% endhint %}

### Response headers

Sometimes you may want to setup custom response headers after action execution, the `set_header` function is here to reach out this goal.

Before executing any end function described above, you should be able to add headers to the action response like the exemple below.

```python
from forestadmin.datasource_toolkit.decorators.action.context.single import ActionContextSingle
from forestadmin.datasource_toolkit.decorators.action.result_builder import ResultBuilder
from forestadmin.datasource_toolkit.interfaces.actions import ActionResult

async def execute(
    context: ActionContextSingle, result_builder: ResultBuilder
) -> Union[None, ActionResult]:
    return result_builder.set_header("myHeaderName", "myHeaderValue").redirect(
        "https://www.royalmail.com/portal/rm/track?trackNumber=ZW924750388GB"
    )

agent.customize_collection("companies").add_action("Mark as live", {
    "scope": "Single",
    "execute": execute
})
```
