diff --git a/hledger-lib/Hledger/Data/Account.hs b/hledger-lib/Hledger/Data/Account.hs index 78b40d7ce..d1ef12c56 100644 --- a/hledger-lib/Hledger/Data/Account.hs +++ b/hledger-lib/Hledger/Data/Account.hs @@ -11,6 +11,7 @@ module Hledger.Data.Account where import Data.List import Data.Maybe +import Data.Ord import qualified Data.Map as M import Safe (headMay, lookupJustDef) import Test.HUnit @@ -183,6 +184,12 @@ filterAccounts p a | p a = a : concatMap (filterAccounts p) (asubs a) | otherwise = concatMap (filterAccounts p) (asubs a) +-- | Sort an account tree by inclusive amount. +sortAccountTreeByAmount :: Account -> Account +sortAccountTreeByAmount a + | null $ asubs a = a + | otherwise = a{asubs=sortBy (flip $ comparing aibalance) $ map sortAccountTreeByAmount $ asubs a} + -- | Search an account list by name. lookupAccount :: AccountName -> [Account] -> Maybe Account lookupAccount a = find ((==a).aname) diff --git a/hledger-lib/Hledger/Reports/BalanceReport.hs b/hledger-lib/Hledger/Reports/BalanceReport.hs index 93c512542..563b98c4d 100644 --- a/hledger-lib/Hledger/Reports/BalanceReport.hs +++ b/hledger-lib/Hledger/Reports/BalanceReport.hs @@ -92,7 +92,7 @@ balanceReport opts q j = (items, total) dbg1 "accts" $ take 1 $ clipAccountsAndAggregate (queryDepth q) $ flattenAccounts accts | flat_ opts = dbg1 "accts" $ - maybesort $ + maybesortflat $ filterzeros $ filterempty $ drop 1 $ clipAccountsAndAggregate (queryDepth q) $ flattenAccounts accts @@ -101,6 +101,7 @@ balanceReport opts q j = (items, total) drop 1 $ flattenAccounts $ markboring $ prunezeros $ + maybesorttree $ clipAccounts (queryDepth q) accts where balance = if flat_ opts then aebalance else aibalance @@ -108,9 +109,12 @@ balanceReport opts q j = (items, total) filterempty = filter (\a -> anumpostings a > 0 || not (isZeroMixedAmount (balance a))) prunezeros = if empty_ opts then id else fromMaybe nullacct . pruneAccounts (isZeroMixedAmount . balance) markboring = if no_elide_ opts then id else markBoringParentAccounts - maybesort = if sort_amount_ opts then sortBy (maybeflip $ comparing balance) else id + maybesortflat | sort_amount_ opts = sortBy (maybeflip $ comparing balance) + | otherwise = id where maybeflip = if normalbalance_ opts == Just NormalNegative then id else flip + maybesorttree | sort_amount_ opts = sortAccountTreeByAmount + | otherwise = id items = dbg1 "items" $ map (balanceReportItem opts q) accts' total | not (flat_ opts) = dbg1 "total" $ sum [amt | (_,_,indent,amt) <- items, indent == 0] | otherwise = dbg1 "total" $