Skip to content

Compute and declare a field

The workflow adds the field discount amount to incoming invoices, and its script computes it: 2 % of the gross total, rounded to the cent. This is how a coded workflow adds a field your document types don’t have yet, and fills it at once.

The workflow starts for every document of the type incoming-invoice. Its file workflow.yaml:

$schema: 'https://docs.acriva.de/schemas/workflow.schema.json'
format: 1
schemaVersion: 4
sdk: '1.0.0'
key: computed-field
name: Feld berechnen und deklarieren
template: custom
trigger:
documentType: incoming-invoice
fields:
- key: discountAmount
kind: money
labelDe: Skontobetrag
labelEn: Discount amount
documentTypes:
- incoming-invoice
start: compute
steps:
- kind: script
name: compute
label: Skontobetrag berechnen
script: compute.ts
hook: onDocumentArrived
inputs:
- kind: field
key: totalGross
type: money
returns: []
exits: []
next: approve
- kind: humanTask
name: approve
label: Freigabe
taskKind: approve
assignees:
- when: null
assignee:
kind: costCenterResponsible
fallback:
kind: role
role: Buchhaltung
options:
excludeRequester: true
excludeActorsOfSteps: []
pickFile: false
next: approved
onRejected: rejected
- kind: end
name: approved
label: Freigegeben
outcome: approved
- kind: end
name: rejected
label: Zurückgewiesen
outcome: rejected

Hook: onDocumentArrived · Inputs: totalGross · Return values: none

import { defineScript, money } from '@acriva/workflow-sdk';
/** The early-payment discount, as a share of the gross total. */
const DISCOUNT_RATE = 0.02;
export default defineScript({
hook: 'onDocumentArrived',
run(ctx) {
const total = ctx.document.fields.totalGross;
// Without a gross total there is nothing to compute, and the field stays empty.
if (total == null) return;
// money.round rounds half away from zero to cents: 1.995 becomes 2.00.
const discount = money.round(total * DISCOUNT_RATE);
ctx.log('Discount', money.format(discount));
ctx.setField('discountAmount', discount);
},
});

A test runs each of these cases in the sandbox and compares the result.

  • Input: totalGross 1249.5
  • Exit: the default next step
  • Changes: field discountAmount = 24.99
  • Input: totalGross null
  • Exit: the default next step
  • Changes: none
  • Input: totalGross 99.75
  • Exit: the default next step
  • Changes: field discountAmount = 2