2023-08-06 16:27:33 +12:00
|
|
|
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
|
2023-08-06 16:27:33 +12:00
|
|
|
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-08-06 16:27:33 +12:00
|
|
|
|
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
|
2023-08-06 16:27:33 +12:00
|
|
|
end
|
|
|
|
end
|