Add desc/description as possible sort field

This commit is contained in:
Michael Rees 2024-07-22 15:00:53 -05:00 committed by Simon Michael
parent 25bcf3eebb
commit 693360344c
3 changed files with 30 additions and 4 deletions

View File

@ -25,7 +25,7 @@ where
import Data.List (nub, sortBy, sortOn)
import Data.List.Extra (nubSort)
import Data.Maybe (isJust, isNothing)
import Data.Maybe (isJust, isNothing, fromMaybe)
import Data.Ord
import Data.Text (Text)
import Data.Time.Calendar (Day)
@ -123,13 +123,21 @@ registerRunningCalculationFn ropts
comparePostings :: ReportOpts -> SortSpec -> (Posting, Maybe Period) -> (Posting, Maybe Period) -> Ordering
comparePostings _ [] _ _ = EQ
comparePostings ropts (ex:es) (a, pa) (b, pb) =
let comparison = case ex of
let
getDescription p =
let tx = ptransaction p
description = fmap (\t -> tdescription t) tx
-- If there's no transaction attached, then use empty text for the description
in fromMaybe "" description
comparison = case ex of
Amount' False -> compare (pamount a) (pamount b)
Account' False -> compare (paccount a) (paccount b)
Date' False -> compare (postingDateOrDate2 (whichDate ropts) a) (postingDateOrDate2 (whichDate ropts) b)
Description' False -> compare (getDescription a) (getDescription b)
Amount' True -> compare (Down (pamount a)) (Down (pamount b))
Account' True -> compare (Down (paccount a)) (Down (paccount b))
Date' True -> compare (Down (postingDateOrDate2 (whichDate ropts) a)) (Down (postingDateOrDate2 (whichDate ropts) b))
Description' True -> compare (Down (getDescription a)) (Down (getDescription b))
in
if comparison == EQ then comparePostings ropts es (a, pa) (b, pb) else comparison

View File

@ -676,9 +676,10 @@ queryFromFlags ReportOpts{..} = simplifyQuery $ And flagsq
-- Each of these takes a bool, which shows if it has been inverted
-- (True -> has been inverted, reverse the order)
data SortField
= Date' Bool
| Account' Bool
= Account' Bool
| Amount' Bool
| Date' Bool
| Description' Bool
deriving (Show, Eq)
type SortSpec = [SortField]
@ -697,6 +698,8 @@ getSortSpec opts =
"date" -> Date' isNegated
"account" -> Account' isNegated
"amount" -> Amount' isNegated
"desc" -> Description' isNegated
"description" -> Description' isNegated
_ -> error' $ "unsupported field '" ++ t ++ "' given to --sort"
where isNegated = isPrefixOf "-" t
trimmed = fromMaybe t (stripPrefix "-" t)

View File

@ -74,3 +74,18 @@ $ hledger -f - register --sort -date
a -1 0
2024-01-01 Demo a 1 1
b -1 0
# ** 6. --sort with description
<
2024-01-01 Other
a 1
b
2024-01-02 Demo
c 1
a
$ hledger -f - register --sort desc
2024-01-02 Demo c 1 1
a -1 0
2024-01-01 Other a 1 1
b -1 0