%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.2 is compatible and bundled with Mule 4.2. This version of Mule reached its End of Life on May 2, 2023, when Extended Support ended. 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.
Before you begin, note that DataWeave version 2 (%dw 2.0) is for Mule 4 apps. For a
Mule 3 app, refer to DataWeave 1.0
(%dw 1.0) examples,
within the Mule 3.9 documentation set. For other Mule versions, you can use
the Mule Runtime version selector in the table of contents.
It makes use of the following:
-
mapfunction to go through all the items in the input. -
basic math operations like
*,+and-. -
String concatenation with
++. -
asto 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.
-
reducefunction 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
}
}
}



