Skip to content

Coding Reports

This guide is for whoever writes the code of a report: the structure of the .ht file, the onInit script, the Handlebars template, helpers and partials. It describes the language, not the tools.

{
"editor_type": "report_v2",
"label": "Equipment record",
"description": "Data sheet of a piece of equipment.",
"target": ["equipment"],
"country": [],
"lang": ["en-GB"],
"tags": [],
"output_type": "html",
"template": "<html>...<h1>{{equipment.name}}</h1>...</html>",
"script": "async function onInit() { ... }",
"helpers": "var helpers = {}",
"partials": {}
}
KeyTypeDescription
editor_typestringAlways "report_v2".
labelstringRequired. Name of the report.
descriptionstringOptional description.
targetstring[]Launch points of the report (see Launch points).
countrystring[]ISO 3166-1 alpha-2 codes (IT, GB…).
langstring[]App locales (it-IT, en-GB, es-ES, de-DE, fr-FR).
tagsstring[]Free classification, for example a family such as iso-45001. The format rules are in Report Editor.
output_typestringhtml (default), csv or text. See Printing and exporting.
templatestringHTML + Handlebars. Its context is the object returned by onInit().
scriptstringJavaScript defining async function onInit(), which loads the data.
helpersstringJavaScript defining var helpers = { ... }: report-specific Handlebars helpers.
partialsobjectOther files included in the template (see Partials).

The report loads its own data. script defines an async function onInit(); whatever it returns becomes the context of the template: if it returns { equipment, office }, the template uses {{equipment.name}}.

Inside onInit, this gives you:

  • this.runtime.context: where the report was launched from, {} when there is no entity

    KeyContent
    entity_idid of the entity the report is printed from
    entity_typeits type, uppercase (EQUIPMENT, OFFICE, CERTIFICATE…)
    office_id, office_countrythe office of the entity (or the entity itself, if it is an office)
    project_id, project_countrythe project
    unit_id, unit_countrythe unit / supplier, if any
  • this.runtime.target: the launch point (e.g. office.equipment_list), null when unknown

  • this.fetchAll(url, options): calls a paginated v2 index endpoint and returns all the rows

Data comes from the REST API v2, called with the session of the logged-in user. Use relative URLs (no leading /):

  • one record: fetch('v2/<resource>/view?id=' + id) (the view/<id> form does not exist)
  • a list: this.fetchAll('v2/<resource>/index', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ filter: { office_id: id } }) })
async function onInit() {
const entityId = this.runtime.context.entity_id;
const officeId = this.runtime.context.office_id;
const result = { equipment: {}, office: {} };
if (!entityId) {
return result;
}
const equipmentResponse = await fetch('v2/equipment/view?id=' + entityId);
if (equipmentResponse.ok) {
result.equipment = await equipmentResponse.json();
}
if (officeId) {
const officeResponse = await fetch('v2/office/view?id=' + officeId);
if (officeResponse.ok) {
result.office = await officeResponse.json();
}
}
return result;
}
  • Name and form. The script must define a function named onInit, normally async. If there is no such function, the script does nothing and the template renders with no data. onInit takes no arguments: everything it needs comes from this.
  • Strict mode, private declarations. The script runs in strict mode. What it declares (constants, functions) is visible only to the script itself: it does not leak into the page and the template or the helpers cannot see it. You can declare other functions and constants next to onInit, or inside it, and use them from it. The globals of the page (window, fetch, URL…) are available.
  • this is only available directly in onInit. It exposes exactly two things: runtime and fetchAll. A function declared next to onInit does not receive it: pass this.runtime or the values you need as arguments. Arrow functions written inside onInit keep this as usual.
  • The return value is the template context. If onInit returns an object, its keys are merged into the data of the template. Return a plain object: undefined and other non-object values are ignored, and an array would be merged key by key (0, 1…), which is never what you want.
  • Reserved key partials. The data object holds the partials under the key partials. Do not return a key with that name from onInit.
  • Partials do not run scripts. If a partial is a .ht file, only its template is used: its own script is not executed. The data of a partial must be returned by the onInit of the report that includes it.

fetch is the browser fetch, with the session of the logged-in user: the report sees exactly what the user can see. Keep in mind:

  • fetch does not fail on an HTTP error (403, 404, 500…): it returns a response with ok set to false. Always check response.ok before reading the body, as in the example above.
  • this.fetchAll(url, options) takes the same arguments as fetch and returns the array of all the rows, already parsed. It adds the page query parameter itself and requests the pages one after another until it has collected X-Pagination-Total-Count rows or a page comes back empty. Do not add page yourself.
  • fetchAll throws an error if a page answers with an HTTP error, and the whole run stops. Wrap the call in try / catch when a list is optional.
  • fetchAll expects an index endpoint that answers with an array. Use plain fetch for view endpoints.
  • fetchAll requests the pages of one list one after another. To avoid a request per row, load the children of a whole scope with one call and group them in the script (see below).
async function onInit() {
const officeId = this.runtime.context.office_id;
const result = { equipment: [] };
if (!officeId) {
return result;
}
try {
result.equipment = await this.fetchAll('v2/equipment/index', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ filter: { office_id: officeId } })
});
} catch (error) {
result.equipment = [];
}
return result;
}
  • if data is missing, return empty structures ({}, []) instead of throwing: the template must render anyway;
  • keep user-facing text in the template, not in the script (the script is the same in every language);
  • when a report has several targets, tell the cases apart with this.runtime.context.entity_type;
  • prepare the data in onInit (filter, group, sort, compute totals) and keep the template for the layout: Handlebars is deliberately poor in logic;
  • avoid one request per row (for example one view for each person of a list): load the whole list with one index filtered on the scope (office_id, subtenant_id…) and match the rows by id in the script;
  • filters support operators, for example { filter: { work_group_id: { in: [1, 2, 3] } } }.

The template is HTML with CSS and Handlebars:

  • static content: text, images, layout, <style> rules (including @page for paper size and margins);
  • dynamic content: expressions such as {{equipment.name}}, blocks such as {{#each}}, {{#if}}, and helpers.
<html>
<head>
<meta charset='utf-8'>
<style>
@page { size: A4 portrait; margin: 1.5cm; }
table th { font-weight: bold; }
</style>
</head>
<body>
<h1>{{equipment.name}}</h1>
<p>{{office.name}}</p>
<table>
<thead>
<tr><th>Surname</th><th>Name</th></tr>
</thead>
<tbody>
{{#eachSort equipment.entityEmployee "last_name"}}
<tr><td>{{last_name}}</td><td>{{first_name}}</td></tr>
{{/eachSort}}
</tbody>
</table>
<p>{{today}}</p>
</body>
</html>

See the Handlebars guide for expressions and built-in helpers (if, unless, each, with…).

4HSE registers these helpers for every report: dateFormat, today, t, eachSort, sum, prod, eq, ne, lt, gt, lte, gte, and, or, distinct, select, join, qr, logo4hse, eachHcs, hc. The most common ones:

dateFormat(dateString)
Starting from a date in the yyyy-mm-dd format, it returns the date formatted according to the user’s language. If the value is missing, it prints a blank line (____________) to be filled in by hand, which is handy in printed forms.

{{ dateFormat "2010-10-05" }} // User language: it-IT, returns 05/10/2010

t(namespace, key)
Returns a translation of the app in the user’s language, for example a label that is already translated in 4HSE.

{{t "common" "select"}} // User language: it-IT, returns Seleziona

qr(text) draws a QR code, logo4hse the 4HSE logo. Both return SVG markup, so they must be written with triple braces, otherwise Handlebars shows the tags as text (see Escaping).

{{{qr verifyUrl}}}
{{{logo4hse}}}

today()
Returns the current date formatted according to the user’s language.

{{ today }} // 05/10/2020

eachSort(context, sortAttribute, direction, options)
Iterates a collection of resources ordered by an attribute in ascending or descending order ("asc" or "desc", ascending by default). Example: scroll through the entire collection of offices ordering them in ascending order office1, office2 as in the example below.

The attribute can be a path ("person.last_name"). The values are compared as text, so 10 comes before 9: to sort by a number, sort in onInit. The collection itself is sorted, not a copy.

//offices = [{name: "office3"},{name: "office1"}]
{{#eachSort offices "name" "asc"}}
{{name}} // office1,office3
{{/eachSort}}

sum(v1, v2)
Sums v1 and v2. Addition of two numbers that returns a result. If a value is a string, the two are joined instead ("1" and "2" give "12"): convert the values to numbers in onInit when they come from the API.

{{sum 1 2}} // 3

prod(v1, v2)
Multiplication between v1 and v2.

{{prod 3 2}} // 6

eq(v1, v2)
Compares if v1 is equal to v2. Returns a boolean value. The comparison is strict: 1 and "1" are different (ne is strict too). Check the type of the values you get from the API before comparing them. lt, gt, lte and gte compare strings in alphabetical order.

{{eq "1" "2"}} // false
{{eq "2" "2"}} // true

ne(v1, v2)
Compares if v1 is different from v2. Returns a boolean value.

{{ne "1" "2"}} // true
{{ne "2" "2"}} // false

lt(v1, v2)
Compares if v1 is less than v2. Returns a boolean value.

{{lt "1" "2"}} // true
{{lt "2" "2"}} // false
{{lt "3" "2"}} // false

gt(v1, v2)
Compares if v1 is greater than v2. Returns a boolean value.

{{gt "1" "2"}} // false
{{gt "2" "2"}} // false
{{gt "3" "2"}} // true

lte(v1, v2)
Compares if v1 is less than or equal to v2. Returns a boolean value.

{{lte "1" "2"}} // true
{{lte "2" "2"}} // true
{{lte "3" "2"}} // false

gte(v1, v2)
Compares if v1 is greater than or equal to v2. Returns a boolean value.

{{gte "1" "2"}} // false
{{gte "2" "2"}} // true
{{gte "3" "2"}} // true

and(cond1, cond2, …​ condN)
Executes a logical AND between two or more conditions. Returns a boolean value.

or(cond1, cond2, …​ condN)
Executes a logical OR between two or more conditions. Returns a boolean value.

and, or and the comparison helpers return a value, so they are used inside {{#if}} as sub-expressions, in parentheses:

{{#if (and (gt quantity 0) (eq status "VALID"))}}
In use
{{/if}}

distinct(list, key)
Starting from a collection, it returns a list of unique resources based on the value of an attribute (key). When several resources have the same value, the first one is kept.

select(path)
Looks into the current data following a path and keeps only the elements where the last attribute of the path has a value. In the path, * stands for “each element of the list”. The result is a copy: the original data is not changed.

With officeRisk a list of risks, each with a list riskDemand:

{{select "officeRisk.*.riskDemand.*.probability"}}

returns the risks that have at least one riskDemand, and in each risk only the riskDemand where probability is filled.

join(list1, list2, …​, listN, key)
Joins two or more collections into one. If the last argument is a string, it is used as distinct does: the elements with the same value of that attribute appear only once.

{{#each (join people suppliers "id")}}
{{name}}
{{/each}}

In this example, an array based on the officeRisk collection ordered by name is iterated. The iterable array is obtained by combining the distinct, join, and select directives.

{{#eachSort // 1
(distinct // 3
(join // 4
(select "officeRisk.*.riskDemand.*.probability") // 5
(select "officeRisk.*.riskDemand.*.damage") // 6
)
"office_risk_id" // 3
)
"name" // 2
}}
  1. Iterator.

  2. Sorts an array of objects by the name attribute.

  3. Excludes from iteration all objects with the same office_risk_id (to avoid duplicates).

  4. Joins two collections into one.

  5. The first collection is officeRisk. From this collection, it selects only the objects where the officeRisk.riskDemand attribute is filled and office.riskDemand.probability is filled.

  6. The second collection is still officeRisk but selects only the objects where the officeRisk.riskDemand attribute is filled and office.riskDemand.damage is filled.

Handlebars turns the characters <, >, & and quotes of every value into text, so that data cannot change the page: {{description}} shows <b>x</b> as it is written. To print HTML, write the expression with triple braces, {{{html}}}. Do it only for markup you control (such as the output of qr and logo4hse), never for text entered by users.

Helpers needed by a single report go in its helpers field:

var helpers = {
fullName(person) {
return person.last_name + ' ' + person.first_name;
}
}
{{ fullName person }}

A helper is a function that receives the values written after its name. The last argument is always an options object added by Handlebars: for a block helper ({{#name}}...{{/name}}) options.fn(context) renders the content of the block. this is the current context. A helper that returns HTML must wrap it in new Handlebars.SafeString(html), or the tags are shown as text.

A partial is a piece of template kept in its own file and included in the report (see Partials for what it is and when to use it).

Declare the partials in partials, mapping the alias (the name used in the template) to the file:

"partials": {
"header": { "path": "/projects/<project_id>/templates/header.ht", "name": "header.ht" }
}

Then include it where you want the piece to appear:

{{> header}}
<h1>{{equipment.name}}</h1>

How it works:

  • the file can be a .ht, an .html or a .hdoc. From a .ht only the template is taken, and its own script and helpers are not run; from an .html or .hdoc the whole content is taken;
  • the partial is rendered with the data of the place where it is included. It has no data of its own: it uses the keys returned by the onInit of the report, so a header that prints {{office.name}} needs a report that returns office;
  • the partial can use the helpers of the report, but it cannot declare its own;
  • the files are read every time the report is generated, so a change to the file is used at the next run;

In the editor, partials are added in the Partials tab: see Report Editor.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.