@impl true
def change(changeset, _opts, _context) do
items = Ash.Changeset.get_argument(changeset, :items) || []
valid_items =
for item <- items,
{:ok, record} <- [maybe_invoice_item(item)] do
record
end
{subtotal, tax_total, total} =
Enum.reduce(valid_items, {0, 0, 0}, fn item, {subtotal, tax_total, total} ->
{
Decimal.add(subtotal, item.subtotal),
Decimal.add(tax_total, item.tax_amount),
Decimal.add(total, item.total)
}
end)
Ash.Changeset.force_change_attributes(changeset, %{
subtotal: subtotal,
tax_total: tax_total,
total: total
})
end
defp maybe_invoice_item(item) do
InvoiceItem
|> Ash.Changeset.for_create(:create_invoice_item, item)
|> Ash.Changeset.apply_attributes()
end
@impl true
def change(changeset, _opts, _context) do
items = Ash.Changeset.get_argument(changeset, :items) || []
valid_items =
for item <- items,
{:ok, record} <- [maybe_invoice_item(item)] do
record
end
{subtotal, tax_total, total} =
Enum.reduce(valid_items, {0, 0, 0}, fn item, {subtotal, tax_total, total} ->
{
Decimal.add(subtotal, item.subtotal),
Decimal.add(tax_total, item.tax_amount),
Decimal.add(total, item.total)
}
end)
Ash.Changeset.force_change_attributes(changeset, %{
subtotal: subtotal,
tax_total: tax_total,
total: total
})
end
defp maybe_invoice_item(item) do
InvoiceItem
|> Ash.Changeset.for_create(:create_invoice_item, item)
|> Ash.Changeset.apply_attributes()
end