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
Section titled “The workflow”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: 1schemaVersion: 4sdk: '1.0.0'key: computed-fieldname: Feld berechnen und deklarierentemplate: customtrigger: documentType: incoming-invoicefields: - key: discountAmount kind: money labelDe: Skontobetrag labelEn: Discount amount documentTypes: - incoming-invoicestart: computesteps: - 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: rejectedThe script compute.ts
Section titled “The script compute.ts”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); },});What it does
Section titled “What it does”A test runs each of these cases in the sandbox and compares the result.
An invoice of €1,249.50
Section titled “An invoice of €1,249.50”- Input:
totalGross1249.5 - Exit: the default next step
- Changes: field
discountAmount=24.99
An invoice without a gross total
Section titled “An invoice without a gross total”- Input:
totalGrossnull - Exit: the default next step
- Changes: none
An amount that rounds up
Section titled “An amount that rounds up”- Input:
totalGross99.75 - Exit: the default next step
- Changes: field
discountAmount=2