Skip to main content

Node: Script

The Script node is a kind of "smart calculator" inside the Hashdata automation flow. Every time someone submits a form, the Script can read all the answers at once and turn that data into information ready to use. It adds up values, counts how many items failed, calculates deadlines and percentages, builds texts automatically and decides whether a situation is normal, deserves attention or requires immediate action. In an equipment checklist, for example, it identifies on its own which items failed, separates the critical ones from the simple ones, sets the priority and writes the description of the failure found. All of this happens in seconds, the moment the response arrives, without anyone having to open a spreadsheet, check item by item or type up a report.

The result of this calculation becomes raw material for the rest of the flow. The Script can decide which path the automation follows, for example blocking a piece of equipment and calling maintenance, or just recording that everything is fine. It can automatically fill in a Work Order in PDF, build the text of an email, choose who should receive each notice according to the unit or the person in charge, and even generate tables with the list of pending items for the body of the email or document. In practice, business rules that used to depend on someone's experience to be applied (what is serious, who needs to know, what must be done) are now applied the same way every time, in every unit, with full traceability. The team stops spending time organizing information and starts acting on it.


The Script node runs code that you write to calculate values from the data of previous nodes — form responses, approval results, outputs of other scripts. The results (text, number, list of emails or list of objects) can be used in the following nodes: in the text of emails, in conditions, in recipients, in the status, in the content of PDFs and in other text fields.

The node runs on its own, without waiting for any external action, and moves on as soon as the code finishes.


When to use​

Use the Script node when a value that the process needs does not exist ready-made in any form. Common examples:

  1. Calculations — sum items, count non-conformities, apply a discount, calculate a deadline, a percentage or a total amount from several responses.
  2. Classifying — set a status (for example, CLEARED, WARNING or BLOCKED) and a priority from rules with different weights.
  3. Building texts — compose a message, an email subject or the description of a Work Order with parts of different responses.
  4. Choosing recipients — return a list of emails that depends on the responses (for example, the manager of each branch).
  5. Tables in emails and PDFs — return a list of rows (item, quantity, value) to appear as a table in the body of the email or of the PDF.
  6. Deciding the path — calculate a number or a text to use as a condition in an If/Else node.
NeedRecommended feature
Show the answer to a field in an email or PDFRegular workflow variable
Simple condition on one or a few questionsIf/Else with source Question
Rule that combines many fields, with different criteriaScript + If/Else with source Script
Value shown to the respondent while filling in the formForm Calculated Field (Script)
Workflow Script × form calculated field

The calculated field runs while the form is being filled in and saves the result in the response itself (for example, avgByTag('r')*100 for a compliance percentage). The Script node runs after submission, reads the whole response and delivers values to the flow. The two complement each other: the calculated field informs whoever fills in the form, and the Script decides what the process does.

Programming knowledge required

The code is written in TypeScript in an editor with autocomplete. For simple rules, such as showing the answer to a field, prefer the regular workflow variables: the Script node is for when you need to calculate.


Before you start: prepare the form​

The Script reads the answers by the Field Name of each question. That is why the form must be ready before you configure the node.

The form must be ready before the Script

Configure all the questions of the form, with the Field Name filled in, and publish the form before creating the Script node. This way the test context and the autocomplete already include all the fields, and the script works as expected from the first test.

  1. Field Name on every question used by the script — in the form editor, under Element Attributes → Field Name. This name becomes the key of the question in the data the script receives.
  2. Naming pattern — use lowercase, no accents, no spaces and a fixed number of digits: item_01 … item_25, equipment, hour_meter. Text Display blocks do not get a name.
  3. Same meaning in every answer — in Yes/No checklists, write the questions so that "No" always means a failure. For example, "No water/oil leak" instead of "Water/oil leak".
  4. Value assigned to options — in Configure selection, turn on Assign value to items (for example, Yes = 1 and No = 0). This lets you compare by the text or by the value.
  5. Comment and photo per option — on the same screen, the Comm. and Photos switches can be turned on only for the "No" option. The operator records evidence only when there is a failure, and filling in the form becomes faster.
  6. Tags — if the form uses a calculated field by tag (for example, avgByTag('r')), keep the tag only on the questions that should count toward the average. Numeric fields, such as a battery level, should stay out of it.
  7. Publish the form.
Field Name is not a tag

The Field Name and the Tags sit side by side under Element Attributes, but they have different functions. A question without a Field Name reaches the script with an automatically generated key (for example, qt_6aedab461b8d267155213d55), even if it has a tag with the desired name. Calculated fields without a name also appear this way.


Configuration​

Click the node on the workflow editor canvas. The side panel has the Label field, three tabs, Inputs, Outputs and Test, and the Code area right below them. The shortcuts Alt+I, Alt+O and Alt+T switch tabs; they do not work while you are typing in a field or in the code editor.

  • Label — the name of the node on the canvas, in the variable picker (for example, "Classify checklist → status") and in the If/Else conditions. Use a verb that describes the calculation.
  • Minimum configuration — one input, one declared output and the calculateValue function returning that output.

Inputs — what the script reads​

Each input gives the script the data of one previous node of the workflow. Click Add input and fill in:

FieldDescription
TypeData (default) delivers the node's data; PDF delivers the link and the file name of the node's PDF. See PDF type input.
Previous nodeThe node the data comes from ("Select a previous node"). Only nodes that come before the Script in the flow appear. With the PDF type, only nodes that produce a PDF appear.
Variable nameThe name the code uses to access this data. See the naming rules.

In the code, the input arrives by its declared name, between the braces of the signature:

function calculateValue({ checklist }: Context): Result { ... }

If the name in the code is different from the input name, the editor underlines the variable in red.

What the script receives depends on the type of the selected node:

Previous nodeWhat the script receives
Form Response trigger, Request Form Response and Request Follow-UpThe form response, with one item per question (number, text, date, chosen options, etc.) and information about the response. The editor's autocomplete shows the real fields of the form. See Structure of a form response.
ApprovalThe node name, the approval result and the comment of whoever responded. Before the response, only the name.
Scheduled triggerThe node name and the scheduled time.
Trigger: Action Plan and Request Action PlanThe action plan data of that node.
Another Script nodeThe outputs that the other script returned. This is how a script uses the result of another, including lists of objects.
Other nodes (Wait, Send Email, Create PDF, etc.)The node name and the time the flow reached it.
Integration nodes cannot be inputs

Webhook, Slack, Teams, Google Sheets, Excel, Google Drive and OneDrive cannot be inputs, because they do not produce data for the script to read.

Data is read at execution time

The format of the data reflects what the previous node has at the moment the script runs. If the form changes later, the data received changes along with it. The action plan is the exception: its data is stored when the trigger fires or when the requested plan is created, and a later change to the plan does not reach the script.

Structure of a form response​

An input linked to a form trigger arrives with four parts:

{
"checklist": {
"formId": "6aed0730ca681f11ccb29a37",
"formName": "Inspection Checklist",
"response": {
"equipment": { "name": "equipment", "tags": [], "label": "EMP-01" },
"hour_meter": { "name": "hour_meter", "tags": [], "number": 1523.4 },
"item_01": { "name": "item_01", "tags": ["#r"], "label": "Yes", "number": 1 },
"item_02": { "name": "item_02", "tags": ["#r"], "label": "No", "number": 0, "comment": "Hose leaking" }
},
"metadata": {
"SURVEY_ID": "6aedb8e058d722c8a03b78a7",
"RESPONDENT_IS_ANONYMOUS": "0",
"RESPONSE_SUBMITTED_AT": "2026-11-06 11:24:16",
"N_OF_ATTACHMENTS": 1,
"TOTAL_TIME": 312,
"NET_TIME": 287,
"RESPONDENT_USER_ID": "69b16aa871cb3030b6523e72",
"RESPONDENT_EMAIL": "operator@company.com"
}
}
}
PartContent
formId / formNameIdentification of the form.
responseAn object with one key per question. The key is the question's Field Name.
metadataCollection data: collection ID, whether the response is anonymous, submission date and time (YYYY-MM-DD HH:MM:SS), number of attachments, total and net filling times, ID and email of the user who responded.

Each question inside response contains:

PropertyAppears inContent
nameAll questionsThe Field Name.
tagsAll questionsList of the question's tags, or an empty list.
labelSingle selectionThe text of the chosen option (for example, "Yes" or "No").
numberSelection with an assigned value, numeric fields and calculated fieldsThe value of the option (for example, 1 or 0), the number typed in or the result of the calculation.
commentQuestions that accept comments, when the respondent commentedThe comment, exactly as written. A comment made only of spaces counts as missing: comment does not appear.
Comment without a value

A question with a comment usually also has a value, because the form does not accept sending only the comment. The exception is changing the question type while discarding the values that do not convert: the old answer keeps only the comment and reaches the script as { name, tags, comment }, without label or number.

The comment reaches only the workflow Script node. The form's calculated field (Script or Formula) does not receive the comment of the answers.

See the exact format of any field

To check how a question type arrives, create a text output called structure and return JSON.stringify(checklist, null, 2). Insert this output into a test email sent only to you: it contains the complete response, exactly as the script receives it. Remove the output from the email once the flow is validated.

Read the answers safely

An unanswered question may not exist in response, and a question without a comment has no comment. Always use ?. and ?? when reading the fields, for example: answers["hour_meter"]?.number ?? 0 or answers["item_02"]?.comment ?? ''.

PDF type input​

With the PDF type, the script receives the PDF of the previous node instead of its data. The variable has two fields, both text:

  • url — the address of the PDF.
  • fileName — the file name.

The following can be the previous node: Form Response trigger, Trigger: Action Plan, Request Form Response, Request Follow-Up, Request Action Plan, Create PDF and Workflow History. With any other node, the input shows the error "This node does not produce a PDF" and the workflow cannot be published.

  • With the Create PDF and Workflow History nodes, the script receives the PDF that the node itself already generated.
  • With the others, the PDF is generated on each run of the script, which makes it take longer. The editor shows a notice when this happens. If another node in the same execution already generated that node's PDF (for example, an email with the response attached), it is reused: the PDF is generated only once.
  • If the chosen node did not run in this execution (for example, the other side of a condition), url and fileName arrive empty, and the Script history records the notice about a node that did not run.
  • If the PDF generation fails, the script does not run with an empty link: the instance ends with status Failed, as with a failure to read the form (see When the previous node did not run).

An email shows plain text as text, not as a link. For the link to be clickable, return the address in the format [label](url) in an output of type Text:

return { pdf: '[Open PDF](' + pdf.url + ')' };

Here pdf is the name of the input variable and also the name of the output. Returning only pdf.url makes the email show the address without a link. In the editor, when you type pdf., the PDF Markdown link suggestion inserts this expression ready to use. The [label](url) format is explained in Link and table in the email and PDF body.

Outputs — what the script returns​

Each output is a value that the script delivers to the following nodes. Click Add output, choose the Type and give it a name. There are four types:

TypeWhat it isWhere it can be used
TextA sentence or a word. A date returned as text arrives at the destination as text in ISO format (for example, 2026-03-01T10:00:00.000Z).Texts in general (emails, status, file name, PDF content) and conditions.
NumberA valid number. NaN and infinity are rejected.Texts in general and conditions.
Email listA list of email addresses.Recipients of the email nodes ("Add from a Script node").
Object listA table: each item of the list is a row, and you declare the attributes (columns), each of type Text or Number.Only in the body of an email or of a PDF, as a table, or as an input of another Script node.

Every declared output must come back in the script's result, with the declared type. If one is missing, comes with a different type, or if a row of a list lacks an attribute, the node fails and the message says which output or row caused the failure. Anything the script returns beyond the declared outputs is discarded.

  • The output name must be identical to the key used in the return. A key with no declared output is underlined in red in the editor.
  • The order of the outputs in the list does not matter.
  • If the declared name differs from the returned one, the test shows, for example: The output descripton does not have the declared type (received: undefined).
Object list only in the email and PDF body

The object list appears as a table in the body of the five email nodes: Approval, Send Email, Request Form Response, Request Follow-Up and Request Action Plan, and in the content of Create PDF. It does not work in the subject, the status, the PDF file name, nor in Slack, Teams, webhook, spreadsheet or Drive.

Code​

The code has a fixed structure rule: the calculateValue function must be the first thing in the code, with the signature below. Helper functions and constants go after it, never before.

function calculateValue({ order, approval }: Context): Result {
const total = calculateTotal(order);
return { total, summary: `Total: ${total}` };
}

function calculateTotal(order: Context['order']): number {
// helper functions go after calculateValue
return 0;
}
  • Between the braces of the signature, list the names of the inputs that the script uses (order, approval).
  • The function returns an object, with one key for each declared output.
  • Context and Result are types generated automatically from the inputs and outputs configured in the panel.
  • try/catch, throw and Error are allowed: use them to handle expected situations and return a default value.
  • Common JavaScript features work normally: ?., ??, template strings, filter, map, join, Number, String, JSON.stringify and constants declared at the end of the code.
  • Blocked words, which prevent the code from being saved: async, await, import, importScripts, eval, then, prototype, __proto__, setTimeout, setInterval, constructor, fetch and XMLHttpRequest. They also cannot be used as variable or property names. The script has no access to the internet, files or timers.
  • The code can have up to 100,000 characters.
  • A syntax error is reported with the line where it occurs, and the workflow cannot be published until the code compiles.
The code is compiled on the automatic save

The code is compiled when the draft is saved, which happens on its own every 30 seconds or when you close the node panel. If the warning "Code not compiled yet" appears, wait for the automatic save; if the warning persists, fix the syntax errors.

// Safe access to the form response
const answers: any = (checklist as any)?.response ?? {};
const meta: any = (checklist as any)?.metadata ?? {};

// Reading a number, with a default value
const hourMeter = Number(answers["hour_meter"]?.number ?? 0);

// Robust Yes/No: accepts the text or the option value
function isNo(resp: any): boolean {
if (!resp) return false;
const label = String(resp.label ?? "").trim().toLowerCase();
return label === "no" || resp.number === 0;
}
  • Separate configuration from logic — lists of items, weights, limits and registries go in constants at the end of the code (for example, ITEMS and BATTERY_LIMIT). To change the rule, just edit the constant.
  • Line breaks — use \n in texts. In the test result they appear literally as \n; in the email and in the PDF they become line breaks.
  • Status values — prefer uppercase values (BLOCKED, CLEARED). Conditions compare the exact text.

Naming rules​

NameRuleWhy
Input (variable name) and OutputOnly letters without accents, numbers and _; starts with a letter; up to 60 characters; cannot be a reserved JavaScript word (such as class or return) nor one of the blocked words of the code (such as then).The name becomes a variable in the code and a key used in the texts ({{script...}}). An accent, hyphen or space would break both.
Attribute of an object listFree (it can have spaces in the middle and accents), except the characters , " & < > }, and with no space at the start or the end.These characters interfere with the column list of the email table (,), the HTML text (& < > ") and the closing of the variable (}). Identical names in the same list are not accepted either.

Two inputs, or two outputs, cannot have the same name.


Using the results in the following nodes​

The outputs appear in the Script group of the variable picker of the text fields, and in two other places:

  • Texts — in the subject and body of the email nodes, in the status of the Set Status node, and in the file name and content of Create PDF. The value goes into the text in place of the variable.
  • Conditions — in a rule of type Script (node, output, operator and value). Outputs of type Text or Number work. On the arrow that leaves the Script itself, the rule can also use the outputs of that same Script. If the output changes type or is removed later, the rule shows "The output changed type or was removed. Review the output, the operator and the value of this rule."
  • Recipients — in the email nodes, Add from a Script node uses an output of type Emails. Repeated or invalid addresses are ignored, and what was discarded is recorded in the history.

Variable picker​

Every variable is inserted through the tag icon, in the text editor or to the right of the field. The picker shows a searchable tree:

  • Script node — by its label, with one item per output (for example, Classify checklist → status, priority, description).
  • Form — the Metadata folder (collection data) and the Questions folder (each question by its wording).

In the editor, the inserted variable appears as a blue pill. A variable that does not exist appears as a red pill.

Always insert variables through the picker

Text typed or pasted in the {{name}} format does not become a variable: it appears as a red pill and prevents the workflow from being published. Delete the red pills and insert the variables through the tag icon.

Respondent user contains the ID

In Metadata, the Respondent user variable contains the user's internal ID (for example, 69b16aa871cb3030b6523e72). To identify who responded in an email or a Work Order, use the respondent's email.

Conditions in If/Else​

  1. In Conditions, choose the source Script (the others are Question and Collection Metadata).
  2. In Script node, select the node by its label.
  3. Choose the output, the operator (for example, equal to) and the value (for example, BLOCKED).
  4. Press Tab or click outside the value field to register it. Until that happens, the field shows "Enter the complement".
Connect both If/Else outputs

The True and False outputs must be connected for the workflow to be published. When the False path has no action, connect it to a Set Status node (for example, "No critical failure").

  • A text in the format [label](url), in an output of type Text, becomes a clickable link in the email body and in the PDF content (only http and https addresses). In the subject and the other fields, the text appears as it was written.
  • An object list becomes a table in the email body and in the PDF content, with one column per attribute. The variable picker always includes the column list, in the order you select them. An empty list shows only the header.

Tips for the email and PDF editors​

  • The editors are rich text editors: headings, bold, colors, alignment, lists, images, tables and variables. The Load template (example) button shows a ready-made template with these features.
  • In the email, the paperclip on the toolbar attaches the PDFs generated by previous nodes, such as the one from Create PDF.
  • When you click a table, a toolbar appears for inserting and removing rows and columns, merging and splitting cells and deleting the table.
  • Tables placed right after one another merge into one. Separate each table with a line of text, such as the section title.
  • In the generated PDF, tables appear without borders. For forms such as a Work Order, prefer one field per line, in the format Label: value, with dotted lines for what will be filled in by hand.
  • Multi-line texts coming from the Script (such as a service description) look better in their own paragraph, outside a table.
  • The PDF file name also accepts variables, and the .pdf extension is added automatically.
User-typed text is safe

Texts coming from form responses, when they enter the email or the PDF through a script, do not run code or improper formatting: the content is shown as text.


Testing the script​

The Test tab, next to Inputs and Outputs, runs the script without triggering the workflow. It only appears for those who can edit the workflow:

  1. Click Load sample context. The Context field is filled with an example for each input, in the real format of the chosen node, using the forms that are on the screen.
  2. Adjust the values of the example for the case you want to simulate. In a form input, every question of the example has comment with the fictitious text Example comment: delete it to simulate an answer without a comment. In an input of the PDF type, the example has fictitious url and fileName (https://example.com/document.pdf and document.pdf): the test generates no PDF. If you add or rename an input later, the missing keys are added to the context when you run, without losing what you already edited.
  3. Click Run. The Result appears beside it, or the error message, if any.
Simulate each scenario by editing the context

The sample context comes with default values: the first option of each question and fixed numbers. To test a failure, edit the JSON directly. For example, to mark item 22 as "No":

"item_22": { "name": "item_22", "tags": ["#r"], "label": "No", "number": 0 }

If a new form field does not appear in the example yet, add it to the context by hand. Keep one context for each scenario (cleared, warning, blocked) and run all of them after every change to the code.

Points of attention:

  • The test uses the code that is on the screen, without needing to save the draft first. Syntax errors, signature errors or blocked words appear in the Result.
  • The test and the real execution have the same limit of 10 seconds per execution, and 64 MB of memory. Exceeding the time shows "The script exceeded the 10-second limit".
  • The server accepts 2 tests at the same time. If there are more, "Too many tests are running. Wait a few seconds and try again" appears: just try again. The tests never delay the scripts of running workflows, which have their own slots.
  • If the Context is not valid JSON, "The provided context is not valid JSON." appears. Check the commas and quotes, and whether the pasted text is complete.
  • The Context can be up to 256 KB. Above that, "The test context exceeds the 256 KB limit" appears, and the test does not even start.
  • Keyboard shortcuts, such as Cmd+A or Ctrl+A, act on the box where the cursor is. Click inside Context or Code before selecting everything.
  • In the Result, line breaks appear as \n, and texts generated with JSON.stringify appear with \". This is only how they are displayed.

Publishing​

When you click Publish, the editor validates the whole workflow and lists the inconsistencies found. Nodes with pending issues get a red border on the canvas, and the warning appears at the top of the node panel.

MessageWhat to do
"IF/ELSE without a configured False transition"Connect the False output of the If/Else to a node.
"A template uses a variable that does not exist or an unsupported syntax. Blocks and helpers only apply to SCRIPT outputs (script.*); for the other variables, use only those inserted through the variable picker"Delete the red pills and insert the variables through the picker. One message appears per variable.
"This node does not produce a PDF"In the PDF type input, choose a node that produces a PDF.
"Code not compiled yet"Wait for the automatic save or fix the syntax.
Check the save before continuing

The top of the editor shows "Draft saved at…". If "Automatic save paused" appears, fix the pending field (for example, a condition value not registered yet) and click Try again before adding new nodes. If a node is deleted by mistake, the Undo button on the editor toolbar brings it back.


When the script fails​

If the script exceeds 10 seconds or 64 MB, throws an unhandled error, returns an output with the wrong type, or returns a result larger than 256 KB, the node fails. As a result:

  • The instance gets the status Failed, and the workflow owner receives an email about it, with the link to see the events.
  • The error appears in the instance history, with the cause (for example, which output or row was wrong).
  • The script's input data is not sent to error monitoring tools nor recorded in the server log, because it may contain form responses.
Handle what is expected

Use try/catch for predictable cases (empty field, division by zero) and return a default value. This way the instance moves on instead of failing.


When the previous node did not run​

The workflow only guarantees that there is a path from the previous node to the Script, not that the node has already run. This happens, for example, when the Script reads a node from the other side of an If/Else, or when an approval has not been answered yet.

In these cases the data arrives empty (the input arrives as an object with no data, the text appears blank; in a PDF type input, url and fileName arrive empty and no PDF is generated for that node; a node that started and failed also counts as not run), and the node that read the data shows in the instance history the warning "Empty data from nodes that had not run yet", with the name of each node. The workflow does not fail because of this: handle the empty case in the code.

An action plan node may have run and still deliver an empty object: when the plan could not be read, or when the problem or the action that started the flow was removed before the workflow stored its data. In that case the history shows the warning "Unavailable data from nodes that ran before", with the name of the node, and the workflow also carries on.

This is different from a failure to read the form or the response, or to generate the PDF of a PDF input (for example, a momentary outage of the database or of file storage): in that case the script does not run with empty data. The instance gets the Failed status, the workflow owner receives the warning email, and the error appears in the history as a script failure.


Complete example: inspection checklist with Work Order​

A forklift inspection checklist with Yes/No items, some of which are critical. If any critical item fails, the equipment is blocked and a Work Order in PDF is sent to maintenance.

Flow​

  1. Trigger: Form Response "Checklist received", firing only on New response — this way, editing a response does not generate a new Work Order.
  2. Script "Classify checklist".
  3. If/Else "Critical failure": source Script, status equal to BLOCKED.
  4. True output:
    1. Set Status — "Blocked – awaiting maintenance".
    2. Create PDF — the Work Order template, with the Script variables.
    3. Send Email — to maintenance, with description in the body and the PDF attached.
  5. False output: Set Status — "No critical failure".

Classification rule​

StatusConditionPriority
BLOCKEDAt least one critical item with "No".1
WARNINGNo critical item failed, but at least one regular item with "No" (or battery below the limit, when defined).2
CLEAREDAll items with "Yes".3

Node configuration​

  • Input: node "Checklist received", with the variable checklist.
  • Outputs:
OutputTypeContent
statusTextBLOCKED, WARNING or CLEARED.
priorityNumber1, 2 or 3.
descriptionTextDescription of the services, with the failed items.
critical_nc_countNumberNumber of critical items that failed.
nc_countNumberTotal number of items that failed.
battery_levelNumberReported charge level.
work_order_numberTextWork Order number, generated from the submission date and time.
equipmentTextEquipment chosen in the form.
locationTextLocation of the equipment, from the registry in the code.
managerTextManager of the equipment, from the registry in the code.
extensionTextPhone extension, from the registry in the code.
hour_meterTextFormatted hour meter (for example, "1523.4 h").
checklist_dateTextDate and time of the checklist (for example, "06/11/2026 10:36").
structureTextDiagnostics: the complete response. Remove from the emails after validating.

Code​

function calculateValue({ checklist }: Context): Result {
const answers: any = (checklist as any)?.response ?? {};
const meta: any = (checklist as any)?.metadata ?? {};

// Classification
const nonCompliant = ITEMS.filter(item => isNonCompliant(answers[item.id]));
const criticalNC = nonCompliant.filter(item => item.critical);

const batteryLevel = Number(answers["item_18"]?.number ?? 0);
const lowBattery = BATTERY_LIMIT !== null && batteryLevel < BATTERY_LIMIT;

const status = criticalNC.length > 0 ? "BLOCKED"
: (nonCompliant.length > 0 || lowBattery) ? "WARNING"
: "CLEARED";

const priority = status === "BLOCKED" ? 1 : status === "WARNING" ? 2 : 3;

// Description of the services
const header = status === "BLOCKED"
? "AUTOMATIC BLOCK: Critical Failure Detected"
: status === "WARNING" ? "WARNING: Non-critical failure detected" : "";

const lines = nonCompliant.map(item => `- ${item.num} - ${item.name}`);
if (lowBattery) lines.push(`- 18 - Battery charge level (${batteryLevel}%)`);

const description = lines.length
? `${header}\n\nCHECKLIST ITEMS WITH FAILURE:\n${lines.join("\n")}`
: "No non-conformity recorded.";

// Work Order identification
const equipment = String(answers["equipment"]?.label ?? "").trim();
const record = REGISTRY[equipment] ?? { location: "", manager: "", extension: "" };

const submittedAt = String(meta.RESPONSE_SUBMITTED_AT ?? ""); // "2026-11-06 10:36:32"
const work_order_number = submittedAt ? "WO-" + submittedAt.replace(/\D/g, "") : "";

const hourMeterNum = answers["hour_meter"]?.number;
const hour_meter = hourMeterNum !== undefined && hourMeterNum !== null && hourMeterNum !== ""
? `${hourMeterNum} h`
: "";

return {
status,
priority,
description,
critical_nc_count: criticalNC.length,
nc_count: nonCompliant.length,
battery_level: batteryLevel,
work_order_number,
equipment,
location: record.location,
manager: record.manager,
extension: record.extension,
hour_meter,
checklist_date: formatDate(submittedAt),
structure: JSON.stringify(checklist, null, 2)
};
}

function isNonCompliant(resp: any): boolean {
if (!resp) return false;
const label = String(resp.label ?? "").trim().toLowerCase();
return label === "no" || resp.number === 0;
}

function formatDate(dateTime: string): string {
// "2026-11-06 10:36:32" -> "06/11/2026 10:36"
const m = dateTime.match(/^(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2})/);
return m ? `${m[3]}/${m[2]}/${m[1]} ${m[4]}:${m[5]}` : dateTime;
}

const BATTERY_LIMIT: number | null = null; // e.g.: 20 to require at least 20%

// Equipment registry: the key must be IDENTICAL to the option text in the form
const REGISTRY: Record<string, { location: string; manager: string; extension: string }> = {
"EMP-01": { location: "Shipping", manager: "Manager Name", extension: "1234" },
"EMP-02": { location: "Cold room", manager: "Manager Name", extension: "1235" }
};

const ITEMS = [
{ id: "item_01", num: 1, name: "Water/oil leak", critical: true },
{ id: "item_02", num: 2, name: "Hoses", critical: false },
{ id: "item_03", num: 3, name: "General paintwork", critical: false },
{ id: "item_04", num: 4, name: "Material stuck in wheels", critical: false },
{ id: "item_05", num: 5, name: "Front/rear wheels", critical: false },
{ id: "item_06", num: 6, name: "Mast chains", critical: true },
{ id: "item_07", num: 7, name: "Seat belt", critical: true },
{ id: "item_08", num: 8, name: "Fire extinguisher", critical: false },
{ id: "item_09", num: 9, name: "Air conditioning system", critical: false },
{ id: "item_10", num: 10, name: "Protective acrylic/glass", critical: false },
{ id: "item_11", num: 11, name: "Pedals/Joystick/Controls", critical: true },
{ id: "item_12", num: 12, name: "Horn and headlight", critical: true },
{ id: "item_13", num: 13, name: "Brake and steering wheel", critical: true },
{ id: "item_14", num: 14, name: "Mirrors", critical: false },
{ id: "item_15", num: 15, name: "Rotating beacon", critical: false },
{ id: "item_16", num: 16, name: "Reverse alarm", critical: false },
{ id: "item_17", num: 17, name: "Error code on the panel", critical: false },
{ id: "item_19", num: 19, name: "Brake light", critical: false },
{ id: "item_20", num: 20, name: "Panel warning light", critical: false },
{ id: "item_21", num: 21, name: "Steering", critical: true },
{ id: "item_22", num: 22, name: "Mast", critical: true },
{ id: "item_23", num: 23, name: "Inching pedal", critical: true },
{ id: "item_24", num: 24, name: "Safety guards", critical: false },
{ id: "item_25", num: 25, name: "Safety pedal or tiller", critical: true }
];
Registry inside the code

The operator chooses only the equipment in the form. The location, the manager and the extension come from the REGISTRY constant, which avoids typing errors and makes the checklist faster. The key of each piece of equipment must be identical to the option text in the form, including spaces, hyphens and slashes.

List names describe the failure

In the ITEMS constant, the names describe the failure ("Water/oil leak"), not the form question ("No water/oil leak"). This way the Work Order description is clear to whoever will carry out the service.

Test result​

With the equipment EMP-01, the hour meter 1523.4 and items 3 and 22 marked as "No":

OutputValue
statusBLOCKED
priority1
critical_nc_count1
nc_count2
work_order_numberWO-20261106103632
locationShipping
hour_meter1523.4 h
checklist_date06/11/2026 10:36

description:

AUTOMATIC BLOCK: Critical Failure Detected

CHECKLIST ITEMS WITH FAILURE:
- 3 - General paintwork
- 22 - Mast

Possible improvements​

  • Table of items in the Work Order — replace description with an Object list output (attributes Item, Description, Critical). The Work Order in the PDF and in the email then shows a table.
  • Recipients by unit — return an Email list output with the person in charge of each piece of equipment and use it in Add from a Script node.
  • Warning path — on the False output, add a second If/Else with status equal to WARNING, to request scheduled maintenance with Request Action Plan.
  • Digital execution and release — after the email, use Request Form Response for maintenance to record the service, Approval for the manager to validate it and a second Create PDF to generate the closed Work Order.
  • More safety — wrap the calculation in try/catch and return status = "ERROR" with a description, so the instance moves on.

Common errors and solutions​

What appearsCauseSolution
Signature variable underlined in redInput without a name, or with a different name.Make the Variable name match the name used in the code.
return key underlined in redOutput not declared.Declare the output with the same name and the right type.
Calculated value does not appear in the ResultOutput not declared: anything not declared is discarded.Declare the output on the Outputs tab.
"The output X does not have the declared type (received: undefined)"Output name different from the return key.Fix one of the two names.
"calculateValue is not defined"Code area empty or without the function.Paste the complete code, starting with calculateValue.
response empty or missing a field in the test contextQuestion without a Field Name, or form not published.Fill in the Field Name and publish the form before creating the Script; if needed, add the field to the context by hand.
Field arrives with a qt_... keyQuestion without a Field Name (the name was put in Tags).Fill in the Field Name and remove the tag.
Inverted classification on a questionQuestion where "Yes" indicates a failure.Rewrite the question so that "No" always indicates a failure.
Sample context always without failuresThe example uses default values.Edit the context manually.
"Code not compiled yet"Draft not saved yet.Wait for the automatic save; if it persists, fix the syntax.
Code is not savedBlocked word (then, fetch, async…).Remove or rename it.
"The script exceeded the 10-second limit"Heavy calculation or endless loop.Simplify the logic.
"The provided context is not valid JSON."Misplaced comma or quote, or incomplete pasted text.Fix the JSON or paste the whole block again.
"Enter the complement" (If/Else)Condition value not registered.Press Tab or click outside the field.
"IF/ELSE without a configured False transition"False output not connected.Connect the False output to a node.
Red pill in a templateVariable typed by hand or from a field that does not exist.Insert it through the variable picker.
Requester appears as a code in the PDFRespondent user variable, which contains the ID.Use the respondent's email.
Merged tables or tables without borders in the PDFTables placed one after another; the PDF does not draw borders.Separate them with a line of text or use one field per line.
"The output changed type or was removed…"Output changed after being used in a condition.Review the condition rule.
Instance with status FailedUnhandled error, wrong type, time, memory or size limit, or failure to read the data.Check the instance history and handle the predictable cases with try/catch.

Step-by-step guide​

  1. Form — fill in the Field Name of every question used, standardize the meaning of the answers, assign values to the options and publish.
  2. Node — with the form ready, create the Script, connect it to the previous node and give it a label with a verb.
  3. Input — choose the previous node and give it a valid variable name.
  4. Diagnostics — create the structure output (Text) with JSON.stringify(input, null, 2), load the context and check that response contains all the fields.
  5. Outputs — declare each output with the exact name and the correct type.
  6. Code — calculateValue first, reading with ?. and ??, rules and registries in constants at the end, no blocked words, try/catch for the predictable cases.
  7. Tests — one context per scenario, including empty fields and extreme cases.
  8. Following nodes — variables always through the picker (blue pill), both If/Else outputs connected, condition values identical to those returned by the code.
  9. Publishing — resolve all the inconsistencies and run the first real test with an internal recipient, with the structure output in the email body.
  10. Final adjustment — remove structure from the emails and replace the test recipients with the final ones.

Best Practices​

  • Use names that explain the value: order_total and manager_emails help more than x and list.
  • Declare only the inputs you use: the script receives only what you configured, and this keeps the autocomplete cleaner.
  • Prepare the form first: Field Name filled in on every question and the form published before creating the Script.
  • Test before publishing: use Load sample context, adjust the values with extreme cases (empty field, empty list, all items failing) and run.
  • Keep the script short: each script should calculate a set of values. For different steps, chain two Script nodes.
  • Separate rule and configuration: lists, weights, limits and registries in constants make adjustments easy without touching the logic.
  • Combine with the Set Status node: a status on each path helps you know, in the instances panel, which step the instance is in and which decision the Script made.