> For the complete documentation index, see [llms.txt](https://docs.eximee.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.eximee.com/documentation/documentation-en/budowanie-aplikacji/logika-biznesowa/scriptcode/zadanie-skryptowe-scripttask/api-zadan-skryptowych.md).

# Script Tasks API

\
The platform provides the ability to create script task handler logic from Eximee Designer. The process designer only needs to write the handler logic and attach it in the process.

## Creating a script task <a href="#zadanieskryptowe-tworzeniezadaniaskryptowego" id="zadanieskryptowe-tworzeniezadaniaskryptowego"></a>

Script tasks can be created and edited using the Eximee Designer application. To do this, in the module **Library** select the tab **Script tasks**:

<figure><img src="https://2112972046-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2CssJT0zIo4SJQLbSZ6l%2Fuploads%2FYw3d6gs72b0Ijnh8BhYH%2Fimage.png?alt=media&amp;token=7621e387-2eca-47c4-ba77-5141a61b665b" alt=""><figcaption><p><em><strong>Figure 1.</strong> Script tasks tab window</em></p></figcaption></figure>

A detailed description of script creation is available in: [Script tasks](https://docs.eximee.com/documentation/documentation-en/budowanie-aplikacji/logika-biznesowa/scriptcode/zadanie-skryptowe-scripttask.md).

### Handler API <a href="#zadanieskryptowe-apihandlerow" id="zadanieskryptowe-apihandlerow"></a>

```typescript
interface Task {
   getVariable(name): string;                                 // Retrieve a process variable with the identifier specified in the parameter
   getAllVariables(): {[key: string]: string};                // Retrieve all variables in the process
   getProcessIntanceId(): string;                             // Returns the process instance identifier
}
 
interface Context {
   complete(variables: [key: string]: string, modelChanges?: [key: string]: string): void; // Complete the task and pass the variables specified in the parameter to the process, as well as optionally changes in the data model (a null value at a key clears that key)
   handleFailure(cause: string): void;                        // Report an incident on the task (e.g. system error) together with the reason specified in the parameter (the process stops until intervention)    
   handleBpmnError(errorCode: string, cause?: string): void;  // Report a predefined business error on the task together with the error code and reason specified in the parameter (the BPMN error handling path is started)
    
   // Deprecated
   getModel(String processInstanceId, List<String> fieldsNames): Map<String, String> // Call the data model by providing the process instance id and a list of keys whose values we want to retrieve.
                                                                                     // Deprecated method. Use api.model
}
 
interface Logger {
    info(message: string, ...args: any);                      // Logging at INFO level                
    debug(message: string, ...args: any);                     // Logging at DEBUG level
    warn(message: string, ...args: any);                      // Logging at WARN level
    error(message: string, ...args: any);                     // Logging at ERROR level
    trace(message: string, ...args: any);                     // Logging at TRACE level
}
 
function nonsensitive(arg: any): String;
 
function handle(task: Task, context: Context): void {}


```

{% hint style="info" %}
Setting the list of groups that will have access to the process instance on the case list

[Process data operations and access](https://github.com/Consdata/eximee-docs/tree/main/budowanie-aplikacji/logika-biznesowa/scriptcode/skrypty-scriptservice/api-skryptow/operacje-i-dostep-do-danych-procesu.md)
{% endhint %}

### Sample script tasks <a href="#zadanieskryptowe-przykladowezadaniaskryptowe" id="zadanieskryptowe-przykladowezadaniaskryptowe"></a>

The script retrieves the variable with the identifier "testVariable", multiplies it by itself, and assigns the result to a new variable "result":

```javascript
function handle(task, context) {
    Logger.info("Starting script task sensitiveName={}, nonSensitiveName={}", 'SECRET_DATA', nonsensitive('NON_SECRET_DATA'))
 
    const testVariableNumber = task.getVariable('testVariable');
    const testVariablePower = testVariableNumber * testVariableNumber;
     
    Logger.info("Ending script task")
    context.complete({'result': testVariablePower});
 }
```

### Calling REST services in a script task <a href="#zadanieskryptowe-wywolanieuslugrestwzadaniuskryptowym" id="zadanieskryptowe-wywolanieuslugrestwzadaniuskryptowym"></a>

Call documentation: [\[Rest\] Calling external REST services (ScriptCode)](https://docs.eximee.com/documentation/documentation-en/budowanie-aplikacji/logika-biznesowa/scriptcode/restapi-integracje-z-zewnetrznymi-systemami.md)

{% hint style="danger" %}
The only change compared to the above documentation is the configuration file.

For ScriptCode Handler it is called **script-handler-api.xml** and is located in the directory **`/etc/eximee/webforms/script-handler-config`**
{% endhint %}

Example of a script task with an external REST service call:

```typescript
function handle(task, context) {
    // Retrieve the process variable with the key "testVariable"
    let value = task.getVariable('testVariable');
     
    // Retrieve the process variable with the key "result"
    let result = task.getVariable('result');
 
    if (value == null || isNaN(value)) {
        // Report an error on the task along with the error code "errorCode"
         context.handleBpmnError("errorCode", "No value for the process variable with key testVariable");
    }
 
    value = value * 5
    result = result * 5
    Logger.info("Passed: [value={}, result={}]", value, result);
          
    try {
        let response = api.rest.v1.get("questionnaire", {}, {});
 
        Logger.info("Task ended successfully");
        context.complete({'variable1': value, 'variable2': result, 'Questionnaires': response.body});
    }
    catch(e) {
        Logger.warn("Exception occured: {}", e.message);
        context.handleFailure("Failed to retrieve questionnaire list " + e.message);
    }      
}
```

### Retrieving business application configuration <a href="#zadanieskryptowe-pobieraniekonfiguracjiaplikacjibiznesowej" id="zadanieskryptowe-pobieraniekonfiguracjiaplikacjibiznesowej"></a>

Call documentation: [Scripts (scriptService)#Retrievingapplicationconfiguration](https://docs.eximee.com/documentation/documentation-en/budowanie-aplikacji/logika-biznesowa/scriptcode/skrypty-scriptservice/api-skryptow.md#skrypty-scriptservice-pobieraniekonfiguracjiaplikacji)

Example of a script task with configuration retrieval:

```javascript
function handle(task, context) {
    // Retrieve variables from the configuration
    const skipTask = api.config.v1.get("script.task.skip.task")
    const titleName = api.config.v1.getOrDefault("script.task.title.name", "Default title")
     
    // Complete the task and pass the variables (skipTask, titleName) to the process
    context.complete({'skipTask': skipTask, 'titleName': titleName});
}
```

### Calling Eximee Status in ScriptCode Handler <a href="#zadanieskryptowe-wywolanieeximeestatuswscriptcodehandlerze" id="zadanieskryptowe-wywolanieeximeestatuswscriptcodehandlerze"></a>

{% hint style="danger" %}
For the call to work correctly, complete the EXIMEE\_STATUS\_URL parameter pointing to the eximee-status API.

Methods calling eximee-status require a process variable **statusId**, which should contain the application number for which the specified update is to be made.
{% endhint %}

#### Status API <a href="#zadanieskryptowe-statusapi" id="zadanieskryptowe-statusapi"></a>

```typescript
interface EximeeStatusClient {
   updateStatus(statusName: string, statusDescription: string): void;   // Update the status name and description
   updateMetadata(metadata: string): void;                               // Update the application metadata
   getMetadata(): Object;                                               // Retrieve the application metadata
   getClientFormsBasicInfo(): Object;                                   // Retrieve the list of application statuses for the logged-in client (Method available from version 4.154.0. The client must be logged in for the functionality to work.)
 }
```

Example ScriptCodeHandler with eximee-status call:

```javascript
function handle(task, context) {
    try {
        api.status.v1.updateStatus("NEW_STATUS", "STATUS_DESC");
 
        Logger.info("Task ended successfully");
        context.complete({});
    }
    catch(e) {
        Logger.warn("Exception occured: {}", e.message);
        context.handleFailure("Failed to retrieve questionnaire list " + e.message);
    }      
}
```

### Retrieving Content contents <a href="#zadanieskryptowe-pobieraniezawartoscitresci" id="zadanieskryptowe-pobieraniezawartoscitresci"></a>

{% hint style="info" %}
Functionality available from platform version: **3.332.0**
{% endhint %}

From a script task you can retrieve the content of the artifact **Content** (TextContent) created in **Eximee Designer**, using the function: `api.repository.v1.textContent`. This function returns an object that contains the content for each of the defined translations. To retrieve the content for a given translation, use the function `language`. Example usage:

```javascript
const artifactName = "footer";
const artifactVersion = "*";
const language = "pl";
  
const contentArtifact = api.repository.v1.textContent(artifactName, artifactVersion);
const footerPl = contentArtifact.language(language).text();
```

{% hint style="danger" %}

1. Function **`textContent`** throws an exception if it cannot find an artifact with the given parameters.
2. Function **`language`** throws an exception if it cannot find a translation in the given language.
   {% endhint %}

If we are not sure that the parameters we provided are correct, we can handle exceptions using **try catch**:

```javascript
const artifactName = "footer";
const artifactVersion = "*";
const language = "pl";
  
let contentArtifact;
try {
    contentArtifact = api.repository.v1.textContent(artifactName, artifactVersion);
} catch (error) {
    context.handleFailure("No artifact found with name: " + artifactName + " and version: " + artifactVersion);
    return;
}
  
let footerPl;  
try {
    footerPl = contentArtifact.language(language).text(); 
} catch (error) {
    context.handleFailure("No translation found in the artifact for language: " + language);
    return;
}
 
context.complete({'output': footerPl});
```

### Data model

More information in [Data model API](https://docs.eximee.com/documentation/documentation-en/budowanie-aplikacji/model-danych/wykorzystanie-modelu-danych/api-modelu-danych.md)

### Saving data in the data model

In script tasks we can save data to the model using the 'complete' method; the first parameter saves data to the process, and the second parameter saves data to the model:

{% hint style="warning" %}
The model key must exist in the data model for the data to be saved correctly.
{% endhint %}

```js
function handle(task, context) {
    const branchId = task.getVariable('branchId');
    const isDocumentChangedRequired = task.getVariable('isDocumentChangedRequired');
    const documentsNotes = task.getVariable('documentsNotes');
 
    let modelUpdate = { "Ugoda.Adres.Oddzial": branchId, "Ugoda.CzyWymaganaZmianaTresciUmowy": isDocumentChangedRequired }
 
    if (isDocumentChangedRequired == "true") {
        modelUpdate['Ugoda.Uwagi'] = documentsNotes
    }
    context.complete({}, modelUpdate);
}
```

### Clearing a data model key

Clearing a key removes the values saved in the model under that key and in all of its child nodes. You can clear a field, an array, or a node with child fields, including a nested one. More information about these elements is available on the page [Data model structure](https://docs.eximee.com/documentation/documentation-en/budowanie-aplikacji/model-danych/struktura-modelu-danych.md).

To clear a key, assign it the value `complete` in the second parameter of the method `null`:

```js
function handle(task, context) {
    // Clear the obligations array and applicant data
    context.complete({}, {
        "kredyt.zobowiazania": null,
        "kredyt.wnioskodawca": null
    });
}
```

#### Reading after clearing

After clearing, a key is read in the same way as a key to which no value has ever been saved:

| Key                                                         | Reading after clearing                                                     |
| ----------------------------------------------------------- | -------------------------------------------------------------------------- |
| Field with a default value, with no other data source       | field default value                                                        |
| Field without a default value and with no other data source | empty text                                                                 |
| Array with no other data source                             | array with no elements                                                     |
| Field or array with another data source                     | value from this source                                                     |
| Node with child fields                                      | values of individual child fields and arrays, according to the rules above |

Clearing applies only to values saved in the model, i.e. in a data source of type **ValueMap**. Values retrieved from other data sources, e.g. from a service, remain unchanged. Therefore, an array also fed from another source is not empty after clearing. More information about data sources can be found on the page [Editing the data model](https://docs.eximee.com/documentation/documentation-en/budowanie-aplikacji/model-danych/edycja-modelu-danych.md#zrodlo-danych).

#### Specifying a key

The key is given as a dot-separated path, just like when reading from the model ([Data model API](https://docs.eximee.com/documentation/documentation-en/budowanie-aplikacji/model-danych/wykorzystanie-modelu-danych/api-modelu-danych.md)):

* An array can be specified with `[]` or without this notation: `kredyt.zobowiazania` and `kredyt.zobowiazania[]` clear the entire array. The key type follows from the data model definition.
* The parent array of the specified key can be indicated by `[]` or the element index: `kredyt.wnioskodawcy[].dochody` clears the incomes of all applicants, and `kredyt.wnioskodawcy[1].dochody` - only the income of the applicant at index 1 (the second on the list).
* Clearing applies to the specified node and its child nodes: `kredyt.wnioskodawca` does not clear the key `kredyt.wnioskodawcaDodatkowy`.
* You cannot clear a single array element: `kredyt.zobowiazania[2]` does not clear any values.

#### Write order

The method `complete` first clears the specified keys and then saves the remaining values from the same call. This allows you to clear existing values and save new ones in a single call, e.g. replace an entire array with new elements:

```js
context.complete({}, {
    "kredyt.zobowiazania": null,
    "kredyt.zobowiazania[0].bank": "Bank A",
    "kredyt.zobowiazania[0].kwota": "500"
});
```

After the task is finished, the array `kredyt.zobowiazania` contains one element with values bank: `Bank A` / `500`.

{% hint style="warning" %}
If the task ends with the method `handleFailure` or `handleBpmnError` or is interrupted by an exception before calling `complete`, no values will be cleared or saved.
{% endhint %}

#### A key that cannot be cleared

Specifying a key that does not exist in the data model definition, or using invalid notation, does not clear any values or interrupt the task. Invalid notation is for example `kredyt.zobowiazania[2]`, use `[]` on a field that is not an array, or providing a variable name instead of an element index.

#### What clearing does not include

Clearing is available only through the `complete` method in a script task. Emptying a field in a form does not clear the key - the form saves the empty text as a regular value. The object `api.model.v1` is used for reading only.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

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

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.eximee.com/documentation/documentation-en/budowanie-aplikacji/logika-biznesowa/scriptcode/zadanie-skryptowe-scripttask/api-zadan-skryptowych.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
