data: Add Posting.at_cost() method.

This commit is contained in:
Brett Smith 2020-06-15 09:48:50 -04:00
parent a2ee9c73fe
commit f21ac740f2
3 changed files with 32 additions and 14 deletions

View file

@ -408,6 +408,12 @@ class Posting(BasePosting):
except AttributeError: except AttributeError:
pass pass
def at_cost(self) -> Amount:
if self.cost is None:
return self.units
else:
return Amount(self.units.number * self.cost.number, self.cost.currency)
_KT = TypeVar('_KT', bound=Hashable) _KT = TypeVar('_KT', bound=Hashable)
_VT = TypeVar('_VT') _VT = TypeVar('_VT')

View file

@ -356,22 +356,10 @@ class RelatedPostings(Sequence[data.Posting]):
yield post, balance yield post, balance
def balance(self) -> Balance: def balance(self) -> Balance:
for _, balance in self.iter_with_balance(): return Balance(post.units for post in self)
pass
try:
return balance
except NameError:
return Balance()
def balance_at_cost(self) -> Balance: def balance_at_cost(self) -> Balance:
balance = MutableBalance() return Balance(post.at_cost() for post in self)
for post in self:
if post.cost is None:
balance += post.units
else:
number = post.units.number * post.cost.number
balance += data.Amount(number, post.cost.currency)
return balance
def meta_values(self, def meta_values(self,
key: MetaKey, key: MetaKey,

View file

@ -82,3 +82,27 @@ def test_from_entries_mix_txns_and_other_directives(simple_txn):
assert all(source[x] == post[x] for x in range(len(source) - 1)) assert all(source[x] == post[x] for x in range(len(source) - 1))
assert isinstance(post.account, data.Account) assert isinstance(post.account, data.Account)
assert post.meta['note'] # Only works with PostingMeta assert post.meta['note'] # Only works with PostingMeta
@pytest.mark.parametrize('cost_num', [105, 110, 115])
def test_at_cost(cost_num):
post = data.Posting(
'Income:Donations',
testutil.Amount(25, 'EUR'),
testutil.Cost(cost_num, 'JPY'),
None,
'*',
None,
)
assert post.at_cost() == testutil.Amount(25 * cost_num, 'JPY')
def test_at_cost_no_cost():
amount = testutil.Amount(25, 'EUR')
post = data.Posting(
'Income:Donations',
amount,
None,
None,
'*',
None,
)
assert post.at_cost() == amount