From fc513ccb914a12a093c33ce2b697477849b9a4f5 Mon Sep 17 00:00:00 2001 From: Doc Ritezel Date: Thu, 15 Feb 2018 23:01:10 -0800 Subject: [PATCH] Allow addresses to present zero balances when they do not have a balance --- lib/explorer/credit.ex | 1 + lib/explorer/debit.ex | 1 + lib/explorer/forms/address_form.ex | 7 ++++++- test/explorer/forms/address_form_test.exs | 10 +++++++++- 4 files changed, 17 insertions(+), 2 deletions(-) diff --git a/lib/explorer/credit.ex b/lib/explorer/credit.ex index 3e28fffadd..6e478d148e 100644 --- a/lib/explorer/credit.ex +++ b/lib/explorer/credit.ex @@ -23,4 +23,5 @@ defmodule Explorer.Credit do def refresh do SQL.query!(Repo, "REFRESH MATERIALIZED VIEW CONCURRENTLY credits;", [], timeout: 120_000) end + def null, do: %__MODULE__{value: Decimal.new(0), count: 0} end diff --git a/lib/explorer/debit.ex b/lib/explorer/debit.ex index dcccfcc3d2..3d793a16c9 100644 --- a/lib/explorer/debit.ex +++ b/lib/explorer/debit.ex @@ -23,4 +23,5 @@ defmodule Explorer.Debit do def refresh do SQL.query!(Repo, "REFRESH MATERIALIZED VIEW CONCURRENTLY debits;", [], timeout: 120_000) end + def null, do: %__MODULE__{value: Decimal.new(0), count: 0} end diff --git a/lib/explorer/forms/address_form.ex b/lib/explorer/forms/address_form.ex index f7840f057e..9ad85c740d 100644 --- a/lib/explorer/forms/address_form.ex +++ b/lib/explorer/forms/address_form.ex @@ -1,8 +1,13 @@ defmodule Explorer.AddressForm do @moduledoc false + alias Explorer.Credit + alias Explorer.Debit + def build(address) do - balance = Decimal.sub(address.credit.value, address.debit.value) + credit = address.credit || Credit.null + debit = address.debit || Debit.null + balance = Decimal.sub(credit.value, debit.value) Map.put(address, :balance, balance) end end diff --git a/test/explorer/forms/address_form_test.exs b/test/explorer/forms/address_form_test.exs index 36cf8cffe0..f3ec876313 100644 --- a/test/explorer/forms/address_form_test.exs +++ b/test/explorer/forms/address_form_test.exs @@ -6,7 +6,7 @@ defmodule Explorer.AddressFormTest do alias Explorer.Debit describe "build/1" do - test "that it has a balance" do + test "returns a balance" do address = insert(:address, %{hash: "bert"}) insert(:transaction, value: 5) |> with_addresses(%{to: "bert", from: "ernie"}) insert(:transaction, value: 5) |> with_addresses(%{to: "bert", from: "kermit"}) @@ -15,5 +15,13 @@ defmodule Explorer.AddressFormTest do Debit.refresh assert AddressForm.build(Repo.preload(address, [:debit, :credit])).balance == Decimal.new(10) end + + test "returns a zero balance when the address does not have balances" do + address = insert(:address, %{hash: "bert"}) + insert(:transaction, value: 5) |> with_addresses(%{to: "bert", from: "ernie"}) + insert(:transaction, value: 5) |> with_addresses(%{to: "bert", from: "kermit"}) + + assert AddressForm.build(Repo.preload(address, [:debit, :credit])).balance == Decimal.new(0) + end end end