Hi, hello. I’m trying to implement a formula which involves Money
types. I’m using ex_money
library to deal with this. I have to calculate this on my changeset
. The formula is:
annual_amortization = amount * dedicated_percentage * depreciation_rate * initial_value / 10_000
That should return me a Money
value.
This is how I’m defining this:
schema "intangible_fixed_assets_processes" do
field :amount, :integer
field :annual_amortization, Money.Ecto.Composite.Type
field :dedicated_percentage, :decimal
field :depreciation_rate, :decimal
field :initial_value, Money.Ecto.Composite.Type
......
end
My changeset:
def changeset(intangible_fixed_asset_process, attrs) do
...
|> calculate_annual_amortization()
end
And my calculate_annual_amortization
function:
def calculate_annual_amortization(changeset) do
amount = get_change(changeset, :amount)
dedicated_percentage = get_change(changeset, :dedicated_percentage)
initial_value = get_change(changeset, :initial_value)
depreciation_rate = get_change(changeset, :depreciation_rate)
result = initial_value
|> Money.mult(amount)
|> Money.mult(dedicated_percentage)
|> Money.mult(depreciation_rate)
|> Money.div!(10_000)
with {:ok, annual_amortization} <- result do
put_change(changeset, :annual_amortization, annual_amortization)
end
end
But, that function gives obvious argument errors because the result of multiplying Money
types is like this:
iex> Money.mult(Money.new(:USD, 200), 2)
{:ok, Money.new(:USD, 400)} <--------------------------
Actually, the argument errors will start here |> Money.mult(dedicated_percentage)
I’m not very experienced with Elixir or ex_money
. Does anyone know which is the most elegant way to calculate this? Actually, I can’t even figure out a non-elegant way either