ash_double_entry/lib/account/calculations/balance_as_of_ulid.ex

29 lines
979 B
Elixir
Raw Normal View History

defmodule AshDoubleEntry.Account.Calculations.BalanceAsOfUlid do
2023-09-27 02:46:07 +13:00
# Calculates the balance as of a given transfer id. See the getting started guide for more.
@moduledoc false
2024-04-02 10:21:49 +13:00
use Ash.Resource.Calculation
require Ash.Expr
def expression(opts, context) do
resource = opts[:resource]
2023-12-06 13:49:23 +13:00
balance_resource = AshDoubleEntry.Account.Info.account_balance_resource!(resource)
2023-12-06 13:49:23 +13:00
if AshDoubleEntry.Balance.Info.balance_money_composite_type?(balance_resource) do
Ash.Expr.expr(
first(balances,
field: :balance,
2024-04-02 10:21:49 +13:00
query: [sort: [transfer_id: :desc], filter: transfer_id <= ^context.arguments[:ulid]]
2023-12-23 15:19:49 +13:00
) || composite_type(%{currency: currency, amount: 0}, AshMoney.Types.Money)
2023-12-06 13:49:23 +13:00
)
else
Ash.Expr.expr(
first(balances,
field: :balance,
2024-04-02 10:21:49 +13:00
query: [sort: [transfer_id: :desc], filter: transfer_id <= ^context.arguments[:ulid]]
2023-12-23 15:19:49 +13:00
) || %{currency: currency, amount: 0}
2023-12-06 13:49:23 +13:00
)
end
end
end