%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)
}
}
Define a Custom Addition Function
DataWeave 2.1 is compatible with Mule 4.1. Standard Support for Mule 4.1 ended on November 2, 2020, and this version of Mule will reach its End of Life on November 2, 2022, when Extended Support ends. Deployments of new applications to CloudHub that use this version of Mule are no longer allowed. Only in-place updates to applications are permitted. MuleSoft recommends that you upgrade to the latest version of Mule 4 that is in Standard Support so that your applications run with the latest fixes and security enhancements. |
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.
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.
{
"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"
}
]
}
}
{
"invoice": {
"header": {
"customer_name": "ACME, Inc.",
"customer_state": "CA"
},
"items": {
"item": {
"description": "Product 1",
"quantity": "2",
"unit_price": "10",
"discount": "5.00%",
"subtotal": 19.00
},
"item": {
"description": "Product 2",
"quantity": "1",
"unit_price": "30",
"discount": "5.00%",
"subtotal": 28.50
}
},
"totals": {
"subtotal": 47.50,
"tax": "8.500%",
"total": 51.53750
}
}
}