Zum Inhalt springen

Feld berechnen und deklarieren

Der Workflow legt für Eingangsrechnungen das Feld Skontobetrag an, und sein Skript berechnet es: 2 % des Bruttobetrags, auf den Cent gerundet. So ergänzen Sie mit einem programmierten Workflow ein Feld, das Ihre Dokumenttypen noch nicht haben, und füllen es zugleich.

Der Workflow startet für jedes Dokument vom Typ incoming-invoice. Seine Datei 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 · Eingaben: totalGross · Rückgaben: keine

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);
},
});

Ein Test führt jeden dieser Fälle in der Sandbox aus und vergleicht das Ergebnis.

  • Eingabe: totalGross 1249.5
  • Ausgang: der Standard-Nachfolger
  • Änderungen: Feld discountAmount = 24.99
  • Eingabe: totalGross null
  • Ausgang: der Standard-Nachfolger
  • Änderungen: keine
  • Eingabe: totalGross 99.75
  • Ausgang: der Standard-Nachfolger
  • Änderungen: Feld discountAmount = 2