Define a Custom Addition Function

This DataWeave example takes in a set of item prices and stock amounts and uses several functions to calculate subtotals, deduct discounts and add taxes. Before you begin, note that 2.x versions of DataWeave are used by Mule 4 apps. For DataWeave in Mule 3 apps, refer to DataWeave version 1.2 examples. For other DataWeave versions, you can use the version selector in the DataWeave table of contents.

It makes use of the following:

  • map function to go through all the items in the input.

  • basic math operations like *, + and -.

  • String concatenation with ++.

  • as to force string values into numbers.

  • Fixed values in the header to set tax and discount amounts.

  • A custom function in the header, to define once and use multiple times in the code.

  • reduce function to aggregate the various items into a total.

DataWeave Script:
%dw 2.0
output application/json
var tax = 0.085
var discount = 0.05
fun getSubtotal (items) = items reduce ((item, accumulator = 0) ->
        accumulator + (item.unit_price * item.quantity * (1 - discount)))
---
invoice: {
    header: payload.invoice.header,
    items: { (payload.invoice.items map {
        item : {
            description: $.description,
            quantity: $.quantity,
            unit_price: $.unit_price,
            discount: (discount * 100) as Number ++ "%",
            subtotal: $.unit_price * $.quantity * (1 - discount)
        }
    }) },
    totals:
    {
        subtotal: getSubtotal(payload.invoice.items ),
        tax: (tax * 100) as Number ++ "%",
        total: getSubtotal(payload.invoice.items ) * (1 + tax)
    }
}
Input JSON Payload:
{
  "invoice": {
    "header": {
      "customer_name": "ACME, Inc.",
      "customer_state": "CA"
    },
    "items": [
      {
        "description": "Product 1",
        "quantity": "2",
        "unit_price": "10"
      },
      {
        "description": "Product 2",
        "quantity": "1",
        "unit_price": "30"
      }
    ]
  }
}
Output
{
  "invoice": {
    "header": {
      "customer_name": "ACME, Inc.",
      "customer_state": "CA"
    },
    "items": {
      "item": {
        "description": "Product 1",
        "quantity": "2",
        "unit_price": "10",
        "discount": "5%",
        "subtotal": 19.00
      },
      "item": {
        "description": "Product 2",
        "quantity": "1",
        "unit_price": "30",
        "discount": "5%",
        "subtotal": 28.50
      }
    },
    "totals": {
      "subtotal": 47.50,
      "tax": "8.500%",
      "total": 51.53750
    }
  }
}

Was this article helpful?

💙 Thanks for your feedback!

Edit on GitHub