{-|

Postings report, used by the register command.

-}

{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}

module Hledger.Reports.PostingsReport (
  PostingsReport,
  PostingsReportItem,
  postingsReport,
  mkpostingsReportItem,

  -- * Tests
  tests_PostingsReport
)
where

import Data.List
import Data.List.Extra (nubSort)
import Data.Maybe
-- import Data.Text (Text)
import qualified Data.Text as T
import Data.Time.Calendar
import Safe (headMay, lastMay)

import Hledger.Data
import Hledger.Query
import Hledger.Utils
import Hledger.Reports.ReportOptions


-- | A postings report is a list of postings with a running total, a label
-- for the total field, and a little extra transaction info to help with rendering.
-- This is used eg for the register command.
type PostingsReport = (String               -- label for the running balance column XXX remove
                      ,[PostingsReportItem] -- line items, one per posting
                      )
type PostingsReportItem = (Maybe Day    -- The posting date, if this is the first posting in a
                                        -- transaction or if it's different from the previous
                                        -- posting's date. Or if this a summary posting, the
                                        -- report interval's start date if this is the first
                                        -- summary posting in the interval.
                          ,Maybe Day    -- If this is a summary posting, the report interval's
                                        -- end date if this is the first summary posting in
                                        -- the interval.
                          ,Maybe String -- The posting's transaction's description, if this is the first posting in the transaction.
                          ,Posting      -- The posting, possibly with the account name depth-clipped.
                          ,MixedAmount  -- The running total after this posting, or with --average,
                                        -- the running average posting amount. With --historical,
                                        -- postings before the report start date are included in
                                        -- the running total/average.
                          )

-- | A summary posting summarises the activity in one account within a report
-- interval. It is kludgily represented by a regular Posting with no description,
-- the interval's start date stored as the posting date, and the interval's end
-- date attached with a tuple.
type SummaryPosting = (Posting, Day)

-- | Select postings from the journal and add running balance and other
-- information to make a postings report. Used by eg hledger's register command.
postingsReport :: ReportOpts -> Query -> Journal -> PostingsReport
postingsReport :: ReportOpts -> Query -> Journal -> PostingsReport
postingsReport ropts :: ReportOpts
ropts@ReportOpts{..} q :: Query
q j :: Journal
j =
  (String
totallabel, [PostingsReportItem]
items)
    where
      reportspan :: DateSpan
reportspan  = ReportOpts -> Query -> Journal -> DateSpan
adjustReportDates ReportOpts
ropts Query
q Journal
j
      whichdate :: WhichDate
whichdate   = ReportOpts -> WhichDate
whichDateFromOpts ReportOpts
ropts
      depth :: Int
depth       = Query -> Int
queryDepth Query
q
      styles :: Map CommoditySymbol AmountStyle
styles      = Journal -> Map CommoditySymbol AmountStyle
journalCommodityStyles Journal
j
      priceoracle :: PriceOracle
priceoracle = Bool -> Journal -> PriceOracle
journalPriceOracle Bool
infer_value_ Journal
j
      multiperiod :: Bool
multiperiod = Interval
interval_ Interval -> Interval -> Bool
forall a. Eq a => a -> a -> Bool
/= Interval
NoInterval
      today :: Day
today       = Day -> Maybe Day -> Day
forall a. a -> Maybe a -> a
fromMaybe (String -> Day
forall a. String -> a
error' "postingsReport: could not pick a valuation date, ReportOpts today_ is unset") Maybe Day
today_

      -- postings to be included in the report, and similarly-matched postings before the report start date
      (precedingps :: [Posting]
precedingps, reportps :: [Posting]
reportps) = ReportOpts
-> Query -> Journal -> DateSpan -> ([Posting], [Posting])
matchedPostingsBeforeAndDuring ReportOpts
ropts Query
q Journal
j DateSpan
reportspan

      -- Postings, or summary postings with their subperiod's end date, to be displayed.
      [(Posting, Maybe Day)]
displayps :: [(Posting, Maybe Day)]
        | Bool
multiperiod =
            let summaryps :: [SummaryPosting]
summaryps = Interval
-> WhichDate
-> Int
-> Bool
-> DateSpan
-> [Posting]
-> [SummaryPosting]
summarisePostingsByInterval Interval
interval_ WhichDate
whichdate Int
depth Bool
showempty DateSpan
reportspan [Posting]
reportps
            in [(Posting -> Day -> Posting
pvalue Posting
p Day
lastday, Day -> Maybe Day
forall a. a -> Maybe a
Just Day
periodend) | (p :: Posting
p, periodend :: Day
periodend) <- [SummaryPosting]
summaryps, let lastday :: Day
lastday = Integer -> Day -> Day
addDays (-1) Day
periodend]
        | Bool
otherwise =
            [(Posting -> Day -> Posting
pvalue Posting
p Day
reportorjournallast, Maybe Day
forall a. Maybe a
Nothing) | Posting
p <- [Posting]
reportps]
        where
          showempty :: Bool
showempty = Bool
empty_ Bool -> Bool -> Bool
|| Bool
average_
          -- We may be converting posting amounts to value, per hledger_options.m4.md "Effect of --value on reports".
          pvalue :: Posting -> Day -> Posting
pvalue p :: Posting
p periodlast :: Day
periodlast = Posting
-> (ValuationType -> Posting) -> Maybe ValuationType -> Posting
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Posting
p (PriceOracle
-> Map CommoditySymbol AmountStyle
-> Day
-> Maybe Day
-> Day
-> Bool
-> Posting
-> ValuationType
-> Posting
postingApplyValuation PriceOracle
priceoracle Map CommoditySymbol AmountStyle
styles Day
periodlast Maybe Day
mreportlast Day
today Bool
multiperiod Posting
p) Maybe ValuationType
value_
            where
              mreportlast :: Maybe Day
mreportlast = ReportOpts -> Maybe Day
reportPeriodLastDay ReportOpts
ropts
          reportorjournallast :: Day
reportorjournallast =
            Day -> Maybe Day -> Day
forall a. a -> Maybe a -> a
fromMaybe (String -> Day
forall a. String -> a
error' "postingsReport: expected a non-empty journal") (Maybe Day -> Day) -> Maybe Day -> Day
forall a b. (a -> b) -> a -> b
$ -- XXX shouldn't happen
            ReportOpts -> Journal -> Maybe Day
reportPeriodOrJournalLastDay ReportOpts
ropts Journal
j

      -- Posting report items ready for display.
      items :: [PostingsReportItem]
items =
        String -> [PostingsReportItem] -> [PostingsReportItem]
forall a. Show a => String -> a -> a
dbg1 "postingsReport items" ([PostingsReportItem] -> [PostingsReportItem])
-> [PostingsReportItem] -> [PostingsReportItem]
forall a b. (a -> b) -> a -> b
$
        [(Posting, Maybe Day)]
-> (Posting, Maybe Day)
-> WhichDate
-> Int
-> MixedAmount
-> (Int -> MixedAmount -> MixedAmount -> MixedAmount)
-> Int
-> [PostingsReportItem]
postingsReportItems [(Posting, Maybe Day)]
displayps (Posting
nullposting,Maybe Day
forall a. Maybe a
Nothing) WhichDate
whichdate Int
depth MixedAmount
startbal Int -> MixedAmount -> MixedAmount -> MixedAmount
runningcalc Int
startnum
        where
          -- In historical mode we'll need a starting balance, which we
          -- may be converting to value per hledger_options.m4.md "Effect
          -- of --value on reports".
          -- XXX balance report doesn't value starting balance.. should this ?
          historical :: Bool
historical = BalanceType
balancetype_ BalanceType -> BalanceType -> Bool
forall a. Eq a => a -> a -> Bool
== BalanceType
HistoricalBalance
          startbal :: MixedAmount
startbal | Bool
average_  = if Bool
historical then MixedAmount -> MixedAmount
bvalue MixedAmount
precedingavg else 0
                   | Bool
otherwise = if Bool
historical then MixedAmount -> MixedAmount
bvalue MixedAmount
precedingsum else 0
            where
              precedingsum :: MixedAmount
precedingsum = [Posting] -> MixedAmount
sumPostings [Posting]
precedingps
              precedingavg :: MixedAmount
precedingavg | [Posting] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Posting]
precedingps = 0
                           | Bool
otherwise        = Quantity -> MixedAmount -> MixedAmount
divideMixedAmount (Int -> Quantity
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Int -> Quantity) -> Int -> Quantity
forall a b. (a -> b) -> a -> b
$ [Posting] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Posting]
precedingps) MixedAmount
precedingsum
              bvalue :: MixedAmount -> MixedAmount
bvalue = (MixedAmount -> MixedAmount)
-> (ValuationType -> MixedAmount -> MixedAmount)
-> Maybe ValuationType
-> MixedAmount
-> MixedAmount
forall b a. b -> (a -> b) -> Maybe a -> b
maybe MixedAmount -> MixedAmount
forall a. a -> a
id (PriceOracle
-> Map CommoditySymbol AmountStyle
-> Day
-> Maybe Day
-> Day
-> Bool
-> ValuationType
-> MixedAmount
-> MixedAmount
mixedAmountApplyValuation PriceOracle
priceoracle Map CommoditySymbol AmountStyle
styles Day
daybeforereportstart Maybe Day
forall a. Maybe a
Nothing Day
today Bool
multiperiod) Maybe ValuationType
value_
                  -- XXX constrain valuation type to AtDate daybeforereportstart here ?
                where
                  daybeforereportstart :: Day
daybeforereportstart =
                    Day -> (Day -> Day) -> Maybe Day -> Day
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (String -> Day
forall a. String -> a
error' "postingsReport: expected a non-empty journal") -- XXX shouldn't happen
                    (Integer -> Day -> Day
addDays (-1))
                    (Maybe Day -> Day) -> Maybe Day -> Day
forall a b. (a -> b) -> a -> b
$ ReportOpts -> Journal -> Maybe Day
reportPeriodOrJournalStart ReportOpts
ropts Journal
j

          runningcalc :: Int -> MixedAmount -> MixedAmount -> MixedAmount
runningcalc = ReportOpts -> Int -> MixedAmount -> MixedAmount -> MixedAmount
registerRunningCalculationFn ReportOpts
ropts
          startnum :: Int
startnum = if Bool
historical then [Posting] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Posting]
precedingps Int -> Int -> Int
forall a. Num a => a -> a -> a
+ 1 else 1

-- | Based on the given report options, return a function that does the appropriate
-- running calculation for the register report, ie a running average or running total.
-- This function will take the item number, previous average/total, and new posting amount,
-- and return the new average/total.
registerRunningCalculationFn :: ReportOpts -> (Int -> MixedAmount -> MixedAmount -> MixedAmount)
registerRunningCalculationFn :: ReportOpts -> Int -> MixedAmount -> MixedAmount -> MixedAmount
registerRunningCalculationFn ropts :: ReportOpts
ropts
  | ReportOpts -> Bool
average_ ReportOpts
ropts = \i :: Int
i avg :: MixedAmount
avg amt :: MixedAmount
amt -> MixedAmount
avg MixedAmount -> MixedAmount -> MixedAmount
forall a. Num a => a -> a -> a
+ Quantity -> MixedAmount -> MixedAmount
divideMixedAmount (Int -> Quantity
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
i) (MixedAmount
amt MixedAmount -> MixedAmount -> MixedAmount
forall a. Num a => a -> a -> a
- MixedAmount
avg)
  | Bool
otherwise      = \_ bal :: MixedAmount
bal amt :: MixedAmount
amt -> MixedAmount
bal MixedAmount -> MixedAmount -> MixedAmount
forall a. Num a => a -> a -> a
+ MixedAmount
amt

totallabel :: String
totallabel = "Total"

-- | Adjust report start/end dates to more useful ones based on
-- journal data and report intervals. Ie:
-- 1. If the start date is unspecified, use the earliest date in the journal (if any)
-- 2. If the end date is unspecified, use the latest date in the journal (if any)
-- 3. If a report interval is specified, enlarge the dates to enclose whole intervals
adjustReportDates :: ReportOpts -> Query -> Journal -> DateSpan
adjustReportDates :: ReportOpts -> Query -> Journal -> DateSpan
adjustReportDates opts :: ReportOpts
opts q :: Query
q j :: Journal
j = DateSpan
reportspan
  where
    -- see also multiBalanceReport
    requestedspan :: DateSpan
requestedspan       = String -> DateSpan -> DateSpan
forall a. Show a => String -> a -> a
dbg1 "requestedspan"       (DateSpan -> DateSpan) -> DateSpan -> DateSpan
forall a b. (a -> b) -> a -> b
$ Query -> DateSpan
queryDateSpan' Query
q                                       -- span specified by -b/-e/-p options and query args
    journalspan :: DateSpan
journalspan         = String -> DateSpan -> DateSpan
forall a. Show a => String -> a -> a
dbg1 "journalspan"         (DateSpan -> DateSpan) -> DateSpan -> DateSpan
forall a b. (a -> b) -> a -> b
$ DateSpan
dates DateSpan -> DateSpan -> DateSpan
`spanUnion` DateSpan
date2s                               -- earliest and latest dates (or date2s) in the journal
      where
        dates :: DateSpan
dates  = Bool -> Journal -> DateSpan
journalDateSpan Bool
False Journal
j
        date2s :: DateSpan
date2s = Bool -> Journal -> DateSpan
journalDateSpan Bool
True  Journal
j
    requestedspanclosed :: DateSpan
requestedspanclosed = String -> DateSpan -> DateSpan
forall a. Show a => String -> a -> a
dbg1 "requestedspanclosed" (DateSpan -> DateSpan) -> DateSpan -> DateSpan
forall a b. (a -> b) -> a -> b
$ DateSpan
requestedspan DateSpan -> DateSpan -> DateSpan
`spanDefaultsFrom` DateSpan
journalspan           -- if open-ended, close it using the journal's dates (if any)
    intervalspans :: [DateSpan]
intervalspans       = String -> [DateSpan] -> [DateSpan]
forall a. Show a => String -> a -> a
dbg1 "intervalspans"       ([DateSpan] -> [DateSpan]) -> [DateSpan] -> [DateSpan]
forall a b. (a -> b) -> a -> b
$ Interval -> DateSpan -> [DateSpan]
splitSpan (ReportOpts -> Interval
interval_ ReportOpts
opts) DateSpan
requestedspanclosed  -- get the whole intervals enclosing that
    mreportstart :: Maybe Day
mreportstart        = String -> Maybe Day -> Maybe Day
forall a. Show a => String -> a -> a
dbg1 "reportstart"         (Maybe Day -> Maybe Day) -> Maybe Day -> Maybe Day
forall a b. (a -> b) -> a -> b
$ Maybe Day -> (DateSpan -> Maybe Day) -> Maybe DateSpan -> Maybe Day
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Maybe Day
forall a. Maybe a
Nothing DateSpan -> Maybe Day
spanStart (Maybe DateSpan -> Maybe Day) -> Maybe DateSpan -> Maybe Day
forall a b. (a -> b) -> a -> b
$ [DateSpan] -> Maybe DateSpan
forall a. [a] -> Maybe a
headMay [DateSpan]
intervalspans        -- start of the first interval, or open ended
    mreportend :: Maybe Day
mreportend          = String -> Maybe Day -> Maybe Day
forall a. Show a => String -> a -> a
dbg1 "reportend"           (Maybe Day -> Maybe Day) -> Maybe Day -> Maybe Day
forall a b. (a -> b) -> a -> b
$ Maybe Day -> (DateSpan -> Maybe Day) -> Maybe DateSpan -> Maybe Day
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Maybe Day
forall a. Maybe a
Nothing DateSpan -> Maybe Day
spanEnd   (Maybe DateSpan -> Maybe Day) -> Maybe DateSpan -> Maybe Day
forall a b. (a -> b) -> a -> b
$ [DateSpan] -> Maybe DateSpan
forall a. [a] -> Maybe a
lastMay [DateSpan]
intervalspans        -- end of the last interval, or open ended
    reportspan :: DateSpan
reportspan          = String -> DateSpan -> DateSpan
forall a. Show a => String -> a -> a
dbg1 "reportspan"          (DateSpan -> DateSpan) -> DateSpan -> DateSpan
forall a b. (a -> b) -> a -> b
$ Maybe Day -> Maybe Day -> DateSpan
DateSpan Maybe Day
mreportstart Maybe Day
mreportend                       -- the requested span enlarged to whole intervals if possible

-- | Find postings matching a given query, within a given date span,
-- and also any similarly-matched postings before that date span.
-- Date restrictions and depth restrictions in the query are ignored.
-- A helper for the postings report.
matchedPostingsBeforeAndDuring :: ReportOpts -> Query -> Journal -> DateSpan -> ([Posting],[Posting])
matchedPostingsBeforeAndDuring :: ReportOpts
-> Query -> Journal -> DateSpan -> ([Posting], [Posting])
matchedPostingsBeforeAndDuring opts :: ReportOpts
opts q :: Query
q j :: Journal
j (DateSpan mstart :: Maybe Day
mstart mend :: Maybe Day
mend) =
  String -> ([Posting], [Posting]) -> ([Posting], [Posting])
forall a. Show a => String -> a -> a
dbg1 "beforeps, duringps" (([Posting], [Posting]) -> ([Posting], [Posting]))
-> ([Posting], [Posting]) -> ([Posting], [Posting])
forall a b. (a -> b) -> a -> b
$ (Posting -> Bool) -> [Posting] -> ([Posting], [Posting])
forall a. (a -> Bool) -> [a] -> ([a], [a])
span (Query
beforestartq Query -> Posting -> Bool
`matchesPosting`) [Posting]
beforeandduringps
  where
    beforestartq :: Query
beforestartq = String -> Query -> Query
forall a. Show a => String -> a -> a
dbg1 "beforestartq" (Query -> Query) -> Query -> Query
forall a b. (a -> b) -> a -> b
$ DateSpan -> Query
dateqtype (DateSpan -> Query) -> DateSpan -> Query
forall a b. (a -> b) -> a -> b
$ Maybe Day -> Maybe Day -> DateSpan
DateSpan Maybe Day
forall a. Maybe a
Nothing Maybe Day
mstart
    beforeandduringps :: [Posting]
beforeandduringps =
      String -> [Posting] -> [Posting]
forall a. Show a => String -> a -> a
dbg1 "ps5" ([Posting] -> [Posting]) -> [Posting] -> [Posting]
forall a b. (a -> b) -> a -> b
$ (Posting -> Day) -> [Posting] -> [Posting]
forall b a. Ord b => (a -> b) -> [a] -> [a]
sortOn Posting -> Day
sortdate ([Posting] -> [Posting]) -> [Posting] -> [Posting]
forall a b. (a -> b) -> a -> b
$                                           -- sort postings by date or date2
      String -> [Posting] -> [Posting]
forall a. Show a => String -> a -> a
dbg1 "ps4" ([Posting] -> [Posting]) -> [Posting] -> [Posting]
forall a b. (a -> b) -> a -> b
$ (if ReportOpts -> Bool
invert_ ReportOpts
opts then (Posting -> Posting) -> [Posting] -> [Posting]
forall a b. (a -> b) -> [a] -> [b]
map Posting -> Posting
negatePostingAmount else [Posting] -> [Posting]
forall a. a -> a
id) ([Posting] -> [Posting]) -> [Posting] -> [Posting]
forall a b. (a -> b) -> a -> b
$    -- with --invert, invert amounts
      String -> [Posting] -> [Posting]
forall a. Show a => String -> a -> a
dbg1 "ps3" ([Posting] -> [Posting]) -> [Posting] -> [Posting]
forall a b. (a -> b) -> a -> b
$ (Posting -> Posting) -> [Posting] -> [Posting]
forall a b. (a -> b) -> [a] -> [b]
map (Query -> Posting -> Posting
filterPostingAmount Query
symq) ([Posting] -> [Posting]) -> [Posting] -> [Posting]
forall a b. (a -> b) -> a -> b
$                            -- remove amount parts which the query's cur: terms would exclude
      String -> [Posting] -> [Posting]
forall a. Show a => String -> a -> a
dbg1 "ps2" ([Posting] -> [Posting]) -> [Posting] -> [Posting]
forall a b. (a -> b) -> a -> b
$ (if ReportOpts -> Bool
related_ ReportOpts
opts then (Posting -> [Posting]) -> [Posting] -> [Posting]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap Posting -> [Posting]
relatedPostings else [Posting] -> [Posting]
forall a. a -> a
id) ([Posting] -> [Posting]) -> [Posting] -> [Posting]
forall a b. (a -> b) -> a -> b
$ -- with -r, replace each with its sibling postings
      String -> [Posting] -> [Posting]
forall a. Show a => String -> a -> a
dbg1 "ps1" ([Posting] -> [Posting]) -> [Posting] -> [Posting]
forall a b. (a -> b) -> a -> b
$ (Posting -> Bool) -> [Posting] -> [Posting]
forall a. (a -> Bool) -> [a] -> [a]
filter (Query
beforeandduringq Query -> Posting -> Bool
`matchesPosting`) ([Posting] -> [Posting]) -> [Posting] -> [Posting]
forall a b. (a -> b) -> a -> b
$                -- filter postings by the query, with no start date or depth limit
                  Journal -> [Posting]
journalPostings (Journal -> [Posting]) -> Journal -> [Posting]
forall a b. (a -> b) -> a -> b
$
                  ReportOpts -> Journal -> Journal
journalSelectingAmountFromOpts ReportOpts
opts Journal
j    -- maybe convert to cost early, will be seen by amt:. XXX what about converting to value ?
      where
        beforeandduringq :: Query
beforeandduringq = String -> Query -> Query
forall a. Show a => String -> a -> a
dbg1 "beforeandduringq" (Query -> Query) -> Query -> Query
forall a b. (a -> b) -> a -> b
$ [Query] -> Query
And [Query -> Query
depthless (Query -> Query) -> Query -> Query
forall a b. (a -> b) -> a -> b
$ Query -> Query
dateless Query
q, Query
beforeendq]
          where
            depthless :: Query -> Query
depthless  = (Query -> Bool) -> Query -> Query
filterQuery (Bool -> Bool
not (Bool -> Bool) -> (Query -> Bool) -> Query -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Query -> Bool
queryIsDepth)
            dateless :: Query -> Query
dateless   = (Query -> Bool) -> Query -> Query
filterQuery (Bool -> Bool
not (Bool -> Bool) -> (Query -> Bool) -> Query -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Query -> Bool
queryIsDateOrDate2)
            beforeendq :: Query
beforeendq = DateSpan -> Query
dateqtype (DateSpan -> Query) -> DateSpan -> Query
forall a b. (a -> b) -> a -> b
$ Maybe Day -> Maybe Day -> DateSpan
DateSpan Maybe Day
forall a. Maybe a
Nothing Maybe Day
mend
        sortdate :: Posting -> Day
sortdate = if ReportOpts -> Bool
date2_ ReportOpts
opts then Posting -> Day
postingDate2 else Posting -> Day
postingDate
        symq :: Query
symq = String -> Query -> Query
forall a. Show a => String -> a -> a
dbg1 "symq" (Query -> Query) -> Query -> Query
forall a b. (a -> b) -> a -> b
$ (Query -> Bool) -> Query -> Query
filterQuery Query -> Bool
queryIsSym Query
q
    dateqtype :: DateSpan -> Query
dateqtype
      | Query -> Bool
queryIsDate2 Query
dateq Bool -> Bool -> Bool
|| (Query -> Bool
queryIsDate Query
dateq Bool -> Bool -> Bool
&& ReportOpts -> Bool
date2_ ReportOpts
opts) = DateSpan -> Query
Date2
      | Bool
otherwise = DateSpan -> Query
Date
      where
        dateq :: Query
dateq = String -> Query -> Query
forall a. Show a => String -> a -> a
dbg1 "dateq" (Query -> Query) -> Query -> Query
forall a b. (a -> b) -> a -> b
$ (Query -> Bool) -> Query -> Query
filterQuery Query -> Bool
queryIsDateOrDate2 (Query -> Query) -> Query -> Query
forall a b. (a -> b) -> a -> b
$ String -> Query -> Query
forall a. Show a => String -> a -> a
dbg1 "q" Query
q  -- XXX confused by multiple date:/date2: ?

-- | Generate postings report line items from a list of postings or (with
-- non-Nothing dates attached) summary postings.
postingsReportItems :: [(Posting,Maybe Day)] -> (Posting,Maybe Day) -> WhichDate -> Int -> MixedAmount -> (Int -> MixedAmount -> MixedAmount -> MixedAmount) -> Int -> [PostingsReportItem]
postingsReportItems :: [(Posting, Maybe Day)]
-> (Posting, Maybe Day)
-> WhichDate
-> Int
-> MixedAmount
-> (Int -> MixedAmount -> MixedAmount -> MixedAmount)
-> Int
-> [PostingsReportItem]
postingsReportItems [] _ _ _ _ _ _ = []
postingsReportItems ((p :: Posting
p,menddate :: Maybe Day
menddate):ps :: [(Posting, Maybe Day)]
ps) (pprev :: Posting
pprev,menddateprev :: Maybe Day
menddateprev) wd :: WhichDate
wd d :: Int
d b :: MixedAmount
b runningcalcfn :: Int -> MixedAmount -> MixedAmount -> MixedAmount
runningcalcfn itemnum :: Int
itemnum = PostingsReportItem
iPostingsReportItem -> [PostingsReportItem] -> [PostingsReportItem]
forall a. a -> [a] -> [a]
:([(Posting, Maybe Day)]
-> (Posting, Maybe Day)
-> WhichDate
-> Int
-> MixedAmount
-> (Int -> MixedAmount -> MixedAmount -> MixedAmount)
-> Int
-> [PostingsReportItem]
postingsReportItems [(Posting, Maybe Day)]
ps (Posting
p,Maybe Day
menddate) WhichDate
wd Int
d MixedAmount
b' Int -> MixedAmount -> MixedAmount -> MixedAmount
runningcalcfn (Int
itemnumInt -> Int -> Int
forall a. Num a => a -> a -> a
+1))
    where
      i :: PostingsReportItem
i = Bool
-> Bool
-> WhichDate
-> Maybe Day
-> Posting
-> MixedAmount
-> PostingsReportItem
mkpostingsReportItem Bool
showdate Bool
showdesc WhichDate
wd Maybe Day
menddate Posting
p' MixedAmount
b'
      (showdate :: Bool
showdate, showdesc :: Bool
showdesc) | Maybe Day -> Bool
forall a. Maybe a -> Bool
isJust Maybe Day
menddate = (Maybe Day
menddate Maybe Day -> Maybe Day -> Bool
forall a. Eq a => a -> a -> Bool
/= Maybe Day
menddateprev,        Bool
False)
                           | Bool
otherwise       = (Bool
isfirstintxn Bool -> Bool -> Bool
|| Bool
isdifferentdate, Bool
isfirstintxn)
      isfirstintxn :: Bool
isfirstintxn = Posting -> Maybe Transaction
ptransaction Posting
p Maybe Transaction -> Maybe Transaction -> Bool
forall a. Eq a => a -> a -> Bool
/= Posting -> Maybe Transaction
ptransaction Posting
pprev
      isdifferentdate :: Bool
isdifferentdate = case WhichDate
wd of PrimaryDate   -> Posting -> Day
postingDate Posting
p  Day -> Day -> Bool
forall a. Eq a => a -> a -> Bool
/= Posting -> Day
postingDate Posting
pprev
                                   SecondaryDate -> Posting -> Day
postingDate2 Posting
p Day -> Day -> Bool
forall a. Eq a => a -> a -> Bool
/= Posting -> Day
postingDate2 Posting
pprev
      p' :: Posting
p' = Posting
p{paccount :: CommoditySymbol
paccount= Int -> CommoditySymbol -> CommoditySymbol
clipOrEllipsifyAccountName Int
d (CommoditySymbol -> CommoditySymbol)
-> CommoditySymbol -> CommoditySymbol
forall a b. (a -> b) -> a -> b
$ Posting -> CommoditySymbol
paccount Posting
p}
      b' :: MixedAmount
b' = Int -> MixedAmount -> MixedAmount -> MixedAmount
runningcalcfn Int
itemnum MixedAmount
b (Posting -> MixedAmount
pamount Posting
p)

-- | Generate one postings report line item, containing the posting,
-- the current running balance, and optionally the posting date and/or
-- the transaction description.
mkpostingsReportItem :: Bool -> Bool -> WhichDate -> Maybe Day -> Posting -> MixedAmount -> PostingsReportItem
mkpostingsReportItem :: Bool
-> Bool
-> WhichDate
-> Maybe Day
-> Posting
-> MixedAmount
-> PostingsReportItem
mkpostingsReportItem showdate :: Bool
showdate showdesc :: Bool
showdesc wd :: WhichDate
wd menddate :: Maybe Day
menddate p :: Posting
p b :: MixedAmount
b =
  (if Bool
showdate then Day -> Maybe Day
forall a. a -> Maybe a
Just Day
date else Maybe Day
forall a. Maybe a
Nothing
  ,Maybe Day
menddate
  ,if Bool
showdesc then String -> Maybe String
forall a. a -> Maybe a
Just String
desc else Maybe String
forall a. Maybe a
Nothing
  ,Posting
p
  ,MixedAmount
b
  )
  where
    date :: Day
date = case WhichDate
wd of PrimaryDate   -> Posting -> Day
postingDate Posting
p
                      SecondaryDate -> Posting -> Day
postingDate2 Posting
p
    desc :: String
desc = CommoditySymbol -> String
T.unpack (CommoditySymbol -> String) -> CommoditySymbol -> String
forall a b. (a -> b) -> a -> b
$ CommoditySymbol
-> (Transaction -> CommoditySymbol)
-> Maybe Transaction
-> CommoditySymbol
forall b a. b -> (a -> b) -> Maybe a -> b
maybe "" Transaction -> CommoditySymbol
tdescription (Maybe Transaction -> CommoditySymbol)
-> Maybe Transaction -> CommoditySymbol
forall a b. (a -> b) -> a -> b
$ Posting -> Maybe Transaction
ptransaction Posting
p

-- | Convert a list of postings into summary postings, one per interval,
-- aggregated to the specified depth if any.
-- Each summary posting will have a non-Nothing interval end date.
summarisePostingsByInterval :: Interval -> WhichDate -> Int -> Bool -> DateSpan -> [Posting] -> [SummaryPosting]
summarisePostingsByInterval :: Interval
-> WhichDate
-> Int
-> Bool
-> DateSpan
-> [Posting]
-> [SummaryPosting]
summarisePostingsByInterval interval :: Interval
interval wd :: WhichDate
wd depth :: Int
depth showempty :: Bool
showempty reportspan :: DateSpan
reportspan ps :: [Posting]
ps = (DateSpan -> [SummaryPosting]) -> [DateSpan] -> [SummaryPosting]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap DateSpan -> [SummaryPosting]
summarisespan ([DateSpan] -> [SummaryPosting]) -> [DateSpan] -> [SummaryPosting]
forall a b. (a -> b) -> a -> b
$ Interval -> DateSpan -> [DateSpan]
splitSpan Interval
interval DateSpan
reportspan
    where
      summarisespan :: DateSpan -> [SummaryPosting]
summarisespan s :: DateSpan
s = DateSpan
-> WhichDate -> Int -> Bool -> [Posting] -> [SummaryPosting]
summarisePostingsInDateSpan DateSpan
s WhichDate
wd Int
depth Bool
showempty (DateSpan -> [Posting]
postingsinspan DateSpan
s)
      postingsinspan :: DateSpan -> [Posting]
postingsinspan s :: DateSpan
s = (Posting -> Bool) -> [Posting] -> [Posting]
forall a. (a -> Bool) -> [a] -> [a]
filter (WhichDate -> DateSpan -> Posting -> Bool
isPostingInDateSpan' WhichDate
wd DateSpan
s) [Posting]
ps

-- | Given a date span (representing a report interval) and a list of
-- postings within it, aggregate the postings into one summary posting per
-- account. Each summary posting will have a non-Nothing interval end date.
--
-- When a depth argument is present, postings to accounts of greater
-- depth are also aggregated where possible. If the depth is 0, all
-- postings in the span are aggregated into a single posting with
-- account name "...".
--
-- The showempty flag includes spans with no postings and also postings
-- with 0 amount.
--
summarisePostingsInDateSpan :: DateSpan -> WhichDate -> Int -> Bool -> [Posting] -> [SummaryPosting]
summarisePostingsInDateSpan :: DateSpan
-> WhichDate -> Int -> Bool -> [Posting] -> [SummaryPosting]
summarisePostingsInDateSpan (DateSpan b :: Maybe Day
b e :: Maybe Day
e) wd :: WhichDate
wd depth :: Int
depth showempty :: Bool
showempty ps :: [Posting]
ps
    | [Posting] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Posting]
ps Bool -> Bool -> Bool
&& (Maybe Day -> Bool
forall a. Maybe a -> Bool
isNothing Maybe Day
b Bool -> Bool -> Bool
|| Maybe Day -> Bool
forall a. Maybe a -> Bool
isNothing Maybe Day
e) = []
    | [Posting] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Posting]
ps Bool -> Bool -> Bool
&& Bool
showempty = [(Posting
summaryp, Day
e')]
    | Bool
otherwise = [SummaryPosting]
summarypes
    where
      postingdate :: Posting -> Day
postingdate = if WhichDate
wd WhichDate -> WhichDate -> Bool
forall a. Eq a => a -> a -> Bool
== WhichDate
PrimaryDate then Posting -> Day
postingDate else Posting -> Day
postingDate2
      b' :: Day
b' = Day -> Maybe Day -> Day
forall a. a -> Maybe a -> a
fromMaybe (Day -> (Posting -> Day) -> Maybe Posting -> Day
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Day
nulldate Posting -> Day
postingdate (Maybe Posting -> Day) -> Maybe Posting -> Day
forall a b. (a -> b) -> a -> b
$ [Posting] -> Maybe Posting
forall a. [a] -> Maybe a
headMay [Posting]
ps) Maybe Day
b
      e' :: Day
e' = Day -> Maybe Day -> Day
forall a. a -> Maybe a -> a
fromMaybe (Day -> (Posting -> Day) -> Maybe Posting -> Day
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (Integer -> Day -> Day
addDays 1 Day
nulldate) Posting -> Day
postingdate (Maybe Posting -> Day) -> Maybe Posting -> Day
forall a b. (a -> b) -> a -> b
$ [Posting] -> Maybe Posting
forall a. [a] -> Maybe a
lastMay [Posting]
ps) Maybe Day
e
      summaryp :: Posting
summaryp = Posting
nullposting{pdate :: Maybe Day
pdate=Day -> Maybe Day
forall a. a -> Maybe a
Just Day
b'}
      clippedanames :: [CommoditySymbol]
clippedanames | Int
depth Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> 0 = [CommoditySymbol] -> [CommoditySymbol]
forall a. Eq a => [a] -> [a]
nub ([CommoditySymbol] -> [CommoditySymbol])
-> [CommoditySymbol] -> [CommoditySymbol]
forall a b. (a -> b) -> a -> b
$ (CommoditySymbol -> CommoditySymbol)
-> [CommoditySymbol] -> [CommoditySymbol]
forall a b. (a -> b) -> [a] -> [b]
map (Int -> CommoditySymbol -> CommoditySymbol
clipAccountName Int
depth) [CommoditySymbol]
anames
                    | Bool
otherwise = ["..."]
      summaryps :: [Posting]
summaryps | Int
depth Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> 0 = [Posting
summaryp{paccount :: CommoditySymbol
paccount=CommoditySymbol
a,pamount :: MixedAmount
pamount=CommoditySymbol -> MixedAmount
balance CommoditySymbol
a} | CommoditySymbol
a <- [CommoditySymbol]
clippedanames]
                | Bool
otherwise = [Posting
summaryp{paccount :: CommoditySymbol
paccount="...",pamount :: MixedAmount
pamount=[MixedAmount] -> MixedAmount
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum ([MixedAmount] -> MixedAmount) -> [MixedAmount] -> MixedAmount
forall a b. (a -> b) -> a -> b
$ (Posting -> MixedAmount) -> [Posting] -> [MixedAmount]
forall a b. (a -> b) -> [a] -> [b]
map Posting -> MixedAmount
pamount [Posting]
ps}]
      summarypes :: [SummaryPosting]
summarypes = (Posting -> SummaryPosting) -> [Posting] -> [SummaryPosting]
forall a b. (a -> b) -> [a] -> [b]
map (, Day
e') ([Posting] -> [SummaryPosting]) -> [Posting] -> [SummaryPosting]
forall a b. (a -> b) -> a -> b
$ (if Bool
showempty then [Posting] -> [Posting]
forall a. a -> a
id else (Posting -> Bool) -> [Posting] -> [Posting]
forall a. (a -> Bool) -> [a] -> [a]
filter (Bool -> Bool
not (Bool -> Bool) -> (Posting -> Bool) -> Posting -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. MixedAmount -> Bool
mixedAmountLooksZero (MixedAmount -> Bool)
-> (Posting -> MixedAmount) -> Posting -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Posting -> MixedAmount
pamount)) [Posting]
summaryps
      anames :: [CommoditySymbol]
anames = [CommoditySymbol] -> [CommoditySymbol]
forall a. Ord a => [a] -> [a]
nubSort ([CommoditySymbol] -> [CommoditySymbol])
-> [CommoditySymbol] -> [CommoditySymbol]
forall a b. (a -> b) -> a -> b
$ (Posting -> CommoditySymbol) -> [Posting] -> [CommoditySymbol]
forall a b. (a -> b) -> [a] -> [b]
map Posting -> CommoditySymbol
paccount [Posting]
ps
      -- aggregate balances by account, like ledgerFromJournal, then do depth-clipping
      accts :: [Account]
accts = [Posting] -> [Account]
accountsFromPostings [Posting]
ps
      balance :: CommoditySymbol -> MixedAmount
balance a :: CommoditySymbol
a = MixedAmount
-> (Account -> MixedAmount) -> Maybe Account -> MixedAmount
forall b a. b -> (a -> b) -> Maybe a -> b
maybe MixedAmount
nullmixedamt Account -> MixedAmount
bal (Maybe Account -> MixedAmount) -> Maybe Account -> MixedAmount
forall a b. (a -> b) -> a -> b
$ CommoditySymbol -> [Account] -> Maybe Account
lookupAccount CommoditySymbol
a [Account]
accts
        where
          bal :: Account -> MixedAmount
bal = if CommoditySymbol -> Bool
isclipped CommoditySymbol
a then Account -> MixedAmount
aibalance else Account -> MixedAmount
aebalance
          isclipped :: CommoditySymbol -> Bool
isclipped a :: CommoditySymbol
a = CommoditySymbol -> Int
accountNameLevel CommoditySymbol
a Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
depth

negatePostingAmount :: Posting -> Posting
negatePostingAmount :: Posting -> Posting
negatePostingAmount p :: Posting
p = Posting
p { pamount :: MixedAmount
pamount = MixedAmount -> MixedAmount
forall a. Num a => a -> a
negate (MixedAmount -> MixedAmount) -> MixedAmount -> MixedAmount
forall a b. (a -> b) -> a -> b
$ Posting -> MixedAmount
pamount Posting
p }


-- tests

tests_PostingsReport :: TestTree
tests_PostingsReport = String -> [TestTree] -> TestTree
tests "PostingsReport" [

   String -> Assertion -> TestTree
test "postingsReport" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ do
    let (query :: Query
query, journal :: Journal
journal) gives :: (Query, Journal) -> Int -> Assertion
`gives` n :: Int
n = ([PostingsReportItem] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length ([PostingsReportItem] -> Int) -> [PostingsReportItem] -> Int
forall a b. (a -> b) -> a -> b
$ PostingsReport -> [PostingsReportItem]
forall a b. (a, b) -> b
snd (PostingsReport -> [PostingsReportItem])
-> PostingsReport -> [PostingsReportItem]
forall a b. (a -> b) -> a -> b
$ ReportOpts -> Query -> Journal -> PostingsReport
postingsReport ReportOpts
defreportopts Query
query Journal
journal) Int -> Int -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= Int
n
    -- with the query specified explicitly
    (Query
Any, Journal
nulljournal) (Query, Journal) -> Int -> Assertion
`gives` 0
    (Query
Any, Journal
samplejournal) (Query, Journal) -> Int -> Assertion
`gives` 13
    -- register --depth just clips account names
    (Int -> Query
Depth 2, Journal
samplejournal) (Query, Journal) -> Int -> Assertion
`gives` 13
    ([Query] -> Query
And [Int -> Query
Depth 1, Status -> Query
StatusQ Status
Cleared, String -> Query
Acct "expenses"], Journal
samplejournal) (Query, Journal) -> Int -> Assertion
`gives` 2
    ([Query] -> Query
And [[Query] -> Query
And [Int -> Query
Depth 1, Status -> Query
StatusQ Status
Cleared], String -> Query
Acct "expenses"], Journal
samplejournal) (Query, Journal) -> Int -> Assertion
`gives` 2
    -- with query and/or command-line options
    ([PostingsReportItem] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length ([PostingsReportItem] -> Int) -> [PostingsReportItem] -> Int
forall a b. (a -> b) -> a -> b
$ PostingsReport -> [PostingsReportItem]
forall a b. (a, b) -> b
snd (PostingsReport -> [PostingsReportItem])
-> PostingsReport -> [PostingsReportItem]
forall a b. (a -> b) -> a -> b
$ ReportOpts -> Query -> Journal -> PostingsReport
postingsReport ReportOpts
defreportopts Query
Any Journal
samplejournal) Int -> Int -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= 13
    ([PostingsReportItem] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length ([PostingsReportItem] -> Int) -> [PostingsReportItem] -> Int
forall a b. (a -> b) -> a -> b
$ PostingsReport -> [PostingsReportItem]
forall a b. (a, b) -> b
snd (PostingsReport -> [PostingsReportItem])
-> PostingsReport -> [PostingsReportItem]
forall a b. (a -> b) -> a -> b
$ ReportOpts -> Query -> Journal -> PostingsReport
postingsReport ReportOpts
defreportopts{interval_ :: Interval
interval_=Int -> Interval
Months 1} Query
Any Journal
samplejournal) Int -> Int -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= 11
    ([PostingsReportItem] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length ([PostingsReportItem] -> Int) -> [PostingsReportItem] -> Int
forall a b. (a -> b) -> a -> b
$ PostingsReport -> [PostingsReportItem]
forall a b. (a, b) -> b
snd (PostingsReport -> [PostingsReportItem])
-> PostingsReport -> [PostingsReportItem]
forall a b. (a -> b) -> a -> b
$ ReportOpts -> Query -> Journal -> PostingsReport
postingsReport ReportOpts
defreportopts{interval_ :: Interval
interval_=Int -> Interval
Months 1, empty_ :: Bool
empty_=Bool
True} Query
Any Journal
samplejournal) Int -> Int -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= 20
    ([PostingsReportItem] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length ([PostingsReportItem] -> Int) -> [PostingsReportItem] -> Int
forall a b. (a -> b) -> a -> b
$ PostingsReport -> [PostingsReportItem]
forall a b. (a, b) -> b
snd (PostingsReport -> [PostingsReportItem])
-> PostingsReport -> [PostingsReportItem]
forall a b. (a -> b) -> a -> b
$ ReportOpts -> Query -> Journal -> PostingsReport
postingsReport ReportOpts
defreportopts (String -> Query
Acct "assets:bank:checking") Journal
samplejournal) Int -> Int -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= 5

     -- (defreportopts, And [Acct "a a", Acct "'b"], samplejournal2) `gives` 0
     -- [(Just (parsedate "2008-01-01","income"),assets:bank:checking             $1,$1)
     -- ,(Nothing,income:salary                   $-1,0)
     -- ,(Just (2008-06-01,"gift"),assets:bank:checking             $1,$1)
     -- ,(Nothing,income:gifts                    $-1,0)
     -- ,(Just (2008-06-02,"save"),assets:bank:saving               $1,$1)
     -- ,(Nothing,assets:bank:checking            $-1,0)
     -- ,(Just (2008-06-03,"eat & shop"),expenses:food                    $1,$1)
     -- ,(Nothing,expenses:supplies                $1,$2)
     -- ,(Nothing,assets:cash                     $-2,0)
     -- ,(Just (2008-12-31,"pay off"),liabilities:debts                $1,$1)
     -- ,(Nothing,assets:bank:checking            $-1,0)

    {-
        let opts = defreportopts
        (postingsReportAsText opts $ postingsReport opts (queryFromOpts date1 opts) j) `is` unlines
         ["2008/01/01 income               assets:bank:checking             $1           $1"
         ,"                                income:salary                   $-1            0"
         ,"2008/06/01 gift                 assets:bank:checking             $1           $1"
         ,"                                income:gifts                    $-1            0"
         ,"2008/06/02 save                 assets:bank:saving               $1           $1"
         ,"                                assets:bank:checking            $-1            0"
         ,"2008/06/03 eat & shop           expenses:food                    $1           $1"
         ,"                                expenses:supplies                $1           $2"
         ,"                                assets:cash                     $-2            0"
         ,"2008/12/31 pay off              liabilities:debts                $1           $1"
         ,"                                assets:bank:checking            $-1            0"
         ]

      ,"postings report with cleared option" ~:
       do
        let opts = defreportopts{cleared_=True}
        j <- readJournal' sample_journal_str
        (postingsReportAsText opts $ postingsReport opts (queryFromOpts date1 opts) j) `is` unlines
         ["2008/06/03 eat & shop           expenses:food                    $1           $1"
         ,"                                expenses:supplies                $1           $2"
         ,"                                assets:cash                     $-2            0"
         ,"2008/12/31 pay off              liabilities:debts                $1           $1"
         ,"                                assets:bank:checking            $-1            0"
         ]

      ,"postings report with uncleared option" ~:
       do
        let opts = defreportopts{uncleared_=True}
        j <- readJournal' sample_journal_str
        (postingsReportAsText opts $ postingsReport opts (queryFromOpts date1 opts) j) `is` unlines
         ["2008/01/01 income               assets:bank:checking             $1           $1"
         ,"                                income:salary                   $-1            0"
         ,"2008/06/01 gift                 assets:bank:checking             $1           $1"
         ,"                                income:gifts                    $-1            0"
         ,"2008/06/02 save                 assets:bank:saving               $1           $1"
         ,"                                assets:bank:checking            $-1            0"
         ]

      ,"postings report sorts by date" ~:
       do
        j <- readJournal' $ unlines
            ["2008/02/02 a"
            ,"  b  1"
            ,"  c"
            ,""
            ,"2008/01/01 d"
            ,"  e  1"
            ,"  f"
            ]
        let opts = defreportopts
        registerdates (postingsReportAsText opts $ postingsReport opts (queryFromOpts date1 opts) j) `is` ["2008/01/01","2008/02/02"]

      ,"postings report with account pattern" ~:
       do
        j <- samplejournal
        let opts = defreportopts{patterns_=["cash"]}
        (postingsReportAsText opts $ postingsReport opts (queryFromOpts date1 opts) j) `is` unlines
         ["2008/06/03 eat & shop           assets:cash                     $-2          $-2"
         ]

      ,"postings report with account pattern, case insensitive" ~:
       do
        j <- samplejournal
        let opts = defreportopts{patterns_=["cAsH"]}
        (postingsReportAsText opts $ postingsReport opts (queryFromOpts date1 opts) j) `is` unlines
         ["2008/06/03 eat & shop           assets:cash                     $-2          $-2"
         ]

      ,"postings report with display expression" ~:
       do
        j <- samplejournal
        let gives displayexpr =
                (registerdates (postingsReportAsText opts $ postingsReport opts (queryFromOpts date1 opts) j) `is`)
                    where opts = defreportopts{display_=Just displayexpr}
        "d<[2008/6/2]"  `gives` ["2008/01/01","2008/06/01"]
        "d<=[2008/6/2]" `gives` ["2008/01/01","2008/06/01","2008/06/02"]
        "d=[2008/6/2]"  `gives` ["2008/06/02"]
        "d>=[2008/6/2]" `gives` ["2008/06/02","2008/06/03","2008/12/31"]
        "d>[2008/6/2]"  `gives` ["2008/06/03","2008/12/31"]

      ,"postings report with period expression" ~:
       do
        j <- samplejournal
        let periodexpr `gives` dates = do
              j' <- samplejournal
              registerdates (postingsReportAsText opts $ postingsReport opts (queryFromOpts date1 opts) j') `is` dates
                  where opts = defreportopts{period_=maybePeriod date1 periodexpr}
        ""     `gives` ["2008/01/01","2008/06/01","2008/06/02","2008/06/03","2008/12/31"]
        "2008" `gives` ["2008/01/01","2008/06/01","2008/06/02","2008/06/03","2008/12/31"]
        "2007" `gives` []
        "june" `gives` ["2008/06/01","2008/06/02","2008/06/03"]
        "monthly" `gives` ["2008/01/01","2008/06/01","2008/12/01"]
        "quarterly" `gives` ["2008/01/01","2008/04/01","2008/10/01"]
        let opts = defreportopts{period_=maybePeriod date1 "yearly"}
        (postingsReportAsText opts $ postingsReport opts (queryFromOpts date1 opts) j) `is` unlines
         ["2008/01/01 - 2008/12/31         assets:bank:saving               $1           $1"
         ,"                                assets:cash                     $-2          $-1"
         ,"                                expenses:food                    $1            0"
         ,"                                expenses:supplies                $1           $1"
         ,"                                income:gifts                    $-1            0"
         ,"                                income:salary                   $-1          $-1"
         ,"                                liabilities:debts                $1            0"
         ]
        let opts = defreportopts{period_=maybePeriod date1 "quarterly"}
        registerdates (postingsReportAsText opts $ postingsReport opts (queryFromOpts date1 opts) j) `is` ["2008/01/01","2008/04/01","2008/10/01"]
        let opts = defreportopts{period_=maybePeriod date1 "quarterly",empty_=True}
        registerdates (postingsReportAsText opts $ postingsReport opts (queryFromOpts date1 opts) j) `is` ["2008/01/01","2008/04/01","2008/07/01","2008/10/01"]

      ]

      , "postings report with depth arg" ~:
       do
        j <- samplejournal
        let opts = defreportopts{depth_=Just 2}
        (postingsReportAsText opts $ postingsReport opts (queryFromOpts date1 opts) j) `is` unlines
         ["2008/01/01 income               assets:bank                      $1           $1"
         ,"                                income:salary                   $-1            0"
         ,"2008/06/01 gift                 assets:bank                      $1           $1"
         ,"                                income:gifts                    $-1            0"
         ,"2008/06/02 save                 assets:bank                      $1           $1"
         ,"                                assets:bank                     $-1            0"
         ,"2008/06/03 eat & shop           expenses:food                    $1           $1"
         ,"                                expenses:supplies                $1           $2"
         ,"                                assets:cash                     $-2            0"
         ,"2008/12/31 pay off              liabilities:debts                $1           $1"
         ,"                                assets:bank                     $-1            0"
         ]

    -}

  ,String -> Assertion -> TestTree
test "summarisePostingsByInterval" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$
    Interval
-> WhichDate
-> Int
-> Bool
-> DateSpan
-> [Posting]
-> [SummaryPosting]
summarisePostingsByInterval (Int -> Interval
Quarters 1) WhichDate
PrimaryDate 99999 Bool
False (Maybe Day -> Maybe Day -> DateSpan
DateSpan Maybe Day
forall a. Maybe a
Nothing Maybe Day
forall a. Maybe a
Nothing) [] [SummaryPosting] -> [SummaryPosting] -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= []

  -- ,tests_summarisePostingsInDateSpan = [
    --  "summarisePostingsInDateSpan" ~: do
    --   let gives (b,e,depth,showempty,ps) =
    --           (summarisePostingsInDateSpan (mkdatespan b e) depth showempty ps `is`)
    --   let ps =
    --           [
    --            nullposting{lpdescription="desc",lpaccount="expenses:food:groceries",lpamount=Mixed [usd 1]}
    --           ,nullposting{lpdescription="desc",lpaccount="expenses:food:dining",   lpamount=Mixed [usd 2]}
    --           ,nullposting{lpdescription="desc",lpaccount="expenses:food",          lpamount=Mixed [usd 4]}
    --           ,nullposting{lpdescription="desc",lpaccount="expenses:food:dining",   lpamount=Mixed [usd 8]}
    --           ]
    --   ("2008/01/01","2009/01/01",0,9999,False,[]) `gives`
    --    []
    --   ("2008/01/01","2009/01/01",0,9999,True,[]) `gives`
    --    [
    --     nullposting{lpdate=parsedate "2008/01/01",lpdescription="- 2008/12/31"}
    --    ]
    --   ("2008/01/01","2009/01/01",0,9999,False,ts) `gives`
    --    [
    --     nullposting{lpdate=parsedate "2008/01/01",lpdescription="- 2008/12/31",lpaccount="expenses:food",          lpamount=Mixed [usd 4]}
    --    ,nullposting{lpdate=parsedate "2008/01/01",lpdescription="- 2008/12/31",lpaccount="expenses:food:dining",   lpamount=Mixed [usd 10]}
    --    ,nullposting{lpdate=parsedate "2008/01/01",lpdescription="- 2008/12/31",lpaccount="expenses:food:groceries",lpamount=Mixed [usd 1]}
    --    ]
    --   ("2008/01/01","2009/01/01",0,2,False,ts) `gives`
    --    [
    --     nullposting{lpdate=parsedate "2008/01/01",lpdescription="- 2008/12/31",lpaccount="expenses:food",lpamount=Mixed [usd 15]}
    --    ]
    --   ("2008/01/01","2009/01/01",0,1,False,ts) `gives`
    --    [
    --     nullposting{lpdate=parsedate "2008/01/01",lpdescription="- 2008/12/31",lpaccount="expenses",lpamount=Mixed [usd 15]}
    --    ]
    --   ("2008/01/01","2009/01/01",0,0,False,ts) `gives`
    --    [
    --     nullposting{lpdate=parsedate "2008/01/01",lpdescription="- 2008/12/31",lpaccount="",lpamount=Mixed [usd 15]}
    --    ]

 ]