From c0d12f5d1c7c58362d971003a7fdd86d73c58f5c Mon Sep 17 00:00:00 2001 From: Nikolay Orlyuk Date: Wed, 11 Jan 2017 22:09:07 +0200 Subject: [PATCH] Normalize amount in infereBalancingAmount (#469) This fixes issue exposed by a fix for simonmichael/hledger#465 --- hledger-lib/Hledger/Data/Transaction.hs | 35 ++++++++++++++++++++++++- tests/journal/commodities.test | 15 +++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/hledger-lib/Hledger/Data/Transaction.hs b/hledger-lib/Hledger/Data/Transaction.hs index 9e95c9dba..f1c860715 100644 --- a/hledger-lib/Hledger/Data/Transaction.hs +++ b/hledger-lib/Hledger/Data/Transaction.hs @@ -244,6 +244,38 @@ tests_postingAsLines = [ ] ] +tests_inference = [ + "inferBalancingAmount" ~: do + let p `gives` p' = assertEqual (show p) (Right p') $ inferTransaction p + inferTransaction :: Transaction -> Either String Transaction + inferTransaction = runIdentity . runExceptT . inferBalancingAmount (\_ _ -> return ()) + nulltransaction `gives` nulltransaction + nulltransaction{ + tpostings=[ + "a" `post` usd (-5), + "b" `post` missingamt + ]} + `gives` + nulltransaction{ + tpostings=[ + "a" `post` usd (-5), + "b" `post` usd 5 + ]} + nulltransaction{ + tpostings=[ + "a" `post` usd (-5), + "b" `post` (eur 3 @@ usd 4), + "c" `post` missingamt + ]} + `gives` + nulltransaction{ + tpostings=[ + "a" `post` usd (-5), + "b" `post` (eur 3 @@ usd 4), + "c" `post` usd 1 + ]} + ] + indent :: String -> String indent = (" "++) @@ -371,7 +403,7 @@ inferBalancingAmount update t@Transaction{tpostings=ps} | not (hasAmount p) = updateAmount p bvsum inferamount p = return p updateAmount p amt = update (paccount p) amt' >> return p { pamount=amt' } - where amt' = costOfMixedAmount (-amt) + where amt' = normaliseMixedAmount $ costOfMixedAmount (-amt) -- | Infer prices for this transaction's posting amounts, if needed to make -- the postings balance, and if possible. This is done once for the real @@ -471,6 +503,7 @@ postingSetTransaction t p = p{ptransaction=Just t} tests_Hledger_Data_Transaction = TestList $ concat [ tests_postingAsLines, tests_showTransactionUnelided, + tests_inference, [ "showTransaction" ~: do assertEqual "show a balanced transaction, eliding last amount" diff --git a/tests/journal/commodities.test b/tests/journal/commodities.test index 3c7508a9e..71264ded7 100644 --- a/tests/journal/commodities.test +++ b/tests/journal/commodities.test @@ -32,3 +32,18 @@ hledger -f- balance -------------------- 0 >>>=0 + +# 4. autobalance with prices +hledger -f- print +<<< +2016/1/1 + saving-card $-105 + snacks 95 EUR @@ $100 + Equity:Unbalanced +>>> +2016/01/01 + saving-card $-105 + snacks 95 EUR @@ $100 + Equity:Unbalanced $5 + +>>>=0